Files
vetta-infer/crates/vetta-infer-ld/src/packer.rs
T
adm 48de65d395 [LD] moe_batched: end-to-end batched MoE (M=B) verified BIT-EXACT on real weights
Composes the landed batched kernels into the full prefill MoE: cast f32->f16 ->
bucket CSR (count/prefix/scatter) -> grouped w13 GEMM (gather tokens via bucket_tok)
-> SiTU batched -> grouped w2 GEMM (SiTU output bucket-ordered, identity index) ->
reduce_buckets_masked (scatter-back + weighted reduce). All device-side, no host
ids/output round-trip. expert_arena_grouped_gemv_f16 helper dispatches NVFP4/MXFP8.

Parity vs per-token moe_device on REAL weights: layer 0 (NVFP4) + layer 20 (MXFP8),
B=8, same router ids/weights => max_rel 0.0 BIT-EXACT both formats.

moe_batched marked allow(dead_code) until the batched layer forward wires it (next
brick). Additive — decode default unchanged.

Verified: hip GPU 31, ld GPU 20, workspace CPU -D warnings green, 6 Lean 0 sorryAx.
2026-12-01 23:58:52 +01:00

1189 lines
77 KiB
Rust

//! GPU weight packer (feature `hip`): load real `.safetensors` tensors into
//! device buffers, the bridge from the canonical IR to GPU-resident weights.
//! This is where the per-layer loading/precision policy will be applied
//! (engine-side model composition); today it loads the trunk for the first
//! real-weight GPU run.
use crate::SafetensorsArchive;
use vetta_infer_hip::DeviceBuf;
/// Load a tensor's raw bytes into a device buffer (dtype preserved).
pub fn load_raw(ar: &SafetensorsArchive, name: &str) -> Result<DeviceBuf, String> {
let info = ar.tensors.get(name).ok_or_else(|| format!("tensor not found: {name}"))?;
let bytes = info.byte_len() as usize;
let mut host = vec![0u8; bytes];
ar.read_slice(name, 0, &mut host)?;
let buf = DeviceBuf::alloc(bytes)?;
buf.h2d_bytes(&host)?;
Ok(buf)
}
fn bf16_to_f32(h: u16) -> f32 { f32::from_bits((h as u32) << 16) }
/// Load a BF16 tensor converted to f32 (e.g. norm weights for the f32 rms_norm
/// kernel — the reference upcasts BF16 norms to f32 at load).
pub fn load_bf16_as_f32(ar: &SafetensorsArchive, name: &str) -> Result<DeviceBuf, String> {
let info = ar.tensors.get(name).ok_or_else(|| format!("tensor not found: {name}"))?;
if info.dtype != "BF16" { return Err(format!("{name}: expected BF16, got {}", info.dtype)); }
let bytes = info.byte_len() as usize;
let mut host = vec![0u8; bytes];
ar.read_slice(name, 0, &mut host)?;
let f: Vec<f32> = host.chunks_exact(2).map(|c| bf16_to_f32(u16::from_le_bytes([c[0], c[1]]))).collect();
let buf = DeviceBuf::alloc(f.len() * 4)?;
buf.h2d(&f)?;
Ok(buf)
}
/// One NVFP4 expert matrix resident on device: packed E2M1 [N,K/2], E4M3 group
/// scales [N,K/16], and outer_scale = amax[e] / denominator (default 2688 =
/// 448*6 when the denominator tensor is absent — exact strata semantics).
pub struct ExpertMatrix {
pub packed: DeviceBuf,
pub scales: DeviceBuf,
pub outer: f32,
pub n: i32,
pub k: i32,
pub mxfp8: bool,
}
/// Load expert `e` of layer `layer`, matrix `mat` ("w13" or "w2"), from the
/// real safetensors archive. Zero requantization: bytes go to device as-is.
/// Layers 0..19 are NVFP4 (E2M1 + E4M3/16 + outer=amax/denom); layers 20..23
/// are MXFP8 (E4M3 + UE8M0/32, no outer). Detected by the amax tensor presence.
pub fn load_expert_matrix(ar: &SafetensorsArchive, layer: usize, e: usize, mat: &str) -> Result<ExpertMatrix, 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 _sinfo = ar.tensors.get(&sname).ok_or_else(|| format!("missing {sname}"))?;
let n = winfo.shape[1] as i32;
if !ar.tensors.contains_key(&aname) {
// MXFP8: w [n_exp, N, K] full, scale [n_exp, N, K/32], no outer.
let k = winfo.shape[2] as i32;
let w_per_e = (n as usize) * (k as usize);
let s_per_e = (n as usize) * (k as usize / 32);
let mut wbytes = vec![0u8; w_per_e];
ar.read_slice(&wname, (e * w_per_e) as u64, &mut wbytes)?;
let mut sbytes = vec![0u8; s_per_e];
ar.read_slice(&sname, (e * s_per_e) as u64, &mut sbytes)?;
let packed = DeviceBuf::alloc(w_per_e)?; packed.h2d_bytes(&wbytes)?;
let scales = DeviceBuf::alloc(s_per_e)?; scales.h2d_bytes(&sbytes)?;
return Ok(ExpertMatrix { packed, scales, outer: 1.0, n, k, mxfp8: true });
}
// NVFP4: w shape [n_exp, N, K/2]; scale [n_exp, N, K/16].
let k_half = winfo.shape[2] as usize;
let k = (k_half * 2) as i32;
let w_per_e = (n as usize) * k_half;
let s_per_e = (n as usize) * (k as usize / 16);
let mut wbytes = vec![0u8; w_per_e];
ar.read_slice(&wname, (e * w_per_e) as u64, &mut wbytes)?;
let mut sbytes = vec![0u8; s_per_e];
ar.read_slice(&sname, (e * s_per_e) as u64, &mut sbytes)?;
let mut amax_b = [0u8; 4];
ar.read_slice(&aname, (e * 4) as u64, &mut amax_b)?;
let amax = f32::from_le_bytes(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
};
let outer = amax / den;
let packed = DeviceBuf::alloc(w_per_e)?;
packed.h2d_bytes(&wbytes)?;
let scales = DeviceBuf::alloc(s_per_e)?;
scales.h2d_bytes(&sbytes)?;
Ok(ExpertMatrix { packed, scales, outer, n, k, mxfp8: false })
}
/// Run the expert GEMV dispatching on the quantization format (NVFP4 / MXFP8).
pub fn expert_gemv(em: &ExpertMatrix, x: &DeviceBuf, y: &DeviceBuf) -> Result<(), String> {
if em.mxfp8 {
vetta_infer_hip::mxfp8_gemv(&em.packed, &em.scales, x, y, em.n, em.k)
} else {
vetta_infer_hip::nvfp4_gemv(&em.packed, &em.scales, em.outer, x, y, em.n, em.k)
}
}
/// FP16-activation expert GEMV (exact strata B=1 path: x is FP16 mlpf16/act).
pub fn expert_gemv_f16(em: &ExpertMatrix, x: &DeviceBuf, y: &DeviceBuf) -> Result<(), String> {
if em.mxfp8 {
vetta_infer_hip::mxfp8_gemv_f16(&em.packed, &em.scales, x, y, em.n, em.k)
} else {
vetta_infer_hip::nvfp4_gemv_f16(&em.packed, &em.scales, em.outer, x, y, em.n, em.k)
}
}
/// 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, y_offset: i64) -> 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, y_offset)
} 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, y_offset)
}
}
/// 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::*;
use vetta_infer_abi::vplan::VplanOp;
use vetta_infer_rt::executor::{execute, ExecOp, OpParams};
/// FIRST REAL-WEIGHT GPU RUN: load the real Inkling trunk weights and run
/// embed -> embed_norm -> final_norm -> cast -> unembed on GPU, producing
/// real logits over vocab 201024 and an argmax token. Trunk-only (skip-layer
/// baseline) — proves packer + executor + sampling on real data; the full
/// layered forward + Inkling parity refinements come next.
#[test]
#[ignore] // requires GPU + --features hip + /mnt/models/Inkling
fn trunk_run_real_weights() {
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
let hidden = 2304usize;
let vocab = 201024usize;
let token_id = 100i32;
let embed = load_raw(&ar, "model.llm.embed.weight").unwrap();
let embed_norm = load_bf16_as_f32(&ar, "model.llm.embed_norm.weight").unwrap();
let final_norm = load_bf16_as_f32(&ar, "model.llm.norm.weight").unwrap();
let unembed = load_raw(&ar, "model.llm.unembed.weight").unwrap();
let tokens = DeviceBuf::alloc(4).unwrap();
tokens.h2d_bytes(&token_id.to_le_bytes()).unwrap();
let residual = DeviceBuf::alloc(hidden * 4).unwrap();
let norm1 = DeviceBuf::alloc(hidden * 4).unwrap();
let norm2 = DeviceBuf::alloc(hidden * 4).unwrap();
let normbf = DeviceBuf::alloc(hidden * 2).unwrap();
let logits = DeviceBuf::alloc(vocab * 4).unwrap();
// 0 embed, 1 tokens, 2 embed_norm, 3 final_norm, 4 unembed,
// 5 residual, 6 norm1, 7 norm2, 8 normbf, 9 logits.
let buffers = vec![embed, tokens, embed_norm, final_norm, unembed, residual, norm1, norm2, normbf, logits];
let ops = vec![
ExecOp { op: VplanOp::EmbedBf16, reads: vec![0, 1], writes: vec![5], params: OpParams::Embed { b: 1, d: hidden as i32, vocab: vocab as i32 } },
ExecOp { op: VplanOp::RmsNorm, reads: vec![5, 2], writes: vec![6], params: OpParams::RmsNorm { rows: 1, d: hidden as i32, eps: 1e-6 } },
ExecOp { op: VplanOp::RmsNorm, reads: vec![6, 3], writes: vec![7], params: OpParams::RmsNorm { rows: 1, d: hidden as i32, eps: 1e-6 } },
ExecOp { op: VplanOp::CastF32Bf16, reads: vec![7], writes: vec![8], params: OpParams::Cast { n: hidden } },
ExecOp { op: VplanOp::GemmBf16, reads: vec![8, 4], writes: vec![9], params: OpParams::Gemm { m: 1, n: vocab as i32, k: hidden as i32 } },
];
execute(&buffers, &ops).unwrap();
let mut lg = vec![0f32; vocab];
buffers[9].d2h(&mut lg).unwrap();
assert!(lg.iter().all(|v| v.is_finite()), "logits must be finite");
let mut idx: Vec<usize> = (0..vocab).collect();
idx.sort_by(|&a, &b| lg[b].partial_cmp(&lg[a]).unwrap());
let top5: Vec<(usize, f32)> = idx[..5].iter().map(|&i| (i, lg[i])).collect();
eprintln!("FIRST REAL-WEIGHT GPU RUN (trunk-only): argmax token={} top5={:?}", idx[0], top5);
assert!(idx[0] < vocab);
}
fn e2m1(nib: u8) -> f32 {
const LUT: [f32; 16] = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0];
LUT[(nib & 15) as usize]
}
fn e4m3(b: u8) -> f32 {
let sign = ((b & 0x80) as u32) << 24;
let exp = (b >> 3) & 0xF;
let mant = b & 7;
if exp == 0 {
if mant == 0 { return f32::from_bits(sign); }
let val = mant as f32 / 512.0;
return if b & 0x80 != 0 { -val } else { val };
} else if exp == 15 && mant == 7 { return 0.0; }
f32::from_bits(sign | ((exp as u32 + 120) << 23) | ((mant as u32) << 20))
}
/// Real NVFP4 expert GEMV parity: load layer-0 expert-0 w13 from the real
/// archive, run nvfp4_gemv on GPU, compare to a CPU dequant oracle over the
/// real packed weights + scales + outer_scale (amax/denominator).
#[test]
#[ignore]
fn real_expert_nvfp4_gemv_parity() {
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
let em = load_expert_matrix(&ar, 0, 0, "w13").unwrap();
let (n, k) = (em.n as usize, em.k as usize);
assert_eq!((n, k), (2304, 2304));
let x: Vec<f32> = (0..k).map(|i| ((i % 41) as f32 - 20.0) * 0.02).collect();
// GPU.
let dx = DeviceBuf::alloc(k * 4).unwrap(); dx.h2d(&x).unwrap();
let dy = DeviceBuf::alloc(n * 4).unwrap();
vetta_infer_hip::nvfp4_gemv(&em.packed, &em.scales, em.outer, &dx, &dy, em.n, em.k).unwrap();
let mut got = vec![0f32; n]; dy.d2h(&mut got).unwrap();
// CPU oracle over the real bytes.
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("model.llm.layers.0.mlp.experts.w13_weight", 0, &mut wb).unwrap();
let mut sb = vec![0u8; s_per_e];
ar.read_slice("model.llm.layers.0.mlp.experts.w13_weight_scale", 0, &mut sb).unwrap();
let mut want = 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]) * em.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);
}
}
want[ni] = acc;
}
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 expert w13 NVFP4 GEMV: outer={} max_rel_err={max_rel:.3e}", em.outer);
// 1e-3: f32 accumulation-order difference over K=2304 (GPU per-group
// partial sums + block reduction vs CPU sequential); math is identical.
assert!(max_rel < 1e-3, "real expert NVFP4 parity failed: {max_rel}");
}
// FP16 -> f32 decode (for reading back the GPU cast_f32_f16 output).
fn f16_to_f32(h: u16) -> f32 {
let sign = ((h & 0x8000) as u32) << 16;
let exp = (h >> 10) & 0x1f;
let mant = (h & 0x3ff) as u32;
if exp == 0 {
if mant == 0 { return f32::from_bits(sign); }
let v = (mant as f32) * (2.0f32).powi(-24);
return if sign != 0 { -v } else { v };
}
if exp == 31 { return if mant == 0 { f32::from_bits(sign | 0x7f800000) } else { f32::NAN }; }
f32::from_bits(sign | ((exp as u32 + 112) << 23) | (mant << 13))
}
/// Real NVFP4 expert GEMV FP16-activation parity (exact strata B=1 path):
/// cast x to FP16 on GPU, run nvfp4_gemv_f16, compare to a CPU oracle over
/// the SAME fp16-rounded x with group-of-16 partial dot then scale-fma.
#[test]
#[ignore]
fn real_expert_nvfp4_gemv_f16_parity() {
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
let em = load_expert_matrix(&ar, 0, 0, "w13").unwrap();
let (n, k) = (em.n as usize, em.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 mut x16b = vec![0u8; k * 2]; dx16.d2h_bytes(&mut x16b).unwrap();
let x16: Vec<f32> = x16b.chunks_exact(2).map(|c| f16_to_f32(u16::from_le_bytes([c[0], c[1]]))).collect();
let dy = DeviceBuf::alloc(n * 4).unwrap();
vetta_infer_hip::nvfp4_gemv_f16(&em.packed, &em.scales, em.outer, &dx16, &dy, em.n, em.k).unwrap();
let mut got = vec![0f32; n]; dy.d2h(&mut got).unwrap();
let mut wb = vec![0u8; n * (k / 2)];
ar.read_slice("model.llm.layers.0.mlp.experts.w13_weight", 0, &mut wb).unwrap();
let mut sb = vec![0u8; n * (k / 16)];
ar.read_slice("model.llm.layers.0.mlp.experts.w13_weight_scale", 0, &mut sb).unwrap();
let mut want = 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]) * em.outer;
let mut d = 0f32;
for j in 0..8 {
let byte = wb[ni * (k / 2) + b * 8 + j];
d += x16[b * 16 + j * 2] * e2m1(byte & 15) + x16[b * 16 + j * 2 + 1] * e2m1(byte >> 4);
}
acc = d.mul_add(sc, acc);
}
want[ni] = acc;
}
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 expert w13 NVFP4 GEMV f16: max_rel_err={max_rel:.3e}");
// 2e-3: fp16 input rounding is identical on both sides; only the f32
// group-sum accumulation order differs (GPU strided + tree vs CPU seq).
assert!(max_rel < 2e-3, "real expert NVFP4 f16 parity failed: {max_rel}");
}
fn ue8m0(e: u8) -> f32 {
if e == 255 { return 0.0; }
if e == 0 { return f32::from_bits(0x00400000); }
f32::from_bits((e as u32) << 23)
}
/// Real MXFP8 expert GEMV parity (layers 20..23): load layer-20 expert-0
/// w13, run mxfp8_gemv on GPU, compare to a CPU dequant oracle (E4M3 weight
/// * UE8M0 scale per group of 32, no outer scale).
#[test]
#[ignore]
fn real_expert_mxfp8_gemv_parity() {
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
let em = load_expert_matrix(&ar, 20, 0, "w13").unwrap();
assert!(em.mxfp8, "layer 20 must be MXFP8");
let (n, k) = (em.n as usize, em.k as usize);
assert_eq!((n, k), (2304, 2304));
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 dy = DeviceBuf::alloc(n * 4).unwrap();
vetta_infer_hip::mxfp8_gemv(&em.packed, &em.scales, &dx, &dy, em.n, em.k).unwrap();
let mut got = vec![0f32; n]; dy.d2h(&mut got).unwrap();
let mut wb = vec![0u8; n * k];
ar.read_slice("model.llm.layers.20.mlp.experts.w13_weight", 0, &mut wb).unwrap();
let mut sb = vec![0u8; n * (k / 32)];
ar.read_slice("model.llm.layers.20.mlp.experts.w13_weight_scale", 0, &mut sb).unwrap();
let mut want = vec![0f32; n];
for ni in 0..n {
let mut acc = 0f32;
for b in 0..k / 32 {
let sc = ue8m0(sb[ni * (k / 32) + b]);
for j in 0..32 { acc += x[b * 32 + j] * e4m3(wb[ni * k + b * 32 + j]) * sc; }
}
want[ni] = acc;
}
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 expert w13 MXFP8 GEMV: max_rel_err={max_rel:.3e}");
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, 0).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();
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[2 * j]; let u = gu[2 * j + 1];
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 = std::sync::Arc::new(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);
// 5e-3: f32 accumulation-order difference (GPU per-group partial sums +
// block reduction vs CPU sequential) composed over 8 experts, amplified
// on near-zero outputs by the 1e-3 relative floor; math is identical.
assert!(max_rel < 5e-3, "real MoE block parity failed: {max_rel}");
}
fn read_bf16_f32(ar: &SafetensorsArchive, name: &str) -> Vec<f32> {
let info = ar.tensors.get(name).unwrap();
let mut b = vec![0u8; info.byte_len() as usize];
ar.read_slice(name, 0, &mut b).unwrap();
b.chunks_exact(2).map(|c| bf16_to_f32(u16::from_le_bytes([c[0], c[1]]))).collect()
}
fn proj_cpu(x_bf: &[f32], w: &[f32], n: usize, k: usize) -> Vec<f32> {
(0..n).map(|ni| (0..k).map(|kk| x_bf[kk] * w[ni * k + kk]).sum()).collect()
}
fn l2_clip_cpu(x: &[f32], scale: Option<&[f32]>, rows: usize, hd: usize, clip: f32) -> Vec<f32> {
let mut out = vec![0f32; rows * hd];
for r in 0..rows {
let v: Vec<f32> = (0..hd).map(|d| x[r * hd + d] * scale.map(|s| s[r * hd + d]).unwrap_or(1.0)).collect();
let ss: f32 = v.iter().map(|t| t * t).sum();
let fac = (clip / (ss.sqrt() + 1e-6)).min(1.0);
for d in 0..hd { out[r * hd + d] = v[d] * fac; }
}
out
}
// one static ShortConv4 step (no dyn): y = (x0 + sw0*h0+sw1*h1+sw2*h2+sw3*x0)/sqrt(5); shift ring.
fn sconv_step(x0: &[f32], sw: &[f32], hist: &mut [f32], c: usize) -> Vec<f32> {
let inv = 0.44721359549995793f32;
let mut y = vec![0f32; c];
for ch in 0..c {
let h0 = hist[ch]; let h1 = hist[c + ch]; let h2 = hist[2 * c + ch];
let w = &sw[ch * 4..ch * 4 + 4];
y[ch] = (x0[ch] + w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * x0[ch]) * inv;
}
for ch in 0..c { let h1 = hist[c + ch]; let h2 = hist[2 * c + ch]; hist[ch] = bf16_trunc(h1); hist[c + ch] = bf16_trunc(h2); hist[2 * c + ch] = bf16_trunc(x0[ch]); }
y
}
/// REAL ATTENTION BLOCK end-to-end on real Inkling layer-0 (SWA) weights:
/// attn_norm -> 6 projections (wq/wk/wv/wr/gate/sink) -> ShortConv K/V ->
/// Q/R/K L2-clip -> relpos bias -> KV store -> flash SWA GQA (window+relpos+
/// sink+gate) -> O-proj -> attn ShortConv. Run T sequential decode steps so
/// the KV cache + shortconv history grow; parity vs a full CPU oracle.
#[test]
#[ignore]
fn real_attention_block_end_to_end() {
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
let p = "model.llm.layers.0.attn";
let (hidden, n_head, n_kv, hd, d_rel, rel_extent) = (2304usize, 24usize, 8usize, 128usize, 16usize, 1024usize);
let (qk_clip, rel_clip, eps) = (22.627416997969522f32, 8.0f32, 1e-6f32);
let swa_win = 1024i32;
let steps = 3usize;
let kv_dim = n_kv * hd;
let q_dim = n_head * hd;
let scale = 1.0f32 / (hd as f32).sqrt();
// --- load real weights (device) ---
let attn_norm = load_bf16_as_f32(&ar, "model.llm.layers.0.attn_norm.weight").unwrap();
let wq = load_raw(&ar, &format!("{p}.wq_du.weight")).unwrap();
let wk = load_raw(&ar, &format!("{p}.wk_dv.weight")).unwrap();
let wv = load_raw(&ar, &format!("{p}.wv_dv.weight")).unwrap();
let wr = load_raw(&ar, &format!("{p}.wr_du.weight")).unwrap();
let wg = load_raw(&ar, &format!("{p}.gate_attn.weight")).unwrap();
let ws = load_raw(&ar, &format!("{p}.attn_sink_proj.weight")).unwrap();
let wo = load_raw(&ar, &format!("{p}.wo_ud.weight")).unwrap();
let q_sc = load_bf16_as_f32(&ar, &format!("{p}.q_l2_clip.scale")).unwrap();
let r_sc = load_bf16_as_f32(&ar, &format!("{p}.rel_l2_clip.scale")).unwrap();
let rel_proj = load_bf16_as_f32(&ar, &format!("{p}.rel_logits_proj.proj")).unwrap();
let k_sconv = load_bf16_as_f32(&ar, &format!("{p}.k_sconv.weight")).unwrap();
let v_sconv = load_bf16_as_f32(&ar, &format!("{p}.v_sconv.weight")).unwrap();
let a_sconv = load_bf16_as_f32(&ar, "model.llm.layers.0.attn_sconv.weight").unwrap();
// --- device scratch + state ---
let in0 = DeviceBuf::alloc(hidden * 4).unwrap();
let in0_bf = DeviceBuf::alloc(hidden * 2).unwrap();
let q = DeviceBuf::alloc(q_dim * 4).unwrap();
let k_raw = DeviceBuf::alloc(kv_dim * 4).unwrap();
let v_raw = DeviceBuf::alloc(kv_dim * 4).unwrap();
let r_raw = DeviceBuf::alloc(n_head * d_rel * 4).unwrap();
let gatea = DeviceBuf::alloc(q_dim * 4).unwrap();
let sinks = DeviceBuf::alloc(n_head * 4).unwrap();
let k_cv = DeviceBuf::alloc(kv_dim * 4).unwrap();
let v_cv = DeviceBuf::alloc(kv_dim * 4).unwrap();
let hist_k = DeviceBuf::alloc(3 * kv_dim * 4).unwrap(); hist_k.h2d(&vec![0f32; 3 * kv_dim]).unwrap();
let hist_v = DeviceBuf::alloc(3 * kv_dim * 4).unwrap(); hist_v.h2d(&vec![0f32; 3 * kv_dim]).unwrap();
let hist_a = DeviceBuf::alloc(3 * hidden * 4).unwrap(); hist_a.h2d(&vec![0f32; 3 * hidden]).unwrap();
let rel_bias = DeviceBuf::alloc(n_head * rel_extent * 4).unwrap();
let k_cache = DeviceBuf::alloc(n_kv * steps * hd * 4).unwrap(); k_cache.h2d(&vec![0f32; n_kv * steps * hd]).unwrap();
let v_cache = DeviceBuf::alloc(n_kv * steps * hd * 4).unwrap(); v_cache.h2d(&vec![0f32; n_kv * steps * hd]).unwrap();
let aout = DeviceBuf::alloc(q_dim * 4).unwrap();
let aout_bf = DeviceBuf::alloc(q_dim * 2).unwrap();
let oproj = DeviceBuf::alloc(hidden * 4).unwrap();
let attn_out = DeviceBuf::alloc(hidden * 4).unwrap();
let slot0 = DeviceBuf::alloc(4).unwrap(); slot0.h2d_bytes(&0i32.to_le_bytes()).unwrap();
// --- CPU oracle weights/state ---
let an_f = read_bf16_f32(&ar, "model.llm.layers.0.attn_norm.weight");
let wq_f = read_bf16_f32(&ar, &format!("{p}.wq_du.weight"));
let wk_f = read_bf16_f32(&ar, &format!("{p}.wk_dv.weight"));
let wv_f = read_bf16_f32(&ar, &format!("{p}.wv_dv.weight"));
let wr_f = read_bf16_f32(&ar, &format!("{p}.wr_du.weight"));
let wg_f = read_bf16_f32(&ar, &format!("{p}.gate_attn.weight"));
let ws_f = read_bf16_f32(&ar, &format!("{p}.attn_sink_proj.weight"));
let wo_f = read_bf16_f32(&ar, &format!("{p}.wo_ud.weight"));
let q_sc_f = read_bf16_f32(&ar, &format!("{p}.q_l2_clip.scale"));
let r_sc_f = read_bf16_f32(&ar, &format!("{p}.rel_l2_clip.scale"));
let rp_f = read_bf16_f32(&ar, &format!("{p}.rel_logits_proj.proj"));
let ks_f = read_bf16_f32(&ar, &format!("{p}.k_sconv.weight"));
let vs_f = read_bf16_f32(&ar, &format!("{p}.v_sconv.weight"));
let as_f = read_bf16_f32(&ar, "model.llm.layers.0.attn_sconv.weight");
let mut hk = vec![0f32; 3 * kv_dim];
let mut hv = vec![0f32; 3 * kv_dim];
let mut ha = vec![0f32; 3 * hidden];
let mut kc = vec![0f32; n_kv * steps * hd];
let mut vc = vec![0f32; n_kv * steps * hd];
for t in 0..steps {
let pos = t as i32;
let x: Vec<f32> = (0..hidden).map(|i| (((i + t * 31) % 53) as f32 - 26.0) * 0.02).collect();
let dx = DeviceBuf::alloc(hidden * 4).unwrap(); dx.h2d(&x).unwrap();
// GPU chain
vetta_infer_hip::rms_norm_f32(&dx, Some(&attn_norm), &in0, 1, hidden as i32, eps).unwrap();
vetta_infer_hip::cast_f32_bf16(&in0, &in0_bf, hidden).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wq, &q, 1, q_dim as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wk, &k_raw, 1, kv_dim as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wv, &v_raw, 1, kv_dim as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wr, &r_raw, 1, (n_head * d_rel) as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wg, &gatea, 1, q_dim as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &ws, &sinks, 1, n_head as i32, hidden as i32).unwrap();
vetta_infer_hip::shortconv4_decode(&k_raw, &k_sconv, &hist_k, &k_cv, &slot0, 1, kv_dim as i32).unwrap();
vetta_infer_hip::shortconv4_decode(&v_raw, &v_sconv, &hist_v, &v_cv, &slot0, 1, kv_dim as i32).unwrap();
vetta_infer_hip::l2_clip(&q, Some(&q_sc), n_head as i32, hd as i32, qk_clip, false, pos).unwrap();
vetta_infer_hip::l2_clip(&r_raw, Some(&r_sc), n_head as i32, d_rel as i32, rel_clip, false, pos).unwrap();
vetta_infer_hip::l2_clip(&k_cv, None, n_kv as i32, hd as i32, qk_clip, false, pos).unwrap();
let lim = (pos + 1).min(rel_extent as i32);
rel_bias.h2d(&vec![0f32; n_head * rel_extent]).unwrap();
vetta_infer_hip::relpos_bias(&r_raw, &rel_proj, &rel_bias, n_head as i32, d_rel as i32, rel_extent as i32, lim).unwrap();
vetta_infer_hip::kv_store(&k_cv, &v_cv, &k_cache, &v_cache, pos, n_kv as i32, hd as i32, steps as i32, eps).unwrap();
vetta_infer_hip::flash_swa_gqa_decode(&q, &k_cache, &v_cache, &aout, n_head as i32, n_kv as i32, steps as i32, hd as i32, scale, swa_win, pos, Some(&rel_bias), rel_extent as i32, Some(&sinks), Some(&gatea)).unwrap();
vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, q_dim).unwrap();
vetta_infer_hip::gemm_bf16(&aout_bf, &wo, &oproj, 1, hidden as i32, q_dim as i32).unwrap();
vetta_infer_hip::shortconv4_decode(&oproj, &a_sconv, &hist_a, &attn_out, &slot0, 1, hidden as i32).unwrap();
let mut got = vec![0f32; hidden]; attn_out.d2h(&mut got).unwrap();
// CPU oracle chain
let in0_c = rms_norm_cpu(&x, &an_f, eps);
let in0_bf_c: Vec<f32> = in0_c.iter().map(|&v| bf16_trunc(v)).collect();
let q_c = proj_cpu(&in0_bf_c, &wq_f, q_dim, hidden);
let k_raw_c = proj_cpu(&in0_bf_c, &wk_f, kv_dim, hidden);
let v_raw_c = proj_cpu(&in0_bf_c, &wv_f, kv_dim, hidden);
let r_raw_c = proj_cpu(&in0_bf_c, &wr_f, n_head * d_rel, hidden);
let gatea_c = proj_cpu(&in0_bf_c, &wg_f, q_dim, hidden);
let sinks_c = proj_cpu(&in0_bf_c, &ws_f, n_head, hidden);
let k_cv_c = sconv_step(&k_raw_c, &ks_f, &mut hk, kv_dim);
let v_cv_c = sconv_step(&v_raw_c, &vs_f, &mut hv, kv_dim);
let q_cl = l2_clip_cpu(&q_c, Some(&q_sc_f), n_head, hd, qk_clip);
let r_cl = l2_clip_cpu(&r_raw_c, Some(&r_sc_f), n_head, d_rel, rel_clip);
let k_cl = l2_clip_cpu(&k_cv_c, None, n_kv, hd, qk_clip);
let mut rb_c = vec![0f32; n_head * rel_extent];
for h in 0..n_head { for dist in 0..lim as usize { let mut acc = 0f32; for rc in 0..d_rel { acc += r_cl[h * d_rel + rc] * rp_f[rc * rel_extent + dist]; } rb_c[h * rel_extent + dist] = acc; } }
for h in 0..n_kv {
let ss: f32 = (0..hd).map(|d| v_cv_c[h * hd + d] * v_cv_c[h * hd + d]).sum();
let fac = 1.0 / (ss / hd as f32 + eps).sqrt();
for d in 0..hd { let off = (h * steps + t) * hd + d; kc[off] = k_cl[h * hd + d]; vc[off] = v_cv_c[h * hd + d] * fac; }
}
// flash SWA CPU
let k_start = if swa_win > 0 && pos >= swa_win { (pos - swa_win + 1) as usize } else { 0 };
let mut aout_c = vec![0f32; q_dim];
for h in 0..n_head {
let kvh = h / (n_head / n_kv);
let sink = sinks_c[h];
let mut m = sink;
let mut scores = Vec::new(); let mut poss = Vec::new();
for s in k_start..=(pos as usize) {
let mut dot = 0f32; for d in 0..hd { dot += q_cl[h * hd + d] * kc[(kvh * steps + s) * hd + d]; }
dot *= scale;
let dist = pos as usize - s; if dist < rel_extent { dot += rb_c[h * rel_extent + dist]; }
scores.push(dot); poss.push(s); m = m.max(dot);
}
let exps: Vec<f32> = scores.iter().map(|sc| (sc - m).exp()).collect();
let denom = (sink - m).exp() + exps.iter().sum::<f32>();
let inv = 1.0 / denom.max(1e-30);
for d in 0..hd {
let mut acc = 0f32; for (i, &s) in poss.iter().enumerate() { acc += exps[i] * inv * vc[(kvh * steps + s) * hd + d]; }
acc *= 1.0 / (1.0 + (-gatea_c[h * hd + d]).exp());
aout_c[h * hd + d] = acc;
}
}
let aout_bf_c: Vec<f32> = aout_c.iter().map(|&v| bf16_trunc(v)).collect();
let oproj_c = proj_cpu(&aout_bf_c, &wo_f, hidden, q_dim);
let want = sconv_step(&oproj_c, &as_f, &mut ha, hidden);
// Parity uses a combined absolute+relative tolerance (allclose style).
// Stage bisection shows the attention output (aout) matches the CPU
// oracle to <1e-6 ABSOLUTE at every step; the only divergence enters
// at the bf16 cast of aout + O-proj GEMM, where a few elements cross a
// bf16 rounding boundary (GPU/CPU f32 softmax accumulation order). At
// near-cancellation O-proj outputs (~1e-3) a pure-relative metric
// explodes (max_abs stays ~5e-4) even though the math is identical.
// atol=2e-3 + rtol=3e-3 bounds this benign artifact while still
// catching any genuine wiring bug (which yields O(1) absolute error).
let mut mr = 0f32; let mut ma = 0f32;
for (g, w) in got.iter().zip(want.iter()) { let ae = (g - w).abs(); ma = ma.max(ae); mr = mr.max(ae / w.abs().max(1e-3)); }
eprintln!("REAL attention block step {t}: max_rel_err={mr:.3e} max_abs_err={ma:.3e}");
let ok = got.iter().zip(want.iter()).all(|(g, w)| (g - w).abs() <= 2e-3 + 3e-3 * w.abs());
assert!(ok, "real attention block step {t} parity failed: max_rel={mr} max_abs={ma}");
}
}
/// FULL REAL LAYER (ip=0, SWA layer 0) end-to-end: attention block + AttnRes
/// block snapshot (block_size=6) + MoE block + residual, with the exact
/// Inkling deep-residual cadence:
/// in0 = attn_norm(cur) (ip==0: no attention mix)
/// asc = attn_block(in0) (projections..flash..O-proj..sconv)
/// ip%6==0: block0 <- cur; cur = asc
/// mlpin = mlp_norm(attn_res_mix([block0], cur, mlp_queries[0]))
/// moeout = moe_block(mlpin)
/// cur += mlp_sconv(moeout) (MoE residual is a plain add)
/// Parity vs a full CPU oracle.
#[test]
#[ignore]
fn real_full_layer_end_to_end() {
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
let p = "model.llm.layers.0.attn";
let (hidden, n_head, n_kv, hd, d_rel, rel_extent) = (2304usize, 24usize, 8usize, 128usize, 16usize, 1024usize);
let (inter, n_experts, top_k) = (1152usize, 128usize, 8usize);
let (qk_clip, rel_clip, eps, route_scale) = (22.627416997969522f32, 8.0f32, 1e-6f32, 8.0f32);
let (beta, lb) = (4.0f32, 25.0f32);
let kv_dim = n_kv * hd; let q_dim = n_head * hd;
let scale = 1.0f32 / (hd as f32).sqrt();
let pos = 0i32; let steps = 1usize;
let x: Vec<f32> = (0..hidden).map(|i| ((i % 53) as f32 - 26.0) * 0.02).collect();
// === GPU full layer via the reusable layer forward (ld::layer) ===
let dims = crate::layer::Dims { hidden, n_head, n_kv, hd, d_rel, rel_extent, inter, n_experts, top_k, block_size: 6, qk_clip, rel_clip, eps, route_scale, beta, lb, swa_win: 1024 };
let lw = crate::layer::load_layer(&ar, 0, true).unwrap();
let mut st = crate::layer::new_state(&dims, steps, 3).unwrap();
let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap();
let mut blocks: Vec<DeviceBuf> = Vec::new();
let cache = crate::layer::WeightCache::new(ar.clone());
crate::layer::layer_forward_swa(&cache, &lw, &mut st, &dims, &cur, &mut blocks, pos, 0, None).unwrap();
assert_eq!(blocks.len(), 1, "ip=0 must snapshot one depth block");
let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap();
// === CPU oracle ===
let an_f = read_bf16_f32(&ar, "model.llm.layers.0.attn_norm.weight");
let wq_f = read_bf16_f32(&ar, &format!("{p}.wq_du.weight"));
let wk_f = read_bf16_f32(&ar, &format!("{p}.wk_dv.weight"));
let wv_f = read_bf16_f32(&ar, &format!("{p}.wv_dv.weight"));
let wr_f = read_bf16_f32(&ar, &format!("{p}.wr_du.weight"));
let wg_f = read_bf16_f32(&ar, &format!("{p}.gate_attn.weight"));
let ws_f = read_bf16_f32(&ar, &format!("{p}.attn_sink_proj.weight"));
let wo_f = read_bf16_f32(&ar, &format!("{p}.wo_ud.weight"));
let q_sc_f = read_bf16_f32(&ar, &format!("{p}.q_l2_clip.scale"));
let r_sc_f = read_bf16_f32(&ar, &format!("{p}.rel_l2_clip.scale"));
let rp_f = read_bf16_f32(&ar, &format!("{p}.rel_logits_proj.proj"));
let ks_f = read_bf16_f32(&ar, &format!("{p}.k_sconv.weight"));
let vs_f = read_bf16_f32(&ar, &format!("{p}.v_sconv.weight"));
let as_f = read_bf16_f32(&ar, "model.llm.layers.0.attn_sconv.weight");
let mn_f = read_bf16_f32(&ar, "model.llm.layers.0.mlp_norm.weight");
let ms_f = read_bf16_f32(&ar, "model.llm.layers.0.mlp_sconv.weight");
let mq_f = { let mut b = vec![0u8; hidden * 4]; ar.read_slice("model.llm.attn_res.mlp_queries.0", 0, &mut b).unwrap(); b.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::<Vec<f32>>() };
let mut hk = vec![0f32; 3 * kv_dim]; let mut hv = vec![0f32; 3 * kv_dim]; let mut ha = vec![0f32; 3 * hidden]; let mut hm = vec![0f32; 3 * hidden];
let mut cur_c = x.clone();
let in0_c = rms_norm_cpu(&cur_c, &an_f, eps);
let in0_bf_c: Vec<f32> = in0_c.iter().map(|&v| bf16_trunc(v)).collect();
let q_c = proj_cpu(&in0_bf_c, &wq_f, q_dim, hidden);
let k_raw_c = proj_cpu(&in0_bf_c, &wk_f, kv_dim, hidden);
let v_raw_c = proj_cpu(&in0_bf_c, &wv_f, kv_dim, hidden);
let r_raw_c = proj_cpu(&in0_bf_c, &wr_f, n_head * d_rel, hidden);
let gatea_c = proj_cpu(&in0_bf_c, &wg_f, q_dim, hidden);
let sinks_c = proj_cpu(&in0_bf_c, &ws_f, n_head, hidden);
let k_cv_c = sconv_step(&k_raw_c, &ks_f, &mut hk, kv_dim);
let v_cv_c = sconv_step(&v_raw_c, &vs_f, &mut hv, kv_dim);
let q_cl = l2_clip_cpu(&q_c, Some(&q_sc_f), n_head, hd, qk_clip);
let r_cl = l2_clip_cpu(&r_raw_c, Some(&r_sc_f), n_head, d_rel, rel_clip);
let k_cl = l2_clip_cpu(&k_cv_c, None, n_kv, hd, qk_clip);
let mut rb_c = vec![0f32; n_head * rel_extent];
for h in 0..n_head { let mut acc = 0f32; for rc in 0..d_rel { acc += r_cl[h * d_rel + rc] * rp_f[rc * rel_extent]; } rb_c[h * rel_extent] = acc; }
let mut kc = vec![0f32; n_kv * hd]; let mut vc = vec![0f32; n_kv * hd];
for h in 0..n_kv { let ss: f32 = (0..hd).map(|d| v_cv_c[h * hd + d] * v_cv_c[h * hd + d]).sum(); let fac = 1.0 / (ss / hd as f32 + eps).sqrt(); for d in 0..hd { kc[h * hd + d] = k_cl[h * hd + d]; vc[h * hd + d] = v_cv_c[h * hd + d] * fac; } }
// flash at pos=0 (single position) + sink
let mut aout_c = vec![0f32; q_dim];
for h in 0..n_head { let kvh = h / (n_head / n_kv); let sink = sinks_c[h]; let mut dot = 0f32; for d in 0..hd { dot += q_cl[h * hd + d] * kc[kvh * hd + d]; } dot = dot * scale + rb_c[h * rel_extent]; let m = sink.max(dot); let es = (dot - m).exp(); let denom = (sink - m).exp() + es; let inv = 1.0 / denom.max(1e-30); for d in 0..hd { let mut acc = es * inv * vc[kvh * hd + d]; acc *= 1.0 / (1.0 + (-gatea_c[h * hd + d]).exp()); aout_c[h * hd + d] = acc; } }
let aout_bf_c: Vec<f32> = aout_c.iter().map(|&v| bf16_trunc(v)).collect();
let oproj_c = proj_cpu(&aout_bf_c, &wo_f, hidden, q_dim);
let asc_c = sconv_step(&oproj_c, &as_f, &mut ha, hidden);
// block rule: block0 = cur_c; cur_c = asc_c
let block0_c = cur_c.clone();
cur_c = asc_c;
// mix([block0], cur, mlp_query) then mlp_norm
let mix_c = {
let states = [&block0_c, &cur_c];
let mut scores = [0f32; 2]; let mut irs = [0f32; 2];
let inv_sqrt_d = 1.0 / (hidden as f32).sqrt();
for s in 0..2 { let sv = states[s]; let ss: f32 = sv.iter().map(|v| v * v).sum(); let dot: f32 = sv.iter().zip(&mq_f).map(|(v, q)| v * q).sum(); let ir = 1.0 / (ss / hidden as f32 + eps).sqrt(); irs[s] = ir; scores[s] = dot * ir * inv_sqrt_d; }
let mx = scores[0].max(scores[1]); let e0 = (scores[0] - mx).exp(); let e1 = (scores[1] - mx).exp(); let sum = e0 + e1;
let w0 = e0 / sum * irs[0]; let w1 = e1 / sum * irs[1];
(0..hidden).map(|d| w0 * block0_c[d] + w1 * cur_c[d]).collect::<Vec<f32>>()
};
let mlpin_c = rms_norm_cpu(&mix_c, &mn_f, eps);
let gw_f = read_bf16_f32(&ar, "model.llm.layers.0.mlp.gate.weight");
// Router reads F32 mlpin (strata B=1 launch_f32_linear), not bf16.
let rlog_c = proj_cpu(&mlpin_c, &gw_f, n_experts, hidden);
let mut gb = vec![0u8; n_experts * 4]; ar.read_slice("model.llm.layers.0.mlp.gate.bias", 0, &mut gb).unwrap();
let bias_c: 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> = rlog_c.iter().map(|&l| 1.0 / (1.0 + (-l).exp())).collect();
let mut score: Vec<f32> = (0..n_experts).map(|e| prob[e] + bias_c[e]).collect();
let mut ids_c = vec![0usize; top_k]; let mut w_c = vec![0f32; top_k]; let mut wsum = 0f32;
for kk in 0..top_k { let mut bv = f32::NEG_INFINITY; let mut bi = 0; for e in 0..n_experts { if score[e] > bv { bv = score[e]; bi = e; } } ids_c[kk] = bi; w_c[kk] = prob[bi]; wsum += prob[bi]; score[bi] = -1e30; }
let inv = route_scale / (wsum + 1e-20); for kk in 0..top_k { w_c[kk] *= inv; }
let mut moeout_c = vec![0f32; hidden];
for kk in 0..top_k { let e = ids_c[kk]; let o13 = expert_outer(&ar, 0, e, "w13"); let gu_c = nvfp4_gemv_cpu(&ar, 0, e, "w13", &mlpin_c, 2 * inter, hidden, o13); let act_c = situ_cpu(&gu_c, inter, beta, lb); let o2 = expert_outer(&ar, 0, e, "w2"); let ye_c = nvfp4_gemv_cpu(&ar, 0, e, "w2", &act_c, hidden, inter, o2); for d in 0..hidden { moeout_c[d] += w_c[kk] * ye_c[d]; } }
let msc_c = sconv_step(&moeout_c, &ms_f, &mut hm, hidden);
let want: Vec<f32> = (0..hidden).map(|d| cur_c[d] + msc_c[d]).collect();
let mut mr = 0f32; for (g, w) in got.iter().zip(want.iter()) { mr = mr.max((g - w).abs() / w.abs().max(1e-3)); }
eprintln!("REAL full layer (ip=0): experts={:?} max_rel_err={mr:.3e}", ids_c);
// 5e-3: f32 accumulation-order (GPU per-group partials + block reduce vs
// CPU sequential) over 8 experts, amplified by the SiTU nonlinearity;
// same artifact class as real_moe_block_end_to_end. Math is identical.
assert!(mr < 5e-3, "real full layer parity failed: {mr}");
}
// CPU dyn ShortConv step (full-attn): static_w already in kernel [C,4] order
// (reversed taps), dyn_taps [n_heads,4], scale 1/3.
fn sconv_dyn_step(x0: &[f32], sw: &[f32], dyn_t: &[f32], hist: &mut [f32], c: usize, n_heads: usize) -> Vec<f32> {
let mut y = vec![0f32; c];
for ch in 0..c {
let h0 = hist[ch]; let h1 = hist[c + ch]; let h2 = hist[2 * c + ch];
let w = &sw[ch * 4..ch * 4 + 4];
let head = ch / (c / n_heads);
let dt = &dyn_t[head * 4..head * 4 + 4];
y[ch] = (x0[ch] + w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * x0[ch] + dt[0] * x0[ch] + dt[1] * h2 + dt[2] * h1 + dt[3] * h0) / 3.0;
}
for ch in 0..c { let h1 = hist[c + ch]; let h2 = hist[2 * c + ch]; hist[ch] = bf16_trunc(h1); hist[c + ch] = bf16_trunc(h2); hist[2 * c + ch] = bf16_trunc(x0[ch]); }
y
}
/// Full-attn layer (ip=5) CPU-oracle parity: 3-query mix split + separate
/// q/k/v norms + projections from distinct inputs + dyn ShortConv + global
/// attention + MoE. Blocks empty (mix over cur only). Isolates the full-attn
/// wiring that was previously only smoke-tested.
#[test]
#[ignore]
fn real_full_attn_layer_end_to_end() {
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
let ip = 5usize;
let p = format!("model.llm.layers.{ip}.attn");
let l = format!("model.llm.layers.{ip}");
let (hidden, n_head, n_kv, hd, d_rel, rel_extent) = (2304usize, 24usize, 8usize, 128usize, 16usize, 1024usize);
let (inter, n_experts, top_k) = (1152usize, 128usize, 8usize);
let (qk_clip, rel_clip, eps, route_scale) = (22.627416997969522f32, 8.0f32, 1e-6f32, 8.0f32);
let (beta, lb) = (4.0f32, 25.0f32);
let kv_dim = n_kv * hd; let q_dim = n_head * hd;
let scale = 1.0f32 / (hd as f32).sqrt();
let pos = 0i32;
let x: Vec<f32> = (0..hidden).map(|i| ((i % 53) as f32 - 26.0) * 0.02).collect();
let dims = crate::layer::Dims { hidden, n_head, n_kv, hd, d_rel, rel_extent, inter, n_experts, top_k, block_size: 6, qk_clip, rel_clip, eps, route_scale, beta, lb, swa_win: 1024 };
let lw = crate::layer::load_full_layer(&ar, ip, &dims).unwrap();
let mut st = crate::layer::new_state(&dims, 1, 3).unwrap();
let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap();
let mut blocks: Vec<DeviceBuf> = Vec::new();
let cache = crate::layer::WeightCache::new(ar.clone());
crate::layer::layer_forward_full(&cache, &lw, &mut st, &dims, &cur, &mut blocks, pos, 0, None).unwrap();
let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap();
// CPU oracle
let qn_f = read_bf16_f32(&ar, &format!("{l}.q_input_norm.weight"));
let kn_f = read_bf16_f32(&ar, &format!("{l}.k_input_norm.weight"));
let vn_f = read_bf16_f32(&ar, &format!("{l}.v_input_norm.weight"));
let wq_f = read_bf16_f32(&ar, &format!("{p}.wq_du.weight"));
let wk_f = read_bf16_f32(&ar, &format!("{p}.wk_dv.weight"));
let wv_f = read_bf16_f32(&ar, &format!("{p}.wv_dv.weight"));
let wr_f = read_bf16_f32(&ar, &format!("{p}.wr_du.weight"));
let wg_f = read_bf16_f32(&ar, &format!("{p}.gate_attn.weight"));
let ws_f = read_bf16_f32(&ar, &format!("{p}.attn_sink_proj.weight"));
let wo_f = read_bf16_f32(&ar, &format!("{p}.wo_ud.weight"));
let q_sc_f = read_bf16_f32(&ar, &format!("{p}.q_l2_clip.scale"));
let r_sc_f = read_bf16_f32(&ar, &format!("{p}.rel_l2_clip.scale"));
let rp_f = read_bf16_f32(&ar, &format!("{p}.rel_logits_proj.proj"));
let kp_f = read_bf16_f32(&ar, &format!("{p}.k_sconv.weight_proj"));
let vp_f = read_bf16_f32(&ar, &format!("{p}.v_sconv.weight_proj"));
let as_f = read_bf16_f32(&ar, &format!("{l}.attn_sconv.weight"));
let mn_f = read_bf16_f32(&ar, &format!("{l}.mlp_norm.weight"));
let ms_f = read_bf16_f32(&ar, &format!("{l}.mlp_sconv.weight"));
// static_w [4,C] -> kernel [C,4] reversed taps
let kw_raw = read_bf16_f32(&ar, &format!("{p}.k_sconv.static_w"));
let vw_raw = read_bf16_f32(&ar, &format!("{p}.v_sconv.static_w"));
let mut ks_f = vec![0f32; kv_dim * 4]; let mut vs_f = vec![0f32; kv_dim * 4];
for lag in 0..4 { for ch in 0..kv_dim { ks_f[ch * 4 + (3 - lag)] = kw_raw[lag * kv_dim + ch]; vs_f[ch * 4 + (3 - lag)] = vw_raw[lag * kv_dim + ch]; } }
// 3-query mix over cur only (n_blocks=0): out[q] = cur*inv_rms(cur)
let aq_f = { let mut b = vec![0u8; 3 * hidden * 4]; ar.read_slice("model.llm.attn_res.attn_queries.4", 0, &mut b).unwrap(); b.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::<Vec<f32>>() };
let ss_cur: f32 = x.iter().map(|v| v * v).sum(); let ir_cur = 1.0 / (ss_cur / hidden as f32 + eps).sqrt();
let mix_q: Vec<Vec<f32>> = (0..3).map(|q| { let dot: f32 = x.iter().zip(&aq_f[q * hidden..(q + 1) * hidden]).map(|(v, w)| v * w).sum(); let _ = dot; x.iter().map(|v| v * ir_cur).collect() }).collect();
let in0_c = rms_norm_cpu(&mix_q[0], &qn_f, eps);
let in1_c = rms_norm_cpu(&mix_q[1], &kn_f, eps);
let in2_c = rms_norm_cpu(&mix_q[2], &vn_f, eps);
let in0_bf: Vec<f32> = in0_c.iter().map(|&v| bf16_trunc(v)).collect();
let in1_bf: Vec<f32> = in1_c.iter().map(|&v| bf16_trunc(v)).collect();
let in2_bf: Vec<f32> = in2_c.iter().map(|&v| bf16_trunc(v)).collect();
let q_c = proj_cpu(&in0_bf, &wq_f, q_dim, hidden);
let k_raw_c = proj_cpu(&in1_bf, &wk_f, kv_dim, hidden);
let v_raw_c = proj_cpu(&in2_bf, &wv_f, kv_dim, hidden);
let r_raw_c = proj_cpu(&in0_bf, &wr_f, n_head * d_rel, hidden);
let gatea_c = proj_cpu(&in0_bf, &wg_f, q_dim, hidden);
let sinks_c = proj_cpu(&in0_bf, &ws_f, n_head, hidden);
let k_dyn_c = proj_cpu(&in1_bf, &kp_f, n_kv * 4, hidden);
let v_dyn_c = proj_cpu(&in2_bf, &vp_f, n_kv * 4, hidden);
let mut hk = vec![0f32; 3 * kv_dim]; let mut hv = vec![0f32; 3 * kv_dim]; let mut ha = vec![0f32; 3 * hidden]; let mut hm = vec![0f32; 3 * hidden];
let k_cv_c = sconv_dyn_step(&k_raw_c, &ks_f, &k_dyn_c, &mut hk, kv_dim, n_kv);
let v_cv_c = sconv_dyn_step(&v_raw_c, &vs_f, &v_dyn_c, &mut hv, kv_dim, n_kv);
let q_cl = l2_clip_cpu(&q_c, Some(&q_sc_f), n_head, hd, qk_clip);
let r_cl = l2_clip_cpu(&r_raw_c, Some(&r_sc_f), n_head, d_rel, rel_clip);
let k_cl = l2_clip_cpu(&k_cv_c, None, n_kv, hd, qk_clip);
let mut rb_c = vec![0f32; n_head * rel_extent];
for h in 0..n_head { let mut acc = 0f32; for rc in 0..d_rel { acc += r_cl[h * d_rel + rc] * rp_f[rc * rel_extent]; } rb_c[h * rel_extent] = acc; }
let mut kc = vec![0f32; n_kv * hd]; let mut vc = vec![0f32; n_kv * hd];
for h in 0..n_kv { let ss: f32 = (0..hd).map(|d| v_cv_c[h * hd + d] * v_cv_c[h * hd + d]).sum(); let fac = 1.0 / (ss / hd as f32 + eps).sqrt(); for d in 0..hd { kc[h * hd + d] = k_cl[h * hd + d]; vc[h * hd + d] = v_cv_c[h * hd + d] * fac; } }
let mut aout_c = vec![0f32; q_dim];
for h in 0..n_head { let kvh = h / (n_head / n_kv); let sink = sinks_c[h]; let mut dot = 0f32; for d in 0..hd { dot += q_cl[h * hd + d] * kc[kvh * hd + d]; } dot = dot * scale + rb_c[h * rel_extent]; let m = sink.max(dot); let es = (dot - m).exp(); let denom = (sink - m).exp() + es; let inv = 1.0 / denom.max(1e-30); for d in 0..hd { let mut acc = es * inv * vc[kvh * hd + d]; acc *= 1.0 / (1.0 + (-gatea_c[h * hd + d]).exp()); aout_c[h * hd + d] = acc; } }
let aout_bf: Vec<f32> = aout_c.iter().map(|&v| bf16_trunc(v)).collect();
let oproj_c = proj_cpu(&aout_bf, &wo_f, hidden, q_dim);
let asc_c = sconv_step(&oproj_c, &as_f, &mut ha, hidden);
// ip=5 %6 !=0 -> cur += asc
let cur_c: Vec<f32> = x.iter().zip(&asc_c).map(|(a, b)| a + b).collect();
// MoE: mix over cur only (n_blocks=0) -> mlp_norm
let mq_f = { let mut b = vec![0u8; hidden * 4]; ar.read_slice(&format!("model.llm.attn_res.mlp_queries.{ip}"), 0, &mut b).unwrap(); b.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::<Vec<f32>>() };
let ss2: f32 = cur_c.iter().map(|v| v * v).sum(); let ir2 = 1.0 / (ss2 / hidden as f32 + eps).sqrt();
let _ = mq_f;
let mix_c: Vec<f32> = cur_c.iter().map(|v| v * ir2).collect();
let mlpin_c = rms_norm_cpu(&mix_c, &mn_f, eps);
let gw_f = read_bf16_f32(&ar, &format!("{l}.mlp.gate.weight"));
// Router reads F32 mlpin (strata B=1 launch_f32_linear), not bf16.
let rlog_c = proj_cpu(&mlpin_c, &gw_f, n_experts, hidden);
let mut gb = vec![0u8; n_experts * 4]; ar.read_slice(&format!("{l}.mlp.gate.bias"), 0, &mut gb).unwrap();
let bias_c: 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> = rlog_c.iter().map(|&l| 1.0 / (1.0 + (-l).exp())).collect();
let mut score: Vec<f32> = (0..n_experts).map(|e| prob[e] + bias_c[e]).collect();
let mut ids_c = vec![0usize; top_k]; let mut w_c = vec![0f32; top_k]; let mut wsum = 0f32;
for kk in 0..top_k { let mut bv = f32::NEG_INFINITY; let mut bi = 0; for e in 0..n_experts { if score[e] > bv { bv = score[e]; bi = e; } } ids_c[kk] = bi; w_c[kk] = prob[bi]; wsum += prob[bi]; score[bi] = -1e30; }
let inv = route_scale / (wsum + 1e-20); for kk in 0..top_k { w_c[kk] *= inv; }
let mut moeout_c = vec![0f32; hidden];
for kk in 0..top_k { let e = ids_c[kk]; let o13 = expert_outer(&ar, ip, e, "w13"); let gu_c = nvfp4_gemv_cpu(&ar, ip, e, "w13", &mlpin_c, 2 * inter, hidden, o13); let act_c = situ_cpu(&gu_c, inter, beta, lb); let o2 = expert_outer(&ar, ip, e, "w2"); let ye_c = nvfp4_gemv_cpu(&ar, ip, e, "w2", &act_c, hidden, inter, o2); for d in 0..hidden { moeout_c[d] += w_c[kk] * ye_c[d]; } }
let msc_c = sconv_step(&moeout_c, &ms_f, &mut hm, hidden);
let want: Vec<f32> = (0..hidden).map(|d| cur_c[d] + msc_c[d]).collect();
let mut mr = 0f32; for (g, w) in got.iter().zip(want.iter()) { mr = mr.max((g - w).abs() / w.abs().max(1e-3)); }
eprintln!("REAL full-attn layer (ip=5): experts={:?} max_rel_err={mr:.3e}", ids_c);
// 5e-3: same benign f32 accumulation-order artifact as real_full_layer.
assert!(mr < 5e-3, "real full-attn layer parity failed: {mr}");
}
/// Stage-by-stage GPU-vs-CPU bisect of the full-attn attention (ip=5).
#[test]
#[ignore]
fn full_attn_bisect() {
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
let ip = 5usize;
let p = format!("model.llm.layers.{ip}.attn");
let l = format!("model.llm.layers.{ip}");
let (hidden, n_head, n_kv, hd, d_rel, rel_extent) = (2304usize, 24usize, 8usize, 128usize, 16usize, 1024usize);
let (qk_clip, rel_clip, eps) = (22.627416997969522f32, 8.0f32, 1e-6f32);
let kv_dim = n_kv * hd; let q_dim = n_head * hd;
let scale = 1.0f32 / (hd as f32).sqrt();
let x: Vec<f32> = (0..hidden).map(|i| ((i % 53) as f32 - 26.0) * 0.02).collect();
let dims = crate::layer::Dims { hidden, n_head, n_kv, hd, d_rel, rel_extent, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip, rel_clip, eps, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 };
let lw = crate::layer::load_full_layer(&ar, ip, &dims).unwrap();
let cmp = |name: &str, g: &[f32], w: &[f32]| { let mut mr = 0f32; let mut ma = 0f32; let mut mr_big = 0f32; for (a, b) in g.iter().zip(w.iter()) { let d = (a - b).abs(); ma = ma.max(d); mr = mr.max(d / b.abs().max(1e-3)); if b.abs() > 0.1 { mr_big = mr_big.max(d / b.abs()); } } eprintln!("[bisect] {name}: max_rel={mr:.3e} max_abs={ma:.3e} rel_big={mr_big:.3e}"); };
// GPU mix (n_blocks=0, 3 queries)
let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap();
let blk = DeviceBuf::alloc(hidden * 4).unwrap(); blk.h2d(&vec![0f32; hidden]).unwrap();
let mx3 = DeviceBuf::alloc(3 * hidden * 4).unwrap();
vetta_infer_hip::attn_res_mix(&blk, &cur, &lw.attn_query, &mx3, 0, 1, 3, hidden as i32, eps).unwrap();
let mut mx_h = vec![0f32; 3 * hidden]; mx3.d2h(&mut mx_h).unwrap();
let ss: f32 = x.iter().map(|v| v * v).sum(); let ir = 1.0 / (ss / hidden as f32 + eps).sqrt();
let mix_w: Vec<f32> = x.iter().map(|v| v * ir).collect();
cmp("mix_q0", &mx_h[0..hidden], &mix_w);
// GPU norms
let in0 = DeviceBuf::alloc(hidden * 4).unwrap(); in0.h2d(&mx_h[0..hidden]).unwrap();
let in1 = DeviceBuf::alloc(hidden * 4).unwrap(); in1.h2d(&mx_h[hidden..2 * hidden]).unwrap();
let in2 = DeviceBuf::alloc(hidden * 4).unwrap(); in2.h2d(&mx_h[2 * hidden..3 * hidden]).unwrap();
vetta_infer_hip::rms_norm_f32(&in0, Some(&lw.q_norm), &in0, 1, hidden as i32, eps).unwrap();
vetta_infer_hip::rms_norm_f32(&in1, Some(&lw.k_norm), &in1, 1, hidden as i32, eps).unwrap();
vetta_infer_hip::rms_norm_f32(&in2, Some(&lw.v_norm), &in2, 1, hidden as i32, eps).unwrap();
let qn_f = read_bf16_f32(&ar, &format!("{l}.q_input_norm.weight"));
let kn_f = read_bf16_f32(&ar, &format!("{l}.k_input_norm.weight"));
let vn_f = read_bf16_f32(&ar, &format!("{l}.v_input_norm.weight"));
let in0_w = rms_norm_cpu(&mix_w, &qn_f, eps); let in1_w = rms_norm_cpu(&mix_w, &kn_f, eps); let _in2_w = rms_norm_cpu(&mix_w, &vn_f, eps);
let mut g0 = vec![0f32; hidden]; in0.d2h(&mut g0).unwrap(); cmp("in0_norm", &g0, &in0_w);
let mut g1 = vec![0f32; hidden]; in1.d2h(&mut g1).unwrap(); cmp("in1_norm", &g1, &in1_w);
// GPU projections
let in0_bf = DeviceBuf::alloc(hidden * 2).unwrap(); vetta_infer_hip::cast_f32_bf16(&in0, &in0_bf, hidden).unwrap();
let in1_bf = DeviceBuf::alloc(hidden * 2).unwrap(); vetta_infer_hip::cast_f32_bf16(&in1, &in1_bf, hidden).unwrap();
let in2_bf = DeviceBuf::alloc(hidden * 2).unwrap(); vetta_infer_hip::cast_f32_bf16(&in2, &in2_bf, hidden).unwrap();
let q = DeviceBuf::alloc(q_dim * 4).unwrap(); vetta_infer_hip::gemm_bf16(&in0_bf, &lw.wq, &q, 1, q_dim as i32, hidden as i32).unwrap();
let k_raw = DeviceBuf::alloc(kv_dim * 4).unwrap(); vetta_infer_hip::gemm_bf16(&in1_bf, &lw.wk, &k_raw, 1, kv_dim as i32, hidden as i32).unwrap();
let in0_bf_w: Vec<f32> = in0_w.iter().map(|&v| bf16_trunc(v)).collect();
let in1_bf_w: Vec<f32> = in1_w.iter().map(|&v| bf16_trunc(v)).collect();
let wq_f = read_bf16_f32(&ar, &format!("{p}.wq_du.weight"));
let wk_f = read_bf16_f32(&ar, &format!("{p}.wk_dv.weight"));
let q_w = proj_cpu(&in0_bf_w, &wq_f, q_dim, hidden);
let k_raw_w = proj_cpu(&in1_bf_w, &wk_f, kv_dim, hidden);
let mut gq = vec![0f32; q_dim]; q.d2h(&mut gq).unwrap(); cmp("q_proj", &gq, &q_w);
let mut gk = vec![0f32; kv_dim]; k_raw.d2h(&mut gk).unwrap(); cmp("k_proj", &gk, &k_raw_w);
// GPU dyn shortconv K
let k_dyn = DeviceBuf::alloc(n_kv * 4 * 4).unwrap(); vetta_infer_hip::gemm_bf16(&in1_bf, &lw.k_proj, &k_dyn, 1, (n_kv * 4) as i32, hidden as i32).unwrap();
let histk = DeviceBuf::alloc(3 * kv_dim * 4).unwrap(); histk.h2d(&vec![0f32; 3 * kv_dim]).unwrap();
let k_cv = DeviceBuf::alloc(kv_dim * 4).unwrap(); let slot0 = DeviceBuf::alloc(4).unwrap(); slot0.h2d_bytes(&0i32.to_le_bytes()).unwrap();
vetta_infer_hip::shortconv4_dyn_decode(&k_raw, &lw.k_static, &k_dyn, &histk, &k_cv, &slot0, 1, kv_dim as i32, n_kv as i32).unwrap();
let kp_f = read_bf16_f32(&ar, &format!("{p}.k_sconv.weight_proj"));
let k_dyn_w = proj_cpu(&in1_bf_w, &kp_f, n_kv * 4, hidden);
let kw_raw = read_bf16_f32(&ar, &format!("{p}.k_sconv.static_w"));
let mut ks_f = vec![0f32; kv_dim * 4]; for lag in 0..4 { for ch in 0..kv_dim { ks_f[ch * 4 + (3 - lag)] = kw_raw[lag * kv_dim + ch]; } }
let mut hk = vec![0f32; 3 * kv_dim];
let k_cv_w = sconv_dyn_step(&k_raw_w, &ks_f, &k_dyn_w, &mut hk, kv_dim, n_kv);
let mut gkc = vec![0f32; kv_dim]; k_cv.d2h(&mut gkc).unwrap(); cmp("k_dyn_sconv", &gkc, &k_cv_w);
let mut gkd = vec![0f32; n_kv * 4]; k_dyn.d2h(&mut gkd).unwrap(); cmp("k_dyn_taps", &gkd, &k_dyn_w);
// ---- continue: V path + clips + attention + oproj + asc + cur + mlpin + MoE ----
let v_raw = DeviceBuf::alloc(kv_dim * 4).unwrap(); vetta_infer_hip::gemm_bf16(&in2_bf, &lw.wv, &v_raw, 1, kv_dim as i32, hidden as i32).unwrap();
let v_dyn = DeviceBuf::alloc(n_kv * 4 * 4).unwrap(); vetta_infer_hip::gemm_bf16(&in2_bf, &lw.v_proj, &v_dyn, 1, (n_kv * 4) as i32, hidden as i32).unwrap();
let histv = DeviceBuf::alloc(3 * kv_dim * 4).unwrap(); histv.h2d(&vec![0f32; 3 * kv_dim]).unwrap();
let v_cv = DeviceBuf::alloc(kv_dim * 4).unwrap();
vetta_infer_hip::shortconv4_dyn_decode(&v_raw, &lw.v_static, &v_dyn, &histv, &v_cv, &slot0, 1, kv_dim as i32, n_kv as i32).unwrap();
let r_raw = DeviceBuf::alloc(n_head * d_rel * 4).unwrap(); vetta_infer_hip::gemm_bf16(&in0_bf, &lw.wr, &r_raw, 1, (n_head * d_rel) as i32, hidden as i32).unwrap();
let gatea = DeviceBuf::alloc(q_dim * 4).unwrap(); vetta_infer_hip::gemm_bf16(&in0_bf, &lw.wg, &gatea, 1, q_dim as i32, hidden as i32).unwrap();
let sinks = DeviceBuf::alloc(n_head * 4).unwrap(); vetta_infer_hip::gemm_bf16(&in0_bf, &lw.ws, &sinks, 1, n_head as i32, hidden as i32).unwrap();
vetta_infer_hip::l2_clip(&q, Some(&lw.q_sc), n_head as i32, hd as i32, qk_clip, true, 0).unwrap();
vetta_infer_hip::l2_clip(&r_raw, Some(&lw.r_sc), n_head as i32, d_rel as i32, rel_clip, true, 0).unwrap();
vetta_infer_hip::l2_clip(&k_cv, None, n_kv as i32, hd as i32, qk_clip, false, 0).unwrap();
let rel_bias = DeviceBuf::alloc(n_head * rel_extent * 4).unwrap(); rel_bias.h2d(&vec![0f32; n_head * rel_extent]).unwrap();
vetta_infer_hip::relpos_bias(&r_raw, &lw.rel_proj, &rel_bias, n_head as i32, d_rel as i32, rel_extent as i32, 1).unwrap();
let kcache = DeviceBuf::alloc(n_kv * hd * 4).unwrap(); let vcache = DeviceBuf::alloc(n_kv * hd * 4).unwrap();
vetta_infer_hip::kv_store(&k_cv, &v_cv, &kcache, &vcache, 0, n_kv as i32, hd as i32, 1, eps).unwrap();
let aout = DeviceBuf::alloc(q_dim * 4).unwrap();
vetta_infer_hip::flash_swa_gqa_decode(&q, &kcache, &vcache, &aout, n_head as i32, n_kv as i32, 1, hd as i32, scale, 0, 0, Some(&rel_bias), rel_extent as i32, Some(&sinks), Some(&gatea)).unwrap();
let aout_bf = DeviceBuf::alloc(q_dim * 2).unwrap(); vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, q_dim).unwrap();
let oproj = DeviceBuf::alloc(hidden * 4).unwrap(); vetta_infer_hip::gemm_bf16(&aout_bf, &lw.wo, &oproj, 1, hidden as i32, q_dim as i32).unwrap();
let hista = DeviceBuf::alloc(3 * hidden * 4).unwrap(); hista.h2d(&vec![0f32; 3 * hidden]).unwrap();
let asc = DeviceBuf::alloc(hidden * 4).unwrap(); vetta_infer_hip::shortconv4_decode(&oproj, &lw.a_sconv, &hista, &asc, &slot0, 1, hidden as i32).unwrap();
// CPU oracle for V/attention/asc
let in2_bf_w: Vec<f32> = _in2_w.iter().map(|&v| bf16_trunc(v)).collect();
let wv_f = read_bf16_f32(&ar, &format!("{p}.wv_dv.weight"));
let wr_f = read_bf16_f32(&ar, &format!("{p}.wr_du.weight"));
let wg_f = read_bf16_f32(&ar, &format!("{p}.gate_attn.weight"));
let ws_f = read_bf16_f32(&ar, &format!("{p}.attn_sink_proj.weight"));
let wo_f = read_bf16_f32(&ar, &format!("{p}.wo_ud.weight"));
let vp_f = read_bf16_f32(&ar, &format!("{p}.v_sconv.weight_proj"));
let vw_raw = read_bf16_f32(&ar, &format!("{p}.v_sconv.static_w"));
let mut vs_f = vec![0f32; kv_dim * 4]; for lag in 0..4 { for ch in 0..kv_dim { vs_f[ch * 4 + (3 - lag)] = vw_raw[lag * kv_dim + ch]; } }
let v_raw_w = proj_cpu(&in2_bf_w, &wv_f, kv_dim, hidden);
let v_dyn_w = proj_cpu(&in2_bf_w, &vp_f, n_kv * 4, hidden);
let mut hv = vec![0f32; 3 * kv_dim];
let v_cv_w = sconv_dyn_step(&v_raw_w, &vs_f, &v_dyn_w, &mut hv, kv_dim, n_kv);
let mut gvc = vec![0f32; kv_dim]; v_cv.d2h(&mut gvc).unwrap(); cmp("v_dyn_sconv", &gvc, &v_cv_w);
let q_sc_f = read_bf16_f32(&ar, &format!("{p}.q_l2_clip.scale"));
let r_sc_f = read_bf16_f32(&ar, &format!("{p}.rel_l2_clip.scale"));
let rp_f = read_bf16_f32(&ar, &format!("{p}.rel_logits_proj.proj"));
let q_cl_w = l2_clip_cpu(&q_w, Some(&q_sc_f), n_head, hd, qk_clip);
let r_raw_w = proj_cpu(&in0_bf_w, &wr_f, n_head * d_rel, hidden);
let r_cl_w = l2_clip_cpu(&r_raw_w, Some(&r_sc_f), n_head, d_rel, rel_clip);
let k_cl_w = l2_clip_cpu(&k_cv_w, None, n_kv, hd, qk_clip);
let mut rb_w = vec![0f32; n_head * rel_extent];
for h in 0..n_head { let mut acc = 0f32; for rc in 0..d_rel { acc += r_cl_w[h * d_rel + rc] * rp_f[rc * rel_extent]; } rb_w[h * rel_extent] = acc; }
let mut kc_w = vec![0f32; n_kv * hd]; let mut vc_w = vec![0f32; n_kv * hd];
for h in 0..n_kv { let ss: f32 = (0..hd).map(|d| v_cv_w[h * hd + d] * v_cv_w[h * hd + d]).sum(); let fac = 1.0 / (ss / hd as f32 + eps).sqrt(); for d in 0..hd { kc_w[h * hd + d] = k_cl_w[h * hd + d]; vc_w[h * hd + d] = v_cv_w[h * hd + d] * fac; } }
let gatea_w = proj_cpu(&in0_bf_w, &wg_f, q_dim, hidden);
let sinks_w = proj_cpu(&in0_bf_w, &ws_f, n_head, hidden);
let mut aout_w = vec![0f32; q_dim];
for h in 0..n_head { let kvh = h / (n_head / n_kv); let sink = sinks_w[h]; let mut dot = 0f32; for d in 0..hd { dot += q_cl_w[h * hd + d] * kc_w[kvh * hd + d]; } dot = dot * scale + rb_w[h * rel_extent]; let m = sink.max(dot); let es = (dot - m).exp(); let denom = (sink - m).exp() + es; let inv = 1.0 / denom.max(1e-30); for d in 0..hd { let mut acc = es * inv * vc_w[kvh * hd + d]; acc *= 1.0 / (1.0 + (-gatea_w[h * hd + d]).exp()); aout_w[h * hd + d] = acc; } }
let mut gaout = vec![0f32; q_dim]; aout.d2h(&mut gaout).unwrap(); cmp("aout", &gaout, &aout_w);
let aout_bf_w: Vec<f32> = aout_w.iter().map(|&v| bf16_trunc(v)).collect();
let oproj_w = proj_cpu(&aout_bf_w, &wo_f, hidden, q_dim);
let as_f = read_bf16_f32(&ar, &format!("{l}.attn_sconv.weight"));
let mut ha = vec![0f32; 3 * hidden];
let asc_w = sconv_step(&oproj_w, &as_f, &mut ha, hidden);
let mut gasc = vec![0f32; hidden]; asc.d2h(&mut gasc).unwrap(); cmp("asc", &gasc, &asc_w);
let cur_c: Vec<f32> = x.iter().zip(&asc_w).map(|(a, b)| a + b).collect();
let mut gcur = vec![0f32; hidden]; cur.d2h(&mut gcur).unwrap();
// cur on GPU is still x (layer_forward not called); compute GPU cur = x + asc
let cur_gpu: Vec<f32> = x.iter().zip(&gasc).map(|(a, b)| a + b).collect();
cmp("cur_after_attn", &cur_gpu, &cur_c);
let ss2: f32 = cur_c.iter().map(|v| v * v).sum(); let ir2 = 1.0 / (ss2 / hidden as f32 + eps).sqrt();
let mix_c: Vec<f32> = cur_c.iter().map(|v| v * ir2).collect();
let mn_f = read_bf16_f32(&ar, &format!("{l}.mlp_norm.weight"));
let mlpin_c = rms_norm_cpu(&mix_c, &mn_f, eps);
// GPU mlpin from cur_gpu
let curbuf = DeviceBuf::alloc(hidden * 4).unwrap(); curbuf.h2d(&cur_gpu).unwrap();
let blk0 = DeviceBuf::alloc(hidden * 4).unwrap(); blk0.h2d(&vec![0f32; hidden]).unwrap();
let mixg = DeviceBuf::alloc(hidden * 4).unwrap(); vetta_infer_hip::attn_res_mix(&blk0, &curbuf, &lw.mlp_query, &mixg, 0, 1, 1, hidden as i32, eps).unwrap();
let mlping = DeviceBuf::alloc(hidden * 4).unwrap(); vetta_infer_hip::rms_norm_f32(&mixg, Some(&lw.mlp_norm), &mlping, 1, hidden as i32, eps).unwrap();
let mut gmlpin = vec![0f32; hidden]; mlping.d2h(&mut gmlpin).unwrap(); cmp("mlpin", &gmlpin, &mlpin_c);
let _ = gcur;
}
}