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