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<f32>,
101    /// Tentative lane-2 state during speculative verify.
102    pub linear_scratch: Vec<f32>,
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    /// Grouped GQA attention: all Q-heads of one KV group in a single
450    /// pass over the stored K rows and a single pass over the V rows
451    /// (per-head `attend` re-read the shared group storage
452    /// heads_per_kv times — roadmap §3 P1). Per-head score order,
453    /// softmax and V accumulation are IDENTICAL to `attend`, so each
454    /// head's output is bit-for-bit the same.
455    ///
456    /// `q_group`: `[n_heads_in_group × head_dim]` (global head order);
457    /// `out`: same shape; `imp_acc[0..stored]` accumulates the probs of
458    /// every head (Born importance), matching the caller's former loop.
459    /// `scale` is the score scale (1/√hd unless the arch overrides);
460    /// `first` is the earliest visible position — sliding-window layers
461    /// pass `stored − window` so older rows get zero probability.
462    #[allow(clippy::too_many_arguments)]
463    pub fn attend_group(
464        &self,
465        q_group: &[f32],
466        kv_head: usize,
467        out: &mut [f32],
468        imp_acc: &mut [f32],
469        scale: f32,
470        first: usize,
471    ) {
472        let hd = self.head_dim;
473        let nheads = q_group.len() / hd;
474        debug_assert_eq!(out.len(), nheads * hd);
475        let stored = if self.mode == KvMode::F32 {
476            self.k[kv_head].len() / hd
477        } else {
478            self.head_len(kv_head)
479        };
480        if stored == 0 {
481            out.fill(0.0);
482            return;
483        }
484        let first = first.min(stored.saturating_sub(1));
485
486        thread_local! {
487            /// scores [nheads × stored] — reused across layers/tokens.
488            static GQA_SCORES: std::cell::RefCell<Vec<f32>> =
489                const { std::cell::RefCell::new(Vec::new()) };
490            /// q ⊙ col_k per head (q8 K mode).
491            static GQA_QC: std::cell::RefCell<Vec<f32>> =
492                const { std::cell::RefCell::new(Vec::new()) };
493        }
494
495        GQA_SCORES.with(|sc| {
496            let mut scores = sc.borrow_mut();
497            if first > 0 {
498                // Out-of-window rows stay at −inf → exp gives exactly 0,
499                // so softmax / V / importance need no special-casing.
500                scores.clear();
501                scores.resize(nheads * stored, f32::NEG_INFINITY);
502            } else {
503                scores.resize(nheads * stored, 0.0);
504            }
505
506            // ── score pass: each stored K row is read ONCE for all heads.
507            if self.mode.quant_k() {
508                let (kq, ks) = (&self.kq[kv_head], &self.ks[kv_head]);
509                let kcol = &self.kcol[kv_head];
510                let ng = hd.div_ceil(KV_K_GROUP);
511                GQA_QC.with(|qc| {
512                    let mut qcb = qc.borrow_mut();
513                    qcb.resize(nheads * hd, 0.0);
514                    for h in 0..nheads {
515                        for d in 0..hd {
516                            let qv = q_group[h * hd + d];
517                            qcb[h * hd + d] = if kcol.is_empty() { qv } else { qv * kcol[d] };
518                        }
519                    }
520                    for p in first..stored {
521                        let row = &kq[p * hd..(p + 1) * hd];
522                        // SAFETY: i8 and u8 share layout; dot_i8_f32 reads
523                        // the bytes back as i8.
524                        let row_u8 = unsafe {
525                            std::slice::from_raw_parts(row.as_ptr() as *const u8, row.len())
526                        };
527                        for h in 0..nheads {
528                            let qch = &qcb[h * hd..(h + 1) * hd];
529                            let mut dot = 0.0f32;
530                            for g in 0..ng {
531                                let g0 = g * KV_K_GROUP;
532                                let g1 = (g0 + KV_K_GROUP).min(hd);
533                                dot += crate::qtensor::dot_i8_f32(&row_u8[g0..g1], &qch[g0..g1])
534                                    * ks[p * ng + g];
535                            }
536                            scores[h * stored + p] = dot * scale;
537                        }
538                    }
539                });
540            } else {
541                let k = &self.k[kv_head];
542                for p in first..stored {
543                    let row = &k[p * hd..(p + 1) * hd];
544                    for h in 0..nheads {
545                        scores[h * stored + p] =
546                            crate::attention::dot_f32(&q_group[h * hd..(h + 1) * hd], row)
547                                * scale;
548                    }
549                }
550            }
551
552            // ── per-head softmax (identical to attend / attention_head).
553            for h in 0..nheads {
554                let s = &mut scores[h * stored..(h + 1) * stored];
555                let max_score = s.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
556                let mut sum = 0.0f32;
557                for v in s.iter_mut() {
558                    *v = (*v - max_score).exp();
559                    sum += *v;
560                }
561                if sum > 0.0 {
562                    for v in s.iter_mut() {
563                        *v /= sum;
564                    }
565                }
566            }
567
568            // ── value pass: each stored V row is read ONCE for all heads.
569            out.fill(0.0);
570            if self.mode.quant_v() {
571                let (vq, vs) = (&self.vq[kv_head], &self.vs[kv_head]);
572                for p in first..stored {
573                    let row = &vq[p * hd..(p + 1) * hd];
574                    for h in 0..nheads {
575                        let w = scores[h * stored + p] * vs[p];
576                        if w.abs() < 1e-12 {
577                            continue;
578                        }
579                        crate::qtensor::axpy_i8_f32(&mut out[h * hd..(h + 1) * hd], row, w);
580                    }
581                }
582                let vcol = &self.vcol[kv_head];
583                if !vcol.is_empty() {
584                    for h in 0..nheads {
585                        for d in 0..hd {
586                            out[h * hd + d] *= vcol[d];
587                        }
588                    }
589                }
590            } else {
591                let v = &self.v[kv_head];
592                for p in first..stored {
593                    let row = &v[p * hd..(p + 1) * hd];
594                    for h in 0..nheads {
595                        let w = scores[h * stored + p];
596                        if w.abs() < 1e-12 {
597                            continue;
598                        }
599                        crate::attention::axpy_f32(&mut out[h * hd..(h + 1) * hd], row, w);
600                    }
601                }
602            }
603
604            // ── Born-importance accumulation (Σ probs over heads), same
605            // head order as the caller's former per-head loop.
606            let n = imp_acc.len().min(stored);
607            for h in 0..nheads {
608                let s = &scores[h * stored..(h + 1) * stored];
609                for (dst, &p) in imp_acc[..n].iter_mut().zip(s) {
610                    *dst += p;
611                }
612            }
613        });
614    }
615
616    /// Batched causal attend for a prefill chunk (macOS/AArch64): the
617    /// cache already holds every chunk row (`s0` old + `b` new). Per
618    /// Q-head the scores GEMM `Q·Kᵀ` rides the AMX, the causal softmax
619    /// zeroes the not-yet-visible tail so the `P·V` GEMM needs no
620    /// mask, and Born importance takes the masked column sums. Same
621    /// math as the per-position attend; summation order differs
622    /// (tolerance-class, like the projection GEMMs).
623    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
624    #[allow(clippy::too_many_arguments)]
625    pub fn attend_chunk(
626        &mut self,
627        q_all: &[f32],
628        b: usize,
629        s0: usize,
630        nh: usize,
631        heads_per_kv: usize,
632        hd: usize,
633        out: &mut [f32],
634        pool: Option<&crate::pool::Pool>,
635        scale: f32,
636        window: Option<usize>,
637    ) {
638        let n = s0 + b;
639        struct SendPtr(*mut f32);
640        unsafe impl Send for SendPtr {}
641        unsafe impl Sync for SendPtr {}
642        impl SendPtr {
643            fn at(&self, i: usize) -> *mut f32 {
644                // Method receiver keeps the closure capturing &SendPtr
645                // (2021 disjoint capture would grab the raw field).
646                unsafe { self.0.add(i) }
647            }
648        }
649        thread_local! {
650            static SCRATCH: std::cell::RefCell<(Vec<f32>, Vec<f32>, Vec<f32>)> =
651                const { std::cell::RefCell::new((Vec::new(), Vec::new(), Vec::new())) };
652        }
653        SCRATCH.with(|s| {
654            let mut s = s.borrow_mut();
655            let (qpanel, scores, aopanel) = &mut *s;
656            // The whole KV-group attends in one GEMM pair: the group's
657            // Q-heads stack head-major into one tall panel [hpk·b, hd]
658            // (row hl·b + bi), so each layer costs 2 sgemm calls per
659            // group instead of 2 per head — fat M keeps the AMX fed.
660            let m = heads_per_kv * b;
661            qpanel.resize(m * hd, 0.0);
662            scores.resize(m * n, 0.0);
663            aopanel.resize(m * hd, 0.0);
664            for g in 0..self.num_kv_heads {
665                let kmat = &self.k[g];
666                let vmat = &self.v[g];
667                debug_assert_eq!(kmat.len(), n * hd);
668                for hl in 0..heads_per_kv {
669                    let hh = g * heads_per_kv + hl;
670                    for bi in 0..b {
671                        qpanel[(hl * b + bi) * hd..(hl * b + bi + 1) * hd]
672                            .copy_from_slice(&q_all[bi * nh * hd + hh * hd..][..hd]);
673                    }
674                }
675                crate::qtensor::sgemm_rm(m, n, hd, scale, qpanel, hd, kmat, hd, true, scores, n);
676                // Causal softmax, row-parallel (rows are disjoint).
677                let sp = SendPtr(scores.as_mut_ptr());
678                let run = |start: usize, end: usize| {
679                    for r in start..end {
680                        let allowed = s0 + (r % b) + 1;
681                        // Sliding-window layers see only the last W of
682                        // the causal range; the zeroed head contributes
683                        // nothing to P·V or Born importance.
684                        let lo = window.map(|w| allowed.saturating_sub(w)).unwrap_or(0);
685                        // SAFETY: workers cover disjoint row ranges.
686                        let row = unsafe { std::slice::from_raw_parts_mut(sp.at(r * n), n) };
687                        crate::attention::softmax_row(&mut row[lo..allowed]);
688                        row[..lo].fill(0.0);
689                        row[allowed..].fill(0.0);
690                    }
691                };
692                match pool {
693                    Some(p) if m >= 64 => p.run_rows(m, &run),
694                    _ => run(0, m),
695                }
696                // Born importance: masked column sums (probs of the
697                // zeroed tail contribute nothing, same as the CPU
698                // per-position accumulate).
699                let ni = self.imp.len().min(n);
700                for r in 0..m {
701                    let al = (s0 + (r % b) + 1).min(ni);
702                    for (dst, &p) in self.imp[..al].iter_mut().zip(&scores[r * n..r * n + al]) {
703                        *dst += p;
704                    }
705                }
706                crate::qtensor::sgemm_rm(m, hd, n, 1.0, scores, n, vmat, hd, false, aopanel, hd);
707                for hl in 0..heads_per_kv {
708                    let hh = g * heads_per_kv + hl;
709                    for bi in 0..b {
710                        out[bi * nh * hd + hh * hd..][..hd]
711                            .copy_from_slice(&aopanel[(hl * b + bi) * hd..(hl * b + bi + 1) * hd]);
712                    }
713                }
714            }
715        });
716    }
717
718    /// Roll back the last `n_drop` positions (speculative-decode reject).
719    pub fn truncate_last(&mut self, n_drop: usize) {
720        let d = n_drop.min(self.seq_len);
721        for h in 0..self.num_kv_heads {
722            let keep = self.k[h].len().saturating_sub(d * self.head_dim);
723            self.k[h].truncate(keep);
724            self.v[h].truncate(keep);
725            let ngk = self.head_dim.div_ceil(KV_K_GROUP);
726            let keep_q = self.kq[h].len().saturating_sub(d * self.head_dim);
727            self.kq[h].truncate(keep_q);
728            let keep_vq = self.vq[h].len().saturating_sub(d * self.head_dim);
729            self.vq[h].truncate(keep_vq);
730            let keep_ks = self.ks[h].len().saturating_sub(d * ngk);
731            self.ks[h].truncate(keep_ks);
732            let keep_vs = self.vs[h].len().saturating_sub(d);
733            self.vs[h].truncate(keep_vs);
734        }
735        self.imp.truncate(self.imp.len().saturating_sub(d));
736        self.seq_len -= d;
737    }
738
739    /// Accumulate attention mass per stored position (summed over heads).
740    pub fn accumulate_imp(&mut self, probs: &[f32]) {
741        for (dst, &p) in self.imp.iter_mut().zip(probs) {
742            *dst += p;
743        }
744    }
745
746    /// Contiguous keys of one head: `[stored_len × head_dim]`.
747    pub fn head_keys(&self, kv_head: usize) -> &[f32] {
748        &self.k[kv_head]
749    }
750
751    pub fn head_values(&self, kv_head: usize) -> &[f32] {
752        &self.v[kv_head]
753    }
754
755    /// Number of positions actually stored for a head (0 for dead heads).
756    pub fn head_len(&self, kv_head: usize) -> usize {
757        let ng = self.head_dim.div_ceil(KV_K_GROUP);
758        (self.k[kv_head].len() / self.head_dim)
759            .max(self.ks[kv_head].len() / ng)
760            .max(self.vs[kv_head].len())
761    }
762
763    /// Clear cache (e.g. on new conversation or task switch).
764    pub fn clear(&mut self) {
765        for h in 0..self.num_kv_heads {
766            self.k[h].clear();
767            self.v[h].clear();
768            self.kq[h].clear();
769            self.ks[h].clear();
770            self.vq[h].clear();
771            self.vs[h].clear();
772            self.kcol[h].clear();
773            self.vcol[h].clear();
774        }
775        self.imp.clear();
776        self.linear_state.clear();
777        self.linear_scratch.clear();
778        // Fresh conversation → the pipeline re-arms collection if the
779        // layer is o1-flagged (landmarks are per-prompt, never reused).
780        self.o1 = None;
781        self.seq_len = 0;
782    }
783
784    /// Memory usage in bytes.
785    pub fn memory_bytes(&self) -> usize {
786        let floats: usize = self.k.iter().map(Vec::len).sum::<usize>()
787            + self.v.iter().map(Vec::len).sum::<usize>()
788            + self.ks.iter().map(Vec::len).sum::<usize>()
789            + self.vs.iter().map(Vec::len).sum::<usize>()
790            + self.kcol.iter().map(Vec::len).sum::<usize>()
791            + self.vcol.iter().map(Vec::len).sum::<usize>();
792        let bytes: usize = self.kq.iter().map(Vec::len).sum::<usize>()
793            + self.vq.iter().map(Vec::len).sum::<usize>();
794        floats * std::mem::size_of::<f32>()
795            + bytes
796            // O(1) recurrent state of linear-core layers (vmf_phase/GDN):
797            // constant in context, but real memory — the honest "KV+state"
798            // line must count it (a pure-linear model reported 0 before).
799            + self.linear_state.len() * std::mem::size_of::<f32>()
800            // O(1) Nyström state (window + sinks + skeleton) — same
801            // discipline: constant in context, but real memory.
802            + self.o1_memory_bytes()
803    }
804
805    /// Drop oldest positions, keeping the last `keep_last`.
806    fn evict(&mut self, keep_last: usize) {
807        // A sealed o1 layer stores nothing per position — the Nyström
808        // state IS the eviction policy; resetting seq_len here would lie
809        // about the context depth.
810        if self.o1_sealed() || self.seq_len <= keep_last {
811            return;
812        }
813        let drop = self.seq_len - keep_last;
814        for h in 0..self.num_kv_heads {
815            // Dead heads store fewer positions; drop proportionally.
816            let stored = self.head_len(h);
817            let d = drop.min(stored);
818            let hd = self.head_dim;
819            fn drop_front<T>(v: &mut Vec<T>, n: usize) {
820                let n = n.min(v.len());
821                v.drain(..n);
822            }
823            drop_front(&mut self.k[h], d * hd);
824            drop_front(&mut self.v[h], d * hd);
825            drop_front(&mut self.kq[h], d * hd);
826            drop_front(&mut self.vq[h], d * hd);
827            drop_front(&mut self.ks[h], d * hd.div_ceil(KV_K_GROUP));
828            drop_front(&mut self.vs[h], d);
829        }
830        let d = drop.min(self.imp.len());
831        self.imp.drain(..d);
832        self.seq_len = keep_last;
833    }
834
835    /// Born eviction: keep `sink` earliest positions (attention sinks),
836    /// the `recent` latest, and fill the rest of the `keep_last` budget
837    /// with the positions carrying the highest accumulated attention
838    /// mass (vmfcore: PPL 8.342 vs 8.687 for recency-only, full 8.295).
839    fn evict_born(&mut self, keep_last: usize, sink: usize, recent: usize) {
840        if self.o1_sealed() {
841            return; // see evict(): the o1 state is its own eviction
842        }
843        let stored = self.imp.len();
844        if stored <= keep_last {
845            return;
846        }
847        // Budget discipline: sinks first, recents next, both clamped so
848        // the total never exceeds keep_last.
849        let sink_n = sink.min(keep_last);
850        let recent_n = recent.min(keep_last - sink_n);
851        let mut keep = vec![false; stored];
852        for k in keep.iter_mut().take(sink_n) {
853            *k = true;
854        }
855        for k in keep.iter_mut().skip(stored.saturating_sub(recent_n)) {
856            *k = true;
857        }
858        let mut budget = keep_last.saturating_sub(keep.iter().filter(|&&x| x).count());
859        // Highest accumulated mass first among the middle positions.
860        let mut order: Vec<usize> = (0..stored).filter(|&i| !keep[i]).collect();
861        order.sort_by(|&a, &b| {
862            self.imp[b].partial_cmp(&self.imp[a]).unwrap_or(std::cmp::Ordering::Equal)
863        });
864        for i in order {
865            if budget == 0 {
866                break;
867            }
868            keep[i] = true;
869            budget -= 1;
870        }
871
872        let kept: Vec<usize> = (0..stored).filter(|&i| keep[i]).collect();
873        let hd = self.head_dim;
874        fn gather<T: Copy>(src: &[T], kept: &[usize], step: usize) -> Vec<T> {
875            let mut out = Vec::with_capacity(kept.len() * step);
876            for &i in kept {
877                out.extend_from_slice(&src[i * step..(i + 1) * step]);
878            }
879            out
880        }
881        // Each storage is gathered INDEPENDENTLY: in mixed modes
882        // (q8k/q8v) K and V live in different storages — the paired branch
883        // panicked (q8v) or silently left V uncompressed (q8k);
884        // found by adversarial review, closed by regression tests.
885        for h in 0..self.num_kv_heads {
886            if !self.k[h].is_empty() {
887                self.k[h] = gather(&self.k[h], &kept, hd);
888            }
889            if !self.v[h].is_empty() {
890                self.v[h] = gather(&self.v[h], &kept, hd);
891            }
892            if !self.kq[h].is_empty() {
893                self.kq[h] = gather(&self.kq[h], &kept, hd);
894                self.ks[h] = gather(&self.ks[h], &kept, hd.div_ceil(KV_K_GROUP));
895            }
896            if !self.vq[h].is_empty() {
897                self.vq[h] = gather(&self.vq[h], &kept, hd);
898                self.vs[h] = gather(&self.vs[h], &kept, 1);
899            }
900        }
901        self.imp = kept.iter().map(|&i| self.imp[i]).collect();
902        self.seq_len = kept.len();
903    }
904}
905
906/// Eviction policy for a bounded cache.
907#[derive(Debug, Clone, Copy, PartialEq, Eq)]
908pub enum EvictionPolicy {
909    /// Sliding window: keep only the most recent positions.
910    Recent,
911    /// Born rule: sinks + recents + top accumulated attention mass.
912    Born { sink: usize },
913}
914
915/// Full KV cache for all layers.
916#[derive(Debug)]
917pub struct KvCache {
918    pub layers: Vec<LayerKvCache>,
919    pub max_seq_len: usize,
920    pub policy: EvictionPolicy,
921}
922
923impl KvCache {
924    pub fn new(num_layers: usize, num_kv_heads: usize, head_dim: usize, max_seq_len: usize) -> Self {
925        let layers = (0..num_layers)
926            .map(|_| LayerKvCache::new(num_kv_heads, head_dim))
927            .collect();
928        Self {
929            layers,
930            max_seq_len,
931            policy: EvictionPolicy::Born { sink: 4 },
932        }
933    }
934
935    pub fn clear(&mut self) {
936        for layer in &mut self.layers {
937            layer.clear();
938        }
939    }
940
941    pub fn total_memory_bytes(&self) -> usize {
942        self.layers.iter().map(|l| l.memory_bytes()).sum()
943    }
944
945    /// Current sequence length (max across layers — dead layers may lag).
946    pub fn seq_len(&self) -> usize {
947        self.layers.iter().map(|l| l.seq_len).max().unwrap_or(0)
948    }
949
950    pub fn needs_eviction(&self) -> bool {
951        self.seq_len() >= self.max_seq_len
952    }
953
954    /// Evict down to `keep_last` positions according to the policy.
955    pub fn evict(&mut self, keep_last: usize) {
956        match self.policy {
957            EvictionPolicy::Recent => {
958                for layer in &mut self.layers {
959                    layer.evict(keep_last);
960                }
961            }
962            EvictionPolicy::Born { sink } => {
963                let recent = (keep_last / 2).max(1);
964                for layer in &mut self.layers {
965                    layer.evict_born(keep_last, sink, recent);
966                }
967            }
968        }
969    }
970}
971
972#[cfg(test)]
973mod tests {
974    use super::*;
975
976    #[test]
977    fn append_tracks_seq_len_and_layout() {
978        let mut cache = LayerKvCache::new(4, 8);
979        cache.mode = KvMode::F32;
980        assert_eq!(cache.seq_len, 0);
981
982        let k: Vec<f32> = (0..32).map(|i| i as f32).collect();
983        let v = vec![2.0f32; 32];
984        cache.append(&k, &v, &[true; 4]);
985
986        assert_eq!(cache.seq_len, 1);
987        assert_eq!(cache.head_len(0), 1);
988        // head 1 slice is contiguous and equals its part of k_new
989        assert_eq!(cache.head_keys(1), &k[8..16]);
990        assert_eq!(cache.memory_bytes(), 256);
991    }
992
993    #[test]
994    fn dead_head_stores_nothing() {
995        let mut cache = LayerKvCache::new(2, 4);
996        cache.mode = KvMode::F32;
997        let k = vec![1.0f32; 8];
998        let v = vec![2.0f32; 8];
999        cache.append(&k, &v, &[true, false]);
1000        cache.append(&k, &v, &[true, false]);
1001
1002        assert_eq!(cache.seq_len, 2);
1003        assert_eq!(cache.head_len(0), 2);
1004        assert_eq!(cache.head_len(1), 0, "dead head must not store KV");
1005        assert_eq!(cache.memory_bytes(), 2 * 2 * 4 * 4);
1006    }
1007
1008    #[test]
1009    fn eviction_keeps_recent() {
1010        let mut cache = KvCache::new(2, 4, 8, 10);
1011        cache.policy = EvictionPolicy::Recent;
1012        for l in &mut cache.layers { l.mode = KvMode::F32; }
1013        let k = vec![1.0f32; 32];
1014        let v = vec![2.0f32; 32];
1015        for _ in 0..8 {
1016            for layer in &mut cache.layers {
1017                layer.append(&k, &v, &[true; 4]);
1018            }
1019        }
1020        assert_eq!(cache.seq_len(), 8);
1021        assert!(!cache.needs_eviction());
1022
1023        cache.evict(4);
1024        assert_eq!(cache.seq_len(), 4);
1025        assert_eq!(cache.layers[0].head_len(0), 4);
1026    }
1027
1028    #[test]
1029    fn truncate_rolls_back_speculative_positions() {
1030        let mut cache = LayerKvCache::new(2, 4);
1031        cache.mode = KvMode::F32;
1032        for pos in 0..5 {
1033            let k = vec![pos as f32; 8];
1034            let v = vec![pos as f32; 8];
1035            cache.append(&k, &v, &[true; 2]);
1036        }
1037        cache.truncate_last(2);
1038        assert_eq!(cache.seq_len, 3);
1039        assert_eq!(cache.head_len(0), 3);
1040        assert_eq!(cache.head_keys(0)[2 * 4], 2.0, "position 2 survives");
1041    }
1042
1043    /// q8_2f-attend ≈ f32-attend: 100 positions (crosses the field freeze
1044    /// at the 64th), pseudo-random vectors, relative tolerance of the
1045    /// int8 grid. Plus rollback and Born eviction on the q8 storage.
1046    #[test]
1047    fn q8_attend_matches_f32_within_grid() {
1048        let (heads, hd) = (2, 32);
1049        let mut f = LayerKvCache::new(heads, hd);
1050        f.mode = KvMode::F32;
1051        let mut q8 = LayerKvCache::new(heads, hd);
1052        q8.mode = KvMode::Q8 { k: true, v: true };
1053
1054        let synth = |p: usize, salt: usize| -> Vec<f32> {
1055            (0..heads * hd)
1056                .map(|i| {
1057                    let x = ((i * 31 + p * 17 + salt * 7 + 3) % 97) as f32 / 97.0 - 0.5;
1058                    // channel structure: even channels ×4 (checks the 2f field)
1059                    if i % 2 == 0 { x * 4.0 } else { x * 0.25 }
1060                })
1061                .collect()
1062        };
1063        for p in 0..100 {
1064            let k = synth(p, 1);
1065            let v = synth(p, 2);
1066            f.append(&k, &v, &[true; 2]);
1067            q8.append(&k, &v, &[true; 2]);
1068        }
1069        let q: Vec<f32> = (0..hd).map(|i| ((i * 13 + 5) % 89) as f32 / 89.0 - 0.5).collect();
1070        for g in 0..heads {
1071            let (of, pf) = f.attend(&q, g);
1072            let (o8, p8) = q8.attend(&q, g);
1073            let scale = of.iter().fold(0f32, |m, x| m.max(x.abs())).max(1e-6);
1074            for d in 0..hd {
1075                assert!(
1076                    (of[d] - o8[d]).abs() <= scale * 0.03 + 1e-3,
1077                    "g{g} d{d}: f32 {} vs q8 {}", of[d], o8[d]
1078                );
1079            }
1080            for p in 0..100 {
1081                assert!((pf[p] - p8[p]).abs() < 0.02, "prob p{p}");
1082            }
1083        }
1084        // rollback + eviction live on the q8 storage
1085        q8.truncate_last(30);
1086        assert_eq!(q8.head_len(0), 70);
1087        let imp: Vec<f32> = (0..70).map(|i| i as f32).collect();
1088        q8.accumulate_imp(&imp);
1089        q8.evict_born(20, 2, 8);
1090        assert_eq!(q8.head_len(0), 20);
1091        let (o, _) = q8.attend(&q, 0);
1092        assert!(o.iter().all(|x| x.is_finite()));
1093        // memory: q8 ≈ 1 byte/element + scale per row (vs 4 for f32)
1094        assert!(q8.memory_bytes() * 3 < f.memory_bytes());
1095    }
1096
1097    /// Grouped GQA attend must be bit-identical to per-head attend in
1098    /// every KV mode (it is the same math with rows streamed once).
1099    #[test]
1100    fn attend_group_equals_per_head_attend_bitexact() {
1101        let (kv_heads, hd, hpk) = (2usize, 32usize, 3usize); // 6 Q-heads
1102        for mode in [KvMode::F32, KvMode::Q8 { k: true, v: true }] {
1103            let mut c = LayerKvCache::new(kv_heads, hd);
1104            c.mode = mode;
1105            for p in 0..70 {
1106                let k: Vec<f32> = (0..kv_heads * hd)
1107                    .map(|i| ((i * 31 + p * 17 + 3) % 97) as f32 / 97.0 - 0.5)
1108                    .collect();
1109                let v: Vec<f32> = (0..kv_heads * hd)
1110                    .map(|i| ((i * 13 + p * 29 + 7) % 89) as f32 / 89.0 - 0.5)
1111                    .collect();
1112                c.append(&k, &v, &[true; 2]);
1113            }
1114            let q: Vec<f32> = (0..kv_heads * hpk * hd)
1115                .map(|i| ((i * 11 + 5) % 83) as f32 / 83.0 - 0.5)
1116                .collect();
1117            for g in 0..kv_heads {
1118                let span = g * hpk * hd..(g + 1) * hpk * hd;
1119                let mut out = vec![0f32; hpk * hd];
1120                let mut imp = vec![0f32; 70];
1121                c.attend_group(
1122                    &q[span.clone()],
1123                    g,
1124                    &mut out,
1125                    &mut imp,
1126                    1.0 / (hd as f32).sqrt(),
1127                    0,
1128                );
1129                let mut imp_ref = vec![0f32; 70];
1130                for h in 0..hpk {
1131                    let qh = &q[span.start + h * hd..span.start + (h + 1) * hd];
1132                    let (o, probs) = c.attend(qh, g);
1133                    assert_eq!(
1134                        &out[h * hd..(h + 1) * hd],
1135                        &o[..],
1136                        "mode {mode:?} g{g} h{h}: grouped attend must be bit-identical"
1137                    );
1138                    for (dst, &p) in imp_ref.iter_mut().zip(&probs) {
1139                        *dst += p;
1140                    }
1141                }
1142                assert_eq!(imp, imp_ref, "mode {mode:?} g{g}: Born mass must match");
1143            }
1144        }
1145    }
1146
1147    /// Review regression: Born eviction in MIXED modes. q8v used to
1148    /// panic (gather over an empty v[h]), q8k silently left raw V
1149    /// uncompressed (stale rows under kept keys + memory leak).
1150    #[test]
1151    fn born_eviction_mixed_modes_stay_consistent() {
1152        for (mk, mv) in [(false, true), (true, false)] {
1153            let mut c = LayerKvCache::new(1, 4);
1154            c.mode = KvMode::Q8 { k: mk, v: mv };
1155            for p in 0..80 {
1156                let k = vec![p as f32 * 0.01; 4];
1157                let v = vec![p as f32; 4];
1158                c.append(&k, &v, &[true]);
1159            }
1160            let imp: Vec<f32> = (0..80).map(|i| i as f32).collect();
1161            c.accumulate_imp(&imp);
1162            let before = c.memory_bytes();
1163            c.evict_born(20, 4, 8); // q8v: used to panic here
1164            assert_eq!(c.head_len(0), 20, "k={mk} v={mv}");
1165            assert!(c.memory_bytes() < before / 2,
1166                    "memory must shrink (k={mk} v={mv})");
1167            // V rows match the kept set: the heaviest positions
1168            // (tail 60..79) must be present in the attend output.
1169            let (out, _) = c.attend(&[1.0, 1.0, 1.0, 1.0], 0);
1170            assert!(out[0] > 30.0,
1171                    "V from the kept tail, not the stale head (k={mk} v={mv}, out {})",
1172                    out[0]);
1173        }
1174    }
1175
1176    #[test]
1177    fn born_eviction_keeps_high_mass_position() {
1178        let mut cache = KvCache::new(1, 1, 2, 16);
1179        cache.policy = EvictionPolicy::Born { sink: 1 };
1180        for l in &mut cache.layers { l.mode = KvMode::F32; }
1181        let layer = &mut cache.layers[0];
1182        // 8 positions; keys carry the position index so we can verify
1183        // exactly which positions survive the gather.
1184        for pos in 0..8 {
1185            let k = vec![pos as f32; 2];
1186            let v = vec![pos as f32 + 100.0; 2];
1187            layer.append(&k, &v, &[true]);
1188        }
1189        // Position 3 carries the most attention mass (Born importance).
1190        let mut imp = vec![0.05f32; 8];
1191        imp[3] = 5.0;
1192        layer.accumulate_imp(&imp);
1193
1194        cache.evict(4); // sink 1 + recent 2 + 1 top-mass slot
1195        let layer = &cache.layers[0];
1196        assert_eq!(layer.seq_len, 4);
1197        let kept_keys: Vec<f32> = (0..4).map(|i| layer.head_keys(0)[i * 2]).collect();
1198        assert_eq!(
1199            kept_keys,
1200            vec![0.0, 3.0, 6.0, 7.0],
1201            "kept = sink(0) + Born-top(3) + recent(6,7)"
1202        );
1203        // imp stays aligned with the gathered positions.
1204        assert_eq!(layer.head_len(0), 4);
1205    }
1206}