[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:
1 parent
b99d3a7a6a
commit
87a66aee37
8 files changed
+196
-6
No files matched your search
Generated
+1
@@ -56,6 +56,7 @@ name = "vetta-infer-rt"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"vetta-infer-abi",
|
"vetta-infer-abi",
|
||||||
|
"vetta-infer-hip",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ pub enum VplanOp {
|
|||||||
RelPosBias,
|
RelPosBias,
|
||||||
MoeRouterTopk,
|
MoeRouterTopk,
|
||||||
VecAdd,
|
VecAdd,
|
||||||
|
CastF32Bf16,
|
||||||
VitFlashAttnWmma,
|
VitFlashAttnWmma,
|
||||||
GpuPenaltiesTopk,
|
GpuPenaltiesTopk,
|
||||||
// Encoder lane (M1.5 embedder, docs/ARCHITECTURE.md §4)
|
// Encoder lane (M1.5 embedder, docs/ARCHITECTURE.md §4)
|
||||||
@@ -81,6 +82,7 @@ impl VplanOp {
|
|||||||
Self::RelPosBias => "relpos_bias",
|
Self::RelPosBias => "relpos_bias",
|
||||||
Self::MoeRouterTopk => "moe_router_topk",
|
Self::MoeRouterTopk => "moe_router_topk",
|
||||||
Self::VecAdd => "vec_add",
|
Self::VecAdd => "vec_add",
|
||||||
|
Self::CastF32Bf16 => "cast_f32_bf16",
|
||||||
Self::VitFlashAttnWmma => "vit_flash_attn_wmma",
|
Self::VitFlashAttnWmma => "vit_flash_attn_wmma",
|
||||||
Self::GpuPenaltiesTopk => "gpu_penalties_topk",
|
Self::GpuPenaltiesTopk => "gpu_penalties_topk",
|
||||||
Self::LayerNorm => "layer_norm",
|
Self::LayerNorm => "layer_norm",
|
||||||
@@ -118,6 +120,7 @@ impl VplanOp {
|
|||||||
"relpos_bias" => Self::RelPosBias,
|
"relpos_bias" => Self::RelPosBias,
|
||||||
"moe_router_topk" => Self::MoeRouterTopk,
|
"moe_router_topk" => Self::MoeRouterTopk,
|
||||||
"vec_add" => Self::VecAdd,
|
"vec_add" => Self::VecAdd,
|
||||||
|
"cast_f32_bf16" => Self::CastF32Bf16,
|
||||||
"vit_flash_attn_wmma" => Self::VitFlashAttnWmma,
|
"vit_flash_attn_wmma" => Self::VitFlashAttnWmma,
|
||||||
"gpu_penalties_topk" => Self::GpuPenaltiesTopk,
|
"gpu_penalties_topk" => Self::GpuPenaltiesTopk,
|
||||||
"layer_norm" => Self::LayerNorm,
|
"layer_norm" => Self::LayerNorm,
|
||||||
@@ -152,7 +155,7 @@ mod tests {
|
|||||||
VplanOp::GdnRecurrentStep, VplanOp::MoeRouteBucket, VplanOp::MoeW13Wmma,
|
VplanOp::GdnRecurrentStep, VplanOp::MoeRouteBucket, VplanOp::MoeW13Wmma,
|
||||||
VplanOp::MoeW2Wmma, VplanOp::MoeReduce, VplanOp::VitFlashAttnWmma,
|
VplanOp::MoeW2Wmma, VplanOp::MoeReduce, VplanOp::VitFlashAttnWmma,
|
||||||
VplanOp::AttnResMix, VplanOp::ShortConv4, VplanOp::LoopCtrl, VplanOp::L2Clip,
|
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::GpuPenaltiesTopk, VplanOp::LayerNorm, VplanOp::FlashFullAttn,
|
||||||
VplanOp::GeluErf, VplanOp::PoolL2norm, VplanOp::LoopLayer, VplanOp::BranchB,
|
VplanOp::GeluErf, VplanOp::PoolL2norm, VplanOp::LoopLayer, VplanOp::BranchB,
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -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,
|
m: c_int, n_experts: c_int, k_top: c_int, route_scale: c_float, stream: *mut c_void,
|
||||||
) -> c_int;
|
) -> 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_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(())
|
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"))]
|
#[cfg(all(test, feature = "hip"))]
|
||||||
mod gpu_tests {
|
mod gpu_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|||||||
@@ -5,4 +5,9 @@ edition.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
vetta-infer-abi = { path = "../vetta-infer-abi" }
|
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"]
|
||||||
@@ -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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
//! `vetta-infer-rt`: operational runtime (docs/ARCHITECTURE.md §2, §5).
|
//! `vetta-infer-rt`: operational runtime (docs/ARCHITECTURE.md §2, §5).
|
||||||
//!
|
//!
|
||||||
//! Executes the boot-lowered `CompiledPlan` on the HIP backend at full speed,
|
//! 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
|
//! zero probes on the hot path. `lab` shares this executor core. Hosts the
|
||||||
//! hosts the hybrid prefix/checkpoint state; the HIP FFI and plan executor
|
//! hybrid prefix/checkpoint state and (feature `hip`) the GPU executor that
|
||||||
//! land with M1.
|
//! dispatches the arena-validated plan onto the verified microkernels.
|
||||||
|
|
||||||
pub mod prefix;
|
pub mod prefix;
|
||||||
|
|
||||||
|
#[cfg(feature = "hip")]
|
||||||
|
pub mod executor;
|
||||||
@@ -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,
|
int vetta_vec_add(const float* a, const float* b, float* y, size_t n,
|
||||||
vetta_stream_t stream);
|
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):
|
// Core <15 microkernel entry points (implemented progressively in M1 & M2):
|
||||||
// 1. k_embed_bf16
|
// 1. k_embed_bf16
|
||||||
// 2. k_rms_norm
|
// 2. k_rms_norm
|
||||||
|
|||||||
@@ -321,4 +321,26 @@ extern "C" int vetta_vec_add(const float* a, const float* b, float* y, size_t n,
|
|||||||
k_vec_add<<<grid, nt, 0, s>>>(a, b, y, n);
|
k_vec_add<<<grid, nt, 0, s>>>(a, b, y, n);
|
||||||
HIP_CHECK(hipGetLastError());
|
HIP_CHECK(hipGetLastError());
|
||||||
return 0;
|
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<<<grid, nt, 0, s>>>(x, y, n);
|
||||||
|
HIP_CHECK(hipGetLastError());
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user