[Core] batched SWA layer (M=B) bit-exact vs sequential + BatchBlocks arena + batched controller

layer_forward_swa_batched mirrors layer_forward_swa at M=B: device-resident
BatchBlocks arena [max_blocks,B,h] (attn_res_mix reads directly, snapshot via
copy_f32_at, truncate for bank rollback), strided msgs gather + apply_controller_batched
(ctrl_pack_batched + gemm M=B + ctrl_apply), shortconv prefill_par+update_hist,
l2_clip_batched, relpos/kv_store/flash prefill, router_gemv_batched + moe_batched.

layer_swa_batched_parity (real weights ip=1, B=8, f16 KV + device MoE aligned):
cur[B,h] BIT-EXACT (0.0) AND KV cache byte-identical vs 8 sequential M=1 calls.
Found+fixed the l2_clip out-of-bounds scale bug via per-stage bisection.
This commit is contained in:
adm committed 2026-12-02 00:21:00 +01:00
1 parent 51b230cdd2
commit 3dbb6bb1b4
1 file changed
+211
+211
View File
@@ -477,6 +477,121 @@ pub fn layer_forward_swa(
Ok(())
}
/// Batched SWA layer (M=B prefill): mirrors layer_forward_swa with every kernel
/// at M=B. cur [B,h] in place; blocks is the device-resident arena; pos [B] device
/// (per-token causal positions), max_pos = largest pos. ctrl msgs is [B*4,h] device
/// (attn_res_mix output); channels gathered strided. KV cache filled for all B
/// positions before the causal flash reads. ShortConv uses prefill_par + update_hist.
#[allow(dead_code)] // wired by forward_batch (next brick)
fn layer_forward_swa_batched(
cache: &WeightCache, w: &LayerWeights, 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;
let k_cv = DeviceBuf::alloc(bu * kv_dim * 4)?;
let v_cv = DeviceBuf::alloc(bu * kv_dim * 4)?;
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])?;
let aout = DeviceBuf::alloc(bu * q_dim * 4)?;
let aout_bf = DeviceBuf::alloc(bu * q_dim * 2)?;
let oproj = DeviceBuf::alloc(bu * h * 4)?;
let asc = DeviceBuf::alloc(bu * h * 4)?;
// k1: attention input base.
let base = DeviceBuf::alloc(bu * h * 4)?;
if w.ip == 0 {
vetta_infer_hip::copy_f32(cur, &base, bu * h)?;
} else {
let aq = w.attn_query.as_ref().ok_or("ip>0 needs attn_query")?;
vetta_infer_hip::attn_res_mix(&blocks.arena, cur, aq, &base, blocks.count as i32, b, 1, h as i32, d.eps)?;
}
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)?;
let in0_bf = DeviceBuf::alloc(bu * h * 2)?;
if let Some((cw, msgs)) = ctrl {
let in1 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::copy_f32(&base, &in1, bu * h)?;
let in2 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::copy_f32(&base, &in2, bu * h)?;
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(&base, &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(&base, Some(&w.attn_norm), &base, b, h as i32, d.eps)?;
vetta_infer_hip::rms_norm_f32(&in1, Some(&w.attn_norm), &in1, b, h as i32, d.eps)?;
vetta_infer_hip::rms_norm_f32(&in2, Some(&w.attn_norm), &in2, b, h as i32, d.eps)?;
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)?;
vetta_infer_hip::cast_f32_bf16(&base, &in0_bf, bu * h)?;
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)?;
} else {
let in0 = DeviceBuf::alloc(bu * h * 4)?;
vetta_infer_hip::rms_norm_f32(&base, Some(&w.attn_norm), &in0, b, h as i32, d.eps)?;
vetta_infer_hip::cast_f32_bf16(&in0, &in0_bf, bu * h)?;
vetta_infer_hip::gemm_bf16(&in0_bf, &w.wq, &q, b, q_dim as i32, h as i32)?;
vetta_infer_hip::gemm_bf16(&in0_bf, &w.wk, &k_raw, b, kv_dim as i32, h as i32)?;
vetta_infer_hip::gemm_bf16(&in0_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)?;
}
// k2: ShortConv prefill (parallel causal) + history roll, then clip/relpos/KV.
vetta_infer_hip::shortconv4_prefill_par(&k_raw, &w.k_sconv, None, &st.hist_k[pass], &k_cv, b, kv_dim as i32, 0)?;
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::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).
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(), d.swa_win, pos, max_pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea), b)?;
// k4: O-proj + attn shortconv + block boundary.
vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, bu * q_dim)?;
vetta_infer_hip::gemm_bf16(&aout_bf, &w.wo, &oproj, b, h as i32, q_dim as i32)?;
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)?;
}
// k5: MoE input = mlp_norm(mix(blocks, cur, mlp_query)).
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)?;
// k6: batched router + batched MoE.
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)?;
// k7: mlp shortconv + plain residual add.
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(())
}
/// Embed a single token id from the real BF16 embed table -> f32 cur [hidden].
/// Exact strata k_embed_lookup: gather the row THEN RMS-normalize it with
/// embed_norm.weight (the embed lookup fuses gather + norm).
@@ -1045,6 +1160,50 @@ impl LoopMsgs {
}
}
/// Batched loop controller (M=B): target/msg [B,h] in place. ctrl_pack_batched ->
/// down/gain/forget gemm_bf16 M=B -> ctrl_apply over B*h. Same math as M=1.
#[allow(dead_code)] // wired by the batched layer forward
fn apply_controller_batched(target: &DeviceBuf, msg: &DeviceBuf, cw: &ControllerWeights, ch: usize, hidden: usize, gate_rank: usize, eps: f32, b: i32) -> Result<(), String> {
let bu = b as usize;
let packed = DeviceBuf::alloc(bu * 2 * hidden * 2)?;
vetta_infer_hip::ctrl_pack_batched(target, msg, &packed, hidden as i32, eps, b)?;
let gate = DeviceBuf::alloc(bu * gate_rank * 4)?;
vetta_infer_hip::gemm_bf16(&packed, &cw.down[ch], &gate, b, gate_rank as i32, (2 * hidden) as i32)?;
let gate_bf = DeviceBuf::alloc(bu * gate_rank * 2)?; vetta_infer_hip::cast_f32_bf16(&gate, &gate_bf, bu * gate_rank)?;
let gain = DeviceBuf::alloc(bu * hidden * 4)?;
let forget = DeviceBuf::alloc(bu * hidden * 4)?;
vetta_infer_hip::gemm_bf16(&gate_bf, &cw.gain[ch], &gain, b, hidden as i32, gate_rank as i32)?;
vetta_infer_hip::gemm_bf16(&gate_bf, &cw.forget[ch], &forget, b, hidden as i32, gate_rank as i32)?;
vetta_infer_hip::ctrl_apply(target, msg, &gain, &forget, target, bu * hidden)?;
Ok(())
}
/// Device-resident depth-block arena for the batched forward: [max_blocks, B, h]
/// contiguous, the exact layout attn_res_mix reads (blocks [n_blocks, M, D]).
/// Snapshot copies cur [B,h] into arena[count] device-side (no host gather);
/// truncate implements the core-loop bank rollback depth restoration.
#[allow(dead_code)] // wired by the batched forward
struct BatchBlocks {
arena: DeviceBuf,
count: usize,
b: usize,
h: usize,
}
#[allow(dead_code)]
impl BatchBlocks {
fn new(b: usize, h: usize, max_blocks: usize) -> Result<Self, String> {
let arena = DeviceBuf::alloc(max_blocks * b * h * 4)?;
Ok(Self { arena, count: 0, b, h })
}
fn snapshot(&mut self, cur: &DeviceBuf) -> Result<(), String> {
vetta_infer_hip::copy_f32_at(cur, &self.arena, self.count * self.b * self.h, self.b * self.h)?;
self.count += 1;
Ok(())
}
fn truncate(&mut self, n: usize) { self.count = n; }
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1202,4 +1361,56 @@ mod tests {
assert!(max_rel < 3e-3, "batched MoE parity failed at ip={ip}: {max_rel}");
}
}
/// Batched SWA layer (M=B) vs B sequential M=1 layer_forward_swa on REAL weights
/// (ip=1, no snapshot). Aligns KV dtype (f16) + device MoE so the only difference
/// is batching. Compares the residual stream cur[B,h] AND the KV cache.
#[test]
#[ignore]
fn layer_swa_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 = 1usize;
let w = cache.swa_layer(ip).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();
// Batched.
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_swa_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();
// Sequential M=1.
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_swa(&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)); }
// KV cache byte-compare (f16).
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_swa_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 SWA layer cur parity failed: {max_rel}");
assert!(kv_match, "batched SWA layer KV cache must be byte-identical");
}
}