Files
vetta-infer/crates/vetta-infer-hip/src/lib.rs
T
adm 216983abae [HIP] P1 b6: BF16 dense projection WMMA tensor-core GEMM
k_gemm_bf16_wmma: drop-in for the tiled-LDS scalar k_gemm_bf16 (same bf16 X[M,K]/
W[N,K], f32 Y[M,N]). BM16/BN128(8 waves)/BK64 LDS; bf16 operands feed
__builtin_amdgcn_wmma_f32_16x16x16_bf16_w32 directly (no dequant). gemm_bf16 binding
dispatches WMMA for prefill (m>=16, k%64==0); decode m<16 keeps scalar;
VETTA_NO_BF16_WMMA=1 forces scalar (A/B baseline).
Parity vs serial-K CPU oracle (global-scale): 1.0e-7..3.0e-7 (bf16 products exact in
f32, only accumulation order differs). gw serve_gen 4/4; ld forward_batch argmax
111==111 (greedy gate), max_abs unchanged 7.25e-2.
MEASURED prefill 2048 synthetic A/B: scalar 36.2s -> WMMA 27.8s (-23%).
Cumulative prefill 60 -> 27.8s (-54%); reference ~4.5s, gap ~6x.
Suite GREEN: hip35 ld23 gw4 GPU serial, CPU -D warnings 23, Lean 6/6 0sorryAx.
2026-12-02 04:28:48 +01:00

2318 lines
135 KiB
Rust

