Added a reference-ground-truth debugging loop: drove the strata-inkling reference engine (--serve, GEN protocol) on the same prompts to obtain the correct continuations, then compared against vetta's forward. - tokenizers crate (fancy-regex) added to vetta-infer-ld for real BPE encode/decode from tokenizer.json. - forward_inkling_with_state: stateful variant exposing the persistent per-layer KV cache + shortconv history across decode positions, enabling autoregressive prefill + generation. forward_inkling wraps it with fresh state. - generate_continuation_real_prompt test: encode prompt -> token-by-token prefill -> greedy sampling via the hardened abi sampler -> decode. TWO REAL BUGS FOUND via reference comparison (reference: "The capital of France is" -> " Paris."; single token 100 -> argmax 68014): 1. embed_token omitted embed_norm: the reference k_embed_lookup fuses gather + RMS-normalize with embed_norm.weight. Fixed (gather then rms_norm). 2. full-attn ShortConv static_w transpose had REVERSED tap order: reference upload_sc uses kt[c*4+(3-lag)] = kw[lag*kv_dim+c]; fixed to match. NOTE: generation is still divergent after these two fixes (single-token argmax moved 120533 -> 100, reference 68014); further correctness debugging is in progress. These two fixes are verified-correct against the reference semantics. Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS; lean proofs (5 files) green; generation + full-forward tests run (--features hip, --ignored).
746 lines
42 KiB
Rust
746 lines
42 KiB
Rust
//! 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, 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,
|
|
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, &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)?;
|
|
if let Some((cw, msgs)) = ctrl {
|
|
apply_controller(&mlpin, &msgs.channel(3, h)?, cw, 3, h, 64, 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")?;
|
|
expert_gemv(&w13, &mlpin, &gu)?;
|
|
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)?;
|
|
expert_gemv(&w2, &act, &ye)?;
|
|
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(())
|
|
}
|
|
|
|
/// 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(ar: &SafetensorsArchive, token: i32, hidden: usize, vocab: usize) -> Result<DeviceBuf, String> {
|
|
let table = load_raw(ar, "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 = load_bf16_as_f32(ar, "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(ar: &SafetensorsArchive, cur: &DeviceBuf, hidden: usize, vocab: usize, eps: f32) -> Result<DeviceBuf, String> {
|
|
let norm = load_bf16_as_f32(ar, "model.llm.norm.weight")?;
|
|
let unembed = load_raw(ar, "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(ar: &SafetensorsArchive, cur: &DeviceBuf, blocks: &[DeviceBuf], hidden: usize, vocab: usize, eps: f32, cap: f32) -> Result<DeviceBuf, String> {
|
|
let oq = load_raw(ar, "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(ar, &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(
|
|
ar: &SafetensorsArchive, schedule: &[usize], d: &Dims, token: i32, max_seq: usize, pos: i32,
|
|
) -> Result<(DeviceBuf, Vec<DeviceBuf>), String> {
|
|
let cur = embed_token(ar, token, d.hidden, /*vocab*/ 201024)?;
|
|
let mut blocks: Vec<DeviceBuf> = Vec::new();
|
|
for &ip in schedule {
|
|
let w = load_layer(ar, ip, true)?;
|
|
let mut st = new_state(d, max_seq)?;
|
|
layer_forward_swa(ar, &w, &mut st, d, &cur, &mut blocks, pos, 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(ar: &SafetensorsArchive, ip: usize, hidden: usize) -> Result<DeviceBuf, String> {
|
|
let i = ip - 6;
|
|
let q_cp = load_raw(ar, "model.llm.middle_cycle_cross_pass_queries")?;
|
|
let kv_cp = load_raw(ar, "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)
|
|
}
|
|
|
|
/// Run one physical layer step (SWA or full-attn dispatch), reusing its
|
|
/// persistent state (KV cache + shortconv history) across loop passes.
|
|
fn run_layer(
|
|
ar: &SafetensorsArchive, d: &Dims, ip: usize, cur: &DeviceBuf, blocks: &mut Vec<DeviceBuf>,
|
|
states: &mut [Option<LayerState>], max_seq: usize, pos: i32,
|
|
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();
|
|
if is_swa(ip) {
|
|
let w = load_layer(ar, ip, true)?;
|
|
layer_forward_swa(ar, &w, st, d, cur, blocks, pos, ctrl)
|
|
} else {
|
|
let w = load_full_layer(ar, ip, d)?;
|
|
layer_forward_full(ar, &w, st, d, cur, blocks, pos, ctrl)
|
|
}
|
|
}
|
|
|
|
/// 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(
|
|
ar: &SafetensorsArchive, d: &Dims, token: i32, vocab: usize, max_seq: usize, pos: i32, cap: f32,
|
|
) -> Result<DeviceBuf, String> {
|
|
let mut states: Vec<Option<LayerState>> = (0..24).map(|_| None).collect();
|
|
forward_inkling_with_state(ar, 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(
|
|
ar: &SafetensorsArchive, d: &Dims, token: i32, vocab: usize, max_seq: usize, pos: i32, cap: f32,
|
|
states: &mut [Option<LayerState>],
|
|
) -> Result<DeviceBuf, String> {
|
|
let h = d.hidden;
|
|
let cur = embed_token(ar, token, h, vocab)?;
|
|
let mut blocks: Vec<DeviceBuf> = Vec::new();
|
|
// Prelude.
|
|
for ip in 0..6 { run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, None)?; }
|
|
let mut prelude = vec![0f32; h]; cur.d2h(&mut prelude)?;
|
|
let n_prelude_blocks = blocks.len();
|
|
// Core: 3 passes.
|
|
for p in 0..3 {
|
|
let mut bank: Vec<DeviceBuf> = 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 {
|
|
let mq = load_msg_queries(ar, 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 = load_controllers(ar, ip)?;
|
|
run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, Some((&cw, &msgs)))?;
|
|
} else {
|
|
run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, None)?;
|
|
}
|
|
}
|
|
}
|
|
// Coda.
|
|
for ip in 18..24 { run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, None)?; }
|
|
final_logits(ar, &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<DeviceBuf, String> {
|
|
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<f32> = 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<FullLayerWeights, String> {
|
|
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(
|
|
ar: &SafetensorsArchive, w: &FullLayerWeights, st: &mut LayerState, d: &Dims,
|
|
cur: &DeviceBuf, blocks: &mut Vec<DeviceBuf>, pos: i32,
|
|
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, &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, &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, &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)?;
|
|
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 let Some((cw, msgs)) = ctrl {
|
|
apply_controller(&mlpin, &msgs.channel(3, h)?, cw, 3, h, 64, d.eps)?;
|
|
}
|
|
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")?;
|
|
expert_gemv(&w13, &mlpin, &gu)?;
|
|
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)?;
|
|
expert_gemv(&w2, &act, &ye)?;
|
|
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)?;
|
|
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(())
|
|
}
|
|
|
|
/// 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<ControllerWeights, String> {
|
|
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<DeviceBuf, String> {
|
|
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 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(&ar, &[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(&ar, &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 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(&ar, 100, d.hidden, 201024).unwrap();
|
|
let mut blocks: Vec<DeviceBuf> = 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(&ar, &w, &mut st, &d, &cur, &mut blocks, 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 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(&ar, &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<usize> = (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 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<i32> = tok.encode(prompt, false).unwrap().get_ids().iter().map(|&x| x as i32).collect();
|
|
let n_gen = 16usize;
|
|
let max_seq = ids.len() + n_gen + 2;
|
|
let mut states: Vec<Option<LayerState>> = (0..24).map(|_| None).collect();
|
|
let mut history: Vec<i32> = Vec::new();
|
|
let mut pos = 0i32;
|
|
let mut logits = DeviceBuf::alloc(vocab * 4).unwrap();
|
|
for &t in &ids {
|
|
logits = forward_inkling_with_state(&ar, &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<u32> = 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(&ar, &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());
|
|
}
|
|
} |