From c3e32ad08f6ae04f0e654b00265d682de1bb9c2d Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER Date: Sat, 5 Dec 2026 23:21:26 +0300 Subject: [PATCH 01/16] HIP RDNA2: prefill attention on hipBLAS RDNA2 has no matrix cores: the flash prefill kernel and the dot2 GEMMs run at 0.5-12 TFLOPS, and as the context grows the attention of a prefill chunk dominates its time. This runs the attention of a chunk on the library's Tensile kernels instead (hipBLAS, fp16 in, f16 scores, f32 out): - ffi: GemmEx and GemmEx_v2 bindings (the legacy entry takes hipblasDatatype_t, the _v2 entry hipDataType; C = x W^T needs OP_N for B). - hip: attn_prefill_blas - K/V and Q as f16, Q K^T a head into an f16 score block, a wave-a-row softmax with the QSA mask, P V a head straight into out, then 1/sum and the query gate applied in att_scale. Past 32k keys, or on a chunk the kernels do not cover, the flash kernel keeps running (attn_prefill_m_at falls through to attn_prefill_m). - On by default for RDNA2 only (gfx103*); STRATA_HIPBLAS=1 turns the library path on on any HIP card, =0 off anywhere. - kernels.cu: kv_to_h, q_to_h, att_softmax, att_scale, and att_exp for RDNA2's v_exp_f32. The CUDA build compiles them and never launches them. Verified on Qwen4-35B-A3B Q4_K_M, RX 6800 XT (gfx1030): a 5.9k-token multi-topic dialogue answers all four planted facts; a 5.7k decoy recall matches llama.cpp. Series numbers (all four RDNA2 PRs): warm prefill 4K 494 -> 1007, 16K 239 -> 1264, 32K 134 -> 1052 tok/s. --- src/backend.rs | 5 + src/cuda/kernels.cu | 121 ++++++ src/cuda/mod.rs | 7 +- src/gpu_model/prefill.rs | 6 +- src/hip/ffi.rs | 852 ++++++++++++++++++++++----------------- src/hip/mod.rs | 83 +++- 6 files changed, 692 insertions(+), 382 deletions(-) diff --git a/src/backend.rs b/src/backend.rs index efbacad0..a3c57541 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -608,6 +608,11 @@ pub trait Backend: Send { /// words a row, rows up to `t` rounded up to 64; see `qsa_select`). `qm` 0: no mask. `sink` (0 = none): per-head /// attention-sink logits. `win` (0 = none): sliding-window width. 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<()>; + #[allow(clippy::too_many_arguments)] + fn attn_prefill_m_at(&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, _pos: usize) -> anyhow::Result<()> { + self.attn_prefill_m(q, kc, vc, qg, out, step, t, nh, nkv, hd, scale, qm, mw, sink, win) + } /// QSA indexer keys (see `Model::qsa`): pool the blocks of 4 positions that the `t` raw keys (rows of 128) at /// positions step[0] .. complete into `pool` (rows of 128 per block: mean, rms norm with `w`, NEOX rope at the /// block's first position). `ring`: 4 rows of 128, the raw keys of the incomplete block (row = position % 4). diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 64454c0e..d63da890 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -6064,6 +6064,127 @@ extern "C" __global__ void moe_combine_seq(float* x, const float* ye, const floa x[i] += y; } +extern "C" __global__ void kv_to_h(const u16* kc, const u16* vc, u16* k16, u16* v16, int rows, int n, int hd) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * n / 8) return; + size_t off = (size_t)(i / (hd / 8)) * hd + (i % (hd / 8)) * 8; + unsigned o[4]; + ldkv(kc, off, hd, o); + *(uint4*)(k16 + off) = *(uint4*)o; + ldkv(vc, off, hd, o); + *(uint4*)(v16 + off) = *(uint4*)o; +} + +extern "C" __global__ void q_to_h(const float* q, __half* out, int n, float scale) { + int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x); + if (i >= n) return; + float4 v = *(const float4*)(q + i); + *(uint2*)(out + i) = make_uint2(h2pack(v.x * scale, v.y * scale), h2pack(v.z * scale, v.w * scale)); +} + +#if STRATA_HIP +__device__ __forceinline__ float att_exp(float x) { + float y = x * 1.442695041f, r; + asm volatile("v_exp_f32 %0, %1" : "=v"(r) : "0"(y)); + return r; +} +#define ATT_EXP(x) att_exp(x) +#else +#define ATT_EXP(x) __expf(x) +#endif + +template +__device__ __forceinline__ void att_softmax_wave(u16* row, float* inv, int n, int L, const unsigned* mr) { + const int lane = threadIdx.x & 31, nv = L >> 3; + auto bits = [&](int k) { return mr[k >> 7] >> ((k >> 2) & 31); }; + float m = -3.402823466e38f; + for (int v = lane; v < nv; v += 32) { + int k = v << 3; + unsigned w = 3u; + if constexpr (MASKED) { + w = bits(k); + if (!(w & 3u)) continue; + } + uint4 x = *(const uint4*)(row + k); + float f[8] = {h2f((u16)x.x), h2f((u16)(x.x >> 16)), h2f((u16)x.y), h2f((u16)(x.y >> 16)), + h2f((u16)x.z), h2f((u16)(x.z >> 16)), h2f((u16)x.w), h2f((u16)(x.w >> 16))}; + if (k + 8 <= n) { +#pragma unroll + for (int j = 0; j < 8; j++) + if (w >> (j >> 2) & 1u) m = fmaxf(m, f[j]); + } else { +#pragma unroll + for (int j = 0; j < 8; j++) + if (k + j < n && (w >> (j >> 2) & 1u)) m = fmaxf(m, f[j]); + } + } + for (int k = (nv << 3) + lane; k < n; k += 32) + if (!MASKED || (bits(k) & 1u)) m = fmaxf(m, h2f(row[k])); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) m = fmaxf(m, __shfl_xor_sync(0xffffffffu, m, o)); + float sum = 0.f; + for (int v = lane; v < nv; v += 32) { + int k = v << 3; + unsigned w = 3u; + if constexpr (MASKED) { + w = bits(k); + if (!(w & 3u)) { *(uint4*)(row + k) = make_uint4(0u, 0u, 0u, 0u); continue; } + } + uint4 x = *(const uint4*)(row + k); + float f[8] = {h2f((u16)x.x), h2f((u16)(x.x >> 16)), h2f((u16)x.y), h2f((u16)(x.y >> 16)), + h2f((u16)x.z), h2f((u16)(x.z >> 16)), h2f((u16)x.w), h2f((u16)(x.w >> 16))}; + unsigned p[4] = {}; + if (k + 8 <= n) { +#pragma unroll + for (int j = 0; j < 8; j++) { + float e = (w >> (j >> 2) & 1u) ? ATT_EXP(f[j] - m) : 0.f; + sum += e; + p[j >> 1] |= (unsigned)f2h(e) << (16 * (j & 1)); + } + } else { +#pragma unroll + for (int j = 0; j < 8; j++) { + float e = k + j < n && (w >> (j >> 2) & 1u) ? ATT_EXP(f[j] - m) : 0.f; + sum += e; + p[j >> 1] |= (unsigned)f2h(e) << (16 * (j & 1)); + } + } + *(uint4*)(row + k) = make_uint4(p[0], p[1], p[2], p[3]); + } + for (int k = (nv << 3) + lane; k < n; k += 32) { + float e = !MASKED || (bits(k) & 1u) ? ATT_EXP(h2f(row[k]) - m) : 0.f; + sum += e; + row[k] = f2h(e); + } +#pragma unroll + for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); + if (lane == 0) *inv = sum > 0.f ? 1.f / sum : 0.f; +} + +extern "C" __global__ void att_softmax(u16* s, float* inv, int qb, int L, int pos, int q0, int nh, int rows, + const unsigned* qm, int mw) { + int r = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5); + if (r >= rows) return; + int i = r / nh, n = pos + q0 + i + 1; + u16* row = s + (size_t)(r % nh) * qb * L + (size_t)i * L; + if (qm) att_softmax_wave(row, inv + r, n, L, qm + (size_t)(q0 + i) * mw); + else att_softmax_wave(row, inv + r, n, L, 0); +} + +extern "C" __global__ void att_scale(float* out, const float* inv, const float* qg, int nh, int hd, int n) { + int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x); + if (i >= n) return; + float4 v = *(float4*)(out + i); + float s = inv[i / hd]; + if (qg) { + const float* g = qg + (size_t)(i / (nh * hd)) * nh * 2 * hd + (size_t)((i / hd) % nh) * 2 * hd + hd + i % hd; + v.x *= s * sigmoid(g[0]); v.y *= s * sigmoid(g[1]); v.z *= s * sigmoid(g[2]); v.w *= s * sigmoid(g[3]); + } else { + v.x *= s; v.y *= s; v.z *= s; v.w *= s; + } + *(float4*)(out + i) = v; +} + // ---- attention prefill (flash, tensor cores) ---- // grid = (ceil(T / 64), heads), block = 128: warp w owns queries 16w .. 16w + 15 of the tile. Query t (position diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 989c3f11..a585eae7 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -587,6 +587,7 @@ fn kernel_names_with(sm80: bool, dp4a: bool) -> Vec { .chain(QTYPES.iter().filter(int8_d).map(|&t| kname("gemmd", t))) .chain([64, 128, 256, 512].iter().flat_map(|h| [format!("attn_decode_{h}"), format!("attn_decode_gqa_{h}")])) .chain(["attn_decode_gqa4_128".to_string()]) + .chain(["kv_to_h", "q_to_h", "att_softmax", "att_scale"].map(String::from)) .collect() } @@ -2415,8 +2416,8 @@ mod tests { #[test] fn kernel_names() { let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); - assert_eq!(sm80.len(), 470); - assert_eq!(sm70.len(), 398); + assert_eq!(sm80.len(), 474); + assert_eq!(sm70.len(), 402); assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmd")), "sm_70 must not load the int8 prefill GEMM: {:?}", sm70.iter().filter(|n| n.starts_with("gemmi")).collect::>()); @@ -2427,7 +2428,7 @@ mod tests { #[test] fn kernel_names_tu11x_dp4a() { let tu11x = super::kernel_names_with(false, true); - assert_eq!(tu11x.len(), 446); + assert_eq!(tu11x.len(), 450); assert!(tu11x.contains(&"gemmi_q4_k".to_string())); assert!(tu11x.contains(&"gemmis_q8_0".to_string())); assert!(tu11x.iter().all(|n| !n.starts_with("gemmd")), diff --git a/src/gpu_model/prefill.rs b/src/gpu_model/prefill.rs index c16fa787..a7f439c5 100644 --- a/src/gpu_model/prefill.rs +++ b/src/gpu_model/prefill.rs @@ -757,7 +757,11 @@ impl GpuModel<'_> { } _ => (kc[self.cur].addr(), vc[self.cur].addr()), }; - g.attn_prefill_m(at(l.b), kca, vca, if c.q_gate { at(l.a) } else { 0 }, at(l.d), step, t, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), qm, mw, sink_addr, win)?; + if rows.is_none() { + g.attn_prefill_m_at(at(l.b), kca, vca, if c.q_gate { at(l.a) } else { 0 }, at(l.d), step, t, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), qm, mw, sink_addr, win, self.pos)?; + } else { + g.attn_prefill_m(at(l.b), kca, vca, if c.q_gate { at(l.a) } else { 0 }, at(l.d), step, t, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), qm, mw, sink_addr, win)?; + } probe(&mut tr, "q", &pf.slab, at(l.a), nh * qs, t)?; probe(&mut tr, "k", &pf.slab, kk, kv, t)?; probe(&mut tr, "v", &pf.slab, vv, kv, t)?; diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs index 18a5d51e..a4827fc9 100644 --- a/src/hip/ffi.rs +++ b/src/hip/ffi.rs @@ -1,377 +1,475 @@ -//! 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 HOST_REGISTER_PORTABLE: u32 = 1; -pub const HOST_REGISTER_READ_ONLY: u32 = 8; -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; -/// `hipDeviceAttributeMultiprocessorCount`: compute units, or half of them in WGP mode. -pub const ATTR_MULTIPROCESSOR_COUNT: c_int = 63; - -/// 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 -} - -/// 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_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, - pub stream_sync: unsafe extern "C" fn(Stream) -> 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_destroy: unsafe extern "C" fn(Event) -> c_int, - pub stream_wait_event: unsafe extern "C" fn(Stream, Event, u32) -> 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 host_register: unsafe extern "C" fn(*mut c_void, usize, u32) -> c_int, - pub host_unregister: unsafe extern "C" fn(*mut c_void) -> c_int, - pub module_load: unsafe extern "C" fn(*mut Module, *const c_void) -> 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, - _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_async: g!("hipMemsetAsync"), - memcpy: g!("hipMemcpy"), - memcpy_async: g!("hipMemcpyAsync"), - stream_create: g!("hipStreamCreateWithFlags"), - stream_sync: g!("hipStreamSynchronize"), - 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_destroy: g!("hipEventDestroy"), - stream_wait_event: g!("hipStreamWaitEvent"), - host_malloc: g!("hipHostMalloc"), - host_free: g!("hipHostFree"), - host_device_ptr: g!("hipHostGetDevicePointer"), - host_register: g!("hipHostRegister"), - host_unregister: g!("hipHostUnregister"), - module_load: g!("hipModuleLoadData"), - function: g!("hipModuleGetFunction"), - launch: g!("hipModuleLaunchKernel"), - func_set_attribute: g!("hipFuncSetAttribute"), - error_string: g!("hipGetErrorString"), - _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_BUF / 8]; - let r = unsafe { f(buf.as_mut_ptr().cast(), device) }; - if r != HIP_SUCCESS { return None } - find_gfx(unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), PROP_BUF) }) - } - - /// The device's PCI address as sysfs names it ("0000:0c:00.0"), or None when the runtime does not give it. - pub fn pci_bus_id(&self, device: c_int) -> Option { - let f: unsafe extern "C" fn(*mut c_char, c_int, c_int) -> c_int = unsafe { Self::sym(&self._lib, "hipDeviceGetPCIBusId") }?; - let mut buf = [0 as c_char; 64]; - if unsafe { f(buf.as_mut_ptr(), 64, device) } != HIP_SUCCESS { return None } - Some(unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy().to_lowercase()) - } - - 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 { - /// 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() -> 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 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 => { tried.push(format!("{}: no {}", path.display(), $n)); continue } } } } - return Ok(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, - }); - } - } - Err(format!("no hiprtc: {}", tried.join(", "))) - } - - 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")?, - ]; - if arch.starts_with("gfx10") { - opts.push(std::ffi::CString::new("-mno-wavefrontsize64")?); - } - 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) }; } -} - -#[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); - } -} +//! 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 HOST_REGISTER_PORTABLE: u32 = 1; +pub const HOST_REGISTER_READ_ONLY: u32 = 8; +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; +/// `hipDeviceAttributeMultiprocessorCount`: compute units, or half of them in WGP mode. +pub const ATTR_MULTIPROCESSOR_COUNT: c_int = 63; + +/// 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 +} + +/// 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 const BLAS_OP_N: c_int = 111; +pub const BLAS_OP_T: c_int = 112; +pub const BLAS_R_16F: c_int = 150; +pub const BLAS_R_32F: c_int = 151; +pub const BLAS_COMPUTE_32F: c_int = BLAS_R_32F; +pub const BLAS_GEMM_DEFAULT: c_int = 160; +pub const BLAS_V2_R_16F: c_int = 2; +pub const BLAS_V2_COMPUTE_32F: c_int = 2; + +type GemmEx = unsafe extern "C" fn(*mut c_void, c_int, c_int, c_int, c_int, c_int, *const c_void, *const c_void, + c_int, c_int, *const c_void, c_int, c_int, *const c_void, *mut c_void, c_int, + c_int, c_int, c_int) -> c_int; + +pub struct Blas { + handle: *mut c_void, + destroy: unsafe extern "C" fn(*mut c_void) -> c_int, + set_stream: unsafe extern "C" fn(*mut c_void, Stream) -> c_int, + gemm_ex: GemmEx, + gemm_ex_v2: Option, + _lib: &'static Library, +} + +impl Drop for Blas { + fn drop(&mut self) { if !self.handle.is_null() { unsafe { (self.destroy)(self.handle) }; } } +} + +impl Blas { + pub fn open() -> anyhow::Result { + let want = candidates(std::env::var_os("STRATA_HIPBLAS").map(Into::into), + &["hipblas.dll", "libhipblas.so", "libhipblas.so.7", "libhipblas.so.6"]); + let mut tried = Vec::new(); + for path in &want { + let lib = match unsafe { Library::new(path) } { + Ok(l) => l, + Err(e) => { tried.push(format!("{}: not loadable ({e})", path.display())); continue } + }; + unsafe { + let create: unsafe extern "C" fn(*mut *mut c_void) -> c_int = match Self::sym(&lib, "hipblasCreate") { + Some(f) => f, + None => { tried.push(format!("{}: no hipblasCreate", path.display())); continue } + }; + let Some(set_stream) = Self::sym:: c_int>(&lib, "hipblasSetStream") else { + tried.push(format!("{}: no hipblasSetStream", path.display())); continue + }; + let Some(gemm_ex) = Self::sym::(&lib, "hipblasGemmEx") else { + tried.push(format!("{}: no hipblasGemmEx", path.display())); continue + }; + let Some(destroy) = Self::sym:: c_int>(&lib, "hipblasDestroy") else { + tried.push(format!("{}: no hipblasDestroy", path.display())); continue + }; + let mut handle: *mut c_void = std::ptr::null_mut(); + if create(&mut handle) != 0 || handle.is_null() { + tried.push(format!("{}: hipblasCreate failed", path.display())); continue + } + let gemm_ex_v2 = Self::sym::(&lib, "hipblasGemmEx_v2"); + return Ok(Blas { handle, destroy, set_stream, gemm_ex, gemm_ex_v2, _lib: Box::leak(Box::new(lib)) }); + } + } + Err(anyhow::anyhow!("no hipblas: {}", tried.join(", "))).context("hipblas init") + } + + pub fn set_stream(&self, stream: Stream) -> anyhow::Result<()> { + let r = unsafe { (self.set_stream)(self.handle, stream) }; + if r != 0 { anyhow::bail!("hipblasSetStream: {r}") } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + pub fn gemm_ex_f16_f32(&self, transa: c_int, transb: c_int, m: usize, n: usize, k: usize, alpha: f32, + a: u64, lda: usize, b: u64, ldb: usize, beta: f32, c: u64, ldc: usize) -> anyhow::Result<()> { + let r = unsafe { (self.gemm_ex)(self.handle, transa, transb, m as c_int, n as c_int, k as c_int, + &alpha as *const f32 as *const c_void, a as *const c_void, BLAS_R_16F, lda as c_int, + b as *const c_void, BLAS_R_16F, ldb as c_int, + &beta as *const f32 as *const c_void, c as *mut c_void, BLAS_R_32F, ldc as c_int, + BLAS_COMPUTE_32F, BLAS_GEMM_DEFAULT) }; + if r != 0 { anyhow::bail!("hipblasGemmEx({m}x{n}x{k}): status {r}") } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + pub fn gemm_ex_f16_f16(&self, transa: c_int, transb: c_int, m: usize, n: usize, k: usize, alpha: f32, + a: u64, lda: usize, b: u64, ldb: usize, beta: f32, c: u64, ldc: usize) -> anyhow::Result<()> { + let Some(f) = self.gemm_ex_v2 else { anyhow::bail!("hipblasGemmEx_v2 is not exported") }; + let r = unsafe { f(self.handle, transa, transb, m as c_int, n as c_int, k as c_int, + &alpha as *const f32 as *const c_void, a as *const c_void, BLAS_V2_R_16F, lda as c_int, + b as *const c_void, BLAS_V2_R_16F, ldb as c_int, + &beta as *const f32 as *const c_void, c as *mut c_void, BLAS_V2_R_16F, ldc as c_int, + BLAS_V2_COMPUTE_32F, BLAS_GEMM_DEFAULT) }; + if r != 0 { anyhow::bail!("hipblasGemmEx_v2({m}x{n}x{k}): status {r}") } + Ok(()) + } + + unsafe fn sym(lib: &Library, name: &str) -> Option { + let s = unsafe { lib.get::(format!("{name}").as_bytes()).ok() }?; + Some(*s) + } +} + +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_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, + pub stream_sync: unsafe extern "C" fn(Stream) -> 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_destroy: unsafe extern "C" fn(Event) -> c_int, + pub stream_wait_event: unsafe extern "C" fn(Stream, Event, u32) -> 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 host_register: unsafe extern "C" fn(*mut c_void, usize, u32) -> c_int, + pub host_unregister: unsafe extern "C" fn(*mut c_void) -> c_int, + pub module_load: unsafe extern "C" fn(*mut Module, *const c_void) -> 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, + _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_async: g!("hipMemsetAsync"), + memcpy: g!("hipMemcpy"), + memcpy_async: g!("hipMemcpyAsync"), + stream_create: g!("hipStreamCreateWithFlags"), + stream_sync: g!("hipStreamSynchronize"), + 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_destroy: g!("hipEventDestroy"), + stream_wait_event: g!("hipStreamWaitEvent"), + host_malloc: g!("hipHostMalloc"), + host_free: g!("hipHostFree"), + host_device_ptr: g!("hipHostGetDevicePointer"), + host_register: g!("hipHostRegister"), + host_unregister: g!("hipHostUnregister"), + module_load: g!("hipModuleLoadData"), + function: g!("hipModuleGetFunction"), + launch: g!("hipModuleLaunchKernel"), + func_set_attribute: g!("hipFuncSetAttribute"), + error_string: g!("hipGetErrorString"), + _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_BUF / 8]; + let r = unsafe { f(buf.as_mut_ptr().cast(), device) }; + if r != HIP_SUCCESS { return None } + find_gfx(unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), PROP_BUF) }) + } + + /// The device's PCI address as sysfs names it ("0000:0c:00.0"), or None when the runtime does not give it. + pub fn pci_bus_id(&self, device: c_int) -> Option { + let f: unsafe extern "C" fn(*mut c_char, c_int, c_int) -> c_int = unsafe { Self::sym(&self._lib, "hipDeviceGetPCIBusId") }?; + let mut buf = [0 as c_char; 64]; + if unsafe { f(buf.as_mut_ptr(), 64, device) } != HIP_SUCCESS { return None } + Some(unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy().to_lowercase()) + } + + 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 { + /// 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() -> 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 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 => { tried.push(format!("{}: no {}", path.display(), $n)); continue } } } } + return Ok(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, + }); + } + } + Err(format!("no hiprtc: {}", tried.join(", "))) + } + + 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")?, + ]; + if arch.starts_with("gfx10") { + opts.push(std::ffi::CString::new("-mno-wavefrontsize64")?); + } + 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) }; } +} + +#[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); + } +} diff --git a/src/hip/mod.rs b/src/hip/mod.rs index cfa7119b..cd6990e2 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -80,6 +80,11 @@ pub struct Gpu { /// Pinned staging for large `htod`, used as a ring: the copy returns before its DMA, so the host fills the next /// region while the card reads the previous one (expert streaming in prefill). staging: Mutex, + blas: Option, + att_kv: std::cell::RefCell>, + att_q: std::cell::RefCell>, + att_s: std::cell::RefCell>, + att_inv: std::cell::RefCell>, } // The HIP handles are raw pointers but the runtime is thread-safe for the calls the backend makes, and `Backend` @@ -177,6 +182,55 @@ fn cache_key(src: &str, arch: &str, rtc: &str) -> u64 { } impl Gpu { + + fn blas_buf(&self, cell: &std::cell::RefCell>, bytes: usize) -> anyhow::Result { + let mut b = cell.borrow_mut(); + if b.as_ref().map(|buf| buf.len() < bytes).unwrap_or(true) { + *b = None; + *b = Some(self.alloc(bytes)?); + } + Ok(b.as_ref().unwrap().addr()) + } + + fn attn_prefill_blas(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, t: usize, pos: usize, nh: usize, nkv: usize, hd: usize, + scale: f32, qm: u64, mw: usize) -> anyhow::Result<()> { + let blas = self.blas.as_ref().unwrap(); + let (rows, n) = (pos + t, nkv * hd); + let kv_bytes = rows * n * 2; + let k16 = self.blas_buf(&self.att_kv, 2 * kv_bytes)?; + let v16 = k16 + kv_bytes as u64; + launch!(self, "kv_to_h", cfg(((rows * n / 8).div_ceil(256) as u32, 1), 256, 0), + kc, vc, k16, v16, rows as i32, n as i32, hd as i32); + let q16 = self.blas_buf(&self.att_q, t * nh * hd * 2)?; + launch!(self, "q_to_h", cfg(((t * nh * hd / 4).div_ceil(256) as u32, 1), 256, 0), q, q16, (t * nh * hd) as i32, scale); + let qb = (ATT_S_BYTES / (nh * ((pos + t + 7) & !7) * 2)).clamp(1, ATT_QB).min(t).max(1); + let s = self.blas_buf(&self.att_s, nh * qb * ((pos + t + 7) & !7) * 2)?; + let inv = self.blas_buf(&self.att_inv, t * nh * 4)?; + for q0 in (0..t).step_by(qb) { + let (b, l) = (qb.min(t - q0), pos + q0 + qb.min(t - q0)); + let lp = (l + 7) & !7; + for h in 0..nh { + let sh = s + (h * qb * lp * 2) as u64; + blas.gemm_ex_f16_f16(ffi::BLAS_OP_T, ffi::BLAS_OP_N, l, b, hd, 1.0, + k16 + ((h / (nh / nkv)) * hd * 2) as u64, n, q16 + ((q0 * nh + h) * hd * 2) as u64, nh * hd, + 0.0, sh, lp)?; + } + launch!(self, "att_softmax", cfg(((b * nh).div_ceil(8) as u32, 1), 256, 0), + s, inv + (q0 * nh * 4) as u64, qb as i32, lp as i32, pos as i32, q0 as i32, nh as i32, (b * nh) as i32, + qm, mw as i32); + for h in 0..nh { + let sh = s + (h * qb * lp * 2) as u64; + blas.gemm_ex_f16_f32(ffi::BLAS_OP_N, ffi::BLAS_OP_N, hd, b, l, 1.0, + v16 + ((h / (nh / nkv)) * hd * 2) as u64, n, sh, lp, 0.0, + out + ((q0 * nh + h) * hd * 4) as u64, nh * hd)?; + } + launch!(self, "att_scale", cfg(((b * nh * hd / 4).div_ceil(256) as u32, 1), 256, 0), + out + (q0 * nh * hd * 4) as u64, inv + (q0 * nh * 4) as u64, + if qg == 0 { 0 } else { qg + (q0 * nh * 2 * hd * 4) as u64 }, + nh as i32, hd as i32, (b * nh * hd) as i32); + } + Ok(()) + } pub fn new(device: usize) -> anyhow::Result { let (kv_k_mode, kv_v_mode) = (crate::cuda::kv_k_mode(), crate::cuda::kv_v_mode()); anyhow::ensure!(!((kv_k_mode > 0 || kv_v_mode > 0) && crate::cuda::llama_numerics()), "--kv q8/q4 does not combine with --llama-numerics (its attention reads f16 KV)"); @@ -251,8 +305,13 @@ impl Gpu { let sms = hip.attribute(ffi::ATTR_MULTIPROCESSOR_COUNT, device as i32).unwrap_or(16).max(1) as usize; let wm = hip_wmma && wmma_arch(&arch); let (mla_wmma, idx_wmma) = (wm && std::env::var_os("STRATA_MLA_SIMT").is_none(), wm && std::env::var("STRATA_IDX_WMMA").is_ok_and(|v| v == "1")); + let rdna2 = arch.starts_with("gfx103"); + let blas = (std::env::var("STRATA_HIPBLAS").map(|v| v != "0").unwrap_or(rdna2)) + .then(|| ffi::Blas::open().ok()).flatten() + .filter(|b| b.set_stream(stream).is_ok()); + if blas.is_some() { crate::say!("hipblas: prefill GEMMs run on GemmEx (fp16 in, f32 compute)"); } Ok(Gpu { hip, device, stream, side, marks, next_mark: Default::default(), pinned: Default::default(), beside: Default::default(), beside_lag: Default::default(), fns, arch, kv_mode: if kv_k_mode == kv_v_mode { kv_k_mode } else { 10 }, kv_k_mode, kv_v_mode, flags: ink_flags(), pci, max_smem, sms, mla_wmma, idx_wmma, am: am_buf, - graphs: Mutex::new(HashMap::new()), graph_failed: Default::default(), fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging) }) + graphs: Mutex::new(HashMap::new()), graph_failed: Default::default(), fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging), blas, att_kv: Default::default(), att_q: Default::default(), att_s: Default::default(), att_inv: Default::default() }) } pub fn arch(&self) -> &str { &self.arch } @@ -569,6 +628,11 @@ const GRAPHS_MAX: usize = 32; const RING: usize = 64 << 20; /// Mark events of the copy queue (`Gpu::mark`). const MARKS: usize = 64; + +const ATT_QB: usize = 1024; +const ATT_S_BYTES: usize = 768 << 20; +static ATT_FALLBACK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +const ATT_DENSE_MAX: usize = 32768; const RING_MIN: usize = 256 << 10; fn alloc_raw(hip: &Arc, bytes: usize) -> anyhow::Result { @@ -1186,6 +1250,23 @@ impl Backend for Gpu { Ok(()) } + + #[allow(clippy::too_many_arguments)] + fn attn_prefill_m_at(&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, pos: usize) -> anyhow::Result<()> { + if self.blas.is_some() && !ATT_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) + && sink == 0 && win == 0 && hd % 8 == 0 && nh % nkv == 0 && t >= 8 && pos + t <= ATT_DENSE_MAX { + match self.attn_prefill_blas(q, kc, vc, qg, out, t, pos, nh, nkv, hd, scale, qm, mw) { + Ok(()) => return Ok(()), + Err(e) if !ATT_FALLBACK.swap(true, std::sync::atomic::Ordering::Relaxed) => { + crate::say!("hipblas attention: {e:#}; the flash kernel takes over"); + } + Err(_) => {} + } + } + self.attn_prefill_m(q, kc, vc, qg, out, step, t, nh, nkv, hd, scale, qm, mw, sink, win) + } + 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(()) From 98bddb187c5c8b7e24049b7c2950d942cc0a1971 Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER <61810711+I-AM-ENGINEER@users.noreply.github.com> Date: Sun, 6 Dec 2026 03:37:32 +0300 Subject: [PATCH 02/16] hip/ffi.rs: LF line endings and "\0" in the symbol lookup, no code change The raw NUL byte made git treat the file as binary, so it was committed with CRLF and every later diff of it showed the whole file. ASCII again, LF like the rest of the tree. --- src/hip/ffi.rs | 950 ++++++++++++++++++++++++------------------------- 1 file changed, 475 insertions(+), 475 deletions(-) diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs index a4827fc9..6577d420 100644 --- a/src/hip/ffi.rs +++ b/src/hip/ffi.rs @@ -1,475 +1,475 @@ -//! 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 HOST_REGISTER_PORTABLE: u32 = 1; -pub const HOST_REGISTER_READ_ONLY: u32 = 8; -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; -/// `hipDeviceAttributeMultiprocessorCount`: compute units, or half of them in WGP mode. -pub const ATTR_MULTIPROCESSOR_COUNT: c_int = 63; - -/// 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 -} - -/// 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 const BLAS_OP_N: c_int = 111; -pub const BLAS_OP_T: c_int = 112; -pub const BLAS_R_16F: c_int = 150; -pub const BLAS_R_32F: c_int = 151; -pub const BLAS_COMPUTE_32F: c_int = BLAS_R_32F; -pub const BLAS_GEMM_DEFAULT: c_int = 160; -pub const BLAS_V2_R_16F: c_int = 2; -pub const BLAS_V2_COMPUTE_32F: c_int = 2; - -type GemmEx = unsafe extern "C" fn(*mut c_void, c_int, c_int, c_int, c_int, c_int, *const c_void, *const c_void, - c_int, c_int, *const c_void, c_int, c_int, *const c_void, *mut c_void, c_int, - c_int, c_int, c_int) -> c_int; - -pub struct Blas { - handle: *mut c_void, - destroy: unsafe extern "C" fn(*mut c_void) -> c_int, - set_stream: unsafe extern "C" fn(*mut c_void, Stream) -> c_int, - gemm_ex: GemmEx, - gemm_ex_v2: Option, - _lib: &'static Library, -} - -impl Drop for Blas { - fn drop(&mut self) { if !self.handle.is_null() { unsafe { (self.destroy)(self.handle) }; } } -} - -impl Blas { - pub fn open() -> anyhow::Result { - let want = candidates(std::env::var_os("STRATA_HIPBLAS").map(Into::into), - &["hipblas.dll", "libhipblas.so", "libhipblas.so.7", "libhipblas.so.6"]); - let mut tried = Vec::new(); - for path in &want { - let lib = match unsafe { Library::new(path) } { - Ok(l) => l, - Err(e) => { tried.push(format!("{}: not loadable ({e})", path.display())); continue } - }; - unsafe { - let create: unsafe extern "C" fn(*mut *mut c_void) -> c_int = match Self::sym(&lib, "hipblasCreate") { - Some(f) => f, - None => { tried.push(format!("{}: no hipblasCreate", path.display())); continue } - }; - let Some(set_stream) = Self::sym:: c_int>(&lib, "hipblasSetStream") else { - tried.push(format!("{}: no hipblasSetStream", path.display())); continue - }; - let Some(gemm_ex) = Self::sym::(&lib, "hipblasGemmEx") else { - tried.push(format!("{}: no hipblasGemmEx", path.display())); continue - }; - let Some(destroy) = Self::sym:: c_int>(&lib, "hipblasDestroy") else { - tried.push(format!("{}: no hipblasDestroy", path.display())); continue - }; - let mut handle: *mut c_void = std::ptr::null_mut(); - if create(&mut handle) != 0 || handle.is_null() { - tried.push(format!("{}: hipblasCreate failed", path.display())); continue - } - let gemm_ex_v2 = Self::sym::(&lib, "hipblasGemmEx_v2"); - return Ok(Blas { handle, destroy, set_stream, gemm_ex, gemm_ex_v2, _lib: Box::leak(Box::new(lib)) }); - } - } - Err(anyhow::anyhow!("no hipblas: {}", tried.join(", "))).context("hipblas init") - } - - pub fn set_stream(&self, stream: Stream) -> anyhow::Result<()> { - let r = unsafe { (self.set_stream)(self.handle, stream) }; - if r != 0 { anyhow::bail!("hipblasSetStream: {r}") } - Ok(()) - } - - #[allow(clippy::too_many_arguments)] - pub fn gemm_ex_f16_f32(&self, transa: c_int, transb: c_int, m: usize, n: usize, k: usize, alpha: f32, - a: u64, lda: usize, b: u64, ldb: usize, beta: f32, c: u64, ldc: usize) -> anyhow::Result<()> { - let r = unsafe { (self.gemm_ex)(self.handle, transa, transb, m as c_int, n as c_int, k as c_int, - &alpha as *const f32 as *const c_void, a as *const c_void, BLAS_R_16F, lda as c_int, - b as *const c_void, BLAS_R_16F, ldb as c_int, - &beta as *const f32 as *const c_void, c as *mut c_void, BLAS_R_32F, ldc as c_int, - BLAS_COMPUTE_32F, BLAS_GEMM_DEFAULT) }; - if r != 0 { anyhow::bail!("hipblasGemmEx({m}x{n}x{k}): status {r}") } - Ok(()) - } - - #[allow(clippy::too_many_arguments)] - pub fn gemm_ex_f16_f16(&self, transa: c_int, transb: c_int, m: usize, n: usize, k: usize, alpha: f32, - a: u64, lda: usize, b: u64, ldb: usize, beta: f32, c: u64, ldc: usize) -> anyhow::Result<()> { - let Some(f) = self.gemm_ex_v2 else { anyhow::bail!("hipblasGemmEx_v2 is not exported") }; - let r = unsafe { f(self.handle, transa, transb, m as c_int, n as c_int, k as c_int, - &alpha as *const f32 as *const c_void, a as *const c_void, BLAS_V2_R_16F, lda as c_int, - b as *const c_void, BLAS_V2_R_16F, ldb as c_int, - &beta as *const f32 as *const c_void, c as *mut c_void, BLAS_V2_R_16F, ldc as c_int, - BLAS_V2_COMPUTE_32F, BLAS_GEMM_DEFAULT) }; - if r != 0 { anyhow::bail!("hipblasGemmEx_v2({m}x{n}x{k}): status {r}") } - Ok(()) - } - - unsafe fn sym(lib: &Library, name: &str) -> Option { - let s = unsafe { lib.get::(format!("{name}").as_bytes()).ok() }?; - Some(*s) - } -} - -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_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, - pub stream_sync: unsafe extern "C" fn(Stream) -> 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_destroy: unsafe extern "C" fn(Event) -> c_int, - pub stream_wait_event: unsafe extern "C" fn(Stream, Event, u32) -> 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 host_register: unsafe extern "C" fn(*mut c_void, usize, u32) -> c_int, - pub host_unregister: unsafe extern "C" fn(*mut c_void) -> c_int, - pub module_load: unsafe extern "C" fn(*mut Module, *const c_void) -> 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, - _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_async: g!("hipMemsetAsync"), - memcpy: g!("hipMemcpy"), - memcpy_async: g!("hipMemcpyAsync"), - stream_create: g!("hipStreamCreateWithFlags"), - stream_sync: g!("hipStreamSynchronize"), - 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_destroy: g!("hipEventDestroy"), - stream_wait_event: g!("hipStreamWaitEvent"), - host_malloc: g!("hipHostMalloc"), - host_free: g!("hipHostFree"), - host_device_ptr: g!("hipHostGetDevicePointer"), - host_register: g!("hipHostRegister"), - host_unregister: g!("hipHostUnregister"), - module_load: g!("hipModuleLoadData"), - function: g!("hipModuleGetFunction"), - launch: g!("hipModuleLaunchKernel"), - func_set_attribute: g!("hipFuncSetAttribute"), - error_string: g!("hipGetErrorString"), - _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_BUF / 8]; - let r = unsafe { f(buf.as_mut_ptr().cast(), device) }; - if r != HIP_SUCCESS { return None } - find_gfx(unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), PROP_BUF) }) - } - - /// The device's PCI address as sysfs names it ("0000:0c:00.0"), or None when the runtime does not give it. - pub fn pci_bus_id(&self, device: c_int) -> Option { - let f: unsafe extern "C" fn(*mut c_char, c_int, c_int) -> c_int = unsafe { Self::sym(&self._lib, "hipDeviceGetPCIBusId") }?; - let mut buf = [0 as c_char; 64]; - if unsafe { f(buf.as_mut_ptr(), 64, device) } != HIP_SUCCESS { return None } - Some(unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy().to_lowercase()) - } - - 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 { - /// 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() -> 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 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 => { tried.push(format!("{}: no {}", path.display(), $n)); continue } } } } - return Ok(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, - }); - } - } - Err(format!("no hiprtc: {}", tried.join(", "))) - } - - 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")?, - ]; - if arch.starts_with("gfx10") { - opts.push(std::ffi::CString::new("-mno-wavefrontsize64")?); - } - 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) }; } -} - -#[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); - } -} +//! 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 HOST_REGISTER_PORTABLE: u32 = 1; +pub const HOST_REGISTER_READ_ONLY: u32 = 8; +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; +/// `hipDeviceAttributeMultiprocessorCount`: compute units, or half of them in WGP mode. +pub const ATTR_MULTIPROCESSOR_COUNT: c_int = 63; + +/// 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 +} + +/// 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 const BLAS_OP_N: c_int = 111; +pub const BLAS_OP_T: c_int = 112; +pub const BLAS_R_16F: c_int = 150; +pub const BLAS_R_32F: c_int = 151; +pub const BLAS_COMPUTE_32F: c_int = BLAS_R_32F; +pub const BLAS_GEMM_DEFAULT: c_int = 160; +pub const BLAS_V2_R_16F: c_int = 2; +pub const BLAS_V2_COMPUTE_32F: c_int = 2; + +type GemmEx = unsafe extern "C" fn(*mut c_void, c_int, c_int, c_int, c_int, c_int, *const c_void, *const c_void, + c_int, c_int, *const c_void, c_int, c_int, *const c_void, *mut c_void, c_int, + c_int, c_int, c_int) -> c_int; + +pub struct Blas { + handle: *mut c_void, + destroy: unsafe extern "C" fn(*mut c_void) -> c_int, + set_stream: unsafe extern "C" fn(*mut c_void, Stream) -> c_int, + gemm_ex: GemmEx, + gemm_ex_v2: Option, + _lib: &'static Library, +} + +impl Drop for Blas { + fn drop(&mut self) { if !self.handle.is_null() { unsafe { (self.destroy)(self.handle) }; } } +} + +impl Blas { + pub fn open() -> anyhow::Result { + let want = candidates(std::env::var_os("STRATA_HIPBLAS").map(Into::into), + &["hipblas.dll", "libhipblas.so", "libhipblas.so.7", "libhipblas.so.6"]); + let mut tried = Vec::new(); + for path in &want { + let lib = match unsafe { Library::new(path) } { + Ok(l) => l, + Err(e) => { tried.push(format!("{}: not loadable ({e})", path.display())); continue } + }; + unsafe { + let create: unsafe extern "C" fn(*mut *mut c_void) -> c_int = match Self::sym(&lib, "hipblasCreate") { + Some(f) => f, + None => { tried.push(format!("{}: no hipblasCreate", path.display())); continue } + }; + let Some(set_stream) = Self::sym:: c_int>(&lib, "hipblasSetStream") else { + tried.push(format!("{}: no hipblasSetStream", path.display())); continue + }; + let Some(gemm_ex) = Self::sym::(&lib, "hipblasGemmEx") else { + tried.push(format!("{}: no hipblasGemmEx", path.display())); continue + }; + let Some(destroy) = Self::sym:: c_int>(&lib, "hipblasDestroy") else { + tried.push(format!("{}: no hipblasDestroy", path.display())); continue + }; + let mut handle: *mut c_void = std::ptr::null_mut(); + if create(&mut handle) != 0 || handle.is_null() { + tried.push(format!("{}: hipblasCreate failed", path.display())); continue + } + let gemm_ex_v2 = Self::sym::(&lib, "hipblasGemmEx_v2"); + return Ok(Blas { handle, destroy, set_stream, gemm_ex, gemm_ex_v2, _lib: Box::leak(Box::new(lib)) }); + } + } + Err(anyhow::anyhow!("no hipblas: {}", tried.join(", "))).context("hipblas init") + } + + pub fn set_stream(&self, stream: Stream) -> anyhow::Result<()> { + let r = unsafe { (self.set_stream)(self.handle, stream) }; + if r != 0 { anyhow::bail!("hipblasSetStream: {r}") } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + pub fn gemm_ex_f16_f32(&self, transa: c_int, transb: c_int, m: usize, n: usize, k: usize, alpha: f32, + a: u64, lda: usize, b: u64, ldb: usize, beta: f32, c: u64, ldc: usize) -> anyhow::Result<()> { + let r = unsafe { (self.gemm_ex)(self.handle, transa, transb, m as c_int, n as c_int, k as c_int, + &alpha as *const f32 as *const c_void, a as *const c_void, BLAS_R_16F, lda as c_int, + b as *const c_void, BLAS_R_16F, ldb as c_int, + &beta as *const f32 as *const c_void, c as *mut c_void, BLAS_R_32F, ldc as c_int, + BLAS_COMPUTE_32F, BLAS_GEMM_DEFAULT) }; + if r != 0 { anyhow::bail!("hipblasGemmEx({m}x{n}x{k}): status {r}") } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + pub fn gemm_ex_f16_f16(&self, transa: c_int, transb: c_int, m: usize, n: usize, k: usize, alpha: f32, + a: u64, lda: usize, b: u64, ldb: usize, beta: f32, c: u64, ldc: usize) -> anyhow::Result<()> { + let Some(f) = self.gemm_ex_v2 else { anyhow::bail!("hipblasGemmEx_v2 is not exported") }; + let r = unsafe { f(self.handle, transa, transb, m as c_int, n as c_int, k as c_int, + &alpha as *const f32 as *const c_void, a as *const c_void, BLAS_V2_R_16F, lda as c_int, + b as *const c_void, BLAS_V2_R_16F, ldb as c_int, + &beta as *const f32 as *const c_void, c as *mut c_void, BLAS_V2_R_16F, ldc as c_int, + BLAS_V2_COMPUTE_32F, BLAS_GEMM_DEFAULT) }; + if r != 0 { anyhow::bail!("hipblasGemmEx_v2({m}x{n}x{k}): status {r}") } + Ok(()) + } + + unsafe fn sym(lib: &Library, name: &str) -> Option { + let s = unsafe { lib.get::(format!("{name}\0").as_bytes()).ok() }?; + Some(*s) + } +} + +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_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, + pub stream_sync: unsafe extern "C" fn(Stream) -> 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_destroy: unsafe extern "C" fn(Event) -> c_int, + pub stream_wait_event: unsafe extern "C" fn(Stream, Event, u32) -> 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 host_register: unsafe extern "C" fn(*mut c_void, usize, u32) -> c_int, + pub host_unregister: unsafe extern "C" fn(*mut c_void) -> c_int, + pub module_load: unsafe extern "C" fn(*mut Module, *const c_void) -> 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, + _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_async: g!("hipMemsetAsync"), + memcpy: g!("hipMemcpy"), + memcpy_async: g!("hipMemcpyAsync"), + stream_create: g!("hipStreamCreateWithFlags"), + stream_sync: g!("hipStreamSynchronize"), + 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_destroy: g!("hipEventDestroy"), + stream_wait_event: g!("hipStreamWaitEvent"), + host_malloc: g!("hipHostMalloc"), + host_free: g!("hipHostFree"), + host_device_ptr: g!("hipHostGetDevicePointer"), + host_register: g!("hipHostRegister"), + host_unregister: g!("hipHostUnregister"), + module_load: g!("hipModuleLoadData"), + function: g!("hipModuleGetFunction"), + launch: g!("hipModuleLaunchKernel"), + func_set_attribute: g!("hipFuncSetAttribute"), + error_string: g!("hipGetErrorString"), + _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_BUF / 8]; + let r = unsafe { f(buf.as_mut_ptr().cast(), device) }; + if r != HIP_SUCCESS { return None } + find_gfx(unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), PROP_BUF) }) + } + + /// The device's PCI address as sysfs names it ("0000:0c:00.0"), or None when the runtime does not give it. + pub fn pci_bus_id(&self, device: c_int) -> Option { + let f: unsafe extern "C" fn(*mut c_char, c_int, c_int) -> c_int = unsafe { Self::sym(&self._lib, "hipDeviceGetPCIBusId") }?; + let mut buf = [0 as c_char; 64]; + if unsafe { f(buf.as_mut_ptr(), 64, device) } != HIP_SUCCESS { return None } + Some(unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy().to_lowercase()) + } + + 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 { + /// 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() -> 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 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 => { tried.push(format!("{}: no {}", path.display(), $n)); continue } } } } + return Ok(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, + }); + } + } + Err(format!("no hiprtc: {}", tried.join(", "))) + } + + 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")?, + ]; + if arch.starts_with("gfx10") { + opts.push(std::ffi::CString::new("-mno-wavefrontsize64")?); + } + 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) }; } +} + +#[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 b509c3d8b5d7d179ba2fd2fff0f222c2e98260c1 Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER <61810711+I-AM-ENGINEER@users.noreply.github.com> Date: Sun, 6 Dec 2026 03:37:50 +0300 Subject: [PATCH 03/16] HIP RDNA2: u16 scores in q_to_h, skip the turbo KV cache, a separate library path var --- src/cuda/kernels.cu | 2 +- src/hip/ffi.rs | 2 +- src/hip/mod.rs | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index d63da890..b43bdd03 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -6075,7 +6075,7 @@ extern "C" __global__ void kv_to_h(const u16* kc, const u16* vc, u16* k16, u16* *(uint4*)(v16 + off) = *(uint4*)o; } -extern "C" __global__ void q_to_h(const float* q, __half* out, int n, float scale) { +extern "C" __global__ void q_to_h(const float* q, u16* out, int n, float scale) { int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x); if (i >= n) return; float4 v = *(const float4*)(q + i); diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs index 6577d420..f214a7b5 100644 --- a/src/hip/ffi.rs +++ b/src/hip/ffi.rs @@ -94,7 +94,7 @@ impl Drop for Blas { impl Blas { pub fn open() -> anyhow::Result { - let want = candidates(std::env::var_os("STRATA_HIPBLAS").map(Into::into), + let want = candidates(std::env::var_os("STRATA_HIPBLAS_LIB").map(Into::into), &["hipblas.dll", "libhipblas.so", "libhipblas.so.7", "libhipblas.so.6"]); let mut tried = Vec::new(); for path in &want { diff --git a/src/hip/mod.rs b/src/hip/mod.rs index cd6990e2..f772a11c 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -1255,6 +1255,7 @@ impl Backend for Gpu { fn attn_prefill_m_at(&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, pos: usize) -> anyhow::Result<()> { if self.blas.is_some() && !ATT_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) + && self.kv_k_mode < 4 && self.kv_v_mode < 4 && sink == 0 && win == 0 && hd % 8 == 0 && nh % nkv == 0 && t >= 8 && pos + t <= ATT_DENSE_MAX { match self.attn_prefill_blas(q, kc, vc, qg, out, t, pos, nh, nkv, hd, scale, qm, mw) { Ok(()) => return Ok(()), From 25b44af72fd34c2113e4e5c1499453ba8a4dc75f Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER <61810711+I-AM-ENGINEER@users.noreply.github.com> Date: Sun, 6 Dec 2026 04:17:50 +0300 Subject: [PATCH 04/16] HIP RDNA2: the prefill attention stays on the GEMMs at any depth (the flash kernel masks a key at a time) --- 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 f772a11c..fb3f1b83 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -632,7 +632,7 @@ const MARKS: usize = 64; const ATT_QB: usize = 1024; const ATT_S_BYTES: usize = 768 << 20; static ATT_FALLBACK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -const ATT_DENSE_MAX: usize = 32768; +const ATT_DENSE_MAX: usize = 1 << 40; const RING_MIN: usize = 256 << 10; fn alloc_raw(hip: &Arc, bytes: usize) -> anyhow::Result { From 8e2c1eac3d25f3b052c18d7aef01c10aa70db320 Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER Date: Sat, 5 Dec 2026 23:38:19 +0300 Subject: [PATCH 05/16] HIP RDNA2: batched MoE rounds on GemmStridedBatchedEx The MoE of a prefill chunk hits hipBLAS through gemm_grouped: the experts of a call dequantize to f16, their x rows gather as f16, and the products run as strided-batched GemmEx (fp16 in/out, f32 accumulate). The per-expert shapes here are small (512x2048), where one GEMM an expert costs more in rocBLAS host time than the products themselves - a whole round runs with one call. - The slots of a call split into items of the sizes Tensile runs fast on this silicon (a cost table per shape; the sizes at which the same GEMM costs 4-8x more are avoided), the cheapest cover picked by a small DP over slot counts. - A round dequants and gathers in one launch each, runs one batched GEMM, and scatters the f16 results into y with the activation (blas_scatter); a call's lone expert keeps a single act-fused GEMM through gemm_splitk_sum. - STRATA_MOE_BATCH=0 puts every expert back on its own GEMM; STRATA_MOE_STATS prints the slot counts of the first calls. - Same gate as the attention (one Blas handle): RDNA2 only by default, STRATA_HIPBLAS=1/0 overrides. CUDA and Vulkan take the trait's default, which forwards gemm_grouped to gemm with the same tile count. Verified on Qwen4-35B-A3B Q4_K_M, RX 6800 XT: the 700-token probe answers all four planted facts (34.7 tok/s decode); the 5.9k dialogue and 5.7k decoy recall match llama.cpp. Series numbers (all four RDNA2 PRs): warm prefill 4K 494 -> 1007, 16K 239 -> 1264, 32K 134 -> 1052 tok/s. --- src/backend.rs | 4 + src/cuda/kernels.cu | 60 ++++++++++++++ src/cuda/mod.rs | 10 +-- src/gpu_model/prefill.rs | 6 +- src/hip/ffi.rs | 23 +++++- src/hip/mod.rs | 173 ++++++++++++++++++++++++++++++++++++++- 6 files changed, 265 insertions(+), 11 deletions(-) diff --git a/src/backend.rs b/src/backend.rs index a3c57541..86b365ba 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -608,6 +608,10 @@ pub trait Backend: Send { /// words a row, rows up to `t` rounded up to 64; see `qsa_select`). `qm` 0: no mask. `sink` (0 = none): per-head /// attention-sink logits. `win` (0 = none): sliding-window width. 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<()>; + fn gemm_grouped(&self, ty: GgmlType, rows: usize, cols: usize, tiles_dev: u64, tiles_host: &[u64], + x: u64, x_stride: usize, n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + self.gemm(ty, rows, cols, tiles_dev, tiles_host.len() / 2, x, x_stride, n_x, xrow, y, y_stride, act) + } #[allow(clippy::too_many_arguments)] fn attn_prefill_m_at(&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, _pos: usize) -> anyhow::Result<()> { diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index b43bdd03..72e5d596 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -6185,6 +6185,66 @@ extern "C" __global__ void att_scale(float* out, const float* inv, const float* *(float4*)(out + i) = v; } +extern "C" __global__ void blas_scatter(const u16* c, const u64* m0, const u64* cnt, int P, int rows, float* y, + int y_stride, int act, int n) { + int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x); + if (i >= n) return; + int d = i % rows, r = (i / rows) % P, e = i / (P * rows); + if ((u64)r >= cnt[e]) return; + uint2 a = *(const uint2*)(c + i); + float4 v = make_float4(h2f((u16)a.x), h2f((u16)(a.x >> 16)), h2f((u16)a.y), h2f((u16)(a.y >> 16))); + float* yr = y + (size_t)((int)m0[e] + r) * y_stride + d; + yr[0] = act == 0 ? v.x : act == 1 ? silu(yr[0]) * v.x : yr[0] + v.x; + yr[1] = act == 0 ? v.y : act == 1 ? silu(yr[1]) * v.y : yr[1] + v.y; + yr[2] = act == 0 ? v.z : act == 1 ? silu(yr[2]) * v.z : yr[2] + v.z; + yr[3] = act == 0 ? v.w : act == 1 ? silu(yr[3]) * v.w : yr[3] + v.w; +} + +#define DEF_DEQUANT_H(T, NAME, SBB) \ + extern "C" __global__ void dequant_h_##NAME(const u8* w, __half* out, int cols, float sc) { \ + const u8* r = w + blockIdx.x * ROWB(cols, SBB); \ + for (int s = threadIdx.x; s < cols / 8; s += blockDim.x) { \ + float v[8]; \ + deq8(r + (size_t)(s >> 5) * SBB, s & 31, v); \ + __half* dst = out + (size_t)blockIdx.x * cols + s * 8; \ + for (int i = 0; i < 8; i++) dst[i] = __float2half(v[i] * sc); \ + } \ + } \ + \ + extern "C" __global__ void dequant_hg_##NAME(const u64* ws, __half* out, int rows, int cols, float sc) { \ + const u8* r = (const u8*)ws[blockIdx.x / rows] + (size_t)(blockIdx.x % rows) * ROWB(cols, SBB); \ + __half* o = out + (size_t)blockIdx.x * cols; \ + for (int s = threadIdx.x; s < cols / 8; s += blockDim.x) { \ + float v[8]; \ + deq8(r + (size_t)(s >> 5) * SBB, s & 31, v); \ + for (int i = 0; i < 8; i++) o[s * 8 + i] = __float2half(v[i] * sc); \ + } \ + } +QTYPES(DEF_DEQUANT_H) + +extern "C" __global__ void x_gather_h(const float* x, int x_stride, const int* xrow, int m0, int cnt, int cols, + __half* out) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= cnt * cols) return; + int r = i / cols, c = i % cols; + int row = xrow ? xrow[m0 + r] : m0 + r; + out[(size_t)r * cols + c] = __float2half(x[(size_t)row * x_stride + c]); +} + +extern "C" __global__ void x_gather_hg(const float* x, int x_stride, const int* xrow, const u64* m0, const u64* cnt, + int P, int cols, int n, __half* out) { + int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x); + if (i >= n) return; + int c = i % cols, r = (i / cols) % P, e = i / (P * cols); + uint2 z = make_uint2(0u, 0u); + if ((u64)r < cnt[e]) { + int row = xrow ? xrow[(int)m0[e] + r] : (int)m0[e] + r; + float4 v = *(const float4*)(x + (size_t)row * x_stride + c); + z = make_uint2((u32)f2h(v.x) | ((u32)f2h(v.y) << 16), (u32)f2h(v.z) | ((u32)f2h(v.w) << 16)); + } + *(uint2*)(out + i) = z; +} + // ---- attention prefill (flash, tensor cores) ---- // grid = (ceil(T / 64), heads), block = 128: warp w owns queries 16w .. 16w + 15 of the tile. Query t (position diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index a585eae7..7d40f4a8 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -581,13 +581,13 @@ fn kernel_names_with(sm80: bool, dp4a: bool) -> Vec { let int8_i = move |&&t: &&GgmlType| (sm80 || dp4a) && !t.float_x(); let int8_d = move |&&t: &&GgmlType| sm80 && !t.float_x(); KERNELS.iter().map(|s| s.to_string()) - .chain(QTYPES.iter().flat_map(|&t| ["dequant", "gemv", "gemvn", "moe_gemv", "gemm", "gemms", "gemmm"].map(|p| kname(p, t)))) + .chain(QTYPES.iter().flat_map(|&t| ["dequant", "dequant_h", "dequant_hg", "gemv", "gemvn", "moe_gemv", "gemm", "gemms", "gemmm"].map(|p| kname(p, t)))) .chain(QTYPES.iter().flat_map(|&t| ["gemv", "gemvn", "moe_gemv"].map(|p| kname(p, t) + "_p"))) .chain(QTYPES.iter().filter(int8_i).flat_map(|&t| [kname("gemmi", t), kname("gemmis", t)])) .chain(QTYPES.iter().filter(int8_d).map(|&t| kname("gemmd", t))) .chain([64, 128, 256, 512].iter().flat_map(|h| [format!("attn_decode_{h}"), format!("attn_decode_gqa_{h}")])) .chain(["attn_decode_gqa4_128".to_string()]) - .chain(["kv_to_h", "q_to_h", "att_softmax", "att_scale"].map(String::from)) + .chain(["kv_to_h", "q_to_h", "att_softmax", "att_scale", "blas_scatter", "x_gather_h", "x_gather_hg"].map(String::from)) .collect() } @@ -2416,8 +2416,8 @@ mod tests { #[test] fn kernel_names() { let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); - assert_eq!(sm80.len(), 474); - assert_eq!(sm70.len(), 402); + assert_eq!(sm80.len(), 537); + assert_eq!(sm70.len(), 465); assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmd")), "sm_70 must not load the int8 prefill GEMM: {:?}", sm70.iter().filter(|n| n.starts_with("gemmi")).collect::>()); @@ -2428,7 +2428,7 @@ mod tests { #[test] fn kernel_names_tu11x_dp4a() { let tu11x = super::kernel_names_with(false, true); - assert_eq!(tu11x.len(), 450); + assert_eq!(tu11x.len(), 513); assert!(tu11x.contains(&"gemmi_q4_k".to_string())); assert!(tu11x.contains(&"gemmis_q8_0".to_string())); assert!(tu11x.iter().all(|n| !n.starts_with("gemmd")), diff --git a/src/gpu_model/prefill.rs b/src/gpu_model/prefill.rs index a7f439c5..eda03a06 100644 --- a/src/gpu_model/prefill.rs +++ b/src/gpu_model/prefill.rs @@ -1046,14 +1046,14 @@ impl GpuModel<'_> { for ((_, cp), (gu, downs)) in steps.iter().zip(&spans) { g.beside(&mut || { if gu[0].1 > 0 { - g.gemm(mg.ty, mg.rows, mg.cols, tp(gu[0].0), gu[0].1, hx, ne, t, xrow_d, at(l.ge), c.n_ff_exp, gate_flags)?; + g.gemm_grouped(mg.ty, mg.rows, mg.cols, tp(gu[0].0), &tiles[2 * gu[0].0..2 * (gu[0].0 + gu[0].1)], hx, ne, t, xrow_d, at(l.ge), c.n_ff_exp, gate_flags)?; gate_flags |= SAME_X; - g.gemm(mu.ty, mu.rows, mu.cols, tp(gu[1].0), gu[1].1, hx, ne, t, xrow_d, at(l.ge), c.n_ff_exp, 1 | gate_flags)?; + g.gemm_grouped(mu.ty, mu.rows, mu.cols, tp(gu[1].0), &tiles[2 * gu[1].0..2 * (gu[1].0 + gu[1].1)], hx, ne, t, xrow_d, at(l.ge), c.n_ff_exp, 1 | gate_flags)?; } for &((s0, n0), lo, hi) in downs { let ge = at(l.ge) + (4 * lo * c.n_ff_exp) as u64; if let Some((s, r)) = rot { g.hadamard(ge, 0, s[1].addr(), 0, ge, c.n_ff_exp, r.block, hi - lo)?; } - g.gemm(md.ty, md.rows, md.cols, tp(s0), n0, at(l.ge) + (4 * lo * c.n_ff_exp) as u64, c.n_ff_exp, hi - lo, 0, at(l.ye) + (4 * lo * ne) as u64, ne, 0)?; + g.gemm_grouped(md.ty, md.rows, md.cols, tp(s0), &tiles[2 * s0..2 * (s0 + n0)], at(l.ge) + (4 * lo * c.n_ff_exp) as u64, c.n_ff_exp, hi - lo, 0, at(l.ye) + (4 * lo * ne) as u64, ne, 0)?; } if let Some(j) = *cp { if !pre_staged(j) { copy(j)?; } } Ok(()) diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs index f214a7b5..8b9783f4 100644 --- a/src/hip/ffi.rs +++ b/src/hip/ffi.rs @@ -3,7 +3,7 @@ use anyhow::{Context, bail}; use libloading::Library; -use std::ffi::{CStr, c_char, c_int, c_void}; +use std::ffi::{CStr, c_char, c_int, c_longlong, c_void}; use std::path::PathBuf; use std::sync::OnceLock; @@ -75,6 +75,10 @@ pub const BLAS_GEMM_DEFAULT: c_int = 160; pub const BLAS_V2_R_16F: c_int = 2; pub const BLAS_V2_COMPUTE_32F: c_int = 2; +type GemmBatchedEx = unsafe extern "C" fn(*mut c_void, c_int, c_int, c_int, c_int, c_int, *const c_void, *const c_void, + c_int, c_int, c_longlong, *const c_void, c_int, c_int, c_longlong, *const c_void, + *mut c_void, c_int, c_int, c_longlong, c_int, c_int, c_int) -> c_int; + type GemmEx = unsafe extern "C" fn(*mut c_void, c_int, c_int, c_int, c_int, c_int, *const c_void, *const c_void, c_int, c_int, *const c_void, c_int, c_int, *const c_void, *mut c_void, c_int, c_int, c_int, c_int) -> c_int; @@ -85,6 +89,7 @@ pub struct Blas { set_stream: unsafe extern "C" fn(*mut c_void, Stream) -> c_int, gemm_ex: GemmEx, gemm_ex_v2: Option, + pub gemm_batched: Option, _lib: &'static Library, } @@ -121,7 +126,8 @@ impl Blas { tried.push(format!("{}: hipblasCreate failed", path.display())); continue } let gemm_ex_v2 = Self::sym::(&lib, "hipblasGemmEx_v2"); - return Ok(Blas { handle, destroy, set_stream, gemm_ex, gemm_ex_v2, _lib: Box::leak(Box::new(lib)) }); + let gemm_batched = Self::sym::(&lib, "hipblasGemmStridedBatchedEx_v2"); + return Ok(Blas { handle, destroy, set_stream, gemm_ex, gemm_ex_v2, gemm_batched, _lib: Box::leak(Box::new(lib)) }); } } Err(anyhow::anyhow!("no hipblas: {}", tried.join(", "))).context("hipblas init") @@ -158,6 +164,19 @@ impl Blas { Ok(()) } + pub fn gemm_batched_f16_f16(&self, transa: c_int, transb: c_int, m: usize, n: usize, k: usize, a: u64, lda: usize, sa: i64, + b: u64, ldb: usize, sb: i64, c: u64, ldc: usize, sc: i64, batch: usize) -> anyhow::Result<()> { + let Some(f) = self.gemm_batched else { anyhow::bail!("hipblasGemmStridedBatchedEx_v2 is not exported") }; + let (alpha, beta) = (1.0f32, 0.0f32); + let r = unsafe { f(self.handle, transa, transb, m as c_int, n as c_int, k as c_int, + &alpha as *const f32 as *const c_void, a as *const c_void, BLAS_V2_R_16F, lda as c_int, sa as c_longlong, + b as *const c_void, BLAS_V2_R_16F, ldb as c_int, sb as c_longlong, + &beta as *const f32 as *const c_void, c as *mut c_void, BLAS_V2_R_16F, ldc as c_int, sc as c_longlong, + batch as c_int, BLAS_V2_COMPUTE_32F, BLAS_GEMM_DEFAULT) }; + if r != 0 { anyhow::bail!("hipblasGemmStridedBatchedEx_v2({m}x{n}x{k} x {batch}): status {r}") } + Ok(()) + } + unsafe fn sym(lib: &Library, name: &str) -> Option { let s = unsafe { lib.get::(format!("{name}\0").as_bytes()).ok() }?; Some(*s) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index fb3f1b83..099690ab 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -85,6 +85,11 @@ pub struct Gpu { att_q: std::cell::RefCell>, att_s: std::cell::RefCell>, att_inv: std::cell::RefCell>, + blas_w: std::cell::RefCell>, + blas_x: std::cell::RefCell>, + blas_y: std::cell::RefCell>, + blas_idx: std::cell::RefCell>, + moe_plan: std::cell::RefCell, Vec)>>, } // The HIP handles are raw pointers but the runtime is thread-safe for the calls the backend makes, and `Backend` @@ -192,6 +197,164 @@ impl Gpu { Ok(b.as_ref().unwrap().addr()) } + fn gemm_grouped(&self, ty: GgmlType, rows: usize, cols: usize, tiles_dev: u64, tiles_host: &[u64], + x: u64, x_stride: usize, n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + let full_act = act; + let (same, act) = (act & SAME_X != 0, act & 3); + let _ = (same, n_x); + let Some(slot_bytes) = rows.checked_mul(cols).and_then(|n| n.checked_mul(2)) else { + return self.gemm(ty, rows, cols, tiles_dev, tiles_host.len() / 2, x, x_stride, n_x, xrow, y, y_stride, full_act); + }; + if tiles_host.len() < 2 || cols % 8 != 0 || act > 2 || ty.float_x() || self.blas.is_none() + || slot_bytes > BLAS_W_BYTES || rows % 4 != 0 { + return self.gemm(ty, rows, cols, tiles_dev, tiles_host.len() / 2, x, x_stride, n_x, xrow, y, y_stride, full_act); + } + let blas = self.blas.as_ref().unwrap(); + let mut ex: Vec<(u64, usize, usize)> = Vec::new(); + let mut i = 0; + while i * 2 < tiles_host.len() { + let (w, m0) = (tiles_host[2 * i], (tiles_host[2 * i + 1] as u32) as usize); + let mut cnt = (tiles_host[2 * i + 1] >> 32) as u32 as usize; + i += 1; + while i * 2 < tiles_host.len() && tiles_host[2 * i] == w && (tiles_host[2 * i + 1] as u32) as usize == m0 + cnt { + cnt += (tiles_host[2 * i + 1] >> 32) as u32 as usize; + i += 1; + } + if cnt > 0 { ex.push((w, m0, cnt)); } + } + let worst = ex.iter().map(|e| (e.2 + 15) / 16).sum::(); + if ex.len() >= 2 && worst <= MOE_ITEMS_MAX && *MOE_BATCH_ON && blas.gemm_batched.is_some() { + return self.moe_rounds(blas, ty, rows, cols, &ex, x, x_stride, xrow, y, y_stride, act); + } + let slot = rows * cols; + let most = ex.iter().map(|e| e.2).max().unwrap_or(1); + let w_buf = self.blas_buf(&self.blas_w, slot * 2)?; + let xp = self.blas_buf(&self.blas_x, most * cols * 2)?; + let yp = self.blas_buf(&self.blas_y, most * rows * 4)?; + for &(w, m0, cnt) in &ex { + launch!(self, &kname("dequant_h", ty), cfg((rows as u32, 1), 256, 0), w, w_buf, cols as i32, 1.0f32); + launch!(self, "x_gather_h", cfg((((cnt * cols + 255) / 256) as u32, 1), 256, 0), + x, x_stride as i32, xrow, m0 as i32, cnt as i32, cols as i32, xp); + if act == 0 { + blas.gemm_ex_f16_f32(ffi::BLAS_OP_T, ffi::BLAS_OP_N, rows, cnt, cols, 1.0, w_buf, cols, xp, cols, + 0.0, y + (m0 as u64) * (y_stride as u64) * 4, y_stride)?; + } else { + blas.gemm_ex_f16_f32(ffi::BLAS_OP_T, ffi::BLAS_OP_N, rows, cnt, cols, 1.0, w_buf, cols, xp, cols, 0.0, yp, rows)?; + launch!(self, "gemm_splitk_sum", cfg((((cnt * rows + 255) / 256) as u32, 1), 256, 0), + yp, 1i32, cnt as i32, rows as i32, y + (m0 as u64) * (y_stride as u64) * 4, y_stride as i32, act); + } + } + Ok(()) + } + fn moe_idx(&self, items: &[(u64, usize, usize, usize)]) -> anyhow::Result { + const WORDS: usize = 3 * MOE_ITEMS_MAX; + const SLOTS: usize = 128; + if self.blas_idx.borrow().is_none() { + let (buf, host) = self.host_mailbox(WORDS * SLOTS)?; + *self.blas_idx.borrow_mut() = Some((buf, host as *mut u64, 0)); + } + let mut b = self.blas_idx.borrow_mut(); + let (buf, host, next) = b.as_mut().unwrap(); + if *next == SLOTS { self.sync()?; *next = 0; } + let n = items.len(); + let p = unsafe { host.add(*next * WORDS) }; + for (i, &(w, m0, cnt, _)) in items.iter().enumerate() { + unsafe { *p.add(i) = w; *p.add(n + i) = m0 as u64; *p.add(2 * n + i) = cnt as u64; } + } + *next += 1; + Ok(buf.addr() + ((*next - 1) * WORDS * 8) as u64) + } + + fn moe_sizes(rows: usize, cols: usize) -> &'static [(usize, f32)] { + if rows < cols { + &[(16, 9.8), (32, 15.9), (48, 27.1), (64, 29.1), (96, 40.6), (384, 47.7), (448, 48.0), (512, 47.0), (768, 70.2), (1536, 123.4)] + } else { + &[(16, 14.3), (32, 16.1), (48, 18.8), (64, 21.8), (192, 20.5), (256, 22.1), (384, 31.5), (640, 47.4), (1024, 71.4)] + } + } + + fn moe_plan(&self, rows: usize, cols: usize, cnt: usize) -> Vec { + let sizes = Self::moe_sizes(rows, cols); + let mut cell = self.moe_plan.borrow_mut(); + let entry = match cell.as_mut() { + Some(e) if e.0 == rows && e.1 == cols => e, + _ => { *cell = Some((rows, cols, vec![0], vec![0.0])); cell.as_mut().unwrap() } + }; + let (_, _, plan, cost) = entry; + for c in cost.len()..=cnt { + let (mut best, mut take) = (f32::INFINITY, sizes[0].0 as u32); + for &(s, k) in sizes { + let total = k + MOE_ITEM_US + if s < c { cost[c - s] } else { 0.0 }; + if total < best { (best, take) = (total, s as u32); } + } + cost.push(best); + plan.push(take); + } + plan.clone() + } + + fn moe_rounds(&self, blas: &ffi::Blas, ty: GgmlType, rows: usize, cols: usize, ex: &[(u64, usize, usize)], + x: u64, x_stride: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + let plan = self.moe_plan(rows, cols, ex.iter().map(|e| e.2).max().unwrap_or(1)); + let mut items: Vec<(u64, usize, usize, usize)> = Vec::with_capacity(ex.len() * 2); + for &(w, m0, cnt) in ex { + let (mut m0, mut c) = (m0, cnt); + while c > 0 { + let s = (plan[c] as usize).min(c); + items.push((w, m0, s, plan[c] as usize)); + m0 += s; + c -= s; + } + } + items.sort_by_key(|it| it.3); + let n = items.len(); + anyhow::ensure!(n <= MOE_ITEMS_MAX, "moe_rounds: {n} items"); + if *MOE_STATS && MOE_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 200 < 6 { + let mut counts: Vec = ex.iter().map(|e| e.2).collect(); + counts.sort_unstable_by(|a, b| b.cmp(a)); + let slots: usize = ex.iter().map(|e| e.2).sum(); + let us: f32 = items.iter().map(|it| Self::moe_sizes(rows, cols).iter().find(|s| s.0 == it.3).unwrap().1 + MOE_ITEM_US).sum(); + crate::say!("moe stats: {rows}x{cols} experts={} slots={} items={} padded={} about {us:.0} us; top {:?}", + ex.len(), slots, n, items.iter().map(|it| it.3).sum::(), &counts[..counts.len().min(16)]); + } + let idx = self.moe_idx(&items)?; + let (wp, m0p, cntp) = (idx, idx + (8 * n) as u64, idx + (16 * n) as u64); + let w_items = (BLAS_W_BYTES / (rows * cols * 2)).max(1); + let b_max = MOE_BATCH.min(n).min(w_items); + let row_cap = (MOE_C_BYTES / (rows * 2)).max(64); + let round = |i: usize| { + let p = items[i].3; + let mut b = 1; + while i + b < n && b < b_max && items[i + b].3 == p && b < row_cap / p { b += 1; } + (b, p) + }; + let (mut x_cap, mut c_cap) = (0usize, 0usize); + let mut i = 0; + while i < n { + let (b, p) = round(i); + x_cap = x_cap.max(b * p * cols * 2); + c_cap = c_cap.max(b * p * rows * 2); + i += b; + } + let w_buf = self.blas_buf(&self.blas_w, b_max * rows * cols * 2)?; + let xp = self.blas_buf(&self.blas_x, x_cap)?; + let c = self.blas_buf(&self.blas_y, c_cap)?; + let mut i = 0; + while i < n { + let (b, p) = round(i); + let (m0, cnt) = (m0p + (8 * i) as u64, cntp + (8 * i) as u64); + launch!(self, &kname("dequant_hg", ty), cfg(((b * rows) as u32, 1), 256, 0), + wp + (8 * i) as u64, w_buf, rows as i32, cols as i32, 1.0f32); + launch!(self, "x_gather_hg", cfg(((b * p * cols / 4).div_ceil(256) as u32, 1), 256, 0), + x, x_stride as i32, xrow, m0, cnt, p as i32, cols as i32, (b * p * cols) as i32, xp); + blas.gemm_batched_f16_f16(ffi::BLAS_OP_T, ffi::BLAS_OP_N, rows, p, cols, w_buf, cols, (rows * cols) as i64, + xp, cols, (p * cols) as i64, c, rows, (p * rows) as i64, b)?; + launch!(self, "blas_scatter", cfg(((b * p * rows / 4).div_ceil(256) as u32, 1), 256, 0), + c, m0, cnt, p as i32, rows as i32, y, y_stride as i32, act, (b * p * rows) as i32); + i += b; + } + Ok(()) + } fn attn_prefill_blas(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, t: usize, pos: usize, nh: usize, nkv: usize, hd: usize, scale: f32, qm: u64, mw: usize) -> anyhow::Result<()> { let blas = self.blas.as_ref().unwrap(); @@ -311,7 +474,7 @@ impl Gpu { .filter(|b| b.set_stream(stream).is_ok()); if blas.is_some() { crate::say!("hipblas: prefill GEMMs run on GemmEx (fp16 in, f32 compute)"); } Ok(Gpu { hip, device, stream, side, marks, next_mark: Default::default(), pinned: Default::default(), beside: Default::default(), beside_lag: Default::default(), fns, arch, kv_mode: if kv_k_mode == kv_v_mode { kv_k_mode } else { 10 }, kv_k_mode, kv_v_mode, flags: ink_flags(), pci, max_smem, sms, mla_wmma, idx_wmma, am: am_buf, - graphs: Mutex::new(HashMap::new()), graph_failed: Default::default(), fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging), blas, att_kv: Default::default(), att_q: Default::default(), att_s: Default::default(), att_inv: Default::default() }) + graphs: Mutex::new(HashMap::new()), graph_failed: Default::default(), fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging), blas, att_kv: Default::default(), att_q: Default::default(), att_s: Default::default(), att_inv: Default::default(), blas_w: Default::default(), blas_x: Default::default(), blas_y: Default::default(), blas_idx: Default::default(), moe_plan: Default::default() }) } pub fn arch(&self) -> &str { &self.arch } @@ -633,6 +796,14 @@ const ATT_QB: usize = 1024; const ATT_S_BYTES: usize = 768 << 20; static ATT_FALLBACK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); const ATT_DENSE_MAX: usize = 1 << 40; +const BLAS_W_BYTES: usize = 384 << 20; +const MOE_BATCH: usize = 32; +const MOE_C_BYTES: usize = 64 << 20; +const MOE_ITEMS_MAX: usize = 2048; +const MOE_ITEM_US: f32 = 10.0; +static MOE_BATCH_ON: LazyLock = LazyLock::new(|| std::env::var("STRATA_MOE_BATCH").map(|v| v != "0").unwrap_or(true)); +static MOE_STATS: LazyLock = LazyLock::new(|| std::env::var("STRATA_MOE_STATS").is_ok()); +static MOE_CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); const RING_MIN: usize = 256 << 10; fn alloc_raw(hip: &Arc, bytes: usize) -> anyhow::Result { From e6548fca04d3f62f43761a6db2bbb49dc61836b8 Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER <61810711+I-AM-ENGINEER@users.noreply.github.com> Date: Sun, 6 Dec 2026 03:40:46 +0300 Subject: [PATCH 06/16] HIP RDNA2: gemm_grouped in the Backend impl (prefill calls it), a dot2 fallback latch --- src/hip/mod.rs | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 099690ab..783cb5f1 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -197,18 +197,8 @@ impl Gpu { Ok(b.as_ref().unwrap().addr()) } - fn gemm_grouped(&self, ty: GgmlType, rows: usize, cols: usize, tiles_dev: u64, tiles_host: &[u64], - x: u64, x_stride: usize, n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { - let full_act = act; - let (same, act) = (act & SAME_X != 0, act & 3); - let _ = (same, n_x); - let Some(slot_bytes) = rows.checked_mul(cols).and_then(|n| n.checked_mul(2)) else { - return self.gemm(ty, rows, cols, tiles_dev, tiles_host.len() / 2, x, x_stride, n_x, xrow, y, y_stride, full_act); - }; - if tiles_host.len() < 2 || cols % 8 != 0 || act > 2 || ty.float_x() || self.blas.is_none() - || slot_bytes > BLAS_W_BYTES || rows % 4 != 0 { - return self.gemm(ty, rows, cols, tiles_dev, tiles_host.len() / 2, x, x_stride, n_x, xrow, y, y_stride, full_act); - } + fn gemm_grouped_blas(&self, ty: GgmlType, rows: usize, cols: usize, tiles_host: &[u64], + x: u64, x_stride: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { let blas = self.blas.as_ref().unwrap(); let mut ex: Vec<(u64, usize, usize)> = Vec::new(); let mut i = 0; @@ -246,6 +236,7 @@ impl Gpu { } Ok(()) } + fn moe_idx(&self, items: &[(u64, usize, usize, usize)]) -> anyhow::Result { const WORDS: usize = 3 * MOE_ITEMS_MAX; const SLOTS: usize = 128; @@ -795,6 +786,7 @@ const MARKS: usize = 64; const ATT_QB: usize = 1024; const ATT_S_BYTES: usize = 768 << 20; static ATT_FALLBACK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static MOE_FALLBACK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); const ATT_DENSE_MAX: usize = 1 << 40; const BLAS_W_BYTES: usize = 384 << 20; const MOE_BATCH: usize = 32; @@ -877,6 +869,28 @@ fn wmma_arch(arch: &str) -> bool { } impl Backend for Gpu { + fn gemm_grouped(&self, ty: GgmlType, rows: usize, cols: usize, tiles_dev: u64, tiles_host: &[u64], + x: u64, x_stride: usize, n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + let full_act = act; + let (same, act) = (act & SAME_X != 0, act & 3); + let _ = (same, n_x); + let dot2 = |g: &Gpu| g.gemm(ty, rows, cols, tiles_dev, tiles_host.len() / 2, x, x_stride, n_x, xrow, y, y_stride, full_act); + let Some(slot_bytes) = rows.checked_mul(cols).and_then(|n| n.checked_mul(2)) else { return dot2(self) }; + if tiles_host.len() < 2 || cols % 8 != 0 || act > 2 || ty.float_x() || self.blas.is_none() + || slot_bytes > BLAS_W_BYTES || rows % 4 != 0 || MOE_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) { + return dot2(self); + } + match self.gemm_grouped_blas(ty, rows, cols, tiles_host, x, x_stride, xrow, y, y_stride, act) { + Ok(()) => Ok(()), + Err(e) => { + if !MOE_FALLBACK.swap(true, std::sync::atomic::Ordering::Relaxed) { + crate::say!("hipblas experts: {e:#}; the dot2 kernel takes over"); + } + Err(e) + } + } + } + fn name(&self) -> &'static str { "hip" } fn device(&self) -> String { self.hip.device_name(self.device as i32) } From c9cb5eec348465f2b307570fb08a199e02bafc0d Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER <61810711+I-AM-ENGINEER@users.noreply.github.com> Date: Sun, 6 Dec 2026 03:44:58 +0300 Subject: [PATCH 07/16] HIP RDNA2: u16 expert tiles (the CUDA build compiles kernels.cu too) --- src/cuda/kernels.cu | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 72e5d596..185d0595 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -6201,19 +6201,19 @@ extern "C" __global__ void blas_scatter(const u16* c, const u64* m0, const u64* } #define DEF_DEQUANT_H(T, NAME, SBB) \ - extern "C" __global__ void dequant_h_##NAME(const u8* w, __half* out, int cols, float sc) { \ + extern "C" __global__ void dequant_h_##NAME(const u8* w, u16* out, int cols, float sc) { \ const u8* r = w + blockIdx.x * ROWB(cols, SBB); \ for (int s = threadIdx.x; s < cols / 8; s += blockDim.x) { \ float v[8]; \ deq8(r + (size_t)(s >> 5) * SBB, s & 31, v); \ - __half* dst = out + (size_t)blockIdx.x * cols + s * 8; \ + u16* dst = out + (size_t)blockIdx.x * cols + s * 8; \ for (int i = 0; i < 8; i++) dst[i] = __float2half(v[i] * sc); \ } \ } \ \ - extern "C" __global__ void dequant_hg_##NAME(const u64* ws, __half* out, int rows, int cols, float sc) { \ + extern "C" __global__ void dequant_hg_##NAME(const u64* ws, u16* out, int rows, int cols, float sc) { \ const u8* r = (const u8*)ws[blockIdx.x / rows] + (size_t)(blockIdx.x % rows) * ROWB(cols, SBB); \ - __half* o = out + (size_t)blockIdx.x * cols; \ + u16* o = out + (size_t)blockIdx.x * cols; \ for (int s = threadIdx.x; s < cols / 8; s += blockDim.x) { \ float v[8]; \ deq8(r + (size_t)(s >> 5) * SBB, s & 31, v); \ @@ -6223,7 +6223,7 @@ extern "C" __global__ void blas_scatter(const u16* c, const u64* m0, const u64* QTYPES(DEF_DEQUANT_H) extern "C" __global__ void x_gather_h(const float* x, int x_stride, const int* xrow, int m0, int cnt, int cols, - __half* out) { + u16* out) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i >= cnt * cols) return; int r = i / cols, c = i % cols; @@ -6232,7 +6232,7 @@ extern "C" __global__ void x_gather_h(const float* x, int x_stride, const int* x } extern "C" __global__ void x_gather_hg(const float* x, int x_stride, const int* xrow, const u64* m0, const u64* cnt, - int P, int cols, int n, __half* out) { + int P, int cols, int n, u16* out) { int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x); if (i >= n) return; int c = i % cols, r = (i / cols) % P, e = i / (P * cols); From 18a40038d388f6b9cbaa0cebd72f1b7f9f8483d6 Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER <61810711+I-AM-ENGINEER@users.noreply.github.com> Date: Sun, 6 Dec 2026 04:04:36 +0300 Subject: [PATCH 08/16] HIP RDNA2: f2h for the expert tiles' stores (a u16 tile takes the f16 bits, not the value) --- src/cuda/kernels.cu | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 185d0595..4ee8a021 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -6207,7 +6207,7 @@ extern "C" __global__ void blas_scatter(const u16* c, const u64* m0, const u64* float v[8]; \ deq8(r + (size_t)(s >> 5) * SBB, s & 31, v); \ u16* dst = out + (size_t)blockIdx.x * cols + s * 8; \ - for (int i = 0; i < 8; i++) dst[i] = __float2half(v[i] * sc); \ + for (int i = 0; i < 8; i++) dst[i] = f2h(v[i] * sc); \ } \ } \ \ @@ -6217,7 +6217,7 @@ extern "C" __global__ void blas_scatter(const u16* c, const u64* m0, const u64* for (int s = threadIdx.x; s < cols / 8; s += blockDim.x) { \ float v[8]; \ deq8(r + (size_t)(s >> 5) * SBB, s & 31, v); \ - for (int i = 0; i < 8; i++) o[s * 8 + i] = __float2half(v[i] * sc); \ + for (int i = 0; i < 8; i++) o[s * 8 + i] = f2h(v[i] * sc); \ } \ } QTYPES(DEF_DEQUANT_H) @@ -6228,7 +6228,7 @@ extern "C" __global__ void x_gather_h(const float* x, int x_stride, const int* x if (i >= cnt * cols) return; int r = i / cols, c = i % cols; int row = xrow ? xrow[m0 + r] : m0 + r; - out[(size_t)r * cols + c] = __float2half(x[(size_t)row * x_stride + c]); + out[(size_t)r * cols + c] = f2h(x[(size_t)row * x_stride + c]); } extern "C" __global__ void x_gather_hg(const float* x, int x_stride, const int* xrow, const u64* m0, const u64* cnt, From 4bce3dc093d19fc847821430ec1ab4ef09ffbd07 Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER <61810711+I-AM-ENGINEER@users.noreply.github.com> Date: Sun, 6 Dec 2026 04:29:57 +0300 Subject: [PATCH 09/16] HIP RDNA2: the experts retry on the dot2 kernel when hipBLAS fails before writing (a partial y lapses the path) --- src/hip/mod.rs | 54 ++++++++++++++++++++++++++++++++------------------ 1 file changed, 35 insertions(+), 19 deletions(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 783cb5f1..984f07f5 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -221,17 +221,24 @@ impl Gpu { let w_buf = self.blas_buf(&self.blas_w, slot * 2)?; let xp = self.blas_buf(&self.blas_x, most * cols * 2)?; let yp = self.blas_buf(&self.blas_y, most * rows * 4)?; - for &(w, m0, cnt) in &ex { - launch!(self, &kname("dequant_h", ty), cfg((rows as u32, 1), 256, 0), w, w_buf, cols as i32, 1.0f32); - launch!(self, "x_gather_h", cfg((((cnt * cols + 255) / 256) as u32, 1), 256, 0), - x, x_stride as i32, xrow, m0 as i32, cnt as i32, cols as i32, xp); - if act == 0 { - blas.gemm_ex_f16_f32(ffi::BLAS_OP_T, ffi::BLAS_OP_N, rows, cnt, cols, 1.0, w_buf, cols, xp, cols, - 0.0, y + (m0 as u64) * (y_stride as u64) * 4, y_stride)?; - } else { - blas.gemm_ex_f16_f32(ffi::BLAS_OP_T, ffi::BLAS_OP_N, rows, cnt, cols, 1.0, w_buf, cols, xp, cols, 0.0, yp, rows)?; - launch!(self, "gemm_splitk_sum", cfg((((cnt * rows + 255) / 256) as u32, 1), 256, 0), - yp, 1i32, cnt as i32, rows as i32, y + (m0 as u64) * (y_stride as u64) * 4, y_stride as i32, act); + for (i, &(w, m0, cnt)) in ex.iter().enumerate() { + let one = |g: &Gpu| -> anyhow::Result<()> { + launch!(g, &kname("dequant_h", ty), cfg((rows as u32, 1), 256, 0), w, w_buf, cols as i32, 1.0f32); + launch!(g, "x_gather_h", cfg((((cnt * cols + 255) / 256) as u32, 1), 256, 0), + x, x_stride as i32, xrow, m0 as i32, cnt as i32, cols as i32, xp); + if act == 0 { + blas.gemm_ex_f16_f32(ffi::BLAS_OP_T, ffi::BLAS_OP_N, rows, cnt, cols, 1.0, w_buf, cols, xp, cols, + 0.0, y + (m0 as u64) * (y_stride as u64) * 4, y_stride)?; + } else { + blas.gemm_ex_f16_f32(ffi::BLAS_OP_T, ffi::BLAS_OP_N, rows, cnt, cols, 1.0, w_buf, cols, xp, cols, 0.0, yp, rows)?; + launch!(g, "gemm_splitk_sum", cfg((((cnt * rows + 255) / 256) as u32, 1), 256, 0), + yp, 1i32, cnt as i32, rows as i32, y + (m0 as u64) * (y_stride as u64) * 4, y_stride as i32, act); + } + Ok(()) + }; + if let Err(e) = one(self) { + if i > 0 { MOE_PARTIAL.store(true, std::sync::atomic::Ordering::Relaxed); } + return Err(e); } } Ok(()) @@ -334,14 +341,21 @@ impl Gpu { while i < n { let (b, p) = round(i); let (m0, cnt) = (m0p + (8 * i) as u64, cntp + (8 * i) as u64); - launch!(self, &kname("dequant_hg", ty), cfg(((b * rows) as u32, 1), 256, 0), - wp + (8 * i) as u64, w_buf, rows as i32, cols as i32, 1.0f32); - launch!(self, "x_gather_hg", cfg(((b * p * cols / 4).div_ceil(256) as u32, 1), 256, 0), - x, x_stride as i32, xrow, m0, cnt, p as i32, cols as i32, (b * p * cols) as i32, xp); + let one = |g: &Gpu| -> anyhow::Result<()> { + launch!(g, &kname("dequant_hg", ty), cfg(((b * rows) as u32, 1), 256, 0), + wp + (8 * i) as u64, w_buf, rows as i32, cols as i32, 1.0f32); + launch!(g, "x_gather_hg", cfg(((b * p * cols / 4).div_ceil(256) as u32, 1), 256, 0), + x, x_stride as i32, xrow, m0, cnt, p as i32, cols as i32, (b * p * cols) as i32, xp); blas.gemm_batched_f16_f16(ffi::BLAS_OP_T, ffi::BLAS_OP_N, rows, p, cols, w_buf, cols, (rows * cols) as i64, - xp, cols, (p * cols) as i64, c, rows, (p * rows) as i64, b)?; - launch!(self, "blas_scatter", cfg(((b * p * rows / 4).div_ceil(256) as u32, 1), 256, 0), - c, m0, cnt, p as i32, rows as i32, y, y_stride as i32, act, (b * p * rows) as i32); + xp, cols, (p * cols) as i64, c, rows, (p * rows) as i64, b)?; + launch!(g, "blas_scatter", cfg(((b * p * rows / 4).div_ceil(256) as u32, 1), 256, 0), + c, m0, cnt, p as i32, rows as i32, y, y_stride as i32, act, (b * p * rows) as i32); + Ok(()) + }; + if let Err(e) = one(self) { + if i > 0 { MOE_PARTIAL.store(true, std::sync::atomic::Ordering::Relaxed); } + return Err(e); + } i += b; } Ok(()) @@ -787,6 +801,7 @@ const ATT_QB: usize = 1024; const ATT_S_BYTES: usize = 768 << 20; static ATT_FALLBACK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); static MOE_FALLBACK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static MOE_PARTIAL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); const ATT_DENSE_MAX: usize = 1 << 40; const BLAS_W_BYTES: usize = 384 << 20; const MOE_BATCH: usize = 32; @@ -882,11 +897,12 @@ impl Backend for Gpu { } match self.gemm_grouped_blas(ty, rows, cols, tiles_host, x, x_stride, xrow, y, y_stride, act) { Ok(()) => Ok(()), + Err(e) if MOE_PARTIAL.load(std::sync::atomic::Ordering::Relaxed) => Err(e), Err(e) => { if !MOE_FALLBACK.swap(true, std::sync::atomic::Ordering::Relaxed) { crate::say!("hipblas experts: {e:#}; the dot2 kernel takes over"); } - Err(e) + dot2(self) } } } From 63071b08a2bfde06eecd9667b00d628cf7d43628 Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER <61810711+I-AM-ENGINEER@users.noreply.github.com> Date: Sun, 6 Dec 2026 04:43:00 +0300 Subject: [PATCH 10/16] HIP RDNA2: size the expert mailbox in u64 slots, and clear the partial latch per call host_mailbox counts u32 words, so WORDS * SLOTS u64 slots need twice the words; the slot writes ran past the pinned allocation. MOE_PARTIAL now starts false on every gemm_grouped call, so a later failure that wrote no y still falls back to the dot2 kernel instead of aborting. --- src/hip/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 984f07f5..2f7b040c 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -248,7 +248,7 @@ impl Gpu { const WORDS: usize = 3 * MOE_ITEMS_MAX; const SLOTS: usize = 128; if self.blas_idx.borrow().is_none() { - let (buf, host) = self.host_mailbox(WORDS * SLOTS)?; + let (buf, host) = self.host_mailbox(WORDS * SLOTS * 2)?; *self.blas_idx.borrow_mut() = Some((buf, host as *mut u64, 0)); } let mut b = self.blas_idx.borrow_mut(); @@ -895,6 +895,7 @@ impl Backend for Gpu { || slot_bytes > BLAS_W_BYTES || rows % 4 != 0 || MOE_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) { return dot2(self); } + MOE_PARTIAL.store(false, std::sync::atomic::Ordering::Relaxed); match self.gemm_grouped_blas(ty, rows, cols, tiles_host, x, x_stride, xrow, y, y_stride, act) { Ok(()) => Ok(()), Err(e) if MOE_PARTIAL.load(std::sync::atomic::Ordering::Relaxed) => Err(e), From d3e91c1f143738ebe4eb4dbd2a4bfc4fb0f64a8c Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER <61810711+I-AM-ENGINEER@users.noreply.github.com> Date: Sun, 6 Dec 2026 14:39:47 +0300 Subject: [PATCH 11/16] HIP RDNA2: the expert rounds leave int8-typed weights to the int8 GEMM --- 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 2f7b040c..069d2d2e 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -891,7 +891,7 @@ impl Backend for Gpu { let _ = (same, n_x); let dot2 = |g: &Gpu| g.gemm(ty, rows, cols, tiles_dev, tiles_host.len() / 2, x, x_stride, n_x, xrow, y, y_stride, full_act); let Some(slot_bytes) = rows.checked_mul(cols).and_then(|n| n.checked_mul(2)) else { return dot2(self) }; - if tiles_host.len() < 2 || cols % 8 != 0 || act > 2 || ty.float_x() || self.blas.is_none() + if tiles_host.len() < 2 || cols % 8 != 0 || act > 2 || ty.float_x() || self.blas.is_none() || self.int8_gemm(ty) || slot_bytes > BLAS_W_BYTES || rows % 4 != 0 || MOE_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) { return dot2(self); } From 52f9d98deb66dcaa7301bfca1117d4eb9a3f32e7 Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER Date: Sun, 6 Dec 2026 00:54:22 +0300 Subject: [PATCH 12/16] HIP RDNA2: dense prefill projections on GemmEx The dense prefill GEMMs (mixer qkv/o, the SSM projections, a dense FFN where the model has one) run on hipBLAS's GemmEx: the matrix dequantizes to f16 once per call, the x block converts to f16, the product runs with an f16 store (the f32 store of the same call is a third of the throughput on RDNA2), and blas_scatter_d writes the result to y with the activation. Matrices of 4096 rows or more process 4096 tokens a step (the 8192-wide Tensile kernel of a 4096x2048 matrix costs what two halves do). A dense GEMM below 512 tokens stays on the dot2 kernel (dequantizing the whole matrix does not pay there); STRATA_HIP_DENSE=0 disables the path; a runtime failure is logged once and hands the rest of the run to dot2 (DENSE_FALLBACK). Same gate as the rest of the series: RDNA2 only by default, STRATA_HIPBLAS=1/0 override. CUDA and Vulkan are untouched - this is the HIP backend's own gemm_dense override. Verified on Qwen4-35B-A3B Q4_K_M, RX 6800 XT: the 700-token probe answers all four planted facts, the server log shows no kernel fallback lines, the 5.7k decoy recall answers 3 of 3 needles on 3 runs. kernel_names 539/467/515. --- src/cuda/kernels.cu | 21 +++++++++++++++++++ src/cuda/mod.rs | 8 +++---- src/hip/mod.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 75 insertions(+), 5 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 4ee8a021..76d4ecbf 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -6245,6 +6245,27 @@ extern "C" __global__ void x_gather_hg(const float* x, int x_stride, const int* *(uint2*)(out + i) = z; } +extern "C" __global__ void x_to_h(const float* x, int x_stride, int cols, int n, __half* out) { + int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x); + if (i >= n) return; + int c = i % cols, r = i / cols; + float4 v = *(const float4*)(x + (size_t)r * x_stride + c); + *(uint2*)(out + i) = make_uint2((u32)f2h(v.x) | ((u32)f2h(v.y) << 16), (u32)f2h(v.z) | ((u32)f2h(v.w) << 16)); +} + +extern "C" __global__ void blas_scatter_d(const u16* c, float* y, int y_stride, int rows, int act, int n) { + int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x); + if (i >= n) return; + int d = i % rows, r = i / rows; + uint2 a = *(const uint2*)(c + i); + float4 v = make_float4(h2f((u16)a.x), h2f((u16)(a.x >> 16)), h2f((u16)a.y), h2f((u16)(a.y >> 16))); + float* yr = y + (size_t)r * y_stride + d; + yr[0] = act == 0 ? v.x : act == 1 ? silu(yr[0]) * v.x : yr[0] + v.x; + yr[1] = act == 0 ? v.y : act == 1 ? silu(yr[1]) * v.y : yr[1] + v.y; + yr[2] = act == 0 ? v.z : act == 1 ? silu(yr[2]) * v.z : yr[2] + v.z; + yr[3] = act == 0 ? v.w : act == 1 ? silu(yr[3]) * v.w : yr[3] + v.w; +} + // ---- attention prefill (flash, tensor cores) ---- // grid = (ceil(T / 64), heads), block = 128: warp w owns queries 16w .. 16w + 15 of the tile. Query t (position diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 7d40f4a8..8b432ca5 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -587,7 +587,7 @@ fn kernel_names_with(sm80: bool, dp4a: bool) -> Vec { .chain(QTYPES.iter().filter(int8_d).map(|&t| kname("gemmd", t))) .chain([64, 128, 256, 512].iter().flat_map(|h| [format!("attn_decode_{h}"), format!("attn_decode_gqa_{h}")])) .chain(["attn_decode_gqa4_128".to_string()]) - .chain(["kv_to_h", "q_to_h", "att_softmax", "att_scale", "blas_scatter", "x_gather_h", "x_gather_hg"].map(String::from)) + .chain(["kv_to_h", "q_to_h", "att_softmax", "att_scale", "blas_scatter", "x_gather_h", "x_gather_hg", "x_to_h", "blas_scatter_d"].map(String::from)) .collect() } @@ -2416,8 +2416,8 @@ mod tests { #[test] fn kernel_names() { let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); - assert_eq!(sm80.len(), 537); - assert_eq!(sm70.len(), 465); + assert_eq!(sm80.len(), 539); + assert_eq!(sm70.len(), 467); assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmd")), "sm_70 must not load the int8 prefill GEMM: {:?}", sm70.iter().filter(|n| n.starts_with("gemmi")).collect::>()); @@ -2428,7 +2428,7 @@ mod tests { #[test] fn kernel_names_tu11x_dp4a() { let tu11x = super::kernel_names_with(false, true); - assert_eq!(tu11x.len(), 513); + assert_eq!(tu11x.len(), 515); assert!(tu11x.contains(&"gemmi_q4_k".to_string())); assert!(tu11x.contains(&"gemmis_q8_0".to_string())); assert!(tu11x.iter().all(|n| !n.starts_with("gemmd")), diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 069d2d2e..abd0b516 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -360,6 +360,33 @@ impl Gpu { } Ok(()) } + fn gemm_dense_blas(&self, w: &GpuTensor, n: usize, x: u64, x_stride: usize, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + let blas = self.blas.as_ref().unwrap(); + let (rows, cols) = (w.rows, w.cols); + let w16 = self.blas_buf(&self.blas_w, rows * cols * 2)?; + launch!(self, &kname("dequant_h", w.ty), cfg((rows as u32, 1), 256, 0), w.ptr, w16, cols as i32, w.scale); + let step_cap = (BLAS_W_BYTES / (2 * rows.max(cols).max(1))).max(1); + let step = (if rows >= 4096 && n > 4096 { 4096 } else { n }).min(step_cap); + let x16 = self.blas_buf(&self.blas_x, step * cols * 2)?; + let c16 = self.blas_buf(&self.blas_y, step * rows * 2)?; + for n0 in (0..n).step_by(step) { + let b = step.min(n - n0); + let done = (|| -> anyhow::Result<()> { + launch!(self, "x_to_h", cfg(((b * cols / 4).div_ceil(256) as u32, 1), 256, 0), + x + (4 * n0 * x_stride) as u64, x_stride as i32, cols as i32, (b * cols) as i32, x16); + blas.gemm_ex_f16_f16(ffi::BLAS_OP_T, ffi::BLAS_OP_N, rows, b, cols, 1.0, w16, cols, x16, cols, 0.0, c16, rows)?; + launch!(self, "blas_scatter_d", cfg(((b * rows / 4).div_ceil(256) as u32, 1), 256, 0), + c16, y + (4 * n0 * y_stride) as u64, y_stride as i32, rows as i32, act, (b * rows) as i32); + Ok(()) + })(); + if let Err(e) = done { + if n0 > 0 { DENSE_PARTIAL.store(true, std::sync::atomic::Ordering::Relaxed); } + return Err(e); + } + } + Ok(()) + } + fn attn_prefill_blas(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, t: usize, pos: usize, nh: usize, nkv: usize, hd: usize, scale: f32, qm: u64, mw: usize) -> anyhow::Result<()> { let blas = self.blas.as_ref().unwrap(); @@ -808,6 +835,11 @@ const MOE_BATCH: usize = 32; const MOE_C_BYTES: usize = 64 << 20; const MOE_ITEMS_MAX: usize = 2048; const MOE_ITEM_US: f32 = 10.0; +const DENSE_MIN: usize = 512; +static DENSE_ON: LazyLock = LazyLock::new(|| std::env::var("STRATA_HIP_DENSE").map(|v| v != "0").unwrap_or(true)); +static DENSE_FALLBACK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static DENSE_PARTIAL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + static MOE_BATCH_ON: LazyLock = LazyLock::new(|| std::env::var("STRATA_MOE_BATCH").map(|v| v != "0").unwrap_or(true)); static MOE_STATS: LazyLock = LazyLock::new(|| std::env::var("STRATA_MOE_STATS").is_ok()); static MOE_CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); @@ -1096,7 +1128,24 @@ impl Backend for Gpu { } 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, w.scale) + let (rows, cols) = (w.rows, w.cols); + let weight_ok = rows.checked_mul(cols).and_then(|v| v.checked_mul(2)).is_some_and(|b| b <= BLAS_W_BYTES); + let act_ok = (act & 3) <= 2 && act & !(3 | SAME_X | crate::backend::MOE_GATE_X) == 0; + let take = *DENSE_ON && !DENSE_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) && !DENSE_PARTIAL.load(std::sync::atomic::Ordering::Relaxed) + && self.blas.is_some() && n >= DENSE_MIN && act_ok && weight_ok + && w.ty.block_elems() >= 32 && cols % 8 == 0 && rows % 4 == 0 && x_stride % 4 == 0 && y_stride % 4 == 0 + && x_stride >= cols && y_stride >= rows; + if take { + match self.gemm_dense_blas(w, n, x, x_stride, y, y_stride, act & 3) { + Ok(()) => return Ok(()), + Err(e) if DENSE_PARTIAL.load(std::sync::atomic::Ordering::Relaxed) => return Err(e), + Err(e) => { + if !DENSE_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) { crate::say!("hipblas dense GEMM ({} {rows} x {cols}, {n} tokens): {e:#}; the dot2 kernel takes over", w.ty.name()); } + DENSE_FALLBACK.store(true, std::sync::atomic::Ordering::Relaxed); + } + } + } + self.gemm_raw(w.ty, rows, 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 } From b7d24936068f49b1362275cdcce7773502d019d9 Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER <61810711+I-AM-ENGINEER@users.noreply.github.com> Date: Sun, 6 Dec 2026 03:45:02 +0300 Subject: [PATCH 13/16] HIP RDNA2: u16 dense tiles (the CUDA build compiles kernels.cu too) --- src/cuda/kernels.cu | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 76d4ecbf..b34f29ae 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -6245,7 +6245,7 @@ extern "C" __global__ void x_gather_hg(const float* x, int x_stride, const int* *(uint2*)(out + i) = z; } -extern "C" __global__ void x_to_h(const float* x, int x_stride, int cols, int n, __half* out) { +extern "C" __global__ void x_to_h(const float* x, int x_stride, int cols, int n, u16* out) { int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x); if (i >= n) return; int c = i % cols, r = i / cols; From 89ad3eecd616c4af969e8c047f9c98c45253803e Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER <61810711+I-AM-ENGINEER@users.noreply.github.com> Date: Sun, 6 Dec 2026 04:43:09 +0300 Subject: [PATCH 14/16] HIP RDNA2: the grouped path asks for the strides the gather and scatter need x_gather_hg reads x a float4 at a time and blas_scatter writes past m0 * y_stride, so a stride that is not a multiple of 4, or one shorter than the row, has to stay on the dot2 kernel - the same gate gemm_dense already has. --- src/hip/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index abd0b516..da7860a8 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -924,7 +924,8 @@ impl Backend for Gpu { let dot2 = |g: &Gpu| g.gemm(ty, rows, cols, tiles_dev, tiles_host.len() / 2, x, x_stride, n_x, xrow, y, y_stride, full_act); let Some(slot_bytes) = rows.checked_mul(cols).and_then(|n| n.checked_mul(2)) else { return dot2(self) }; if tiles_host.len() < 2 || cols % 8 != 0 || act > 2 || ty.float_x() || self.blas.is_none() || self.int8_gemm(ty) - || slot_bytes > BLAS_W_BYTES || rows % 4 != 0 || MOE_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) { + || slot_bytes > BLAS_W_BYTES || rows % 4 != 0 || MOE_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) + || x_stride % 4 != 0 || y_stride % 4 != 0 || x_stride < cols || y_stride < rows { return dot2(self); } MOE_PARTIAL.store(false, std::sync::atomic::Ordering::Relaxed); From 70a132bcdd0bfe29af0c95821d857bd0df37ec1a Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER <61810711+I-AM-ENGINEER@users.noreply.github.com> Date: Sun, 6 Dec 2026 04:49:37 +0300 Subject: [PATCH 15/16] HIP RDNA2: the dense path rejects MOE_GATE_X instead of dropping it --- 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 da7860a8..a38a669b 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -1131,7 +1131,7 @@ impl Backend for Gpu { fn gemm_dense(&self, w: &GpuTensor, n: usize, x: u64, x_stride: usize, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { let (rows, cols) = (w.rows, w.cols); let weight_ok = rows.checked_mul(cols).and_then(|v| v.checked_mul(2)).is_some_and(|b| b <= BLAS_W_BYTES); - let act_ok = (act & 3) <= 2 && act & !(3 | SAME_X | crate::backend::MOE_GATE_X) == 0; + let act_ok = (act & 3) <= 2 && act & !(3 | SAME_X) == 0; let take = *DENSE_ON && !DENSE_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) && !DENSE_PARTIAL.load(std::sync::atomic::Ordering::Relaxed) && self.blas.is_some() && n >= DENSE_MIN && act_ok && weight_ok && w.ty.block_elems() >= 32 && cols % 8 == 0 && rows % 4 == 0 && x_stride % 4 == 0 && y_stride % 4 == 0 From edd130a2e74dd061e236199e5a4949fd98f911d2 Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER <61810711+I-AM-ENGINEER@users.noreply.github.com> Date: Sun, 6 Dec 2026 14:22:32 +0300 Subject: [PATCH 16/16] HIP RDNA2: the dense path leaves int8-typed weights to the int8 GEMM --- 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 a38a669b..d7bcfc31 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -1133,7 +1133,7 @@ impl Backend for Gpu { let weight_ok = rows.checked_mul(cols).and_then(|v| v.checked_mul(2)).is_some_and(|b| b <= BLAS_W_BYTES); let act_ok = (act & 3) <= 2 && act & !(3 | SAME_X) == 0; let take = *DENSE_ON && !DENSE_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) && !DENSE_PARTIAL.load(std::sync::atomic::Ordering::Relaxed) - && self.blas.is_some() && n >= DENSE_MIN && act_ok && weight_ok + && self.blas.is_some() && n >= DENSE_MIN && act_ok && weight_ok && !self.int8_gemm(w.ty) && w.ty.block_elems() >= 32 && cols % 8 == 0 && rows % 4 == 0 && x_stride % 4 == 0 && y_stride % 4 == 0 && x_stride >= cols && y_stride >= rows; if take {