[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}");
|
||||
}
|
||||
|
||||
@@ -329,6 +329,22 @@ impl DeviceBuf {
|
||||
if rc != 0 { return Err("d2d copy2d failed".into()); }
|
||||
Ok(())
|
||||
}
|
||||
/// Pitched device-to-device copy with byte offsets into BOTH buffers: copies
|
||||
/// `height` rows of `width` bytes from `src[src_off..]` (row stride `spitch`)
|
||||
/// into `self[dst_off..]` (row stride `dpitch`). Used by the SWA-window prefix
|
||||
/// snapshot/restore to copy only the last `swa_win` KV positions of each head.
|
||||
pub fn copy2d_at(&self, dst_off: usize, src: &DeviceBuf, src_off: usize, dpitch: usize, spitch: usize, width: usize, height: usize) -> Result<(), String> {
|
||||
if height > 0 {
|
||||
let dlast = dst_off + (height - 1) * dpitch + width;
|
||||
let slast = src_off + (height - 1) * spitch + width;
|
||||
if dlast > self.bytes || slast > src.bytes { return Err("copy2d_at overflow".into()); }
|
||||
}
|
||||
let dp = unsafe { (self.ptr as *mut u8).add(dst_off) as *mut std::os::raw::c_void };
|
||||
let sp = unsafe { (src.ptr as *const u8).add(src_off) as *const std::os::raw::c_void };
|
||||
let rc = unsafe { ffi::vetta_buf_copy2d(dp, dpitch, sp, spitch, width, height) };
|
||||
if rc != 0 { return Err("d2d copy2d_at failed".into()); }
|
||||
Ok(())
|
||||
}
|
||||
/// Async zero-fill of the whole buffer on the default stream (hipMemsetAsync):
|
||||
/// ordered before later kernels with NO blocking host round-trip. Replaces a
|
||||
/// sync `h2d(&vec![0; n])` that would drain the GPU queue every layer visit.
|
||||
|
||||
@@ -277,20 +277,31 @@ pub fn new_state(d: &Dims, max_seq: usize, n_passes: usize) -> Result<LayerState
|
||||
/// it and prefilling the suffix is exact (proofs/prefix_cache.lean restore_equiv).
|
||||
pub struct LayerSnapshot {
|
||||
pub seq_len: usize,
|
||||
/// First KV position stored in this snapshot. For full-attn layers it is 0
|
||||
/// (whole prefix); for SWA layers it is seq_len - min(seq_len, swa_win), so
|
||||
/// only the causal window is checkpointed (the older KV is never read again).
|
||||
pub kv_start: 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> {
|
||||
/// Snapshot the KV prefix plus the current ShortConv history rings. For a
|
||||
/// SWA layer (`swa`) only the last `min(seq_len, swa_win)` KV positions are
|
||||
/// stored (the causal window): attention at any future pos >= seq_len reads
|
||||
/// [pos-swa_win+1..pos] ⊆ [kv_start..pos], so the discarded older KV is never
|
||||
/// observed (proofs/prefix_cache.lean swa_window_restore_equiv). Full-attn
|
||||
/// layers attend globally and keep the whole `[0, seq_len)` prefix.
|
||||
pub fn snapshot(&self, d: &Dims, seq_len: usize, swa: bool) -> Result<LayerSnapshot, String> {
|
||||
let es = if f16_kv() { 2 } else { 4 };
|
||||
let row = seq_len * d.hd * es;
|
||||
let win = if swa { seq_len.min(d.swa_win.max(0) as usize) } else { seq_len };
|
||||
let kv_start = seq_len - win;
|
||||
let row = win * d.hd * es;
|
||||
let src_off = kv_start * 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)?;
|
||||
b.copy2d_at(0, src, src_off, 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<_>, _>>()?;
|
||||
@@ -299,7 +310,7 @@ impl LayerState {
|
||||
let b = DeviceBuf::alloc(src.bytes)?; b.copy_from(src, src.bytes)?; Ok(b)
|
||||
};
|
||||
Ok(LayerSnapshot {
|
||||
seq_len, k_cache, v_cache,
|
||||
seq_len, kv_start, 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])?],
|
||||
@@ -307,17 +318,21 @@ impl LayerState {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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].
|
||||
/// Restore the KV prefix `[kv_start, seq_len)` + history into `self` (whose
|
||||
/// max_seq must be >= snap.seq_len). For SWA snapshots kv_start > 0: positions
|
||||
/// below it are left untouched (never read by the causal window); the suffix
|
||||
/// prefill fills `[seq_len, pos)`. Attention at pos >= seq_len reads only the
|
||||
/// restored window + suffix, so this is observationally exact (restore_equiv).
|
||||
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;
|
||||
let win = snap.seq_len - snap.kv_start;
|
||||
let row = win * d.hd * es;
|
||||
let dst_off = snap.kv_start * 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)?;
|
||||
dst.copy2d_at(dst_off, src, 0, 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)?;
|
||||
dst.copy2d_at(dst_off, src, 0, 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)?;
|
||||
@@ -327,6 +342,20 @@ impl LayerState {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Zero the ShortConv history rings (async device memset). Used when reusing
|
||||
/// persistent states for a COLD request (no prefix restore): the KV prefix is
|
||||
/// overwritten by prefill before any causal read, but the hist rings seed the
|
||||
/// first 3 shortconv steps and must start empty for a fresh conversation.
|
||||
pub fn reset_history(&mut self) -> Result<(), String> {
|
||||
for i in 0..3 {
|
||||
self.hist_k[i].zero_async()?;
|
||||
self.hist_v[i].zero_async()?;
|
||||
self.hist_a[i].zero_async()?;
|
||||
self.hist_m[i].zero_async()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// KV cache dtype switch. The CPU-oracle parity baseline (and the ld packer
|
||||
|
||||
Reference in new issue
Block a user