//! Reusable GPU Inkling layer forward (feature `hip`). //! //! Composes the verified microkernels into a complete layer with persistent //! per-layer state (KV cache + ShortConv history rings) and the exact Inkling //! deep-residual block cadence. The depth-block snapshots (`blocks`) belong to //! the whole forward (the residual stream), so the caller owns them and passes //! them in; each layer appends a snapshot when `ip % block_size == 0`. //! //! Scope today: SWA layers without loop controllers (the prelude). Full-attn //! layers (3-query split), loop controllers (gain/forget/down) and the //! multi-pass bank rollback are layered on next. use crate::packer::{expert_arena_gemv_f16, expert_arena_grouped_gemv_f16, expert_gemv, expert_gemv_f16, load_bf16_as_f32, load_expert_arena, load_expert_matrix, load_raw, ExpertArena, ExpertMatrix}; use crate::SafetensorsArchive; use std::cell::RefCell; use std::collections::HashMap; use std::sync::Arc; use vetta_infer_hip::DeviceBuf; /// Resident weights for one physical layer step `ip`. pub struct LayerWeights { pub ip: usize, pub is_swa: bool, // attention pub attn_norm: DeviceBuf, pub wq: DeviceBuf, pub wk: DeviceBuf, pub wv: DeviceBuf, pub wr: DeviceBuf, pub wg: DeviceBuf, pub ws: DeviceBuf, pub wo: DeviceBuf, pub q_sc: DeviceBuf, pub r_sc: DeviceBuf, pub rel_proj: DeviceBuf, pub k_sconv: DeviceBuf, pub v_sconv: DeviceBuf, pub a_sconv: DeviceBuf, // moe pub mlp_norm: DeviceBuf, pub gate_w: DeviceBuf, pub gate_b: DeviceBuf, pub m_sconv: DeviceBuf, // learned depth-mix queries pub attn_query: Option, // attn_queries[ip-1] (None at ip==0) pub mlp_query: DeviceBuf, // mlp_queries[ip] } /// Persistent per-layer decode state. pub struct LayerState { // KV cache is PER-VISIT (exact strata visit_kv_slot: every core pass owns a // distinct SWA/global KV pool, 40 SWA + 8 global). One cache per pass the // layer actually runs: core layers 3 (pass 0/1/2), prelude/coda 1 (pass 0). // Sharing one cache across passes corrupts multi-token attention. pub k_cache: Vec, pub v_cache: Vec, // per-pass [n_kv, max_seq, hd] // ShortConv history is PER-VISIT (exact strata hist_pool_all + visit*stride): // each core pass has its own history ring, NOT shared across passes. Index // by pass (prelude/coda use pass 0; core uses pass 0/1/2). pub hist_k: [DeviceBuf; 3], pub hist_v: [DeviceBuf; 3], // [3, n_kv*hd] each pub hist_a: [DeviceBuf; 3], pub hist_m: [DeviceBuf; 3], // [3, hidden] each pub max_seq: usize, } /// Forward-pass dimensions (subset of TextConfig needed by a layer). #[derive(Clone, Copy)] pub struct Dims { pub hidden: usize, pub n_head: usize, pub n_kv: usize, pub hd: usize, pub d_rel: usize, pub rel_extent: usize, pub inter: usize, pub n_experts: usize, pub top_k: usize, pub block_size: usize, pub qk_clip: f32, pub rel_clip: f32, pub eps: f32, pub route_scale: f32, pub beta: f32, pub lb: f32, pub swa_win: i32, } impl Dims { pub fn kv_dim(&self) -> usize { self.n_kv * self.hd } pub fn q_dim(&self) -> usize { self.n_head * self.hd } pub fn scale(&self) -> f32 { 1.0 / (self.hd as f32).sqrt() } } /// Resident weight cache: memoizes every device upload (raw tensors, BF16->F32 /// norms, per-layer weights, controllers and the NVFP4/MXFP8 expert matrices) /// so autoregressive decode reuses GPU-resident weights instead of re-reading /// ~3 GiB of expert blobs from NVMe per token. Owns an `Arc` to the archive so the /// serve can keep ONE resident cache across requests (no per-request NVMe re-read /// or re-upload); the maps use interior mutability so the forward can hold shared /// `&WeightCache` while loading lazily. Single-threaded forward (serve decodes on /// one thread). pub struct WeightCache { pub ar: Arc, raw: RefCell>>, bf16: RefCell>>, sconv: RefCell>>, swa: RefCell>>, full: RefCell>>, experts: RefCell>>, arenas: RefCell>>, ctrl: RefCell>>, msgq: RefCell>>, } impl WeightCache { pub fn new(ar: Arc) -> Self { Self { ar, raw: RefCell::new(HashMap::new()), bf16: RefCell::new(HashMap::new()), sconv: RefCell::new(HashMap::new()), swa: RefCell::new(HashMap::new()), full: RefCell::new(HashMap::new()), experts: RefCell::new(HashMap::new()), arenas: RefCell::new(HashMap::new()), ctrl: RefCell::new(HashMap::new()), msgq: RefCell::new(HashMap::new()), } } pub fn raw(&self, name: &str) -> Result, String> { if let Some(v) = self.raw.borrow().get(name) { return Ok(v.clone()); } let v = Arc::new(load_raw(&self.ar, name)?); self.raw.borrow_mut().insert(name.to_string(), v.clone()); Ok(v) } pub fn bf16_f32(&self, name: &str) -> Result, String> { if let Some(v) = self.bf16.borrow().get(name) { return Ok(v.clone()); } let v = Arc::new(load_bf16_as_f32(&self.ar, name)?); self.bf16.borrow_mut().insert(name.to_string(), v.clone()); Ok(v) } pub fn sconv_t(&self, name: &str, c: usize) -> Result, String> { let key = (name.to_string(), c); if let Some(v) = self.sconv.borrow().get(&key) { return Ok(v.clone()); } let v = Arc::new(load_sconv_transposed(&self.ar, name, c)?); self.sconv.borrow_mut().insert(key, v.clone()); Ok(v) } pub fn swa_layer(&self, ip: usize) -> Result, String> { if let Some(v) = self.swa.borrow().get(&ip) { return Ok(v.clone()); } let v = Arc::new(load_layer(&self.ar, ip, true)?); self.swa.borrow_mut().insert(ip, v.clone()); Ok(v) } pub fn full_layer(&self, ip: usize, d: &Dims) -> Result, String> { if let Some(v) = self.full.borrow().get(&ip) { return Ok(v.clone()); } let v = Arc::new(load_full_layer(&self.ar, ip, d)?); self.full.borrow_mut().insert(ip, v.clone()); Ok(v) } pub fn expert(&self, ip: usize, e: usize, mat: &str) -> Result, String> { let key = (ip, e, mat.to_string()); if let Some(v) = self.experts.borrow().get(&key) { return Ok(v.clone()); } let v = Arc::new(load_expert_matrix(&self.ar, ip, e, mat)?); self.experts.borrow_mut().insert(key, v.clone()); Ok(v) } /// Contiguous per-layer expert arena (all experts in one device buffer) for /// the device-routed MoE path. Memoized like `expert`. pub fn expert_arena(&self, ip: usize, mat: &str) -> Result, String> { let key = (ip, mat.to_string()); if let Some(v) = self.arenas.borrow().get(&key) { return Ok(v.clone()); } let v = Arc::new(load_expert_arena(&self.ar, ip, mat)?); self.arenas.borrow_mut().insert(key, v.clone()); Ok(v) } pub fn controllers(&self, ip: usize) -> Result, String> { if let Some(v) = self.ctrl.borrow().get(&ip) { return Ok(v.clone()); } let v = Arc::new(load_controllers(&self.ar, ip)?); self.ctrl.borrow_mut().insert(ip, v.clone()); Ok(v) } /// Stacked cross-pass msg_queries [4, hidden] for core layer ip, memoized. /// These are STATIC model weights: building them per visit did 2 sync D2H + 1 /// sync H2D each (72 PCIe stalls/chunk in prefill, 24/token in decode). Cache /// the device buffer once => zero host round-trips on the hot path. pub fn msg_queries(&self, ip: usize, hidden: usize) -> Result, String> { if let Some(v) = self.msgq.borrow().get(&ip) { return Ok(v.clone()); } let v = Arc::new(load_msg_queries(self, ip, hidden)?); self.msgq.borrow_mut().insert(ip, v.clone()); Ok(v) } /// Eagerly load the WHOLE model to device: trunk (embed/norms/unembed/output /// query/cross-pass queries), every attention layer (SWA or full), the core /// loop controllers, and all expert ARENAS (the contiguous device-MoE layout). /// After this the cache is fully resident: VRAM is populated at boot and NO /// request pays NVMe reads or uploads (the model is ~18 GiB, within the <=80 /// GiB full-UMA-residency policy). This is the serve default; `VETTA_LAZY_LOAD=1` /// defers to first use (still resident across requests once loaded). Idempotent: /// each loader memoizes, so calling it twice uploads nothing new. /// /// Loads the expert ARENAS (not the per-expert `ExpertMatrix` copies): the /// production serve uses the device-routed MoE (`VETTA_DEVICE_MOE`), which /// reads the arena. Prewarming the per-expert matrices too would hold a SECOND /// full copy of the ~16 GiB expert weights (the arena loads lazily on the first /// forward), nearly doubling VRAM. The legacy host `run_experts` path loads /// per-expert matrices lazily on demand if ever selected. pub fn prewarm(&self, d: &Dims, n_layers: usize) -> Result<(), String> { self.raw("model.llm.embed.weight")?; self.bf16_f32("model.llm.embed_norm.weight")?; self.bf16_f32("model.llm.norm.weight")?; self.raw("model.llm.unembed.weight")?; self.raw("model.llm.attn_res.output_query")?; self.raw("model.llm.middle_cycle_cross_pass_queries")?; self.raw("model.llm.middle_cycle_cross_pass_kv_queries")?; for ip in 0..n_layers { if is_swa(ip) { self.swa_layer(ip)?; } else { self.full_layer(ip, d)?; } if (6..18).contains(&ip) { self.controllers(ip)?; } } for ip in 0..n_layers { self.expert_arena(ip, "w13")?; self.expert_arena(ip, "w2")?; } Ok(()) } } pub fn load_layer(ar: &SafetensorsArchive, ip: usize, is_swa: bool) -> Result { let p = format!("model.llm.layers.{ip}.attn"); let attn_query = if ip > 0 { Some(load_raw(ar, &format!("model.llm.attn_res.attn_queries.{}", ip - 1))?) } else { None }; Ok(LayerWeights { ip, is_swa, attn_norm: load_bf16_as_f32(ar, &format!("model.llm.layers.{ip}.attn_norm.weight"))?, wq: load_raw(ar, &format!("{p}.wq_du.weight"))?, wk: load_raw(ar, &format!("{p}.wk_dv.weight"))?, wv: load_raw(ar, &format!("{p}.wv_dv.weight"))?, wr: load_raw(ar, &format!("{p}.wr_du.weight"))?, wg: load_raw(ar, &format!("{p}.gate_attn.weight"))?, ws: load_raw(ar, &format!("{p}.attn_sink_proj.weight"))?, wo: load_raw(ar, &format!("{p}.wo_ud.weight"))?, q_sc: load_bf16_as_f32(ar, &format!("{p}.q_l2_clip.scale"))?, r_sc: load_bf16_as_f32(ar, &format!("{p}.rel_l2_clip.scale"))?, rel_proj: load_bf16_as_f32(ar, &format!("{p}.rel_logits_proj.proj"))?, k_sconv: load_bf16_as_f32(ar, &format!("{p}.k_sconv.weight"))?, v_sconv: load_bf16_as_f32(ar, &format!("{p}.v_sconv.weight"))?, a_sconv: load_bf16_as_f32(ar, &format!("model.llm.layers.{ip}.attn_sconv.weight"))?, mlp_norm: load_bf16_as_f32(ar, &format!("model.llm.layers.{ip}.mlp_norm.weight"))?, gate_w: load_raw(ar, &format!("model.llm.layers.{ip}.mlp.gate.weight"))?, gate_b: load_raw(ar, &format!("model.llm.layers.{ip}.mlp.gate.bias"))?, m_sconv: load_bf16_as_f32(ar, &format!("model.llm.layers.{ip}.mlp_sconv.weight"))?, attn_query, mlp_query: load_raw(ar, &format!("model.llm.attn_res.mlp_queries.{ip}"))?, }) } pub fn new_state(d: &Dims, max_seq: usize, n_passes: usize) -> Result { let zero = |n: usize| -> Result { let b = DeviceBuf::alloc(n * 4)?; b.zero_async()?; Ok(b) }; // KV cache dtype: F32 by default (the verified CPU-oracle baseline); FP16 via // VETTA_F16_KV=1 matches the strata default (KvDtype::FP16) and its // length-dependent rounding (the F32 cache diverges on near-ties as it grows). let kv_n = d.n_kv * max_seq * d.hd; // KV is unpooled: its size scales with max_seq (prompt+max_new), which varies // per request. Pooling by exact size would retain every distinct KV size and // grow VRAM without bound across a multi-turn chat; free it on request end. // Zero-filled with ASYNC device memset (hipMemsetAsync, ~7.5ms GPU for 3.75GB), // NOT a host vec![0]+sync h2d: the latter allocated ~3.75GB system RAM, zeroed // it on CPU and copied it over blocking PCIe every request (~0.5-1.5s stall). // Causal attention only reads [0..=pos] (kv_store overwrites before read), so // the zero is defensive/deterministic rather than required, but keeps the // full-cache byte-parity tests stable across pool reuse. let kv_buf = || -> Result { let b = if f16_kv() { DeviceBuf::alloc_unpooled(kv_n * 2)? } else { DeviceBuf::alloc_unpooled(kv_n * 4)? }; b.zero_async()?; Ok(b) }; let kv_vec = || -> Result, String> { (0..n_passes.max(1)).map(|_| kv_buf()).collect() }; Ok(LayerState { k_cache: kv_vec()?, v_cache: kv_vec()?, hist_k: [zero(3 * d.kv_dim())?, zero(3 * d.kv_dim())?, zero(3 * d.kv_dim())?], hist_v: [zero(3 * d.kv_dim())?, zero(3 * d.kv_dim())?, zero(3 * d.kv_dim())?], hist_a: [zero(3 * d.hidden)?, zero(3 * d.hidden)?, zero(3 * d.hidden)?], hist_m: [zero(3 * d.hidden)?, zero(3 * d.hidden)?, zero(3 * d.hidden)?], max_seq, }) } /// A checkpoint of one layer's decode state at a prefix boundary `seq_len`: the /// KV prefix `[n_kv, seq_len, hd]` per pass + the ShortConv history rings. Sized /// to seq_len (KV unpooled), held in the prefix cache across requests. Restoring /// it and prefilling the suffix is exact (proofs/prefix_cache.lean restore_equiv). pub struct LayerSnapshot { pub seq_len: usize, /// First KV position stored in this snapshot. For full-attn layers it is 0 /// (whole prefix); for SWA layers it is seq_len - min(seq_len, swa_win), so /// only the causal window is checkpointed (the older KV is never read again). pub kv_start: usize, pub k_cache: Vec, pub v_cache: Vec, pub hist_k: [DeviceBuf; 3], pub hist_v: [DeviceBuf; 3], pub hist_a: [DeviceBuf; 3], pub hist_m: [DeviceBuf; 3], } impl LayerState { /// Snapshot the KV prefix plus the current ShortConv history rings. For a /// SWA layer (`swa`) only the last `min(seq_len, swa_win)` KV positions are /// stored (the causal window): attention at any future pos >= seq_len reads /// [pos-swa_win+1..pos] ⊆ [kv_start..pos], so the discarded older KV is never /// observed (proofs/prefix_cache.lean swa_window_restore_equiv). Full-attn /// layers attend globally and keep the whole `[0, seq_len)` prefix. pub fn snapshot(&self, d: &Dims, seq_len: usize, swa: bool) -> Result { let es = if f16_kv() { 2 } else { 4 }; let win = if swa { seq_len.min(d.swa_win.max(0) as usize) } else { seq_len }; let kv_start = seq_len - win; // Ring-aware source slots: the window [kv_start, seq_len) maps to // [kv_start % r, ..) in the SWA ring (r = self.max_seq); it wraps at most // once because win <= swa_win < r. Global pools have kv_start = 0, no wrap. let r = self.max_seq; let s0 = kv_start % r; let first = win.min(r - s0); let row = win * d.hd * es; let snap_kv = |src: &DeviceBuf| -> Result { let b = DeviceBuf::alloc_unpooled(d.n_kv * row)?; b.copy2d_at(0, src, s0 * d.hd * es, row, r * d.hd * es, first * d.hd * es, d.n_kv)?; if win > first { b.copy2d_at(first * d.hd * es, src, 0, row, r * d.hd * es, (win - first) * d.hd * es, d.n_kv)?; } Ok(b) }; let k_cache = self.k_cache.iter().map(snap_kv).collect::, _>>()?; let v_cache = self.v_cache.iter().map(snap_kv).collect::, _>>()?; let cp = |src: &DeviceBuf| -> Result { let b = DeviceBuf::alloc(src.bytes)?; b.copy_from(src, src.bytes)?; Ok(b) }; Ok(LayerSnapshot { seq_len, kv_start, k_cache, v_cache, hist_k: [cp(&self.hist_k[0])?, cp(&self.hist_k[1])?, cp(&self.hist_k[2])?], hist_v: [cp(&self.hist_v[0])?, cp(&self.hist_v[1])?, cp(&self.hist_v[2])?], hist_a: [cp(&self.hist_a[0])?, cp(&self.hist_a[1])?, cp(&self.hist_a[2])?], hist_m: [cp(&self.hist_m[0])?, cp(&self.hist_m[1])?, cp(&self.hist_m[2])?], }) } /// Restore the KV prefix `[kv_start, seq_len)` + history into `self` (whose /// max_seq must be >= snap.seq_len). For SWA snapshots kv_start > 0: positions /// below it are left untouched (never read by the causal window); the suffix /// prefill fills `[seq_len, pos)`. Attention at pos >= seq_len reads only the /// restored window + suffix, so this is observationally exact (restore_equiv). pub fn restore(&mut self, d: &Dims, snap: &LayerSnapshot) -> Result<(), String> { let es = if f16_kv() { 2 } else { 4 }; let win = snap.seq_len - snap.kv_start; let r = self.max_seq; let s0 = snap.kv_start % r; let first = win.min(r - s0); let row = win * d.hd * es; for (dst, src) in self.k_cache.iter().zip(&snap.k_cache) { dst.copy2d_at(s0 * d.hd * es, src, 0, r * d.hd * es, row, first * d.hd * es, d.n_kv)?; if win > first { dst.copy2d_at(0, src, first * d.hd * es, r * d.hd * es, row, (win - first) * d.hd * es, d.n_kv)?; } } for (dst, src) in self.v_cache.iter().zip(&snap.v_cache) { dst.copy2d_at(s0 * d.hd * es, src, 0, r * d.hd * es, row, first * d.hd * es, d.n_kv)?; if win > first { dst.copy2d_at(0, src, first * d.hd * es, r * d.hd * es, row, (win - first) * d.hd * es, d.n_kv)?; } } for i in 0..3 { self.hist_k[i].copy_from(&snap.hist_k[i], snap.hist_k[i].bytes)?; self.hist_v[i].copy_from(&snap.hist_v[i], snap.hist_v[i].bytes)?; self.hist_a[i].copy_from(&snap.hist_a[i], snap.hist_a[i].bytes)?; self.hist_m[i].copy_from(&snap.hist_m[i], snap.hist_m[i].bytes)?; } Ok(()) } /// Zero the ShortConv history rings (async device memset). Used when reusing /// persistent states for a COLD request (no prefix restore): the KV prefix is /// overwritten by prefill before any causal read, but the hist rings seed the /// first 3 shortconv steps and must start empty for a fresh conversation. pub fn reset_history(&mut self) -> Result<(), String> { for i in 0..3 { self.hist_k[i].zero_async()?; self.hist_v[i].zero_async()?; self.hist_a[i].zero_async()?; self.hist_m[i].zero_async()?; } Ok(()) } } /// KV cache dtype switch. The CPU-oracle parity baseline (and the ld packer /// tests) use F32; the resident serve opts into FP16 — the exact strata default /// (KvDtype::FP16, "default lossless FP16"), parity-verified EXACT (16/40 greedy /// tokens) and half the VRAM. Attention math stays f32; only stored K/V round to /// FP16. Process-wide safe switch (no env mutation); serve calls set_kv_f16(true). static KV_F16: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// Select FP16 KV (true) or the F32 baseline (false). The resident serve sets /// true at startup; tests keep the F32 default for CPU-oracle parity. pub fn set_kv_f16(on: bool) { KV_F16.store(on, std::sync::atomic::Ordering::Relaxed); } fn f16_kv() -> bool { if std::env::var("VETTA_F32_KV").is_ok() { return false; } KV_F16.load(std::sync::atomic::Ordering::Relaxed) || std::env::var("VETTA_F16_KV").is_ok() } /// Run one SWA layer step on `cur` (in place), appending a depth-block snapshot /// to `blocks` when `ip % block_size == 0`. `pos` is the decode position. /// Experts are loaded on demand from `ar` (zero requantization). pub fn layer_forward_swa( cache: &WeightCache, w: &LayerWeights, st: &mut LayerState, d: &Dims, cur: &DeviceBuf, blocks: &mut Vec, pos: i32, pass: usize, ctrl: Option<(&ControllerWeights, &LoopMsgs)>, ) -> Result<(), String> { let h = d.hidden; let kv_dim = d.kv_dim(); let q_dim = d.q_dim(); let slot0 = DeviceBuf::alloc(4)?; slot0.h2d_bytes(&0i32.to_le_bytes())?; let k_cv = DeviceBuf::alloc(kv_dim * 4)?; let v_cv = DeviceBuf::alloc(kv_dim * 4)?; let rel_bias = DeviceBuf::alloc(d.n_head * d.rel_extent * 4)?; // kernel writes all rel_extent (0.0f beyond lim): no sync host zero-fill let aout = DeviceBuf::alloc(q_dim * 4)?; let aout_bf = DeviceBuf::alloc(q_dim * 2)?; let oproj = DeviceBuf::alloc(h * 4)?; let asc = DeviceBuf::alloc(h * 4)?; // k1: attention input base. ip==0 -> cur; ip>0 -> mix(blocks,cur,attn_query). let base = DeviceBuf::alloc(h * 4)?; if w.ip == 0 { let mut ch = vec![0f32; h]; cur.d2h(&mut ch)?; base.h2d(&ch)?; } else { let n_blocks = blocks.len(); let blk = DeviceBuf::alloc(n_blocks.max(1) * h * 4)?; let mut bh = vec![0f32; n_blocks.max(1) * h]; for (i, b) in blocks.iter().enumerate() { b.d2h(&mut bh[i * h..(i + 1) * h])?; } blk.h2d(&bh)?; let aq = w.attn_query.as_ref().ok_or("ip>0 needs attn_query")?; vetta_infer_hip::attn_res_mix(&blk, cur, aq, &base, n_blocks as i32, 1, 1, h as i32, d.eps)?; } let q = DeviceBuf::alloc(q_dim * 4)?; let k_raw = DeviceBuf::alloc(kv_dim * 4)?; let v_raw = DeviceBuf::alloc(kv_dim * 4)?; let r_raw = DeviceBuf::alloc(d.n_head * d.d_rel * 4)?; let gatea = DeviceBuf::alloc(q_dim * 4)?; let sinks = DeviceBuf::alloc(d.n_head * 4)?; let in0_bf = DeviceBuf::alloc(h * 2)?; if let Some((cw, msgs)) = ctrl { // has_msgs: 3 separate controlled inputs (attn/k/v channels), then norm. let in1 = DeviceBuf::alloc(h * 4)?; let mut b1 = vec![0f32; h]; base.d2h(&mut b1)?; in1.h2d(&b1)?; let in2 = DeviceBuf::alloc(h * 4)?; let mut b2 = vec![0f32; h]; base.d2h(&mut b2)?; in2.h2d(&b2)?; apply_controller(&base, &msgs.channel(0, h)?, cw, 0, h, 64, d.eps)?; apply_controller(&in1, &msgs.channel(1, h)?, cw, 1, h, 64, d.eps)?; apply_controller(&in2, &msgs.channel(2, h)?, cw, 2, h, 64, d.eps)?; vetta_infer_hip::rms_norm_f32(&base, Some(&w.attn_norm), &base, 1, h as i32, d.eps)?; vetta_infer_hip::rms_norm_f32(&in1, Some(&w.attn_norm), &in1, 1, h as i32, d.eps)?; vetta_infer_hip::rms_norm_f32(&in2, Some(&w.attn_norm), &in2, 1, h as i32, d.eps)?; let in1_bf = DeviceBuf::alloc(h * 2)?; vetta_infer_hip::cast_f32_bf16(&in1, &in1_bf, h)?; let in2_bf = DeviceBuf::alloc(h * 2)?; vetta_infer_hip::cast_f32_bf16(&in2, &in2_bf, h)?; vetta_infer_hip::cast_f32_bf16(&base, &in0_bf, h)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wq, &q, 1, q_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in1_bf, &w.wk, &k_raw, 1, kv_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in2_bf, &w.wv, &v_raw, 1, kv_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wr, &r_raw, 1, (d.n_head * d.d_rel) as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wg, &gatea, 1, q_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.ws, &sinks, 1, d.n_head as i32, h as i32)?; } else { let in0 = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::rms_norm_f32(&base, Some(&w.attn_norm), &in0, 1, h as i32, d.eps)?; vetta_infer_hip::cast_f32_bf16(&in0, &in0_bf, h)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wq, &q, 1, q_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wk, &k_raw, 1, kv_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wv, &v_raw, 1, kv_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wr, &r_raw, 1, (d.n_head * d.d_rel) as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wg, &gatea, 1, q_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.ws, &sinks, 1, d.n_head as i32, h as i32)?; } vetta_infer_hip::shortconv4_decode(&k_raw, &w.k_sconv, &st.hist_k[pass], &k_cv, &slot0, 1, kv_dim as i32)?; vetta_infer_hip::shortconv4_decode(&v_raw, &w.v_sconv, &st.hist_v[pass], &v_cv, &slot0, 1, kv_dim as i32)?; vetta_infer_hip::l2_clip(&q, Some(&w.q_sc), d.n_head as i32, d.hd as i32, d.qk_clip, false, pos)?; vetta_infer_hip::l2_clip(&r_raw, Some(&w.r_sc), d.n_head as i32, d.d_rel as i32, d.rel_clip, false, pos)?; vetta_infer_hip::l2_clip(&k_cv, None, d.n_kv as i32, d.hd as i32, d.qk_clip, false, pos)?; let lim = (pos + 1).min(d.rel_extent as i32); vetta_infer_hip::relpos_bias(&r_raw, &w.rel_proj, &rel_bias, d.n_head as i32, d.d_rel as i32, d.rel_extent as i32, lim)?; if f16_kv() { vetta_infer_hip::kv_store_f16(&k_cv, &v_cv, &st.k_cache[pass], &st.v_cache[pass], pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps)?; } else { vetta_infer_hip::kv_store(&k_cv, &v_cv, &st.k_cache[pass], &st.v_cache[pass], pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps)?; } if w.ip == 0 || (w.ip == 6 && pass == 1) { dbg_norm("q", &q, q_dim); dbg_norm("k_cv", &k_cv, kv_dim); dbg_norm("v_cv", &v_cv, kv_dim); dbg_norm("r_raw", &r_raw, d.n_head * d.d_rel); } // k3: flash SWA GQA. if f16_kv() { vetta_infer_hip::flash_swa_gqa_decode_f16(&q, &st.k_cache[pass], &st.v_cache[pass], &aout, d.n_head as i32, d.n_kv as i32, st.max_seq as i32, d.hd as i32, d.scale(), d.swa_win, pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea))?; } else { vetta_infer_hip::flash_swa_gqa_decode(&q, &st.k_cache[pass], &st.v_cache[pass], &aout, d.n_head as i32, d.n_kv as i32, st.max_seq as i32, d.hd as i32, d.scale(), d.swa_win, pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea))?; } if w.ip == 0 || (w.ip == 6 && pass == 1) { dbg_norm("aout", &aout, q_dim); dbg_norm("sinks", &sinks, d.n_head); dbg_norm("gatea", &gatea, q_dim); } // k4: O-proj + attn shortconv + block boundary. vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, q_dim)?; vetta_infer_hip::gemm_bf16(&aout_bf, &w.wo, &oproj, 1, h as i32, q_dim as i32)?; vetta_infer_hip::shortconv4_decode(&oproj, &w.a_sconv, &st.hist_a[pass], &asc, &slot0, 1, h as i32)?; if w.ip % d.block_size == 0 { let mut cur_h = vec![0f32; h]; cur.d2h(&mut cur_h)?; let snap = DeviceBuf::alloc(h * 4)?; snap.h2d(&cur_h)?; blocks.push(snap); let mut asc_h = vec![0f32; h]; asc.d2h(&mut asc_h)?; cur.h2d(&asc_h)?; } else { vetta_infer_hip::vec_add(cur, &asc, cur, h)?; } if w.ip == 0 || (w.ip == 6 && pass == 1) { dbg_norm("cur_after_attn", cur, h); dbg_norm("asc", &asc, h); } // k5: MoE input = mlp_norm(mix(blocks, cur, mlp_query)). let n_blocks = blocks.len(); let blk = DeviceBuf::alloc(n_blocks.max(1) * h * 4)?; let mut bh = vec![0f32; n_blocks.max(1) * h]; for (i, b) in blocks.iter().enumerate() { b.d2h(&mut bh[i * h..(i + 1) * h])?; } blk.h2d(&bh)?; let mix = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::attn_res_mix(&blk, cur, &w.mlp_query, &mix, n_blocks as i32, 1, 1, h as i32, d.eps)?; // Exact strata order: the mlp loop controller gates the RAW depth-mix // BEFORE mlp_norm (run_attnres -> run_loop_ctrl(mlpin,3) -> k_rms_norm_rows). if let Some((cw, msgs)) = ctrl { apply_controller(&mix, &msgs.channel(3, h)?, cw, 3, h, 64, d.eps)?; } let mlpin = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::rms_norm_f32(&mix, Some(&w.mlp_norm), &mlpin, 1, h as i32, d.eps)?; if w.ip == 0 || (w.ip == 6 && pass == 1) { dbg_norm("mlpin", &mlpin, h); dbg_norm("moe_mix", &mix, h); } // k6: router + experts + reduce. Router reads F32 mlpin (exact strata B=1 // launch_f32_linear); bf16-rounding the router input flips top-k selection. let rlog = DeviceBuf::alloc(d.n_experts * 4)?; vetta_infer_hip::router_gemv(&mlpin, &w.gate_w, &rlog, d.n_experts as i32, h as i32)?; let ids = DeviceBuf::alloc(d.top_k * 4)?; let weights = DeviceBuf::alloc(d.top_k * 4)?; vetta_infer_hip::moe_router_topk(&rlog, Some(&w.gate_b), &ids, &weights, 1, d.n_experts as i32, d.top_k as i32, d.route_scale)?; let moeout = if std::env::var("VETTA_DEVICE_MOE").is_ok() { // Device-resident MoE: ids/weights stay on device, arena indirect GEMV, // no host round-trip (graph-capturable). f16 path, bit-identical math. moe_device(cache, w.ip, &mlpin, &ids, &weights, d, h)? } else { let ids_h = { let mut b = vec![0u8; d.top_k * 4]; ids.d2h_bytes(&mut b)?; b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::>() }; if std::env::var("VETTA_DBG_IDS").is_ok() { eprintln!("[dbg] ip={} GPU experts={:?}", w.ip, ids_h); } let y_part_h = run_experts(cache, w.ip, &ids_h, &mlpin, d, h)?; let y_part = DeviceBuf::alloc(d.top_k * h * 4)?; y_part.h2d(&y_part_h)?; let moeout = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::moe_reduce(&y_part, &weights, &moeout, d.top_k as i32, h as i32)?; if w.ip == 0 || (w.ip == 6 && pass == 1) { dbg_norm("y_part", &y_part, d.top_k * h); dbg_norm("moeout", &moeout, h); } moeout }; // k7: mlp shortconv + plain residual add. let msc = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::shortconv4_decode(&moeout, &w.m_sconv, &st.hist_m[pass], &msc, &slot0, 1, h as i32)?; vetta_infer_hip::vec_add(cur, &msc, cur, h)?; Ok(()) } /// Batched SWA layer (M=B prefill): mirrors layer_forward_swa with every kernel /// at M=B. cur [B,h] in place; blocks is the device-resident arena; pos [B] device /// (per-token causal positions), max_pos = largest pos. ctrl msgs is [B*4,h] device /// (attn_res_mix output); channels gathered strided. KV cache filled for all B /// positions before the causal flash reads. ShortConv uses prefill_par + update_hist. #[allow(dead_code)] // wired by forward_batch (next brick) fn layer_forward_swa_batched( cache: &WeightCache, w: &LayerWeights, st: &mut LayerState, d: &Dims, cur: &DeviceBuf, blocks: &mut BatchBlocks, pos: &DeviceBuf, max_pos: i32, pass: usize, b: i32, ctrl: Option<(&ControllerWeights, &DeviceBuf)>, ) -> Result<(), String> { let h = d.hidden; let kv_dim = d.kv_dim(); let q_dim = d.q_dim(); let bu = b as usize; let k_cv = DeviceBuf::alloc(bu * kv_dim * 4)?; let v_cv = DeviceBuf::alloc(bu * kv_dim * 4)?; let rel_bias = DeviceBuf::alloc(bu * d.n_head * d.rel_extent * 4)?; // kernel writes all rel_extent (0.0f beyond lim): no sync host zero-fill let aout = DeviceBuf::alloc(bu * q_dim * 4)?; let aout_bf = DeviceBuf::alloc(bu * q_dim * 2)?; let oproj = DeviceBuf::alloc(bu * h * 4)?; let asc = DeviceBuf::alloc(bu * h * 4)?; // k1: attention input base. let base = DeviceBuf::alloc(bu * h * 4)?; if w.ip == 0 { vetta_infer_hip::copy_f32(cur, &base, bu * h)?; } else { let aq = w.attn_query.as_ref().ok_or("ip>0 needs attn_query")?; vetta_infer_hip::attn_res_mix(&blocks.arena, cur, aq, &base, blocks.count as i32, b, 1, h as i32, d.eps)?; } let q = DeviceBuf::alloc(bu * q_dim * 4)?; let k_raw = DeviceBuf::alloc(bu * kv_dim * 4)?; let v_raw = DeviceBuf::alloc(bu * kv_dim * 4)?; let r_raw = DeviceBuf::alloc(bu * d.n_head * d.d_rel * 4)?; let gatea = DeviceBuf::alloc(bu * q_dim * 4)?; let sinks = DeviceBuf::alloc(bu * d.n_head * 4)?; let in0_bf = DeviceBuf::alloc(bu * h * 2)?; if let Some((cw, msgs)) = ctrl { let in1 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::copy_f32(&base, &in1, bu * h)?; let in2 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::copy_f32(&base, &in2, bu * h)?; let msg0 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(msgs, &msg0, 0, b, h as i32, 4)?; let msg1 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(msgs, &msg1, 1, b, h as i32, 4)?; let msg2 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(msgs, &msg2, 2, b, h as i32, 4)?; apply_controller_batched(&base, &msg0, cw, 0, h, 64, d.eps, b)?; apply_controller_batched(&in1, &msg1, cw, 1, h, 64, d.eps, b)?; apply_controller_batched(&in2, &msg2, cw, 2, h, 64, d.eps, b)?; vetta_infer_hip::rms_norm_f32(&base, Some(&w.attn_norm), &base, b, h as i32, d.eps)?; vetta_infer_hip::rms_norm_f32(&in1, Some(&w.attn_norm), &in1, b, h as i32, d.eps)?; vetta_infer_hip::rms_norm_f32(&in2, Some(&w.attn_norm), &in2, b, h as i32, d.eps)?; let in1_bf = DeviceBuf::alloc(bu * h * 2)?; vetta_infer_hip::cast_f32_bf16(&in1, &in1_bf, bu * h)?; let in2_bf = DeviceBuf::alloc(bu * h * 2)?; vetta_infer_hip::cast_f32_bf16(&in2, &in2_bf, bu * h)?; vetta_infer_hip::cast_f32_bf16(&base, &in0_bf, bu * h)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wq, &q, b, q_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in1_bf, &w.wk, &k_raw, b, kv_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in2_bf, &w.wv, &v_raw, b, kv_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wr, &r_raw, b, (d.n_head * d.d_rel) as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wg, &gatea, b, q_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.ws, &sinks, b, d.n_head as i32, h as i32)?; } else { let in0 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::rms_norm_f32(&base, Some(&w.attn_norm), &in0, b, h as i32, d.eps)?; vetta_infer_hip::cast_f32_bf16(&in0, &in0_bf, bu * h)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wq, &q, b, q_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wk, &k_raw, b, kv_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wv, &v_raw, b, kv_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wr, &r_raw, b, (d.n_head * d.d_rel) as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wg, &gatea, b, q_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.ws, &sinks, b, d.n_head as i32, h as i32)?; } // k2: ShortConv prefill (parallel causal) + history roll, then clip/relpos/KV. vetta_infer_hip::shortconv4_prefill_par(&k_raw, &w.k_sconv, None, &st.hist_k[pass], &k_cv, b, kv_dim as i32, 0)?; vetta_infer_hip::shortconv4_update_hist(&k_raw, &st.hist_k[pass], b, kv_dim as i32)?; vetta_infer_hip::shortconv4_prefill_par(&v_raw, &w.v_sconv, None, &st.hist_v[pass], &v_cv, b, kv_dim as i32, 0)?; vetta_infer_hip::shortconv4_update_hist(&v_raw, &st.hist_v[pass], b, kv_dim as i32)?; vetta_infer_hip::l2_clip_batched(&q, Some(&w.q_sc), (b as usize * d.n_head) as i32, d.hd as i32, d.qk_clip, false, 0, d.n_head as i32, None)?; vetta_infer_hip::l2_clip_batched(&r_raw, Some(&w.r_sc), (b as usize * d.n_head) as i32, d.d_rel as i32, d.rel_clip, false, 0, d.n_head as i32, None)?; vetta_infer_hip::l2_clip_batched(&k_cv, None, (b as usize * d.n_kv) as i32, d.hd as i32, d.qk_clip, false, 0, d.n_kv as i32, None)?; vetta_infer_hip::relpos_bias_batched(&r_raw, &w.rel_proj, &rel_bias, pos, d.n_head as i32, d.d_rel as i32, d.rel_extent as i32, b)?; vetta_infer_hip::kv_store_f16_batched(&k_cv, &v_cv, &st.k_cache[pass], &st.v_cache[pass], pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps, b)?; // k3: causal flash SWA GQA (M=B). vetta_infer_hip::flash_swa_gqa_prefill_f16(&q, &st.k_cache[pass], &st.v_cache[pass], &aout, d.n_head as i32, d.n_kv as i32, st.max_seq as i32, d.hd as i32, d.scale(), d.swa_win, pos, max_pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea), b)?; // k4: O-proj + attn shortconv + block boundary. vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, bu * q_dim)?; vetta_infer_hip::gemm_bf16(&aout_bf, &w.wo, &oproj, b, h as i32, q_dim as i32)?; vetta_infer_hip::shortconv4_prefill_par(&oproj, &w.a_sconv, None, &st.hist_a[pass], &asc, b, h as i32, 0)?; vetta_infer_hip::shortconv4_update_hist(&oproj, &st.hist_a[pass], b, h as i32)?; if w.ip % d.block_size == 0 { blocks.snapshot(cur)?; vetta_infer_hip::copy_f32(&asc, cur, bu * h)?; } else { vetta_infer_hip::vec_add(cur, &asc, cur, bu * h)?; } // k5: MoE input = mlp_norm(mix(blocks, cur, mlp_query)). let mix = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::attn_res_mix(&blocks.arena, cur, &w.mlp_query, &mix, blocks.count as i32, b, 1, h as i32, d.eps)?; if let Some((cw, msgs)) = ctrl { let msg3 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(msgs, &msg3, 3, b, h as i32, 4)?; apply_controller_batched(&mix, &msg3, cw, 3, h, 64, d.eps, b)?; } let mlpin = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::rms_norm_f32(&mix, Some(&w.mlp_norm), &mlpin, b, h as i32, d.eps)?; // k6: batched router + batched MoE. let rlog = DeviceBuf::alloc(bu * d.n_experts * 4)?; vetta_infer_hip::router_gemv_batched(&mlpin, &w.gate_w, &rlog, d.n_experts as i32, h as i32, b)?; let ids = DeviceBuf::alloc(bu * d.top_k * 4)?; let weights = DeviceBuf::alloc(bu * d.top_k * 4)?; vetta_infer_hip::moe_router_topk(&rlog, Some(&w.gate_b), &ids, &weights, b, d.n_experts as i32, d.top_k as i32, d.route_scale)?; let moeout = moe_batched(cache, w.ip, &mlpin, &ids, &weights, d, h, b)?; // k7: mlp shortconv + plain residual add. let msc = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::shortconv4_prefill_par(&moeout, &w.m_sconv, None, &st.hist_m[pass], &msc, b, h as i32, 0)?; vetta_infer_hip::shortconv4_update_hist(&moeout, &st.hist_m[pass], b, h as i32)?; vetta_infer_hip::vec_add(cur, &msc, cur, bu * h)?; Ok(()) } /// Embed a single token id from the real BF16 embed table -> f32 cur [hidden]. /// Exact strata k_embed_lookup: gather the row THEN RMS-normalize it with /// embed_norm.weight (the embed lookup fuses gather + norm). pub fn embed_token(cache: &WeightCache, token: i32, hidden: usize, vocab: usize) -> Result { let table = cache.raw("model.llm.embed.weight")?; let tok = DeviceBuf::alloc(4)?; tok.h2d_bytes(&token.to_le_bytes())?; let cur = DeviceBuf::alloc(hidden * 4)?; vetta_infer_hip::embed_bf16_gather(&table, &tok, &cur, 1, hidden as i32, vocab as i32)?; let emb_norm = cache.bf16_f32("model.llm.embed_norm.weight")?; vetta_infer_hip::rms_norm_f32(&cur, Some(&emb_norm), &cur, 1, hidden as i32, 1e-6)?; Ok(cur) } /// Final norm + cast + unembed GEMM -> f32 logits [vocab]. pub fn unembed_logits(cache: &WeightCache, cur: &DeviceBuf, hidden: usize, vocab: usize, eps: f32) -> Result { let norm = cache.bf16_f32("model.llm.norm.weight")?; let unembed = cache.raw("model.llm.unembed.weight")?; let n = DeviceBuf::alloc(hidden * 4)?; vetta_infer_hip::rms_norm_f32(cur, Some(&norm), &n, 1, hidden as i32, eps)?; let nb = DeviceBuf::alloc(hidden * 2)?; vetta_infer_hip::cast_f32_bf16(&n, &nb, hidden)?; let logits = DeviceBuf::alloc(vocab * 4)?; vetta_infer_hip::gemm_bf16(&nb, &unembed, &logits, 1, vocab as i32, hidden as i32)?; Ok(logits) } /// Correct final output path: the final norm is itself an AttnRes depth mix /// (output_query over blocks + cur), then norm + unembed + logit softcap. /// h_norm = norm(attn_res_mix(blocks, cur, output_query)); logits = softcap(unembed(h_norm)). pub fn final_logits(cache: &WeightCache, cur: &DeviceBuf, blocks: &[DeviceBuf], hidden: usize, vocab: usize, eps: f32, cap: f32) -> Result { let oq = cache.raw("model.llm.attn_res.output_query")?; let n_blocks = blocks.len(); let blk = DeviceBuf::alloc(n_blocks.max(1) * hidden * 4)?; let mut bh = vec![0f32; n_blocks.max(1) * hidden]; for (i, b) in blocks.iter().enumerate() { b.d2h(&mut bh[i * hidden..(i + 1) * hidden])?; } blk.h2d(&bh)?; let mix = DeviceBuf::alloc(hidden * 4)?; vetta_infer_hip::attn_res_mix(&blk, cur, &oq, &mix, n_blocks as i32, 1, 1, hidden as i32, eps)?; let logits = unembed_logits(cache, &mix, hidden, vocab, eps)?; if cap > 0.0 { vetta_infer_hip::softcap(&logits, &logits, vocab, cap)?; } Ok(logits) } /// Run a schedule of SWA layer steps over an embedded token, returning the /// final residual stream + the accumulated depth-block snapshots. (Prelude / /// single-pass; full-attn layers + loop controllers + bank rollback come next.) pub fn forward_swa_layers( cache: &WeightCache, schedule: &[usize], d: &Dims, token: i32, _max_seq: usize, pos: i32, ) -> Result<(DeviceBuf, Vec), String> { let cur = embed_token(cache, token, d.hidden, /*vocab*/ 201024)?; let mut blocks: Vec = Vec::new(); for &ip in schedule { let w = cache.swa_layer(ip)?; let mut st = new_state(d, swa_ring(d), 1)?; layer_forward_swa(cache, &w, &mut st, d, &cur, &mut blocks, pos, 0, None)?; } Ok((cur, blocks)) } /// Full-attention physical layers (the rest are sliding-window). pub fn is_swa(ip: usize) -> bool { !matches!(ip, 5 | 11 | 17 | 23) } /// Max batched-prefill chunk the SWA ring is sized for. The ring invariant /// (proofs/prefix_cache.lean Part E `ring_no_clobber`) requires /// `ring >= swa_win + chunk`; serve clamps the chunk to this cap. pub const SWA_CHUNK_CAP: usize = 512; /// Circular KV capacity of a SWA pool: `swa_win + SWA_CHUNK_CAP` positions instead /// of the whole context (the causal window never reads older rows). Global pools /// keep a linear `max_context` cache. Sized once, never resized across requests. pub fn swa_ring(d: &Dims) -> usize { d.swa_win.max(0) as usize + SWA_CHUNK_CAP } /// Build the stacked cross-pass msg_queries [4, hidden] for a core layer ip: /// [q_cp[2i], kv_cp[2i], kv_cp[2i+1], q_cp[2i+1]] with i = ip - core_start. fn load_msg_queries(cache: &WeightCache, ip: usize, hidden: usize) -> Result { let i = ip - 6; let q_cp = cache.raw("model.llm.middle_cycle_cross_pass_queries")?; let kv_cp = cache.raw("model.llm.middle_cycle_cross_pass_kv_queries")?; let mut qh = vec![0f32; 24 * hidden]; q_cp.d2h(&mut qh)?; let mut kh = vec![0f32; 24 * hidden]; kv_cp.d2h(&mut kh)?; let mut mq = vec![0f32; 4 * hidden]; mq[0..hidden].copy_from_slice(&qh[(2 * i) * hidden..(2 * i + 1) * hidden]); mq[hidden..2 * hidden].copy_from_slice(&kh[(2 * i) * hidden..(2 * i + 1) * hidden]); mq[2 * hidden..3 * hidden].copy_from_slice(&kh[(2 * i + 1) * hidden..(2 * i + 2) * hidden]); mq[3 * hidden..4 * hidden].copy_from_slice(&qh[(2 * i + 1) * hidden..(2 * i + 2) * hidden]); let buf = DeviceBuf::alloc(4 * hidden * 4)?; buf.h2d(&mq)?; Ok(buf) } /// Gated per-tensor L2-norm dump for reference bisection (VETTA_DBG_NORM=1). fn dbg_norm(name: &str, buf: &DeviceBuf, n: usize) { if std::env::var("VETTA_DBG_NORM").is_err() { return; } let mut h = vec![0f32; n]; buf.d2h(&mut h).unwrap(); let ss = h.iter().map(|v| v * v).sum::().sqrt(); eprintln!("[NORM] v0 {name} norm={ss:.6} h0={:.6} h1={:.6}", h[0], h[1]); } /// Run the top-k experts for one MoE block: w13 GEMV -> SiTU -> w2 GEMV per /// expert, returning the stacked per-expert outputs y_part [top_k, hidden]. /// /// Default is the all-f32 path (the verified parity baseline). The exact strata /// B=1 FP16 path (mlpin cast to FP16, w13 GEMV reads FP16, SiTU stored FP16, w2 /// reads FP16) is available via VETTA_F16_EXPERT=1. MEASURED: switching to FP16 /// shifts tok100 logits by ~0.01 but does NOT flip the near-tie argmax (220 vs /// ref 68014) — the residual gap is the core-loop pass 1/2, not expert precision. fn run_experts( cache: &WeightCache, ip: usize, ids_h: &[i32], mlpin: &DeviceBuf, d: &Dims, h: usize, ) -> Result, String> { let t0 = std::time::Instant::now(); let gu = DeviceBuf::alloc(2 * d.inter * 4)?; let mut y_part_h = vec![0f32; d.top_k * h]; if std::env::var("VETTA_F16_EXPERT").is_ok() { let mlpin16 = DeviceBuf::alloc(h * 2)?; vetta_infer_hip::cast_f32_f16(mlpin, &mlpin16, h)?; let act16 = DeviceBuf::alloc(d.inter * 2)?; for kk in 0..d.top_k { let e = ids_h[kk] as usize; let w13 = cache.expert(ip, e, "w13")?; expert_gemv_f16(&w13, &mlpin16, &gu)?; vetta_infer_hip::situ_f16(&gu, &act16, d.inter as i32, d.beta, d.lb)?; let w2 = cache.expert(ip, e, "w2")?; let ye = DeviceBuf::alloc(h * 4)?; expert_gemv_f16(&w2, &act16, &ye)?; ye.d2h(&mut y_part_h[kk * h..(kk + 1) * h])?; } } else { let act = DeviceBuf::alloc(d.inter * 4)?; for kk in 0..d.top_k { let e = ids_h[kk] as usize; let w13 = cache.expert(ip, e, "w13")?; expert_gemv(&w13, mlpin, &gu)?; vetta_infer_hip::situ(&gu, &act, d.inter as i32, d.beta, d.lb)?; let w2 = cache.expert(ip, e, "w2")?; let ye = DeviceBuf::alloc(h * 4)?; expert_gemv(&w2, &act, &ye)?; ye.d2h(&mut y_part_h[kk * h..(kk + 1) * h])?; } } EXPERT_NS.with(|c| c.set(c.get() + t0.elapsed().as_nanos())); Ok(y_part_h) } /// Device-resident MoE (graph-capturable): expert ids/weights stay on device, /// the arena indirect GEMV selects experts on device, and the per-expert outputs /// accumulate in a device `y_part` (static y_offset = kk*hidden). NO host ids or /// output round-trip. f16 activations (exact strata B=1 path); bit-identical to /// the VETTA_F16_EXPERT host path (same kernels, same data). Returns moeout [h]. fn moe_device( cache: &WeightCache, ip: usize, mlpin: &DeviceBuf, ids: &DeviceBuf, weights: &DeviceBuf, d: &Dims, h: usize, ) -> Result { let t0 = std::time::Instant::now(); let w13 = cache.expert_arena(ip, "w13")?; let w2 = cache.expert_arena(ip, "w2")?; let mlpin16 = DeviceBuf::alloc(h * 2)?; vetta_infer_hip::cast_f32_f16(mlpin, &mlpin16, h)?; let gu = DeviceBuf::alloc(2 * d.inter * 4)?; let act16 = DeviceBuf::alloc(d.inter * 2)?; let y_part = DeviceBuf::alloc(d.top_k * h * 4)?; for kk in 0..d.top_k { expert_arena_gemv_f16(&w13, ids, kk as i32, &mlpin16, &gu, 0)?; vetta_infer_hip::situ_f16(&gu, &act16, d.inter as i32, d.beta, d.lb)?; expert_arena_gemv_f16(&w2, ids, kk as i32, &act16, &y_part, (kk * h) as i64)?; } let moeout = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::moe_reduce(&y_part, weights, &moeout, d.top_k as i32, h as i32)?; EXPERT_NS.with(|c| c.set(c.get() + t0.elapsed().as_nanos())); Ok(moeout) } /// Batched device-resident MoE (M=B prefill): bucket CSR -> grouped w13 GEMM -> /// SiTU batched -> grouped w2 GEMM -> reduce_buckets_masked. All device-side, no /// host ids/output round-trip. `mlpin` [B,h] f32 (cast to f16 internally, exact /// strata B=1 path); `ids`/`weights` [B*top_k] device (from batched router). /// Returns moeout [B,h]. w2 reads SiTU output in bucket order via an identity index. #[allow(dead_code)] // wired by the batched layer forward (next brick) fn moe_batched( cache: &WeightCache, ip: usize, mlpin: &DeviceBuf, ids: &DeviceBuf, weights: &DeviceBuf, d: &Dims, h: usize, b: i32, ) -> Result { let t0 = std::time::Instant::now(); let prof = std::env::var("VETTA_PROF").is_ok(); if prof { vetta_infer_hip::synchronize()?; } // isolate real MoE GPU time (drain prior work) let w13 = cache.expert_arena(ip, "w13")?; let w2 = cache.expert_arena(ip, "w2")?; let top_k = d.top_k; let inter = d.inter; let total = (b as usize) * top_k; let mlpin16 = DeviceBuf::alloc((b as usize) * h * 2)?; vetta_infer_hip::cast_f32_f16(mlpin, &mlpin16, (b as usize) * h)?; // Bucket CSR (device-side). let dcnt = DeviceBuf::alloc(129 * 4)?; dcnt.zero_async()?; let doff = DeviceBuf::alloc(129 * 4)?; let dcur = DeviceBuf::alloc(128 * 4)?; let dbtk = DeviceBuf::alloc(total * 4)?; let ds2b = DeviceBuf::alloc(total * 4)?; vetta_infer_hip::moe_count_buckets(ids, &dcnt, total as i32)?; vetta_infer_hip::moe_prefix_buckets(&dcnt, &doff, &dcur)?; vetta_infer_hip::moe_scatter_buckets(ids, &dcur, &dbtk, &ds2b, total as i32, top_k as i32)?; // w13 grouped GEMM: gather input tokens via bucket_tok -> gu [total, 2*inter]. let gu = DeviceBuf::alloc(total * 2 * inter * 4)?; expert_arena_grouped_gemv_f16(&w13, &doff, Some(&dbtk), &mlpin16, &gu)?; let act16 = DeviceBuf::alloc(total * inter * 2)?; vetta_infer_hip::situ_f16_batched(&gu, &act16, inter as i32, d.beta, d.lb, total as i32)?; // w2 grouped GEMM: SiTU output is already bucket-ordered -> identity index // (bucket_tok=None reads tok = beg+t0+m in-kernel; no host identity h2d sync). let y_part = DeviceBuf::alloc(total * h * 4)?; expert_arena_grouped_gemv_f16(&w2, &doff, None, &act16, &y_part)?; // Scatter-back + weighted reduce per token. let moeout = DeviceBuf::alloc((b as usize) * h * 4)?; vetta_infer_hip::moe_reduce_buckets_masked(&y_part, &ds2b, weights, &moeout, b, top_k as i32, h as i32)?; if prof { vetta_infer_hip::synchronize()?; } EXPERT_NS.with(|c| c.set(c.get() + t0.elapsed().as_nanos())); Ok(moeout) } /// Run one physical layer step (SWA or full-attn dispatch), reusing its /// persistent state (KV cache + shortconv history) across loop passes. fn run_layer( cache: &WeightCache, d: &Dims, ip: usize, cur: &DeviceBuf, blocks: &mut Vec, states: &mut [Option], max_seq: usize, pos: i32, pass: usize, ctrl: Option<(&ControllerWeights, &LoopMsgs)>, ) -> Result<(), String> { if states[ip].is_none() { // Core layers run 3 loop passes (3 distinct KV pools); prelude/coda run 1. let n_passes = if (6..18).contains(&ip) { 3 } else { 1 }; states[ip] = Some(new_state(d, if is_swa(ip) { swa_ring(d) } else { max_seq }, n_passes)?); } let st = states[ip].as_mut().unwrap(); let r = if is_swa(ip) { let w = cache.swa_layer(ip)?; layer_forward_swa(cache, &w, st, d, cur, blocks, pos, pass, ctrl) } else { let w = cache.full_layer(ip, d)?; layer_forward_full(cache, &w, st, d, cur, blocks, pos, pass, ctrl) }; if std::env::var("VETTA_DBG_NORM").is_ok() { let visit = if ip < 6 { ip } else if ip < 18 { 6 + pass * 12 + (ip - 6) } else { 42 + (ip - 18) }; let mut ch = vec![0f32; d.hidden]; cur.d2h(&mut ch).unwrap(); let n = ch.iter().map(|v| v * v).sum::().sqrt(); eprintln!("[NORM] visit={visit} ip={ip} norm={n:.6} v0={:.6} v1={:.6} v2={:.6}", ch[0], ch[1], ch[2]); } r } /// Full Inkling-2-Mini forward for one decode token, following the proven /// schedule (proofs/inkling_loop.lean): prelude [0,6) -> core [6,18) x3 passes /// (bank rollback + cross-pass msgs + controllers on passes 1,2) -> coda /// [18,24) -> final depth mix + unembed + softcap. Returns logits [vocab]. pub fn forward_inkling( cache: &WeightCache, d: &Dims, token: i32, vocab: usize, max_seq: usize, pos: i32, cap: f32, ) -> Result { let mut states: Vec> = (0..24).map(|_| None).collect(); forward_inkling_with_state(cache, d, token, vocab, max_seq, pos, cap, &mut states) } /// Stateful variant: `states` holds the persistent per-layer KV cache + shortconv /// history across decode positions (autoregressive generation). The depth-block /// snapshots reset each forward; the KV/history evolve token by token. pub fn forward_inkling_with_state( cache: &WeightCache, d: &Dims, token: i32, vocab: usize, max_seq: usize, pos: i32, cap: f32, states: &mut [Option], ) -> Result { let h = d.hidden; let prof = std::env::var("VETTA_PROF").is_ok(); let tp0 = std::time::Instant::now(); let cur = embed_token(cache, token, h, vocab)?; let t_embed = tp0.elapsed().as_nanos(); if std::env::var("VETTA_DBG_NORM").is_ok() { let mut eh = vec![0f32; h]; cur.d2h(&mut eh).unwrap(); let n = eh.iter().map(|v| v * v).sum::().sqrt(); eprintln!("[NORM] embed token={token} norm={n:.6} v0={:.6} v1={:.6} v2={:.6}", eh[0], eh[1], eh[2]); } let mut blocks: Vec = Vec::new(); // Prelude. let tp1 = std::time::Instant::now(); for ip in 0..6 { run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, 0, None)?; } let t_prelude = tp1.elapsed().as_nanos(); let mut prelude = vec![0f32; h]; cur.d2h(&mut prelude)?; let n_prelude_blocks = blocks.len(); if std::env::var("VETTA_DBG_NORM").is_ok() { let n = prelude.iter().map(|v| v * v).sum::().sqrt(); eprintln!("[dbg] after prelude: cur_norm={n:.3} blocks={}", blocks.len()); } // Core: 3 passes. let tp2 = std::time::Instant::now(); for p in 0..3 { let mut bank: Vec = Vec::new(); let bank_out = DeviceBuf::alloc(h * 4)?; if p > 0 { // bank = core block snapshots of the previous pass (skip the first). for k in (n_prelude_blocks + 1)..blocks.len() { let mut bh = vec![0f32; h]; blocks[k].d2h(&mut bh)?; let snap = DeviceBuf::alloc(h * 4)?; snap.h2d(&bh)?; bank.push(snap); } let mut co = vec![0f32; h]; cur.d2h(&mut co)?; bank_out.h2d(&co)?; cur.h2d(&prelude)?; // bank rollback to prelude residual blocks.truncate(n_prelude_blocks); } for ip in 6..18 { if p > 0 && std::env::var("VETTA_NO_CTRL").is_err() { let mq = cache.msg_queries(ip, h)?; let n_bank = bank.len(); let blk = DeviceBuf::alloc(n_bank.max(1) * h * 4)?; let mut bh = vec![0f32; n_bank.max(1) * h]; for (i, b) in bank.iter().enumerate() { b.d2h(&mut bh[i * h..(i + 1) * h])?; } blk.h2d(&bh)?; let msgs_buf = DeviceBuf::alloc(4 * h * 4)?; vetta_infer_hip::attn_res_mix(&blk, &bank_out, &mq, &msgs_buf, n_bank as i32, 1, 4, h as i32, d.eps)?; let msgs = LoopMsgs(msgs_buf); let cw = cache.controllers(ip)?; run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, p, Some((&cw, &msgs)))?; } else { run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, p, None)?; } } } // Coda. let t_core = tp2.elapsed().as_nanos(); let tp3 = std::time::Instant::now(); for ip in 18..24 { run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, 0, None)?; } let t_coda = tp3.elapsed().as_nanos(); if std::env::var("VETTA_DBG_NORM").is_ok() { let mut ch = vec![0f32; h]; cur.d2h(&mut ch).unwrap(); let n = ch.iter().map(|v| v * v).sum::().sqrt(); eprintln!("[dbg] after coda: cur_norm={n:.3} blocks={}", blocks.len()); for (i, b) in blocks.iter().enumerate() { let mut bh = vec![0f32; h]; b.d2h(&mut bh).unwrap(); let bn = bh.iter().map(|v| v * v).sum::().sqrt(); eprintln!("[dbg] block[{i}]_norm={bn:.3}"); } } let tp4 = std::time::Instant::now(); let out = final_logits(cache, &cur, &blocks, h, vocab, d.eps, cap); if prof { let t_final = tp4.elapsed().as_nanos(); let exp = EXPERT_NS.with(|c| c.replace(0)); eprintln!("[PROF] pos={pos} embed={:.2}ms prelude={:.2}ms core={:.2}ms coda={:.2}ms final={:.2}ms experts={:.2}ms total={:.2}ms", t_embed as f64 / 1e6, t_prelude as f64 / 1e6, t_core as f64 / 1e6, t_coda as f64 / 1e6, t_final as f64 / 1e6, exp as f64 / 1e6, tp0.elapsed().as_nanos() as f64 / 1e6); } out } /// Batched layer dispatcher (M=B): lazily allocates the per-layer state (core 3 /// passes, prelude/coda 1) and runs the SWA or full-attn batched layer. #[allow(dead_code)] // wired by forward_batch fn run_layer_batched( cache: &WeightCache, d: &Dims, ip: usize, cur: &DeviceBuf, blocks: &mut BatchBlocks, states: &mut [Option], max_seq: usize, pos: &DeviceBuf, max_pos: i32, pass: usize, b: i32, ctrl: Option<(&ControllerWeights, &DeviceBuf)>, ) -> Result<(), String> { if states[ip].is_none() { let n_passes = if (6..18).contains(&ip) { 3 } else { 1 }; states[ip] = Some(new_state(d, if is_swa(ip) { swa_ring(d) } else { max_seq }, n_passes)?); } let st = states[ip].as_mut().unwrap(); if is_swa(ip) { let w = cache.swa_layer(ip)?; layer_forward_swa_batched(cache, &w, st, d, cur, blocks, pos, max_pos, pass, b, ctrl) } else { let w = cache.full_layer(ip, d)?; layer_forward_full_batched(cache, &w, st, d, cur, blocks, pos, max_pos, pass, b, ctrl) } } /// Batched prefill forward (M=B): embed B tokens, run the proven schedule /// (proofs/inkling_loop.lean) prelude [0,6) -> core [6,18) x3 (bank rollback + /// cross-pass msgs + controllers on passes 1,2) -> coda [18,24) -> final depth /// mix + unembed, returning logits [vocab] for the LAST token. The depth-block /// arena is device-resident (snapshot/rollback via device copy, no host gather). /// `states` persists KV/history across the B positions (and across decode steps). #[allow(dead_code)] // wired by serve prefill (next brick) pub fn forward_batch( cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize, base_pos: i32, cap: f32, states: &mut [Option], ) -> Result { forward_batch_inner(cache, d, tokens, vocab, max_seq, base_pos, cap, states, None) } /// forward_batch + DSpark target-tap capture: visits 5/23/41 entry residual and /// visit 48 = output-normed final depth mix. `taps_out[k]` must be [B*hidden] f32. /// These feed dspark_context (the drafter's committed context) per token. pub fn forward_batch_taps( cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize, base_pos: i32, cap: f32, states: &mut [Option], taps_out: &mut [DeviceBuf; 4], ) -> Result { forward_batch_inner(cache, d, tokens, vocab, max_seq, base_pos, cap, states, Some(taps_out)) } fn forward_batch_inner( cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize, base_pos: i32, cap: f32, states: &mut [Option], mut taps: Option<&mut [DeviceBuf; 4]>, ) -> Result { let h = d.hidden; let bu = tokens.len(); if bu == 0 { return Err("forward_batch: empty tokens".into()); } let b = bu as i32; let max_pos = base_pos + b - 1; let prof = std::env::var("VETTA_PROF").is_ok(); let tp0 = std::time::Instant::now(); let gb = |x: usize| x as f64 / 1e9; if prof { eprintln!("[BPROF] B={bu} base_pos={base_pos} vram_start={:.2}GB", gb(vetta_infer_hip::vram_used())); } // Embed B tokens (gather + RMS-norm rows=B). let table = cache.raw("model.llm.embed.weight")?; let tok_bytes: Vec = tokens.iter().flat_map(|t| t.to_le_bytes()).collect(); let dtok = DeviceBuf::alloc(bu * 4)?; dtok.h2d_bytes(&tok_bytes)?; let cur = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::embed_bf16_gather(&table, &dtok, &cur, b, h as i32, vocab as i32)?; let emb_norm = cache.bf16_f32("model.llm.embed_norm.weight")?; vetta_infer_hip::rms_norm_f32(&cur, Some(&emb_norm), &cur, b, h as i32, 1e-6)?; let pos: Vec = (0..bu).map(|m| base_pos + m as i32).collect(); let pos_bytes: Vec = pos.iter().flat_map(|p| p.to_le_bytes()).collect(); let dpos = DeviceBuf::alloc(bu * 4)?; dpos.h2d_bytes(&pos_bytes)?; let mut blocks = BatchBlocks::new(bu, h, 8)?; // Prelude. for ip in 0..6 { if ip == 5 { if let Some(t) = taps.as_deref_mut() { vetta_infer_hip::copy_f32(&cur, &t[0], bu * h)?; } } run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, 0, b, None)?; } if prof { vetta_infer_hip::synchronize()?; eprintln!("[BPROF] prelude {:.1}ms vram={:.2}GB", tp0.elapsed().as_secs_f64()*1e3, gb(vetta_infer_hip::vram_used())); } let n_prelude_blocks = blocks.count; let prelude = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::copy_f32(&cur, &prelude, bu * h)?; // Core: 3 passes with device-side bank rollback. let no_ctrl = std::env::var("VETTA_NO_CTRL").is_ok(); for p in 0..3 { let bank_out = DeviceBuf::alloc(bu * h * 4)?; let mut bank_buf = DeviceBuf::alloc(bu * h * 4)?; let mut n_bank = 0usize; if p > 0 { // bank = core block snapshots of the previous pass (skip the first). n_bank = blocks.count.saturating_sub(n_prelude_blocks + 1); bank_buf = DeviceBuf::alloc(n_bank.max(1) * bu * h * 4)?; if n_bank > 0 { vetta_infer_hip::copy_f32_sub(&blocks.arena, (n_prelude_blocks + 1) * bu * h, &bank_buf, n_bank * bu * h)?; } vetta_infer_hip::copy_f32(&cur, &bank_out, bu * h)?; vetta_infer_hip::copy_f32(&prelude, &cur, bu * h)?; // rollback to prelude residual blocks.truncate(n_prelude_blocks); } for ip in 6..18 { let visit = 6 + p * 12 + (ip - 6); if visit == 23 || visit == 41 { if let Some(t) = taps.as_deref_mut() { let k = if visit == 23 { 1 } else { 2 }; vetta_infer_hip::copy_f32(&cur, &t[k], bu * h)?; } } if p > 0 && !no_ctrl { let mq = cache.msg_queries(ip, h)?; let msgs_buf = DeviceBuf::alloc(bu * 4 * h * 4)?; vetta_infer_hip::attn_res_mix(&bank_buf, &bank_out, &mq, &msgs_buf, n_bank as i32, b, 4, h as i32, d.eps)?; let cw = cache.controllers(ip)?; run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, p, b, Some((&cw, &msgs_buf)))?; } else { run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, p, b, None)?; } } } // Coda. if prof { vetta_infer_hip::synchronize()?; eprintln!("[BPROF] core {:.1}ms vram={:.2}GB", tp0.elapsed().as_secs_f64()*1e3, gb(vetta_infer_hip::vram_used())); } for ip in 18..24 { run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, 0, b, None)?; } if prof { vetta_infer_hip::synchronize()?; eprintln!("[BPROF] coda {:.1}ms vram={:.2}GB", tp0.elapsed().as_secs_f64()*1e3, gb(vetta_infer_hip::vram_used())); } // Final depth mix + unembed the LAST token. let oq = cache.raw("model.llm.attn_res.output_query")?; let mix = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::attn_res_mix(&blocks.arena, &cur, &oq, &mix, blocks.count as i32, b, 1, h as i32, d.eps)?; if let Some(t) = taps.as_deref_mut() { let onorm = cache.bf16_f32("model.llm.norm.weight")?; vetta_infer_hip::rms_norm_f32(&mix, Some(&onorm), &t[3], b, h as i32, d.eps)?; } let last = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::copy_f32_sub(&mix, (bu - 1) * h, &last, h)?; let logits = unembed_logits(cache, &last, h, vocab, d.eps)?; if cap > 0.0 { vetta_infer_hip::softcap(&logits, &logits, vocab, cap)?; } if prof { vetta_infer_hip::synchronize()?; let exp = EXPERT_NS.with(|c| c.replace(0)); eprintln!("[BPROF] total {:.1}ms moe_launch={:.1}ms vram_end={:.2}GB", tp0.elapsed().as_secs_f64()*1e3, exp as f64/1e6, gb(vetta_infer_hip::vram_used())); } Ok(logits) } thread_local! { static EXPERT_NS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Load a full-attn ShortConv static weight tensor [4, C] transposed to the /// kernel's [C, 4] layout (the reference reads sw[c*4+k]). fn load_sconv_transposed(ar: &SafetensorsArchive, name: &str, c: usize) -> Result { let info = ar.tensors.get(name).ok_or_else(|| format!("missing {name}"))?; let mut b = vec![0u8; info.byte_len() as usize]; ar.read_slice(name, 0, &mut b)?; let f: Vec = b.chunks_exact(2).map(|x| f32::from_bits((u16::from_le_bytes([x[0], x[1]]) as u32) << 16)).collect(); // f is [4, C] (lag-major); the kernel reads sw[c*4 + (3-lag)] (exact strata // upload_sc: kt[c*4+(3-lag)] = kw[lag*kv_dim+c]) — tap order REVERSED. let mut t = vec![0f32; c * 4]; for lag in 0..4 { for ch in 0..c { t[ch * 4 + (3 - lag)] = f[lag * c + ch]; } } let buf = DeviceBuf::alloc(c * 4 * 4)?; buf.h2d(&t)?; Ok(buf) } /// Resident weights for a full-attention layer step (3-query mix, separate /// q/k/v input norms, dynamic ShortConv, tau, global attention). pub struct FullLayerWeights { pub ip: usize, pub q_norm: DeviceBuf, pub k_norm: DeviceBuf, pub v_norm: DeviceBuf, pub wq: DeviceBuf, pub wk: DeviceBuf, pub wv: DeviceBuf, pub wr: DeviceBuf, pub wg: DeviceBuf, pub ws: DeviceBuf, pub wo: DeviceBuf, pub q_sc: DeviceBuf, pub r_sc: DeviceBuf, pub rel_proj: DeviceBuf, pub k_static: DeviceBuf, pub v_static: DeviceBuf, pub k_proj: DeviceBuf, pub v_proj: DeviceBuf, pub a_sconv: DeviceBuf, pub mlp_norm: DeviceBuf, pub gate_w: DeviceBuf, pub gate_b: DeviceBuf, pub m_sconv: DeviceBuf, pub attn_query: DeviceBuf, // [3, hidden] pub mlp_query: DeviceBuf, } pub fn load_full_layer(ar: &SafetensorsArchive, ip: usize, d: &Dims) -> Result { let p = format!("model.llm.layers.{ip}.attn"); let l = format!("model.llm.layers.{ip}"); Ok(FullLayerWeights { ip, q_norm: load_bf16_as_f32(ar, &format!("{l}.q_input_norm.weight"))?, k_norm: load_bf16_as_f32(ar, &format!("{l}.k_input_norm.weight"))?, v_norm: load_bf16_as_f32(ar, &format!("{l}.v_input_norm.weight"))?, wq: load_raw(ar, &format!("{p}.wq_du.weight"))?, wk: load_raw(ar, &format!("{p}.wk_dv.weight"))?, wv: load_raw(ar, &format!("{p}.wv_dv.weight"))?, wr: load_raw(ar, &format!("{p}.wr_du.weight"))?, wg: load_raw(ar, &format!("{p}.gate_attn.weight"))?, ws: load_raw(ar, &format!("{p}.attn_sink_proj.weight"))?, wo: load_raw(ar, &format!("{p}.wo_ud.weight"))?, q_sc: load_bf16_as_f32(ar, &format!("{p}.q_l2_clip.scale"))?, r_sc: load_bf16_as_f32(ar, &format!("{p}.rel_l2_clip.scale"))?, rel_proj: load_bf16_as_f32(ar, &format!("{p}.rel_logits_proj.proj"))?, k_static: load_sconv_transposed(ar, &format!("{p}.k_sconv.static_w"), d.kv_dim())?, v_static: load_sconv_transposed(ar, &format!("{p}.v_sconv.static_w"), d.kv_dim())?, k_proj: load_raw(ar, &format!("{p}.k_sconv.weight_proj"))?, v_proj: load_raw(ar, &format!("{p}.v_sconv.weight_proj"))?, a_sconv: load_bf16_as_f32(ar, &format!("{l}.attn_sconv.weight"))?, mlp_norm: load_bf16_as_f32(ar, &format!("{l}.mlp_norm.weight"))?, gate_w: load_raw(ar, &format!("{l}.mlp.gate.weight"))?, gate_b: load_raw(ar, &format!("{l}.mlp.gate.bias"))?, m_sconv: load_bf16_as_f32(ar, &format!("{l}.mlp_sconv.weight"))?, attn_query: load_raw(ar, &format!("model.llm.attn_res.attn_queries.{}", ip - 1))?, mlp_query: load_raw(ar, &format!("model.llm.attn_res.mlp_queries.{ip}"))?, }) } /// Run one full-attention layer step on `cur` (in place). 3-query AttnRes mix /// split into in0/in1/in2, separate q/k/v norms, projections from distinct /// inputs, dynamic ShortConv K/V, tau on Q/R, global (window=0) flash attention. pub fn layer_forward_full( cache: &WeightCache, w: &FullLayerWeights, st: &mut LayerState, d: &Dims, cur: &DeviceBuf, blocks: &mut Vec, pos: i32, pass: usize, ctrl: Option<(&ControllerWeights, &LoopMsgs)>, ) -> Result<(), String> { let h = d.hidden; let kv_dim = d.kv_dim(); let q_dim = d.q_dim(); let slot0 = DeviceBuf::alloc(4)?; slot0.h2d_bytes(&0i32.to_le_bytes())?; // 3-query mix -> [3, h], split into in0/in1/in2. let n_blocks = blocks.len(); let blk = DeviceBuf::alloc(n_blocks.max(1) * h * 4)?; let mut bh = vec![0f32; n_blocks.max(1) * h]; for (i, b) in blocks.iter().enumerate() { b.d2h(&mut bh[i * h..(i + 1) * h])?; } blk.h2d(&bh)?; let mx3 = DeviceBuf::alloc(3 * h * 4)?; vetta_infer_hip::attn_res_mix(&blk, cur, &w.attn_query, &mx3, n_blocks as i32, 1, 3, h as i32, d.eps)?; let mut mx_h = vec![0f32; 3 * h]; mx3.d2h(&mut mx_h)?; let in0 = DeviceBuf::alloc(h * 4)?; in0.h2d(&mx_h[0..h])?; let in1 = DeviceBuf::alloc(h * 4)?; in1.h2d(&mx_h[h..2 * h])?; let in2 = DeviceBuf::alloc(h * 4)?; in2.h2d(&mx_h[2 * h..3 * h])?; if let Some((cw, msgs)) = ctrl { apply_controller(&in0, &msgs.channel(0, h)?, cw, 0, h, 64, d.eps)?; apply_controller(&in1, &msgs.channel(1, h)?, cw, 1, h, 64, d.eps)?; apply_controller(&in2, &msgs.channel(2, h)?, cw, 2, h, 64, d.eps)?; } vetta_infer_hip::rms_norm_f32(&in0, Some(&w.q_norm), &in0, 1, h as i32, d.eps)?; vetta_infer_hip::rms_norm_f32(&in1, Some(&w.k_norm), &in1, 1, h as i32, d.eps)?; vetta_infer_hip::rms_norm_f32(&in2, Some(&w.v_norm), &in2, 1, h as i32, d.eps)?; // projections: q/r/gate/sink from in0; k from in1; v from in2. let in0_bf = DeviceBuf::alloc(h * 2)?; vetta_infer_hip::cast_f32_bf16(&in0, &in0_bf, h)?; let in1_bf = DeviceBuf::alloc(h * 2)?; vetta_infer_hip::cast_f32_bf16(&in1, &in1_bf, h)?; let in2_bf = DeviceBuf::alloc(h * 2)?; vetta_infer_hip::cast_f32_bf16(&in2, &in2_bf, h)?; let q = DeviceBuf::alloc(q_dim * 4)?; let k_raw = DeviceBuf::alloc(kv_dim * 4)?; let v_raw = DeviceBuf::alloc(kv_dim * 4)?; let r_raw = DeviceBuf::alloc(d.n_head * d.d_rel * 4)?; let gatea = DeviceBuf::alloc(q_dim * 4)?; let sinks = DeviceBuf::alloc(d.n_head * 4)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wq, &q, 1, q_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in1_bf, &w.wk, &k_raw, 1, kv_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in2_bf, &w.wv, &v_raw, 1, kv_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wr, &r_raw, 1, (d.n_head * d.d_rel) as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wg, &gatea, 1, q_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.ws, &sinks, 1, d.n_head as i32, h as i32)?; // dynamic shortconv taps + dyn shortconv K/V. let k_dyn = DeviceBuf::alloc(d.n_kv * 4 * 4)?; let v_dyn = DeviceBuf::alloc(d.n_kv * 4 * 4)?; vetta_infer_hip::gemm_bf16(&in1_bf, &w.k_proj, &k_dyn, 1, (d.n_kv * 4) as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in2_bf, &w.v_proj, &v_dyn, 1, (d.n_kv * 4) as i32, h as i32)?; let k_cv = DeviceBuf::alloc(kv_dim * 4)?; let v_cv = DeviceBuf::alloc(kv_dim * 4)?; vetta_infer_hip::shortconv4_dyn_decode(&k_raw, &w.k_static, &k_dyn, &st.hist_k[pass], &k_cv, &slot0, 1, kv_dim as i32, d.n_kv as i32)?; vetta_infer_hip::shortconv4_dyn_decode(&v_raw, &w.v_static, &v_dyn, &st.hist_v[pass], &v_cv, &slot0, 1, kv_dim as i32, d.n_kv as i32)?; // tau on Q/R (full-attn), K clip without tau. vetta_infer_hip::l2_clip(&q, Some(&w.q_sc), d.n_head as i32, d.hd as i32, d.qk_clip, true, pos)?; vetta_infer_hip::l2_clip(&r_raw, Some(&w.r_sc), d.n_head as i32, d.d_rel as i32, d.rel_clip, true, pos)?; vetta_infer_hip::l2_clip(&k_cv, None, d.n_kv as i32, d.hd as i32, d.qk_clip, false, pos)?; let rel_bias = DeviceBuf::alloc(d.n_head * d.rel_extent * 4)?; // kernel writes all rel_extent (0.0f beyond lim): no sync host zero-fill let lim = (pos + 1).min(d.rel_extent as i32); vetta_infer_hip::relpos_bias(&r_raw, &w.rel_proj, &rel_bias, d.n_head as i32, d.d_rel as i32, d.rel_extent as i32, lim)?; if f16_kv() { vetta_infer_hip::kv_store_f16(&k_cv, &v_cv, &st.k_cache[pass], &st.v_cache[pass], pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps)?; } else { vetta_infer_hip::kv_store(&k_cv, &v_cv, &st.k_cache[pass], &st.v_cache[pass], pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps)?; } let aout = DeviceBuf::alloc(q_dim * 4)?; // global attention: window = 0. if f16_kv() { vetta_infer_hip::flash_swa_gqa_decode_f16(&q, &st.k_cache[pass], &st.v_cache[pass], &aout, d.n_head as i32, d.n_kv as i32, st.max_seq as i32, d.hd as i32, d.scale(), 0, pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea))?; } else { vetta_infer_hip::flash_swa_gqa_decode(&q, &st.k_cache[pass], &st.v_cache[pass], &aout, d.n_head as i32, d.n_kv as i32, st.max_seq as i32, d.hd as i32, d.scale(), 0, pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea))?; } let aout_bf = DeviceBuf::alloc(q_dim * 2)?; vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, q_dim)?; let oproj = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::gemm_bf16(&aout_bf, &w.wo, &oproj, 1, h as i32, q_dim as i32)?; let asc = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::shortconv4_decode(&oproj, &w.a_sconv, &st.hist_a[pass], &asc, &slot0, 1, h as i32)?; if w.ip % d.block_size == 0 { let mut cur_h = vec![0f32; h]; cur.d2h(&mut cur_h)?; let snap = DeviceBuf::alloc(h * 4)?; snap.h2d(&cur_h)?; blocks.push(snap); let mut asc_h = vec![0f32; h]; asc.d2h(&mut asc_h)?; cur.h2d(&asc_h)?; } else { vetta_infer_hip::vec_add(cur, &asc, cur, h)?; } // MoE sublayer (identical to SWA): mlp_norm(mix(blocks,cur,mlp_query)) -> router -> experts -> reduce -> sconv -> add. let n_blocks = blocks.len(); let blk = DeviceBuf::alloc(n_blocks.max(1) * h * 4)?; let mut bh = vec![0f32; n_blocks.max(1) * h]; for (i, b) in blocks.iter().enumerate() { b.d2h(&mut bh[i * h..(i + 1) * h])?; } blk.h2d(&bh)?; let mix = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::attn_res_mix(&blk, cur, &w.mlp_query, &mix, n_blocks as i32, 1, 1, h as i32, d.eps)?; // Exact strata order: mlp controller gates the RAW mix BEFORE mlp_norm. if let Some((cw, msgs)) = ctrl { apply_controller(&mix, &msgs.channel(3, h)?, cw, 3, h, 64, d.eps)?; } let mlpin = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::rms_norm_f32(&mix, Some(&w.mlp_norm), &mlpin, 1, h as i32, d.eps)?; let rlog = DeviceBuf::alloc(d.n_experts * 4)?; vetta_infer_hip::router_gemv(&mlpin, &w.gate_w, &rlog, d.n_experts as i32, h as i32)?; let ids = DeviceBuf::alloc(d.top_k * 4)?; let weights = DeviceBuf::alloc(d.top_k * 4)?; vetta_infer_hip::moe_router_topk(&rlog, Some(&w.gate_b), &ids, &weights, 1, d.n_experts as i32, d.top_k as i32, d.route_scale)?; let moeout = if std::env::var("VETTA_DEVICE_MOE").is_ok() { // Device-resident MoE: ids/weights stay on device, arena indirect GEMV, // no host round-trip (graph-capturable). f16 path, bit-identical math. moe_device(cache, w.ip, &mlpin, &ids, &weights, d, h)? } else { let ids_h = { let mut b = vec![0u8; d.top_k * 4]; ids.d2h_bytes(&mut b)?; b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::>() }; if std::env::var("VETTA_DBG_IDS").is_ok() { eprintln!("[dbg] ip={} GPU experts={:?}", w.ip, ids_h); } let y_part_h = run_experts(cache, w.ip, &ids_h, &mlpin, d, h)?; let y_part = DeviceBuf::alloc(d.top_k * h * 4)?; y_part.h2d(&y_part_h)?; let moeout = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::moe_reduce(&y_part, &weights, &moeout, d.top_k as i32, h as i32)?; if w.ip == 0 || (w.ip == 6 && pass == 1) { dbg_norm("y_part", &y_part, d.top_k * h); dbg_norm("moeout", &moeout, h); } moeout }; let msc = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::shortconv4_decode(&moeout, &w.m_sconv, &st.hist_m[pass], &msc, &slot0, 1, h as i32)?; vetta_infer_hip::vec_add(cur, &msc, cur, h)?; Ok(()) } /// Batched full-attention layer (M=B prefill): mirrors layer_forward_full. The /// 3-query mix [B*3,h] is split strided (gather_channel nq=3) into in0/in1/in2, /// each with its own q/k/v norm; K/V use DYNAMIC ShortConv taps (prefill_par with /// dyn_taps [B,n_kv,4]); Q/R clip applies per-token tau (pos_arr); flash window=0 /// (global). MoE sublayer identical to the batched SWA layer. #[allow(dead_code)] // wired by forward_batch (next brick) fn layer_forward_full_batched( cache: &WeightCache, w: &FullLayerWeights, st: &mut LayerState, d: &Dims, cur: &DeviceBuf, blocks: &mut BatchBlocks, pos: &DeviceBuf, max_pos: i32, pass: usize, b: i32, ctrl: Option<(&ControllerWeights, &DeviceBuf)>, ) -> Result<(), String> { let h = d.hidden; let kv_dim = d.kv_dim(); let q_dim = d.q_dim(); let bu = b as usize; // 3-query mix -> [B*3,h], strided split into in0/in1/in2 [B,h]. let mx3 = DeviceBuf::alloc(bu * 3 * h * 4)?; vetta_infer_hip::attn_res_mix(&blocks.arena, cur, &w.attn_query, &mx3, blocks.count as i32, b, 3, h as i32, d.eps)?; let in0 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(&mx3, &in0, 0, b, h as i32, 3)?; let in1 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(&mx3, &in1, 1, b, h as i32, 3)?; let in2 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(&mx3, &in2, 2, b, h as i32, 3)?; if let Some((cw, msgs)) = ctrl { let msg0 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(msgs, &msg0, 0, b, h as i32, 4)?; let msg1 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(msgs, &msg1, 1, b, h as i32, 4)?; let msg2 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(msgs, &msg2, 2, b, h as i32, 4)?; apply_controller_batched(&in0, &msg0, cw, 0, h, 64, d.eps, b)?; apply_controller_batched(&in1, &msg1, cw, 1, h, 64, d.eps, b)?; apply_controller_batched(&in2, &msg2, cw, 2, h, 64, d.eps, b)?; } vetta_infer_hip::rms_norm_f32(&in0, Some(&w.q_norm), &in0, b, h as i32, d.eps)?; vetta_infer_hip::rms_norm_f32(&in1, Some(&w.k_norm), &in1, b, h as i32, d.eps)?; vetta_infer_hip::rms_norm_f32(&in2, Some(&w.v_norm), &in2, b, h as i32, d.eps)?; let in0_bf = DeviceBuf::alloc(bu * h * 2)?; vetta_infer_hip::cast_f32_bf16(&in0, &in0_bf, bu * h)?; let in1_bf = DeviceBuf::alloc(bu * h * 2)?; vetta_infer_hip::cast_f32_bf16(&in1, &in1_bf, bu * h)?; let in2_bf = DeviceBuf::alloc(bu * h * 2)?; vetta_infer_hip::cast_f32_bf16(&in2, &in2_bf, bu * h)?; let q = DeviceBuf::alloc(bu * q_dim * 4)?; let k_raw = DeviceBuf::alloc(bu * kv_dim * 4)?; let v_raw = DeviceBuf::alloc(bu * kv_dim * 4)?; let r_raw = DeviceBuf::alloc(bu * d.n_head * d.d_rel * 4)?; let gatea = DeviceBuf::alloc(bu * q_dim * 4)?; let sinks = DeviceBuf::alloc(bu * d.n_head * 4)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wq, &q, b, q_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in1_bf, &w.wk, &k_raw, b, kv_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in2_bf, &w.wv, &v_raw, b, kv_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wr, &r_raw, b, (d.n_head * d.d_rel) as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.wg, &gatea, b, q_dim as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in0_bf, &w.ws, &sinks, b, d.n_head as i32, h as i32)?; // dynamic ShortConv taps [B,n_kv,4] + dyn prefill K/V. let k_dyn = DeviceBuf::alloc(bu * d.n_kv * 4 * 4)?; let v_dyn = DeviceBuf::alloc(bu * d.n_kv * 4 * 4)?; vetta_infer_hip::gemm_bf16(&in1_bf, &w.k_proj, &k_dyn, b, (d.n_kv * 4) as i32, h as i32)?; vetta_infer_hip::gemm_bf16(&in2_bf, &w.v_proj, &v_dyn, b, (d.n_kv * 4) as i32, h as i32)?; let k_cv = DeviceBuf::alloc(bu * kv_dim * 4)?; let v_cv = DeviceBuf::alloc(bu * kv_dim * 4)?; vetta_infer_hip::shortconv4_prefill_par(&k_raw, &w.k_static, Some(&k_dyn), &st.hist_k[pass], &k_cv, b, kv_dim as i32, d.n_kv as i32)?; vetta_infer_hip::shortconv4_update_hist(&k_raw, &st.hist_k[pass], b, kv_dim as i32)?; vetta_infer_hip::shortconv4_prefill_par(&v_raw, &w.v_static, Some(&v_dyn), &st.hist_v[pass], &v_cv, b, kv_dim as i32, d.n_kv as i32)?; vetta_infer_hip::shortconv4_update_hist(&v_raw, &st.hist_v[pass], b, kv_dim as i32)?; // tau on Q/R (per-token pos), K clip without tau. vetta_infer_hip::l2_clip_batched(&q, Some(&w.q_sc), (b as usize * d.n_head) as i32, d.hd as i32, d.qk_clip, true, 0, d.n_head as i32, Some(pos))?; vetta_infer_hip::l2_clip_batched(&r_raw, Some(&w.r_sc), (b as usize * d.n_head) as i32, d.d_rel as i32, d.rel_clip, true, 0, d.n_head as i32, Some(pos))?; vetta_infer_hip::l2_clip_batched(&k_cv, None, (b as usize * d.n_kv) as i32, d.hd as i32, d.qk_clip, false, 0, d.n_kv as i32, None)?; let rel_bias = DeviceBuf::alloc(bu * d.n_head * d.rel_extent * 4)?; // kernel writes all rel_extent (0.0f beyond lim): no sync host zero-fill vetta_infer_hip::relpos_bias_batched(&r_raw, &w.rel_proj, &rel_bias, pos, d.n_head as i32, d.d_rel as i32, d.rel_extent as i32, b)?; vetta_infer_hip::kv_store_f16_batched(&k_cv, &v_cv, &st.k_cache[pass], &st.v_cache[pass], pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps, b)?; let aout = DeviceBuf::alloc(bu * q_dim * 4)?; // global attention: window = 0. vetta_infer_hip::flash_swa_gqa_prefill_f16(&q, &st.k_cache[pass], &st.v_cache[pass], &aout, d.n_head as i32, d.n_kv as i32, st.max_seq as i32, d.hd as i32, d.scale(), 0, pos, max_pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea), b)?; let aout_bf = DeviceBuf::alloc(bu * q_dim * 2)?; vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, bu * q_dim)?; let oproj = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gemm_bf16(&aout_bf, &w.wo, &oproj, b, h as i32, q_dim as i32)?; let asc = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::shortconv4_prefill_par(&oproj, &w.a_sconv, None, &st.hist_a[pass], &asc, b, h as i32, 0)?; vetta_infer_hip::shortconv4_update_hist(&oproj, &st.hist_a[pass], b, h as i32)?; if w.ip % d.block_size == 0 { blocks.snapshot(cur)?; vetta_infer_hip::copy_f32(&asc, cur, bu * h)?; } else { vetta_infer_hip::vec_add(cur, &asc, cur, bu * h)?; } // MoE sublayer (identical to batched SWA). let mix = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::attn_res_mix(&blocks.arena, cur, &w.mlp_query, &mix, blocks.count as i32, b, 1, h as i32, d.eps)?; if let Some((cw, msgs)) = ctrl { let msg3 = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::gather_channel(msgs, &msg3, 3, b, h as i32, 4)?; apply_controller_batched(&mix, &msg3, cw, 3, h, 64, d.eps, b)?; } let mlpin = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::rms_norm_f32(&mix, Some(&w.mlp_norm), &mlpin, b, h as i32, d.eps)?; let rlog = DeviceBuf::alloc(bu * d.n_experts * 4)?; vetta_infer_hip::router_gemv_batched(&mlpin, &w.gate_w, &rlog, d.n_experts as i32, h as i32, b)?; let ids = DeviceBuf::alloc(bu * d.top_k * 4)?; let weights = DeviceBuf::alloc(bu * d.top_k * 4)?; vetta_infer_hip::moe_router_topk(&rlog, Some(&w.gate_b), &ids, &weights, b, d.n_experts as i32, d.top_k as i32, d.route_scale)?; let moeout = moe_batched(cache, w.ip, &mlpin, &ids, &weights, d, h, b)?; let msc = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::shortconv4_prefill_par(&moeout, &w.m_sconv, None, &st.hist_m[pass], &msc, b, h as i32, 0)?; vetta_infer_hip::shortconv4_update_hist(&moeout, &st.hist_m[pass], b, h as i32)?; vetta_infer_hip::vec_add(cur, &msc, cur, bu * h)?; Ok(()) } /// Loop-controller weights for one layer (4 channels: attn/k/v/mlp), each a /// low-rank down->gain/forget gate applied to the layer input with a message. pub struct ControllerWeights { pub down: [DeviceBuf; 4], // [gate_rank, 2*hidden] pub gain: [DeviceBuf; 4], // [hidden, gate_rank] pub forget: [DeviceBuf; 4], // [hidden, gate_rank] } pub fn load_controllers(ar: &SafetensorsArchive, ip: usize) -> Result { let names = ["attn", "k", "v", "mlp"]; let mut down = Vec::new(); let mut gain = Vec::new(); let mut forget = Vec::new(); for n in names { let p = format!("model.llm.layers.{ip}.controllers.{n}"); down.push(load_raw(ar, &format!("{p}.down_weight"))?); gain.push(load_raw(ar, &format!("{p}.gain_weight"))?); forget.push(load_raw(ar, &format!("{p}.forget_weight"))?); } Ok(ControllerWeights { down: [down.remove(0), down.remove(0), down.remove(0), down.remove(0)], gain: [gain.remove(0), gain.remove(0), gain.remove(0), gain.remove(0)], forget: [forget.remove(0), forget.remove(0), forget.remove(0), forget.remove(0)], }) } /// Apply one loop controller in place on `target` [hidden] using message /// `msg` [hidden]: RMS-pack [target;msg] -> down GEMM [gate_rank] -> gain/forget /// GEMM [hidden] -> target = (1-tanh(forget))*target + tanh(gain)*msg. fn apply_controller(target: &DeviceBuf, msg: &DeviceBuf, cw: &ControllerWeights, ch: usize, hidden: usize, gate_rank: usize, eps: f32) -> Result<(), String> { let packed = DeviceBuf::alloc(2 * hidden * 2)?; vetta_infer_hip::ctrl_pack(target, msg, &packed, hidden as i32, eps)?; let gate = DeviceBuf::alloc(gate_rank * 4)?; vetta_infer_hip::gemm_bf16(&packed, &cw.down[ch], &gate, 1, gate_rank as i32, (2 * hidden) as i32)?; let gate_bf = DeviceBuf::alloc(gate_rank * 2)?; vetta_infer_hip::cast_f32_bf16(&gate, &gate_bf, gate_rank)?; let gain = DeviceBuf::alloc(hidden * 4)?; let forget = DeviceBuf::alloc(hidden * 4)?; vetta_infer_hip::gemm_bf16(&gate_bf, &cw.gain[ch], &gain, 1, hidden as i32, gate_rank as i32)?; vetta_infer_hip::gemm_bf16(&gate_bf, &cw.forget[ch], &forget, 1, hidden as i32, gate_rank as i32)?; vetta_infer_hip::ctrl_apply(target, msg, &gain, &forget, target, hidden)?; Ok(()) } /// Message channels for the loop controllers: msgs [4, hidden] (attn/k/v/mlp). pub struct LoopMsgs(pub DeviceBuf); impl LoopMsgs { fn channel(&self, ch: usize, hidden: usize) -> Result { let mut h = vec![0f32; 4 * hidden]; self.0.d2h(&mut h)?; let buf = DeviceBuf::alloc(hidden * 4)?; buf.h2d(&h[ch * hidden..(ch + 1) * hidden])?; Ok(buf) } } /// Batched loop controller (M=B): target/msg [B,h] in place. ctrl_pack_batched -> /// down/gain/forget gemm_bf16 M=B -> ctrl_apply over B*h. Same math as M=1. #[allow(dead_code)] // wired by the batched layer forward fn apply_controller_batched(target: &DeviceBuf, msg: &DeviceBuf, cw: &ControllerWeights, ch: usize, hidden: usize, gate_rank: usize, eps: f32, b: i32) -> Result<(), String> { let bu = b as usize; let packed = DeviceBuf::alloc(bu * 2 * hidden * 2)?; vetta_infer_hip::ctrl_pack_batched(target, msg, &packed, hidden as i32, eps, b)?; let gate = DeviceBuf::alloc(bu * gate_rank * 4)?; vetta_infer_hip::gemm_bf16(&packed, &cw.down[ch], &gate, b, gate_rank as i32, (2 * hidden) as i32)?; let gate_bf = DeviceBuf::alloc(bu * gate_rank * 2)?; vetta_infer_hip::cast_f32_bf16(&gate, &gate_bf, bu * gate_rank)?; let gain = DeviceBuf::alloc(bu * hidden * 4)?; let forget = DeviceBuf::alloc(bu * hidden * 4)?; vetta_infer_hip::gemm_bf16(&gate_bf, &cw.gain[ch], &gain, b, hidden as i32, gate_rank as i32)?; vetta_infer_hip::gemm_bf16(&gate_bf, &cw.forget[ch], &forget, b, hidden as i32, gate_rank as i32)?; vetta_infer_hip::ctrl_apply(target, msg, &gain, &forget, target, bu * hidden)?; Ok(()) } /// Device-resident depth-block arena for the batched forward: [max_blocks, B, h] /// contiguous, the exact layout attn_res_mix reads (blocks [n_blocks, M, D]). /// Snapshot copies cur [B,h] into arena[count] device-side (no host gather); /// truncate implements the core-loop bank rollback depth restoration. #[allow(dead_code)] // wired by the batched forward struct BatchBlocks { arena: DeviceBuf, count: usize, b: usize, h: usize, } #[allow(dead_code)] impl BatchBlocks { fn new(b: usize, h: usize, max_blocks: usize) -> Result { let arena = DeviceBuf::alloc(max_blocks * b * h * 4)?; Ok(Self { arena, count: 0, b, h }) } fn snapshot(&mut self, cur: &DeviceBuf) -> Result<(), String> { vetta_infer_hip::copy_f32_at(cur, &self.arena, self.count * self.b * self.h, self.b * self.h)?; self.count += 1; Ok(()) } fn truncate(&mut self, n: usize) { self.count = n; } } #[cfg(test)] mod tests { use super::*; /// Multi-layer SWA prelude forward (layers 0..4) + final norm + unembed on /// real weights: verifies cross-layer composition + the depth-block cadence /// (only ip%6==0 snapshots, so the prelude accumulates exactly one block) /// and produces finite logits over vocab 201024. Individual layers are /// parity-verified elsewhere; this checks they compose across layers. #[test] #[ignore] fn multi_layer_prelude_forward() { let ar = Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap()); let cache = WeightCache::new(ar.clone()); let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; let (cur, blocks) = forward_swa_layers(&cache, &[0, 1, 2, 3, 4], &d, 100, 1, 0).unwrap(); assert_eq!(blocks.len(), 1, "prelude 0..4 snapshots only at ip=0"); let logits = final_logits(&cache, &cur, &blocks, d.hidden, 201024, d.eps, 30.0).unwrap(); let mut lg = vec![0f32; 201024]; logits.d2h(&mut lg).unwrap(); assert!(lg.iter().all(|v| v.is_finite()), "logits must be finite"); assert!(lg.iter().all(|v| v.abs() <= 30.0 + 1e-3), "softcap must bound logits"); let argmax = lg.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0; eprintln!("multi-layer prelude (0..4) forward: argmax token={argmax} logit={:.3}", lg[argmax]); assert!(argmax < 201024); } /// Full-attention layer (ip=5) end-to-end on real weights: 3-query AttnRes /// mix split + separate q/k/v norms + projections from distinct inputs + /// dynamic ShortConv K/V + tau + global attention + MoE. Seeded with one /// depth block (as after ip=0); ip=5 % 6 != 0 so no new snapshot. Verifies /// the full-attn path composes and produces a finite residual stream. #[test] #[ignore] fn full_attn_layer_end_to_end() { let ar = Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap()); let cache = WeightCache::new(ar.clone()); let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; let cur = embed_token(&cache, 100, d.hidden, 201024).unwrap(); let mut blocks: Vec = Vec::new(); let mut seed = vec![0f32; d.hidden]; cur.d2h(&mut seed).unwrap(); let b0 = DeviceBuf::alloc(d.hidden * 4).unwrap(); b0.h2d(&seed).unwrap(); blocks.push(b0); let w = load_full_layer(&ar, 5, &d).unwrap(); let mut st = new_state(&d, 1, 3).unwrap(); layer_forward_full(&cache, &w, &mut st, &d, &cur, &mut blocks, 0, 0, None).unwrap(); assert_eq!(blocks.len(), 1, "ip=5 does not snapshot (5%6!=0)"); let mut out = vec![0f32; d.hidden]; cur.d2h(&mut out).unwrap(); assert!(out.iter().all(|v| v.is_finite()), "full-attn residual must be finite"); assert!(out.iter().any(|&v| v != seed[0]), "full-attn layer must transform the residual"); eprintln!("full-attn layer (ip=5) end-to-end: finite residual, no new snapshot"); } /// FULL Inkling-2-Mini forward (48 visits: prelude + core x3 with bank /// rollback + controllers + coda) on real weights -> logits over vocab /// 201024. Verifies the complete proven schedule composes and produces /// finite, softcap-bounded logits. This is the whole model forward. #[test] #[ignore] fn full_inkling_forward_logits() { let ar = Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap()); let cache = WeightCache::new(ar.clone()); let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; let logits = forward_inkling(&cache, &d, 100, 201024, 1, 0, 30.0).unwrap(); let mut lg = vec![0f32; 201024]; logits.d2h(&mut lg).unwrap(); assert!(lg.iter().all(|v| v.is_finite()), "full forward logits must be finite"); assert!(lg.iter().all(|v| v.abs() <= 30.0 + 1e-3), "logits must be softcap-bounded"); let argmax = lg.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0; let mut idx: Vec = (0..201024).collect(); idx.sort_by(|&a, &b| lg[b].partial_cmp(&lg[a]).unwrap()); let top5: Vec<(usize, f32)> = idx[..5].iter().map(|&i| (i, lg[i])).collect(); eprintln!("FULL Inkling forward: argmax token={argmax} logit={:.3} top5={top5:?} logit[68014]={:.3} logit[100]={:.3}", lg[argmax], lg[68014], lg[100]); assert!(argmax < 201024); } /// Autoregressive generation: encode a real prompt, prefill token-by-token /// (persistent KV/history), then greedily sample continuations with the /// hardened abi sampler and decode. Correctness signal: a coherent /// continuation indicates the full forward + state evolution are right. #[test] #[ignore] fn generate_continuation_real_prompt() { use tokenizers::Tokenizer; use vetta_infer_abi::sampler::{sample_logits_exact, SampleReport, SamplerScratch, SamplingOpts, SplitMix64}; let ar = Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap()); let cache = WeightCache::new(ar.clone()); let tok = Tokenizer::from_file("/mnt/models/Inkling/safetensors/tokenizer.json").unwrap(); let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; let vocab = 201024usize; let prompt = "The capital of France is"; let ids: Vec = tok.encode(prompt, false).unwrap().get_ids().iter().map(|&x| x as i32).collect(); eprintln!("[gen] prompt_ids={ids:?}"); let n_gen = 16usize; let max_seq = ids.len() + n_gen + 2; let mut states: Vec> = (0..24).map(|_| None).collect(); let mut history: Vec = Vec::new(); let mut pos = 0i32; let mut logits = DeviceBuf::alloc(vocab * 4).unwrap(); for &t in &ids { logits = forward_inkling_with_state(&cache, &d, t, vocab, max_seq, pos, 30.0, &mut states).unwrap(); history.push(t); pos += 1; } let opts = SamplingOpts::default(); // greedy let mut rng = SplitMix64::new(42); let mut scratch = SamplerScratch::default(); let mut generated: Vec = Vec::new(); for _ in 0..n_gen { let mut lg = vec![0f32; vocab]; logits.d2h(&mut lg).unwrap(); let rep: SampleReport = sample_logits_exact(&mut lg, &opts, &history, None, &mut rng, &mut scratch); generated.push(rep.token as u32); history.push(rep.token); logits = forward_inkling_with_state(&cache, &d, rep.token, vocab, max_seq, pos, 30.0, &mut states).unwrap(); pos += 1; } let text = tok.decode(&generated, true).unwrap(); eprintln!("prompt={prompt:?} -> generated={text:?} (tokens={generated:?})"); assert!(!generated.is_empty()); } /// Batched MoE (moe_batched, M=B) vs per-token device MoE (moe_device) on REAL /// weights, layer 0 (NVFP4) + layer 20 (MXFP8). Same router ids/weights fed to /// both, so the only difference is GEMM accumulation order (grouped MT tiling /// vs wave-per-row). Verifies the batched MoE composition is correct. #[test] #[ignore] fn moe_batched_parity_vs_device() { let ar = Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap()); let cache = WeightCache::new(ar.clone()); let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; let h = d.hidden; let b = 8usize; let top_k = d.top_k; for &ip in &[0usize, 20usize] { let w = cache.swa_layer(ip).unwrap(); let mlpin_h: Vec = (0..b * h).map(|i| ((i % 37) as f32 - 18.0) * 0.02).collect(); let mlpin = DeviceBuf::alloc(b * h * 4).unwrap(); mlpin.h2d(&mlpin_h).unwrap(); let rlog = DeviceBuf::alloc(b * d.n_experts * 4).unwrap(); vetta_infer_hip::router_gemv_batched(&mlpin, &w.gate_w, &rlog, d.n_experts as i32, h as i32, b as i32).unwrap(); let ids = DeviceBuf::alloc(b * top_k * 4).unwrap(); let weights = DeviceBuf::alloc(b * top_k * 4).unwrap(); vetta_infer_hip::moe_router_topk(&rlog, Some(&w.gate_b), &ids, &weights, b as i32, d.n_experts as i32, top_k as i32, d.route_scale).unwrap(); let moeout_b = moe_batched(&cache, ip, &mlpin, &ids, &weights, &d, h, b as i32).unwrap(); let mut ob = vec![0f32; b * h]; moeout_b.d2h(&mut ob).unwrap(); let mut ids_b = vec![0u8; b * top_k * 4]; ids.d2h_bytes(&mut ids_b).unwrap(); let ids_h: Vec = ids_b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect(); let mut weights_h = vec![0f32; b * top_k]; weights.d2h(&mut weights_h).unwrap(); let mut os_all = vec![0f32; b * h]; for m in 0..b { let mlpin_m = DeviceBuf::alloc(h * 4).unwrap(); mlpin_m.h2d(&mlpin_h[m * h..(m + 1) * h]).unwrap(); let ids_m = DeviceBuf::alloc(top_k * 4).unwrap(); let idb: Vec = ids_h[m * top_k..(m + 1) * top_k].iter().flat_map(|x| x.to_le_bytes()).collect(); ids_m.h2d_bytes(&idb).unwrap(); let weights_m = DeviceBuf::alloc(top_k * 4).unwrap(); weights_m.h2d(&weights_h[m * top_k..(m + 1) * top_k]).unwrap(); let moeout_s = moe_device(&cache, ip, &mlpin_m, &ids_m, &weights_m, &d, h).unwrap(); let mut os = vec![0f32; h]; moeout_s.d2h(&mut os).unwrap(); os_all[m * h..(m + 1) * h].copy_from_slice(&os); } // Global-scale normalization: P1 WMMA (ip=0 NVFP4) vs serial fdot2 differs // ~1e-4 absolute, which explodes per-entry on near-zero expert outputs. // ip=20 MXFP8 uses the same Wave32 fdot2 on both paths => bit-exact. let scale = os_all.iter().fold(0f32, |mx, v| mx.max(v.abs())).max(1e-3); let mut max_rel = 0f32; for (g, w) in ob.iter().zip(os_all.iter()) { max_rel = max_rel.max((g - w).abs() / scale); } eprintln!("moe_batched ip={ip} B={b} max_rel_err={max_rel:.3e}"); assert!(max_rel < 3e-3, "batched MoE parity failed at ip={ip}: {max_rel}"); } } /// Batched SWA layer (M=B) vs B sequential M=1 layer_forward_swa on REAL weights /// (ip=1, no snapshot). Aligns KV dtype (f16) + device MoE so the only difference /// is batching. Compares the residual stream cur[B,h] AND the KV cache. #[test] #[ignore] fn layer_swa_batched_parity() { set_kv_f16(true); unsafe { std::env::set_var("VETTA_DEVICE_MOE", "1") }; let ar = Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap()); let cache = WeightCache::new(ar.clone()); let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; let h = d.hidden; let b = 8usize; let base = 5i32; let ip = 1usize; let w = cache.swa_layer(ip).unwrap(); let cur_h: Vec = (0..b * h).map(|i| ((i % 37) as f32 - 18.0) * 0.02).collect(); let seed_h: Vec = (0..b * h).map(|i| ((i % 29) as f32 - 14.0) * 0.01).collect(); let max_seq = (base + b as i32 + 2) as usize; let pos: Vec = (0..b).map(|m| base + m as i32).collect(); let pos_bytes: Vec = pos.iter().flat_map(|x| x.to_le_bytes()).collect(); let dpos = DeviceBuf::alloc(b * 4).unwrap(); dpos.h2d_bytes(&pos_bytes).unwrap(); // Batched. let cur_b = DeviceBuf::alloc(b * h * 4).unwrap(); cur_b.h2d(&cur_h).unwrap(); let mut blocks_b = BatchBlocks::new(b, h, 8).unwrap(); let seed_buf = DeviceBuf::alloc(b * h * 4).unwrap(); seed_buf.h2d(&seed_h).unwrap(); blocks_b.snapshot(&seed_buf).unwrap(); let mut st_b = new_state(&d, max_seq, 1).unwrap(); layer_forward_swa_batched(&cache, &w, &mut st_b, &d, &cur_b, &mut blocks_b, &dpos, base + b as i32 - 1, 0, b as i32, None).unwrap(); let mut cb = vec![0f32; b * h]; cur_b.d2h(&mut cb).unwrap(); // Sequential M=1. let mut st_s = new_state(&d, max_seq, 1).unwrap(); let mut cs = vec![0f32; b * h]; for m in 0..b { let cur_m = DeviceBuf::alloc(h * 4).unwrap(); cur_m.h2d(&cur_h[m * h..(m + 1) * h]).unwrap(); let seed_m = DeviceBuf::alloc(h * 4).unwrap(); seed_m.h2d(&seed_h[m * h..(m + 1) * h]).unwrap(); let mut blocks_m = vec![seed_m]; layer_forward_swa(&cache, &w, &mut st_s, &d, &cur_m, &mut blocks_m, base + m as i32, 0, None).unwrap(); let mut o = vec![0f32; h]; cur_m.d2h(&mut o).unwrap(); cs[m * h..(m + 1) * h].copy_from_slice(&o); } // Normalize by the GLOBAL cur scale, not per-entry: the P1 WMMA MoE differs // from serial fdot2 by ~1e-4 absolute, which explodes as a per-entry relative // error on near-zero residual entries. The KV cache stays byte-identical // (attention precedes MoE) — that is the strong correctness gate here. let cscale = cs.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-3); let mut max_rel = 0f32; for (g, wnt) in cb.iter().zip(cs.iter()) { max_rel = max_rel.max((g - wnt).abs() / cscale); } // KV cache byte-compare (f16). let kvn = d.n_kv * max_seq * d.hd * 2; let mut kb = vec![0u8; kvn]; st_b.k_cache[0].d2h_bytes(&mut kb).unwrap(); let mut ks = vec![0u8; kvn]; st_s.k_cache[0].d2h_bytes(&mut ks).unwrap(); let kv_match = kb == ks; eprintln!("layer_swa_batched ip={ip} B={b} cur_max_rel={max_rel:.3e} kv_byte_identical={kv_match}"); set_kv_f16(false); unsafe { std::env::remove_var("VETTA_DEVICE_MOE") }; assert!(max_rel < 3e-3, "batched SWA layer cur parity failed: {max_rel}"); assert!(kv_match, "batched SWA layer KV cache must be byte-identical"); } /// Batched full-attn layer (M=B) vs B sequential M=1 layer_forward_full on REAL /// weights (ip=5, no snapshot): 3-query split, dyn ShortConv, per-token tau, /// global window. Aligns f16 KV + device MoE. Compares cur[B,h] AND KV cache. #[test] #[ignore] fn layer_full_batched_parity() { set_kv_f16(true); unsafe { std::env::set_var("VETTA_DEVICE_MOE", "1") }; let ar = Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap()); let cache = WeightCache::new(ar.clone()); let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; let h = d.hidden; let b = 8usize; let base = 5i32; let ip = 5usize; let w = cache.full_layer(ip, &d).unwrap(); let cur_h: Vec = (0..b * h).map(|i| ((i % 37) as f32 - 18.0) * 0.02).collect(); let seed_h: Vec = (0..b * h).map(|i| ((i % 29) as f32 - 14.0) * 0.01).collect(); let max_seq = (base + b as i32 + 2) as usize; let pos: Vec = (0..b).map(|m| base + m as i32).collect(); let pos_bytes: Vec = pos.iter().flat_map(|x| x.to_le_bytes()).collect(); let dpos = DeviceBuf::alloc(b * 4).unwrap(); dpos.h2d_bytes(&pos_bytes).unwrap(); let cur_b = DeviceBuf::alloc(b * h * 4).unwrap(); cur_b.h2d(&cur_h).unwrap(); let mut blocks_b = BatchBlocks::new(b, h, 8).unwrap(); let seed_buf = DeviceBuf::alloc(b * h * 4).unwrap(); seed_buf.h2d(&seed_h).unwrap(); blocks_b.snapshot(&seed_buf).unwrap(); let mut st_b = new_state(&d, max_seq, 1).unwrap(); layer_forward_full_batched(&cache, &w, &mut st_b, &d, &cur_b, &mut blocks_b, &dpos, base + b as i32 - 1, 0, b as i32, None).unwrap(); let mut cb = vec![0f32; b * h]; cur_b.d2h(&mut cb).unwrap(); let mut st_s = new_state(&d, max_seq, 1).unwrap(); let mut cs = vec![0f32; b * h]; for m in 0..b { let cur_m = DeviceBuf::alloc(h * 4).unwrap(); cur_m.h2d(&cur_h[m * h..(m + 1) * h]).unwrap(); let seed_m = DeviceBuf::alloc(h * 4).unwrap(); seed_m.h2d(&seed_h[m * h..(m + 1) * h]).unwrap(); let mut blocks_m = vec![seed_m]; layer_forward_full(&cache, &w, &mut st_s, &d, &cur_m, &mut blocks_m, base + m as i32, 0, None).unwrap(); let mut o = vec![0f32; h]; cur_m.d2h(&mut o).unwrap(); cs[m * h..(m + 1) * h].copy_from_slice(&o); } // Normalize by the GLOBAL cur scale, not per-entry: the P1 WMMA MoE differs // from serial fdot2 by ~1e-4 absolute, which explodes as a per-entry relative // error on near-zero residual entries. The KV cache stays byte-identical // (attention precedes MoE) — that is the strong correctness gate here. let cscale = cs.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-3); let mut max_rel = 0f32; for (g, wnt) in cb.iter().zip(cs.iter()) { max_rel = max_rel.max((g - wnt).abs() / cscale); } let kvn = d.n_kv * max_seq * d.hd * 2; let mut kb = vec![0u8; kvn]; st_b.k_cache[0].d2h_bytes(&mut kb).unwrap(); let mut ks = vec![0u8; kvn]; st_s.k_cache[0].d2h_bytes(&mut ks).unwrap(); let kv_match = kb == ks; eprintln!("layer_full_batched ip={ip} B={b} cur_max_rel={max_rel:.3e} kv_byte_identical={kv_match}"); set_kv_f16(false); unsafe { std::env::remove_var("VETTA_DEVICE_MOE") }; assert!(max_rel < 3e-3, "batched full layer cur parity failed: {max_rel}"); assert!(kv_match, "batched full layer KV cache must be byte-identical"); } /// End-to-end batched prefill parity: forward_batch(B tokens) logits for the /// LAST token vs B sequential forward_inkling_with_state calls (states persist). /// Real weights, f16 KV + device MoE aligned. Checks argmax AND logit error. #[test] #[ignore] fn forward_batch_parity() { set_kv_f16(true); unsafe { std::env::set_var("VETTA_DEVICE_MOE", "1") }; let ar = Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap()); let cache = WeightCache::new(ar.clone()); let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; let vocab = 200058usize; let b = 4usize; let max_seq = b + 2; let tokens: Vec = vec![100, 200, 300, 400]; let mut states_b: Vec> = (0..24).map(|_| None).collect(); let logits_b = forward_batch(&cache, &d, &tokens, vocab, max_seq, 0, 0.0, &mut states_b).unwrap(); let mut lb = vec![0f32; vocab]; logits_b.d2h(&mut lb).unwrap(); let mut states_s: Vec> = (0..24).map(|_| None).collect(); let mut ls = vec![0f32; vocab]; for m in 0..b { let lo = forward_inkling_with_state(&cache, &d, tokens[m], vocab, max_seq, m as i32, 0.0, &mut states_s).unwrap(); lo.d2h(&mut ls).unwrap(); } let argb = lb.iter().enumerate().max_by(|a, c| a.1.partial_cmp(c.1).unwrap()).unwrap().0; let args = ls.iter().enumerate().max_by(|a, c| a.1.partial_cmp(c.1).unwrap()).unwrap().0; let mut max_abs = 0f32; let mut max_rel = 0f32; for (g, w) in lb.iter().zip(ls.iter()) { max_abs = max_abs.max((g - w).abs()); max_rel = max_rel.max((g - w).abs() / w.abs().max(1.0)); } let gscale = ls.iter().fold(0f32, |a, v| a.max(v.abs())).max(1e-6); eprintln!("forward_batch B={b} argmax batch={argb} seq={args} max_abs={max_abs:.3e} max_rel={max_rel:.3e} global_rel={:.3e}", max_abs / gscale); set_kv_f16(false); unsafe { std::env::remove_var("VETTA_DEVICE_MOE") }; assert_eq!(argb, args, "forward_batch argmax must match sequential (greedy gate)"); // P1 tolerance: prefill uses FP16 WMMA MoE (tensor-core f32 accumulation // order) + FA2 flash prefill (f16 P/Q rounding) while M=1 decode uses serial // fdot2 + f32 two-pass softmax. Per-kernel ~1e-4..1e-3 compounds through 24 // layers to ~5e-3 of the GLOBAL logit scale (per-entry rel explodes on // near-zero logits). The argmax above + gw serve_gen_multi_token_parity // (greedy-vs-reference EXACT) are the blocking production gates. assert!(max_abs / gscale < 1e-2, "forward_batch logits parity failed: global_rel={}", max_abs / gscale); } /// DSpark tap capture: forward_batch_taps must (a) leave logits BIT-IDENTICAL /// to forward_batch (capture is pure copies) and (b) tap48 = output-normed /// final mix, whose last row unembeds to exactly those logits. #[test] #[ignore] fn forward_batch_taps_capture() { set_kv_f16(true); unsafe { std::env::set_var("VETTA_DEVICE_MOE", "1") }; let ar = Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap()); let cache = WeightCache::new(ar.clone()); let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; let vocab = 200058usize; let b = 4usize; let max_seq = b + 2; let h = d.hidden; let tokens: Vec = vec![100, 200, 300, 400]; let mut st_b: Vec> = (0..24).map(|_| None).collect(); let lb_buf = forward_batch(&cache, &d, &tokens, vocab, max_seq, 0, 0.0, &mut st_b).unwrap(); let mut lb = vec![0f32; vocab]; lb_buf.d2h(&mut lb).unwrap(); let mut st_t: Vec> = (0..24).map(|_| None).collect(); let mut taps: [DeviceBuf; 4] = std::array::from_fn(|_| DeviceBuf::alloc(b * h * 4).unwrap()); let lt_buf = forward_batch_taps(&cache, &d, &tokens, vocab, max_seq, 0, 0.0, &mut st_t, &mut taps).unwrap(); let mut lt = vec![0f32; vocab]; lt_buf.d2h(&mut lt).unwrap(); assert_eq!(lb, lt, "tap capture must not perturb logits"); let last = DeviceBuf::alloc(h * 4).unwrap(); vetta_infer_hip::copy_f32_sub(&taps[3], (b - 1) * h, &last, h).unwrap(); // tap48 is ALREADY output-normed, so unembed it directly (cast bf16 + // gemm), NOT via unembed_logits (which would norm a second time). let nb = DeviceBuf::alloc(h * 2).unwrap(); vetta_infer_hip::cast_f32_bf16(&last, &nb, h).unwrap(); let unembed = cache.raw("model.llm.unembed.weight").unwrap(); let lo = DeviceBuf::alloc(vocab * 4).unwrap(); vetta_infer_hip::gemm_bf16(&nb, &unembed, &lo, 1, vocab as i32, h as i32).unwrap(); let mut l48 = vec![0f32; vocab]; lo.d2h(&mut l48).unwrap(); assert_eq!(lt, l48, "tap48 (output-normed mix) must reproduce logits"); for k in 0..4 { let mut v = vec![0f32; b * h]; taps[k].d2h(&mut v).unwrap(); assert!(v.iter().all(|x| x.is_finite()), "tap{k} non-finite"); assert!(v.iter().any(|x| *x != 0.0), "tap{k} all zero"); } eprintln!("forward_batch_taps: logits bit-identical, tap48 reproduces logits, taps finite"); set_kv_f16(false); unsafe { std::env::remove_var("VETTA_DEVICE_MOE") }; } }