[RT][HIP] GPU executor core + first composed trunk forward verified on gfx1150

- 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).
This commit is contained in:
adm committed 2026-12-01 13:57:07 +01:00
1 parent b99d3a7a6a
commit 87a66aee37
8 files changed
+196 -6

No files matched your search

+143
View File
@@ -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<usize>,
pub writes: Vec<usize>,
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<u16> = (0..vocab * d).map(|i| f32_to_bf16(((i % 29) as f32 - 14.0) * 0.06)).collect();
let tokens: Vec<i32> = vec![5];
let embed_norm: Vec<f32> = (0..d).map(|i| 0.7 + (i % 5) as f32 * 0.1).collect();
let unembed: Vec<u16> = (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<f32> = (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<f32> = (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<u16> = normed.iter().map(|&v| f32_to_bf16(v)).collect();
let want: Vec<f32> = (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}");
}
}
+7 -4
View File
@@ -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;
pub mod prefix;
#[cfg(feature = "hip")]
pub mod executor;