[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.
This commit is contained in:
1 parent
26bff57645
commit
e4dcc5e015
5 files changed
+316
-31
No files matched your search
@@ -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::<Vec<_>>() };
|
||||
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<Vec<f32>, 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<DeviceBuf>,
|
||||
states: &mut [Option<LayerState>], 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::<Vec<_>>() };
|
||||
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)?;
|
||||
|
||||
@@ -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<f32> = (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<f32> = 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); }
|
||||
|
||||
Reference in new issue
Block a user