//! Real GPU `--serve` request loop (feature `hip`) — the engine side of the //! `strata-ctl` wire contract (docs/ARCHITECTURE.md §6). //! //! Wires the three already-verified pieces into a resident inference service: //! * `ld::layer::forward_inkling_with_state` — the full 48-visit Inkling //! forward with persistent per-layer KV/ShortConv state (autoregressive); //! * `abi::sampler` — the hardened zero-allocation sampler (greedy/top-k/p/ //! min-p + penalties, explicit non-finite tracking); //! * `gw::session::ServeSession` — the Lean-proven request lifecycle //! (`proofs/serve_session.lean`): GEN/STOP/QUIT, `GEN 0` pre-warm, and the //! STOP→DONE drain guarantee. //! //! The protocol is token-id based (the consumer sends prompt ids and receives //! `T ` lines), so no tokenizer is needed here. `serve_gen` is a pure //! orchestration function (engine + parsed GEN + stop flag + emit closure) so it //! is callable from an integration test without spawning the binary. use std::io::{self, BufRead, Write}; use std::cell::RefCell; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{mpsc, Arc}; use std::time::Instant; use vetta_infer_abi::sampler::{ sample_logits_exact, SamplerScratch, SamplingOpts, SplitMix64, }; use vetta_infer_abi::serve::{parse_serve_line, ParsedGen, ServeCommand}; use vetta_infer_hip::DeviceBuf; use vetta_infer_ld::inkling::parse_config; use vetta_infer_ld::layer::{forward_batch, forward_inkling_with_state, is_swa, new_state, Dims, LayerSnapshot, LayerState, WeightCache}; use vetta_infer_ld::SafetensorsArchive; #[cfg(feature = "hip")] use vetta_infer_ld::layer::forward_batch_taps; #[cfg(feature = "hip")] use vetta_infer_ld::dspark::{layout_check, spec_round, DsparkContext, DsparkSnapshot, DsparkWeights, DS_HIDDEN}; use crate::session::ServeSession; use crate::{err_line, ready_line}; /// Inkling-2-Mini architecture constants used by the layer kernels that are not /// carried in `TextConfig` (verified against the reference engine; same values /// as the proven `ld::layer` parity tests). `block_size` is /// `n_layers_per_attn_res_block`; `qk_clip`/`rel_clip` are the L2-clip /// thresholds; `beta`/`lb` are the SiTU double-softcap parameters. const BLOCK_SIZE: usize = 6; const QK_CLIP: f32 = 22.627416997969522; const REL_CLIP: f32 = 8.0; const SITU_BETA: f32 = 4.0; const SITU_LB: f32 = 25.0; /// Declared resident context window advertised in `READY` (SWA window is 1024; /// full-attn layers attend globally up to this cap). Sized to accommodate the /// consumer's default generation budget (strata-ctl max_new=16384) plus a large /// agent prompt; KV is allocated per request at prompt+max_new, well within the /// 48 GiB HIP-visible VRAM. Flash scores live in global memory, so full-attn is /// not limited by the 64 KB LDS cap. const MAX_CONTEXT: usize = 32768; /// Clamp the generation budget to the resident window instead of hard-erroring. /// strata-ctl always sends the default budget max_new=16384, so a prompt longer /// than MAX_CONTEXT-16386 (e.g. 16504/16686 seen live) must still run with a /// reduced budget rather than return 0 tokens and kill the agent mid-window. /// `None` = the prompt itself no longer fits (true overflow, hard error). fn clamp_max_new(n_prompt: usize, max_new: usize, max_context: usize) -> Option { if n_prompt + 2 >= max_context { return None; } Some(max_new.min(max_context - n_prompt - 2)) } /// Prefix checkpoint cache (concept ported from strata `--auto-ckpt`, verified in /// proofs/prefix_cache.lean). Keeps snapshots of KV+ShortConv at prefix boundaries /// so a new request whose prompt extends a cached prefix restores it and prefills /// only the NEW tokens (restore_equiv: exact). Pinned anchors {512,1024} are never /// evicted (I3); otherwise LRU eviction at the cap. const PREFIX_CACHE_CAP: usize = 8; fn pinned_anchor(seq: usize) -> bool { seq == 512 || seq == 1024 } /// Grid checkpoints (multiples of 512) are the STABLE prefixes that survive the /// turn-tag tail divergence; boundary/full-sequence checkpoints rarely hit again. /// Eviction prefers dropping non-grid entries so the useful grid is protected. fn is_grid(seq: usize) -> bool { seq % 512 == 0 } struct Checkpoint { tokens: Vec, layers: Vec>, #[cfg(feature = "hip")] dspark: Option, lru: u64, } /// Resident pool of prefix checkpoints (interior mutability: serve_gen holds /// `&InklingEngine`). Single conversation slot (FIFO serve). pub struct PrefixCache { pool: Vec, tick: u64, } impl PrefixCache { pub fn new() -> Self { Self { pool: Vec::new(), tick: 0 } } /// Index + length of the longest checkpoint whose tokens are a STRICT prefix /// of ids (l < ids.len()). The suffix must be non-empty: the final logits come /// from a real forward of the last prompt token, which a full-length restore /// (l == ids.len()) would not produce. Longer next-turn prompts still match. fn best_match(&self, ids: &[i32]) -> Option<(usize, usize)> { let mut best: Option<(usize, usize)> = None; for (i, ck) in self.pool.iter().enumerate() { let l = ck.tokens.len(); if l == 0 || l >= ids.len() { continue; } if ck.tokens[..] == ids[..l] && best.map_or(true, |(_, bl)| l > bl) { best = Some((i, l)); } } best } /// Allocate + restore every checkpointed layer into `states` at `max_seq`. /// Takes `&mut self` to refresh the hit checkpoint's LRU tick: without this a /// just-restored grid checkpoint keeps its old tick and gets evicted by the /// next turn's boundary/full saves, regressing turn 3+ to the pinned anchor. /// Returns `(restored_len, dspark_restored)`. fn restore( &mut self, idx: usize, states: &mut [Option], d: &Dims, max_seq: usize, #[cfg(feature = "hip")] dctx: Option<&mut DsparkContext>, ) -> Result<(usize, bool), String> { let mut dspark_ok = false; { let ck = &self.pool[idx]; // A usable checkpoint must cover EVERY layer: a partially-restored state // would cold-start the missing layers and break prefix equivalence. if ck.layers.len() != states.len() || ck.layers.iter().any(|s| s.is_none()) { return Err("incomplete prefix checkpoint".into()); } for (ip, snap) in ck.layers.iter().enumerate() { if let Some(s) = snap { // Reuse the persistent state when it is already sized for this // request (same cap + pass count); restore overwrites its KV // prefix + hist rings. The stale KV tail beyond seq_len is never // read (causal attention), so reuse is exact (restore_equiv). let want = if is_swa(ip) { vetta_infer_ld::layer::swa_ring(d) } else { max_seq }; let reuse = states[ip].as_ref() .map_or(false, |st| st.max_seq == want && st.k_cache.len() == s.k_cache.len()); if !reuse { states[ip] = Some(new_state(d, want, s.k_cache.len())?); } states[ip].as_mut().unwrap().restore(d, s)?; } } #[cfg(feature = "hip")] if let (Some(dc), Some(ds)) = (dctx, ck.dspark.as_ref()) { dc.restore(ds)?; dspark_ok = true; } } self.tick += 1; self.pool[idx].lru = self.tick; Ok((self.pool[idx].tokens.len(), dspark_ok)) } /// Snapshot all layer states (and optional DSpark context) at `tokens.len()` /// and insert (update / grow / evict oldest unpinned). Mirrors poolInsert in /// proofs/prefix_cache.lean. fn save( &mut self, tokens: &[i32], states: &[Option], d: &Dims, #[cfg(feature = "hip")] dctx: Option<&DsparkContext>, ) -> Result<(), String> { let seq = tokens.len(); if seq == 0 { return Ok(()); } let layers: Vec> = states.iter().enumerate() .map(|(ip, st)| st.as_ref().map(|s| s.snapshot(d, seq, is_swa(ip))).transpose()) .collect::>()?; #[cfg(feature = "hip")] let dspark = match dctx { Some(dc) if dc.len >= seq => Some(dc.snapshot(seq, d.swa_win as usize)?), _ => None, }; self.tick += 1; let lru = self.tick; if let Some(ck) = self.pool.iter_mut().find(|c| c.tokens.len() == seq) { ck.tokens = tokens.to_vec(); ck.layers = layers; ck.lru = lru; #[cfg(feature = "hip")] { ck.dspark = dspark; } return Ok(()); } if self.pool.len() < PREFIX_CACHE_CAP { self.pool.push(Checkpoint { tokens: tokens.to_vec(), layers, #[cfg(feature = "hip")] dspark, lru, }); return Ok(()); } let victim = self.pool.iter().enumerate() .filter(|(_, c)| !pinned_anchor(c.tokens.len())) .min_by_key(|(_, c)| (is_grid(c.tokens.len()) as u8, c.lru)).map(|(i, _)| i); if let Some(i) = victim { self.pool[i] = Checkpoint { tokens: tokens.to_vec(), layers, #[cfg(feature = "hip")] dspark, lru, }; } Ok(()) } } /// A loaded Inkling model ready to run autoregressive forwards. pub struct InklingEngine { cache: WeightCache, d: Dims, vocab: usize, n_layers: usize, eos: i32, cap: f32, prefix: RefCell, /// Persistent per-layer KV/ShortConv states reused across requests, sized to /// `states_cap` (a 4096-bucket >= prompt+max_new). Eliminates the per-request /// ~3.75 GB alloc/free VRAM sawtooth; grown only when a request crosses a bucket. states: RefCell>>, /// Resident context window (advertised in READY). Defaults to MAX_CONTEXT; /// VETTA_MAX_CONTEXT / `--max-context` raise it (like strata) for longer agents. max_context: usize, /// DSpark drafter weights (resident), loaded only when VETTA_SPEC=1 and /// mtp.safetensors passes layout_check. Enables opt-in greedy speculation. #[cfg(feature = "hip")] spec_dw: Option, /// Persistent DSpark context rings reused across requests (mirrors `states`). #[cfg(feature = "hip")] dctx: RefCell>, } impl InklingEngine { /// Load the archive + `config.json` and derive the forward dimensions. pub fn new(dir: &str) -> Result { // Production KV dtype: FP16 (exact strata default, parity-verified EXACT, // half the VRAM of the F32 CPU-oracle baseline). The ld parity tests keep // the F32 default; the resident serve opts in here. vetta_infer_ld::layer::set_kv_f16(true); // Batched prefill uses the device-resident f16 MoE (moe_batched). Align the // M=1 decode to the same f16 device path (moe_device, bit-identical math) so // prefill and decode share one expert precision (verified EXACT greedy). unsafe { std::env::set_var("VETTA_DEVICE_MOE", "1") }; let ar = Arc::new(SafetensorsArchive::open(dir)?); let cfg_path = ar.dir.join("config.json"); let raw = std::fs::read_to_string(&cfg_path) .map_err(|e| format!("read {}: {e}", cfg_path.display()))?; let cfg = parse_config(&raw)?; let t = &cfg.text; let d = Dims { hidden: t.hidden, n_head: t.n_head, n_kv: t.n_kv, hd: t.head_dim, d_rel: t.d_rel, rel_extent: t.rel_extent, inter: t.inter, n_experts: t.n_experts, top_k: t.top_k, block_size: BLOCK_SIZE, qk_clip: QK_CLIP, rel_clip: REL_CLIP, eps: t.rms_eps as f32, route_scale: t.route_scale as f32, beta: SITU_BETA, lb: SITU_LB, swa_win: t.swa_win as i32, }; let max_context = std::env::var("VETTA_MAX_CONTEXT").ok() .and_then(|s| s.parse::().ok()) .filter(|&v| v >= 4096) .unwrap_or(MAX_CONTEXT); // Opt-in DSpark drafter: load resident weights iff VETTA_SPEC=1 and the // mtp shard passes the strict layout check (else disable, never guess). #[cfg(feature = "hip")] let spec_dw = if std::env::var("VETTA_SPEC").is_ok() { let mtp = ar.dir.join("mtp.safetensors"); match SafetensorsArchive::open_file(mtp.to_str().unwrap_or_default()) { Ok(mar) if layout_check(&mar).is_ok() => DsparkWeights::load(&mar).ok(), _ => None, } } else { None }; Ok(Self { cache: WeightCache::new(ar), d, // The served/logit vocab is the UNPADDED size (exact strata // k_unembed_softcap V = vocab_unpadded): rows >= unpadded are padding // tokens whose arbitrary logits must never win the argmax. Using the // padded vocab let padding tokens (e.g. 200193) outrank real ones. vocab: t.unpadded_vocab, n_layers: t.n_layers, eos: cfg.eos_token_id as i32, cap: t.final_logit_softcapping as f32, prefix: RefCell::new(PrefixCache::new()), states: RefCell::new(Vec::new()), max_context, #[cfg(feature = "hip")] spec_dw, #[cfg(feature = "hip")] dctx: RefCell::new(None), }) } pub fn vocab(&self) -> usize { self.vocab } pub fn max_context(&self) -> usize { self.max_context } fn forward( &self, token: i32, pos: i32, max_seq: usize, states: &mut [Option], ) -> Result { forward_inkling_with_state(&self.cache, &self.d, token, self.vocab, max_seq, pos, self.cap, states) } /// Batched prefill chunk (M=B): one forward over B tokens, logits for the last. fn forward_batched( &self, tokens: &[i32], pos: i32, max_seq: usize, states: &mut [Option], ) -> Result { forward_batch(&self.cache, &self.d, tokens, self.vocab, max_seq, pos, self.cap, states) } } /// Prefill chunk size (M=B per batched forward). Default 256 amortizes weight /// streaming + kernel launches across 256 tokens vs the old M=1 per-token path. /// VETTA_PREFILL_CHUNK overrides; 1 forces the sequential path (A/B parity). fn prefill_chunk_size() -> usize { std::env::var("VETTA_PREFILL_CHUNK").ok() .and_then(|s| s.parse::().ok()) .filter(|&c| c >= 1) .unwrap_or(256) } fn emit_all(emit: &mut dyn FnMut(String), lines: Vec) { for l in lines { emit(l); } } /// Drive one GEN request end-to-end against the Lean-proven session FSM, emitting /// wire lines through `emit`. `stop` is set asynchronously (stdin reader thread) /// to interrupt decode; it is consumed here (drain→DONE) and reset on exit. /// /// Each request restores the longest cached prefix of its prompt (if any) and /// prefills only the new suffix tokens; with no match it cold-prefills the whole /// prompt. Both paths are observationally identical (proofs/prefix_cache.lean). pub fn serve_gen( eng: &InklingEngine, g: &ParsedGen, stop: &AtomicBool, emit: &mut dyn FnMut(String), ) { let mut sess = ServeSession::new(); if let Err(e) = sess.on_gen(g) { emit_all(emit, sess.on_error(&e)); return; } let n_prompt = g.ids.len(); let max_context = eng.max_context(); // Clamp the budget to the window (reviewer 2026-12-02): only a prompt that // itself overflows is a hard error; otherwise generate up to the room left. let Some(effective_max_new) = clamp_max_new(n_prompt, g.max_new, max_context) else { emit_all(emit, sess.on_error("prompt exceeds context window")); return; }; // KV capacities are FIXED per layer kind (SWA ring = swa_win+chunk_cap, global // = max_context), allocated once and never resized across requests: no // drop+realloc when a session crosses a 4096 multiple (reviewer punto 2). if eng.states.borrow().len() != eng.n_layers { *eng.states.borrow_mut() = (0..eng.n_layers).map(|_| None).collect(); } let cap = max_context; let mut states = eng.states.borrow_mut(); // Opt-in DSpark speculation (pure greedy, no penalties): capture trunk taps // during prefill to build the drafter context rings, then run a batched // speculative decode (lossless vs forward_batch B=1, proofs/speculative_draft). #[cfg(feature = "hip")] let mut spec_enabled = eng.spec_dw.is_some() && g.sampling.is_greedy() && !g.sampling.has_penalties(); #[cfg(not(feature = "hip"))] let spec_enabled = false; #[cfg(feature = "hip")] let mut dctx_guard = eng.dctx.borrow_mut(); #[cfg(feature = "hip")] if spec_enabled { let need_new = dctx_guard.as_ref().map_or(true, |c| c.cap < cap); if need_new { match DsparkContext::new(cap, DS_HIDDEN) { Ok(c) => *dctx_guard = Some(c), Err(e) => { emit_all(emit, sess.on_error(&e)); stop.store(false, Ordering::Relaxed); return; } } } } // Prefix checkpoint reuse (proofs/prefix_cache.lean restore_equiv): restore // the longest cached strict prefix of this prompt and prefill only the NEW // suffix tokens. VETTA_NO_PREFIX_CACHE forces cold prefill (A/B measurement). let mut start = 0usize; if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() { let matched = eng.prefix.borrow().best_match(&g.ids); if let Some((idx, _l)) = matched { #[cfg(feature = "hip")] let res = eng.prefix.borrow_mut().restore( idx, &mut states[..], &eng.d, cap, if spec_enabled { dctx_guard.as_mut() } else { None }, ); #[cfg(not(feature = "hip"))] let res = eng.prefix.borrow_mut().restore(idx, &mut states[..], &eng.d, cap); match res { Ok((n, dspark_ok)) => { start = n; #[cfg(feature = "hip")] if spec_enabled && !dspark_ok { // Checkpoint lacked DSpark state (e.g. saved while spec was off): // never run the drafter over zeroed prefix rings. spec_enabled = false; } #[cfg(not(feature = "hip"))] let _ = dspark_ok; } Err(_) => { // Incomplete/failed restore: fall back to a clean cold prefill. *states = (0..eng.n_layers).map(|_| None).collect(); } } } } // Cold request (no prefix restored): the persistent states carry the previous // conversation's ShortConv history. Reset the hist rings (the KV prefix is // overwritten by prefill before any causal read) so a fresh conversation starts // empty. A restored request instead overwrites hist via the checkpoint. if start == 0 { for st in states.iter_mut().flatten() { if let Err(e) = st.reset_history() { emit_all(emit, sess.on_error(&e)); stop.store(false, Ordering::Relaxed); return; } } #[cfg(feature = "hip")] if let Some(dc) = dctx_guard.as_mut() { dc.len = 0; } } if std::env::var("VETTA_DBG_PREFIX").is_ok() { eprintln!("[prefix] prompt_len={n_prompt} restored={start}"); if start == 0 { // No match: show each cached checkpoint's length and how many leading // tokens it shares with this prompt, to pinpoint a token divergence // (common < len => the re-rendered prompt differs at that position). let p = eng.prefix.borrow(); for (i, ck) in p.pool.iter().enumerate() { let common = ck.tokens.iter().zip(g.ids.iter()).take_while(|(a, b)| a == b).count(); eprintln!("[prefix] ck[{i}] len={} common_prefix={common}", ck.tokens.len()); } } } // Weights are resident in eng.cache (loaded once at boot, reused across all // requests): no per-request NVMe re-read or re-upload. // --- Prefill: chunked batched (M=B) forward over the NEW prompt tokens. --- // Each chunk runs ONE forward_batch over B tokens (weight streaming + kernel // launches amortized across B), growing KV/history; logits come from the last // token of the final chunk. VETTA_PREFILL_CHUNK=1 restores the M=1 path (A/B). let t0 = Instant::now(); let mut pos = start as i32; let mut history: Vec = g.ids[..start].to_vec(); history.reserve(n_prompt - start + effective_max_new); let mut logits: Option = None; let chunk = prefill_chunk_size().min(vetta_infer_ld::layer::SWA_CHUNK_CAP); let suffix = &g.ids[start..]; let mut done = 0usize; // Monotonic 512-grid threshold: split a chunk exactly on the next grid boundary // so a checkpoint always lands on every multiple of 512 regardless of `start` // (pos % 512 == 0 would miss boundaries when start/suffix aren't aligned). let mut next_grid = ((start / 512) + 1) * 512; while done < suffix.len() { if stop.load(Ordering::Relaxed) { sess.on_stop(); let ms = t0.elapsed().as_secs_f64() * 1000.0; emit_all(emit, sess.on_drain_complete(ms).unwrap_or_default()); stop.store(false, Ordering::Relaxed); return; } let mut take = chunk.min(suffix.len() - done); let pos_now = start + done; if pos_now < next_grid && pos_now + take > next_grid { take = next_grid - pos_now; } let toks = &suffix[done..done + take]; let lg = if spec_enabled { #[cfg(feature = "hip")] { (|| -> Result { let h = eng.d.hidden; let mut taps = [DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?]; let l = forward_batch_taps(&eng.cache, &eng.d, toks, eng.vocab, cap, pos, eng.cap, &mut states[..], &mut taps)?; let pb = DeviceBuf::alloc(take * 4)?; pb.h2d_bytes(&(pos..pos + take as i32).flat_map(|p| p.to_le_bytes()).collect::>())?; let dw = eng.spec_dw.as_ref().unwrap(); let dc = dctx_guard.as_mut().unwrap(); dc.commit(dw, &taps, &pb, take as i32, eng.d.eps, 1e6)?; dc.len = (pos + take as i32) as usize; Ok(l) })() } #[cfg(not(feature = "hip"))] { Err("spec requires hip".into()) } } else if take == 1 { eng.forward(toks[0], pos, cap, &mut states[..]) } else { eng.forward_batched(toks, pos, cap, &mut states[..]) }; match lg { Ok(l) => logits = Some(l), Err(e) => { emit_all(emit, sess.on_error(&e)); stop.store(false, Ordering::Relaxed); return; } } history.extend_from_slice(toks); pos += take as i32; done += take; // Multi-level checkpoint grid (strata --auto-ckpt): save an intermediate // checkpoint on every 512 boundary so the next turn can restore a stable // prefix even when the prompt's trailing turn-tag tokens re-render // differently. best_match picks the longest grid checkpoint that is a full // prefix; grid entries are protected from eviction (is_grid) and refreshed // on restore (lru), so turn 3+ keeps advancing instead of falling to 1024. if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos as usize == next_grid { #[cfg(feature = "hip")] let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, if spec_enabled { dctx_guard.as_ref() } else { None }); #[cfg(not(feature = "hip"))] let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d); if std::env::var("VETTA_DBG_PREFIX").is_ok() { eprintln!("[prefix] grid save seq={pos}"); } next_grid += 512; } let ms = t0.elapsed().as_secs_f64() * 1000.0; if let Ok(pp) = sess.on_prefill_chunk((start + done) as u32, n_prompt as u32, ms) { emit_all(emit, pp); } } let prompt_ms = t0.elapsed().as_secs_f64() * 1000.0; // GEN 0 pre-warm: on_prefill_complete emits DONE directly (never decodes). // `start` is the restored prefix length: >0 emits RESUME (wire-compatible // with strata, so strata-ctl reports the reused/cached prompt tokens). match sess.on_prefill_complete(start as u32, prompt_ms) { Ok(lines) => emit_all(emit, lines), Err(e) => { emit_all(emit, sess.on_error(&e)); stop.store(false, Ordering::Relaxed); return; } } // Checkpoint the PROMPT boundary. This is the prefix that stays token-identical // across turns: strata-ctl re-renders the same system+history text each turn, // while the assistant reply round-trips through detokenize/re-encode (special // tokens stripped) and is NOT token-identical to the generated ids. Saving here // — not only at the post-decode `pos` — is what lets the next turn restore the // stable prefix and prefill only the new dialogue suffix. Mirrors strata // --auto-ckpt's prompt-boundary save (proofs/prefix_cache.lean restore_equiv). if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 { #[cfg(feature = "hip")] let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, if spec_enabled { dctx_guard.as_ref() } else { None }); #[cfg(not(feature = "hip"))] let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d); if std::env::var("VETTA_DBG_PREFIX").is_ok() { eprintln!("[prefix] prompt-boundary save seq={pos}"); } } if effective_max_new == 0 { stop.store(false, Ordering::Relaxed); return; } // --- Decode: sample from the last logits, emit T, advance the forward. --- let opts: SamplingOpts = g.sampling; let mut rng = SplitMix64::new(opts.seed); let mut scratch = SamplerScratch::default(); let t1 = Instant::now(); let mut logits = match logits { Some(l) => l, None => { emit_all(emit, sess.on_error("empty prompt")); stop.store(false, Ordering::Relaxed); return; } }; // --- Opt-in DSpark speculative decode (greedy, lossless vs batched B=1). --- #[cfg(feature = "hip")] if spec_enabled { let dw = eng.spec_dw.as_ref().unwrap(); let dc = dctx_guard.as_mut().unwrap(); let t1 = Instant::now(); let mut lg = vec![0f32; eng.vocab]; if let Err(e) = logits.d2h(&mut lg) { emit_all(emit, sess.on_error(&e)); stop.store(false, Ordering::Relaxed); return; } let argmax = |v: &[f32]| -> i32 { let mut best = 0usize; let mut bz = f32::NEG_INFINITY; for (i, &z) in v.iter().enumerate() { if z > bz { bz = z; best = i; } } best as i32 }; let tok0 = argmax(&lg); let mut finish = "length"; let mut generated = 0usize; let emit_tok = |t: i32, emit: &mut dyn FnMut(String), sess: &mut ServeSession, history: &mut Vec, generated: &mut usize| -> bool { match sess.on_token(t as u32) { Ok(lines) => emit_all(emit, lines), Err(e) => { emit_all(emit, sess.on_error(&e)); return false; } } history.push(t); *generated += 1; true }; if !emit_tok(tok0, emit, &mut sess, &mut history, &mut generated) { stop.store(false, Ordering::Relaxed); return; } let mut cur_pos = pos; let mut next_tok = tok0; // Measured on gfx1150 after single-pass GPU drafter + WMMA/fdot2 + small-M SWA: // Rust coding prompt (128 tok): OFF 6.83 | nd=2 11.93 | nd=3 13.90 | nd=4 13.97 | nd=5 13.69 tok/s // Short prose prompt (96 tok): OFF 4.70 | nd=2 9.21 | nd=3 9.09 | nd=4 8.93 | nd=5 9.09 tok/s // Track an EMA of ACCEPTED tokens per round (not acceptance ratio, which // naturally drops as nd grows and used to clamp code generation down to nd=2). // Start at 5 (optimal on code/structured text) and adapt smoothly 2..7. let mut ema_acc = 2.0f32; let mut n_draft = 5usize; // VETTA_SPEC_ND fixes n_draft (bypasses the EMA) for A/B measurement. let nd_override = std::env::var("VETTA_SPEC_ND").ok().and_then(|v| v.parse::().ok()); let mut offered = 0usize; let mut accepted = 0usize; let mut rounds = 0usize; if tok0 == eng.eos { finish = "stop"; } else { while generated < effective_max_new { if stop.load(Ordering::Relaxed) { sess.on_stop(); let ms = t1.elapsed().as_secs_f64() * 1000.0; emit_all(emit, sess.on_drain_complete(ms).unwrap_or_default()); stop.store(false, Ordering::Relaxed); return; } let left = effective_max_new - generated; let nd = nd_override.unwrap_or(n_draft).min(left.saturating_sub(1)); let (em, nc, nt, done) = match spec_round(&eng.cache, &eng.d, dw, dc, &mut states[..], cur_pos, next_tok, nd, eng.vocab, cap, left, |t| t == eng.eos) { Ok(v) => v, Err(e) => { emit_all(emit, sess.on_error(&e)); stop.store(false, Ordering::Relaxed); return; } }; let mut hit_eos = false; for &t in &em { if !emit_tok(t, emit, &mut sess, &mut history, &mut generated) { stop.store(false, Ordering::Relaxed); return; } if t == eng.eos { hit_eos = true; break; } if generated >= effective_max_new { break; } } if nd > 0 { let acc = em.len().saturating_sub(1); ema_acc = 0.85 * ema_acc + 0.15 * (acc as f32); n_draft = if ema_acc >= 3.5 { 7 } else if ema_acc >= 2.0 { 5 } else if ema_acc >= 1.1 { 4 } else if ema_acc >= 0.6 { 3 } else { 2 }; offered += nd; accepted += acc; } rounds += 1; cur_pos = nc; next_tok = nt; pos = nc; if hit_eos { finish = "stop"; break; } if done || generated >= effective_max_new { finish = "length"; break; } } } let decode_ms = t1.elapsed().as_secs_f64() * 1000.0; if std::env::var("VETTA_DBG_SPEC").is_ok() { eprintln!("[spec] rounds={rounds} offered={offered} accepted={accepted} ema_acc={ema_acc:.3} n_draft={n_draft} generated={generated} decode_ms={decode_ms:.1} tok_s={:.2}", generated as f64 / (decode_ms / 1000.0)); } if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 { let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, Some(dc)); } emit_all(emit, sess.on_finish(finish, decode_ms).unwrap_or_default()); stop.store(false, Ordering::Relaxed); return; } let mut finish = "length"; for step in 0..effective_max_new { if stop.load(Ordering::Relaxed) { sess.on_stop(); let ms = t1.elapsed().as_secs_f64() * 1000.0; emit_all(emit, sess.on_drain_complete(ms).unwrap_or_default()); stop.store(false, Ordering::Relaxed); return; } let mut lg = vec![0f32; eng.vocab]; if let Err(e) = logits.d2h(&mut lg) { emit_all(emit, sess.on_error(&e)); stop.store(false, Ordering::Relaxed); return; } let rep = sample_logits_exact(&mut lg, &opts, &history, None, &mut rng, &mut scratch); if std::env::var("VETTA_DBG_LOGITS").is_ok() { let mut idx: Vec = (0..eng.vocab).collect(); idx.sort_by(|&a, &b| lg[b].partial_cmp(&lg[a]).unwrap()); let top: Vec<(usize, f32)> = idx[..5].iter().map(|&i| (i, lg[i])).collect(); eprintln!("[dbg] step={step} pos={pos} top5={top:?}"); } if rep.nonfinite_logits == eng.vocab { finish = "nonfinite"; break; } // Emit the EOS token as `T ` before closing, exactly like the // reference strata-inkling --serve: strata-ctl's Inkling dialect decoder // reads the end-of-sampling channel token to close the model turn. let is_eos = rep.token == eng.eos; match sess.on_token(rep.token as u32) { Ok(lines) => emit_all(emit, lines), Err(e) => { emit_all(emit, sess.on_error(&e)); stop.store(false, Ordering::Relaxed); return; } } if is_eos { finish = "stop"; break; } history.push(rep.token); if step + 1 == effective_max_new { finish = "length"; break; } match eng.forward(rep.token, pos, cap, &mut states[..]) { Ok(l) => logits = l, Err(e) => { emit_all(emit, sess.on_error(&e)); stop.store(false, Ordering::Relaxed); return; } } pos += 1; } let decode_ms = t1.elapsed().as_secs_f64() * 1000.0; // Also checkpoint the full processed sequence (prompt + generated tokens). This // is a bonus reuse when the next prompt IS token-identical (e.g. a retry); the // prompt-boundary checkpoint above is the robust one for normal chat. `pos` // counts tokens actually folded into `states` (history[..pos]); a sampled token // not forwarded (EOS / last length step) is excluded, keeping the ckpt valid. if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 { #[cfg(feature = "hip")] let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, None); #[cfg(not(feature = "hip"))] let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d); if std::env::var("VETTA_DBG_PREFIX").is_ok() { eprintln!("[prefix] full-sequence save seq={pos}"); } } emit_all(emit, sess.on_finish(finish, decode_ms).unwrap_or_default()); stop.store(false, Ordering::Relaxed); } enum Msg { Gen(ParsedGen), Reset, Err(String), Quit, } /// Resident `--serve` loop: emit `READY`, then read GEN/STOP/QUIT lines from /// stdin and answer on stdout. A reader thread parses commands and raises the /// `stop`/`quit` flags so STOP can interrupt an in-flight decode (the FSM then /// drains to DONE). One request at a time (FIFO), matching the consumer. pub fn run_serve(dir: &str) -> Result<(), String> { let eng = InklingEngine::new(dir)?; // Default: eager full-model residency at boot — VRAM is populated immediately // (like the reference) and no request pays NVMe reads/uploads. The cache is // resident across requests either way. VETTA_LAZY_LOAD=1 defers to first use. if std::env::var("VETTA_LAZY_LOAD").is_err() { eng.cache.prewarm(&eng.d, eng.n_layers)?; } let vocab = eng.vocab(); let stop = Arc::new(AtomicBool::new(false)); let quit = Arc::new(AtomicBool::new(false)); let (tx, rx) = mpsc::channel::(); { let stop = Arc::clone(&stop); let quit = Arc::clone(&quit); std::thread::spawn(move || { let stdin = io::stdin(); for line in stdin.lock().lines() { let Ok(line) = line else { break }; match parse_serve_line(&line, vocab) { Ok(ServeCommand::Gen(g)) => { if tx.send(Msg::Gen(g)).is_err() { break; } } Ok(ServeCommand::Reset) => { if tx.send(Msg::Reset).is_err() { break; } } Ok(ServeCommand::Stop) => stop.store(true, Ordering::Relaxed), Ok(ServeCommand::Quit) => { quit.store(true, Ordering::Relaxed); stop.store(true, Ordering::Relaxed); let _ = tx.send(Msg::Quit); break; } Err(e) => { if tx.send(Msg::Err(e)).is_err() { break; } } } } }); } let stdout = io::stdout(); let mut out = stdout.lock(); let mut emit = |line: String| { let _ = writeln!(out, "{line}"); let _ = out.flush(); }; emit(ready_line(eng.max_context() as u32, true, false, false)); loop { if quit.load(Ordering::Relaxed) { break; } match rx.recv() { Ok(Msg::Gen(g)) => { stop.store(false, Ordering::Relaxed); serve_gen(&eng, &g, &stop, &mut emit); } Ok(Msg::Reset) => { // Per-request state is reset in serve_gen; nothing resident to clear. } Ok(Msg::Err(e)) => emit(err_line(&e)), Ok(Msg::Quit) | Err(_) => break, } } Ok(()) } #[cfg(test)] mod tests { use super::*; /// CPU: the budget clamp must keep long agent prompts runnable (strata-ctl /// always sends max_new=16384) instead of hard-erroring past 16382 tokens, and /// only reject a prompt that itself overflows the window. #[test] fn clamp_max_new_budget() { // live agent prompts 16504/16686 with the default 16384 budget: clamp, run. assert_eq!(clamp_max_new(16504, 16384, 32768), Some(32768 - 16504 - 2)); assert_eq!(clamp_max_new(16686, 16384, 32768), Some(32768 - 16686 - 2)); // small prompt keeps the full budget. assert_eq!(clamp_max_new(2648, 16384, 32768), Some(16384)); // exactly at the last usable prompt position: 1 token of room. assert_eq!(clamp_max_new(32765, 16384, 32768), Some(1)); // prompt itself overflows: hard error (None). assert_eq!(clamp_max_new(32766, 16384, 32768), None); assert_eq!(clamp_max_new(40000, 16384, 32768), None); // configurable larger window accepts the same long prompt unclamped. assert_eq!(clamp_max_new(16504, 16384, 65536), Some(16384)); // GEN 0 pre-warm stays 0 regardless of prompt. assert_eq!(clamp_max_new(2648, 0, 32768), Some(0)); } /// GPU integration: drive `serve_gen` over the wire for the canonical prompt /// "The capital of France is" (ids from the tokenizer) and check the emitted /// lines: first `T` is 152717 (" Paris", exact reference match) and the /// request ends in exactly one DONE. Requires GPU + /mnt/models/Inkling. #[test] #[ignore] fn serve_gen_paris_wire() { crate::gpu_isolated(|| { let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); let g = match parse_serve_line("GEN 4 temperature=0 371,151451,149879,151194,149884", eng.vocab()).unwrap() { ServeCommand::Gen(g) => g, _ => panic!("expected Gen"), }; let stop = AtomicBool::new(false); let mut lines: Vec = Vec::new(); serve_gen(&eng, &g, &stop, &mut |l| lines.push(l)); eprintln!("[serve] lines={lines:?}"); let tokens: Vec<&String> = lines.iter().filter(|l| l.starts_with("T ")).collect(); assert!(!tokens.is_empty(), "must emit at least one token"); assert_eq!(tokens[0].as_str(), "T 152717", "first token must be ' Paris'"); let dones: Vec<&String> = lines.iter().filter(|l| l.starts_with("DONE ")).collect(); assert_eq!(dones.len(), 1, "exactly one DONE per request"); assert!(dones[0].ends_with("length") || dones[0].ends_with("stop")); }); } /// GPU integration: `GEN 0` pre-warm emits DONE with zero tokens (Theorem 7). #[test] #[ignore] fn serve_gen_prewarm_no_tokens() { crate::gpu_isolated(|| { let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); let g = match parse_serve_line("GEN 0 371,151451", eng.vocab()).unwrap() { ServeCommand::Gen(g) => g, _ => panic!("expected Gen"), }; let stop = AtomicBool::new(false); let mut lines: Vec = Vec::new(); serve_gen(&eng, &g, &stop, &mut |l| lines.push(l)); assert!(!lines.iter().any(|l| l.starts_with("T ")), "pre-warm emits no tokens"); assert!(lines.iter().any(|l| l.starts_with("DONE 0 2")), "DONE 0 2 ..."); }); } /// GPU regression: multi-token decode must match the reference EXACTLY. This /// locks in the two correctness fixes that eliminated the systematic token-2+ /// divergence: (1) per-pass KV cache (each core pass owns a distinct KV pool, /// exact strata visit_kv_slot) and (2) unpadded logit vocab (padding tokens /// >= unpadded_vocab_size must never win the argmax). Sequence measured against /// strata-inkling --native model.gguf for "The capital of France is" (greedy). #[test] #[ignore] fn serve_gen_multi_token_parity() { crate::gpu_isolated(|| { let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); let g = match parse_serve_line("GEN 16 temperature=0 371,151451,149879,151194,149884", eng.vocab()).unwrap() { ServeCommand::Gen(g) => g, _ => panic!("expected Gen"), }; let stop = AtomicBool::new(false); let mut lines: Vec = Vec::new(); serve_gen(&eng, &g, &stop, &mut |l| lines.push(l)); let tokens: Vec = lines.iter() .filter(|l| l.starts_with("T ")) .map(|l| l[2..].trim().parse().unwrap()) .collect(); let want = [152717, 13, 68014, 32, 13, 220, 44781, 164452, 68014, 33, 13, 220, 57345, 745, 164452, 68014]; assert_eq!(tokens, want, "multi-token decode must match reference exactly"); }); } /// GPU regression: the EOS token must be emitted as `T ` before /// `DONE ... stop` (wire-compatible with strata-inkling --serve, whose /// dialect decoder in strata-ctl reads the end-of-sampling channel token). /// Sequence measured against the reference for the effort-0 capital chat. #[test] #[ignore] fn serve_gen_emits_eos_then_stop() { crate::gpu_isolated(|| { let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); let ids = "200002,200004,34182,279,154554,150628,25,220,15,200010,200000,200004,1775,149884,149876,151451,149879,151194,30,154710,149881,150011,151290,13,200010,200001,200004"; let g = match parse_serve_line(&format!("GEN 8 temperature=0 {ids}"), eng.vocab()).unwrap() { ServeCommand::Gen(g) => g, _ => panic!("expected Gen"), }; let stop = AtomicBool::new(false); let mut lines: Vec = Vec::new(); serve_gen(&eng, &g, &stop, &mut |l| lines.push(l)); let tokens: Vec = lines.iter() .filter(|l| l.starts_with("T ")) .map(|l| l[2..].trim().parse().unwrap()) .collect(); assert_eq!(tokens, [3967, 198, 200010, 200006], "EOS must be emitted as the last T"); let done = lines.iter().find(|l| l.starts_with("DONE ")).expect("one DONE"); assert!(done.ends_with(" stop"), "finish must be stop, got {done}"); }); } /// GPU: the opt-in DSpark speculative serve path (VETTA_SPEC=1, batched /// verify + rollback + EMA) must emit EXACTLY the same reference tokens as /// the default M=1 decode for the canonical capital prompt. Verifies the /// serve orchestration (pos/history/EOS/length) AND that the batched decode /// path is greedy-vs-reference exact. #[test] #[ignore] fn serve_gen_spec_multi_token_parity() { crate::gpu_isolated(|| { unsafe { std::env::set_var("VETTA_SPEC", "1"); } let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); assert!(eng.spec_dw.is_some(), "drafter weights must load with VETTA_SPEC=1"); let g = match parse_serve_line("GEN 16 temperature=0 371,151451,149879,151194,149884", eng.vocab()).unwrap() { ServeCommand::Gen(g) => g, _ => panic!("expected Gen"), }; let stop = AtomicBool::new(false); let mut lines: Vec = Vec::new(); serve_gen(&eng, &g, &stop, &mut |l| lines.push(l)); let tokens: Vec = lines.iter() .filter(|l| l.starts_with("T ")) .map(|l| l[2..].trim().parse().unwrap()) .collect(); let want = [152717, 13, 68014, 32, 13, 220, 44781, 164452, 68014, 33, 13, 220, 57345, 745, 164452, 68014]; unsafe { std::env::remove_var("VETTA_SPEC"); } assert_eq!(tokens, want, "speculative serve path must match reference exactly"); }); } /// GPU perf probe: spec-on vs spec-off decode tok/s + acceptance on a real /// prompt (GEN 96). Prints measured numbers; no speedup claim without them. #[test] #[ignore] fn serve_gen_spec_perf() { crate::gpu_isolated(|| { let ids = "371,151451,149879,151194,149884"; let run = |spec: bool| -> (f64, usize) { if spec { unsafe { std::env::set_var("VETTA_SPEC", "1"); } } else { unsafe { std::env::remove_var("VETTA_SPEC"); } } unsafe { std::env::set_var("VETTA_DBG_SPEC", "1"); } let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); let g = match parse_serve_line(&format!("GEN 96 temperature=0 {ids}"), eng.vocab()).unwrap() { ServeCommand::Gen(g) => g, _ => panic!("expected Gen"), }; let stop = AtomicBool::new(false); let mut lines: Vec = Vec::new(); let t = Instant::now(); serve_gen(&eng, &g, &stop, &mut |l| lines.push(l)); let ms = t.elapsed().as_secs_f64() * 1000.0; let n = lines.iter().filter(|l| l.starts_with("T ")).count(); unsafe { std::env::remove_var("VETTA_SPEC"); std::env::remove_var("VETTA_DBG_SPEC"); } (ms, n) }; let (off_ms, off_n) = run(false); let (on_ms, on_n) = run(true); eprintln!("spec_perf: OFF {off_n} tok {off_ms:.1}ms {:.2} tok/s | ON {on_n} tok {on_ms:.1}ms {:.2} tok/s", off_n as f64 / (off_ms / 1000.0), on_n as f64 / (on_ms / 1000.0)); assert_eq!(off_n, on_n, "spec must emit the same token count"); }); } /// GPU: multi-turn PrefixCache + DsparkSnapshot restore regression test. /// Turn 1 prefills + generates 16 tokens and saves a checkpoint with DSpark /// state; Turn 2 extends Turn 1's exact prompt + generated tokens with a /// follow-up suffix, hitting RESUME on Turn 1's checkpoint and restoring /// DSpark rings + frnn_last. Turn 2 output with VETTA_SPEC=1 must match /// VETTA_SPEC=0 100% EXACT and emit a non-zero RESUME. #[test] #[ignore] fn serve_gen_spec_prefix_cache_multi_turn_parity() { crate::gpu_isolated(|| { let turn1_ids = "200002,200004,34182,279,154554,150628,25,220,15,200010,200000,200004,10970,261,4660,11,5603,59195,9268,328,261,6164,12,13448,8459,6462,13,200010,200001,200004"; let run_two_turns = |spec: bool| -> (Vec, Vec, usize) { if spec { unsafe { std::env::set_var("VETTA_SPEC", "1"); } } else { unsafe { std::env::remove_var("VETTA_SPEC"); } } let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); let stop = AtomicBool::new(false); // Turn 1 let g1 = match parse_serve_line(&format!("GEN 16 temperature=0 {turn1_ids}"), eng.vocab()).unwrap() { ServeCommand::Gen(g) => g, _ => panic!("expected Gen"), }; let mut l1 = Vec::new(); serve_gen(&eng, &g1, &stop, &mut |l| l1.push(l)); let t1: Vec = l1.iter().filter(|l| l.starts_with("T ")).map(|l| l[2..].trim().parse().unwrap()).collect(); // Turn 2 extends Turn 1 prompt + Turn 1 reply + short follow-up prompt let mut turn2_vec: Vec = turn1_ids.split(',').map(|s| s.to_string()).collect(); for &id in &t1 { turn2_vec.push(id.to_string()); } for extra in [200010, 200000, 200004, 10970, 261, 2324, 13, 200010, 200001, 200004] { turn2_vec.push(extra.to_string()); } let turn2_ids = turn2_vec.join(","); let g2 = match parse_serve_line(&format!("GEN 24 temperature=0 {turn2_ids}"), eng.vocab()).unwrap() { ServeCommand::Gen(g) => g, _ => panic!("expected Gen"), }; let mut l2 = Vec::new(); serve_gen(&eng, &g2, &stop, &mut |l| l2.push(l)); let t2: Vec = l2.iter().filter(|l| l.starts_with("T ")).map(|l| l[2..].trim().parse().unwrap()).collect(); let resumed: usize = l2.iter() .find(|l| l.starts_with("RESUME ")) .and_then(|l| l[7..].trim().parse().ok()) .unwrap_or(0); unsafe { std::env::remove_var("VETTA_SPEC"); } (t1, t2, resumed) }; let (off_t1, off_t2, off_resumed) = run_two_turns(false); let (on_t1, on_t2, on_resumed) = run_two_turns(true); eprintln!("multi-turn prefix cache: off_resumed={off_resumed} on_resumed={on_resumed} t1_len={} t2_len={}", on_t1.len(), on_t2.len()); assert!(on_resumed > 0, "Turn 2 with VETTA_SPEC=1 must hit PrefixCache RESUME"); assert_eq!(on_resumed, off_resumed, "Turn 2 RESUME length must match OFF"); assert_eq!(on_t1, off_t1, "Turn 1 tokens must match OFF exactly"); assert_eq!(on_t2, off_t2, "Turn 2 tokens after PrefixCache+DsparkSnapshot restore must match OFF exactly"); }); } /// GPU: verify that saving multiple large PrefixCache checkpoints (trunk KV + /// ShortConv + DsparkSnapshot across grid boundaries 512, 1024, 1536, 2048) /// keeps GPU VRAM completely flat (0 bytes added per checkpoint in VRAM, /// since all snapshots live in pinned host RAM via `PinnedBuf`). #[test] #[ignore] fn serve_gen_pinned_prefix_cache_vram_flat() { crate::gpu_isolated(|| { unsafe { std::env::set_var("VETTA_SPEC", "1"); } let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); let stop = AtomicBool::new(false); let mut prompt: Vec = Vec::with_capacity(2200); let seed = [200002, 200004, 34182, 279, 154554, 150628, 25, 220, 15, 200010, 200000, 200004]; prompt.extend_from_slice(&seed); let mut vram_samples: Vec<(usize, usize, usize)> = Vec::new(); for target_len in [600usize, 1100, 1600, 2100] { while prompt.len() < target_len { prompt.push(10970 + ((prompt.len() * 17) % 500) as i32); } let ids_str = prompt.iter().map(|t| t.to_string()).collect::>().join(","); let g = match parse_serve_line(&format!("GEN 8 temperature=0 {ids_str}"), eng.vocab()).unwrap() { ServeCommand::Gen(g) => g, _ => panic!("expected Gen"), }; let mut lines = Vec::new(); serve_gen(&eng, &g, &stop, &mut |l| lines.push(l)); let resumed: usize = lines.iter() .find(|l| l.starts_with("RESUME ")) .and_then(|l| l[7..].trim().parse().ok()) .unwrap_or(0); let ckpts = eng.prefix.borrow().pool.len(); let vram = vetta_infer_hip::vram_used(); eprintln!( "pinned_ckpt_vram: prompt={} resumed={} ckpts={} vram={:.2} MiB", target_len, resumed, ckpts, vram as f64 / (1024.0 * 1024.0) ); vram_samples.push((target_len, resumed, vram)); } unsafe { std::env::remove_var("VETTA_SPEC"); } assert!(vram_samples[1].1 >= 512, "Turn 2 must hit >=512 checkpoint, got {}", vram_samples[1].1); assert!(vram_samples[2].1 >= 1024, "Turn 3 must hit >=1024 checkpoint, got {}", vram_samples[2].1); assert!(vram_samples[3].1 >= 1536, "Turn 4 must hit >=1536 checkpoint, got {}", vram_samples[3].1); // Compare VRAM after Turn 1 (once KV + DsparkContext + BUF_POOL are warm) // against Turn 4 (after filling 8 checkpoints up to 2100 tokens). let v1 = vram_samples[0].2; let v4 = vram_samples[3].2; let delta_mb = (v4 as isize - v1 as isize) as f64 / (1024.0 * 1024.0); eprintln!("pinned_ckpt_vram: Turn1->Turn4 delta = {delta_mb:+.2} MiB (expected ~0 MiB)"); assert!( delta_mb.abs() < 32.0, "PrefixCache in pinned RAM must keep VRAM flat across checkpoints, got {delta_mb:+.2} MiB" ); }); } }