[GW][LD][HIP][Proofs] Wire prefix checkpoint cache into serve: restore longest prefix, prefill only new suffix
Concept ported from strata --auto-ckpt, adapted to vetta's contiguous per-pass
KV + ShortConv history (proofs/prefix_cache.lean, restore_equiv). serve_gen now
restores the longest cached STRICT prefix of a prompt and prefills only the new
suffix tokens; the final logits still come from a real forward of the last prompt
token. Checkpoints save at pos (prompt + generated non-EOS tokens) so the next
turn reuses the full prior context. Pinned anchors {512,1024} never evicted (I3),
LRU at cap 6; KV snapshots unpooled (freed on eviction). VETTA_NO_PREFIX_CACHE
forces cold prefill for A/B.
Device-to-device copy FFI (vetta_buf_copy / vetta_buf_copy2d) + DeviceBuf
copy_from/copy2d_from; LayerState snapshot/restore (pitched KV prefix + hist).
Verified: CPU 91 + gw GPU 5 + hip GPU 18 + ld GPU 18 green; Lean 0 sorryAx.
Multi-turn parity EXACT (restore == cold re-prefill), both prewarm- and
decode-state checkpoints. Measured (gfx1150, Inkling-2-Mini, FP16 KV, greedy):
605-token prompt, 600-token cached prefix -> prefill 132.5s cold vs 2.29s warm
(57.8x), end-to-end 133.2s vs 3.2s (41.8x).
This commit is contained in:
1 parent
f12281ec61
commit
736c541887
6 files changed
+220
-10
No files matched your search
@@ -16,6 +16,7 @@
|
||||
//! 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;
|
||||
@@ -26,7 +27,7 @@ use vetta_infer_abi::sampler::{
|
||||
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_inkling_with_state, Dims, LayerState, WeightCache};
|
||||
use vetta_infer_ld::layer::{forward_inkling_with_state, new_state, Dims, LayerSnapshot, LayerState, WeightCache};
|
||||
use vetta_infer_ld::SafetensorsArchive;
|
||||
|
||||
use crate::session::ServeSession;
|
||||
@@ -50,6 +51,92 @@ const SITU_LB: f32 = 25.0;
|
||||
/// not limited by the 64 KB LDS cap.
|
||||
const MAX_CONTEXT: usize = 32768;
|
||||
|
||||
/// 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 = 6;
|
||||
fn pinned_anchor(seq: usize) -> bool { seq == 512 || seq == 1024 }
|
||||
|
||||
struct Checkpoint {
|
||||
tokens: Vec<i32>,
|
||||
layers: Vec<Option<LayerSnapshot>>,
|
||||
lru: u64,
|
||||
}
|
||||
|
||||
/// Resident pool of prefix checkpoints (interior mutability: serve_gen holds
|
||||
/// `&InklingEngine`). Single conversation slot (FIFO serve).
|
||||
pub struct PrefixCache {
|
||||
pool: Vec<Checkpoint>,
|
||||
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`.
|
||||
fn restore(&self, idx: usize, states: &mut [Option<LayerState>], d: &Dims, max_seq: usize) -> Result<usize, String> {
|
||||
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())
|
||||
}
|
||||
|
||||
/// Snapshot all layer states 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<LayerState>], d: &Dims) -> Result<(), String> {
|
||||
let seq = tokens.len();
|
||||
if seq == 0 { return Ok(()); }
|
||||
let layers: Vec<Option<LayerSnapshot>> = states.iter()
|
||||
.map(|st| st.as_ref().map(|s| s.snapshot(d, seq)).transpose())
|
||||
.collect::<Result<_, _>>()?;
|
||||
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;
|
||||
return Ok(());
|
||||
}
|
||||
if self.pool.len() < PREFIX_CACHE_CAP {
|
||||
self.pool.push(Checkpoint { tokens: tokens.to_vec(), layers, lru });
|
||||
return Ok(());
|
||||
}
|
||||
let victim = self.pool.iter().enumerate()
|
||||
.filter(|(_, c)| !pinned_anchor(c.tokens.len()))
|
||||
.min_by_key(|(_, c)| c.lru).map(|(i, _)| i);
|
||||
if let Some(i) = victim {
|
||||
self.pool[i] = Checkpoint { tokens: tokens.to_vec(), layers, lru };
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A loaded Inkling model ready to run autoregressive forwards.
|
||||
pub struct InklingEngine {
|
||||
ar: SafetensorsArchive,
|
||||
@@ -58,6 +145,7 @@ pub struct InklingEngine {
|
||||
n_layers: usize,
|
||||
eos: i32,
|
||||
cap: f32,
|
||||
prefix: RefCell<PrefixCache>,
|
||||
}
|
||||
|
||||
impl InklingEngine {
|
||||
@@ -103,6 +191,7 @@ impl InklingEngine {
|
||||
n_layers: t.n_layers,
|
||||
eos: cfg.eos_token_id as i32,
|
||||
cap: t.final_logit_softcapping as f32,
|
||||
prefix: RefCell::new(PrefixCache::new()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -137,8 +226,9 @@ fn emit_all(emit: &mut dyn FnMut(String), lines: Vec<String>) {
|
||||
/// 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 resets the per-layer state and re-prefills the prompt (prefix
|
||||
/// cache reuse is a later performance refinement; correctness is identical).
|
||||
/// 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,
|
||||
@@ -165,16 +255,36 @@ pub fn serve_gen(
|
||||
}
|
||||
};
|
||||
|
||||
// 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() {
|
||||
if let Some((idx, _l)) = eng.prefix.borrow().best_match(&g.ids) {
|
||||
match eng.prefix.borrow().restore(idx, &mut states, &eng.d, max_seq) {
|
||||
Ok(n) => start = n,
|
||||
Err(_) => {
|
||||
// Incomplete/failed restore: fall back to a clean cold prefill.
|
||||
states = match eng.fresh_states(max_seq) {
|
||||
Ok(s) => s,
|
||||
Err(e) => { emit_all(emit, sess.on_error(&e)); return; }
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 the NEW prompt tokens, growing KV/history. ---
|
||||
let t0 = Instant::now();
|
||||
let mut pos = 0i32;
|
||||
let mut history: Vec<i32> = Vec::with_capacity(n_prompt + g.max_new);
|
||||
let mut pos = start as i32;
|
||||
let mut history: Vec<i32> = g.ids[..start].to_vec();
|
||||
history.reserve(n_prompt - start + g.max_new);
|
||||
let mut logits: Option<DeviceBuf> = None;
|
||||
for (i, &tok) in g.ids.iter().enumerate() {
|
||||
for (i, &tok) in g.ids.iter().enumerate().skip(start) {
|
||||
if stop.load(Ordering::Relaxed) {
|
||||
sess.on_stop();
|
||||
let ms = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
@@ -208,6 +318,10 @@ pub fn serve_gen(
|
||||
}
|
||||
}
|
||||
if g.max_new == 0 {
|
||||
// Pre-warm folded the full prompt into `states`: checkpoint it for reuse.
|
||||
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);
|
||||
}
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
@@ -283,6 +397,13 @@ pub fn serve_gen(
|
||||
pos += 1;
|
||||
}
|
||||
let decode_ms = t1.elapsed().as_secs_f64() * 1000.0;
|
||||
// Checkpoint the full processed prefix (prompt + generated tokens) so the next
|
||||
// turn restores it and prefills only its new suffix. `pos` counts the tokens
|
||||
// actually folded into `states` (history[..pos]); a sampled token that was not
|
||||
// forwarded (EOS / last length step) is excluded, keeping the checkpoint valid.
|
||||
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);
|
||||
}
|
||||
emit_all(emit, sess.on_finish(finish, decode_ms).unwrap_or_default());
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user