[LD] Resident WeightCache: memoize device uploads across decode tokens

Per-token forward re-read ~3 GiB of NVFP4/MXFP8 expert blobs from NVMe and
re-uploaded every layer/norm/query tensor. WeightCache borrows the archive and
memoizes raw tensors, BF16->F32 norms, per-layer weights, controllers and expert
matrices (Arc, interior mutability) so autoregressive decode reuses GPU-resident
weights. The forward path now takes &WeightCache; serve_gen creates one cache
per request shared across prefill + decode.

MEASURED (gfx1150, debug): 21 forwards 36s -> 8.8s (~4x); parity unchanged
(first tokens [152717,13,68014,32,13] exact). Release steady decode ~3.8 tok/s
(DONE 64: decode_ms 16909 over 64 tokens). Suite green: 18 ld GPU + 17 hip GPU.
This commit is contained in:
adm committed 2026-12-01 17:18:21 +01:00
1 parent 5ec55f753f
commit 1df8342f96
3 files changed
+152 -55

No files matched your search

+9 -4
View File
@@ -26,7 +26,7 @@ use vetta_infer_abi::sampler::{
use vetta_infer_abi::serve::{parse_serve_line, ParsedGen, ServeCommand}; use vetta_infer_abi::serve::{parse_serve_line, ParsedGen, ServeCommand};
use vetta_infer_hip::DeviceBuf; use vetta_infer_hip::DeviceBuf;
use vetta_infer_ld::inkling::parse_config; use vetta_infer_ld::inkling::parse_config;
use vetta_infer_ld::layer::{forward_inkling_with_state, Dims, LayerState}; use vetta_infer_ld::layer::{forward_inkling_with_state, Dims, LayerState, WeightCache};
use vetta_infer_ld::SafetensorsArchive; use vetta_infer_ld::SafetensorsArchive;
use crate::session::ServeSession; use crate::session::ServeSession;
@@ -105,12 +105,13 @@ impl InklingEngine {
fn forward( fn forward(
&self, &self,
cache: &WeightCache,
token: i32, token: i32,
pos: i32, pos: i32,
max_seq: usize, max_seq: usize,
states: &mut [Option<LayerState>], states: &mut [Option<LayerState>],
) -> Result<DeviceBuf, String> { ) -> Result<DeviceBuf, String> {
forward_inkling_with_state(&self.ar, &self.d, token, self.vocab, max_seq, pos, self.cap, states) forward_inkling_with_state(cache, &self.d, token, self.vocab, max_seq, pos, self.cap, states)
} }
} }
@@ -152,6 +153,10 @@ pub fn serve_gen(
} }
}; };
// Resident weight cache for this request: weights upload once and stay on
// the GPU across prefill + decode (no per-token NVMe expert re-reads).
let cache = WeightCache::new(&eng.ar);
// --- Prefill: run the forward over every prompt token, growing KV/history. --- // --- Prefill: run the forward over every prompt token, growing KV/history. ---
let t0 = Instant::now(); let t0 = Instant::now();
let mut pos = 0i32; let mut pos = 0i32;
@@ -165,7 +170,7 @@ pub fn serve_gen(
stop.store(false, Ordering::Relaxed); stop.store(false, Ordering::Relaxed);
return; return;
} }
match eng.forward(tok, pos, max_seq, &mut states) { match eng.forward(&cache, tok, pos, max_seq, &mut states) {
Ok(lg) => logits = Some(lg), Ok(lg) => logits = Some(lg),
Err(e) => { Err(e) => {
emit_all(emit, sess.on_error(&e)); emit_all(emit, sess.on_error(&e));
@@ -245,7 +250,7 @@ pub fn serve_gen(
finish = "length"; finish = "length";
break; break;
} }
match eng.forward(rep.token, pos, max_seq, &mut states) { match eng.forward(&cache, rep.token, pos, max_seq, &mut states) {
Ok(l) => logits = l, Ok(l) => logits = l,
Err(e) => { Err(e) => {
emit_all(emit, sess.on_error(&e)); emit_all(emit, sess.on_error(&e));
+139 -49
View File
@@ -10,8 +10,11 @@
//! layers (3-query split), loop controllers (gain/forget/down) and the //! layers (3-query split), loop controllers (gain/forget/down) and the
//! multi-pass bank rollback are layered on next. //! multi-pass bank rollback are layered on next.
use crate::packer::{expert_gemv, expert_gemv_f16, load_bf16_as_f32, load_expert_matrix, load_raw}; use crate::packer::{expert_gemv, expert_gemv_f16, load_bf16_as_f32, load_expert_matrix, load_raw, ExpertMatrix};
use crate::SafetensorsArchive; use crate::SafetensorsArchive;
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;
use vetta_infer_hip::DeviceBuf; use vetta_infer_hip::DeviceBuf;
/// Resident weights for one physical layer step `ip`. /// Resident weights for one physical layer step `ip`.
@@ -59,6 +62,89 @@ impl Dims {
pub fn scale(&self) -> f32 { 1.0 / (self.hd as f32).sqrt() } pub fn scale(&self) -> f32 { 1.0 / (self.hd as f32).sqrt() }
} }
/// Resident weight cache: memoizes every device upload (raw tensors, BF16->F32
/// norms, per-layer weights, controllers and the NVFP4/MXFP8 expert matrices)
/// so autoregressive decode reuses GPU-resident weights instead of re-reading
/// ~3 GiB of expert blobs from NVMe per token. Borrows the archive; the maps
/// use interior mutability so the forward can hold shared `&WeightCache` while
/// loading lazily. Single-threaded forward (serve decodes on one thread).
pub struct WeightCache<'a> {
pub ar: &'a SafetensorsArchive,
raw: RefCell<HashMap<String, Arc<DeviceBuf>>>,
bf16: RefCell<HashMap<String, Arc<DeviceBuf>>>,
sconv: RefCell<HashMap<(String, usize), Arc<DeviceBuf>>>,
swa: RefCell<HashMap<usize, Arc<LayerWeights>>>,
full: RefCell<HashMap<usize, Arc<FullLayerWeights>>>,
experts: RefCell<HashMap<(usize, usize, String), Arc<ExpertMatrix>>>,
ctrl: RefCell<HashMap<usize, Arc<ControllerWeights>>>,
}
impl<'a> WeightCache<'a> {
pub fn new(ar: &'a SafetensorsArchive) -> Self {
Self {
ar,
raw: RefCell::new(HashMap::new()),
bf16: RefCell::new(HashMap::new()),
sconv: RefCell::new(HashMap::new()),
swa: RefCell::new(HashMap::new()),
full: RefCell::new(HashMap::new()),
experts: RefCell::new(HashMap::new()),
ctrl: RefCell::new(HashMap::new()),
}
}
pub fn raw(&self, name: &str) -> Result<Arc<DeviceBuf>, String> {
if let Some(v) = self.raw.borrow().get(name) { return Ok(v.clone()); }
let v = Arc::new(load_raw(self.ar, name)?);
self.raw.borrow_mut().insert(name.to_string(), v.clone());
Ok(v)
}
pub fn bf16_f32(&self, name: &str) -> Result<Arc<DeviceBuf>, String> {
if let Some(v) = self.bf16.borrow().get(name) { return Ok(v.clone()); }
let v = Arc::new(load_bf16_as_f32(self.ar, name)?);
self.bf16.borrow_mut().insert(name.to_string(), v.clone());
Ok(v)
}
pub fn sconv_t(&self, name: &str, c: usize) -> Result<Arc<DeviceBuf>, String> {
let key = (name.to_string(), c);
if let Some(v) = self.sconv.borrow().get(&key) { return Ok(v.clone()); }
let v = Arc::new(load_sconv_transposed(self.ar, name, c)?);
self.sconv.borrow_mut().insert(key, v.clone());
Ok(v)
}
pub fn swa_layer(&self, ip: usize) -> Result<Arc<LayerWeights>, String> {
if let Some(v) = self.swa.borrow().get(&ip) { return Ok(v.clone()); }
let v = Arc::new(load_layer(self.ar, ip, true)?);
self.swa.borrow_mut().insert(ip, v.clone());
Ok(v)
}
pub fn full_layer(&self, ip: usize, d: &Dims) -> Result<Arc<FullLayerWeights>, String> {
if let Some(v) = self.full.borrow().get(&ip) { return Ok(v.clone()); }
let v = Arc::new(load_full_layer(self.ar, ip, d)?);
self.full.borrow_mut().insert(ip, v.clone());
Ok(v)
}
pub fn expert(&self, ip: usize, e: usize, mat: &str) -> Result<Arc<ExpertMatrix>, String> {
let key = (ip, e, mat.to_string());
if let Some(v) = self.experts.borrow().get(&key) { return Ok(v.clone()); }
let v = Arc::new(load_expert_matrix(self.ar, ip, e, mat)?);
self.experts.borrow_mut().insert(key, v.clone());
Ok(v)
}
pub fn controllers(&self, ip: usize) -> Result<Arc<ControllerWeights>, String> {
if let Some(v) = self.ctrl.borrow().get(&ip) { return Ok(v.clone()); }
let v = Arc::new(load_controllers(self.ar, ip)?);
self.ctrl.borrow_mut().insert(ip, v.clone());
Ok(v)
}
}
pub fn load_layer(ar: &SafetensorsArchive, ip: usize, is_swa: bool) -> Result<LayerWeights, String> { pub fn load_layer(ar: &SafetensorsArchive, ip: usize, is_swa: bool) -> Result<LayerWeights, String> {
let p = format!("model.llm.layers.{ip}.attn"); let p = format!("model.llm.layers.{ip}.attn");
let attn_query = if ip > 0 { let attn_query = if ip > 0 {
@@ -106,7 +192,7 @@ pub fn new_state(d: &Dims, max_seq: usize) -> Result<LayerState, String> {
/// to `blocks` when `ip % block_size == 0`. `pos` is the decode position. /// to `blocks` when `ip % block_size == 0`. `pos` is the decode position.
/// Experts are loaded on demand from `ar` (zero requantization). /// Experts are loaded on demand from `ar` (zero requantization).
pub fn layer_forward_swa( pub fn layer_forward_swa(
ar: &SafetensorsArchive, w: &LayerWeights, st: &mut LayerState, d: &Dims, cache: &WeightCache, w: &LayerWeights, st: &mut LayerState, d: &Dims,
cur: &DeviceBuf, blocks: &mut Vec<DeviceBuf>, pos: i32, cur: &DeviceBuf, blocks: &mut Vec<DeviceBuf>, pos: i32,
pass: usize, pass: usize,
ctrl: Option<(&ControllerWeights, &LoopMsgs)>, ctrl: Option<(&ControllerWeights, &LoopMsgs)>,
@@ -227,7 +313,7 @@ pub fn layer_forward_swa(
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)?; 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 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<_>>() };
if std::env::var("VETTA_DBG_IDS").is_ok() { eprintln!("[dbg] ip={} GPU experts={:?}", w.ip, ids_h); } if std::env::var("VETTA_DBG_IDS").is_ok() { eprintln!("[dbg] ip={} GPU experts={:?}", w.ip, ids_h); }
let y_part_h = run_experts(ar, w.ip, &ids_h, &mlpin, d, h)?; let y_part_h = run_experts(cache, w.ip, &ids_h, &mlpin, d, h)?;
let y_part = DeviceBuf::alloc(d.top_k * h * 4)?; y_part.h2d(&y_part_h)?; let y_part = DeviceBuf::alloc(d.top_k * h * 4)?; y_part.h2d(&y_part_h)?;
let moeout = DeviceBuf::alloc(h * 4)?; let moeout = DeviceBuf::alloc(h * 4)?;
vetta_infer_hip::moe_reduce(&y_part, &weights, &moeout, d.top_k as i32, h as i32)?; vetta_infer_hip::moe_reduce(&y_part, &weights, &moeout, d.top_k as i32, h as i32)?;
@@ -243,20 +329,20 @@ pub fn layer_forward_swa(
/// Embed a single token id from the real BF16 embed table -> f32 cur [hidden]. /// 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 /// Exact strata k_embed_lookup: gather the row THEN RMS-normalize it with
/// embed_norm.weight (the embed lookup fuses gather + norm). /// embed_norm.weight (the embed lookup fuses gather + norm).
pub fn embed_token(ar: &SafetensorsArchive, token: i32, hidden: usize, vocab: usize) -> Result<DeviceBuf, String> { pub fn embed_token(cache: &WeightCache, token: i32, hidden: usize, vocab: usize) -> Result<DeviceBuf, String> {
let table = load_raw(ar, "model.llm.embed.weight")?; let table = cache.raw("model.llm.embed.weight")?;
let tok = DeviceBuf::alloc(4)?; tok.h2d_bytes(&token.to_le_bytes())?; let tok = DeviceBuf::alloc(4)?; tok.h2d_bytes(&token.to_le_bytes())?;
let cur = DeviceBuf::alloc(hidden * 4)?; let cur = DeviceBuf::alloc(hidden * 4)?;
vetta_infer_hip::embed_bf16_gather(&table, &tok, &cur, 1, hidden as i32, vocab as i32)?; 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")?; let emb_norm = cache.bf16_f32("model.llm.embed_norm.weight")?;
vetta_infer_hip::rms_norm_f32(&cur, Some(&emb_norm), &cur, 1, hidden as i32, 1e-6)?; vetta_infer_hip::rms_norm_f32(&cur, Some(&emb_norm), &cur, 1, hidden as i32, 1e-6)?;
Ok(cur) Ok(cur)
} }
/// Final norm + cast + unembed GEMM -> f32 logits [vocab]. /// 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> { pub fn unembed_logits(cache: &WeightCache, cur: &DeviceBuf, hidden: usize, vocab: usize, eps: f32) -> Result<DeviceBuf, String> {
let norm = load_bf16_as_f32(ar, "model.llm.norm.weight")?; let norm = cache.bf16_f32("model.llm.norm.weight")?;
let unembed = load_raw(ar, "model.llm.unembed.weight")?; let unembed = cache.raw("model.llm.unembed.weight")?;
let n = DeviceBuf::alloc(hidden * 4)?; let n = DeviceBuf::alloc(hidden * 4)?;
vetta_infer_hip::rms_norm_f32(cur, Some(&norm), &n, 1, hidden as i32, eps)?; vetta_infer_hip::rms_norm_f32(cur, Some(&norm), &n, 1, hidden as i32, eps)?;
let nb = DeviceBuf::alloc(hidden * 2)?; let nb = DeviceBuf::alloc(hidden * 2)?;
@@ -269,8 +355,8 @@ pub fn unembed_logits(ar: &SafetensorsArchive, cur: &DeviceBuf, hidden: usize, v
/// Correct final output path: the final norm is itself an AttnRes depth mix /// Correct final output path: the final norm is itself an AttnRes depth mix
/// (output_query over blocks + cur), then norm + unembed + logit softcap. /// (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)). /// 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> { pub fn final_logits(cache: &WeightCache, 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 oq = cache.raw("model.llm.attn_res.output_query")?;
let n_blocks = blocks.len(); let n_blocks = blocks.len();
let blk = DeviceBuf::alloc(n_blocks.max(1) * hidden * 4)?; let blk = DeviceBuf::alloc(n_blocks.max(1) * hidden * 4)?;
let mut bh = vec![0f32; n_blocks.max(1) * hidden]; let mut bh = vec![0f32; n_blocks.max(1) * hidden];
@@ -278,7 +364,7 @@ pub fn final_logits(ar: &SafetensorsArchive, cur: &DeviceBuf, blocks: &[DeviceBu
blk.h2d(&bh)?; blk.h2d(&bh)?;
let mix = DeviceBuf::alloc(hidden * 4)?; 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)?; 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)?; let logits = unembed_logits(cache, &mix, hidden, vocab, eps)?;
if cap > 0.0 { vetta_infer_hip::softcap(&logits, &logits, vocab, cap)?; } if cap > 0.0 { vetta_infer_hip::softcap(&logits, &logits, vocab, cap)?; }
Ok(logits) Ok(logits)
} }
@@ -287,14 +373,14 @@ pub fn final_logits(ar: &SafetensorsArchive, cur: &DeviceBuf, blocks: &[DeviceBu
/// final residual stream + the accumulated depth-block snapshots. (Prelude / /// final residual stream + the accumulated depth-block snapshots. (Prelude /
/// single-pass; full-attn layers + loop controllers + bank rollback come next.) /// single-pass; full-attn layers + loop controllers + bank rollback come next.)
pub fn forward_swa_layers( pub fn forward_swa_layers(
ar: &SafetensorsArchive, schedule: &[usize], d: &Dims, token: i32, max_seq: usize, pos: i32, cache: &WeightCache, schedule: &[usize], d: &Dims, token: i32, max_seq: usize, pos: i32,
) -> Result<(DeviceBuf, Vec<DeviceBuf>), String> { ) -> Result<(DeviceBuf, Vec<DeviceBuf>), String> {
let cur = embed_token(ar, token, d.hidden, /*vocab*/ 201024)?; let cur = embed_token(cache, token, d.hidden, /*vocab*/ 201024)?;
let mut blocks: Vec<DeviceBuf> = Vec::new(); let mut blocks: Vec<DeviceBuf> = Vec::new();
for &ip in schedule { for &ip in schedule {
let w = load_layer(ar, ip, true)?; let w = cache.swa_layer(ip)?;
let mut st = new_state(d, max_seq)?; let mut st = new_state(d, max_seq)?;
layer_forward_swa(ar, &w, &mut st, d, &cur, &mut blocks, pos, 0, None)?; layer_forward_swa(cache, &w, &mut st, d, &cur, &mut blocks, pos, 0, None)?;
} }
Ok((cur, blocks)) Ok((cur, blocks))
} }
@@ -304,10 +390,10 @@ 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: /// 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. /// [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> { fn load_msg_queries(cache: &WeightCache, ip: usize, hidden: usize) -> Result<DeviceBuf, String> {
let i = ip - 6; let i = ip - 6;
let q_cp = load_raw(ar, "model.llm.middle_cycle_cross_pass_queries")?; let q_cp = cache.raw("model.llm.middle_cycle_cross_pass_queries")?;
let kv_cp = load_raw(ar, "model.llm.middle_cycle_cross_pass_kv_queries")?; let kv_cp = cache.raw("model.llm.middle_cycle_cross_pass_kv_queries")?;
let mut qh = vec![0f32; 24 * hidden]; q_cp.d2h(&mut qh)?; let mut qh = vec![0f32; 24 * hidden]; q_cp.d2h(&mut qh)?;
let mut kh = vec![0f32; 24 * hidden]; kv_cp.d2h(&mut kh)?; let mut kh = vec![0f32; 24 * hidden]; kv_cp.d2h(&mut kh)?;
let mut mq = vec![0f32; 4 * hidden]; let mut mq = vec![0f32; 4 * hidden];
@@ -335,7 +421,7 @@ fn dbg_norm(name: &str, buf: &DeviceBuf, n: usize) {
/// shifts tok100 logits by ~0.01 but does NOT flip the near-tie argmax (220 vs /// shifts tok100 logits by ~0.01 but does NOT flip the near-tie argmax (220 vs
/// ref 68014) — the residual gap is the core-loop pass 1/2, not expert precision. /// ref 68014) — the residual gap is the core-loop pass 1/2, not expert precision.
fn run_experts( fn run_experts(
ar: &SafetensorsArchive, ip: usize, ids_h: &[i32], mlpin: &DeviceBuf, d: &Dims, h: usize, cache: &WeightCache, ip: usize, ids_h: &[i32], mlpin: &DeviceBuf, d: &Dims, h: usize,
) -> Result<Vec<f32>, String> { ) -> Result<Vec<f32>, String> {
let gu = DeviceBuf::alloc(2 * d.inter * 4)?; let gu = DeviceBuf::alloc(2 * d.inter * 4)?;
let mut y_part_h = vec![0f32; d.top_k * h]; let mut y_part_h = vec![0f32; d.top_k * h];
@@ -345,10 +431,10 @@ fn run_experts(
let act16 = DeviceBuf::alloc(d.inter * 2)?; let act16 = DeviceBuf::alloc(d.inter * 2)?;
for kk in 0..d.top_k { for kk in 0..d.top_k {
let e = ids_h[kk] as usize; let e = ids_h[kk] as usize;
let w13 = load_expert_matrix(ar, ip, e, "w13")?; let w13 = cache.expert(ip, e, "w13")?;
expert_gemv_f16(&w13, &mlpin16, &gu)?; expert_gemv_f16(&w13, &mlpin16, &gu)?;
vetta_infer_hip::situ_f16(&gu, &act16, d.inter as i32, d.beta, d.lb)?; vetta_infer_hip::situ_f16(&gu, &act16, d.inter as i32, d.beta, d.lb)?;
let w2 = load_expert_matrix(ar, ip, e, "w2")?; let w2 = cache.expert(ip, e, "w2")?;
let ye = DeviceBuf::alloc(h * 4)?; let ye = DeviceBuf::alloc(h * 4)?;
expert_gemv_f16(&w2, &act16, &ye)?; expert_gemv_f16(&w2, &act16, &ye)?;
ye.d2h(&mut y_part_h[kk * h..(kk + 1) * h])?; ye.d2h(&mut y_part_h[kk * h..(kk + 1) * h])?;
@@ -357,10 +443,10 @@ fn run_experts(
let act = DeviceBuf::alloc(d.inter * 4)?; let act = DeviceBuf::alloc(d.inter * 4)?;
for kk in 0..d.top_k { for kk in 0..d.top_k {
let e = ids_h[kk] as usize; let e = ids_h[kk] as usize;
let w13 = load_expert_matrix(ar, ip, e, "w13")?; let w13 = cache.expert(ip, e, "w13")?;
expert_gemv(&w13, mlpin, &gu)?; expert_gemv(&w13, mlpin, &gu)?;
vetta_infer_hip::situ(&gu, &act, d.inter as i32, d.beta, d.lb)?; vetta_infer_hip::situ(&gu, &act, d.inter as i32, d.beta, d.lb)?;
let w2 = load_expert_matrix(ar, ip, e, "w2")?; let w2 = cache.expert(ip, e, "w2")?;
let ye = DeviceBuf::alloc(h * 4)?; let ye = DeviceBuf::alloc(h * 4)?;
expert_gemv(&w2, &act, &ye)?; expert_gemv(&w2, &act, &ye)?;
ye.d2h(&mut y_part_h[kk * h..(kk + 1) * h])?; ye.d2h(&mut y_part_h[kk * h..(kk + 1) * h])?;
@@ -372,18 +458,18 @@ fn run_experts(
/// Run one physical layer step (SWA or full-attn dispatch), reusing its /// Run one physical layer step (SWA or full-attn dispatch), reusing its
/// persistent state (KV cache + shortconv history) across loop passes. /// persistent state (KV cache + shortconv history) across loop passes.
fn run_layer( fn run_layer(
ar: &SafetensorsArchive, d: &Dims, ip: usize, cur: &DeviceBuf, blocks: &mut Vec<DeviceBuf>, cache: &WeightCache, d: &Dims, ip: usize, cur: &DeviceBuf, blocks: &mut Vec<DeviceBuf>,
states: &mut [Option<LayerState>], max_seq: usize, pos: i32, pass: usize, states: &mut [Option<LayerState>], max_seq: usize, pos: i32, pass: usize,
ctrl: Option<(&ControllerWeights, &LoopMsgs)>, ctrl: Option<(&ControllerWeights, &LoopMsgs)>,
) -> Result<(), String> { ) -> Result<(), String> {
if states[ip].is_none() { states[ip] = Some(new_state(d, max_seq)?); } if states[ip].is_none() { states[ip] = Some(new_state(d, max_seq)?); }
let st = states[ip].as_mut().unwrap(); let st = states[ip].as_mut().unwrap();
let r = if is_swa(ip) { let r = if is_swa(ip) {
let w = load_layer(ar, ip, true)?; let w = cache.swa_layer(ip)?;
layer_forward_swa(ar, &w, st, d, cur, blocks, pos, pass, ctrl) layer_forward_swa(cache, &w, st, d, cur, blocks, pos, pass, ctrl)
} else { } else {
let w = load_full_layer(ar, ip, d)?; let w = cache.full_layer(ip, d)?;
layer_forward_full(ar, &w, st, d, cur, blocks, pos, pass, ctrl) layer_forward_full(cache, &w, st, d, cur, blocks, pos, pass, ctrl)
}; };
if std::env::var("VETTA_DBG_NORM").is_ok() { if std::env::var("VETTA_DBG_NORM").is_ok() {
let visit = if ip < 6 { ip } else if ip < 18 { 6 + pass * 12 + (ip - 6) } else { 42 + (ip - 18) }; let visit = if ip < 6 { ip } else if ip < 18 { 6 + pass * 12 + (ip - 6) } else { 42 + (ip - 18) };
@@ -399,21 +485,21 @@ fn run_layer(
/// (bank rollback + cross-pass msgs + controllers on passes 1,2) -> coda /// (bank rollback + cross-pass msgs + controllers on passes 1,2) -> coda
/// [18,24) -> final depth mix + unembed + softcap. Returns logits [vocab]. /// [18,24) -> final depth mix + unembed + softcap. Returns logits [vocab].
pub fn forward_inkling( pub fn forward_inkling(
ar: &SafetensorsArchive, d: &Dims, token: i32, vocab: usize, max_seq: usize, pos: i32, cap: f32, cache: &WeightCache, d: &Dims, token: i32, vocab: usize, max_seq: usize, pos: i32, cap: f32,
) -> Result<DeviceBuf, String> { ) -> Result<DeviceBuf, String> {
let mut states: Vec<Option<LayerState>> = (0..24).map(|_| None).collect(); 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) forward_inkling_with_state(cache, d, token, vocab, max_seq, pos, cap, &mut states)
} }
/// Stateful variant: `states` holds the persistent per-layer KV cache + shortconv /// Stateful variant: `states` holds the persistent per-layer KV cache + shortconv
/// history across decode positions (autoregressive generation). The depth-block /// history across decode positions (autoregressive generation). The depth-block
/// snapshots reset each forward; the KV/history evolve token by token. /// snapshots reset each forward; the KV/history evolve token by token.
pub fn forward_inkling_with_state( pub fn forward_inkling_with_state(
ar: &SafetensorsArchive, d: &Dims, token: i32, vocab: usize, max_seq: usize, pos: i32, cap: f32, cache: &WeightCache, d: &Dims, token: i32, vocab: usize, max_seq: usize, pos: i32, cap: f32,
states: &mut [Option<LayerState>], states: &mut [Option<LayerState>],
) -> Result<DeviceBuf, String> { ) -> Result<DeviceBuf, String> {
let h = d.hidden; let h = d.hidden;
let cur = embed_token(ar, token, h, vocab)?; let cur = embed_token(cache, token, h, vocab)?;
if std::env::var("VETTA_DBG_NORM").is_ok() { if std::env::var("VETTA_DBG_NORM").is_ok() {
let mut eh = vec![0f32; h]; cur.d2h(&mut eh).unwrap(); let mut eh = vec![0f32; h]; cur.d2h(&mut eh).unwrap();
let n = eh.iter().map(|v| v * v).sum::<f32>().sqrt(); let n = eh.iter().map(|v| v * v).sum::<f32>().sqrt();
@@ -421,7 +507,7 @@ pub fn forward_inkling_with_state(
} }
let mut blocks: Vec<DeviceBuf> = Vec::new(); let mut blocks: Vec<DeviceBuf> = Vec::new();
// Prelude. // Prelude.
for ip in 0..6 { run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, 0, None)?; } for ip in 0..6 { run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, 0, None)?; }
let mut prelude = vec![0f32; h]; cur.d2h(&mut prelude)?; let mut prelude = vec![0f32; h]; cur.d2h(&mut prelude)?;
let n_prelude_blocks = blocks.len(); let n_prelude_blocks = blocks.len();
if std::env::var("VETTA_DBG_NORM").is_ok() { if std::env::var("VETTA_DBG_NORM").is_ok() {
@@ -444,7 +530,7 @@ pub fn forward_inkling_with_state(
} }
for ip in 6..18 { for ip in 6..18 {
if p > 0 && std::env::var("VETTA_NO_CTRL").is_err() { if p > 0 && std::env::var("VETTA_NO_CTRL").is_err() {
let mq = load_msg_queries(ar, ip, h)?; let mq = load_msg_queries(cache, ip, h)?;
let n_bank = bank.len(); let n_bank = bank.len();
let blk = DeviceBuf::alloc(n_bank.max(1) * h * 4)?; let blk = DeviceBuf::alloc(n_bank.max(1) * h * 4)?;
let mut bh = vec![0f32; n_bank.max(1) * h]; let mut bh = vec![0f32; n_bank.max(1) * h];
@@ -453,22 +539,22 @@ pub fn forward_inkling_with_state(
let msgs_buf = DeviceBuf::alloc(4 * h * 4)?; 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)?; 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 msgs = LoopMsgs(msgs_buf);
let cw = load_controllers(ar, ip)?; let cw = cache.controllers(ip)?;
run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, p, Some((&cw, &msgs)))?; run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, p, Some((&cw, &msgs)))?;
} else { } else {
run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, p, None)?; run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, p, None)?;
} }
} }
} }
// Coda. // Coda.
for ip in 18..24 { run_layer(ar, d, ip, &cur, &mut blocks, states, max_seq, pos, 0, None)?; } for ip in 18..24 { run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, 0, None)?; }
if std::env::var("VETTA_DBG_NORM").is_ok() { if std::env::var("VETTA_DBG_NORM").is_ok() {
let mut ch = vec![0f32; h]; cur.d2h(&mut ch).unwrap(); let mut ch = vec![0f32; h]; cur.d2h(&mut ch).unwrap();
let n = ch.iter().map(|v| v * v).sum::<f32>().sqrt(); let n = ch.iter().map(|v| v * v).sum::<f32>().sqrt();
eprintln!("[dbg] after coda: cur_norm={n:.3} blocks={}", blocks.len()); eprintln!("[dbg] after coda: cur_norm={n:.3} blocks={}", blocks.len());
for (i, b) in blocks.iter().enumerate() { let mut bh = vec![0f32; h]; b.d2h(&mut bh).unwrap(); let bn = bh.iter().map(|v| v * v).sum::<f32>().sqrt(); eprintln!("[dbg] block[{i}]_norm={bn:.3}"); } for (i, b) in blocks.iter().enumerate() { let mut bh = vec![0f32; h]; b.d2h(&mut bh).unwrap(); let bn = bh.iter().map(|v| v * v).sum::<f32>().sqrt(); eprintln!("[dbg] block[{i}]_norm={bn:.3}"); }
} }
final_logits(ar, &cur, &blocks, h, vocab, d.eps, cap) final_logits(cache, &cur, &blocks, h, vocab, d.eps, cap)
} }
/// Load a full-attn ShortConv static weight tensor [4, C] transposed to the /// Load a full-attn ShortConv static weight tensor [4, C] transposed to the
@@ -536,7 +622,7 @@ pub fn load_full_layer(ar: &SafetensorsArchive, ip: usize, d: &Dims) -> Result<F
/// split into in0/in1/in2, separate q/k/v norms, projections from distinct /// 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. /// inputs, dynamic ShortConv K/V, tau on Q/R, global (window=0) flash attention.
pub fn layer_forward_full( pub fn layer_forward_full(
ar: &SafetensorsArchive, w: &FullLayerWeights, st: &mut LayerState, d: &Dims, cache: &WeightCache, w: &FullLayerWeights, st: &mut LayerState, d: &Dims,
cur: &DeviceBuf, blocks: &mut Vec<DeviceBuf>, pos: i32, cur: &DeviceBuf, blocks: &mut Vec<DeviceBuf>, pos: i32,
pass: usize, pass: usize,
ctrl: Option<(&ControllerWeights, &LoopMsgs)>, ctrl: Option<(&ControllerWeights, &LoopMsgs)>,
@@ -633,7 +719,7 @@ pub fn layer_forward_full(
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)?; 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 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<_>>() };
if std::env::var("VETTA_DBG_IDS").is_ok() { eprintln!("[dbg] ip={} GPU experts={:?}", w.ip, ids_h); } if std::env::var("VETTA_DBG_IDS").is_ok() { eprintln!("[dbg] ip={} GPU experts={:?}", w.ip, ids_h); }
let y_part_h = run_experts(ar, w.ip, &ids_h, &mlpin, d, h)?; let y_part_h = run_experts(cache, w.ip, &ids_h, &mlpin, d, h)?;
let y_part = DeviceBuf::alloc(d.top_k * h * 4)?; y_part.h2d(&y_part_h)?; let y_part = DeviceBuf::alloc(d.top_k * h * 4)?; y_part.h2d(&y_part_h)?;
let moeout = DeviceBuf::alloc(h * 4)?; let moeout = DeviceBuf::alloc(h * 4)?;
vetta_infer_hip::moe_reduce(&y_part, &weights, &moeout, d.top_k as i32, h as i32)?; vetta_infer_hip::moe_reduce(&y_part, &weights, &moeout, d.top_k as i32, h as i32)?;
@@ -708,10 +794,11 @@ mod tests {
#[ignore] #[ignore]
fn multi_layer_prelude_forward() { fn multi_layer_prelude_forward() {
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap(); let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
let cache = WeightCache::new(&ar);
let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; let 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(); let (cur, blocks) = forward_swa_layers(&cache, &[0, 1, 2, 3, 4], &d, 100, 1, 0).unwrap();
assert_eq!(blocks.len(), 1, "prelude 0..4 snapshots only at ip=0"); 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 logits = final_logits(&cache, &cur, &blocks, d.hidden, 201024, d.eps, 30.0).unwrap();
let mut lg = vec![0f32; 201024]; logits.d2h(&mut lg).unwrap(); 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.is_finite()), "logits must be finite");
assert!(lg.iter().all(|v| v.abs() <= 30.0 + 1e-3), "softcap must bound logits"); assert!(lg.iter().all(|v| v.abs() <= 30.0 + 1e-3), "softcap must bound logits");
@@ -729,14 +816,15 @@ mod tests {
#[ignore] #[ignore]
fn full_attn_layer_end_to_end() { fn full_attn_layer_end_to_end() {
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap(); let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
let cache = WeightCache::new(&ar);
let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; let 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 cur = embed_token(&cache, 100, d.hidden, 201024).unwrap();
let mut blocks: Vec<DeviceBuf> = Vec::new(); let mut blocks: Vec<DeviceBuf> = Vec::new();
let mut seed = vec![0f32; d.hidden]; cur.d2h(&mut seed).unwrap(); 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 b0 = DeviceBuf::alloc(d.hidden * 4).unwrap(); b0.h2d(&seed).unwrap(); blocks.push(b0);
let w = load_full_layer(&ar, 5, &d).unwrap(); let w = load_full_layer(&ar, 5, &d).unwrap();
let mut st = new_state(&d, 1).unwrap(); let mut st = new_state(&d, 1).unwrap();
layer_forward_full(&ar, &w, &mut st, &d, &cur, &mut blocks, 0, 0, None).unwrap(); layer_forward_full(&cache, &w, &mut st, &d, &cur, &mut blocks, 0, 0, None).unwrap();
assert_eq!(blocks.len(), 1, "ip=5 does not snapshot (5%6!=0)"); 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(); 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().all(|v| v.is_finite()), "full-attn residual must be finite");
@@ -752,8 +840,9 @@ mod tests {
#[ignore] #[ignore]
fn full_inkling_forward_logits() { fn full_inkling_forward_logits() {
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap(); let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
let cache = WeightCache::new(&ar);
let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; let 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 logits = forward_inkling(&cache, &d, 100, 201024, 1, 0, 30.0).unwrap();
let mut lg = vec![0f32; 201024]; logits.d2h(&mut lg).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.is_finite()), "full forward logits must be finite");
assert!(lg.iter().all(|v| v.abs() <= 30.0 + 1e-3), "logits must be softcap-bounded"); assert!(lg.iter().all(|v| v.abs() <= 30.0 + 1e-3), "logits must be softcap-bounded");
@@ -775,6 +864,7 @@ mod tests {
use tokenizers::Tokenizer; use tokenizers::Tokenizer;
use vetta_infer_abi::sampler::{sample_logits_exact, SampleReport, SamplerScratch, SamplingOpts, SplitMix64}; use vetta_infer_abi::sampler::{sample_logits_exact, SampleReport, SamplerScratch, SamplingOpts, SplitMix64};
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap(); let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
let cache = WeightCache::new(&ar);
let tok = Tokenizer::from_file("/mnt/models/Inkling/safetensors/tokenizer.json").unwrap(); let 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 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 vocab = 201024usize;
@@ -788,7 +878,7 @@ mod tests {
let mut pos = 0i32; let mut pos = 0i32;
let mut logits = DeviceBuf::alloc(vocab * 4).unwrap(); let mut logits = DeviceBuf::alloc(vocab * 4).unwrap();
for &t in &ids { for &t in &ids {
logits = forward_inkling_with_state(&ar, &d, t, vocab, max_seq, pos, 30.0, &mut states).unwrap(); logits = forward_inkling_with_state(&cache, &d, t, vocab, max_seq, pos, 30.0, &mut states).unwrap();
history.push(t); pos += 1; history.push(t); pos += 1;
} }
let opts = SamplingOpts::default(); // greedy let opts = SamplingOpts::default(); // greedy
@@ -800,7 +890,7 @@ mod tests {
let rep: SampleReport = sample_logits_exact(&mut lg, &opts, &history, None, &mut rng, &mut scratch); let rep: SampleReport = sample_logits_exact(&mut lg, &opts, &history, None, &mut rng, &mut scratch);
generated.push(rep.token as u32); generated.push(rep.token as u32);
history.push(rep.token); history.push(rep.token);
logits = forward_inkling_with_state(&ar, &d, rep.token, vocab, max_seq, pos, 30.0, &mut states).unwrap(); logits = forward_inkling_with_state(&cache, &d, rep.token, vocab, max_seq, pos, 30.0, &mut states).unwrap();
pos += 1; pos += 1;
} }
let text = tok.decode(&generated, true).unwrap(); let text = tok.decode(&generated, true).unwrap();
+4 -2
View File
@@ -716,7 +716,8 @@ mod tests {
let mut st = crate::layer::new_state(&dims, steps).unwrap(); let mut st = crate::layer::new_state(&dims, steps).unwrap();
let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap(); let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap();
let mut blocks: Vec<DeviceBuf> = Vec::new(); let mut blocks: Vec<DeviceBuf> = Vec::new();
crate::layer::layer_forward_swa(&ar, &lw, &mut st, &dims, &cur, &mut blocks, pos, 0, None).unwrap(); let cache = crate::layer::WeightCache::new(&ar);
crate::layer::layer_forward_swa(&cache, &lw, &mut st, &dims, &cur, &mut blocks, pos, 0, None).unwrap();
assert_eq!(blocks.len(), 1, "ip=0 must snapshot one depth block"); assert_eq!(blocks.len(), 1, "ip=0 must snapshot one depth block");
let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap(); let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap();
@@ -838,7 +839,8 @@ mod tests {
let mut st = crate::layer::new_state(&dims, 1).unwrap(); let mut st = crate::layer::new_state(&dims, 1).unwrap();
let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap(); let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap();
let mut blocks: Vec<DeviceBuf> = Vec::new(); let mut blocks: Vec<DeviceBuf> = Vec::new();
crate::layer::layer_forward_full(&ar, &lw, &mut st, &dims, &cur, &mut blocks, pos, 0, None).unwrap(); let cache = crate::layer::WeightCache::new(&ar);
crate::layer::layer_forward_full(&cache, &lw, &mut st, &dims, &cur, &mut blocks, pos, 0, None).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
let qn_f = read_bf16_f32(&ar, &format!("{l}.q_input_norm.weight")); let qn_f = read_bf16_f32(&ar, &format!("{l}.q_input_norm.weight"));