//! `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_long, 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_hip_init_blocking_sync() -> 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_buf_copy(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int;
pub fn vetta_buf_copy2d(dst: *mut c_void, dpitch: usize, src: *const c_void, spitch: usize, width: usize, height: usize) -> c_int;
pub fn vetta_synchronize() -> c_int;
pub fn vetta_vram_used(out: *mut usize) -> c_int;
pub fn vetta_buf_zero_async(dst: *mut c_void, bytes: usize, stream: *mut c_void) -> 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_gemm_bf16_wmma(
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_router_gemv(
x: *const c_float, w: *const u16, y: *mut c_float,
n: c_int, k: c_int, stream: *mut c_void,
) -> c_int;
pub fn vetta_router_gemv_batched(x: *const c_float, w: *const u16, y: *mut c_float, n: c_int, k: c_int, m: 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, scores_scratch: *mut c_float, stream: *mut c_void,
) -> c_int;
pub fn vetta_flash_swa_gqa_decode_f16(
q: *const c_float, k: *const u16, v: *const u16, 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, scores_scratch: *mut c_float, stream: *mut c_void,
) -> c_int;
pub fn vetta_flash_swa_gqa_prefill_f16(
q: *const c_float, k: *const u16, v: *const u16, 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, pos: *const c_int, rel_bias: *const c_float, max_rel: c_int,
sink_logit: *const c_float, gate: *const c_float, scores_scratch: *mut c_float,
n_win_max: c_int, m: c_int, 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_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_f16(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_nvfp4_gemv_f16(
packed: *const u8, scales: *const u8, outer_scale: c_float, x: *const u16, y: *mut c_float,
n: c_int, k: c_int, stream: *mut c_void,
) -> c_int;
pub fn vetta_nvfp4_gemv_f16_indirect(
arena_packed: *const u8, arena_scales: *const u8, outer_arena: *const c_float,
ids: *const c_int, slot: c_int, x: *const u16, y: *mut c_float,
n: c_int, k: c_int, w_stride: c_long, sc_stride: c_long, y_offset: c_long, stream: *mut c_void,
) -> c_int;
pub fn vetta_nvfp4_gemv_f16_mt(
packed: *const u8, scales: *const u8, outer_scale: c_float, x: *const u16, y: *mut c_float,
m: c_int, 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_mxfp8_gemv_f16(weights: *const u8, scales: *const u8, x: *const u16, y: *mut c_float, n: c_int, k: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_mxfp8_gemv_f16_indirect(
arena_weights: *const u8, arena_scales: *const u8, ids: *const c_int, slot: c_int,
x: *const u16, y: *mut c_float, n: c_int, k: c_int, w_stride: c_long, sc_stride: c_long, y_offset: c_long, 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_situ_f16(gu: *const c_float, act: *mut u16, inter: c_int, beta: c_float, lb: c_float, stream: *mut c_void) -> c_int;
pub fn vetta_situ_f16_batched(gu: *const c_float, act: *mut u16, inter: c_int, beta: c_float, lb: c_float, m: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_mxfp8_grouped_gemv_f16(arena_weights: *const u8, arena_scales: *const u8, exp_off: *const c_int, bucket_tok: *const c_int, x: *const u16, y: *mut c_float, n: c_int, k: c_int, n_experts: c_int, w_stride: c_long, sc_stride: c_long, 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_moe_count_buckets(topk_ids: *const c_int, exp_cnt: *mut c_int, total: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_moe_prefix_buckets(exp_cnt: *const c_int, exp_off: *mut c_int, exp_cur: *mut c_int, stream: *mut c_void) -> c_int;
pub fn vetta_moe_scatter_buckets(topk_ids: *const c_int, exp_cur: *mut c_int, bucket_tok: *mut c_int, slotk_to_bidx: *mut c_int, total: c_int, top_k: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_nvfp4_grouped_gemv_f16(
arena_packed: *const u8, arena_scales: *const u8, outer_arena: *const c_float,
exp_off: *const c_int, bucket_tok: *const c_int, x: *const u16, y: *mut c_float,
n: c_int, k: c_int, n_experts: c_int, w_stride: c_long, sc_stride: c_long, stream: *mut c_void,
) -> c_int;
pub fn vetta_nvfp4_grouped_gemm_wmma(
arena_packed: *const u8, arena_scales: *const u8, outer_arena: *const c_float,
exp_off: *const c_int, bucket_tok: *const c_int, x: *const u16, y: *mut c_float,
n: c_int, k: c_int, n_experts: c_int, w_stride: c_long, sc_stride: c_long, stream: *mut c_void,
) -> c_int;
pub fn vetta_moe_reduce_buckets_masked(bucket_y: *const c_float, slotk_to_bidx: *const c_int, tk_w: *const c_float, out: *mut c_float, b: c_int, top_k: c_int, d: 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_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_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, scale_rows: c_int, pos_arr: *const 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_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_f16(k_in: *const c_float, v_in: *const c_float, k_cache: *mut u16, v_cache: *mut u16, 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_f16_batched(k_in: *const c_float, v_in: *const c_float, k_cache: *mut u16, v_cache: *mut u16, pos: *const c_int, n_kv: c_int, hd: c_int, seq: c_int, rms_eps: c_float, m: c_int, 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_pack_batched(cur: *const c_float, msg: *const c_float, packed: *mut u16, d: c_int, eps: c_float, m: c_int, 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<u8> = 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<DeviceInfo> {
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,
/// Whether drop returns this buffer to the size-bucketed pool. Large
/// per-request buffers whose size varies (KV cache) are unpooled so they are
/// truly freed instead of accumulating every distinct size in the pool.
pooled: bool,
}
// Size-bucketed free list of device buffers. The layer forward allocates and
// frees ~25 short-lived intermediates per visit (~1200 hipMalloc/hipFree per
// token); hipMalloc/hipFree each synchronize the device, dominating decode
// latency. Reusing freed buffers by exact size removes that churn. Safe because
// all launches share the default stream and every host copy (hipMemcpy) is
// blocking: a buffer is only recycled after its last use is ordered before the
// next launch that reuses it. Thread-local (cargo test runs tests in parallel).
// Escape hatch: VETTA_NO_BUF_POOL=1 forces raw hipMalloc/hipFree.
#[cfg(feature = "hip")]
thread_local! {
static BUF_POOL: std::cell::RefCell<std::collections::HashMap<usize, Vec<*mut std::os::raw::c_void>>> =
std::cell::RefCell::new(std::collections::HashMap::new());
// Total bytes currently retained (free) in the pool. Capped so the exact-size
// pool cannot accumulate every distinct batched-tail size (bu = suffix % chunk
// varies per turn) forever: beyond MAX_POOL_BYTES a dropped buffer is hipFree'd
// instead of pooled, bounding the multi-turn VRAM leak (audit 2026-12-02 §2.1).
static POOL_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Upper bound on bytes retained in the thread-local buffer pool. Hot fixed-size
/// intermediates (chunk=256 batched + M=1 decode) fit well under this; excess
/// distinct sizes are freed rather than retained without bound.
#[cfg(feature = "hip")]
const MAX_POOL_BYTES: usize = 512 * 1024 * 1024;
#[cfg(feature = "hip")]
static POOL_ENABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
/// Process-wide buffer-pool switch (safe; no env mutation). The resident serve
/// keeps the pool ON for speed. GPU integration tests turn it OFF so every
/// `DeviceBuf` drop calls `hipFree` and device memory is released between tests:
/// the thread-local pool otherwise retains buffers for the lifetime of each
/// libtest worker thread, exhausting the GPU across several full-model tests.
#[cfg(feature = "hip")]
pub fn set_buf_pool_enabled(on: bool) {
POOL_ENABLED.store(on, std::sync::atomic::Ordering::Relaxed);
}
/// Block until all queued GPU work completes. Used at profiling phase boundaries
/// (the batched forward is fully async otherwise); not on the hot path.
#[cfg(feature = "hip")]
pub fn synchronize() -> Result<(), String> {
let rc = unsafe { ffi::vetta_synchronize() };
if rc != 0 { return Err("hipDeviceSynchronize failed".into()); }
Ok(())
}
/// VRAM used bytes (total - free via hipMemGetInfo), for allocation profiling.
#[cfg(feature = "hip")]
pub fn vram_used() -> usize {
let mut used = 0usize;
unsafe { ffi::vetta_vram_used(&mut used) };
used
}
#[cfg(feature = "hip")]
fn pool_enabled() -> bool {
POOL_ENABLED.load(std::sync::atomic::Ordering::Relaxed)
&& std::env::var("VETTA_NO_BUF_POOL").is_err()
}
/// Set the blocking host-wait schedule once, before the first hipMalloc creates
/// the device context, so GPU waits sleep instead of spinning at 100% CPU (exact
/// strata --hip-sync blocking). Escape hatch VETTA_NO_BLOCKING_SYNC=1 keeps the
/// ROCm default spin schedule (for A/B CPU measurement).
#[cfg(feature = "hip")]
fn ensure_sync_init() {
static SYNC_INIT: std::sync::Once = std::sync::Once::new();
SYNC_INIT.call_once(|| unsafe {
if std::env::var("VETTA_NO_BLOCKING_SYNC").is_err() {
ffi::vetta_hip_init_blocking_sync();
}
});
}
#[cfg(feature = "hip")]
fn raw_alloc(bytes: usize) -> Result<*mut std::os::raw::c_void, String> {
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(ptr)
}
#[cfg(feature = "hip")]
impl DeviceBuf {
pub fn alloc(bytes: usize) -> Result<Self, String> {
ensure_sync_init();
if pool_enabled() {
if let Some(ptr) = BUF_POOL.with(|p| p.borrow_mut().get_mut(&bytes).and_then(|v| v.pop())) {
POOL_BYTES.with(|c| c.set(c.get().saturating_sub(bytes)));
return Ok(Self { ptr, bytes, pooled: true });
}
}
Ok(Self { ptr: raw_alloc(bytes)?, bytes, pooled: true })
}
/// Allocate a buffer that is ALWAYS `hipFree`'d on drop (never pooled). For
/// large per-request buffers whose size varies between requests (the KV
/// cache scales with prompt+max_new): the exact-size pool would retain every
/// distinct size and grow VRAM without bound across a multi-turn chat.
pub fn alloc_unpooled(bytes: usize) -> Result<Self, String> {
ensure_sync_init();
Ok(Self { ptr: raw_alloc(bytes)?, bytes, pooled: false })
}
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(())
}
/// Device-to-device copy of `bytes` from `src` into `self`.
pub fn copy_from(&self, src: &DeviceBuf, bytes: usize) -> Result<(), String> {
if bytes > self.bytes || bytes > src.bytes { return Err("copy overflow".into()); }
let rc = unsafe { ffi::vetta_buf_copy(self.ptr, src.ptr, bytes) };
if rc != 0 { return Err("d2d copy failed".into()); }
Ok(())
}
/// Pitched device-to-device copy: `height` rows of `width` bytes, source row
/// stride `spitch`, destination row stride `dpitch` (KV prefix sub-block).
pub fn copy2d_from(&self, src: &DeviceBuf, dpitch: usize, spitch: usize, width: usize, height: usize) -> Result<(), String> {
let rc = unsafe { ffi::vetta_buf_copy2d(self.ptr, dpitch, src.ptr, spitch, width, height) };
if rc != 0 { return Err("d2d copy2d failed".into()); }
Ok(())
}
/// Pitched device-to-device copy with byte offsets into BOTH buffers: copies
/// `height` rows of `width` bytes from `src[src_off..]` (row stride `spitch`)
/// into `self[dst_off..]` (row stride `dpitch`). Used by the SWA-window prefix
/// snapshot/restore to copy only the last `swa_win` KV positions of each head.
pub fn copy2d_at(&self, dst_off: usize, src: &DeviceBuf, src_off: usize, dpitch: usize, spitch: usize, width: usize, height: usize) -> Result<(), String> {
if height > 0 {
let dlast = dst_off + (height - 1) * dpitch + width;
let slast = src_off + (height - 1) * spitch + width;
if dlast > self.bytes || slast > src.bytes { return Err("copy2d_at overflow".into()); }
}
let dp = unsafe { (self.ptr as *mut u8).add(dst_off) as *mut std::os::raw::c_void };
let sp = unsafe { (src.ptr as *const u8).add(src_off) as *const std::os::raw::c_void };
let rc = unsafe { ffi::vetta_buf_copy2d(dp, dpitch, sp, spitch, width, height) };
if rc != 0 { return Err("d2d copy2d_at failed".into()); }
Ok(())
}
/// Async zero-fill of the whole buffer on the default stream (hipMemsetAsync):
/// ordered before later kernels with NO blocking host round-trip. Replaces a
/// sync `h2d(&vec![0; n])` that would drain the GPU queue every layer visit.
pub fn zero_async(&self) -> Result<(), String> {
let rc = unsafe { ffi::vetta_buf_zero_async(self.ptr, self.bytes, std::ptr::null_mut()) };
if rc != 0 { return Err("memset async failed".into()); }
Ok(())
}
}
#[cfg(feature = "hip")]
impl Drop for DeviceBuf {
fn drop(&mut self) {
if self.pooled && pool_enabled() && !self.ptr.is_null() {
// Retain only while under the global pool budget; otherwise hipFree so
// distinct one-off sizes (batched tail chunks) cannot leak unbounded.
let keep = POOL_BYTES.with(|c| {
if c.get().saturating_add(self.bytes) <= MAX_POOL_BYTES {
c.set(c.get() + self.bytes); true
} else { false }
});
if keep {
BUF_POOL.with(|p| p.borrow_mut().entry(self.bytes).or_default().push(self.ptr));
} else {
unsafe { ffi::vetta_buf_free(self.ptr); }
}
} else {
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).
/// Prefill (m>=16, k%64==0) dispatches the BF16 WMMA tensor-core kernel (P1 b6);
/// decode (m<16) keeps the tiled-LDS scalar kernel. VETTA_NO_BF16_WMMA=1 forces
/// scalar everywhere (A/B baseline). WMMA changes f32 accumulation order (~1e-3).
#[cfg(feature = "hip")]
pub fn gemm_bf16(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, m: i32, n: i32, k: i32) -> Result<(), String> {
if m >= 16 && k % 64 == 0 && std::env::var("VETTA_NO_BF16_WMMA").is_err() {
return gemm_bf16_wmma(x, w, y, m, n, k);
}
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_gemm_bf16_wmma: BF16 WMMA tensor-core dense GEMM (same I/O as gemm_bf16).
#[cfg(feature = "hip")]
pub fn gemm_bf16_wmma(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, m: i32, n: i32, k: i32) -> Result<(), String> {
let rc = unsafe {
ffi::vetta_gemm_bf16_wmma(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_bf16_wmma launch failed".into()); }
Ok(())
}
/// Launch k_router_gemv: y[n] = x_f32[k] @ w_bf16[n,k]^T (F32 router input).
#[cfg(feature = "hip")]
pub fn router_gemv(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32) -> Result<(), String> {
let rc = unsafe {
ffi::vetta_router_gemv(x.ptr as *const f32, w.ptr as *const u16, y.ptr as *mut f32, n, k, std::ptr::null_mut())
};
if rc != 0 { return Err("router_gemv launch failed".into()); }
Ok(())
}
/// Batched f32 router GEMM (M=B): x [M,K] f32, w [N,K] bf16 -> y [M,N].
#[cfg(feature = "hip")]
pub fn router_gemv_batched(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32, m: i32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_router_gemv_batched(x.ptr as *const f32, w.ptr as *const u16, y.ptr as *mut f32, n, k, m, std::ptr::null_mut()) };
if rc != 0 { return Err("router_gemv_batched 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(())
}
/// Global scratch for the flash-attention per-head scores `[n_head, n_win]`.
/// Scores live in global memory (not LDS) so the full-attn window is not capped
/// by the 64 KB shared-memory limit; only the `[nt]` reduction stays in shared.
#[cfg(feature = "hip")]
fn flash_scores_scratch(n_head: i32, swa_window: i32, cur_pos: i32) -> Result<DeviceBuf, String> {
let k_start = if swa_window > 0 && cur_pos >= swa_window { cur_pos - swa_window + 1 } else { 0 };
let n_win = (cur_pos - k_start + 1).max(1) as usize;
// Bucket the allocation to a power of two so the pool reuses it as cur_pos
// grows (full-attn n_win increases every token); otherwise every distinct
// size is retained and VRAM creeps up over a long generation. The kernel
// still strides by the actual n_win (<= bucket), so the extra slack is safe.
let cap = n_win.next_power_of_two();
DeviceBuf::alloc(n_head as usize * cap * 4)
}
/// 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 scratch = flash_scores_scratch(n_head, swa_window, cur_pos)?;
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, scratch.ptr as *mut f32, std::ptr::null_mut())
};
if rc != 0 { return Err("flash_swa_gqa launch failed".into()); }
Ok(())
}
/// Launch k_flash_swa_gqa_decode_f16: SWA attention reading an FP16 KV cache
/// (strata default). `k`/`v` are u16 FP16 buffers; attention math stays f32.
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn flash_swa_gqa_decode_f16(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 scratch = flash_scores_scratch(n_head, swa_window, cur_pos)?;
let rc = unsafe {
ffi::vetta_flash_swa_gqa_decode_f16(q.ptr as *const f32, k.ptr as *const u16, v.ptr as *const u16, out.ptr as *mut f32, n_head, n_kv, seq, hd, scale, swa_window, cur_pos, rb, max_rel, sk, gt, scratch.ptr as *mut f32, std::ptr::null_mut())
};
if rc != 0 { return Err("flash_swa_gqa_f16 launch failed".into()); }
Ok(())
}
/// Batched causal flash SWA GQA (M=B) on FP16 KV. `pos` [M] gives each query
/// token's cur_pos (causal); KV cache must already hold all B positions.
/// `max_pos` = largest pos in the batch (sizes the [M,n_head,n_win_max] scratch,
/// allocated unpooled since it varies per batch). q/out/gate [M,n_head,hd].
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn flash_swa_gqa_prefill_f16(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, out: &DeviceBuf, n_head: i32, n_kv: i32, seq: i32, hd: i32, scale: f32, swa_window: i32, pos: &DeviceBuf, max_pos: i32, rel_bias: Option<&DeviceBuf>, max_rel: i32, sink_logit: Option<&DeviceBuf>, gate: Option<&DeviceBuf>, m: i32) -> 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 n_win_max = if swa_window > 0 && max_pos >= swa_window { swa_window } else { max_pos + 1 };
let scratch = DeviceBuf::alloc_unpooled((m as usize) * (n_head as usize) * (n_win_max as usize) * 4)?;
let rc = unsafe {
ffi::vetta_flash_swa_gqa_prefill_f16(q.ptr as *const f32, k.ptr as *const u16, v.ptr as *const u16, out.ptr as *mut f32, n_head, n_kv, seq, hd, scale, swa_window, pos.ptr as *const i32, rb, max_rel, sk, gt, scratch.ptr as *mut f32, n_win_max, m, std::ptr::null_mut())
};
if rc != 0 { return Err("flash_swa_gqa_prefill_f16 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(())
}
/// Device-side f32 copy (dst=src, n elements): depth-block snapshot / bank rollback.
#[cfg(feature = "hip")]
pub fn copy_f32(src: &DeviceBuf, dst: &DeviceBuf, n: usize) -> Result<(), String> {
let rc = unsafe { ffi::vetta_copy_f32(src.ptr as *const f32, dst.ptr as *mut f32, n, std::ptr::null_mut()) };
if rc != 0 { return Err("copy_f32 launch failed".into()); }
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(())
}
/// Device-side f32 copy from `src` at element offset `src_offset` -> dst[0..n]
/// (extract a contiguous arena sub-range, e.g. the core-loop bank or last token).
#[cfg(feature = "hip")]
pub fn copy_f32_sub(src: &DeviceBuf, src_offset: usize, dst: &DeviceBuf, n: usize) -> Result<(), String> {
if src_offset * 4 + n * 4 > src.bytes { return Err("copy_f32_sub overflow".into()); }
let src_ptr = unsafe { (src.ptr as *const f32).add(src_offset) };
let rc = unsafe { ffi::vetta_copy_f32(src_ptr, dst.ptr as *mut f32, n, std::ptr::null_mut()) };
if rc != 0 { return Err("copy_f32_sub launch failed".into()); }
Ok(())
}
/// Launch k_cast_f32_bf16: f32 activation -> BF16 (round-to-nearest-even).
#[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 INTERLEAVED gate/up -> act f32).
#[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_cast_f32_f16: f32 activation -> FP16 (RNE), exact strata k_f32_to_f16.
#[cfg(feature = "hip")]
pub fn cast_f32_f16(x: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result<(), String> {
let rc = unsafe { ffi::vetta_cast_f32_f16(x.ptr as *const f32, y.ptr as *mut u16, n, std::ptr::null_mut()) };
if rc != 0 { return Err("cast_f32_f16 launch failed".into()); }
Ok(())
}
/// Launch k_nvfp4_gemv_f16: NVFP4 GEMV reading FP16 activations (strata B=1 path).
#[cfg(feature = "hip")]
pub fn nvfp4_gemv_f16(packed: &DeviceBuf, scales: &DeviceBuf, outer_scale: f32, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32) -> Result<(), String> {
let rc = unsafe {
ffi::vetta_nvfp4_gemv_f16(packed.ptr as *const u8, scales.ptr as *const u8, outer_scale, x.ptr as *const u16, y.ptr as *mut f32, n, k, std::ptr::null_mut())
};
if rc != 0 { return Err("nvfp4_gemv_f16 launch failed".into()); }
Ok(())
}
/// Device-routed NVFP4 f16 GEMV: the expert id is read from `ids[slot]` on device
/// and indexes a contiguous per-layer arena (packed weights / scales / outer).
/// Launch parameters are static => graph-capturable MoE dispatch (no host ids
/// round-trip). `w_stride`/`sc_stride` are the per-expert byte spans. Same math
/// as `nvfp4_gemv_f16` (shared device body).
#[cfg(feature = "hip")]
pub fn nvfp4_gemv_f16_indirect(arena_packed: &DeviceBuf, arena_scales: &DeviceBuf, outer_arena: &DeviceBuf, ids: &DeviceBuf, slot: i32, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32, w_stride: i64, sc_stride: i64, y_offset: i64) -> Result<(), String> {
let rc = unsafe {
ffi::vetta_nvfp4_gemv_f16_indirect(arena_packed.ptr as *const u8, arena_scales.ptr as *const u8, outer_arena.ptr as *const f32, ids.ptr as *const i32, slot, x.ptr as *const u16, y.ptr as *mut f32, n, k, w_stride, sc_stride, y_offset, std::ptr::null_mut())
};
if rc != 0 { return Err("nvfp4_gemv_f16_indirect launch failed".into()); }
Ok(())
}
/// Batched (M>1) NVFP4 f16 GEMM for prefill: X [M,K] f16, Y [M,N] f32. The W
/// group is dequantized once and reused across MT=16 tokens (M tiled by
/// blockIdx.y), amortizing expert weight bandwidth MT-fold vs the M=1 GEMV.
#[cfg(feature = "hip")]
pub fn nvfp4_gemv_f16_mt(packed: &DeviceBuf, scales: &DeviceBuf, outer_scale: f32, x: &DeviceBuf, y: &DeviceBuf, m: i32, n: i32, k: i32) -> Result<(), String> {
let rc = unsafe {
ffi::vetta_nvfp4_gemv_f16_mt(packed.ptr as *const u8, scales.ptr as *const u8, outer_scale, x.ptr as *const u16, y.ptr as *mut f32, m, n, k, std::ptr::null_mut())
};
if rc != 0 { return Err("nvfp4_gemv_f16_mt launch failed".into()); }
Ok(())
}
/// Launch k_mxfp8_gemv_f16: MXFP8 GEMV reading FP16 activations (strata B=1 path).
#[cfg(feature = "hip")]
pub fn mxfp8_gemv_f16(weights: &DeviceBuf, scales: &DeviceBuf, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32) -> Result<(), String> {
let rc = unsafe {
ffi::vetta_mxfp8_gemv_f16(weights.ptr as *const u8, scales.ptr as *const u8, x.ptr as *const u16, y.ptr as *mut f32, n, k, std::ptr::null_mut())
};
if rc != 0 { return Err("mxfp8_gemv_f16 launch failed".into()); }
Ok(())
}
/// Device-routed MXFP8 f16 GEMV (arena + ids[slot]); graph-capturable, no outer.
#[cfg(feature = "hip")]
pub fn mxfp8_gemv_f16_indirect(arena_weights: &DeviceBuf, arena_scales: &DeviceBuf, ids: &DeviceBuf, slot: i32, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32, w_stride: i64, sc_stride: i64, y_offset: i64) -> Result<(), String> {
let rc = unsafe {
ffi::vetta_mxfp8_gemv_f16_indirect(arena_weights.ptr as *const u8, arena_scales.ptr as *const u8, ids.ptr as *const i32, slot, x.ptr as *const u16, y.ptr as *mut f32, n, k, w_stride, sc_stride, y_offset, std::ptr::null_mut())
};
if rc != 0 { return Err("mxfp8_gemv_f16_indirect launch failed".into()); }
Ok(())
}
/// Launch k_situ_f16: SiTU computed in f32, stored FP16 (exact strata act_out).
#[cfg(feature = "hip")]
pub fn situ_f16(gu: &DeviceBuf, act: &DeviceBuf, inter: i32, beta: f32, lb: f32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_situ_f16(gu.ptr as *const f32, act.ptr as *mut u16, inter, beta, lb, std::ptr::null_mut()) };
if rc != 0 { return Err("situ_f16 launch failed".into()); }
Ok(())
}
/// Batched SiTU (M rows): gu [M,2*inter] interleaved gate/up -> act [M,inter] FP16.
#[cfg(feature = "hip")]
pub fn situ_f16_batched(gu: &DeviceBuf, act: &DeviceBuf, inter: i32, beta: f32, lb: f32, m: i32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_situ_f16_batched(gu.ptr as *const f32, act.ptr as *mut u16, inter, beta, lb, m, std::ptr::null_mut()) };
if rc != 0 { return Err("situ_f16_batched launch failed".into()); }
Ok(())
}
/// Grouped MXFP8 expert GEMM (layers 20-23): grid (N, n_experts), bucket-indexed,
/// 32-byte E4M3 group dequantized once per MT=8 token tile (UE8M0 scale, no outer).
/// X [B,K] f16 -> Y [total_pairs,N] f32 bucket order.
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn mxfp8_grouped_gemv_f16(arena_weights: &DeviceBuf, arena_scales: &DeviceBuf, exp_off: &DeviceBuf, bucket_tok: Option<&DeviceBuf>, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32, n_experts: i32, w_stride: i64, sc_stride: i64) -> Result<(), String> {
let bt = bucket_tok.map(|b| b.ptr as *const i32).unwrap_or(std::ptr::null());
let rc = unsafe {
ffi::vetta_mxfp8_grouped_gemv_f16(arena_weights.ptr as *const u8, arena_scales.ptr as *const u8, exp_off.ptr as *const i32, bt, x.ptr as *const u16, y.ptr as *mut f32, n, k, n_experts, w_stride, sc_stride, std::ptr::null_mut())
};
if rc != 0 { return Err("mxfp8_grouped_gemv_f16 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(())
}
/// Grouped-MoE bucket CSR build (device-side, no host round-trip). `exp_cnt`
/// [129] must be pre-zeroed; after count+prefix, `exp_off` [129] holds CSR
/// offsets and `exp_cur` [128] the write cursors; scatter fills `bucket_tok`
/// [total] (bucket->token) and `slotk_to_bidx` [total] (pair->bucket position).
#[cfg(feature = "hip")]
pub fn moe_count_buckets(topk_ids: &DeviceBuf, exp_cnt: &DeviceBuf, total: i32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_moe_count_buckets(topk_ids.ptr as *const i32, exp_cnt.ptr as *mut i32, total, std::ptr::null_mut()) };
if rc != 0 { return Err("moe_count_buckets launch failed".into()); }
Ok(())
}
#[cfg(feature = "hip")]
pub fn moe_prefix_buckets(exp_cnt: &DeviceBuf, exp_off: &DeviceBuf, exp_cur: &DeviceBuf) -> Result<(), String> {
let rc = unsafe { ffi::vetta_moe_prefix_buckets(exp_cnt.ptr as *const i32, exp_off.ptr as *mut i32, exp_cur.ptr as *mut i32, std::ptr::null_mut()) };
if rc != 0 { return Err("moe_prefix_buckets launch failed".into()); }
Ok(())
}
#[cfg(feature = "hip")]
pub fn moe_scatter_buckets(topk_ids: &DeviceBuf, exp_cur: &DeviceBuf, bucket_tok: &DeviceBuf, slotk_to_bidx: &DeviceBuf, total: i32, top_k: i32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_moe_scatter_buckets(topk_ids.ptr as *const i32, exp_cur.ptr as *mut i32, bucket_tok.ptr as *mut i32, slotk_to_bidx.ptr as *mut i32, total, top_k, std::ptr::null_mut()) };
if rc != 0 { return Err("moe_scatter_buckets launch failed".into()); }
Ok(())
}
/// Grouped MoE expert GEMM (one launch, grid.y = n_experts): expert eid processes
/// its bucket tokens [exp_off[eid], exp_off[eid+1]) via bucket_tok, W dequant
/// amortized MT-fold. X [B,K] f16, Y [total_pairs,N] f32 in bucket order.
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn nvfp4_grouped_gemv_f16(arena_packed: &DeviceBuf, arena_scales: &DeviceBuf, outer_arena: &DeviceBuf, exp_off: &DeviceBuf, bucket_tok: Option<&DeviceBuf>, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32, n_experts: i32, w_stride: i64, sc_stride: i64) -> Result<(), String> {
let bt = bucket_tok.map(|b| b.ptr as *const i32).unwrap_or(std::ptr::null());
let rc = unsafe {
ffi::vetta_nvfp4_grouped_gemv_f16(arena_packed.ptr as *const u8, arena_scales.ptr as *const u8, outer_arena.ptr as *const f32, exp_off.ptr as *const i32, bt, x.ptr as *const u16, y.ptr as *mut f32, n, k, n_experts, w_stride, sc_stride, std::ptr::null_mut())
};
if rc != 0 { return Err("nvfp4_grouped_gemv_f16 launch failed".into()); }
Ok(())
}
/// FP16 WMMA tensor-core grouped MoE GEMM (drop-in for nvfp4_grouped_gemv_f16).
/// Same arena/CSR I/O and Y[total,N] f32 bucket order; K must be a multiple of 64.
/// Matrix-core 16x16x16 tiles (~8x fdot2 ALU throughput). Accumulation order differs
/// from serial fdot2 => ~1e-3 (P1 tolerance; greedy-vs-reference is the blocking gate).
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn nvfp4_grouped_gemm_wmma(arena_packed: &DeviceBuf, arena_scales: &DeviceBuf, outer_arena: &DeviceBuf, exp_off: &DeviceBuf, bucket_tok: Option<&DeviceBuf>, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32, n_experts: i32, w_stride: i64, sc_stride: i64) -> Result<(), String> {
let bt = bucket_tok.map(|b| b.ptr as *const i32).unwrap_or(std::ptr::null());
let rc = unsafe {
ffi::vetta_nvfp4_grouped_gemm_wmma(arena_packed.ptr as *const u8, arena_scales.ptr as *const u8, outer_arena.ptr as *const f32, exp_off.ptr as *const i32, bt, x.ptr as *const u16, y.ptr as *mut f32, n, k, n_experts, w_stride, sc_stride, std::ptr::null_mut())
};
if rc != 0 { return Err("nvfp4_grouped_gemm_wmma launch failed".into()); }
Ok(())
}
/// Scatter-back + weighted reduce per token from bucket-order expert outputs:
/// out[b,d] = sum_kk tk_w[b*top_k+kk] * bucket_y[slotk_to_bidx[b*top_k+kk]*D+d].
#[cfg(feature = "hip")]
pub fn moe_reduce_buckets_masked(bucket_y: &DeviceBuf, slotk_to_bidx: &DeviceBuf, tk_w: &DeviceBuf, out: &DeviceBuf, b: i32, top_k: i32, d: i32) -> Result<(), String> {
let rc = unsafe {
ffi::vetta_moe_reduce_buckets_masked(bucket_y.ptr as *const f32, slotk_to_bidx.ptr as *const i32, tk_w.ptr as *const f32, out.ptr as *mut f32, b, top_k, d, std::ptr::null_mut())
};
if rc != 0 { return Err("moe_reduce_buckets_masked 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(())
}
/// Parallel causal ShortConv over B contiguous prefill tokens (tile 16). hist
/// [3,C] bf16-rounded f32 seed; dyn_taps nullable (static 1/sqrt5 vs dyn 1/3).
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn shortconv4_prefill_par(in_x: &DeviceBuf, static_w: &DeviceBuf, dyn_taps: Option<&DeviceBuf>, hist: &DeviceBuf, out_y: &DeviceBuf, b: i32, c: i32, n_heads: i32) -> Result<(), String> {
let dt = dyn_taps.map(|t| t.ptr as *const f32).unwrap_or(std::ptr::null());
let rc = unsafe { ffi::vetta_shortconv4_prefill_par(in_x.ptr as *const f32, static_w.ptr as *const f32, dt, hist.ptr as *const f32, out_y.ptr as *mut f32, b, c, n_heads, std::ptr::null_mut()) };
if rc != 0 { return Err("shortconv4_prefill_par launch failed".into()); }
Ok(())
}
/// Roll the 3-token ShortConv history after a prefill chunk (last 3 in_x bf16).
#[cfg(feature = "hip")]
pub fn shortconv4_update_hist(in_x: &DeviceBuf, hist: &DeviceBuf, b: i32, c: i32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_shortconv4_update_hist(in_x.ptr as *const f32, hist.ptr as *mut f32, b, c, std::ptr::null_mut()) };
if rc != 0 { return Err("shortconv4_update_hist 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, rows, std::ptr::null(), std::ptr::null_mut()) };
if rc != 0 { return Err("l2_clip launch failed".into()); }
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.
/// `pos_arr` (device [M]) supplies the per-token position for tau (full-attn);
/// pass None to use the scalar `pos` (SWA / no tau).
#[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, pos_arr: Option<&DeviceBuf>) -> Result<(), String> {
let sc = scale.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
let pa = pos_arr.map(|b| b.ptr as *const i32).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, pa, 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].
#[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(())
}
/// Batched relpos bias (M=B): r [M,n_head,d_rel] -> rel_bias [M,n_head,rel_extent],
/// lim[m]=min(pos[m]+1,rel_extent). Kernel writes the full rel_extent (0.0f beyond
/// lim), so the caller need NOT host zero-fill (no sync h2d).
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn relpos_bias_batched(r: &DeviceBuf, rel_proj: &DeviceBuf, rel_bias: &DeviceBuf, pos: &DeviceBuf, n_head: i32, d_rel: i32, rel_extent: i32, m: i32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_relpos_bias_batched(r.ptr as *const f32, rel_proj.ptr as *const f32, rel_bias.ptr as *mut f32, pos.ptr as *const i32, n_head, d_rel, rel_extent, m, std::ptr::null_mut()) };
if rc != 0 { return Err("relpos_bias_batched 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_kv_store_f16: K/V rounded to FP16 (RNE) into a u16 cache (strata FP16 KV).
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn kv_store_f16(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_f16(k_in.ptr as *const f32, v_in.ptr as *const f32, k_cache.ptr as *mut u16, v_cache.ptr as *mut u16, pos, n_kv, hd, seq, rms_eps, std::ptr::null_mut()) };
if rc != 0 { return Err("kv_store_f16 launch failed".into()); }
Ok(())
}
/// Batched KV store (M=B): k_in/v_in [M,n_kv,hd], each token m writes FP16 cache
/// position pos[m]. Fills all B KV positions before batched flash reads them.
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn kv_store_f16_batched(k_in: &DeviceBuf, v_in: &DeviceBuf, k_cache: &DeviceBuf, v_cache: &DeviceBuf, pos: &DeviceBuf, n_kv: i32, hd: i32, seq: i32, rms_eps: f32, m: i32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_kv_store_f16_batched(k_in.ptr as *const f32, v_in.ptr as *const f32, k_cache.ptr as *mut u16, v_cache.ptr as *mut u16, pos.ptr as *const i32, n_kv, hd, seq, rms_eps, m, std::ptr::null_mut()) };
if rc != 0 { return Err("kv_store_f16_batched 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(())
}
/// Batched controller input pack (M=B): cur/msg [M,D] -> packed [M,2D] bf16.
#[cfg(feature = "hip")]
pub fn ctrl_pack_batched(cur: &DeviceBuf, msg: &DeviceBuf, packed: &DeviceBuf, d: i32, eps: f32, m: i32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_ctrl_pack_batched(cur.ptr as *const f32, msg.ptr as *const f32, packed.ptr as *mut u16, d, eps, m, std::ptr::null_mut()) };
if rc != 0 { return Err("ctrl_pack_batched 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<f32> {
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<f32> = (0..rows * d).map(|i| ((i % 37) as f32 - 18.0) * 0.1).collect();
let w: Vec<f32> = (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 { let u = v.to_bits(); ((u + 0x7FFFu32 + ((u >> 16) & 1)) >> 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<u16> = (0..vocab * d).map(|i| f32_to_bf16(((i % 53) as f32 - 26.0) * 0.07)).collect();
let tokens: Vec<i32> = 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<u16> = (0..m * k).map(|i| f32_to_bf16(((i % 41) as f32 - 20.0) * 0.05)).collect();
let w: Vec<u16> = (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}");
}
}
#[test]
#[ignore]
fn gemm_bf16_wmma_parity() {
// P1 b6: BF16 WMMA vs serial-K CPU oracle. Accumulation order differs =>
// numeric tolerance on the GLOBAL signal scale (per-entry rel explodes on
// near-zero outputs); greedy-vs-reference is the blocking gate downstream.
// (17,130,64) exercises partial M and N tiles.
for &(m, n, k) in &[(20usize, 128usize, 128usize), (256, 256, 256), (17, 130, 64)] {
let x: Vec<u16> = (0..m * k).map(|i| f32_to_bf16(((i % 41) as f32 - 20.0) * 0.05)).collect();
let w: Vec<u16> = (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_wmma(&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 scale = want.iter().fold(0f32, |a, v| a.max(v.abs())).max(1e-6);
let mut max_rel = 0f32;
for (g, wnt) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - wnt).abs() / scale); }
eprintln!("gemm_bf16_wmma m={m} n={n} k={k} max_rel_err={max_rel:.3e}");
assert!(max_rel < 3e-3, "gemm_bf16_wmma 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<f32> {
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::<f32>() * 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<f32> = (0..n_head * hd).map(|i| ((i % 23) as f32 - 11.0) * 0.04).collect();
let k: Vec<f32> = (0..n_kv * seq * hd).map(|i| ((i % 31) as f32 - 15.0) * 0.03).collect();
let v: Vec<f32> = (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<f32> {
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<f32> = 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::<f32>();
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<f32> = (0..n_head * hd).map(|i| ((i % 23) as f32 - 11.0) * 0.04).collect();
let k: Vec<f32> = (0..n_kv * seq * hd).map(|i| ((i % 31) as f32 - 15.0) * 0.03).collect();
let v: Vec<f32> = (0..n_kv * seq * hd).map(|i| ((i % 17) as f32 - 8.0) * 0.05).collect();
let rb: Vec<f32> = (0..n_head * max_rel).map(|i| ((i % 13) as f32 - 6.0) * 0.02).collect();
let sink: Vec<f32> = (0..n_head).map(|i| (i as f32) * 0.3 - 1.0).collect();
let gate: Vec<f32> = (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<i32>, Vec<f32>) {
let mut ids = vec![0i32; m * k_top];
let mut weights = vec![0f32; m * k_top];
for mi in 0..m {
let prob: Vec<f32> = (0..n_experts).map(|e| 1.0 / (1.0 + (-logits[mi * n_experts + e]).exp())).collect();
let mut score: Vec<f32> = (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<i32> {
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<f32> = (0..m * n_experts).map(|i| ((i % 47) as f32 - 23.0) * 0.2).collect();
let bias: Vec<f32> = (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<f32> = (0..n).map(|i| (i as f32) * 0.01).collect();
let b: Vec<f32> = (0..n).map(|i| -(i as f32) * 0.003).collect();
let want: Vec<f32> = 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<u8> = (0..n * (k / 2)).map(|i| (i % 256) as u8).collect();
let scales: Vec<u8> = (0..n * (k / 16)).map(|i| ((i * 7 + 3) % 251) as u8).collect();
let x: Vec<f32> = (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}");
}
}
/// Device-routed (indirect) NVFP4 f16 GEMV must be BIT-EXACT vs the direct
/// kernel on the same expert slice: same shared device body, only the weight
/// base address is selected on device from ids[slot]. Builds a synthetic
/// per-layer arena (E experts) and routes several slots through it. This is
/// the foundation for graph-capturable MoE dispatch (no host ids round-trip).
#[test]
#[ignore]
fn nvfp4_gemv_f16_indirect_parity() {
let (n, k, e) = (16usize, 128usize, 4usize);
let w_stride = n * (k / 2);
let sc_stride = n * (k / 16);
let packed: Vec<u8> = (0..e * w_stride).map(|i| (i % 256) as u8).collect();
let scales: Vec<u8> = (0..e * sc_stride).map(|i| ((i * 7 + 3) % 251) as u8).collect();
let outer: Vec<f32> = (0..e).map(|i| 0.3 + 0.1 * i as f32).collect();
let x_f32: Vec<f32> = (0..k).map(|i| (i % 29) as f32 - 14.0).collect(); // integers exact in f16
let ap = DeviceBuf::alloc(packed.len()).unwrap(); ap.h2d_bytes(&packed).unwrap();
let asc = DeviceBuf::alloc(scales.len()).unwrap(); asc.h2d_bytes(&scales).unwrap();
let ao = DeviceBuf::alloc(e * 4).unwrap(); ao.h2d(&outer).unwrap();
let xf = DeviceBuf::alloc(k * 4).unwrap(); xf.h2d(&x_f32).unwrap();
let xh = DeviceBuf::alloc(k * 2).unwrap(); cast_f32_f16(&xf, &xh, k).unwrap();
let ids_vec: Vec<i32> = vec![2, 0, 3, 1];
let ids_bytes: Vec<u8> = ids_vec.iter().flat_map(|x| x.to_le_bytes()).collect();
let dids = DeviceBuf::alloc(ids_bytes.len()).unwrap(); dids.h2d_bytes(&ids_bytes).unwrap();
let yi = DeviceBuf::alloc(n * 4).unwrap();
let yd = DeviceBuf::alloc(n * 4).unwrap();
for slot in 0..ids_vec.len() {
nvfp4_gemv_f16_indirect(&ap, &asc, &ao, &dids, slot as i32, &xh, &yi, n as i32, k as i32, w_stride as i64, sc_stride as i64, 0).unwrap();
let id = ids_vec[slot] as usize;
let sp = DeviceBuf::alloc(w_stride).unwrap(); sp.h2d_bytes(&packed[id * w_stride..(id + 1) * w_stride]).unwrap();
let ss = DeviceBuf::alloc(sc_stride).unwrap(); ss.h2d_bytes(&scales[id * sc_stride..(id + 1) * sc_stride]).unwrap();
nvfp4_gemv_f16(&sp, &ss, outer[id], &xh, &yd, n as i32, k as i32).unwrap();
let mut gi = vec![0f32; n]; yi.d2h(&mut gi).unwrap();
let mut gd = vec![0f32; n]; yd.d2h(&mut gd).unwrap();
assert_eq!(gi, gd, "indirect must equal direct bit-exact (slot {slot}, expert {id})");
}
eprintln!("nvfp4_gemv_f16_indirect: bit-exact vs direct over {} routed slots", ids_vec.len());
}
/// Batched (M>1) NVFP4 f16 GEMM parity vs a CPU dequant oracle over [M,N].
/// M=37 exercises the MT=16 tiling (2 full tiles + a 5-token remainder).
/// Integer activations are exact in f16, so the oracle uses them directly.
#[test]
#[ignore]
fn nvfp4_gemv_f16_mt_parity() {
let (m, n, k) = (37usize, 16usize, 128usize);
let outer = 0.5f32;
let packed: Vec<u8> = (0..n * (k / 2)).map(|i| (i % 256) as u8).collect();
let scales: Vec<u8> = (0..n * (k / 16)).map(|i| ((i * 7 + 3) % 251) as u8).collect();
let xf: Vec<f32> = (0..m * k).map(|i| (i % 29) as f32 - 14.0).collect();
let dp = DeviceBuf::alloc(packed.len()).unwrap(); dp.h2d_bytes(&packed).unwrap();
let ds = DeviceBuf::alloc(scales.len()).unwrap(); ds.h2d_bytes(&scales).unwrap();
let dxf = DeviceBuf::alloc(m * k * 4).unwrap(); dxf.h2d(&xf).unwrap();
let dxh = DeviceBuf::alloc(m * k * 2).unwrap(); cast_f32_f16(&dxf, &dxh, m * k).unwrap();
let dy = DeviceBuf::alloc(m * n * 4).unwrap();
nvfp4_gemv_f16_mt(&dp, &ds, outer, &dxh, &dy, m as i32, n as i32, k as i32).unwrap();
let mut got = vec![0f32; m * n]; dy.d2h(&mut got).unwrap();
let mut want = vec![0f32; m * n];
for mi in 0..m {
for ni in 0..n {
let mut acc = 0f32;
for b in 0..k / 16 {
let sc = e4m3(scales[ni * (k / 16) + b]) * outer;
let mut d = 0f32;
for j in 0..8 {
let byte = packed[ni * (k / 2) + b * 8 + j];
d += xf[mi * k + b * 16 + j * 2] * e2m1(byte & 15) + xf[mi * k + b * 16 + j * 2 + 1] * e2m1(byte >> 4);
}
acc = d.mul_add(sc, acc);
}
want[mi * n + ni] = acc;
}
}
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_f16_mt m={m} n={n} k={k} max_rel_err={max_rel:.3e}");
assert!(max_rel < 2e-3, "batched NVFP4 f16 GEMM 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<f32> = (0..2 * inter).map(|i| ((i % 61) as f32 - 30.0) * 0.3).collect();
let want: Vec<f32> = (0..inter).map(|j| {
let g = gu[2 * j];
let u = gu[2 * j + 1];
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<f32> = (0..top_k * hidden).map(|i| ((i % 43) as f32 - 21.0) * 0.02).collect();
let tk_w: Vec<f32> = (0..top_k).map(|e| 0.5 + (e as f32) * 0.1).collect();
let want: Vec<f32> = (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}");
}
/// Grouped-MoE bucket CSR build parity vs a CPU oracle. Scatter order within
/// a bucket is non-deterministic (atomicAdd), so we verify INVARIANTS: CSR
/// offsets == CPU prefix-sum of counts, slotk_to_bidx is a consistent
/// bijection (bucket_tok[s2b[i]] == i/top_k), and each expert's bucket holds
/// exactly the multiset of tokens routed to it.
#[test]
#[ignore]
fn moe_buckets_parity_vs_cpu() {
let (b, top_k, n_exp) = (37usize, 8usize, 128usize);
let total = b * top_k;
let ids: Vec<i32> = (0..total).map(|i| ((i * 7 + (i / top_k) * 13) % n_exp) as i32).collect();
let ids_bytes: Vec<u8> = ids.iter().flat_map(|x| x.to_le_bytes()).collect();
let dids = DeviceBuf::alloc(total * 4).unwrap(); dids.h2d_bytes(&ids_bytes).unwrap();
let dcnt = DeviceBuf::alloc(129 * 4).unwrap(); dcnt.h2d_bytes(&vec![0u8; 129 * 4]).unwrap();
let doff = DeviceBuf::alloc(129 * 4).unwrap();
let dcur = DeviceBuf::alloc(128 * 4).unwrap();
let dbtk = DeviceBuf::alloc(total * 4).unwrap();
let ds2b = DeviceBuf::alloc(total * 4).unwrap();
moe_count_buckets(&dids, &dcnt, total as i32).unwrap();
moe_prefix_buckets(&dcnt, &doff, &dcur).unwrap();
moe_scatter_buckets(&dids, &dcur, &dbtk, &ds2b, total as i32, top_k as i32).unwrap();
let rd = |buf: &DeviceBuf, n: usize| -> Vec<i32> {
let mut bytes = vec![0u8; n * 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()
};
let off = rd(&doff, 129);
let btk = rd(&dbtk, total);
let s2b = rd(&ds2b, total);
let mut cnt = vec![0i32; 128];
for &e in &ids { cnt[e as usize] += 1; }
let mut coff = vec![0i32; 129];
let mut acc = 0i32;
for e in 0..128 { coff[e] = acc; acc += cnt[e]; }
coff[128] = acc;
assert_eq!(off, coff, "CSR offsets must match CPU prefix-sum");
assert_eq!(off[128], total as i32);
for i in 0..total {
assert_eq!(btk[s2b[i] as usize], (i / top_k) as i32, "slotk_to_bidx bijection broken at {i}");
}
for e in 0..128 {
let mut got: Vec<i32> = btk[off[e] as usize..off[e + 1] as usize].to_vec(); got.sort();
let mut want: Vec<i32> = (0..total).filter(|&i| ids[i] == e as i32).map(|i| (i / top_k) as i32).collect(); want.sort();
assert_eq!(got, want, "expert {e} bucket token multiset mismatch");
}
eprintln!("moe_buckets B={b} top_k={top_k}: CSR offsets + bijection + per-expert multiset exact");
}
/// Grouped MoE expert GEMM parity vs a CPU dequant oracle per (token,expert)
/// pair. Builds a synthetic 4-expert arena + buckets, runs the grouped GEMM
/// (one launch over all experts), and checks Y[bucket_pos] == dequant(W[e]) @
/// X[token] for every pair. Integer activations are exact in f16.
#[test]
#[ignore]
fn nvfp4_grouped_gemv_f16_parity() {
let (b, top_k, n_exp, n, k) = (20usize, 8usize, 4usize, 16usize, 128usize);
let total = b * top_k;
let w_stride = n * (k / 2);
let sc_stride = n * (k / 16);
let packed: Vec<u8> = (0..n_exp * w_stride).map(|i| (i % 256) as u8).collect();
let scales: Vec<u8> = (0..n_exp * sc_stride).map(|i| ((i * 7 + 3) % 251) as u8).collect();
let outer: Vec<f32> = (0..n_exp).map(|i| 0.3 + 0.1 * i as f32).collect();
let ids: Vec<i32> = (0..total).map(|i| ((i * 7 + (i / top_k) * 13) % n_exp) as i32).collect();
let xf: Vec<f32> = (0..b * k).map(|i| (i % 29) as f32 - 14.0).collect();
let ap = DeviceBuf::alloc(packed.len()).unwrap(); ap.h2d_bytes(&packed).unwrap();
let asc = DeviceBuf::alloc(scales.len()).unwrap(); asc.h2d_bytes(&scales).unwrap();
let ao = DeviceBuf::alloc(n_exp * 4).unwrap(); ao.h2d(&outer).unwrap();
let dxf = DeviceBuf::alloc(b * k * 4).unwrap(); dxf.h2d(&xf).unwrap();
let dxh = DeviceBuf::alloc(b * k * 2).unwrap(); cast_f32_f16(&dxf, &dxh, b * k).unwrap();
let ids_bytes: Vec<u8> = ids.iter().flat_map(|x| x.to_le_bytes()).collect();
let dids = DeviceBuf::alloc(total * 4).unwrap(); dids.h2d_bytes(&ids_bytes).unwrap();
let dcnt = DeviceBuf::alloc(129 * 4).unwrap(); dcnt.h2d_bytes(&vec![0u8; 129 * 4]).unwrap();
let doff = DeviceBuf::alloc(129 * 4).unwrap();
let dcur = DeviceBuf::alloc(128 * 4).unwrap();
let dbtk = DeviceBuf::alloc(total * 4).unwrap();
let ds2b = DeviceBuf::alloc(total * 4).unwrap();
moe_count_buckets(&dids, &dcnt, total as i32).unwrap();
moe_prefix_buckets(&dcnt, &doff, &dcur).unwrap();
moe_scatter_buckets(&dids, &dcur, &dbtk, &ds2b, total as i32, top_k as i32).unwrap();
let dy = DeviceBuf::alloc(total * n * 4).unwrap();
nvfp4_grouped_gemv_f16(&ap, &asc, &ao, &doff, Some(&dbtk), &dxh, &dy, n as i32, k as i32, n_exp as i32, w_stride as i64, sc_stride as i64).unwrap();
let mut got = vec![0f32; total * n]; dy.d2h(&mut got).unwrap();
let mut s2b_b = vec![0u8; total * 4]; ds2b.d2h_bytes(&mut s2b_b).unwrap();
let s2b: Vec<i32> = s2b_b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
let mut max_rel = 0f32;
for i in 0..total {
let tok = i / top_k;
let e = ids[i] as usize;
let bp = s2b[i] as usize;
for ni in 0..n {
let mut acc = 0f32;
for bb in 0..k / 16 {
let sc = e4m3(scales[e * sc_stride + ni * (k / 16) + bb]) * outer[e];
let mut d = 0f32;
for j in 0..8 {
let byte = packed[e * w_stride + ni * (k / 2) + bb * 8 + j];
d += xf[tok * k + bb * 16 + j * 2] * e2m1(byte & 15) + xf[tok * k + bb * 16 + j * 2 + 1] * e2m1(byte >> 4);
}
acc = d.mul_add(sc, acc);
}
let g = got[bp * n + ni];
max_rel = max_rel.max((g - acc).abs() / acc.abs().max(1e-3));
}
}
eprintln!("nvfp4_grouped_gemv_f16 B={b} experts={n_exp} pairs={total} max_rel_err={max_rel:.3e}");
assert!(max_rel < 2e-3, "grouped NVFP4 GEMM parity failed: {max_rel}");
}
/// FP16 WMMA grouped GEMM parity vs the same CPU oracle. N=128 exercises all 8
/// wave N-tiles; K=128 (multiple of BK=64). WMMA changes the f32 accumulation
/// order and prescales the dequantized weight in f16 (e4m3*0.0625 exact, E2M1*scale
/// rounded) => P1 numeric tolerance (~1e-3), not bit-exact. Greedy-vs-reference is
/// the blocking production gate (ld forward_batch_parity / gw serve_gen).
#[test]
#[ignore]
fn nvfp4_grouped_gemm_wmma_parity() {
let (b, top_k, n_exp, n, k) = (20usize, 8usize, 4usize, 128usize, 128usize);
let total = b * top_k;
let w_stride = n * (k / 2);
let sc_stride = n * (k / 16);
let packed: Vec<u8> = (0..n_exp * w_stride).map(|i| (i % 256) as u8).collect();
let scales: Vec<u8> = (0..n_exp * sc_stride).map(|i| ((i * 7 + 3) % 251) as u8).collect();
let outer: Vec<f32> = (0..n_exp).map(|i| 0.3 + 0.1 * i as f32).collect();
let ids: Vec<i32> = (0..total).map(|i| ((i * 7 + (i / top_k) * 13) % n_exp) as i32).collect();
let xf: Vec<f32> = (0..b * k).map(|i| (i % 29) as f32 - 14.0).collect();
let ap = DeviceBuf::alloc(packed.len()).unwrap(); ap.h2d_bytes(&packed).unwrap();
let asc = DeviceBuf::alloc(scales.len()).unwrap(); asc.h2d_bytes(&scales).unwrap();
let ao = DeviceBuf::alloc(n_exp * 4).unwrap(); ao.h2d(&outer).unwrap();
let dxf = DeviceBuf::alloc(b * k * 4).unwrap(); dxf.h2d(&xf).unwrap();
let dxh = DeviceBuf::alloc(b * k * 2).unwrap(); cast_f32_f16(&dxf, &dxh, b * k).unwrap();
let ids_bytes: Vec<u8> = ids.iter().flat_map(|x| x.to_le_bytes()).collect();
let dids = DeviceBuf::alloc(total * 4).unwrap(); dids.h2d_bytes(&ids_bytes).unwrap();
let dcnt = DeviceBuf::alloc(129 * 4).unwrap(); dcnt.h2d_bytes(&vec![0u8; 129 * 4]).unwrap();
let doff = DeviceBuf::alloc(129 * 4).unwrap();
let dcur = DeviceBuf::alloc(128 * 4).unwrap();
let dbtk = DeviceBuf::alloc(total * 4).unwrap();
let ds2b = DeviceBuf::alloc(total * 4).unwrap();
moe_count_buckets(&dids, &dcnt, total as i32).unwrap();
moe_prefix_buckets(&dcnt, &doff, &dcur).unwrap();
moe_scatter_buckets(&dids, &dcur, &dbtk, &ds2b, total as i32, top_k as i32).unwrap();
let dy = DeviceBuf::alloc(total * n * 4).unwrap();
nvfp4_grouped_gemm_wmma(&ap, &asc, &ao, &doff, Some(&dbtk), &dxh, &dy, n as i32, k as i32, n_exp as i32, w_stride as i64, sc_stride as i64).unwrap();
let mut got = vec![0f32; total * n]; dy.d2h(&mut got).unwrap();
let mut s2b_b = vec![0u8; total * 4]; ds2b.d2h_bytes(&mut s2b_b).unwrap();
let s2b: Vec<i32> = s2b_b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
let mut max_rel = 0f32;
for i in 0..total {
let tok = i / top_k;
let e = ids[i] as usize;
let bp = s2b[i] as usize;
for ni in 0..n {
let mut acc = 0f32;
for bb in 0..k / 16 {
let sc = e4m3(scales[e * sc_stride + ni * (k / 16) + bb]) * outer[e];
let mut d = 0f32;
for j in 0..8 {
let byte = packed[e * w_stride + ni * (k / 2) + bb * 8 + j];
d += xf[tok * k + bb * 16 + j * 2] * e2m1(byte & 15) + xf[tok * k + bb * 16 + j * 2 + 1] * e2m1(byte >> 4);
}
acc = d.mul_add(sc, acc);
}
let g = got[bp * n + ni];
max_rel = max_rel.max((g - acc).abs() / acc.abs().max(1e-3));
}
}
eprintln!("nvfp4_grouped_gemm_wmma B={b} experts={n_exp} pairs={total} N={n} K={k} max_rel_err={max_rel:.3e}");
assert!(max_rel < 5e-3, "WMMA grouped NVFP4 GEMM parity failed: {max_rel}");
}
/// reduce_buckets_masked parity: scatter-back from bucket order + weighted
/// reduce per token vs a CPU oracle using the same slotk_to_bidx map.
#[test]
#[ignore]
fn moe_reduce_buckets_masked_parity() {
let (b, top_k, d) = (20usize, 8usize, 64usize);
let total = b * top_k;
let ids: Vec<i32> = (0..total).map(|i| ((i * 7 + (i / top_k) * 13) % 128) as i32).collect();
let ids_bytes: Vec<u8> = ids.iter().flat_map(|x| x.to_le_bytes()).collect();
let dids = DeviceBuf::alloc(total * 4).unwrap(); dids.h2d_bytes(&ids_bytes).unwrap();
let dcnt = DeviceBuf::alloc(129 * 4).unwrap(); dcnt.h2d_bytes(&vec![0u8; 129 * 4]).unwrap();
let doff = DeviceBuf::alloc(129 * 4).unwrap();
let dcur = DeviceBuf::alloc(128 * 4).unwrap();
let dbtk = DeviceBuf::alloc(total * 4).unwrap();
let ds2b = DeviceBuf::alloc(total * 4).unwrap();
moe_count_buckets(&dids, &dcnt, total as i32).unwrap();
moe_prefix_buckets(&dcnt, &doff, &dcur).unwrap();
moe_scatter_buckets(&dids, &dcur, &dbtk, &ds2b, total as i32, top_k as i32).unwrap();
let by: Vec<f32> = (0..total * d).map(|i| ((i % 43) as f32 - 21.0) * 0.02).collect();
let w: Vec<f32> = (0..total).map(|i| 0.5 + (i % 7) as f32 * 0.1).collect();
let dby = DeviceBuf::alloc(total * d * 4).unwrap(); dby.h2d(&by).unwrap();
let dw = DeviceBuf::alloc(total * 4).unwrap(); dw.h2d(&w).unwrap();
let dout = DeviceBuf::alloc(b * d * 4).unwrap();
moe_reduce_buckets_masked(&dby, &ds2b, &dw, &dout, b as i32, top_k as i32, d as i32).unwrap();
let mut got = vec![0f32; b * d]; dout.d2h(&mut got).unwrap();
let mut s2b_b = vec![0u8; total * 4]; ds2b.d2h_bytes(&mut s2b_b).unwrap();
let s2b: Vec<i32> = s2b_b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
let mut want = vec![0f32; b * d];
for bb in 0..b {
for dd in 0..d {
let mut acc = 0f32;
for kk in 0..top_k {
let pair = bb * top_k + kk;
acc += w[pair] * by[s2b[pair] as usize * d + dd];
}
want[bb * d + dd] = acc;
}
}
let mut max_rel = 0f32;
for (g, wt) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - wt).abs() / wt.abs().max(1e-3)); }
eprintln!("moe_reduce_buckets_masked B={b} top_k={top_k} D={d} max_rel_err={max_rel:.3e}");
assert!(max_rel < 1e-4, "reduce_buckets_masked parity failed: {max_rel}");
}
/// prefill_par (parallel causal ShortConv, tile 16) must equal B sequential
/// decode steps bit-for-bit (same bf16 history semantics), and update_hist must
/// equal the decode's final history. B=37 exercises a partial last tile.
#[test]
#[ignore]
fn shortconv4_prefill_par_parity() {
let (b, c) = (37usize, 64usize);
let inx: Vec<f32> = (0..b * c).map(|i| ((i % 53) as f32 - 26.0) * 0.03).collect();
let sw: Vec<f32> = (0..c * 4).map(|i| 0.1 + (i % 7) as f32 * 0.05).collect();
let hist0: Vec<f32> = (0..3 * c).map(|i| bf16_to_f32(f32_to_bf16(((i % 17) as f32 - 8.0) * 0.1))).collect();
let din = DeviceBuf::alloc(b * c * 4).unwrap(); din.h2d(&inx).unwrap();
let dsw = DeviceBuf::alloc(c * 4 * 4).unwrap(); dsw.h2d(&sw).unwrap();
let dhist_p = DeviceBuf::alloc(3 * c * 4).unwrap(); dhist_p.h2d(&hist0).unwrap();
let dout_p = DeviceBuf::alloc(b * c * 4).unwrap();
shortconv4_prefill_par(&din, &dsw, None, &dhist_p, &dout_p, b as i32, c as i32, 0).unwrap();
let mut got_p = vec![0f32; b * c]; dout_p.d2h(&mut got_p).unwrap();
let dhist_s = DeviceBuf::alloc(3 * c * 4).unwrap(); dhist_s.h2d(&hist0).unwrap();
let dslot = DeviceBuf::alloc(4).unwrap(); dslot.h2d_bytes(&0i32.to_le_bytes()).unwrap();
let dcur = DeviceBuf::alloc(c * 4).unwrap();
let dout1 = DeviceBuf::alloc(c * 4).unwrap();
let mut got_s = vec![0f32; b * c];
for t in 0..b {
dcur.h2d(&inx[t * c..(t + 1) * c]).unwrap();
shortconv4_decode(&dcur, &dsw, &dhist_s, &dout1, &dslot, 1, c as i32).unwrap();
let mut o = vec![0f32; c]; dout1.d2h(&mut o).unwrap();
got_s[t * c..(t + 1) * c].copy_from_slice(&o);
}
let mut max_rel = 0f32;
for (g, w) in got_p.iter().zip(got_s.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); }
shortconv4_update_hist(&din, &dhist_p, b as i32, c as i32).unwrap();
let mut hp = vec![0f32; 3 * c]; dhist_p.d2h(&mut hp).unwrap();
let mut hs = vec![0f32; 3 * c]; dhist_s.d2h(&mut hs).unwrap();
let mut hmax = 0f32;
for (a, bb) in hp.iter().zip(hs.iter()) { hmax = hmax.max((a - bb).abs()); }
eprintln!("shortconv4_prefill_par B={b} C={c} out_max_rel={max_rel:.3e} hist_max_abs={hmax:.3e}");
assert!(max_rel < 1e-5, "prefill_par output parity failed: {max_rel}");
assert!(hmax < 1e-6, "update_hist parity failed: {hmax}");
}
/// Batched causal flash prefill (M=B) must equal B sequential decode flash f16
/// calls (each cur_pos=base+m), same FP16 KV + rel_bias + sink + gate. win=16
/// exercises windowing; base=10 so early tokens are unwindowed, later windowed.
#[test]
#[ignore]
fn flash_swa_gqa_prefill_f16_parity() {
let (n_head, n_kv, hd, seq, b) = (24usize, 8usize, 128usize, 15usize, 8usize);
let (base, win, max_rel) = (5i32, 1024i32, 1024usize);
let scale = 1.0f32 / (hd as f32).sqrt();
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 vf: Vec<f32> = (0..n_kv * seq * hd).map(|i| ((i % 37) as f32 - 18.0) * 0.02).collect();
let dkf = DeviceBuf::alloc(kf.len() * 4).unwrap(); dkf.h2d(&kf).unwrap();
let dk = DeviceBuf::alloc(kf.len() * 2).unwrap(); cast_f32_f16(&dkf, &dk, kf.len()).unwrap();
let dvf = DeviceBuf::alloc(vf.len() * 4).unwrap(); dvf.h2d(&vf).unwrap();
let dv = DeviceBuf::alloc(vf.len() * 2).unwrap(); cast_f32_f16(&dvf, &dv, vf.len()).unwrap();
let qf: Vec<f32> = (0..b * n_head * hd).map(|i| ((i % 29) as f32 - 14.0) * 0.03).collect();
let rb: Vec<f32> = (0..b * n_head * max_rel).map(|i| ((i % 13) as f32 - 6.0) * 0.01).collect();
let sk: Vec<f32> = (0..b * n_head).map(|i| -2.0 + (i % 5) as f32 * 0.1).collect();
let gt: Vec<f32> = (0..b * n_head * hd).map(|i| ((i % 17) as f32 - 8.0) * 0.05).collect();
let dq = DeviceBuf::alloc(qf.len() * 4).unwrap(); dq.h2d(&qf).unwrap();
let drb = DeviceBuf::alloc(rb.len() * 4).unwrap(); drb.h2d(&rb).unwrap();
let dsk = DeviceBuf::alloc(sk.len() * 4).unwrap(); dsk.h2d(&sk).unwrap();
let dgt = DeviceBuf::alloc(gt.len() * 4).unwrap(); dgt.h2d(&gt).unwrap();
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 dout_p = DeviceBuf::alloc(b * n_head * hd * 4).unwrap();
flash_swa_gqa_prefill_f16(&dq, &dk, &dv, &dout_p, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, win, &dpos, max_pos, Some(&drb), max_rel as i32, Some(&dsk), Some(&dgt), b as i32).unwrap();
let mut got_p = vec![0f32; b * n_head * hd]; dout_p.d2h(&mut got_p).unwrap();
let dq1 = DeviceBuf::alloc(n_head * hd * 4).unwrap();
let drb1 = DeviceBuf::alloc(n_head * max_rel * 4).unwrap();
let dsk1 = DeviceBuf::alloc(n_head * 4).unwrap();
let dgt1 = DeviceBuf::alloc(n_head * hd * 4).unwrap();
let dout1 = DeviceBuf::alloc(n_head * hd * 4).unwrap();
let mut got_s = vec![0f32; b * n_head * hd];
for m in 0..b {
dq1.h2d(&qf[m * n_head * hd..(m + 1) * n_head * hd]).unwrap();
drb1.h2d(&rb[m * n_head * max_rel..(m + 1) * n_head * max_rel]).unwrap();
dsk1.h2d(&sk[m * n_head..(m + 1) * n_head]).unwrap();
dgt1.h2d(&gt[m * n_head * hd..(m + 1) * n_head * hd]).unwrap();
flash_swa_gqa_decode_f16(&dq1, &dk, &dv, &dout1, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, win, pos[m], Some(&drb1), max_rel as i32, Some(&dsk1), Some(&dgt1)).unwrap();
let mut o = vec![0f32; n_head * hd]; dout1.d2h(&mut o).unwrap();
got_s[m * n_head * hd..(m + 1) * n_head * hd].copy_from_slice(&o);
}
let mut max_rel_err = 0f32;
for (g, w) in got_p.iter().zip(got_s.iter()) { max_rel_err = max_rel_err.max((g - w).abs() / w.abs().max(1e-3)); }
eprintln!("flash_swa_gqa_prefill_f16 B={b} n_head={n_head} win={win} max_rel_err={max_rel_err:.3e}");
assert!(max_rel_err < 1e-5, "flash prefill parity failed: {max_rel_err}");
}
/// Batched kv_store_f16 (M=B) must produce byte-identical FP16 caches to B
/// sequential kv_store_f16 calls at pos[m]=base+m.
#[test]
#[ignore]
fn kv_store_f16_batched_parity() {
let (n_kv, hd, seq, b, base) = (2usize, 128usize, 64usize, 20usize, 10i32);
let eps = 1e-6f32;
let ki: Vec<f32> = (0..b * n_kv * hd).map(|i| ((i % 41) as f32 - 20.0) * 0.02).collect();
let vi: Vec<f32> = (0..b * n_kv * hd).map(|i| ((i % 37) as f32 - 18.0) * 0.02).collect();
let dki = DeviceBuf::alloc(ki.len() * 4).unwrap(); dki.h2d(&ki).unwrap();
let dvi = DeviceBuf::alloc(vi.len() * 4).unwrap(); dvi.h2d(&vi).unwrap();
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 cache_bytes = n_kv * seq * hd * 2;
let zeros = vec![0u8; cache_bytes];
let dk_b = DeviceBuf::alloc(cache_bytes).unwrap(); dk_b.h2d_bytes(&zeros).unwrap();
let dv_b = DeviceBuf::alloc(cache_bytes).unwrap(); dv_b.h2d_bytes(&zeros).unwrap();
kv_store_f16_batched(&dki, &dvi, &dk_b, &dv_b, &dpos, n_kv as i32, hd as i32, seq as i32, eps, b as i32).unwrap();
let dk_s = DeviceBuf::alloc(cache_bytes).unwrap(); dk_s.h2d_bytes(&zeros).unwrap();
let dv_s = DeviceBuf::alloc(cache_bytes).unwrap(); dv_s.h2d_bytes(&zeros).unwrap();
let dk1 = DeviceBuf::alloc(n_kv * hd * 4).unwrap();
let dv1 = DeviceBuf::alloc(n_kv * hd * 4).unwrap();
for m in 0..b {
dk1.h2d(&ki[m * n_kv * hd..(m + 1) * n_kv * hd]).unwrap();
dv1.h2d(&vi[m * n_kv * hd..(m + 1) * n_kv * hd]).unwrap();
kv_store_f16(&dk1, &dv1, &dk_s, &dv_s, pos[m], n_kv as i32, hd as i32, seq as i32, eps).unwrap();
}
let mut kb = vec![0u8; cache_bytes]; dk_b.d2h_bytes(&mut kb).unwrap();
let mut vb = vec![0u8; cache_bytes]; dv_b.d2h_bytes(&mut vb).unwrap();
let mut ks = vec![0u8; cache_bytes]; dk_s.d2h_bytes(&mut ks).unwrap();
let mut vs = vec![0u8; cache_bytes]; dv_s.d2h_bytes(&mut vs).unwrap();
assert_eq!(kb, ks, "batched kv_store K cache must be byte-identical");
assert_eq!(vb, vs, "batched kv_store V cache must be byte-identical");
eprintln!("kv_store_f16_batched B={b} n_kv={n_kv} hd={hd}: K/V caches byte-identical");
}
/// Batched SiTU (M rows) must be byte-identical to M sequential situ_f16 calls.
#[test]
#[ignore]
fn situ_f16_batched_parity() {
let (m, inter) = (20usize, 64usize);
let (beta, lb) = (4.0f32, 25.0f32);
let gu: Vec<f32> = (0..m * 2 * inter).map(|i| ((i % 61) as f32 - 30.0) * 0.3).collect();
let dgu = DeviceBuf::alloc(gu.len() * 4).unwrap(); dgu.h2d(&gu).unwrap();
let da_b = DeviceBuf::alloc(m * inter * 2).unwrap();
situ_f16_batched(&dgu, &da_b, inter as i32, beta, lb, m as i32).unwrap();
let mut ab = vec![0u8; m * inter * 2]; da_b.d2h_bytes(&mut ab).unwrap();
let dgu1 = DeviceBuf::alloc(2 * inter * 4).unwrap();
let da1 = DeviceBuf::alloc(inter * 2).unwrap();
for r in 0..m {
dgu1.h2d(&gu[r * 2 * inter..(r + 1) * 2 * inter]).unwrap();
situ_f16(&dgu1, &da1, inter as i32, beta, lb).unwrap();
let mut o = vec![0u8; inter * 2]; da1.d2h_bytes(&mut o).unwrap();
assert_eq!(&ab[r * inter * 2..(r + 1) * inter * 2], &o[..], "situ batched row {r} must be byte-identical");
}
eprintln!("situ_f16_batched M={m} inter={inter}: byte-identical to sequential");
}
/// Grouped MXFP8 expert GEMM parity vs a CPU dequant oracle per (token,expert)
/// pair. UE8M0 scales kept in a realistic exponent range [120,135] (2^-7..2^8)
/// to avoid f32 overflow. Integer activations exact in f16.
#[test]
#[ignore]
fn mxfp8_grouped_gemv_f16_parity() {
let (b, top_k, n_exp, n, k) = (20usize, 8usize, 4usize, 16usize, 128usize);
let total = b * top_k;
let w_stride = n * k;
let sc_stride = n * (k / 32);
let weights: Vec<u8> = (0..n_exp * w_stride).map(|i| (i % 256) as u8).collect();
let scales: Vec<u8> = (0..n_exp * sc_stride).map(|i| (120 + (i * 7 + 3) % 16) as u8).collect();
let ids: Vec<i32> = (0..total).map(|i| ((i * 7 + (i / top_k) * 13) % n_exp) as i32).collect();
let xf: Vec<f32> = (0..b * k).map(|i| (i % 29) as f32 - 14.0).collect();
let aw = DeviceBuf::alloc(weights.len()).unwrap(); aw.h2d_bytes(&weights).unwrap();
let asc = DeviceBuf::alloc(scales.len()).unwrap(); asc.h2d_bytes(&scales).unwrap();
let dxf = DeviceBuf::alloc(b * k * 4).unwrap(); dxf.h2d(&xf).unwrap();
let dxh = DeviceBuf::alloc(b * k * 2).unwrap(); cast_f32_f16(&dxf, &dxh, b * k).unwrap();
let ids_bytes: Vec<u8> = ids.iter().flat_map(|x| x.to_le_bytes()).collect();
let dids = DeviceBuf::alloc(total * 4).unwrap(); dids.h2d_bytes(&ids_bytes).unwrap();
let dcnt = DeviceBuf::alloc(129 * 4).unwrap(); dcnt.h2d_bytes(&vec![0u8; 129 * 4]).unwrap();
let doff = DeviceBuf::alloc(129 * 4).unwrap();
let dcur = DeviceBuf::alloc(128 * 4).unwrap();
let dbtk = DeviceBuf::alloc(total * 4).unwrap();
let ds2b = DeviceBuf::alloc(total * 4).unwrap();
moe_count_buckets(&dids, &dcnt, total as i32).unwrap();
moe_prefix_buckets(&dcnt, &doff, &dcur).unwrap();
moe_scatter_buckets(&dids, &dcur, &dbtk, &ds2b, total as i32, top_k as i32).unwrap();
let dy = DeviceBuf::alloc(total * n * 4).unwrap();
mxfp8_grouped_gemv_f16(&aw, &asc, &doff, Some(&dbtk), &dxh, &dy, n as i32, k as i32, n_exp as i32, w_stride as i64, sc_stride as i64).unwrap();
let mut got = vec![0f32; total * n]; dy.d2h(&mut got).unwrap();
let mut s2b_b = vec![0u8; total * 4]; ds2b.d2h_bytes(&mut s2b_b).unwrap();
let s2b: Vec<i32> = s2b_b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
let ue8m0 = |bb: u8| ((bb as i32 - 127) as f32).exp2();
let mut max_rel = 0f32;
for i in 0..total {
let tok = i / top_k;
let e = ids[i] as usize;
let bp = s2b[i] as usize;
for ni in 0..n {
let mut acc = 0f32;
for bb in 0..k / 32 {
let sc = ue8m0(scales[e * sc_stride + ni * (k / 32) + bb]);
let mut d = 0f32;
for j in 0..32 { d += xf[tok * k + bb * 32 + j] * e4m3(weights[e * w_stride + ni * k + bb * 32 + j]); }
acc = d.mul_add(sc, acc);
}
let g = got[bp * n + ni];
max_rel = max_rel.max((g - acc).abs() / acc.abs().max(1e-3));
}
}
eprintln!("mxfp8_grouped_gemv_f16 B={b} experts={n_exp} pairs={total} max_rel_err={max_rel:.3e}");
assert!(max_rel < 2e-3, "grouped MXFP8 GEMM parity failed: {max_rel}");
}
/// Batched f32 router GEMM (M=B) vs M sequential router_gemv (same block
/// reduction order => bit-exact).
#[test]
#[ignore]
fn router_gemv_batched_parity() {
let (m, n, k) = (20usize, 16usize, 128usize);
let x: Vec<f32> = (0..m * k).map(|i| ((i % 29) as f32 - 14.0) * 0.03).collect();
let w: Vec<u16> = (0..n * k).map(|i| f32_to_bf16(((i % 23) as f32 - 11.0) * 0.04)).collect();
let dx = DeviceBuf::alloc(m * k * 4).unwrap(); dx.h2d(&x).unwrap();
let dw = DeviceBuf::alloc(n * k * 2).unwrap(); dw.h2d_bytes(bytemuck_u16(&w)).unwrap();
let dy_b = DeviceBuf::alloc(m * n * 4).unwrap();
router_gemv_batched(&dx, &dw, &dy_b, n as i32, k as i32, m as i32).unwrap();
let mut yb = vec![0f32; m * n]; dy_b.d2h(&mut yb).unwrap();
let dx1 = DeviceBuf::alloc(k * 4).unwrap();
let dy1 = DeviceBuf::alloc(n * 4).unwrap();
let mut max_rel = 0f32;
for mi in 0..m {
dx1.h2d(&x[mi * k..(mi + 1) * k]).unwrap();
router_gemv(&dx1, &dw, &dy1, n as i32, k as i32).unwrap();
let mut o = vec![0f32; n]; dy1.d2h(&mut o).unwrap();
for ni in 0..n { max_rel = max_rel.max((yb[mi * n + ni] - o[ni]).abs() / o[ni].abs().max(1e-3)); }
}
eprintln!("router_gemv_batched M={m} N={n} K={k} max_rel_err={max_rel:.3e}");
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, None).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.
#[test]
#[ignore]
fn relpos_bias_batched_parity() {
let (m, n_head, d_rel, rel_extent, base) = (20usize, 8usize, 16usize, 64usize, 10i32);
let r: Vec<f32> = (0..m * n_head * d_rel).map(|i| ((i % 17) as f32 - 8.0) * 0.05).collect();
let rp: Vec<f32> = (0..d_rel * rel_extent).map(|i| ((i % 13) as f32 - 6.0) * 0.02).collect();
let pos: Vec<i32> = (0..m).map(|mi| base + mi as i32).collect();
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 pos_bytes: Vec<u8> = pos.iter().flat_map(|x| x.to_le_bytes()).collect();
let dpos = DeviceBuf::alloc(m * 4).unwrap(); dpos.h2d_bytes(&pos_bytes).unwrap();
let row = n_head * rel_extent;
let zeros = vec![0f32; m * row];
let db_b = DeviceBuf::alloc(zeros.len() * 4).unwrap(); db_b.h2d(&zeros).unwrap();
relpos_bias_batched(&dr, &drp, &db_b, &dpos, n_head as i32, d_rel as i32, rel_extent as i32, m as i32).unwrap();
let mut bb = vec![0f32; zeros.len()]; db_b.d2h(&mut bb).unwrap();
let dr1 = DeviceBuf::alloc(n_head * d_rel * 4).unwrap();
let db1 = DeviceBuf::alloc(row * 4).unwrap();
let mut max_rel = 0f32;
for mi in 0..m {
dr1.h2d(&r[mi * n_head * d_rel..(mi + 1) * n_head * d_rel]).unwrap();
db1.h2d(&vec![0f32; row]).unwrap();
let lim = (pos[mi] + 1).min(rel_extent as i32);
relpos_bias(&dr1, &drp, &db1, n_head as i32, d_rel as i32, rel_extent as i32, lim).unwrap();
let mut o = vec![0f32; row]; db1.d2h(&mut o).unwrap();
for j in 0..row { max_rel = max_rel.max((bb[mi * row + j] - o[j]).abs() / o[j].abs().max(1e-3)); }
}
eprintln!("relpos_bias_batched M={m} n_head={n_head} max_rel_err={max_rel:.3e}");
assert!(max_rel < 1e-5, "relpos batched parity failed: {max_rel}");
}
/// Batched ctrl_pack (M=B) byte-identical to M sequential ctrl_pack.
#[test]
#[ignore]
fn ctrl_pack_batched_parity() {
let (m, d) = (20usize, 128usize);
let eps = 1e-6f32;
let cur: Vec<f32> = (0..m * d).map(|i| ((i % 31) as f32 - 15.0) * 0.04).collect();
let msg: Vec<f32> = (0..m * d).map(|i| ((i % 27) as f32 - 13.0) * 0.03).collect();
let dc = DeviceBuf::alloc(m * d * 4).unwrap(); dc.h2d(&cur).unwrap();
let dm = DeviceBuf::alloc(m * d * 4).unwrap(); dm.h2d(&msg).unwrap();
let dp_b = DeviceBuf::alloc(m * 2 * d * 2).unwrap();
ctrl_pack_batched(&dc, &dm, &dp_b, d as i32, eps, m as i32).unwrap();
let mut pb = vec![0u8; m * 2 * d * 2]; dp_b.d2h_bytes(&mut pb).unwrap();
let dc1 = DeviceBuf::alloc(d * 4).unwrap();
let dm1 = DeviceBuf::alloc(d * 4).unwrap();
let dp1 = DeviceBuf::alloc(2 * d * 2).unwrap();
for mi in 0..m {
dc1.h2d(&cur[mi * d..(mi + 1) * d]).unwrap();
dm1.h2d(&msg[mi * d..(mi + 1) * d]).unwrap();
ctrl_pack(&dc1, &dm1, &dp1, d as i32, eps).unwrap();
let mut o = vec![0u8; 2 * d * 2]; dp1.d2h_bytes(&mut o).unwrap();
assert_eq!(&pb[mi * 2 * d * 2..(mi + 1) * 2 * d * 2], &o[..], "ctrl_pack batched row {mi}");
}
eprintln!("ctrl_pack_batched M={m} D={d}: byte-identical to sequential");
}
/// copy_f32 device-side copy is exact (dst == src).
#[test]
#[ignore]
fn copy_f32_exact() {
let n = 1024usize;
let src: Vec<f32> = (0..n).map(|i| (i as f32 - 512.0) * 0.013).collect();
let ds = DeviceBuf::alloc(n * 4).unwrap(); ds.h2d(&src).unwrap();
let dd = DeviceBuf::alloc(n * 4).unwrap();
copy_f32(&ds, &dd, n).unwrap();
let mut got = vec![0f32; n]; dd.d2h(&mut got).unwrap();
assert_eq!(got, src, "copy_f32 must be exact");
}
#[test]
#[ignore]
fn shortconv4_multistep_parity() {
let c = 64usize;
let steps = 6usize;
let inv_sqrt5 = 0.44721359549995793f32;
let sw: Vec<f32> = (0..c * 4).map(|i| ((i % 17) as f32 - 8.0) * 0.05).collect();
let mut hist: Vec<f32> = (0..3 * c).map(|i| ((i % 11) as f32 - 5.0) * 0.1).collect();
let xs: Vec<Vec<f32>> = (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 { let h1 = hist[c + ch]; let h2 = hist[2 * c + ch]; hist[ch] = bf16_to_f32(f32_to_bf16(h1)); hist[c + ch] = bf16_to_f32(f32_to_bf16(h2)); hist[2 * c + ch] = bf16_to_f32(f32_to_bf16(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<f32> = (0..c * 4).map(|i| ((i % 17) as f32 - 8.0) * 0.05).collect();
let mut hist: Vec<f32> = (0..3 * c).map(|i| ((i % 11) as f32 - 5.0) * 0.1).collect();
let xs: Vec<Vec<f32>> = (0..steps).map(|t| (0..c).map(|i| ((i + t * 7) % 23) as f32 * 0.03 - 0.3).collect()).collect();
let dyns: Vec<Vec<f32>> = (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 { let h1 = hist[c + ch]; let h2 = hist[2 * c + ch]; hist[ch] = bf16_to_f32(f32_to_bf16(h1)); hist[c + ch] = bf16_to_f32(f32_to_bf16(h2)); hist[2 * c + ch] = bf16_to_f32(f32_to_bf16(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<f32> = (0..nb * m * d).map(|i| ((i % 37) as f32 - 18.0) * 0.03).collect();
let cur: Vec<f32> = (0..m * d).map(|i| ((i % 29) as f32 - 14.0) * 0.04).collect();
let queries: Vec<f32> = (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<f32> = scores.iter().map(|sc| (sc - mx).exp()).collect();
let sum: f32 = exps.iter().sum();
let weights: Vec<f32> = 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<f32> {
let mut out = vec![0f32; rows * hd];
for r in 0..rows {
let v: Vec<f32> = (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<f32> = (0..rows * hd).map(|i| ((i % 29) as f32 - 14.0) * 0.5).collect();
let scale: Vec<f32> = (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<f32> = (0..n_head * d_rel).map(|i| ((i % 13) as f32 - 6.0) * 0.1).collect();
let rp: Vec<f32> = (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<f32> = (0..n_kv * hd2).map(|i| ((i % 17) as f32 - 8.0) * 0.2).collect();
let v_in: Vec<f32> = (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");
}
/// FP16 KV cache path (strata default KvDtype::FP16): kv_store_f16 rounds K/V
/// to FP16 (RNE); flash_swa_gqa_decode_f16 reads them back. Verifies (a) the
/// stored K equals cast_f32_f16(k_in) bit-for-bit, and (b) attention over the
/// decoded FP16 KV matches a CPU oracle fed the SAME decoded values.
#[test]
#[ignore]
fn fp16_kv_store_and_flash_parity() {
let f16dec = |h: u16| -> f32 {
let sign = ((h & 0x8000) as u32) << 16;
let exp = (h >> 10) & 0x1f;
let mant = (h & 0x3ff) as u32;
if exp == 0 { return f32::from_bits(sign | ((mant as f32 * 2f32.powi(-24)).to_bits())); }
if exp == 31 { return f32::from_bits(sign | 0x7f800000 | (mant << 13)); }
f32::from_bits(sign | (((exp as u32 + 112) << 23) | (mant << 13)))
};
let (n_head, n_kv, hd, seq) = (4usize, 2usize, 8usize, 6usize);
let eps = 1e-6f32; let scale = 1.0 / (hd as f32).sqrt();
// Store K/V for positions 0..seq via kv_store_f16.
let dkc = DeviceBuf::alloc(n_kv * seq * hd * 2).unwrap(); dkc.h2d_bytes(&vec![0u8; n_kv * seq * hd * 2]).unwrap();
let dvc = DeviceBuf::alloc(n_kv * seq * hd * 2).unwrap(); dvc.h2d_bytes(&vec![0u8; n_kv * seq * hd * 2]).unwrap();
let mut k_in_all = vec![0f32; seq * n_kv * hd];
let mut v_in_all = vec![0f32; seq * n_kv * hd];
for p in 0..seq {
let k_in: Vec<f32> = (0..n_kv * hd).map(|i| (((i + p * 7) % 17) as f32 - 8.0) * 0.2).collect();
let v_in: Vec<f32> = (0..n_kv * hd).map(|i| (((i + p * 5) % 19) as f32 - 9.0) * 0.3).collect();
k_in_all[p * n_kv * hd..(p + 1) * n_kv * hd].copy_from_slice(&k_in);
v_in_all[p * n_kv * hd..(p + 1) * n_kv * hd].copy_from_slice(&v_in);
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();
kv_store_f16(&dki, &dvi, &dkc, &dvc, p as i32, n_kv as i32, hd as i32, seq as i32, eps).unwrap();
}
// (a) K stored bits == cast_f32_f16(k_in) bits (both RNE).
let dk_all = DeviceBuf::alloc(k_in_all.len() * 4).unwrap(); dk_all.h2d(&k_in_all).unwrap();
let dk16 = DeviceBuf::alloc(k_in_all.len() * 2).unwrap();
cast_f32_f16(&dk_all, &dk16, k_in_all.len()).unwrap();
let mut ref_k16 = vec![0u8; k_in_all.len() * 2]; dk16.d2h_bytes(&mut ref_k16).unwrap();
let mut got_kc = vec![0u8; n_kv * seq * hd * 2]; dkc.d2h_bytes(&mut got_kc).unwrap();
// cache layout [n_kv, seq, hd]; ref_k16 layout [seq, n_kv, hd] -> transpose.
for h in 0..n_kv { for p in 0..seq { for d in 0..hd {
let got = u16::from_le_bytes([got_kc[(h * seq + p) * hd * 2 + d * 2], got_kc[(h * seq + p) * hd * 2 + d * 2 + 1]]);
let want = u16::from_le_bytes([ref_k16[(p * n_kv + h) * hd * 2 + d * 2], ref_k16[(p * n_kv + h) * hd * 2 + d * 2 + 1]]);
assert_eq!(got, want, "kv_store_f16 K bits mismatch h={h} p={p} d={d}");
}}}
// Decode the actual FP16 KV the flash kernel reads.
let mut got_vc = vec![0u8; n_kv * seq * hd * 2]; dvc.d2h_bytes(&mut got_vc).unwrap();
let dec = |b: &[u8], off: usize| f16dec(u16::from_le_bytes([b[off], b[off + 1]]));
let mut kc = vec![0f32; n_kv * seq * hd]; let mut vc = vec![0f32; n_kv * seq * hd];
for i in 0..n_kv * seq * hd { kc[i] = dec(&got_kc, i * 2); vc[i] = dec(&got_vc, i * 2); }
// (b) flash_f16 at cur_pos = seq-1 vs CPU oracle over decoded KV (window 0).
let q: Vec<f32> = (0..n_head * hd).map(|i| ((i % 13) as f32 - 6.0) * 0.1).collect();
let dq = DeviceBuf::alloc(q.len() * 4).unwrap(); dq.h2d(&q).unwrap();
let dout = DeviceBuf::alloc(n_head * hd * 4).unwrap();
let cur_pos = (seq - 1) as i32;
flash_swa_gqa_decode_f16(&dq, &dkc, &dvc, &dout, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, 0, cur_pos, None, 0, None, None).unwrap();
let mut got = vec![0f32; n_head * hd]; dout.d2h(&mut got).unwrap();
let mut want = vec![0f32; n_head * hd];
for h in 0..n_head { let kvh = h / (n_head / n_kv);
let mut dots = vec![0f32; seq];
for s in 0..seq { let mut dot = 0f32; for d in 0..hd { dot += q[h * hd + d] * kc[(kvh * seq + s) * hd + d]; } dots[s] = dot * scale; }
let m = dots.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
let es: Vec<f32> = dots.iter().map(|d| (d - m).exp()).collect();
let sum: f32 = es.iter().sum(); let inv = 1.0 / sum.max(1e-30);
for d in 0..hd { let mut acc = 0f32; for s in 0..seq { acc += es[s] * inv * vc[(kvh * seq + s) * hd + d]; } want[h * hd + d] = acc; }
}
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!("fp16 KV store + flash max_rel_err={mr:.3e}");
assert!(mr < 1e-4, "flash_swa_gqa_decode_f16 parity failed: {mr}");
}
#[test]
#[ignore]
fn softcap_parity_vs_cpu() {
let cap = 30.0f32;
let n = 5000usize;
let x: Vec<f32> = (0..n).map(|i| ((i % 201) as f32 - 100.0) * 0.5).collect();
let want: Vec<f32> = 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 { let u = x.to_bits(); ((u + 0x7FFFu32 + ((u >> 16) & 1)) >> 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<f32> = (0..d).map(|i| ((i % 29) as f32 - 14.0) * 0.1).collect();
let msg: Vec<f32> = (0..d).map(|i| ((i % 23) as f32 - 11.0) * 0.08).collect();
let down: Vec<u16> = (0..gr * 2 * d).map(|i| bf(((i % 31) as f32 - 15.0) * 0.02)).collect();
let gain_w: Vec<u16> = (0..d * gr).map(|i| bf(((i % 17) as f32 - 8.0) * 0.03)).collect();
let forget_w: Vec<u16> = (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::<f32>() / d as f32 + eps).sqrt();
let im = 1.0 / (msg.iter().map(|v| v * v).sum::<f32>() / 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<f32> = (0..gr).map(|n| (0..2 * d).map(|k| pk[k] * ubf(down[n * 2 * d + k])).sum()).collect();
let gate_bf_c: Vec<f32> = gate_c.iter().map(|&v| trunc(v)).collect();
let gain_c: Vec<f32> = (0..d).map(|i| (0..gr).map(|r| gate_bf_c[r] * ubf(gain_w[i * gr + r])).sum()).collect();
let forget_c: Vec<f32> = (0..d).map(|i| (0..gr).map(|r| gate_bf_c[r] * ubf(forget_w[i * gr + r])).sum()).collect();
let want: Vec<f32> = (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) }
}
}