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 scale 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 {
17        k: bool,
18        v: bool,
19    },
20}
21
22impl KvMode {
23    pub fn from_env() -> Self {
24        match std::env::var("CMF_KV").as_deref() {
25            Ok("q8") | Ok("q8_2f") => KvMode::Q8 { k: true, v: true },
26            Ok("q8k") => KvMode::Q8 { k: true, v: false },
27            Ok("q8v") => KvMode::Q8 { k: false, v: true },
28            _ => KvMode::F32,
29        }
30    }
31
32    fn quant_k(self) -> bool {
33        matches!(self, KvMode::Q8 { k: true, .. })
34    }
35
36    fn quant_v(self) -> bool {
37        matches!(self, KvMode::Q8 { v: true, .. })
38    }
39}
40
41/// Positions before freezing the per-channel field (2f): before — col ≡ 1,
42/// after — col = RMS over channels of the stored rows, old rows are requantized.
43const KV_COL_WARMUP: usize = 64;
44
45/// K-rows are quantized in groups of 32 channels (scale per group):
46/// attention logits are sensitive to the dot-product error, per-group scales
47/// localize it along RoPE bands (35B: +4.6% PPL with a per-row scale
48/// → target <1% with a per-group one). V — per-row scale (measured +0.56%).
49const KV_K_GROUP: usize = 32;
50
51/// Source of `LayerKvCache::generation`. Process-wide so two caches (or a
52/// cache and a restored clone of itself from another moment) never share a
53/// value by accident: a device mirror keyed by (generation, rows) can then tell
54/// "the rows I hold" from "the same number of different rows".
55static KV_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
56
57fn next_gen() -> u64 {
58    KV_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
59}
60
61/// Per-layer O(1) Nyström attention state (runtime `attn_type`
62/// override — spec §7 presence-driven pattern, no format change).
63///
64/// Collecting: the prompt pass still runs EXACT cache attention (the
65/// prefill outputs feed the residual stream, so they cannot be
66/// deferred) while the per-position rotated queries are buffered;
67/// `o1_seal()` then freezes landmarks + M from the full prompt, replays
68/// it into per-KV-group streaming states, and DROPS the full KV.
69/// Sealed: decode replaces cache attention with
70/// `NystromState::step_group()`.
71#[derive(Debug, Clone)]
72pub enum O1State {
73    Collecting {
74        m: usize,
75        w: usize,
76        sink: usize,
77        rect: crate::nystrom::O1Rect,
78        /// Optional completed-row barrier. `None` means the caller will
79        /// request a full-prompt seal; `Some(B)` keeps a short prompt exact
80        /// until the first skeleton-safe boundary B.
81        seal_at: Option<usize>,
82        /// Rotated post-norm queries, `[pos × num_heads × head_dim]`.
83        q_buf: Vec<f32>,
84    },
85    /// One state per KV GROUP, each holding its group's Q heads. The
86    /// exact window / sinks / K̃ are stored once per group (every Q head
87    /// of the group reads the same k/v rows); only the far field, Q̃ and
88    /// M — the query-dependent pieces — stay per Q head. See
89    /// `NystromState` for which piece is which and why.
90    Sealed {
91        groups: Vec<crate::nystrom::NystromState>,
92    },
93}
94
95/// KV cache for a single layer, head-major.
96#[derive(Debug, Clone)]
97pub struct LayerKvCache {
98    pub mode: KvMode,
99    /// Per-KV-head keys: `k[h]` is `[seq_len × head_dim]` (empty if head is dead).
100    k: Vec<Vec<f32>>,
101    /// Per-KV-head values, same layout.
102    v: Vec<Vec<f32>>,
103    /// q8 storage (mode == Q8_2F): int8 rows + f32 scale per row.
104    kq: Vec<Vec<i8>>,
105    ks: Vec<Vec<f32>>,
106    vq: Vec<Vec<i8>>,
107    vs: Vec<Vec<f32>>,
108    /// Per-channel scale fields per head [head_dim]; empty until frozen.
109    kcol: Vec<Vec<f32>>,
110    vcol: Vec<Vec<f32>>,
111    /// Accumulated attention mass per stored position: importance of a
112    /// position is how much probability mass reads it.
113    imp: Vec<f32>,
114    /// Rows stored (grows once per token, dead heads included). Stored
115    /// row 0 is absolute position `base`, so this equals the context depth
116    /// only while `base == 0`; [`Self::pos_len`] is the depth. Every attend
117    /// indexes rows, never positions (eviction made this a row count long
118    /// before `trim_window` did).
119    pub seq_len: usize,
120    /// Absolute position of stored row 0. Only `trim_window` advances it;
121    /// 0 on every layer that was never trimmed.
122    base: usize,
123    /// The attend window of a layer that keeps only its tail
124    /// (`trim_window`), set by the first call. A property of the layer,
125    /// not of the conversation: `clear()` keeps it. Such a layer bounds
126    /// itself, so the cache-wide eviction leaves it alone.
127    tail: Option<usize>,
128    /// Storage generation: a fresh value on every mutation other than
129    /// `append` and `truncate_last` (clear, trim, eviction, wire import,
130    /// resets). A device mirror that copies these rows keys its validity on
131    /// (generation, rows): a trimmed layer's row count is periodic (576..639 for a
132    /// 512 window), so the count alone can match a different set of rows.
133    /// Appends and rollbacks show up in the count, and the speculative
134    /// paths re-point their mirrors themselves, so they keep the value.
135    generation: u64,
136    pub num_kv_heads: usize,
137    pub head_dim: usize,
138    /// Linear-core recurrent state S (vmf_phase), f64; empty on full layers.
139    pub linear_state: Vec<f32>,
140    /// Tentative lane-2 state during speculative verify.
141    pub linear_scratch: Vec<f32>,
142    /// The legacy cache wire has no operator tag. Delta operators therefore
143    /// bind this layer to a fail-closed boundary until a versioned wire
144    /// schema can carry the linear-core identity.
145    linear_wire_allowed: bool,
146    /// O(1) Nyström override (None = plain cache attention).
147    pub o1: Option<O1State>,
148    /// A deferred seal failure is terminal for the current request. The
149    /// attention functions return only a hidden vector, so the pipeline
150    /// consumes this side channel at its next forward boundary.
151    o1_error: Option<String>,
152    /// Rows the next seal keeps exact, ascending.
153    pub(crate) o1_keep: Vec<usize>,
154    /// The pipeline chooses the exact rows over every far-field layer once all of
155    /// them hold the boundary's rows (`o1_choose_exact_rows`), and seals then: the
156    /// layer does not convert itself on reaching the boundary (only before a row
157    /// past it would be appended).
158    pub(crate) o1_await_keep: bool,
159    /// One row in this many is in the query trace.
160    o1_q_stride: usize,
161    /// The geometry of the last `o1_begin`.
162    o1_params: Option<(usize, usize, usize, crate::nystrom::O1Rect)>,
163    /// Set when a collecting state actually becomes sealed. Pipeline owns
164    /// the epoch bump and consumes this bit after a complete forward.
165    o1_transitioned: bool,
166    /// Learned per-Q-head attention-sink logits of this layer (gpt-oss /
167    /// MiMo-V2 `self_attn.sinks`, one f32 per Q head). The sink is an
168    /// extra softmax column with no value: it joins the max and the
169    /// denominator of every head's softmax and so lets a head attend to
170    /// "nothing". These are WEIGHTS, not sequence state — `clear()` and
171    /// the wire import keep them. None = an ordinary softmax.
172    pub sinks: Option<Vec<f32>>,
173    /// Natively bounded anchor (`swa_sink_v1`): a fixed-size ring
174    /// installed from the header at load, never per prompt. A layer that
175    /// carries it stores NOTHING per position (`k`/`v` stay empty).
176    pub bounded: Option<crate::bounded::BoundedState>,
177    /// Which state record this layer exchanges on the wire (v2).
178    pub wire_kind: WireKind,
179    /// This layer's index in the stack (the wire header names it).
180    pub wire_layer: u32,
181    /// hash64 of the model's operator identity
182    /// (`ModelArch::linear_core_identity` JSON); 0 = no operator record.
183    pub wire_identity: u64,
184    /// `kv_abs_max`'s running answer: max |x| over the f32 K rows and over
185    /// the V rows `[0, kv_amax_rows)` of every head (+inf once one was inf
186    /// or NaN).
187    kv_amax: [f32; 2],
188    kv_amax_rows: usize,
189}
190
191/// State-record kind of the versioned cache wire (`export_wire` v2).
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193#[repr(u8)]
194pub enum WireKind {
195    /// Per-position K/V (+ importance) — the legacy body.
196    Full = 0,
197    /// Recurrent state vector (S + conv ring), f32.
198    Linear = 1,
199    /// Bounded anchor: insert counter + ring K/V.
200    Bounded = 2,
201    /// A full layer that stores only its tail (`trim_window`): `base` as
202    /// u64, then the `Full` body of the stored rows. Sent only when
203    /// `base > 0`, so an untrimmed record is byte-identical to `Full`; a
204    /// peer that predates it refuses it as an unknown kind instead of
205    /// reading the tail as a whole history.
206    FullTail = 3,
207}
208
209impl WireKind {
210    fn from_u8(v: u8) -> Option<Self> {
211        match v {
212            0 => Some(WireKind::Full),
213            1 => Some(WireKind::Linear),
214            2 => Some(WireKind::Bounded),
215            3 => Some(WireKind::FullTail),
216            _ => None,
217        }
218    }
219}
220
221/// Magic of the versioned state wire.
222pub const WIRE_MAGIC: &[u8; 4] = b"CMFS";
223/// Current wire version.
224pub const WIRE_VERSION: u32 = 2;
225
226/// A layer's exact rows, for the choice of those a seal keeps.
227pub(crate) struct GroupRows<'a> {
228    k: &'a [Vec<f32>],
229    v: &'a [Vec<f32>],
230    hd: usize,
231}
232
233impl crate::dory::LayerRows for GroupRows<'_> {
234    fn key(&self, kh: usize, r: usize) -> &[f32] {
235        &self.k[kh][r * self.hd..(r + 1) * self.hd]
236    }
237    fn value(&self, kh: usize, r: usize) -> &[f32] {
238        &self.v[kh][r * self.hd..(r + 1) * self.hd]
239    }
240}
241
242impl LayerKvCache {
243    pub(crate) fn o1_set_q_stride(&mut self, stride: usize) {
244        self.o1_q_stride = stride.max(1);
245    }
246
247    /// The whole query trace at once, `[rows / stride][num_heads][hd]`.
248    pub(crate) fn o1_set_q_trace(&mut self, q: Vec<f32>) {
249        if let Some(O1State::Collecting { q_buf, .. }) = &mut self.o1 {
250            *q_buf = q;
251        }
252    }
253
254    /// Back to collecting over rows kept in host memory, `[rows][nkv][hd]`: the next
255    /// seal builds this layer's far field anew from them.
256    pub(crate) fn o1_recollect(&mut self, k: &[f32], v: &[f32], q: Vec<f32>, stride: usize, rows: usize) -> bool {
257        let Some(O1State::Sealed { .. }) = &self.o1 else { return false };
258        let (hd, nk) = (self.head_dim, self.num_kv_heads);
259        if self.o1_params.is_none() {
260            return false;
261        }
262        let (m, w, sink, rect) = self.o1_params.unwrap();
263        for g in 0..nk {
264            let mut kg = Vec::with_capacity(rows * hd);
265            let mut vg = Vec::with_capacity(rows * hd);
266            for r in 0..rows {
267                kg.extend_from_slice(&k[(r * nk + g) * hd..(r * nk + g + 1) * hd]);
268                vg.extend_from_slice(&v[(r * nk + g) * hd..(r * nk + g + 1) * hd]);
269            }
270            self.k[g] = kg;
271            self.v[g] = vg;
272        }
273        self.seq_len = rows;
274        self.o1_q_stride = stride.max(1);
275        self.o1_keep.clear();
276        self.o1 = Some(O1State::Collecting { m, w, sink, rect, seal_at: Some(rows), q_buf: q });
277        true
278    }
279
280    pub(crate) fn o1_is_collecting(&self) -> bool {
281        matches!(self.o1, Some(O1State::Collecting { .. }))
282    }
283
284    pub(crate) fn group_rows(&self) -> GroupRows<'_> {
285        GroupRows { k: &self.k, v: &self.v, hd: self.head_dim }
286    }
287
288    pub fn new(num_kv_heads: usize, head_dim: usize) -> Self {
289        Self {
290            sinks: None,
291            mode: KvMode::from_env(),
292            k: vec![Vec::new(); num_kv_heads],
293            v: vec![Vec::new(); num_kv_heads],
294            kq: vec![Vec::new(); num_kv_heads],
295            ks: vec![Vec::new(); num_kv_heads],
296            vq: vec![Vec::new(); num_kv_heads],
297            vs: vec![Vec::new(); num_kv_heads],
298            kcol: vec![Vec::new(); num_kv_heads],
299            vcol: vec![Vec::new(); num_kv_heads],
300            imp: Vec::new(),
301            seq_len: 0,
302            base: 0,
303            tail: None,
304            generation: next_gen(),
305            num_kv_heads,
306            head_dim,
307            linear_state: Vec::new(),
308            linear_scratch: Vec::new(),
309            linear_wire_allowed: true,
310            o1: None,
311            o1_error: None,
312            o1_keep: Vec::new(),
313            o1_await_keep: false,
314            o1_q_stride: 1,
315            o1_params: None,
316            o1_transitioned: false,
317            bounded: None,
318            wire_kind: WireKind::Full,
319            wire_layer: 0,
320            wire_identity: 0,
321            kv_amax: [0.0; 2],
322            kv_amax_rows: 0,
323        }
324    }
325
326    /// (max |k|, max |v|) over every K and over every V entry the cache
327    /// stores in f32, +inf when one is inf or NaN: what the wgpu prefill
328    /// compares with f16's range before its matrix-unit attention casts
329    /// these rows to f16. Lazy — it scans only the rows appended since the
330    /// last call; every other change to the rows (truncate, evict, clear,
331    /// import, an o1 seal) moves the scanned mark back
332    /// (`kv_rows_changed`), and a scan from the first row starts afresh.
333    pub(crate) fn kv_abs_max(&mut self) -> (f32, f32) {
334        let hd = self.head_dim.max(1);
335        let rows = self.kv_rows();
336        if rows < self.kv_amax_rows {
337            self.kv_amax_rows = 0;
338        }
339        if self.kv_amax_rows == 0 {
340            self.kv_amax = [0.0; 2];
341        }
342        let from = self.kv_amax_rows * hd;
343        for (m, heads) in self.kv_amax.iter_mut().zip([&self.k, &self.v]) {
344            for x in heads.iter().filter(|x| x.len() > from) {
345                *m = m.max(crate::gpu::abs_max_or_inf(&x[from..]));
346            }
347        }
348        self.kv_amax_rows = rows;
349        (self.kv_amax[0], self.kv_amax[1])
350    }
351
352    /// `kv_abs_max` for a caller that took the maxima of the rows it just
353    /// appended itself: `chunk` = (from, upto, max |k|, max |v|) over the
354    /// rows `[from, upto)`. Folded in without a scan when the cache holds
355    /// exactly `upto` rows and every row before `from` was scanned; else
356    /// the plain scan.
357    pub(crate) fn kv_abs_max_after(&mut self, chunk: (usize, usize, f32, f32)) -> (f32, f32) {
358        let (from, upto, km, vm) = chunk;
359        if self.kv_amax_rows != from || self.kv_rows() != upto || from > upto {
360            return self.kv_abs_max();
361        }
362        if from == 0 {
363            self.kv_amax = [0.0; 2];
364        }
365        self.kv_amax = [self.kv_amax[0].max(km), self.kv_amax[1].max(vm)];
366        self.kv_amax_rows = upto;
367        (self.kv_amax[0], self.kv_amax[1])
368    }
369
370    /// Rows any head stores.
371    fn kv_rows(&self) -> usize {
372        let hd = self.head_dim.max(1);
373        self.k
374            .iter()
375            .chain(&self.v)
376            .map(|x| x.len() / hd)
377            .max()
378            .unwrap_or(0)
379    }
380
381    /// Rows from `first` on may no longer be the ones `kv_abs_max` scanned.
382    fn kv_rows_changed(&mut self, first: usize) {
383        self.kv_amax_rows = self.kv_amax_rows.min(first);
384    }
385
386    // ── Natively bounded anchor (swa_sink_v1) ──
387
388    /// Give this layer its fixed-size ring (`[kvh][window][hd]` K and V).
389    /// Called once at load from the header; the record is zeroed on
390    /// `clear()` and never reallocated.
391    pub fn install_bounded(&mut self, window: usize) {
392        self.bounded = Some(crate::bounded::BoundedState::new(
393            self.num_kv_heads,
394            self.head_dim,
395            window,
396        ));
397        self.wire_kind = WireKind::Bounded;
398    }
399
400    /// One position of the bounded operator: insert the raw `k, v`
401    /// (`[kvh][hd]`) into slot `t mod W`, then attend every Q head of
402    /// `q` (`[nh][hd]`, raw) over sinks ∪ window into `out` (`[nh][hd]`).
403    /// Nothing is appended per position.
404    #[allow(clippy::too_many_arguments)]
405    pub fn bounded_step(
406        &mut self,
407        q: &[f32],
408        k: &[f32],
409        v: &[f32],
410        w: &crate::bounded::BoundedWeights,
411        rope: &crate::bounded::BoundedRope,
412        scale: f32,
413        num_heads: usize,
414        out: &mut [f32],
415    ) {
416        let st = self
417            .bounded
418            .as_mut()
419            .expect("bounded_step on a layer without an installed ring");
420        st.insert(k, v);
421        st.attend(q, num_heads, &w.sink_k, &w.sink_v, w.sink, &w.group_windows, rope, scale, out);
422        // Honest context depth for the memory/seq report — nothing is
423        // stored per position.
424        self.seq_len += 1;
425    }
426
427    /// Bytes of the bounded ring (0 on other layers).
428    pub fn bounded_state_bytes(&self) -> usize {
429        self.bounded.as_ref().map(|b| b.state_bytes()).unwrap_or(0)
430    }
431
432    /// Bit-for-bit copy of the ring for speculation (None on other layers).
433    pub fn bounded_snapshot(&self) -> Option<crate::bounded::BoundedSnapshot> {
434        self.bounded.as_ref().map(|b| b.snapshot())
435    }
436
437    /// Restore a ring snapshot taken on this layer; `seq_len` follows the
438    /// restored insert counter.
439    pub fn bounded_restore(&mut self, s: &crate::bounded::BoundedSnapshot) {
440        if let Some(b) = self.bounded.as_mut() {
441            b.restore(s);
442            self.seq_len = b.seen;
443            self.generation = next_gen();
444        }
445    }
446
447    /// Bind this layer to the legacy cache-wire policy. Delta layers must
448    /// refuse untagged state exchange rather than risk a plausible additive
449    /// interpretation on the peer.
450    pub fn set_linear_wire_allowed(&mut self, allowed: bool) {
451        self.linear_wire_allowed = allowed;
452    }
453
454    /// Discard tentative recurrent state after a speculative rejection or
455    /// any other path that abandons the lane-2 result.
456    pub fn discard_linear_scratch(&mut self) {
457        self.linear_scratch.clear();
458    }
459
460    /// Per-KV-head stored keys `[seq_len × head_dim]` (GPU token graph
461    /// sync): the stored tail, row 0 = position `base()`.
462    pub fn k_heads(&self) -> &[Vec<f32>] {
463        &self.k
464    }
465    /// Per-KV-head stored values `[seq_len × head_dim]`, row 0 = `base()`.
466    pub fn v_heads(&self) -> &[Vec<f32>] {
467        &self.v
468    }
469
470    // ── Sliding-window tail (trim_window) ──
471
472    /// Absolute position of stored row 0 (0 unless `trim_window` dropped
473    /// a prefix).
474    pub fn base(&self) -> usize {
475        self.base
476    }
477
478    /// Absolute context depth: the position the next append will hold.
479    pub fn pos_len(&self) -> usize {
480        self.base + self.seq_len
481    }
482
483    /// Storage generation (see the field): with the row count, the key a
484    /// device copy of these rows is valid under.
485    pub fn generation(&self) -> u64 {
486        self.generation
487    }
488
489    /// The window this layer trims to, once `trim_window` ran on it.
490    pub fn tail_window(&self) -> Option<usize> {
491        self.tail
492    }
493
494    /// Drop the rows a sliding-window layer can never read again. A query
495    /// at position p reads p−w+1..=p only, so once more than `2w` rows are
496    /// stored the front is drained down to `w + slack` rows, the cut
497    /// rounded DOWN to an absolute position that is a multiple of `align`
498    /// (so `w + slack ..= w + slack + align − 1` rows stay). Returns the
499    /// rows dropped.
500    ///
501    /// The rows that stay keep their order and values (`Vec::drain` of the
502    /// front), and every attend indexes rows relative to the newest one
503    /// (`first = rows − w`), so each later query sees the very rows it saw
504    /// untrimmed — bit for bit. `slack` rows past the window are what a
505    /// rollback (`truncate_last`) may take back without losing a row the
506    /// window needs. `align` keeps device GEMMs that reduce over the rows
507    /// from row 0 in fixed tiles on the tile grid they had untrimmed (the
508    /// dropped rows were whole all-zero tiles there).
509    ///
510    /// Callers trim only at a safe point: never between a call's appends
511    /// and its attend or importance accumulation (a prefill chunk appends
512    /// all its rows first and indexes them from the count it started at).
513    ///
514    /// No-op on an O(1) or bounded layer (they own their bound), and on a
515    /// q8 layer whose per-channel field is not frozen yet: the freeze
516    /// reads every stored row, so dropping one before it would change it.
517    pub fn trim_window(&mut self, w: usize, slack: usize, align: usize) -> usize {
518        self.trim_window_anchored(w, slack, align, usize::MAX)
519    }
520
521    /// `trim_window` that also keeps every row a rollback to `anchor −
522    /// slack` or later still reads (the cut never passes `anchor − w −
523    /// slack`). The pipeline anchors at the current turn's prompt end, so
524    /// the next chat turn can drop the whole answer however long it ran
525    /// (`Pipeline::rollback_prefix_len`); `usize::MAX` is the plain trim.
526    pub fn trim_window_anchored(
527        &mut self,
528        w: usize,
529        slack: usize,
530        align: usize,
531        anchor: usize,
532    ) -> usize {
533        if self.o1.is_some() || self.bounded.is_some() || w == 0 {
534            return 0;
535        }
536        self.tail = Some(w);
537        if self.seq_len <= 2 * w {
538            return 0;
539        }
540        if matches!(self.mode, KvMode::Q8 { .. })
541            && self.kcol.iter().all(Vec::is_empty)
542            && self.vcol.iter().all(Vec::is_empty)
543        {
544            return 0;
545        }
546        let align = align.max(1);
547        let keep_from = self
548            .pos_len()
549            .saturating_sub(w + slack)
550            .min(anchor.saturating_sub(w + slack));
551        let new_base = keep_from / align * align;
552        if new_base <= self.base {
553            return 0;
554        }
555        let d = new_base - self.base;
556        let hd = self.head_dim;
557        fn drop_front<T>(v: &mut Vec<T>, n: usize) {
558            let n = n.min(v.len());
559            v.drain(..n);
560        }
561        for h in 0..self.num_kv_heads {
562            drop_front(&mut self.k[h], d * hd);
563            drop_front(&mut self.v[h], d * hd);
564            drop_front(&mut self.kq[h], d * hd);
565            drop_front(&mut self.vq[h], d * hd);
566            drop_front(&mut self.ks[h], d * hd.div_ceil(KV_K_GROUP));
567            drop_front(&mut self.vs[h], d);
568        }
569        drop_front(&mut self.imp, d);
570        self.base = new_base;
571        self.seq_len -= d;
572        self.generation = next_gen();
573        // `kv_abs_max` counts its scanned mark from the old row 0. Moved
574        // with the rows, the next scan still starts at the first row it has
575        // not seen; left in place, rows appended after the trim up to the
576        // old mark would never be scanned. The maxima may keep a dropped
577        // row's value, which only over-states.
578        self.kv_amax_rows = self.kv_amax_rows.saturating_sub(d);
579        d
580    }
581
582    // ── O(1) Nyström override ──
583
584    /// Arm query collection for a fresh prompt pass (a cleared cache).
585    pub fn o1_begin(&mut self, m: usize, w: usize, sink: usize, rect: crate::nystrom::O1Rect) {
586        self.o1_begin_with_boundary(m, w, sink, rect, None);
587    }
588
589    /// Arm query collection with an optional completed-row seal barrier.
590    /// The barrier is deliberately part of the existing collecting state:
591    /// no second history or scheduler is introduced for short prompts.
592    pub(crate) fn o1_begin_with_boundary(
593        &mut self,
594        m: usize,
595        w: usize,
596        sink: usize,
597        rect: crate::nystrom::O1Rect,
598        seal_at: Option<usize>,
599    ) {
600        self.o1 = Some(O1State::Collecting {
601            m,
602            w,
603            sink,
604            rect,
605            seal_at,
606            q_buf: Vec::new(),
607        });
608        self.o1_keep.clear();
609        self.o1_await_keep = false;
610        self.o1_q_stride = 1;
611        self.o1_params = Some((m, w, sink, rect));
612        self.o1_error = None;
613        self.o1_transitioned = false;
614    }
615
616    /// Record one position's rotated queries (`[num_heads × head_dim]`)
617    /// during the exact prompt pass. No-op unless collecting — the hook
618    /// sits inside qwen_attention so every prefill flavor (sequential,
619    /// batched) feeds the same trace.
620    pub fn o1_push_q(&mut self, q_all: &[f32]) {
621        if let Some(O1State::Collecting { q_buf, .. }) = &mut self.o1 {
622            q_buf.extend_from_slice(q_all);
623        }
624    }
625
626    /// The rotated-query trace collected so far (`[rows × num_heads ×
627    /// head_dim]`), while collecting.
628    pub(crate) fn o1_q_trace(&self) -> Option<&[f32]> {
629        match &self.o1 {
630            Some(O1State::Collecting { q_buf, .. }) => Some(q_buf),
631            _ => None,
632        }
633    }
634
635    /// Move a collecting layer's deferred boundary (the seal diagnostics
636    /// collect past it, then seal at the row count they choose).
637    pub(crate) fn o1_set_boundary(&mut self, at: usize) {
638        if let Some(O1State::Collecting { seal_at, .. }) = &mut self.o1 {
639            *seal_at = Some(at);
640        }
641    }
642
643    pub fn o1_sealed(&self) -> bool {
644        matches!(self.o1, Some(O1State::Sealed { .. }))
645    }
646
647    /// Pending completed-row barrier, if any. A plain full-prompt seal has
648    /// no barrier until the caller asks to seal.
649    pub(crate) fn o1_pending_boundary(&self) -> Option<usize> {
650        match &self.o1 {
651            Some(O1State::Collecting { seal_at, .. }) => *seal_at,
652            _ => None,
653        }
654    }
655
656    /// Whether a batch of `count` exact rows would cross the deferred
657    /// boundary. This lets batched/pair callers split before row B rather
658    /// than appending exact KV past the point where conversion is required.
659    /// A batch that ends exactly on the boundary crosses nothing: all its
660    /// rows are exact, and the caller seals after it. `CMF_O1_WALK_BOUNDARY=1`
661    /// walks such a batch row by row as before.
662    pub(crate) fn o1_boundary_crossed_by(&self, count: usize) -> bool {
663        static WALK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
664        let walk =
665            *WALK.get_or_init(|| std::env::var("CMF_O1_WALK_BOUNDARY").as_deref() == Ok("1"));
666        let Some(target) = self.o1_pending_boundary() else {
667            return false;
668        };
669        target <= self.seq_len
670            || self
671                .seq_len
672                .checked_add(count)
673                .map_or(true, |next| next > target || (walk && next == target))
674    }
675
676    pub(crate) fn take_o1_transition(&mut self) -> bool {
677        std::mem::take(&mut self.o1_transitioned)
678    }
679
680    pub(crate) fn take_o1_error(&self) -> Option<String> {
681        // Error observation is deliberately non-consuming.  The error is the
682        // append guard for this request; removing it would let a caller that
683        // ignored the returned Err resume ordinary KV growth after the
684        // bounded transition dropped its overlay.  `clear()` is the explicit
685        // reset boundary that clears the latch.
686        self.o1_error.clone()
687    }
688
689    /// Abort a malformed deferred transition after attention has already
690    /// produced its current row. Clearing the exact storage and dropping
691    /// the overlay makes the state unrecoverable by continued decode; the
692    /// pipeline then routes through its normal graph/cancel cleanup.
693    pub(crate) fn o1_abort(&mut self, err: String) {
694        self.k.iter_mut().for_each(Vec::clear);
695        self.v.iter_mut().for_each(Vec::clear);
696        self.kv_rows_changed(0);
697        self.kq.iter_mut().for_each(Vec::clear);
698        self.ks.iter_mut().for_each(Vec::clear);
699        self.vq.iter_mut().for_each(Vec::clear);
700        self.vs.iter_mut().for_each(Vec::clear);
701        self.kcol.iter_mut().for_each(Vec::clear);
702        self.vcol.iter_mut().for_each(Vec::clear);
703        self.imp.clear();
704        self.o1 = None;
705        self.seq_len = 0;
706        self.base = 0;
707        self.generation = next_gen();
708        self.o1_transitioned = false;
709        self.o1_error = Some(err);
710    }
711
712    /// Freeze the prompt into per-KV-group Nyström states and drop this
713    /// layer's full KV. Returns false while a short collecting layer is
714    /// below its deferred boundary; malformed prerequisites abort the
715    /// layer instead of silently resuming exact KV growth. The seal needs
716    /// f32 KV rows (`CMF_KV=q8` stores int8), every group densely stored, a
717    /// full q trace, and a GQA fan-out that actually divides.
718    pub fn o1_seal(&mut self, num_heads: usize) -> bool {
719        match self.o1_seal_checked(num_heads) {
720            Ok(sealed) => sealed,
721            Err(err) => {
722                tracing::error!("o1: seal aborted: {err}");
723                self.o1_abort(err);
724                false
725            }
726        }
727    }
728
729    /// Checked seal implementation. Validation happens while the collecting
730    /// state and full KV are still intact; only a valid completed boundary
731    /// is allowed to destructively convert them.
732    pub(crate) fn o1_seal_checked(&mut self, num_heads: usize) -> Result<bool, String> {
733        if let Some(err) = self.o1_error.clone() {
734            return Err(err);
735        }
736        // Idempotent: sealing a sealed (or plain) layer must not disturb its
737        // state, and a plain layer is not an O(1) participant.
738        if !matches!(self.o1, Some(O1State::Collecting { .. })) {
739            return Ok(self.o1_sealed());
740        }
741        let (m, w, sink, requested_boundary, q_len) = match &self.o1 {
742            Some(O1State::Collecting {
743                m,
744                w,
745                sink,
746                rect: _,
747                seal_at,
748                q_buf,
749            }) => (*m, *w, *sink, *seal_at, q_buf.len()),
750            _ => unreachable!("checked above"),
751        };
752        let floor = crate::nystrom::o1_deferred_boundary(w, sink)
753            .ok_or_else(|| "o1 seal: w + sink + slack + 1 overflow".to_string())?;
754        let target = requested_boundary.unwrap_or(floor).max(floor);
755        let t = self.seq_len;
756        if t < target {
757            if let Some(O1State::Collecting { seal_at, .. }) = &mut self.o1 {
758                if *seal_at != Some(target) {
759                    *seal_at = Some(target);
760                    tracing::info!(
761                        "o1 deferred seal: current rows={t}, boundary={target} (floor={floor})"
762                    );
763                }
764            }
765            return Ok(false);
766        }
767
768        let hd = self.head_dim;
769        if t == 0 {
770            return Err("o1 seal: cannot seal an empty layer".into());
771        }
772        if self.mode != KvMode::F32 {
773            return Err("o1 seal: requires dense F32 KV storage".into());
774        }
775        if self.num_kv_heads == 0 || num_heads == 0 || num_heads % self.num_kv_heads != 0 {
776            return Err(format!(
777                "o1 seal: invalid GQA geometry num_heads={num_heads} num_kv_heads={}",
778                self.num_kv_heads
779            ));
780        }
781        let hpk = num_heads / self.num_kv_heads;
782        let expected_k = t
783            .checked_mul(hd)
784            .ok_or_else(|| "o1 seal: KV row length overflow".to_string())?;
785        let stride = self.o1_q_stride;
786        let expected_q = t
787            .div_ceil(stride)
788            .checked_mul(hd)
789            .and_then(|v| v.checked_mul(num_heads))
790            .ok_or_else(|| "o1 seal: query trace length overflow".to_string())?;
791        if q_len != expected_q {
792            return Err(format!(
793                "o1 seal: query trace has {q_len} values, expected {expected_q}"
794            ));
795        }
796        if (0..self.num_kv_heads)
797            .any(|g| self.k[g].len() != expected_k || self.v[g].len() != expected_k)
798        {
799            return Err("o1 seal: KV heads are not densely populated".into());
800        }
801        if m < 4 || w == 0 {
802            return Err(format!("o1 seal: invalid geometry m={m} w={w}"));
803        }
804
805        let Some(O1State::Collecting {
806            m,
807            w,
808            sink,
809            rect,
810            q_buf,
811            ..
812        }) = self.o1.take()
813        else {
814            unreachable!("collecting state disappeared after validation");
815        };
816        // One KV group's state depends on that group's rows alone, so the
817        // groups seal on their own threads: the replay of every prompt row
818        // into the far field is the host's share of a turbo prompt (7 s of
819        // 33 for 16 000 tokens on an RTX 2000 Ada before this), and it ran
820        // one group after another. Each thread transposes its own group of
821        // the position-major query trace (the state wants each head's
822        // queries contiguous).
823        let wire_layer = self.wire_layer;
824        let keep = &self.o1_keep;
825        let (ks, vs) = (&self.k, &self.v);
826        let q_buf = &q_buf;
827        // the far rows' sums on the card when it can take them (CUDA): the host
828        // seals each group from its rows by index, without the replay, and the
829        // card sums the far rows
830        let t_seal0 = std::time::Instant::now();
831        let dev = crate::gpu::o1_far_sums_on() && std::env::var_os("CMF_O1_CAPTURE").is_none();
832        let order: Vec<u32> = if keep.is_empty() { (0..t as u32).collect() } else { crate::dory::seal_order(t, sink, keep) };
833        let order = &order;
834        type Sealed = (crate::nystrom::NystromState, Option<std::ops::Range<usize>>);
835        let seal_group = move |g: usize| -> Sealed {
836            let calib = crate::nystrom::O1Calib::load(wire_layer, g, hd, hpk);
837            let wg = crate::nystrom::wide_window(wire_layer, g).unwrap_or(w);
838            let mut st = crate::nystrom::NystromState::new_group(m, w, sink + keep.len(), hpk)
839                .with_landmarks_from(if keep.is_empty() { 0 } else { sink + keep.len() })
840                .with_window(wg)
841                .with_rect(rect)
842                .with_calib(calib);
843            if dev {
844                if let Some(range) = st.seal_gathered(&ks[g], &vs[g], q_buf, stride, num_heads, g * hpk, order, t, hd, hd) {
845                    return (st, Some(range));
846                }
847            }
848            let mut qh = vec![0.0f32; hpk * t * hd];
849            for hh in 0..hpk {
850                let h = g * hpk + hh;
851                for p in 0..t {
852                    let src = (p / stride * num_heads + h) * hd;
853                    let dst = (hh * t + p) * hd;
854                    qh[dst..dst + hd].copy_from_slice(&q_buf[src..src + hd]);
855                }
856            }
857            let qs: Vec<&[f32]> = (0..hpk)
858                .map(|hh| &qh[hh * t * hd..(hh + 1) * t * hd])
859                .collect();
860            crate::nystrom::capture_seal(wire_layer, g, t, hd, hpk, &qh, &ks[g], &vs[g]);
861            if keep.is_empty() {
862                st.prefill_group(&qs, &ks[g], &vs[g], t, hd, hd);
863            } else {
864                // The kept rows go right behind the sinks, and leave the far field.
865                let pick = |src: &[f32]| -> Vec<f32> {
866                    let mut out = Vec::with_capacity(t * hd);
867                    for &r in order {
868                        out.extend_from_slice(&src[r as usize * hd..(r as usize + 1) * hd]);
869                    }
870                    out
871                };
872                let qo: Vec<Vec<f32>> = qs.iter().map(|q| pick(q)).collect();
873                let qr: Vec<&[f32]> = qo.iter().map(|q| &q[..]).collect();
874                st.prefill_group(&qr, &pick(&ks[g]), &pick(&vs[g]), t, hd, hd);
875            }
876            (st, None)
877        };
878        let sealed: Vec<Sealed> = if self.num_kv_heads > 1 {
879            std::thread::scope(|s| {
880                let hs: Vec<_> = (0..self.num_kv_heads).map(|g| s.spawn(move || seal_group(g))).collect();
881                hs.into_iter().map(|h| h.join().expect("o1 seal: a group's thread panicked")).collect()
882            })
883        } else {
884            vec![seal_group(0)]
885        };
886        let t_groups = t_seal0.elapsed().as_secs_f64();
887        let (mut groups, fars): (Vec<_>, Vec<_>) = sealed.into_iter().unzip();
888        if fars.iter().any(Option::is_some) {
889            // every group's far rows on the card at once; the host's replay
890            // when the card declines (or the groups' windows differ)
891            let same = fars.iter().all(|f| f.is_some() && f == &fars[0]);
892            let (m_eff, _, scale) = groups[0].far_geometry();
893            let mut done = false;
894            if same && groups.iter().all(|g| g.far_geometry().0 == m_eff) {
895                let range = fars[0].clone().unwrap();
896                let mut qt = Vec::with_capacity(self.num_kv_heads * hpk * m_eff * hd);
897                for g in &groups {
898                    for h in 0..hpk {
899                        qt.extend_from_slice(g.far_q_tilde(h));
900                    }
901                }
902                let kf: Vec<&[f32]> = ks.iter().map(|k| &k[..]).collect();
903                let vf: Vec<&[f32]> = vs.iter().map(|v| &v[..]).collect();
904                if let Some((mz, th)) = crate::gpu::o1_far_sums(self.num_kv_heads, hpk, hd, m_eff, scale, &qt, &order[range.clone()], &kf, &vf) {
905                    for (gi, g) in groups.iter_mut().enumerate() {
906                        for h in 0..hpk {
907                            let hh = gi * hpk + h;
908                            let z = &mz[hh * 2 * m_eff..(hh + 1) * 2 * m_eff];
909                            g.set_far_sums(h, &z[..m_eff], &z[m_eff..], &th[hh * m_eff * hd..(hh + 1) * m_eff * hd], range.len());
910                        }
911                    }
912                    done = true;
913                }
914            }
915            if std::env::var("CMF_PREFILL_PROF").is_ok() {
916                eprintln!("o1 seal of a layer: groups {t_groups:.3} s, far sums {:.3} s ({})", t_seal0.elapsed().as_secs_f64() - t_groups, if done { "card" } else { "host" });
917            }
918            if !done {
919                std::thread::scope(|s| {
920                    for (gi, (g, f)) in groups.iter_mut().zip(&fars).enumerate() {
921                        if let Some(range) = f {
922                            let (k, v) = (&ks[gi][..], &vs[gi][..]);
923                            s.spawn(move || g.replay_far_idx(k, v, &order[range.clone()]));
924                        }
925                    }
926                });
927            }
928        }
929        if std::env::var_os("CMF_O1_SEAL_DIAG").is_some() {
930            let d: Vec<_> = groups.iter().map(|g| g.seal_diag()).collect();
931            let mx = |f: fn(&(f32, f32, f32, f32, f32, bool)) -> f32| d.iter().map(f).fold(0f32, f32::max);
932            eprintln!(
933                "o1 seal diag: layer {} rows {t} kept {} |M| {:.3e} mass {:.3e} numerator {:.3e} |q~| {:.3e} |k~| {:.3e} finite {}",
934                self.wire_layer,
935                self.o1_keep.len(),
936                mx(|x| x.0),
937                mx(|x| x.1),
938                mx(|x| x.2),
939                mx(|x| x.3),
940                mx(|x| x.4),
941                d.iter().all(|x| x.5)
942            );
943        }
944        // The states now carry everything decode needs — release the
945        // O(context) storage (this is the memory claim, not a cosmetic).
946        for h in 0..self.num_kv_heads {
947            self.k[h] = Vec::new();
948            self.v[h] = Vec::new();
949        }
950        self.kv_rows_changed(0);
951        self.imp = Vec::new();
952        self.o1 = Some(O1State::Sealed { groups });
953        self.o1_transitioned = true;
954        Ok(true)
955    }
956
957    /// One decode step on a sealed layer: per KV group, insert the
958    /// group's fresh (k, v) ONCE and read every Q head's attention
959    /// output. Returns `[num_heads × head_dim]`. Head h belongs to group
960    /// h/hpk, so a group's Q heads are contiguous in `q_all`/`out` —
961    /// same math as the shared KV row the exact path appends once.
962    /// Device views of the sealed o1 groups, or None when o1 is not
963    /// sealed on this layer (or any group is in the degenerate
964    /// exact-only mode the GPU path does not carry).
965    pub fn o1_views(&self) -> Option<Vec<crate::nystrom::O1DeviceView<'_>>> {
966        let Some(O1State::Sealed { groups }) = &self.o1 else {
967            return None;
968        };
969        let views: Vec<_> = groups.iter().map(|g| g.device_view()).collect();
970        if views.iter().any(|v| v.exact_only) {
971            return None;
972        }
973        Some(views)
974    }
975
976    pub fn o1_step(
977        &mut self,
978        q_all: &[f32],
979        k_new: &[f32],
980        v_new: &[f32],
981        num_heads: usize,
982    ) -> Vec<f32> {
983        let hd = self.head_dim;
984        let hpk = num_heads / self.num_kv_heads.max(1);
985        let mut out = vec![0.0f32; num_heads * hd];
986        let Some(O1State::Sealed { groups }) = &mut self.o1 else {
987            debug_assert!(false, "o1_step on an unsealed layer");
988            return out;
989        };
990        for (g, st) in groups.iter_mut().enumerate() {
991            let (lo, hi) = (g * hpk * hd, (g + 1) * hpk * hd);
992            st.step_group(
993                &q_all[lo..hi],
994                &k_new[g * hd..(g + 1) * hd],
995                &v_new[g * hd..(g + 1) * hd],
996                &mut out[lo..hi],
997            );
998        }
999        // Track the true context depth for the honest memory/seq report
1000        // (nothing is stored per position — the state is O(1)).
1001        self.seq_len += 1;
1002        out
1003    }
1004
1005    /// Bytes held by the O(1) override (query trace while collecting,
1006    /// per-KV-group states once sealed).
1007    pub fn o1_memory_bytes(&self) -> usize {
1008        match &self.o1 {
1009            Some(O1State::Collecting { q_buf, .. }) => q_buf.len() * std::mem::size_of::<f32>(),
1010            Some(O1State::Sealed { groups }) => groups.iter().map(|s| s.memory_bytes()).sum(),
1011            None => 0,
1012        }
1013    }
1014
1015    /// Quantize one row against the per-channel field (empty col = 1);
1016    /// `group` — elements per scale (the whole row or KV_K_GROUP).
1017    fn quant_row(row: &[f32], col: &[f32], q: &mut Vec<i8>, sc: &mut Vec<f32>, group: usize) {
1018        let mut resid = vec![0.0f32; row.len()];
1019        for (d, &x) in row.iter().enumerate() {
1020            resid[d] = if col.is_empty() { x } else { x / col[d] };
1021        }
1022        for g0 in (0..row.len()).step_by(group) {
1023            let g1 = (g0 + group).min(row.len());
1024            let mut absmax = 0.0f32;
1025            for &r in &resid[g0..g1] {
1026                absmax = absmax.max(r.abs());
1027            }
1028            let s = (absmax / 127.0).max(1e-12);
1029            sc.push(s);
1030            for &r in &resid[g0..g1] {
1031                q.push((r / s).round().clamp(-127.0, 127.0) as i8);
1032            }
1033        }
1034    }
1035
1036    /// Freeze the 2f field: col = RMS of channels over stored rows, old
1037    /// rows are requantized against the new field (once per conversation).
1038    fn freeze_cols(&mut self) {
1039        let hd = self.head_dim;
1040        let ngk = hd.div_ceil(KV_K_GROUP);
1041        for h in 0..self.num_kv_heads {
1042            for (qv, sv, colv, group) in [
1043                (
1044                    &mut self.kq[h],
1045                    &mut self.ks[h],
1046                    &mut self.kcol[h],
1047                    KV_K_GROUP,
1048                ),
1049                (&mut self.vq[h], &mut self.vs[h], &mut self.vcol[h], hd),
1050            ] {
1051                let spp = if group == hd { 1 } else { ngk }; // scales per position
1052                let n = sv.len() / spp;
1053                if n == 0 {
1054                    continue;
1055                }
1056                // Dequantize to f32, RMS over channels, requantize.
1057                let mut rows = vec![0.0f32; n * hd];
1058                for p in 0..n {
1059                    for d in 0..hd {
1060                        rows[p * hd + d] = qv[p * hd + d] as f32 * sv[p * spp + d / group];
1061                    }
1062                }
1063                let mut col = vec![0.0f32; hd];
1064                for p in 0..n {
1065                    for d in 0..hd {
1066                        col[d] += rows[p * hd + d] * rows[p * hd + d];
1067                    }
1068                }
1069                for c in col.iter_mut() {
1070                    *c = (*c / n as f32).sqrt().max(1e-6);
1071                }
1072                qv.clear();
1073                sv.clear();
1074                for p in 0..n {
1075                    Self::quant_row(&rows[p * hd..(p + 1) * hd], &col, qv, sv, group);
1076                }
1077                *colv = col;
1078            }
1079        }
1080    }
1081
1082    /// Append K/V for one position. `k_new`/`v_new` are
1083    /// `[num_kv_heads × head_dim]`; heads with `alive[h] == false` are
1084    /// skipped (their slices stay empty).
1085    /// Room for `rows` more rows of plain f32 storage, taken once: a prompt's
1086    /// rows coming back from a device mirror otherwise grow each head's
1087    /// vectors by doubling, a copy of everything stored so far each time.
1088    pub(crate) fn reserve_rows(&mut self, rows: usize) {
1089        if self.mode != KvMode::F32 {
1090            return;
1091        }
1092        let n = rows * self.head_dim;
1093        for h in 0..self.num_kv_heads {
1094            self.k[h].reserve(n);
1095            self.v[h].reserve(n);
1096        }
1097        self.imp.reserve(rows);
1098    }
1099
1100    pub fn append(&mut self, k_new: &[f32], v_new: &[f32], alive: &[bool]) {
1101        // A failed bounded transition is terminal until the sequence is
1102        // cleared. Do not let an ignored boolean/result resume plain KV
1103        // growth after the O(1) collector has aborted.
1104        if self.o1_error.is_some() {
1105            return;
1106        }
1107        debug_assert_eq!(k_new.len(), self.num_kv_heads * self.head_dim);
1108        debug_assert_eq!(v_new.len(), self.num_kv_heads * self.head_dim);
1109        // Freeze the 2f field AT THE START of append: only rows that
1110        // survived verify are visible (a rejected lane-2 draft does not
1111        // pollute the field — found in review), and the threshold uses >=
1112        // rather than strict equality (in small windows eviction may
1113        // oscillate across 64).
1114        if matches!(self.mode, KvMode::Q8 { .. })
1115            && self.seq_len >= KV_COL_WARMUP
1116            && self.kcol.iter().all(Vec::is_empty)
1117            && self.vcol.iter().all(Vec::is_empty)
1118        {
1119            self.freeze_cols();
1120        }
1121        for h in 0..self.num_kv_heads {
1122            if !alive.get(h).copied().unwrap_or(true) {
1123                continue;
1124            }
1125            let s = h * self.head_dim;
1126            if self.mode.quant_k() {
1127                Self::quant_row(
1128                    &k_new[s..s + self.head_dim],
1129                    &self.kcol[h],
1130                    &mut self.kq[h],
1131                    &mut self.ks[h],
1132                    KV_K_GROUP,
1133                );
1134            } else {
1135                self.k[h].extend_from_slice(&k_new[s..s + self.head_dim]);
1136            }
1137            if self.mode.quant_v() {
1138                Self::quant_row(
1139                    &v_new[s..s + self.head_dim],
1140                    &self.vcol[h],
1141                    &mut self.vq[h],
1142                    &mut self.vs[h],
1143                    self.head_dim,
1144                );
1145            } else {
1146                self.v[h].extend_from_slice(&v_new[s..s + self.head_dim]);
1147            }
1148        }
1149        self.imp.push(0.0);
1150        self.seq_len += 1;
1151    }
1152
1153    /// Per-head attention over its own storage: the f32 branch is
1154    /// bit-for-bit equal to attention_head() over slices; the q8 branch
1155    /// computes score = s_k·⟨q⊙col_k, k_q⟩ and the weighted sum of V in i8
1156    /// with f32 accumulation. Returns (output [head_dim], probs [stored]).
1157    pub fn attend(&self, q: &[f32], kv_head: usize) -> (Vec<f32>, Vec<f32>) {
1158        // Full-context layers only: a trimmed tail is not the whole row.
1159        debug_assert!(self.tail.is_none(), "attend() on a sliding-window tail");
1160        let hd = self.head_dim;
1161        if self.mode == KvMode::F32 {
1162            let stored = self.k[kv_head].len() / hd;
1163            return crate::attention::attention_head(
1164                q,
1165                &self.k[kv_head],
1166                &self.v[kv_head],
1167                hd,
1168                stored,
1169            );
1170        }
1171        let stored = self.head_len(kv_head);
1172        let scale = 1.0 / (hd as f32).sqrt();
1173        let mut scores = vec![0.0f32; stored];
1174        if self.mode.quant_k() {
1175            let (kq, ks) = (&self.kq[kv_head], &self.ks[kv_head]);
1176            // q ⊙ col_k — once per call.
1177            let kcol = &self.kcol[kv_head];
1178            let mut qc = vec![0.0f32; hd];
1179            for d in 0..hd {
1180                qc[d] = if kcol.is_empty() {
1181                    q[d]
1182                } else {
1183                    q[d] * kcol[d]
1184                };
1185            }
1186            let ng = hd.div_ceil(KV_K_GROUP);
1187            for p in 0..stored {
1188                let row = &kq[p * hd..(p + 1) * hd];
1189                // SAFETY: i8 and u8 share layout; dot_i8_f32 reads the
1190                // bytes back as i8.
1191                let row_u8 =
1192                    unsafe { std::slice::from_raw_parts(row.as_ptr() as *const u8, row.len()) };
1193                let mut dot = 0.0f32;
1194                for g in 0..ng {
1195                    let g0 = g * KV_K_GROUP;
1196                    let g1 = (g0 + KV_K_GROUP).min(hd);
1197                    dot +=
1198                        crate::qtensor::dot_i8_f32(&row_u8[g0..g1], &qc[g0..g1]) * ks[p * ng + g];
1199                }
1200                scores[p] = dot * scale;
1201            }
1202        } else {
1203            let k = &self.k[kv_head];
1204            for p in 0..stored {
1205                let row = &k[p * hd..(p + 1) * hd];
1206                scores[p] = crate::attention::dot_f32(q, row) * scale;
1207            }
1208        }
1209        let max_score = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
1210        let mut sum = 0.0f32;
1211        for s in scores.iter_mut() {
1212            *s = (*s - max_score).exp();
1213            sum += *s;
1214        }
1215        if sum > 0.0 {
1216            for s in scores.iter_mut() {
1217                *s /= sum;
1218            }
1219        }
1220        let mut acc = vec![0.0f32; hd];
1221        if self.mode.quant_v() {
1222            let (vq, vs) = (&self.vq[kv_head], &self.vs[kv_head]);
1223            for p in 0..stored {
1224                let w = scores[p] * vs[p];
1225                if w.abs() < 1e-12 {
1226                    continue;
1227                }
1228                crate::qtensor::axpy_i8_f32(&mut acc, &vq[p * hd..(p + 1) * hd], w);
1229            }
1230            let vcol = &self.vcol[kv_head];
1231            if !vcol.is_empty() {
1232                for d in 0..hd {
1233                    acc[d] *= vcol[d];
1234                }
1235            }
1236        } else {
1237            let v = &self.v[kv_head];
1238            for p in 0..stored {
1239                let w = scores[p];
1240                if w.abs() < 1e-12 {
1241                    continue;
1242                }
1243                crate::attention::axpy_f32(&mut acc, &v[p * hd..(p + 1) * hd], w);
1244            }
1245        }
1246        (acc, scores)
1247    }
1248
1249    /// Grouped GQA attention: all Q-heads of one KV group in a single
1250    /// pass over the stored K rows and a single pass over the V rows
1251    /// (per-head `attend` re-read the shared group storage
1252    /// heads_per_kv times — roadmap §3 P1). Per-head score order,
1253    /// softmax and V accumulation are IDENTICAL to `attend`, so each
1254    /// head's output is bit-for-bit the same.
1255    ///
1256    /// `q_group`: `[n_heads_in_group × head_dim]` (global head order);
1257    /// `out`: same shape; `imp_acc[0..stored]` accumulates the probabilities
1258    /// of every head (attention importance), matching the caller's former loop.
1259    /// `scale` is the score scale (1/√hd unless the arch overrides);
1260    /// `first` is the earliest visible position — sliding-window layers
1261    /// pass `stored − window` so older rows get zero probability.
1262    /// `sinks` holds one learned sink logit per head of `q_group` (the
1263    /// caller slices `self.sinks` to the group's heads) or is empty for
1264    /// an ordinary softmax.
1265    #[allow(clippy::too_many_arguments)]
1266    pub fn attend_group(
1267        &self,
1268        q_group: &[f32],
1269        kv_head: usize,
1270        out: &mut [f32],
1271        imp_acc: &mut [f32],
1272        scale: f32,
1273        first: usize,
1274        softcap: f32,
1275        sinks: &[f32],
1276    ) {
1277        self.attend_group_upto(
1278            q_group,
1279            kv_head,
1280            out,
1281            imp_acc,
1282            scale,
1283            first,
1284            softcap,
1285            usize::MAX,
1286            sinks,
1287        )
1288    }
1289
1290    /// `attend_group` over the first `upto` stored rows only — what the
1291    /// same call saw when the cache held exactly `upto` rows. A prefill
1292    /// chunk appends all its rows first and then attends every position
1293    /// in parallel; position `i` passes `upto = s0 + i + 1`, which makes
1294    /// its result bit-identical to the sequential append-then-attend.
1295    ///
1296    /// Only the visible rows `[first, stored)` are scored, so a
1297    /// sliding-window decode step costs O(window), not O(context). The
1298    /// rows before `first` get probability exactly 0 — what the former
1299    /// −inf-filled score row produced (exp(−inf) = 0 adds nothing to the
1300    /// max, the sum, V or the importance), so the result is bit-identical
1301    /// to scoring the whole row.
1302    ///
1303    /// Learned sinks (`sinks` non-empty, one per head): the sink logit
1304    /// joins the softmax max and adds exp(sink − max) to the denominator;
1305    /// it has no value row. Identical to appending a value-less column,
1306    /// which is how gpt-oss and MiMo-V2 define it.
1307    #[allow(clippy::too_many_arguments)]
1308    pub fn attend_group_upto(
1309        &self,
1310        q_group: &[f32],
1311        kv_head: usize,
1312        out: &mut [f32],
1313        imp_acc: &mut [f32],
1314        scale: f32,
1315        first: usize,
1316        softcap: f32,
1317        upto: usize,
1318        sinks: &[f32],
1319    ) {
1320        let hd = self.head_dim;
1321        let nheads = q_group.len() / hd;
1322        debug_assert_eq!(out.len(), nheads * hd);
1323        assert!(
1324            sinks.is_empty() || sinks.len() == nheads,
1325            "attend_group: {} sink logits for {nheads} heads",
1326            sinks.len()
1327        );
1328        let stored = if self.mode == KvMode::F32 {
1329            self.k[kv_head].len() / hd
1330        } else {
1331            self.head_len(kv_head)
1332        }
1333        .min(upto);
1334        if stored == 0 {
1335            out.fill(0.0);
1336            return;
1337        }
1338        let first = first.min(stored.saturating_sub(1));
1339        // Visible span: row p ∈ [first, stored) lives at column p − first.
1340        let span = stored - first;
1341
1342        thread_local! {
1343            /// scores [nheads × span] — reused across layers/tokens.
1344            static GQA_SCORES: std::cell::RefCell<Vec<f32>> =
1345                const { std::cell::RefCell::new(Vec::new()) };
1346            /// q ⊙ col_k per head (q8 K mode).
1347            static GQA_QC: std::cell::RefCell<Vec<f32>> =
1348                const { std::cell::RefCell::new(Vec::new()) };
1349        }
1350
1351        GQA_SCORES.with(|sc| {
1352            let mut scores = sc.borrow_mut();
1353            scores.resize(nheads * span, 0.0);
1354
1355            // ── score pass: each stored K row is read ONCE for all heads.
1356            if self.mode.quant_k() {
1357                let (kq, ks) = (&self.kq[kv_head], &self.ks[kv_head]);
1358                let kcol = &self.kcol[kv_head];
1359                let ng = hd.div_ceil(KV_K_GROUP);
1360                GQA_QC.with(|qc| {
1361                    let mut qcb = qc.borrow_mut();
1362                    qcb.resize(nheads * hd, 0.0);
1363                    for h in 0..nheads {
1364                        for d in 0..hd {
1365                            let qv = q_group[h * hd + d];
1366                            qcb[h * hd + d] = if kcol.is_empty() { qv } else { qv * kcol[d] };
1367                        }
1368                    }
1369                    for p in first..stored {
1370                        let row = &kq[p * hd..(p + 1) * hd];
1371                        // SAFETY: i8 and u8 share layout; dot_i8_f32 reads
1372                        // the bytes back as i8.
1373                        let row_u8 = unsafe {
1374                            std::slice::from_raw_parts(row.as_ptr() as *const u8, row.len())
1375                        };
1376                        for h in 0..nheads {
1377                            let qch = &qcb[h * hd..(h + 1) * hd];
1378                            let mut dot = 0.0f32;
1379                            for g in 0..ng {
1380                                let g0 = g * KV_K_GROUP;
1381                                let g1 = (g0 + KV_K_GROUP).min(hd);
1382                                dot += crate::qtensor::dot_i8_f32(&row_u8[g0..g1], &qch[g0..g1])
1383                                    * ks[p * ng + g];
1384                            }
1385                            scores[h * span + (p - first)] = dot * scale;
1386                        }
1387                    }
1388                });
1389            } else {
1390                let k = &self.k[kv_head];
1391                for p in first..stored {
1392                    let row = &k[p * hd..(p + 1) * hd];
1393                    for h in 0..nheads {
1394                        scores[h * span + (p - first)] =
1395                            crate::attention::dot_f32(&q_group[h * hd..(h + 1) * hd], row) * scale;
1396                    }
1397                }
1398            }
1399
1400            // Gemma-2 attention-logit soft-capping: tanh-squash the
1401            // COMPUTED scores before the softmax (every scored row is in
1402            // the window; a learned sink is not a score and is not capped).
1403            if softcap > 0.0 {
1404                for v in scores.iter_mut() {
1405                    *v = softcap * (*v / softcap).tanh();
1406                }
1407            }
1408
1409            // ── per-head softmax (identical to attend / attention_head;
1410            // a sink joins the max and the denominator, never the rows).
1411            for h in 0..nheads {
1412                let s = &mut scores[h * span..(h + 1) * span];
1413                let row_max = s.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
1414                let sink = sinks.get(h).copied();
1415                let max_score = match sink {
1416                    Some(z) => row_max.max(z),
1417                    None => row_max,
1418                };
1419                let mut sum = 0.0f32;
1420                for v in s.iter_mut() {
1421                    *v = (*v - max_score).exp();
1422                    sum += *v;
1423                }
1424                if let Some(z) = sink {
1425                    sum += (z - max_score).exp();
1426                }
1427                if sum > 0.0 {
1428                    for v in s.iter_mut() {
1429                        *v /= sum;
1430                    }
1431                }
1432            }
1433
1434            // ── value pass: each stored V row is read ONCE for all heads.
1435            out.fill(0.0);
1436            if self.mode.quant_v() {
1437                let (vq, vs) = (&self.vq[kv_head], &self.vs[kv_head]);
1438                for p in first..stored {
1439                    let row = &vq[p * hd..(p + 1) * hd];
1440                    for h in 0..nheads {
1441                        let w = scores[h * span + (p - first)] * vs[p];
1442                        if w.abs() < 1e-12 {
1443                            continue;
1444                        }
1445                        crate::qtensor::axpy_i8_f32(&mut out[h * hd..(h + 1) * hd], row, w);
1446                    }
1447                }
1448                let vcol = &self.vcol[kv_head];
1449                if !vcol.is_empty() {
1450                    for h in 0..nheads {
1451                        for d in 0..hd {
1452                            out[h * hd + d] *= vcol[d];
1453                        }
1454                    }
1455                }
1456            } else {
1457                let v = &self.v[kv_head];
1458                for p in first..stored {
1459                    let row = &v[p * hd..(p + 1) * hd];
1460                    for h in 0..nheads {
1461                        let w = scores[h * span + (p - first)];
1462                        if w.abs() < 1e-12 {
1463                            continue;
1464                        }
1465                        crate::attention::axpy_f32(&mut out[h * hd..(h + 1) * hd], row, w);
1466                    }
1467                }
1468            }
1469
1470            // ── Attention-importance accumulation (Σ probs over heads), same
1471            // head order as the caller's former per-head loop. Rows before
1472            // `first` carry probability 0 and are left untouched.
1473            let n = imp_acc.len().min(stored);
1474            if n > first {
1475                for h in 0..nheads {
1476                    let s = &scores[h * span..(h + 1) * span];
1477                    for (dst, &p) in imp_acc[first..n].iter_mut().zip(s) {
1478                        *dst += p;
1479                    }
1480                }
1481            }
1482        });
1483    }
1484
1485    /// Batched causal attend for a prefill chunk (macOS, AArch64, x86-64):
1486    /// the cache already holds every chunk row (`s0` old + `b` new). Per
1487    /// KV group the scores GEMM `Q·Kᵀ` rides Accelerate (AMX) or the
1488    /// portable micro-GEMM (NEON, AVX2), the causal softmax zeroes the
1489    /// not-yet-visible tail so the `P·V` GEMM needs no mask, and
1490    /// attention importance takes the masked column sums. A sliding
1491    /// window bounds the key range of the whole chunk, so a windowed
1492    /// layer costs O(b·(b + w)) rather than O(b·n). Same math as the
1493    /// per-position attend; summation order differs (tolerance-class,
1494    /// like the projection GEMMs).
1495    #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
1496    #[allow(clippy::too_many_arguments)]
1497    pub fn attend_chunk(
1498        &mut self,
1499        q_all: &[f32],
1500        b: usize,
1501        s0: usize,
1502        nh: usize,
1503        heads_per_kv: usize,
1504        hd: usize,
1505        out: &mut [f32],
1506        pool: Option<&crate::pool::Pool>,
1507        scale: f32,
1508        window: Option<usize>,
1509    ) {
1510        let n = s0 + b;
1511        // A masking window: the earliest key any row of this chunk sees
1512        // is `s0 + 1 - w`, so the GEMM pair runs over the keys [lo0, n)
1513        // only — at 16 000 rows a 512-wide window is 32× less work than
1514        // the full causal range, and the zeroed columns contributed
1515        // nothing anyway.
1516        let lo0 = window.map_or(0, |w| (s0 + 1).saturating_sub(w)).min(n);
1517        let nk = n - lo0;
1518        struct SendPtr(*mut f32);
1519        unsafe impl Send for SendPtr {}
1520        unsafe impl Sync for SendPtr {}
1521        impl SendPtr {
1522            fn at(&self, i: usize) -> *mut f32 {
1523                // Method receiver keeps the closure capturing &SendPtr
1524                // (2021 disjoint capture would grab the raw field).
1525                unsafe { self.0.add(i) }
1526            }
1527        }
1528        thread_local! {
1529            static SCRATCH: std::cell::RefCell<(Vec<f32>, Vec<f32>, Vec<f32>, Vec<f32>)> =
1530                const { std::cell::RefCell::new((Vec::new(), Vec::new(), Vec::new(), Vec::new())) };
1531        }
1532        // The portable micro-GEMM (NEON, AVX2) pays dearly for the
1533        // gathered Bᵀ loads of the scores multiply — pack Kᵀ once per
1534        // (group, chunk) and hand it the sequential-B fast path instead.
1535        // Accelerate keeps the no-copy transposed call.
1536        let neon_gemm = cfg!(not(target_os = "macos"))
1537            || std::env::var("CMF_FORCE_NEON_GEMM")
1538                .map(|v| v == "1")
1539                .unwrap_or(false);
1540        SCRATCH.with(|s| {
1541            let mut s = s.borrow_mut();
1542            let (qpanel, scores, aopanel, ktpack) = &mut *s;
1543            // The whole KV-group attends in one GEMM pair: the group's
1544            // Q-heads stack head-major into one tall panel [hpk·b, hd]
1545            // (row hl·b + bi), so each layer costs 2 sgemm calls per
1546            // group instead of 2 per head — fat M keeps the AMX fed.
1547            let m = heads_per_kv * b;
1548            qpanel.resize(m * hd, 0.0);
1549            scores.resize(m * nk, 0.0);
1550            aopanel.resize(m * hd, 0.0);
1551            for g in 0..self.num_kv_heads {
1552                debug_assert_eq!(self.k[g].len(), n * hd);
1553                let kmat = &self.k[g][lo0 * hd..n * hd];
1554                let vmat = &self.v[g][lo0 * hd..n * hd];
1555                for hl in 0..heads_per_kv {
1556                    let hh = g * heads_per_kv + hl;
1557                    for bi in 0..b {
1558                        qpanel[(hl * b + bi) * hd..(hl * b + bi + 1) * hd]
1559                            .copy_from_slice(&q_all[bi * nh * hd + hh * hd..][..hd]);
1560                    }
1561                }
1562                if neon_gemm {
1563                    ktpack.resize(hd * nk, 0.0);
1564                    {
1565                        // Each worker transposes its own key rows into
1566                        // its own columns of Kᵀ.
1567                        let sp_kt = SendPtr(ktpack.as_mut_ptr());
1568                        let run = |start: usize, end: usize| {
1569                            for p in start..end {
1570                                let row = &kmat[p * hd..(p + 1) * hd];
1571                                for (d, &v) in row.iter().enumerate() {
1572                                    // SAFETY: column p belongs to this worker alone.
1573                                    unsafe { *sp_kt.at(d * nk + p) = v };
1574                                }
1575                            }
1576                        };
1577                        match pool {
1578                            Some(p) if nk >= 2048 => p.run_rows(nk, &run),
1579                            _ => run(0, nk),
1580                        }
1581                    }
1582                    // Accelerate threads its own GEMM; the micro-kernel
1583                    // splits the m rows across the pool instead.
1584                    let sp_q = SendPtr(qpanel.as_ptr() as *mut f32);
1585                    let sp_s = SendPtr(scores.as_mut_ptr());
1586                    let kt = &*ktpack;
1587                    let run = |start: usize, end: usize| {
1588                        if end > start {
1589                            // SAFETY: workers write disjoint score rows.
1590                            let a = unsafe {
1591                                std::slice::from_raw_parts(sp_q.at(start * hd), (end - start) * hd)
1592                            };
1593                            let c = unsafe {
1594                                std::slice::from_raw_parts_mut(
1595                                    sp_s.at(start * nk),
1596                                    (end - start) * nk,
1597                                )
1598                            };
1599                            crate::qtensor::micro_gemm_rm(
1600                                end - start,
1601                                nk,
1602                                hd,
1603                                scale,
1604                                a,
1605                                hd,
1606                                kt,
1607                                nk,
1608                                false,
1609                                c,
1610                                nk,
1611                            );
1612                        }
1613                    };
1614                    match pool {
1615                        Some(p) if m >= 64 => p.run_rows(m, &run),
1616                        _ => run(0, m),
1617                    }
1618                } else {
1619                    crate::qtensor::sgemm_rm(
1620                        m, nk, hd, scale, qpanel, hd, kmat, hd, true, scores, nk,
1621                    );
1622                }
1623                // Causal softmax, row-parallel (rows are disjoint).
1624                let sp = SendPtr(scores.as_mut_ptr());
1625                let run = |start: usize, end: usize| {
1626                    for r in start..end {
1627                        // Key indices relative to lo0, the first key of
1628                        // the GEMM range.
1629                        let allowed = s0 + (r % b) + 1 - lo0;
1630                        // Sliding-window layers see only the last W of
1631                        // the causal range; the zeroed head contributes
1632                        // nothing to P·V or attention importance.
1633                        let lo = window
1634                            .map(|w| (s0 + (r % b) + 1).saturating_sub(w) - lo0)
1635                            .unwrap_or(0);
1636                        // SAFETY: workers cover disjoint row ranges.
1637                        let row = unsafe { std::slice::from_raw_parts_mut(sp.at(r * nk), nk) };
1638                        crate::attention::softmax_row(&mut row[lo..allowed]);
1639                        row[..lo].fill(0.0);
1640                        row[allowed..].fill(0.0);
1641                    }
1642                };
1643                match pool {
1644                    Some(p) if m >= 64 => p.run_rows(m, &run),
1645                    _ => run(0, m),
1646                }
1647                // Attention importance: masked column sums (probs of the
1648                // zeroed tail contribute nothing, same as the CPU
1649                // per-position accumulate).
1650                let ni = self.imp.len().min(n);
1651                for r in 0..m {
1652                    let al = (s0 + (r % b) + 1).min(ni);
1653                    if al > lo0 {
1654                        for (dst, &p) in self.imp[lo0..al]
1655                            .iter_mut()
1656                            .zip(&scores[r * nk..r * nk + (al - lo0)])
1657                        {
1658                            *dst += p;
1659                        }
1660                    }
1661                }
1662                if neon_gemm {
1663                    let sp_s = SendPtr(scores.as_mut_ptr());
1664                    let sp_o = SendPtr(aopanel.as_mut_ptr());
1665                    let run = |start: usize, end: usize| {
1666                        if end > start {
1667                            // SAFETY: workers write disjoint output rows.
1668                            let a = unsafe {
1669                                std::slice::from_raw_parts(sp_s.at(start * nk), (end - start) * nk)
1670                            };
1671                            let c = unsafe {
1672                                std::slice::from_raw_parts_mut(
1673                                    sp_o.at(start * hd),
1674                                    (end - start) * hd,
1675                                )
1676                            };
1677                            crate::qtensor::micro_gemm_rm(
1678                                end - start,
1679                                hd,
1680                                nk,
1681                                1.0,
1682                                a,
1683                                nk,
1684                                vmat,
1685                                hd,
1686                                false,
1687                                c,
1688                                hd,
1689                            );
1690                        }
1691                    };
1692                    match pool {
1693                        Some(p) if m >= 64 => p.run_rows(m, &run),
1694                        _ => run(0, m),
1695                    }
1696                } else {
1697                    crate::qtensor::sgemm_rm(
1698                        m, hd, nk, 1.0, scores, nk, vmat, hd, false, aopanel, hd,
1699                    );
1700                }
1701                for hl in 0..heads_per_kv {
1702                    let hh = g * heads_per_kv + hl;
1703                    for bi in 0..b {
1704                        out[bi * nh * hd + hh * hd..][..hd]
1705                            .copy_from_slice(&aopanel[(hl * b + bi) * hd..(hl * b + bi + 1) * hd]);
1706                    }
1707                }
1708            }
1709        });
1710    }
1711
1712    /// Roll back the last `n_drop` positions (speculative-decode reject).
1713    pub fn truncate_last(&mut self, n_drop: usize) {
1714        self.discard_linear_scratch();
1715        let d = n_drop.min(self.seq_len);
1716        if let Some(b) = self.bounded.as_mut() {
1717            // The ring rolls back through its undo rows; nothing is
1718            // stored per position, so there is nothing else to drop.
1719            let rolled = b.rollback(d);
1720            if rolled < d {
1721                tracing::warn!(
1722                    "bounded anchor: rollback of {d} exceeds the undo depth ({rolled} restored)"
1723                );
1724            }
1725            self.seq_len = b.seen;
1726            return;
1727        }
1728        // A trimmed tail keeps `slack` rows past its window for exactly
1729        // this; a deeper rollback leaves the next query short of rows its
1730        // window reads (no Spark path rolls back more than 2).
1731        if let Some(w) = self.tail
1732            && self.base > 0
1733            && self.seq_len - d < w.saturating_sub(1)
1734        {
1735            tracing::warn!(
1736                "sliding tail: rollback of {d} leaves {} rows under the {w}-row window",
1737                self.seq_len - d
1738            );
1739        }
1740        let mut first_changed = usize::MAX;
1741        for h in 0..self.num_kv_heads {
1742            let keep = self.k[h].len().saturating_sub(d * self.head_dim);
1743            if !self.k[h].is_empty() || !self.v[h].is_empty() {
1744                first_changed = first_changed.min(keep / self.head_dim.max(1));
1745            }
1746            self.k[h].truncate(keep);
1747            self.v[h].truncate(keep);
1748            let ngk = self.head_dim.div_ceil(KV_K_GROUP);
1749            let keep_q = self.kq[h].len().saturating_sub(d * self.head_dim);
1750            self.kq[h].truncate(keep_q);
1751            let keep_vq = self.vq[h].len().saturating_sub(d * self.head_dim);
1752            self.vq[h].truncate(keep_vq);
1753            let keep_ks = self.ks[h].len().saturating_sub(d * ngk);
1754            self.ks[h].truncate(keep_ks);
1755            let keep_vs = self.vs[h].len().saturating_sub(d);
1756            self.vs[h].truncate(keep_vs);
1757        }
1758        self.imp.truncate(self.imp.len().saturating_sub(d));
1759        self.seq_len -= d;
1760        self.kv_rows_changed(first_changed);
1761    }
1762
1763    /// Accumulate attention mass per stored position (summed over heads).
1764    pub fn accumulate_imp(&mut self, probs: &[f32]) {
1765        for (dst, &p) in self.imp.iter_mut().zip(probs) {
1766            *dst += p;
1767        }
1768    }
1769
1770    /// Contiguous keys of one head: `[stored_len × head_dim]`.
1771    pub fn head_keys(&self, kv_head: usize) -> &[f32] {
1772        &self.k[kv_head]
1773    }
1774
1775    pub fn head_values(&self, kv_head: usize) -> &[f32] {
1776        &self.v[kv_head]
1777    }
1778
1779    /// Number of positions actually stored for a head (0 for dead heads).
1780    pub fn head_len(&self, kv_head: usize) -> usize {
1781        let ng = self.head_dim.div_ceil(KV_K_GROUP);
1782        (self.k[kv_head].len() / self.head_dim)
1783            .max(self.ks[kv_head].len() / ng)
1784            .max(self.vs[kv_head].len())
1785    }
1786
1787    /// Clear cache (e.g. on new conversation or task switch).
1788    pub fn clear(&mut self) {
1789        self.kv_rows_changed(0);
1790        for h in 0..self.num_kv_heads {
1791            self.k[h].clear();
1792            self.v[h].clear();
1793            self.kq[h].clear();
1794            self.ks[h].clear();
1795            self.vq[h].clear();
1796            self.vs[h].clear();
1797            self.kcol[h].clear();
1798            self.vcol[h].clear();
1799        }
1800        self.imp.clear();
1801        self.linear_state.clear();
1802        self.discard_linear_scratch();
1803        // Fresh conversation → the pipeline re-arms collection if the
1804        // layer is o1-flagged (landmarks are per-prompt, never reused).
1805        self.o1 = None;
1806        self.o1_error = None;
1807        self.o1_transitioned = false;
1808        // The bounded ring is zeroed in place: its size is a property of
1809        // the file, not of the conversation.
1810        if let Some(b) = self.bounded.as_mut() {
1811            b.clear();
1812        }
1813        self.seq_len = 0;
1814        // `tail` stays: the window is the layer's, not the conversation's.
1815        self.base = 0;
1816        self.generation = next_gen();
1817    }
1818
1819    /// Serialize this layer's state for the wire (versioned, v2): a
1820    /// fixed header `{magic "CMFS", version, operator identity hash64,
1821    /// layer, kind, f16 flag, position}` followed by one record whose
1822    /// shape the kind fixes — per-position K/V (+ importance) for a full
1823    /// layer, the recurrent vector for a linear layer, the insert counter
1824    /// + ring K/V for a bounded anchor. `f16` halves the K/V payloads and
1825    /// is the caller's explicit choice, exactly like the hidden-state
1826    /// wire; recurrent vectors stay f32 whatever the wire dtype (they are
1827    /// the ONLY state a linear layer has — rounding them rounds the whole
1828    /// history).
1829    ///
1830    /// REFUSES rather than travelling half-complete. A cache carrying
1831    /// frozen columns, a Nyström overlay or q8 storage holds state this
1832    /// format does not describe, and shipping the rest would land a
1833    /// plausible-looking cache that answers differently — the failure
1834    /// mode this whole format exists to avoid.
1835    pub fn export_wire(&self, f16: bool) -> Result<Vec<u8>, String> {
1836        if !matches!(self.mode, KvMode::F32) {
1837            return Err("kv export: only the F32 cache is described by this                         format (CMF_KV=q8 stores int8 rows and per-row scales)"
1838                .into());
1839        }
1840        if self.o1.is_some() {
1841            return Err("kv export: an O(1) Nyström overlay is not part of                         this format — the skeletons are irreversible and                         would have to travel with it"
1842                .into());
1843        }
1844        // Frozen columns only exist under q8 storage, which is refused
1845        // above. If one shows up under an F32 cache the format is lying
1846        // about something and the transfer must not proceed.
1847        if self.kcol.iter().any(|c| !c.is_empty()) || self.vcol.iter().any(|c| !c.is_empty()) {
1848            return Err(
1849                "kv export: frozen columns under an F32 cache — refusing to ship \
1850                        a state this format does not describe"
1851                    .into(),
1852            );
1853        }
1854        let mut out = Vec::with_capacity(self.memory_bytes() / if f16 { 2 } else { 1 } + 64);
1855        let u = |v: u32, o: &mut Vec<u8>| o.extend_from_slice(&v.to_le_bytes());
1856        out.extend_from_slice(WIRE_MAGIC);
1857        u(WIRE_VERSION, &mut out);
1858        out.extend_from_slice(&self.wire_identity.to_le_bytes());
1859        u(self.wire_layer, &mut out);
1860        // A trimmed full layer travels as its tail and says where it starts.
1861        let kind = match self.wire_kind {
1862            WireKind::Full if self.base > 0 => WireKind::FullTail,
1863            k => k,
1864        };
1865        out.push(kind as u8);
1866        out.push(u8::from(f16));
1867        out.extend_from_slice(&0u16.to_le_bytes());
1868        // The header carries the absolute depth (== seq_len untrimmed).
1869        out.extend_from_slice(&(self.pos_len() as u64).to_le_bytes());
1870        let push = |xs: &[f32], o: &mut Vec<u8>| {
1871            if f16 {
1872                for &x in xs {
1873                    o.extend_from_slice(&cortiq_core::quant::f32_to_f16(x).to_le_bytes());
1874                }
1875            } else {
1876                for &x in xs {
1877                    o.extend_from_slice(&x.to_le_bytes());
1878                }
1879            }
1880        };
1881        match kind {
1882            WireKind::Full => self.export_full_body(f16, &mut out),
1883            WireKind::FullTail => {
1884                out.extend_from_slice(&(self.base as u64).to_le_bytes());
1885                self.export_full_body(f16, &mut out);
1886            }
1887            WireKind::Linear => {
1888                u(self.num_kv_heads as u32, &mut out);
1889                u(self.head_dim as u32, &mut out);
1890                u(self.linear_state.len() as u32, &mut out);
1891                for &x in &self.linear_state {
1892                    out.extend_from_slice(&x.to_le_bytes());
1893                }
1894            }
1895            WireKind::Bounded => {
1896                let b = self
1897                    .bounded
1898                    .as_ref()
1899                    .ok_or("kv export: bounded wire kind without an installed ring")?;
1900                u(self.num_kv_heads as u32, &mut out);
1901                u(self.head_dim as u32, &mut out);
1902                u(b.window as u32, &mut out);
1903                u(b.len() as u32, &mut out);
1904                u(b.head() as u32, &mut out);
1905                push(&b.ring_k, &mut out);
1906                push(&b.ring_v, &mut out);
1907            }
1908        }
1909        Ok(out)
1910    }
1911
1912    /// The per-position record (the whole legacy wire): f16 flag,
1913    /// seq_len, geometry, recurrent vector, importance, per-head K/V.
1914    fn export_full_body(&self, f16: bool, out: &mut Vec<u8>) {
1915        let u = |v: u32, o: &mut Vec<u8>| o.extend_from_slice(&v.to_le_bytes());
1916        u(u8::from(f16) as u32, out);
1917        u(self.seq_len as u32, out);
1918        u(self.num_kv_heads as u32, out);
1919        u(self.head_dim as u32, out);
1920        u(self.linear_state.len() as u32, out);
1921        // Attention importance is ordinary state: every attention call
1922        // accumulates it and eviction reads it. Leaving it behind would
1923        // hand the far side a cache that forgets the RIGHT positions
1924        // later — a divergence that shows up only under pressure.
1925        u(self.imp.len() as u32, out);
1926        let push = |xs: &[f32], o: &mut Vec<u8>| {
1927            if f16 {
1928                for &x in xs {
1929                    o.extend_from_slice(&cortiq_core::quant::f32_to_f16(x).to_le_bytes());
1930                }
1931            } else {
1932                for &x in xs {
1933                    o.extend_from_slice(&x.to_le_bytes());
1934                }
1935            }
1936        };
1937        for &x in &self.linear_state {
1938            out.extend_from_slice(&x.to_le_bytes());
1939        }
1940        for &x in &self.imp {
1941            out.extend_from_slice(&x.to_le_bytes());
1942        }
1943        for h in 0..self.num_kv_heads {
1944            u(self.k[h].len() as u32, out);
1945            push(&self.k[h], out);
1946            u(self.v[h].len() as u32, out);
1947            push(&self.v[h], out);
1948        }
1949    }
1950
1951    /// Install a peer's state over this layer. The geometry must match the
1952    /// model both sides hold — it is checked, not assumed. Accepts the
1953    /// versioned wire (magic "CMFS") and, for full/linear layers, the old
1954    /// unversioned per-position body.
1955    pub fn import_wire(&mut self, buf: &[u8]) -> Result<(), String> {
1956        if buf.len() >= 4 && &buf[..4] == WIRE_MAGIC {
1957            return self.import_wire_v2(buf);
1958        }
1959        // Legacy (unversioned) wire: no operator tag travels with it.
1960        if !self.linear_wire_allowed {
1961            return Err(
1962                "kv import: Delta linear state cannot use the unversioned cache wire; refusing until the wire carries operator identity".into(),
1963            );
1964        }
1965        if self.bounded.is_some() {
1966            return Err(
1967                "kv import: a bounded anchor takes only the versioned wire (v2) — the \
1968                 unversioned body has no ring record"
1969                    .into(),
1970            );
1971        }
1972        let n = self.import_full_body(buf)?;
1973        if n != buf.len() {
1974            return Err(format!(
1975                "kv import: {} trailing byte(s) after the record",
1976                buf.len() - n
1977            ));
1978        }
1979        Ok(())
1980    }
1981
1982    fn import_wire_v2(&mut self, buf: &[u8]) -> Result<(), String> {
1983        let need = |n: usize, o: usize| -> Result<(), String> {
1984            if o + n > buf.len() {
1985                Err("kv import: truncated header".into())
1986            } else {
1987                Ok(())
1988            }
1989        };
1990        need(28, 0)?;
1991        let version = u32::from_le_bytes(buf[4..8].try_into().unwrap());
1992        if version != WIRE_VERSION {
1993            return Err(format!(
1994                "kv import: wire version {version}, this runtime speaks {WIRE_VERSION}"
1995            ));
1996        }
1997        let identity = u64::from_le_bytes(buf[8..16].try_into().unwrap());
1998        let layer = u32::from_le_bytes(buf[16..20].try_into().unwrap());
1999        let kind = WireKind::from_u8(buf[20])
2000            .ok_or_else(|| format!("kv import: unknown state kind {}", buf[20]))?;
2001        let f16 = buf[21] != 0;
2002        let position = u64::from_le_bytes(buf[24..32].try_into().unwrap()) as usize;
2003        if identity != self.wire_identity {
2004            return Err(format!(
2005                "kv import: peer operator identity {identity:016x} != mine {:016x} — \
2006                 the two sides do not hold the same operator",
2007                self.wire_identity
2008            ));
2009        }
2010        if layer != self.wire_layer {
2011            return Err(format!(
2012                "kv import: record is for layer {layer}, this is layer {}",
2013                self.wire_layer
2014            ));
2015        }
2016        // A full layer takes its trimmed tail too.
2017        let fits = kind == self.wire_kind
2018            || (kind == WireKind::FullTail && self.wire_kind == WireKind::Full);
2019        if !fits {
2020            return Err(format!(
2021                "kv import: record kind {kind:?} does not match this layer's {:?}",
2022                self.wire_kind
2023            ));
2024        }
2025        let mut o = 32usize;
2026        let u32_at = |o: &mut usize| -> Result<u32, String> {
2027            if *o + 4 > buf.len() {
2028                return Err("kv import: truncated record".into());
2029            }
2030            let v = u32::from_le_bytes(buf[*o..*o + 4].try_into().unwrap());
2031            *o += 4;
2032            Ok(v)
2033        };
2034        let need_payload = |n: usize, o: usize| -> Result<(), String> {
2035            if o + n > buf.len() {
2036                Err("kv import: truncated payload".into())
2037            } else {
2038                Ok(())
2039            }
2040        };
2041        match kind {
2042            WireKind::Full => {
2043                let n = self.import_full_body(&buf[o..])?;
2044                o += n;
2045                if self.seq_len != position {
2046                    return Err(format!(
2047                        "kv import: header position {position} != record seq_len {}",
2048                        self.seq_len
2049                    ));
2050                }
2051            }
2052            WireKind::FullTail => {
2053                need_payload(8, o)?;
2054                let base = u64::from_le_bytes(buf[o..o + 8].try_into().unwrap()) as usize;
2055                o += 8;
2056                let n = self.import_full_body(&buf[o..])?;
2057                o += n;
2058                if base.checked_add(self.seq_len) != Some(position) {
2059                    let rows = self.seq_len;
2060                    self.reset_per_position_storage();
2061                    self.seq_len = 0;
2062                    return Err(format!(
2063                        "kv import: tail base {base} + {rows} rows != header position {position}"
2064                    ));
2065                }
2066                self.base = base;
2067            }
2068            WireKind::Linear => {
2069                let heads = u32_at(&mut o)? as usize;
2070                let hd = u32_at(&mut o)? as usize;
2071                if heads != self.num_kv_heads || hd != self.head_dim {
2072                    return Err(format!(
2073                        "kv import: peer sent {heads}×{hd} per position, this layer is {}×{}",
2074                        self.num_kv_heads, self.head_dim
2075                    ));
2076                }
2077                let lin = u32_at(&mut o)? as usize;
2078                need_payload(lin * 4, o)?;
2079                self.linear_state = (0..lin)
2080                    .map(|i| f32::from_le_bytes(buf[o + i * 4..o + i * 4 + 4].try_into().unwrap()))
2081                    .collect();
2082                o += lin * 4;
2083                self.reset_per_position_storage();
2084                self.seq_len = position;
2085            }
2086            WireKind::Bounded => {
2087                let heads = u32_at(&mut o)? as usize;
2088                let hd = u32_at(&mut o)? as usize;
2089                let window = u32_at(&mut o)? as usize;
2090                let len = u32_at(&mut o)? as usize;
2091                let head = u32_at(&mut o)? as usize;
2092                let b = self
2093                    .bounded
2094                    .as_mut()
2095                    .ok_or("kv import: bounded record for a layer without a ring")?;
2096                if heads != b.num_kv_heads || hd != b.head_dim || window != b.window {
2097                    return Err(format!(
2098                        "kv import: bounded record {heads}×{window}×{hd} does not fit this \
2099                         layer's ring {}×{}×{}",
2100                        b.num_kv_heads, b.window, b.head_dim
2101                    ));
2102                }
2103                if len != position.min(window) || head != position % window {
2104                    return Err(format!(
2105                        "kv import: bounded record len/head {len}/{head} inconsistent with \
2106                         position {position} (window {window})"
2107                    ));
2108                }
2109                let n = b.ring_k.len();
2110                let w = if f16 { 2 } else { 4 };
2111                need_payload(2 * n * w, o)?;
2112                let read = |o: usize, dst: &mut [f32]| {
2113                    for (i, d) in dst.iter_mut().enumerate() {
2114                        let at = o + i * w;
2115                        *d = if f16 {
2116                            cortiq_core::quant::f16_to_f32(u16::from_le_bytes(
2117                                buf[at..at + 2].try_into().unwrap(),
2118                            ))
2119                        } else {
2120                            f32::from_le_bytes(buf[at..at + 4].try_into().unwrap())
2121                        };
2122                    }
2123                };
2124                read(o, &mut b.ring_k);
2125                o += n * w;
2126                read(o, &mut b.ring_v);
2127                o += n * w;
2128                b.seen = position;
2129                // The undo rows describe inserts this side never made.
2130                let snap = b.snapshot();
2131                b.restore(&snap);
2132                self.linear_state = Vec::new();
2133                self.reset_per_position_storage();
2134                self.seq_len = position;
2135            }
2136        }
2137        if o != buf.len() {
2138            return Err(format!(
2139                "kv import: {} trailing byte(s) after the record",
2140                buf.len() - o
2141            ));
2142        }
2143        Ok(())
2144    }
2145
2146    /// Empty every per-position store (keeps the recurrent vector and
2147    /// the bounded ring untouched).
2148    fn reset_per_position_storage(&mut self) {
2149        let heads = self.num_kv_heads;
2150        self.mode = KvMode::F32;
2151        self.k = vec![Vec::new(); heads];
2152        self.v = vec![Vec::new(); heads];
2153        self.kv_rows_changed(0);
2154        self.kq = vec![Vec::new(); heads];
2155        self.ks = vec![Vec::new(); heads];
2156        self.vq = vec![Vec::new(); heads];
2157        self.vs = vec![Vec::new(); heads];
2158        self.kcol = vec![Vec::new(); heads];
2159        self.vcol = vec![Vec::new(); heads];
2160        self.imp = Vec::new();
2161        self.discard_linear_scratch();
2162        self.o1 = None;
2163        self.o1_error = None;
2164        self.o1_transitioned = false;
2165        self.base = 0;
2166        self.generation = next_gen();
2167    }
2168
2169    /// Parse the per-position record (legacy wire body); returns the
2170    /// bytes consumed.
2171    fn import_full_body(&mut self, buf: &[u8]) -> Result<usize, String> {
2172        let mut o = 0usize;
2173        let u32_at = |o: &mut usize| -> Result<u32, String> {
2174            if *o + 4 > buf.len() {
2175                return Err("kv import: truncated header".into());
2176            }
2177            let v = u32::from_le_bytes(buf[*o..*o + 4].try_into().unwrap());
2178            *o += 4;
2179            Ok(v)
2180        };
2181        let f16 = u32_at(&mut o)? != 0;
2182        let seq_len = u32_at(&mut o)? as usize;
2183        let heads = u32_at(&mut o)? as usize;
2184        let hd = u32_at(&mut o)? as usize;
2185        let lin = u32_at(&mut o)? as usize;
2186        let nimp = u32_at(&mut o)? as usize;
2187        if heads != self.num_kv_heads || hd != self.head_dim {
2188            return Err(format!(
2189                "kv import: peer sent {heads}×{hd} per position, this layer is {}×{}",
2190                self.num_kv_heads, self.head_dim
2191            ));
2192        }
2193        let w = if f16 { 2 } else { 4 };
2194        let need = |n: usize, o: usize| -> Result<(), String> {
2195            if o + n > buf.len() {
2196                Err("kv import: truncated payload".into())
2197            } else {
2198                Ok(())
2199            }
2200        };
2201        need(lin * 4, o)?;
2202        self.linear_state = (0..lin)
2203            .map(|i| f32::from_le_bytes(buf[o + i * 4..o + i * 4 + 4].try_into().unwrap()))
2204            .collect();
2205        o += lin * 4;
2206        need(nimp * 4, o)?;
2207        let imp: Vec<f32> = (0..nimp)
2208            .map(|i| f32::from_le_bytes(buf[o + i * 4..o + i * 4 + 4].try_into().unwrap()))
2209            .collect();
2210        o += nimp * 4;
2211        let mut k: Vec<Vec<f32>> = Vec::with_capacity(heads);
2212        let mut v: Vec<Vec<f32>> = Vec::with_capacity(heads);
2213        for _ in 0..heads {
2214            for which in 0..2 {
2215                let n = u32_at(&mut o)? as usize;
2216                need(n * w, o)?;
2217                let xs: Vec<f32> = (0..n)
2218                    .map(|i| {
2219                        let at = o + i * w;
2220                        if f16 {
2221                            cortiq_core::quant::f16_to_f32(u16::from_le_bytes(
2222                                buf[at..at + 2].try_into().unwrap(),
2223                            ))
2224                        } else {
2225                            f32::from_le_bytes(buf[at..at + 4].try_into().unwrap())
2226                        }
2227                    })
2228                    .collect();
2229                o += n * w;
2230                if which == 0 { k.push(xs) } else { v.push(xs) }
2231            }
2232        }
2233        self.reset_per_position_storage();
2234        self.k = k;
2235        self.v = v;
2236        self.imp = imp;
2237        self.seq_len = seq_len;
2238        Ok(o)
2239    }
2240
2241    pub fn memory_bytes(&self) -> usize {
2242        let floats: usize = self.k.iter().map(Vec::len).sum::<usize>()
2243            + self.v.iter().map(Vec::len).sum::<usize>()
2244            + self.ks.iter().map(Vec::len).sum::<usize>()
2245            + self.vs.iter().map(Vec::len).sum::<usize>()
2246            + self.kcol.iter().map(Vec::len).sum::<usize>()
2247            + self.vcol.iter().map(Vec::len).sum::<usize>();
2248        let bytes: usize = self.kq.iter().map(Vec::len).sum::<usize>()
2249            + self.vq.iter().map(Vec::len).sum::<usize>();
2250        floats * std::mem::size_of::<f32>()
2251            + bytes
2252            // O(1) recurrent state of linear-core layers (vmf_phase/GDN):
2253            // constant in context, but real memory — the honest "KV+state"
2254            // line must count it (a pure-linear model reported 0 before).
2255            + self.linear_state.len() * std::mem::size_of::<f32>()
2256            // O(1) Nyström state (window + sinks + skeleton) — same
2257            // discipline: constant in context, but real memory.
2258            + self.o1_memory_bytes()
2259            // Natively bounded anchor: the ring is the whole state of the
2260            // layer, fixed by the header.
2261            + self.bounded_state_bytes()
2262    }
2263
2264    /// Drop oldest positions, keeping the last `keep_last`.
2265    fn evict(&mut self, keep_last: usize) {
2266        // A collecting o1 layer owns a still-needed exact prefix and query
2267        // trace.  Evicting it would lower the effective seal boundary while
2268        // leaving q_buf untouched, so conversion could never match its KV
2269        // rows.  A sealed layer stores nothing per position — the Nyström
2270        // state IS the eviction policy; resetting seq_len here would lie
2271        // about the context depth.  Both states therefore bypass ordinary
2272        // eviction until the transition or explicit reset completes.  A
2273        // bounded anchor likewise: the ring evicts itself every token.
2274        // A sliding-window tail (`trim_window`) bounds itself and must stay
2275        // the exact contiguous window its attends index.
2276        if self.o1.is_some()
2277            || self.bounded.is_some()
2278            || self.tail.is_some()
2279            || self.seq_len <= keep_last
2280        {
2281            return;
2282        }
2283        self.generation = next_gen();
2284        let drop = self.seq_len - keep_last;
2285        for h in 0..self.num_kv_heads {
2286            // Dead heads store fewer positions; drop proportionally.
2287            let stored = self.head_len(h);
2288            let d = drop.min(stored);
2289            let hd = self.head_dim;
2290            fn drop_front<T>(v: &mut Vec<T>, n: usize) {
2291                let n = n.min(v.len());
2292                v.drain(..n);
2293            }
2294            drop_front(&mut self.k[h], d * hd);
2295            drop_front(&mut self.v[h], d * hd);
2296            self.kv_rows_changed(0);
2297            drop_front(&mut self.kq[h], d * hd);
2298            drop_front(&mut self.vq[h], d * hd);
2299            drop_front(&mut self.ks[h], d * hd.div_ceil(KV_K_GROUP));
2300            drop_front(&mut self.vs[h], d);
2301        }
2302        let d = drop.min(self.imp.len());
2303        self.imp.drain(..d);
2304        self.seq_len = keep_last;
2305    }
2306
2307    /// Mass-based eviction: keep `sink` earliest positions (attention sinks),
2308    /// the `recent` latest, and fill the rest of the `keep_last` budget
2309    /// with the positions carrying the highest accumulated attention
2310    /// mass (vmfcore: PPL 8.342 vs 8.687 for recency-only, full 8.295).
2311    fn evict_born(&mut self, keep_last: usize, sink: usize, recent: usize) {
2312        if self.o1.is_some() || self.bounded.is_some() || self.tail.is_some() {
2313            // See evict(): collecting must retain the exact prefix as well as
2314            // sealed O(1) state must retain its own bounded representation;
2315            // a bounded anchor's ring is its own eviction, and a sliding
2316            // tail its own (a gather would make its rows non-contiguous).
2317            return;
2318        }
2319        let stored = self.imp.len();
2320        if stored <= keep_last {
2321            return;
2322        }
2323        self.generation = next_gen();
2324        // Budget discipline: sinks first, recents next, both clamped so
2325        // the total never exceeds keep_last.
2326        let sink_n = sink.min(keep_last);
2327        let recent_n = recent.min(keep_last - sink_n);
2328        let mut keep = vec![false; stored];
2329        for k in keep.iter_mut().take(sink_n) {
2330            *k = true;
2331        }
2332        for k in keep.iter_mut().skip(stored.saturating_sub(recent_n)) {
2333            *k = true;
2334        }
2335        let mut budget = keep_last.saturating_sub(keep.iter().filter(|&&x| x).count());
2336        // Highest accumulated mass first among the middle positions.
2337        let mut order: Vec<usize> = (0..stored).filter(|&i| !keep[i]).collect();
2338        order.sort_by(|&a, &b| {
2339            self.imp[b]
2340                .partial_cmp(&self.imp[a])
2341                .unwrap_or(std::cmp::Ordering::Equal)
2342        });
2343        for i in order {
2344            if budget == 0 {
2345                break;
2346            }
2347            keep[i] = true;
2348            budget -= 1;
2349        }
2350
2351        let kept: Vec<usize> = (0..stored).filter(|&i| keep[i]).collect();
2352        let hd = self.head_dim;
2353        fn gather<T: Copy>(src: &[T], kept: &[usize], step: usize) -> Vec<T> {
2354            let mut out = Vec::with_capacity(kept.len() * step);
2355            for &i in kept {
2356                out.extend_from_slice(&src[i * step..(i + 1) * step]);
2357            }
2358            out
2359        }
2360        // Each storage is gathered INDEPENDENTLY: in mixed modes
2361        // (q8k/q8v) K and V live in different storages — the paired branch
2362        // panicked (q8v) or silently left V uncompressed (q8k);
2363        // found by adversarial review, closed by regression tests.
2364        for h in 0..self.num_kv_heads {
2365            if !self.k[h].is_empty() {
2366                self.k[h] = gather(&self.k[h], &kept, hd);
2367                self.kv_rows_changed(0);
2368            }
2369            if !self.v[h].is_empty() {
2370                self.v[h] = gather(&self.v[h], &kept, hd);
2371                self.kv_rows_changed(0);
2372            }
2373            if !self.kq[h].is_empty() {
2374                self.kq[h] = gather(&self.kq[h], &kept, hd);
2375                self.ks[h] = gather(&self.ks[h], &kept, hd.div_ceil(KV_K_GROUP));
2376            }
2377            if !self.vq[h].is_empty() {
2378                self.vq[h] = gather(&self.vq[h], &kept, hd);
2379                self.vs[h] = gather(&self.vs[h], &kept, 1);
2380            }
2381        }
2382        self.imp = kept.iter().map(|&i| self.imp[i]).collect();
2383        self.seq_len = kept.len();
2384    }
2385}
2386
2387/// Eviction policy for a bounded cache.
2388#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2389pub enum EvictionPolicy {
2390    /// Sliding window: keep only the most recent positions.
2391    Recent,
2392    /// Mass-based eviction: sinks + recents + top accumulated attention mass.
2393    Born { sink: usize },
2394}
2395
2396/// Full KV cache for all layers.
2397#[derive(Debug)]
2398pub struct KvCache {
2399    pub layers: Vec<LayerKvCache>,
2400    pub max_seq_len: usize,
2401    pub policy: EvictionPolicy,
2402}
2403
2404impl KvCache {
2405    pub fn new(
2406        num_layers: usize,
2407        num_kv_heads: usize,
2408        head_dim: usize,
2409        max_seq_len: usize,
2410    ) -> Self {
2411        let layers = (0..num_layers)
2412            .map(|li| {
2413                let mut l = LayerKvCache::new(num_kv_heads, head_dim);
2414                l.wire_layer = li as u32;
2415                l
2416            })
2417            .collect();
2418        Self {
2419            layers,
2420            max_seq_len,
2421            policy: EvictionPolicy::Born { sink: 4 },
2422        }
2423    }
2424
2425    pub fn clear(&mut self) {
2426        for layer in &mut self.layers {
2427            layer.clear();
2428        }
2429    }
2430
2431    pub fn total_memory_bytes(&self) -> usize {
2432        self.layers.iter().map(|l| l.memory_bytes()).sum()
2433    }
2434
2435    /// Bytes owned by linear-core recurrent state (including the tentative
2436    /// speculative scratch).  This is reported separately from attention KV
2437    /// so a serving slot's O(1) capacity can be compared with its context
2438    /// cache without guessing from model geometry.
2439    pub fn recurrent_state_bytes(&self) -> usize {
2440        let floats: usize = self
2441            .layers
2442            .iter()
2443            .map(|l| l.linear_state.len() + l.linear_scratch.len())
2444            .sum();
2445        floats * std::mem::size_of::<f32>()
2446    }
2447
2448    /// Attention KV (or sealed O(1) attention state) bytes, excluding the
2449    /// linear recurrent vectors returned by [`recurrent_state_bytes`].
2450    pub fn attention_state_bytes(&self) -> usize {
2451        self.total_memory_bytes()
2452            .saturating_sub(self.recurrent_state_bytes())
2453    }
2454
2455    /// Current sequence length (max across layers — dead layers may lag):
2456    /// the absolute depth, which a trimmed sliding layer keeps in
2457    /// `pos_len()` while it stores only its tail.
2458    pub fn seq_len(&self) -> usize {
2459        self.layers.iter().map(|l| l.pos_len()).max().unwrap_or(0)
2460    }
2461
2462    /// Bytes owned by bounded-anchor rings (constant in context).
2463    pub fn bounded_state_bytes(&self) -> usize {
2464        self.layers.iter().map(|l| l.bounded_state_bytes()).sum()
2465    }
2466
2467    /// True when some layer with PER-POSITION storage reached the cap.
2468    /// Bounded anchors hold nothing per position and never need it: a
2469    /// model whose every layer is O(1) has no eviction cliff at all. A
2470    /// sliding tail (`trim_window`) bounds itself and is not counted.
2471    pub fn needs_eviction(&self) -> bool {
2472        self.layers
2473            .iter()
2474            .filter(|l| l.bounded.is_none() && l.tail.is_none())
2475            .map(|l| l.seq_len)
2476            .max()
2477            .unwrap_or(0)
2478            >= self.max_seq_len
2479    }
2480
2481    /// Evict down to `keep_last` positions according to the policy.
2482    pub fn evict(&mut self, keep_last: usize) {
2483        match self.policy {
2484            EvictionPolicy::Recent => {
2485                for layer in &mut self.layers {
2486                    layer.evict(keep_last);
2487                }
2488            }
2489            EvictionPolicy::Born { sink } => {
2490                let recent = (keep_last / 2).max(1);
2491                for layer in &mut self.layers {
2492                    layer.evict_born(keep_last, sink, recent);
2493                }
2494            }
2495        }
2496    }
2497}
2498
2499#[cfg(test)]
2500mod tests {
2501    use super::*;
2502
2503    /// The lazy K/V maximum the wgpu prefill's f16 guard reads: rows a
2504    /// truncation drops and later appends rewrite are scanned again, an
2505    /// inf or NaN reports +inf, `clear` starts afresh, and a caller's own
2506    /// maxima of the rows it just appended fold in only when they continue
2507    /// the scanned prefix.
2508    #[test]
2509    fn kv_abs_max_follows_appends_truncation_and_clear() {
2510        let (heads, hd) = (2usize, 4usize);
2511        let mut c = LayerKvCache::new(heads, hd);
2512        c.mode = KvMode::F32;
2513        let row = |x: f32| vec![x; heads * hd];
2514        for _ in 0..4 {
2515            c.append(&row(0.5), &row(-0.25), &[]);
2516        }
2517        assert_eq!(c.kv_abs_max(), (0.5, 0.25));
2518        c.truncate_last(2);
2519        c.append(&row(-9.0), &row(3.0), &[]);
2520        c.append(&row(0.5), &row(0.25), &[]);
2521        assert_eq!(c.kv_abs_max(), (9.0, 3.0), "rewritten rows were not rescanned");
2522        c.append(&row(f32::NAN), &row(0.0), &[]);
2523        assert_eq!(c.kv_abs_max().0, f32::INFINITY);
2524        c.clear();
2525        c.append(&row(1.0), &row(2.0), &[]);
2526        assert_eq!(c.kv_abs_max(), (1.0, 2.0));
2527        c.append(&row(4.0), &row(1.0), &[]);
2528        // Rows [1, 2) continue the scanned prefix: the caller's maxima.
2529        assert_eq!(c.kv_abs_max_after((1, 2, 4.0, 1.0)), (4.0, 2.0));
2530        c.append(&row(8.0), &row(1.0), &[]);
2531        // A stale `from` falls back to the scan.
2532        assert_eq!(c.kv_abs_max_after((0, 3, 0.0, 0.0)), (8.0, 2.0));
2533    }
2534
2535    /// A trim drops rows from the front: `kv_abs_max` must still scan every
2536    /// row appended after it, also when more are appended than were dropped
2537    /// before the next call.
2538    #[test]
2539    fn kv_abs_max_scans_rows_appended_after_a_trim() {
2540        let (heads, hd, w) = (1usize, 4usize, 8usize);
2541        let mut c = LayerKvCache::new(heads, hd);
2542        c.mode = KvMode::F32;
2543        let row = |x: f32| vec![x; heads * hd];
2544        for _ in 0..(2 * w + 4) {
2545            c.append(&row(0.5), &row(0.5), &[]);
2546        }
2547        assert_eq!(c.kv_abs_max(), (0.5, 0.5));
2548        let d = c.trim_window(w, 2, 2);
2549        assert!(d > 0, "the trim must drop rows for this test");
2550        // The first row after the trim is large, then more rows than were
2551        // dropped: without moving the mark, rows [stored - d, old mark) —
2552        // the large one among them — would go unscanned.
2553        let first_new = c.kv_rows();
2554        c.append(&row(-7.0), &row(6.0), &[]);
2555        for _ in 0..(d + 3) {
2556            c.append(&row(0.5), &row(0.5), &[]);
2557        }
2558        assert!(c.kv_rows() > 2 * w + 4 && first_new < 2 * w + 4);
2559        assert_eq!(c.kv_abs_max(), (7.0, 6.0));
2560    }
2561
2562    #[test]
2563    fn memory_breakdown_separates_recurrent_and_attention_state() {
2564        let mut cache = KvCache::new(1, 1, 4, 16);
2565        cache.layers[0].linear_state = vec![0.0; 8];
2566        cache.layers[0].linear_scratch = vec![0.0; 4];
2567        cache.layers[0].append(&[0.0; 4], &[1.0; 4], &[true]);
2568        let recurrent = cache.recurrent_state_bytes();
2569        assert_eq!(recurrent, 12 * std::mem::size_of::<f32>());
2570        assert_eq!(
2571            cache.attention_state_bytes() + recurrent,
2572            cache.total_memory_bytes()
2573        );
2574        assert!(cache.attention_state_bytes() > 0);
2575    }
2576
2577    #[test]
2578    fn wire_round_trip_reproduces_attention() {
2579        // The state has to arrive as state, not as something that looks
2580        // like it: the oracle is what the layer ANSWERS, not what it
2581        // stores. Same query, same output, bit for bit.
2582        let (heads, hd) = (2usize, 4usize);
2583        let mut a = LayerKvCache::new(heads, hd);
2584        for p in 0..5 {
2585            let k: Vec<f32> = (0..heads * hd)
2586                .map(|i| (p * 10 + i) as f32 * 0.031)
2587                .collect();
2588            let v: Vec<f32> = (0..heads * hd)
2589                .map(|i| (p * 7 + i) as f32 * -0.017)
2590                .collect();
2591            a.append(&k, &v, &[true, true]);
2592        }
2593        a.linear_state = vec![0.5, -0.25, 1.0];
2594        let q: Vec<f32> = (0..hd).map(|i| 0.1 * (i as f32 + 1.0)).collect();
2595
2596        let bytes = a.export_wire(false).expect("f32 cache exports");
2597        let mut b = LayerKvCache::new(heads, hd);
2598        b.linear_scratch = vec![9.0; 3];
2599        b.import_wire(&bytes).expect("import");
2600        assert!(
2601            b.linear_scratch.is_empty(),
2602            "import must discard tentative state"
2603        );
2604
2605        assert_eq!(b.seq_len, a.seq_len);
2606        assert_eq!(b.linear_state, a.linear_state);
2607        for h in 0..heads {
2608            let (oa, sa) = a.attend(&q, h);
2609            let (ob, sb) = b.attend(&q, h);
2610            assert_eq!(oa, ob, "head {h} attention output diverged");
2611            assert_eq!(sa, sb, "head {h} attention scores diverged");
2612        }
2613    }
2614
2615    #[test]
2616    fn wire_refuses_what_it_cannot_describe() {
2617        // A refusal is the feature: a cache whose extra state this format
2618        // does not carry must not travel looking complete.
2619        let mut c = LayerKvCache::new(1, 4);
2620        c.mode = KvMode::Q8 { k: true, v: true };
2621        let err = c.export_wire(false).unwrap_err();
2622        assert!(err.contains("F32"), "{err}");
2623    }
2624
2625    #[test]
2626    fn wire_refuses_unversioned_delta_state() {
2627        // The versioned wire carries the operator identity, so a delta
2628        // layer exports; only the OLD unversioned body is refused.
2629        let mut c = LayerKvCache::new(1, 4);
2630        c.set_linear_wire_allowed(false);
2631        let bytes = c.export_wire(false).expect("v2 export carries identity");
2632        assert_eq!(&bytes[..4], WIRE_MAGIC);
2633        let err = c.import_wire(&[0, 0, 0, 0]).unwrap_err();
2634        assert!(err.contains("operator identity"), "{err}");
2635    }
2636
2637    #[test]
2638    fn wire_v2_round_trips_linear_and_bounded_records() {
2639        // Linear record: the recurrent vector travels f32 whatever the
2640        // wire dtype and the per-position stores come back empty.
2641        let mut a = LayerKvCache::new(1, 4);
2642        a.wire_kind = WireKind::Linear;
2643        a.wire_identity = 0xC0FFEE;
2644        a.linear_state = vec![0.5, -0.25, 1.0, 3.5];
2645        a.seq_len = 9;
2646        let bytes = a.export_wire(true).unwrap();
2647        let mut b = LayerKvCache::new(1, 4);
2648        b.wire_kind = WireKind::Linear;
2649        b.wire_identity = 0xC0FFEE;
2650        b.import_wire(&bytes).unwrap();
2651        assert_eq!(b.linear_state, a.linear_state);
2652        assert_eq!(b.seq_len, 9);
2653        // Identity mismatch is a refusal, not a warning.
2654        let mut c = LayerKvCache::new(1, 4);
2655        c.wire_kind = WireKind::Linear;
2656        let err = c.import_wire(&bytes).unwrap_err();
2657        assert!(err.contains("operator identity"), "{err}");
2658
2659        // Bounded record, f32 and f16 rings.
2660        let (kvh, hd, w) = (2, 4, 8);
2661        let mut a = LayerKvCache::new(kvh, hd);
2662        a.install_bounded(w);
2663        let k: Vec<f32> = (0..kvh * hd).map(|i| i as f32 * 0.125).collect();
2664        for p in 0..11 {
2665            a.bounded.as_mut().unwrap().insert(&k, &k);
2666            a.seq_len = p + 1;
2667        }
2668        for f16 in [false, true] {
2669            let bytes = a.export_wire(f16).unwrap();
2670            let mut b = LayerKvCache::new(kvh, hd);
2671            b.install_bounded(w);
2672            b.import_wire(&bytes).unwrap();
2673            let (ra, rb) = (a.bounded.as_ref().unwrap(), b.bounded.as_ref().unwrap());
2674            assert_eq!(rb.seen, 11);
2675            assert_eq!(b.seq_len, 11);
2676            // 0.125 multiples are exact in f16, so both dtypes round-trip bit for bit.
2677            assert!(ra.same_state(rb), "f16={f16}");
2678            // A ring of another width refuses the record.
2679            let mut c = LayerKvCache::new(kvh, hd);
2680            c.install_bounded(w * 2);
2681            assert!(c.import_wire(&bytes).is_err());
2682        }
2683    }
2684
2685    #[test]
2686    fn wire_import_checks_geometry() {
2687        let a = LayerKvCache::new(2, 4);
2688        let bytes = a.export_wire(false).unwrap();
2689        let mut wrong = LayerKvCache::new(2, 8);
2690        let err = wrong.import_wire(&bytes).unwrap_err();
2691        assert!(err.contains("2×4"), "{err}");
2692    }
2693
2694    #[test]
2695    fn append_tracks_seq_len_and_layout() {
2696        let mut cache = LayerKvCache::new(4, 8);
2697        cache.mode = KvMode::F32;
2698        assert_eq!(cache.seq_len, 0);
2699
2700        let k: Vec<f32> = (0..32).map(|i| i as f32).collect();
2701        let v = vec![2.0f32; 32];
2702        cache.append(&k, &v, &[true; 4]);
2703
2704        assert_eq!(cache.seq_len, 1);
2705        assert_eq!(cache.head_len(0), 1);
2706        // head 1 slice is contiguous and equals its part of k_new
2707        assert_eq!(cache.head_keys(1), &k[8..16]);
2708        assert_eq!(cache.memory_bytes(), 256);
2709    }
2710
2711    #[test]
2712    fn dead_head_stores_nothing() {
2713        let mut cache = LayerKvCache::new(2, 4);
2714        cache.mode = KvMode::F32;
2715        let k = vec![1.0f32; 8];
2716        let v = vec![2.0f32; 8];
2717        cache.append(&k, &v, &[true, false]);
2718        cache.append(&k, &v, &[true, false]);
2719
2720        assert_eq!(cache.seq_len, 2);
2721        assert_eq!(cache.head_len(0), 2);
2722        assert_eq!(cache.head_len(1), 0, "dead head must not store KV");
2723        assert_eq!(cache.memory_bytes(), 2 * 2 * 4 * 4);
2724    }
2725
2726    #[test]
2727    fn eviction_keeps_recent() {
2728        let mut cache = KvCache::new(2, 4, 8, 10);
2729        cache.policy = EvictionPolicy::Recent;
2730        for l in &mut cache.layers {
2731            l.mode = KvMode::F32;
2732        }
2733        let k = vec![1.0f32; 32];
2734        let v = vec![2.0f32; 32];
2735        for _ in 0..8 {
2736            for layer in &mut cache.layers {
2737                layer.append(&k, &v, &[true; 4]);
2738            }
2739        }
2740        assert_eq!(cache.seq_len(), 8);
2741        assert!(!cache.needs_eviction());
2742
2743        cache.evict(4);
2744        assert_eq!(cache.seq_len(), 4);
2745        assert_eq!(cache.layers[0].head_len(0), 4);
2746    }
2747
2748    /// A batch that ends exactly on the deferred boundary holds only exact
2749    /// rows and must stay on the batched path; only a batch that would
2750    /// append a row past the boundary is split. (Walking the boundary chunk
2751    /// row by row sent the 27B's last prefix rows down another projection
2752    /// route than every other prefix row and flipped its O(1) generation.)
2753    #[test]
2754    fn o1_batch_ending_on_boundary_does_not_cross_it() {
2755        const B: usize = 19;
2756        let mut layer = KvCache::new(1, 1, 4, 64).layers.remove(0);
2757        layer.mode = KvMode::F32;
2758        layer.o1_begin_with_boundary(4, 8, 2, crate::nystrom::O1Rect::Aggregate, Some(B));
2759        for _ in 0..B - 3 {
2760            layer.o1_push_q(&[0.1; 8]);
2761            layer.append(&[0.2; 4], &[0.3; 4], &[]);
2762        }
2763        assert!(!layer.o1_boundary_crossed_by(1));
2764        assert!(
2765            !layer.o1_boundary_crossed_by(3),
2766            "ends on B: exact rows only"
2767        );
2768        assert!(layer.o1_boundary_crossed_by(4), "row B+1 must not be exact");
2769        for _ in 0..3 {
2770            layer.o1_push_q(&[0.1; 8]);
2771            layer.append(&[0.2; 4], &[0.3; 4], &[]);
2772        }
2773        assert!(layer.o1_boundary_crossed_by(1), "at B every row is past it");
2774    }
2775
2776    #[test]
2777    fn collecting_o1_eviction_retains_exact_storage_until_boundary() {
2778        const B: usize = 19;
2779        let q = vec![0.1f32; 8];
2780        let k = vec![0.2f32; 4];
2781        let v = vec![0.3f32; 4];
2782
2783        for policy in [EvictionPolicy::Recent, EvictionPolicy::Born { sink: 2 }] {
2784            let mut cache = KvCache::new(1, 1, 4, 6);
2785            cache.policy = policy;
2786            cache.layers[0].mode = KvMode::F32;
2787            cache.layers[0].o1_begin_with_boundary(
2788                4,
2789                8,
2790                2,
2791                crate::nystrom::O1Rect::Aggregate,
2792                Some(B),
2793            );
2794
2795            for pos in 0..B {
2796                {
2797                    let layer = &mut cache.layers[0];
2798                    layer.o1_push_q(&q);
2799                    layer.append(&k, &v, &[]);
2800                }
2801                if pos + 1 < B {
2802                    cache.evict(3);
2803                }
2804            }
2805
2806            let layer = &cache.layers[0];
2807            let rows = B * layer.head_dim;
2808            assert_eq!(layer.seq_len, B, "policy {policy:?} retained depth");
2809            assert_eq!(layer.k[0].len(), rows, "policy {policy:?} K rows");
2810            assert_eq!(layer.v[0].len(), rows, "policy {policy:?} V rows");
2811            assert!(
2812                layer.k[0].capacity() >= rows,
2813                "policy {policy:?} K capacity"
2814            );
2815            assert!(
2816                layer.v[0].capacity() >= rows,
2817                "policy {policy:?} V capacity"
2818            );
2819            let q_capacity = match layer.o1.as_ref() {
2820                Some(O1State::Collecting { q_buf, .. }) => q_buf.capacity(),
2821                other => panic!("policy {policy:?} changed state early: {other:?}"),
2822            };
2823            assert!(
2824                q_capacity >= B * 8,
2825                "policy {policy:?} Q capacity must cover the exact prefix"
2826            );
2827
2828            assert!(cache.layers[0].o1_seal_checked(2).unwrap());
2829            assert_eq!(cache.layers[0].k[0].capacity(), 0, "K released after seal");
2830            assert_eq!(cache.layers[0].v[0].capacity(), 0, "V released after seal");
2831        }
2832    }
2833
2834    #[test]
2835    fn truncate_rolls_back_speculative_positions() {
2836        let mut cache = LayerKvCache::new(2, 4);
2837        cache.mode = KvMode::F32;
2838        for pos in 0..5 {
2839            let k = vec![pos as f32; 8];
2840            let v = vec![pos as f32; 8];
2841            cache.append(&k, &v, &[true; 2]);
2842        }
2843        cache.truncate_last(2);
2844        assert_eq!(cache.seq_len, 3);
2845        assert_eq!(cache.head_len(0), 3);
2846        assert_eq!(cache.head_keys(0)[2 * 4], 2.0, "position 2 survives");
2847    }
2848
2849    /// q8_2f-attend ≈ f32-attend: 100 positions (crosses the field freeze
2850    /// at the 64th), pseudo-random vectors, relative tolerance of the
2851    /// int8 grid. Plus rollback and mass-based eviction on the q8 storage.
2852    #[test]
2853    fn q8_attend_matches_f32_within_grid() {
2854        let (heads, hd) = (2, 32);
2855        let mut f = LayerKvCache::new(heads, hd);
2856        f.mode = KvMode::F32;
2857        let mut q8 = LayerKvCache::new(heads, hd);
2858        q8.mode = KvMode::Q8 { k: true, v: true };
2859
2860        let synth = |p: usize, salt: usize| -> Vec<f32> {
2861            (0..heads * hd)
2862                .map(|i| {
2863                    let x = ((i * 31 + p * 17 + salt * 7 + 3) % 97) as f32 / 97.0 - 0.5;
2864                    // channel structure: even channels ×4 (checks the 2f field)
2865                    if i % 2 == 0 { x * 4.0 } else { x * 0.25 }
2866                })
2867                .collect()
2868        };
2869        for p in 0..100 {
2870            let k = synth(p, 1);
2871            let v = synth(p, 2);
2872            f.append(&k, &v, &[true; 2]);
2873            q8.append(&k, &v, &[true; 2]);
2874        }
2875        let q: Vec<f32> = (0..hd)
2876            .map(|i| ((i * 13 + 5) % 89) as f32 / 89.0 - 0.5)
2877            .collect();
2878        for g in 0..heads {
2879            let (of, pf) = f.attend(&q, g);
2880            let (o8, p8) = q8.attend(&q, g);
2881            let scale = of.iter().fold(0f32, |m, x| m.max(x.abs())).max(1e-6);
2882            for d in 0..hd {
2883                assert!(
2884                    (of[d] - o8[d]).abs() <= scale * 0.03 + 1e-3,
2885                    "g{g} d{d}: f32 {} vs q8 {}",
2886                    of[d],
2887                    o8[d]
2888                );
2889            }
2890            for p in 0..100 {
2891                assert!((pf[p] - p8[p]).abs() < 0.02, "prob p{p}");
2892            }
2893        }
2894        // rollback + eviction live on the q8 storage
2895        q8.truncate_last(30);
2896        assert_eq!(q8.head_len(0), 70);
2897        let imp: Vec<f32> = (0..70).map(|i| i as f32).collect();
2898        q8.accumulate_imp(&imp);
2899        q8.evict_born(20, 2, 8);
2900        assert_eq!(q8.head_len(0), 20);
2901        let (o, _) = q8.attend(&q, 0);
2902        assert!(o.iter().all(|x| x.is_finite()));
2903        // memory: q8 ≈ 1 byte/element + scale per row (vs 4 for f32)
2904        assert!(q8.memory_bytes() * 3 < f.memory_bytes());
2905    }
2906
2907    /// Grouped GQA attend must be bit-identical to per-head attend in
2908    /// every KV mode (it is the same math with rows streamed once).
2909    #[test]
2910    fn attend_group_equals_per_head_attend_bitexact() {
2911        let (kv_heads, hd, hpk) = (2usize, 32usize, 3usize); // 6 Q-heads
2912        for mode in [KvMode::F32, KvMode::Q8 { k: true, v: true }] {
2913            let mut c = LayerKvCache::new(kv_heads, hd);
2914            c.mode = mode;
2915            for p in 0..70 {
2916                let k: Vec<f32> = (0..kv_heads * hd)
2917                    .map(|i| ((i * 31 + p * 17 + 3) % 97) as f32 / 97.0 - 0.5)
2918                    .collect();
2919                let v: Vec<f32> = (0..kv_heads * hd)
2920                    .map(|i| ((i * 13 + p * 29 + 7) % 89) as f32 / 89.0 - 0.5)
2921                    .collect();
2922                c.append(&k, &v, &[true; 2]);
2923            }
2924            let q: Vec<f32> = (0..kv_heads * hpk * hd)
2925                .map(|i| ((i * 11 + 5) % 83) as f32 / 83.0 - 0.5)
2926                .collect();
2927            for g in 0..kv_heads {
2928                let span = g * hpk * hd..(g + 1) * hpk * hd;
2929                let mut out = vec![0f32; hpk * hd];
2930                let mut imp = vec![0f32; 70];
2931                c.attend_group(
2932                    &q[span.clone()],
2933                    g,
2934                    &mut out,
2935                    &mut imp,
2936                    1.0 / (hd as f32).sqrt(),
2937                    0,
2938                    0.0,
2939                    &[],
2940                );
2941                let mut imp_ref = vec![0f32; 70];
2942                for h in 0..hpk {
2943                    let qh = &q[span.start + h * hd..span.start + (h + 1) * hd];
2944                    let (o, probs) = c.attend(qh, g);
2945                    assert_eq!(
2946                        &out[h * hd..(h + 1) * hd],
2947                        &o[..],
2948                        "mode {mode:?} g{g} h{h}: grouped attend must be bit-identical"
2949                    );
2950                    for (dst, &p) in imp_ref.iter_mut().zip(&probs) {
2951                        *dst += p;
2952                    }
2953                }
2954                assert_eq!(
2955                    imp, imp_ref,
2956                    "mode {mode:?} g{g}: attention mass must match"
2957                );
2958            }
2959        }
2960    }
2961
2962    /// Learned sinks (gpt-oss / MiMo-V2): the grouped softmax must equal a
2963    /// softmax over the visible rows PLUS an explicit value-less sink
2964    /// column, computed independently in f64 — at position 0 (one stored
2965    /// row), mid-sequence, and with the window truncating the rows. The
2966    /// importance row must be the row probabilities (the sink's share is
2967    /// nobody's importance).
2968    #[test]
2969    fn sink_attend_matches_explicit_sink_column() {
2970        let (nkv, hd, hpk) = (2usize, 8usize, 3usize);
2971        let rows = 9usize;
2972        let mut c = LayerKvCache::new(nkv, hd);
2973        c.mode = KvMode::F32;
2974        let kv = |r: usize, i: usize, a: usize, m: usize| {
2975            (((r * a + i * 7 + 3) % m) as f32 / m as f32 - 0.5) * 2.0
2976        };
2977        let mut ks = Vec::new();
2978        let mut vs = Vec::new();
2979        for r in 0..rows {
2980            let k: Vec<f32> = (0..nkv * hd).map(|i| kv(r, i, 31, 97)).collect();
2981            let v: Vec<f32> = (0..nkv * hd).map(|i| kv(r, i, 17, 89)).collect();
2982            c.append(&k, &v, &[]);
2983            ks.push(k);
2984            vs.push(v);
2985        }
2986        let q: Vec<f32> = (0..nkv * hpk * hd)
2987            .map(|i| (((i * 11 + 5) % 83) as f32 / 83.0 - 0.5) * 3.0)
2988            .collect();
2989        // Mixed signs and one sink that dominates its head.
2990        let sinks = [0.7f32, -1.3, 2.5, 0.0, -4.0, 6.0];
2991        let scale = 1.0 / (hd as f32).sqrt();
2992        let mut checked = 0usize;
2993        for upto in [1usize, 2, 5, 9] {
2994            for window in [None, Some(3usize), Some(1)] {
2995                let first = window.map(|w| upto.saturating_sub(w)).unwrap_or(0);
2996                for g in 0..nkv {
2997                    let qg = &q[g * hpk * hd..(g + 1) * hpk * hd];
2998                    let sg = &sinks[g * hpk..(g + 1) * hpk];
2999                    let mut out = vec![0f32; hpk * hd];
3000                    let mut imp = vec![0f32; upto];
3001                    c.attend_group_upto(qg, g, &mut out, &mut imp, scale, first, 0.0, upto, sg);
3002                    let mut imp_ref = vec![0f64; upto];
3003                    for h in 0..hpk {
3004                        let qh = &qg[h * hd..(h + 1) * hd];
3005                        // Logits of the visible rows, then the sink column.
3006                        let mut z: Vec<f64> = (first..upto)
3007                            .map(|p| {
3008                                let k = &ks[p][g * hd..(g + 1) * hd];
3009                                qh.iter()
3010                                    .zip(k)
3011                                    .map(|(&a, &b)| a as f64 * b as f64)
3012                                    .sum::<f64>()
3013                                    * scale as f64
3014                            })
3015                            .collect();
3016                        z.push(sg[h] as f64);
3017                        let m = z.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
3018                        let e: Vec<f64> = z.iter().map(|&x| (x - m).exp()).collect();
3019                        let s: f64 = e.iter().sum();
3020                        let p: Vec<f64> = e.iter().map(|&x| x / s).collect();
3021                        // The sink column carries a zero value vector.
3022                        for d in 0..hd {
3023                            let want: f64 = (first..upto)
3024                                .map(|r| p[r - first] * vs[r][g * hd + d] as f64)
3025                                .sum();
3026                            let got = out[h * hd + d] as f64;
3027                            assert!(
3028                                (got - want).abs() < 1e-6,
3029                                "upto {upto} window {window:?} g{g} h{h} d{d}: {got} vs {want}"
3030                            );
3031                        }
3032                        for r in first..upto {
3033                            imp_ref[r] += p[r - first];
3034                        }
3035                        checked += 1;
3036                    }
3037                    for r in 0..upto {
3038                        assert!(
3039                            (imp[r] as f64 - imp_ref[r]).abs() < 1e-6,
3040                            "imp upto {upto} window {window:?} g{g} row {r}: {} vs {}",
3041                            imp[r],
3042                            imp_ref[r]
3043                        );
3044                    }
3045                    // The sink takes real mass: rows sum below 1.
3046                    let row_mass: f32 = imp.iter().sum();
3047                    assert!(row_mass < hpk as f32, "sinks must absorb some mass");
3048                }
3049            }
3050        }
3051        assert_eq!(checked, 4 * 3 * nkv * hpk);
3052    }
3053
3054    /// Scoring only the window's rows must be bit-identical to the former
3055    /// whole-row scoring (−inf outside the window) — with and without a
3056    /// sink, output and importance. The reference is the plain per-head
3057    /// softmax over the same rows written out here.
3058    #[test]
3059    fn windowed_attend_equals_masked_full_row() {
3060        let (nkv, hd, hpk) = (1usize, 16usize, 2usize);
3061        let rows = 40usize;
3062        let mut c = LayerKvCache::new(nkv, hd);
3063        c.mode = KvMode::F32;
3064        for r in 0..rows {
3065            let k: Vec<f32> = (0..hd)
3066                .map(|i| ((r * 13 + i * 5) % 29) as f32 / 29.0 - 0.5)
3067                .collect();
3068            let v: Vec<f32> = (0..hd)
3069                .map(|i| ((r * 7 + i * 3) % 31) as f32 / 31.0 - 0.5)
3070                .collect();
3071            c.append(&k, &v, &[]);
3072        }
3073        let q: Vec<f32> = (0..hpk * hd)
3074            .map(|i| ((i * 19) % 23) as f32 / 23.0 - 0.5)
3075            .collect();
3076        let scale = 0.25f32;
3077        for w in [1usize, 7, 39, 40, 100] {
3078            let first = rows.saturating_sub(w);
3079            let mut out = vec![0f32; hpk * hd];
3080            let mut imp = vec![0f32; rows];
3081            c.attend_group(&q, 0, &mut out, &mut imp, scale, first, 0.0, &[]);
3082            // Reference: the historical full-row −inf-masked kernel.
3083            let mut out_ref = vec![0f32; hpk * hd];
3084            let mut imp_ref = vec![0f32; rows];
3085            for h in 0..hpk {
3086                let mut s = vec![f32::NEG_INFINITY; rows];
3087                for p in first..rows {
3088                    s[p] = crate::attention::dot_f32(
3089                        &q[h * hd..(h + 1) * hd],
3090                        &c.head_keys(0)[p * hd..(p + 1) * hd],
3091                    ) * scale;
3092                }
3093                let m = s.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
3094                let mut sum = 0f32;
3095                for v in s.iter_mut() {
3096                    *v = (*v - m).exp();
3097                    sum += *v;
3098                }
3099                for v in s.iter_mut() {
3100                    *v /= sum;
3101                }
3102                for p in first..rows {
3103                    if s[p].abs() < 1e-12 {
3104                        continue;
3105                    }
3106                    crate::attention::axpy_f32(
3107                        &mut out_ref[h * hd..(h + 1) * hd],
3108                        &c.head_values(0)[p * hd..(p + 1) * hd],
3109                        s[p],
3110                    );
3111                }
3112                for (d, &p) in imp_ref.iter_mut().zip(&s) {
3113                    *d += p;
3114                }
3115            }
3116            let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
3117            assert_eq!(bits(&out), bits(&out_ref), "out window {w}");
3118            assert_eq!(bits(&imp), bits(&imp_ref), "imp window {w}");
3119        }
3120    }
3121
3122    /// Sinks are weights: a new conversation (clear) and a wire import
3123    /// must keep them.
3124    #[test]
3125    fn sinks_survive_clear_and_wire_import() {
3126        let mut c = LayerKvCache::new(1, 4);
3127        c.mode = KvMode::F32;
3128        c.sinks = Some(vec![0.5, -0.5]);
3129        c.append(&[1.0; 4], &[2.0; 4], &[]);
3130        let wire = c.export_wire(false).unwrap();
3131        c.clear();
3132        assert_eq!(c.sinks.as_deref(), Some(&[0.5f32, -0.5][..]));
3133        c.import_wire(&wire).unwrap();
3134        assert_eq!(c.sinks.as_deref(), Some(&[0.5f32, -0.5][..]));
3135        assert_eq!(c.seq_len, 1);
3136    }
3137
3138    /// Review regression: mass-based eviction in MIXED modes. q8v used to
3139    /// panic (gather over an empty v[h]), q8k silently left raw V
3140    /// uncompressed (stale rows under kept keys + memory leak).
3141    #[test]
3142    fn born_eviction_mixed_modes_stay_consistent() {
3143        for (mk, mv) in [(false, true), (true, false)] {
3144            let mut c = LayerKvCache::new(1, 4);
3145            c.mode = KvMode::Q8 { k: mk, v: mv };
3146            for p in 0..80 {
3147                let k = vec![p as f32 * 0.01; 4];
3148                let v = vec![p as f32; 4];
3149                c.append(&k, &v, &[true]);
3150            }
3151            let imp: Vec<f32> = (0..80).map(|i| i as f32).collect();
3152            c.accumulate_imp(&imp);
3153            let before = c.memory_bytes();
3154            c.evict_born(20, 4, 8); // q8v: used to panic here
3155            assert_eq!(c.head_len(0), 20, "k={mk} v={mv}");
3156            assert!(
3157                c.memory_bytes() < before / 2,
3158                "memory must shrink (k={mk} v={mv})"
3159            );
3160            // V rows match the kept set: the heaviest positions
3161            // (tail 60..79) must be present in the attend output.
3162            let (out, _) = c.attend(&[1.0, 1.0, 1.0, 1.0], 0);
3163            assert!(
3164                out[0] > 30.0,
3165                "V from the kept tail, not the stale head (k={mk} v={mv}, out {})",
3166                out[0]
3167            );
3168        }
3169    }
3170
3171    #[test]
3172    fn born_eviction_keeps_high_mass_position() {
3173        let mut cache = KvCache::new(1, 1, 2, 16);
3174        cache.policy = EvictionPolicy::Born { sink: 1 };
3175        for l in &mut cache.layers {
3176            l.mode = KvMode::F32;
3177        }
3178        let layer = &mut cache.layers[0];
3179        // 8 positions; keys carry the position index so we can verify
3180        // exactly which positions survive the gather.
3181        for pos in 0..8 {
3182            let k = vec![pos as f32; 2];
3183            let v = vec![pos as f32 + 100.0; 2];
3184            layer.append(&k, &v, &[true]);
3185        }
3186        // Position 3 carries the most attention mass.
3187        let mut imp = vec![0.05f32; 8];
3188        imp[3] = 5.0;
3189        layer.accumulate_imp(&imp);
3190
3191        cache.evict(4); // sink 1 + recent 2 + 1 top-mass slot
3192        let layer = &cache.layers[0];
3193        assert_eq!(layer.seq_len, 4);
3194        let kept_keys: Vec<f32> = (0..4).map(|i| layer.head_keys(0)[i * 2]).collect();
3195        assert_eq!(
3196            kept_keys,
3197            vec![0.0, 3.0, 6.0, 7.0],
3198            "kept = sink(0) + mass-top(3) + recent(6,7)"
3199        );
3200        // imp stays aligned with the gathered positions.
3201        assert_eq!(layer.head_len(0), 4);
3202    }
3203
3204    // ── Sliding-window tail (trim_window) ──
3205
3206    /// Deterministic row of `n` values in [-1, 1) for position `p`.
3207    fn swa_row(p: usize, n: usize, salt: usize) -> Vec<f32> {
3208        (0..n)
3209            .map(|i| ((p * 7919 + i * 104_729 + salt * 1_299_709) % 2003) as f32 / 1001.5 - 1.0)
3210            .collect()
3211    }
3212
3213    fn bits(v: &[f32]) -> Vec<u32> {
3214        v.iter().map(|x| x.to_bits()).collect()
3215    }
3216
3217    /// The stored tail is the untrimmed cache's rows from `base` on, in
3218    /// order, with the bounds the trigger promises — a dead head included.
3219    #[test]
3220    fn swa_trim_keeps_contiguous_tail() {
3221        let (nkv, hd, w, slack, align) = (2usize, 8usize, 6usize, 2usize, 4usize);
3222        let alive = [true, false];
3223        let mut full = LayerKvCache::new(nkv, hd);
3224        full.mode = KvMode::F32;
3225        let mut t = full.clone();
3226        let mut trims = 0;
3227        for p in 0..100 {
3228            let (k, v) = (swa_row(p, nkv * hd, 1), swa_row(p, nkv * hd, 2));
3229            full.append(&k, &v, &alive);
3230            t.append(&k, &v, &alive);
3231            if t.trim_window(w, slack, align) > 0 {
3232                trims += 1;
3233                assert!(
3234                    (w + slack..w + slack + align).contains(&t.seq_len),
3235                    "rows after a trim: {}",
3236                    t.seq_len
3237                );
3238            }
3239            assert!(t.seq_len <= 2 * w, "rows {} past the trigger", t.seq_len);
3240            assert_eq!(t.pos_len(), p + 1);
3241            assert_eq!(t.base() % align, 0);
3242            assert_eq!(t.base() + t.seq_len, full.seq_len);
3243            let b = t.base();
3244            assert_eq!(t.head_keys(0), &full.head_keys(0)[b * hd..]);
3245            assert_eq!(t.head_values(0), &full.head_values(0)[b * hd..]);
3246            assert!(t.head_keys(1).is_empty() && t.head_values(1).is_empty());
3247            assert_eq!(t.imp.len(), t.seq_len);
3248        }
3249        assert!(trims > 5, "only {trims} trims in 100 positions");
3250        assert_eq!(t.tail_window(), Some(w));
3251        assert_eq!(full.tail_window(), None);
3252    }
3253
3254    /// A tail trimmed under a turn anchor keeps every row the window at the
3255    /// anchor reads, however long the answer runs past it; rolling the whole
3256    /// answer back leaves exactly the untrimmed rows there, and the anchor
3257    /// moved on lets the plain trim drain them again.
3258    #[test]
3259    fn swa_anchored_trim_keeps_the_rollback_window() {
3260        let (nkv, hd, w, slack, align) = (1usize, 4usize, 6usize, 2usize, 4usize);
3261        let alive = [true];
3262        let mut full = LayerKvCache::new(nkv, hd);
3263        full.mode = KvMode::F32;
3264        let mut t = full.clone();
3265        let anchor = 40usize;
3266        for p in 0..100 {
3267            let (k, v) = (swa_row(p, nkv * hd, 1), swa_row(p, nkv * hd, 2));
3268            full.append(&k, &v, &alive);
3269            t.append(&k, &v, &alive);
3270            t.trim_window_anchored(w, slack, align, anchor);
3271            assert!(
3272                t.base() + w <= anchor - slack + 1,
3273                "base {} at {p}",
3274                t.base()
3275            );
3276        }
3277        let back = anchor - slack;
3278        t.truncate_last(t.pos_len() - back);
3279        full.truncate_last(full.pos_len() - back);
3280        assert_eq!(t.pos_len(), back);
3281        let b = t.base();
3282        assert!(t.seq_len >= w - 1);
3283        assert_eq!(t.head_keys(0), &full.head_keys(0)[b * hd..]);
3284        assert_eq!(t.head_values(0), &full.head_values(0)[b * hd..]);
3285        for p in back..back + 3 * w {
3286            let (k, v) = (swa_row(p, nkv * hd, 1), swa_row(p, nkv * hd, 2));
3287            t.append(&k, &v, &alive);
3288            t.trim_window_anchored(w, slack, align, usize::MAX);
3289        }
3290        assert!(t.seq_len <= 2 * w);
3291    }
3292
3293    /// Two caches fed the same rows, one trimmed: every windowed attend
3294    /// (`first = rows − w`) gives the same output and importance, bit for
3295    /// bit, under F32 and the q8 cache — the q8 field freezes at 64 rows,
3296    /// before the first trim.
3297    #[test]
3298    fn swa_trimmed_attend_equals_untrimmed() {
3299        let (nkv, hd, hpk) = (2usize, 16usize, 2usize);
3300        for mode in [KvMode::F32, KvMode::Q8 { k: true, v: true }] {
3301            for (w, slack, align) in [(40usize, 2usize, 4usize), (37, 5, 16), (64, 64, 64)] {
3302                let mut full = LayerKvCache::new(nkv, hd);
3303                full.mode = mode;
3304                let mut t = full.clone();
3305                let scale = 0.3f32;
3306                let mut trims = 0;
3307                for p in 0..400 {
3308                    let (k, v) = (swa_row(p, nkv * hd, 3), swa_row(p, nkv * hd, 4));
3309                    full.append(&k, &v, &[]);
3310                    t.append(&k, &v, &[]);
3311                    let q = swa_row(p, nkv * hpk * hd, 5);
3312                    for g in 0..nkv {
3313                        let qg = &q[g * hpk * hd..(g + 1) * hpk * hd];
3314                        let (nf, nt) = (full.head_len(g), t.head_len(g));
3315                        let (mut of, mut ot) = (vec![0f32; hpk * hd], vec![0f32; hpk * hd]);
3316                        let (mut imf, mut imt) = (vec![0f32; nf], vec![0f32; nt]);
3317                        full.attend_group(
3318                            qg,
3319                            g,
3320                            &mut of,
3321                            &mut imf,
3322                            scale,
3323                            nf.saturating_sub(w),
3324                            0.0,
3325                            &[],
3326                        );
3327                        t.attend_group(
3328                            qg,
3329                            g,
3330                            &mut ot,
3331                            &mut imt,
3332                            scale,
3333                            nt.saturating_sub(w),
3334                            0.0,
3335                            &[],
3336                        );
3337                        assert_eq!(bits(&of), bits(&ot), "{mode:?} w {w} pos {p} group {g}");
3338                        assert_eq!(bits(&imf[t.base()..]), bits(&imt), "{mode:?} w {w} pos {p}");
3339                        full.accumulate_imp(&imf);
3340                        t.accumulate_imp(&imt);
3341                    }
3342                    if t.trim_window(w, slack, align) > 0 {
3343                        trims += 1;
3344                    }
3345                    assert_eq!(bits(&full.imp[t.base()..]), bits(&t.imp));
3346                }
3347                assert!(trims > 0, "{mode:?} w {w}: never trimmed");
3348            }
3349        }
3350    }
3351
3352    /// A rollback no deeper than the slack, then new rows: still the
3353    /// untrimmed answer.
3354    #[test]
3355    fn swa_truncate_after_trim() {
3356        let (nkv, hd, w) = (1usize, 8usize, 10usize);
3357        let mut full = LayerKvCache::new(nkv, hd);
3358        full.mode = KvMode::F32;
3359        let mut t = full.clone();
3360        let mut p = 0usize;
3361        for round in 0..60 {
3362            for _ in 0..3 {
3363                let (k, v) = (swa_row(p, hd, 6), swa_row(p, hd, 7));
3364                full.append(&k, &v, &[]);
3365                t.append(&k, &v, &[]);
3366                p += 1;
3367            }
3368            t.trim_window(w, 2, 4);
3369            // Speculative-style rollback of 2, then replacement rows.
3370            full.truncate_last(2);
3371            t.truncate_last(2);
3372            p -= 2;
3373            assert_eq!(t.pos_len(), full.seq_len);
3374            for _ in 0..2 {
3375                let (k, v) = (swa_row(p, hd, 8 + round), swa_row(p, hd, 9 + round));
3376                full.append(&k, &v, &[]);
3377                t.append(&k, &v, &[]);
3378                p += 1;
3379            }
3380            let q = swa_row(p, hd, 10);
3381            let (nf, nt) = (full.head_len(0), t.head_len(0));
3382            let (mut of, mut ot) = (vec![0f32; hd], vec![0f32; hd]);
3383            let (mut imf, mut imt) = (vec![0f32; nf], vec![0f32; nt]);
3384            full.attend_group(&q, 0, &mut of, &mut imf, 0.5, nf - w.min(nf), 0.0, &[]);
3385            t.attend_group(&q, 0, &mut ot, &mut imt, 0.5, nt - w.min(nt), 0.0, &[]);
3386            assert_eq!(bits(&of), bits(&ot), "round {round}");
3387        }
3388        assert!(t.base() > 0);
3389    }
3390
3391    /// The cache-wide eviction leaves a sliding tail alone, and a tail
3392    /// does not count toward the eviction trigger.
3393    #[test]
3394    fn swa_evict_skips_tail() {
3395        for policy in [EvictionPolicy::Recent, EvictionPolicy::Born { sink: 1 }] {
3396            let mut c = KvCache::new(2, 1, 4, 30);
3397            c.policy = policy;
3398            for p in 0..25 {
3399                for l in &mut c.layers {
3400                    l.append(&swa_row(p, 4, 1), &swa_row(p, 4, 2), &[]);
3401                }
3402                c.layers[0].trim_window(8, 2, 4);
3403            }
3404            let t_rows = c.layers[0].seq_len;
3405            let t_base = c.layers[0].base();
3406            assert!(t_base > 0);
3407            assert!(!c.needs_eviction(), "25 rows < cap 30");
3408            for p in 25..30 {
3409                for l in &mut c.layers {
3410                    l.append(&swa_row(p, 4, 1), &swa_row(p, 4, 2), &[]);
3411                }
3412            }
3413            // Layer 0 (tail, 5 rows past its last trim) is not what triggers.
3414            assert!(c.needs_eviction());
3415            let gen0 = c.layers[0].generation();
3416            c.evict(10);
3417            assert_eq!(c.layers[0].seq_len, t_rows + 5, "{policy:?}: tail evicted");
3418            assert_eq!(c.layers[0].base(), t_base);
3419            assert_eq!(c.layers[0].generation(), gen0);
3420            assert_eq!(
3421                c.layers[1].seq_len, 10,
3422                "{policy:?}: full layer not evicted"
3423            );
3424            assert_eq!(c.seq_len(), 30, "absolute depth from the tail");
3425        }
3426    }
3427
3428    /// `generation` moves on every mutation a device copy cannot follow by its
3429    /// row count, and stays on appends and rollbacks.
3430    #[test]
3431    fn swa_gen_bumps() {
3432        let mut l = LayerKvCache::new(1, 4);
3433        l.mode = KvMode::F32;
3434        let g0 = l.generation();
3435        assert_ne!(
3436            LayerKvCache::new(1, 4).generation(),
3437            g0,
3438            "fresh caches differ"
3439        );
3440        for p in 0..20 {
3441            l.append(&swa_row(p, 4, 1), &swa_row(p, 4, 2), &[]);
3442        }
3443        assert_eq!(l.generation(), g0, "append");
3444        l.truncate_last(2);
3445        assert_eq!(l.generation(), g0, "truncate_last");
3446        assert_eq!(l.trim_window(10, 2, 4), 0, "18 rows ≤ 2w: no trim");
3447        assert_eq!(l.generation(), g0, "a no-op trim");
3448        for p in 18..21 {
3449            l.append(&swa_row(p, 4, 1), &swa_row(p, 4, 2), &[]);
3450        }
3451        assert!(l.trim_window(10, 2, 4) > 0);
3452        let g1 = l.generation();
3453        assert_ne!(g1, g0, "trim");
3454        let snap = l.clone();
3455        l.clear();
3456        let g2 = l.generation();
3457        assert_ne!(g2, g1, "clear");
3458        assert_eq!((l.base(), l.pos_len(), l.tail_window()), (0, 0, Some(10)));
3459        let mut e = LayerKvCache::new(1, 4);
3460        e.mode = KvMode::F32;
3461        for p in 0..12 {
3462            e.append(&swa_row(p, 4, 1), &swa_row(p, 4, 2), &[]);
3463        }
3464        let ge = e.generation();
3465        e.evict(20);
3466        assert_eq!(e.generation(), ge, "an eviction that does nothing");
3467        e.evict(6);
3468        assert_ne!(e.generation(), ge, "evict");
3469        let ge = e.generation();
3470        e.evict_born(3, 1, 1);
3471        assert_ne!(e.generation(), ge, "evict_born");
3472        let mut i = LayerKvCache::new(1, 4);
3473        let gi = i.generation();
3474        i.import_wire(&snap.export_wire(false).unwrap()).unwrap();
3475        assert_ne!(i.generation(), gi, "import");
3476        assert_ne!(
3477            i.generation(),
3478            snap.generation(),
3479            "an import is new storage"
3480        );
3481    }
3482
3483    /// A trimmed layer travels as `FullTail` and answers the same on the
3484    /// far side; an untrimmed one is still byte-for-byte `Full`; a layer
3485    /// with another kind refuses the tail.
3486    #[test]
3487    fn wire_full_tail_roundtrip() {
3488        let (nkv, hd, w) = (2usize, 4usize, 6usize);
3489        let mut a = LayerKvCache::new(nkv, hd);
3490        a.mode = KvMode::F32;
3491        for p in 0..5 {
3492            a.append(&swa_row(p, nkv * hd, 1), &swa_row(p, nkv * hd, 2), &[]);
3493        }
3494        let plain = a.export_wire(false).unwrap();
3495        assert_eq!(plain[20], WireKind::Full as u8, "untrimmed stays Full");
3496        assert_eq!(u64::from_le_bytes(plain[24..32].try_into().unwrap()), 5);
3497        for p in 5..40 {
3498            a.append(&swa_row(p, nkv * hd, 1), &swa_row(p, nkv * hd, 2), &[]);
3499            a.trim_window(w, 2, 4);
3500        }
3501        assert!(a.base() > 0);
3502        for f16 in [false, true] {
3503            let bytes = a.export_wire(f16).unwrap();
3504            assert_eq!(bytes[20], WireKind::FullTail as u8);
3505            assert_eq!(u64::from_le_bytes(bytes[24..32].try_into().unwrap()), 40);
3506            let mut b = LayerKvCache::new(nkv, hd);
3507            b.import_wire(&bytes).expect("tail import");
3508            assert_eq!(
3509                (b.base(), b.seq_len, b.pos_len()),
3510                (a.base(), a.seq_len, 40)
3511            );
3512            if !f16 {
3513                let q = swa_row(99, 2 * hd, 3);
3514                for g in 0..nkv {
3515                    let n = a.head_len(g);
3516                    let (mut oa, mut ob) = (vec![0f32; 2 * hd], vec![0f32; 2 * hd]);
3517                    let (mut ia, mut ib) = (vec![0f32; n], vec![0f32; n]);
3518                    a.attend_group(&q, g, &mut oa, &mut ia, 0.5, n - w, 0.0, &[]);
3519                    b.attend_group(&q, g, &mut ob, &mut ib, 0.5, n - w, 0.0, &[]);
3520                    assert_eq!(bits(&oa), bits(&ob));
3521                }
3522                // ... and a Full import over it puts row 0 back at 0.
3523                b.import_wire(&plain).unwrap();
3524                assert_eq!((b.base(), b.pos_len()), (0, 5));
3525            }
3526        }
3527        // A position that disagrees with base + rows is refused.
3528        let mut bad = a.export_wire(false).unwrap();
3529        bad[24..32].copy_from_slice(&41u64.to_le_bytes());
3530        assert!(LayerKvCache::new(nkv, hd).import_wire(&bad).is_err());
3531        // A bounded layer does not take a tail.
3532        let mut r = LayerKvCache::new(nkv, hd);
3533        r.install_bounded(8);
3534        let err = r.import_wire(&a.export_wire(false).unwrap()).unwrap_err();
3535        assert!(err.contains("does not match"), "{err}");
3536    }
3537}
3538
3539#[cfg(all(test, any(target_arch = "aarch64", target_arch = "x86_64")))]
3540mod chunk_attend_tests {
3541    use super::*;
3542
3543    /// The batched chunk attend against a double-precision softmax
3544    /// attention over the same cache rows: full causal, a window that
3545    /// masks (the GEMM pair then runs over the window's key range only)
3546    /// and a window wider than the context; attention importance too.
3547    /// On macOS this is the Accelerate arm (the NEON arm with
3548    /// CMF_FORCE_NEON_GEMM=1), elsewhere the NEON or AVX2 micro-GEMM.
3549    #[test]
3550    fn attend_chunk_matches_naive_attention() {
3551        let (nkv, hd, hpk) = (2usize, 32usize, 3usize);
3552        let nh = nkv * hpk;
3553        let (s0, b) = (40usize, 48usize);
3554        let n = s0 + b;
3555        let scale = 1.0 / (hd as f32).sqrt();
3556        for window in [None, Some(16usize), Some(200usize)] {
3557            let mut c = LayerKvCache::new(nkv, hd);
3558            c.mode = KvMode::F32;
3559            for p in 0..n {
3560                let k: Vec<f32> = (0..nkv * hd)
3561                    .map(|i| ((i * 31 + p * 17 + 3) % 97) as f32 / 97.0 - 0.5)
3562                    .collect();
3563                let v: Vec<f32> = (0..nkv * hd)
3564                    .map(|i| ((i * 13 + p * 29 + 7) % 89) as f32 / 89.0 - 0.5)
3565                    .collect();
3566                c.append(&k, &v, &[true; 2]);
3567            }
3568            let q: Vec<f32> = (0..b * nh * hd)
3569                .map(|i| ((i * 11 + 5) % 83) as f32 / 83.0 - 0.5)
3570                .collect();
3571            let imp0 = c.imp.clone();
3572            let mut out = vec![0f32; b * nh * hd];
3573            c.attend_chunk(&q, b, s0, nh, hpk, hd, &mut out, None, scale, window);
3574            let mut expect = vec![0f64; b * nh * hd];
3575            let mut imp_ref: Vec<f64> = imp0.iter().map(|&x| x as f64).collect();
3576            for bi in 0..b {
3577                let lim = s0 + bi + 1;
3578                let lo = window.map_or(0, |w| lim.saturating_sub(w));
3579                for hh in 0..nh {
3580                    let g = hh / hpk;
3581                    let qv = &q[bi * nh * hd + hh * hd..][..hd];
3582                    let mut sc: Vec<f64> = (lo..lim)
3583                        .map(|p| {
3584                            let kr = &c.k[g][p * hd..(p + 1) * hd];
3585                            qv.iter().zip(kr).map(|(&x, &y)| x as f64 * y as f64).sum::<f64>()
3586                                * scale as f64
3587                        })
3588                        .collect();
3589                    let mx = sc.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
3590                    let mut z = 0f64;
3591                    for s in sc.iter_mut() {
3592                        *s = (*s - mx).exp();
3593                        z += *s;
3594                    }
3595                    for (idx, p) in (lo..lim).enumerate() {
3596                        let pr = sc[idx] / z;
3597                        if p < imp_ref.len() {
3598                            imp_ref[p] += pr;
3599                        }
3600                        let vr = &c.v[g][p * hd..(p + 1) * hd];
3601                        for d in 0..hd {
3602                            expect[bi * nh * hd + hh * hd + d] += pr * vr[d] as f64;
3603                        }
3604                    }
3605                }
3606            }
3607            for (i, (&x, &y)) in out.iter().zip(&expect).enumerate() {
3608                assert!(
3609                    (x as f64 - y).abs() <= 1e-4,
3610                    "window {window:?} out[{i}]: {x} vs {y}"
3611                );
3612            }
3613            assert_eq!(c.imp.len(), imp0.len(), "window {window:?}: importance length changed");
3614            for (p, (&x, &y)) in c.imp.iter().zip(&imp_ref).enumerate() {
3615                assert!(
3616                    (x as f64 - y).abs() <= 1e-3 * (1.0 + y.abs()),
3617                    "window {window:?} imp[{p}]: {x} vs {y}"
3618                );
3619            }
3620        }
3621    }
3622}