[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:
1 parent
5ec55f753f
commit
1df8342f96
3 files changed
+152
-55
No files matched your search
@@ -10,8 +10,11 @@
|
||||
//! layers (3-query split), loop controllers (gain/forget/down) and the
|
||||
//! 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 std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use vetta_infer_hip::DeviceBuf;
|
||||
|
||||
/// 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() }
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let p = format!("model.llm.layers.{ip}.attn");
|
||||
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.
|
||||
/// Experts are loaded on demand from `ar` (zero requantization).
|
||||
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,
|
||||
pass: usize,
|
||||
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)?;
|
||||
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); }
|
||||
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 moeout = DeviceBuf::alloc(h * 4)?;
|
||||
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].
|
||||
/// 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")?;
|
||||
pub fn embed_token(cache: &WeightCache, token: i32, hidden: usize, vocab: usize) -> Result<DeviceBuf, String> {
|
||||
let table = cache.raw("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")?;
|
||||
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)?;
|
||||
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")?;
|
||||
pub fn unembed_logits(cache: &WeightCache, cur: &DeviceBuf, hidden: usize, vocab: usize, eps: f32) -> Result<DeviceBuf, String> {
|
||||
let norm = cache.bf16_f32("model.llm.norm.weight")?;
|
||||
let unembed = cache.raw("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)?;
|
||||
@@ -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
|
||||
/// (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")?;
|
||||
pub fn final_logits(cache: &WeightCache, cur: &DeviceBuf, blocks: &[DeviceBuf], hidden: usize, vocab: usize, eps: f32, cap: f32) -> Result<DeviceBuf, String> {
|
||||
let oq = cache.raw("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];
|
||||
@@ -278,7 +364,7 @@ pub fn final_logits(ar: &SafetensorsArchive, cur: &DeviceBuf, blocks: &[DeviceBu
|
||||
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)?;
|
||||
let logits = unembed_logits(cache, &mix, hidden, vocab, eps)?;
|
||||
if cap > 0.0 { vetta_infer_hip::softcap(&logits, &logits, vocab, cap)?; }
|
||||
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 /
|
||||
/// 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,
|
||||
cache: &WeightCache, 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 cur = embed_token(cache, token, d.hidden, /*vocab*/ 201024)?;
|
||||
let mut blocks: Vec<DeviceBuf> = Vec::new();
|
||||
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)?;
|
||||
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))
|
||||
}
|
||||
@@ -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:
|
||||
/// [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 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 q_cp = cache.raw("model.llm.middle_cycle_cross_pass_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 kh = vec![0f32; 24 * hidden]; kv_cp.d2h(&mut kh)?;
|
||||
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
|
||||
/// ref 68014) — the residual gap is the core-loop pass 1/2, not expert precision.
|
||||
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> {
|
||||
let gu = DeviceBuf::alloc(2 * d.inter * 4)?;
|
||||
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)?;
|
||||
for kk in 0..d.top_k {
|
||||
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)?;
|
||||
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)?;
|
||||
expert_gemv_f16(&w2, &act16, &ye)?;
|
||||
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)?;
|
||||
for kk in 0..d.top_k {
|
||||
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)?;
|
||||
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)?;
|
||||
expert_gemv(&w2, &act, &ye)?;
|
||||
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
|
||||
/// persistent state (KV cache + shortconv history) across loop passes.
|
||||
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,
|
||||
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();
|
||||
let r = if is_swa(ip) {
|
||||
let w = load_layer(ar, ip, true)?;
|
||||
layer_forward_swa(ar, &w, st, d, cur, blocks, pos, pass, ctrl)
|
||||
let w = cache.swa_layer(ip)?;
|
||||
layer_forward_swa(cache, &w, st, d, cur, blocks, pos, pass, ctrl)
|
||||
} else {
|
||||
let w = load_full_layer(ar, ip, d)?;
|
||||
layer_forward_full(ar, &w, st, d, cur, blocks, pos, pass, ctrl)
|
||||
let w = cache.full_layer(ip, d)?;
|
||||
layer_forward_full(cache, &w, st, d, cur, blocks, pos, pass, ctrl)
|
||||
};
|
||||
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) };
|
||||
@@ -399,21 +485,21 @@ fn run_layer(
|
||||
/// (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,
|
||||
cache: &WeightCache, 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)
|
||||
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
|
||||
/// 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,
|
||||
cache: &WeightCache, 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 cur = embed_token(cache, token, h, vocab)?;
|
||||
if std::env::var("VETTA_DBG_NORM").is_ok() {
|
||||
let mut eh = vec![0f32; h]; cur.d2h(&mut eh).unwrap();
|
||||
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();
|
||||
// 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 n_prelude_blocks = blocks.len();
|
||||
if std::env::var("VETTA_DBG_NORM").is_ok() {
|
||||
@@ -444,7 +530,7 @@ pub fn forward_inkling_with_state(
|
||||
}
|
||||
for ip in 6..18 {
|
||||
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 blk = DeviceBuf::alloc(n_bank.max(1) * h * 4)?;
|
||||
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)?;
|
||||
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, p, Some((&cw, &msgs)))?;
|
||||
let cw = cache.controllers(ip)?;
|
||||
run_layer(cache, d, ip, &cur, &mut blocks, states, max_seq, pos, p, Some((&cw, &msgs)))?;
|
||||
} 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.
|
||||
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() {
|
||||
let mut ch = vec![0f32; h]; cur.d2h(&mut ch).unwrap();
|
||||
let n = ch.iter().map(|v| v * v).sum::<f32>().sqrt();
|
||||
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}"); }
|
||||
}
|
||||
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
|
||||
@@ -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
|
||||
/// 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,
|
||||
cache: &WeightCache, w: &FullLayerWeights, st: &mut LayerState, d: &Dims,
|
||||
cur: &DeviceBuf, blocks: &mut Vec<DeviceBuf>, pos: i32,
|
||||
pass: usize,
|
||||
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)?;
|
||||
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); }
|
||||
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 moeout = DeviceBuf::alloc(h * 4)?;
|
||||
vetta_infer_hip::moe_reduce(&y_part, &weights, &moeout, d.top_k as i32, h as i32)?;
|
||||
@@ -708,10 +794,11 @@ mod tests {
|
||||
#[ignore]
|
||||
fn multi_layer_prelude_forward() {
|
||||
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 (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");
|
||||
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();
|
||||
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");
|
||||
@@ -729,14 +816,15 @@ mod tests {
|
||||
#[ignore]
|
||||
fn full_attn_layer_end_to_end() {
|
||||
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 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 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, 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)");
|
||||
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");
|
||||
@@ -752,8 +840,9 @@ mod tests {
|
||||
#[ignore]
|
||||
fn full_inkling_forward_logits() {
|
||||
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 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();
|
||||
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");
|
||||
@@ -775,6 +864,7 @@ mod tests {
|
||||
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 cache = WeightCache::new(&ar);
|
||||
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;
|
||||
@@ -788,7 +878,7 @@ mod tests {
|
||||
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();
|
||||
logits = forward_inkling_with_state(&cache, &d, t, vocab, max_seq, pos, 30.0, &mut states).unwrap();
|
||||
history.push(t); pos += 1;
|
||||
}
|
||||
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);
|
||||
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();
|
||||
logits = forward_inkling_with_state(&cache, &d, rep.token, vocab, max_seq, pos, 30.0, &mut states).unwrap();
|
||||
pos += 1;
|
||||
}
|
||||
let text = tok.decode(&generated, true).unwrap();
|
||||
|
||||
Reference in new issue
Block a user