[LD] REAL MoE block end-to-end on Inkling weights — verified kernels compose
- real_moe_block_end_to_end test: the MoE half of a real Inkling layer runs end-to-end on real layer-0 weights, composing the verified kernels: mlp_norm (rms_norm) -> cast f32->bf16 -> router GEMM (gate.weight [128,2304] BF16) -> sigmoid top-8 router (gate.bias, route_scale=8) -> 8 real NVFP4 experts (w13 GEMV -> SiTU beta4/lb25 -> w2 GEMV, outer=amax/denominator) -> weighted reduce. - Parity vs a FULL CPU oracle (rms_norm + bf16-truncate cast + BF16 router GEMM + sigmoid top-8 + per-expert NVFP4 dequant GEMV + SiTU + reduce): router ids match exactly ([31,124,0,7,69,121,14,2]), output max_rel_err 5.6e-4. - This is the integration milestone: the individually-verified kernels compose into a correct real MoE block on real data, with the bf16 cast boundary handled explicitly (the dtype-mismatch bug class). The MoE half of a real Inkling layer now runs correctly; the attention half is next. Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS; lean proofs (4 files, 42 theorems) green; real MoE block PASS (--features hip, --ignored).
This commit is contained in:
1 parent
61c0b21a93
commit
a5ee804641
1 file changed
+143
@@ -202,4 +202,147 @@ mod tests {
|
||||
// partial sums + block reduction vs CPU sequential); math is identical.
|
||||
assert!(max_rel < 1e-3, "real expert NVFP4 parity failed: {max_rel}");
|
||||
}
|
||||
|
||||
fn bf16_trunc(x: f32) -> f32 { f32::from_bits(x.to_bits() & 0xFFFF0000) }
|
||||
fn rms_norm_cpu(x: &[f32], w: &[f32], eps: f32) -> Vec<f32> {
|
||||
let d = x.len();
|
||||
let ss: f32 = x.iter().map(|v| v * v).sum();
|
||||
let ir = 1.0 / (ss / d as f32 + eps).sqrt();
|
||||
x.iter().zip(w).map(|(v, wv)| v * ir * wv).collect()
|
||||
}
|
||||
fn situ_cpu(gu: &[f32], inter: usize, beta: f32, lb: f32) -> Vec<f32> {
|
||||
(0..inter).map(|j| {
|
||||
let g = gu[j]; let u = gu[inter + j];
|
||||
let ga = beta * (g / beta).tanh() * (1.0 / (1.0 + (-g).exp()));
|
||||
let ua = lb * (u / lb).tanh();
|
||||
ga * ua
|
||||
}).collect()
|
||||
}
|
||||
// CPU NVFP4 dequant GEMV over real per-expert bytes: y[n] = dequant(W)[n,k] @ x[k].
|
||||
fn nvfp4_gemv_cpu(ar: &SafetensorsArchive, layer: usize, e: usize, mat: &str, x: &[f32], n: usize, k: usize, outer: f32) -> Vec<f32> {
|
||||
let base = format!("model.llm.layers.{layer}.mlp.experts.{mat}");
|
||||
let w_per_e = n * (k / 2);
|
||||
let s_per_e = n * (k / 16);
|
||||
let mut wb = vec![0u8; w_per_e];
|
||||
ar.read_slice(&format!("{base}_weight"), (e * w_per_e) as u64, &mut wb).unwrap();
|
||||
let mut sb = vec![0u8; s_per_e];
|
||||
ar.read_slice(&format!("{base}_weight_scale"), (e * s_per_e) as u64, &mut sb).unwrap();
|
||||
let mut y = vec![0f32; n];
|
||||
for ni in 0..n {
|
||||
let mut acc = 0f32;
|
||||
for b in 0..k / 16 {
|
||||
let sc = e4m3(sb[ni * (k / 16) + b]) * outer;
|
||||
for j in 0..8 {
|
||||
let byte = wb[ni * (k / 2) + b * 8 + j];
|
||||
acc += x[b * 16 + j * 2] * (e2m1(byte & 15) * sc) + x[b * 16 + j * 2 + 1] * (e2m1(byte >> 4) * sc);
|
||||
}
|
||||
}
|
||||
y[ni] = acc;
|
||||
}
|
||||
y
|
||||
}
|
||||
fn expert_outer(ar: &SafetensorsArchive, layer: usize, e: usize, mat: &str) -> f32 {
|
||||
let base = format!("model.llm.layers.{layer}.mlp.experts.{mat}");
|
||||
let mut ab = [0u8; 4];
|
||||
ar.read_slice(&format!("{base}_weight_amax"), (e * 4) as u64, &mut ab).unwrap();
|
||||
let amax = f32::from_le_bytes(ab);
|
||||
let dname = format!("{base}_weight_outer_scale_denominator");
|
||||
let den = if ar.tensors.contains_key(&dname) {
|
||||
let mut db = [0u8; 4]; ar.read_slice(&dname, 0, &mut db).unwrap();
|
||||
let d = f32::from_le_bytes(db); if d == 0.0 { 2688.0 } else { d }
|
||||
} else { 2688.0 };
|
||||
amax / den
|
||||
}
|
||||
|
||||
/// REAL MoE BLOCK end-to-end on real Inkling layer-0 weights: mlp_norm ->
|
||||
/// router (gate GEMM + sigmoid top-8) -> 8 real NVFP4 experts (w13 GEMV ->
|
||||
/// SiTU -> w2 GEMV) -> weighted reduce. Composes the verified kernels on
|
||||
/// real data, parity-checked against a full CPU oracle (incl. the bf16 cast
|
||||
/// at the router GEMM boundary).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn real_moe_block_end_to_end() {
|
||||
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
|
||||
let (hidden, inter, n_experts, top_k) = (2304usize, 1152usize, 128usize, 8usize);
|
||||
let route_scale = 8.0f32;
|
||||
let (beta, lb) = (4.0f32, 25.0f32);
|
||||
let eps = 1e-6f32;
|
||||
let x: Vec<f32> = (0..hidden).map(|i| ((i % 53) as f32 - 26.0) * 0.02).collect();
|
||||
|
||||
// --- GPU weights ---
|
||||
let mlp_norm = load_bf16_as_f32(&ar, "model.llm.layers.0.mlp_norm.weight").unwrap();
|
||||
let gate_w = load_raw(&ar, "model.llm.layers.0.mlp.gate.weight").unwrap();
|
||||
let gate_b = load_raw(&ar, "model.llm.layers.0.mlp.gate.bias").unwrap();
|
||||
|
||||
let dx = DeviceBuf::alloc(hidden * 4).unwrap(); dx.h2d(&x).unwrap();
|
||||
let normed = DeviceBuf::alloc(hidden * 4).unwrap();
|
||||
let normed_bf = DeviceBuf::alloc(hidden * 2).unwrap();
|
||||
let logits = DeviceBuf::alloc(n_experts * 4).unwrap();
|
||||
let ids = DeviceBuf::alloc(top_k * 4).unwrap();
|
||||
let weights = DeviceBuf::alloc(top_k * 4).unwrap();
|
||||
let gu = DeviceBuf::alloc(2 * inter * 4).unwrap();
|
||||
let act = DeviceBuf::alloc(inter * 4).unwrap();
|
||||
let moe_out = DeviceBuf::alloc(hidden * 4).unwrap();
|
||||
|
||||
vetta_infer_hip::rms_norm_f32(&dx, Some(&mlp_norm), &normed, 1, hidden as i32, eps).unwrap();
|
||||
vetta_infer_hip::cast_f32_bf16(&normed, &normed_bf, hidden).unwrap();
|
||||
vetta_infer_hip::gemm_bf16(&normed_bf, &gate_w, &logits, 1, n_experts as i32, hidden as i32).unwrap();
|
||||
vetta_infer_hip::moe_router_topk(&logits, Some(&gate_b), &ids, &weights, 1, n_experts as i32, top_k as i32, route_scale).unwrap();
|
||||
let ids_host = {
|
||||
let mut b = vec![0u8; top_k * 4]; ids.d2h_bytes(&mut b).unwrap();
|
||||
b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::<Vec<_>>()
|
||||
};
|
||||
let mut y_part_host = vec![0f32; top_k * hidden];
|
||||
for kk in 0..top_k {
|
||||
let e = ids_host[kk] as usize;
|
||||
let w13 = load_expert_matrix(&ar, 0, e, "w13").unwrap();
|
||||
vetta_infer_hip::nvfp4_gemv(&w13.packed, &w13.scales, w13.outer, &normed, &gu, w13.n, w13.k).unwrap();
|
||||
vetta_infer_hip::situ(&gu, &act, inter as i32, beta, lb).unwrap();
|
||||
let w2 = load_expert_matrix(&ar, 0, e, "w2").unwrap();
|
||||
let ye = DeviceBuf::alloc(hidden * 4).unwrap();
|
||||
vetta_infer_hip::nvfp4_gemv(&w2.packed, &w2.scales, w2.outer, &act, &ye, w2.n, w2.k).unwrap();
|
||||
ye.d2h(&mut y_part_host[kk * hidden..(kk + 1) * hidden]).unwrap();
|
||||
}
|
||||
let y_part = DeviceBuf::alloc(top_k * hidden * 4).unwrap(); y_part.h2d(&y_part_host).unwrap();
|
||||
vetta_infer_hip::moe_reduce(&y_part, &weights, &moe_out, top_k as i32, hidden as i32).unwrap();
|
||||
let mut got = vec![0f32; hidden]; moe_out.d2h(&mut got).unwrap();
|
||||
|
||||
// --- CPU oracle ---
|
||||
let mut nb = vec![0u8; hidden * 2]; ar.read_slice("model.llm.layers.0.mlp_norm.weight", 0, &mut nb).unwrap();
|
||||
let mlp_norm_f: Vec<f32> = nb.chunks_exact(2).map(|c| bf16_to_f32(u16::from_le_bytes([c[0], c[1]]))).collect();
|
||||
let normed_cpu = rms_norm_cpu(&x, &mlp_norm_f, eps);
|
||||
let normed_bf_cpu: Vec<f32> = normed_cpu.iter().map(|&v| bf16_trunc(v)).collect();
|
||||
let mut gw = vec![0u8; n_experts * hidden * 2]; ar.read_slice("model.llm.layers.0.mlp.gate.weight", 0, &mut gw).unwrap();
|
||||
let gate_w_f: Vec<f32> = gw.chunks_exact(2).map(|c| bf16_to_f32(u16::from_le_bytes([c[0], c[1]]))).collect();
|
||||
let logits_cpu: Vec<f32> = (0..n_experts).map(|n| (0..hidden).map(|k| normed_bf_cpu[k] * gate_w_f[n * hidden + k]).sum()).collect();
|
||||
let mut gb = vec![0u8; n_experts * 4]; ar.read_slice("model.llm.layers.0.mlp.gate.bias", 0, &mut gb).unwrap();
|
||||
let bias_cpu: Vec<f32> = gb.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
|
||||
let prob: Vec<f32> = logits_cpu.iter().map(|&l| 1.0 / (1.0 + (-l).exp())).collect();
|
||||
let mut score: Vec<f32> = (0..n_experts).map(|e| prob[e] + bias_cpu[e]).collect();
|
||||
let mut ids_cpu = vec![0usize; top_k];
|
||||
let mut w_cpu = vec![0f32; top_k];
|
||||
let mut wsum = 0f32;
|
||||
for kk in 0..top_k {
|
||||
let mut bv = f32::NEG_INFINITY; let mut bi = 0usize;
|
||||
for e in 0..n_experts { if score[e] > bv { bv = score[e]; bi = e; } }
|
||||
ids_cpu[kk] = bi; w_cpu[kk] = prob[bi]; wsum += prob[bi]; score[bi] = -1e30;
|
||||
}
|
||||
let inv = route_scale / (wsum + 1e-20);
|
||||
for kk in 0..top_k { w_cpu[kk] *= inv; }
|
||||
assert_eq!(ids_host.iter().map(|&i| i as usize).collect::<Vec<_>>(), ids_cpu, "router ids must match");
|
||||
let mut want = vec![0f32; hidden];
|
||||
for kk in 0..top_k {
|
||||
let e = ids_cpu[kk];
|
||||
let o13 = expert_outer(&ar, 0, e, "w13");
|
||||
let gu_cpu = nvfp4_gemv_cpu(&ar, 0, e, "w13", &normed_cpu, 2 * inter, hidden, o13);
|
||||
let act_cpu = situ_cpu(&gu_cpu, inter, beta, lb);
|
||||
let o2 = expert_outer(&ar, 0, e, "w2");
|
||||
let ye_cpu = nvfp4_gemv_cpu(&ar, 0, e, "w2", &act_cpu, hidden, inter, o2);
|
||||
for d in 0..hidden { want[d] += w_cpu[kk] * ye_cpu[d]; }
|
||||
}
|
||||
let mut max_rel = 0f32;
|
||||
for (g, w) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); }
|
||||
eprintln!("REAL MoE block end-to-end: experts={:?} max_rel_err={max_rel:.3e}", ids_cpu);
|
||||
assert!(max_rel < 2e-3, "real MoE block parity failed: {max_rel}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user