From c3e32ad08f6ae04f0e654b00265d682de1bb9c2d Mon Sep 17 00:00:00 2001 From: I-AM-ENGINEER Date: Sat, 5 Dec 2026 23:21:26 +0300 Subject: [PATCH 1/4] 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 2/4] 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 3/4] 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 4/4] 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 {