[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:
adm committed 2026-12-02 02:52:32 +01:00
1 parent a6ca73105c
commit 47f8b52070
4 files changed
+159 -42

No files matched your search

+51 -30
View File
@@ -16,7 +16,7 @@
//! is callable from an integration test without spawning the binary. //! is callable from an integration test without spawning the binary.
use std::io::{self, BufRead, Write}; use std::io::{self, BufRead, Write};
use std::cell::RefCell; use std::cell::{Cell, RefCell};
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc}; use std::sync::{mpsc, Arc};
use std::time::Instant; 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_abi::serve::{parse_serve_line, ParsedGen, ServeCommand};
use vetta_infer_hip::DeviceBuf; use vetta_infer_hip::DeviceBuf;
use vetta_infer_ld::inkling::parse_config; 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 vetta_infer_ld::SafetensorsArchive;
use crate::session::ServeSession; use crate::session::ServeSession;
@@ -109,9 +109,16 @@ impl PrefixCache {
} }
for (ip, snap) in ck.layers.iter().enumerate() { for (ip, snap) in ck.layers.iter().enumerate() {
if let Some(s) = snap { if let Some(s) = snap {
let mut st = new_state(d, max_seq, s.k_cache.len())?; // Reuse the persistent state when it is already sized for this
st.restore(d, s)?; // request (same cap + pass count); restore overwrites its KV
states[ip] = Some(st); // 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> { fn save(&mut self, tokens: &[i32], states: &[Option<LayerState>], d: &Dims) -> Result<(), String> {
let seq = tokens.len(); let seq = tokens.len();
if seq == 0 { return Ok(()); } if seq == 0 { return Ok(()); }
let layers: Vec<Option<LayerSnapshot>> = states.iter() let layers: Vec<Option<LayerSnapshot>> = states.iter().enumerate()
.map(|st| st.as_ref().map(|s| s.snapshot(d, seq)).transpose()) .map(|(ip, st)| st.as_ref().map(|s| s.snapshot(d, seq, is_swa(ip))).transpose())
.collect::<Result<_, _>>()?; .collect::<Result<_, _>>()?;
self.tick += 1; self.tick += 1;
let lru = self.tick; let lru = self.tick;
@@ -157,6 +164,11 @@ pub struct InklingEngine {
eos: i32, eos: i32,
cap: f32, cap: f32,
prefix: RefCell<PrefixCache>, 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 { impl InklingEngine {
@@ -207,6 +219,8 @@ impl InklingEngine {
eos: cfg.eos_token_id as i32, eos: cfg.eos_token_id as i32,
cap: t.final_logit_softcapping as f32, cap: t.final_logit_softcapping as f32,
prefix: RefCell::new(PrefixCache::new()), prefix: RefCell::new(PrefixCache::new()),
states: RefCell::new(Vec::new()),
states_cap: Cell::new(0),
}) })
} }
@@ -214,11 +228,6 @@ impl InklingEngine {
self.vocab 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( fn forward(
&self, &self,
token: i32, token: i32,
@@ -282,13 +291,15 @@ pub fn serve_gen(
emit_all(emit, sess.on_error("prompt + max_new exceeds context window")); emit_all(emit, sess.on_error("prompt + max_new exceeds context window"));
return; return;
} }
let mut states = match eng.fresh_states(max_seq) { // Persistent KV states: size once to a 4096-bucket cap >= max_seq and reuse
Ok(s) => s, // across requests (no per-request ~3.75 GB alloc/free sawtooth). Grow only when
Err(e) => { // a request crosses the bucket. `cap` is the KV stride passed to the forwards.
emit_all(emit, sess.on_error(&e)); let cap = max_seq.next_multiple_of(4096).min(MAX_CONTEXT);
return; 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 // Prefix checkpoint reuse (proofs/prefix_cache.lean restore_equiv): restore
// the longest cached strict prefix of this prompt and prefill only the NEW // 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() { if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() {
let matched = eng.prefix.borrow().best_match(&g.ids); let matched = eng.prefix.borrow().best_match(&g.ids);
if let Some((idx, _l)) = matched { 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, Ok(n) => start = n,
Err(_) => { Err(_) => {
// Incomplete/failed restore: fall back to a clean cold prefill. // Incomplete/failed restore: fall back to a clean cold prefill.
states = match eng.fresh_states(max_seq) { *states = (0..eng.n_layers).map(|_| None).collect();
Ok(s) => s,
Err(e) => { emit_all(emit, sess.on_error(&e)); return; }
};
} }
} }
} }
} }
// 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() { if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] prompt_len={n_prompt} restored={start}"); eprintln!("[prefix] prompt_len={n_prompt} restored={start}");
if start == 0 { if start == 0 {
@@ -357,9 +378,9 @@ pub fn serve_gen(
} }
let toks = &suffix[done..done + take]; let toks = &suffix[done..done + take];
let lg = if take == 1 { let lg = if take == 1 {
eng.forward(toks[0], pos, max_seq, &mut states) eng.forward(toks[0], pos, cap, &mut states[..])
} else { } else {
eng.forward_batched(toks, pos, max_seq, &mut states) eng.forward_batched(toks, pos, cap, &mut states[..])
}; };
match lg { match lg {
Ok(l) => logits = Some(l), Ok(l) => logits = Some(l),
@@ -379,7 +400,7 @@ pub fn serve_gen(
// prefix; grid entries are protected from eviction (is_grid) and refreshed // prefix; grid entries are protected from eviction (is_grid) and refreshed
// on restore (lru), so turn 3+ keeps advancing instead of falling to 1024. // 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 { 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() { if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] grid save seq={pos}"); 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 // stable prefix and prefill only the new dialogue suffix. Mirrors strata
// --auto-ckpt's prompt-boundary save (proofs/prefix_cache.lean restore_equiv). // --auto-ckpt's prompt-boundary save (proofs/prefix_cache.lean restore_equiv).
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 { 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() { if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] prompt-boundary save seq={pos}"); eprintln!("[prefix] prompt-boundary save seq={pos}");
} }
@@ -480,7 +501,7 @@ pub fn serve_gen(
finish = "length"; finish = "length";
break; break;
} }
match eng.forward(rep.token, pos, max_seq, &mut states) { match eng.forward(rep.token, pos, cap, &mut states[..]) {
Ok(l) => logits = l, Ok(l) => logits = l,
Err(e) => { Err(e) => {
emit_all(emit, sess.on_error(&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 // counts tokens actually folded into `states` (history[..pos]); a sampled token
// not forwarded (EOS / last length step) is excluded, keeping the ckpt valid. // not forwarded (EOS / last length step) is excluded, keeping the ckpt valid.
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 { 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() { if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] full-sequence save seq={pos}"); eprintln!("[prefix] full-sequence save seq={pos}");
} }
+16
View File
@@ -329,6 +329,22 @@ impl DeviceBuf {
if rc != 0 { return Err("d2d copy2d failed".into()); } if rc != 0 { return Err("d2d copy2d failed".into()); }
Ok(()) 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): /// Async zero-fill of the whole buffer on the default stream (hipMemsetAsync):
/// ordered before later kernels with NO blocking host round-trip. Replaces a /// 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. /// sync `h2d(&vec![0; n])` that would drain the GPU queue every layer visit.
+41 -12
View File
@@ -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). /// it and prefilling the suffix is exact (proofs/prefix_cache.lean restore_equiv).
pub struct LayerSnapshot { pub struct LayerSnapshot {
pub seq_len: usize, 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 k_cache: Vec<DeviceBuf>, pub v_cache: Vec<DeviceBuf>,
pub hist_k: [DeviceBuf; 3], pub hist_v: [DeviceBuf; 3], pub hist_k: [DeviceBuf; 3], pub hist_v: [DeviceBuf; 3],
pub hist_a: [DeviceBuf; 3], pub hist_m: [DeviceBuf; 3], pub hist_a: [DeviceBuf; 3], pub hist_m: [DeviceBuf; 3],
} }
impl LayerState { impl LayerState {
/// Snapshot the KV prefix `[0, seq_len)` (pitched copy out of the /// Snapshot the KV prefix plus the current ShortConv history rings. For a
/// `[n_kv, max_seq, hd]` cache) plus the current ShortConv history rings. /// SWA layer (`swa`) only the last `min(seq_len, swa_win)` KV positions are
pub fn snapshot(&self, d: &Dims, seq_len: usize) -> Result<LayerSnapshot, String> { /// 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 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 snap_kv = |src: &DeviceBuf| -> Result<DeviceBuf, String> {
let b = DeviceBuf::alloc_unpooled(d.n_kv * row)?; 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) Ok(b)
}; };
let k_cache = self.k_cache.iter().map(snap_kv).collect::<Result<Vec<_>, _>>()?; 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) let b = DeviceBuf::alloc(src.bytes)?; b.copy_from(src, src.bytes)?; Ok(b)
}; };
Ok(LayerSnapshot { 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_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_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_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 /// Restore the KV prefix `[kv_start, seq_len)` + history into `self` (whose
/// max_seq must be >= snap.seq_len). Positions >= seq_len stay zero for the /// max_seq must be >= snap.seq_len). For SWA snapshots kv_start > 0: positions
/// suffix prefill to fill; attention at pos >= seq_len reads only [0, pos]. /// 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> { pub fn restore(&mut self, d: &Dims, snap: &LayerSnapshot) -> Result<(), String> {
let es = if f16_kv() { 2 } else { 4 }; 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) { 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) { 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 { for i in 0..3 {
self.hist_k[i].copy_from(&snap.hist_k[i], snap.hist_k[i].bytes)?; self.hist_k[i].copy_from(&snap.hist_k[i], snap.hist_k[i].bytes)?;
@@ -327,6 +342,20 @@ impl LayerState {
} }
Ok(()) 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 /// KV cache dtype switch. The CPU-oracle parity baseline (and the ld packer
+51
View File
@@ -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; pinned. The engine relies on this combinatorial fact (cap ≥ 3) when evicting;
`poolInsert_preserves_pinned` proves the I3 invariant that anchors survive. -/ `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 end VettaPrefixCache