[LD][HIP] Contiguous expert arena + device-routed MXFP8/NVFP4 GEMV (graph-capturable MoE foundation)

ExpertArena loads a whole layer expert tensor in ONE contiguous device buffer
(the safetensors already store [n_exp,N,K/2] NVFP4 / [n_exp,N,K] MXFP8), with a
per-expert outer_scale array. The indirect GEMV indexes expert id from a DEVICE
buffer (ids[slot]) => static launch params, no host ids round-trip.

Add MXFP8 f16 indirect kernel (mirrors NVFP4: shared device body + direct +
indirect wrappers). expert_arena_gemv_f16 dispatches NVFP4/MXFP8.

Parity on REAL weights: arena-indirect BIT-EXACT vs per-expert direct for layer 0
(NVFP4) and layer 20 (MXFP8), 4 routed experts each. Additive — forward default
unchanged (wiring into the device-resident MoE path is the next brick).

Verified: ld GPU 19 + hip GPU 19 green, workspace CPU -D warnings green, 6 Lean
proofs 0 sorryAx.
This commit is contained in:
adm committed 2026-12-01 22:39:39 +01:00
1 parent 4c82040610
commit 752edeaade
3 files changed
+151 -1

No files matched your search

+106
View File
@@ -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<ExpertArena, String> {
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<f32> = 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<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 ids_vec: Vec<i32> = vec![0, 1, 5, 127];
let ids_bytes: Vec<u8> = 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<f32> {
let d = x.len();