Files
vetta-infer/crates/vetta-infer-hip/src/lib.rs
T
adm bd0d4f2a63 [HIP] GPU backend bring-up: feature-gated hipcc build + first verified kernel on gfx1150
- New crate vetta-infer-hip: HIP FFI/DMA backend (unsafe isolated here per
  AGENTS.md). Kernel build is feature-gated (`hip`, default OFF) so
  `cargo test --workspace` stays host-independent (97/97, no toolchain).
  build.rs invokes hipcc --offload-arch=gfx1150, archives libvetta_kernels.a,
  links amdhip64 from ROCM_PATH/lib.
- kernels/hip/vetta_kernels.hip: device query, minimal device-buffer
  lifecycle (alloc/free/h2d/d2h, RAII DeviceBuf), and the first microkernel
  k_rms_norm_f32 (one block/row, shared-mem reduction). C ABI extended in
  vetta_kernels.h.
- Safe wrappers: query_device, DeviceBuf, rms_norm_f32.

Verified LIVE on Sogliola (cargo test -p vetta-infer-hip --features hip
-- --ignored): device = AMD Radeon 890M Graphics gfx1150 CU=8 UMA=true;
rms_norm parity vs CPU oracle max_rel_err ~1.3e-6 across rows 1/4/3/2 and
d 2304/128/1024 (tolerance 1e-4). First GPU compute verified end-to-end:
hipcc -> static lib -> FFI -> launch -> parity. This opens the GPU execution
half (executor + remaining kernels toward the first served token).
2026-12-01 04:46:14 +01:00

176 lines
6.4 KiB
Rust

