[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:
1 parent
4c82040610
commit
752edeaade
3 files changed
+151
-1
No files matched your search
@@ -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> {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<<<N, 256, 0, s>>>(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) {
|
||||
|
||||
Reference in new issue
Block a user