diff --git a/crates/vetta-infer-gw/src/serve.rs b/crates/vetta-infer-gw/src/serve.rs index fc15c7a..0642aa5 100644 --- a/crates/vetta-infer-gw/src/serve.rs +++ b/crates/vetta-infer-gw/src/serve.rs @@ -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], d: &Dims) -> Result<(), String> { let seq = tokens.len(); if seq == 0 { return Ok(()); } - let layers: Vec> = states.iter() - .map(|st| st.as_ref().map(|s| s.snapshot(d, seq)).transpose()) + let layers: Vec> = states.iter().enumerate() + .map(|(ip, st)| st.as_ref().map(|s| s.snapshot(d, seq, is_swa(ip))).transpose()) .collect::>()?; self.tick += 1; let lru = self.tick; @@ -157,6 +164,11 @@ pub struct InklingEngine { eos: i32, cap: f32, prefix: RefCell, + /// 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>>, + states_cap: Cell, } 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>, 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}"); } diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 2e892e1..61c70fc 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -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. diff --git a/crates/vetta-infer-ld/src/layer.rs b/crates/vetta-infer-ld/src/layer.rs index 90d32e1..0e611ad 100644 --- a/crates/vetta-infer-ld/src/layer.rs +++ b/crates/vetta-infer-ld/src/layer.rs @@ -277,20 +277,31 @@ pub fn new_state(d: &Dims, max_seq: usize, n_passes: usize) -> Result, pub v_cache: Vec, 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 { + /// 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 { 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 { 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::, _>>()?; @@ -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 diff --git a/proofs/prefix_cache.lean b/proofs/prefix_cache.lean index 1fe304c..683b3c4 100644 --- a/proofs/prefix_cache.lean +++ b/proofs/prefix_cache.lean @@ -255,4 +255,55 @@ theorem poolInsert_nodup (cap : Nat) (pool : List Nat) (seq : Nat) pinned. The engine relies on this combinatorial fact (cap ≥ 3) when evicting; `poolInsert_preserves_pinned` proves the I3 invariant that anchors survive. -/ +/-! ## Part D: SWA-window checkpoint observational equivalence + +A SWA layer attends only to the causal window `[winStart w p, p]` at position +`p` (kernel `k_flash_swa_gqa_*`: `k_start = p - w + 1` when `p ≥ w`, else 0). +So a checkpoint at `seq_len = n` need only store KV from `kvStart w n = n - min n w` +(the last `min n w` positions); the older KV is never read again. Restoring that +window and prefilling the suffix is observationally exact for every future +position `p ≥ n`. Full-attention layers keep the whole prefix (`kvStart = 0`). +This is the memory refinement that shrinks SWA checkpoints (~40 of 48 pools). -/ + +/-- First KV position a SWA checkpoint at `n` must retain (window `w`). -/ +def kvStart (w n : Nat) : Nat := n - min n w + +/-- First KV position the SWA attention reads at position `p` (window `w`). -/ +def winStart (w p : Nat) : Nat := if p ≥ w then p - w + 1 else 0 + +/-- CONTAINMENT: for any future position `p ≥ n`, the attention window starts at + or after the checkpoint's retained start, so the window is fully covered by + `[kvStart w n, p]` (restored window `[kvStart, n)` + suffix `[n, p]`). -/ +theorem kvStart_le_winStart (w n p : Nat) (h : n ≤ p) : + kvStart w n ≤ winStart w p := by + unfold kvStart winStart + split + · omega + · have hn : n ≤ w := by omega + have : min n w = n := Nat.min_eq_left hn + omega + +/-- Observational equivalence of windowed restore. `read kv p` is the SWA attention + output, which by the kernel contract depends only on KV in `[winStart w p, p]` + (`hwin`). If the restored+suffix cache `kv'` agrees with the cold cache `kv` on + `[kvStart w n, p]` (`hagree` — restored window + causal suffix), then the read + at `p` is identical. The containment lemma lifts the agreement to the window. -/ +theorem swa_window_restore_equiv {V R : Type} (w n p : Nat) + (read : (Nat → V) → Nat → R) + (hwin : ∀ kv kv' : Nat → V, + (∀ i, winStart w p ≤ i → i ≤ p → kv i = kv' i) → read kv p = read kv' p) + (kv kv' : Nat → V) (hn : n ≤ p) + (hagree : ∀ i, kvStart w n ≤ i → i ≤ p → kv i = kv' i) : + read kv p = read kv' p := by + apply hwin + intro i hi1 hi2 + exact hagree i (Nat.le_trans (kvStart_le_winStart w n p hn) hi1) hi2 + +/-- A full-attention checkpoint retains everything: its window covers the whole + prefix (`n ≤ w`), so `kvStart w n = 0` and no KV is discarded. -/ +theorem kvStart_full (n w : Nat) (h : n ≤ w) : kvStart w n = 0 := by + unfold kvStart + have : min n w = n := Nat.min_eq_left h + omega + end VettaPrefixCache \ No newline at end of file