[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).
This commit is contained in:
1 parent
f57060caa7
commit
bd0d4f2a63
7 files changed
+361
No files matched your search
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "vetta-infer-hip"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
description = "HIP FFI/DMA backend for gfx1150 (RDNA 3.5). Kernel build is feature-gated so the default workspace stays host-independent."
|
||||
|
||||
[features]
|
||||
# Enable to compile kernels/hip/*.hip via hipcc and link the HIP runtime.
|
||||
# Default OFF: `cargo test --workspace` needs no GPU/toolchain.
|
||||
hip = []
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Build the HIP microkernels via hipcc when the `hip` feature is enabled.
|
||||
//! Default (no feature): no toolchain invocation — the workspace stays
|
||||
//! host-independent. With `--features hip`: compile kernels/hip/vetta_kernels.hip
|
||||
//! for gfx1150, archive it, and link the HIP runtime.
|
||||
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
fn main() {
|
||||
let manifest = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
|
||||
let kernels = manifest.join("../../kernels/hip");
|
||||
println!("cargo:rerun-if-changed={}", kernels.join("vetta_kernels.hip").display());
|
||||
println!("cargo:rerun-if-changed={}", kernels.join("vetta_kernels.h").display());
|
||||
println!("cargo:rerun-if-env-changed=HIPCC");
|
||||
|
||||
if env::var("CARGO_FEATURE_HIP").is_err() {
|
||||
return; // host-independent default: nothing to build
|
||||
}
|
||||
|
||||
let hipcc = env::var("HIPCC").unwrap_or_else(|_| "/opt/rocm/bin/hipcc".to_string());
|
||||
let out = PathBuf::from(env::var("OUT_DIR").unwrap());
|
||||
let src = kernels.join("vetta_kernels.hip");
|
||||
let obj = out.join("vetta_kernels.o");
|
||||
let lib = out.join("libvetta_kernels.a");
|
||||
|
||||
let arch = env::var("VETTA_OFFLOAD_ARCH").unwrap_or_else(|_| "gfx1150".to_string());
|
||||
let status = Command::new(&hipcc)
|
||||
.arg(format!("--offload-arch={arch}"))
|
||||
.args(["-O3", "-std=c++17", "-fPIC", "-c"])
|
||||
.arg(&src)
|
||||
.arg("-o")
|
||||
.arg(&obj)
|
||||
.status()
|
||||
.unwrap_or_else(|e| panic!("failed to spawn {hipcc}: {e}"));
|
||||
assert!(status.success(), "hipcc compile failed for {}", src.display());
|
||||
|
||||
let status = Command::new("ar")
|
||||
.arg("rcs")
|
||||
.arg(&lib)
|
||||
.arg(&obj)
|
||||
.status()
|
||||
.expect("failed to spawn ar");
|
||||
assert!(status.success(), "ar archive failed");
|
||||
|
||||
println!("cargo:rustc-link-search=native={}", out.display());
|
||||
let rocm = env::var("ROCM_PATH").unwrap_or_else(|_| "/opt/rocm".to_string());
|
||||
println!("cargo:rustc-link-search=native={rocm}/lib");
|
||||
println!("cargo:rustc-link-lib=static=vetta_kernels");
|
||||
println!("cargo:rustc-link-lib=amdhip64");
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//! `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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user