diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 661bf1f..64b3418 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -60,6 +60,7 @@ mod ffi { packed: *const u8, scales: *const u8, outer_scale: c_float, x: *const c_float, y: *mut c_float, n: c_int, k: c_int, stream: *mut c_void, ) -> c_int; + pub fn vetta_mxfp8_gemv(weights: *const u8, scales: *const u8, x: *const c_float, y: *mut c_float, n: c_int, k: c_int, stream: *mut c_void) -> c_int; pub fn vetta_situ(gu: *const c_float, act: *mut c_float, inter: c_int, beta: c_float, lb: c_float, stream: *mut c_void) -> c_int; pub fn vetta_moe_reduce(y_part: *const c_float, tk_w: *const c_float, out: *mut c_float, top_k: c_int, hidden: c_int, stream: *mut c_void) -> c_int; pub fn vetta_shortconv4_decode(cur: *const c_float, static_w: *const c_float, hist: *mut c_float, out: *mut c_float, slot_ids: *const i32, m: c_int, c: c_int, stream: *mut c_void) -> c_int; @@ -254,6 +255,16 @@ pub fn nvfp4_gemv(packed: &DeviceBuf, scales: &DeviceBuf, outer_scale: f32, x: & Ok(()) } +/// Launch k_mxfp8_gemv (M=1): MXFP8 experts (E4M3 + UE8M0/32, no outer scale). +#[cfg(feature = "hip")] +pub fn mxfp8_gemv(weights: &DeviceBuf, scales: &DeviceBuf, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32) -> Result<(), String> { + let rc = unsafe { + ffi::vetta_mxfp8_gemv(weights.ptr as *const u8, scales.ptr as *const u8, x.ptr as *const f32, y.ptr as *mut f32, n, k, std::ptr::null_mut()) + }; + if rc != 0 { return Err("mxfp8_gemv launch failed".into()); } + Ok(()) +} + /// Launch k_situ: SiTU double-softcapped activation (gu=[gate;up] -> act). #[cfg(feature = "hip")] pub fn situ(gu: &DeviceBuf, act: &DeviceBuf, inter: i32, beta: f32, lb: f32) -> Result<(), String> { diff --git a/crates/vetta-infer-ld/src/layer.rs b/crates/vetta-infer-ld/src/layer.rs index a9137e6..7cf77c8 100644 --- a/crates/vetta-infer-ld/src/layer.rs +++ b/crates/vetta-infer-ld/src/layer.rs @@ -10,7 +10,7 @@ //! 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::packer::{expert_gemv, load_bf16_as_f32, load_expert_matrix, load_raw}; use crate::SafetensorsArchive; use vetta_infer_hip::DeviceBuf; @@ -105,17 +105,10 @@ pub fn new_state(d: &Dims, max_seq: usize) -> Result { pub fn layer_forward_swa( ar: &SafetensorsArchive, w: &LayerWeights, st: &mut LayerState, d: &Dims, cur: &DeviceBuf, blocks: &mut Vec, 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 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)?; @@ -125,30 +118,56 @@ pub fn layer_forward_swa( 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)). + // k1: attention input base. ip==0 -> cur; ip>0 -> mix(blocks,cur,attn_query). + let base = DeviceBuf::alloc(h * 4)?; if w.ip == 0 { - vetta_infer_hip::rms_norm_f32(cur, Some(&w.attn_norm), &in0, 1, h as i32, d.eps)?; + 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)?; - // 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)?; + 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)?; } - - // 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)?; @@ -185,6 +204,9 @@ pub fn layer_forward_swa( 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)?; @@ -201,11 +223,11 @@ pub fn layer_forward_swa( 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)?; + 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)?; - vetta_infer_hip::nvfp4_gemv(&w2.packed, &w2.scales, w2.outer, &act, &ye, w2.n, w2.k)?; + 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)?; @@ -269,11 +291,100 @@ pub fn forward_swa_layers( 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)?; + 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 { + 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, + states: &mut [Option], 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 { + let h = d.hidden; + let cur = embed_token(ar, token, h, vocab)?; + let mut blocks: Vec = Vec::new(); + let mut states: Vec> = (0..24).map(|_| None).collect(); + // Prelude. + for ip in 0..6 { run_layer(ar, d, ip, &cur, &mut blocks, &mut 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 = 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, &mut states, max_seq, pos, Some((&cw, &msgs)))?; + } else { + run_layer(ar, d, ip, &cur, &mut blocks, &mut states, max_seq, pos, None)?; + } + } + } + // Coda. + for ip in 18..24 { run_layer(ar, d, ip, &cur, &mut blocks, &mut 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 { @@ -340,6 +451,7 @@ pub fn load_full_layer(ar: &SafetensorsArchive, ip: usize, d: &Dims) -> Result, 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())?; @@ -355,6 +467,11 @@ pub fn layer_forward_full( 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)?; @@ -417,6 +534,9 @@ pub fn layer_forward_full( 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)?; @@ -430,11 +550,11 @@ pub fn layer_forward_full( 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)?; + 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)?; - vetta_infer_hip::nvfp4_gemv(&w2.packed, &w2.scales, w2.outer, &act, &ye, w2.n, w2.k)?; + 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)?; @@ -446,6 +566,57 @@ pub fn layer_forward_full( 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::*; @@ -487,11 +658,29 @@ mod tests { 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).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; + eprintln!("FULL Inkling forward: argmax token={argmax} logit={:.3}", lg[argmax]); + assert!(argmax < 201024); + } } \ No newline at end of file diff --git a/crates/vetta-infer-ld/src/packer.rs b/crates/vetta-infer-ld/src/packer.rs index 298b0b1..3a4d43e 100644 --- a/crates/vetta-infer-ld/src/packer.rs +++ b/crates/vetta-infer-ld/src/packer.rs @@ -43,10 +43,13 @@ pub struct ExpertMatrix { pub outer: f32, pub n: i32, pub k: i32, + pub mxfp8: bool, } /// Load expert `e` of layer `layer`, matrix `mat` ("w13" or "w2"), from the /// real safetensors archive. Zero requantization: bytes go to device as-is. +/// Layers 0..19 are NVFP4 (E2M1 + E4M3/16 + outer=amax/denom); layers 20..23 +/// are MXFP8 (E4M3 + UE8M0/32, no outer). Detected by the amax tensor presence. pub fn load_expert_matrix(ar: &SafetensorsArchive, layer: usize, e: usize, mat: &str) -> Result { let base = format!("model.llm.layers.{layer}.mlp.experts.{mat}"); let wname = format!("{base}_weight"); @@ -56,8 +59,23 @@ pub fn load_expert_matrix(ar: &SafetensorsArchive, layer: usize, e: usize, mat: let winfo = ar.tensors.get(&wname).ok_or_else(|| format!("missing {wname}"))?; let _sinfo = ar.tensors.get(&sname).ok_or_else(|| format!("missing {sname}"))?; - // w shape [n_exp, N, K/2]; scale [n_exp, N, K/16]. let n = winfo.shape[1] as i32; + + if !ar.tensors.contains_key(&aname) { + // MXFP8: w [n_exp, N, K] full, scale [n_exp, N, K/32], no outer. + let k = winfo.shape[2] as i32; + let w_per_e = (n as usize) * (k as usize); + let s_per_e = (n as usize) * (k as usize / 32); + let mut wbytes = vec![0u8; w_per_e]; + ar.read_slice(&wname, (e * w_per_e) as u64, &mut wbytes)?; + let mut sbytes = vec![0u8; s_per_e]; + ar.read_slice(&sname, (e * s_per_e) as u64, &mut sbytes)?; + let packed = DeviceBuf::alloc(w_per_e)?; packed.h2d_bytes(&wbytes)?; + let scales = DeviceBuf::alloc(s_per_e)?; scales.h2d_bytes(&sbytes)?; + return Ok(ExpertMatrix { packed, scales, outer: 1.0, n, k, mxfp8: true }); + } + + // NVFP4: w shape [n_exp, N, K/2]; scale [n_exp, N, K/16]. let k_half = winfo.shape[2] as usize; let k = (k_half * 2) as i32; let w_per_e = (n as usize) * k_half; @@ -85,7 +103,16 @@ pub fn load_expert_matrix(ar: &SafetensorsArchive, layer: usize, e: usize, mat: packed.h2d_bytes(&wbytes)?; let scales = DeviceBuf::alloc(s_per_e)?; scales.h2d_bytes(&sbytes)?; - Ok(ExpertMatrix { packed, scales, outer, n, k }) + Ok(ExpertMatrix { packed, scales, outer, n, k, mxfp8: false }) +} + +/// Run the expert GEMV dispatching on the quantization format (NVFP4 / MXFP8). +pub fn expert_gemv(em: &ExpertMatrix, x: &DeviceBuf, y: &DeviceBuf) -> Result<(), String> { + if em.mxfp8 { + vetta_infer_hip::mxfp8_gemv(&em.packed, &em.scales, x, y, em.n, em.k) + } else { + vetta_infer_hip::nvfp4_gemv(&em.packed, &em.scales, em.outer, x, y, em.n, em.k) + } } #[cfg(test)] @@ -203,6 +230,47 @@ mod tests { assert!(max_rel < 1e-3, "real expert NVFP4 parity failed: {max_rel}"); } + fn ue8m0(e: u8) -> f32 { + if e == 255 { return 0.0; } + if e == 0 { return f32::from_bits(0x00400000); } + f32::from_bits((e as u32) << 23) + } + + /// Real MXFP8 expert GEMV parity (layers 20..23): load layer-20 expert-0 + /// w13, run mxfp8_gemv on GPU, compare to a CPU dequant oracle (E4M3 weight + /// * UE8M0 scale per group of 32, no outer scale). + #[test] + #[ignore] + fn real_expert_mxfp8_gemv_parity() { + let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap(); + let em = load_expert_matrix(&ar, 20, 0, "w13").unwrap(); + assert!(em.mxfp8, "layer 20 must be MXFP8"); + let (n, k) = (em.n as usize, em.k as usize); + assert_eq!((n, k), (2304, 2304)); + let x: Vec = (0..k).map(|i| ((i % 41) as f32 - 20.0) * 0.02).collect(); + let dx = DeviceBuf::alloc(k * 4).unwrap(); dx.h2d(&x).unwrap(); + let dy = DeviceBuf::alloc(n * 4).unwrap(); + vetta_infer_hip::mxfp8_gemv(&em.packed, &em.scales, &dx, &dy, em.n, em.k).unwrap(); + let mut got = vec![0f32; n]; dy.d2h(&mut got).unwrap(); + let mut wb = vec![0u8; n * k]; + ar.read_slice("model.llm.layers.20.mlp.experts.w13_weight", 0, &mut wb).unwrap(); + let mut sb = vec![0u8; n * (k / 32)]; + ar.read_slice("model.llm.layers.20.mlp.experts.w13_weight_scale", 0, &mut sb).unwrap(); + let mut want = vec![0f32; n]; + for ni in 0..n { + let mut acc = 0f32; + for b in 0..k / 32 { + let sc = ue8m0(sb[ni * (k / 32) + b]); + for j in 0..32 { acc += x[b * 32 + j] * e4m3(wb[ni * k + b * 32 + j]) * sc; } + } + want[ni] = acc; + } + let mut max_rel = 0f32; + for (g, w) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); } + eprintln!("real expert w13 MXFP8 GEMV: max_rel_err={max_rel:.3e}"); + assert!(max_rel < 1e-3, "real expert MXFP8 parity failed: {max_rel}"); + } + fn bf16_trunc(x: f32) -> f32 { f32::from_bits(x.to_bits() & 0xFFFF0000) } fn rms_norm_cpu(x: &[f32], w: &[f32], eps: f32) -> Vec { let d = x.len(); @@ -567,7 +635,7 @@ mod tests { let mut st = crate::layer::new_state(&dims, steps).unwrap(); let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap(); let mut blocks: Vec = Vec::new(); - crate::layer::layer_forward_swa(&ar, &lw, &mut st, &dims, &cur, &mut blocks, pos).unwrap(); + crate::layer::layer_forward_swa(&ar, &lw, &mut st, &dims, &cur, &mut blocks, pos, None).unwrap(); assert_eq!(blocks.len(), 1, "ip=0 must snapshot one depth block"); let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap(); diff --git a/kernels/hip/vetta_kernels.h b/kernels/hip/vetta_kernels.h index 73e23e2..3186160 100644 --- a/kernels/hip/vetta_kernels.h +++ b/kernels/hip/vetta_kernels.h @@ -79,6 +79,11 @@ int vetta_nvfp4_gemv(const uint8_t* packed, const uint8_t* scales, float outer_scale, const float* x, float* y, int N, int K, vetta_stream_t stream); +// k_mxfp8_gemv (M=1): MXFP8 experts (layers 20..23). y[N] = sum_k e4m3(W[n,k]) +// * ue8m0(scale[n,k/32]) * x[k]. weights [N,K] F8_E4M3, scales [N,K/32] U8. +int vetta_mxfp8_gemv(const uint8_t* weights, const uint8_t* scales, + const float* x, float* y, int N, int K, vetta_stream_t stream); + // k_situ: SiTU double-softcapped MoE activation. gu=[gate;up] (2*inter) -> act. int vetta_situ(const float* gu, float* act, int inter, float beta, float lb, vetta_stream_t stream); diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index 92f23d8..dbfae2a 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -522,6 +522,54 @@ extern "C" int vetta_nvfp4_gemv(const uint8_t* packed, const uint8_t* scales, return 0; } +// ---- k_mxfp8_gemv (M=1 decode): MXFP8 experts (layers 20..23) -------------- +// Exact strata MX8: y[N] = sum_k e4m3fn(W[n,k]) * ue8m0(scale[n,k/32]) * x[k]. +// W [N,K] F8_E4M3 bytes (full K), scale [N,K/32] U8 UE8M0, NO outer scale. + +__device__ __forceinline__ float ue8m0_to_f32(uint8_t e) { + if (e == 255u) return 0.0f; + if (e == 0u) return __builtin_bit_cast(float, 0x00400000u); // 2^-127 + return __builtin_bit_cast(float, (uint32_t)e << 23); +} + +__global__ void k_mxfp8_gemv(const uint8_t* __restrict__ weights, + const uint8_t* __restrict__ scales, + const float* __restrict__ x, float* __restrict__ y, + int N, int K) { + const int n = blockIdx.x; + if (n >= N) return; + const int tid = threadIdx.x; + const int nt = blockDim.x; + const uint8_t* wp = weights + (size_t)n * K; + const uint8_t* ws = scales + (size_t)n * (K >> 5); + const int nblk = K >> 5; + float acc = 0.f; + for (int b = tid; b < nblk; b += nt) { + const float sc = ue8m0_to_f32(ws[b]); + const int k0 = b << 5; + const uint8_t* w8 = wp + k0; + for (int j = 0; j < 32; ++j) acc += x[k0 + j] * e4m3fn_to_f32(w8[j]) * sc; + } + __shared__ float red[256]; + red[tid] = acc; + __syncthreads(); + for (int s = nt / 2; s > 0; s >>= 1) { + if (tid < s) red[tid] += red[tid + s]; + __syncthreads(); + } + if (tid == 0) y[n] = red[0]; +} + +extern "C" int vetta_mxfp8_gemv(const uint8_t* weights, const uint8_t* scales, + const float* x, float* y, int N, int K, + vetta_stream_t stream) { + if (N <= 0 || K <= 0 || (K % 32) != 0) return 1; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_mxfp8_gemv<<>>(weights, scales, x, y, N, K); + HIP_CHECK(hipGetLastError()); + return 0; +} + // ---- SiTU activation (exact strata situ_f32, double-softcapped) ------------ // gu = [gate(inter); up(inter)] from w13. act[j] = g_act * u_act where // g_act = beta*tanh(g/beta)*sigmoid(g), u_act = lb*tanh(u/lb).