[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:
adm committed 2026-12-01 20:30:13 +01:00
1 parent f12281ec61
commit 736c541887
6 files changed
+220 -10

No files matched your search

+128 -7
View File
@@ -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);
}
+16
View File
@@ -29,6 +29,8 @@ mod ffi {
pub fn vetta_buf_free(p: *mut c_void) -> c_int;
pub fn vetta_buf_h2d(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int;
pub fn vetta_buf_d2h(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int;
pub fn vetta_buf_copy(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int;
pub fn vetta_buf_copy2d(dst: *mut c_void, dpitch: usize, src: *const c_void, spitch: usize, width: usize, height: usize) -> c_int;
pub fn vetta_rms_norm_f32(
x: *const c_float, w: *const c_float, y: *mut c_float,
rows: c_int, d: c_int, eps: c_float, stream: *mut c_void,
@@ -242,6 +244,20 @@ impl DeviceBuf {
if rc != 0 { return Err("d2h failed".into()); }
Ok(())
}
/// Device-to-device copy of `bytes` from `src` into `self`.
pub fn copy_from(&self, src: &DeviceBuf, bytes: usize) -> Result<(), String> {
if bytes > self.bytes || bytes > src.bytes { return Err("copy overflow".into()); }
let rc = unsafe { ffi::vetta_buf_copy(self.ptr, src.ptr, bytes) };
if rc != 0 { return Err("d2d copy failed".into()); }
Ok(())
}
/// Pitched device-to-device copy: `height` rows of `width` bytes, source row
/// stride `spitch`, destination row stride `dpitch` (KV prefix sub-block).
pub fn copy2d_from(&self, src: &DeviceBuf, dpitch: usize, spitch: usize, width: usize, height: usize) -> Result<(), String> {
let rc = unsafe { ffi::vetta_buf_copy2d(self.ptr, dpitch, src.ptr, spitch, width, height) };
if rc != 0 { return Err("d2d copy2d failed".into()); }
Ok(())
}
}
#[cfg(feature = "hip")]
+58
View File
@@ -207,6 +207,64 @@ pub fn new_state(d: &Dims, max_seq: usize, n_passes: usize) -> Result<LayerState
})
}
/// A checkpoint of one layer's decode state at a prefix boundary `seq_len`: the
/// KV prefix `[n_kv, seq_len, hd]` per pass + the ShortConv history rings. Sized
/// to seq_len (KV unpooled), held in the prefix cache across requests. Restoring
/// it and prefilling the suffix is exact (proofs/prefix_cache.lean restore_equiv).
pub struct LayerSnapshot {
pub seq_len: usize,
pub k_cache: Vec<DeviceBuf>, pub v_cache: Vec<DeviceBuf>,
pub hist_k: [DeviceBuf; 3], pub hist_v: [DeviceBuf; 3],
pub hist_a: [DeviceBuf; 3], pub hist_m: [DeviceBuf; 3],
}
impl LayerState {
/// Snapshot the KV prefix `[0, seq_len)` (pitched copy out of the
/// `[n_kv, max_seq, hd]` cache) plus the current ShortConv history rings.
pub fn snapshot(&self, d: &Dims, seq_len: usize) -> Result<LayerSnapshot, String> {
let es = if f16_kv() { 2 } else { 4 };
let row = seq_len * d.hd * es;
let snap_kv = |src: &DeviceBuf| -> Result<DeviceBuf, String> {
let b = DeviceBuf::alloc_unpooled(d.n_kv * row)?;
b.copy2d_from(src, row, self.max_seq * d.hd * es, row, d.n_kv)?;
Ok(b)
};
let k_cache = self.k_cache.iter().map(snap_kv).collect::<Result<Vec<_>, _>>()?;
let v_cache = self.v_cache.iter().map(snap_kv).collect::<Result<Vec<_>, _>>()?;
let cp = |src: &DeviceBuf| -> Result<DeviceBuf, String> {
let b = DeviceBuf::alloc(src.bytes)?; b.copy_from(src, src.bytes)?; Ok(b)
};
Ok(LayerSnapshot {
seq_len, k_cache, v_cache,
hist_k: [cp(&self.hist_k[0])?, cp(&self.hist_k[1])?, cp(&self.hist_k[2])?],
hist_v: [cp(&self.hist_v[0])?, cp(&self.hist_v[1])?, cp(&self.hist_v[2])?],
hist_a: [cp(&self.hist_a[0])?, cp(&self.hist_a[1])?, cp(&self.hist_a[2])?],
hist_m: [cp(&self.hist_m[0])?, cp(&self.hist_m[1])?, cp(&self.hist_m[2])?],
})
}
/// Restore the KV prefix `[0, snap.seq_len)` + history into `self` (whose
/// max_seq must be >= snap.seq_len). Positions >= seq_len stay zero for the
/// suffix prefill to fill; attention at pos >= seq_len reads only [0, pos].
pub fn restore(&mut self, d: &Dims, snap: &LayerSnapshot) -> Result<(), String> {
let es = if f16_kv() { 2 } else { 4 };
let row = snap.seq_len * d.hd * es;
for (dst, src) in self.k_cache.iter().zip(&snap.k_cache) {
dst.copy2d_from(src, self.max_seq * d.hd * es, row, row, d.n_kv)?;
}
for (dst, src) in self.v_cache.iter().zip(&snap.v_cache) {
dst.copy2d_from(src, self.max_seq * d.hd * es, row, row, d.n_kv)?;
}
for i in 0..3 {
self.hist_k[i].copy_from(&snap.hist_k[i], snap.hist_k[i].bytes)?;
self.hist_v[i].copy_from(&snap.hist_v[i], snap.hist_v[i].bytes)?;
self.hist_a[i].copy_from(&snap.hist_a[i], snap.hist_a[i].bytes)?;
self.hist_m[i].copy_from(&snap.hist_m[i], snap.hist_m[i].bytes)?;
}
Ok(())
}
}
/// KV cache dtype switch. The CPU-oracle parity baseline (and the ld packer
/// tests) use F32; the resident serve opts into FP16 — the exact strata default
/// (KvDtype::FP16, "default lossless FP16"), parity-verified EXACT (16/40 greedy