Skip to main content

cortiq_engine/
kv_cache.rs

1//! KV cache — per-layer, head-major storage.
2//!
3//! Layout: one contiguous `Vec<f32>` per KV head (`[pos × head_dim]`),
4//! so per-head attention reads a straight slice — no per-head gather
5//! copies per token. Dead GQA groups (all Q heads masked) store
6//! nothing at all: masked heads cost neither FLOPs nor memory.
7
8/// KV storage mode. `CMF_KV=q8` enables the q8_2f cache: an int8 row per
9/// (position, head) + an f32 scale per row + a per-channel field 𝒲×θ,
10/// frozen after WARMUP positions with retroactive requantization
11/// (D4: "KV-quant 2f"). Memory ×~3.7 smaller than f32.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum KvMode {
14    F32,
15    /// Quantized components: (K, V) — sensitivity diagnostics.
16    Q8 { k: bool, v: bool },
17}
18
19impl KvMode {
20    pub fn from_env() -> Self {
21        match std::env::var("CMF_KV").as_deref() {
22            Ok("q8") | Ok("q8_2f") => KvMode::Q8 { k: true, v: true },
23            Ok("q8k") => KvMode::Q8 { k: true, v: false },
24            Ok("q8v") => KvMode::Q8 { k: false, v: true },
25            _ => KvMode::F32,
26        }
27    }
28
29    fn quant_k(self) -> bool {
30        matches!(self, KvMode::Q8 { k: true, .. })
31    }
32
33    fn quant_v(self) -> bool {
34        matches!(self, KvMode::Q8 { v: true, .. })
35    }
36}
37
38/// Positions before freezing the per-channel field (2f): before — col ≡ 1,
39/// after — col = RMS over channels of the stored rows, old rows are requantized.
40const KV_COL_WARMUP: usize = 64;
41
42/// K-rows are quantized in groups of 32 channels (scale per group):
43/// attention logits are sensitive to the dot-product error, per-group scales
44/// localize it along RoPE bands (35B: +4.6% PPL with a per-row scale
45/// → target <1% with a per-group one). V — per-row scale (measured +0.56%).
46const KV_K_GROUP: usize = 32;
47
48/// Per-layer O(1) Nyström attention state (runtime `attn_type`
49/// override — spec §7 presence-driven pattern, no format change).
50///
51/// Collecting: the prompt pass still runs EXACT cache attention (the
52/// prefill outputs feed the residual stream, so they cannot be
53/// deferred) while the per-position rotated queries are buffered;
54/// `o1_seal()` then freezes landmarks + M from the full prompt, replays
55/// it into per-KV-group streaming states, and DROPS the full KV.
56/// Sealed: decode replaces cache attention with
57/// `NystromState::step_group()`.
58#[derive(Debug, Clone)]
59pub enum O1State {
60    Collecting {
61        m: usize,
62        w: usize,
63        sink: usize,
64        rect: crate::nystrom::O1Rect,
65        /// Rotated post-norm queries, `[pos × num_heads × head_dim]`.
66        q_buf: Vec<f32>,
67    },
68    /// One state per KV GROUP, each holding its group's Q heads. The
69    /// exact window / sinks / K̃ are stored once per group (every Q head
70    /// of the group reads the same k/v rows); only the far field, Q̃ and
71    /// M — the query-dependent pieces — stay per Q head. See
72    /// `NystromState` for which piece is which and why.
73    Sealed { groups: Vec<crate::nystrom::NystromState> },
74}
75
76/// KV cache for a single layer, head-major.
77#[derive(Debug, Clone)]
78pub struct LayerKvCache {
79    pub mode: KvMode,
80    /// Per-KV-head keys: `k[h]` is `[seq_len × head_dim]` (empty if head is dead).
81    k: Vec<Vec<f32>>,
82    /// Per-KV-head values, same layout.
83    v: Vec<Vec<f32>>,
84    /// q8 storage (mode == Q8_2F): int8 rows + f32 scale per row.
85    kq: Vec<Vec<i8>>,
86    ks: Vec<Vec<f32>>,
87    vq: Vec<Vec<i8>>,
88    vs: Vec<Vec<f32>>,
89    /// Per-channel fields 𝒲×θ per head [head_dim]; empty until frozen.
90    kcol: Vec<Vec<f32>>,
91    vcol: Vec<Vec<f32>>,
92    /// Accumulated attention mass per stored position (Born rule:
93    /// importance of a position = how much probability mass reads it).
94    imp: Vec<f32>,
95    /// Positions appended so far (grows once per token, dead heads included).
96    pub seq_len: usize,
97    pub num_kv_heads: usize,
98    pub head_dim: usize,
99    /// Linear-core condensate S (vmf_phase), f64; empty on full layers.
100    pub linear_state: Vec<f64>,
101    /// Tentative lane-2 state during speculative verify.
102    pub linear_scratch: Vec<f64>,
103    /// O(1) Nyström override (None = plain cache attention).
104    pub o1: Option<O1State>,
105}
106
107impl LayerKvCache {
108    pub fn new(num_kv_heads: usize, head_dim: usize) -> Self {
109        Self {
110            mode: KvMode::from_env(),
111            k: vec![Vec::new(); num_kv_heads],
112            v: vec![Vec::new(); num_kv_heads],
113            kq: vec![Vec::new(); num_kv_heads],
114            ks: vec![Vec::new(); num_kv_heads],
115            vq: vec![Vec::new(); num_kv_heads],
116            vs: vec![Vec::new(); num_kv_heads],
117            kcol: vec![Vec::new(); num_kv_heads],
118            vcol: vec![Vec::new(); num_kv_heads],
119            imp: Vec::new(),
120            seq_len: 0,
121            num_kv_heads,
122            head_dim,
123            linear_state: Vec::new(),
124            linear_scratch: Vec::new(),
125            o1: None,
126        }
127    }
128
129    // ── O(1) Nyström override ──
130
131    /// Arm query collection for a fresh prompt pass (a cleared cache).
132    pub fn o1_begin(&mut self, m: usize, w: usize, sink: usize, rect: crate::nystrom::O1Rect) {
133        self.o1 = Some(O1State::Collecting { m, w, sink, rect, q_buf: Vec::new() });
134    }
135
136    /// Record one position's rotated queries (`[num_heads × head_dim]`)
137    /// during the exact prompt pass. No-op unless collecting — the hook
138    /// sits inside qwen_attention so every prefill flavor (sequential,
139    /// batched) feeds the same trace.
140    pub fn o1_push_q(&mut self, q_all: &[f32]) {
141        if let Some(O1State::Collecting { q_buf, .. }) = &mut self.o1 {
142            q_buf.extend_from_slice(q_all);
143        }
144    }
145
146    pub fn o1_sealed(&self) -> bool {
147        matches!(self.o1, Some(O1State::Sealed { .. }))
148    }
149
150    /// Freeze the prompt into per-KV-group Nyström states and drop this
151    /// layer's full KV. Returns false (layer stays exact, KV kept) when
152    /// the preconditions fail: the seal needs f32 KV rows (`CMF_KV=q8`
153    /// stores int8), every group densely stored, a full q trace, and a
154    /// GQA fan-out that actually divides.
155    pub fn o1_seal(&mut self, num_heads: usize) -> bool {
156        // Idempotent: sealing a sealed (or plain) layer must not
157        // disturb its state — check before take().
158        if !matches!(self.o1, Some(O1State::Collecting { .. })) {
159            return self.o1_sealed();
160        }
161        let Some(O1State::Collecting { m, w, sink, rect, q_buf }) = self.o1.take() else {
162            unreachable!("checked above");
163        };
164        let (hd, t) = (self.head_dim, self.seq_len);
165        let nkv = self.num_kv_heads.max(1);
166        let hpk = num_heads / nkv;
167        let ok = t > 0
168            && self.mode == KvMode::F32
169            && q_buf.len() == t * num_heads * hd
170            && hpk * nkv == num_heads
171            && (0..self.num_kv_heads).all(|g| self.head_len(g) == t);
172        if !ok {
173            tracing::warn!(
174                "o1: cannot seal (needs f32 KV mode, dense heads, full query \
175                 trace, num_heads divisible by num_kv_heads) — layer keeps \
176                 exact attention"
177            );
178            return false;
179        }
180        let mut groups = Vec::with_capacity(self.num_kv_heads);
181        // Query trace is position-major; the state wants each head's
182        // queries contiguous, so transpose one group at a time.
183        let mut qh = vec![0.0f32; hpk * t * hd];
184        for g in 0..self.num_kv_heads {
185            for hh in 0..hpk {
186                let h = g * hpk + hh;
187                for p in 0..t {
188                    let src = (p * num_heads + h) * hd;
189                    let dst = (hh * t + p) * hd;
190                    qh[dst..dst + hd].copy_from_slice(&q_buf[src..src + hd]);
191                }
192            }
193            let qs: Vec<&[f32]> = (0..hpk).map(|hh| &qh[hh * t * hd..(hh + 1) * t * hd]).collect();
194            let mut st = crate::nystrom::NystromState::new_group(m, w, sink, hpk).with_rect(rect);
195            st.prefill_group(&qs, &self.k[g], &self.v[g], t, hd, hd);
196            groups.push(st);
197        }
198        // The states now carry everything decode needs — release the
199        // O(context) storage (this is the memory claim, not a cosmetic).
200        for h in 0..self.num_kv_heads {
201            self.k[h] = Vec::new();
202            self.v[h] = Vec::new();
203        }
204        self.imp = Vec::new();
205        self.o1 = Some(O1State::Sealed { groups });
206        true
207    }
208
209    /// One decode step on a sealed layer: per KV group, insert the
210    /// group's fresh (k, v) ONCE and read every Q head's attention
211    /// output. Returns `[num_heads × head_dim]`. Head h belongs to group
212    /// h/hpk, so a group's Q heads are contiguous in `q_all`/`out` —
213    /// same math as the shared KV row the exact path appends once.
214    pub fn o1_step(
215        &mut self,
216        q_all: &[f32],
217        k_new: &[f32],
218        v_new: &[f32],
219        num_heads: usize,
220    ) -> Vec<f32> {
221        let hd = self.head_dim;
222        let hpk = num_heads / self.num_kv_heads.max(1);
223        let mut out = vec![0.0f32; num_heads * hd];
224        let Some(O1State::Sealed { groups }) = &mut self.o1 else {
225            debug_assert!(false, "o1_step on an unsealed layer");
226            return out;
227        };
228        for (g, st) in groups.iter_mut().enumerate() {
229            let (lo, hi) = (g * hpk * hd, (g + 1) * hpk * hd);
230            st.step_group(
231                &q_all[lo..hi],
232                &k_new[g * hd..(g + 1) * hd],
233                &v_new[g * hd..(g + 1) * hd],
234                &mut out[lo..hi],
235            );
236        }
237        // Track the true context depth for the honest memory/seq report
238        // (nothing is stored per position — the state is O(1)).
239        self.seq_len += 1;
240        out
241    }
242
243    /// Bytes held by the O(1) override (query trace while collecting,
244    /// per-KV-group states once sealed).
245    pub fn o1_memory_bytes(&self) -> usize {
246        match &self.o1 {
247            Some(O1State::Collecting { q_buf, .. }) => {
248                q_buf.len() * std::mem::size_of::<f32>()
249            }
250            Some(O1State::Sealed { groups }) => {
251                groups.iter().map(|s| s.memory_bytes()).sum()
252            }
253            None => 0,
254        }
255    }
256
257    /// Quantize one row against the per-channel field (empty col = 1);
258    /// `group` — elements per scale (the whole row or KV_K_GROUP).
259    fn quant_row(row: &[f32], col: &[f32], q: &mut Vec<i8>, sc: &mut Vec<f32>,
260                 group: usize) {
261        let mut resid = vec![0.0f32; row.len()];
262        for (d, &x) in row.iter().enumerate() {
263            resid[d] = if col.is_empty() { x } else { x / col[d] };
264        }
265        for g0 in (0..row.len()).step_by(group) {
266            let g1 = (g0 + group).min(row.len());
267            let mut absmax = 0.0f32;
268            for &r in &resid[g0..g1] {
269                absmax = absmax.max(r.abs());
270            }
271            let s = (absmax / 127.0).max(1e-12);
272            sc.push(s);
273            for &r in &resid[g0..g1] {
274                q.push((r / s).round().clamp(-127.0, 127.0) as i8);
275            }
276        }
277    }
278
279    /// Freeze the 2f field: col = RMS of channels over stored rows, old
280    /// rows are requantized against the new field (once per conversation).
281    fn freeze_cols(&mut self) {
282        let hd = self.head_dim;
283        let ngk = hd.div_ceil(KV_K_GROUP);
284        for h in 0..self.num_kv_heads {
285            for (qv, sv, colv, group) in [
286                (&mut self.kq[h], &mut self.ks[h], &mut self.kcol[h], KV_K_GROUP),
287                (&mut self.vq[h], &mut self.vs[h], &mut self.vcol[h], hd),
288            ] {
289                let spp = if group == hd { 1 } else { ngk }; // scales per position
290                let n = sv.len() / spp;
291                if n == 0 {
292                    continue;
293                }
294                // Dequantize to f32, RMS over channels, requantize.
295                let mut rows = vec![0.0f32; n * hd];
296                for p in 0..n {
297                    for d in 0..hd {
298                        rows[p * hd + d] =
299                            qv[p * hd + d] as f32 * sv[p * spp + d / group];
300                    }
301                }
302                let mut col = vec![0.0f32; hd];
303                for p in 0..n {
304                    for d in 0..hd {
305                        col[d] += rows[p * hd + d] * rows[p * hd + d];
306                    }
307                }
308                for c in col.iter_mut() {
309                    *c = (*c / n as f32).sqrt().max(1e-6);
310                }
311                qv.clear();
312                sv.clear();
313                for p in 0..n {
314                    Self::quant_row(&rows[p * hd..(p + 1) * hd], &col, qv, sv, group);
315                }
316                *colv = col;
317            }
318        }
319    }
320
321    /// Append K/V for one position. `k_new`/`v_new` are
322    /// `[num_kv_heads × head_dim]`; heads with `alive[h] == false` are
323    /// skipped (their slices stay empty).
324    pub fn append(&mut self, k_new: &[f32], v_new: &[f32], alive: &[bool]) {
325        debug_assert_eq!(k_new.len(), self.num_kv_heads * self.head_dim);
326        debug_assert_eq!(v_new.len(), self.num_kv_heads * self.head_dim);
327        // Freeze the 2f field AT THE START of append: only rows that
328        // survived verify are visible (a rejected lane-2 draft does not
329        // pollute the field — found in review), and the threshold uses >=
330        // rather than strict equality (in small windows eviction may
331        // oscillate across 64).
332        if matches!(self.mode, KvMode::Q8 { .. })
333            && self.seq_len >= KV_COL_WARMUP
334            && self.kcol.iter().all(Vec::is_empty)
335            && self.vcol.iter().all(Vec::is_empty)
336        {
337            self.freeze_cols();
338        }
339        for h in 0..self.num_kv_heads {
340            if !alive.get(h).copied().unwrap_or(true) {
341                continue;
342            }
343            let s = h * self.head_dim;
344            if self.mode.quant_k() {
345                Self::quant_row(&k_new[s..s + self.head_dim],
346                                &self.kcol[h], &mut self.kq[h], &mut self.ks[h],
347                                KV_K_GROUP);
348            } else {
349                self.k[h].extend_from_slice(&k_new[s..s + self.head_dim]);
350            }
351            if self.mode.quant_v() {
352                Self::quant_row(&v_new[s..s + self.head_dim],
353                                &self.vcol[h], &mut self.vq[h], &mut self.vs[h],
354                                self.head_dim);
355            } else {
356                self.v[h].extend_from_slice(&v_new[s..s + self.head_dim]);
357            }
358        }
359        self.imp.push(0.0);
360        self.seq_len += 1;
361    }
362
363    /// Per-head attention over its own storage: the f32 branch is
364    /// bit-for-bit equal to attention_head() over slices; the q8 branch
365    /// computes score = s_k·⟨q⊙col_k, k_q⟩ and the weighted sum of V in i8
366    /// with f32 accumulation. Returns (output [head_dim], probs [stored]).
367    pub fn attend(&self, q: &[f32], kv_head: usize) -> (Vec<f32>, Vec<f32>) {
368        let hd = self.head_dim;
369        if self.mode == KvMode::F32 {
370            let stored = self.k[kv_head].len() / hd;
371            return crate::attention::attention_head(
372                q, &self.k[kv_head], &self.v[kv_head], hd, stored);
373        }
374        let stored = self.head_len(kv_head);
375        let scale = 1.0 / (hd as f32).sqrt();
376        let mut scores = vec![0.0f32; stored];
377        if self.mode.quant_k() {
378            let (kq, ks) = (&self.kq[kv_head], &self.ks[kv_head]);
379            // q ⊙ col_k — once per call.
380            let kcol = &self.kcol[kv_head];
381            let mut qc = vec![0.0f32; hd];
382            for d in 0..hd {
383                qc[d] = if kcol.is_empty() { q[d] } else { q[d] * kcol[d] };
384            }
385            let ng = hd.div_ceil(KV_K_GROUP);
386            for p in 0..stored {
387                let row = &kq[p * hd..(p + 1) * hd];
388                // SAFETY: i8 and u8 share layout; dot_i8_f32 reads the
389                // bytes back as i8.
390                let row_u8 = unsafe {
391                    std::slice::from_raw_parts(row.as_ptr() as *const u8, row.len())
392                };
393                let mut dot = 0.0f32;
394                for g in 0..ng {
395                    let g0 = g * KV_K_GROUP;
396                    let g1 = (g0 + KV_K_GROUP).min(hd);
397                    dot += crate::qtensor::dot_i8_f32(&row_u8[g0..g1], &qc[g0..g1])
398                        * ks[p * ng + g];
399                }
400                scores[p] = dot * scale;
401            }
402        } else {
403            let k = &self.k[kv_head];
404            for p in 0..stored {
405                let row = &k[p * hd..(p + 1) * hd];
406                scores[p] = crate::attention::dot_f32(q, row) * scale;
407            }
408        }
409        let max_score = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
410        let mut sum = 0.0f32;
411        for s in scores.iter_mut() {
412            *s = (*s - max_score).exp();
413            sum += *s;
414        }
415        if sum > 0.0 {
416            for s in scores.iter_mut() {
417                *s /= sum;
418            }
419        }
420        let mut acc = vec![0.0f32; hd];
421        if self.mode.quant_v() {
422            let (vq, vs) = (&self.vq[kv_head], &self.vs[kv_head]);
423            for p in 0..stored {
424                let w = scores[p] * vs[p];
425                if w.abs() < 1e-12 {
426                    continue;
427                }
428                crate::qtensor::axpy_i8_f32(&mut acc, &vq[p * hd..(p + 1) * hd], w);
429            }
430            let vcol = &self.vcol[kv_head];
431            if !vcol.is_empty() {
432                for d in 0..hd {
433                    acc[d] *= vcol[d];
434                }
435            }
436        } else {
437            let v = &self.v[kv_head];
438            for p in 0..stored {
439                let w = scores[p];
440                if w.abs() < 1e-12 {
441                    continue;
442                }
443                crate::attention::axpy_f32(&mut acc, &v[p * hd..(p + 1) * hd], w);
444            }
445        }
446        (acc, scores)
447    }
448
449    /// Roll back the last `n_drop` positions (speculative-decode reject).
450    pub fn truncate_last(&mut self, n_drop: usize) {
451        let d = n_drop.min(self.seq_len);
452        for h in 0..self.num_kv_heads {
453            let keep = self.k[h].len().saturating_sub(d * self.head_dim);
454            self.k[h].truncate(keep);
455            self.v[h].truncate(keep);
456            let ngk = self.head_dim.div_ceil(KV_K_GROUP);
457            let keep_q = self.kq[h].len().saturating_sub(d * self.head_dim);
458            self.kq[h].truncate(keep_q);
459            let keep_vq = self.vq[h].len().saturating_sub(d * self.head_dim);
460            self.vq[h].truncate(keep_vq);
461            let keep_ks = self.ks[h].len().saturating_sub(d * ngk);
462            self.ks[h].truncate(keep_ks);
463            let keep_vs = self.vs[h].len().saturating_sub(d);
464            self.vs[h].truncate(keep_vs);
465        }
466        self.imp.truncate(self.imp.len().saturating_sub(d));
467        self.seq_len -= d;
468    }
469
470    /// Accumulate attention mass per stored position (summed over heads).
471    pub fn accumulate_imp(&mut self, probs: &[f32]) {
472        for (dst, &p) in self.imp.iter_mut().zip(probs) {
473            *dst += p;
474        }
475    }
476
477    /// Contiguous keys of one head: `[stored_len × head_dim]`.
478    pub fn head_keys(&self, kv_head: usize) -> &[f32] {
479        &self.k[kv_head]
480    }
481
482    pub fn head_values(&self, kv_head: usize) -> &[f32] {
483        &self.v[kv_head]
484    }
485
486    /// Number of positions actually stored for a head (0 for dead heads).
487    pub fn head_len(&self, kv_head: usize) -> usize {
488        let ng = self.head_dim.div_ceil(KV_K_GROUP);
489        (self.k[kv_head].len() / self.head_dim)
490            .max(self.ks[kv_head].len() / ng)
491            .max(self.vs[kv_head].len())
492    }
493
494    /// Clear cache (e.g. on new conversation or task switch).
495    pub fn clear(&mut self) {
496        for h in 0..self.num_kv_heads {
497            self.k[h].clear();
498            self.v[h].clear();
499            self.kq[h].clear();
500            self.ks[h].clear();
501            self.vq[h].clear();
502            self.vs[h].clear();
503            self.kcol[h].clear();
504            self.vcol[h].clear();
505        }
506        self.imp.clear();
507        self.linear_state.clear();
508        self.linear_scratch.clear();
509        // Fresh conversation → the pipeline re-arms collection if the
510        // layer is o1-flagged (landmarks are per-prompt, never reused).
511        self.o1 = None;
512        self.seq_len = 0;
513    }
514
515    /// Memory usage in bytes.
516    pub fn memory_bytes(&self) -> usize {
517        let floats: usize = self.k.iter().map(Vec::len).sum::<usize>()
518            + self.v.iter().map(Vec::len).sum::<usize>()
519            + self.ks.iter().map(Vec::len).sum::<usize>()
520            + self.vs.iter().map(Vec::len).sum::<usize>()
521            + self.kcol.iter().map(Vec::len).sum::<usize>()
522            + self.vcol.iter().map(Vec::len).sum::<usize>();
523        let bytes: usize = self.kq.iter().map(Vec::len).sum::<usize>()
524            + self.vq.iter().map(Vec::len).sum::<usize>();
525        floats * std::mem::size_of::<f32>()
526            + bytes
527            // O(1) recurrent state of linear-core layers (vmf_phase/GDN):
528            // constant in context, but real memory — the honest "KV+state"
529            // line must count it (a pure-linear model reported 0 before).
530            + self.linear_state.len() * std::mem::size_of::<f64>()
531            // O(1) Nyström state (window + sinks + skeleton) — same
532            // discipline: constant in context, but real memory.
533            + self.o1_memory_bytes()
534    }
535
536    /// Drop oldest positions, keeping the last `keep_last`.
537    fn evict(&mut self, keep_last: usize) {
538        // A sealed o1 layer stores nothing per position — the Nyström
539        // state IS the eviction policy; resetting seq_len here would lie
540        // about the context depth.
541        if self.o1_sealed() || self.seq_len <= keep_last {
542            return;
543        }
544        let drop = self.seq_len - keep_last;
545        for h in 0..self.num_kv_heads {
546            // Dead heads store fewer positions; drop proportionally.
547            let stored = self.head_len(h);
548            let d = drop.min(stored);
549            let hd = self.head_dim;
550            fn drop_front<T>(v: &mut Vec<T>, n: usize) {
551                let n = n.min(v.len());
552                v.drain(..n);
553            }
554            drop_front(&mut self.k[h], d * hd);
555            drop_front(&mut self.v[h], d * hd);
556            drop_front(&mut self.kq[h], d * hd);
557            drop_front(&mut self.vq[h], d * hd);
558            drop_front(&mut self.ks[h], d * hd.div_ceil(KV_K_GROUP));
559            drop_front(&mut self.vs[h], d);
560        }
561        let d = drop.min(self.imp.len());
562        self.imp.drain(..d);
563        self.seq_len = keep_last;
564    }
565
566    /// Born eviction: keep `sink` earliest positions (attention sinks),
567    /// the `recent` latest, and fill the rest of the `keep_last` budget
568    /// with the positions carrying the highest accumulated attention
569    /// mass (vmfcore: PPL 8.342 vs 8.687 for recency-only, full 8.295).
570    fn evict_born(&mut self, keep_last: usize, sink: usize, recent: usize) {
571        if self.o1_sealed() {
572            return; // see evict(): the o1 state is its own eviction
573        }
574        let stored = self.imp.len();
575        if stored <= keep_last {
576            return;
577        }
578        // Budget discipline: sinks first, recents next, both clamped so
579        // the total never exceeds keep_last.
580        let sink_n = sink.min(keep_last);
581        let recent_n = recent.min(keep_last - sink_n);
582        let mut keep = vec![false; stored];
583        for k in keep.iter_mut().take(sink_n) {
584            *k = true;
585        }
586        for k in keep.iter_mut().skip(stored.saturating_sub(recent_n)) {
587            *k = true;
588        }
589        let mut budget = keep_last.saturating_sub(keep.iter().filter(|&&x| x).count());
590        // Highest accumulated mass first among the middle positions.
591        let mut order: Vec<usize> = (0..stored).filter(|&i| !keep[i]).collect();
592        order.sort_by(|&a, &b| {
593            self.imp[b].partial_cmp(&self.imp[a]).unwrap_or(std::cmp::Ordering::Equal)
594        });
595        for i in order {
596            if budget == 0 {
597                break;
598            }
599            keep[i] = true;
600            budget -= 1;
601        }
602
603        let kept: Vec<usize> = (0..stored).filter(|&i| keep[i]).collect();
604        let hd = self.head_dim;
605        fn gather<T: Copy>(src: &[T], kept: &[usize], step: usize) -> Vec<T> {
606            let mut out = Vec::with_capacity(kept.len() * step);
607            for &i in kept {
608                out.extend_from_slice(&src[i * step..(i + 1) * step]);
609            }
610            out
611        }
612        // Each storage is gathered INDEPENDENTLY: in mixed modes
613        // (q8k/q8v) K and V live in different storages — the paired branch
614        // panicked (q8v) or silently left V uncompressed (q8k);
615        // found by adversarial review, closed by regression tests.
616        for h in 0..self.num_kv_heads {
617            if !self.k[h].is_empty() {
618                self.k[h] = gather(&self.k[h], &kept, hd);
619            }
620            if !self.v[h].is_empty() {
621                self.v[h] = gather(&self.v[h], &kept, hd);
622            }
623            if !self.kq[h].is_empty() {
624                self.kq[h] = gather(&self.kq[h], &kept, hd);
625                self.ks[h] = gather(&self.ks[h], &kept, hd.div_ceil(KV_K_GROUP));
626            }
627            if !self.vq[h].is_empty() {
628                self.vq[h] = gather(&self.vq[h], &kept, hd);
629                self.vs[h] = gather(&self.vs[h], &kept, 1);
630            }
631        }
632        self.imp = kept.iter().map(|&i| self.imp[i]).collect();
633        self.seq_len = kept.len();
634    }
635}
636
637/// Eviction policy for a bounded cache.
638#[derive(Debug, Clone, Copy, PartialEq, Eq)]
639pub enum EvictionPolicy {
640    /// Sliding window: keep only the most recent positions.
641    Recent,
642    /// Born rule: sinks + recents + top accumulated attention mass.
643    Born { sink: usize },
644}
645
646/// Full KV cache for all layers.
647#[derive(Debug)]
648pub struct KvCache {
649    pub layers: Vec<LayerKvCache>,
650    pub max_seq_len: usize,
651    pub policy: EvictionPolicy,
652}
653
654impl KvCache {
655    pub fn new(num_layers: usize, num_kv_heads: usize, head_dim: usize, max_seq_len: usize) -> Self {
656        let layers = (0..num_layers)
657            .map(|_| LayerKvCache::new(num_kv_heads, head_dim))
658            .collect();
659        Self {
660            layers,
661            max_seq_len,
662            policy: EvictionPolicy::Born { sink: 4 },
663        }
664    }
665
666    pub fn clear(&mut self) {
667        for layer in &mut self.layers {
668            layer.clear();
669        }
670    }
671
672    pub fn total_memory_bytes(&self) -> usize {
673        self.layers.iter().map(|l| l.memory_bytes()).sum()
674    }
675
676    /// Current sequence length (max across layers — dead layers may lag).
677    pub fn seq_len(&self) -> usize {
678        self.layers.iter().map(|l| l.seq_len).max().unwrap_or(0)
679    }
680
681    pub fn needs_eviction(&self) -> bool {
682        self.seq_len() >= self.max_seq_len
683    }
684
685    /// Evict down to `keep_last` positions according to the policy.
686    pub fn evict(&mut self, keep_last: usize) {
687        match self.policy {
688            EvictionPolicy::Recent => {
689                for layer in &mut self.layers {
690                    layer.evict(keep_last);
691                }
692            }
693            EvictionPolicy::Born { sink } => {
694                let recent = (keep_last / 2).max(1);
695                for layer in &mut self.layers {
696                    layer.evict_born(keep_last, sink, recent);
697                }
698            }
699        }
700    }
701}
702
703#[cfg(test)]
704mod tests {
705    use super::*;
706
707    #[test]
708    fn append_tracks_seq_len_and_layout() {
709        let mut cache = LayerKvCache::new(4, 8);
710        cache.mode = KvMode::F32;
711        assert_eq!(cache.seq_len, 0);
712
713        let k: Vec<f32> = (0..32).map(|i| i as f32).collect();
714        let v = vec![2.0f32; 32];
715        cache.append(&k, &v, &[true; 4]);
716
717        assert_eq!(cache.seq_len, 1);
718        assert_eq!(cache.head_len(0), 1);
719        // head 1 slice is contiguous and equals its part of k_new
720        assert_eq!(cache.head_keys(1), &k[8..16]);
721        assert_eq!(cache.memory_bytes(), 256);
722    }
723
724    #[test]
725    fn dead_head_stores_nothing() {
726        let mut cache = LayerKvCache::new(2, 4);
727        cache.mode = KvMode::F32;
728        let k = vec![1.0f32; 8];
729        let v = vec![2.0f32; 8];
730        cache.append(&k, &v, &[true, false]);
731        cache.append(&k, &v, &[true, false]);
732
733        assert_eq!(cache.seq_len, 2);
734        assert_eq!(cache.head_len(0), 2);
735        assert_eq!(cache.head_len(1), 0, "dead head must not store KV");
736        assert_eq!(cache.memory_bytes(), 2 * 2 * 4 * 4);
737    }
738
739    #[test]
740    fn eviction_keeps_recent() {
741        let mut cache = KvCache::new(2, 4, 8, 10);
742        cache.policy = EvictionPolicy::Recent;
743        for l in &mut cache.layers { l.mode = KvMode::F32; }
744        let k = vec![1.0f32; 32];
745        let v = vec![2.0f32; 32];
746        for _ in 0..8 {
747            for layer in &mut cache.layers {
748                layer.append(&k, &v, &[true; 4]);
749            }
750        }
751        assert_eq!(cache.seq_len(), 8);
752        assert!(!cache.needs_eviction());
753
754        cache.evict(4);
755        assert_eq!(cache.seq_len(), 4);
756        assert_eq!(cache.layers[0].head_len(0), 4);
757    }
758
759    #[test]
760    fn truncate_rolls_back_speculative_positions() {
761        let mut cache = LayerKvCache::new(2, 4);
762        cache.mode = KvMode::F32;
763        for pos in 0..5 {
764            let k = vec![pos as f32; 8];
765            let v = vec![pos as f32; 8];
766            cache.append(&k, &v, &[true; 2]);
767        }
768        cache.truncate_last(2);
769        assert_eq!(cache.seq_len, 3);
770        assert_eq!(cache.head_len(0), 3);
771        assert_eq!(cache.head_keys(0)[2 * 4], 2.0, "position 2 survives");
772    }
773
774    /// q8_2f-attend ≈ f32-attend: 100 positions (crosses the field freeze
775    /// at the 64th), pseudo-random vectors, relative tolerance of the
776    /// int8 grid. Plus rollback and Born eviction on the q8 storage.
777    #[test]
778    fn q8_attend_matches_f32_within_grid() {
779        let (heads, hd) = (2, 32);
780        let mut f = LayerKvCache::new(heads, hd);
781        f.mode = KvMode::F32;
782        let mut q8 = LayerKvCache::new(heads, hd);
783        q8.mode = KvMode::Q8 { k: true, v: true };
784
785        let synth = |p: usize, salt: usize| -> Vec<f32> {
786            (0..heads * hd)
787                .map(|i| {
788                    let x = ((i * 31 + p * 17 + salt * 7 + 3) % 97) as f32 / 97.0 - 0.5;
789                    // channel structure: even channels ×4 (checks the 2f field)
790                    if i % 2 == 0 { x * 4.0 } else { x * 0.25 }
791                })
792                .collect()
793        };
794        for p in 0..100 {
795            let k = synth(p, 1);
796            let v = synth(p, 2);
797            f.append(&k, &v, &[true; 2]);
798            q8.append(&k, &v, &[true; 2]);
799        }
800        let q: Vec<f32> = (0..hd).map(|i| ((i * 13 + 5) % 89) as f32 / 89.0 - 0.5).collect();
801        for g in 0..heads {
802            let (of, pf) = f.attend(&q, g);
803            let (o8, p8) = q8.attend(&q, g);
804            let scale = of.iter().fold(0f32, |m, x| m.max(x.abs())).max(1e-6);
805            for d in 0..hd {
806                assert!(
807                    (of[d] - o8[d]).abs() <= scale * 0.03 + 1e-3,
808                    "g{g} d{d}: f32 {} vs q8 {}", of[d], o8[d]
809                );
810            }
811            for p in 0..100 {
812                assert!((pf[p] - p8[p]).abs() < 0.02, "prob p{p}");
813            }
814        }
815        // rollback + eviction live on the q8 storage
816        q8.truncate_last(30);
817        assert_eq!(q8.head_len(0), 70);
818        let imp: Vec<f32> = (0..70).map(|i| i as f32).collect();
819        q8.accumulate_imp(&imp);
820        q8.evict_born(20, 2, 8);
821        assert_eq!(q8.head_len(0), 20);
822        let (o, _) = q8.attend(&q, 0);
823        assert!(o.iter().all(|x| x.is_finite()));
824        // memory: q8 ≈ 1 byte/element + scale per row (vs 4 for f32)
825        assert!(q8.memory_bytes() * 3 < f.memory_bytes());
826    }
827
828    /// Review regression: Born eviction in MIXED modes. q8v used to
829    /// panic (gather over an empty v[h]), q8k silently left raw V
830    /// uncompressed (stale rows under kept keys + memory leak).
831    #[test]
832    fn born_eviction_mixed_modes_stay_consistent() {
833        for (mk, mv) in [(false, true), (true, false)] {
834            let mut c = LayerKvCache::new(1, 4);
835            c.mode = KvMode::Q8 { k: mk, v: mv };
836            for p in 0..80 {
837                let k = vec![p as f32 * 0.01; 4];
838                let v = vec![p as f32; 4];
839                c.append(&k, &v, &[true]);
840            }
841            let imp: Vec<f32> = (0..80).map(|i| i as f32).collect();
842            c.accumulate_imp(&imp);
843            let before = c.memory_bytes();
844            c.evict_born(20, 4, 8); // q8v: used to panic here
845            assert_eq!(c.head_len(0), 20, "k={mk} v={mv}");
846            assert!(c.memory_bytes() < before / 2,
847                    "memory must shrink (k={mk} v={mv})");
848            // V rows match the kept set: the heaviest positions
849            // (tail 60..79) must be present in the attend output.
850            let (out, _) = c.attend(&[1.0, 1.0, 1.0, 1.0], 0);
851            assert!(out[0] > 30.0,
852                    "V from the kept tail, not the stale head (k={mk} v={mv}, out {})",
853                    out[0]);
854        }
855    }
856
857    #[test]
858    fn born_eviction_keeps_high_mass_position() {
859        let mut cache = KvCache::new(1, 1, 2, 16);
860        cache.policy = EvictionPolicy::Born { sink: 1 };
861        for l in &mut cache.layers { l.mode = KvMode::F32; }
862        let layer = &mut cache.layers[0];
863        // 8 positions; keys carry the position index so we can verify
864        // exactly which positions survive the gather.
865        for pos in 0..8 {
866            let k = vec![pos as f32; 2];
867            let v = vec![pos as f32 + 100.0; 2];
868            layer.append(&k, &v, &[true]);
869        }
870        // Position 3 carries the most attention mass (Born importance).
871        let mut imp = vec![0.05f32; 8];
872        imp[3] = 5.0;
873        layer.accumulate_imp(&imp);
874
875        cache.evict(4); // sink 1 + recent 2 + 1 top-mass slot
876        let layer = &cache.layers[0];
877        assert_eq!(layer.seq_len, 4);
878        let kept_keys: Vec<f32> = (0..4).map(|i| layer.head_keys(0)[i * 2]).collect();
879        assert_eq!(
880            kept_keys,
881            vec![0.0, 3.0, 6.0, 7.0],
882            "kept = sink(0) + Born-top(3) + recent(6,7)"
883        );
884        // imp stays aligned with the gathered positions.
885        assert_eq!(layer.head_len(0), 4);
886    }
887}