[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:
1 parent
25ffc820f8
commit
0929bde578
3 files changed
+230
-105
No files matched your search
@@ -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(())
|
||||
}
|
||||
Reference in new issue
Block a user