[LD] reusable GPU layer forward (ld::layer) with persistent per-layer state

- ld::layer (feature hip): LayerWeights (load_layer reads all attention + MoE
  weights + learned depth-mix queries for a physical step ip), LayerState
  (persistent KV cache + ShortConv history rings, new_state), Dims, and
  layer_forward_swa — a complete SWA layer step composing the verified
  microkernels with the exact Inkling deep-residual cadence:
    ip==0: in0=attn_norm(cur); ip>0: in0=attn_norm(mix(blocks,cur,attn_query))
    attention block -> asc; ip%block_size==0: snapshot cur->blocks, cur=asc
      else cur+=asc
    mlpin=mlp_norm(mix(blocks,cur,mlp_query)); MoE block; cur+=mlp_sconv(moeout)
  The depth-block snapshots are owned by the caller (the forward residual
  stream); experts loaded on demand (zero requantization).
- Refactored real_full_layer_end_to_end to drive the GPU side through
  layer_forward_swa; the unchanged full CPU oracle still verifies it
  (max_rel_err 6.6e-4, identical experts) AND asserts the ip=0 block snapshot.
  This is the reusable foundation for the multi-layer forward.

Scope: SWA layers without loop controllers (prelude). Full-attn 3-query split,
loop controllers (gain/forget/down) and multi-pass bank rollback come next.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; real full layer via reusable fn PASS
(--features hip, --ignored).
This commit is contained in:
adm committed 2026-12-01 14:46:05 +01:00
1 parent 25ffc820f8
commit 0929bde578
3 files changed
+230 -105

No files matched your search

