diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 7fbc212..f815c76 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -85,6 +85,10 @@ mod ffi { ) -> 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_mxfp8_gemv_f16_indirect( + arena_weights: *const u8, arena_scales: *const u8, ids: *const c_int, slot: c_int, + x: *const u16, y: *mut c_float, n: c_int, k: c_int, w_stride: c_long, sc_stride: c_long, 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; @@ -471,6 +475,16 @@ pub fn mxfp8_gemv_f16(weights: &DeviceBuf, scales: &DeviceBuf, x: &DeviceBuf, y: Ok(()) } +/// Device-routed MXFP8 f16 GEMV (arena + ids[slot]); graph-capturable, no outer. +#[cfg(feature = "hip")] +pub fn mxfp8_gemv_f16_indirect(arena_weights: &DeviceBuf, arena_scales: &DeviceBuf, ids: &DeviceBuf, slot: i32, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32, w_stride: i64, sc_stride: i64) -> Result<(), String> { + let rc = unsafe { + ffi::vetta_mxfp8_gemv_f16_indirect(arena_weights.ptr as *const u8, arena_scales.ptr as *const u8, ids.ptr as *const i32, slot, x.ptr as *const u16, y.ptr as *mut f32, n, k, w_stride, sc_stride, std::ptr::null_mut()) + }; + if rc != 0 { return Err("mxfp8_gemv_f16_indirect 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> { diff --git a/crates/vetta-infer-ld/src/packer.rs b/crates/vetta-infer-ld/src/packer.rs index 7b8218a..198f31f 100644 --- a/crates/vetta-infer-ld/src/packer.rs +++ b/crates/vetta-infer-ld/src/packer.rs @@ -124,6 +124,80 @@ pub fn expert_gemv_f16(em: &ExpertMatrix, x: &DeviceBuf, y: &DeviceBuf) -> Resul } } +/// A whole layer's expert matrices packed in ONE contiguous device arena, exactly +/// as the safetensors already store them ([n_exp, N, K/2] NVFP4 / [n_exp, N, K] +/// MXFP8). The device-routed (indirect) GEMV indexes expert `id` via +/// `id * w_stride`, so the MoE dispatch needs NO host ids round-trip and the +/// launch parameters stay static => graph-capturable. `outer` holds one +/// precomputed amax/denominator per expert (NVFP4) or 1.0 (MXFP8). +pub struct ExpertArena { + pub packed: DeviceBuf, + pub scales: DeviceBuf, + pub outer: DeviceBuf, + pub n: i32, + pub k: i32, + pub n_exp: usize, + pub mxfp8: bool, + pub w_stride: i64, + pub sc_stride: i64, +} + +/// Load the full expert arena for `layer`/`mat` ("w13" or "w2") in one upload. +/// Zero requantization: bytes go to device as-is (same format detection as +/// load_expert_matrix: amax presence => NVFP4, else MXFP8). +pub fn load_expert_arena(ar: &SafetensorsArchive, layer: usize, mat: &str) -> Result { + let base = format!("model.llm.layers.{layer}.mlp.experts.{mat}"); + let wname = format!("{base}_weight"); + let sname = format!("{base}_weight_scale"); + let aname = format!("{base}_weight_amax"); + let dname = format!("{base}_weight_outer_scale_denominator"); + let winfo = ar.tensors.get(&wname).ok_or_else(|| format!("missing {wname}"))?; + let n_exp = winfo.shape[0] as usize; + let n = winfo.shape[1] as i32; + let mxfp8 = !ar.tensors.contains_key(&aname); + + let (k, w_per_e, s_per_e) = if mxfp8 { + let k = winfo.shape[2] as i32; + (k, (n as usize) * (k as usize), (n as usize) * (k as usize / 32)) + } else { + let k_half = winfo.shape[2] as usize; + let k = (k_half * 2) as i32; + (k, (n as usize) * k_half, (n as usize) * (k as usize / 16)) + }; + + let mut wbytes = vec![0u8; n_exp * w_per_e]; + ar.read_slice(&wname, 0, &mut wbytes)?; + let mut sbytes = vec![0u8; n_exp * s_per_e]; + ar.read_slice(&sname, 0, &mut sbytes)?; + let packed = DeviceBuf::alloc(wbytes.len())?; packed.h2d_bytes(&wbytes)?; + let scales = DeviceBuf::alloc(sbytes.len())?; scales.h2d_bytes(&sbytes)?; + + let outer_h: Vec = if mxfp8 { + vec![1.0; n_exp] + } else { + let mut amax_b = vec![0u8; n_exp * 4]; + ar.read_slice(&aname, 0, &mut amax_b)?; + let den = if ar.tensors.contains_key(&dname) { + let mut d_b = [0u8; 4]; ar.read_slice(&dname, 0, &mut d_b)?; + let d = f32::from_le_bytes(d_b); if d == 0.0 { 2688.0 } else { d } + } else { 2688.0 }; + amax_b.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]) / den).collect() + }; + let outer = DeviceBuf::alloc(n_exp * 4)?; outer.h2d(&outer_h)?; + + Ok(ExpertArena { packed, scales, outer, n, k, n_exp, mxfp8, w_stride: w_per_e as i64, sc_stride: s_per_e as i64 }) +} + +/// Device-routed expert GEMV from an arena: expert id read from `ids[slot]` on +/// device. Dispatches NVFP4 / MXFP8. Bit-identical math to expert_gemv_f16. +pub fn expert_arena_gemv_f16(a: &ExpertArena, ids: &DeviceBuf, slot: i32, x: &DeviceBuf, y: &DeviceBuf) -> Result<(), String> { + if a.mxfp8 { + vetta_infer_hip::mxfp8_gemv_f16_indirect(&a.packed, &a.scales, ids, slot, x, y, a.n, a.k, a.w_stride, a.sc_stride) + } else { + vetta_infer_hip::nvfp4_gemv_f16_indirect(&a.packed, &a.scales, &a.outer, ids, slot, x, y, a.n, a.k, a.w_stride, a.sc_stride) + } +} + #[cfg(test)] mod tests { use super::*; @@ -338,6 +412,38 @@ mod tests { assert!(max_rel < 1e-3, "real expert MXFP8 parity failed: {max_rel}"); } + /// Arena (device-routed) expert GEMV must be BIT-EXACT vs the per-expert + /// direct GEMV on real weights: same shared device body, only the base + /// address is selected on device from ids[slot]. Covers NVFP4 (layer 0) and + /// MXFP8 (layer 20). Validates the contiguous-arena foundation for + /// graph-capturable MoE dispatch (no host ids round-trip). + #[test] + #[ignore] + fn real_expert_arena_indirect_parity() { + let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap()); + for &layer in &[0usize, 20] { + let arena = load_expert_arena(&ar, layer, "w13").unwrap(); + let (n, k) = (arena.n as usize, arena.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 ids_vec: Vec = vec![0, 1, 5, 127]; + let ids_bytes: Vec = ids_vec.iter().flat_map(|v| v.to_le_bytes()).collect(); + let dids = DeviceBuf::alloc(ids_bytes.len()).unwrap(); dids.h2d_bytes(&ids_bytes).unwrap(); + let yi = DeviceBuf::alloc(n * 4).unwrap(); + let yd = DeviceBuf::alloc(n * 4).unwrap(); + for slot in 0..ids_vec.len() { + expert_arena_gemv_f16(&arena, &dids, slot as i32, &dx16, &yi).unwrap(); + let em = load_expert_matrix(&ar, layer, ids_vec[slot] as usize, "w13").unwrap(); + expert_gemv_f16(&em, &dx16, &yd).unwrap(); + let mut gi = vec![0f32; n]; yi.d2h(&mut gi).unwrap(); + let mut gd = vec![0f32; n]; yd.d2h(&mut gd).unwrap(); + assert_eq!(gi, gd, "arena indirect != direct (layer {layer}, slot {slot})"); + } + eprintln!("expert arena indirect bit-exact vs direct: layer {layer} ({})", if arena.mxfp8 { "MXFP8" } else { "NVFP4" }); + } + } + fn bf16_trunc(x: f32) -> f32 { let u = x.to_bits(); let r = 0x7FFFu32 + ((u >> 16) & 1); f32::from_bits(((u + r) >> 16) << 16) } fn rms_norm_cpu(x: &[f32], w: &[f32], eps: f32) -> Vec { let d = x.len(); diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index 5aae2c2..442bdd3 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -889,7 +889,7 @@ extern "C" int vetta_mxfp8_gemv(const uint8_t* weights, const uint8_t* scales, // ---- 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, +__device__ __forceinline__ void mxfp8_gemv_f16_body(const uint8_t* __restrict__ weights, const uint8_t* __restrict__ scales, const uint16_t* __restrict__ x, float* __restrict__ y, int N, int K) { @@ -919,6 +919,36 @@ __global__ void k_mxfp8_gemv_f16(const uint8_t* __restrict__ weights, if (tid == 0) y[n] = red[0]; } +__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) { + mxfp8_gemv_f16_body(weights, scales, x, y, N, K); +} + +// Indirect (device-routed) MXFP8 f16 GEMV: expert id from ids[slot] indexes a +// contiguous arena (weights / scales). MXFP8 has no outer scale. Same body. +__global__ void k_mxfp8_gemv_f16_indirect(const uint8_t* __restrict__ arena_weights, + const uint8_t* __restrict__ arena_scales, + const int* __restrict__ ids, int slot, + const uint16_t* __restrict__ x, float* __restrict__ y, + int N, int K, long w_stride, long sc_stride) { + const int id = ids[slot]; + mxfp8_gemv_f16_body(arena_weights + (long)id * w_stride, + arena_scales + (long)id * sc_stride, x, y, N, K); +} + +extern "C" int vetta_mxfp8_gemv_f16_indirect(const uint8_t* arena_weights, + const uint8_t* arena_scales, const int* ids, int slot, + const uint16_t* x, float* y, int N, int K, + long w_stride, long sc_stride, vetta_stream_t stream) { + if (N <= 0 || K <= 0 || (K % 32) != 0 || slot < 0) return 1; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_mxfp8_gemv_f16_indirect<<>>(arena_weights, arena_scales, ids, slot, x, y, N, K, w_stride, sc_stride); + HIP_CHECK(hipGetLastError()); + return 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) {