[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).
This commit is contained in:
adm committed 2026-12-01 14:40:20 +01:00
1 parent b5d6d7cee3
commit 77c86535d0
1 file changed
+191
+191
View File
@@ -345,4 +345,195 @@ mod tests {
eprintln!("REAL MoE block end-to-end: experts={:?} max_rel_err={max_rel:.3e}", ids_cpu); 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}"); 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}");
}
}
} }