[Core] Flat VRAM: persistent KV states + SWA-window prefix checkpoints
a6 (persistent states): serve_gen allocated+freed ~3.75GB KV every request (the +/-3.75GB sawtooth, max_new=16384). InklingEngine now holds persistent per-layer states sized to a 4096-bucket cap >= prompt+max_new, reused across requests and grown only on a bucket crossing. restore reuses a correctly-sized state; a cold request resets the ShortConv hist rings (reset_history, async) since the KV prefix is overwritten by prefill before any causal read. Verified: two identical GEN16384 requests -> vram 23.46/23.49GB flat (no sawtooth), identical reference output; twice-paris cold-reuse output identical. a8 (SWA-window checkpoints): 40 of 48 KV pools are SWA (swa_win=1024) but the snapshot stored the full seq_len on all of them (~510MB/checkpoint at seq2600). Now SWA layers checkpoint only the last min(seq,1024) positions (kv_start offset via new DeviceBuf::copy2d_at); full-attn layers keep the whole prefix. Checkpoint ~210MB. proofs/prefix_cache.lean Part D proves kvStart_le_winStart containment + swa_window_restore_equiv (windowed restore observationally exact). Verified: cold vs restored(1536, window truncated to [512,1536)) emit identical tokens. Measured 5-turn VRAM climb +2.6GB -> +1.16GB (bounded by cap 8), KV flat. Suite green: ld23 hip33 gw4 GPU serial, CPU -D warnings, Lean 0 sorryAx.
This commit is contained in:
1 parent
a6ca73105c
commit
47f8b52070
4 files changed
+159
-42
No files matched your search
@@ -16,7 +16,7 @@
|
||||
//! is callable from an integration test without spawning the binary.
|
||||
|
||||
use std::io::{self, BufRead, Write};
|
||||
use std::cell::RefCell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{mpsc, Arc};
|
||||
use std::time::Instant;
|
||||
@@ -27,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_batch, forward_inkling_with_state, new_state, Dims, LayerSnapshot, LayerState, WeightCache};
|
||||
use vetta_infer_ld::layer::{forward_batch, forward_inkling_with_state, is_swa, new_state, Dims, LayerSnapshot, LayerState, WeightCache};
|
||||
use vetta_infer_ld::SafetensorsArchive;
|
||||
|
||||
use crate::session::ServeSession;
|
||||
@@ -109,9 +109,16 @@ impl PrefixCache {
|
||||
}
|
||||
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);
|
||||
// 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 reuse = states[ip].as_ref()
|
||||
.map_or(false, |st| st.max_seq == max_seq && st.k_cache.len() == s.k_cache.len());
|
||||
if !reuse {
|
||||
states[ip] = Some(new_state(d, max_seq, s.k_cache.len())?);
|
||||
}
|
||||
states[ip].as_mut().unwrap().restore(d, s)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,8 +132,8 @@ impl PrefixCache {
|
||||
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())
|
||||
let layers: Vec<Option<LayerSnapshot>> = states.iter().enumerate()
|
||||
.map(|(ip, st)| st.as_ref().map(|s| s.snapshot(d, seq, is_swa(ip))).transpose())
|
||||
.collect::<Result<_, _>>()?;
|
||||
self.tick += 1;
|
||||
let lru = self.tick;
|
||||
@@ -157,6 +164,11 @@ pub struct InklingEngine {
|
||||
eos: i32,
|
||||
cap: f32,
|
||||
prefix: RefCell<PrefixCache>,
|
||||
/// 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<Vec<Option<LayerState>>>,
|
||||
states_cap: Cell<usize>,
|
||||
}
|
||||
|
||||
impl InklingEngine {
|
||||
@@ -207,6 +219,8 @@ impl InklingEngine {
|
||||
eos: cfg.eos_token_id as i32,
|
||||
cap: t.final_logit_softcapping as f32,
|
||||
prefix: RefCell::new(PrefixCache::new()),
|
||||
states: RefCell::new(Vec::new()),
|
||||
states_cap: Cell::new(0),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -214,11 +228,6 @@ impl InklingEngine {
|
||||
self.vocab
|
||||
}
|
||||
|
||||
fn fresh_states(&self, _max_seq: usize) -> Result<Vec<Option<LayerState>>, String> {
|
||||
// States are allocated lazily per layer by run_layer; start all None.
|
||||
Ok((0..self.n_layers).map(|_| None).collect())
|
||||
}
|
||||
|
||||
fn forward(
|
||||
&self,
|
||||
token: i32,
|
||||
@@ -282,13 +291,15 @@ pub fn serve_gen(
|
||||
emit_all(emit, sess.on_error("prompt + max_new exceeds context window"));
|
||||
return;
|
||||
}
|
||||
let mut states = match eng.fresh_states(max_seq) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
emit_all(emit, sess.on_error(&e));
|
||||
return;
|
||||
}
|
||||
};
|
||||
// Persistent KV states: size once to a 4096-bucket cap >= max_seq and reuse
|
||||
// across requests (no per-request ~3.75 GB alloc/free sawtooth). Grow only when
|
||||
// a request crosses the bucket. `cap` is the KV stride passed to the forwards.
|
||||
let cap = max_seq.next_multiple_of(4096).min(MAX_CONTEXT);
|
||||
if eng.states_cap.get() < cap || eng.states.borrow().len() != eng.n_layers {
|
||||
*eng.states.borrow_mut() = (0..eng.n_layers).map(|_| None).collect();
|
||||
eng.states_cap.set(cap);
|
||||
}
|
||||
let mut states = eng.states.borrow_mut();
|
||||
|
||||
// Prefix checkpoint reuse (proofs/prefix_cache.lean restore_equiv): restore
|
||||
// the longest cached strict prefix of this prompt and prefill only the NEW
|
||||
@@ -297,18 +308,28 @@ pub fn serve_gen(
|
||||
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 {
|
||||
match eng.prefix.borrow_mut().restore(idx, &mut states, &eng.d, max_seq) {
|
||||
match eng.prefix.borrow_mut().restore(idx, &mut states[..], &eng.d, cap) {
|
||||
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; }
|
||||
};
|
||||
*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;
|
||||
}
|
||||
}
|
||||
}
|
||||
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
||||
eprintln!("[prefix] prompt_len={n_prompt} restored={start}");
|
||||
if start == 0 {
|
||||
@@ -357,9 +378,9 @@ pub fn serve_gen(
|
||||
}
|
||||
let toks = &suffix[done..done + take];
|
||||
let lg = if take == 1 {
|
||||
eng.forward(toks[0], pos, max_seq, &mut states)
|
||||
eng.forward(toks[0], pos, cap, &mut states[..])
|
||||
} else {
|
||||
eng.forward_batched(toks, pos, max_seq, &mut states)
|
||||
eng.forward_batched(toks, pos, cap, &mut states[..])
|
||||
};
|
||||
match lg {
|
||||
Ok(l) => logits = Some(l),
|
||||
@@ -379,7 +400,7 @@ pub fn serve_gen(
|
||||
// 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);
|
||||
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}");
|
||||
}
|
||||
@@ -410,7 +431,7 @@ pub fn serve_gen(
|
||||
// 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 {
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states, &eng.d);
|
||||
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}");
|
||||
}
|
||||
@@ -480,7 +501,7 @@ pub fn serve_gen(
|
||||
finish = "length";
|
||||
break;
|
||||
}
|
||||
match eng.forward(rep.token, pos, max_seq, &mut states) {
|
||||
match eng.forward(rep.token, pos, cap, &mut states[..]) {
|
||||
Ok(l) => logits = l,
|
||||
Err(e) => {
|
||||
emit_all(emit, sess.on_error(&e));
|
||||
@@ -497,7 +518,7 @@ pub fn serve_gen(
|
||||
// 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 {
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states, &eng.d);
|
||||
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}");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user