diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index f815c76..9851f43 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -81,13 +81,13 @@ mod ffi { pub fn vetta_nvfp4_gemv_f16_indirect( arena_packed: *const u8, arena_scales: *const u8, outer_arena: *const c_float, 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, + n: c_int, k: c_int, w_stride: c_long, sc_stride: c_long, y_offset: c_long, 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_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, + x: *const u16, y: *mut c_float, n: c_int, k: c_int, w_stride: c_long, sc_stride: c_long, y_offset: 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; @@ -457,9 +457,9 @@ pub fn nvfp4_gemv_f16(packed: &DeviceBuf, scales: &DeviceBuf, outer_scale: f32, /// round-trip). `w_stride`/`sc_stride` are the per-expert byte spans. Same math /// as `nvfp4_gemv_f16` (shared device body). #[cfg(feature = "hip")] -pub fn nvfp4_gemv_f16_indirect(arena_packed: &DeviceBuf, arena_scales: &DeviceBuf, outer_arena: &DeviceBuf, ids: &DeviceBuf, slot: i32, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32, w_stride: i64, sc_stride: i64) -> Result<(), String> { +pub fn nvfp4_gemv_f16_indirect(arena_packed: &DeviceBuf, arena_scales: &DeviceBuf, outer_arena: &DeviceBuf, ids: &DeviceBuf, slot: i32, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32, w_stride: i64, sc_stride: i64, y_offset: i64) -> Result<(), String> { let rc = unsafe { - ffi::vetta_nvfp4_gemv_f16_indirect(arena_packed.ptr as *const u8, arena_scales.ptr as *const u8, outer_arena.ptr as *const f32, 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()) + ffi::vetta_nvfp4_gemv_f16_indirect(arena_packed.ptr as *const u8, arena_scales.ptr as *const u8, outer_arena.ptr as *const f32, ids.ptr as *const i32, slot, x.ptr as *const u16, y.ptr as *mut f32, n, k, w_stride, sc_stride, y_offset, std::ptr::null_mut()) }; if rc != 0 { return Err("nvfp4_gemv_f16_indirect launch failed".into()); } Ok(()) @@ -477,9 +477,9 @@ pub fn mxfp8_gemv_f16(weights: &DeviceBuf, scales: &DeviceBuf, x: &DeviceBuf, y: /// 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> { +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, y_offset: 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()) + 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, y_offset, std::ptr::null_mut()) }; if rc != 0 { return Err("mxfp8_gemv_f16_indirect launch failed".into()); } Ok(()) @@ -960,7 +960,7 @@ mod gpu_tests { let yi = DeviceBuf::alloc(n * 4).unwrap(); let yd = DeviceBuf::alloc(n * 4).unwrap(); for slot in 0..ids_vec.len() { - nvfp4_gemv_f16_indirect(&ap, &asc, &ao, &dids, slot as i32, &xh, &yi, n as i32, k as i32, w_stride as i64, sc_stride as i64).unwrap(); + nvfp4_gemv_f16_indirect(&ap, &asc, &ao, &dids, slot as i32, &xh, &yi, n as i32, k as i32, w_stride as i64, sc_stride as i64, 0).unwrap(); let id = ids_vec[slot] as usize; let sp = DeviceBuf::alloc(w_stride).unwrap(); sp.h2d_bytes(&packed[id * w_stride..(id + 1) * w_stride]).unwrap(); let ss = DeviceBuf::alloc(sc_stride).unwrap(); ss.h2d_bytes(&scales[id * sc_stride..(id + 1) * sc_stride]).unwrap(); diff --git a/crates/vetta-infer-ld/src/layer.rs b/crates/vetta-infer-ld/src/layer.rs index accbeb6..a3a2130 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, expert_gemv_f16, load_bf16_as_f32, load_expert_matrix, load_raw, ExpertMatrix}; +use crate::packer::{expert_arena_gemv_f16, expert_gemv, expert_gemv_f16, load_bf16_as_f32, load_expert_arena, load_expert_matrix, load_raw, ExpertArena, ExpertMatrix}; use crate::SafetensorsArchive; use std::cell::RefCell; use std::collections::HashMap; @@ -82,6 +82,7 @@ pub struct WeightCache { swa: RefCell>>, full: RefCell>>, experts: RefCell>>, + arenas: RefCell>>, ctrl: RefCell>>, } @@ -95,6 +96,7 @@ impl WeightCache { swa: RefCell::new(HashMap::new()), full: RefCell::new(HashMap::new()), experts: RefCell::new(HashMap::new()), + arenas: RefCell::new(HashMap::new()), ctrl: RefCell::new(HashMap::new()), } } @@ -143,6 +145,16 @@ impl WeightCache { Ok(v) } + /// Contiguous per-layer expert arena (all experts in one device buffer) for + /// the device-routed MoE path. Memoized like `expert`. + pub fn expert_arena(&self, ip: usize, mat: &str) -> Result, String> { + let key = (ip, mat.to_string()); + if let Some(v) = self.arenas.borrow().get(&key) { return Ok(v.clone()); } + let v = Arc::new(load_expert_arena(&self.ar, ip, mat)?); + self.arenas.borrow_mut().insert(key, v.clone()); + Ok(v) + } + pub fn controllers(&self, ip: usize) -> Result, String> { if let Some(v) = self.ctrl.borrow().get(&ip) { return Ok(v.clone()); } let v = Arc::new(load_controllers(&self.ar, ip)?); @@ -443,13 +455,20 @@ pub fn layer_forward_swa( let ids = DeviceBuf::alloc(d.top_k * 4)?; let weights = DeviceBuf::alloc(d.top_k * 4)?; 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 y_part_h = run_experts(cache, 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)?; - if w.ip == 0 || (w.ip == 6 && pass == 1) { dbg_norm("y_part", &y_part, d.top_k * h); dbg_norm("moeout", &moeout, h); } + let moeout = if std::env::var("VETTA_DEVICE_MOE").is_ok() { + // Device-resident MoE: ids/weights stay on device, arena indirect GEMV, + // no host round-trip (graph-capturable). f16 path, bit-identical math. + moe_device(cache, w.ip, &mlpin, &ids, &weights, d, h)? + } else { + 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 y_part_h = run_experts(cache, 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)?; + if w.ip == 0 || (w.ip == 6 && pass == 1) { dbg_norm("y_part", &y_part, d.top_k * h); dbg_norm("moeout", &moeout, h); } + moeout + }; // k7: mlp shortconv + plain residual add. let msc = DeviceBuf::alloc(h * 4)?; @@ -589,6 +608,33 @@ fn run_experts( Ok(y_part_h) } +/// Device-resident MoE (graph-capturable): expert ids/weights stay on device, +/// the arena indirect GEMV selects experts on device, and the per-expert outputs +/// accumulate in a device `y_part` (static y_offset = kk*hidden). NO host ids or +/// output round-trip. f16 activations (exact strata B=1 path); bit-identical to +/// the VETTA_F16_EXPERT host path (same kernels, same data). Returns moeout [h]. +fn moe_device( + cache: &WeightCache, ip: usize, mlpin: &DeviceBuf, ids: &DeviceBuf, weights: &DeviceBuf, d: &Dims, h: usize, +) -> Result { + let t0 = std::time::Instant::now(); + let w13 = cache.expert_arena(ip, "w13")?; + let w2 = cache.expert_arena(ip, "w2")?; + let mlpin16 = DeviceBuf::alloc(h * 2)?; + vetta_infer_hip::cast_f32_f16(mlpin, &mlpin16, h)?; + let gu = DeviceBuf::alloc(2 * d.inter * 4)?; + let act16 = DeviceBuf::alloc(d.inter * 2)?; + let y_part = DeviceBuf::alloc(d.top_k * h * 4)?; + for kk in 0..d.top_k { + expert_arena_gemv_f16(&w13, ids, kk as i32, &mlpin16, &gu, 0)?; + vetta_infer_hip::situ_f16(&gu, &act16, d.inter as i32, d.beta, d.lb)?; + expert_arena_gemv_f16(&w2, ids, kk as i32, &act16, &y_part, (kk * h) as i64)?; + } + let moeout = DeviceBuf::alloc(h * 4)?; + vetta_infer_hip::moe_reduce(&y_part, weights, &moeout, d.top_k as i32, h as i32)?; + EXPERT_NS.with(|c| c.set(c.get() + t0.elapsed().as_nanos())); + Ok(moeout) +} + /// Run one physical layer step (SWA or full-attn dispatch), reusing its /// persistent state (KV cache + shortconv history) across loop passes. fn run_layer( @@ -884,13 +930,20 @@ pub fn layer_forward_full( let ids = DeviceBuf::alloc(d.top_k * 4)?; let weights = DeviceBuf::alloc(d.top_k * 4)?; 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 y_part_h = run_experts(cache, 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)?; - if w.ip == 0 || (w.ip == 6 && pass == 1) { dbg_norm("y_part", &y_part, d.top_k * h); dbg_norm("moeout", &moeout, h); } + let moeout = if std::env::var("VETTA_DEVICE_MOE").is_ok() { + // Device-resident MoE: ids/weights stay on device, arena indirect GEMV, + // no host round-trip (graph-capturable). f16 path, bit-identical math. + moe_device(cache, w.ip, &mlpin, &ids, &weights, d, h)? + } else { + 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 y_part_h = run_experts(cache, 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)?; + if w.ip == 0 || (w.ip == 6 && pass == 1) { dbg_norm("y_part", &y_part, d.top_k * h); dbg_norm("moeout", &moeout, h); } + moeout + }; let msc = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::shortconv4_decode(&moeout, &w.m_sconv, &st.hist_m[pass], &msc, &slot0, 1, h as i32)?; vetta_infer_hip::vec_add(cur, &msc, cur, h)?; diff --git a/crates/vetta-infer-ld/src/packer.rs b/crates/vetta-infer-ld/src/packer.rs index 198f31f..3a30df0 100644 --- a/crates/vetta-infer-ld/src/packer.rs +++ b/crates/vetta-infer-ld/src/packer.rs @@ -190,11 +190,11 @@ pub fn load_expert_arena(ar: &SafetensorsArchive, layer: usize, mat: &str) -> Re /// 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> { +pub fn expert_arena_gemv_f16(a: &ExpertArena, ids: &DeviceBuf, slot: i32, x: &DeviceBuf, y: &DeviceBuf, y_offset: i64) -> 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) + 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, y_offset) } 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) + 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, y_offset) } } @@ -433,7 +433,7 @@ mod tests { 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(); + expert_arena_gemv_f16(&arena, &dids, slot as i32, &dx16, &yi, 0).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(); diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index 442bdd3..fe7bed4 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -808,22 +808,22 @@ __global__ void __launch_bounds__(256) k_nvfp4_gemv_f16_indirect( const int* __restrict__ ids, int slot, const uint16_t* __restrict__ x, float* __restrict__ y, int N, int K, - long w_stride, long sc_stride) { + long w_stride, long sc_stride, long y_offset) { const int id = ids[slot]; nvfp4_gemv_f16_body(arena_packed + (long)id * w_stride, arena_scales + (long)id * sc_stride, - outer_arena[id], x, y, N, K); + outer_arena[id], x, y + y_offset, N, K); } extern "C" int vetta_nvfp4_gemv_f16_indirect(const uint8_t* arena_packed, const uint8_t* arena_scales, const float* outer_arena, const int* ids, int slot, const uint16_t* x, float* y, - int N, int K, long w_stride, long sc_stride, + int N, int K, long w_stride, long sc_stride, long y_offset, vetta_stream_t stream) { if (N <= 0 || K <= 0 || (K % 16) != 0 || slot < 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_nvfp4_gemv_f16_indirect<<<(N + 7) / 8, 256, 0, s>>>( - arena_packed, arena_scales, outer_arena, ids, slot, x, y, N, K, w_stride, sc_stride); + arena_packed, arena_scales, outer_arena, ids, slot, x, y, N, K, w_stride, sc_stride, y_offset); HIP_CHECK(hipGetLastError()); return 0; } @@ -932,19 +932,19 @@ __global__ void k_mxfp8_gemv_f16_indirect(const uint8_t* __restrict__ arena_weig 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) { + int N, int K, long w_stride, long sc_stride, long y_offset) { 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); + arena_scales + (long)id * sc_stride, x, y + y_offset, 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) { + long w_stride, long sc_stride, long y_offset, 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); + k_mxfp8_gemv_f16_indirect<<>>(arena_weights, arena_scales, ids, slot, x, y, N, K, w_stride, sc_stride, y_offset); HIP_CHECK(hipGetLastError()); return 0; }