+220
View File
@@ -0,0 +1,220 @@
//! 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::{load_bf16_as_f32, load_expert_matrix, load_raw};
use crate::SafetensorsArchive;
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<DeviceBuf>, // 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]
pub hist_k: DeviceBuf, pub hist_v: DeviceBuf, // [3, n_kv*hd]
pub hist_a: DeviceBuf, pub hist_m: DeviceBuf, // [3, hidden]
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() }
}
pub fn load_layer(ar: &SafetensorsArchive, ip: usize, is_swa: bool) -> Result<LayerWeights, String> {
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<LayerState, String> {
let zero = |n: usize| -> Result<DeviceBuf, String> { 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())?,
hist_v: zero(3 * d.kv_dim())?,
hist_a: zero(3 * d.hidden)?,
hist_m: 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(
ar: &SafetensorsArchive, w: &LayerWeights, st: &mut LayerState, d: &Dims,
cur: &DeviceBuf, blocks: &mut Vec<DeviceBuf>, pos: i32,
) -> 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 in0 = DeviceBuf::alloc(h * 4)?;
let in0_bf = DeviceBuf::alloc(h * 2)?;
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 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. ip==0 -> attn_norm(cur); ip>0 -> attn_norm(mix(blocks,cur,attn_query)).
if w.ip == 0 {
vetta_infer_hip::rms_norm_f32(cur, Some(&w.attn_norm), &in0, 1, h as i32, d.eps)?;
} else {
let n_blocks = blocks.len();
let blk = DeviceBuf::alloc(n_blocks.max(1) * h * 4)?;
// pack block snapshots contiguously [n_blocks, 1, h]
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)?;
let aq = w.attn_query.as_ref().ok_or("ip>0 needs attn_query")?;
vetta_infer_hip::attn_res_mix(&blk, cur, aq, &mix, n_blocks as i32, 1, 1, h as i32, d.eps)?;
vetta_infer_hip::rms_norm_f32(&mix, Some(&w.attn_norm), &in0, 1, h as i32, d.eps)?;
}
// k2: projections + shortconv K/V + clip + relpos + KV store.
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, &k_cv, &slot0, 1, kv_dim as i32)?;
vetta_infer_hip::shortconv4_decode(&v_raw, &w.v_sconv, &st.hist_v, &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)?;
// 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))?;
// 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, &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)?;
}
// 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)?;
let mlpin = DeviceBuf::alloc(h * 4)?;
vetta_infer_hip::rms_norm_f32(&mix, Some(&w.mlp_norm), &mlpin, 1, h as i32, d.eps)?;
// k6: router + experts + reduce.
let mlpin_bf = DeviceBuf::alloc(h * 2)?;
vetta_infer_hip::cast_f32_bf16(&mlpin, &mlpin_bf, h)?;
let rlog = DeviceBuf::alloc(d.n_experts * 4)?;
vetta_infer_hip::gemm_bf16(&mlpin_bf, &w.gate_w, &rlog, 1, 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::<Vec<_>>() };
let gu = DeviceBuf::alloc(2 * d.inter * 4)?;
let act = DeviceBuf::alloc(d.inter * 4)?;
let mut y_part_h = vec![0f32; d.top_k * h];
for kk in 0..d.top_k {
let e = ids_h[kk] as usize;
let w13 = load_expert_matrix(ar, w.ip, e, "w13")?;
vetta_infer_hip::nvfp4_gemv(&w13.packed, &w13.scales, w13.outer, &mlpin, &gu, w13.n, w13.k)?;
vetta_infer_hip::situ(&gu, &act, d.inter as i32, d.beta, d.lb)?;
let w2 = load_expert_matrix(ar, w.ip, e, "w2")?;
let ye = DeviceBuf::alloc(h * 4)?;
vetta_infer_hip::nvfp4_gemv(&w2.packed, &w2.scales, w2.outer, &act, &ye, w2.n, w2.k)?;
ye.d2h(&mut y_part_h[kk * h..(kk + 1) * 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)?;
// k7: mlp shortconv + plain residual add.
let msc = DeviceBuf::alloc(h * 4)?;
vetta_infer_hip::shortconv4_decode(&moeout, &w.m_sconv, &st.hist_m, &msc, &slot0, 1, h as i32)?;
vetta_infer_hip::vec_add(cur, &msc, cur, h)?;
Ok(())
}
+3
View File
@@ -17,6 +17,9 @@ pub mod inkling_graph;
#[cfg(feature = "hip")] #[cfg(feature = "hip")]
pub mod packer; pub mod packer;
#[cfg(feature = "hip")]
pub mod layer;
use std::collections::{BTreeSet, HashMap}; use std::collections::{BTreeSet, HashMap};
use std::fs::{self, File, OpenOptions}; use std::fs::{self, File, OpenOptions};
use std::os::unix::fs::FileExt; use std::os::unix::fs::FileExt;
+7 -105
View File
@@ -561,112 +561,14 @@ mod tests {
let pos = 0i32; let steps = 1usize; let pos = 0i32; let steps = 1usize;
let x: Vec<f32> = (0..hidden).map(|i| ((i % 53) as f32 - 26.0) * 0.02).collect(); let x: Vec<f32> = (0..hidden).map(|i| ((i % 53) as f32 - 26.0) * 0.02).collect();
// attention weights (device) // === GPU full layer via the reusable layer forward (ld::layer) ===
let attn_norm = load_bf16_as_f32(&ar, "model.llm.layers.0.attn_norm.weight").unwrap(); let dims = crate::layer::Dims { hidden, n_head, n_kv, hd, d_rel, rel_extent, inter, n_experts, top_k, block_size: 6, qk_clip, rel_clip, eps, route_scale, beta, lb, swa_win: 1024 };
let wq = load_raw(&ar, &format!("{p}.wq_du.weight")).unwrap(); let lw = crate::layer::load_layer(&ar, 0, true).unwrap();
let wk = load_raw(&ar, &format!("{p}.wk_dv.weight")).unwrap(); let mut st = crate::layer::new_state(&dims, steps).unwrap();
let wv = load_raw(&ar, &format!("{p}.wv_dv.weight")).unwrap();
let wr = load_raw(&ar, &format!("{p}.wr_du.weight")).unwrap();
let wg = load_raw(&ar, &format!("{p}.gate_attn.weight")).unwrap();
let ws = load_raw(&ar, &format!("{p}.attn_sink_proj.weight")).unwrap();
let wo = load_raw(&ar, &format!("{p}.wo_ud.weight")).unwrap();
let q_sc = load_bf16_as_f32(&ar, &format!("{p}.q_l2_clip.scale")).unwrap();
let r_sc = load_bf16_as_f32(&ar, &format!("{p}.rel_l2_clip.scale")).unwrap();
let rel_proj = load_bf16_as_f32(&ar, &format!("{p}.rel_logits_proj.proj")).unwrap();
let k_sconv = load_bf16_as_f32(&ar, &format!("{p}.k_sconv.weight")).unwrap();
let v_sconv = load_bf16_as_f32(&ar, &format!("{p}.v_sconv.weight")).unwrap();
let a_sconv = load_bf16_as_f32(&ar, "model.llm.layers.0.attn_sconv.weight").unwrap();
// MoE weights (device)
let mlp_norm = load_bf16_as_f32(&ar, "model.llm.layers.0.mlp_norm.weight").unwrap();
let gate_w = load_raw(&ar, "model.llm.layers.0.mlp.gate.weight").unwrap();
let gate_b = load_raw(&ar, "model.llm.layers.0.mlp.gate.bias").unwrap();
let m_sconv = load_bf16_as_f32(&ar, "model.llm.layers.0.mlp_sconv.weight").unwrap();
let mlp_query = load_raw(&ar, "model.llm.attn_res.mlp_queries.0").unwrap(); // F32 [2304]
// scratch + state
let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap(); let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap();
let in0 = DeviceBuf::alloc(hidden * 4).unwrap(); let mut blocks: Vec<DeviceBuf> = Vec::new();
let in0_bf = DeviceBuf::alloc(hidden * 2).unwrap(); crate::layer::layer_forward_swa(&ar, &lw, &mut st, &dims, &cur, &mut blocks, pos).unwrap();
let q = DeviceBuf::alloc(q_dim * 4).unwrap(); assert_eq!(blocks.len(), 1, "ip=0 must snapshot one depth block");
let k_raw = DeviceBuf::alloc(kv_dim * 4).unwrap();
let v_raw = DeviceBuf::alloc(kv_dim * 4).unwrap();
let r_raw = DeviceBuf::alloc(n_head * d_rel * 4).unwrap();
let gatea = DeviceBuf::alloc(q_dim * 4).unwrap();
let sinks = DeviceBuf::alloc(n_head * 4).unwrap();
let k_cv = DeviceBuf::alloc(kv_dim * 4).unwrap();
let v_cv = DeviceBuf::alloc(kv_dim * 4).unwrap();
let hist_k = DeviceBuf::alloc(3 * kv_dim * 4).unwrap(); hist_k.h2d(&vec![0f32; 3 * kv_dim]).unwrap();
let hist_v = DeviceBuf::alloc(3 * kv_dim * 4).unwrap(); hist_v.h2d(&vec![0f32; 3 * kv_dim]).unwrap();
let hist_a = DeviceBuf::alloc(3 * hidden * 4).unwrap(); hist_a.h2d(&vec![0f32; 3 * hidden]).unwrap();
let hist_m = DeviceBuf::alloc(3 * hidden * 4).unwrap(); hist_m.h2d(&vec![0f32; 3 * hidden]).unwrap();
let rel_bias = DeviceBuf::alloc(n_head * rel_extent * 4).unwrap(); rel_bias.h2d(&vec![0f32; n_head * rel_extent]).unwrap();
let k_cache = DeviceBuf::alloc(n_kv * steps * hd * 4).unwrap(); k_cache.h2d(&vec![0f32; n_kv * steps * hd]).unwrap();
let v_cache = DeviceBuf::alloc(n_kv * steps * hd * 4).unwrap(); v_cache.h2d(&vec![0f32; n_kv * steps * hd]).unwrap();
let aout = DeviceBuf::alloc(q_dim * 4).unwrap();
let aout_bf = DeviceBuf::alloc(q_dim * 2).unwrap();
let oproj = DeviceBuf::alloc(hidden * 4).unwrap();
let asc = DeviceBuf::alloc(hidden * 4).unwrap();
let block0 = DeviceBuf::alloc(hidden * 4).unwrap();
let mix_out = DeviceBuf::alloc(hidden * 4).unwrap();
let mlpin = DeviceBuf::alloc(hidden * 4).unwrap();
let mlpin_bf = DeviceBuf::alloc(hidden * 2).unwrap();
let rlog = DeviceBuf::alloc(n_experts * 4).unwrap();
let ids = DeviceBuf::alloc(top_k * 4).unwrap();
let weights = DeviceBuf::alloc(top_k * 4).unwrap();
let gu = DeviceBuf::alloc(2 * inter * 4).unwrap();
let act = DeviceBuf::alloc(inter * 4).unwrap();
let moeout = DeviceBuf::alloc(hidden * 4).unwrap();
let msc = DeviceBuf::alloc(hidden * 4).unwrap();
let slot0 = DeviceBuf::alloc(4).unwrap(); slot0.h2d_bytes(&0i32.to_le_bytes()).unwrap();
// === GPU full layer ===
// attention input: ip==0 -> attn_norm(cur)
vetta_infer_hip::rms_norm_f32(&cur, Some(&attn_norm), &in0, 1, hidden as i32, eps).unwrap();
vetta_infer_hip::cast_f32_bf16(&in0, &in0_bf, hidden).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wq, &q, 1, q_dim as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wk, &k_raw, 1, kv_dim as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wv, &v_raw, 1, kv_dim as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wr, &r_raw, 1, (n_head * d_rel) as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &wg, &gatea, 1, q_dim as i32, hidden as i32).unwrap();
vetta_infer_hip::gemm_bf16(&in0_bf, &ws, &sinks, 1, n_head as i32, hidden as i32).unwrap();
vetta_infer_hip::shortconv4_decode(&k_raw, &k_sconv, &hist_k, &k_cv, &slot0, 1, kv_dim as i32).unwrap();
vetta_infer_hip::shortconv4_decode(&v_raw, &v_sconv, &hist_v, &v_cv, &slot0, 1, kv_dim as i32).unwrap();
vetta_infer_hip::l2_clip(&q, Some(&q_sc), n_head as i32, hd as i32, qk_clip, false, pos).unwrap();
vetta_infer_hip::l2_clip(&r_raw, Some(&r_sc), n_head as i32, d_rel as i32, rel_clip, false, pos).unwrap();
vetta_infer_hip::l2_clip(&k_cv, None, n_kv as i32, hd as i32, qk_clip, false, pos).unwrap();
vetta_infer_hip::relpos_bias(&r_raw, &rel_proj, &rel_bias, n_head as i32, d_rel as i32, rel_extent as i32, 1).unwrap();
vetta_infer_hip::kv_store(&k_cv, &v_cv, &k_cache, &v_cache, pos, n_kv as i32, hd as i32, steps as i32, eps).unwrap();
vetta_infer_hip::flash_swa_gqa_decode(&q, &k_cache, &v_cache, &aout, n_head as i32, n_kv as i32, steps as i32, hd as i32, scale, 1024, pos, Some(&rel_bias), rel_extent as i32, Some(&sinks), Some(&gatea)).unwrap();
vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, q_dim).unwrap();
vetta_infer_hip::gemm_bf16(&aout_bf, &wo, &oproj, 1, hidden as i32, q_dim as i32).unwrap();
vetta_infer_hip::shortconv4_decode(&oproj, &a_sconv, &hist_a, &asc, &slot0, 1, hidden as i32).unwrap();
// block rule ip%6==0: block0 <- cur; cur = asc
let mut cur_host = vec![0f32; hidden]; cur.d2h(&mut cur_host).unwrap();
block0.h2d(&cur_host).unwrap();
let mut asc_host = vec![0f32; hidden]; asc.d2h(&mut asc_host).unwrap();
cur.h2d(&asc_host).unwrap();
// MoE input: mlp_norm(attn_res_mix([block0], cur, mlp_queries[0]))
vetta_infer_hip::attn_res_mix(&block0, &cur, &mlp_query, &mix_out, 1, 1, 1, hidden as i32, eps).unwrap();
vetta_infer_hip::rms_norm_f32(&mix_out, Some(&mlp_norm), &mlpin, 1, hidden as i32, eps).unwrap();
vetta_infer_hip::cast_f32_bf16(&mlpin, &mlpin_bf, hidden).unwrap();
vetta_infer_hip::gemm_bf16(&mlpin_bf, &gate_w, &rlog, 1, n_experts as i32, hidden as i32).unwrap();
vetta_infer_hip::moe_router_topk(&rlog, Some(&gate_b), &ids, &weights, 1, n_experts as i32, top_k as i32, route_scale).unwrap();
let ids_host = { let mut b = vec![0u8; top_k * 4]; ids.d2h_bytes(&mut b).unwrap(); b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect::<Vec<_>>() };
let mut y_part_host = vec![0f32; top_k * hidden];
for kk in 0..top_k {
let e = ids_host[kk] as usize;
let w13 = load_expert_matrix(&ar, 0, e, "w13").unwrap();
vetta_infer_hip::nvfp4_gemv(&w13.packed, &w13.scales, w13.outer, &mlpin, &gu, w13.n, w13.k).unwrap();
vetta_infer_hip::situ(&gu, &act, inter as i32, beta, lb).unwrap();
let w2 = load_expert_matrix(&ar, 0, e, "w2").unwrap();
let ye = DeviceBuf::alloc(hidden * 4).unwrap();
vetta_infer_hip::nvfp4_gemv(&w2.packed, &w2.scales, w2.outer, &act, &ye, w2.n, w2.k).unwrap();
ye.d2h(&mut y_part_host[kk * hidden..(kk + 1) * hidden]).unwrap();
}
let y_part = DeviceBuf::alloc(top_k * hidden * 4).unwrap(); y_part.h2d(&y_part_host).unwrap();
vetta_infer_hip::moe_reduce(&y_part, &weights, &moeout, top_k as i32, hidden as i32).unwrap();
vetta_infer_hip::shortconv4_decode(&moeout, &m_sconv, &hist_m, &msc, &slot0, 1, hidden as i32).unwrap();
vetta_infer_hip::vec_add(&cur, &msc, &cur, hidden).unwrap();
let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap(); let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap();
// === CPU oracle === // === CPU oracle ===