[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
Generated
+4
@@ -22,6 +22,10 @@ dependencies = [
|
||||
"vetta-infer-ld",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vetta-infer-hip"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "vetta-infer-kn"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
resolver = "3"
|
||||
members = [
|
||||
"crates/vetta-infer-abi",
|
||||
"crates/vetta-infer-hip",
|
||||
"crates/vetta-infer-kn",
|
||||
"crates/vetta-infer-ld",
|
||||
"crates/vetta-infer-cc",
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,16 @@ int vetta_hip_query_device(int dev_id, vetta_device_info_t* out_info);
|
||||
int vetta_hip_register_uma_pages(void* host_aligned_ptr, size_t bytes, void** out_dev_ptr);
|
||||
int vetta_hip_unregister_uma_pages(void* host_aligned_ptr);
|
||||
|
||||
// Minimal device buffer lifecycle (executor foundation).
|
||||
int vetta_buf_alloc(void** out, size_t bytes);
|
||||
int vetta_buf_free(void* p);
|
||||
int vetta_buf_h2d(void* dst, const void* src, size_t bytes);
|
||||
int vetta_buf_d2h(void* dst, const void* src, size_t bytes);
|
||||
|
||||
// k_rms_norm (kernel #2): y[row] = x[row] * rsqrt(mean(x^2)+eps) * w.
|
||||
int vetta_rms_norm_f32(const float* x, const float* w, float* y,
|
||||
int rows, int D, float eps, vetta_stream_t stream);
|
||||
|
||||
// Core <15 microkernel entry points (implemented progressively in M1 & M2):
|
||||
// 1. k_embed_bf16
|
||||
// 2. k_rms_norm
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// kernels/hip/vetta_kernels.hip
|
||||
// First RDNA 3.5 (gfx1150) HIP microkernels + minimal runtime helpers.
|
||||
// Built by vetta-infer-hip/build.rs via hipcc --offload-arch=gfx1150.
|
||||
// Parity discipline: every kernel is checked against a CPU oracle (opt-in
|
||||
// GPU test) before it is wired into the executor.
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include "vetta_kernels.h"
|
||||
|
||||
#define HIP_CHECK(call) \
|
||||
do { \
|
||||
hipError_t _e = (call); \
|
||||
if (_e != hipSuccess) { \
|
||||
std::fprintf(stderr, "[vetta-hip] %s:%d %s -> %s\n", __FILE__, \
|
||||
__LINE__, #call, hipGetErrorString(_e)); \
|
||||
return 1; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
// ---- device query ----------------------------------------------------------
|
||||
|
||||
extern "C" int vetta_hip_query_device(int dev_id, vetta_device_info_t* out) {
|
||||
if (!out) return 1;
|
||||
int n = 0;
|
||||
HIP_CHECK(hipGetDeviceCount(&n));
|
||||
if (dev_id < 0 || dev_id >= n) return 1;
|
||||
hipDeviceProp_t p;
|
||||
HIP_CHECK(hipGetDeviceProperties(&p, dev_id));
|
||||
std::memset(out, 0, sizeof(*out));
|
||||
std::snprintf(out->name, sizeof(out->name), "%s", p.name);
|
||||
std::snprintf(out->gcn_arch, sizeof(out->gcn_arch), "%s", p.gcnArchName);
|
||||
out->multi_processor_count = p.multiProcessorCount;
|
||||
out->wave_size = p.warpSize;
|
||||
out->total_vram_bytes = (uint64_t)p.totalGlobalMem;
|
||||
int uma = 0;
|
||||
hipDeviceGetAttribute(&uma, hipDeviceAttributeIntegrated, dev_id);
|
||||
out->is_uma = uma;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---- minimal device buffer lifecycle (UMA-aware) ---------------------------
|
||||
|
||||
extern "C" int vetta_buf_alloc(void** out, size_t bytes) {
|
||||
if (!out) return 1;
|
||||
HIP_CHECK(hipMalloc(out, bytes));
|
||||
return 0;
|
||||
}
|
||||
extern "C" int vetta_buf_free(void* p) {
|
||||
if (!p) return 0;
|
||||
HIP_CHECK(hipFree(p));
|
||||
return 0;
|
||||
}
|
||||
extern "C" int vetta_buf_h2d(void* dst, const void* src, size_t bytes) {
|
||||
HIP_CHECK(hipMemcpy(dst, src, bytes, hipMemcpyHostToDevice));
|
||||
return 0;
|
||||
}
|
||||
extern "C" int vetta_buf_d2h(void* dst, const void* src, size_t bytes) {
|
||||
HIP_CHECK(hipMemcpy(dst, src, bytes, hipMemcpyDeviceToHost));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---- k_rms_norm (kernel #2): y = x * rsqrt(mean(x^2)+eps) * w --------------
|
||||
// One block per row; block-wide reduction over D. f32 in/out.
|
||||
|
||||
__global__ void k_rms_norm_f32(const float* __restrict__ x,
|
||||
const float* __restrict__ w,
|
||||
float* __restrict__ y, int D, float eps) {
|
||||
const int row = blockIdx.x;
|
||||
const float* xr = x + (size_t)row * D;
|
||||
float* yr = y + (size_t)row * D;
|
||||
const int tid = threadIdx.x;
|
||||
const int nthreads = blockDim.x;
|
||||
|
||||
float ss = 0.f;
|
||||
for (int i = tid; i < D; i += nthreads) {
|
||||
float v = xr[i];
|
||||
ss += v * v;
|
||||
}
|
||||
// block reduction via shared memory
|
||||
__shared__ float red[256];
|
||||
red[tid] = ss;
|
||||
__syncthreads();
|
||||
for (int s = nthreads / 2; s > 0; s >>= 1) {
|
||||
if (tid < s) red[tid] += red[tid + s];
|
||||
__syncthreads();
|
||||
}
|
||||
const float inv = rsqrtf(red[0] / (float)D + eps);
|
||||
for (int i = tid; i < D; i += nthreads) {
|
||||
yr[i] = xr[i] * inv * (w ? w[i] : 1.f);
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" int vetta_rms_norm_f32(const float* x, const float* w, float* y,
|
||||
int rows, int D, float eps,
|
||||
vetta_stream_t stream) {
|
||||
if (rows <= 0 || D <= 0) return 1;
|
||||
int threads = D < 256 ? ((D + 31) / 32) * 32 : 256;
|
||||
if (threads < 32) threads = 32;
|
||||
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
|
||||
k_rms_norm_f32<<<rows, threads, 0, s>>>(x, w, y, D, eps);
|
||||
HIP_CHECK(hipGetLastError());
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user