//! `vetta-infer-hip`: HIP FFI/DMA backend for gfx1150 (RDNA 3.5). //! //! `unsafe` is isolated here (FFI/DMA fence wrappers) per AGENTS.md. The kernel //! build is feature-gated (`--features hip`): the default workspace compiles //! without a GPU/toolchain. Every kernel is parity-checked against a CPU oracle //! (opt-in GPU test) before being wired into the executor. /// Primary offload target (Sogliola: Radeon 890M, RDNA 3.5). pub const TARGET_ARCH: &str = "gfx1150"; #[cfg(feature = "hip")] mod ffi { use std::os::raw::{c_char, c_float, c_int, c_void}; #[repr(C)] pub struct DeviceInfoRaw { pub name: [c_char; 128], pub gcn_arch: [c_char; 64], pub multi_processor_count: c_int, pub wave_size: c_int, pub total_vram_bytes: u64, pub is_uma: c_int, } unsafe extern "C" { pub fn vetta_hip_query_device(dev_id: c_int, out: *mut DeviceInfoRaw) -> c_int; pub fn vetta_buf_alloc(out: *mut *mut c_void, bytes: usize) -> c_int; pub fn vetta_buf_free(p: *mut c_void) -> c_int; pub fn vetta_buf_h2d(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int; pub fn vetta_buf_d2h(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int; pub fn vetta_rms_norm_f32( x: *const c_float, w: *const c_float, y: *mut c_float, rows: c_int, d: c_int, eps: c_float, stream: *mut c_void, ) -> c_int; pub fn vetta_embed_bf16_gather( table: *const u16, tokens: *const i32, out: *mut c_float, b: c_int, d: c_int, vocab: c_int, stream: *mut c_void, ) -> c_int; pub fn vetta_gemm_bf16( x: *const u16, w: *const u16, y: *mut c_float, m: c_int, n: c_int, k: c_int, stream: *mut c_void, ) -> c_int; pub fn vetta_flash_gqa_decode( q: *const c_float, k: *const c_float, v: *const c_float, out: *mut c_float, n_head: c_int, n_kv: c_int, seq: c_int, hd: c_int, scale: c_float, stream: *mut c_void, ) -> c_int; pub fn vetta_flash_swa_gqa_decode( q: *const c_float, k: *const c_float, v: *const c_float, out: *mut c_float, n_head: c_int, n_kv: c_int, seq: c_int, hd: c_int, scale: c_float, swa_window: c_int, cur_pos: c_int, rel_bias: *const c_float, max_rel: c_int, sink_logit: *const c_float, gate: *const c_float, stream: *mut c_void, ) -> c_int; pub fn vetta_moe_router_topk( logits: *const c_float, bias: *const c_float, topk_ids: *mut i32, topk_weights: *mut c_float, m: c_int, n_experts: c_int, k_top: c_int, route_scale: c_float, 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_cast_f32_bf16(x: *const c_float, y: *mut u16, n: usize, stream: *mut c_void) -> c_int; pub fn vetta_nvfp4_gemv( packed: *const u8, scales: *const u8, outer_scale: c_float, x: *const c_float, y: *mut c_float, n: c_int, k: c_int, stream: *mut c_void, ) -> c_int; pub fn vetta_mxfp8_gemv(weights: *const u8, scales: *const u8, x: *const c_float, y: *mut c_float, n: c_int, k: c_int, stream: *mut c_void) -> c_int; pub fn vetta_situ(gu: *const c_float, act: *mut c_float, inter: c_int, beta: c_float, lb: c_float, stream: *mut c_void) -> c_int; pub fn vetta_moe_reduce(y_part: *const c_float, tk_w: *const c_float, out: *mut c_float, top_k: c_int, hidden: c_int, stream: *mut c_void) -> c_int; pub fn vetta_shortconv4_decode(cur: *const c_float, static_w: *const c_float, hist: *mut c_float, out: *mut c_float, slot_ids: *const i32, m: c_int, c: c_int, stream: *mut c_void) -> c_int; pub fn vetta_shortconv4_dyn_decode(cur: *const c_float, static_w: *const c_float, dyn_taps: *const c_float, hist: *mut c_float, out: *mut c_float, slot_ids: *const i32, m: c_int, c: c_int, n_heads: 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_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_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_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_softcap(x: *const c_float, y: *mut c_float, n: usize, cap: c_float, stream: *mut c_void) -> c_int; pub fn vetta_ctrl_pack(cur: *const c_float, msg: *const c_float, packed: *mut u16, d: c_int, eps: c_float, stream: *mut c_void) -> c_int; pub fn vetta_ctrl_apply(cur: *const c_float, msg: *const c_float, gain: *const c_float, forget: *const c_float, out: *mut c_float, n: usize, stream: *mut c_void) -> c_int; } } #[cfg(feature = "hip")] pub use ffi::DeviceInfoRaw; /// Safe device description. #[cfg(feature = "hip")] #[derive(Debug, Clone)] pub struct DeviceInfo { pub name: String, pub gcn_arch: String, pub cu_count: i32, pub wave_size: i32, pub total_vram_bytes: u64, pub is_uma: bool, } #[cfg(feature = "hip")] fn cstr(buf: &[std::os::raw::c_char]) -> String { let bytes: Vec = buf.iter().take_while(|&&c| c != 0).map(|&c| c as u8).collect(); String::from_utf8_lossy(&bytes).into_owned() } /// Query device `dev_id`. Returns `None` on any HIP error. #[cfg(feature = "hip")] pub fn query_device(dev_id: i32) -> Option { let mut raw = DeviceInfoRaw { name: [0; 128], gcn_arch: [0; 64], multi_processor_count: 0, wave_size: 0, total_vram_bytes: 0, is_uma: 0, }; let rc = unsafe { ffi::vetta_hip_query_device(dev_id, &mut raw) }; if rc != 0 { return None; } Some(DeviceInfo { name: cstr(&raw.name), gcn_arch: cstr(&raw.gcn_arch), cu_count: raw.multi_processor_count, wave_size: raw.wave_size, total_vram_bytes: raw.total_vram_bytes, is_uma: raw.is_uma != 0, }) } /// Owned device buffer (RAII free). #[cfg(feature = "hip")] pub struct DeviceBuf { pub ptr: *mut std::os::raw::c_void, pub bytes: usize, } #[cfg(feature = "hip")] impl DeviceBuf { pub fn alloc(bytes: usize) -> Result { let mut ptr: *mut std::os::raw::c_void = std::ptr::null_mut(); let rc = unsafe { ffi::vetta_buf_alloc(&mut ptr, bytes) }; if rc != 0 || ptr.is_null() { return Err(format!("hipMalloc({bytes}) failed")); } Ok(Self { ptr, bytes }) } pub fn h2d(&self, src: &[f32]) -> Result<(), String> { let bytes = src.len() * 4; if bytes > self.bytes { return Err("h2d overflow".into()); } let rc = unsafe { ffi::vetta_buf_h2d(self.ptr, src.as_ptr() as *const _, bytes) }; if rc != 0 { return Err("h2d failed".into()); } Ok(()) } pub fn d2h(&self, dst: &mut [f32]) -> Result<(), String> { let bytes = dst.len() * 4; if bytes > self.bytes { return Err("d2h overflow".into()); } let rc = unsafe { ffi::vetta_buf_d2h(dst.as_mut_ptr() as *mut _, self.ptr, bytes) }; if rc != 0 { return Err("d2h failed".into()); } Ok(()) } pub fn h2d_bytes(&self, src: &[u8]) -> Result<(), String> { if src.len() > self.bytes { return Err("h2d overflow".into()); } let rc = unsafe { ffi::vetta_buf_h2d(self.ptr, src.as_ptr() as *const _, src.len()) }; if rc != 0 { return Err("h2d failed".into()); } Ok(()) } pub fn d2h_bytes(&self, dst: &mut [u8]) -> Result<(), String> { if dst.len() > self.bytes { return Err("d2h overflow".into()); } let rc = unsafe { ffi::vetta_buf_d2h(dst.as_mut_ptr() as *mut _, self.ptr, dst.len()) }; if rc != 0 { return Err("d2h failed".into()); } Ok(()) } } #[cfg(feature = "hip")] impl Drop for DeviceBuf { fn drop(&mut self) { unsafe { ffi::vetta_buf_free(self.ptr); } } } /// Launch k_rms_norm over `rows` rows of width `d` (device pointers). #[cfg(feature = "hip")] pub fn rms_norm_f32(x: &DeviceBuf, w: Option<&DeviceBuf>, y: &DeviceBuf, rows: i32, d: i32, eps: f32) -> Result<(), String> { let wp = w.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null()); let rc = unsafe { ffi::vetta_rms_norm_f32(x.ptr as *const f32, wp, y.ptr as *mut f32, rows, d, eps, std::ptr::null_mut()) }; if rc != 0 { return Err("rms_norm launch failed".into()); } Ok(()) } /// Launch k_embed_bf16_gather: `b` token rows from BF16 table `[vocab, d]` → f32. #[cfg(feature = "hip")] pub fn embed_bf16_gather(table: &DeviceBuf, tokens: &DeviceBuf, out: &DeviceBuf, b: i32, d: i32, vocab: i32) -> Result<(), String> { let rc = unsafe { ffi::vetta_embed_bf16_gather(table.ptr as *const u16, tokens.ptr as *const i32, out.ptr as *mut f32, b, d, vocab, std::ptr::null_mut()) }; if rc != 0 { return Err("embed launch failed".into()); } Ok(()) } /// Launch k_gemm_bf16: y[m,n] = x[m,k] @ w[n,k]^T (BF16 in, f32 accumulate). #[cfg(feature = "hip")] pub fn gemm_bf16(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, m: i32, n: i32, k: i32) -> Result<(), String> { let rc = unsafe { ffi::vetta_gemm_bf16(x.ptr as *const u16, w.ptr as *const u16, y.ptr as *mut f32, m, n, k, std::ptr::null_mut()) }; if rc != 0 { return Err("gemm launch failed".into()); } Ok(()) } /// Launch k_flash_gqa_decode: single-token GQA attention over a f32 KV cache. #[cfg(feature = "hip")] pub fn flash_gqa_decode(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, out: &DeviceBuf, n_head: i32, n_kv: i32, seq: i32, hd: i32, scale: f32) -> Result<(), String> { let rc = unsafe { ffi::vetta_flash_gqa_decode(q.ptr as *const f32, k.ptr as *const f32, v.ptr as *const f32, out.ptr as *mut f32, n_head, n_kv, seq, hd, scale, std::ptr::null_mut()) }; if rc != 0 { return Err("flash_gqa launch failed".into()); } Ok(()) } /// Launch k_flash_swa_gqa_decode: Inkling SWA window + relpos + sink + gate. /// `rel_bias`, `sink_logit`, `gate` are optional (None -> NULL). #[cfg(feature = "hip")] #[allow(clippy::too_many_arguments)] pub fn flash_swa_gqa_decode(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, out: &DeviceBuf, n_head: i32, n_kv: i32, seq: i32, hd: i32, scale: f32, swa_window: i32, cur_pos: i32, rel_bias: Option<&DeviceBuf>, max_rel: i32, sink_logit: Option<&DeviceBuf>, gate: Option<&DeviceBuf>) -> Result<(), String> { let rb = rel_bias.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null()); let sk = sink_logit.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null()); let gt = gate.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null()); let rc = unsafe { ffi::vetta_flash_swa_gqa_decode(q.ptr as *const f32, k.ptr as *const f32, v.ptr as *const f32, out.ptr as *mut f32, n_head, n_kv, seq, hd, scale, swa_window, cur_pos, rb, max_rel, sk, gt, std::ptr::null_mut()) }; if rc != 0 { return Err("flash_swa_gqa launch failed".into()); } Ok(()) } /// Launch k_moe_router_topk (Inkling exact sigmoid router). #[cfg(feature = "hip")] pub fn moe_router_topk(logits: &DeviceBuf, bias: Option<&DeviceBuf>, ids: &DeviceBuf, weights: &DeviceBuf, m: i32, n_experts: i32, k_top: i32, route_scale: f32) -> Result<(), String> { let bp = bias.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null()); let rc = unsafe { ffi::vetta_moe_router_topk(logits.ptr as *const f32, bp, ids.ptr as *mut i32, weights.ptr as *mut f32, m, n_experts, k_top, route_scale, std::ptr::null_mut()) }; if rc != 0 { return Err("router launch failed".into()); } Ok(()) } /// Launch k_vec_add: y = a + b elementwise. #[cfg(feature = "hip")] pub fn vec_add(a: &DeviceBuf, b: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result<(), String> { let rc = unsafe { ffi::vetta_vec_add(a.ptr as *const f32, b.ptr as *const f32, y.ptr as *mut f32, n, std::ptr::null_mut()) }; if rc != 0 { return Err("vec_add launch failed".into()); } Ok(()) } /// Launch k_cast_f32_bf16: f32 activation -> BF16 (truncate). #[cfg(feature = "hip")] pub fn cast_f32_bf16(x: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result<(), String> { let rc = unsafe { ffi::vetta_cast_f32_bf16(x.ptr as *const f32, y.ptr as *mut u16, n, std::ptr::null_mut()) }; if rc != 0 { return Err("cast launch failed".into()); } Ok(()) } /// Launch k_nvfp4_gemv (M=1): y[n] = dequant(W)[n,k] @ x[k] (NVFP4). #[cfg(feature = "hip")] pub fn nvfp4_gemv(packed: &DeviceBuf, scales: &DeviceBuf, outer_scale: f32, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32) -> Result<(), String> { let rc = unsafe { ffi::vetta_nvfp4_gemv(packed.ptr as *const u8, scales.ptr as *const u8, outer_scale, x.ptr as *const f32, y.ptr as *mut f32, n, k, std::ptr::null_mut()) }; if rc != 0 { return Err("nvfp4_gemv launch failed".into()); } Ok(()) } /// Launch k_mxfp8_gemv (M=1): MXFP8 experts (E4M3 + UE8M0/32, no outer scale). #[cfg(feature = "hip")] pub fn mxfp8_gemv(weights: &DeviceBuf, scales: &DeviceBuf, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32) -> Result<(), String> { let rc = unsafe { ffi::vetta_mxfp8_gemv(weights.ptr as *const u8, scales.ptr as *const u8, x.ptr as *const f32, y.ptr as *mut f32, n, k, std::ptr::null_mut()) }; if rc != 0 { return Err("mxfp8_gemv launch failed".into()); } Ok(()) } /// Launch k_situ: SiTU double-softcapped activation (gu=[gate;up] -> act). #[cfg(feature = "hip")] pub fn situ(gu: &DeviceBuf, act: &DeviceBuf, inter: i32, beta: f32, lb: f32) -> Result<(), String> { let rc = unsafe { ffi::vetta_situ(gu.ptr as *const f32, act.ptr as *mut f32, inter, beta, lb, std::ptr::null_mut()) }; if rc != 0 { return Err("situ launch failed".into()); } Ok(()) } /// Launch k_moe_reduce: out[d] = sum_e tk_w[e]*y_part[e,d]. #[cfg(feature = "hip")] pub fn moe_reduce(y_part: &DeviceBuf, tk_w: &DeviceBuf, out: &DeviceBuf, top_k: i32, hidden: i32) -> Result<(), String> { let rc = unsafe { ffi::vetta_moe_reduce(y_part.ptr as *const f32, tk_w.ptr as *const f32, out.ptr as *mut f32, top_k, hidden, std::ptr::null_mut()) }; if rc != 0 { return Err("moe_reduce launch failed".into()); } Ok(()) } /// Launch k_shortconv4_decode (static): updates `hist` ring in place. #[cfg(feature = "hip")] pub fn shortconv4_decode(cur: &DeviceBuf, static_w: &DeviceBuf, hist: &DeviceBuf, out: &DeviceBuf, slot_ids: &DeviceBuf, m: i32, c: i32) -> Result<(), String> { let rc = unsafe { ffi::vetta_shortconv4_decode(cur.ptr as *const f32, static_w.ptr as *const f32, hist.ptr as *mut f32, out.ptr as *mut f32, slot_ids.ptr as *const i32, m, c, std::ptr::null_mut()) }; if rc != 0 { return Err("shortconv4 launch failed".into()); } Ok(()) } /// Launch k_shortconv4_dyn_decode: full-attn ShortConv4 with dynamic taps. #[cfg(feature = "hip")] #[allow(clippy::too_many_arguments)] pub fn shortconv4_dyn_decode(cur: &DeviceBuf, static_w: &DeviceBuf, dyn_taps: &DeviceBuf, hist: &DeviceBuf, out: &DeviceBuf, slot_ids: &DeviceBuf, m: i32, c: i32, n_heads: i32) -> Result<(), String> { let rc = unsafe { ffi::vetta_shortconv4_dyn_decode(cur.ptr as *const f32, static_w.ptr as *const f32, dyn_taps.ptr as *const f32, hist.ptr as *mut f32, out.ptr as *mut f32, slot_ids.ptr as *const i32, m, c, n_heads, std::ptr::null_mut()) }; if rc != 0 { return Err("shortconv4_dyn launch failed".into()); } Ok(()) } /// Launch k_attn_res_mix: Inkling AttnRes deep-residual block-mix. #[cfg(feature = "hip")] #[allow(clippy::too_many_arguments)] pub fn attn_res_mix(blocks: &DeviceBuf, cur: &DeviceBuf, queries: &DeviceBuf, out: &DeviceBuf, n_blocks: i32, m: i32, n_queries: i32, d: i32, eps: f32) -> Result<(), String> { let rc = unsafe { ffi::vetta_attn_res_mix(blocks.ptr as *const f32, cur.ptr as *const f32, queries.ptr as *const f32, out.ptr as *mut f32, n_blocks, m, n_queries, d, eps, std::ptr::null_mut()) }; if rc != 0 { return Err("attn_res_mix launch failed".into()); } Ok(()) } /// Launch k_l2_clip: per-head L2 clip + optional scale + optional tau (in place). #[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> { 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()) }; if rc != 0 { return Err("l2_clip launch failed".into()); } Ok(()) } /// Launch k_relpos_bias: rel_bias[h,dist] = sum_rc R[h,rc]*rel_proj[rc,dist]. #[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> { let rc = unsafe { ffi::vetta_relpos_bias(r.ptr as *const f32, rel_proj.ptr as *const f32, rel_bias.ptr as *mut f32, n_head, d_rel, rel_extent, lim, std::ptr::null_mut()) }; if rc != 0 { return Err("relpos_bias launch failed".into()); } Ok(()) } /// Launch k_kv_store: K (pre-clipped) as-is + V RMS-normalized into f32 cache. #[cfg(feature = "hip")] #[allow(clippy::too_many_arguments)] pub fn kv_store(k_in: &DeviceBuf, v_in: &DeviceBuf, k_cache: &DeviceBuf, v_cache: &DeviceBuf, pos: i32, n_kv: i32, hd: i32, seq: i32, rms_eps: f32) -> Result<(), String> { let rc = unsafe { ffi::vetta_kv_store(k_in.ptr as *const f32, v_in.ptr as *const f32, k_cache.ptr as *mut f32, v_cache.ptr as *mut f32, pos, n_kv, hd, seq, rms_eps, std::ptr::null_mut()) }; if rc != 0 { return Err("kv_store launch failed".into()); } Ok(()) } /// Launch k_softcap: y = cap * tanh(x / cap). #[cfg(feature = "hip")] pub fn softcap(x: &DeviceBuf, y: &DeviceBuf, n: usize, cap: f32) -> Result<(), String> { let rc = unsafe { ffi::vetta_softcap(x.ptr as *const f32, y.ptr as *mut f32, n, cap, std::ptr::null_mut()) }; if rc != 0 { return Err("softcap launch failed".into()); } Ok(()) } /// Launch k_ctrl_pack: RMS-normalize cur & msg -> packed BF16 [2D]. #[cfg(feature = "hip")] pub fn ctrl_pack(cur: &DeviceBuf, msg: &DeviceBuf, packed: &DeviceBuf, d: i32, eps: f32) -> Result<(), String> { let rc = unsafe { ffi::vetta_ctrl_pack(cur.ptr as *const f32, msg.ptr as *const f32, packed.ptr as *mut u16, d, eps, std::ptr::null_mut()) }; if rc != 0 { return Err("ctrl_pack launch failed".into()); } Ok(()) } /// Launch k_ctrl_apply: out = (1-tanh(forget))*cur + tanh(gain)*msg. #[cfg(feature = "hip")] pub fn ctrl_apply(cur: &DeviceBuf, msg: &DeviceBuf, gain: &DeviceBuf, forget: &DeviceBuf, out: &DeviceBuf, n: usize) -> Result<(), String> { let rc = unsafe { ffi::vetta_ctrl_apply(cur.ptr as *const f32, msg.ptr as *const f32, gain.ptr as *const f32, forget.ptr as *const f32, out.ptr as *mut f32, n, std::ptr::null_mut()) }; if rc != 0 { return Err("ctrl_apply launch failed".into()); } Ok(()) } #[cfg(all(test, feature = "hip"))] mod gpu_tests { use super::*; fn cpu_rms_norm(x: &[f32], w: Option<&[f32]>, rows: usize, d: usize, eps: f32) -> Vec { let mut y = vec![0f32; rows * d]; for r in 0..rows { let xr = &x[r * d..(r + 1) * d]; let ss: f32 = xr.iter().map(|v| v * v).sum(); let inv = 1.0f32 / (ss / d as f32 + eps).sqrt(); for i in 0..d { y[r * d + i] = xr[i] * inv * w.map(|w| w[i]).unwrap_or(1.0); } } y } #[test] #[ignore] // requires GPU + --features hip fn device_is_gfx1150() { let d = query_device(0).expect("device query"); eprintln!("device: {} ({}) CU={} UMA={}", d.name, d.gcn_arch, d.cu_count, d.is_uma); assert!(d.gcn_arch.contains("gfx1150"), "expected gfx1150, got {}", d.gcn_arch); } #[test] #[ignore] fn rms_norm_parity_vs_cpu() { for &(rows, d) in &[(1usize, 2304usize), (4, 2304), (3, 128), (2, 1024)] { let x: Vec = (0..rows * d).map(|i| ((i % 37) as f32 - 18.0) * 0.1).collect(); let w: Vec = (0..d).map(|i| 0.5 + (i % 13) as f32 * 0.05).collect(); let eps = 1e-6f32; let want = cpu_rms_norm(&x, Some(&w), rows, d, eps); let dx = DeviceBuf::alloc(x.len() * 4).unwrap(); let dw = DeviceBuf::alloc(w.len() * 4).unwrap(); let dy = DeviceBuf::alloc(want.len() * 4).unwrap(); dx.h2d(&x).unwrap(); dw.h2d(&w).unwrap(); rms_norm_f32(&dx, Some(&dw), &dy, rows as i32, d as i32, eps).unwrap(); let mut got = vec![0f32; want.len()]; dy.d2h(&mut got).unwrap(); let mut max_rel = 0f32; for (g, wnt) in got.iter().zip(want.iter()) { let denom = wnt.abs().max(1e-3); max_rel = max_rel.max((g - wnt).abs() / denom); } eprintln!("rms_norm rows={rows} d={d} max_rel_err={max_rel:.3e}"); assert!(max_rel < 1e-4, "rms_norm parity failed: {max_rel}"); } } fn f32_to_bf16(v: f32) -> u16 { (v.to_bits() >> 16) as u16 } fn bf16_to_f32(h: u16) -> f32 { f32::from_bits((h as u32) << 16) } #[test] #[ignore] fn embed_bf16_parity_exact() { let (vocab, d, b) = (16usize, 64usize, 3usize); let table: Vec = (0..vocab * d).map(|i| f32_to_bf16(((i % 53) as f32 - 26.0) * 0.07)).collect(); let tokens: Vec = vec![1, 5, 15]; let mut want = vec![0f32; b * d]; for (bi, &tok) in tokens.iter().enumerate() { for i in 0..d { want[bi * d + i] = bf16_to_f32(table[tok as usize * d + i]); } } let dt = DeviceBuf::alloc(table.len() * 2).unwrap(); let dk = DeviceBuf::alloc(tokens.len() * 4).unwrap(); let dy = DeviceBuf::alloc(want.len() * 4).unwrap(); dt.h2d_bytes(bytemuck_u16(&table)).unwrap(); dk.h2d_bytes(bytemuck_i32(&tokens)).unwrap(); embed_bf16_gather(&dt, &dk, &dy, b as i32, d as i32, vocab as i32).unwrap(); let mut got = vec![0f32; want.len()]; dy.d2h(&mut got).unwrap(); assert_eq!(got, want, "embed gather must be exact"); } #[test] #[ignore] fn gemm_bf16_parity_vs_cpu() { for &(m, n, k) in &[(2usize, 8usize, 16usize), (4, 32, 64), (1, 128, 256)] { let x: Vec = (0..m * k).map(|i| f32_to_bf16(((i % 41) as f32 - 20.0) * 0.05)).collect(); let w: Vec = (0..n * k).map(|i| f32_to_bf16(((i % 29) as f32 - 14.0) * 0.06)).collect(); let mut want = vec![0f32; m * n]; for mi in 0..m { for ni in 0..n { let mut acc = 0f32; for kk in 0..k { acc += bf16_to_f32(x[mi * k + kk]) * bf16_to_f32(w[ni * k + kk]); } want[mi * n + ni] = acc; } } let dx = DeviceBuf::alloc(x.len() * 2).unwrap(); let dw = DeviceBuf::alloc(w.len() * 2).unwrap(); let dy = DeviceBuf::alloc(want.len() * 4).unwrap(); dx.h2d_bytes(bytemuck_u16(&x)).unwrap(); dw.h2d_bytes(bytemuck_u16(&w)).unwrap(); gemm_bf16(&dx, &dw, &dy, m as i32, n as i32, k as i32).unwrap(); let mut got = vec![0f32; want.len()]; dy.d2h(&mut got).unwrap(); let mut max_rel = 0f32; for (g, wnt) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - wnt).abs() / wnt.abs().max(1e-3)); } eprintln!("gemm m={m} n={n} k={k} max_rel_err={max_rel:.3e}"); assert!(max_rel < 1e-3, "gemm parity failed: {max_rel}"); } } fn cpu_attn(q: &[f32], k: &[f32], v: &[f32], n_head: usize, n_kv: usize, seq: usize, hd: usize, scale: f32) -> Vec { let group = n_head / n_kv; let mut out = vec![0f32; n_head * hd]; for h in 0..n_head { let kvh = h / group; let qh = &q[h * hd..(h + 1) * hd]; let mut scores = vec![0f32; seq]; for s in 0..seq { let ks = &k[(kvh * seq + s) * hd..(kvh * seq + s + 1) * hd]; scores[s] = qh.iter().zip(ks).map(|(a, b)| a * b).sum::() * scale; } let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max); let mut denom = 0f32; for s in 0..seq { scores[s] = (scores[s] - m).exp(); denom += scores[s]; } for d in 0..hd { let mut acc = 0f32; for s in 0..seq { acc += scores[s] / denom * v[(kvh * seq + s) * hd + d]; } out[h * hd + d] = acc; } } out } #[test] #[ignore] fn flash_gqa_decode_parity_vs_cpu() { for &(n_head, n_kv, seq, hd) in &[(8usize, 2usize, 32usize, 64usize), (24, 8, 128, 128), (4, 4, 16, 32)] { let scale = 1.0f32 / (hd as f32).sqrt(); let q: Vec = (0..n_head * hd).map(|i| ((i % 23) as f32 - 11.0) * 0.04).collect(); let k: Vec = (0..n_kv * seq * hd).map(|i| ((i % 31) as f32 - 15.0) * 0.03).collect(); let v: Vec = (0..n_kv * seq * hd).map(|i| ((i % 17) as f32 - 8.0) * 0.05).collect(); let want = cpu_attn(&q, &k, &v, n_head, n_kv, seq, hd, scale); let dq = DeviceBuf::alloc(q.len() * 4).unwrap(); let dk = DeviceBuf::alloc(k.len() * 4).unwrap(); let dv = DeviceBuf::alloc(v.len() * 4).unwrap(); let dy = DeviceBuf::alloc(want.len() * 4).unwrap(); dq.h2d(&q).unwrap(); dk.h2d(&k).unwrap(); dv.h2d(&v).unwrap(); flash_gqa_decode(&dq, &dk, &dv, &dy, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale).unwrap(); let mut got = vec![0f32; want.len()]; dy.d2h(&mut got).unwrap(); let mut max_rel = 0f32; for (g, wnt) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - wnt).abs() / wnt.abs().max(1e-3)); } eprintln!("flash_gqa nh={n_head} nkv={n_kv} seq={seq} hd={hd} max_rel_err={max_rel:.3e}"); assert!(max_rel < 1e-4, "flash_gqa parity failed: {max_rel}"); } } #[allow(clippy::too_many_arguments)] fn cpu_swa_attn(q: &[f32], k: &[f32], v: &[f32], n_head: usize, n_kv: usize, seq: usize, hd: usize, scale: f32, window: i32, cur_pos: i32, rb: Option<&[f32]>, max_rel: usize, sink: Option<&[f32]>, gate: Option<&[f32]>) -> Vec { let k_start = if window > 0 && cur_pos >= window { (cur_pos - window + 1) as usize } else { 0 }; let mut out = vec![0f32; n_head * hd]; for h in 0..n_head { let kvh = h / (n_head / n_kv); let sink_v = sink.map(|s| s[h]); let mut m = sink_v.unwrap_or(f32::NEG_INFINITY); let mut scores = Vec::new(); let mut positions = Vec::new(); for s in k_start..=(cur_pos as usize) { let mut dot = 0f32; for d in 0..hd { dot += q[h * hd + d] * k[(kvh * seq + s) * hd + d]; } dot *= scale; let dist = cur_pos as usize - s; if let Some(rb) = rb { if dist < max_rel { dot += rb[h * max_rel + dist]; } } scores.push(dot); positions.push(s); m = m.max(dot); } let exps: Vec = scores.iter().map(|sc| (sc - m).exp()).collect(); let mut denom = sink_v.map(|sv| (sv - m).exp()).unwrap_or(0.0); denom += exps.iter().sum::(); let inv = 1.0 / denom.max(1e-30); for d in 0..hd { let mut acc = 0f32; for (i, &s) in positions.iter().enumerate() { acc += exps[i] * inv * v[(kvh * seq + s) * hd + d]; } if let Some(g) = gate { acc *= 1.0 / (1.0 + (-g[h * hd + d]).exp()); } out[h * hd + d] = acc; } } out } #[test] #[ignore] fn flash_swa_gqa_parity_vs_cpu() { // (window, use_relpos, use_sink, use_gate) for &(window, ur, us, ug) in &[(4i32, true, true, true), (0, true, true, true), (6, false, false, false), (3, true, false, true)] { let (n_head, n_kv, seq, hd) = (8usize, 2usize, 32usize, 64usize); let cur_pos = (seq - 1) as i32; let max_rel = 32usize; let scale = 1.0f32 / (hd as f32).sqrt(); let q: Vec = (0..n_head * hd).map(|i| ((i % 23) as f32 - 11.0) * 0.04).collect(); let k: Vec = (0..n_kv * seq * hd).map(|i| ((i % 31) as f32 - 15.0) * 0.03).collect(); let v: Vec = (0..n_kv * seq * hd).map(|i| ((i % 17) as f32 - 8.0) * 0.05).collect(); let rb: Vec = (0..n_head * max_rel).map(|i| ((i % 13) as f32 - 6.0) * 0.02).collect(); let sink: Vec = (0..n_head).map(|i| (i as f32) * 0.3 - 1.0).collect(); let gate: Vec = (0..n_head * hd).map(|i| ((i % 29) as f32 - 14.0) * 0.1).collect(); let want = cpu_swa_attn(&q, &k, &v, n_head, n_kv, seq, hd, scale, window, cur_pos, ur.then_some(rb.as_slice()), max_rel, us.then_some(sink.as_slice()), ug.then_some(gate.as_slice())); let dq = DeviceBuf::alloc(q.len() * 4).unwrap(); let dk = DeviceBuf::alloc(k.len() * 4).unwrap(); let dv = DeviceBuf::alloc(v.len() * 4).unwrap(); let dy = DeviceBuf::alloc(want.len() * 4).unwrap(); let drb = DeviceBuf::alloc(rb.len() * 4).unwrap(); let dsk = DeviceBuf::alloc(sink.len() * 4).unwrap(); let dgt = DeviceBuf::alloc(gate.len() * 4).unwrap(); dq.h2d(&q).unwrap(); dk.h2d(&k).unwrap(); dv.h2d(&v).unwrap(); drb.h2d(&rb).unwrap(); dsk.h2d(&sink).unwrap(); dgt.h2d(&gate).unwrap(); flash_swa_gqa_decode(&dq, &dk, &dv, &dy, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, window, cur_pos, ur.then_some(&drb), max_rel as i32, us.then_some(&dsk), ug.then_some(&dgt)).unwrap(); let mut got = vec![0f32; want.len()]; dy.d2h(&mut got).unwrap(); let mut max_rel_err = 0f32; for (g, w) in got.iter().zip(want.iter()) { max_rel_err = max_rel_err.max((g - w).abs() / w.abs().max(1e-3)); } eprintln!("flash_swa window={window} rel={ur} sink={us} gate={ug} max_rel_err={max_rel_err:.3e}"); assert!(max_rel_err < 1e-4, "flash_swa parity failed: {max_rel_err}"); } } fn cpu_router(logits: &[f32], bias: &[f32], m: usize, n_experts: usize, k_top: usize, route_scale: f32) -> (Vec, Vec) { let mut ids = vec![0i32; m * k_top]; let mut weights = vec![0f32; m * k_top]; for mi in 0..m { let prob: Vec = (0..n_experts).map(|e| 1.0 / (1.0 + (-logits[mi * n_experts + e]).exp())).collect(); let mut score: Vec = (0..n_experts).map(|e| prob[e] + bias[e]).collect(); let mut wsum = 0f32; for k in 0..k_top { let mut bv = f32::NEG_INFINITY; let mut bi = 0usize; for e in 0..n_experts { if score[e] > bv { bv = score[e]; bi = e; } } ids[mi * k_top + k] = bi as i32; weights[mi * k_top + k] = prob[bi]; wsum += prob[bi]; score[bi] = -1e30; } let inv = route_scale / (wsum + 1e-20); for k in 0..k_top { weights[mi * k_top + k] *= inv; } } (ids, weights) } fn read_i32(buf: &DeviceBuf, len: usize) -> Vec { let mut bytes = vec![0u8; len * 4]; buf.d2h_bytes(&mut bytes).unwrap(); bytes.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect() } #[test] #[ignore] fn moe_router_parity_vs_cpu() { let (m, n_experts, k_top, route_scale) = (2usize, 128usize, 8usize, 8.0f32); let logits: Vec = (0..m * n_experts).map(|i| ((i % 47) as f32 - 23.0) * 0.2).collect(); let bias: Vec = (0..n_experts).map(|i| ((i % 19) as f32 - 9.0) * 0.03).collect(); let (want_ids, want_w) = cpu_router(&logits, &bias, m, n_experts, k_top, route_scale); let dl = DeviceBuf::alloc(logits.len() * 4).unwrap(); let db = DeviceBuf::alloc(bias.len() * 4).unwrap(); let di = DeviceBuf::alloc(want_ids.len() * 4).unwrap(); let dw = DeviceBuf::alloc(want_w.len() * 4).unwrap(); dl.h2d(&logits).unwrap(); db.h2d(&bias).unwrap(); moe_router_topk(&dl, Some(&db), &di, &dw, m as i32, n_experts as i32, k_top as i32, route_scale).unwrap(); let got_ids = read_i32(&di, want_ids.len()); let mut got_w = vec![0f32; want_w.len()]; dw.d2h(&mut got_w).unwrap(); assert_eq!(got_ids, want_ids, "router top-k ids must match exactly"); let mut max_rel = 0f32; for (g, w) in got_w.iter().zip(want_w.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); } eprintln!("router max_rel_err={max_rel:.3e}"); assert!(max_rel < 1e-5, "router weights parity failed: {max_rel}"); } #[test] #[ignore] fn vec_add_exact() { let n = 10000usize; let a: Vec = (0..n).map(|i| (i as f32) * 0.01).collect(); let b: Vec = (0..n).map(|i| -(i as f32) * 0.003).collect(); let want: Vec = a.iter().zip(&b).map(|(x, y)| x + y).collect(); let da = DeviceBuf::alloc(n * 4).unwrap(); let db = DeviceBuf::alloc(n * 4).unwrap(); let dy = DeviceBuf::alloc(n * 4).unwrap(); da.h2d(&a).unwrap(); db.h2d(&b).unwrap(); vec_add(&da, &db, &dy, n).unwrap(); let mut got = vec![0f32; n]; dy.d2h(&mut got).unwrap(); assert_eq!(got, want, "vec_add must be exact"); } fn e2m1(nib: u8) -> f32 { const LUT: [f32; 16] = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0]; LUT[(nib & 15) as usize] } fn e4m3(b: u8) -> f32 { let sign = ((b & 0x80) as u32) << 24; let exp = (b >> 3) & 0xF; let mant = b & 7; if exp == 0 { if mant == 0 { return f32::from_bits(sign); } let val = mant as f32 / 512.0; return if b & 0x80 != 0 { -val } else { val }; } else if exp == 15 && mant == 7 { return 0.0; } f32::from_bits(sign | ((exp as u32 + 120) << 23) | ((mant as u32) << 20)) } #[test] #[ignore] fn nvfp4_gemv_parity_vs_cpu() { for &(n, k) in &[(8usize, 64usize), (16, 256), (32, 128)] { let outer = 0.5f32; let packed: Vec = (0..n * (k / 2)).map(|i| (i % 256) as u8).collect(); let scales: Vec = (0..n * (k / 16)).map(|i| ((i * 7 + 3) % 251) as u8).collect(); let x: Vec = (0..k).map(|i| ((i % 29) as f32 - 14.0) * 0.04).collect(); // CPU oracle: dequant then dot, f32. let mut want = vec![0f32; n]; for ni in 0..n { let mut acc = 0f32; for b in 0..k / 16 { let sc = e4m3(scales[ni * (k / 16) + b]) * outer; for j in 0..8 { let byte = packed[ni * (k / 2) + b * 8 + j]; let w0 = e2m1(byte & 15) * sc; let w1 = e2m1(byte >> 4) * sc; acc += x[b * 16 + j * 2] * w0 + x[b * 16 + j * 2 + 1] * w1; } } want[ni] = acc; } let dp = DeviceBuf::alloc(packed.len()).unwrap(); let ds = DeviceBuf::alloc(scales.len()).unwrap(); let dx = DeviceBuf::alloc(x.len() * 4).unwrap(); let dy = DeviceBuf::alloc(n * 4).unwrap(); dp.h2d_bytes(&packed).unwrap(); ds.h2d_bytes(&scales).unwrap(); dx.h2d(&x).unwrap(); nvfp4_gemv(&dp, &ds, outer, &dx, &dy, n as i32, k as i32).unwrap(); let mut got = vec![0f32; n]; dy.d2h(&mut got).unwrap(); let mut max_rel = 0f32; for (g, w) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); } eprintln!("nvfp4_gemv n={n} k={k} max_rel_err={max_rel:.3e}"); assert!(max_rel < 1e-4, "nvfp4 parity failed: {max_rel}"); } } #[test] #[ignore] fn situ_parity_vs_cpu() { let (beta, lb) = (4.0f32, 25.0f32); for &inter in &[1152usize, 64, 256] { let gu: Vec = (0..2 * inter).map(|i| ((i % 61) as f32 - 30.0) * 0.3).collect(); let want: Vec = (0..inter).map(|j| { let g = gu[j]; let u = gu[inter + j]; let sig = 1.0 / (1.0 + (-g).exp()); let ga = beta * (g / beta).tanh() * sig; let ua = lb * (u / lb).tanh(); ga * ua }).collect(); let dgu = DeviceBuf::alloc(gu.len() * 4).unwrap(); let da = DeviceBuf::alloc(inter * 4).unwrap(); dgu.h2d(&gu).unwrap(); situ(&dgu, &da, inter as i32, beta, lb).unwrap(); let mut got = vec![0f32; inter]; da.d2h(&mut got).unwrap(); let mut max_rel = 0f32; for (g, w) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); } eprintln!("situ inter={inter} max_rel_err={max_rel:.3e}"); assert!(max_rel < 1e-5, "situ parity failed: {max_rel}"); } } #[test] #[ignore] fn moe_reduce_parity_vs_cpu() { let (top_k, hidden) = (8usize, 2304usize); let y_part: Vec = (0..top_k * hidden).map(|i| ((i % 43) as f32 - 21.0) * 0.02).collect(); let tk_w: Vec = (0..top_k).map(|e| 0.5 + (e as f32) * 0.1).collect(); let want: Vec = (0..hidden).map(|d| (0..top_k).map(|e| tk_w[e] * y_part[e * hidden + d]).sum()).collect(); let dy = DeviceBuf::alloc(y_part.len() * 4).unwrap(); let dw = DeviceBuf::alloc(tk_w.len() * 4).unwrap(); let dout = DeviceBuf::alloc(hidden * 4).unwrap(); dy.h2d(&y_part).unwrap(); dw.h2d(&tk_w).unwrap(); moe_reduce(&dy, &dw, &dout, top_k as i32, hidden as i32).unwrap(); let mut got = vec![0f32; hidden]; dout.d2h(&mut got).unwrap(); let mut max_rel = 0f32; for (g, w) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); } eprintln!("moe_reduce max_rel_err={max_rel:.3e}"); assert!(max_rel < 1e-5, "moe_reduce parity failed: {max_rel}"); } #[test] #[ignore] fn shortconv4_multistep_parity() { let c = 64usize; let steps = 6usize; let inv_sqrt5 = 0.44721359549995793f32; let sw: Vec = (0..c * 4).map(|i| ((i % 17) as f32 - 8.0) * 0.05).collect(); let mut hist: Vec = (0..3 * c).map(|i| ((i % 11) as f32 - 5.0) * 0.1).collect(); let xs: Vec> = (0..steps).map(|t| (0..c).map(|i| ((i + t * 7) % 23) as f32 * 0.03 - 0.3).collect()).collect(); let dsw = DeviceBuf::alloc(sw.len() * 4).unwrap(); dsw.h2d(&sw).unwrap(); let dh = DeviceBuf::alloc(hist.len() * 4).unwrap(); dh.h2d(&hist).unwrap(); let dcur = DeviceBuf::alloc(c * 4).unwrap(); let dout = DeviceBuf::alloc(c * 4).unwrap(); let dslot = DeviceBuf::alloc(4).unwrap(); dslot.h2d_bytes(&0i32.to_le_bytes()).unwrap(); for t in 0..steps { // CPU oracle step (hist evolves on host). let mut want = vec![0f32; c]; for ch in 0..c { let h0 = hist[ch]; let h1 = hist[c + ch]; let h2 = hist[2 * c + ch]; let x0 = xs[t][ch]; let w = &sw[ch * 4..ch * 4 + 4]; want[ch] = (x0 + w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * x0) * inv_sqrt5; } for ch in 0..c { hist[ch] = hist[c + ch]; hist[c + ch] = hist[2 * c + ch]; hist[2 * c + ch] = xs[t][ch]; } // GPU step (hist evolves on device). dcur.h2d(&xs[t]).unwrap(); shortconv4_decode(&dcur, &dsw, &dh, &dout, &dslot, 1, c as i32).unwrap(); let mut got = vec![0f32; c]; dout.d2h(&mut got).unwrap(); let mut max_rel = 0f32; for (g, w) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); } assert!(max_rel < 1e-5, "shortconv4 step {t} parity failed: {max_rel}"); } // device history must match host history after all steps. let mut dh_host = vec![0f32; 3 * c]; dh.d2h(&mut dh_host).unwrap(); assert_eq!(dh_host, hist, "shortconv4 history ring must match"); eprintln!("shortconv4 {steps}-step recurrence + history ring: exact"); } #[test] #[ignore] fn shortconv4_dyn_multistep_parity() { let c = 64usize; let n_heads = 4usize; let steps = 5usize; let sw: Vec = (0..c * 4).map(|i| ((i % 17) as f32 - 8.0) * 0.05).collect(); let mut hist: Vec = (0..3 * c).map(|i| ((i % 11) as f32 - 5.0) * 0.1).collect(); let xs: Vec> = (0..steps).map(|t| (0..c).map(|i| ((i + t * 7) % 23) as f32 * 0.03 - 0.3).collect()).collect(); let dyns: Vec> = (0..steps).map(|t| (0..n_heads * 4).map(|i| ((i + t * 5) % 13) as f32 * 0.02 - 0.1).collect()).collect(); let dsw = DeviceBuf::alloc(sw.len() * 4).unwrap(); dsw.h2d(&sw).unwrap(); let dh = DeviceBuf::alloc(hist.len() * 4).unwrap(); dh.h2d(&hist).unwrap(); let dcur = DeviceBuf::alloc(c * 4).unwrap(); let dout = DeviceBuf::alloc(c * 4).unwrap(); let ddyn = DeviceBuf::alloc(n_heads * 4 * 4).unwrap(); let dslot = DeviceBuf::alloc(4).unwrap(); dslot.h2d_bytes(&0i32.to_le_bytes()).unwrap(); for t in 0..steps { let mut want = vec![0f32; c]; for ch in 0..c { let h0 = hist[ch]; let h1 = hist[c + ch]; let h2 = hist[2 * c + ch]; let x0 = xs[t][ch]; let w = &sw[ch * 4..ch * 4 + 4]; let head = ch / (c / n_heads); let dt = &dyns[t][head * 4..head * 4 + 4]; let y = x0 + w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * x0 + dt[0] * x0 + dt[1] * h2 + dt[2] * h1 + dt[3] * h0; want[ch] = y / 3.0; } for ch in 0..c { hist[ch] = hist[c + ch]; hist[c + ch] = hist[2 * c + ch]; hist[2 * c + ch] = xs[t][ch]; } dcur.h2d(&xs[t]).unwrap(); ddyn.h2d(&dyns[t]).unwrap(); shortconv4_dyn_decode(&dcur, &dsw, &ddyn, &dh, &dout, &dslot, 1, c as i32, n_heads as i32).unwrap(); let mut got = vec![0f32; c]; dout.d2h(&mut got).unwrap(); let mut mr = 0f32; for (g, w) in got.iter().zip(want.iter()) { mr = mr.max((g - w).abs() / w.abs().max(1e-3)); } assert!(mr < 1e-5, "shortconv4_dyn step {t} parity failed: {mr}"); } let mut dh_host = vec![0f32; 3 * c]; dh.d2h(&mut dh_host).unwrap(); assert_eq!(dh_host, hist, "shortconv4_dyn history ring must match"); eprintln!("shortconv4_dyn {steps}-step recurrence + history ring: exact"); } #[test] #[ignore] fn attn_res_mix_parity_vs_cpu() { let (nb, m, nq, d) = (3usize, 2usize, 2usize, 64usize); let eps = 1e-6f32; let blocks: Vec = (0..nb * m * d).map(|i| ((i % 37) as f32 - 18.0) * 0.03).collect(); let cur: Vec = (0..m * d).map(|i| ((i % 29) as f32 - 14.0) * 0.04).collect(); let queries: Vec = (0..nq * d).map(|i| ((i % 19) as f32 - 9.0) * 0.05).collect(); let n_states = nb + 1; let inv_sqrt_d = 1.0 / (d as f32).sqrt(); let state = |s: usize, mi: usize, dd: usize| -> f32 { if s < nb { blocks[(s * m + mi) * d + dd] } else { cur[mi * d + dd] } }; let mut want = vec![0f32; m * nq * d]; for mi in 0..m { for q in 0..nq { let mut scores = vec![0f32; n_states]; let mut irs = vec![0f32; n_states]; for s in 0..n_states { let mut ss = 0f32; let mut dot = 0f32; for dd in 0..d { let x = state(s, mi, dd); ss += x * x; dot += x * queries[q * d + dd]; } let ir = 1.0 / (ss / d as f32 + eps).sqrt(); irs[s] = ir; scores[s] = dot * ir * inv_sqrt_d; } let mx = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max); let exps: Vec = scores.iter().map(|sc| (sc - mx).exp()).collect(); let sum: f32 = exps.iter().sum(); let weights: Vec = exps.iter().zip(&irs).map(|(e, ir)| (e / sum) * ir).collect(); for dd in 0..d { let mut acc = 0f32; for s in 0..n_states { acc += weights[s] * state(s, mi, dd); } want[(mi * nq + q) * d + dd] = acc; } } } let db = DeviceBuf::alloc(blocks.len() * 4).unwrap(); let dc = DeviceBuf::alloc(cur.len() * 4).unwrap(); let dq = DeviceBuf::alloc(queries.len() * 4).unwrap(); let dout = DeviceBuf::alloc(want.len() * 4).unwrap(); db.h2d(&blocks).unwrap(); dc.h2d(&cur).unwrap(); dq.h2d(&queries).unwrap(); attn_res_mix(&db, &dc, &dq, &dout, nb as i32, m as i32, nq as i32, d as i32, eps).unwrap(); let mut got = vec![0f32; want.len()]; dout.d2h(&mut got).unwrap(); let mut max_rel = 0f32; for (g, w) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); } eprintln!("attn_res_mix nb={nb} m={m} nq={nq} d={d} max_rel_err={max_rel:.3e}"); assert!(max_rel < 1e-4, "attn_res_mix parity failed: {max_rel}"); } fn l2_clip_cpu(x: &[f32], scale: Option<&[f32]>, rows: usize, hd: usize, clip: f32, apply_tau: bool, pos: i32) -> Vec { let mut out = vec![0f32; rows * hd]; for r in 0..rows { let v: Vec = (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 mut fac = (clip / (ss.sqrt() + 1e-6)).min(1.0); if apply_tau { let rr = (pos + 1) as f32 / 8192.0; fac *= 1.0 + 0.1 * rr.max(1.0).ln(); } for d in 0..hd { out[r * hd + d] = v[d] * fac; } } out } #[test] #[ignore] fn k2_prep_kernels_parity() { // --- l2_clip (with scale + tau, and without) --- let (rows, hd) = (4usize, 8usize); let x: Vec = (0..rows * hd).map(|i| ((i % 29) as f32 - 14.0) * 0.5).collect(); let scale: Vec = (0..rows * hd).map(|i| 0.5 + (i % 7) as f32 * 0.1).collect(); for &(use_scale, tau, pos) in &[(true, true, 10000i32), (false, false, 0)] { let clip = 2.0f32; let want = l2_clip_cpu(&x, use_scale.then_some(scale.as_slice()), rows, hd, clip, tau, pos); let dx = DeviceBuf::alloc(x.len() * 4).unwrap(); dx.h2d(&x).unwrap(); let ds = DeviceBuf::alloc(scale.len() * 4).unwrap(); ds.h2d(&scale).unwrap(); l2_clip(&dx, use_scale.then_some(&ds), rows as i32, hd as i32, clip, tau, pos).unwrap(); let mut got = vec![0f32; x.len()]; dx.d2h(&mut got).unwrap(); let mut mr = 0f32; for (g, w) in got.iter().zip(want.iter()) { mr = mr.max((g - w).abs() / w.abs().max(1e-3)); } assert!(mr < 1e-5, "l2_clip parity failed (scale={use_scale} tau={tau}): {mr}"); } // --- relpos_bias --- let (n_head, d_rel, rel_extent, lim) = (4usize, 4usize, 16usize, 10i32); let r: Vec = (0..n_head * d_rel).map(|i| ((i % 13) as f32 - 6.0) * 0.1).collect(); let rp: Vec = (0..d_rel * rel_extent).map(|i| ((i % 11) as f32 - 5.0) * 0.05).collect(); let mut want_rb = 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[h * d_rel + rc] * rp[rc * rel_extent + dist]; } want_rb[h * rel_extent + dist] = acc; } } let dr = DeviceBuf::alloc(r.len() * 4).unwrap(); dr.h2d(&r).unwrap(); let drp = DeviceBuf::alloc(rp.len() * 4).unwrap(); drp.h2d(&rp).unwrap(); let drb = DeviceBuf::alloc(want_rb.len() * 4).unwrap(); drb.h2d(&vec![0f32; want_rb.len()]).unwrap(); relpos_bias(&dr, &drp, &drb, n_head as i32, d_rel as i32, rel_extent as i32, lim).unwrap(); let mut got_rb = vec![0f32; want_rb.len()]; drb.d2h(&mut got_rb).unwrap(); let mut mr = 0f32; for (g, w) in got_rb.iter().zip(want_rb.iter()) { mr = mr.max((g - w).abs() / w.abs().max(1e-3)); } assert!(mr < 1e-5, "relpos_bias parity failed: {mr}"); // --- kv_store --- let (n_kv, hd2, seq, pos) = (2usize, 8usize, 16usize, 5i32); let eps = 1e-6f32; let k_in: Vec = (0..n_kv * hd2).map(|i| ((i % 17) as f32 - 8.0) * 0.2).collect(); let v_in: Vec = (0..n_kv * hd2).map(|i| ((i % 19) as f32 - 9.0) * 0.3).collect(); let mut want_k = vec![0f32; n_kv * seq * hd2]; let mut want_v = vec![0f32; n_kv * seq * hd2]; for h in 0..n_kv { let ss: f32 = (0..hd2).map(|d| v_in[h * hd2 + d] * v_in[h * hd2 + d]).sum(); let fac = 1.0 / (ss / hd2 as f32 + eps).sqrt(); for d in 0..hd2 { let off = (h * seq + pos as usize) * hd2 + d; want_k[off] = k_in[h * hd2 + d]; want_v[off] = v_in[h * hd2 + d] * fac; } } let dki = DeviceBuf::alloc(k_in.len() * 4).unwrap(); dki.h2d(&k_in).unwrap(); let dvi = DeviceBuf::alloc(v_in.len() * 4).unwrap(); dvi.h2d(&v_in).unwrap(); let dkc = DeviceBuf::alloc(want_k.len() * 4).unwrap(); let dvc = DeviceBuf::alloc(want_v.len() * 4).unwrap(); dkc.h2d(&vec![0f32; want_k.len()]).unwrap(); dvc.h2d(&vec![0f32; want_v.len()]).unwrap(); kv_store(&dki, &dvi, &dkc, &dvc, pos, n_kv as i32, hd2 as i32, seq as i32, eps).unwrap(); let mut got_k = vec![0f32; want_k.len()]; dkc.d2h(&mut got_k).unwrap(); let mut got_v = vec![0f32; want_v.len()]; dvc.d2h(&mut got_v).unwrap(); assert_eq!(got_k, want_k, "kv_store K must match exactly"); let mut mr = 0f32; for (g, w) in got_v.iter().zip(want_v.iter()) { mr = mr.max((g - w).abs() / w.abs().max(1e-3)); } assert!(mr < 1e-5, "kv_store V parity failed: {mr}"); eprintln!("k2 prep kernels (l2_clip + relpos_bias + kv_store): parity OK"); } #[test] #[ignore] fn softcap_parity_vs_cpu() { let cap = 30.0f32; let n = 5000usize; let x: Vec = (0..n).map(|i| ((i % 201) as f32 - 100.0) * 0.5).collect(); let want: Vec = x.iter().map(|&v| cap * (v / cap).tanh()).collect(); let dx = DeviceBuf::alloc(n * 4).unwrap(); dx.h2d(&x).unwrap(); let dy = DeviceBuf::alloc(n * 4).unwrap(); softcap(&dx, &dy, n, cap).unwrap(); let mut got = vec![0f32; n]; dy.d2h(&mut got).unwrap(); 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!("softcap max_rel_err={mr:.3e}"); assert!(mr < 1e-5, "softcap parity failed: {mr}"); assert!(got.iter().all(|v| v.abs() <= cap + 1e-3), "softcap must bound logits"); } #[test] #[ignore] fn loop_controller_parity_vs_cpu() { let bf = |x: f32| -> u16 { (x.to_bits() >> 16) as u16 }; let ubf = |h: u16| -> f32 { f32::from_bits((h as u32) << 16) }; let trunc = |x: f32| -> f32 { ubf(bf(x)) }; let (d, gr) = (64usize, 8usize); let eps = 1e-6f32; let cur: Vec = (0..d).map(|i| ((i % 29) as f32 - 14.0) * 0.1).collect(); let msg: Vec = (0..d).map(|i| ((i % 23) as f32 - 11.0) * 0.08).collect(); let down: Vec = (0..gr * 2 * d).map(|i| bf(((i % 31) as f32 - 15.0) * 0.02)).collect(); let gain_w: Vec = (0..d * gr).map(|i| bf(((i % 17) as f32 - 8.0) * 0.03)).collect(); let forget_w: Vec = (0..d * gr).map(|i| bf(((i % 19) as f32 - 9.0) * 0.03)).collect(); // GPU let dc = DeviceBuf::alloc(d * 4).unwrap(); dc.h2d(&cur).unwrap(); let dm = DeviceBuf::alloc(d * 4).unwrap(); dm.h2d(&msg).unwrap(); let packed = DeviceBuf::alloc(2 * d * 2).unwrap(); ctrl_pack(&dc, &dm, &packed, d as i32, eps).unwrap(); let dd = DeviceBuf::alloc(down.len() * 2).unwrap(); dd.h2d_bytes(bytemuck_u16(&down)).unwrap(); let gate = DeviceBuf::alloc(gr * 4).unwrap(); gemm_bf16(&packed, &dd, &gate, 1, gr as i32, (2 * d) as i32).unwrap(); let gate_bf = DeviceBuf::alloc(gr * 2).unwrap(); cast_f32_bf16(&gate, &gate_bf, gr).unwrap(); let dg = DeviceBuf::alloc(gain_w.len() * 2).unwrap(); dg.h2d_bytes(bytemuck_u16(&gain_w)).unwrap(); let df = DeviceBuf::alloc(forget_w.len() * 2).unwrap(); df.h2d_bytes(bytemuck_u16(&forget_w)).unwrap(); let gain = DeviceBuf::alloc(d * 4).unwrap(); let forget = DeviceBuf::alloc(d * 4).unwrap(); gemm_bf16(&gate_bf, &dg, &gain, 1, d as i32, gr as i32).unwrap(); gemm_bf16(&gate_bf, &df, &forget, 1, d as i32, gr as i32).unwrap(); let out = DeviceBuf::alloc(d * 4).unwrap(); ctrl_apply(&dc, &dm, &gain, &forget, &out, d).unwrap(); let mut got = vec![0f32; d]; out.d2h(&mut got).unwrap(); // CPU oracle let ic = 1.0 / (cur.iter().map(|v| v * v).sum::() / d as f32 + eps).sqrt(); let im = 1.0 / (msg.iter().map(|v| v * v).sum::() / d as f32 + eps).sqrt(); let mut pk = vec![0f32; 2 * d]; for i in 0..d { pk[i] = trunc(cur[i] * ic); pk[d + i] = trunc(msg[i] * im); } let gate_c: Vec = (0..gr).map(|n| (0..2 * d).map(|k| pk[k] * ubf(down[n * 2 * d + k])).sum()).collect(); let gate_bf_c: Vec = gate_c.iter().map(|&v| trunc(v)).collect(); let gain_c: Vec = (0..d).map(|i| (0..gr).map(|r| gate_bf_c[r] * ubf(gain_w[i * gr + r])).sum()).collect(); let forget_c: Vec = (0..d).map(|i| (0..gr).map(|r| gate_bf_c[r] * ubf(forget_w[i * gr + r])).sum()).collect(); let want: Vec = (0..d).map(|i| (1.0 - forget_c[i].tanh()) * cur[i] + gain_c[i].tanh() * msg[i]).collect(); 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!("loop_controller max_rel_err={mr:.3e}"); assert!(mr < 1e-4, "loop controller parity failed: {mr}"); } fn bytemuck_u16(v: &[u16]) -> &[u8] { unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2) } } fn bytemuck_i32(v: &[i32]) -> &[u8] { unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 4) } } }