From 87a66aee37b5709ba4651d6ba1c0943ea311ed08 Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Tue, 1 Dec 2026 13:57:07 +0100 Subject: [PATCH] [RT][HIP] GPU executor core + first composed trunk forward verified on gfx1150 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - rt::executor (feature `hip`): the bridge from the arena-validated plan to GPU compute. ExecOp { op, reads, writes, params } + OpParams (concrete shapes) + execute() dispatching the verified microkernels (embed, rms_norm, gemm_bf16, flash_gqa, moe_router, vec_add, cast). Lowering CompiledPlans+IR -> ExecOp lands with the packer; this core proves dispatch + composition. - First COMPOSED GPU forward: embed gather -> rms_norm -> cast f32->bf16 -> gemm(unembed), verified end-to-end vs a CPU oracle (<1e-4). The composition test caught a real dtype-transition bug (f32 activation fed to a BF16 GEMM) — fixed by adding the cast kernel the reference also inserts before matmul. - kernels/hip: k_cast_f32_bf16 (f32 activation -> BF16 truncate) + C ABI + wrapper. abi::vplan: CastF32Bf16 opcode (31 total). - rt: optional hip dependency, feature-gated (default workspace stays host-independent). Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS; lean proofs (4 files, 42 theorems) green; GPU parity 7/7 + composed trunk forward 1/1 (--features hip). Principle recorded: parity-first baseline, then our own measured improvements (Federico). --- Cargo.lock | 1 + crates/vetta-infer-abi/src/vplan.rs | 5 +- crates/vetta-infer-hip/src/lib.rs | 9 ++ crates/vetta-infer-rt/Cargo.toml | 7 +- crates/vetta-infer-rt/src/executor.rs | 143 ++++++++++++++++++++++++++ crates/vetta-infer-rt/src/lib.rs | 11 +- kernels/hip/vetta_kernels.h | 4 + kernels/hip/vetta_kernels.hip | 22 ++++ 8 files changed, 196 insertions(+), 6 deletions(-) create mode 100644 crates/vetta-infer-rt/src/executor.rs diff --git a/Cargo.lock b/Cargo.lock index 7a5c6f4..fe2ca24 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -56,6 +56,7 @@ name = "vetta-infer-rt" version = "0.1.0" dependencies = [ "vetta-infer-abi", + "vetta-infer-hip", ] [[package]] diff --git a/crates/vetta-infer-abi/src/vplan.rs b/crates/vetta-infer-abi/src/vplan.rs index 323b0bc..0f098af 100644 --- a/crates/vetta-infer-abi/src/vplan.rs +++ b/crates/vetta-infer-abi/src/vplan.rs @@ -33,6 +33,7 @@ pub enum VplanOp { RelPosBias, MoeRouterTopk, VecAdd, + CastF32Bf16, VitFlashAttnWmma, GpuPenaltiesTopk, // Encoder lane (M1.5 embedder, docs/ARCHITECTURE.md §4) @@ -81,6 +82,7 @@ impl VplanOp { Self::RelPosBias => "relpos_bias", Self::MoeRouterTopk => "moe_router_topk", Self::VecAdd => "vec_add", + Self::CastF32Bf16 => "cast_f32_bf16", Self::VitFlashAttnWmma => "vit_flash_attn_wmma", Self::GpuPenaltiesTopk => "gpu_penalties_topk", Self::LayerNorm => "layer_norm", @@ -118,6 +120,7 @@ impl VplanOp { "relpos_bias" => Self::RelPosBias, "moe_router_topk" => Self::MoeRouterTopk, "vec_add" => Self::VecAdd, + "cast_f32_bf16" => Self::CastF32Bf16, "vit_flash_attn_wmma" => Self::VitFlashAttnWmma, "gpu_penalties_topk" => Self::GpuPenaltiesTopk, "layer_norm" => Self::LayerNorm, @@ -152,7 +155,7 @@ mod tests { VplanOp::GdnRecurrentStep, VplanOp::MoeRouteBucket, VplanOp::MoeW13Wmma, VplanOp::MoeW2Wmma, VplanOp::MoeReduce, VplanOp::VitFlashAttnWmma, VplanOp::AttnResMix, VplanOp::ShortConv4, VplanOp::LoopCtrl, VplanOp::L2Clip, - VplanOp::KvStore, VplanOp::RelPosBias, VplanOp::MoeRouterTopk, VplanOp::VecAdd, + VplanOp::KvStore, VplanOp::RelPosBias, VplanOp::MoeRouterTopk, VplanOp::VecAdd, VplanOp::CastF32Bf16, VplanOp::GpuPenaltiesTopk, VplanOp::LayerNorm, VplanOp::FlashFullAttn, VplanOp::GeluErf, VplanOp::PoolL2norm, VplanOp::LoopLayer, VplanOp::BranchB, ]; diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 920cee1..5ad7bbf 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -49,6 +49,7 @@ mod ffi { m: c_int, n_experts: c_int, k_top: c_int, route_scale: c_float, stream: *mut c_void, ) -> c_int; pub fn vetta_vec_add(a: *const c_float, b: *const c_float, y: *mut c_float, n: usize, stream: *mut c_void) -> c_int; + pub fn vetta_cast_f32_bf16(x: *const c_float, y: *mut u16, n: usize, stream: *mut c_void) -> c_int; } } @@ -199,6 +200,14 @@ pub fn vec_add(a: &DeviceBuf, b: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result< Ok(()) } +/// Launch k_cast_f32_bf16: f32 activation -> BF16 (truncate). +#[cfg(feature = "hip")] +pub fn cast_f32_bf16(x: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result<(), String> { + let rc = unsafe { ffi::vetta_cast_f32_bf16(x.ptr as *const f32, y.ptr as *mut u16, n, std::ptr::null_mut()) }; + if rc != 0 { return Err("cast launch failed".into()); } + Ok(()) +} + #[cfg(all(test, feature = "hip"))] mod gpu_tests { use super::*; diff --git a/crates/vetta-infer-rt/Cargo.toml b/crates/vetta-infer-rt/Cargo.toml index ec8f58f..4f1a137 100644 --- a/crates/vetta-infer-rt/Cargo.toml +++ b/crates/vetta-infer-rt/Cargo.toml @@ -5,4 +5,9 @@ edition.workspace = true license.workspace = true [dependencies] -vetta-infer-abi = { path = "../vetta-infer-abi" } \ No newline at end of file +vetta-infer-abi = { path = "../vetta-infer-abi" } +vetta-infer-hip = { path = "../vetta-infer-hip", optional = true } + +[features] +# Enable the GPU executor (links the HIP backend + kernels). +hip = ["dep:vetta-infer-hip", "vetta-infer-hip/hip"] \ No newline at end of file diff --git a/crates/vetta-infer-rt/src/executor.rs b/crates/vetta-infer-rt/src/executor.rs new file mode 100644 index 0000000..54bda3e --- /dev/null +++ b/crates/vetta-infer-rt/src/executor.rs @@ -0,0 +1,143 @@ +//! GPU executor core (feature `hip`): dispatch a typed op sequence onto the +//! verified HIP microkernels. This is the bridge from the arena-validated +//! `CompiledPlan` to real GPU compute. +//! +//! Parity-first: every dispatched kernel is already parity-verified against a +//! CPU oracle. The lowering from `CompiledPlans` + IR into `ExecOp` (attaching +//! concrete shapes) lands with the packer; this core proves the dispatch + +//! kernel composition on real hardware. + +use vetta_infer_abi::vplan::VplanOp; +use vetta_infer_hip::DeviceBuf; + +/// Concrete shape parameters for one op (attached at lowering time). +#[derive(Debug, Clone)] +pub enum OpParams { + /// reads [table, tokens], writes [out] + Embed { b: i32, d: i32, vocab: i32 }, + /// reads [x, w], writes [y] + RmsNorm { rows: i32, d: i32, eps: f32 }, + /// reads [x, w], writes [y] (y[m,n] = x[m,k] @ w[n,k]^T) + Gemm { m: i32, n: i32, k: i32 }, + /// reads [q, k, v], writes [out] + FlashGqa { n_head: i32, n_kv: i32, seq: i32, hd: i32, scale: f32 }, + /// reads [logits] or [logits, bias], writes [ids, weights] + Router { m: i32, n_experts: i32, k_top: i32, route_scale: f32 }, + /// reads [a, b], writes [y] + VecAdd { n: usize }, + /// reads [x f32], writes [y bf16] + Cast { n: usize }, +} + +#[derive(Debug, Clone)] +pub struct ExecOp { + pub op: VplanOp, + pub reads: Vec, + pub writes: Vec, + pub params: OpParams, +} + +/// Execute `ops` over a buffer table indexed by arena decl index. +pub fn execute(buffers: &[DeviceBuf], ops: &[ExecOp]) -> Result<(), String> { + for (i, o) in ops.iter().enumerate() { + let r = |k: usize| -> Result<&DeviceBuf, String> { + o.reads.get(k).and_then(|&idx| buffers.get(idx)).ok_or_else(|| format!("op {i}: bad read operand")) + }; + let w = |k: usize| -> Result<&DeviceBuf, String> { + o.writes.get(k).and_then(|&idx| buffers.get(idx)).ok_or_else(|| format!("op {i}: bad write operand")) + }; + let res = match (&o.op, &o.params) { + (VplanOp::EmbedBf16, OpParams::Embed { b, d, vocab }) => { + vetta_infer_hip::embed_bf16_gather(r(0)?, r(1)?, w(0)?, *b, *d, *vocab) + } + (VplanOp::RmsNorm, OpParams::RmsNorm { rows, d, eps }) => { + vetta_infer_hip::rms_norm_f32(r(0)?, Some(r(1)?), w(0)?, *rows, *d, *eps) + } + (VplanOp::GemmBf16, OpParams::Gemm { m, n, k }) => { + vetta_infer_hip::gemm_bf16(r(0)?, r(1)?, w(0)?, *m, *n, *k) + } + (VplanOp::FlashGqaWmma, OpParams::FlashGqa { n_head, n_kv, seq, hd, scale }) => { + vetta_infer_hip::flash_gqa_decode(r(0)?, r(1)?, r(2)?, w(0)?, *n_head, *n_kv, *seq, *hd, *scale) + } + (VplanOp::MoeRouterTopk, OpParams::Router { m, n_experts, k_top, route_scale }) => { + let bias = if o.reads.len() > 1 { Some(r(1)?) } else { None }; + vetta_infer_hip::moe_router_topk(r(0)?, bias, w(0)?, w(1)?, *m, *n_experts, *k_top, *route_scale) + } + (VplanOp::VecAdd, OpParams::VecAdd { n }) => { + vetta_infer_hip::vec_add(r(0)?, r(1)?, w(0)?, *n) + } + (VplanOp::CastF32Bf16, OpParams::Cast { n }) => { + vetta_infer_hip::cast_f32_bf16(r(0)?, w(0)?, *n) + } + _ => Err(format!("op {i}: opcode {:?} not yet dispatched (params {:?})", o.op, o.params)), + }; + res.map_err(|e| format!("op {i} ({:?}): {e}", o.op))?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn f32_to_bf16(v: f32) -> u16 { (v.to_bits() >> 16) as u16 } + fn bf16_to_f32(h: u16) -> f32 { f32::from_bits((h as u32) << 16) } + fn bytes_u16(v: &[u16]) -> &[u8] { unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2) } } + fn bytes_i32(v: &[i32]) -> &[u8] { unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 4) } } + + /// Composed trunk forward on GPU: embed gather -> rms_norm -> gemm(unembed), + /// verified end-to-end against a CPU oracle. Proves kernel composition + + /// buffer dataflow (the executor's core operation) on real hardware. + #[test] + #[ignore] // requires GPU + --features hip + fn trunk_forward_composed_parity() { + let (vocab, d, b) = (16usize, 8usize, 1usize); + let eps = 1e-6f32; + let table: Vec = (0..vocab * d).map(|i| f32_to_bf16(((i % 29) as f32 - 14.0) * 0.06)).collect(); + let tokens: Vec = vec![5]; + let embed_norm: Vec = (0..d).map(|i| 0.7 + (i % 5) as f32 * 0.1).collect(); + let unembed: Vec = (0..vocab * d).map(|i| f32_to_bf16(((i % 37) as f32 - 18.0) * 0.04)).collect(); + + // CPU oracle. + let tok = tokens[0] as usize; + let emb: Vec = (0..d).map(|i| bf16_to_f32(table[tok * d + i])).collect(); + let ss: f32 = emb.iter().map(|v| v * v).sum(); + let inv = 1.0f32 / (ss / d as f32 + eps).sqrt(); + let normed: Vec = (0..d).map(|i| emb[i] * inv * embed_norm[i]).collect(); + // Activations are cast f32->bf16 before the BF16 GEMM (reference behavior). + let normed_bf: Vec = normed.iter().map(|&v| f32_to_bf16(v)).collect(); + let want: Vec = (0..vocab).map(|n| { + (0..d).map(|k| bf16_to_f32(normed_bf[k]) * bf16_to_f32(unembed[n * d + k])).sum() + }).collect(); + + // Buffers: 0 table, 1 tokens, 2 embed_norm, 3 unembed, 4 residual, + // 5 norm_out(f32), 6 logits, 7 norm_bf16. + let table_b = DeviceBuf::alloc(table.len() * 2).unwrap(); + let tok_b = DeviceBuf::alloc(tokens.len() * 4).unwrap(); + let en_b = DeviceBuf::alloc(d * 4).unwrap(); + let ue_b = DeviceBuf::alloc(unembed.len() * 2).unwrap(); + let res_b = DeviceBuf::alloc(b * d * 4).unwrap(); + let norm_b = DeviceBuf::alloc(b * d * 4).unwrap(); + let log_b = DeviceBuf::alloc(b * vocab * 4).unwrap(); + let normbf_b = DeviceBuf::alloc(b * d * 2).unwrap(); + table_b.h2d_bytes(bytes_u16(&table)).unwrap(); + tok_b.h2d_bytes(bytes_i32(&tokens)).unwrap(); + en_b.h2d(&embed_norm).unwrap(); + ue_b.h2d_bytes(bytes_u16(&unembed)).unwrap(); + let buffers = vec![table_b, tok_b, en_b, ue_b, res_b, norm_b, log_b, normbf_b]; + + let ops = vec![ + ExecOp { op: VplanOp::EmbedBf16, reads: vec![0, 1], writes: vec![4], params: OpParams::Embed { b: b as i32, d: d as i32, vocab: vocab as i32 } }, + ExecOp { op: VplanOp::RmsNorm, reads: vec![4, 2], writes: vec![5], params: OpParams::RmsNorm { rows: b as i32, d: d as i32, eps } }, + ExecOp { op: VplanOp::CastF32Bf16, reads: vec![5], writes: vec![7], params: OpParams::Cast { n: b * d } }, + ExecOp { op: VplanOp::GemmBf16, reads: vec![7, 3], writes: vec![6], params: OpParams::Gemm { m: b as i32, n: vocab as i32, k: d as i32 } }, + ]; + execute(&buffers, &ops).unwrap(); + let mut got = vec![0f32; want.len()]; + buffers[6].d2h(&mut got).unwrap(); + let mut max_rel = 0f32; + for (g, wnt) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - wnt).abs() / wnt.abs().max(1e-3)); } + eprintln!("composed trunk forward max_rel_err={max_rel:.3e}"); + assert!(max_rel < 1e-4, "composed trunk parity failed: {max_rel}"); + } +} \ No newline at end of file diff --git a/crates/vetta-infer-rt/src/lib.rs b/crates/vetta-infer-rt/src/lib.rs index 0b5246a..eeea582 100644 --- a/crates/vetta-infer-rt/src/lib.rs +++ b/crates/vetta-infer-rt/src/lib.rs @@ -1,8 +1,11 @@ //! `vetta-infer-rt`: operational runtime (docs/ARCHITECTURE.md §2, §5). //! //! Executes the boot-lowered `CompiledPlan` on the HIP backend at full speed, -//! zero probes on the hot path. `lab` shares this executor core. Today it -//! hosts the hybrid prefix/checkpoint state; the HIP FFI and plan executor -//! land with M1. +//! zero probes on the hot path. `lab` shares this executor core. Hosts the +//! hybrid prefix/checkpoint state and (feature `hip`) the GPU executor that +//! dispatches the arena-validated plan onto the verified microkernels. -pub mod prefix; \ No newline at end of file +pub mod prefix; + +#[cfg(feature = "hip")] +pub mod executor; \ No newline at end of file diff --git a/kernels/hip/vetta_kernels.h b/kernels/hip/vetta_kernels.h index 6a3da0b..f828b19 100644 --- a/kernels/hip/vetta_kernels.h +++ b/kernels/hip/vetta_kernels.h @@ -60,6 +60,10 @@ int vetta_moe_router_topk(const float* logits, const float* bias, int vetta_vec_add(const float* a, const float* b, float* y, size_t n, vetta_stream_t stream); +// k_cast_f32_bf16: f32 activation -> BF16 (truncate) before a BF16 GEMM. +int vetta_cast_f32_bf16(const float* x, uint16_t* y, size_t n, + vetta_stream_t stream); + // Core <15 microkernel entry points (implemented progressively in M1 & M2): // 1. k_embed_bf16 // 2. k_rms_norm diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index 6de542a..21e1785 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -321,4 +321,26 @@ extern "C" int vetta_vec_add(const float* a, const float* b, float* y, size_t n, k_vec_add<<>>(a, b, y, n); HIP_CHECK(hipGetLastError()); return 0; +} + +// ---- k_cast_f32_bf16: f32 activation -> BF16 (truncate) before GEMM -------- +// The residual stream is f32; trunk/expert GEMMs read BF16 activations (the +// reference inserts k_f32_to_bf16/f16 before the matmul). Truncation matches +// the bf16 weight storage; RNE rounding is a later precision refinement. + +__global__ void k_cast_f32_bf16(const float* __restrict__ x, uint16_t* __restrict__ y, + size_t n) { + size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) y[i] = (uint16_t)(__float_as_uint(x[i]) >> 16); +} + +extern "C" int vetta_cast_f32_bf16(const float* x, uint16_t* y, size_t n, + vetta_stream_t stream) { + if (n == 0) return 0; + const int nt = 256; + const size_t grid = (n + nt - 1) / nt; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_cast_f32_bf16<<>>(x, y, n); + HIP_CHECK(hipGetLastError()); + return 0; } \ No newline at end of file