[LD][HIP] Device-resident MoE path (opt-in VETTA_DEVICE_MOE): no host ids/output round-trip

moe_device runs the whole MoE on device: router ids/weights stay on device, the
arena indirect GEMV selects experts on device, per-expert outputs accumulate in a
device y_part via a STATIC y_offset=kk*hidden (added to both indirect kernels).
No ids D2H, no per-expert output D2H/H2D => the MoE block is now graph-capturable.

WeightCache gains a memoized expert_arena(ip,mat) accessor. Both SWA and full-attn
MoE blocks dispatch to moe_device under VETTA_DEVICE_MOE=1; the default f32 host
path is unchanged (parity baseline preserved).

Parity: 16/16 greedy tokens IDENTICAL between VETTA_DEVICE_MOE=1 and the
VETTA_F16_EXPERT=1 host path (same kernels/data). Arena indirect bit-exact vs
direct on real weights (NVFP4 layer 0 + MXFP8 layer 20).

Verified: ld GPU 19 + hip GPU 19 green, workspace CPU -D warnings green, 6 Lean
proofs 0 sorryAx. Next: device-resident depth-block/bank machinery, then HIP graph
capture of the decode step.
This commit is contained in:
adm committed 2026-12-01 22:43:47 +01:00
1 parent 752edeaade
commit 0914fae8c8
4 files changed
+87 -34

No files matched your search

+68 -15
View File
@@ -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<HashMap<usize, Arc<LayerWeights>>>,
full: RefCell<HashMap<usize, Arc<FullLayerWeights>>>,
experts: RefCell<HashMap<(usize, usize, String), Arc<ExpertMatrix>>>,
arenas: RefCell<HashMap<(usize, String), Arc<ExpertArena>>>,
ctrl: RefCell<HashMap<usize, Arc<ControllerWeights>>>,
}
@@ -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<Arc<ExpertArena>, 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<Arc<ControllerWeights>, 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::<Vec<_>>() };
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::<Vec<_>>() };
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<DeviceBuf, String> {
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::<Vec<_>>() };
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::<Vec<_>>() };
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)?;