diff --git a/crates/vetta-infer-ld/src/layer.rs b/crates/vetta-infer-ld/src/layer.rs index a3a2130..1995646 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_arena_gemv_f16, expert_gemv, expert_gemv_f16, load_bf16_as_f32, load_expert_arena, load_expert_matrix, load_raw, ExpertArena, ExpertMatrix}; +use crate::packer::{expert_arena_gemv_f16, expert_arena_grouped_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; @@ -635,6 +635,50 @@ fn moe_device( Ok(moeout) } +/// Batched device-resident MoE (M=B prefill): bucket CSR -> grouped w13 GEMM -> +/// SiTU batched -> grouped w2 GEMM -> reduce_buckets_masked. All device-side, no +/// host ids/output round-trip. `mlpin` [B,h] f32 (cast to f16 internally, exact +/// strata B=1 path); `ids`/`weights` [B*top_k] device (from batched router). +/// Returns moeout [B,h]. w2 reads SiTU output in bucket order via an identity index. +#[allow(dead_code)] // wired by the batched layer forward (next brick) +fn moe_batched( + cache: &WeightCache, ip: usize, mlpin: &DeviceBuf, ids: &DeviceBuf, weights: &DeviceBuf, d: &Dims, h: usize, b: i32, +) -> Result { + let t0 = std::time::Instant::now(); + let w13 = cache.expert_arena(ip, "w13")?; + let w2 = cache.expert_arena(ip, "w2")?; + let top_k = d.top_k; + let inter = d.inter; + let total = (b as usize) * top_k; + let mlpin16 = DeviceBuf::alloc((b as usize) * h * 2)?; + vetta_infer_hip::cast_f32_f16(mlpin, &mlpin16, (b as usize) * h)?; + // Bucket CSR (device-side). + let dcnt = DeviceBuf::alloc(129 * 4)?; dcnt.h2d_bytes(&vec![0u8; 129 * 4])?; + let doff = DeviceBuf::alloc(129 * 4)?; + let dcur = DeviceBuf::alloc(128 * 4)?; + let dbtk = DeviceBuf::alloc(total * 4)?; + let ds2b = DeviceBuf::alloc(total * 4)?; + vetta_infer_hip::moe_count_buckets(ids, &dcnt, total as i32)?; + vetta_infer_hip::moe_prefix_buckets(&dcnt, &doff, &dcur)?; + vetta_infer_hip::moe_scatter_buckets(ids, &dcur, &dbtk, &ds2b, total as i32, top_k as i32)?; + // w13 grouped GEMM: gather input tokens via bucket_tok -> gu [total, 2*inter]. + let gu = DeviceBuf::alloc(total * 2 * inter * 4)?; + expert_arena_grouped_gemv_f16(&w13, &doff, &dbtk, &mlpin16, &gu)?; + let act16 = DeviceBuf::alloc(total * inter * 2)?; + vetta_infer_hip::situ_f16_batched(&gu, &act16, inter as i32, d.beta, d.lb, total as i32)?; + // w2 grouped GEMM: SiTU output is already bucket-ordered -> identity index. + let idx: Vec = (0..total as i32).collect(); + let idx_bytes: Vec = idx.iter().flat_map(|x| x.to_le_bytes()).collect(); + let didx = DeviceBuf::alloc(total * 4)?; didx.h2d_bytes(&idx_bytes)?; + let y_part = DeviceBuf::alloc(total * h * 4)?; + expert_arena_grouped_gemv_f16(&w2, &doff, &didx, &act16, &y_part)?; + // Scatter-back + weighted reduce per token. + let moeout = DeviceBuf::alloc((b as usize) * h * 4)?; + vetta_infer_hip::moe_reduce_buckets_masked(&y_part, &ds2b, weights, &moeout, b, 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( @@ -1117,4 +1161,45 @@ mod tests { eprintln!("prompt={prompt:?} -> generated={text:?} (tokens={generated:?})"); assert!(!generated.is_empty()); } + + /// Batched MoE (moe_batched, M=B) vs per-token device MoE (moe_device) on REAL + /// weights, layer 0 (NVFP4) + layer 20 (MXFP8). Same router ids/weights fed to + /// both, so the only difference is GEMM accumulation order (grouped MT tiling + /// vs wave-per-row). Verifies the batched MoE composition is correct. + #[test] + #[ignore] + fn moe_batched_parity_vs_device() { + let ar = Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap()); + let cache = WeightCache::new(ar.clone()); + let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; + let h = d.hidden; let b = 8usize; let top_k = d.top_k; + for &ip in &[0usize, 20usize] { + let w = cache.swa_layer(ip).unwrap(); + let mlpin_h: Vec = (0..b * h).map(|i| ((i % 37) as f32 - 18.0) * 0.02).collect(); + let mlpin = DeviceBuf::alloc(b * h * 4).unwrap(); mlpin.h2d(&mlpin_h).unwrap(); + let rlog = DeviceBuf::alloc(b * d.n_experts * 4).unwrap(); + vetta_infer_hip::router_gemv_batched(&mlpin, &w.gate_w, &rlog, d.n_experts as i32, h as i32, b as i32).unwrap(); + let ids = DeviceBuf::alloc(b * top_k * 4).unwrap(); + let weights = DeviceBuf::alloc(b * top_k * 4).unwrap(); + vetta_infer_hip::moe_router_topk(&rlog, Some(&w.gate_b), &ids, &weights, b as i32, d.n_experts as i32, top_k as i32, d.route_scale).unwrap(); + let moeout_b = moe_batched(&cache, ip, &mlpin, &ids, &weights, &d, h, b as i32).unwrap(); + let mut ob = vec![0f32; b * h]; moeout_b.d2h(&mut ob).unwrap(); + let mut ids_b = vec![0u8; b * top_k * 4]; ids.d2h_bytes(&mut ids_b).unwrap(); + let ids_h: Vec = ids_b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect(); + let mut weights_h = vec![0f32; b * top_k]; weights.d2h(&mut weights_h).unwrap(); + let mut max_rel = 0f32; + for m in 0..b { + let mlpin_m = DeviceBuf::alloc(h * 4).unwrap(); mlpin_m.h2d(&mlpin_h[m * h..(m + 1) * h]).unwrap(); + let ids_m = DeviceBuf::alloc(top_k * 4).unwrap(); + let idb: Vec = ids_h[m * top_k..(m + 1) * top_k].iter().flat_map(|x| x.to_le_bytes()).collect(); + ids_m.h2d_bytes(&idb).unwrap(); + let weights_m = DeviceBuf::alloc(top_k * 4).unwrap(); weights_m.h2d(&weights_h[m * top_k..(m + 1) * top_k]).unwrap(); + let moeout_s = moe_device(&cache, ip, &mlpin_m, &ids_m, &weights_m, &d, h).unwrap(); + let mut os = vec![0f32; h]; moeout_s.d2h(&mut os).unwrap(); + for j in 0..h { max_rel = max_rel.max((ob[m * h + j] - os[j]).abs() / os[j].abs().max(1e-3)); } + } + eprintln!("moe_batched ip={ip} B={b} max_rel_err={max_rel:.3e}"); + assert!(max_rel < 3e-3, "batched MoE parity failed at ip={ip}: {max_rel}"); + } + } } \ No newline at end of file diff --git a/crates/vetta-infer-ld/src/packer.rs b/crates/vetta-infer-ld/src/packer.rs index 3a30df0..8eb7523 100644 --- a/crates/vetta-infer-ld/src/packer.rs +++ b/crates/vetta-infer-ld/src/packer.rs @@ -198,6 +198,18 @@ pub fn expert_arena_gemv_f16(a: &ExpertArena, ids: &DeviceBuf, slot: i32, x: &De } } +/// Grouped (batched) expert GEMM from an arena: one launch over all experts, +/// expert eid processes its bucket tokens [exp_off[eid],exp_off[eid+1]) indexed +/// by `bucket_tok`. X [B,K] f16 (gathered) or [total,K] f16 (bucket order, pass an +/// identity index). Y [total_pairs,N] f32 in bucket order. Dispatches NVFP4/MXFP8. +pub fn expert_arena_grouped_gemv_f16(a: &ExpertArena, exp_off: &DeviceBuf, bucket_tok: &DeviceBuf, x: &DeviceBuf, y: &DeviceBuf) -> Result<(), String> { + if a.mxfp8 { + vetta_infer_hip::mxfp8_grouped_gemv_f16(&a.packed, &a.scales, exp_off, bucket_tok, x, y, a.n, a.k, a.n_exp as i32, a.w_stride, a.sc_stride) + } else { + vetta_infer_hip::nvfp4_grouped_gemv_f16(&a.packed, &a.scales, &a.outer, exp_off, bucket_tok, x, y, a.n, a.k, a.n_exp as i32, a.w_stride, a.sc_stride) + } +} + #[cfg(test)] mod tests { use super::*;