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