//! `vetta-infer-hip`: HIP FFI/DMA backend for gfx1150 (RDNA 3.5).
//!
//! `unsafe` is isolated here (FFI/DMA fence wrappers) per AGENTS.md. The kernel
//! build is feature-gated (`--features hip`): the default workspace compiles
//! without a GPU/toolchain. Every kernel is parity-checked against a CPU oracle
//! (opt-in GPU test) before being wired into the executor.
/// Primary offload target (Sogliola: Radeon 890M, RDNA 3.5).
pub const TARGET_ARCH: &str = "gfx1150";
#[cfg(feature = "hip")]
mod ffi {
use std::os::raw::{c_char, c_float, c_int, c_void};
#[repr(C)]
pub struct DeviceInfoRaw {
pub name: [c_char; 128],
pub gcn_arch: [c_char; 64],
pub multi_processor_count: c_int,
pub wave_size: c_int,
pub total_vram_bytes: u64,
pub is_uma: c_int,
}
unsafe extern "C" {
pub fn vetta_hip_query_device(dev_id: c_int, out: *mut DeviceInfoRaw) -> c_int;
pub fn vetta_buf_alloc(out: *mut *mut c_void, bytes: usize) -> c_int;
pub fn vetta_buf_free(p: *mut c_void) -> c_int;
pub fn vetta_buf_h2d(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int;
pub fn vetta_buf_d2h(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int;
pub fn vetta_rms_norm_f32(
x: *const c_float, w: *const c_float, y: *mut c_float,
rows: c_int, d: c_int, eps: c_float, stream: *mut c_void,
) -> c_int;
}
}
#[cfg(feature = "hip")]
pub use ffi::DeviceInfoRaw;
/// Safe device description.
#[cfg(feature = "hip")]
#[derive(Debug, Clone)]
pub struct DeviceInfo {
pub name: String,
pub gcn_arch: String,
pub cu_count: i32,
pub wave_size: i32,
pub total_vram_bytes: u64,
pub is_uma: bool,
}
#[cfg(feature = "hip")]
fn cstr(buf: &[std::os::raw::c_char]) -> String {
let bytes: Vec<u8> = buf.iter().take_while(|&&c| c != 0).map(|&c| c as u8).collect();
String::from_utf8_lossy(&bytes).into_owned()
}
/// Query device `dev_id`. Returns `None` on any HIP error.
#[cfg(feature = "hip")]
pub fn query_device(dev_id: i32) -> Option<DeviceInfo> {
let mut raw = DeviceInfoRaw {
name: [0; 128], gcn_arch: [0; 64], multi_processor_count: 0,
wave_size: 0, total_vram_bytes: 0, is_uma: 0,
};
let rc = unsafe { ffi::vetta_hip_query_device(dev_id, &mut raw) };
if rc != 0 { return None; }
Some(DeviceInfo {
name: cstr(&raw.name), gcn_arch: cstr(&raw.gcn_arch),
cu_count: raw.multi_processor_count, wave_size: raw.wave_size,
total_vram_bytes: raw.total_vram_bytes, is_uma: raw.is_uma != 0,
})
}
/// Owned device buffer (RAII free).
#[cfg(feature = "hip")]
pub struct DeviceBuf {
pub ptr: *mut std::os::raw::c_void,
pub bytes: usize,
}
#[cfg(feature = "hip")]
impl DeviceBuf {
pub fn alloc(bytes: usize) -> Result<Self, String> {
let mut ptr: *mut std::os::raw::c_void = std::ptr::null_mut();
let rc = unsafe { ffi::vetta_buf_alloc(&mut ptr, bytes) };
if rc != 0 || ptr.is_null() { return Err(format!("hipMalloc({bytes}) failed")); }
Ok(Self { ptr, bytes })
}
pub fn h2d(&self, src: &[f32]) -> Result<(), String> {
let bytes = src.len() * 4;
if bytes > self.bytes { return Err("h2d overflow".into()); }
let rc = unsafe { ffi::vetta_buf_h2d(self.ptr, src.as_ptr() as *const _, bytes) };
if rc != 0 { return Err("h2d failed".into()); }
Ok(())
}
pub fn d2h(&self, dst: &mut [f32]) -> Result<(), String> {
let bytes = dst.len() * 4;
if bytes > self.bytes { return Err("d2h overflow".into()); }
let rc = unsafe { ffi::vetta_buf_d2h(dst.as_mut_ptr() as *mut _, self.ptr, bytes) };
if rc != 0 { return Err("d2h failed".into()); }
Ok(())
}
}
#[cfg(feature = "hip")]
impl Drop for DeviceBuf {
fn drop(&mut self) {
unsafe { ffi::vetta_buf_free(self.ptr); }
}
}
/// Launch k_rms_norm over `rows` rows of width `d` (device pointers).
#[cfg(feature = "hip")]
pub fn rms_norm_f32(x: &DeviceBuf, w: Option<&DeviceBuf>, y: &DeviceBuf, rows: i32, d: i32, eps: f32) -> Result<(), String> {
let wp = w.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
let rc = unsafe {
ffi::vetta_rms_norm_f32(x.ptr as *const f32, wp, y.ptr as *mut f32, rows, d, eps, std::ptr::null_mut())
};
if rc != 0 { return Err("rms_norm launch failed".into()); }
Ok(())
}
#[cfg(all(test, feature = "hip"))]
mod gpu_tests {
use super::*;
fn cpu_rms_norm(x: &[f32], w: Option<&[f32]>, rows: usize, d: usize, eps: f32) -> Vec<f32> {
let mut y = vec![0f32; rows * d];
for r in 0..rows {
let xr = &x[r * d..(r + 1) * d];
let ss: f32 = xr.iter().map(|v| v * v).sum();
let inv = 1.0f32 / (ss / d as f32 + eps).sqrt();
for i in 0..d {
y[r * d + i] = xr[i] * inv * w.map(|w| w[i]).unwrap_or(1.0);
}
}
y
}
#[test]
#[ignore] // requires GPU + --features hip
fn device_is_gfx1150() {
let d = query_device(0).expect("device query");
eprintln!("device: {} ({}) CU={} UMA={}", d.name, d.gcn_arch, d.cu_count, d.is_uma);
assert!(d.gcn_arch.contains("gfx1150"), "expected gfx1150, got {}", d.gcn_arch);
}
#[test]
#[ignore]
fn rms_norm_parity_vs_cpu() {
for &(rows, d) in &[(1usize, 2304usize), (4, 2304), (3, 128), (2, 1024)] {
let x: Vec<f32> = (0..rows * d).map(|i| ((i % 37) as f32 - 18.0) * 0.1).collect();
let w: Vec<f32> = (0..d).map(|i| 0.5 + (i % 13) as f32 * 0.05).collect();
let eps = 1e-6f32;
let want = cpu_rms_norm(&x, Some(&w), rows, d, eps);
let dx = DeviceBuf::alloc(x.len() * 4).unwrap();
let dw = DeviceBuf::alloc(w.len() * 4).unwrap();
let dy = DeviceBuf::alloc(want.len() * 4).unwrap();
dx.h2d(&x).unwrap();
dw.h2d(&w).unwrap();
rms_norm_f32(&dx, Some(&dw), &dy, rows as i32, d as i32, eps).unwrap();
let mut got = vec![0f32; want.len()];
dy.d2h(&mut got).unwrap();
let mut max_rel = 0f32;
for (g, wnt) in got.iter().zip(want.iter()) {
let denom = wnt.abs().max(1e-3);
max_rel = max_rel.max((g - wnt).abs() / denom);
}
eprintln!("rms_norm rows={rows} d={d} max_rel_err={max_rel:.3e}");
assert!(max_rel < 1e-4, "rms_norm parity failed: {max_rel}");
}
}
}