[Core] batched full-attn layer (M=B) bit-exact + l2_clip per-token tau

layer_forward_full_batched mirrors layer_forward_full at M=B: 3-query mix
[B*3,h] split strided via gather_channel(nq=3) into in0/in1/in2 with separate
q/k/v norms; DYNAMIC ShortConv K/V via shortconv4_prefill_par(dyn_taps[B,n_kv,4])
(already supported dyn path, no new kernel); Q/R l2_clip with per-token tau;
global flash window=0; MoE sublayer identical to batched SWA.

k_l2_clip gains pos_arr (device [M]): tau uses pos_arr[r/scale_rows] per token
(full-attn) else scalar pos. l2_clip passes null (M=1 unchanged); l2_clip_batched
takes Option<&DeviceBuf> pos_arr.

layer_full_batched_parity (real weights ip=5, B=8, f16 KV + device MoE):
cur[B,h] BIT-EXACT (0.0) AND KV byte-identical vs 8 sequential M=1 calls.
Both layer types (SWA + full-attn) now batched and verified.
This commit is contained in:
adm committed 2026-12-02 00:24:37 +01:00
1 parent 3dbb6bb1b4
commit 1aaf7f12c2
4 files changed
+170 -13

No files matched your search

+153 -3
View File
@@ -550,9 +550,9 @@ fn layer_forward_swa_batched(
vetta_infer_hip::shortconv4_update_hist(&k_raw, &st.hist_k[pass], b, kv_dim as i32)?;
vetta_infer_hip::shortconv4_prefill_par(&v_raw, &w.v_sconv, None, &st.hist_v[pass], &v_cv, b, kv_dim as i32, 0)?;
vetta_infer_hip::shortconv4_update_hist(&v_raw, &st.hist_v[pass], b, kv_dim as i32)?;
vetta_infer_hip::l2_clip_batched(&q, Some(&w.q_sc), (b as usize * d.n_head) as i32, d.hd as i32, d.qk_clip, false, 0, d.n_head as i32)?;
vetta_infer_hip::l2_clip_batched(&r_raw, Some(&w.r_sc), (b as usize * d.n_head) as i32, d.d_rel as i32, d.rel_clip, false, 0, d.n_head as i32)?;
vetta_infer_hip::l2_clip_batched(&k_cv, None, (b as usize * d.n_kv) as i32, d.hd as i32, d.qk_clip, false, 0, d.n_kv as i32)?;
vetta_infer_hip::l2_clip_batched(&q, Some(&w.q_sc), (b as usize * d.n_head) as i32, d.hd as i32, d.qk_clip, false, 0, d.n_head as i32, None)?;
vetta_infer_hip::l2_clip_batched(&r_raw, Some(&w.r_sc), (b as usize * d.n_head) as i32, d.d_rel as i32, d.rel_clip, false, 0, d.n_head as i32, None)?;
vetta_infer_hip::l2_clip_batched(&k_cv, None, (b as usize * d.n_kv) as i32, d.hd as i32, d.qk_clip, false, 0, d.n_kv as i32, None)?;
vetta_infer_hip::relpos_bias_batched(&r_raw, &w.rel_proj, &rel_bias, pos, d.n_head as i32, d.d_rel as i32, d.rel_extent as i32, b)?;
vetta_infer_hip::kv_store_f16_batched(&k_cv, &v_cv, &st.k_cache[pass], &st.v_cache[pass], pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps, b)?;
// k3: causal flash SWA GQA (M=B).
@@ -1109,6 +1109,107 @@ pub fn layer_forward_full(
Ok(())
}
/// Batched full-attention layer (M=B prefill): mirrors layer_forward_full. The
/// 3-query mix [B*3,h] is split strided (gather_channel nq=3) into in0/in1/in2,
/// each with its own q/k/v norm; K/V use DYNAMIC ShortConv taps (prefill_par with
/// dyn_taps [B,n_kv,4]); Q/R clip applies per-token tau (pos_arr); flash window=0
/// (global). MoE sublayer identical to the batched SWA layer.
#[allow(dead_code)] // wired by forward_batch (next brick)
fn layer_forward_full_batched(
cache: &WeightCache, w: &FullLayerWeights, st: &mut LayerState, d: &Dims,
cur: &DeviceBuf, blocks: &mut BatchBlocks, pos: &DeviceBuf, max_pos: i32,
pass: usize, b: i32, ctrl: Option<(&ControllerWeights, &DeviceBuf)>,
) -> Result<(), String> {
let h = d.hidden; let kv_dim = d.kv_dim(); let q_dim = d.q_dim();
let bu = b as usize;
// 3-query mix -> [B*3,h], strided split into in0/in1/in2 [B,h].
let mx3 = DeviceBuf::alloc(bu * 3 * h * 4)?;
vetta_infer_hip::attn_res_mix(&blocks.arena, cur, &w.attn_query, &mx3, blocks.count as i32, b, 3, h as i32, d.eps)?;
let in0 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(&mx3, &in0, 0, b, h as i32, 3)?;
let in1 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(&mx3, &in1, 1, b, h as i32, 3)?;
let in2 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(&mx3, &in2, 2, b, h as i32, 3)?;
if let Some((cw, msgs)) = ctrl {
let msg0 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(msgs, &msg0, 0, b, h as i32, 4)?;
let msg1 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(msgs, &msg1, 1, b, h as i32, 4)?;
let msg2 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(msgs, &msg2, 2, b, h as i32, 4)?;
apply_controller_batched(&in0, &msg0, cw, 0, h, 64, d.eps, b)?;
apply_controller_batched(&in1, &msg1, cw, 1, h, 64, d.eps, b)?;
apply_controller_batched(&in2, &msg2, cw, 2, h, 64, d.eps, b)?;
}
vetta_infer_hip::rms_norm_f32(&in0, Some(&w.q_norm), &in0, b, h as i32, d.eps)?;
vetta_infer_hip::rms_norm_f32(&in1, Some(&w.k_norm), &in1, b, h as i32, d.eps)?;
vetta_infer_hip::rms_norm_f32(&in2, Some(&w.v_norm), &in2, b, h as i32, d.eps)?;
let in0_bf = DeviceBuf::alloc(bu * h * 2)?; vetta_infer_hip::cast_f32_bf16(&in0, &in0_bf, bu * h)?;
let in1_bf = DeviceBuf::alloc(bu * h * 2)?; vetta_infer_hip::cast_f32_bf16(&in1, &in1_bf, bu * h)?;
let in2_bf = DeviceBuf::alloc(bu * h * 2)?; vetta_infer_hip::cast_f32_bf16(&in2, &in2_bf, bu * h)?;
let q = DeviceBuf::alloc(bu * q_dim * 4)?;
let k_raw = DeviceBuf::alloc(bu * kv_dim * 4)?;
let v_raw = DeviceBuf::alloc(bu * kv_dim * 4)?;
let r_raw = DeviceBuf::alloc(bu * d.n_head * d.d_rel * 4)?;
let gatea = DeviceBuf::alloc(bu * q_dim * 4)?;
let sinks = DeviceBuf::alloc(bu * d.n_head * 4)?;
vetta_infer_hip::gemm_bf16(&in0_bf, &w.wq, &q, b, q_dim as i32, h as i32)?;
vetta_infer_hip::gemm_bf16(&in1_bf, &w.wk, &k_raw, b, kv_dim as i32, h as i32)?;
vetta_infer_hip::gemm_bf16(&in2_bf, &w.wv, &v_raw, b, kv_dim as i32, h as i32)?;
vetta_infer_hip::gemm_bf16(&in0_bf, &w.wr, &r_raw, b, (d.n_head * d.d_rel) as i32, h as i32)?;
vetta_infer_hip::gemm_bf16(&in0_bf, &w.wg, &gatea, b, q_dim as i32, h as i32)?;
vetta_infer_hip::gemm_bf16(&in0_bf, &w.ws, &sinks, b, d.n_head as i32, h as i32)?;
// dynamic ShortConv taps [B,n_kv,4] + dyn prefill K/V.
let k_dyn = DeviceBuf::alloc(bu * d.n_kv * 4 * 4)?;
let v_dyn = DeviceBuf::alloc(bu * d.n_kv * 4 * 4)?;
vetta_infer_hip::gemm_bf16(&in1_bf, &w.k_proj, &k_dyn, b, (d.n_kv * 4) as i32, h as i32)?;
vetta_infer_hip::gemm_bf16(&in2_bf, &w.v_proj, &v_dyn, b, (d.n_kv * 4) as i32, h as i32)?;
let k_cv = DeviceBuf::alloc(bu * kv_dim * 4)?;
let v_cv = DeviceBuf::alloc(bu * kv_dim * 4)?;
vetta_infer_hip::shortconv4_prefill_par(&k_raw, &w.k_static, Some(&k_dyn), &st.hist_k[pass], &k_cv, b, kv_dim as i32, d.n_kv as i32)?;
vetta_infer_hip::shortconv4_update_hist(&k_raw, &st.hist_k[pass], b, kv_dim as i32)?;
vetta_infer_hip::shortconv4_prefill_par(&v_raw, &w.v_static, Some(&v_dyn), &st.hist_v[pass], &v_cv, b, kv_dim as i32, d.n_kv as i32)?;
vetta_infer_hip::shortconv4_update_hist(&v_raw, &st.hist_v[pass], b, kv_dim as i32)?;
// tau on Q/R (per-token pos), K clip without tau.
vetta_infer_hip::l2_clip_batched(&q, Some(&w.q_sc), (b as usize * d.n_head) as i32, d.hd as i32, d.qk_clip, true, 0, d.n_head as i32, Some(pos))?;
vetta_infer_hip::l2_clip_batched(&r_raw, Some(&w.r_sc), (b as usize * d.n_head) as i32, d.d_rel as i32, d.rel_clip, true, 0, d.n_head as i32, Some(pos))?;
vetta_infer_hip::l2_clip_batched(&k_cv, None, (b as usize * d.n_kv) as i32, d.hd as i32, d.qk_clip, false, 0, d.n_kv as i32, None)?;
let rel_bias = DeviceBuf::alloc(bu * d.n_head * d.rel_extent * 4)?;
rel_bias.h2d(&vec![0f32; bu * d.n_head * d.rel_extent])?;
vetta_infer_hip::relpos_bias_batched(&r_raw, &w.rel_proj, &rel_bias, pos, d.n_head as i32, d.d_rel as i32, d.rel_extent as i32, b)?;
vetta_infer_hip::kv_store_f16_batched(&k_cv, &v_cv, &st.k_cache[pass], &st.v_cache[pass], pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps, b)?;
let aout = DeviceBuf::alloc(bu * q_dim * 4)?;
// global attention: window = 0.
vetta_infer_hip::flash_swa_gqa_prefill_f16(&q, &st.k_cache[pass], &st.v_cache[pass], &aout, d.n_head as i32, d.n_kv as i32, st.max_seq as i32, d.hd as i32, d.scale(), 0, pos, max_pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea), b)?;
let aout_bf = DeviceBuf::alloc(bu * q_dim * 2)?; vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, bu * q_dim)?;
let oproj = DeviceBuf::alloc(bu * h * 4)?;
vetta_infer_hip::gemm_bf16(&aout_bf, &w.wo, &oproj, b, h as i32, q_dim as i32)?;
let asc = DeviceBuf::alloc(bu * h * 4)?;
vetta_infer_hip::shortconv4_prefill_par(&oproj, &w.a_sconv, None, &st.hist_a[pass], &asc, b, h as i32, 0)?;
vetta_infer_hip::shortconv4_update_hist(&oproj, &st.hist_a[pass], b, h as i32)?;
if w.ip % d.block_size == 0 {
blocks.snapshot(cur)?;
vetta_infer_hip::copy_f32(&asc, cur, bu * h)?;
} else {
vetta_infer_hip::vec_add(cur, &asc, cur, bu * h)?;
}
// MoE sublayer (identical to batched SWA).
let mix = DeviceBuf::alloc(bu * h * 4)?;
vetta_infer_hip::attn_res_mix(&blocks.arena, cur, &w.mlp_query, &mix, blocks.count as i32, b, 1, h as i32, d.eps)?;
if let Some((cw, msgs)) = ctrl {
let msg3 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(msgs, &msg3, 3, b, h as i32, 4)?;
apply_controller_batched(&mix, &msg3, cw, 3, h, 64, d.eps, b)?;
}
let mlpin = DeviceBuf::alloc(bu * h * 4)?;
vetta_infer_hip::rms_norm_f32(&mix, Some(&w.mlp_norm), &mlpin, b, h as i32, d.eps)?;
let rlog = DeviceBuf::alloc(bu * d.n_experts * 4)?;
vetta_infer_hip::router_gemv_batched(&mlpin, &w.gate_w, &rlog, d.n_experts as i32, h as i32, b)?;
let ids = DeviceBuf::alloc(bu * d.top_k * 4)?;
let weights = DeviceBuf::alloc(bu * d.top_k * 4)?;
vetta_infer_hip::moe_router_topk(&rlog, Some(&w.gate_b), &ids, &weights, b, d.n_experts as i32, d.top_k as i32, d.route_scale)?;
let moeout = moe_batched(cache, w.ip, &mlpin, &ids, &weights, d, h, b)?;
let msc = DeviceBuf::alloc(bu * h * 4)?;
vetta_infer_hip::shortconv4_prefill_par(&moeout, &w.m_sconv, None, &st.hist_m[pass], &msc, b, h as i32, 0)?;
vetta_infer_hip::shortconv4_update_hist(&moeout, &st.hist_m[pass], b, h as i32)?;
vetta_infer_hip::vec_add(cur, &msc, cur, bu * h)?;
Ok(())
}
/// Loop-controller weights for one layer (4 channels: attn/k/v/mlp), each a
/// low-rank down->gain/forget gate applied to the layer input with a message.
pub struct ControllerWeights {
@@ -1413,4 +1514,53 @@ mod tests {
assert!(max_rel < 3e-3, "batched SWA layer cur parity failed: {max_rel}");
assert!(kv_match, "batched SWA layer KV cache must be byte-identical");
}
/// Batched full-attn layer (M=B) vs B sequential M=1 layer_forward_full on REAL
/// weights (ip=5, no snapshot): 3-query split, dyn ShortConv, per-token tau,
/// global window. Aligns f16 KV + device MoE. Compares cur[B,h] AND KV cache.
#[test]
#[ignore]
fn layer_full_batched_parity() {
set_kv_f16(true);
unsafe { std::env::set_var("VETTA_DEVICE_MOE", "1") };
let ar = Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
let cache = WeightCache::new(ar.clone());
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 h = d.hidden; let b = 8usize; let base = 5i32; let ip = 5usize;
let w = cache.full_layer(ip, &d).unwrap();
let cur_h: Vec<f32> = (0..b * h).map(|i| ((i % 37) as f32 - 18.0) * 0.02).collect();
let seed_h: Vec<f32> = (0..b * h).map(|i| ((i % 29) as f32 - 14.0) * 0.01).collect();
let max_seq = (base + b as i32 + 2) as usize;
let pos: Vec<i32> = (0..b).map(|m| base + m as i32).collect();
let pos_bytes: Vec<u8> = pos.iter().flat_map(|x| x.to_le_bytes()).collect();
let dpos = DeviceBuf::alloc(b * 4).unwrap(); dpos.h2d_bytes(&pos_bytes).unwrap();
let cur_b = DeviceBuf::alloc(b * h * 4).unwrap(); cur_b.h2d(&cur_h).unwrap();
let mut blocks_b = BatchBlocks::new(b, h, 8).unwrap();
let seed_buf = DeviceBuf::alloc(b * h * 4).unwrap(); seed_buf.h2d(&seed_h).unwrap();
blocks_b.snapshot(&seed_buf).unwrap();
let mut st_b = new_state(&d, max_seq, 1).unwrap();
layer_forward_full_batched(&cache, &w, &mut st_b, &d, &cur_b, &mut blocks_b, &dpos, base + b as i32 - 1, 0, b as i32, None).unwrap();
let mut cb = vec![0f32; b * h]; cur_b.d2h(&mut cb).unwrap();
let mut st_s = new_state(&d, max_seq, 1).unwrap();
let mut cs = vec![0f32; b * h];
for m in 0..b {
let cur_m = DeviceBuf::alloc(h * 4).unwrap(); cur_m.h2d(&cur_h[m * h..(m + 1) * h]).unwrap();
let seed_m = DeviceBuf::alloc(h * 4).unwrap(); seed_m.h2d(&seed_h[m * h..(m + 1) * h]).unwrap();
let mut blocks_m = vec![seed_m];
layer_forward_full(&cache, &w, &mut st_s, &d, &cur_m, &mut blocks_m, base + m as i32, 0, None).unwrap();
let mut o = vec![0f32; h]; cur_m.d2h(&mut o).unwrap();
cs[m * h..(m + 1) * h].copy_from_slice(&o);
}
let mut max_rel = 0f32;
for (g, wnt) in cb.iter().zip(cs.iter()) { max_rel = max_rel.max((g - wnt).abs() / wnt.abs().max(1e-3)); }
let kvn = d.n_kv * max_seq * d.hd * 2;
let mut kb = vec![0u8; kvn]; st_b.k_cache[0].d2h_bytes(&mut kb).unwrap();
let mut ks = vec![0u8; kvn]; st_s.k_cache[0].d2h_bytes(&mut ks).unwrap();
let kv_match = kb == ks;
eprintln!("layer_full_batched ip={ip} B={b} cur_max_rel={max_rel:.3e} kv_byte_identical={kv_match}");
set_kv_f16(false);
unsafe { std::env::remove_var("VETTA_DEVICE_MOE") };
assert!(max_rel < 3e-3, "batched full layer cur parity failed: {max_rel}");
assert!(kv_match, "batched full layer KV cache must be byte-identical");
}
}