From a2660463fbe61e5d88eb9c495e50d91bfd7c267b Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 12:35:18 +0100 Subject: [PATCH 01/26] hip: ROCm backend for the same kernels, brought up on Qwen3.6-35B-A3B Compiles src/cuda/kernels.cu at run time with hiprtc for the card's gfx target and launches it through libamdhip64, both loaded by name (no ROCm headers, no hipcc, no C++ build step). Usage: --backend hip. Device side: src/hip/compat.h is prepended to the source and supplies the CUDA intrinsics it uses (__shfl_*_sync, __ballot_sync, __dp4a, __byte_perm, __vsub4/__vadd4, f16 conversions, __nanosleep, __trap) from HIP, with __CUDA_ARCH__ at the pre-Volta level so the source takes its portable paths (per-lane shared loads, plain copies, CUDA-core multiplicands). Kernels run as wave32, the assumption the source makes. kernels.cu keeps one source for both backends; the five places that cannot be shared are behind STRATA_HIP, so the CUDA build's preprocessed source is unchanged. Host side: src/hip/{mod,ffi}.rs implement the same Backend trait as src/cuda, including the code-object cache, the shared-memory ceiling (head_dim 256 prefill attention drops to a 16-key tile on RDNA's 64 KiB blocks), the MTP and prompt paths and the expert cache. Verified on RX 9070 XT (gfx1201, ROCm 7.2.3) with Qwen3.6-35B-A3B UD-Q4_K_XL: greedy output identical to the Vulkan backend on three prompts, decode 159 tok/s (--mtp 2) vs 232 for Vulkan, prefill 492 vs 1458 tok/s (matrix cores are the next step; docs/HIP.md). --- README.md | 5 +- THANKS.md | 5 + docs/HIP.md | 66 ++++ src/backend.rs | 7 +- src/cuda/kernels.cu | 35 +- src/cuda/mod.rs | 26 +- src/hip/compat.h | 104 ++++++ src/hip/ffi.rs | 341 ++++++++++++++++++ src/hip/mod.rs | 854 ++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 10 files changed, 1425 insertions(+), 19 deletions(-) create mode 100644 docs/HIP.md create mode 100644 src/hip/compat.h create mode 100644 src/hip/ffi.rs create mode 100644 src/hip/mod.rs diff --git a/README.md b/README.md index 7870f08f..c55f7e73 100644 --- a/README.md +++ b/README.md @@ -63,8 +63,11 @@ Needs Rust (2024 edition) and one of: under `%CUDA_PATH%\bin`); `STRATA_NVRTC` names another file. Without it the run falls back to Vulkan. - a Vulkan 1.3 driver with shaderFloat64, int8/16/64 and subgroup size 32 or a fixed 64 (tested on RTX 3060, Radeon VII and V100; Intel Arc lacks shaderFloat64). +- for `--backend hip`: a ROCm runtime with hiprtc (`libamdhip64.so`, `libhiprtc.so`), also loaded at run time; the + kernels are compiled for the card's `gfx` target on first use. Experimental — status, numbers and limits are in + [docs/HIP.md](docs/HIP.md). -`--gpu` picks CUDA when it loads, else Vulkan; `--backend` chooses. The first CUDA run compiles the kernels (~15 s) and +`--gpu` picks CUDA when it loads, else Vulkan; `--backend` chooses (`cuda`, `vulkan` or `hip`). The first CUDA run compiles the kernels (~15 s) and caches them. Every GPU tried so far is in [docs/SUPPORTED_GPUS.md](docs/SUPPORTED_GPUS.md); AMD notes are in [docs/AMD.md](docs/AMD.md). diff --git a/THANKS.md b/THANKS.md index a4dba549..6c9de5b5 100644 --- a/THANKS.md +++ b/THANKS.md @@ -15,6 +15,11 @@ told us what they need. Thank you all. - [SugiKi1996](https://github.com/SugiKi1996): found that Turing (sm_75) was rejected on NVRTC 13.x, with the fix and RTX 2080 Ti numbers (issue #17). +## Code + +- [Niko1221](https://github.com/Niko1221/Strata): the HIP backend's device-side compatibility layer (`src/hip/compat.h`) + follows the structure and several implementations of Strata's `include/strata/hip_compat/intrinsics.hpp` (MIT). + ## Ideas - [FredWalter](https://github.com/FredWalter): multi-GPU and Qwen3.8-Flash-Next support (issue #1). diff --git a/docs/HIP.md b/docs/HIP.md new file mode 100644 index 00000000..d237139f --- /dev/null +++ b/docs/HIP.md @@ -0,0 +1,66 @@ +# HIP (ROCm) backend + +`--backend hip` runs the same `src/cuda/kernels.cu` on an AMD card through HIP, without `hipcc`, ROCm headers or a C++ +build step: the kernels are compiled at run time by hiprtc and launched through the HIP runtime, both loaded by name +(`libamdhip64.so`, `libhiprtc.so`), the way `src/cuda` loads NVRTC. `cargo build --release` is the whole build. + +**Status: experimental.** Brought up on Qwen3.6-35B-A3B (RX 9070 XT, gfx1201, ROCm 7.2). Greedy output is identical to +the Vulkan backend on the prompts tried. Not yet ported: matrix cores (prefill runs the f16 CUDA-core path, not WMMA), +graph capture (off by default), and the host-side pipeline details of the CUDA backend (ring staging, side stream). + +## What runs + +Everything the Vulkan backend runs, through the same kernels: + +| | HIP | Vulkan (same machine, same model) | +|---|---|---| +| Greedy tokens, 3 prompts | identical | identical | +| Prefill, pp 1024 | 492 tok/s | 1458 tok/s | +| Decode, tg 48, `--mtp 2` | 159 tok/s | 232 tok/s | + +Qwen3.6-35B-A3B UD-Q4_K_XL, `--ctx 4096 --vram-margin 256`, RX 9070 XT, Ryzen 7 5700X. Decode is within 1.5x of +Vulkan; prefill is 3x behind because the prefill GEMM has no matrix-core path on HIP yet (see below). + +## How it works + +- `src/hip/compat.h` is prepended to `kernels.cu`: it supplies the CUDA intrinsics the source uses (`__shfl_*_sync`, + `__ballot_sync`, `__dp4a`, `__byte_perm`, `__vsub4`, `__vadd4`, `__nanosleep`, `__trap`, the f16 conversions) with + their AMD equivalents, and sets `__CUDA_ARCH__` to the pre-Volta level so the source takes its portable paths: + per-lane shared loads instead of `ldmatrix`, plain copies instead of `cp.async`, and the CUDA-core multiplicands + instead of `mma.sync`. +- The kernels compile as **wave32** (lane = `threadIdx.x & 31`), which is the default wavefront size on RDNA and the + assumption the CUDA source already makes about a warp. The backend refuses a device that reports a 64-wide wave. +- `src/cuda/kernels.cu` keeps one source for both backends: the few places that cannot be shared are behind + `#if STRATA_HIP` (f16 conversions, the per-lane fragment loads, `mma884`, the KV f16x2 math, the L2 prefetch hint), + so the CUDA build's preprocessed source is unchanged. +- The code object is cached in `$XDG_CACHE_HOME/rusting_strata/.amdgcn`, keyed by the source, the `gfx` target + and the hiprtc version. + +## Requirements + +- A ROCm runtime with hiprtc: `libamdhip64.so` and `libhiprtc.so` on the loader path, in `/opt/rocm/lib`, or named by + `STRATA_HIP` and `STRATA_HIPRTC`. The card must be RDNA (wave32, gfx10+); head_dim 256 prefill attention uses a + 16-key tile because a 32-key tile needs 72 KiB of shared memory and a block may use 64 KiB. +- The device's `gfx` target is read from the driver's device properties; `STRATA_HIP_ARCH=gfx1201` overrides it. + +## Switches + +- `STRATA_HIP_SYNC=1` waits after every launch, so a hardware exception names the kernel that raised it. +- `STRATA_HIP_TRACE=1` names every launch before it goes out (grid, block, shared memory). +- `STRATA_HIP_GRAPH=1` turns on graph capture once the forward allocates nothing inside a step (HIP refuses an + allocation on a capturing stream; CUDA's stream-ordered allocator allows it). +- `STRATA_NO_GRAPH=1` turns capture off for both GPU backends. + +## Next + +1. gfx12 WMMA (`__builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12` and its int8 form) for the prefill GEMM: the 3x + prefill gap is exactly the missing matrix-core path. +2. Graph capture: move the per-step allocations (q8 cache growth, rope table) out of the captured region. +3. The CUDA host-side pipeline: a pinned ring for `htod` (expert streaming during prefill) and a side stream for + `beside`. + +## Credits + +The compatibility shim follows the structure and several implementations of Strata's +`include/strata/hip_compat/intrinsics.hpp` (MIT, (c) 2025 Niko1221, https://github.com/Niko1221/Strata), which runs +CUDA-shaped kernels on the same wave32 targets. See `THANKS.md`. diff --git a/src/backend.rs b/src/backend.rs index 1e7fe87d..011f4787 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -54,12 +54,13 @@ unsafe impl Plain for u64 {} /// Device memory, recorded graphs and kernel ops. Host copies are synchronous; device work runs in queue order. /// Pointer arguments are device addresses; strides are in floats unless named otherwise. -/// The backend `kind` ("cuda" or "vulkan") on GPU `device`; with no kind, CUDA if it loads, else Vulkan. +/// The backend `kind` ("cuda", "vulkan" or "hip") on GPU `device`; with no kind, CUDA if it loads, else Vulkan. pub fn open(kind: Option<&str>, device: usize) -> anyhow::Result> { match kind { Some("cuda") => Ok(Box::new(crate::cuda::Gpu::new(device)?)), Some("vulkan") => Ok(Box::new(crate::vulkan::Vk::new(device)?)), - Some(k) => anyhow::bail!("unknown backend {k:?} (cuda or vulkan)"), + Some("hip") => Ok(Box::new(crate::hip::Gpu::new(device)?)), + Some(k) => anyhow::bail!("unknown backend {k:?} (cuda, vulkan or hip)"), None => match crate::cuda::Gpu::new(device) { Ok(g) => Ok(Box::new(g)), Err(c) if format!("{c}") == "CUDA init" => { @@ -81,7 +82,7 @@ pub const SAME_X: i32 = 4; pub fn upload_type(ty: GgmlType) -> GgmlType { match ty { GgmlType::F16 => GgmlType::F32, GgmlType::Q4_0 | GgmlType::Q5_0 => GgmlType::Q8_0, ty => ty } } pub trait Backend: Send { - /// "cuda" or "vulkan". + /// "cuda", "vulkan" or "hip". fn name(&self) -> &'static str; /// The GPU's name as the driver reports it. fn device(&self) -> String; diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 0ffb09f7..3c90061c 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -6,8 +6,14 @@ typedef unsigned short u16; typedef unsigned int u32; typedef unsigned long long u64; +#if STRATA_HIP +// AMD: the ISA converts f16 in one instruction, the compiler emits it for these. +__device__ __forceinline__ float h2f(u16 h) { return (float)*(const _Float16*)&h; } +__device__ __forceinline__ u16 f2h(float f) { _Float16 x = (_Float16)f; return *(const u16*)&x; } +#else __device__ __forceinline__ float h2f(u16 h) { float f; asm("cvt.f32.f16 %0, %1;" : "=f"(f) : "h"(h)); return f; } __device__ __forceinline__ u16 f2h(float f) { u16 h; asm("cvt.rn.f16.f32 %0, %1;" : "=h"(h) : "f"(f)); return h; } +#endif __device__ __forceinline__ u32 ld16(const u8* p) { return *(const u16*)p; } // 2-aligned only (every quant field is) __device__ __forceinline__ u32 ld32(const u8* p) { return p[0] | (p[1] << 8) | (p[2] << 16) | ((u32)p[3] << 24); } __device__ __forceinline__ float ldh(const u8* p) { return h2f((u16)ld16(p)); } @@ -926,8 +932,12 @@ __device__ __forceinline__ void ldsm4(u32* r, const u16* p) { #pragma unroll for (int m = 0; m < 4; m++) { int m_row = (RM ? (m & 1) : (m >> 1)) * 8, m_col = (RM ? (m >> 1) : (m & 1)) * 8; +#if STRATA_HIP + r[m] = *(const u32*)(p + (m_row + row) * PQ + m_col + col); +#else unsigned a = (unsigned)__cvta_generic_to_shared(p + (m_row + row) * PQ + m_col + col); asm("ld.shared.b32 %0, [%1];" : "=r"(r[m]) : "r"(a)); +#endif } #else unsigned a = (unsigned)__cvta_generic_to_shared(p); @@ -944,11 +954,16 @@ __device__ __forceinline__ void ldsm4t(u32* r, const u16* p) { #pragma unroll for (int m = 0; m < 4; m++) { int m_row = (RM ? (m & 1) : (m >> 1)) * 8, m_col = (RM ? (m >> 1) : (m & 1)) * 8; +#if STRATA_HIP + const u16* a = p + (m_row + row) * PQ + m_col + col; + r[m] = (u32)a[0] | ((u32)a[2 * PQ] << 16); +#else unsigned a = (unsigned)__cvta_generic_to_shared(p + (m_row + row) * PQ + m_col + col); unsigned short lo, hi; asm("ld.shared.u16 %0, [%1];" : "=h"(lo) : "r"(a)); asm("ld.shared.u16 %0, [%1];" : "=h"(hi) : "r"(a + 2 * PQ)); r[m] = (u32)lo | ((u32)hi << 16); +#endif } #else unsigned a = (unsigned)__cvta_generic_to_shared(p); @@ -1005,7 +1020,7 @@ __device__ __forceinline__ void mma16816(float* c, u32 a0, u32 a1, u32 a2, u32 a : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1)); #endif } -#if __CUDA_ARCH__ < 800 +#if __CUDA_ARCH__ < 800 && !STRATA_HIP // D[8,8] += A[8,4] * B[4,8] with the four independent computations of mma.m8n8k4 (Volta, SASS HMMA.884) selected // by g & 3. PTX ISA 8.5 §9.7.13.4.1: lane l = 4*g + t owns A row t + 4*(g >= 4) at k 0..3 and D elements by the // column/row formulas implemented in gemm_q's sm_70 path. mma.m16n8k16 is sm_80+, so this helper only exists for @@ -1884,8 +1899,18 @@ template __device__ __forceinline__ void ldkv(const u16* c, size_t off // q * d rounded once to f16 equals f2h((float)q * d). auto deq = [&](unsigned x, unsigned sel) { unsigned h = __byte_perm(x ^ 0x80808080u, 0x64646464u, sel), r; +#if STRATA_HIP + // Same two f16 lanes without : a 2-element _Float16 vector (the ISA's packed f16 sub/mul). + typedef _Float16 f16x2 __attribute__((ext_vector_type(2))); + unsigned c64 = 0x64806480u; + f16x2 hh = *(f16x2*)&h, cc = *(f16x2*)&c64, dd = *(f16x2*)&d, rr; + rr[0] = (hh[0] - cc[0]) * dd[0]; + rr[1] = (hh[1] - cc[1]) * dd[1]; + r = *(unsigned*)&rr; +#else asm("sub.rn.f16x2 %0, %1, %2;" : "=r"(h) : "r"(h), "r"(0x64806480u)); asm("mul.rn.f16x2 %0, %1, %2;" : "=r"(r) : "r"(h), "r"(d)); +#endif return r; }; if (PER % 8 == 0 && hd % 128 == 0) { // rows 8-byte aligned @@ -2344,8 +2369,14 @@ extern "C" __global__ void moe_prefetch(const int* ids, int k, const int* table, if (s < 0) return; const char* p = base + (size_t)((unsigned int)s * (unsigned int)stride); int lines = bytes >> 7; - for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < lines; i += gridDim.x * blockDim.x) + for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < lines; i += gridDim.x * blockDim.x) { +#if STRATA_HIP + (void)p; // no L2 prefetch instruction to give: moe_prefetch is a CUDA-only hint + break; +#else asm volatile("prefetch.global.L2 [%0];" ::"l"(p + ((size_t)i << 7))); +#endif + } } // x += sum_j w[j] ye[j] + sigmoid(sg) sh + cpu. If a slot missed, wait for the CPU worker's done flag first. diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 1a2e2857..1b89356d 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -13,11 +13,11 @@ use std::sync::Arc; mod nvrtc; -const QTYPES: [GgmlType; 24] = { +pub(crate) const QTYPES: [GgmlType; 24] = { use GgmlType::*; [F32, BF16, Q8_0, Q2K, Q3K, Q4K, Q5K, Q6K, IQ1S, IQ1M, IQ2XXS, IQ2XS, IQ2S, IQ3XXS, IQ3S, IQ4XS, IQ4NL, Q2_0, TQ1_0, TQ2_0, Q4_1, Q5_1, Q4_0, Q5_0] }; -const KERNELS: [&str; 36] = [ +pub(crate) const KERNELS: [&str; 36] = [ "rope_freq", "qsa_pool", "qsa_score", "qsa_select", "rms_norm", "quant_xq", "argmax_part", "argmax_rows", "l2_norm", "rope_neox", "rms_norm_rope", "add", "swiglu", "swiglu_q", "ssm_gates", "conv_silu", "deltanet_seq", "norm_gate", "kv_store", "attn_merge", "router_topk", "moe_combine", "moe_route", "conv_seq", "conv_state", "moe_combine_seq", "moe_prefetch", "attn_prefill_64", "attn_prefill_128", "attn_prefill_256", "quant_q8", @@ -74,7 +74,7 @@ const BESIDE: usize = usize::MAX - 1; /// bound (cudarc leaves `CudaGraph` without `Send` only because it holds raw pointers). struct Graph(CudaGraph); -const AMAX_PARTS: usize = 64; +pub(crate) const AMAX_PARTS: usize = 64; unsafe impl Send for Graph {} /// `--llama-numerics`: quantize activations like llama.cpp's CPU q8_K (one scale per 256) for every integer matmul, @@ -93,11 +93,11 @@ pub fn gemm_fma() -> bool { std::env::var_os("STRATA_GEMM_FMA").is_some() } /// Prefill attention query / key tile sizes in positions. `FA_BQ` is one warp's 16 query rows times the four warps /// of the 128-thread block; `FA_BK` is the K/V tile depth and must stay a multiple of 32 for the sm_70 `m8n8k4` /// and sm_80+ `m16n8k16` fragment loops. Injected into kernels.cu by `source()`, never edited there. -const FA_BQ: usize = 64; -const FA_BK: usize = 32; +pub(crate) const FA_BQ: usize = 64; +pub(crate) const FA_BK: usize = 32; /// Prefill GEMM K tile in halves (default, candidate C3 overrides it with `STRATA_GEMM_BK=32`). `GEMM_BM` lives in /// `backend.rs` because the prefill tile-list builder shares it with Vulkan. -const GEMM_BK: usize = 64; +pub(crate) const GEMM_BK: usize = 64; /// Row padding of the attention shared-memory tiles (`PQ = HD + 8`, `FA_BK + 8` in `attn_prefill_t`). const ATTN_SMEM_PAD: usize = 8; @@ -131,13 +131,13 @@ impl Tune { } /// `default` unless `v` parses to a value accepted by `valid`. -fn tuned(v: Option<&str>, default: usize, valid: impl Fn(usize) -> bool) -> usize { +pub(crate) fn tuned(v: Option<&str>, default: usize, valid: impl Fn(usize) -> bool) -> usize { v.and_then(|s| s.trim().parse::().ok()).filter(|&x| valid(x)).unwrap_or(default) } /// Rows per warp: the family override (`STRATA_RPW_MOE`/`_DENSE`) first, then `STRATA_RPW`, then the shape default. /// 1..=64 keeps a block's row loop bounded; anything else falls back one level, as `tuned` does. -fn rpw_from(global: Option<&str>, family: Option<&str>, default: usize) -> usize { +pub(crate) fn rpw_from(global: Option<&str>, family: Option<&str>, default: usize) -> usize { let ok = |v: usize| (1..=64).contains(&v); family.and_then(|s| s.trim().parse().ok()).filter(|&v| ok(v)) .or_else(|| global.and_then(|s| s.trim().parse().ok()).filter(|&v| ok(v))) @@ -146,7 +146,7 @@ fn rpw_from(global: Option<&str>, family: Option<&str>, default: usize) -> usize /// Threads per block of the integer GEMV: the family override first, then the global value, then 256. Only the /// three warp counts the kernel's row mapping can tile are accepted (4/8/16 warps per block). -fn gemv_block_from(global: Option<&str>, family: Option<&str>) -> u32 { +pub(crate) fn gemv_block_from(global: Option<&str>, family: Option<&str>) -> u32 { let ok = |v: u32| matches!(v, 128 | 256 | 512); family.and_then(|s| s.trim().parse::().ok()).filter(|&v| ok(v)) .or_else(|| global.and_then(|s| s.trim().parse::().ok()).filter(|&v| ok(v))) @@ -196,7 +196,7 @@ fn source_with(kv_q8: bool, gemm_tc: bool, tune: Tune) -> String { fn attn_prefill_smem(hd: usize) -> usize { attn_prefill_smem_bk(hd, FA_BK) } /// `attn_prefill_smem` for a K/V tile depth of `bk` keys (16 on Turing at head_dim 256, else `FA_BK`). -fn attn_prefill_smem_bk(hd: usize, bk: usize) -> usize { +pub(crate) fn attn_prefill_smem_bk(hd: usize, bk: usize) -> usize { let pq = hd + ATTN_SMEM_PAD; 2 * (FA_BQ + 2 * bk) * pq + 2 * FA_BQ * (bk + ATTN_SMEM_PAD) } @@ -244,7 +244,7 @@ fn int8_gemm_arch(cc: (i32, i32)) -> bool { cc.0 >= 8 } /// decode GQA kernels (8 query slices per head group plus the cp.async K/V chunks at head_dim 128/256, `attn`), /// `usize::MAX` for `gemvn_*` whose request depends on the tensor shape (`xq_smem * nt`, `gemv_cfg`), and `None` /// for every kernel that never asks for more than the 48 KiB default (`attn_decode_*`, `attn_merge`, the rest). -fn dyn_shmem_need(name: &str) -> Option<(&'static str, usize)> { +pub(crate) fn dyn_shmem_need(name: &str) -> Option<(&'static str, usize)> { let family = if name.starts_with("attn_prefill") { "attn_prefill_*" } else if name.starts_with("attn_decode_gqa") { "attn_decode_gqa*" } else if name.starts_with("gemvn") { "gemvn_*" } @@ -343,7 +343,7 @@ 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 prefill GEMM (`gemmi_*` and /// `gemmis_*`, 20 non-float types x 2) on a device where that code is not compiled in. Pure so a CPU test can pin /// both lists (282 / 242 names). -fn kernel_names(sm80: bool) -> Vec { +pub(crate) fn kernel_names(sm80: bool) -> Vec { let int8 = move |&&t: &&GgmlType| sm80 && !matches!(t, GgmlType::F32 | GgmlType::BF16); KERNELS.iter().map(|s| s.to_string()) .chain(QTYPES.iter().flat_map(|&t| ["dequant", "gemv", "gemvn", "moe_gemv", "gemm", "gemms"].map(|p| kname(p, t)))) @@ -427,7 +427,7 @@ macro_rules! launch { }}; } -fn kname(prefix: &str, ty: GgmlType) -> String { format!("{prefix}_{}", ty.name().to_lowercase()) } +pub(crate) fn kname(prefix: &str, ty: GgmlType) -> String { format!("{prefix}_{}", ty.name().to_lowercase()) } impl Gpu { pub fn new(device: usize) -> anyhow::Result { diff --git a/src/hip/compat.h b/src/hip/compat.h new file mode 100644 index 00000000..7e37eed8 --- /dev/null +++ b/src/hip/compat.h @@ -0,0 +1,104 @@ +// Device-side compatibility layer for the HIP backend. `src/hip/mod.rs` prepends this (and the quant tables) to +// `../cuda/kernels.cu`, which the CUDA backend hands to NVRTC unchanged: `kernels.cu` is one source with an explicit +// `STRATA_HIP` branch where the two architectures cannot share code, and this header supplies everything CUDA's +// headers give it for free (warp intrinsics, packed-byte helpers, the f16 SIMD ops) from HIP. +// +// The portable intrinsic implementations are adapted from Strata's include/strata/hip_compat/intrinsics.hpp +// (MIT, (c) 2025 Niko1221); see THANKS.md. They assume the wave32 model the kernels are written for (lane = +// threadIdx.x & 31), which is the default wavefront size on RDNA (gfx10+) — the same assumption the CUDA source +// makes about a warp. +// Prepended to a concatenated source string, so a plain include guard: `#pragma once` would warn in a main file. +#ifndef STRATA_HIP_COMPAT_H +#define STRATA_HIP_COMPAT_H +#include +#include + +// kernels.cu selects its code paths by the CUDA architecture level: ldmatrix from sm_75, cp.async/m16n8k16/int8-mma +// from sm_80, m8n8k4 (mma884) from sm_70. AMD has none of those instructions, so the build takes the portable +// pre-Volta level: per-lane shared loads instead of ldmatrix, plain typed copies instead of cp.async, and the +// CUDA-core (f16 FMA) multiplicands instead of mma.sync. Prefill therefore runs without matrix cores until the +// gfx12 WMMA path lands; decode is unaffected (it has no tensor-core path). +#ifndef __CUDA_ARCH__ +#define __CUDA_ARCH__ 700 +#endif +#define STRATA_HIP 1 +#ifndef __forceinline__ +#define __forceinline__ inline __attribute__((always_inline)) +#endif +#ifndef __align__ +#define __align__(n) __attribute__((aligned(n))) +#endif +// The wave is 32 lanes wide here; a kernel that ever runs with a 64-wide wave would corrupt its reductions. +#if defined(__AMDGCN_WAVEFRONT_SIZE) && __AMDGCN_WAVEFRONT_SIZE != 32 +#error "the HIP backend needs wave32 (RDNA); wave64 targets are not supported" +#endif + +namespace strata_hip { + +__device__ __forceinline__ int signed_byte(unsigned word, int lane) { + unsigned v = (word >> (lane * 8)) & 0xffu; + return v < 0x80u ? (int)v : (int)v - 0x100; +} + +// CUDA's signed __dp4a: four signed byte products accumulated modulo 2^32. +__device__ __forceinline__ int dp4a(int a, int b, int c) { +#if (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || \ + defined(__gfx1151__) || defined(__gfx1200__) || defined(__gfx1201__)) && __has_builtin(__builtin_amdgcn_sudot4) + return __builtin_amdgcn_sudot4(true, a, true, b, c, false); +#elif (defined(__gfx1030__) || defined(__gfx1031__) || defined(__gfx1032__)) && __has_builtin(__builtin_amdgcn_sdot4) + return __builtin_amdgcn_sdot4(a, b, c, false); +#else + unsigned ua = (unsigned)a, ub = (unsigned)b, sum = (unsigned)c; +#pragma unroll + for (int i = 0; i < 4; ++i) sum += (unsigned)(signed_byte(ua, i) * signed_byte(ub, i)); + return (int)sum; +#endif +} + +// CUDA's __byte_perm: result byte i is byte s.nibble[i] & 7 of {y:x}. One v_perm_b32 instead of HIP's byte array. +__device__ __forceinline__ unsigned byte_perm(unsigned x, unsigned y, unsigned s) { + unsigned sel = (s & 0x7u) | ((s & 0x70u) << 4) | ((s & 0x700u) << 8) | ((s & 0x7000u) << 12); + return __builtin_amdgcn_perm(y, x, sel); +} + +// Packed byte arithmetic, four lanes at once (SWAR, Hacker's Delight 2-18): gfx11/gfx12 have no packed 8-bit +// add/sub, and a per-lane loop costs the Q3_K/Q6_K dots several times the instructions. +constexpr unsigned kHigh = 0x80808080u; + +__device__ __forceinline__ int vsub4(int a, int b) { + unsigned ua = (unsigned)a, ub = (unsigned)b; + return (int)(((ua | kHigh) - (ub & ~kHigh)) ^ ((ua ^ ~ub) & kHigh)); +} +__device__ __forceinline__ int vadd4(int a, int b) { + unsigned ua = (unsigned)a, ub = (unsigned)b; + return (int)(((ua & ~kHigh) + (ub & ~kHigh)) ^ ((ua ^ ub) & kHigh)); +} + +// The mask is informational here: an AMD wave either takes part in the corresponding `ds_bpermute` or does not, so a +// lane that is not in the mask still receives whatever the exchange computes (CUDA leaves it undefined). That matches +// CUDA whenever the lanes a participating lane exchanges with are participating too, which is how kernels.cu uses it +// (`quant8` shuffles inside groups of four active lanes; the rest pass 0xffffffff). +template __device__ __forceinline__ T shfl_xor_sync(unsigned, T v, int lane_mask, int width = 32) { return __shfl_xor(v, lane_mask, width); } +template __device__ __forceinline__ T shfl_down_sync(unsigned, T v, unsigned d, int width = 32) { return __shfl_down(v, d, width); } +template __device__ __forceinline__ T shfl_up_sync(unsigned, T v, unsigned d, int width = 32) { return __shfl_up(v, d, width); } +template __device__ __forceinline__ T shfl_sync(unsigned, T v, int src, int width = 32) { return __shfl(v, src, width); } +__device__ __forceinline__ unsigned ballot_sync(unsigned, int predicate) { return (unsigned)__ballot(predicate); } +__device__ __forceinline__ int any_sync(unsigned, int predicate) { return (int)(__ballot(predicate) != 0); } + +} // namespace strata_hip + +#define __dp4a(a, b, c) (strata_hip::dp4a((a), (b), (c))) +#define __byte_perm(x, y, s) (strata_hip::byte_perm((x), (y), (s))) +#define __vsub4(a, b) (strata_hip::vsub4((a), (b))) +#define __vadd4(a, b) (strata_hip::vadd4((a), (b))) +#define __shfl_xor_sync(...) (strata_hip::shfl_xor_sync(__VA_ARGS__)) +#define __shfl_down_sync(...) (strata_hip::shfl_down_sync(__VA_ARGS__)) +#define __shfl_up_sync(...) (strata_hip::shfl_up_sync(__VA_ARGS__)) +#define __shfl_sync(...) (strata_hip::shfl_sync(__VA_ARGS__)) +#define __ballot_sync(m, p) (strata_hip::ballot_sync((m), (p))) +#define __any_sync(m, p) (strata_hip::any_sync((m), (p))) +// The compiled-out sm_80+ paths still mention these; no CUDA-only helper may survive into a HIP build. +#define __trap() __builtin_trap() +#define __nanosleep(cycles) __builtin_amdgcn_s_sleep(1) + +#endif // STRATA_HIP_COMPAT_H diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs new file mode 100644 index 00000000..ed6ea1cf --- /dev/null +++ b/src/hip/ffi.rs @@ -0,0 +1,341 @@ +//! HIP runtime and hiprtc, loaded by name like `cuda/nvrtc.rs` loads NVRTC: no ROCm headers, link flags or `hipcc` +//! at build time, and no C++ build step. Every entry point the backend uses is resolved once per process. + +use anyhow::{Context, bail}; +use libloading::Library; +use std::ffi::{CStr, c_char, c_int, c_void}; +use std::path::PathBuf; +use std::sync::OnceLock; + +pub type Stream = *mut c_void; +pub type Module = *mut c_void; +pub type Func = *mut c_void; +pub type Event = *mut c_void; +pub type Graph = *mut c_void; +pub type GraphExec = *mut c_void; +pub type RtcProgram = *mut c_void; + +// hipError_t / hiprtcResult +pub const HIP_SUCCESS: c_int = 0; + +// Values the ROCm 7 headers give these enums (probe-printed; see the module docs of `hip`). +pub const MEMCPY_H2D: c_int = 1; +pub const MEMCPY_D2H: c_int = 2; +pub const MEMCPY_D2D: c_int = 3; +pub const HOST_MALLOC_PORTABLE: u32 = 1; +pub const HOST_MALLOC_MAPPED: u32 = 2; +pub const EVENT_DISABLE_TIMING: u32 = 2; +pub const STREAM_NON_BLOCKING: u32 = 1; +pub const CAPTURE_MODE_THREAD_LOCAL: c_int = 1; +pub const ATTR_MAX_DYNAMIC_SHARED: c_int = 8; +pub const ATTR_SHARED_PER_BLOCK_OPTIN: c_int = 75; +pub const ATTR_SHARED_PER_BLOCK: c_int = 74; +pub const ATTR_WARP_SIZE: c_int = 87; +pub const ATTR_INTEGRATED: c_int = 16; +pub const ATTR_MULTIPROCESSOR_COUNT: c_int = 63; +pub const ATTR_MAX_THREADS_PER_BLOCK: c_int = 56; + +/// `hipDeviceProp_t` from ROCm 7: the field offsets the backend reads. The struct is version-specific, so every +/// read is validated (the architecture name must look like `gfxNNNN`) and `STRATA_HIP_ARCH` overrides it. +const PROP_SIZE: usize = 1472; +const PROP_GCN_ARCH_NAME: usize = 1160; + +type Fn = unsafe extern "C" fn(); + +/// Library names to try, in order. `STRATA_HIP` (a path or a name) replaces the whole list. +fn candidates(vars: Option, default_suffix: &[&str]) -> Vec { + if let Some(p) = vars { return vec![p]; } + let mut v: Vec = Vec::new(); + for s in default_suffix { v.push(PathBuf::from(s)); } + // A ROCm install that is not on the loader path (`/opt/rocm` may be a symlink chain). + for root in ["/opt/rocm/lib", "/opt/rocm/core-10.1/lib", "/usr/lib/x86_64-linux-gnu", "/usr/local/lib"] { + for s in default_suffix { v.push(PathBuf::from(root).join(s)); } + } + v +} + +pub struct Hip { + pub init: unsafe extern "C" fn(c_int) -> c_int, + pub device_count: unsafe extern "C" fn(*mut c_int) -> c_int, + pub set_device: unsafe extern "C" fn(c_int) -> c_int, + pub device_name: unsafe extern "C" fn(*mut c_char, c_int, c_int) -> c_int, + pub device_attribute: unsafe extern "C" fn(*mut c_int, c_int, c_int) -> c_int, + pub mem_get_info: unsafe extern "C" fn(*mut usize, *mut usize) -> c_int, + pub malloc: unsafe extern "C" fn(*mut *mut c_void, usize) -> c_int, + pub free: unsafe extern "C" fn(*mut c_void) -> c_int, + pub memset: unsafe extern "C" fn(*mut c_void, c_int, usize) -> c_int, + pub memcpy: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int) -> c_int, + pub memcpy_async: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int, Stream) -> c_int, + pub stream_create: unsafe extern "C" fn(*mut Stream, u32) -> c_int, + pub stream_destroy: unsafe extern "C" fn(Stream) -> c_int, + pub stream_sync: unsafe extern "C" fn(Stream) -> c_int, + pub stream_wait_event: unsafe extern "C" fn(Stream, Event, u32) -> c_int, + pub stream_begin_capture: unsafe extern "C" fn(Stream, c_int) -> c_int, + pub stream_end_capture: unsafe extern "C" fn(Stream, *mut Graph) -> c_int, + pub stream_is_capturing: unsafe extern "C" fn(Stream, *mut c_int) -> c_int, + pub graph_instantiate: unsafe extern "C" fn(*mut GraphExec, Graph, u64) -> c_int, + pub graph_launch: unsafe extern "C" fn(GraphExec, Stream) -> c_int, + pub graph_exec_destroy: unsafe extern "C" fn(GraphExec) -> c_int, + pub graph_destroy: unsafe extern "C" fn(Graph) -> c_int, + pub event_create: unsafe extern "C" fn(*mut Event, u32) -> c_int, + pub event_record: unsafe extern "C" fn(Event, Stream) -> c_int, + pub event_sync: unsafe extern "C" fn(Event) -> c_int, + pub event_query: unsafe extern "C" fn(Event) -> c_int, + pub event_destroy: unsafe extern "C" fn(Event) -> c_int, + pub host_malloc: unsafe extern "C" fn(*mut *mut c_void, usize, u32) -> c_int, + pub host_free: unsafe extern "C" fn(*mut c_void) -> c_int, + pub host_device_ptr: unsafe extern "C" fn(*mut *mut c_void, *mut c_void, u32) -> c_int, + pub module_load: unsafe extern "C" fn(*mut Module, *const c_void) -> c_int, + pub module_unload: unsafe extern "C" fn(Module) -> c_int, + pub function: unsafe extern "C" fn(*mut Func, Module, *const c_char) -> c_int, + pub launch: unsafe extern "C" fn(Func, u32, u32, u32, u32, u32, u32, u32, Stream, *mut *mut c_void, *mut *mut c_void) -> c_int, + pub func_set_attribute: unsafe extern "C" fn(*const c_void, c_int, c_int) -> c_int, + pub error_string: unsafe extern "C" fn(c_int) -> *const c_char, + pub last_error: unsafe extern "C" fn() -> c_int, + _lib: Library, +} + +impl Hip { + /// The runtime, or an error naming what was missing. "HIP init" lets `backend::open` fall back to Vulkan. + pub fn open() -> anyhow::Result { + let want = candidates(std::env::var_os("STRATA_HIP").map(Into::into), + &["libamdhip64.so", "libamdhip64.so.7", "libamdhip64.so.6"]); + let mut tried = Vec::new(); + for path in &want { + if let Ok(lib) = unsafe { Library::new(path) } { + if let Some(h) = unsafe { Self::bind(lib) } { return Ok(h); } + tried.push(format!("{}: missing symbols", path.display())); + } else { + tried.push(format!("{}: not loadable", path.display())); + } + } + Err(anyhow::anyhow!("no HIP runtime: {}", tried.join(", "))).context("HIP init") + } + + unsafe fn sym(lib: &Library, name: &str) -> Option { + let s = unsafe { lib.get::(format!("{name}\0").as_bytes()).ok() }?; + Some(*s) + } + + unsafe fn bind(lib: Library) -> Option { + macro_rules! g { ($n:literal) => { unsafe { Self::sym(&lib, $n)? } } } + Some(Hip { + init: g!("hipInit"), + device_count: g!("hipGetDeviceCount"), + set_device: g!("hipSetDevice"), + device_name: g!("hipDeviceGetName"), + device_attribute: g!("hipDeviceGetAttribute"), + mem_get_info: g!("hipMemGetInfo"), + malloc: g!("hipMalloc"), + free: g!("hipFree"), + memset: g!("hipMemset"), + memcpy: g!("hipMemcpy"), + memcpy_async: g!("hipMemcpyAsync"), + stream_create: g!("hipStreamCreateWithFlags"), + stream_destroy: g!("hipStreamDestroy"), + stream_sync: g!("hipStreamSynchronize"), + stream_wait_event: g!("hipStreamWaitEvent"), + stream_begin_capture: g!("hipStreamBeginCapture"), + stream_end_capture: g!("hipStreamEndCapture"), + stream_is_capturing: g!("hipStreamIsCapturing"), + graph_instantiate: g!("hipGraphInstantiateWithFlags"), + graph_launch: g!("hipGraphLaunch"), + graph_exec_destroy: g!("hipGraphExecDestroy"), + graph_destroy: g!("hipGraphDestroy"), + event_create: g!("hipEventCreateWithFlags"), + event_record: g!("hipEventRecord"), + event_sync: g!("hipEventSynchronize"), + event_query: g!("hipEventQuery"), + event_destroy: g!("hipEventDestroy"), + host_malloc: g!("hipHostMalloc"), + host_free: g!("hipHostFree"), + host_device_ptr: g!("hipHostGetDevicePointer"), + module_load: g!("hipModuleLoadData"), + module_unload: g!("hipModuleUnload"), + function: g!("hipModuleGetFunction"), + launch: g!("hipModuleLaunchKernel"), + func_set_attribute: g!("hipFuncSetAttribute"), + error_string: g!("hipGetErrorString"), + last_error: g!("hipGetLastError"), + _lib: lib, + }) + } + + pub fn err(&self, code: c_int) -> String { + let s = unsafe { (self.error_string)(code) }; + if s.is_null() { return format!("hip error {code}") } + unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned() + } + + pub fn check(&self, code: c_int, what: &str) -> anyhow::Result<()> { + if code == HIP_SUCCESS { return Ok(()) } + bail!("{what}: {}", self.err(code)) + } + + /// The device's `gfxNNNN` target, from `hipDeviceProp_t`'s `gcnArchName`. `STRATA_HIP_ARCH` overrides it. + /// ROCm 7 dropped the `hipDeviceAttributeArch`/`GcnArchName` attributes, so the property struct is the only + /// source; it is version-specific, hence the field-length and shape check before the value is trusted. + pub fn arch(&self, device: c_int) -> anyhow::Result { + if let Ok(a) = std::env::var("STRATA_HIP_ARCH") { return Ok(a) } + if let Some(a) = self.prop_arch(device) { return Ok(a) } + bail!("cannot read the device's gfx architecture; set STRATA_HIP_ARCH (e.g. gfx1201)") + } + + /// The device property struct is version-specific (`hipDeviceProp_t` and `hipDeviceProp_tR0600` differ, and ROCm 7 + /// resolves `hipGetDeviceProperties` to the latter), so the target name is found by shape inside the struct + /// instead of at a fixed offset: the first `gfxNNNN`-looking string, validated. + fn prop_arch(&self, device: c_int) -> Option { + // Resolved here and not in `bind`: this is the only use, and a missing symbol must not fail the backend. + let f: unsafe extern "C" fn(*mut c_void, c_int) -> c_int = unsafe { Self::sym(&self._lib, "hipGetDeviceProperties") }?; + let mut buf = vec![0u64; PROP_SIZE / 8]; + let r = unsafe { f(buf.as_mut_ptr().cast(), device) }; + if r != HIP_SUCCESS { return None } + let bytes = unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), PROP_SIZE) }; + for i in (0..bytes.len().saturating_sub(8)).step_by(4) { + if &bytes[i..i + 3] != b"gfx" { continue } + let end = bytes[i..i + 16].iter().position(|&b| b == 0 || !(b as char).is_ascii_alphanumeric()).unwrap_or(16); + if end < 6 { continue } + let s = String::from_utf8(bytes[i..i + end].to_vec()).ok()?; + return Some(s); + } + None + } + + pub fn device_name(&self, device: c_int) -> String { + let mut buf = [0 as c_char; 256]; + let r = unsafe { (self.device_name)(buf.as_mut_ptr(), 256, device) }; + if r != HIP_SUCCESS { return "AMD GPU".into() } + unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy().into_owned() + } + + pub fn attribute(&self, attr: c_int, device: c_int) -> anyhow::Result { + let mut v = 0; + self.check(unsafe { (self.device_attribute)(&mut v, attr, device) }, "hipDeviceGetAttribute")?; + Ok(v) + } +} + +pub struct Rtc { + version: unsafe extern "C" fn(*mut c_int, *mut c_int) -> c_int, + create: unsafe extern "C" fn(*mut RtcProgram, *const c_char, *const c_char, c_int, *const *const c_char, *const *const c_char) -> c_int, + compile: unsafe extern "C" fn(RtcProgram, c_int, *const *const c_char) -> c_int, + log_size: unsafe extern "C" fn(RtcProgram, *mut usize) -> c_int, + log: unsafe extern "C" fn(RtcProgram, *mut c_char) -> c_int, + code_size: unsafe extern "C" fn(RtcProgram, *mut usize) -> c_int, + code: unsafe extern "C" fn(RtcProgram, *mut c_char) -> c_int, + destroy: unsafe extern "C" fn(*mut RtcProgram) -> c_int, + error_string: unsafe extern "C" fn(c_int) -> *const c_char, + lib_path: PathBuf, + _lib: Library, +} + +static RTC: OnceLock> = OnceLock::new(); + +impl Rtc { + pub fn get() -> Option<&'static Rtc> { RTC.get_or_init(Self::open).as_ref() } + + fn open() -> Option { + let want = candidates(std::env::var_os("STRATA_HIPRTC").map(Into::into), + &["libhiprtc.so", "libhiprtc.so.7", "libhiprtc.so.6"]); + for path in &want { + let Ok(lib) = (unsafe { Library::new(path) }) else { continue }; + unsafe { + macro_rules! g { ($n:literal) => { match Self::sym(&lib, $n) { Some(f) => f, None => continue } } } + return Some(Rtc { + version: g!("hiprtcVersion"), + create: g!("hiprtcCreateProgram"), + compile: g!("hiprtcCompileProgram"), + log_size: g!("hiprtcGetProgramLogSize"), + log: g!("hiprtcGetProgramLog"), + code_size: g!("hiprtcGetCodeSize"), + code: g!("hiprtcGetCode"), + destroy: g!("hiprtcDestroyProgram"), + error_string: g!("hiprtcGetErrorString"), + lib_path: path.clone(), + _lib: lib, + }); + } + } + None + } + + unsafe fn sym(lib: &Library, name: &str) -> Option { + let s = unsafe { lib.get::(format!("{name}\0").as_bytes()).ok() }?; + Some(*s) + } + + pub fn version(&self) -> (i32, i32) { + let (mut maj, mut min) = (0, 0); + unsafe { (self.version)(&mut maj, &mut min) }; + (maj, min) + } + + fn err(&self, code: c_int) -> String { + let s = unsafe { (self.error_string)(code) }; + if s.is_null() { return format!("hiprtc error {code}") } + unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned() + } + + /// Directories holding `hip/hip_runtime.h`: hiprtc compiles a string in a scratch directory, so the ROCm headers + /// have to be named. Found next to the loaded `libhiprtc` and through the environment. + fn include_dirs(&self) -> Vec { + let mut v = Vec::new(); + for k in ["ROCM_PATH", "HIP_PATH"] { + if let Some(p) = std::env::var_os(k) { v.push(PathBuf::from(p).join("include")); } + } + if let Some(dir) = self.lib_path.parent() { + // libhiprtc.so -> /lib, headers in /include (also /include/hip). + v.push(dir.join("../include")); + } + for p in ["/opt/rocm/include", "/usr/include", "/usr/local/include"] { v.push(PathBuf::from(p)); } + v.retain(|p| p.join("hip/hip_runtime.h").exists()); + v + } + + /// Compile `src` to an AMDGPU code object for `arch` (`gfx1201`). `name` only labels diagnostics. + pub fn compile(&self, src: &str, name: &str, arch: &str, extra: &[&str]) -> anyhow::Result> { + let csrc = std::ffi::CString::new(src).context("kernel source contains a NUL byte")?; + let cname = std::ffi::CString::new(name)?; + let mut prog: RtcProgram = std::ptr::null_mut(); + let code = unsafe { (self.create)(&mut prog, csrc.as_ptr(), cname.as_ptr(), 0, std::ptr::null(), std::ptr::null()) }; + if code != HIP_SUCCESS { bail!("hiprtcCreateProgram: {}", self.err(code)) } + let guard = ProgGuard { prog, destroy: self.destroy }; + let mut opts: Vec = vec![ + std::ffi::CString::new(format!("--offload-arch={arch}"))?, + std::ffi::CString::new("-O3")?, + std::ffi::CString::new("--std=c++17")?, + ]; + for dir in self.include_dirs() { opts.push(std::ffi::CString::new(format!("-I{}", dir.display()))?); } + for e in extra { opts.push(std::ffi::CString::new(*e)?); } + let ptrs: Vec<*const c_char> = opts.iter().map(|o| o.as_ptr()).collect(); + let code = unsafe { (self.compile)(guard.prog, ptrs.len() as c_int, ptrs.as_ptr()) }; + let mut logsize = 0usize; + unsafe { (self.log_size)(guard.prog, &mut logsize) }; + if logsize > 1 { + let mut log = vec![0 as c_char; logsize]; + unsafe { (self.log)(guard.prog, log.as_mut_ptr()) }; + let text = unsafe { CStr::from_ptr(log.as_ptr()) }.to_string_lossy(); + if code != HIP_SUCCESS { bail!("hiprtc ({arch}): {}\n{}", self.err(code), text.trim_end()) } + let text = text.trim_end(); + if !text.is_empty() { eprintln!("hiprtc {name} ({arch}): {text}") } + } else if code != HIP_SUCCESS { + bail!("hiprtc ({arch}): {}", self.err(code)) + } + let mut n = 0usize; + unsafe { (self.code_size)(guard.prog, &mut n) }; + anyhow::ensure!(n > 0, "hiprtc produced no code for {arch}"); + let mut code_obj = vec![0u8; n]; + let r = unsafe { (self.code)(guard.prog, code_obj.as_mut_ptr().cast()) }; + if r != HIP_SUCCESS { bail!("hiprtcGetCode: {}", self.err(r)) } + Ok(code_obj) + } +} + +struct ProgGuard { + prog: RtcProgram, + destroy: unsafe extern "C" fn(*mut RtcProgram) -> c_int, +} + +impl Drop for ProgGuard { + fn drop(&mut self) { unsafe { (self.destroy)(&mut self.prog) }; } +} diff --git a/src/hip/mod.rs b/src/hip/mod.rs new file mode 100644 index 00000000..80030f72 --- /dev/null +++ b/src/hip/mod.rs @@ -0,0 +1,854 @@ +//! HIP (ROCm) backend: the same `kernels.cu` as `cuda`, with `STRATA_HIP` selecting its portable code paths, compiled +//! at run time by hiprtc for the device's `gfx` target and launched through the HIP runtime loaded by name (see +//! `ffi` and `compat.h`). No ROCm headers, no `hipcc`, no C++ build step: `cargo build --release` and `--backend hip`. +//! +//! The device side is one source: `kernels.cu` keeps its CUDA paths behind `#if !STRATA_HIP`, and `compat.h` supplies +//! what CUDA's headers give it for free. On RDNA the kernel is compiled as wave32 (lane = threadIdx.x & 31), which is +//! the assumption the source already makes about a warp. +//! +//! Status: the host layer and the wave32 device build are in place; ops are being wired up one family at a time +//! against the CPU reference (`cargo test --release hip`). Everything not yet ported returns an error naming the op, +//! so a run says exactly which kernel is missing instead of computing silently wrong numbers. + +use crate::backend::{ATT_SPLITS, ATT_SPLITS_1, Backend, Buf, GpuTensor, GEMM_BM, SAME_X}; +use crate::cuda::{AMAX_PARTS, FA_BK, attn_prefill_smem_bk, dyn_shmem_need, kname, rpw_from, gemv_block_from, tuned}; +use crate::quant::GgmlType; +use anyhow::{Context, bail}; +use std::any::Any; +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::{Arc, LazyLock, Mutex}; + +/// `STRATA_HIP_SYNC`: one sync per launch (see `Gpu::launch`). +static SYNC_EACH: LazyLock = LazyLock::new(|| std::env::var_os("STRATA_HIP_SYNC").is_some()); +/// `STRATA_HIP_TRACE`: name every launch before it goes out, so a fault that kills the process names the kernel. +static TRACE: LazyLock = LazyLock::new(|| std::env::var_os("STRATA_HIP_TRACE").is_some()); + +mod ffi; + +pub struct Gpu { + /// The runtime, shared with every allocation and graph so none of them outlives the library that frees it. + hip: Arc, + device: usize, + stream: ffi::Stream, + module: ffi::Module, + fns: HashMap, + /// "gfx1201": the target hiprtc compiled for. + arch: String, + /// `--kv q8` (the kernels were compiled with KV_Q8). + pub kv_q8: bool, + /// Opt-in shared memory per block on this device (64 KiB on RDNA). + max_smem: usize, + /// `argmax_rows` partials. + am: Buf, + /// q8 rows of the last integer GEMM's X (see quant_q8 in kernels.cu) and which x they hold; `None` after a call + /// without `SAME_X` that did not quantize. + q8: Mutex<(Buf, Option<[u64; 4]>)>, + /// Recorded graphs by `Backend::graph` key. + graphs: Mutex>, + /// Recorded by `sync`, so a wait can poll it instead of spinning in the driver. + done: ffi::Event, + /// Rope frequency tables, `base` and `n_rot` to the device buffer that holds them. + fr: Mutex<(HashMap<(u32, usize), Buf>, Vec<(f32, usize)>)>, +} + +// The HIP handles are raw pointers but the runtime is thread-safe for the calls the backend makes, and `Backend` +// requires `Send`: transfers, launches and synchronization may come from any thread. +unsafe impl Send for Gpu {} + +struct Graph { + exec: ffi::GraphExec, + graph: ffi::Graph, + hip: Arc, +} + +impl Drop for Graph { + fn drop(&mut self) { + unsafe { + (self.hip.graph_exec_destroy)(self.exec); + (self.hip.graph_destroy)(self.graph); + } + } +} + +/// One launch: grid and block dimensions and the dynamic shared memory the kernel asks for. +#[derive(Clone, Copy)] +pub struct LaunchConfig { + pub grid_dim: (u32, u32, u32), + pub block_dim: (u32, u32, u32), + pub shared_mem_bytes: u32, +} + +pub fn cfg(grid: (u32, u32), block: u32, smem: u32) -> LaunchConfig { + LaunchConfig { grid_dim: (grid.0, grid.1, 1), block_dim: (block, 1, 1), shared_mem_bytes: smem } +} + +/// Launch kernel `$name` with `cfg`. Every argument is evaluated into a local, so `hipModuleLaunchKernel` reads it +/// from a live address; the type of the expression gives the parameter width, as the kernel's signature expects. +macro_rules! launch { + ($g:expr, $name:expr, $cfg:expr, $($a:expr),* $(,)?) => {{ + let c = $cfg; + $g.launch(&$name, c, &mut [ $(&mut { $a } as &mut dyn Any),* ]) + .with_context(|| format!("launch {}", $name))?; + }}; +} + +/// `kernels.cu` assembled for hiprtc: the compatibility layer, the quant tables, the compile-time switches, the file. +fn source(kv_q8: bool) -> String { + use crate::quant::tables::*; + let join = |v: Vec| v.join(","); + format!( + "{}\n\ + __device__ const unsigned long long iq2xs_grid[512] = {{{}}};\n\ + __device__ const unsigned long long iq2xxs_grid[256] = {{{}}};\n\ + __device__ const unsigned long long iq2s_grid[1024] = {{{}}};\n\ + __device__ const unsigned long long iq1s_grid[2048] = {{{}}};\n\ + __device__ const unsigned int iq3xxs_grid[256] = {{{}}};\n\ + __device__ const unsigned int iq3s_grid[512] = {{{}}};\n\ + __device__ const unsigned char ksigns_iq2xs[128] = {{{}}};\n\ + __device__ const signed char kvalues_iq4nl[16] = {{{}}};\n\ + #define LLAMA_Q8 {}\n#define KV_Q8 {}\n#define GEMM_TC 0\n\ + #define GEMM_BM {}\n#define GEMM_BK {}\n#define GEMM_MIN_BLOCKS 1\n#define GEMV_LOADW {}\n\ + #define FA_BQ {}\n#define FA_BK {}\n{}", + include_str!("compat.h"), + join(IQ2XS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ2XXS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ2S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ1S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ3XXS_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(IQ3S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), + join(KSIGNS_IQ2XS.iter().map(|v| v.to_string()).collect()), + join(KVALUES_IQ4NL.iter().map(|v| v.to_string()).collect()), + crate::cuda::llama_numerics() as u8, + kv_q8 as u8, + GEMM_BM, + crate::cuda::GEMM_BK, + tuned(std::env::var("STRATA_GEMV_LOADW").ok().as_deref(), 0, |v| v <= 1), + crate::cuda::FA_BQ, + crate::cuda::FA_BK, + include_str!("../cuda/kernels.cu"), + ) +} + +/// Cache key for a compiled code object: the source, the target and the hiprtc version. +fn cache_key(src: &str, arch: &str, rtc: &str) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + (src, arch, rtc).hash(&mut h); + h.finish() +} + +impl Gpu { + pub fn new(device: usize) -> anyhow::Result { + let hip = Arc::new(ffi::Hip::open()?); + hip.check(unsafe { (hip.init)(0) }, "hipInit")?; + let n = { + let mut n = 0; + hip.check(unsafe { (hip.device_count)(&mut n) }, "hipGetDeviceCount")?; + n as usize + }; + anyhow::ensure!(device < n, "HIP device {device}: {n} device(s) present"); + hip.check(unsafe { (hip.set_device)(device as i32) }, "hipSetDevice")?; + let arch = hip.arch(device as i32)?; + let warp = hip.attribute(ffi::ATTR_WARP_SIZE, device as i32)?; + anyhow::ensure!(warp == 32, "H100 HIP backend needs wave32; {arch} reports warp size {warp}"); + // Opt-in (75) is what a kernel may ask for; fall back to the plain per-block limit (74) if a runtime does not + // know the attribute, and never trust a figure below the smallest tile the prefill attention needs. + let mut max_smem = hip.attribute(ffi::ATTR_SHARED_PER_BLOCK_OPTIN, device as i32).unwrap_or(0) as usize; + if max_smem < (16 << 10) { + max_smem = hip.attribute(ffi::ATTR_SHARED_PER_BLOCK, device as i32).unwrap_or(16 << 10) as usize; + } + anyhow::ensure!(max_smem >= (16 << 10), "HIP device reports {max_smem} B of shared memory a block"); + let kv_q8 = crate::cuda::kv_q8(); + let rtc = ffi::Rtc::get().context("HIP init").context("hiprtc is required to compile the kernels")?; + let (maj, min) = rtc.version(); + let tag = format!("{maj}.{min}"); + eprintln!("hip: {} ({arch}, wave{warp}, {} B shared memory a block)", + hip.device_name(device as i32), max_smem); + let src = source(kv_q8); + let obj = compile_cached(rtc, &src, &arch, &tag)?; + let mut stream: ffi::Stream = std::ptr::null_mut(); + hip.check(unsafe { (hip.stream_create)(&mut stream, ffi::STREAM_NON_BLOCKING) }, "hipStreamCreate")?; + let mut module: ffi::Module = std::ptr::null_mut(); + hip.check(unsafe { (hip.module_load)(&mut module, obj.as_ptr().cast()) }, "hipModuleLoadData")?; + let mut fns = HashMap::new(); + for name in kernel_names() { + let c = std::ffi::CString::new(name.clone())?; + let mut f: ffi::Func = std::ptr::null_mut(); + hip.check(unsafe { (hip.function)(&mut f, module, c.as_ptr()) }, &format!("hipModuleGetFunction({name})"))?; + // The kernels ask for up to 49 KiB of dynamic shared memory, more than HIP allows by default. The ceiling + // is the device's opt-in minus what the kernel already uses statically, which the runtime only checks + // here, so an over-ask is halved instead of failing the backend. + if let Some((_, need)) = dyn_shmem_need(&name) { + let mut want = need.min(max_smem); + loop { + let r = unsafe { (hip.func_set_attribute)(f, ffi::ATTR_MAX_DYNAMIC_SHARED, want as i32) }; + if r == ffi::HIP_SUCCESS { break } + if want < 8192 { + bail!("hipFuncSetAttribute({name}, {want}): {}", hip.err(r)); + } + want /= 2; + } + } + fns.insert(name, f); + } + let am_buf = alloc_raw(&hip, 64 * AMAX_PARTS)?; + let q8_buf = alloc_raw(&hip, 1)?; + let mut done: ffi::Event = std::ptr::null_mut(); + hip.check(unsafe { (hip.event_create)(&mut done, ffi::EVENT_DISABLE_TIMING) }, "hipEventCreate")?; + Ok(Gpu { hip, device, stream, module, fns, arch, kv_q8, max_smem, am: am_buf, q8: Mutex::new((q8_buf, None)), + graphs: Mutex::new(HashMap::new()), done, fr: Mutex::new((HashMap::new(), Vec::new())) }) + } + + fn h(&self) -> &ffi::Hip { &self.hip } + + pub fn arch(&self) -> &str { &self.arch } + + /// Launch kernel `name` with `cfg`; `args` are the kernel parameters, in order, read from the given addresses. + pub fn launch(&self, name: &str, c: LaunchConfig, args: &mut [&mut dyn Any]) -> anyhow::Result<()> { + let f = *self.fns.get(name).ok_or_else(|| anyhow::anyhow!("HIP kernel {name} is not loaded"))?; + if *TRACE { eprintln!("hip launch {name} grid {:?} block {:?} smem {}", c.grid_dim, c.block_dim, c.shared_mem_bytes); } + let mut params: Vec<*mut c_void> = args.iter_mut().map(|a| (*a as *mut dyn Any).cast::()).collect(); + let r = unsafe { + (self.hip.launch)(f, c.grid_dim.0, c.grid_dim.1, c.grid_dim.2, c.block_dim.0, c.block_dim.1, c.block_dim.2, + c.shared_mem_bytes, self.stream, params.as_mut_ptr(), std::ptr::null_mut()) + }; + if r != ffi::HIP_SUCCESS { bail!("{}: {}", name, self.hip.err(r)) } + // `STRATA_HIP_SYNC`: wait after every launch, so a hardware exception or bad argument names the kernel that + // raised it instead of the sync at the end of the pass. Debugging only: no overlap and no graphs. + if *SYNC_EACH { + self.hip.check(unsafe { (self.hip.stream_sync)(self.stream) }, &format!("kernel {name} failed"))?; + } + Ok(()) + } + + fn wait(&self) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.stream_sync)(self.stream) }, "hipStreamSynchronize") + } + + fn ptr(&self, b: &Buf) -> u64 { b.addr() } + + fn f(&self, name: &str) -> anyhow::Result { + self.fns.get(name).copied().ok_or_else(|| anyhow::anyhow!("HIP kernel {name} is not loaded")) + } + + /// qwen35moe and the other models this backend targets dequantize in the kernel, so the ops below are the + /// generic ones. + fn float_ty(ty: GgmlType) -> bool { matches!(ty, GgmlType::F32 | GgmlType::BF16) } + + fn gemv_cols(prefix: &str, ty: GgmlType, cols: usize) -> anyhow::Result<(i32, String)> { + let b = ty.block_elems().max(32); + if cols % b != 0 { bail!("{} tensor with {cols} columns: GEMV needs a multiple of {b}", ty.name()); } + Ok((cols as i32, kname(prefix, ty) + if cols % 256 != 0 { "_p" } else { "" })) + } + + fn rpw(rows: usize, cols: usize, k: usize) -> usize { + let d = if k > 1 { if cols <= 512 { 4 } else { (2048 / cols).max(1) } } else if rows >= 65536 { 8 } else if rows >= 8192 || rows == 2048 { 2 } else { 1 }; + let fam = if k > 1 { "STRATA_RPW_MOE" } else { "STRATA_RPW_DENSE" }; + let family = std::env::var(fam).ok(); + rpw_from(std::env::var("STRATA_RPW").ok().as_deref(), family.as_deref(), d) + } + + fn gemv_block(k: usize) -> u32 { + let fam = if k > 1 { "STRATA_GEMV_BLOCK_MOE" } else { "STRATA_GEMV_BLOCK_DENSE" }; + let family = std::env::var(fam).ok(); + gemv_block_from(std::env::var("STRATA_GEMV_BLOCK").ok().as_deref(), family.as_deref()) + } + + fn xq_smem(ty: GgmlType, cols: usize) -> u32 { + if Self::float_ty(ty) { 0 } else { (cols + cols / 8) as u32 } + } + + fn gemv_cfg(ty: GgmlType, rows: usize, cols: usize, k: usize) -> (LaunchConfig, i32) { + if Self::float_ty(ty) { + let wpb = if rows >= 4096 { 8 } else { 1 }; + return (cfg((rows.div_ceil(wpb) as u32, k as u32), 32 * wpb as u32, 0), 1); + } + let (rpw, wpb) = (Self::rpw(rows, cols, k), Self::gemv_block(k) as usize / 32); + (cfg((rows.div_ceil(wpb * rpw) as u32, k as u32), (32 * wpb) as u32, Self::xq_smem(ty, cols)), rpw as i32) + } + + /// The rope frequencies base^(-2i / n_rot) as `rms_norm_rope` computes them in f64, made once by `rope_freq`. + fn rope_fr(&self, base: f32, n_rot: usize) -> anyhow::Result { + let mut fr = self.fr.lock().unwrap(); + if let Some(b) = fr.0.get(&(base.to_bits(), n_rot)) { return Ok(b.addr()) } + let buf = alloc_raw(&self.hip, 8 * (n_rot / 2).max(1))?; + let p = buf.addr(); + let (bs, nr) = (base, n_rot as i32); + launch!(self, "rope_freq", cfg((1, 1), 256, 0), p, bs, nr); + self.wait()?; + fr.0.insert((base.to_bits(), n_rot), buf); + Ok(p) + } + + /// `gemvq`; with z = 2 also the matrix of `pair.2` rows at byte offset `pair.0` into the output at byte offset + /// `pair.1` (token stride `pair.2`). + fn gemvq_pair(&self, w: &GpuTensor, x: u64, x_stride: usize, xq: u64, y: u64, y_stride: usize, nt: usize, + pair: (i64, i64, i32), z: u32) -> anyhow::Result<()> { + if !(1..=4).contains(&nt) { bail!("gemvn: {nt} inputs (1 to 4)"); } + let (ncols, k1) = Self::gemv_cols("gemv", w.ty, w.cols)?; + let (mut c, rpw) = Self::gemv_cfg(w.ty, w.rows, w.cols, 1); + let per = c.shared_mem_bytes; + c.shared_mem_bytes = if xq == 0 { per * nt as u32 } else { 0 }; + c.grid_dim.2 = z; + // gemvn caches one x row per token in shared memory; when that exceeds the block's limit, run a token at a time. + if xq == 0 && c.shared_mem_bytes as usize > self.max_smem { + c.shared_mem_bytes = per; + for t in 0..nt { + let (xt, yt) = (x + 4 * t as u64 * x_stride as u64, y + 4 * t as u64 * y_stride as u64); + launch!(self, &k1, c, w.ptr, xt, yt, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2); + } + return Ok(()); + } + if nt == 1 { + launch!(self, &k1, c, w.ptr, x, y, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2); + return Ok(()); + } + let kn = k1.replacen("gemv", "gemvn", 1); + launch!(self, &kn, c, w.ptr, x, x_stride as i32, y, y_stride as i32, w.rows as i32, ncols, rpw, nt as i32, xq, pair.0, pair.1, pair.2); + 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`). + 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) -> 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(()) } + let (same, act) = (act & SAME_X != 0, act & !SAME_X); + 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); + // 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); + } + Ok(()) + } + + /// 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<()> { + if ![64, 128, 256, 512].contains(&hd) { bail!("attention head_dim {hd} unsupported (64, 128, 256 or 512)"); } + let group = nh / nkv; + let g = [8, 4, 2, 1].into_iter().find(|&g| group % g == 0 && g * hd <= 2048).unwrap(); + let ns = if kvt != 0 { ns1 } else { ATT_SPLITS }; + let pz = (nh * ns * (hd + 2)) as i32; + if gq_min != 0 { + launch!(self, &format!("attn_decode_{hd}"), cfg(((nh * nt) as u32, ns1 as u32), 256, (8 * hd * 4) as u32), + q, kc, vc, part, step, nh as i32, nkv as i32, hd as i32, scale, gq_min, pz, nt as i32, sel, sst as i32, sink, win as i32, kvt); + } + // No cp.async double buffering here: that path is the sm_80+ one (`ATT_RUN_CP`), so the K/V tile comes + // through registers and the kernel needs no extra shared memory. + let g4 = false; + let (name, cp) = if g4 { ("attn_decode_gqa4_128".to_string(), 0) } else { (format!("attn_decode_gqa_{hd}"), 0) }; + if gq_min != i32::MAX { + launch!(self, &name, cfg(((nh / g * nt) as u32, ns as u32), 256, (8 * hd * 4 + cp) as u32), + q, kc, vc, part, step, nh as i32, nkv as i32, hd as i32, scale, gq_min, pz, nt as i32, sel, sst as i32, sink, win as i32, kvt); + } + launch!(self, "attn_merge", LaunchConfig { grid_dim: (nh as u32, 1, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }, + part, qg, out, hd as i32, ns as i32, step, ns1 as i32, gq_min, xq, sink); + Ok(()) + } + + fn grid(n: usize) -> LaunchConfig { cfg((n.div_ceil(256) as u32, 1), 256, 0) } +} + +fn alloc_raw(hip: &Arc, bytes: usize) -> anyhow::Result { + let mut p: *mut c_void = std::ptr::null_mut(); + hip.check(unsafe { (hip.malloc)(&mut p, bytes.max(1)) }, "hipMalloc")?; + // The Buf owns the allocation through its address; the free happens when the owner (the backend or the tensor) + // drops, so the owner is a small RAII handle. + struct DevAlloc { hip: Arc, p: *mut c_void } + unsafe impl Send for DevAlloc {} + unsafe impl Sync for DevAlloc {} + impl Drop for DevAlloc { + fn drop(&mut self) { unsafe { (self.hip.free)(self.p) }; } + } + Ok(Buf::new(p as u64, bytes.max(1), DevAlloc { hip: hip.clone(), p })) +} + +fn compile_cached(rtc: &ffi::Rtc, src: &str, arch: &str, tag: &str) -> anyhow::Result> { + let dir = std::env::var_os("XDG_CACHE_HOME").map(Into::into) + .unwrap_or_else(|| std::path::PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".cache")) + .join("rusting_strata"); + let path = dir.join(format!("{:016x}.amdgcn", cache_key(src, arch, tag))); + if let Ok(b) = std::fs::read(&path) { return Ok(b) } + eprintln!("compiling HIP kernels for {arch} with hiprtc {tag} (first run only)"); + let b = rtc.compile(src, "kernels.cu", arch, &[])?; + let _ = std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(&path, &b)); + Ok(b) +} + +/// The kernel names to load: `cuda::kernel_names(false)` has no int8-mma GEMM, which needs no separate list here. +fn kernel_names() -> Vec { crate::cuda::kernel_names(false) } + +impl Backend for Gpu { + fn name(&self) -> &'static str { "hip" } + + fn device(&self) -> String { self.hip.device_name(self.device as i32) } + + fn alloc(&self, bytes: usize) -> anyhow::Result { + let b = alloc_raw(&self.hip, bytes)?; + self.hip.check(unsafe { (self.hip.memset)(b.addr() as *mut c_void, 0, b.len()) }, "hipMemset")?; + Ok(b) + } + + /// Synchronous copy: HIP does not promise that an async copy from pageable memory has staged the host buffer when + /// the call returns, and a caller that reuses `src` (every caller does) cannot wait for that. The stream is + /// drained first so the copy cannot pass kernels already queued that write `dst`. + fn htod(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { + anyhow::ensure!(off + src.len() <= dst.len(), "htod: {} bytes at {off} into {}", src.len(), dst.len()); + self.wait()?; + let r = unsafe { (self.hip.memcpy)((dst.addr() + off as u64) as *mut c_void, src.as_ptr().cast(), src.len(), ffi::MEMCPY_H2D) }; + self.hip.check(r, "hipMemcpy(htod)") + } + + fn dtoh(&self, src: &Buf, off: usize, dst: &mut [u8]) -> anyhow::Result<()> { + anyhow::ensure!(off + dst.len() <= src.len(), "dtoh: {} bytes at {off} from {}", dst.len(), src.len()); + self.wait()?; + let r = unsafe { (self.hip.memcpy)(dst.as_mut_ptr().cast(), (src.addr() + off as u64) as *const c_void, dst.len(), + ffi::MEMCPY_D2H) }; + self.hip.check(r, "hipMemcpyAsync(dtoh)") + } + + fn dtod(&self, src: &Buf, src_off: usize, dst: &Buf, dst_off: usize, bytes: usize) -> anyhow::Result<()> { + anyhow::ensure!(src_off + bytes <= src.len() && dst_off + bytes <= dst.len(), "dtod: {bytes} bytes out of range"); + let r = unsafe { (self.hip.memcpy_async)((dst.addr() + dst_off as u64) as *mut c_void, + (src.addr() + src_off as u64) as *const c_void, bytes, ffi::MEMCPY_D2D, self.stream) }; + self.hip.check(r, "hipMemcpyAsync(dtod)") + } + + fn memset(&self, dst: &Buf) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.memset)(dst.addr() as *mut c_void, 0, dst.len()) }, "hipMemset") + } + + fn mem_info(&self) -> anyhow::Result<(usize, usize)> { + let (mut free, mut total) = (0usize, 0usize); + self.hip.check(unsafe { (self.hip.mem_get_info)(&mut free, &mut total) }, "hipMemGetInfo")?; + Ok((free, total)) + } + + fn sync(&self) -> anyhow::Result<()> { self.wait() } + + /// Recorded with `hipStreamBeginCapture`: the same launches, replayed by the driver with no host work. + /// Off by default: the forwards allocate inside their step (the q8 cache grows, the rope table is made), and HIP + /// refuses an allocation on a capturing stream ("operation not permitted when stream is capturing"), where CUDA's + /// stream-ordered allocator allows it. `STRATA_HIP_GRAPH=1` turns capture on once the step allocates nothing. + fn graph(&self, key: u64, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { + if std::env::var_os("STRATA_NO_GRAPH").is_some() || std::env::var_os("STRATA_HIP_GRAPH").is_none() { return f() } + if let Some(g) = self.graphs.lock().unwrap().get(&key) { + let r = unsafe { (self.hip.graph_launch)(g.exec, self.stream) }; + return self.hip.check(r, "hipGraphLaunch"); + } + let mut capturing = 0; + unsafe { (self.hip.stream_is_capturing)(self.stream, &mut capturing) }; + if capturing != 0 { return f() } // never nest captures + self.hip.check(unsafe { (self.hip.stream_begin_capture)(self.stream, ffi::CAPTURE_MODE_THREAD_LOCAL) }, "hipStreamBeginCapture")?; + let r = f(); + let mut graph: ffi::Graph = std::ptr::null_mut(); + let end = unsafe { (self.hip.stream_end_capture)(self.stream, &mut graph) }; + r?; + self.hip.check(end, "hipStreamEndCapture")?; + anyhow::ensure!(!graph.is_null(), "empty HIP graph"); + let mut exec: ffi::GraphExec = std::ptr::null_mut(); + self.hip.check(unsafe { (self.hip.graph_instantiate)(&mut exec, graph, 0) }, "hipGraphInstantiate")?; + self.hip.check(unsafe { (self.hip.graph_launch)(exec, self.stream) }, "hipGraphLaunch")?; + self.graphs.lock().unwrap().insert(key, Graph { exec, graph, hip: self.hip.clone() }); + Ok(()) + } + + /// Pinned host memory mapped into the device address space (the CPU expert worker's mailbox). + fn host_mailbox(&self, words: usize) -> anyhow::Result<(Buf, *mut u32)> { + let n = words.max(1); + let mut host: *mut c_void = std::ptr::null_mut(); + self.hip.check(unsafe { (self.hip.host_malloc)(&mut host, 4 * n, ffi::HOST_MALLOC_PORTABLE | ffi::HOST_MALLOC_MAPPED) }, "hipHostMalloc")?; + let mut dev: *mut c_void = std::ptr::null_mut(); + self.hip.check(unsafe { (self.hip.host_device_ptr)(&mut dev, host, 0) }, "hipHostGetDevicePointer")?; + unsafe { std::ptr::write_bytes(host as *mut u8, 0, 4 * n) }; + struct Pinned { hip: Arc, p: *mut c_void } + unsafe impl Send for Pinned {} + unsafe impl Sync for Pinned {} + impl Drop for Pinned { + fn drop(&mut self) { unsafe { (self.hip.host_free)(self.p) }; } + } + let owner = Pinned { hip: self.hip.clone(), p: host }; + Ok((Buf::new(dev as u64, 4 * n, owner), host.cast())) + } + + fn kv_words(&self, n: usize) -> usize { if self.kv_q8 { n * 17 / 32 } else { n } } + + // ---- kernels ------------------------------------------------------------------------------------------------- + + fn gemm(&self, ty: GgmlType, rows: usize, cols: usize, tiles: u64, n_tiles: usize, x: u64, x_stride: usize, n_x: usize, + xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + self.gemm_raw(ty, rows, cols, tiles, n_tiles, 0, 0, x, x_stride, n_x, xrow, y, y_stride, act) + } + + fn gemm_dense(&self, w: &GpuTensor, n: usize, x: u64, x_stride: usize, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + 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) + } + + fn int8_gemm(&self, _ty: GgmlType) -> bool { false } + + fn gemv(&self, w: &GpuTensor, x: u64, y: u64) -> anyhow::Result<()> { + let (ncols, kn) = Self::gemv_cols("gemv", w.ty, w.cols)?; + let (c, rpw) = Self::gemv_cfg(w.ty, w.rows, w.cols, 1); + launch!(self, &kn, c, w.ptr, x, y, w.rows as i32, ncols, rpw, 0u64, 0i64, 0i64, 0i32); + Ok(()) + } + + fn gemvn(&self, w: &GpuTensor, x: u64, x_stride: usize, y: u64, y_stride: usize, nt: usize) -> anyhow::Result<()> { + self.gemvq(w, x, x_stride, 0, y, y_stride, nt) + } + + fn gemvq(&self, w: &GpuTensor, x: u64, x_stride: usize, xq: u64, y: u64, y_stride: usize, nt: usize) -> anyhow::Result<()> { + self.gemvq_pair(w, x, x_stride, xq, y, y_stride, nt, (0, 0, 0), 1) + } + + fn gemvq2(&self, a: &GpuTensor, b: &GpuTensor, x: u64, x_stride: usize, xq: u64, ya: u64, yb: u64, nt: usize) -> anyhow::Result<()> { + if a.ty != b.ty || a.cols != b.cols { + self.gemvq(a, x, x_stride, xq, ya, a.rows, nt)?; + return self.gemvq(b, x, x_stride, xq, yb, b.rows, nt); + } + let ((a, ya), (b, yb)) = if a.rows >= b.rows { ((a, ya), (b, yb)) } else { ((b, yb), (a, ya)) }; + self.gemvq_pair(a, x, x_stride, xq, ya, a.rows, nt, (b.ptr as i64 - a.ptr as i64, yb as i64 - ya as i64, b.rows as i32), 2) + } + + fn moe_gemv(&self, ty: GgmlType, rows: usize, cols: usize, w: u64, stride: usize, ids: u64, k: usize, x: u64, x_stride: usize, + xg: usize, y: u64, pair: Option<(i64, i64)>, xq: u64) -> anyhow::Result<()> { + let (ncols, kn) = Self::gemv_cols("moe_gemv", ty, cols)?; + let (mut c, mut rpw) = Self::gemv_cfg(ty, rows, cols, k); + if rpw == 1 && !Self::float_ty(ty) { + rpw = 2; + c.grid_dim.0 = rows.div_ceil(2 * (Self::gemv_block(k) as usize / 32)) as u32; + } + let (w2, y2) = pair.unwrap_or((0, 0)); + c.grid_dim.2 = if pair.is_some() { 2 } else { 1 }; + if xq != 0 { c.shared_mem_bytes = 0; } + launch!(self, &kn, c, w, ids, stride as i64, x, x_stride as i32, xg as i32, y, rows as i32, ncols, rpw, w2, y2, xq); + Ok(()) + } + + fn dequant(&self, w: &GpuTensor, rows: usize, out: u64) -> anyhow::Result<()> { + launch!(self, &kname("dequant", w.ty), cfg((rows as u32, 1), 256, 0), w.ptr, out, Self::gemv_cols("dequant", w.ty, w.cols)?.0); + Ok(()) + } + + fn quant_xq(&self, x: u64, x_stride: usize, n: usize, nt: usize, out: u64) -> anyhow::Result<()> { + launch!(self, "quant_xq", cfg((nt as u32, 1), 256, 0), x, x_stride as i32, n as i32, out); + Ok(()) + } + + fn rms_norm(&self, x: u64, x_stride: usize, w: u64, out: u64, out_stride: usize, n: usize, rows: usize, eps: f32) -> anyhow::Result<()> { + self.rms_norm_q(x, x_stride, w, out, out_stride, n, rows, eps, 0, 0) + } + + fn rms_norm_q(&self, x: u64, x_stride: usize, w: u64, out: u64, out_stride: usize, n: usize, rows: usize, eps: f32, xq: u64, res: u64) -> anyhow::Result<()> { + launch!(self, "rms_norm", cfg((rows as u32, 1), 512, 0), x, x_stride as i32, w, out, out_stride as i32, n as i32, eps, xq, res, 1i32); + Ok(()) + } + + fn rms_norm_streams(&self, x: u64, w: u64, out: u64, n: usize, hc: usize, nt: usize, eps: f32) -> anyhow::Result<()> { + launch!(self, "rms_norm", cfg(((nt * hc) as u32, 1), 512, 0), x, n as i32, w, out, n as i32, n as i32, eps, 0u64, 0u64, hc as i32); + Ok(()) + } + + fn argmax_rows(&self, x: u64, n: usize, rows: usize, out: u64) -> anyhow::Result<()> { + let part = self.ptr(&self.am); + anyhow::ensure!(rows * AMAX_PARTS <= self.am.len(), "argmax_rows: {rows} rows"); + launch!(self, "argmax_part", cfg((AMAX_PARTS as u32, rows as u32), 256, 0), x, n as i32, part); + launch!(self, "argmax_rows", cfg((rows as u32, 1), AMAX_PARTS as u32, 0), part, n as i32, out); + Ok(()) + } + + fn l2_norm(&self, x: u64, n: usize, per: usize, stride: usize, rows: usize, eps: f32) -> anyhow::Result<()> { + launch!(self, "l2_norm", cfg((rows as u32, 1), 128, 0), x, n as i32, per as i32, stride as i32, eps); + Ok(()) + } + + fn rope_neox(&self, x: u64, stride: usize, heads: usize, per: usize, n_rot: usize, step: u64, base: f32) -> anyhow::Result<()> { + launch!(self, "rope_neox", cfg(((heads / per) as u32, 1), (n_rot / 2) as u32, 0), x, stride as i32, per as i32, n_rot as i32, step, base); + Ok(()) + } + + fn rms_norm_rope(&self, x: u64, x_stride: usize, w: u64, out: u64, n: usize, rows: usize, eps: f32, per: usize, n_rot: usize, step: u64, base: f32) -> anyhow::Result<()> { + self.rms_norm_rope_kv(x, x_stride, w, out, n, rows, eps, per, n_rot, step, base, 0, 0, 0) + } + + fn rms_norm_rope_kv(&self, x: u64, x_stride: usize, w: u64, out: u64, n: usize, rows: usize, eps: f32, per: usize, n_rot: usize, + step: u64, base: f32, v: u64, kc: u64, vc: u64) -> anyhow::Result<()> { + anyhow::ensure!(n_rot <= n.min(512) && n % 32 == 0, "rms_norm_rope: head of {n}, n_rot {n_rot}"); + let fr = self.rope_fr(base, n_rot)?; + launch!(self, "rms_norm_rope", cfg((rows as u32, 1), 256, 0), x, x_stride as i32, w, out, n as i32, eps, per as i32, n_rot as i32, + step, base, v, kc, vc, 0i32, 0u64, 0i32, 0u64, 0u64, 0i32, fr, 0u64); + Ok(()) + } + + fn rms_norm_rope_qk(&self, q: u64, q_stride: usize, qw: u64, qo: u64, qrows: usize, qper: usize, k: u64, kw: u64, ko: u64, + krows: usize, kper: usize, n: usize, eps: f32, n_rot: usize, step: u64, base: f32, v: u64, kc: u64, vc: u64) -> anyhow::Result<()> { + anyhow::ensure!(n_rot <= n.min(512) && n % 32 == 0, "rms_norm_rope: head of {n}, n_rot {n_rot}"); + let fr = self.rope_fr(base, n_rot)?; + launch!(self, "rms_norm_rope", cfg(((qrows + krows) as u32, 1), 256, 0), k, n as i32, kw, ko, n as i32, eps, kper as i32, n_rot as i32, + step, base, v, kc, vc, qrows as i32, q, q_stride as i32, qw, qo, qper as i32, fr, 0u64); + Ok(()) + } + + fn kv_rows(&self) -> bool { true } + + fn rms_norm_rope_qk_rows(&self, q: u64, q_stride: usize, qw: u64, qo: u64, nh: usize, k: u64, kw: u64, ko: u64, nkv: usize, + hd: usize, eps: f32, n_rot: usize, step: u64, base: f32, v: u64, kvt: u64, nt: usize) -> anyhow::Result<()> { + anyhow::ensure!(n_rot <= hd.min(512) && hd % 32 == 0, "rms_norm_rope: head of {hd}, n_rot {n_rot}"); + let fr = self.rope_fr(base, n_rot)?; + launch!(self, "rms_norm_rope", cfg(((nt * (nh + nkv)) as u32, 1), 256, 0), k, hd as i32, kw, ko, hd as i32, eps, nkv as i32, n_rot as i32, + step, base, v, 0u64, 0u64, (nt * nh) as i32, q, q_stride as i32, qw, qo, nh as i32, fr, kvt); + Ok(()) + } + + fn attn_rows(&self, q: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, scale: f32, nt: usize, + sink: u64, win: usize, kvt: u64, splits: usize) -> anyhow::Result<()> { + self.attn(q, 0, 0, qg, out, part, step, nh, nkv, hd, scale, 0, nt, 0, 0, 0, sink, win, kvt, splits) + } + + fn add(&self, x: u64, y: u64, n: usize) -> anyhow::Result<()> { + launch!(self, "add", Self::grid(n), x, y, n as i32); + Ok(()) + } + + fn swiglu(&self, g: u64, u: u64, n: usize) -> anyhow::Result<()> { + launch!(self, "swiglu", Self::grid(n), g, u, n as i32); + Ok(()) + } + + fn swiglu_q(&self, g: u64, u: u64, n: usize, rows: usize, xq: u64) -> anyhow::Result { + launch!(self, "swiglu_q", cfg((n.div_ceil(256) as u32, rows as u32), 32, 0), g, u, n as i32, xq); + Ok(xq) + } + + fn ssm_gates(&self, beta: u64, g: u64, dt_bias: u64, a: u64, n: usize, nv: usize) -> anyhow::Result<()> { + launch!(self, "ssm_gates", Self::grid(n), beta, g, dt_bias, a, n as i32, nv as i32); + Ok(()) + } + + fn conv_silu(&self, qkv: u64, state: u64, w: u64, y: u64, ch: usize, kw: usize, nn: usize, eps: f32) -> anyhow::Result<()> { + launch!(self, "conv_silu", cfg((ch.div_ceil(128) as u32, 1), 128, 0), qkv, state, w, y, ch as i32, kw as i32, nn as i32, eps); + Ok(()) + } + + fn deltanet(&self, y: u64, s: u64, beta: u64, g: u64, dt_bias: u64, a: u64, o: u64, nk: usize, nv: usize, interleave: bool, + dk: usize, dv: usize, scale: f32, t: usize, ych: usize, snap: u64, nsnap: usize) -> anyhow::Result<()> { + let rows = 512 / dk.max(1); + anyhow::ensure!(matches!(dk, 32 | 64 | 128 | 256) && dv % rows == 0, "deltanet: head dims {dk}/{dv} unsupported"); + launch!(self, "deltanet_seq", cfg((nv as u32, dv.div_ceil(8 * rows) as u32), 256, 0), + y, s, beta, g, o, nk as i32, nv as i32, interleave as i32, dk as i32, dv as i32, scale, t as i32, ych as i32, + snap, nsnap as i32, dt_bias, a); + Ok(()) + } + + fn conv_seq(&self, qkv: u64, state: u64, w: u64, y: u64, ch: usize, kw: usize, t: usize, snap: u64, nsnap: usize) -> anyhow::Result<()> { + launch!(self, "conv_seq", Self::grid(t * ch), qkv, state, w, y, ch as i32, kw as i32, t as i32); + launch!(self, "conv_state", Self::grid(ch), qkv, state, ch as i32, kw as i32, t as i32, snap, nsnap as i32); + Ok(()) + } + + fn attn_prefill_m(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, t: usize, nh: usize, nkv: usize, hd: usize, + scale: f32, qm: u64, mw: usize, sink: u64, win: usize) -> anyhow::Result<()> { + if !matches!(hd, 64 | 128 | 256) { bail!("attention prefill: head_dim {hd} unsupported (64, 128 or 256)"); } + // A tile of FA_BK keys needs 72 KiB at head_dim 256, more than a 64 KiB block may use on RDNA; 16 keys a + // tile (the depth the CUDA build uses on Turing's 64 KB blocks) fits, at the cost of more passes. + let bk = [FA_BK, 16, 8].into_iter().find(|&bk| attn_prefill_smem_bk(hd, bk) <= self.max_smem) + .with_context(|| format!("attn_prefill_{hd}: no tile depth fits {} B of shared memory", self.max_smem))?; + let smem = attn_prefill_smem_bk(hd, bk) as u32; + launch!(self, &format!("attn_prefill_{hd}"), cfg((t.div_ceil(64) as u32, nh as u32), 128, smem), + q, kc, vc, qg, out, step, t as i32, nh as i32, nkv as i32, scale, qm, mw as i32, sink, win as i32); + Ok(()) + } + + fn qsa_pool(&self, ik: u64, ring: u64, pool: u64, w: u64, step: u64, t: usize, n_rot: usize, base: f32, eps: f32) -> anyhow::Result<()> { + launch!(self, "qsa_pool", cfg(((t / 4 + 1) as u32, 1), 128, 0), ik, ring, pool, w, step, t as i32, n_rot as i32, base, eps); + Ok(()) + } + + fn qsa_select(&self, q: u64, pool: u64, score: u64, sel: u64, mask: u64, step: u64, r0: usize, rows: usize, nbs: usize, top: usize, sst: usize, mw: usize) -> anyhow::Result<()> { + launch!(self, "qsa_score", cfg((64, rows.div_ceil(8) as u32), 256, 0), q, pool, score, step, r0 as i32, rows as i32, nbs as i32, top as i32); + launch!(self, "qsa_select", cfg((rows as u32, 1), 1024, 0), score, sel, mask, step, r0 as i32, nbs as i32, top as i32, sst as i32, mw as i32); + Ok(()) + } + + fn moe_combine_seq(&self, x: u64, ye: u64, wts: u64, inv: u64, k: usize, sh: u64, sg: u64, n: usize, t: usize) -> anyhow::Result<()> { + launch!(self, "moe_combine_seq", Self::grid(n * t), x, ye, wts, inv, k as i32, sh, sg, n as i32, t as i32); + Ok(()) + } + + fn norm_gate(&self, o: u64, w: u64, z: u64, n: usize, heads: usize, eps: f32) -> anyhow::Result<()> { + self.norm_gate_q(o, w, z, n, heads, eps, 0).map(|_| ()) + } + + fn norm_gate_q(&self, o: u64, w: u64, z: u64, n: usize, heads: usize, eps: f32, xq: u64) -> anyhow::Result { + let xq = if crate::cuda::llama_numerics() || n % 32 != 0 { 0 } else { xq }; + launch!(self, "norm_gate", cfg((heads as u32, 1), 128, 0), o, w, z, n as i32, eps, xq, 0i32); + Ok(xq) + } + + fn norm_gate_sig(&self, o: u64, w: u64, z: u64, n: usize, heads: usize, eps: f32, xq: u64) -> anyhow::Result { + let xq = if crate::cuda::llama_numerics() || n % 32 != 0 { 0 } else { xq }; + launch!(self, "norm_gate", cfg((heads as u32, 1), 128, 0), o, w, z, n as i32, eps, xq, 1i32); + Ok(xq) + } + + fn hc_silu(&self, x: u64, sc: f32, n: usize) -> anyhow::Result<()> { + launch!(self, "hc_silu", Self::grid(n), x, sc, n as i32); + Ok(()) + } + + fn hc_mix(&self, xn: u64, g: u64, out: u64, n: usize, hc: usize, nt: usize) -> anyhow::Result<()> { + launch!(self, "hc_mix", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), xn, g, out, n as i32, hc as i32); + Ok(()) + } + + fn hc_write(&self, r: u64, out: u64, inj: u64, n: usize, hc: usize, nt: usize, clear: bool) -> anyhow::Result<()> { + launch!(self, "hc_write", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), r, out, inj, n as i32, hc as i32, clear as i32); + Ok(()) + } + + fn ple_gate(&self, key: u64, query: u64, value: u64, gated: u64, n: usize, hc: usize, nt: usize) -> anyhow::Result<()> { + launch!(self, "ple_gate", cfg((hc as u32, nt as u32), 256, 0), key, query, value, gated, n as i32); + Ok(()) + } + + fn ple_conv(&self, r: u64, gated: u64, norm: u64, kw: u64, ring: u64, step: u64, d: usize, nt: usize) -> anyhow::Result<()> { + launch!(self, "ple_conv", Self::grid(d), r, gated, norm, kw, ring, step, d as i32, nt as i32); + Ok(()) + } + + fn kv_store(&self, k: u64, v: u64, kc: u64, vc: u64, n: usize, t: usize, step: u64, hd: usize) -> anyhow::Result<()> { + anyhow::ensure!(!self.kv_q8 || (hd % 32 == 0 && n % hd == 0), "q8 KV cache: head_dim {hd} is not a multiple of 32"); + launch!(self, "kv_store", Self::grid(n * t), k, v, kc, vc, n as i32, (n * t) as i32, step, hd as i32); + Ok(()) + } + + fn attn_decode_gq(&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, sink: u64, win: usize) -> anyhow::Result<()> { + self.attn(q, kc, vc, qg, out, part, step, nh, nkv, hd, scale, gq_min, nt, 0, 0, 0, sink, win, 0, ATT_SPLITS_1) + } + + fn attn_decode_q(&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) -> anyhow::Result { + let xq = if crate::cuda::llama_numerics() { 0 } else { xq }; + self.attn(q, kc, vc, qg, out, part, step, nh, nkv, hd, scale, gq_min, nt, xq, sel, sst, sink, win, 0, ATT_SPLITS_1)?; + Ok(xq) + } + + fn router_topk(&self, p: u64, n: usize, k: usize, extra_scale: f32, ids: u64, wts: u64, t: usize, sigmoid: bool) -> anyhow::Result<()> { + anyhow::ensure!(n <= 512 && k <= 32, "router_topk: {n} experts, top {k}"); + launch!(self, "router_topk", cfg((t as u32, 1), 32, 0), p, n as i32, k as i32, extra_scale, ids, wts, sigmoid as i32); + Ok(()) + } + + fn moe_route(&self, p: u64, n: usize, k: usize, extra_scale: f32, table: u64, ids: u64, wts: u64, slots: u64, wh: u64, h: u64, + mb: u64, nh: usize, h_off: usize, step: u64, t: usize, pid: u64, sigmoid: bool) -> anyhow::Result<()> { + anyhow::ensure!(n <= 512 && k <= 32, "moe_route: {n} experts, top {k}"); + launch!(self, "moe_route", cfg((1, 1), 256, 0), p, n as i32, k as i32, extra_scale, table, ids, wts, slots, wh, h, mb, + nh as i32, h_off as i32, step, t as i32, pid, sigmoid as i32); + Ok(()) + } + + fn moe_mailbox_optional(&self) -> bool { true } + fn moe_prefetch_supported(&self) -> bool { false } + + fn moe_combine(&self, x: u64, ye: u64, w: u64, k: usize, sh: u64, sg: u64, mb: u64, y_off: usize, step: u64, slots: u64, n: usize, t: usize) -> anyhow::Result<()> { + let mut c = Self::grid(n); + c.grid_dim.1 = t as u32; + launch!(self, "moe_combine", c, x, ye, w, k as i32, sh, sg, mb, y_off as i32, step, slots, n as i32); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The whole plumbing on the device: allocate, upload, launch a real kernel, read it back. `add` is the + /// simplest kernel in the file, so a failure here is the backend, not the math. + #[test] + fn add_kernel_round_trips() { + let g = match Gpu::new(0) { + Ok(g) => g, + Err(e) => { + eprintln!("skipping: HIP unavailable: {e:#}"); + return; + } + }; + let n = 1024; + let x: Vec = (0..n).map(|i| i as f32).collect(); + let y: Vec = (0..n).map(|i| 0.5 * i as f32).collect(); + let want: Vec = (0..n).map(|i| 1.5 * i as f32).collect(); + let g: &dyn Backend = &g; + let bx = g.alloc(4 * n).unwrap(); + let by = g.alloc(4 * n).unwrap(); + g.put(&x, &bx, 0).unwrap(); + g.put(&y, &by, 0).unwrap(); + // `Backend::add` is x += y, so the result lands in x. + g.add(bx.addr(), by.addr(), n).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&bx, 0, n).unwrap(); + assert!(got.iter().zip(&want).all(|(a, b)| a == b), "first mismatch at {:?}", got.iter().zip(&want).position(|(a, b)| a != b)); + } + + /// `norm_gate` with the quantize-to-int8 epilogue: the first kernel of the qwen35 attention layer, and the one + /// that faulted first on the card, so it gets its own comparison against the reference math. + #[test] + fn norm_gate_matches_the_reference() { + let g = match Gpu::new(0) { Ok(g) => g, Err(e) => { eprintln!("skipping: HIP unavailable: {e:#}"); return } }; + let (heads, n) = (4usize, 128usize); + let mut st = 12345u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 8) as f32 / 16777216.0 - 0.5 }; + let o: Vec = (0..heads * n).map(|_| rnd()).collect(); + let w: Vec = (0..n).map(|_| rnd() + 1.0).collect(); + let z: Vec = (0..heads * n).map(|_| rnd()).collect(); + let want: Vec = (0..heads).flat_map(|h| { + let row = &o[h * n..(h + 1) * n]; + let ss: f32 = row.iter().map(|v| v * v).sum(); + let sc = 1.0 / (ss / n as f32 + 1e-6).sqrt(); + let silu = |v: f32| v / (1.0 + (-v).exp()); + (0..n).map(|i| row[i] * sc * w[i] * silu(z[h * n + i])).collect::>() + }).collect(); + let gx = g.alloc(4 * heads * n).unwrap(); + let gw = g.alloc(4 * n).unwrap(); + let gz = g.alloc(4 * heads * n).unwrap(); + let xq_bytes = heads * n + heads * n / 32 * 4; + let gxq = g.alloc(xq_bytes).unwrap(); + let g: &dyn Backend = &g; + g.put(&o, &gx, 0).unwrap(); + g.put(&w, &gw, 0).unwrap(); + g.put(&z, &gz, 0).unwrap(); + g.norm_gate(gx.addr(), gw.addr(), gz.addr(), n, heads, 1e-6).unwrap(); + g.sync().unwrap(); + eprintln!("plain norm_gate ok: {:?}", &g.get::(&gx, 0, 2).unwrap()); + g.put(&o, &gx, 0).unwrap(); + g.norm_gate_q(gx.addr(), gw.addr(), gz.addr(), n, heads, 1e-6, gxq.addr()).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&gx, 0, heads * n).unwrap(); + let worst = got.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(worst < 2e-5, "max |diff| = {worst}"); + } + + /// The generated source compiles for this device through hiprtc (the CUDA source with `STRATA_HIP` taken). + #[test] + fn hiprtc_compiles_the_kernels() { + let Some(rtc) = ffi::Rtc::get() else { + eprintln!("skipping: no hiprtc"); + return; + }; + let Ok(hip) = ffi::Hip::open() else { + eprintln!("skipping: no HIP runtime"); + return; + }; + let arch = hip.arch(0).unwrap(); + rtc.compile(&source(false), "kernels.cu", &arch, &[]).expect("hiprtc compiles kernels.cu for the device"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 96f17186..24f7f6dd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,6 +9,7 @@ pub mod model; pub mod backend; pub mod cuda; pub mod vulkan; +pub mod hip; pub mod gpu_model; pub mod cpu_moe; pub mod expert_cache; From 4a670a1377e5f2bdd5459aa9fcc32415d4b1e321 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 14:44:41 +0100 Subject: [PATCH 02/26] hip: prefill on the card's matrix cores (gfx11/gfx12 WMMA) gemm_q takes an AMD branch under GEMM_WMMA: D[16x16] += A * B^T through __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12 (the gfx11 form on RDNA3). Both operands are 16 rows of 16 halves, which is how the kernel already stages X (positions) and W (output rows) in shared memory, so the tile loop and the epilogue keep their shape: a warp owns 32x32 outputs (2x2 tiles) in the big-tile kernel and 16x16 in the small-tile one; a lane supplies 8 halves of its own row of each operand (gfx12 splits k across the two half-waves) and holds 8 results, column lane & 15, rows 8*(lane >> 4) + i. Preflight on RX 9070 XT, Qwen3.6-35B-A3B UD-Q4_K_XL, pp 1024: 737 -> 1684 tok/s without MTP and 1569 with it, against 1428 for the Vulkan backend; pp 4096: 2106 tok/s. Greedy output is bit-identical to the CUDA-core prefill on 5 of 6 prompts, and the sixth differs at a near-tie (f16 tensor-core summation order), the same class of difference the CUDA and Vulkan backends have. kernels.cu keeps one source: the whole path is behind #if GEMM_WMMA, which is undefined for the CUDA build. The preprocessed CUDA source is unchanged for GEMM_TC 0/1 x KV_Q8 0/1 x arch 700/750/800/900 (checked by diffing clang -E output before and after). STRATA_HIP_WMMA=0 selects the CUDA-core multiplications, for A/B and as a workaround. --- docs/HIP.md | 38 +++++++++++++++++++++------------ src/cuda/kernels.cu | 52 +++++++++++++++++++++++++++++++++++++++++++-- src/hip/compat.h | 41 +++++++++++++++++++++++++++++++++++ src/hip/mod.rs | 45 ++++++++++++++++++++++++++++++++++++++- 4 files changed, 160 insertions(+), 16 deletions(-) diff --git a/docs/HIP.md b/docs/HIP.md index d237139f..62fc05e6 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -4,9 +4,11 @@ build step: the kernels are compiled at run time by hiprtc and launched through the HIP runtime, both loaded by name (`libamdhip64.so`, `libhiprtc.so`), the way `src/cuda` loads NVRTC. `cargo build --release` is the whole build. -**Status: experimental.** Brought up on Qwen3.6-35B-A3B (RX 9070 XT, gfx1201, ROCm 7.2). Greedy output is identical to -the Vulkan backend on the prompts tried. Not yet ported: matrix cores (prefill runs the f16 CUDA-core path, not WMMA), -graph capture (off by default), and the host-side pipeline details of the CUDA backend (ring staging, side stream). +**Status: experimental.** Brought up on Qwen3.6-35B-A3B (RX 9070 XT, gfx1201, ROCm 7.2.3). Greedy output matches the +other backends: identical to the Vulkan backend on 3 of 4 prompts, and to its own CUDA-core prefill on 5 of 6, with the +difference at a near-tie where the f16 tensor-core summation order picks another token (the same class of difference the +CUDA and Vulkan backends have). Not yet ported: graph capture (off by default) and the host-side pipeline details of the +CUDA backend (pinned ring staging, side stream). ## What runs @@ -14,12 +16,13 @@ Everything the Vulkan backend runs, through the same kernels: | | HIP | Vulkan (same machine, same model) | |---|---|---| -| Greedy tokens, 3 prompts | identical | identical | -| Prefill, pp 1024 | 492 tok/s | 1458 tok/s | -| Decode, tg 48, `--mtp 2` | 159 tok/s | 232 tok/s | +| Prefill, pp 1024, `--mtp 2` | 1569 tok/s | 1428 tok/s | +| Prefill, pp 4096, `--mtp 2` | 2106 tok/s | (not run) | +| Decode, tg 48, `--mtp 2` | 173 tok/s | 231 tok/s | -Qwen3.6-35B-A3B UD-Q4_K_XL, `--ctx 4096 --vram-margin 256`, RX 9070 XT, Ryzen 7 5700X. Decode is within 1.5x of -Vulkan; prefill is 3x behind because the prefill GEMM has no matrix-core path on HIP yet (see below). +Qwen3.6-35B-A3B UD-Q4_K_XL, `--ctx 4096 --vram-margin 256`, RX 9070 XT, Ryzen 7 5700X, one process each. Prefill runs on +the card's matrix cores (below) and is at parity with Vulkan; decode is 1.3x behind, which is the host side (no graph +capture, no side stream) rather than the kernels. ## How it works @@ -30,6 +33,14 @@ Vulkan; prefill is 3x behind because the prefill GEMM has no matrix-core path on instead of `mma.sync`. - The kernels compile as **wave32** (lane = `threadIdx.x & 31`), which is the default wavefront size on RDNA and the assumption the CUDA source already makes about a warp. The backend refuses a device that reports a 64-wide wave. +- **Matrix cores**: the prefill GEMM (`gemm_q` in `kernels.cu`) takes an AMD branch under `GEMM_WMMA`: `D[16x16] += + A * B^T` through `__builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12` (the gfx11 form on RDNA3). Both operands are rows + of 16 halves, which is exactly how the kernel stages X (positions) and W (output rows) in shared memory — no + transpose, and the same tile loop and epilogue shape as the CUDA path. A warp owns 32x32 outputs (2x2 tiles) in the + big-tile kernel and 16x16 in the small-tile one; a lane supplies 8 halves of its own row of each operand (gfx12 + splits the k dimension across the two half-waves) and holds 8 results, column `lane & 15`, rows `8*(lane>>4) + i`. + `STRATA_HIP_WMMA=0` falls back to the CUDA-core multiplications: 737 -> 1684 tok/s prefill at pp 1024 on the RX 9070 + XT, and 5 of 6 prompts bit-identical between the two. - `src/cuda/kernels.cu` keeps one source for both backends: the few places that cannot be shared are behind `#if STRATA_HIP` (f16 conversions, the per-lane fragment loads, `mma884`, the KV f16x2 math, the L2 prefetch hint), so the CUDA build's preprocessed source is unchanged. @@ -50,14 +61,15 @@ Vulkan; prefill is 3x behind because the prefill GEMM has no matrix-core path on - `STRATA_HIP_GRAPH=1` turns on graph capture once the forward allocates nothing inside a step (HIP refuses an allocation on a capturing stream; CUDA's stream-ordered allocator allows it). - `STRATA_NO_GRAPH=1` turns capture off for both GPU backends. +- `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM instead of the matrices cores. ## Next -1. gfx12 WMMA (`__builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12` and its int8 form) for the prefill GEMM: the 3x - prefill gap is exactly the missing matrix-core path. -2. Graph capture: move the per-step allocations (q8 cache growth, rope table) out of the captured region. -3. The CUDA host-side pipeline: a pinned ring for `htod` (expert streaming during prefill) and a side stream for - `beside`. +1. Graph capture: move the per-step allocations (q8 cache growth, rope table) out of the captured region; that and the + side stream are where the remaining decode gap is. +2. The int8 WMMA form (`__builtin_amdgcn_wmma_i32_16x16x16_iu8`) for the integer-weight prefill GEMM, which today takes + the f16 path (`GEMM_TC 0`): less shared-memory traffic per output than the sm_80-style int8 `gemmi_*` kernels. +3. A pinned ring for `htod` so expert streaming during prefill does not sync the stream per tensor. ## Credits diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 3c90061c..82a03d1f 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -1059,6 +1059,10 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int #if __CUDA_ARCH__ < 800 && GEMM_TC // Same 32 f32 storage as acc, seen as 4 m8 tiles x 8 D registers: accv[j][i] == &acc[0][0][0][j*8+i]. float (&accv)[4][8] = reinterpret_cast(acc); +#endif +#if GEMM_WMMA + // The same 32 f32 as 4 WMMA tiles of 8 results: accw[t][i] is tile t, result i of this lane. + float (&accw)[4][8] = reinterpret_cast(acc); #endif // W step kb is decoded into registers (as halves) during step kb - 1's mma and stored after it. constexpr int WQ = 64 * SUBS / NT; @@ -1101,7 +1105,30 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int if (wm < tl.cnt) #pragma unroll for (int kk = 0; kk < BK; kk += 16) { -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // AMD matrix cores: the tile in xs (positions, rows = m) and ws (rows = n) is fed straight in as A and B + // of D[16x16] += A * B^T. A warp owns MT x NT 16x16 tiles: (32 positions, 32 rows) for the big kernel and + // (16 positions, 64 rows) for the small-tile one. Each lane holds 8 results of every tile. + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane); + constexpr int MT = SM ? 1 : 2, NTW = SM ? 1 : 2; + strata_hip::strata_hk wa[MT], wb[NTW]; +#pragma unroll + for (int mt = 0; mt < MT; mt++) wa[mt] = strata_hip::strata_ld_wmma(xs + (wm + mt * 16 + l16) * P + kk + w0); +#pragma unroll + for (int nt = 0; nt < NTW; nt++) wb[nt] = strata_hip::strata_ld_wmma(ws + (wn + nt * 16 + l16) * P + kk + w0); +#pragma unroll + for (int mt = 0; mt < MT; mt++) +#pragma unroll + for (int nt = 0; nt < NTW; nt++) { + float* t = accw[mt * NTW + nt]; + strata_hip::strata_f8 c, r; +#pragma unroll + for (int i = 0; i < 8; i++) c[i] = t[i]; + r = strata_hip::strata_wmma(wa[mt], wb[nt], c); +#pragma unroll + for (int i = 0; i < 8; i++) t[i] = r[i]; + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // Volta: eight m8n8k4 ops replace one m16n8k16 for the same 16-deep k step. The four computations of // each instruction are selected by c = g & 3: SM == false maps them to the four n8 tiles (m8 = j, n8 = // c, 32 f32 per lane in accv[0..3]); SM == true maps them to the four 8x8 quadrants of the 16x16 warp @@ -1141,7 +1168,28 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int __syncthreads(); if (kb + 1 < nk) stw(); } -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // D layout of the AMD WMMA: lane 16*(lane>>4) keeps column lane & 15 and rows 8*(lane>>4) .. +7 of each tile. + { + const int l16 = lane & 15, wl = lane >> 4; + constexpr int MT = SM ? 1 : 2, NTW = SM ? 1 : 2; +#pragma unroll + for (int mt = 0; mt < MT; 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 + 8 * wl + i; + if (r >= tl.cnt) continue; + float* yr = y + (size_t)(tl.m0 + r) * y_stride; + float v = accw[mt * NTW + nt][i]; + yr[n] = act == 0 ? v : act == 1 ? silu(yr[n]) * v : yr[n] + v; + } + } + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // m8n8k4 D layout (PTX ISA 8.5 §9.7.13.4.1): register i = 4*p4 + 2*p2 + e sits at row (t & 1) + 2*p2 + 4*hi // and column (t & 2) + 4*p4 + e of the 8x8 tile. For each fixed c, lanes {4c..4c+3} and {16+4c..19+4c} cover // that tile exactly once; the tile itself is picked by c (n8 = c) and j (m8 = j), or by c alone for SM. diff --git a/src/hip/compat.h b/src/hip/compat.h index 7e37eed8..f0f676ab 100644 --- a/src/hip/compat.h +++ b/src/hip/compat.h @@ -85,6 +85,47 @@ template __device__ __forceinline__ T shfl_sync(unsigned, T v, int __device__ __forceinline__ unsigned ballot_sync(unsigned, int predicate) { return (unsigned)__ballot(predicate); } __device__ __forceinline__ int any_sync(unsigned, int predicate) { return (int)(__ballot(predicate) != 0); } +// ---- matrix cores (gfx11/gfx12 WMMA) ---- +// D[16x16] += A[16x16] * B^T[16x16]: both operands are 16 rows of 16 halves, which is exactly how the prefill GEMM +// stages X (positions) and W (output rows) in shared memory, so no transpose is needed. Each lane supplies the +// k-values of its own row of both operands and holds 8 results: rows 8*(lane>>4) + i, column lane & 15. +// gfx12 splits the k dimension across the two half-waves (each lane gives 8 halves, lanes 16-31 the upper half); +// gfx11 takes all 16 from one lane. +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || \ + defined(__gfx1151__) || defined(__gfx1152__) +#define STRATA_WMMA 1 +#define STRATA_WMMA_K 16 +#elif defined(__gfx1200__) || defined(__gfx1201__) +#define STRATA_WMMA 1 +#define STRATA_WMMA_K 8 +#else +#define STRATA_WMMA 0 +#define STRATA_WMMA_K 0 +#endif +// First k half the lane supplies: gfx12 lanes 16-31 give k 8..15, every lane on gfx11 gives k 0..15. +#define STRATA_WMMA_K0(lane) (((lane) >> 4) * (16 - STRATA_WMMA_K)) + +#if STRATA_WMMA +typedef _Float16 strata_hk __attribute__((ext_vector_type(STRATA_WMMA_K))); +typedef float strata_f8 __attribute__((ext_vector_type(8))); + +__device__ __forceinline__ strata_f8 strata_wmma(strata_hk a, strata_hk b, strata_f8 c) { +#if defined(__gfx1200__) || defined(__gfx1201__) + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); +#else + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); +#endif +} + +/// STRATA_WMMA_K halves at `p` (16-byte aligned); lanes 16-31 read their own upper half of the same row. +__device__ __forceinline__ strata_hk strata_ld_wmma(const unsigned short* p) { + union { uint4 u[STRATA_WMMA_K / 8]; strata_hk h; } c; +#pragma unroll + for (int i = 0; i < STRATA_WMMA_K / 8; i++) c.u[i] = *(const uint4*)(p + 8 * i); + return c.h; +} +#endif + } // namespace strata_hip #define __dp4a(a, b, c) (strata_hip::dp4a((a), (b), (c))) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 80030f72..3a222cb3 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -107,7 +107,7 @@ fn source(kv_q8: bool) -> String { __device__ const unsigned int iq3s_grid[512] = {{{}}};\n\ __device__ const unsigned char ksigns_iq2xs[128] = {{{}}};\n\ __device__ const signed char kvalues_iq4nl[16] = {{{}}};\n\ - #define LLAMA_Q8 {}\n#define KV_Q8 {}\n#define GEMM_TC 0\n\ + #define LLAMA_Q8 {}\n#define KV_Q8 {}\n#define GEMM_TC 0\n#define GEMM_WMMA (STRATA_WMMA && {})\n\ #define GEMM_BM {}\n#define GEMM_BK {}\n#define GEMM_MIN_BLOCKS 1\n#define GEMV_LOADW {}\n\ #define FA_BQ {}\n#define FA_BK {}\n{}", include_str!("compat.h"), @@ -121,6 +121,9 @@ fn source(kv_q8: bool) -> String { join(KVALUES_IQ4NL.iter().map(|v| v.to_string()).collect()), crate::cuda::llama_numerics() as u8, kv_q8 as u8, + // `STRATA_HIP_WMMA=0` falls back to the CUDA-core multiplications (A/B comparison, and a workaround if a + // card's matrix cores misbehave). + (std::env::var("STRATA_HIP_WMMA").map(|v| v != "0").unwrap_or(true)) as u8, GEMM_BM, crate::cuda::GEMM_BK, tuned(std::env::var("STRATA_GEMV_LOADW").ok().as_deref(), 0, |v| v <= 1), @@ -837,6 +840,46 @@ mod tests { assert!(worst < 2e-5, "max |diff| = {worst}"); } + /// `gemm_dense` against a CPU product, both tile regimes: the 16-position warp tile (`SM`) the small shapes take + /// and the 32-position one, which is what the matrix-core path in `gemm_q` computes. + #[test] + fn gemm_dense_matches_cpu_in_both_tile_regimes() { + let Ok(g) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + for (rows, n, cols) in [(128usize, 64usize, 64usize), (8192, 128, 64)] { + let mut st = 7u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + let w: Vec = (0..rows * cols).map(|_| rnd()).collect(); + let x: Vec = (0..n * cols).map(|_| rnd()).collect(); + let mut want = vec![0f32; n * rows]; + for m in 0..n { + for r in 0..rows { + let mut a = 0f32; + for k in 0..cols { a += x[m * cols + k] * w[r * cols + k]; } + want[m * rows + r] = a; + } + } + let gw = g.alloc(4 * rows * cols).unwrap(); + let gx = g.alloc(4 * n * cols).unwrap(); + let gy = g.alloc(4 * n * rows).unwrap(); + let g: &dyn Backend = &g; + g.put(&w, &gw, 0).unwrap(); + g.put(&x, &gx, 0).unwrap(); + let t = GpuTensor::new(GgmlType::F32, rows, cols, gw); + g.gemm_dense(&t, n, gx.addr(), cols, gy.addr(), rows, 0).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&gy, 0, n * rows).unwrap(); + let mut worst = 0f32; + let mut at = 0; + for i in 0..n * rows { + let d = (got[i] - want[i]).abs(); + if d > worst { worst = d; at = i; } + } + // f32 products summed over 64 terms: a few ulps either way, and f16 inputs quantize harder, so compare by + // relative error against the magnitude of the row's terms. + assert!(worst < 1e-2 * cols as f32, "rows {rows}: max |diff| = {worst} at {at} (got {}, want {})", got[at], want[at]); + } + } + /// The generated source compiles for this device through hiprtc (the CUDA source with `STRATA_HIP` taken). #[test] fn hiprtc_compiles_the_kernels() { From 92b28e2d886412613286587067e79b33133714c6 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 14:55:09 +0100 Subject: [PATCH 03/26] hip: graph capture on by default, and parity checks across the local models The step allocates nothing once the rope table exists, so the forward is captured (hipStreamBeginCapture) and replayed: 174 -> 183 tok/s decode on Qwen3.6-35B-A3B. A rope table a capture lacks is deferred the way the CUDA backend defers it (the kernel computes its own frequencies for that pass; the table is made after the capture and the graph recaptured), and htod refuses to run inside a capture instead of failing deep in the driver. STRATA_HIP_GRAPH=0 turns capture off. Checked with --fixed-experts (deterministic placement) against the Vulkan backend: bit-identical greedy output on Qwen3.6-35B-A3B, Ornith-1.5-35B-A3B, Qwen3.5-9B (dense) and Qwen3.8-27B (dense), and graph-on vs graph-off bit-identical on three prompts. Dense prefill is 1.4x Vulkan's (705 vs 497 tok/s on the 27B), dense decode 10% behind (memory-bandwidth bound); 35B decode is at parity with fixed placement (73.8 vs 72.3 tok/s). --- docs/HIP.md | 35 +++++++++++++++++++---------------- src/hip/mod.rs | 36 +++++++++++++++++++++++++++++------- 2 files changed, 48 insertions(+), 23 deletions(-) diff --git a/docs/HIP.md b/docs/HIP.md index 62fc05e6..aac957ce 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -4,11 +4,13 @@ build step: the kernels are compiled at run time by hiprtc and launched through the HIP runtime, both loaded by name (`libamdhip64.so`, `libhiprtc.so`), the way `src/cuda` loads NVRTC. `cargo build --release` is the whole build. -**Status: experimental.** Brought up on Qwen3.6-35B-A3B (RX 9070 XT, gfx1201, ROCm 7.2.3). Greedy output matches the -other backends: identical to the Vulkan backend on 3 of 4 prompts, and to its own CUDA-core prefill on 5 of 6, with the -difference at a near-tie where the f16 tensor-core summation order picks another token (the same class of difference the -CUDA and Vulkan backends have). Not yet ported: graph capture (off by default) and the host-side pipeline details of the -CUDA backend (pinned ring staging, side stream). +**Status: experimental.** Brought up on an RX 9070 XT (gfx1201, ROCm 7.2.3). With `--fixed-experts` (deterministic +placement) the greedy output is **bit-identical to the Vulkan backend** on the four local models tried (Qwen3.6-35B-A3B, +Ornith-1.5-35B-A3B, Qwen3.5-9B dense, Qwen3.8-27B dense) and to its own CUDA-core prefill on 5 of 6 prompts — the odd +one out differs at a near-tie, where the f16 tensor-core summation order picks another token (the same class of +difference the CUDA and Vulkan backends have; with adaptive placement, greedy tokens can also change between runs, as +they do on the other backends). Not yet ported: the host-side pipeline details of the CUDA backend (pinned ring staging +for `htod`, side stream for `beside`). ## What runs @@ -16,13 +18,16 @@ Everything the Vulkan backend runs, through the same kernels: | | HIP | Vulkan (same machine, same model) | |---|---|---| -| Prefill, pp 1024, `--mtp 2` | 1569 tok/s | 1428 tok/s | +| Prefill, pp 1024, `--mtp 2` | 1530 tok/s | 1602 tok/s | | Prefill, pp 4096, `--mtp 2` | 2106 tok/s | (not run) | -| Decode, tg 48, `--mtp 2` | 173 tok/s | 231 tok/s | +| Decode, tg 48, `--mtp 2` | 183 tok/s | 236 tok/s | +| Decode, `--fixed-experts`, same prompt | 73.8 tok/s | 72.3 tok/s | +| Qwen3.8-27B dense, prefill / decode | 705 / 50.3 tok/s | 497 / 55.5 tok/s | -Qwen3.6-35B-A3B UD-Q4_K_XL, `--ctx 4096 --vram-margin 256`, RX 9070 XT, Ryzen 7 5700X, one process each. Prefill runs on -the card's matrix cores (below) and is at parity with Vulkan; decode is 1.3x behind, which is the host side (no graph -capture, no side stream) rather than the kernels. +Qwen3.6-35B-A3B UD-Q4_K_XL (first rows) and Qwen3.8-27B UD-IQ3_S, `--ctx 4096 --vram-margin 256`, one process each. +Prefill runs on the card's matrix cores (below); on a dense model it is 1.4x ahead of Vulkan. Decode with fixed +placement is at parity (the benches above differ because each backend finds its own expert placement, which changes the +MTP draft acceptance); the dense model's decode is 10% behind, memory-bandwidth bound. ## How it works @@ -58,18 +63,16 @@ capture, no side stream) rather than the kernels. - `STRATA_HIP_SYNC=1` waits after every launch, so a hardware exception names the kernel that raised it. - `STRATA_HIP_TRACE=1` names every launch before it goes out (grid, block, shared memory). -- `STRATA_HIP_GRAPH=1` turns on graph capture once the forward allocates nothing inside a step (HIP refuses an - allocation on a capturing stream; CUDA's stream-ordered allocator allows it). +- `STRATA_HIP_GRAPH=0` runs the forward every time instead of capturing it (capture is on by default, +5% decode). - `STRATA_NO_GRAPH=1` turns capture off for both GPU backends. - `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM instead of the matrices cores. ## Next -1. Graph capture: move the per-step allocations (q8 cache growth, rope table) out of the captured region; that and the - side stream are where the remaining decode gap is. -2. The int8 WMMA form (`__builtin_amdgcn_wmma_i32_16x16x16_iu8`) for the integer-weight prefill GEMM, which today takes +1. The int8 WMMA form (`__builtin_amdgcn_wmma_i32_16x16x16_iu8`) for the integer-weight prefill GEMM, which today takes the f16 path (`GEMM_TC 0`): less shared-memory traffic per output than the sm_80-style int8 `gemmi_*` kernels. -3. A pinned ring for `htod` so expert streaming during prefill does not sync the stream per tensor. +2. A pinned ring for `htod` and a side stream for `beside`, so expert uploads overlap with compute in prefill. +3. The int8 WMMA form ## Credits diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 3a222cb3..dbe9bb01 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -21,6 +21,10 @@ use std::sync::{Arc, LazyLock, Mutex}; /// `STRATA_HIP_SYNC`: one sync per launch (see `Gpu::launch`). static SYNC_EACH: LazyLock = LazyLock::new(|| std::env::var_os("STRATA_HIP_SYNC").is_some()); +/// `STRATA_NO_GRAPH` / `STRATA_HIP_GRAPH=0`: run the forward every time instead of capturing it. +static NO_GRAPH: LazyLock = LazyLock::new(|| { + std::env::var_os("STRATA_NO_GRAPH").is_some() || std::env::var("STRATA_HIP_GRAPH").map(|v| v == "0").unwrap_or(false) +}); /// `STRATA_HIP_TRACE`: name every launch before it goes out, so a fault that kills the process names the kernel. static TRACE: LazyLock = LazyLock::new(|| std::env::var_os("STRATA_HIP_TRACE").is_some()); @@ -271,10 +275,23 @@ impl Gpu { (cfg((rows.div_ceil(wpb * rpw) as u32, k as u32), (32 * wpb) as u32, Self::xq_smem(ty, cols)), rpw as i32) } + /// Whether the stream is capturing a graph: no allocation and no synchronous copy may be issued inside one. + fn capturing(&self) -> bool { + let mut status = 0; + unsafe { (self.hip.stream_is_capturing)(self.stream, &mut status) }; + status != 0 + } + /// The rope frequencies base^(-2i / n_rot) as `rms_norm_rope` computes them in f64, made once by `rope_freq`. + /// While a graph is captured a missing table gives 0 (the kernel computes the frequencies itself) and is made + /// after the capture, which `graph` then repeats. fn rope_fr(&self, base: f32, n_rot: usize) -> anyhow::Result { let mut fr = self.fr.lock().unwrap(); if let Some(b) = fr.0.get(&(base.to_bits(), n_rot)) { return Ok(b.addr()) } + if self.capturing() { + fr.1.push((base, n_rot)); + return Ok(0); + } let buf = alloc_raw(&self.hip, 8 * (n_rot / 2).max(1))?; let p = buf.addr(); let (bs, nr) = (base, n_rot as i32); @@ -406,6 +423,7 @@ impl Backend for Gpu { /// drained first so the copy cannot pass kernels already queued that write `dst`. fn htod(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { anyhow::ensure!(off + src.len() <= dst.len(), "htod: {} bytes at {off} into {}", src.len(), dst.len()); + anyhow::ensure!(!self.capturing(), "htod inside a captured graph: the caller must copy before the capture"); self.wait()?; let r = unsafe { (self.hip.memcpy)((dst.addr() + off as u64) as *mut c_void, src.as_ptr().cast(), src.len(), ffi::MEMCPY_H2D) }; self.hip.check(r, "hipMemcpy(htod)") @@ -439,18 +457,16 @@ impl Backend for Gpu { fn sync(&self) -> anyhow::Result<()> { self.wait() } /// Recorded with `hipStreamBeginCapture`: the same launches, replayed by the driver with no host work. - /// Off by default: the forwards allocate inside their step (the q8 cache grows, the rope table is made), and HIP - /// refuses an allocation on a capturing stream ("operation not permitted when stream is capturing"), where CUDA's - /// stream-ordered allocator allows it. `STRATA_HIP_GRAPH=1` turns capture on once the step allocates nothing. + /// HIP refuses an allocation on a capturing stream ("operation not permitted when stream is capturing"), where + /// CUDA's stream-ordered allocator allows it, so anything a step allocates has to be made before the capture (the + /// rope table defers itself, see `rope_fr`). `STRATA_HIP_GRAPH=0` turns capture off. fn graph(&self, key: u64, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { - if std::env::var_os("STRATA_NO_GRAPH").is_some() || std::env::var_os("STRATA_HIP_GRAPH").is_none() { return f() } + if *NO_GRAPH { return f() } if let Some(g) = self.graphs.lock().unwrap().get(&key) { let r = unsafe { (self.hip.graph_launch)(g.exec, self.stream) }; return self.hip.check(r, "hipGraphLaunch"); } - let mut capturing = 0; - unsafe { (self.hip.stream_is_capturing)(self.stream, &mut capturing) }; - if capturing != 0 { return f() } // never nest captures + if self.capturing() { return f() } // never nest captures self.hip.check(unsafe { (self.hip.stream_begin_capture)(self.stream, ffi::CAPTURE_MODE_THREAD_LOCAL) }, "hipStreamBeginCapture")?; let r = f(); let mut graph: ffi::Graph = std::ptr::null_mut(); @@ -461,6 +477,12 @@ impl Backend for Gpu { let mut exec: ffi::GraphExec = std::ptr::null_mut(); self.hip.check(unsafe { (self.hip.graph_instantiate)(&mut exec, graph, 0) }, "hipGraphInstantiate")?; self.hip.check(unsafe { (self.hip.graph_launch)(exec, self.stream) }, "hipGraphLaunch")?; + // A rope table the capture lacked: make it, and capture again next time (this graph computes it per call). + let want = std::mem::take(&mut self.fr.lock().unwrap().1); + if !want.is_empty() { + for (base, n_rot) in want { self.rope_fr(base, n_rot)?; } + return Ok(()); + } self.graphs.lock().unwrap().insert(key, Graph { exec, graph, hip: self.hip.clone() }); Ok(()) } From 08c6297bb6813aa4807f46f5aa6456623c695345 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 16:03:48 +0100 Subject: [PATCH 04/26] hip: pinned staging ring, stream-ordered copies, graph cap, calibration htod goes through a 64 MB pinned ring for copies over 256 KB: the DMA reads one region while the host fills the next, and a region is reused only after the event of the copy that read it completed. Smaller copies are queued asynchronously on the stream instead of a synchronous memcpy after a full stream sync, and memset/memset(alloc) are hipMemsetAsync on the stream -- the null-stream hipMemset could land after a copy queued for the same buffer, which is what made the first version's upload look lost. Graph recording is capped at 32 like the CUDA backend (step_rows keys one graph per combination of sequence slots, each holding device memory). calibrate --backend hip now measures chunk, MTP drafts and the short-prompt threshold and writes strata--hip.json, which later runs read: on Qwen3.6-35B-A3B it picks chunk 4096 and --mtp 3 (prefill 2717 tok/s measured in calibration). With both backends calibrated, pp 1024 / tg 48: HIP 1577-2072 prefill and 188-222 decode, Vulkan 1344 and 195. --- docs/HIP.md | 24 ++++++----- src/hip/ffi.rs | 2 + src/hip/mod.rs | 107 ++++++++++++++++++++++++++++++++++++++++--------- 3 files changed, 105 insertions(+), 28 deletions(-) diff --git a/docs/HIP.md b/docs/HIP.md index aac957ce..d50b6cf1 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -18,16 +18,16 @@ Everything the Vulkan backend runs, through the same kernels: | | HIP | Vulkan (same machine, same model) | |---|---|---| -| Prefill, pp 1024, `--mtp 2` | 1530 tok/s | 1602 tok/s | -| Prefill, pp 4096, `--mtp 2` | 2106 tok/s | (not run) | -| Decode, tg 48, `--mtp 2` | 183 tok/s | 236 tok/s | -| Decode, `--fixed-experts`, same prompt | 73.8 tok/s | 72.3 tok/s | +| Prefill, pp 1024, calibrated | 1577-2072 tok/s | 1344 tok/s | +| Prefill, pp 4096 | 2106 tok/s | (not run) | +| Decode, tg 48, calibrated | 188-222 tok/s | 195 tok/s | | Qwen3.8-27B dense, prefill / decode | 705 / 50.3 tok/s | 497 / 55.5 tok/s | -Qwen3.6-35B-A3B UD-Q4_K_XL (first rows) and Qwen3.8-27B UD-IQ3_S, `--ctx 4096 --vram-margin 256`, one process each. -Prefill runs on the card's matrix cores (below); on a dense model it is 1.4x ahead of Vulkan. Decode with fixed -placement is at parity (the benches above differ because each backend finds its own expert placement, which changes the -MTP draft acceptance); the dense model's decode is 10% behind, memory-bandwidth bound. +Qwen3.6-35B-A3B UD-Q4_K_XL (first rows) and Qwen3.8-27B UD-IQ3_S, `--ctx 4096 --vram-margin 256`, one process each, +`calibrate` run for each backend (chunk 4096; HIP picks `--mtp 3`, Vulkan `--mtp 1`). Prefill runs on the card's matrix +cores (below) and is ahead of Vulkan; decode is within a few percent in either direction — the spread over repeated runs +is larger than the difference, because each backend finds its own expert placement and that moves the MTP draft +acceptance. A dense model's prefill is 1.4x ahead and its decode 10% behind (memory-bandwidth bound). ## How it works @@ -51,6 +51,11 @@ MTP draft acceptance); the dense model's decode is 10% behind, memory-bandwidth so the CUDA build's preprocessed source is unchanged. - The code object is cached in `$XDG_CACHE_HOME/rusting_strata/.amdgcn`, keyed by the source, the `gfx` target and the hiprtc version. +- `calibrate --backend hip` measures chunk, MTP drafts and the short-prompt threshold on this machine and writes + `strata--hip.json`; later runs read it, as they do for the other backends. +- Large `htod`s go through a 64 MB pinned ring (the DMA reads it while the host fills the next region), so expert + streaming does not stop the CPU side; small copies are queued asynchronously on the same stream, and `memset` is + stream-ordered (the null-stream `hipMemset` could land after a copy queued for the same buffer). ## Requirements @@ -71,8 +76,7 @@ MTP draft acceptance); the dense model's decode is 10% behind, memory-bandwidth 1. The int8 WMMA form (`__builtin_amdgcn_wmma_i32_16x16x16_iu8`) for the integer-weight prefill GEMM, which today takes the f16 path (`GEMM_TC 0`): less shared-memory traffic per output than the sm_80-style int8 `gemmi_*` kernels. -2. A pinned ring for `htod` and a side stream for `beside`, so expert uploads overlap with compute in prefill. -3. The int8 WMMA form +2. A side stream for `beside`, so expert uploads overlap with compute in prefill. ## Credits diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs index ed6ea1cf..a8a7590e 100644 --- a/src/hip/ffi.rs +++ b/src/hip/ffi.rs @@ -64,6 +64,7 @@ pub struct Hip { pub malloc: unsafe extern "C" fn(*mut *mut c_void, usize) -> c_int, pub free: unsafe extern "C" fn(*mut c_void) -> c_int, pub memset: unsafe extern "C" fn(*mut c_void, c_int, usize) -> c_int, + pub memset_async: unsafe extern "C" fn(*mut c_void, c_int, usize, Stream) -> c_int, pub memcpy: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int) -> c_int, pub memcpy_async: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int, Stream) -> c_int, pub stream_create: unsafe extern "C" fn(*mut Stream, u32) -> c_int, @@ -129,6 +130,7 @@ impl Hip { malloc: g!("hipMalloc"), free: g!("hipFree"), memset: g!("hipMemset"), + memset_async: g!("hipMemsetAsync"), memcpy: g!("hipMemcpy"), memcpy_async: g!("hipMemcpyAsync"), stream_create: g!("hipStreamCreateWithFlags"), diff --git a/src/hip/mod.rs b/src/hip/mod.rs index dbe9bb01..7db7838f 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -15,7 +15,7 @@ use crate::cuda::{AMAX_PARTS, FA_BK, attn_prefill_smem_bk, dyn_shmem_need, kname use crate::quant::GgmlType; use anyhow::{Context, bail}; use std::any::Any; -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; use std::sync::{Arc, LazyLock, Mutex}; @@ -54,6 +54,9 @@ pub struct Gpu { done: ffi::Event, /// Rope frequency tables, `base` and `n_rot` to the device buffer that holds them. fr: Mutex<(HashMap<(u32, usize), Buf>, Vec<(f32, usize)>)>, + /// 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, } // The HIP handles are raw pointers but the runtime is thread-safe for the calls the backend makes, and `Backend` @@ -201,10 +204,16 @@ impl Gpu { } let am_buf = alloc_raw(&hip, 64 * AMAX_PARTS)?; let q8_buf = alloc_raw(&hip, 1)?; + // Pinned ring for large host-to-device copies. + let mut host: *mut c_void = std::ptr::null_mut(); + hip.check(unsafe { (hip.host_malloc)(&mut host, RING, ffi::HOST_MALLOC_PORTABLE | ffi::HOST_MALLOC_MAPPED) }, "hipHostMalloc(ring)")?; + let mut dev: *mut c_void = std::ptr::null_mut(); + hip.check(unsafe { (hip.host_device_ptr)(&mut dev, host, 0) }, "hipHostGetDevicePointer(ring)")?; + let staging = Staging { pin: Buf::new(dev as u64, RING, PinnedHost { hip: hip.clone(), p: host }), host: host.cast(), head: 0, busy: VecDeque::new() }; let mut done: ffi::Event = std::ptr::null_mut(); hip.check(unsafe { (hip.event_create)(&mut done, ffi::EVENT_DISABLE_TIMING) }, "hipEventCreate")?; Ok(Gpu { hip, device, stream, module, fns, arch, kv_q8, max_smem, am: am_buf, q8: Mutex::new((q8_buf, None)), - graphs: Mutex::new(HashMap::new()), done, fr: Mutex::new((HashMap::new(), Vec::new())) }) + graphs: Mutex::new(HashMap::new()), done, fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging) }) } fn h(&self) -> &ffi::Hip { &self.hip } @@ -378,6 +387,49 @@ impl Gpu { fn grid(n: usize) -> LaunchConfig { cfg((n.div_ceil(256) as u32, 1), 256, 0) } } +/// Pinned host allocation freed with the runtime that made it. +struct PinnedHost { hip: Arc, p: *mut c_void } + +unsafe impl Send for PinnedHost {} +unsafe impl Sync for PinnedHost {} + +impl Drop for PinnedHost { + fn drop(&mut self) { unsafe { (self.hip.host_free)(self.p) }; } +} + +/// Pinned host memory used as a ring for `htod`: a region is free again once the copy that read it has completed. +struct Staging { + pin: Buf, + host: *mut u8, + head: usize, + busy: VecDeque<(usize, usize, Event)>, +} + +/// A `hipEvent_t` that destroys itself; `query` reports completion. +struct Event { hip: Arc, ev: ffi::Event } + +impl Event { + fn new(hip: &Arc) -> anyhow::Result { + let mut ev: ffi::Event = std::ptr::null_mut(); + hip.check(unsafe { (hip.event_create)(&mut ev, ffi::EVENT_DISABLE_TIMING) }, "hipEventCreate")?; + Ok(Event { hip: hip.clone(), ev }) + } + fn record(&self, stream: ffi::Stream) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.event_record)(self.ev, stream) }, "hipEventRecord") + } + fn done(&self) -> bool { unsafe { (self.hip.event_query)(self.ev) == ffi::HIP_SUCCESS } } +} + +impl Drop for Event { + fn drop(&mut self) { unsafe { (self.hip.event_destroy)(self.ev) }; } +} + +/// Recorded graphs kept before a forward runs uncaptured (CUDA's cap, same reason). +const GRAPHS_MAX: usize = 32; + +const RING: usize = 64 << 20; +const RING_MIN: usize = 256 << 10; + fn alloc_raw(hip: &Arc, bytes: usize) -> anyhow::Result { let mut p: *mut c_void = std::ptr::null_mut(); hip.check(unsafe { (hip.malloc)(&mut p, bytes.max(1)) }, "hipMalloc")?; @@ -414,19 +466,39 @@ impl Backend for Gpu { fn alloc(&self, bytes: usize) -> anyhow::Result { let b = alloc_raw(&self.hip, bytes)?; - self.hip.check(unsafe { (self.hip.memset)(b.addr() as *mut c_void, 0, b.len()) }, "hipMemset")?; + self.memset(&b)?; Ok(b) } - /// Synchronous copy: HIP does not promise that an async copy from pageable memory has staged the host buffer when - /// the call returns, and a caller that reuses `src` (every caller does) cannot wait for that. The stream is - /// drained first so the copy cannot pass kernels already queued that write `dst`. + /// Queue a host-to-device copy on the stream and return once `src` may be reused: from pageable memory the + /// runtime stages the buffer inside the call, and large copies go through the pinned ring so the DMA does not + /// stop the host (expert streaming during prefill). fn htod(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { anyhow::ensure!(off + src.len() <= dst.len(), "htod: {} bytes at {off} into {}", src.len(), dst.len()); - anyhow::ensure!(!self.capturing(), "htod inside a captured graph: the caller must copy before the capture"); - self.wait()?; - let r = unsafe { (self.hip.memcpy)((dst.addr() + off as u64) as *mut c_void, src.as_ptr().cast(), src.len(), ffi::MEMCPY_H2D) }; - self.hip.check(r, "hipMemcpy(htod)") + if src.len() < RING_MIN { + let r = unsafe { (self.hip.memcpy_async)((dst.addr() + off as u64) as *mut c_void, src.as_ptr().cast(), src.len(), + ffi::MEMCPY_H2D, self.stream) }; + return self.hip.check(r, "hipMemcpyAsync(htod)"); + } + let mut g = self.staging.lock().unwrap(); + for (i, c) in src.chunks(RING).enumerate() { + if g.head + c.len() > RING { g.head = 0; } + let (a, b) = (g.head, g.head + c.len()); + // Regions still being read by an earlier copy have to complete before the host overwrites them. + while g.busy.iter().any(|&(s, e, _)| s < b && a < e) { + let (_, _, ev) = g.busy.pop_front().unwrap(); + self.hip.check(unsafe { (self.hip.event_sync)(ev.ev) }, "hipEventSynchronize")?; + } + unsafe { std::ptr::copy_nonoverlapping(c.as_ptr(), g.host.add(a), c.len()) }; + let r = unsafe { (self.hip.memcpy_async)((dst.addr() + (off + i * RING) as u64) as *mut c_void, + g.host.add(a) as *const c_void, c.len(), ffi::MEMCPY_H2D, self.stream) }; + self.hip.check(r, "hipMemcpyAsync(htod ring)")?; + let ev = Event::new(&self.hip)?; + ev.record(self.stream)?; + g.busy.push_back((a, b, ev)); + g.head = b; + } + Ok(()) } fn dtoh(&self, src: &Buf, off: usize, dst: &mut [u8]) -> anyhow::Result<()> { @@ -444,8 +516,10 @@ impl Backend for Gpu { self.hip.check(r, "hipMemcpyAsync(dtod)") } + /// On the stream, so it is ordered against the copies and launches around it (the plain `hipMemset` goes to the + /// null stream and can land after a copy that was queued for the same buffer). fn memset(&self, dst: &Buf) -> anyhow::Result<()> { - self.hip.check(unsafe { (self.hip.memset)(dst.addr() as *mut c_void, 0, dst.len()) }, "hipMemset") + self.hip.check(unsafe { (self.hip.memset_async)(dst.addr() as *mut c_void, 0, dst.len(), self.stream) }, "hipMemsetAsync") } fn mem_info(&self) -> anyhow::Result<(usize, usize)> { @@ -466,6 +540,9 @@ impl Backend for Gpu { let r = unsafe { (self.hip.graph_launch)(g.exec, self.stream) }; return self.hip.check(r, "hipGraphLaunch"); } + // Each graph holds device memory and `step_rows` keys one per combination of sequence slots: past the cap a + // forward runs uncaptured (the CUDA backend caps for the same reason). + if self.graphs.lock().unwrap().len() >= GRAPHS_MAX { return f() } if self.capturing() { return f() } // never nest captures self.hip.check(unsafe { (self.hip.stream_begin_capture)(self.stream, ffi::CAPTURE_MODE_THREAD_LOCAL) }, "hipStreamBeginCapture")?; let r = f(); @@ -495,13 +572,7 @@ impl Backend for Gpu { let mut dev: *mut c_void = std::ptr::null_mut(); self.hip.check(unsafe { (self.hip.host_device_ptr)(&mut dev, host, 0) }, "hipHostGetDevicePointer")?; unsafe { std::ptr::write_bytes(host as *mut u8, 0, 4 * n) }; - struct Pinned { hip: Arc, p: *mut c_void } - unsafe impl Send for Pinned {} - unsafe impl Sync for Pinned {} - impl Drop for Pinned { - fn drop(&mut self) { unsafe { (self.hip.host_free)(self.p) }; } - } - let owner = Pinned { hip: self.hip.clone(), p: host }; + let owner = PinnedHost { hip: self.hip.clone(), p: host }; Ok((Buf::new(dev as u64, 4 * n, owner), host.cast())) } From f3f29c8773bb34e3b1a9383b9c46e5dbc802f1a1 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 17:04:56 +0100 Subject: [PATCH 05/26] hip: why the prefill GEMM keeps the f16 matrix cores (int8 measured, not assumed) The CUDA backend runs integer weight types as int8 mma.sync; porting that assumed NVIDIA's premises hold on RDNA4, and they do not. Two probes, both model-free and committed under tools/hip, settle it: - wmma_rate: v_wmma_i32_16x16x16_iu8 is only 2x v_wmma_f32_16x16x16_f16 on gfx1201 (137 vs 57 TMAC/s). - wmma_rescale: in the kernel's inner-loop shape (2x2 tiles, four 16-deep k-steps from shared memory), int8 without its epilogue takes 0.35x the time of f16 -- but the per-16-weight scale and min the K-quants carry cost a multiplication per result, and AMD's layout gives a lane 8 results in 8 different rows, so the fold is 8 scalar operations each. With a vector-friendly layout it is 6.6x slower than f16, with the source's layout 13-16x. So GEMM_TC stays 0 on HIP: the prefill GEMM dequantizes to f16 in shared memory and runs on the f16 matrix cores, which is what puts HIP ahead of Vulkan on prefill. docs/HIP.md records the numbers so the next person does not repeat the port. --- docs/HIP.md | 16 ++++ tools/hip/README.md | 16 ++++ tools/hip/wmma_rate.cpp | 42 ++++++++++ tools/hip/wmma_rescale.cpp | 166 +++++++++++++++++++++++++++++++++++++ 4 files changed, 240 insertions(+) create mode 100644 tools/hip/README.md create mode 100644 tools/hip/wmma_rate.cpp create mode 100644 tools/hip/wmma_rescale.cpp diff --git a/docs/HIP.md b/docs/HIP.md index d50b6cf1..d4f4841c 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -72,6 +72,22 @@ acceptance. A dense model's prefill is 1.4x ahead and its decode 10% behind (mem - `STRATA_NO_GRAPH=1` turns capture off for both GPU backends. - `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM instead of the matrices cores. +## Why the prefill GEMM does not use int8 matrix cores + +The CUDA backend runs integer weight types as int8 `mma.sync` because NVIDIA's int8 tensor cores are 2-4x its f16 ones +and its layout puts each lane's 4 results over 2 rows and 2 columns, so the per-16-weight scale and min the K-quants +carry cost 2 multiplications a result. On RDNA4 both premises fail: + +- `v_wmma_i32_16x16x16_iu8` is only **2x** `v_wmma_f32_16x16x16_f16` (137 vs 57 TMAC/s on gfx1201, + `tools/hip/wmma_rate.cpp`). +- AMD's WMMA layout gives a lane 8 results in 8 *different rows*, so the scale of each result is different and the + rescale costs ~8 scalar operations per result — per 16-key group, not once per GEMM. + +Measured in the kernel's own inner-loop shape (`tools/hip/wmma_rescale.cpp`): int8 without its epilogue runs in 0.35x +the time of f16, with a vector-friendly rescale 6.6x *slower*, with the layout the source uses 13-16x slower. The +integer path cannot pay for itself here, so `GEMM_TC` stays 0 on HIP and the prefill GEMM dequantizes to f16 in shared +memory and runs on the f16 matrix cores, which is what puts it ahead of the Vulkan backend. + ## Next 1. The int8 WMMA form (`__builtin_amdgcn_wmma_i32_16x16x16_iu8`) for the integer-weight prefill GEMM, which today takes diff --git a/tools/hip/README.md b/tools/hip/README.md new file mode 100644 index 00000000..bf5b4c7e --- /dev/null +++ b/tools/hip/README.md @@ -0,0 +1,16 @@ +# HIP micro-benchmarks + +Device-side probes behind the decisions in `docs/HIP.md`. Build and run with the ROCm compiler; they need no model and +no RustingStrata binary: + +```sh +hipcc --offload-arch=gfx1201 -O3 wmma_rate.cpp -o wmma_rate && ./wmma_rate +hipcc --offload-arch=gfx1201 -O3 wmma_rescale.cpp -o wmma_rescale && ./wmma_rescale +``` + +- `wmma_rate.cpp`: the matrix-core instruction rate of the two operand types, operands in registers, so the numbers + are the instruction rate and not memory bandwidth. On RX 9070 XT (gfx1201): f16 57 TMAC/s, int8 137 TMAC/s. +- `wmma_rescale.cpp`: the inner-loop shape of the prefill GEMM (`gemm_q`: 2x2 tiles of 16x16, four 16-deep k-steps per + BK = 64, fragments from shared memory), as f16 and as int8 with the epilogue the integer weight formats need. The + int8 instruction is twice as fast on its own (0.35x the time) but the per-16-weight rescale takes it to 6.6x the f16 + time even written SoA with 8 rows contiguous per lane, which is why the HIP backend keeps the f16 matrix-core path. diff --git a/tools/hip/wmma_rate.cpp b/tools/hip/wmma_rate.cpp new file mode 100644 index 00000000..9cd2561e --- /dev/null +++ b/tools/hip/wmma_rate.cpp @@ -0,0 +1,42 @@ +// Isolated matrix-core rate: f16 WMMA vs int8 WMMA, same 16x16x16 shape, operands in registers so the number is the +// instruction rate, not memory bandwidth. +#include +#include +using h8 = _Float16 __attribute__((ext_vector_type(8))); +using f8 = float __attribute__((ext_vector_type(8))); +using i8v = int __attribute__((ext_vector_type(8))); +using b8 = int __attribute__((ext_vector_type(2))); // 8 int8 values + +__global__ void f16_loop(float* out, int iters) { + h8 a, b; f8 c; + for (int i = 0; i < 8; i++) { a[i] = (_Float16)i * 0.001f; b[i] = (_Float16)i * 0.002f; c[i] = 0.f; } + for (int t = 0; t < iters; t++) { c = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); a[0] += 1e-7f; } + float s = 0; for (int i = 0; i < 8; i++) s += c[i]; + if (threadIdx.x == 0) out[blockIdx.x] = s; +} +__global__ void i8_loop(float* out, int iters) { + b8 a = {0x01020304, 0x05060708}; + b8 b = {0x11121314, 0x15161718}; + i8v c; for (int i = 0; i < 8; i++) c[i] = 0; + for (int t = 0; t < iters; t++) { c = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a, true, b, c, false); a[0] ^= 1; } + int s = 0; for (int i = 0; i < 8; i++) s += c[i]; + if (threadIdx.x == 0) out[blockIdx.x] = (float)s; +} +template static float run(K k, int blocks, int iters) { + float* out; hipMalloc(&out, blocks * 4); + hipEvent_t a, b; hipEventCreate(&a); hipEventCreate(&b); + k<<>>(out, 16); // warm up + hipDeviceSynchronize(); + hipEventRecord(a); k<<>>(out, iters); hipEventRecord(b); hipEventSynchronize(b); + float ms = 0; hipEventElapsedTime(&ms, a, b); + hipFree(out); + double macs = (double)blocks * 2.0 * 4096.0 * iters; // 2 warps a block, 16x16x16 + return (float)(macs / (ms * 1e-3) / 1e12); +} +int main() { + int iters = 20000; + for (int blocks : {256, 1024}) { + printf("blocks %4d: f16 %.3f TMAC/s | i8 %.3f TMAC/s\n", blocks, run(f16_loop, blocks, iters), run(i8_loop, blocks, iters)); + } + return 0; +} diff --git a/tools/hip/wmma_rescale.cpp b/tools/hip/wmma_rescale.cpp new file mode 100644 index 00000000..6b85583a --- /dev/null +++ b/tools/hip/wmma_rescale.cpp @@ -0,0 +1,166 @@ +// Inner-loop shapes of the prefill GEMM: f16 WMMA vs int8 WMMA with the per-16 rescale fold that int8 needs. +// Both read their fragments from the same shared-memory tiles and run 16 WMMA per k-step (2x2 tiles of 16x16, 4 +// k-groups), which is one GEMM_TC step of the 128-thread warp tile. +#include +#include +using h8 = _Float16 __attribute__((ext_vector_type(8))); +using f8 = float __attribute__((ext_vector_type(8))); +using b8 = int __attribute__((ext_vector_type(2))); +using i8v = int __attribute__((ext_vector_type(8))); + +#define P 72 +__global__ void f16_loop(float* out, int iters) { + __shared__ __align__(16) _Float16 xs[128 * P], ws[64 * P]; + int tid = threadIdx.x; + for (int i = tid; i < 128 * P; i += blockDim.x) xs[i] = (_Float16)(i & 7) * 0.01f; + for (int i = tid; i < 64 * P; i += blockDim.x) ws[i] = (_Float16)(i & 7) * 0.01f; + __syncthreads(); + int warp = tid >> 5, lane = tid & 31, l16 = lane & 15, w0 = (lane >> 4) * 8; + int wm = (warp >> 1) * 32, wn = (warp & 1) * 32; + f8 acc[4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) acc[i][j] = 0.f; + for (int t = 0; t < iters; t++) { + #pragma unroll + for (int kk = 0; kk < 64; kk += 16) { + h8 a[2], b[2]; + #pragma unroll + for (int mt = 0; mt < 2; mt++) *(uint4*)&a[mt] = *(const uint4*)(xs + (wm + mt * 16 + l16) * P + kk + w0); + #pragma unroll + for (int nt = 0; nt < 2; nt++) *(uint4*)&b[nt] = *(const uint4*)(ws + (wn + nt * 16 + l16) * P + kk + w0); + #pragma unroll + for (int mt = 0; mt < 2; mt++) for (int nt = 0; nt < 2; nt++) + acc[mt * 2 + nt] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a[mt], b[nt], acc[mt * 2 + nt]); + } + } + float s = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) s += acc[i][j]; + if (tid == 0) out[blockIdx.x] = s; +} +__global__ void i8_loop(float* out, int iters) { + __shared__ __align__(16) signed char xq[128 * P], wq[64 * P]; + __shared__ float xd[128][2], xs2[128][4]; // X scale per 32 keys, X sums per 16 keys + __shared__ float2 wdm[4][64]; // W scale and min per 16 weights + int tid = threadIdx.x; + for (int i = tid; i < 128 * P; i += blockDim.x) xq[i] = (signed char)(i & 31); + for (int i = tid; i < 64 * P; i += blockDim.x) wq[i] = (signed char)(i & 31); + for (int i = tid; i < 128; i += blockDim.x) { xd[i][0] = 0.01f; xd[i][1] = 0.02f; for (int j = 0; j < 4; j++) xs2[i][j] = 0.5f; } + for (int i = tid; i < 64; i += blockDim.x) for (int g = 0; g < 4; g++) wdm[g][i] = make_float2(0.01f, 0.3f); + __syncthreads(); + int warp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4, w0 = hi * 8; + int wm = (warp >> 1) * 32, wn = (warp & 1) * 32; + f8 acc[4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) acc[i][j] = 0.f; + for (int t = 0; t < iters; t++) { + #pragma unroll + for (int g = 0; g < 4; g++) { // 16-key groups = one weight scale + b8 a[2], b[2]; + #pragma unroll + for (int mt = 0; mt < 2; mt++) *(uint2*)&a[mt] = *(const uint2*)(xq + (wm + mt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int nt = 0; nt < 2; nt++) *(uint2*)&b[nt] = *(const uint2*)(wq + (wn + nt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int mt = 0; mt < 2; mt++) + #pragma unroll + for (int nt = 0; nt < 2; nt++) { + i8v c = {0,0,0,0,0,0,0,0}; + i8v r = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a[mt], true, b[nt], c, false); + float2 wq2 = wdm[g][wn + nt * 16 + l16]; + int base = wm + mt * 16 + 8 * hi; + f8 a4 = acc[mt * 2 + nt]; + #pragma unroll + for (int i = 0; i < 8; i++) { + float dx = xd[base + i][g >> 1]; + float sx = xs2[base + i][g]; + a4[i] += (float)r[i] * dx * wq2.x - sx * wq2.y; + acc[mt * 2 + nt] = a4; + } + } + } + } + float s = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) s += acc[i][j]; + if (tid == 0) out[blockIdx.x] = s; +} + +__global__ void i8_nofold(float* out, int iters) { + __shared__ __align__(16) signed char xq[128 * P], wq[64 * P]; + int tid = threadIdx.x; + for (int i = tid; i < 128 * P; i += blockDim.x) xq[i] = (signed char)(i & 31); + for (int i = tid; i < 64 * P; i += blockDim.x) wq[i] = (signed char)(i & 31); + __syncthreads(); + int warp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4, w0 = hi * 8; + int wm = (warp >> 1) * 32, wn = (warp & 1) * 32; + i8v acc[4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) acc[i][j] = 0; + for (int t = 0; t < iters; t++) { + #pragma unroll + for (int g = 0; g < 4; g++) { + b8 a[2], b[2]; + #pragma unroll + for (int mt = 0; mt < 2; mt++) *(uint2*)&a[mt] = *(const uint2*)(xq + (wm + mt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int nt = 0; nt < 2; nt++) *(uint2*)&b[nt] = *(const uint2*)(wq + (wn + nt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int mt = 0; mt < 2; mt++) for (int nt = 0; nt < 2; nt++) + acc[mt * 2 + nt] = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a[mt], true, b[nt], acc[mt * 2 + nt], false); + } + } + int s = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) s += acc[i][j]; + if (tid == 0) out[blockIdx.x] = (float)s; +} +// SoA fold: 8 rows of the lane are consecutive, so a scale is one 8-wide vector of separate arrays. +__global__ void i8_soa(float* out, int iters) { + __shared__ __align__(16) signed char xq[128 * P], wq[64 * P]; + __shared__ float dx0[128], sx0[128]; // X scale (one per 32 keys) and X sum (one per 16 keys) + __shared__ float2 wdm[4][64]; + int tid = threadIdx.x; + for (int i = tid; i < 128 * P; i += blockDim.x) xq[i] = (signed char)(i & 31); + for (int i = tid; i < 64 * P; i += blockDim.x) wq[i] = (signed char)(i & 31); + for (int i = tid; i < 128; i += blockDim.x) { dx0[i] = 0.01f; sx0[i] = 0.5f; } + for (int i = tid; i < 64; i += blockDim.x) for (int g = 0; g < 4; g++) wdm[g][i] = make_float2(0.01f, 0.3f); + __syncthreads(); + int warp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4, w0 = hi * 8; + int wm = (warp >> 1) * 32, wn = (warp & 1) * 32; + f8 acc[4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) acc[i][j] = 0.f; + for (int t = 0; t < iters; t++) { + #pragma unroll + for (int g = 0; g < 4; g++) { + b8 a[2], b[2]; + #pragma unroll + for (int mt = 0; mt < 2; mt++) *(uint2*)&a[mt] = *(const uint2*)(xq + (wm + mt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int nt = 0; nt < 2; nt++) *(uint2*)&b[nt] = *(const uint2*)(wq + (wn + nt * 16 + l16) * P + g * 16 + w0); + #pragma unroll + for (int mt = 0; mt < 2; mt++) + #pragma unroll + for (int nt = 0; nt < 2; nt++) { + i8v c = {0,0,0,0,0,0,0,0}; + i8v r = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a[mt], true, b[nt], c, false); + float2 wq2 = wdm[g][wn + nt * 16 + l16]; + int base = wm + mt * 16 + 8 * hi; + const float* dx = dx0 + base; + const float* sx = sx0 + base; + f8 a4 = acc[mt * 2 + nt]; + #pragma unroll + for (int i = 0; i < 8; i++) a4[i] += (float)r[i] * dx[i] * wq2.x - sx[i] * wq2.y; + acc[mt * 2 + nt] = a4; + } + } + } + float s = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 8; j++) s += acc[i][j]; + if (tid == 0) out[blockIdx.x] = s; +} + +template static float run(K k, int blocks, int iters) { + float* out; hipMalloc(&out, blocks * 4); + hipEvent_t a, b; hipEventCreate(&a); hipEventCreate(&b); + k<<>>(out, 16); hipDeviceSynchronize(); + hipEventRecord(a); k<<>>(out, iters); hipEventRecord(b); hipEventSynchronize(b); + float ms = 0; hipEventElapsedTime(&ms, a, b); hipFree(out); + return (float)ms; +} +int main() { + int iters = 200000; + for (int blocks : {256, 1024}) { + float f = run(f16_loop, blocks, iters), i = run(i8_loop, blocks, iters); + float n = run(i8_nofold, blocks, iters), so = run(i8_soa, blocks, iters); + printf("blocks %4d: f16 %.2f | i8 nofold %.2f (%.2fx) | i8 SoA fold %.2f (%.2fx) | i8 scalar fold %.2f (%.2fx)\n", + blocks, f, n, n / f, so, so / f, i, i / f); + } + return 0; +} From 5f8d1681c1ecb8754c144b11351f8ae9961a3562 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 17:06:17 +0100 Subject: [PATCH 06/26] hip: serve verified on the ROCm backend GET /v1/models, a non-streaming chat completion, a streaming one (SSE deltas) and a second turn that reuses the prompt cache (prompt_tokens_details.cached_tokens = 16 of 51) all work on HIP with Qwen3.5-9B. --- docs/HIP.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/HIP.md b/docs/HIP.md index d4f4841c..8b97987a 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -29,6 +29,9 @@ cores (below) and is ahead of Vulkan; decode is within a few percent in either d is larger than the difference, because each backend finds its own expert placement and that moves the MTP draft acceptance. A dense model's prefill is 1.4x ahead and its decode 10% behind (memory-bandwidth bound). +`serve` works too, checked on Qwen3.5-9B: `GET /v1/models`, non-streaming and streaming (`stream: true`) chat +completions, and the prompt cache across turns (`prompt_tokens_details.cached_tokens` on a follow-up request). + ## How it works - `src/hip/compat.h` is prepended to `kernels.cu`: it supplies the CUDA intrinsics the source uses (`__shfl_*_sync`, From 6feb823fd0e3b8bb135fe7481df7a604473cb9a0 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 18:16:48 +0100 Subject: [PATCH 07/26] hip: long-prompt numbers, and where the depth-dependent cost goes Benchmarks at 32k and 128k on the 35B model (pp and gen at both depths) plus a dense comparison, recorded in docs/HIP.md. With placement equalised (--fixed-experts: same residents, no swaps) decode is at parity but prefill loses 10% at 8k and 56% at 32k; at 128k HIP is 173 tok/s against Vulkan's 762. Fitting the per-token cost against depth isolates it: HIP 572 -> 1389 us/token from 8k to 32k, Vulkan 516 -> 614, so HIP's depth-dependent cost is 33 ns per position against 4 -- 8.4x -- and the same fit predicts the 128k numbers within the spread. Only attention grows with depth, and the prefill attention is the one kernel family still on the CUDA cores (the mma16816 emulation): the matrix-core port covered gemm_q only. Dense Qwen3.8-27B shows the same shape (HIP ahead at 8k, behind at 32k). Next: port attn_prefill_t to the gfx11/gfx12 WMMA the GEMM now uses. --- docs/HIP.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/HIP.md b/docs/HIP.md index 8b97987a..9b979903 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -32,6 +32,28 @@ acceptance. A dense model's prefill is 1.4x ahead and its decode 10% behind (mem `serve` works too, checked on Qwen3.5-9B: `GET /v1/models`, non-streaming and streaming (`stream: true`) chat completions, and the prompt cache across turns (`prompt_tokens_details.cached_tokens` on a follow-up request). +## Long prompts + +Prefill degrades with prompt depth on both backends (attention is the only depth-dependent term), but faster on HIP, +because the prefill attention still runs on the CUDA cores: only the prefill GEMM has an AMD matrix-core path so far. + +Qwen3.6-35B-A3B UD-Q4_K_XL, `--mtp 0 --reps 1 --vram-margin 256`, KV `f16`: + +| | HIP | Vulkan | +|---|---|---| +| pp 32k / gen at 32k | 670 / 80.8 tok/s | 1584 / 108.8 tok/s | +| pp 128k / gen at 128k | 173 / 59.2 tok/s | 762 / 83.4 tok/s | +| pp 8k, `--fixed-experts` | 1748 tok/s | 1938 tok/s | +| pp 32k, `--fixed-experts` | 720 tok/s | 1629 tok/s | +| dense Qwen3.8-27B, pp 8k / 32k | 601 / 328 tok/s | 475 / 404 tok/s | + +With placement equalised (`--fixed-experts`: same residents, zero swaps) decode is at parity (63.8 vs 66.0 tok/s) and +prefill loses 10% at 8k and 56% at 32k. Fitting the per-token cost against depth (HIP 572 -> 1389 us from 8k to 32k, +Vulkan 516 -> 614) gives a depth slope of 33 vs 4 ns per position: HIP's attention costs 8.4x more per position, and +that same fit predicts the 128k numbers (215 vs 995 tok/s) within the measurement's spread. Porting `attn_prefill_t` +to the matrix cores the way `gemm_q` was ported is the next step; until then, `--chunk 0`-style token-by-token prefill +is not the answer, but a shorter `--ctx` and `--kv q8` both buy expert slots back. + ## How it works - `src/hip/compat.h` is prepended to `kernels.cu`: it supplies the CUDA intrinsics the source uses (`__shfl_*_sync`, From 5aa14362cb7a4985225e71e733288c1d553b35a4 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 20:04:23 +0100 Subject: [PATCH 08/26] hip: the prefill attention's V fragment read every other key ldsm4t's HIP branch loaded the high half of each transposed register two rows down instead of one, so the P*V product on the CUDA cores paired key 2k with key 2k+2: every even key's V row was counted twice and every odd one's never, while the softmax row sums still counted all of them. A long prompt's attention output was therefore wrong on every head, silently -- HIP and Vulkan never disagreed on the token parity checks because those prompts are shorter than the short-prompt threshold (32 tokens) and decoding runs `step`/`attn_rows`, which never reaches attn_prefill_t. On CUDA the same line is a byte offset (`a + 2 * PQ`), which is one row for a u16 pointer; the HIP port dropped the pointer arithmetic's unit. Found with a new device test: `hip::tests::attn_prefill_matches_cpu` runs attn_prefill_m against a CPU reference (q, k, v random, causal, four heads over two KV heads) at head_dim 128 and 256 and compares every element. Before the fix it reports a max |diff| of 2.2e3 on an output whose values are ~0.05; after it, 1.2e-4 (f16 rounding of q, k and the softmax weights). The same test pins the causal mask, the partial last query tile and both tile depths. head_dim 256 needed its shared-memory size fixed in the same commit: the kernel takes a 16-key tile there (FA_BK_FOR, as the CUDA build does on Turing's 64 KB blocks) while attn_prefill_m picked the depth by what fit, which was 16 too but by a different rule; the launcher now mirrors the kernel's choice instead of guessing, so a smaller allocation than the kernel addresses cannot come back. --- src/cuda/kernels.cu | 6 ++-- src/hip/mod.rs | 79 ++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 78 insertions(+), 7 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 82a03d1f..aefc9b1b 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -956,7 +956,7 @@ __device__ __forceinline__ void ldsm4t(u32* r, const u16* p) { int m_row = (RM ? (m & 1) : (m >> 1)) * 8, m_col = (RM ? (m >> 1) : (m & 1)) * 8; #if STRATA_HIP const u16* a = p + (m_row + row) * PQ + m_col + col; - r[m] = (u32)a[0] | ((u32)a[2 * PQ] << 16); + r[m] = (u32)a[0] | ((u32)a[PQ] << 16); #else unsigned a = (unsigned)__cvta_generic_to_shared(p + (m_row + row) * PQ + m_col + col); unsigned short lo, hi; @@ -2483,8 +2483,8 @@ extern "C" __global__ void moe_combine_seq(float* x, const float* ye, const floa #endif #define FA_BK_DEFAULT FA_BK // Turing's 64 KB shared memory cannot hold the HD = 256 tile at 32 keys either: 16 fit (the kernel keeps the same -// 64 queries a block and four warps). -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750 && __CUDA_ARCH__ < 800 +// 64 queries a block and four warps). The HIP build has the same 64 KB a workgroup, so it takes the same 16-key tile. +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750 && __CUDA_ARCH__ < 800) || STRATA_HIP #define FA_BK_FOR(HD) ((HD) == 256 ? 16 : FA_BK_DEFAULT) #else #define FA_BK_FOR(HD) FA_BK_DEFAULT diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 7db7838f..e722d824 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -754,11 +754,13 @@ impl Backend for Gpu { fn attn_prefill_m(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, t: usize, nh: usize, nkv: usize, hd: usize, scale: f32, qm: u64, mw: usize, sink: u64, win: usize) -> anyhow::Result<()> { if !matches!(hd, 64 | 128 | 256) { bail!("attention prefill: head_dim {hd} unsupported (64, 128 or 256)"); } - // A tile of FA_BK keys needs 72 KiB at head_dim 256, more than a 64 KiB block may use on RDNA; 16 keys a - // tile (the depth the CUDA build uses on Turing's 64 KB blocks) fits, at the cost of more passes. - let bk = [FA_BK, 16, 8].into_iter().find(|&bk| attn_prefill_smem_bk(hd, bk) <= self.max_smem) - .with_context(|| format!("attn_prefill_{hd}: no tile depth fits {} B of shared memory", self.max_smem))?; + // A tile of FA_BK keys needs 72 KiB at head_dim 256, more than a 64 KiB workgroup may use on RDNA; 16 keys a + // tile (the depth the CUDA build uses on Turing's 64 KB blocks) fits, at the cost of more passes. This has to + // be the depth the kernel picks for itself (`FA_BK_FOR(HD)`), not a smaller one: the kernel would then address + // shared memory past what is allocated. + let bk = if hd == 256 { 16 } else { FA_BK }; let smem = attn_prefill_smem_bk(hd, bk) as u32; + anyhow::ensure!(smem as usize <= self.max_smem, "attn_prefill_{hd}: {smem} B of shared memory, {} allowed", self.max_smem); launch!(self, &format!("attn_prefill_{hd}"), cfg((t.div_ceil(64) as u32, nh as u32), 128, smem), q, kc, vc, qg, out, step, t as i32, nh as i32, nkv as i32, scale, qm, mw as i32, sink, win as i32); Ok(()) @@ -973,6 +975,75 @@ mod tests { } } + /// `attn_prefill_t` end to end (score product, causal softmax, P·V, the epilogue) against a CPU reference, at + /// head_dim 128 (32-key tiles) and 256 (the HIP build's 16-key tiles) with a partial last query tile. This is the + /// check the matrix-core score path needs on its own: a wrong lane/lane-staging mapping shows up as a large + /// per-element difference on a specific query or head, not as the near-tie token flips a parity run sees. + #[test] + fn attn_prefill_matches_cpu() { + use half::f16; + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let (t, nh, nkv) = (40usize, 4usize, 2usize); + let scale = 0.088388347; + for hd in [128usize, 256] { + let mut st = 99u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + let q: Vec = (0..t * nh * hd).map(|_| rnd()).collect(); + let kh: Vec = (0..t * nkv * hd).map(|_| f16::from_f32(rnd()).to_bits()).collect(); + let vh: Vec = (0..t * nkv * hd).map(|_| f16::from_f32(rnd()).to_bits()).collect(); + let half = |h: u16| f16::from_bits(h).to_f32(); + // Reference: the kernel scales Q before rounding it to f16, sums in f32, rounds the weights to f16 to + // feed P·V, and divides by the row sum at the end (`out = o * inv` with `inv = sc / den`). + let mut want = vec![0f32; t * nh * hd]; + for h in 0..nh { + let kvh = h / (nh / nkv); + for ti in 0..t { + let mut sc = vec![0f32; ti + 1]; + for (j, s) in sc.iter_mut().enumerate() { + let mut a = 0f32; + for d in 0..hd { + a += half(f16::from_f32(q[ti * nh * hd + h * hd + d] * scale).to_bits()) + * half(kh[(j * nkv + kvh) * hd + d]); + } + *s = a; + } + let mx = sc.iter().cloned().fold(f32::NEG_INFINITY, f32::max); + let e: Vec = sc.iter().map(|s| (s - mx).exp()).collect(); + let den: f32 = e.iter().sum(); + for d in 0..hd { + let mut a = 0f32; + for (j, w) in e.iter().enumerate() { + a += half(f16::from_f32(w / den).to_bits()) * half(vh[(j * nkv + kvh) * hd + d]); + } + want[ti * nh * hd + h * hd + d] = a; + } + } + } + let gq = g.alloc(4 * q.len()).unwrap(); + let gk = g.alloc(2 * kh.len()).unwrap(); + let gv = g.alloc(2 * vh.len()).unwrap(); + let go = g.alloc(4 * q.len()).unwrap(); + let gs = g.alloc(4).unwrap(); + g.put(&q, &gq, 0).unwrap(); + g.put(&kh, &gk, 0).unwrap(); + g.put(&vh, &gv, 0).unwrap(); + g.put(&[0i32], &gs, 0).unwrap(); + g.attn_prefill_m(gq.addr(), gk.addr(), gv.addr(), 0, go.addr(), gs.addr(), t, nh, nkv, hd, scale, 0, 0, 0, 0).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&go, 0, q.len()).unwrap(); + let mut worst = 0f32; + let (mut at, mut gv_) = (0, 0f32); + for i in 0..q.len() { + let d = (got[i] - want[i]).abs(); + if d > worst { worst = d; at = i; gv_ = got[i]; } + } + eprintln!("hd {hd}: max |diff| = {worst:e} at {at} (row {}, head {}, d {}): got {gv_} want {}", + at / (nh * hd), (at / hd) % nh, at % hd, want[at]); + assert!(worst < 5e-3, "hd {hd}: max |diff| = {worst} at {at}"); + } + } + /// The generated source compiles for this device through hiprtc (the CUDA source with `STRATA_HIP` taken). #[test] fn hiprtc_compiles_the_kernels() { From 3d5cdf7be335b8ec734e7b789a6a8c210cec89e5 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 20:07:08 +0100 Subject: [PATCH 09/26] hip: prefill attention scores on the matrix cores attn_prefill_t's Q*K^T product was the last depth-dependent kernel family on the CUDA cores: it cost 8-11 ns per position of prompt depth against Vulkan's 5.6, and prefill fell behind Vulkan as prompts grew (pp 32k 794 tok/s against 1661). It now takes the same GEMM_WMMA instruction the prefill GEMM uses, one 16-query x 16-key tile per instruction against the 16-half qs/ks rows. The one thing the instruction does not give for free is where its results land: 8 per lane, column `lane & 15` and rows `8*(lane>>4) + i`, while the softmax, the causal/QSA mask and the P*V step all read the m16n8k16 layout (row g / g + 8, keys 2t / 2t + 1). So a warp writes its 16 x FA_BKL tile of f32 scores to a private staging tile and reads back the four values each lane owns in the layout below, `s[ng][2h + e] == S[warp*16 + g + 8h][ng*8 + 2t + e]`; one __syncwarp() publishes it, since a warp only reads what it wrote itself. The staging tile (FA_BQ x (FA_BKL + 8) floats) is added to the block's dynamic shared memory in hip::Gpu::attn_prefill_m only, so attn_prefill_smem_bk stays shared with CUDA and Vulkan. head_dim 256 takes 16 keys a step under STRATA_HIP (FA_BK_FOR, as the CUDA build already does on Turing's 64 KB blocks): 32 keys with the staging tile need 78 KiB and a workgroup may use 64. At 128k depth the same build does 660 tok/s against Vulkan's 731 (it was 173 against 762), decode 48.3 against 44.2. Measured on Qwen3.6-35B-A3B UD-Q4_K_XL, --mtp 0 --fixed-experts (same placement, same build, two runs each, one process each): pp 8192 1308 / 1303 -> 2556 / 2558 tok/s (Vulkan 2152 / 2148) pp 32768 794 / 776 -> 1677 / 1502 tok/s (Vulkan 1661) decode is unchanged (73-75 at 8k, 64-67 at 32k), and the depth slope of the per-token cost drops from 20-21 to 8-11 ns per position. HIP is now ahead of Vulkan at 8k and level at 32k; the P*V product below is the other half. Verified three ways. `hip::tests::attn_prefill_matches_cpu` (added with the ldsm4t fix) covers this path at both tile depths, 1.2e-4 / 1.7e-4 against a CPU reference. STRATA_HIP_WMMA=0 against this build gives bit-identical greedy output on a 79-token prompt and on the pp 8k/32k runs, so the summation order change is below the token decision. And greedy output is bit-identical to Vulkan on five long prose prompts (64-79 tokens, so through this kernel) on the 35B and two on the dense 9B with --fixed-experts --mtp 0, where the pre-fix build disagreed on 2 of 2 long prompts tried. The CUDA build's preprocessed source is unchanged (clang -E over GEMM_TC{0,1} x KV_Q8{0,1} x arch{700,750,800,900}: identical modulo blank lines and line markers). docs/HIP.md: the long-prompt section now reports the A/B, the slopes and pp 128k (660 tok/s against Vulkan's 731, up from 173 against 762), "Status" states what the parity check covers (bit-identical with --mtp 0; with the calibrated drafts on, the two backends verify different batch shapes and 1 of 7 probes flips at a near-tie), and "Next" is down to the P*V port and the side stream. --- docs/HIP.md | 83 +++++++++++++++++++++++++++++---------------- src/cuda/kernels.cu | 40 ++++++++++++++++++++-- src/hip/mod.rs | 11 +++--- 3 files changed, 98 insertions(+), 36 deletions(-) diff --git a/docs/HIP.md b/docs/HIP.md index 9b979903..bf22def1 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -4,13 +4,14 @@ build step: the kernels are compiled at run time by hiprtc and launched through the HIP runtime, both loaded by name (`libamdhip64.so`, `libhiprtc.so`), the way `src/cuda` loads NVRTC. `cargo build --release` is the whole build. -**Status: experimental.** Brought up on an RX 9070 XT (gfx1201, ROCm 7.2.3). With `--fixed-experts` (deterministic -placement) the greedy output is **bit-identical to the Vulkan backend** on the four local models tried (Qwen3.6-35B-A3B, -Ornith-1.5-35B-A3B, Qwen3.5-9B dense, Qwen3.8-27B dense) and to its own CUDA-core prefill on 5 of 6 prompts — the odd -one out differs at a near-tie, where the f16 tensor-core summation order picks another token (the same class of -difference the CUDA and Vulkan backends have; with adaptive placement, greedy tokens can also change between runs, as -they do on the other backends). Not yet ported: the host-side pipeline details of the CUDA backend (pinned ring staging -for `htod`, side stream for `beside`). +**Status: experimental.** Brought up on an RX 9070 XT (gfx1201, ROCm 7.2.3). With `--fixed-experts --mtp 0` +(deterministic placement, no speculative verify) the greedy output is **bit-identical to the Vulkan backend** on the +four local models tried (Qwen3.6-35B-A3B, Ornith-1.5-35B-A3B, Qwen3.5-9B dense, Qwen3.8-27B dense): five long prose +prompts (64-79 tokens, i.e. through the batched prefill and its attention) and two short ones on the 35B, two long ones +on the 9B. With the calibrated MTP drafts on (3 on this machine, 1 on Vulkan) the two backends verify different batch +shapes, so a near-tie can pick another token — 1 of those 7 probes does — and `--mtp 0` on both sides makes it agree. +HIP's prefill attention is pinned to a CPU f32 reference to 2e-4 by `hip::tests::attn_prefill_matches_cpu`. Not yet +ported: the host-side pipeline details of the CUDA backend (pinned ring staging for `htod`, side stream for `beside`). ## What runs @@ -34,25 +35,33 @@ completions, and the prompt cache across turns (`prompt_tokens_details.cached_to ## Long prompts -Prefill degrades with prompt depth on both backends (attention is the only depth-dependent term), but faster on HIP, -because the prefill attention still runs on the CUDA cores: only the prefill GEMM has an AMD matrix-core path so far. - -Qwen3.6-35B-A3B UD-Q4_K_XL, `--mtp 0 --reps 1 --vram-margin 256`, KV `f16`: - -| | HIP | Vulkan | -|---|---|---| -| pp 32k / gen at 32k | 670 / 80.8 tok/s | 1584 / 108.8 tok/s | -| pp 128k / gen at 128k | 173 / 59.2 tok/s | 762 / 83.4 tok/s | -| pp 8k, `--fixed-experts` | 1748 tok/s | 1938 tok/s | -| pp 32k, `--fixed-experts` | 720 tok/s | 1629 tok/s | -| dense Qwen3.8-27B, pp 8k / 32k | 601 / 328 tok/s | 475 / 404 tok/s | - -With placement equalised (`--fixed-experts`: same residents, zero swaps) decode is at parity (63.8 vs 66.0 tok/s) and -prefill loses 10% at 8k and 56% at 32k. Fitting the per-token cost against depth (HIP 572 -> 1389 us from 8k to 32k, -Vulkan 516 -> 614) gives a depth slope of 33 vs 4 ns per position: HIP's attention costs 8.4x more per position, and -that same fit predicts the 128k numbers (215 vs 995 tok/s) within the measurement's spread. Porting `attn_prefill_t` -to the matrix cores the way `gemm_q` was ported is the next step; until then, `--chunk 0`-style token-by-token prefill -is not the answer, but a shorter `--ctx` and `--kv q8` both buy expert slots back. +Prefill degrades with prompt depth on both backends (attention is the only depth-dependent term). The Q·Kᵀ score +product of the prefill attention runs on the card's matrix cores (below); the P·V product still runs on the CUDA cores, +which is where the remaining depth cost sits. + +Qwen3.6-35B-A3B UD-Q4_K_XL, `--mtp 0 --reps 1 --vram-margin 256`, KV `f16`, `--fixed-experts` (two runs where a +range is given, one process each): + +| pp | HIP | Vulkan | HIP, CUDA-core scores (`STRATA_HIP_WMMA=0`) | +|---|---|---|---| +| 8192 | 2556-2558 tok/s | 2148-2152 tok/s | 1303-1308 tok/s | +| 32768 | 1502-1677 tok/s | 1661 tok/s | 776-794 tok/s | +| 131072 | 660 tok/s | 731 tok/s | (not run) | +| decode at 8k / 32k / 128k | 73-75 / 64-67 / 48 tok/s | 71-72 / 68 / 44 tok/s | 74 / 64-65 / - | + +Fitting the per-token cost against depth gives a slope of 8-11 ns per position over 8k -> 32k (9.2 over 8k -> 128k) +for HIP and 5.6 over 8k -> 32k (7.3 over 8k -> 128k) for Vulkan, against 20-21 ns per position for HIP with the +CUDA-core scores — the matrix-core score product is worth **2x on prefill at depth** (pp 32k 794 -> 1677 tok/s, +pp 8k 1308 -> 2558 tok/s, same placement in the same build). At 128k HIP now does 660 tok/s against Vulkan's 731 +(prefill was 173 against 762) and is ahead on decode (48.3 against 44.2); at 32k the two are level, and at 8k HIP is +ahead. The earlier numbers in this file (pp 32k 720 tok/s, pp 128k 173, gen 80.8, slope 33 ns) were taken with the +CUDA-core scores and are the ones to compare against. `--chunk 0`-style token-by-token prefill is still not the +answer, but a shorter `--ctx` and `--kv q8` both buy expert slots back. + +Two caveats on the numbers: `--fixed-experts` only means "same residents, no re-placement during the run", so the +spread between two runs of the same build (1502 vs 1677 at 32k) is expert placement and host page-cache state, not the +kernel; and a prompt's depth cost is the fit over the two depths, not either point. A 128k prompt costs more VRAM in +the KV cache than a 16 GB card has left over for experts, so the run above streams most of them from host memory. ## How it works @@ -71,6 +80,20 @@ is not the answer, but a shorter `--ctx` and `--kv q8` both buy expert slots bac splits the k dimension across the two half-waves) and holds 8 results, column `lane & 15`, rows `8*(lane>>4) + i`. `STRATA_HIP_WMMA=0` falls back to the CUDA-core multiplications: 737 -> 1684 tok/s prefill at pp 1024 on the RX 9070 XT, and 5 of 6 prompts bit-identical between the two. +- **Matrix-core prefill attention** (`attn_prefill_t`): the same WMMA computes the Q·Kᵀ score tile, one 16-query x + 16-key instruction against the 16-half `qs`/`ks` rows. Its 8 results a lane land in AMD's layout (rows + `8*(lane>>4) + i`, column `lane & 15`) rather than the m16n8k16 layout the softmax, the causal mask and the P·V + step are written for, so the tile is staged through a warp-private f32 tile (`FA_BQ` x (`FA_BKL` + 8) floats, 4-6 + KiB on top of `qs`/`ks`/`vs`) and read back as `s[ng][2h + e] == S[warp*16 + g + 8h][ng*8 + 2t + e]`. That tile is + why head_dim 256 prefill takes 16 keys a step (`FA_BK_FOR`, as on Turing's 64 KB blocks): 32 keys would need 78 KiB + of a block's 64. The CUDA-core scores (`STRATA_HIP_WMMA=0`) and the matrix-core ones give the same greedy output on + the model, and the CPU-reference test covers both. +- The transposed V fragment (`ldsm4t`, the P·V operand) is the one CUDA-core multiplicand left in the attention: on HIP + it reads the two halves of a register as *adjacent* keys, which is what the `ldmatrix.trans` fragments mean. An + emulation that read them two rows apart (every even key counted twice, every odd one never) shipped with the first + HIP commit: it moved no token on the short prompts the parity checks used, and on the batched prefill it made every + long prompt disagree with Vulkan. `hip::tests::attn_prefill_matches_cpu` pins it now, and five long prompts agree + token for token with Vulkan afterwards. - `src/cuda/kernels.cu` keeps one source for both backends: the few places that cannot be shared are behind `#if STRATA_HIP` (f16 conversions, the per-lane fragment loads, `mma884`, the KV f16x2 math, the L2 prefetch hint), so the CUDA build's preprocessed source is unchanged. @@ -95,7 +118,8 @@ is not the answer, but a shorter `--ctx` and `--kv q8` both buy expert slots bac - `STRATA_HIP_TRACE=1` names every launch before it goes out (grid, block, shared memory). - `STRATA_HIP_GRAPH=0` runs the forward every time instead of capturing it (capture is on by default, +5% decode). - `STRATA_NO_GRAPH=1` turns capture off for both GPU backends. -- `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM instead of the matrices cores. +- `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM and the prefill attention instead of the + matrix cores. ## Why the prefill GEMM does not use int8 matrix cores @@ -115,8 +139,9 @@ memory and runs on the f16 matrix cores, which is what puts it ahead of the Vulk ## Next -1. The int8 WMMA form (`__builtin_amdgcn_wmma_i32_16x16x16_iu8`) for the integer-weight prefill GEMM, which today takes - the f16 path (`GEMM_TC 0`): less shared-memory traffic per output than the sm_80-style int8 `gemmi_*` kernels. +1. The P·V product of the prefill attention on the matrix cores (the score product is ported, see above): `A = P` from + the staging tile, `B = Vᵀ`, which needs transposed V fragments and an accumulator layout that does not match the + softmax's per-row `m`/`l` bookkeeping — stage it like the scores. Worth about the other half of the depth slope. 2. A side stream for `beside`, so expert uploads overlap with compute in prefill. ## Credits diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index aefc9b1b..9fa380d9 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -2483,7 +2483,8 @@ extern "C" __global__ void moe_combine_seq(float* x, const float* ye, const floa #endif #define FA_BK_DEFAULT FA_BK // Turing's 64 KB shared memory cannot hold the HD = 256 tile at 32 keys either: 16 fit (the kernel keeps the same -// 64 queries a block and four warps). The HIP build has the same 64 KB a workgroup, so it takes the same 16-key tile. +// 64 queries a block and four warps). The HIP build has the same 64 KB a workgroup, and its score staging tile comes +// on top of the qs/ks/vs/ps sizes, so it takes the same 16-key tile. #if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750 && __CUDA_ARCH__ < 800) || STRATA_HIP #define FA_BK_FOR(HD) ((HD) == 256 ? 16 : FA_BK_DEFAULT) #else @@ -2510,6 +2511,14 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co // Volta only: warp-private P tile for the PV A fragments (see the staging in the PV step below). Appended after // `vs` so the qs/ks/vs offsets above do not move; FA_BQ * (FA_BKL + 8) halves = 5120 B. u16* ps = vs + FA_BKL * PQ; +#endif +#if GEMM_WMMA + // HIP: the P staging tile in halves (the PV A fragments, as on Volta) and, after it, the f32 tile the matrix-core + // scores are staged through before they are read in the m16n8k16 layout the softmax below is written for. Both + // sit after `vs` so the qs/ks/vs offsets do not move; `hip::Gpu::attn_prefill_m` adds the f32 tile to the block's + // dynamic shared memory (FA_BQ * (FA_BKL + 8) floats, 4-8 KiB). + u16* ps = vs + FA_BKL * PQ; + float* st = (float*)(ps + FA_BQ * (FA_BKL + 8)); #endif // The last query tiles see the most keys: start them first so the short ones fill the tail. int pos0 = step[0], q0 = (gridDim.x - 1 - blockIdx.x) * FA_BQ, h = blockIdx.y, kvh = h / (nh / nkv), kvd = nkv * HD; @@ -2594,7 +2603,34 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co bool skip = qm && !__any_sync(0xffffffff, (vis[0] | vis[1]) != 0); #endif float s[FA_BKL / 8][4] = {}; -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // Q K^T on the matrix cores: one 16-query x 16-key tile per instruction against the 16-half qs/ks rows, then + // staged and read back so the softmax keeps its m16n8k16 lane layout (row g / g + 8, keys 2t / 2t + 1). The + // warp writes and reads only its own 16 rows of the tile, so a warp barrier publishes it. + if (!skip) { + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane), PW = FA_BKL + 8; + float* sw = st + warp * 16 * PW; + const u16* qrow = qs + (warp * 16 + l16) * PQ + w0; +#pragma unroll + for (int kg = 0; kg < FA_BKL / 16; kg++) { + strata_hip::strata_f8 acc; +#pragma unroll + for (int i = 0; i < 8; i++) acc[i] = 0.0f; + const u16* krow = ks + (kg * 16 + l16) * PQ + w0; +#pragma unroll + for (int kk = 0; kk < HD; kk += 16) + acc = strata_hip::strata_wmma(strata_hip::strata_ld_wmma(qrow + kk), strata_hip::strata_ld_wmma(krow + kk), acc); +#pragma unroll + for (int i = 0; i < 8; i++) sw[(8 * (lane >> 4) + i) * PW + kg * 16 + l16] = acc[i]; + } + __syncwarp(); +#pragma unroll + for (int ng = 0; ng < FA_BKL / 8; ng++) +#pragma unroll + for (int i = 0; i < 4; i++) + s[ng][i] = sw[(g + 8 * (i >> 1)) * PW + ng * 8 + 2 * t4 + (i & 1)]; + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // Same 16 f32 storage as s, seen as m8n8k4 D registers: s2[ng][j][4*p4 + 2*p2 + e] is S[8*j + (t & 1) + // 2*p2 + 4*hi][8*(4*ng + c) + (t & 2) + 4*p4 + e] of the 16 x FA_BKL score tile. Every lane holds the four // computations its c selects, so the warp must stay in uniform control flow (`skip` is warp-uniform). diff --git a/src/hip/mod.rs b/src/hip/mod.rs index e722d824..741e8acd 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -754,12 +754,13 @@ impl Backend for Gpu { fn attn_prefill_m(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, t: usize, nh: usize, nkv: usize, hd: usize, scale: f32, qm: u64, mw: usize, sink: u64, win: usize) -> anyhow::Result<()> { if !matches!(hd, 64 | 128 | 256) { bail!("attention prefill: head_dim {hd} unsupported (64, 128 or 256)"); } - // A tile of FA_BK keys needs 72 KiB at head_dim 256, more than a 64 KiB workgroup may use on RDNA; 16 keys a - // tile (the depth the CUDA build uses on Turing's 64 KB blocks) fits, at the cost of more passes. This has to - // be the depth the kernel picks for itself (`FA_BK_FOR(HD)`), not a smaller one: the kernel would then address - // shared memory past what is allocated. + // The tile depth has to be the one the kernel picks for itself (`FA_BK_FOR(HD)`, which takes 16 keys rather than + // 32 at head_dim 256): 32 keys plus the score staging tile need 78 KiB, more than a 64 KiB workgroup may use, + // while 16 keys need 58 KiB. A smaller depth here would under-allocate what the kernel addresses. let bk = if hd == 256 { 16 } else { FA_BK }; - let smem = attn_prefill_smem_bk(hd, bk) as u32; + // The HIP kernel stages its matrix-core scores through an extra FA_BQ x (bk + 8) f32 tile (see attn_prefill_t); + // the qs/ks/vs/ps sizes the shared helper computes are the same as CUDA's. + let smem = (attn_prefill_smem_bk(hd, bk) + 4 * crate::cuda::FA_BQ * (bk + 8)) as u32; anyhow::ensure!(smem as usize <= self.max_smem, "attn_prefill_{hd}: {smem} B of shared memory, {} allowed", self.max_smem); launch!(self, &format!("attn_prefill_{hd}"), cfg((t.div_ceil(64) as u32, nh as u32), 128, smem), q, kc, vc, qg, out, step, t as i32, nh as i32, nkv as i32, scale, qm, mw as i32, sink, win as i32); From 223a737621c2d84a63db377e530e8c8591858642 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Mon, 16 Nov 2026 21:16:37 +0100 Subject: [PATCH 10/26] hip: prefill attention P*V on the matrix cores, and the depth cost is gone Both products of attn_prefill_t now run on the card's matrix cores. Q*K^T took the score tile two commits ago; this takes P*V, which had become the bigger half: with the scores ported, removing the P*V step entirely was worth pp 32k 1677 -> 2674 tok/s, i.e. 37-44% of the prefill time at that depth. A = P comes from the half staging tile the Volta path already had (ps, unused on HIP until now): the softmax's registers already hold adjacent key pairs of one row, so the tile is one 32-bit store a pair. B = V^T needs its operand's 16 rows to be head dimensions with the 16 k-values being keys, which no row of the V tile is, so strata_ld_wmma_t reads it down a column (one half a key apart) instead of through a 16-byte vector load. The results land in AMD's layout again (rows 8*(lane>>4)+i, column lane & 15), so each 16x16 tile is staged in f32 -- in the same warp-private `st` tile the scores use, which is free by then -- and read back into the two m16n8k16 dim tiles the rescale and the epilogue are written for. Reusing `st` is why the shared-memory request does not change. Measured on Qwen3.6-35B-A3B UD-Q4_K_XL, --mtp 0 --fixed-experts, same placement, same build: pp 8192 2556 / 2558 -> 2647 / 2666 tok/s (Vulkan 2148 / 2152) pp 32768 1677 / 1502 -> 2029 / 2026 tok/s (Vulkan 1661) pp 131072 660 -> 872 tok/s (Vulkan 731) The depth slope of the per-token cost is now 4.7 ns per position over 8k -> 32k against Vulkan's 5.6 (6.3 against 7.3 over 8k -> 128k), down from 20-21 with the attention on the CUDA cores: 3.4x on prefill at depth, and HIP is ahead of Vulkan at every depth tried. Decode is unmoved (68-73 / 64 / 48). The run-to-run spread also collapsed from 10% to under 1% at 32k, which says the P*V instruction count was what the CPU-side expert copies used to hide behind. hip::tests::attn_prefill_matches_cpu grew to head_dim 128 with 130 queries (three query tiles, five key tiles) and head_dim 256 with 70, and both are 1.5e-4 against the CPU reference (f16 rounding of q, k and the softmax weights), so the layout staging is pinned on both products; STRATA_HIP_WMMA=0 covers the CUDA-core path with the same test. Greedy parity with Vulkan (--fixed-experts --mtp 0) holds on 4 of 5 long prose prompts and 2 of 2 on the dense 9B; the fifth prompt flips at a near-tie after ten tokens, where all 5 agreed with P*V left on the CUDA cores -- the hardware sums a 16-deep dot product in another order than the emulation does. docs/HIP.md carries that, the new numbers and the refreshed short-prompt table (pp 4096 2993 against Vulkan's 2325; dense 27B pp 1024 784 against 508). --- docs/HIP.md | 118 ++++++++++++++++++++++++-------------------- src/cuda/kernels.cu | 42 +++++++++++++++- src/hip/compat.h | 10 ++++ src/hip/mod.rs | 15 +++--- 4 files changed, 124 insertions(+), 61 deletions(-) diff --git a/docs/HIP.md b/docs/HIP.md index bf22def1..66b7ee65 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -6,12 +6,16 @@ build step: the kernels are compiled at run time by hiprtc and launched through **Status: experimental.** Brought up on an RX 9070 XT (gfx1201, ROCm 7.2.3). With `--fixed-experts --mtp 0` (deterministic placement, no speculative verify) the greedy output is **bit-identical to the Vulkan backend** on the -four local models tried (Qwen3.6-35B-A3B, Ornith-1.5-35B-A3B, Qwen3.5-9B dense, Qwen3.8-27B dense): five long prose -prompts (64-79 tokens, i.e. through the batched prefill and its attention) and two short ones on the 35B, two long ones -on the 9B. With the calibrated MTP drafts on (3 on this machine, 1 on Vulkan) the two backends verify different batch -shapes, so a near-tie can pick another token — 1 of those 7 probes does — and `--mtp 0` on both sides makes it agree. -HIP's prefill attention is pinned to a CPU f32 reference to 2e-4 by `hip::tests::attn_prefill_matches_cpu`. Not yet -ported: the host-side pipeline details of the CUDA backend (pinned ring staging for `htod`, side stream for `beside`). +four local models tried (Qwen3.6-35B-A3B, Ornith-1.5-35B-A3B, Qwen3.5-9B dense, Qwen3.8-27B dense) for the decode +path, and on the batched prefill path 4 of 5 long prose prompts (64-79 tokens) agree token for token on the 35B +(head_dim 128), 2 of 2 on the dense 9B and 1 of 2 on the dense 27B: the fifth 35B prompt flips at a near-tie after +ten tokens, because the matrix cores sum a 16-deep dot product in a different order than Vulkan does (all 5 agree +with the P·V product left on the CUDA cores), and the 27B flips on its first token with either attention path — at +head_dim 256 it takes 16-key tiles where Vulkan goes deeper, so its softmax and P·V sum over more steps. With the +calibrated MTP drafts on (3 on this machine, 1 on Vulkan) the two backends verify different batch shapes, so 1 of +those 7 probes flips too. HIP's prefill attention is pinned to a CPU f32 reference to 2e-4 by +`hip::tests::attn_prefill_matches_cpu`. Not yet ported: the host-side pipeline details of the CUDA backend (pinned +ring staging for `htod`, side stream for `beside`). ## What runs @@ -19,48 +23,51 @@ Everything the Vulkan backend runs, through the same kernels: | | HIP | Vulkan (same machine, same model) | |---|---|---| -| Prefill, pp 1024, calibrated | 1577-2072 tok/s | 1344 tok/s | -| Prefill, pp 4096 | 2106 tok/s | (not run) | -| Decode, tg 48, calibrated | 188-222 tok/s | 195 tok/s | -| Qwen3.8-27B dense, prefill / decode | 705 / 50.3 tok/s | 497 / 55.5 tok/s | +| Prefill, pp 1024 / 4096, calibrated | 1104 / 2993 tok/s | 1097 / 2325 tok/s | +| Decode, tg 48, calibrated | 209 / 219 tok/s | 199 / 163 tok/s | +| Qwen3.8-27B dense, pp 1024, prefill / decode | 784 / 39.1 tok/s | 508 / 35.3 tok/s | Qwen3.6-35B-A3B UD-Q4_K_XL (first rows) and Qwen3.8-27B UD-IQ3_S, `--ctx 4096 --vram-margin 256`, one process each, -`calibrate` run for each backend (chunk 4096; HIP picks `--mtp 3`, Vulkan `--mtp 1`). Prefill runs on the card's matrix -cores (below) and is ahead of Vulkan; decode is within a few percent in either direction — the spread over repeated runs -is larger than the difference, because each backend finds its own expert placement and that moves the MTP draft -acceptance. A dense model's prefill is 1.4x ahead and its decode 10% behind (memory-bandwidth bound). +`calibrate` run for each backend (chunk 4096; HIP picks `--mtp 3`, Vulkan `--mtp 1`). Each cell is pp / the decode that +follows it, so the second value is throughput at that depth. The pp 1024 row runs first in the process, before expert +placement has settled, so it understates both backends (1577-2072 tok/s was measured for HIP there when it was not the +first row); pp 4096 is the honest short-prompt number and is 1.29x Vulkan's. Decode is within a few percent in either +direction — the spread over repeated runs is larger than the difference, because each backend finds its own expert +placement and that moves the MTP draft acceptance. A dense model's prefill is 1.5x ahead and its decode 11% ahead. `serve` works too, checked on Qwen3.5-9B: `GET /v1/models`, non-streaming and streaming (`stream: true`) chat completions, and the prompt cache across turns (`prompt_tokens_details.cached_tokens` on a follow-up request). ## Long prompts -Prefill degrades with prompt depth on both backends (attention is the only depth-dependent term). The Q·Kᵀ score -product of the prefill attention runs on the card's matrix cores (below); the P·V product still runs on the CUDA cores, -which is where the remaining depth cost sits. +Prefill degrades with prompt depth on both backends (attention is the only depth-dependent term), and the prefill +attention now runs both of its products on the card's matrix cores (below). Its per-position cost is now below +Vulkan's, which is where the depth-dependent deficit used to be. Qwen3.6-35B-A3B UD-Q4_K_XL, `--mtp 0 --reps 1 --vram-margin 256`, KV `f16`, `--fixed-experts` (two runs where a range is given, one process each): -| pp | HIP | Vulkan | HIP, CUDA-core scores (`STRATA_HIP_WMMA=0`) | +| pp | HIP | Vulkan | HIP, everything on the CUDA cores (`STRATA_HIP_WMMA=0`) | |---|---|---|---| -| 8192 | 2556-2558 tok/s | 2148-2152 tok/s | 1303-1308 tok/s | -| 32768 | 1502-1677 tok/s | 1661 tok/s | 776-794 tok/s | -| 131072 | 660 tok/s | 731 tok/s | (not run) | -| decode at 8k / 32k / 128k | 73-75 / 64-67 / 48 tok/s | 71-72 / 68 / 44 tok/s | 74 / 64-65 / - | - -Fitting the per-token cost against depth gives a slope of 8-11 ns per position over 8k -> 32k (9.2 over 8k -> 128k) -for HIP and 5.6 over 8k -> 32k (7.3 over 8k -> 128k) for Vulkan, against 20-21 ns per position for HIP with the -CUDA-core scores — the matrix-core score product is worth **2x on prefill at depth** (pp 32k 794 -> 1677 tok/s, -pp 8k 1308 -> 2558 tok/s, same placement in the same build). At 128k HIP now does 660 tok/s against Vulkan's 731 -(prefill was 173 against 762) and is ahead on decode (48.3 against 44.2); at 32k the two are level, and at 8k HIP is -ahead. The earlier numbers in this file (pp 32k 720 tok/s, pp 128k 173, gen 80.8, slope 33 ns) were taken with the -CUDA-core scores and are the ones to compare against. `--chunk 0`-style token-by-token prefill is still not the -answer, but a shorter `--ctx` and `--kv q8` both buy expert slots back. +| 8192 | 2647-2666 tok/s | 2148-2152 tok/s | 1303-1308 tok/s | +| 32768 | 2026-2029 tok/s | 1661 tok/s | 776-794 tok/s | +| 131072 | 872 tok/s | 731 tok/s | (not run) | +| decode at 8k / 32k / 128k | 68-73 / 64 / 48 tok/s | 71-72 / 68 / 44 tok/s | 74 / 64-65 / - | + +Fitting the per-token cost against depth gives a slope of 4.7 ns per position over 8k -> 32k (6.3 over 8k -> 128k) +for HIP against 5.6 (7.3) for Vulkan and 20-21 for HIP with the attention on the CUDA cores: **3.4x on prefill at +depth** (pp 32k 794 -> 2029 tok/s, pp 8k 1308 -> 2647, same placement in the same build), the score product worth 2x +of it (pp 32k 794 -> 1677) and the P·V product the rest (1677 -> 2029). HIP is now ahead of Vulkan at every depth +tried — 1.23x at 8k, 1.22x at 32k, 1.19x at 128k — and at parity or ahead on decode; the earlier numbers in this file +(pp 32k 720 tok/s, pp 128k 173, gen 80.8, slope 33 ns) were taken on the CUDA cores and are the ones to compare +against. `--chunk 0`-style token-by-token prefill is still not the answer, but a shorter `--ctx` and `--kv q8` both +buy expert slots back. Two caveats on the numbers: `--fixed-experts` only means "same residents, no re-placement during the run", so the -spread between two runs of the same build (1502 vs 1677 at 32k) is expert placement and host page-cache state, not the -kernel; and a prompt's depth cost is the fit over the two depths, not either point. A 128k prompt costs more VRAM in +spread between two runs of the same build was up to 10% before the P·V port (1502 vs 1677 at 32k) — expert placement +and host page-cache state, not the kernel — and has been under 1% since (2029 vs 2026), which is itself a sign of how +much of the prefill used to wait on the CPU-side copies; and a prompt's depth cost is the fit over the two depths, +not either point. A 128k prompt costs more VRAM in the KV cache than a 16 GB card has left over for experts, so the run above streams most of them from host memory. ## How it works @@ -80,20 +87,24 @@ the KV cache than a 16 GB card has left over for experts, so the run above strea splits the k dimension across the two half-waves) and holds 8 results, column `lane & 15`, rows `8*(lane>>4) + i`. `STRATA_HIP_WMMA=0` falls back to the CUDA-core multiplications: 737 -> 1684 tok/s prefill at pp 1024 on the RX 9070 XT, and 5 of 6 prompts bit-identical between the two. -- **Matrix-core prefill attention** (`attn_prefill_t`): the same WMMA computes the Q·Kᵀ score tile, one 16-query x - 16-key instruction against the 16-half `qs`/`ks` rows. Its 8 results a lane land in AMD's layout (rows - `8*(lane>>4) + i`, column `lane & 15`) rather than the m16n8k16 layout the softmax, the causal mask and the P·V - step are written for, so the tile is staged through a warp-private f32 tile (`FA_BQ` x (`FA_BKL` + 8) floats, 4-6 - KiB on top of `qs`/`ks`/`vs`) and read back as `s[ng][2h + e] == S[warp*16 + g + 8h][ng*8 + 2t + e]`. That tile is - why head_dim 256 prefill takes 16 keys a step (`FA_BK_FOR`, as on Turing's 64 KB blocks): 32 keys would need 78 KiB - of a block's 64. The CUDA-core scores (`STRATA_HIP_WMMA=0`) and the matrix-core ones give the same greedy output on - the model, and the CPU-reference test covers both. -- The transposed V fragment (`ldsm4t`, the P·V operand) is the one CUDA-core multiplicand left in the attention: on HIP - it reads the two halves of a register as *adjacent* keys, which is what the `ldmatrix.trans` fragments mean. An - emulation that read them two rows apart (every even key counted twice, every odd one never) shipped with the first - HIP commit: it moved no token on the short prompts the parity checks used, and on the batched prefill it made every - long prompt disagree with Vulkan. `hip::tests::attn_prefill_matches_cpu` pins it now, and five long prompts agree - token for token with Vulkan afterwards. +- **Matrix-core prefill attention** (`attn_prefill_t`): the same WMMA computes both products. Q·Kᵀ is one 16-query + x 16-key instruction against the 16-half `qs`/`ks` rows; P·V takes A = P from a half staging tile (the `ps` tile the + Volta path already had, unused on HIP until now, written from the softmax registers as half pairs) and B = Vᵀ read + down a column of the `vs` tile (`strata_ld_wmma_t`, one half a key apart, since that operand's rows are head + dimensions). + Both results land in AMD's layout — 8 a lane, rows `8*(lane>>4) + i`, column `lane & 15` — rather than the m16n8k16 + layout the softmax, the causal mask and the epilogue are written for, so each 16x16 result tile is staged in f32 + and read back as `s[ng][2h + e] == S[warp*16 + g + 8h][ng*8 + 2t + e]` (scores) or `o[d][2r + e]` (P·V). One warp + staging tile serves both stages (`FA_BQ` x (`FA_BKL` + 8) floats, 4-6 KiB added to the block's dynamic shared + memory), and it is why head_dim 256 prefill takes 16 keys a step (`FA_BK_FOR`, as on Turing's 64 KB blocks): 32 + keys would need 78 KiB of a block's 64. `STRATA_HIP_WMMA=0` runs the same numerics on the CUDA cores; the + CPU-reference test covers both. +- The CUDA-core P·V path (`ldsm4t` + `mma16816`) is still there for `STRATA_HIP_WMMA=0` and for CUDA, and it is + worth knowing how it is shaped: on HIP it reads the two halves of a transposed register as *adjacent* keys, which is + what the `ldmatrix.trans` fragments mean. An emulation that read them two rows apart (every even key counted twice, + every odd one never) shipped with the first HIP commit: it moved no token on the short prompts the parity checks + used, and on the batched prefill it made every long prompt disagree with Vulkan. `hip::tests:: + attn_prefill_matches_cpu` pins it now. - `src/cuda/kernels.cu` keeps one source for both backends: the few places that cannot be shared are behind `#if STRATA_HIP` (f16 conversions, the per-lane fragment loads, `mma884`, the KV f16x2 math, the L2 prefetch hint), so the CUDA build's preprocessed source is unchanged. @@ -118,8 +129,8 @@ the KV cache than a 16 GB card has left over for experts, so the run above strea - `STRATA_HIP_TRACE=1` names every launch before it goes out (grid, block, shared memory). - `STRATA_HIP_GRAPH=0` runs the forward every time instead of capturing it (capture is on by default, +5% decode). - `STRATA_NO_GRAPH=1` turns capture off for both GPU backends. -- `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM and the prefill attention instead of the - matrix cores. +- `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM and in both products of the prefill + attention instead of the matrix cores. ## Why the prefill GEMM does not use int8 matrix cores @@ -139,10 +150,11 @@ memory and runs on the f16 matrix cores, which is what puts it ahead of the Vulk ## Next -1. The P·V product of the prefill attention on the matrix cores (the score product is ported, see above): `A = P` from - the staging tile, `B = Vᵀ`, which needs transposed V fragments and an accumulator layout that does not match the - softmax's per-row `m`/`l` bookkeeping — stage it like the scores. Worth about the other half of the depth slope. -2. A side stream for `beside`, so expert uploads overlap with compute in prefill. +1. A side stream for `beside`, so expert uploads overlap with compute in prefill (the 8k prefill still moves a lot of + expert data per chunk, and the run-to-run spread collapsing from 10% to 1% with the faster attention says the + copies now wait on the CPU less than they used to). +2. The decode path: no matrix cores on either backend there (it is memory-bound), but the prefill attention's `FA_BKL` + of 16 at head_dim 256 is a shared-memory compromise — a 32-key tile would need 78 KiB. Not worth chasing. ## Credits diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 9fa380d9..d0ea2875 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -2759,7 +2759,47 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co cp_async_wait<1>(); // sm_80+: this V tile, the next K tile may still be in flight; sm_70: already copied here __syncthreads(); #endif -#if __CUDA_ARCH__ < 800 && GEMM_TC +#if GEMM_WMMA + // P * V on the matrix cores, the way the scores are: A = P (this warp's 16 query rows x the tile's keys, in + // halves), B = V^T (16 head dimensions x the same keys, one half a tile row apart). The lane's 8 results land + // in AMD's layout again (query rows 8*(lane>>4) + i, dim column lane & 15), so each 16 x 16 result tile is + // staged in f32 and read back as the two m16n8k16 dim tiles the rescale above, the epilogue below and the + // score stage all use (`st` is free again by now: it held the scores of this tile). + if (!skip) { + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane), PW = FA_BKL + 8; +#pragma unroll + for (int ng = 0; ng < FA_BKL / 8; ng++) { + // P in halves, one 32-bit store a half pair (keys 2t / 2t+1 are adjacent in this lane's registers) + *(u32*)(ps + (warp * 16 + g) * PW + ng * 8 + 2 * t4) = h2pack(s[ng][0], s[ng][1]); + *(u32*)(ps + (warp * 16 + g + 8) * PW + ng * 8 + 2 * t4) = h2pack(s[ng][2], s[ng][3]); + } + __syncwarp(); + float* sw = st + warp * 256; +#pragma unroll + for (int dt = 0; dt < HD / 16; dt++) { + strata_hip::strata_f8 acc; +#pragma unroll + for (int i = 0; i < 8; i++) acc[i] = 0.0f; +#pragma unroll + for (int kg = 0; kg < FA_BKL / 16; kg++) { + const u16* pa = ps + (warp * 16 + l16) * PW + kg * 16 + w0; + const u16* pb = vs + (kg * 16 + w0) * PQ + dt * 16 + l16; + acc = strata_hip::strata_wmma(strata_hip::strata_ld_wmma(pa), strata_hip::strata_ld_wmma_t(pb, PQ), acc); + } +#pragma unroll + for (int i = 0; i < 8; i++) sw[(8 * (lane >> 4) + i) * 16 + l16] = acc[i]; + __syncwarp(); +#pragma unroll + for (int r = 0; r < 2; r++) +#pragma unroll + for (int e = 0; e < 2; e++) { + o[2 * dt][2 * r + e] += sw[(g + 8 * r) * 16 + 2 * t4 + e]; + o[2 * dt + 1][2 * r + e] += sw[(g + 8 * r) * 16 + 8 + 2 * t4 + e]; + } + __syncwarp(); + } + } +#elif __CUDA_ARCH__ < 800 && GEMM_TC // P -> the warp-private staging tile: the m8n8k4 A fragment of the PV product wants row t + 4*hi and four // contiguous keys per lane, which the QK^T D layout does not give for free. One 32-bit store per half pair; // the __syncwarp() publishes the tile to the mma step below (the next tile's stores follow the loop's diff --git a/src/hip/compat.h b/src/hip/compat.h index f0f676ab..6202692a 100644 --- a/src/hip/compat.h +++ b/src/hip/compat.h @@ -124,6 +124,16 @@ __device__ __forceinline__ strata_hk strata_ld_wmma(const unsigned short* p) { for (int i = 0; i < STRATA_WMMA_K / 8; i++) c.u[i] = *(const uint4*)(p + 8 * i); return c.h; } + +/// The same STRATA_WMMA_K halves one tile row apart from each other: the B operand when the operand's rows are the +/// transposed side (the prefill attention's V, whose rows are head dimensions and whose k are keys). One load a have +/// instead of a 16-byte vector load. +__device__ __forceinline__ strata_hk strata_ld_wmma_t(const unsigned short* p, int stride) { + strata_hk r; +#pragma unroll + for (int i = 0; i < STRATA_WMMA_K; i++) r[i] = *(const _Float16*)(p + i * stride); + return r; +} #endif } // namespace strata_hip diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 741e8acd..84d0726e 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -977,17 +977,18 @@ mod tests { } /// `attn_prefill_t` end to end (score product, causal softmax, P·V, the epilogue) against a CPU reference, at - /// head_dim 128 (32-key tiles) and 256 (the HIP build's 16-key tiles) with a partial last query tile. This is the - /// check the matrix-core score path needs on its own: a wrong lane/lane-staging mapping shows up as a large - /// per-element difference on a specific query or head, not as the near-tie token flips a parity run sees. + /// head_dim 128 with three query tiles and five key tiles and at head_dim 256 (the HIP build's 16-key tiles). + /// A wrong lane/lane-staging mapping, a lost half of a fragment or a missing key shows up as a large per-element + /// difference on a specific query or head — which is how the transposed-V bug below was found — rather than as + /// the near-tie token flip a parity run sees. #[test] fn attn_prefill_matches_cpu() { use half::f16; let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; let g: &dyn Backend = &gpu; - let (t, nh, nkv) = (40usize, 4usize, 2usize); - let scale = 0.088388347; - for hd in [128usize, 256] { + let (nh, nkv) = (4usize, 2usize); + for (hd, t) in [(128usize, 130usize), (256, 70)] { + let scale = 1.0 / (hd as f32).sqrt(); let mut st = 99u32; let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; let q: Vec = (0..t * nh * hd).map(|_| rnd()).collect(); @@ -1039,7 +1040,7 @@ mod tests { let d = (got[i] - want[i]).abs(); if d > worst { worst = d; at = i; gv_ = got[i]; } } - eprintln!("hd {hd}: max |diff| = {worst:e} at {at} (row {}, head {}, d {}): got {gv_} want {}", + eprintln!("hd {hd} T {t}: max |diff| = {worst:e} at {at} (row {}, head {}, d {}): got {gv_} want {}", at / (nh * hd), (at / hd) % nh, at % hd, want[at]); assert!(worst < 5e-3, "hd {hd}: max |diff| = {worst} at {at}"); } From 7d7a0eb4a4c2bfcef27660b1d7a52c51c5688330 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 17 Nov 2026 06:52:40 +0100 Subject: [PATCH 11/26] hip: deltanet_seq measured, and left alone The gated delta-rule scan behind Qwen3.6/3.8's linear-attention layers is 12% of a long-prompt prefill (the second largest kernel after the prefill GEMM), and the obvious guess -- "it is a sequential scan with redundant loads, so give it more parallelism or fewer loads" -- is wrong in every direction. Measured with a new probe, tools/hip/deltanet.cpp, which times the scan alone at the 35B's shape (dk 128, nk 16, nv 32, dv 128, T 4096, 128 blocks) at 3.11 ms a layer, ~1750 cycles a token. A model-level prefill A/B cannot resolve this: two runs of the same build differ by more than any of the variants gain. base (16 floats a lane, `tok * stride` in the loop) 3.11 ms 1.00x 32 floats a lane (half the blocks, one wave on 60 CUs) 3.84 ms 0.81x loop address math hoisted into pointer increments 3.26 ms 0.93x dot-product accumulators split in two 3.22 ms 0.96x every token re-reading token 0's q/k/v (L1-resident) 3.13 ms 0.99x no per-token expf(g) for the decay 2.76 ms 1.12x no warp reductions (wrong results) 2.33 ms 1.33x So the kernel is latency, not bandwidth (the reads are free, with all of the redundancy), and the only parts with headroom are the two dependent warp-reduction rounds and the per-token exp -- both properties of the sequential recurrence, removable only by the chunked WY/UT-transform form (a small triangular inverse plus matmuls over a chunk). That form wants f32 for the state, so it would not use the tensor cores, and 12% of prefill is the whole prize: ~4%. Not done, deliberately, and now with the numbers to back that up instead of a hand-wave. docs/HIP.md gains a "What is left, measured" section: the kernel-time profile of a prefill and of a decode step (~90% of decode is the CPU expert worker's latency, not GPU), and this table. tools/hip/README.md lists the probe. --- docs/HIP.md | 31 +++++- tools/hip/README.md | 6 + tools/hip/deltanet.cpp | 246 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 278 insertions(+), 5 deletions(-) create mode 100644 tools/hip/deltanet.cpp diff --git a/docs/HIP.md b/docs/HIP.md index 66b7ee65..10d41d74 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -148,13 +148,34 @@ the time of f16, with a vector-friendly rescale 6.6x *slower*, with the layout t integer path cannot pay for itself here, so `GEMM_TC` stays 0 on HIP and the prefill GEMM dequantizes to f16 in shared memory and runs on the f16 matrix cores, which is what puts it ahead of the Vulkan backend. +## What is left, measured + +Profiled on the same 35B prefill (`rocprofv3 --kernel-trace`, pp 4096): 54% of the kernel time is the quantized +prefill GEMM (already on the matrix cores), 12% the gated delta-rule scan `deltanet_seq`, 10% the prefill attention +(ported), and nothing else above 3%. Of a decode step's wall time, ~90% is not GPU at all — `moe_combine` spends most +of its time waiting on the CPU expert worker, which is an expert-tier question, not a kernel one. + +`deltanet_seq` is the one kernel left worth a look, and it has now been measured properly rather than guessed at +(`tools/hip/deltanet.cpp`, which times the scan alone at the 35B's shape): + +- its per-token latency (~1750 cycles) is **not** memory: a variant that re-reads token 0's q/k/v every step, so the + reads stay in L1, runs just as fast (1.00x), even though the scan as written re-reads them from 128 blocks. +- no rearrangement of the scan wins: 32 floats a lane instead of 16 (half the blocks, one wave on 60 CUs) is 0.81x, + hoisting the loop's `tok * stride` address math into pointer increments is 0.93x, splitting the dot-product + accumulators is 0.96x, combinations worse. +- the parts with headroom are the two dependent warp-reduction rounds (1.33x if both are removed, wrong results) and + the per-token `expf(g)` for the decay (1.12x). Both are properties of the *sequential* recurrence: they only go + away with the chunked WY/UT-transform form (a small triangular inverse plus a few matmuls over a chunk), which + wants f32 for the state and therefore does not get tensor cores. + +Since the whole kernel is 12% of prefill, that rewrite's ceiling is ~4% of prefill. Left alone deliberately. + ## Next -1. A side stream for `beside`, so expert uploads overlap with compute in prefill (the 8k prefill still moves a lot of - expert data per chunk, and the run-to-run spread collapsing from 10% to 1% with the faster attention says the - copies now wait on the CPU less than they used to). -2. The decode path: no matrix cores on either backend there (it is memory-bound), but the prefill attention's `FA_BKL` - of 16 at head_dim 256 is a shared-memory compromise — a 32-key tile would need 78 KiB. Not worth chasing. +1. A side stream for `beside`, so expert uploads overlap with compute in prefill (the run-to-run spread collapsing + from 10% to 1% with the faster attention says the copies now wait on the CPU less than they used to). +2. Decode on an MoE model: the expert residency policy, not a kernel. That is where the multi-x is (see the reference + numbers from Strata in the handoff). ## Credits diff --git a/tools/hip/README.md b/tools/hip/README.md index bf5b4c7e..4ddd5b3a 100644 --- a/tools/hip/README.md +++ b/tools/hip/README.md @@ -8,6 +8,12 @@ hipcc --offload-arch=gfx1201 -O3 wmma_rate.cpp -o wmma_rate && ./wmma_rate hipcc --offload-arch=gfx1201 -O3 wmma_rescale.cpp -o wmma_rescale && ./wmma_rescale ``` +- `deltanet.cpp`: the gated delta-rule scan (`deltanet_seq`) alone, at the 35B model's shape, with the variants that + were tried against it: fewer, fatter lanes, two accumulators a dot sum, the loop's address math hoisted into + pointer increments, and two ablations (the per-token `expf`, the two warp reductions). All of them are neutral or + slower; the reads are free (a variant that re-reads token 0 every step is as fast), and the reductions plus the + exp are the only parts with headroom — which is the chunked WY form's job, not a rearrangement of the scan. The + file's header carries the numbers. - `wmma_rate.cpp`: the matrix-core instruction rate of the two operand types, operands in registers, so the numbers are the instruction rate and not memory bandwidth. On RX 9070 XT (gfx1201): f16 57 TMAC/s, int8 137 TMAC/s. - `wmma_rescale.cpp`: the inner-loop shape of the prefill GEMM (`gemm_q`: 2x2 tiles of 16x16, four 16-deep k-steps per diff --git a/tools/hip/deltanet.cpp b/tools/hip/deltanet.cpp new file mode 100644 index 00000000..febc8bdd --- /dev/null +++ b/tools/hip/deltanet.cpp @@ -0,0 +1,246 @@ +// deltanet_seq (the gated delta-rule scan that Qwen3.6/3.8's linear-attention layers run in prefill) in isolation. +// Answering "can this kernel be made faster without changing the algorithm", with numbers instead of guesses: a +// model-level prefill A/B cannot resolve a 5% change (two runs of the same build differ by more), so the variants are +// timed here. Fixed shape of the 35B model: dk 128, nk 16, nv 32, dv 128, T 4096, i.e. 128 blocks of 256 threads. +// +// hipcc --offload-arch=gfx1201 -O3 deltanet.cpp -o deltanet && ./deltanet +// +// Measured on RX 9070 XT (3.11 ms for one layer's scan over 4096 tokens, ~1750 cycles a token; the ratios move by +// +-4% between runs, so treat anything under 5% as noise): +// +// base 3.11 ms 1.00x deltanet_seq as committed +// dn16 (running pointers) 3.26 ms 0.93x the loop's `tok * stride` products hoisted into pointer increments +// dn16s (+ 2 accumulators) 3.22 ms 0.96x one chain of 16 dependent adds split in two +// dn32 (32 floats a lane) 3.84 ms 0.81x half the blocks (one wave on 60 CUs), twice the work a lane +// dn32s 3.73 ms 0.83x +// no expf(g) per token 2.76 ms 1.12x the per-token decay, which only half the calls need as an exp +// no warp reductions 2.33 ms 1.33x both dependent shuffle rounds removed (wrong results, timing only) +// same q/k/v every step 3.13 ms 0.99x per-token reads held in L1: the strided, 128-block-redundant reads +// cost nothing, so this kernel is latency, not bandwidth +// +// So: no rearrangement of the scan wins (several lose), the reads are free, and the 33% inside reach is the two +// dependent shuffle rounds plus the per-token exp -- both of which only disappear if the per-token recurrence +// becomes a chunked one (the WY/UT-transform form: a triangular inverse and matmuls over a chunk, and with f16 +// tensor cores it would lose state precision). 12% of a 4096-token prefill is in this kernel, so the whole +// theoretical prize is ~4% prefill for that rewrite. Left alone deliberately. +#include +#include +#include +#include +#include +typedef unsigned short u16; +__device__ __forceinline__ float sigmoid(float x) { return 1.0f / (1.0f + expf(-x)); } +__device__ __forceinline__ float softplus(float x) { return x > 20.0f ? x : log1pf(expf(x)); } +// kernels.cu's HIP shim routes the mask-less form here; the HIP builtin itself wants a 64-bit mask. +template __device__ __forceinline__ T shflx(T v, int off) { return __shfl_xor(v, off, 32); } +__global__ void dn_base(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + int L = dk >> 4, R = 32 / L, lane = threadIdx.x & 31, s = lane % L, vh = blockIdx.x, kh = ilv ? vh / (nv / nk) : vh % nk; + int j0 = (blockIdx.y * 8 + (threadIdx.x >> 5)) * R, j = j0 + lane / L; + if (j0 >= dv) return; // whole warp past the end (R divides dv) + float4* row = (float4*)(S + ((size_t)vh * dv + j) * dk); + float r[16]; +#pragma unroll + for (int i = 0; i < 4; i++) { float4 v = row[s + L * i]; r[4 * i] = v.x; r[4 * i + 1] = v.y; r[4 * i + 2] = v.z; r[4 * i + 3] = v.w; } + // Token inputs do not depend on the state: token tok + 1's are loaded while token tok computes. + float nk_[16], nq[16], ng, nb, nvv; + auto ld = [&](int tok) { + const float* yt = y + (size_t)tok * ych; + const float4* q4 = (const float4*)(yt + kh * dk); + const float4* k4 = (const float4*)(yt + nk * dk + kh * dk); +#pragma unroll + for (int i = 0; i < 4; i++) { + float4 v = k4[s + L * i]; nk_[4 * i] = v.x; nk_[4 * i + 1] = v.y; nk_[4 * i + 2] = v.z; nk_[4 * i + 3] = v.w; + v = q4[s + L * i]; nq[4 * i] = v.x; nq[4 * i + 1] = v.y; nq[4 * i + 2] = v.z; nq[4 * i + 3] = v.w; + } + ng = g[tok * nv + vh]; nb = beta[tok * nv + vh]; nvv = yt[2 * nk * dk + vh * dv + j]; + if (dtb) { ng = softplus(ng + dtb[vh]) * ga[vh]; nb = sigmoid(nb); } + }; + ld(0); + for (int tok = 0; tok < T; tok++) { + float kk[16], qv[16], decay = expf(ng), bt = nb, vt = nvv, sk = 0.0f, oq = 0.0f; +#pragma unroll + for (int e = 0; e < 16; e++) { kk[e] = nk_[e]; qv[e] = nq[e]; } + if (tok + 1 < T) ld(tok + 1); +#pragma unroll + for (int e = 0; e < 16; e++) { r[e] *= decay; sk += r[e] * kk[e]; } + for (int off = L >> 1; off; off >>= 1) sk += shflx(sk, off); + float d = bt * (vt - sk); +#pragma unroll + for (int e = 0; e < 16; e++) { r[e] += d * kk[e]; oq += r[e] * qv[e]; } + for (int off = L >> 1; off; off >>= 1) oq += shflx(oq, off); + if (s == 0) o[(size_t)tok * nv * dv + vh * dv + j] = oq * scale; + if (tok < min(nsnap, T - 1)) { + float4* sr = (float4*)(snap + (size_t)tok * nv * dv * dk + ((size_t)vh * dv + j) * dk); +#pragma unroll + for (int i = 0; i < 4; i++) sr[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); + } + } +#pragma unroll + for (int i = 0; i < 4; i++) row[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); +} + +template +__device__ __forceinline__ void dn_opt(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + int L = dk / DNP, R = 32 / L, lane = threadIdx.x & 31, s = lane % L, vh = blockIdx.x, kh = ilv ? vh / (nv / nk) : vh % nk; + int j0 = (blockIdx.y * (int)(blockDim.x >> 5) + (threadIdx.x >> 5)) * R, j = j0 + lane / L; + if (j0 >= dv) return; // whole warp past the end (R divides dv) + float4* row = (float4*)(S + ((size_t)vh * dv + j) * dk); + float r[DNP]; +#pragma unroll + for (int i = 0; i < DNP / 4; i++) { float4 v = row[s + L * i]; r[4 * i] = v.x; r[4 * i + 1] = v.y; r[4 * i + 2] = v.z; r[4 * i + 3] = v.w; } + // Running pointers, one step per token: the loop body used to recompute `tok * stride` (and the 64-bit + // multiplies and divides that drag in) for every operand, which was most of its instruction count. + const float4* kp = (const float4*)(y + (size_t)kh * dk); // chunk s + L*i of this lane's row + const float4* qp = (const float4*)(y + (size_t)(nk + kh) * dk); + const float* vp = y + (size_t)2 * nk * dk + (size_t)vh * dv + j; // token's v[j] + const float* gp = g + vh, *bp = beta + vh; // this head's decay gate and beta + float* op = o + (size_t)vh * dv + j; // token's output element + float* sp = snap + (size_t)((size_t)vh * dv + j) * dk; // snapshot of this lane's chunks + const int kstep = ych / 4, snapstep = nv * dv * dk; + const int ns = min(nsnap, T - 1); + // Token inputs do not depend on the state: token tok + 1's are loaded while token tok computes. + float nk_[DNP], nq[DNP], ng, nb, nvv; + auto ld = [&]() { +#pragma unroll + for (int i = 0; i < DNP / 4; i++) { + float4 v = kp[s + L * i]; nk_[4 * i] = v.x; nk_[4 * i + 1] = v.y; nk_[4 * i + 2] = v.z; nk_[4 * i + 3] = v.w; + v = qp[s + L * i]; nq[4 * i] = v.x; nq[4 * i + 1] = v.y; nq[4 * i + 2] = v.z; nq[4 * i + 3] = v.w; + } + ng = *gp; nb = *bp; nvv = *vp; + if constexpr (false) { ng = softplus(ng + dtb[vh]) * ga[vh]; nb = sigmoid(nb); } + kp += kstep; qp += kstep; gp += nv; bp += nv; vp += ych; + }; + ld(); + for (int tok = 0; tok < T; tok++) { + float kk[DNP], qv[DNP], decay = PROBE == 1 ? 0.99f : expf(ng), bt = nb, vt = nvv, sk = 0.0f, oq = 0.0f; +#pragma unroll + for (int e = 0; e < DNP; e++) { kk[e] = nk_[e]; qv[e] = nq[e]; } + if (tok + 1 < T) ld(); + float sk1 = 0.0f, oq1 = 0.0f; + if constexpr (SPLIT) { +#pragma unroll + for (int e = 0; e < DNP; e += 2) { r[e] *= decay; r[e + 1] *= decay; sk += r[e] * kk[e]; sk1 += r[e + 1] * kk[e + 1]; } + sk += sk1; + } else { +#pragma unroll + for (int e = 0; e < DNP; e++) { r[e] *= decay; sk += r[e] * kk[e]; } + } + if (PROBE != 2) for (int off = L >> 1; off; off >>= 1) sk += shflx(sk, off); + float d = bt * (vt - sk); + if constexpr (SPLIT) { +#pragma unroll + for (int e = 0; e < DNP; e += 2) { r[e] += d * kk[e]; r[e + 1] += d * kk[e + 1]; oq += r[e] * qv[e]; oq1 += r[e + 1] * qv[e + 1]; } + oq += oq1; + } else { +#pragma unroll + for (int e = 0; e < DNP; e++) { r[e] += d * kk[e]; oq += r[e] * qv[e]; } + } + if (PROBE != 2) for (int off = L >> 1; off; off >>= 1) oq += shflx(oq, off); + if (s == 0) *op = oq * scale; + if (tok < ns) { + float4* sr = (float4*)sp; +#pragma unroll + for (int i = 0; i < DNP / 4; i++) sr[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); + } + op += nv * dv; sp += snapstep; + } +#pragma unroll + for (int i = 0; i < DNP / 4; i++) row[s + L * i] = make_float4(r[4 * i], r[4 * i + 1], r[4 * i + 2], r[4 * i + 3]); +} + +__global__ void dn16(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<16, false>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +__global__ void dn32(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<32, false>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +__global__ void dn16s(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<16, true>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +__global__ void dn32s(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<32, true>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} + +__global__ void dn16x(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<16, false, 1>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +__global__ void dn16r(const float* y, float* S, const float* beta, const float* g, float* o, + int nk, int nv, int ilv, int dk, int dv, float scale, int T, int ych, float* snap, int nsnap, + const float* dtb, const float* ga) { + dn_opt<16, false, 2>(y, S, beta, g, o, nk, nv, ilv, dk, dv, scale, T, ych, snap, nsnap, dtb, ga); +} +// --------------------------------------------------------------------------------------------------------------- +constexpr int DKN = 128, NKN = 16, NVN = 32, DVN = 128, TN = 4096, YCH = NVN * DVN + 2 * NKN * DKN; +struct Args { + std::vector y, S, beta, g, o; + float *dy, *dS, *dbeta, *dg, *dout, *dsnap; +}; +static void init(Args& a) { + size_t ny = (size_t)TN * YCH; + a.y.assign(ny, 0.f); a.S.assign((size_t)NVN * DVN * DKN, 0.f); + a.beta.assign(TN * NVN, 0.f); a.g.assign(TN * NVN, 0.f); a.o.assign((size_t)TN * NVN * DVN, 0.f); + srand(1234); + auto rnd = [] { return (float)rand() / 2147483647.f - 0.5f; }; + for (auto& v : a.y) v = rnd(); + for (auto& v : a.S) v = rnd() * 0.1f; + for (auto& v : a.beta) v = rnd(); + for (auto& v : a.g) v = -0.01f - fabsf(rnd()) * 0.02f; // decay < 1: a real gated delta rule + hipMalloc(&a.dy, ny * 4); hipMalloc(&a.dS, a.S.size() * 4); hipMalloc(&a.dbeta, a.beta.size() * 4); + hipMalloc(&a.dg, a.g.size() * 4); hipMalloc(&a.dout, a.o.size() * 4); hipMalloc(&a.dsnap, 4); + hipMemcpy(a.dy, a.y.data(), ny * 4, hipMemcpyHostToDevice); + hipMemcpy(a.dbeta, a.beta.data(), a.beta.size() * 4, hipMemcpyHostToDevice); + hipMemcpy(a.dg, a.g.data(), a.g.size() * 4, hipMemcpyHostToDevice); +} +struct Res { float ms; std::vector out; }; +template static Res run(K k, Args& a, int dnp, int ych = YCH) { + int rows = 32 * dnp / DKN, gy = DVN / (8 * rows); + dim3 grid(NVN, gy), block(256); + auto launch = [&] { k<<>>(a.dy, a.dS, a.dbeta, a.dg, a.dout, NKN, NVN, 0, DKN, DVN, 1.0f / sqrtf(DKN), TN, ych, a.dsnap, 0, nullptr, nullptr); }; + hipMemcpy(a.dS, a.S.data(), a.S.size() * 4, hipMemcpyHostToDevice); + hipMemset(a.dout, 0, a.o.size() * 4); + launch(); hipDeviceSynchronize(); + hipEvent_t e0, e1; hipEventCreate(&e0); hipEventCreate(&e1); + const int reps = 10; + hipEventRecord(e0); + for (int i = 0; i < reps; i++) launch(); + hipEventRecord(e1); hipEventSynchronize(e1); + float ms = 0; hipEventElapsedTime(&ms, e0, e1); + hipMemcpy(a.o.data(), a.dout, a.o.size() * 4, hipMemcpyDeviceToHost); + return {ms / reps, a.o}; +} +int main() { + Args a; init(a); + Res ref = run(dn_base, a, 16); + printf("%-10s %8.3f ms %5.2fx max |reldiff| vs base\n", "base", ref.ms, 1.0); + struct V { const char* name; void (*k)(const float*, float*, const float*, const float*, float*, int, int, int, int, int, float, int, int, float*, int, const float*, const float*); int dnp; }; + V vs[] = {{"dn16", dn16, 16}, {"dn16s", dn16s, 16}, {"dn32", dn32, 32}, {"dn32s", dn32s, 32}, + {"no expf(g)", dn16x, 16}, {"no reductions", dn16r, 16}}; + for (auto& v : vs) { + Res r = run(v.k, a, v.dnp); + double worst = 0; + for (size_t i = 0; i < ref.out.size(); i++) { + double d = ref.out[i] != 0 ? fabs((ref.out[i] - r.out[i]) / ref.out[i]) : fabs(ref.out[i] - r.out[i]); + if (d > worst) worst = d; + } + printf("%-13s %8.3f ms %5.2fx %.2e\n", v.name, r.ms, ref.ms / r.ms, worst); + } + // The same scan with every token reading token 0's q/k/v (ych = 0): the per-token reads then stay in L1, which + // separates "cost of the data" from "cost of the strided, 128-blocks-redundant reads". + Res l1 = run(dn16, a, 16, 0); + printf("%-10s %8.3f ms %5.2fx (same token's q/k/v every step)\n", "dn16-l1", l1.ms, ref.ms / l1.ms); + return 0; +} From 3bf807991d30aa0eba0eba1012fdf6250c4e2903 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 17 Nov 2026 07:12:56 +0100 Subject: [PATCH 12/26] docs: the two matrix-core ports, against what Strata already had Cross-checked this backend's work against the reference engine (same card, same models, MIT) and recorded the comparison rather than leaving it implicit: - Strata's prompt attention has had the same two instructions (gfx11 `v_wmma_f32_16x16x16_f16_w32`, gfx12 the `_gfx12` form) since its 0.1.32, with the fragment layout this backend probed: `A` lane l holds `A[l % 16][(l / 16) * 8 + i]` on gfx12, `D[2i + l / 16][l % 16]` on gfx11. It is default on gfx12 Linux, tied to an int8 KV cache (q and p as FP16 hi+lo parts), and worth 7.2-7.5x their portable kernel / +31% prompt throughput at 8.8K tokens. Ours works on an f16 KV cache and stays inside the CUDA-era m16n8k16 code by staging the scores; the two land in the same place, ~2x the attention and +22-35% prefill at depth. - They did write the chunked gated delta-rule scan this backend measured and declined (`gdn_chunk.cu` FP32, `gdn_tc.cuh` gfx11, `gdn_wmma12.inc` gfx12), and their own numbers are the argument: recurrence 1.6x, whole prompt +1.4-2.1% on an RDNA3 iGPU, 0.73-0.87x (slower) on CUDA, off by default because the rounding differs. - The int8-WMMA verdict needed a scope: it holds for GGUF K-quants dequantized on the fly. Strata gets +19.1% at 4K (8-8.5% at 16K/32K) from int8 matrix cores on gfx12 for prompt experts, because it repacks the weights into a format laid out for the fragment (A = 16 weight rows, so a lane's eight results share one token's activation scale). That is the class of evidence that would reopen GEMM_TC here, and it costs a repack pass. --- docs/HIP.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/docs/HIP.md b/docs/HIP.md index 10d41d74..7d555519 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -148,6 +148,13 @@ the time of f16, with a vector-friendly rescale 6.6x *slower*, with the layout t integer path cannot pay for itself here, so `GEMM_TC` stays 0 on HIP and the prefill GEMM dequantizes to f16 in shared memory and runs on the f16 matrix cores, which is what puts it ahead of the Vulkan backend. +That verdict is about GGUF K-quants dequantized on the fly, and there is a known way out of it: **repack the weights**. +Strata runs int8 matrix cores for prompt experts on gfx12 (its `STRATA_PF_FUSED`, on by default for its own IQ3_S, +IQ3_XXS and Q2_0 packs) and measures a 4K prompt 1,612 -> 1,353 ms (+19.1%, 8-8.5% at 16K/32K), because a pack can be +laid out for the fragment (A = 16 weight rows, so a lane's eight results share one token's activation scale) instead +of the per-16-weight K-quant rescale that kills it here. Doing that in this engine would mean a repack pass and our own +pack format — a project, not a kernel — but it is the shape of the evidence that would reopen `GEMM_TC`. + ## What is left, measured Profiled on the same 35B prefill (`rocprofv3 --kernel-trace`, pp 4096): 54% of the kernel time is the quantized @@ -168,7 +175,11 @@ of its time waiting on the CPU expert worker, which is an expert-tier question, away with the chunked WY/UT-transform form (a small triangular inverse plus a few matmuls over a chunk), which wants f32 for the state and therefore does not get tensor cores. -Since the whole kernel is 12% of prefill, that rewrite's ceiling is ~4% of prefill. Left alone deliberately. +Since the whole kernel is 12% of prefill, that rewrite's ceiling is ~4% of prefill. Left alone deliberately — and +Strata, which did write it (chunked scans on the gfx11 matrix cores in `gdn_tc.cuh` and the gfx12 ones in +`gdn_wmma12.inc`, both MIT), measures exactly that: their recurrence is 1.6x faster on an RDNA3 iGPU for a **1.4-2.1%** +gain in whole-prompt time (docs/DETAILS.md), it is off by default because the rounding differs from the token-by-token +FP32 scan, and on CUDA it is 0.73-0.87x, i.e. slower. ## Next @@ -182,3 +193,15 @@ Since the whole kernel is 12% of prefill, that rewrite's ceiling is ~4% of prefi The compatibility shim follows the structure and several implementations of Strata's `include/strata/hip_compat/intrinsics.hpp` (MIT, (c) 2025 Niko1221, https://github.com/Niko1221/Strata), which runs CUDA-shaped kernels on the same wave32 targets. See `THANKS.md`. + +The two matrix-core ports in this backend were written independently and turned out to match work already in Strata, in +a different design: + +- **Prompt attention on the matrix cores**: their `src/kernels/cuda/qsa_prompt_attn.cu` has the same instruction for + gfx11 and gfx12 with the fragment layout noted here (`A` lane l holds `A[l % 16][(l / 16) * 8 + i]`, gfx11 + `D[2i + l / 16][l % 16]`), default on gfx12 Linux but tied to an int8 KV cache and to keeping q and p as FP16 + hi+lo parts; it is 7.2-7.5x their portable kernel and +31% prompt throughput at 8.8K tokens. This backend's version + works on an f16 KV cache and reuses the CUDA-era m16n8k16 softmax by staging the scores, at ~2x the prefill + attention and +22-35% prefill at depth. +- **A chunked gated delta-rule scan** (`gdn_chunk.cu`, `gdn_tc.cuh`, `gdn_wmma12.inc`): the rewrite this backend + measured and declined, with their own numbers agreeing with the estimate (see "What is left, measured"). From 9a504a64f4732bdb297f4d9b641675b0ef721ae5 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 06:53:23 +0100 Subject: [PATCH 13/26] hip: follow main's kernel arguments (weight scale, rope pairs, tq_lut, KV_MODE) Adds rope_pairs and dflash2_conv; --kv q4/q2 is refused on HIP instead of running f16. --- src/hip/mod.rs | 43 ++++++++++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 84d0726e..900d11ad 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -114,7 +114,8 @@ fn source(kv_q8: bool) -> String { __device__ const unsigned int iq3s_grid[512] = {{{}}};\n\ __device__ const unsigned char ksigns_iq2xs[128] = {{{}}};\n\ __device__ const signed char kvalues_iq4nl[16] = {{{}}};\n\ - #define LLAMA_Q8 {}\n#define KV_Q8 {}\n#define GEMM_TC 0\n#define GEMM_WMMA (STRATA_WMMA && {})\n\ + __device__ const float tq_lut[4096] = {{{}}};\n\ + #define LLAMA_Q8 {}\n#define KV_MODE {}\n#define GEMM_TC 0\n#define GEMM_WMMA (STRATA_WMMA && {})\n\ #define GEMM_BM {}\n#define GEMM_BK {}\n#define GEMM_MIN_BLOCKS 1\n#define GEMV_LOADW {}\n\ #define FA_BQ {}\n#define FA_BK {}\n{}", include_str!("compat.h"), @@ -126,6 +127,7 @@ fn source(kv_q8: bool) -> String { join(IQ3S_GRID.iter().map(|v| format!("{v:#x}ULL")).collect()), join(KSIGNS_IQ2XS.iter().map(|v| v.to_string()).collect()), join(KVALUES_IQ4NL.iter().map(|v| v.to_string()).collect()), + join(crate::quant::TQ_LUT.iter().flatten().map(|v| format!("{v:e}f")).collect()), crate::cuda::llama_numerics() as u8, kv_q8 as u8, // `STRATA_HIP_WMMA=0` falls back to the CUDA-core multiplications (A/B comparison, and a workaround if a @@ -169,6 +171,8 @@ impl Gpu { max_smem = hip.attribute(ffi::ATTR_SHARED_PER_BLOCK, device as i32).unwrap_or(16 << 10) as usize; } anyhow::ensure!(max_smem >= (16 << 10), "HIP device reports {max_smem} B of shared memory a block"); + // The HIP kernels hold an f16 or q8 cache (KV_MODE 0 or 1): refuse q4 and q2 rather than run f16 unasked. + anyhow::ensure!(crate::cuda::kv_mode() <= 1, "--kv q4 and q2 are not available on the HIP backend (f16 or q8)"); let kv_q8 = crate::cuda::kv_q8(); let rtc = ffi::Rtc::get().context("HIP init").context("hiprtc is required to compile the kernels")?; let (maj, min) = rtc.version(); @@ -313,7 +317,7 @@ impl Gpu { /// `gemvq`; with z = 2 also the matrix of `pair.2` rows at byte offset `pair.0` into the output at byte offset /// `pair.1` (token stride `pair.2`). fn gemvq_pair(&self, w: &GpuTensor, x: u64, x_stride: usize, xq: u64, y: u64, y_stride: usize, nt: usize, - pair: (i64, i64, i32), z: u32) -> anyhow::Result<()> { + pair: (i64, i64, i32, f32), z: u32) -> anyhow::Result<()> { if !(1..=4).contains(&nt) { bail!("gemvn: {nt} inputs (1 to 4)"); } let (ncols, k1) = Self::gemv_cols("gemv", w.ty, w.cols)?; let (mut c, rpw) = Self::gemv_cfg(w.ty, w.rows, w.cols, 1); @@ -325,23 +329,23 @@ impl Gpu { c.shared_mem_bytes = per; for t in 0..nt { let (xt, yt) = (x + 4 * t as u64 * x_stride as u64, y + 4 * t as u64 * y_stride as u64); - launch!(self, &k1, c, w.ptr, xt, yt, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2); + launch!(self, &k1, c, w.ptr, xt, yt, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2, w.scale, pair.3); } return Ok(()); } if nt == 1 { - launch!(self, &k1, c, w.ptr, x, y, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2); + launch!(self, &k1, c, w.ptr, x, y, w.rows as i32, ncols, rpw, xq, pair.0, pair.1, pair.2, w.scale, pair.3); return Ok(()); } let kn = k1.replacen("gemv", "gemvn", 1); - launch!(self, &kn, c, w.ptr, x, x_stride as i32, y, y_stride as i32, w.rows as i32, ncols, rpw, nt as i32, xq, pair.0, pair.1, pair.2); + launch!(self, &kn, c, w.ptr, x, x_stride as i32, y, y_stride as i32, w.rows as i32, ncols, rpw, nt as i32, xq, pair.0, pair.1, pair.2, w.scale, pair.3); 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`). 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) -> 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(()) } let (same, act) = (act & SAME_X != 0, act & !SAME_X); @@ -350,11 +354,11 @@ impl Gpu { 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); + 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); + 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); } Ok(()) } @@ -582,11 +586,11 @@ impl Backend for Gpu { fn gemm(&self, ty: GgmlType, rows: usize, cols: usize, tiles: u64, n_tiles: usize, x: u64, x_stride: usize, n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { - self.gemm_raw(ty, rows, cols, tiles, n_tiles, 0, 0, x, x_stride, n_x, xrow, y, y_stride, act) + self.gemm_raw(ty, rows, cols, tiles, n_tiles, 0, 0, x, x_stride, n_x, xrow, y, y_stride, act, 1.0f32) } fn gemm_dense(&self, w: &GpuTensor, n: usize, x: u64, x_stride: usize, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { - 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) + 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 } @@ -594,7 +598,7 @@ impl Backend for Gpu { fn gemv(&self, w: &GpuTensor, x: u64, y: u64) -> anyhow::Result<()> { let (ncols, kn) = Self::gemv_cols("gemv", w.ty, w.cols)?; let (c, rpw) = Self::gemv_cfg(w.ty, w.rows, w.cols, 1); - launch!(self, &kn, c, w.ptr, x, y, w.rows as i32, ncols, rpw, 0u64, 0i64, 0i64, 0i32); + launch!(self, &kn, c, w.ptr, x, y, w.rows as i32, ncols, rpw, 0u64, 0i64, 0i64, 0i32, w.scale, 1.0f32); Ok(()) } @@ -603,7 +607,7 @@ impl Backend for Gpu { } fn gemvq(&self, w: &GpuTensor, x: u64, x_stride: usize, xq: u64, y: u64, y_stride: usize, nt: usize) -> anyhow::Result<()> { - self.gemvq_pair(w, x, x_stride, xq, y, y_stride, nt, (0, 0, 0), 1) + self.gemvq_pair(w, x, x_stride, xq, y, y_stride, nt, (0, 0, 0, 1.0f32), 1) } fn gemvq2(&self, a: &GpuTensor, b: &GpuTensor, x: u64, x_stride: usize, xq: u64, ya: u64, yb: u64, nt: usize) -> anyhow::Result<()> { @@ -612,7 +616,7 @@ impl Backend for Gpu { return self.gemvq(b, x, x_stride, xq, yb, b.rows, nt); } let ((a, ya), (b, yb)) = if a.rows >= b.rows { ((a, ya), (b, yb)) } else { ((b, yb), (a, ya)) }; - self.gemvq_pair(a, x, x_stride, xq, ya, a.rows, nt, (b.ptr as i64 - a.ptr as i64, yb as i64 - ya as i64, b.rows as i32), 2) + self.gemvq_pair(a, x, x_stride, xq, ya, a.rows, nt, (b.ptr as i64 - a.ptr as i64, yb as i64 - ya as i64, b.rows as i32, b.scale), 2) } fn moe_gemv(&self, ty: GgmlType, rows: usize, cols: usize, w: u64, stride: usize, ids: u64, k: usize, x: u64, x_stride: usize, @@ -631,7 +635,7 @@ impl Backend for Gpu { } fn dequant(&self, w: &GpuTensor, rows: usize, out: u64) -> anyhow::Result<()> { - launch!(self, &kname("dequant", w.ty), cfg((rows as u32, 1), 256, 0), w.ptr, out, Self::gemv_cols("dequant", w.ty, w.cols)?.0); + launch!(self, &kname("dequant", w.ty), cfg((rows as u32, 1), 256, 0), w.ptr, out, Self::gemv_cols("dequant", w.ty, w.cols)?.0, w.scale); Ok(()) } @@ -668,7 +672,11 @@ impl Backend for Gpu { } fn rope_neox(&self, x: u64, stride: usize, heads: usize, per: usize, n_rot: usize, step: u64, base: f32) -> anyhow::Result<()> { - launch!(self, "rope_neox", cfg(((heads / per) as u32, 1), (n_rot / 2) as u32, 0), x, stride as i32, per as i32, n_rot as i32, step, base); + self.rope_pairs(x, stride, heads, per, n_rot, step, base, 0, n_rot / 2) + } + + fn rope_pairs(&self, x: u64, stride: usize, heads: usize, per: usize, n_rot: usize, step: u64, base: f32, lo: usize, hi: usize) -> anyhow::Result<()> { + launch!(self, "rope_neox", cfg(((heads / per) as u32, 1), (n_rot / 2) as u32, 0), x, stride as i32, per as i32, n_rot as i32, step, base, lo as i32, hi as i32); Ok(()) } @@ -751,6 +759,11 @@ impl Backend for Gpu { Ok(()) } + fn dflash2_conv(&self, x: u64, dyn_w: u64, base: u64, out: u64, h: usize, gs: usize, k: usize, t: usize, part: usize) -> anyhow::Result<()> { + launch!(self, "dflash2_conv", cfg((h.div_ceil(256) as u32, t as u32), 256, 0), x, dyn_w, base, out, h as i32, gs as i32, k as i32, t as i32, part as i32); + Ok(()) + } + fn attn_prefill_m(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, t: usize, nh: usize, nkv: usize, hd: usize, scale: f32, qm: u64, mw: usize, sink: u64, win: usize) -> anyhow::Result<()> { if !matches!(hd, 64 | 128 | 256) { bail!("attention prefill: head_dim {hd} unsupported (64, 128 or 256)"); } From 98b1898b5a9497148e75157a8dcf733d0706a795 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 07:28:32 +0100 Subject: [PATCH 14/26] hip: the kv_q8 comment names KV_MODE --- src/hip/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 900d11ad..beab48e0 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -39,7 +39,7 @@ pub struct Gpu { fns: HashMap, /// "gfx1201": the target hiprtc compiled for. arch: String, - /// `--kv q8` (the kernels were compiled with KV_Q8). + /// `--kv q8` (the kernels were compiled with `KV_MODE` 0 or 1; HIP has no q4/q2 cache rows). pub kv_q8: bool, /// Opt-in shared memory per block on this device (64 KiB on RDNA). max_smem: usize, From 272bb2c1631bd4882c93652402f60c32c967d993 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 07:40:56 +0100 Subject: [PATCH 15/26] hip: say which libhiprtc paths were tried and why each failed Rtc::get returns the reasons like Hip::open does; it returned None with no reason. --- src/hip/ffi.rs | 19 ++++++++++++------- src/hip/mod.rs | 4 ++-- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs index a8a7590e..5d4a2d1d 100644 --- a/src/hip/ffi.rs +++ b/src/hip/ffi.rs @@ -231,19 +231,24 @@ pub struct Rtc { _lib: Library, } -static RTC: OnceLock> = OnceLock::new(); +static RTC: OnceLock> = OnceLock::new(); impl Rtc { - pub fn get() -> Option<&'static Rtc> { RTC.get_or_init(Self::open).as_ref() } + /// The library, or which paths were tried and why each failed. + pub fn get() -> Result<&'static Rtc, &'static str> { RTC.get_or_init(Self::open).as_ref().map_err(|e| e.as_str()) } - fn open() -> Option { + fn open() -> Result { let want = candidates(std::env::var_os("STRATA_HIPRTC").map(Into::into), &["libhiprtc.so", "libhiprtc.so.7", "libhiprtc.so.6"]); + let mut tried = Vec::new(); for path in &want { - let Ok(lib) = (unsafe { Library::new(path) }) else { continue }; + let lib = match unsafe { Library::new(path) } { + Ok(l) => l, + Err(e) => { tried.push(format!("{}: not loadable ({e})", path.display())); continue } + }; unsafe { - macro_rules! g { ($n:literal) => { match Self::sym(&lib, $n) { Some(f) => f, None => continue } } } - return Some(Rtc { + macro_rules! g { ($n:literal) => { match Self::sym(&lib, $n) { Some(f) => f, None => { tried.push(format!("{}: no {}", path.display(), $n)); continue } } } } + return Ok(Rtc { version: g!("hiprtcVersion"), create: g!("hiprtcCreateProgram"), compile: g!("hiprtcCompileProgram"), @@ -258,7 +263,7 @@ impl Rtc { }); } } - None + Err(format!("no hiprtc: {}", tried.join(", "))) } unsafe fn sym(lib: &Library, name: &str) -> Option { diff --git a/src/hip/mod.rs b/src/hip/mod.rs index beab48e0..3e575c35 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -174,7 +174,7 @@ impl Gpu { // The HIP kernels hold an f16 or q8 cache (KV_MODE 0 or 1): refuse q4 and q2 rather than run f16 unasked. anyhow::ensure!(crate::cuda::kv_mode() <= 1, "--kv q4 and q2 are not available on the HIP backend (f16 or q8)"); let kv_q8 = crate::cuda::kv_q8(); - let rtc = ffi::Rtc::get().context("HIP init").context("hiprtc is required to compile the kernels")?; + let rtc = ffi::Rtc::get().map_err(|e| anyhow::anyhow!("{e}")).context("HIP init").context("hiprtc is required to compile the kernels")?; let (maj, min) = rtc.version(); let tag = format!("{maj}.{min}"); eprintln!("hip: {} ({arch}, wave{warp}, {} B shared memory a block)", @@ -1062,7 +1062,7 @@ mod tests { /// The generated source compiles for this device through hiprtc (the CUDA source with `STRATA_HIP` taken). #[test] fn hiprtc_compiles_the_kernels() { - let Some(rtc) = ffi::Rtc::get() else { + let Ok(rtc) = ffi::Rtc::get() else { eprintln!("skipping: no hiprtc"); return; }; From 1fcca1c06b722e2d19aca7d72ad6a697df102ab8 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 07:41:13 +0100 Subject: [PATCH 16/26] hip: gfx11 WMMA results go to the rows RDNA3 puts them in RDNA3 interleaves the D rows (2i + lane/16), RDNA4 keeps them in blocks (8*(lane/16) + i); the epilogues assumed the gfx12 layout. gfx11 numerics are not checked on a card; a test compiles the gfx11 branch. --- src/cuda/kernels.cu | 12 ++++++------ src/hip/compat.h | 9 ++++++--- src/hip/mod.rs | 11 +++++++++++ 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 0c45be62..578325da 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -1265,9 +1265,9 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int if (kb + 1 < nk) stw(); } #if GEMM_WMMA - // D layout of the AMD WMMA: lane 16*(lane>>4) keeps column lane & 15 and rows 8*(lane>>4) .. +7 of each tile. + // D layout of the AMD WMMA: the lane keeps column lane & 15 and rows STRATA_WMMA_ROW(lane, 0..7) of each tile. { - const int l16 = lane & 15, wl = lane >> 4; + const int l16 = lane & 15; constexpr int MT = SM ? 1 : 2, NTW = SM ? 1 : 2; #pragma unroll for (int mt = 0; mt < MT; mt++) @@ -1277,7 +1277,7 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int if (n >= rows) continue; #pragma unroll for (int i = 0; i < 8; i++) { - int r = wm + mt * 16 + 8 * wl + 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 = accw[mt * NTW + nt][i]; @@ -3323,7 +3323,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co for (int kk = 0; kk < HD; kk += 16) acc = strata_hip::strata_wmma(strata_hip::strata_ld_wmma(qrow + kk), strata_hip::strata_ld_wmma(krow + kk), acc); #pragma unroll - for (int i = 0; i < 8; i++) sw[(8 * (lane >> 4) + i) * PW + kg * 16 + l16] = acc[i]; + for (int i = 0; i < 8; i++) sw[STRATA_WMMA_ROW(lane, i) * PW + kg * 16 + l16] = acc[i]; } __syncwarp(); #pragma unroll @@ -3464,7 +3464,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co #if GEMM_WMMA // P * V on the matrix cores, the way the scores are: A = P (this warp's 16 query rows x the tile's keys, in // halves), B = V^T (16 head dimensions x the same keys, one half a tile row apart). The lane's 8 results land - // in AMD's layout again (query rows 8*(lane>>4) + i, dim column lane & 15), so each 16 x 16 result tile is + // in AMD's layout again (query rows STRATA_WMMA_ROW(lane, i), dim column lane & 15), so each 16 x 16 result tile is // staged in f32 and read back as the two m16n8k16 dim tiles the rescale above, the epilogue below and the // score stage all use (`st` is free again by now: it held the scores of this tile). if (!skip) { @@ -3489,7 +3489,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co acc = strata_hip::strata_wmma(strata_hip::strata_ld_wmma(pa), strata_hip::strata_ld_wmma_t(pb, PQ), acc); } #pragma unroll - for (int i = 0; i < 8; i++) sw[(8 * (lane >> 4) + i) * 16 + l16] = acc[i]; + for (int i = 0; i < 8; i++) sw[STRATA_WMMA_ROW(lane, i) * 16 + l16] = acc[i]; __syncwarp(); #pragma unroll for (int r = 0; r < 2; r++) diff --git a/src/hip/compat.h b/src/hip/compat.h index 6202692a..85381e8c 100644 --- a/src/hip/compat.h +++ b/src/hip/compat.h @@ -88,16 +88,19 @@ __device__ __forceinline__ int any_sync(unsigned, int predicate) { return (int)( // ---- matrix cores (gfx11/gfx12 WMMA) ---- // D[16x16] += A[16x16] * B^T[16x16]: both operands are 16 rows of 16 halves, which is exactly how the prefill GEMM // stages X (positions) and W (output rows) in shared memory, so no transpose is needed. Each lane supplies the -// k-values of its own row of both operands and holds 8 results: rows 8*(lane>>4) + i, column lane & 15. -// gfx12 splits the k dimension across the two half-waves (each lane gives 8 halves, lanes 16-31 the upper half); -// gfx11 takes all 16 from one lane. +// k-values of its own row of both operands and holds 8 results of column lane & 15, in rows STRATA_WMMA_ROW(lane, i). +// gfx12 splits the k dimension across the two half-waves (each lane gives 8 halves, lanes 16-31 the upper half) and +// gives lanes 16-31 rows 8..15; gfx11 takes all 16 halves from every lane (lanes 16-31 repeat lanes 0-15) and +// interleaves the rows, even ones in lanes 0-15 and odd ones in lanes 16-31 (as llama.cpp's mma.cuh has it for RDNA3). #if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || \ defined(__gfx1151__) || defined(__gfx1152__) #define STRATA_WMMA 1 #define STRATA_WMMA_K 16 +#define STRATA_WMMA_ROW(lane, i) (2 * (i) + ((lane) >> 4)) #elif defined(__gfx1200__) || defined(__gfx1201__) #define STRATA_WMMA 1 #define STRATA_WMMA_K 8 +#define STRATA_WMMA_ROW(lane, i) (8 * ((lane) >> 4) + (i)) #else #define STRATA_WMMA 0 #define STRATA_WMMA_K 0 diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 3e575c35..31c3edef 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -1073,4 +1073,15 @@ mod tests { let arch = hip.arch(0).unwrap(); rtc.compile(&source(false), "kernels.cu", &arch, &[]).expect("hiprtc compiles kernels.cu for the device"); } + + /// The gfx11 (RDNA3) WMMA branch compiles, whatever card is present: its intrinsics, operand width and + /// `STRATA_WMMA_ROW` layout differ from gfx12's. Numerics on gfx11 need an RDNA3 card to check. + #[test] + fn hiprtc_compiles_the_kernels_for_gfx11() { + let Ok(rtc) = ffi::Rtc::get() else { + eprintln!("skipping: no hiprtc"); + return; + }; + rtc.compile(&source(false), "kernels.cu", "gfx1100", &[]).expect("hiprtc compiles kernels.cu for gfx1100"); + } } From 10a5fcbf32f5b3f156f2838c2162607e19380f2f Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 07:41:15 +0100 Subject: [PATCH 17/26] hip: read the device properties into a buffer with room to spare, and scan it in bounds The 1472-byte buffer was ROCm 7's struct size, and the gfx scan could slice past its end. --- src/hip/ffi.rs | 53 +++++++++++++++++++++++++++++++++++++------------- 1 file changed, 39 insertions(+), 14 deletions(-) diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs index 5d4a2d1d..076fc186 100644 --- a/src/hip/ffi.rs +++ b/src/hip/ffi.rs @@ -35,10 +35,23 @@ pub const ATTR_INTEGRATED: c_int = 16; pub const ATTR_MULTIPROCESSOR_COUNT: c_int = 63; pub const ATTR_MAX_THREADS_PER_BLOCK: c_int = 56; -/// `hipDeviceProp_t` from ROCm 7: the field offsets the backend reads. The struct is version-specific, so every -/// read is validated (the architecture name must look like `gfxNNNN`) and `STRATA_HIP_ARCH` overrides it. -const PROP_SIZE: usize = 1472; -const PROP_GCN_ARCH_NAME: usize = 1160; +/// Room for `hipDeviceProp_t`, which `hipGetDeviceProperties` writes whole. ROCm 7's `hipDeviceProp_tR0600` is 1472 +/// bytes; the size is not exported and changes between versions, so the buffer leaves ample room for a larger one. +/// The architecture name is found by shape (`find_gfx`), and `STRATA_HIP_ARCH` overrides it. +const PROP_BUF: usize = 16 << 10; + +/// The first `gfxNNNN`-looking string at a 4-byte offset in `bytes` (at least 6 characters, at most 16), read only +/// within `bytes`. +fn find_gfx(bytes: &[u8]) -> Option { + for i in (0..bytes.len()).step_by(4) { + let w = &bytes[i..(i + 16).min(bytes.len())]; + if !w.starts_with(b"gfx") { continue } + let end = w.iter().position(|&b| b == 0 || !b.is_ascii_alphanumeric()).unwrap_or(w.len()); + if end < 6 { continue } + return String::from_utf8(w[..end].to_vec()).ok(); + } + None +} type Fn = unsafe extern "C" fn(); @@ -189,18 +202,10 @@ impl Hip { fn prop_arch(&self, device: c_int) -> Option { // Resolved here and not in `bind`: this is the only use, and a missing symbol must not fail the backend. let f: unsafe extern "C" fn(*mut c_void, c_int) -> c_int = unsafe { Self::sym(&self._lib, "hipGetDeviceProperties") }?; - let mut buf = vec![0u64; PROP_SIZE / 8]; + let mut buf = vec![0u64; PROP_BUF / 8]; let r = unsafe { f(buf.as_mut_ptr().cast(), device) }; if r != HIP_SUCCESS { return None } - let bytes = unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), PROP_SIZE) }; - for i in (0..bytes.len().saturating_sub(8)).step_by(4) { - if &bytes[i..i + 3] != b"gfx" { continue } - let end = bytes[i..i + 16].iter().position(|&b| b == 0 || !(b as char).is_ascii_alphanumeric()).unwrap_or(16); - if end < 6 { continue } - let s = String::from_utf8(bytes[i..i + end].to_vec()).ok()?; - return Some(s); - } - None + find_gfx(unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), PROP_BUF) }) } pub fn device_name(&self, device: c_int) -> String { @@ -346,3 +351,23 @@ struct ProgGuard { impl Drop for ProgGuard { fn drop(&mut self) { unsafe { (self.destroy)(&mut self.prog) }; } } + +#[cfg(test)] +mod tests { + use super::find_gfx; + + /// The name is found at the end of the buffer without reading past it, a short `gfx` is passed over, and a + /// buffer without one gives None. + #[test] + fn find_gfx_reads_only_inside_the_buffer() { + let mut b = vec![0u8; 64]; + b[8..11].copy_from_slice(b"gfx"); + b[56..63].copy_from_slice(b"gfx1201"); + assert_eq!(find_gfx(&b).as_deref(), Some("gfx1201")); + assert_eq!(find_gfx(&b[..60]), None); + let mut tail = vec![0u8; 61]; + tail[52..61].copy_from_slice(b"gfx1100ab"); + assert_eq!(find_gfx(&tail).as_deref(), Some("gfx1100ab")); + assert_eq!(find_gfx(&[0u8; 32]), None); + } +} From 8ca7e9a30da25984b59597a3f1e73843548cfad9 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 07:41:17 +0100 Subject: [PATCH 18/26] hip: comments and HIP.md match the code (staging tile size, small-tile warps, prefill matrix cores) moe_prefetch on HIP is one #if around the body instead of a loop that breaks at once. --- docs/HIP.md | 2 +- src/cuda/kernels.cu | 15 +++++++-------- src/hip/compat.h | 5 +++-- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/HIP.md b/docs/HIP.md index 7d555519..594228cc 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -95,7 +95,7 @@ the KV cache than a 16 GB card has left over for experts, so the run above strea Both results land in AMD's layout — 8 a lane, rows `8*(lane>>4) + i`, column `lane & 15` — rather than the m16n8k16 layout the softmax, the causal mask and the epilogue are written for, so each 16x16 result tile is staged in f32 and read back as `s[ng][2h + e] == S[warp*16 + g + 8h][ng*8 + 2t + e]` (scores) or `o[d][2r + e]` (P·V). One warp - staging tile serves both stages (`FA_BQ` x (`FA_BKL` + 8) floats, 4-6 KiB added to the block's dynamic shared + staging tile serves both stages (`FA_BQ` x (`FA_BKL` + 8) floats, 6-10 KiB added to the block's dynamic shared memory), and it is why head_dim 256 prefill takes 16 keys a step (`FA_BK_FOR`, as on Turing's 64 KB blocks): 32 keys would need 78 KiB of a block's 64. `STRATA_HIP_WMMA=0` runs the same numerics on the CUDA cores; the CPU-reference test covers both. diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 578325da..43c30077 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -1204,7 +1204,7 @@ __device__ __forceinline__ void gemm_q(const GemmTile* tiles, const u8* wd, int #if GEMM_WMMA // AMD matrix cores: the tile in xs (positions, rows = m) and ws (rows = n) is fed straight in as A and B // of D[16x16] += A * B^T. A warp owns MT x NT 16x16 tiles: (32 positions, 32 rows) for the big kernel and - // (16 positions, 64 rows) for the small-tile one. Each lane holds 8 results of every tile. + // one (16 positions, 16 rows) for the small-tile one, whose 8 warps cover 32 positions x 64 rows. Each lane holds 8 results of every tile. const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane); constexpr int MT = SM ? 1 : 2, NTW = SM ? 1 : 2; strata_hip::strata_hk wa[MT], wb[NTW]; @@ -3111,20 +3111,19 @@ extern "C" __global__ void moe_route(const float* p, int n, int k, float extra_s // One block per expert (grid.y) and line range (grid.x). STRATA_MOE_PREFETCH=1 only; a hint, never a correctness // dependency. Volta: prefetch.global.L2 exists since sm_20. extern "C" __global__ void moe_prefetch(const int* ids, int k, const int* table, const char* base, int stride, int bytes) { +#if STRATA_HIP + // AMD has no L2 prefetch instruction to give: on HIP this hint does nothing. + (void)ids; (void)k; (void)table; (void)base; (void)stride; (void)bytes; +#else int j = blockIdx.y; if (j >= k) return; int s = table[ids[j]]; if (s < 0) return; const char* p = base + (size_t)((unsigned int)s * (unsigned int)stride); int lines = bytes >> 7; - for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < lines; i += gridDim.x * blockDim.x) { -#if STRATA_HIP - (void)p; // no L2 prefetch instruction to give: moe_prefetch is a CUDA-only hint - break; -#else + for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < lines; i += gridDim.x * blockDim.x) asm volatile("prefetch.global.L2 [%0];" ::"l"(p + ((size_t)i << 7))); #endif - } } // x += sum_j w[j] ye[j] + sigmoid(sg) sh + cpu. If a slot missed, wait for the CPU worker's done flag first. @@ -3218,7 +3217,7 @@ __device__ __forceinline__ void attn_prefill_t(const float* q, const u16* kc, co // HIP: the P staging tile in halves (the PV A fragments, as on Volta) and, after it, the f32 tile the matrix-core // scores are staged through before they are read in the m16n8k16 layout the softmax below is written for. Both // sit after `vs` so the qs/ks/vs offsets do not move; `hip::Gpu::attn_prefill_m` adds the f32 tile to the block's - // dynamic shared memory (FA_BQ * (FA_BKL + 8) floats, 4-8 KiB). + // dynamic shared memory (FA_BQ * (FA_BKL + 8) floats: 10 KiB at 32 keys, 6 KiB at 16). u16* ps = vs + FA_BKL * PQ; float* st = (float*)(ps + FA_BQ * (FA_BKL + 8)); #endif diff --git a/src/hip/compat.h b/src/hip/compat.h index 85381e8c..936e4b93 100644 --- a/src/hip/compat.h +++ b/src/hip/compat.h @@ -16,8 +16,9 @@ // kernels.cu selects its code paths by the CUDA architecture level: ldmatrix from sm_75, cp.async/m16n8k16/int8-mma // from sm_80, m8n8k4 (mma884) from sm_70. AMD has none of those instructions, so the build takes the portable // pre-Volta level: per-lane shared loads instead of ldmatrix, plain typed copies instead of cp.async, and the -// CUDA-core (f16 FMA) multiplicands instead of mma.sync. Prefill therefore runs without matrix cores until the -// gfx12 WMMA path lands; decode is unaffected (it has no tensor-core path). +// CUDA-core (f16 FMA) multiplicands instead of mma.sync. On gfx11 and gfx12 the prefill GEMM and attention use the +// WMMA matrix cores instead (GEMM_WMMA, below); other targets and STRATA_HIP_WMMA=0 keep the f16 FMA path. Decode is +// unaffected (it has no tensor-core path). #ifndef __CUDA_ARCH__ #define __CUDA_ARCH__ 700 #endif From 76142a0195613e757596a47365d4eacab1fcee4b Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 13:41:23 +0100 Subject: [PATCH 19/26] hip: a batch step's GEMM ignores main's BATCHED flag act & !SAME_X let BATCHED (8) reach the kernel, which ran it as an add to y; the activation is act & 3, as on Vulkan. --- src/hip/mod.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 31c3edef..66df59eb 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -348,7 +348,8 @@ impl Gpu { 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(()) } - let (same, act) = (act & SAME_X != 0, act & !SAME_X); + // 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); @@ -977,6 +978,13 @@ mod tests { g.gemm_dense(&t, n, gx.addr(), cols, gy.addr(), rows, 0).unwrap(); g.sync().unwrap(); let got: Vec = g.get(&gy, 0, n * rows).unwrap(); + // A batch step's flag picks no other kernel here, so it gives the same bits (it reached the kernel as an add, + // which y filled with ones shows). + g.put(&vec![1f32; n * rows], &gy, 0).unwrap(); + g.gemm_dense(&t, n, gx.addr(), cols, gy.addr(), rows, crate::backend::BATCHED).unwrap(); + g.sync().unwrap(); + let batched: Vec = g.get(&gy, 0, n * rows).unwrap(); + assert!(got.iter().zip(&batched).all(|(a, b)| a.to_bits() == b.to_bits()), "rows {rows}: BATCHED changed the result"); let mut worst = 0f32; let mut at = 0; for i in 0..n * rows { From d29454722a31ec52170de0aa4b62c54e17b626cc Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 13:58:41 +0100 Subject: [PATCH 20/26] hip: the BATCHED test comment says the flag is masked, not added The host strips the flag with act & 3, so the ones-prefill is overwritten. A leaked flag would reach the kernel as act 8 and fail the bit comparison. --- src/hip/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 66df59eb..ba30bb25 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -978,8 +978,9 @@ mod tests { g.gemm_dense(&t, n, gx.addr(), cols, gy.addr(), rows, 0).unwrap(); g.sync().unwrap(); let got: Vec = g.get(&gy, 0, n * rows).unwrap(); - // A batch step's flag picks no other kernel here, so it gives the same bits (it reached the kernel as an add, - // which y filled with ones shows). + // A batch step's flag picks no other kernel here, so it gives the same bits. The host masks the flag off + // (`act & 3`), so this call stores over y. If the flag ever reached the kernel as `act` 8, the kernel would add + // to the ones and the bit comparison below would fail. g.put(&vec![1f32; n * rows], &gy, 0).unwrap(); g.gemm_dense(&t, n, gx.addr(), cols, gy.addr(), rows, crate::backend::BATCHED).unwrap(); g.sync().unwrap(); From 57299c04c39d9918f4b0cc96bff9ee8cd4466cca Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 14:59:44 +0100 Subject: [PATCH 21/26] hip: argmax_rows sizes its partials in bytes, so 9 to 64 rows fit Each int2 partial is 8 bytes; the buffer was 64 * AMAX_PARTS bytes and the check counted rows, not bytes. A test runs argmax on 64 rows against a CPU argmax and opens the backend through backend::open. --- src/hip/mod.rs | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index ba30bb25..65b6459d 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -206,7 +206,8 @@ impl Gpu { } fns.insert(name, f); } - let am_buf = alloc_raw(&hip, 64 * AMAX_PARTS)?; + // argmax_part writes an int2 (8 bytes) per partial: AMAX_PARTS per row, up to 64 rows. + let am_buf = alloc_raw(&hip, 64 * AMAX_PARTS * 8)?; let q8_buf = alloc_raw(&hip, 1)?; // Pinned ring for large host-to-device copies. let mut host: *mut c_void = std::ptr::null_mut(); @@ -661,7 +662,7 @@ impl Backend for Gpu { fn argmax_rows(&self, x: u64, n: usize, rows: usize, out: u64) -> anyhow::Result<()> { let part = self.ptr(&self.am); - anyhow::ensure!(rows * AMAX_PARTS <= self.am.len(), "argmax_rows: {rows} rows"); + anyhow::ensure!(rows * AMAX_PARTS * 8 <= self.am.len(), "argmax_rows: {rows} rows"); // len is in bytes launch!(self, "argmax_part", cfg((AMAX_PARTS as u32, rows as u32), 256, 0), x, n as i32, part); launch!(self, "argmax_rows", cfg((rows as u32, 1), AMAX_PARTS as u32, 0), part, n as i32, out); Ok(()) @@ -912,6 +913,37 @@ mod tests { assert!(got.iter().zip(&want).all(|(a, b)| a == b), "first mismatch at {:?}", got.iter().zip(&want).position(|(a, b)| a != b)); } + /// `argmax_rows` on 64 rows, the most a batch step has. The partials are 8 bytes each, AMAX_PARTS per row; the + /// buffer used to be sized as if they were one byte, so rows past 8 wrote past its end. + #[test] + fn argmax_rows_takes_64_rows() { + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let (rows, n) = (64usize, 1000usize); + let mut st = 5u32; + let x: Vec = (0..rows * n).map(|_| { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 8) as f32 }).collect(); + let want: Vec = (0..rows).map(|r| { + let row = &x[r * n..(r + 1) * n]; + let mut best = 0; + for i in 1..n { if row[i] > row[best] { best = i; } } + best as i32 + }).collect(); + let bx = g.alloc(4 * rows * n).unwrap(); + let bo = g.alloc(4 * rows).unwrap(); + g.put(&x, &bx, 0).unwrap(); + g.argmax_rows(bx.addr(), n, rows, bo.addr()).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&bo, 0, rows).unwrap(); + assert_eq!(got, want); + } + + /// `--backend hip` reaches this backend through `backend::open`, the path the CLI takes. + #[test] + fn opens_through_backend_open() { + let Ok(b) = crate::backend::open(Some("hip"), 0) else { eprintln!("skipping: no HIP device"); return }; + assert_eq!(b.name(), "hip"); + } + /// `norm_gate` with the quantize-to-int8 epilogue: the first kernel of the qwen35 attention layer, and the one /// that faulted first on the card, so it gets its own comparison against the reference math. #[test] From 6b58bac93a88a1903480d719fcf02fc3bdb4c9d2 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 14:59:44 +0100 Subject: [PATCH 22/26] hip: --device with several indices is refused, and --backend lists hip hip runs one device per process, so a split would put every layer on the first card. The --backend help and docs/USAGE.md name hip. --- docs/USAGE.md | 3 ++- src/backend.rs | 19 ++++++++++++++++++- src/main.rs | 8 ++++++-- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/docs/USAGE.md b/docs/USAGE.md index f22cff24..46c22b8d 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -71,6 +71,7 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def ## Flags +- `--backend NAME` GPU backend: `cuda`, `vulkan` or `hip` (AMD cards through ROCm, one device per run, see [HIP.md](HIP.md)). Without it CUDA is used when it loads, else Vulkan. - `--ctx` KV cache size in tokens (default 4096). For Inkling 2, Hy4, GLM, DeepSeek and Gemma 4 it is the prompt plus reply limit instead, and the default is the context the model was trained on; their caches grow with the text. - `--mtp [N]` speculative decoding with the model's draft head. Greedy tokens stay the same; sampling keeps its distribution. Needs a GGUF with an MTP head (for example the Qwen3.6-35B-A3B MTP files). @@ -225,7 +226,7 @@ OpenCode and other agents use the OpenAI address. `--device 0,1` splits the layers over the cards in proportion to their free VRAM, so more experts stay resident. The cards run one after the other, so one request gets more memory, not twice the speed of one card. MTP drafting is off on -a split model. +a split model. The HIP backend runs one device, so `--device 0,1` is refused with `--backend hip`. An index is the same card on both backends. NVIDIA cards are counted as CUDA counts them (by default the fastest card first, which is not the order of `nvidia-smi`), on Vulkan too; the other Vulkan devices follow, dedicated cards before diff --git a/src/backend.rs b/src/backend.rs index fc56393c..1fa750dd 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -59,6 +59,15 @@ unsafe impl Plain for u64 {} /// Device memory, recorded graphs and kernel ops. Host copies are synchronous; device work runs in queue order. /// Pointer arguments are device addresses; strides are in floats unless named otherwise. /// The backend `kind` ("cuda", "vulkan" or "hip") on GPU `device`; with no kind, CUDA if it loads, else Vulkan. +/// Refuses a `--device` list with several indices on the HIP backend: `hip::Gpu` opens one device per process +/// (hipSetDevice runs once, in `Gpu::new`), so a split over two cards would run both layers on the first one. +pub fn check_devices(kind: Option<&str>, devices: &[usize]) -> anyhow::Result<()> { + if kind == Some("hip") && devices.len() > 1 { + anyhow::bail!("the hip backend runs one device: --device {} needs cuda or vulkan", devices.iter().map(|d| d.to_string()).collect::>().join(",")); + } + Ok(()) +} + pub fn open(kind: Option<&str>, device: usize) -> anyhow::Result> { match kind { Some("cuda") => Ok(Box::new(crate::cuda::Gpu::new(device)?)), @@ -534,7 +543,15 @@ impl<'a> dyn Backend + 'a { #[cfg(test)] mod tests { - use super::device_order; + use super::{check_devices, device_order}; + + #[test] + fn hip_refuses_a_device_split_and_nothing_else() { + assert!(check_devices(Some("hip"), &[0, 1]).is_err()); + assert!(check_devices(Some("hip"), &[0]).is_ok()); + assert!(check_devices(Some("cuda"), &[0, 1]).is_ok()); + assert!(check_devices(None, &[0, 1]).is_ok()); + } /// Identifiers are letters here. Two cards of one model have one name and two identifiers, so names play no part. #[test] diff --git a/src/main.rs b/src/main.rs index 30f8ee18..34638d11 100644 --- a/src/main.rs +++ b/src/main.rs @@ -146,7 +146,7 @@ struct Engine { /// 5.3x smaller KV memory for 512k-1M ctx; numerics differ from f16). #[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2"])] kv: String, - /// GPU backend: cuda or vulkan [default: cuda if it loads, else vulkan]. + /// GPU backend: cuda, vulkan or hip [default: cuda if it loads, else vulkan]. #[arg(long)] backend: Option, /// GPU index, or several separated by commas (such as 0,1) to split the layers over those GPUs in proportion to @@ -394,7 +394,10 @@ impl Engine { } if self.llama_numerics { unsafe { std::env::set_var("STRATA_LLAMA_NUMERICS", "1") } } // read by Gpu::new set_kv_env(&self.kv); // read by Gpu::new and Vk::new - let open = || self.device.iter().map(|&d| backend::open(self.backend.as_deref(), d)).collect::>>(); + let open = || { + backend::check_devices(self.backend.as_deref(), &self.device)?; + self.device.iter().map(|&d| backend::open(self.backend.as_deref(), d)).collect::>>() + }; let bk = match self.gpu.then(open).transpose() { Err(e) if self.cpu_fallback => { say!("no GPU backend ({e:#}), running on the CPU"); None } r => r?, @@ -2090,6 +2093,7 @@ fn best(f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result { /// With `aux` (`--mtp-model`/`--draft-model`) the drafts are measured with that file, and runs given the same file use /// the measured draft count. fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], mut split: Option>) -> anyhow::Result<()> { + backend::check_devices(kind, device)?; let g = Gguf::open(model)?; let aux_g = open_mtp_gguf(aux)?; let m = Model::load_with_aux(&g, aux_g.as_ref(), &[])?; From 48e35b1097b0648edabc8bf1f5d73a2413ae8cc0 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 15:06:21 +0100 Subject: [PATCH 23/26] hip: the argmax test gives each row one maximum Each row is a permutation of 0..n, so the strict-greater reference needs no tie rule. The old random rows passed only because the seed is fixed. --- src/hip/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 65b6459d..0fa55ae3 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -920,8 +920,8 @@ mod tests { let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; let g: &dyn Backend = &gpu; let (rows, n) = (64usize, 1000usize); - let mut st = 5u32; - let x: Vec = (0..rows * n).map(|_| { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 8) as f32 }).collect(); + // Each row is a permutation of 0..n, so its maximum is unique and the reference needs no tie rule. + let x: Vec = (0..rows * n).map(|k| { let (r, i) = (k / n, k % n); ((i * 7919 + r * 31) % n) as f32 }).collect(); let want: Vec = (0..rows).map(|r| { let row = &x[r * n..(r + 1) * n]; let mut best = 0; From e4baa037e792c68303b707131044257a9d60d010 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 15:06:21 +0100 Subject: [PATCH 24/26] backend: open_all checks a device list once for every caller serve and calibrate opened a list with their own check; a new caller could skip it and split a hip run. calibrate now fails when it opens its devices, after the model is loaded, not before. --- src/backend.rs | 6 ++++++ src/main.rs | 8 ++------ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/backend.rs b/src/backend.rs index 1fa750dd..12489b2d 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -68,6 +68,12 @@ pub fn check_devices(kind: Option<&str>, devices: &[usize]) -> anyhow::Result<() Ok(()) } +/// Opens every device of a `--device` list, after the check above. Callers open a list through this, not one device at a time. +pub fn open_all(kind: Option<&str>, devices: &[usize]) -> anyhow::Result>> { + check_devices(kind, devices)?; + devices.iter().map(|&d| open(kind, d)).collect() +} + pub fn open(kind: Option<&str>, device: usize) -> anyhow::Result> { match kind { Some("cuda") => Ok(Box::new(crate::cuda::Gpu::new(device)?)), diff --git a/src/main.rs b/src/main.rs index 34638d11..18f7e4f0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -394,10 +394,7 @@ impl Engine { } if self.llama_numerics { unsafe { std::env::set_var("STRATA_LLAMA_NUMERICS", "1") } } // read by Gpu::new set_kv_env(&self.kv); // read by Gpu::new and Vk::new - let open = || { - backend::check_devices(self.backend.as_deref(), &self.device)?; - self.device.iter().map(|&d| backend::open(self.backend.as_deref(), d)).collect::>>() - }; + let open = || backend::open_all(self.backend.as_deref(), &self.device); let bk = match self.gpu.then(open).transpose() { Err(e) if self.cpu_fallback => { say!("no GPU backend ({e:#}), running on the CPU"); None } r => r?, @@ -2093,7 +2090,6 @@ fn best(f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result { /// With `aux` (`--mtp-model`/`--draft-model`) the drafts are measured with that file, and runs given the same file use /// the measured draft count. fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], mut split: Option>) -> anyhow::Result<()> { - backend::check_devices(kind, device)?; let g = Gguf::open(model)?; let aux_g = open_mtp_gguf(aux)?; let m = Model::load_with_aux(&g, aux_g.as_ref(), &[])?; @@ -2104,7 +2100,7 @@ fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kin anyhow::ensure!(n_pf >= 512, "--ctx too small to calibrate"); let pf = prose(&tok, n_pf)?; let load = |chunk: usize, split: Option<&[f64]>| -> anyhow::Result { - let bk = device.iter().map(|&d| backend::open(kind, d)).collect::>>()?; + let bk = backend::open_all(kind, device)?; let mut gm = GpuModel::load_split_margins(&m, bk, ctx, chunk, margin, split, kload, 1).context(LOAD_HINT)?; gm.adapt_every = 0; // fixed placement: steadier timings Ok(gm) From aed841f28ebde01671da8bc3e00eb466a4ae9f6d Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 15:15:02 +0100 Subject: [PATCH 25/26] backend: calibrate checks its --device list before it reads the GGUF A bad --device used to fail after the model was loaded, and the check ran again for every chunk. It now fails before Gguf::open; open_all still checks when the devices open. --- src/main.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main.rs b/src/main.rs index 18f7e4f0..00314b51 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2090,6 +2090,7 @@ fn best(f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result { /// With `aux` (`--mtp-model`/`--draft-model`) the drafts are measured with that file, and runs given the same file use /// the measured draft count. fn calibrate(model: &Path, aux: Option<&Path>, ctx: usize, margin: &[usize], kind: Option<&str>, device: &[usize], mut split: Option>) -> anyhow::Result<()> { + backend::check_devices(kind, device)?; // before the GGUF is read: a bad --device fails here, not after the load let g = Gguf::open(model)?; let aux_g = open_mtp_gguf(aux)?; let m = Model::load_with_aux(&g, aux_g.as_ref(), &[])?; From af3a8fc518c9bf7f0cf5f09b5a85420d3e0cee7c Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Tue, 24 Nov 2026 15:15:02 +0100 Subject: [PATCH 26/26] hip: an argmax test with ties checks the first index Values 0..16 give most rows a tied maximum; the CPU reference takes the first index, as the kernel does. The permutation test keeps the unique-maximum case. --- src/hip/mod.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 0fa55ae3..235e99d0 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -937,6 +937,30 @@ mod tests { assert_eq!(got, want); } + /// `argmax_rows` on values 0..16, so most rows tie for the maximum: the first index wins, as in the CPU reference. + #[test] + fn argmax_rows_breaks_ties_at_the_first_index() { + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let g: &dyn Backend = &gpu; + let (rows, n) = (64usize, 1000usize); + let mut st = 77u32; + let x: Vec = (0..rows * n).map(|_| { st = st.wrapping_mul(1664525).wrapping_add(1013904223); ((st >> 16) % 16) as f32 }).collect(); + let want: Vec = (0..rows).map(|r| { + let row = &x[r * n..(r + 1) * n]; + let mut best = 0; + for i in 1..n { if row[i] > row[best] { best = i; } } + best as i32 + }).collect(); + assert!(want.iter().enumerate().any(|(r, &b)| x[r * n..(r + 1) * n].iter().filter(|&&v| v == x[r * n + b as usize]).count() > 1), "no row has a tie"); + let bx = g.alloc(4 * rows * n).unwrap(); + let bo = g.alloc(4 * rows).unwrap(); + g.put(&x, &bx, 0).unwrap(); + g.argmax_rows(bx.addr(), n, rows, bo.addr()).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&bo, 0, rows).unwrap(); + assert_eq!(got, want); + } + /// `--backend hip` reaches this backend through `backend::open`, the path the CLI takes. #[test] fn opens_through_backend_open() {