//! 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_gemv, expert_gemv_f16, load_bf16_as_f32, load_expert_matrix, load_raw, 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 { pub k_cache: DeviceBuf, pub v_cache: DeviceBuf, // [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. Borrows the archive; 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<'a> { pub ar: &'a SafetensorsArchive, raw: RefCell>>, bf16: RefCell>>, sconv: RefCell>>, swa: RefCell>>, full: RefCell>>, experts: RefCell>>, ctrl: RefCell>>, } impl<'a> WeightCache<'a> { pub fn new(ar: &'a SafetensorsArchive) -> 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()), ctrl: 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) } 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) } } 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) -> Result { let zero = |n: usize| -> Result { let b = DeviceBuf::alloc(n * 4)?; b.h2d(&vec![0f32; n])?; Ok(b) }; Ok(LayerState { k_cache: zero(d.n_kv * max_seq * d.hd)?, v_cache: zero(d.n_kv * max_seq * d.hd)?, 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, }) } /// 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)?; rel_bias.h2d(&vec![0f32; d.n_head * d.rel_extent])?; 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)?; vetta_infer_hip::kv_store(&k_cv, &v_cv, &st.k_cache, &st.v_cache, 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. vetta_infer_hip::flash_swa_gqa_decode(&q, &st.k_cache, &st.v_cache, &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 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); } // 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(()) } /// 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, max_seq)?; 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) } /// 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 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])?; } } Ok(y_part_h) } /// 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() { states[ip] = Some(new_state(d, max_seq)?); } 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 cur = embed_token(cache, token, h, vocab)?; 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. for ip in 0..6 { run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, 0, None)?; } 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. 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 = load_msg_queries(cache, 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. for ip in 18..24 { run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, 0, None)?; } 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}"); } } final_logits(cache, &cur, &blocks, h, vocab, d.eps, cap) } /// 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)?; rel_bias.h2d(&vec![0f32; d.n_head * d.rel_extent])?; 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)?; vetta_infer_hip::kv_store(&k_cv, &v_cv, &st.k_cache, &st.v_cache, 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. vetta_infer_hip::flash_swa_gqa_decode(&q, &st.k_cache, &st.v_cache, &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 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); } 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(()) } /// 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) } } #[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 = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap(); let cache = WeightCache::new(&ar); 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 = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap(); let cache = WeightCache::new(&ar); 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).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 = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap(); let cache = WeightCache::new(&ar); 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 = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap(); let cache = WeightCache::new(&ar); 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()); } }