From e4dcc5e0157bb10b71a047331123ac533f2207f3 Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Tue, 1 Dec 2026 16:53:18 +0100 Subject: [PATCH] [HIP] FP16 expert-path kernels (strata B=1 parity), opt-in; refactor run_experts Add the exact strata B=1 FP16 expert path as verified kernels: k_cast_f32_f16 (RNE), k_nvfp4_gemv_f16 / k_mxfp8_gemv_f16 (FP16 activations, group partial dot then scale-fma, fdot2 order), k_situ_f16 (SiTU f32 -> stored FP16). Rust wrappers + expert_gemv_f16 dispatch. Refactor the duplicated SWA/full expert loops into ld::layer::run_experts. Default stays all-f32 (verified parity baseline); VETTA_F16_EXPERT=1 selects the FP16 path. MEASURED A/B (tok100): f32 argmax 220 (23.074) / 68014 22.643; fp16 argmax 220 (23.069) / 68014 22.632. FP16 shifts logits ~0.01 but does NOT flip the near-tie: the residual gap vs reference is the core-loop pass 1/2, NOT expert precision. FP16 kept opt-in for once the loop is fixed. New real_expert_nvfp4_gemv_f16_parity (GPU fp16 vs CPU oracle over same fp16-rounded x) green. Verified: workspace -D warnings, 18 ld GPU + 17 hip GPU green. --- crates/vetta-infer-hip/src/lib.rs | 45 ++++++++- crates/vetta-infer-ld/src/layer.rs | 78 ++++++++++------ crates/vetta-infer-ld/src/packer.rs | 67 ++++++++++++++ kernels/hip/vetta_kernels.h | 20 +++- kernels/hip/vetta_kernels.hip | 137 ++++++++++++++++++++++++++++ 5 files changed, 316 insertions(+), 31 deletions(-) diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index a9e1aae..5e0814c 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -60,12 +60,19 @@ mod ffi { ) -> 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; + pub fn vetta_cast_f32_f16(x: *const c_float, y: *mut u16, n: usize, stream: *mut c_void) -> c_int; pub fn vetta_nvfp4_gemv( packed: *const u8, scales: *const u8, outer_scale: c_float, x: *const c_float, y: *mut c_float, n: c_int, k: c_int, stream: *mut c_void, ) -> c_int; + pub fn vetta_nvfp4_gemv_f16( + packed: *const u8, scales: *const u8, outer_scale: c_float, x: *const u16, y: *mut c_float, + n: c_int, k: c_int, stream: *mut c_void, + ) -> c_int; pub fn vetta_mxfp8_gemv(weights: *const u8, scales: *const u8, x: *const c_float, y: *mut c_float, n: c_int, k: c_int, stream: *mut c_void) -> c_int; + pub fn vetta_mxfp8_gemv_f16(weights: *const u8, scales: *const u8, x: *const u16, y: *mut c_float, n: c_int, k: c_int, stream: *mut c_void) -> c_int; pub fn vetta_situ(gu: *const c_float, act: *mut c_float, inter: c_int, beta: c_float, lb: c_float, stream: *mut c_void) -> c_int; + pub fn vetta_situ_f16(gu: *const c_float, act: *mut u16, inter: c_int, beta: c_float, lb: c_float, stream: *mut c_void) -> c_int; pub fn vetta_moe_reduce(y_part: *const c_float, tk_w: *const c_float, out: *mut c_float, top_k: c_int, hidden: c_int, stream: *mut c_void) -> c_int; pub fn vetta_shortconv4_decode(cur: *const c_float, static_w: *const c_float, hist: *mut c_float, out: *mut c_float, slot_ids: *const i32, m: c_int, c: c_int, stream: *mut c_void) -> c_int; pub fn vetta_shortconv4_dyn_decode(cur: *const c_float, static_w: *const c_float, dyn_taps: *const c_float, hist: *mut c_float, out: *mut c_float, slot_ids: *const i32, m: c_int, c: c_int, n_heads: c_int, stream: *mut c_void) -> c_int; @@ -279,7 +286,7 @@ pub fn mxfp8_gemv(weights: &DeviceBuf, scales: &DeviceBuf, x: &DeviceBuf, y: &De Ok(()) } -/// Launch k_situ: SiTU double-softcapped activation (gu=[gate;up] -> act). +/// Launch k_situ: SiTU double-softcapped activation (gu INTERLEAVED gate/up -> act f32). #[cfg(feature = "hip")] pub fn situ(gu: &DeviceBuf, act: &DeviceBuf, inter: i32, beta: f32, lb: f32) -> Result<(), String> { let rc = unsafe { ffi::vetta_situ(gu.ptr as *const f32, act.ptr as *mut f32, inter, beta, lb, std::ptr::null_mut()) }; @@ -287,6 +294,42 @@ pub fn situ(gu: &DeviceBuf, act: &DeviceBuf, inter: i32, beta: f32, lb: f32) -> Ok(()) } +/// Launch k_cast_f32_f16: f32 activation -> FP16 (RNE), exact strata k_f32_to_f16. +#[cfg(feature = "hip")] +pub fn cast_f32_f16(x: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result<(), String> { + let rc = unsafe { ffi::vetta_cast_f32_f16(x.ptr as *const f32, y.ptr as *mut u16, n, std::ptr::null_mut()) }; + if rc != 0 { return Err("cast_f32_f16 launch failed".into()); } + Ok(()) +} + +/// Launch k_nvfp4_gemv_f16: NVFP4 GEMV reading FP16 activations (strata B=1 path). +#[cfg(feature = "hip")] +pub fn nvfp4_gemv_f16(packed: &DeviceBuf, scales: &DeviceBuf, outer_scale: f32, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32) -> Result<(), String> { + let rc = unsafe { + ffi::vetta_nvfp4_gemv_f16(packed.ptr as *const u8, scales.ptr as *const u8, outer_scale, x.ptr as *const u16, y.ptr as *mut f32, n, k, std::ptr::null_mut()) + }; + if rc != 0 { return Err("nvfp4_gemv_f16 launch failed".into()); } + Ok(()) +} + +/// Launch k_mxfp8_gemv_f16: MXFP8 GEMV reading FP16 activations (strata B=1 path). +#[cfg(feature = "hip")] +pub fn mxfp8_gemv_f16(weights: &DeviceBuf, scales: &DeviceBuf, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32) -> Result<(), String> { + let rc = unsafe { + ffi::vetta_mxfp8_gemv_f16(weights.ptr as *const u8, scales.ptr as *const u8, x.ptr as *const u16, y.ptr as *mut f32, n, k, std::ptr::null_mut()) + }; + if rc != 0 { return Err("mxfp8_gemv_f16 launch failed".into()); } + Ok(()) +} + +/// Launch k_situ_f16: SiTU computed in f32, stored FP16 (exact strata act_out). +#[cfg(feature = "hip")] +pub fn situ_f16(gu: &DeviceBuf, act: &DeviceBuf, inter: i32, beta: f32, lb: f32) -> Result<(), String> { + let rc = unsafe { ffi::vetta_situ_f16(gu.ptr as *const f32, act.ptr as *mut u16, inter, beta, lb, std::ptr::null_mut()) }; + if rc != 0 { return Err("situ_f16 launch failed".into()); } + Ok(()) +} + /// Launch k_moe_reduce: out[d] = sum_e tk_w[e]*y_part[e,d]. #[cfg(feature = "hip")] pub fn moe_reduce(y_part: &DeviceBuf, tk_w: &DeviceBuf, out: &DeviceBuf, top_k: i32, hidden: i32) -> Result<(), String> { diff --git a/crates/vetta-infer-ld/src/layer.rs b/crates/vetta-infer-ld/src/layer.rs index 3216d2f..04aee8b 100644 --- a/crates/vetta-infer-ld/src/layer.rs +++ b/crates/vetta-infer-ld/src/layer.rs @@ -10,7 +10,7 @@ //! layers (3-query split), loop controllers (gain/forget/down) and the //! multi-pass bank rollback are layered on next. -use crate::packer::{expert_gemv, load_bf16_as_f32, load_expert_matrix, load_raw}; +use crate::packer::{expert_gemv, expert_gemv_f16, load_bf16_as_f32, load_expert_matrix, load_raw}; use crate::SafetensorsArchive; use vetta_infer_hip::DeviceBuf; @@ -225,19 +225,7 @@ pub fn layer_forward_swa( vetta_infer_hip::moe_router_topk(&rlog, Some(&w.gate_b), &ids, &weights, 1, d.n_experts as i32, d.top_k as i32, d.route_scale)?; let ids_h = { let mut b = vec![0u8; d.top_k * 4]; ids.d2h_bytes(&mut b)?; b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::>() }; if std::env::var("VETTA_DBG_IDS").is_ok() { eprintln!("[dbg] ip={} GPU experts={:?}", w.ip, ids_h); } - let gu = DeviceBuf::alloc(2 * d.inter * 4)?; - let act = DeviceBuf::alloc(d.inter * 4)?; - let mut y_part_h = vec![0f32; d.top_k * h]; - for kk in 0..d.top_k { - let e = ids_h[kk] as usize; - let w13 = load_expert_matrix(ar, w.ip, e, "w13")?; - expert_gemv(&w13, &mlpin, &gu)?; - vetta_infer_hip::situ(&gu, &act, d.inter as i32, d.beta, d.lb)?; - let w2 = load_expert_matrix(ar, w.ip, e, "w2")?; - let ye = DeviceBuf::alloc(h * 4)?; - expert_gemv(&w2, &act, &ye)?; - ye.d2h(&mut y_part_h[kk * h..(kk + 1) * h])?; - } + let y_part_h = run_experts(ar, w.ip, &ids_h, &mlpin, d, h)?; let y_part = DeviceBuf::alloc(d.top_k * h * 4)?; y_part.h2d(&y_part_h)?; let moeout = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::moe_reduce(&y_part, &weights, &moeout, d.top_k as i32, h as i32)?; @@ -328,8 +316,7 @@ fn load_msg_queries(ar: &SafetensorsArchive, ip: usize, hidden: usize) -> Result let buf = DeviceBuf::alloc(4 * hidden * 4)?; buf.h2d(&mq)?; Ok(buf) } -/// Run one physical layer step (SWA or full-attn dispatch), reusing its -/// persistent state (KV cache + shortconv history) across loop passes. +/// Gated per-tensor L2-norm dump for reference bisection (VETTA_DBG_NORM=1). fn dbg_norm(name: &str, buf: &DeviceBuf, n: usize) { if std::env::var("VETTA_DBG_NORM").is_err() { return; } let mut h = vec![0f32; n]; buf.d2h(&mut h).unwrap(); @@ -337,6 +324,51 @@ fn dbg_norm(name: &str, buf: &DeviceBuf, n: usize) { eprintln!("[NORM] v0 {name} norm={ss:.6} h0={:.6} h1={:.6}", h[0], h[1]); } +/// Run the top-k experts for one MoE block: w13 GEMV -> SiTU -> w2 GEMV per +/// expert, returning the stacked per-expert outputs y_part [top_k, hidden]. +/// +/// Default is the all-f32 path (the verified parity baseline). The exact strata +/// B=1 FP16 path (mlpin cast to FP16, w13 GEMV reads FP16, SiTU stored FP16, w2 +/// reads FP16) is available via VETTA_F16_EXPERT=1. MEASURED: switching to FP16 +/// shifts tok100 logits by ~0.01 but does NOT flip the near-tie argmax (220 vs +/// ref 68014) — the residual gap is the core-loop pass 1/2, not expert precision. +fn run_experts( + ar: &SafetensorsArchive, ip: usize, ids_h: &[i32], mlpin: &DeviceBuf, d: &Dims, h: usize, +) -> Result, String> { + let gu = DeviceBuf::alloc(2 * d.inter * 4)?; + let mut y_part_h = vec![0f32; d.top_k * h]; + if std::env::var("VETTA_F16_EXPERT").is_ok() { + let mlpin16 = DeviceBuf::alloc(h * 2)?; + vetta_infer_hip::cast_f32_f16(mlpin, &mlpin16, h)?; + let act16 = DeviceBuf::alloc(d.inter * 2)?; + for kk in 0..d.top_k { + let e = ids_h[kk] as usize; + let w13 = load_expert_matrix(ar, ip, e, "w13")?; + expert_gemv_f16(&w13, &mlpin16, &gu)?; + vetta_infer_hip::situ_f16(&gu, &act16, d.inter as i32, d.beta, d.lb)?; + let w2 = load_expert_matrix(ar, ip, e, "w2")?; + let ye = DeviceBuf::alloc(h * 4)?; + expert_gemv_f16(&w2, &act16, &ye)?; + ye.d2h(&mut y_part_h[kk * h..(kk + 1) * h])?; + } + } else { + let act = DeviceBuf::alloc(d.inter * 4)?; + for kk in 0..d.top_k { + let e = ids_h[kk] as usize; + let w13 = load_expert_matrix(ar, ip, e, "w13")?; + expert_gemv(&w13, mlpin, &gu)?; + vetta_infer_hip::situ(&gu, &act, d.inter as i32, d.beta, d.lb)?; + let w2 = load_expert_matrix(ar, ip, e, "w2")?; + let ye = DeviceBuf::alloc(h * 4)?; + expert_gemv(&w2, &act, &ye)?; + ye.d2h(&mut y_part_h[kk * h..(kk + 1) * h])?; + } + } + Ok(y_part_h) +} + +/// Run one physical layer step (SWA or full-attn dispatch), reusing its +/// persistent state (KV cache + shortconv history) across loop passes. fn run_layer( ar: &SafetensorsArchive, d: &Dims, ip: usize, cur: &DeviceBuf, blocks: &mut Vec, states: &mut [Option], max_seq: usize, pos: i32, pass: usize, @@ -598,19 +630,7 @@ pub fn layer_forward_full( vetta_infer_hip::moe_router_topk(&rlog, Some(&w.gate_b), &ids, &weights, 1, d.n_experts as i32, d.top_k as i32, d.route_scale)?; let ids_h = { let mut b = vec![0u8; d.top_k * 4]; ids.d2h_bytes(&mut b)?; b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::>() }; if std::env::var("VETTA_DBG_IDS").is_ok() { eprintln!("[dbg] ip={} GPU experts={:?}", w.ip, ids_h); } - let gu = DeviceBuf::alloc(2 * d.inter * 4)?; - let act = DeviceBuf::alloc(d.inter * 4)?; - let mut y_part_h = vec![0f32; d.top_k * h]; - for kk in 0..d.top_k { - let e = ids_h[kk] as usize; - let w13 = load_expert_matrix(ar, w.ip, e, "w13")?; - expert_gemv(&w13, &mlpin, &gu)?; - vetta_infer_hip::situ(&gu, &act, d.inter as i32, d.beta, d.lb)?; - let w2 = load_expert_matrix(ar, w.ip, e, "w2")?; - let ye = DeviceBuf::alloc(h * 4)?; - expert_gemv(&w2, &act, &ye)?; - ye.d2h(&mut y_part_h[kk * h..(kk + 1) * h])?; - } + let y_part_h = run_experts(ar, w.ip, &ids_h, &mlpin, d, h)?; let y_part = DeviceBuf::alloc(d.top_k * h * 4)?; y_part.h2d(&y_part_h)?; let moeout = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::moe_reduce(&y_part, &weights, &moeout, d.top_k as i32, h as i32)?; diff --git a/crates/vetta-infer-ld/src/packer.rs b/crates/vetta-infer-ld/src/packer.rs index 9ddef2f..57bc553 100644 --- a/crates/vetta-infer-ld/src/packer.rs +++ b/crates/vetta-infer-ld/src/packer.rs @@ -115,6 +115,15 @@ pub fn expert_gemv(em: &ExpertMatrix, x: &DeviceBuf, y: &DeviceBuf) -> Result<() } } +/// FP16-activation expert GEMV (exact strata B=1 path: x is FP16 mlpf16/act). +pub fn expert_gemv_f16(em: &ExpertMatrix, x: &DeviceBuf, y: &DeviceBuf) -> Result<(), String> { + if em.mxfp8 { + vetta_infer_hip::mxfp8_gemv_f16(&em.packed, &em.scales, x, y, em.n, em.k) + } else { + vetta_infer_hip::nvfp4_gemv_f16(&em.packed, &em.scales, em.outer, x, y, em.n, em.k) + } +} + #[cfg(test)] mod tests { use super::*; @@ -230,6 +239,64 @@ mod tests { assert!(max_rel < 1e-3, "real expert NVFP4 parity failed: {max_rel}"); } + // FP16 -> f32 decode (for reading back the GPU cast_f32_f16 output). + fn f16_to_f32(h: u16) -> f32 { + let sign = ((h & 0x8000) as u32) << 16; + let exp = (h >> 10) & 0x1f; + let mant = (h & 0x3ff) as u32; + if exp == 0 { + if mant == 0 { return f32::from_bits(sign); } + let v = (mant as f32) * (2.0f32).powi(-24); + return if sign != 0 { -v } else { v }; + } + if exp == 31 { return if mant == 0 { f32::from_bits(sign | 0x7f800000) } else { f32::NAN }; } + f32::from_bits(sign | ((exp as u32 + 112) << 23) | (mant << 13)) + } + + /// Real NVFP4 expert GEMV FP16-activation parity (exact strata B=1 path): + /// cast x to FP16 on GPU, run nvfp4_gemv_f16, compare to a CPU oracle over + /// the SAME fp16-rounded x with group-of-16 partial dot then scale-fma. + #[test] + #[ignore] + fn real_expert_nvfp4_gemv_f16_parity() { + let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap(); + let em = load_expert_matrix(&ar, 0, 0, "w13").unwrap(); + let (n, k) = (em.n as usize, em.k as usize); + let x: Vec = (0..k).map(|i| ((i % 41) as f32 - 20.0) * 0.02).collect(); + let dx = DeviceBuf::alloc(k * 4).unwrap(); dx.h2d(&x).unwrap(); + let dx16 = DeviceBuf::alloc(k * 2).unwrap(); + vetta_infer_hip::cast_f32_f16(&dx, &dx16, k).unwrap(); + let mut x16b = vec![0u8; k * 2]; dx16.d2h_bytes(&mut x16b).unwrap(); + let x16: Vec = x16b.chunks_exact(2).map(|c| f16_to_f32(u16::from_le_bytes([c[0], c[1]]))).collect(); + let dy = DeviceBuf::alloc(n * 4).unwrap(); + vetta_infer_hip::nvfp4_gemv_f16(&em.packed, &em.scales, em.outer, &dx16, &dy, em.n, em.k).unwrap(); + let mut got = vec![0f32; n]; dy.d2h(&mut got).unwrap(); + let mut wb = vec![0u8; n * (k / 2)]; + ar.read_slice("model.llm.layers.0.mlp.experts.w13_weight", 0, &mut wb).unwrap(); + let mut sb = vec![0u8; n * (k / 16)]; + ar.read_slice("model.llm.layers.0.mlp.experts.w13_weight_scale", 0, &mut sb).unwrap(); + let mut want = vec![0f32; n]; + for ni in 0..n { + let mut acc = 0f32; + for b in 0..k / 16 { + let sc = e4m3(sb[ni * (k / 16) + b]) * em.outer; + let mut d = 0f32; + for j in 0..8 { + let byte = wb[ni * (k / 2) + b * 8 + j]; + d += x16[b * 16 + j * 2] * e2m1(byte & 15) + x16[b * 16 + j * 2 + 1] * e2m1(byte >> 4); + } + acc = d.mul_add(sc, acc); + } + want[ni] = acc; + } + let mut max_rel = 0f32; + for (g, w) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); } + eprintln!("real expert w13 NVFP4 GEMV f16: max_rel_err={max_rel:.3e}"); + // 2e-3: fp16 input rounding is identical on both sides; only the f32 + // group-sum accumulation order differs (GPU strided + tree vs CPU seq). + assert!(max_rel < 2e-3, "real expert NVFP4 f16 parity failed: {max_rel}"); + } + fn ue8m0(e: u8) -> f32 { if e == 255 { return 0.0; } if e == 0 { return f32::from_bits(0x00400000); } diff --git a/kernels/hip/vetta_kernels.h b/kernels/hip/vetta_kernels.h index 0cb0e80..80260a9 100644 --- a/kernels/hip/vetta_kernels.h +++ b/kernels/hip/vetta_kernels.h @@ -78,21 +78,39 @@ int vetta_vec_add(const float* a, const float* b, float* y, size_t n, int vetta_cast_f32_bf16(const float* x, uint16_t* y, size_t n, vetta_stream_t stream); +// k_cast_f32_f16: f32 activation -> FP16 (RNE), exact strata k_f32_to_f16. +int vetta_cast_f32_f16(const float* x, uint16_t* y, size_t n, + vetta_stream_t stream); + // k_nvfp4_gemv (M=1): y[N] = dequant(W)[N,K] @ x[K], NVFP4 (E2M1 + E4M3/16 + // f32 outer_scale). packed [N,K/2], scales [N,K/16]. K % 16 == 0. int vetta_nvfp4_gemv(const uint8_t* packed, const uint8_t* scales, float outer_scale, const float* x, float* y, int N, int K, vetta_stream_t stream); +// k_nvfp4_gemv_f16: FP16-activation variant (exact strata B=1 expert path). +int vetta_nvfp4_gemv_f16(const uint8_t* packed, const uint8_t* scales, + float outer_scale, const uint16_t* x, float* y, + int N, int K, vetta_stream_t stream); + // k_mxfp8_gemv (M=1): MXFP8 experts (layers 20..23). y[N] = sum_k e4m3(W[n,k]) // * ue8m0(scale[n,k/32]) * x[k]. weights [N,K] F8_E4M3, scales [N,K/32] U8. int vetta_mxfp8_gemv(const uint8_t* weights, const uint8_t* scales, const float* x, float* y, int N, int K, vetta_stream_t stream); -// k_situ: SiTU double-softcapped MoE activation. gu=[gate;up] (2*inter) -> act. +// k_mxfp8_gemv_f16: FP16-activation variant (exact strata MX8 expert path). +int vetta_mxfp8_gemv_f16(const uint8_t* weights, const uint8_t* scales, + const uint16_t* x, float* y, int N, int K, vetta_stream_t stream); + +// k_situ: SiTU double-softcapped MoE activation. gu INTERLEAVED gate/up +// (row 2j=gate[j], 2j+1=up[j], 2*inter) -> act f32. int vetta_situ(const float* gu, float* act, int inter, float beta, float lb, vetta_stream_t stream); +// k_situ_f16: SiTU computed in f32, stored FP16 (exact strata act_out half). +int vetta_situ_f16(const float* gu, uint16_t* act, int inter, float beta, float lb, + vetta_stream_t stream); + // k_moe_reduce: out[d] = sum_e tk_w[e]*y_part[e,d] (weighted expert sum). int vetta_moe_reduce(const float* y_part, const float* tk_w, float* out, int top_k, int hidden, vetta_stream_t stream); diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index e9696c9..1def3a7 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -5,6 +5,7 @@ // GPU test) before it is wired into the executor. #include +#include #include #include #include "vetta_kernels.h" @@ -490,6 +491,31 @@ extern "C" int vetta_cast_f32_bf16(const float* x, uint16_t* y, size_t n, return 0; } +// ---- k_cast_f32_f16: f32 activation -> FP16 (RNE) --------------------------- +// Exact strata k_f32_to_f16: the B=1 expert path reads FP16 activations +// (mlpf16), and SiTU stores its output as FP16 before the w2 GEMV. + +__global__ void k_cast_f32_f16(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] = __half_as_ushort(__float2half_rn(x[i])); +} + +extern "C" int vetta_cast_f32_f16(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_f16<<>>(x, y, n); + HIP_CHECK(hipGetLastError()); + return 0; +} + +__device__ __forceinline__ float f16_to_f32(uint16_t h) { + return __half2float(__ushort_as_half(h)); +} + // ---- NVFP4 (SF4) codecs — exact semantics from strata ink_hip_common ------- // E2M1 nibble LUT; F8_E4M3FN group scale (16 weights/group); f32 outer_scale. // Layout: packed_e2m1 [N, K/2] (low nib = even col, high nib = odd col), @@ -565,6 +591,55 @@ extern "C" int vetta_nvfp4_gemv(const uint8_t* packed, const uint8_t* scales, return 0; } +// ---- k_nvfp4_gemv_f16: FP16-activation variant (exact strata B=1 path) ------ +// x is FP16 (mlpf16); E2M1 nibbles are exact in FP16, so each product is +// f32(fp16 x) * e2m1. Group-of-16 partial sums are scaled AFTER the dot +// (acc = fmaf(d, sc, acc), exact k_moe_direct_w13_situ / w2_par fdot2 order). + +__global__ void k_nvfp4_gemv_f16(const uint8_t* __restrict__ packed, + const uint8_t* __restrict__ scales, + float outer_scale, const uint16_t* __restrict__ x, + float* __restrict__ y, int N, int K) { + const int n = blockIdx.x; + if (n >= N) return; + const int tid = threadIdx.x; + const int nt = blockDim.x; + const uint8_t* wp = packed + (size_t)n * (K >> 1); + const uint8_t* ws = scales + (size_t)n * (K >> 4); + const int nblk = K >> 4; + float acc = 0.f; + for (int b = tid; b < nblk; b += nt) { + const float sc = e4m3fn_to_f32(ws[b]) * outer_scale; + const int k0 = b << 4; + const uint8_t* w8 = wp + b * 8; + float d = 0.f; + for (int j = 0; j < 8; ++j) { + uint8_t byte = w8[j]; + d += f16_to_f32(x[k0 + j * 2]) * sf4_e2m1_f32(byte & 15u) + + f16_to_f32(x[k0 + j * 2 + 1]) * sf4_e2m1_f32(byte >> 4); + } + acc = fmaf(d, sc, acc); + } + __shared__ float red[256]; + red[tid] = acc; + __syncthreads(); + for (int s = nt / 2; s > 0; s >>= 1) { + if (tid < s) red[tid] += red[tid + s]; + __syncthreads(); + } + if (tid == 0) y[n] = red[0]; +} + +extern "C" int vetta_nvfp4_gemv_f16(const uint8_t* packed, const uint8_t* scales, + float outer_scale, const uint16_t* x, float* y, + int N, int K, vetta_stream_t stream) { + if (N <= 0 || K <= 0 || (K % 16) != 0) return 1; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_nvfp4_gemv_f16<<>>(packed, scales, outer_scale, x, y, N, K); + HIP_CHECK(hipGetLastError()); + return 0; +} + // ---- k_mxfp8_gemv (M=1 decode): MXFP8 experts (layers 20..23) -------------- // Exact strata MX8: y[N] = sum_k e4m3fn(W[n,k]) * ue8m0(scale[n,k/32]) * x[k]. // W [N,K] F8_E4M3 bytes (full K), scale [N,K/32] U8 UE8M0, NO outer scale. @@ -613,6 +688,49 @@ extern "C" int vetta_mxfp8_gemv(const uint8_t* weights, const uint8_t* scales, return 0; } +// ---- k_mxfp8_gemv_f16: FP16-activation variant (exact strata MX8 path) ------ +// E4M3 weights are exact in FP16; group-of-32 partial dot then scale-fma. + +__global__ void k_mxfp8_gemv_f16(const uint8_t* __restrict__ weights, + const uint8_t* __restrict__ scales, + const uint16_t* __restrict__ x, float* __restrict__ y, + int N, int K) { + const int n = blockIdx.x; + if (n >= N) return; + const int tid = threadIdx.x; + const int nt = blockDim.x; + const uint8_t* wp = weights + (size_t)n * K; + const uint8_t* ws = scales + (size_t)n * (K >> 5); + const int nblk = K >> 5; + float acc = 0.f; + for (int b = tid; b < nblk; b += nt) { + const float sc = ue8m0_to_f32(ws[b]); + const int k0 = b << 5; + const uint8_t* w8 = wp + k0; + float d = 0.f; + for (int j = 0; j < 32; ++j) d += f16_to_f32(x[k0 + j]) * e4m3fn_to_f32(w8[j]); + acc = fmaf(d, sc, acc); + } + __shared__ float red[256]; + red[tid] = acc; + __syncthreads(); + for (int s = nt / 2; s > 0; s >>= 1) { + if (tid < s) red[tid] += red[tid + s]; + __syncthreads(); + } + if (tid == 0) y[n] = red[0]; +} + +extern "C" int vetta_mxfp8_gemv_f16(const uint8_t* weights, const uint8_t* scales, + const uint16_t* x, float* y, int N, int K, + vetta_stream_t stream) { + if (N <= 0 || K <= 0 || (K % 32) != 0) return 1; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_mxfp8_gemv_f16<<>>(weights, scales, x, y, N, K); + HIP_CHECK(hipGetLastError()); + return 0; +} + // ---- SiTU activation (exact strata situ_f32, double-softcapped) ------------ // gu rows are INTERLEAVED gate/up (exact strata k_moe_direct_w13_situ: // row 2j=gate[j], row 2j+1=up[j]). act[j] = g_act * u_act where @@ -641,6 +759,25 @@ extern "C" int vetta_situ(const float* gu, float* act, int inter, float beta, return 0; } +// ---- k_situ_f16: SiTU computed in f32, stored FP16 (exact strata act_out) --- +// The reference stores static_cast(situ_f32(g, u)) before the w2 GEMV. + +__global__ void k_situ_f16(const float* __restrict__ gu, uint16_t* __restrict__ act, + int inter, float beta, float lb) { + int j = blockIdx.x * blockDim.x + threadIdx.x; + if (j < inter) act[j] = __half_as_ushort(__float2half_rn(situ_f32(gu[2 * j], gu[2 * j + 1], beta, lb))); +} + +extern "C" int vetta_situ_f16(const float* gu, uint16_t* act, int inter, float beta, + float lb, vetta_stream_t stream) { + if (inter <= 0) return 1; + const int nt = 256; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_situ_f16<<<(inter + nt - 1) / nt, nt, 0, s>>>(gu, act, inter, beta, lb); + HIP_CHECK(hipGetLastError()); + return 0; +} + // ---- k_moe_reduce: out[d] = sum_e tk_w[e] * y_part[e, d] ------------------- __global__ void k_moe_reduce(const float* __restrict__ y_part,