diff --git a/crates/vetta-infer-gw/src/serve.rs b/crates/vetta-infer-gw/src/serve.rs index a6e6bbb..fc15c7a 100644 --- a/crates/vetta-infer-gw/src/serve.rs +++ b/crates/vetta-infer-gw/src/serve.rs @@ -56,8 +56,12 @@ const MAX_CONTEXT: usize = 32768; /// 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 = 6; +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, @@ -92,21 +96,28 @@ impl PrefixCache { } /// Allocate + restore every checkpointed layer into `states` at `max_seq`. - fn restore(&self, idx: usize, states: &mut [Option], d: &Dims, max_seq: usize) -> Result { - 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 { - let mut st = new_state(d, max_seq, s.k_cache.len())?; - st.restore(d, s)?; - states[ip] = Some(st); + /// 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. + fn restore(&mut self, idx: usize, states: &mut [Option], d: &Dims, max_seq: usize) -> Result { + { + 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 { + let mut st = new_state(d, max_seq, s.k_cache.len())?; + st.restore(d, s)?; + states[ip] = Some(st); + } } } - Ok(ck.tokens.len()) + self.tick += 1; + self.pool[idx].lru = self.tick; + Ok(self.pool[idx].tokens.len()) } /// Snapshot all layer states at `tokens.len()` and insert (update / grow / @@ -129,7 +140,7 @@ impl PrefixCache { } let victim = self.pool.iter().enumerate() .filter(|(_, c)| !pinned_anchor(c.tokens.len())) - .min_by_key(|(_, c)| c.lru).map(|(i, _)| i); + .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, lru }; } @@ -284,8 +295,9 @@ pub fn serve_gen( // 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() { - if let Some((idx, _l)) = eng.prefix.borrow().best_match(&g.ids) { - match eng.prefix.borrow().restore(idx, &mut states, &eng.d, max_seq) { + let matched = eng.prefix.borrow().best_match(&g.ids); + if let Some((idx, _l)) = matched { + match eng.prefix.borrow_mut().restore(idx, &mut states, &eng.d, max_seq) { Ok(n) => start = n, Err(_) => { // Incomplete/failed restore: fall back to a clean cold prefill. @@ -326,6 +338,10 @@ pub fn serve_gen( let chunk = prefill_chunk_size(); 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(); @@ -334,7 +350,11 @@ pub fn serve_gen( stop.store(false, Ordering::Relaxed); return; } - let take = chunk.min(suffix.len() - done); + 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 take == 1 { eng.forward(toks[0], pos, max_seq, &mut states) @@ -353,16 +373,17 @@ pub fn serve_gen( pos += take as i32; done += take; // Multi-level checkpoint grid (strata --auto-ckpt): save an intermediate - // checkpoint every 512 tokens so the next turn can restore a stable prefix - // even when the prompt's trailing turn-tag tokens re-render differently - // (strata-ctl serializes the turn boundary differently once turn 1 becomes - // history). best_match then picks the longest 512-grid checkpoint that is a - // full prefix, instead of discarding everything over a 2-token tail mismatch. - if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 && pos % 512 == 0 { + // 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 { 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) {