From 5ae2072981030d6d122defddfd6ec200844d3cdd Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Tue, 1 Dec 2026 15:02:17 +0100 Subject: [PATCH] [LD] full-attention layer forward (3-query mix, dyn ShortConv, tau, global attn) - ld::layer: FullLayerWeights + load_full_layer + layer_forward_full + load_sconv_transposed (the full-attn k/v_sconv.static_w tensor is [4,C], transposed to the kernel's [C,4] layout). The full-attn layer step: mx3 = attn_res_mix(blocks, cur, attn_queries[ip-1] (3 queries)) -> split in0/in1/in2 = rms_norm(mx3[j], q/k/v_input_norm.weight) (separate norms) q/r/gate/sink from in0; k from in1; v from in2 (distinct inputs) k_dyn/v_dyn = in1/in2 @ k/v_sconv.weight_proj; dyn ShortConv4 K/V (1/3) Q/R L2-clip with tau (full-attn), K clip without; relpos bias; KV store global flash attention (window=0); O-proj + attn ShortConv; block cadence MoE sublayer identical to SWA. - full_attn_layer_end_to_end test: layer 5 on real weights, seeded with one depth block; finite residual + correct cadence (ip=5 %6!=0 -> no snapshot). Smoke-verified composition (all constituent kernels are individually parity-verified); a full CPU-oracle parity of the full-attn wiring is a follow-up refinement. Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS; lean proofs (5 files) green; full-attn layer end-to-end PASS (--features hip, --ignored). --- crates/vetta-infer-ld/src/layer.rs | 196 +++++++++++++++++++++++++++++ 1 file changed, 196 insertions(+) diff --git a/crates/vetta-infer-ld/src/layer.rs b/crates/vetta-infer-ld/src/layer.rs index 1a52fa9..a9137e6 100644 --- a/crates/vetta-infer-ld/src/layer.rs +++ b/crates/vetta-infer-ld/src/layer.rs @@ -274,6 +274,178 @@ pub fn forward_swa_layers( Ok((cur, blocks)) } +/// Load a full-attn ShortConv static weight tensor [4, C] transposed to the +/// kernel's [C, 4] layout (the reference reads sw[c*4+k]). +fn load_sconv_transposed(ar: &SafetensorsArchive, name: &str, c: usize) -> Result { + let info = ar.tensors.get(name).ok_or_else(|| format!("missing {name}"))?; + let mut b = vec![0u8; info.byte_len() as usize]; + ar.read_slice(name, 0, &mut b)?; + let f: Vec = b.chunks_exact(2).map(|x| f32::from_bits((u16::from_le_bytes([x[0], x[1]]) as u32) << 16)).collect(); + // f is [4, C]; transpose to [C, 4]. + let mut t = vec![0f32; c * 4]; + for k in 0..4 { for ch in 0..c { t[ch * 4 + k] = f[k * c + ch]; } } + let buf = DeviceBuf::alloc(c * 4 * 4)?; buf.h2d(&t)?; Ok(buf) +} + +/// Resident weights for a full-attention layer step (3-query mix, separate +/// q/k/v input norms, dynamic ShortConv, tau, global attention). +pub struct FullLayerWeights { + pub ip: usize, + pub q_norm: DeviceBuf, pub k_norm: DeviceBuf, pub v_norm: DeviceBuf, + pub wq: DeviceBuf, pub wk: DeviceBuf, pub wv: DeviceBuf, pub wr: DeviceBuf, + pub wg: DeviceBuf, pub ws: DeviceBuf, pub wo: DeviceBuf, + pub q_sc: DeviceBuf, pub r_sc: DeviceBuf, pub rel_proj: DeviceBuf, + pub k_static: DeviceBuf, pub v_static: DeviceBuf, pub k_proj: DeviceBuf, pub v_proj: DeviceBuf, + pub a_sconv: DeviceBuf, + pub mlp_norm: DeviceBuf, pub gate_w: DeviceBuf, pub gate_b: DeviceBuf, pub m_sconv: DeviceBuf, + pub attn_query: DeviceBuf, // [3, hidden] + pub mlp_query: DeviceBuf, +} + +pub fn load_full_layer(ar: &SafetensorsArchive, ip: usize, d: &Dims) -> Result { + let p = format!("model.llm.layers.{ip}.attn"); + let l = format!("model.llm.layers.{ip}"); + Ok(FullLayerWeights { + ip, + q_norm: load_bf16_as_f32(ar, &format!("{l}.q_input_norm.weight"))?, + k_norm: load_bf16_as_f32(ar, &format!("{l}.k_input_norm.weight"))?, + v_norm: load_bf16_as_f32(ar, &format!("{l}.v_input_norm.weight"))?, + wq: load_raw(ar, &format!("{p}.wq_du.weight"))?, + wk: load_raw(ar, &format!("{p}.wk_dv.weight"))?, + wv: load_raw(ar, &format!("{p}.wv_dv.weight"))?, + wr: load_raw(ar, &format!("{p}.wr_du.weight"))?, + wg: load_raw(ar, &format!("{p}.gate_attn.weight"))?, + ws: load_raw(ar, &format!("{p}.attn_sink_proj.weight"))?, + wo: load_raw(ar, &format!("{p}.wo_ud.weight"))?, + q_sc: load_bf16_as_f32(ar, &format!("{p}.q_l2_clip.scale"))?, + r_sc: load_bf16_as_f32(ar, &format!("{p}.rel_l2_clip.scale"))?, + rel_proj: load_bf16_as_f32(ar, &format!("{p}.rel_logits_proj.proj"))?, + k_static: load_sconv_transposed(ar, &format!("{p}.k_sconv.static_w"), d.kv_dim())?, + v_static: load_sconv_transposed(ar, &format!("{p}.v_sconv.static_w"), d.kv_dim())?, + k_proj: load_raw(ar, &format!("{p}.k_sconv.weight_proj"))?, + v_proj: load_raw(ar, &format!("{p}.v_sconv.weight_proj"))?, + a_sconv: load_bf16_as_f32(ar, &format!("{l}.attn_sconv.weight"))?, + mlp_norm: load_bf16_as_f32(ar, &format!("{l}.mlp_norm.weight"))?, + gate_w: load_raw(ar, &format!("{l}.mlp.gate.weight"))?, + gate_b: load_raw(ar, &format!("{l}.mlp.gate.bias"))?, + m_sconv: load_bf16_as_f32(ar, &format!("{l}.mlp_sconv.weight"))?, + attn_query: load_raw(ar, &format!("model.llm.attn_res.attn_queries.{}", ip - 1))?, + mlp_query: load_raw(ar, &format!("model.llm.attn_res.mlp_queries.{ip}"))?, + }) +} + +/// Run one full-attention layer step on `cur` (in place). 3-query AttnRes mix +/// split into in0/in1/in2, separate q/k/v norms, projections from distinct +/// inputs, dynamic ShortConv K/V, tau on Q/R, global (window=0) flash attention. +pub fn layer_forward_full( + ar: &SafetensorsArchive, w: &FullLayerWeights, st: &mut LayerState, d: &Dims, + cur: &DeviceBuf, blocks: &mut Vec, pos: i32, +) -> Result<(), String> { + let h = d.hidden; let kv_dim = d.kv_dim(); let q_dim = d.q_dim(); + let slot0 = DeviceBuf::alloc(4)?; slot0.h2d_bytes(&0i32.to_le_bytes())?; + // 3-query mix -> [3, h], split into in0/in1/in2. + let n_blocks = blocks.len(); + let blk = DeviceBuf::alloc(n_blocks.max(1) * h * 4)?; + let mut bh = vec![0f32; n_blocks.max(1) * h]; + for (i, b) in blocks.iter().enumerate() { b.d2h(&mut bh[i * h..(i + 1) * h])?; } + blk.h2d(&bh)?; + let mx3 = DeviceBuf::alloc(3 * h * 4)?; + vetta_infer_hip::attn_res_mix(&blk, cur, &w.attn_query, &mx3, n_blocks as i32, 1, 3, h as i32, d.eps)?; + let mut mx_h = vec![0f32; 3 * h]; mx3.d2h(&mut mx_h)?; + let in0 = DeviceBuf::alloc(h * 4)?; in0.h2d(&mx_h[0..h])?; + let in1 = DeviceBuf::alloc(h * 4)?; in1.h2d(&mx_h[h..2 * h])?; + let in2 = DeviceBuf::alloc(h * 4)?; in2.h2d(&mx_h[2 * h..3 * h])?; + vetta_infer_hip::rms_norm_f32(&in0, Some(&w.q_norm), &in0, 1, h as i32, d.eps)?; + vetta_infer_hip::rms_norm_f32(&in1, Some(&w.k_norm), &in1, 1, h as i32, d.eps)?; + vetta_infer_hip::rms_norm_f32(&in2, Some(&w.v_norm), &in2, 1, h as i32, d.eps)?; + // projections: q/r/gate/sink from in0; k from in1; v from in2. + let in0_bf = DeviceBuf::alloc(h * 2)?; vetta_infer_hip::cast_f32_bf16(&in0, &in0_bf, h)?; + let in1_bf = DeviceBuf::alloc(h * 2)?; vetta_infer_hip::cast_f32_bf16(&in1, &in1_bf, h)?; + let in2_bf = DeviceBuf::alloc(h * 2)?; vetta_infer_hip::cast_f32_bf16(&in2, &in2_bf, h)?; + let q = DeviceBuf::alloc(q_dim * 4)?; + let k_raw = DeviceBuf::alloc(kv_dim * 4)?; + let v_raw = DeviceBuf::alloc(kv_dim * 4)?; + let r_raw = DeviceBuf::alloc(d.n_head * d.d_rel * 4)?; + let gatea = DeviceBuf::alloc(q_dim * 4)?; + let sinks = DeviceBuf::alloc(d.n_head * 4)?; + vetta_infer_hip::gemm_bf16(&in0_bf, &w.wq, &q, 1, q_dim as i32, h as i32)?; + vetta_infer_hip::gemm_bf16(&in1_bf, &w.wk, &k_raw, 1, kv_dim as i32, h as i32)?; + vetta_infer_hip::gemm_bf16(&in2_bf, &w.wv, &v_raw, 1, kv_dim as i32, h as i32)?; + vetta_infer_hip::gemm_bf16(&in0_bf, &w.wr, &r_raw, 1, (d.n_head * d.d_rel) as i32, h as i32)?; + vetta_infer_hip::gemm_bf16(&in0_bf, &w.wg, &gatea, 1, q_dim as i32, h as i32)?; + vetta_infer_hip::gemm_bf16(&in0_bf, &w.ws, &sinks, 1, d.n_head as i32, h as i32)?; + // dynamic shortconv taps + dyn shortconv K/V. + let k_dyn = DeviceBuf::alloc(d.n_kv * 4 * 4)?; + let v_dyn = DeviceBuf::alloc(d.n_kv * 4 * 4)?; + vetta_infer_hip::gemm_bf16(&in1_bf, &w.k_proj, &k_dyn, 1, (d.n_kv * 4) as i32, h as i32)?; + vetta_infer_hip::gemm_bf16(&in2_bf, &w.v_proj, &v_dyn, 1, (d.n_kv * 4) as i32, h as i32)?; + let k_cv = DeviceBuf::alloc(kv_dim * 4)?; + let v_cv = DeviceBuf::alloc(kv_dim * 4)?; + vetta_infer_hip::shortconv4_dyn_decode(&k_raw, &w.k_static, &k_dyn, &st.hist_k, &k_cv, &slot0, 1, kv_dim as i32, d.n_kv as i32)?; + vetta_infer_hip::shortconv4_dyn_decode(&v_raw, &w.v_static, &v_dyn, &st.hist_v, &v_cv, &slot0, 1, kv_dim as i32, d.n_kv as i32)?; + // tau on Q/R (full-attn), K clip without tau. + vetta_infer_hip::l2_clip(&q, Some(&w.q_sc), d.n_head as i32, d.hd as i32, d.qk_clip, true, pos)?; + vetta_infer_hip::l2_clip(&r_raw, Some(&w.r_sc), d.n_head as i32, d.d_rel as i32, d.rel_clip, true, pos)?; + vetta_infer_hip::l2_clip(&k_cv, None, d.n_kv as i32, d.hd as i32, d.qk_clip, false, pos)?; + let rel_bias = DeviceBuf::alloc(d.n_head * d.rel_extent * 4)?; + rel_bias.h2d(&vec![0f32; d.n_head * d.rel_extent])?; + let lim = (pos + 1).min(d.rel_extent as i32); + vetta_infer_hip::relpos_bias(&r_raw, &w.rel_proj, &rel_bias, d.n_head as i32, d.d_rel as i32, d.rel_extent as i32, lim)?; + vetta_infer_hip::kv_store(&k_cv, &v_cv, &st.k_cache, &st.v_cache, pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps)?; + let aout = DeviceBuf::alloc(q_dim * 4)?; + // global attention: window = 0. + vetta_infer_hip::flash_swa_gqa_decode(&q, &st.k_cache, &st.v_cache, &aout, d.n_head as i32, d.n_kv as i32, st.max_seq as i32, d.hd as i32, d.scale(), 0, pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea))?; + let aout_bf = DeviceBuf::alloc(q_dim * 2)?; vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, q_dim)?; + let oproj = DeviceBuf::alloc(h * 4)?; + vetta_infer_hip::gemm_bf16(&aout_bf, &w.wo, &oproj, 1, h as i32, q_dim as i32)?; + let asc = DeviceBuf::alloc(h * 4)?; + vetta_infer_hip::shortconv4_decode(&oproj, &w.a_sconv, &st.hist_a, &asc, &slot0, 1, h as i32)?; + if w.ip % d.block_size == 0 { + let mut cur_h = vec![0f32; h]; cur.d2h(&mut cur_h)?; + let snap = DeviceBuf::alloc(h * 4)?; snap.h2d(&cur_h)?; blocks.push(snap); + let mut asc_h = vec![0f32; h]; asc.d2h(&mut asc_h)?; cur.h2d(&asc_h)?; + } else { + vetta_infer_hip::vec_add(cur, &asc, cur, h)?; + } + // MoE sublayer (identical to SWA): mlp_norm(mix(blocks,cur,mlp_query)) -> router -> experts -> reduce -> sconv -> add. + let n_blocks = blocks.len(); + let blk = DeviceBuf::alloc(n_blocks.max(1) * h * 4)?; + let mut bh = vec![0f32; n_blocks.max(1) * h]; + for (i, b) in blocks.iter().enumerate() { b.d2h(&mut bh[i * h..(i + 1) * h])?; } + blk.h2d(&bh)?; + let mix = DeviceBuf::alloc(h * 4)?; + vetta_infer_hip::attn_res_mix(&blk, cur, &w.mlp_query, &mix, n_blocks as i32, 1, 1, h as i32, d.eps)?; + let mlpin = DeviceBuf::alloc(h * 4)?; + vetta_infer_hip::rms_norm_f32(&mix, Some(&w.mlp_norm), &mlpin, 1, h as i32, d.eps)?; + let mlpin_bf = DeviceBuf::alloc(h * 2)?; vetta_infer_hip::cast_f32_bf16(&mlpin, &mlpin_bf, h)?; + let rlog = DeviceBuf::alloc(d.n_experts * 4)?; + vetta_infer_hip::gemm_bf16(&mlpin_bf, &w.gate_w, &rlog, 1, d.n_experts as i32, h as i32)?; + let ids = DeviceBuf::alloc(d.top_k * 4)?; + let weights = DeviceBuf::alloc(d.top_k * 4)?; + vetta_infer_hip::moe_router_topk(&rlog, Some(&w.gate_b), &ids, &weights, 1, d.n_experts as i32, d.top_k as i32, d.route_scale)?; + let ids_h = { let mut b = vec![0u8; d.top_k * 4]; ids.d2h_bytes(&mut b)?; b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::>() }; + let gu = DeviceBuf::alloc(2 * d.inter * 4)?; + let act = DeviceBuf::alloc(d.inter * 4)?; + let mut y_part_h = vec![0f32; d.top_k * h]; + for kk in 0..d.top_k { + let e = ids_h[kk] as usize; + let w13 = load_expert_matrix(ar, w.ip, e, "w13")?; + vetta_infer_hip::nvfp4_gemv(&w13.packed, &w13.scales, w13.outer, &mlpin, &gu, w13.n, w13.k)?; + vetta_infer_hip::situ(&gu, &act, d.inter as i32, d.beta, d.lb)?; + let w2 = load_expert_matrix(ar, w.ip, e, "w2")?; + let ye = DeviceBuf::alloc(h * 4)?; + vetta_infer_hip::nvfp4_gemv(&w2.packed, &w2.scales, w2.outer, &act, &ye, w2.n, w2.k)?; + ye.d2h(&mut y_part_h[kk * h..(kk + 1) * h])?; + } + let y_part = DeviceBuf::alloc(d.top_k * h * 4)?; y_part.h2d(&y_part_h)?; + let moeout = DeviceBuf::alloc(h * 4)?; + vetta_infer_hip::moe_reduce(&y_part, &weights, &moeout, d.top_k as i32, h as i32)?; + let msc = DeviceBuf::alloc(h * 4)?; + vetta_infer_hip::shortconv4_decode(&moeout, &w.m_sconv, &st.hist_m, &msc, &slot0, 1, h as i32)?; + vetta_infer_hip::vec_add(cur, &msc, cur, h)?; + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -298,4 +470,28 @@ mod tests { eprintln!("multi-layer prelude (0..4) forward: argmax token={argmax} logit={:.3}", lg[argmax]); assert!(argmax < 201024); } + + /// Full-attention layer (ip=5) end-to-end on real weights: 3-query AttnRes + /// mix split + separate q/k/v norms + projections from distinct inputs + + /// dynamic ShortConv K/V + tau + global attention + MoE. Seeded with one + /// depth block (as after ip=0); ip=5 % 6 != 0 so no new snapshot. Verifies + /// the full-attn path composes and produces a finite residual stream. + #[test] + #[ignore] + fn full_attn_layer_end_to_end() { + let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap(); + let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; + let cur = embed_token(&ar, 100, d.hidden, 201024).unwrap(); + let mut blocks: Vec = Vec::new(); + let mut seed = vec![0f32; d.hidden]; cur.d2h(&mut seed).unwrap(); + let b0 = DeviceBuf::alloc(d.hidden * 4).unwrap(); b0.h2d(&seed).unwrap(); blocks.push(b0); + let w = load_full_layer(&ar, 5, &d).unwrap(); + let mut st = new_state(&d, 1).unwrap(); + layer_forward_full(&ar, &w, &mut st, &d, &cur, &mut blocks, 0).unwrap(); + assert_eq!(blocks.len(), 1, "ip=5 does not snapshot (5%6!=0)"); + let mut out = vec![0f32; d.hidden]; cur.d2h(&mut out).unwrap(); + assert!(out.iter().all(|v| v.is_finite()), "full-attn residual must be finite"); + assert!(out.iter().any(|&v| v != seed[0]), "full-attn layer must transform the residual"); + eprintln!("full-attn layer (ip=5) end-to-end: finite residual, no new snapshot"); + } } \ No newline at end of file