Files
vetta-infer/crates/vetta-infer-ld/src/packer.rs
T
adm 77c86535d0 [LD] REAL attention block end-to-end on Inkling weights — both layer halves now compose
- real_attention_block_end_to_end test: the attention half of a real Inkling
  layer-0 (SWA) runs end-to-end on real weights, composing the verified kernels:
  attn_norm -> cast -> 6 projections (wq_du/wk_dv/wv_dv/wr_du/gate_attn/
  attn_sink_proj via gemm_bf16) -> ShortConv4 K/V -> Q/R/K L2-clip (qk_clip
  22.627, rel_clip 8.0, tau off for SWA) -> relpos bias projection -> KV store
  (K clipped, V RMS-normalized) -> flash SWA GQA (window 1024 + relpos + sink +
  sigmoid gate) -> cast -> O-proj (wo_ud) -> attn ShortConv4.
- Run T=3 sequential decode steps so the KV cache + shortconv history rings
  grow autoregressively; parity vs a FULL CPU oracle at every step:
  max_rel_err 2.9e-6 / 3.9e-6 / 5.1e-6. The bf16 cast boundaries (input norm ->
  projections, attn out -> O-proj) are handled explicitly.
- With the real MoE block (5.6e-4), BOTH halves of a real Inkling layer now
  compose correctly on real data. Next: join them into a full layer with the
  AttnRes block-mix residual cadence (block_size=6), then loop controllers +
  multi-layer forward + lowering + sampling.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; real attention block PASS
(--features hip, --ignored).
2026-12-01 14:40:20 +01:00

539 lines
30 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,
}
/// Load expert `e` of layer `layer`, matrix `mat` ("w13" or "w2"), from the
/// real safetensors archive. Zero requantization: bytes go to device as-is.
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}"))?;
// w shape [n_exp, N, K/2]; scale [n_exp, N, K/16].
let n = winfo.shape[1] as i32;
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 })
}
#[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 = 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 = 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}");
}
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}");
}
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 { hist[ch] = hist[c + ch]; hist[c + ch] = hist[2 * c + ch]; hist[2 * c + ch] = 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 = 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);
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 attention block step {t}: max_rel_err={mr:.3e}");
assert!(mr < 3e-3, "real attention block step {t} parity failed: {mr}");
}
}
}