Compare commits

..
2 Commits
Author SHA1 Message Date
adm 3dbb6bb1b4 [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.
2026-12-02 00:21:00 +01:00
adm 51b230cdd2 [HIP] l2_clip scale_rows fix (batched per-head scale) + gather_channel + copy_f32_at + l2_clip_batched
k_l2_clip indexed the per-head scale as scale[r*hd] with r=row. For M=1
rows=n_head so r=head (correct); for batched rows=M*n_head the rows >= n_head
read the [n_head,hd] scale OUT OF BOUNDS, corrupting q/r (r_raw clipped to 0).
Add scale_rows param: sc = scale[(r % scale_rows)*hd]. l2_clip passes rows
(M=1 unchanged); new l2_clip_batched passes n_head. Regression test
l2_clip_batched_parity (M=8,n_head=24,hd=128) bit-exact vs sequential.

Also: k_gather_channel (strided msgs channel [B*nq,h]->[B,h] for batched
controllers), copy_f32_at (offset copy into depth-block arena). Flash prefill
parity test now exercises the real config (n_head=24,n_kv=8,hd=128,win=1024).
2026-12-02 00:20:55 +01:00
4 changed files with 299 additions and 10 deletions

No files matched your search

+61 -4
View File
@@ -77,6 +77,7 @@ mod ffi {
) -> c_int; ) -> c_int;
pub fn vetta_vec_add(a: *const c_float, b: *const c_float, y: *mut c_float, n: usize, stream: *mut c_void) -> c_int; pub fn vetta_vec_add(a: *const c_float, b: *const c_float, y: *mut c_float, n: usize, stream: *mut c_void) -> c_int;
pub fn vetta_copy_f32(src: *const c_float, dst: *mut c_float, n: usize, stream: *mut c_void) -> c_int; pub fn vetta_copy_f32(src: *const c_float, dst: *mut c_float, n: usize, stream: *mut c_void) -> c_int;
pub fn vetta_gather_channel(msgs: *const c_float, dst: *mut c_float, ch: c_int, b: c_int, h: c_int, nq: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_cast_f32_bf16(x: *const c_float, y: *mut u16, n: usize, stream: *mut c_void) -> c_int; pub fn vetta_cast_f32_bf16(x: *const c_float, y: *mut u16, n: usize, stream: *mut c_void) -> c_int;
pub fn vetta_cast_f32_f16(x: *const c_float, y: *mut u16, n: usize, stream: *mut c_void) -> c_int; pub fn vetta_cast_f32_f16(x: *const c_float, y: *mut u16, n: usize, stream: *mut c_void) -> c_int;
pub fn vetta_nvfp4_gemv( pub fn vetta_nvfp4_gemv(
@@ -121,7 +122,7 @@ mod ffi {
pub fn vetta_shortconv4_prefill_par(in_x: *const c_float, static_w: *const c_float, dyn_taps: *const c_float, hist: *const c_float, out_y: *mut c_float, b: c_int, c: c_int, n_heads: c_int, stream: *mut c_void) -> c_int; pub fn vetta_shortconv4_prefill_par(in_x: *const c_float, static_w: *const c_float, dyn_taps: *const c_float, hist: *const c_float, out_y: *mut c_float, b: c_int, c: c_int, n_heads: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_shortconv4_update_hist(in_x: *const c_float, hist: *mut c_float, b: c_int, c: c_int, stream: *mut c_void) -> c_int; pub fn vetta_shortconv4_update_hist(in_x: *const c_float, hist: *mut c_float, b: c_int, c: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_attn_res_mix(blocks: *const c_float, cur: *const c_float, queries: *const c_float, out: *mut c_float, n_blocks: c_int, m: c_int, n_queries: c_int, d: c_int, eps: c_float, stream: *mut c_void) -> c_int; pub fn vetta_attn_res_mix(blocks: *const c_float, cur: *const c_float, queries: *const c_float, out: *mut c_float, n_blocks: c_int, m: c_int, n_queries: c_int, d: c_int, eps: c_float, stream: *mut c_void) -> c_int;
pub fn vetta_l2_clip(x: *mut c_float, scale: *const c_float, rows: c_int, hd: c_int, clip: c_float, apply_tau: c_int, pos: c_int, stream: *mut c_void) -> c_int; pub fn vetta_l2_clip(x: *mut c_float, scale: *const c_float, rows: c_int, hd: c_int, clip: c_float, apply_tau: c_int, pos: c_int, scale_rows: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_relpos_bias(r: *const c_float, rel_proj: *const c_float, rel_bias: *mut c_float, n_head: c_int, d_rel: c_int, rel_extent: c_int, lim: c_int, stream: *mut c_void) -> c_int; pub fn vetta_relpos_bias(r: *const c_float, rel_proj: *const c_float, rel_bias: *mut c_float, n_head: c_int, d_rel: c_int, rel_extent: c_int, lim: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_relpos_bias_batched(r: *const c_float, rel_proj: *const c_float, rel_bias: *mut c_float, pos: *const c_int, n_head: c_int, d_rel: c_int, rel_extent: c_int, m: c_int, stream: *mut c_void) -> c_int; pub fn vetta_relpos_bias_batched(r: *const c_float, rel_proj: *const c_float, rel_bias: *mut c_float, pos: *const c_int, n_head: c_int, d_rel: c_int, rel_extent: c_int, m: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_kv_store(k_in: *const c_float, v_in: *const c_float, k_cache: *mut c_float, v_cache: *mut c_float, pos: c_int, n_kv: c_int, hd: c_int, seq: c_int, rms_eps: c_float, stream: *mut c_void) -> c_int; pub fn vetta_kv_store(k_in: *const c_float, v_in: *const c_float, k_cache: *mut c_float, v_cache: *mut c_float, pos: c_int, n_kv: c_int, hd: c_int, seq: c_int, rms_eps: c_float, stream: *mut c_void) -> c_int;
@@ -461,6 +462,24 @@ pub fn copy_f32(src: &DeviceBuf, dst: &DeviceBuf, n: usize) -> Result<(), String
Ok(()) Ok(())
} }
/// Device-side f32 copy into `dst` at element offset `dst_offset` (arena snapshot).
#[cfg(feature = "hip")]
pub fn copy_f32_at(src: &DeviceBuf, dst: &DeviceBuf, dst_offset: usize, n: usize) -> Result<(), String> {
if dst_offset * 4 + n * 4 > dst.bytes { return Err("copy_f32_at overflow".into()); }
let dst_ptr = unsafe { (dst.ptr as *mut f32).add(dst_offset) };
let rc = unsafe { ffi::vetta_copy_f32(src.ptr as *const f32, dst_ptr, n, std::ptr::null_mut()) };
if rc != 0 { return Err("copy_f32_at launch failed".into()); }
Ok(())
}
/// Gather controller message channel `ch` from msgs [B*nq,h] -> dst [B,h] (strided).
#[cfg(feature = "hip")]
pub fn gather_channel(msgs: &DeviceBuf, dst: &DeviceBuf, ch: i32, b: i32, h: i32, nq: i32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_gather_channel(msgs.ptr as *const f32, dst.ptr as *mut f32, ch, b, h, nq, std::ptr::null_mut()) };
if rc != 0 { return Err("gather_channel launch failed".into()); }
Ok(())
}
/// Launch k_cast_f32_bf16: f32 activation -> BF16 (round-to-nearest-even). /// Launch k_cast_f32_bf16: f32 activation -> BF16 (round-to-nearest-even).
#[cfg(feature = "hip")] #[cfg(feature = "hip")]
pub fn cast_f32_bf16(x: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result<(), String> { pub fn cast_f32_bf16(x: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result<(), String> {
@@ -696,11 +715,23 @@ pub fn attn_res_mix(blocks: &DeviceBuf, cur: &DeviceBuf, queries: &DeviceBuf, ou
#[cfg(feature = "hip")] #[cfg(feature = "hip")]
pub fn l2_clip(x: &DeviceBuf, scale: Option<&DeviceBuf>, rows: i32, hd: i32, clip: f32, apply_tau: bool, pos: i32) -> Result<(), String> { pub fn l2_clip(x: &DeviceBuf, scale: Option<&DeviceBuf>, rows: i32, hd: i32, clip: f32, apply_tau: bool, pos: i32) -> Result<(), String> {
let sc = scale.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null()); let sc = scale.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
let rc = unsafe { ffi::vetta_l2_clip(x.ptr as *mut f32, sc, rows, hd, clip, apply_tau as i32, pos, std::ptr::null_mut()) }; let rc = unsafe { ffi::vetta_l2_clip(x.ptr as *mut f32, sc, rows, hd, clip, apply_tau as i32, pos, rows, std::ptr::null_mut()) };
if rc != 0 { return Err("l2_clip launch failed".into()); } if rc != 0 { return Err("l2_clip launch failed".into()); }
Ok(()) Ok(())
} }
/// Batched L2 clip (rows = M*n_head): the per-head scale repeats every
/// `scale_rows` (=n_head) rows, so row r uses scale[r % scale_rows]. Without this
/// the batched rows >= n_head would index the [n_head,hd] scale out of bounds.
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn l2_clip_batched(x: &DeviceBuf, scale: Option<&DeviceBuf>, rows: i32, hd: i32, clip: f32, apply_tau: bool, pos: i32, scale_rows: i32) -> Result<(), String> {
let sc = scale.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
let rc = unsafe { ffi::vetta_l2_clip(x.ptr as *mut f32, sc, rows, hd, clip, apply_tau as i32, pos, scale_rows, std::ptr::null_mut()) };
if rc != 0 { return Err("l2_clip_batched launch failed".into()); }
Ok(())
}
/// Launch k_relpos_bias: rel_bias[h,dist] = sum_rc R[h,rc]*rel_proj[rc,dist]. /// Launch k_relpos_bias: rel_bias[h,dist] = sum_rc R[h,rc]*rel_proj[rc,dist].
#[cfg(feature = "hip")] #[cfg(feature = "hip")]
pub fn relpos_bias(r: &DeviceBuf, rel_proj: &DeviceBuf, rel_bias: &DeviceBuf, n_head: i32, d_rel: i32, rel_extent: i32, lim: i32) -> Result<(), String> { pub fn relpos_bias(r: &DeviceBuf, rel_proj: &DeviceBuf, rel_bias: &DeviceBuf, n_head: i32, d_rel: i32, rel_extent: i32, lim: i32) -> Result<(), String> {
@@ -1448,8 +1479,8 @@ mod gpu_tests {
#[test] #[test]
#[ignore] #[ignore]
fn flash_swa_gqa_prefill_f16_parity() { fn flash_swa_gqa_prefill_f16_parity() {
let (n_head, n_kv, hd, seq, b) = (8usize, 2usize, 128usize, 64usize, 20usize); let (n_head, n_kv, hd, seq, b) = (24usize, 8usize, 128usize, 15usize, 8usize);
let (base, win, max_rel) = (10i32, 16i32, 16usize); let (base, win, max_rel) = (5i32, 1024i32, 1024usize);
let scale = 1.0f32 / (hd as f32).sqrt(); let scale = 1.0f32 / (hd as f32).sqrt();
let max_pos = base + (b as i32) - 1; let max_pos = base + (b as i32) - 1;
let kf: Vec<f32> = (0..n_kv * seq * hd).map(|i| ((i % 41) as f32 - 20.0) * 0.02).collect(); let kf: Vec<f32> = (0..n_kv * seq * hd).map(|i| ((i % 41) as f32 - 20.0) * 0.02).collect();
@@ -1633,6 +1664,32 @@ mod gpu_tests {
assert!(max_rel < 1e-6, "router batched parity failed: {max_rel}"); assert!(max_rel < 1e-6, "router batched parity failed: {max_rel}");
} }
/// Batched l2_clip (rows=M*n_head) must match M sequential per-head l2_clip:
/// the per-head scale repeats every n_head rows (r % scale_rows). Regression
/// guard for the out-of-bounds scale indexing that corrupted batched q/r.
#[test]
#[ignore]
fn l2_clip_batched_parity() {
let (m, n_head, hd) = (8usize, 24usize, 128usize);
let clip = 22.627416997969522f32;
let x: Vec<f32> = (0..m * n_head * hd).map(|i| ((i % 41) as f32 - 20.0) * 0.3).collect();
let sc: Vec<f32> = (0..n_head * hd).map(|i| 0.5 + (i % 13) as f32 * 0.05).collect();
let dx = DeviceBuf::alloc(x.len() * 4).unwrap(); dx.h2d(&x).unwrap();
let dsc = DeviceBuf::alloc(sc.len() * 4).unwrap(); dsc.h2d(&sc).unwrap();
l2_clip_batched(&dx, Some(&dsc), (m * n_head) as i32, hd as i32, clip, false, 0, n_head as i32).unwrap();
let mut got = vec![0f32; x.len()]; dx.d2h(&mut got).unwrap();
let dx1 = DeviceBuf::alloc(n_head * hd * 4).unwrap();
let mut max_rel = 0f32;
for mi in 0..m {
dx1.h2d(&x[mi * n_head * hd..(mi + 1) * n_head * hd]).unwrap();
l2_clip(&dx1, Some(&dsc), n_head as i32, hd as i32, clip, false, 0).unwrap();
let mut o = vec![0f32; n_head * hd]; dx1.d2h(&mut o).unwrap();
for i in 0..n_head * hd { max_rel = max_rel.max((got[mi * n_head * hd + i] - o[i]).abs() / o[i].abs().max(1e-3)); }
}
eprintln!("l2_clip_batched M={m} n_head={n_head} hd={hd} max_rel_err={max_rel:.3e}");
assert!(max_rel < 1e-6, "batched l2_clip parity failed: {max_rel}");
}
/// Batched relpos bias (M=B, lim per token) vs M sequential relpos_bias. /// Batched relpos bias (M=B, lim per token) vs M sequential relpos_bias.
#[test] #[test]
#[ignore] #[ignore]
+211
View File
@@ -477,6 +477,121 @@ pub fn layer_forward_swa(
Ok(()) 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]. /// 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 /// Exact strata k_embed_lookup: gather the row THEN RMS-normalize it with
/// embed_norm.weight (the embed lookup fuses gather + norm). /// 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -1202,4 +1361,56 @@ mod tests {
assert!(max_rel < 3e-3, "batched MoE parity failed at ip={ip}: {max_rel}"); 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");
}
} }
+1 -1
View File
@@ -149,7 +149,7 @@ int vetta_attn_res_mix(const float* blocks, const float* cur, const float* queri
// k_l2_clip: per-head L2 clip + optional per-dim scale + optional tau (in place). // k_l2_clip: per-head L2 clip + optional per-dim scale + optional tau (in place).
int vetta_l2_clip(float* x, const float* scale, int rows, int hd, float clip, int vetta_l2_clip(float* x, const float* scale, int rows, int hd, float clip,
int apply_tau, int pos, vetta_stream_t stream); int apply_tau, int pos, int scale_rows, vetta_stream_t stream);
// k_relpos_bias: rel_bias[h,dist] = sum_rc R[h,rc]*rel_proj[rc,dist], dist<lim. // k_relpos_bias: rel_bias[h,dist] = sum_rc R[h,rc]*rel_proj[rc,dist], dist<lim.
int vetta_relpos_bias(const float* r, const float* rel_proj, float* rel_bias, int vetta_relpos_bias(const float* r, const float* rel_proj, float* rel_bias,
+26 -5
View File
@@ -681,6 +681,26 @@ extern "C" int vetta_copy_f32(const float* src, float* dst, size_t n, vetta_stre
return 0; return 0;
} }
// ---- k_gather_channel: extract controller message channel ch as [B,h] -------
// msgs is [B*nq, h] (attn_res_mix out[(m*nq+q)*h]); dst[m,h] = msgs[(m*nq+ch)*h].
// Strided gather so apply_controller_batched reads a contiguous [B,h] channel.
__global__ void k_gather_channel(const float* __restrict__ msgs, float* __restrict__ dst,
int ch, int B, int h, int nq) {
const int d = blockIdx.x * blockDim.x + threadIdx.x;
const int m = blockIdx.y;
if (d >= h || m >= B) return;
dst[(size_t)m * h + d] = msgs[((size_t)m * nq + ch) * h + d];
}
extern "C" int vetta_gather_channel(const float* msgs, float* dst, int ch, int B, int h, int nq, vetta_stream_t stream) {
if (B <= 0 || h <= 0 || nq <= 0 || ch < 0 || ch >= nq) return 1;
dim3 grid((h + 255) / 256, B);
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
k_gather_channel<<<grid, 256, 0, s>>>(msgs, dst, ch, B, h, nq);
HIP_CHECK(hipGetLastError());
return 0;
}
// ---- k_router_gemv: y[N] = x_f32[K] @ w_bf16[N,K]^T, f32 accumulate -------- // ---- k_router_gemv: y[N] = x_f32[K] @ w_bf16[N,K]^T, f32 accumulate --------
// Exact strata B=1 router (launch_f32_linear): the router reads the F32 mlpin // Exact strata B=1 router (launch_f32_linear): the router reads the F32 mlpin
// (NOT bf16-rounded) against the bf16 gate weight promoted to f32. Rounding the // (NOT bf16-rounded) against the bf16 gate weight promoted to f32. Rounding the
@@ -1607,13 +1627,14 @@ extern "C" int vetta_attn_res_mix(const float* blocks, const float* cur, const f
// (pos+1)/8192)); x = v*fac. One block per row (head), in place. // (pos+1)/8192)); x = v*fac. One block per row (head), in place.
__global__ void k_l2_clip(float* __restrict__ x, const float* __restrict__ scale, __global__ void k_l2_clip(float* __restrict__ x, const float* __restrict__ scale,
int rows, int hd, float clip, int apply_tau, int pos) { int rows, int hd, float clip, int apply_tau, int pos, int scale_rows) {
const int r = blockIdx.x; const int r = blockIdx.x;
if (r >= rows) return; if (r >= rows) return;
const int tid = threadIdx.x; const int tid = threadIdx.x;
const int nt = blockDim.x; const int nt = blockDim.x;
float* xv = x + (size_t)r * hd; float* xv = x + (size_t)r * hd;
const float* sc = scale ? (scale + (size_t)r * hd) : nullptr; // Per-head scale repeats every scale_rows rows (batched rows = M*n_head).
const float* sc = scale ? (scale + (size_t)(r % scale_rows) * hd) : nullptr;
__shared__ float red[256]; __shared__ float red[256];
__shared__ float fac_s; __shared__ float fac_s;
const float v = (tid < hd) ? (xv[tid] * (sc ? sc[tid] : 1.f)) : 0.f; const float v = (tid < hd) ? (xv[tid] * (sc ? sc[tid] : 1.f)) : 0.f;
@@ -1633,10 +1654,10 @@ __global__ void k_l2_clip(float* __restrict__ x, const float* __restrict__ scale
} }
extern "C" int vetta_l2_clip(float* x, const float* scale, int rows, int hd, extern "C" int vetta_l2_clip(float* x, const float* scale, int rows, int hd,
float clip, int apply_tau, int pos, vetta_stream_t stream) { float clip, int apply_tau, int pos, int scale_rows, vetta_stream_t stream) {
if (rows <= 0 || hd <= 0 || hd > 256) return 1; if (rows <= 0 || hd <= 0 || hd > 256 || scale_rows <= 0) return 1;
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
k_l2_clip<<<rows, 256, 0, s>>>(x, scale, rows, hd, clip, apply_tau, pos); k_l2_clip<<<rows, 256, 0, s>>>(x, scale, rows, hd, clip, apply_tau, pos, scale_rows);
HIP_CHECK(hipGetLastError()); HIP_CHECK(hipGetLastError());
return 0; return 0;
} }