cortiq_engine/nystrom.rs
1//! Nyström (landmark) attention kernel — streaming per-GQA-group runtime
2//! for long-context `attn_type: nystrom` layers.
3//!
4//! Attention splits into an EXACT sliding window (last `w` keys) and a
5//! landmark-skeleton far field sharing ONE joint denominator:
6//!
7//! ```text
8//! out(q_t) = (Σ_{j>t-w} e_j·v_j + F·M·T_far) / (Σ_{j>t-w} e_j + F·M·Z_far)
9//! e_j = exp(q_t·k_j/√d) exact near weights
10//! F_i = exp(q_t·k̃_i/√d) scores vs landmark keys
11//! M = pinv_reg(exp(Q̃·K̃ᵀ/√d)) fixed after prefill
12//! T_far = Σ_{j≤t-w} exp(Q̃·k_j/√d)·v_jᵀ [m × dv]
13//! Z_far = Σ_{j≤t-w} exp(Q̃·k_j/√d) [m]
14//! ```
15//!
16//! exp(q·k) is a PSD kernel, so the UNNORMALIZED skeleton (classic
17//! Nyström/CUR) is legal. Do NOT row-softmax the factors and do NOT
18//! normalize the key scores over landmarks — both "simplifications"
19//! measurably collapse quality (validated in the torch matrix probes).
20//!
21//! Boundary discipline: key j enters T/Z at the exact step it LEAVES
22//! the window (t = j+w) — delayed insertion, no overlap, no hole; the
23//! near mass stays exact rather than Nyström-estimated.
24//!
25//! Sink tokens (spec §5b, StreamingLLM discipline): the first `sink`
26//! keys of the sequence are PERMANENT exact keys — the near mask is
27//! (t-j < w) OR (j < sink) — and must never enter the far accumulators.
28//! Here they never enter the ring window in the first place (they live
29//! in a dedicated buffer), so delayed insertion cannot see them: no
30//! double count, no gap. Measured: sinks make the full 28/28-layer
31//! O(1) conversion viable — the default mode.
32//!
33//! Quality of THIS kernel, measured through it (`cortiq ppl --o1 all`,
34//! Qwen3-0.6B, all 28 layers, m=32 W=128 sink=4, wikitext-2 val, 12×512
35//! windows, landmarks frozen at a 256-token prefill): ×1.296 vs exact
36//! attention over the same scored tokens (28.04 vs 21.63).
37//!
38//! The older ×1.177 figure is NOT this operator: it comes from the torch
39//! matrix probe, which (a) rectifies every per-(t,j) weight — impossible
40//! to stream, the weights are never materialized — (b) builds landmarks
41//! from the FULL sequence rather than the prefill, and (c) averages in
42//! the first W positions, which are pure-exact and cost nothing. Quote
43//! ×1.296 for the runtime; ×1.177 is an upper bound the runtime cannot
44//! reach by construction.
45//!
46//! fp32 numerics: raw exp overflows on real logits, so shifts are
47//! absorbed into diagonals. T̂[i]/Ẑ[i] live at scale e^{-m_i} with a
48//! per-landmark running max m_i (flash-style rescale on growth); each
49//! token's landmark row uses its own shift f; near and far are brought
50//! to one common scale before the single joint division.
51
52/// Which rectifier keeps the skeleton's estimated far mass non-negative.
53///
54/// pinv(exp(Q̃K̃ᵀ/√d)) is violently ill-conditioned, so M is indefinite
55/// and the raw skeleton estimates negative weights for a large minority
56/// of keys (measured on Qwen3-0.6B: 23.5% of far weights negative,
57/// carrying 24.5% of the absolute far mass). Unrectified, the joint
58/// denominator goes near-zero/negative and the model collapses (×510).
59///
60/// The matrix probe rectifies every estimated weight — `west =
61/// ((Fu@Mu)@E).clamp_min(0)`. A STREAMING kernel cannot do that: the
62/// per-(t, j) weights are never materialized, they exist only already
63/// contracted against the accumulators. Two streaming-legal stand-ins:
64///
65/// MEASURED (Qwen3-0.6B, all 28 layers, W=128, sink=4, wikitext-2 val,
66/// 12×512 windows, landmarks frozen at a 256-token prefill — i.e. the
67/// runtime's real discipline, `cortiq ppl --o1`):
68///
69/// ```text
70/// m=8 m=16 m=32
71/// agg 28.51 (×1.318) 28.82 (×1.332) 28.04 (×1.296) ← default
72/// fm 28.97 (×1.340) 29.69 (×1.373) 30.58 (×1.414)
73/// ```
74///
75/// `Aggregate` wins at every m, so it stays the default. `Fm` is kept
76/// selectable because its per-key guarantee is the intuitively "correct"
77/// fix and someone will re-derive it: this table is the evidence that it
78/// costs quality HERE, and the reason is that the guarantee is bought by
79/// destroying signal — clamping a landmark's coefficient zeroes its
80/// contribution to EVERY far key, including the majority where the
81/// weighted sum was already positive and accurate.
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub enum O1Rect {
84 /// Clamp only the AGGREGATE far denominator: a row whose skeleton
85 /// denominator comes out negative drops its far field entirely.
86 /// Coarse — negative per-key mass survives untouched whenever the
87 /// row sum happens to stay positive — but measured BEST (see above):
88 /// the surviving negatives are apparently error-cancelling, not
89 /// error-causing.
90 Aggregate,
91 /// Clamp FM = F_u·M_u (an m-vector, per query row) at zero.
92 /// ŵ(t,j) = Σ_b FM[b]·E[b,j] and E = exp(·) ≥ 0 ELEMENTWISE, so
93 /// FM ≥ 0 is SUFFICIENT for every far weight to be non-negative —
94 /// a per-key guarantee bought with O(m) work on a vector the row
95 /// already materializes, state untouched. It is strictly stronger
96 /// than the probe's clamp (a negative landmark is dropped for every
97 /// key, not only where the sum would go negative), so this is a
98 /// DIFFERENT operator, not an emulation of the matrix reference —
99 /// and, measured, a worse one. Opt in with `--o1-rect fm`.
100 Fm,
101}
102
103/// Ridge factor for the regularized pseudo-inverse of the landmark
104/// kernel: λ = RIDGE_REL · mean(diag(AᵀA)).
105pub const RIDGE_REL: f64 = 1e-6;
106/// The ridge factor of a seal that keeps exact rows beside its far field
107/// (`with_landmarks_from`). A query that reads one of those rows lies off
108/// the landmarks' span, and at 1e-6 the pseudo-inverse turns that into a
109/// far mass of either sign and any size: where it came out large it drowned
110/// the exact row. Aion-1.0-Instruct Turbo answered one planted-fact prompt
111/// of 24 with a loop of two characters, and which prompt depended on where
112/// the landmark means began. From 1e-5 to 1e-1 both prompts read their fact
113/// back under every landmark rule tried; `CMF_O1_RIDGE` sets another factor.
114pub const RIDGE_REL_EXACT: f64 = 1e-4;
115/// `RIDGE_REL_EXACT`, or the factor `CMF_O1_RIDGE` names (1e-6 is the
116/// skeleton as it was).
117fn exact_ridge() -> f64 {
118 static R: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
119 *R.get_or_init(|| std::env::var("CMF_O1_RIDGE").ok().and_then(|s| s.parse::<f64>().ok()).filter(|r| *r > 0.0).unwrap_or(RIDGE_REL_EXACT))
120}
121/// Floor for the joint denominator (mirrors the reference probe).
122const DEN_EPS: f32 = 1e-30;
123/// Prompts of length ≤ w + EXACT_SLACK skip the skeleton entirely:
124/// tiny prefills duplicate segment-mean landmarks (singular Au).
125const EXACT_SLACK: usize = 8;
126
127/// First prompt length that is safe to convert to the streaming skeleton.
128/// Keep this arithmetic checked: the value is also the deferred boundary
129/// stored by the exact KV collector, and a wrapped boundary would turn a
130/// malformed configuration into an immediate or never-ending transition.
131pub(crate) fn o1_deferred_boundary(w: usize, sink: usize) -> Option<usize> {
132 w.checked_add(sink)?
133 .checked_add(EXACT_SLACK)?
134 .checked_add(1)
135}
136
137/// Patent-17 claim 1 probe (`CMF_O1_FARONLY=1`): drop the window from
138/// the READOUT — sinks + far field only — while the ring keeps its
139/// staging role (delayed insertion is untouched). In a GDN hybrid the
140/// near field is carried by the linear-core neighbours; the window is
141/// ~70% of the operator's state and most of its per-token work. Only
142/// engages once the far field holds mass (far_len > 0) — before the
143/// first eviction the window is the only history there is.
144/// Patent-17 claim 9 (`CMF_O1_RESEAL=R`, 0/absent = off): landmarks and
145/// the mixing matrix are FROZEN at prefill, and the deep-layer stream
146/// drifts away from them — measured x3.5-3.9 ppl on the 0.8B hybrid
147/// where the matrix probe reads x1.075. Every R evictions the operator
148/// rebuilds K-landmarks from a ring of recent evicted keys, Q-landmarks
149/// from recent queries, re-inverts M, and re-warms the far accumulators
150/// by re-inserting the ring — sinks and the window stay exact
151/// throughout. Far mass older than the ring is dropped: under drifted
152/// landmarks it was mis-binned anyway, and the ring covers the depth
153/// the ppl gate scores.
154fn reseal_every() -> usize {
155 static R: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
156 *R.get_or_init(|| {
157 std::env::var("CMF_O1_RESEAL")
158 .ok()
159 .and_then(|v| v.parse().ok())
160 .unwrap_or(0)
161 })
162}
163
164/// Sample-ring capacity for reseal (evicted keys/values per group,
165/// recent queries per head).
166const RESEAL_CAP: usize = 256;
167
168fn far_only() -> bool {
169 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
170 *ON.get_or_init(|| std::env::var("CMF_O1_FARONLY").as_deref() == Ok("1"))
171}
172
173/// Control arm (`CMF_O1_NOFAR=1`): read sinks + window only and drop
174/// the far field — StreamingLLM under the same seal. The yardstick the
175/// skeleton has to beat: a far estimate that scores worse than no far
176/// estimate injects wrong mass rather than missing it.
177fn no_far() -> bool {
178 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
179 *ON.get_or_init(|| std::env::var("CMF_O1_NOFAR").as_deref() == Ok("1"))
180}
181
182/// Calibrated skeleton for ONE GQA group (`CMF_O1_CALIB=dir`): landmarks
183/// fixed from a calibration corpus instead of segment means of the
184/// prompt, and optionally a least-squares mixing matrix per Q head in
185/// place of pinv(exp(Q̃K̃ᵀ/√d)). Written by `scripts/o1_calib_fit.py`
186/// from `CMF_O1_CAPTURE` dumps; a layer or group without a file seals
187/// the ordinary way.
188///
189/// File `L{layer}_g{group}.o1c`, little-endian: u32 m, d, q_heads,
190/// has_mu, then f32 K̃ `[m][d]`, Q̃ `[q_heads][m][d]`, and when has_mu
191/// M `[q_heads][m][m]` (row a, column b — the runtime's `mu` layout).
192#[derive(Clone, Debug)]
193pub struct O1Calib {
194 m: usize,
195 k_tilde: Vec<f32>,
196 q_tilde: Vec<Vec<f32>>,
197 mu: Option<Vec<Vec<f32>>>,
198}
199
200impl O1Calib {
201 /// The calibration of (layer, group), or None when `CMF_O1_CALIB` is
202 /// unset or holds no file for it. A file whose geometry disagrees
203 /// with the layer is refused loudly rather than half-applied.
204 pub fn load(layer: u32, group: usize, d: usize, q_heads: usize) -> Option<Self> {
205 let dir = std::env::var("CMF_O1_CALIB").ok()?;
206 let path = std::path::Path::new(&dir).join(format!("L{layer}_g{group}.o1c"));
207 if !path.exists() {
208 return None;
209 }
210 match Self::read(&path, d, q_heads) {
211 Ok(c) => Some(c),
212 Err(e) => {
213 tracing::error!(
214 "o1 calib {}: {e} — layer seals uncalibrated",
215 path.display()
216 );
217 None
218 }
219 }
220 }
221
222 /// Parse one `.o1c` file for a group of `q_heads` heads of width `d`.
223 pub fn read(path: &std::path::Path, d: usize, q_heads: usize) -> Result<Self, String> {
224 let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
225 let u = |i: usize| -> Result<usize, String> {
226 let b = bytes.get(i * 4..i * 4 + 4).ok_or("truncated header")?;
227 Ok(u32::from_le_bytes(b.try_into().unwrap()) as usize)
228 };
229 let (m, fd, fh, has_mu) = (u(0)?, u(1)?, u(2)?, u(3)? != 0);
230 let want = m * d + q_heads * m * d + if has_mu { q_heads * m * m } else { 0 };
231 if fd != d
232 || fh != q_heads
233 || !(4..=O1_MAX_CALIB_M).contains(&m)
234 || bytes.len() != 16 + want * 4
235 {
236 return Err(format!(
237 "geometry m={m} d={fd} heads={fh} ({} bytes) does not fit d={d} heads={q_heads}",
238 bytes.len()
239 ));
240 }
241 let f: Vec<f32> = bytes[16..]
242 .chunks_exact(4)
243 .map(|c| f32::from_le_bytes(c.try_into().unwrap()))
244 .collect();
245 let (kt, rest) = f.split_at(m * d);
246 let (qt, mu) = rest.split_at(q_heads * m * d);
247 Ok(Self::from_parts(
248 m,
249 kt.to_vec(),
250 qt.chunks_exact(m * d).map(<[f32]>::to_vec).collect(),
251 has_mu.then(|| mu.chunks_exact(m * m).map(<[f32]>::to_vec).collect()),
252 ))
253 }
254
255 /// m landmarks: K̃ `[m][d]`, one Q̃ `[m][d]` per head, optionally one
256 /// M `[m][m]` per head.
257 pub fn from_parts(
258 m: usize,
259 k_tilde: Vec<f32>,
260 q_tilde: Vec<Vec<f32>>,
261 mu: Option<Vec<Vec<f32>>>,
262 ) -> Self {
263 O1Calib {
264 m,
265 k_tilde,
266 q_tilde,
267 mu,
268 }
269 }
270}
271
272/// `CMF_O1_WIDE="layer:group,..."` — KV groups whose exact window widens
273/// to `CMF_O1_WIDE_W` keys (default 2048, the device's sink + window cap
274/// with the default 4 sinks). Copying heads lose a key the moment it
275/// leaves the window; a wide window keeps recall exact out to its width
276/// while the state stays O(1). Returns the width for (layer, group).
277pub fn wide_window(layer: u32, group: usize) -> Option<usize> {
278 static CFG: std::sync::OnceLock<(Vec<(u32, usize)>, usize)> = std::sync::OnceLock::new();
279 let (set, w) = CFG.get_or_init(|| {
280 let set = std::env::var("CMF_O1_WIDE")
281 .ok()
282 .map(|v| {
283 v.split(',')
284 .filter_map(|p| {
285 let (l, g) = p.trim().split_once(':')?;
286 Some((l.parse().ok()?, g.parse().ok()?))
287 })
288 .collect()
289 })
290 .unwrap_or_default();
291 let w = std::env::var("CMF_O1_WIDE_W")
292 .ok()
293 .and_then(|v| v.parse().ok())
294 .unwrap_or(2048);
295 (set, w)
296 });
297 set.contains(&(layer, group)).then_some(*w)
298}
299
300/// Landmark budget a calibration file may carry — the device mirror's
301/// limit, so a calibrated seal stays graph-portable.
302const O1_MAX_CALIB_M: usize = 32;
303
304/// `CMF_O1_CAPTURE=dir`: every seal writes each group's prompt queries,
305/// keys and values — the calibration corpus `scripts/o1_calib_fit.py`
306/// reads. File `L{layer}_g{group}_{n}.f32`: u32 t, d, q_heads, then f32
307/// Q `[q_heads][t][d]`, K `[t][d]`, V `[t][d]` (post-RoPE, as the seal
308/// sees them).
309#[allow(clippy::too_many_arguments)]
310pub(crate) fn capture_seal(
311 layer: u32,
312 group: usize,
313 t: usize,
314 d: usize,
315 q_heads: usize,
316 qs: &[f32],
317 ks: &[f32],
318 vs: &[f32],
319) {
320 use std::sync::atomic::{AtomicUsize, Ordering};
321 static N: AtomicUsize = AtomicUsize::new(0);
322 let Ok(dir) = std::env::var("CMF_O1_CAPTURE") else {
323 return;
324 };
325 let n = N.fetch_add(1, Ordering::Relaxed);
326 let path = std::path::Path::new(&dir).join(format!("L{layer}_g{group}_{n:05}.f32"));
327 let mut out = Vec::with_capacity(12 + (qs.len() + ks.len() + vs.len()) * 4);
328 for x in [t, d, q_heads] {
329 out.extend_from_slice(&(x as u32).to_le_bytes());
330 }
331 for x in qs.iter().chain(ks).chain(vs) {
332 out.extend_from_slice(&x.to_le_bytes());
333 }
334 if let Err(e) = std::fs::write(&path, out) {
335 tracing::error!("o1 capture {}: {e}", path.display());
336 }
337}
338
339/// Streaming Nyström attention state for ONE GQA group.
340///
341/// State splits along the GQA grain, because the operator does:
342///
343/// * SHARED per KV group (`NystromGroup`) — the exact window ring, the
344/// sink buffer and the key landmarks K̃. Under GQA every Q head of a
345/// group reads the SAME k/v rows, so all three are bit-identical
346/// across the group; storing them once per group instead of once per
347/// Q head is the point of this split (identical arithmetic,
348/// ×heads_per_kv less window memory). K̃ = seg_means(ks, t, d, m_eff)
349/// is a pure function of the group's keys and of `t` (which fixes
350/// m_eff), so it is shareable for the same reason the keys are.
351/// * PRIVATE per Q head (`NystromHead`) — the far accumulators T̂/Ẑ and
352/// their per-landmark running maxima, the QUERY landmarks Q̃, and the
353/// mixing matrix M = pinv(exp(Q̃K̃ᵀ/√d)). Q̃ is built from that head's
354/// own queries, so M and the far field it drives are per-Q-head and
355/// cannot be shared: the far mass a head accumulates is contracted
356/// against its own query landmarks.
357///
358/// Lifecycle: `new(m, w, sink)` → `prefill(prompt)` once → `step()` per
359/// decode token (single-head façade), or `new_group`/`prefill_group`/
360/// `step_group` for a whole GQA group at once. All buffers are flat
361/// `Vec<f32>`, row-major; the skeleton path performs no allocations
362/// inside `step()`.
363#[derive(Clone, Debug)]
364pub struct NystromState {
365 group: NystromGroup,
366 heads: Vec<NystromHead>,
367 /// Consumed by the seal (`with_calib`); None = segment means + pinv.
368 calib: Option<O1Calib>,
369}
370
371/// The part of the state a GQA group shares: everything derived from
372/// the group's KEYS and VALUES alone (see `NystromState`).
373#[derive(Clone, Debug)]
374struct NystromGroup {
375 /// Landmark budget (m) — effective count may be lower (`m_eff`).
376 m: usize,
377 /// Exact-window width in keys.
378 w: usize,
379 /// The window the layer was configured with. A widened group
380 /// (`with_window`) still decides exact-only against it, so it seals at
381 /// the same boundary as its narrow neighbours — the device needs every
382 /// group of a layer in skeleton mode.
383 base_w: usize,
384 /// Permanent exact sink keys at positions 0..sink (spec §5b).
385 sink: usize,
386 /// Rows of the seal's order before this one stay out of the landmark
387 /// means (`with_landmarks_from`): the rows a seal keeps exact behind the
388 /// sinks. 0 = every row, the historical means.
389 lm_from: usize,
390 /// Ridge factor of the skeleton's pseudo-inverse (`RIDGE_REL`, or
391 /// `RIDGE_REL_EXACT` beside exact rows).
392 ridge: f64,
393 d: usize,
394 dv: usize,
395 /// Effective landmark count: clamp(t/8, 4, m) at prefill. Derived
396 /// from the prompt length, hence equal for every head of the group.
397 m_eff: usize,
398 /// Short-prompt mode: window holds ALL keys, no skeleton. The
399 /// buffer grows on decode, so this mode may allocate in `step()` —
400 /// acceptable for the ≤ w+8-token degenerate case.
401 exact_only: bool,
402 scale: f32,
403 /// Window keys `[cap][d]` — ring buffer in skeleton mode (cap = w),
404 /// append-only in exact-only mode.
405 win_k: Vec<f32>,
406 /// Window values `[cap][dv]`.
407 win_v: Vec<f32>,
408 win_len: usize,
409 /// Ring slot of the OLDEST window entry (0 while not yet full).
410 win_head: usize,
411 /// Sink keys `[sink_len][d]` — filled once at prefill, immutable.
412 sink_k: Vec<f32>,
413 /// Sink values `[sink_len][dv]`.
414 sink_v: Vec<f32>,
415 /// Number of stored sink tokens (0 in exact-only mode, where every
416 /// key is permanent-exact anyway).
417 sink_len: usize,
418 /// Key landmarks `[m_eff][d]` — segment means of the group's keys.
419 k_tilde: Vec<f32>,
420 /// Reseal sample ring: recent EVICTED keys/values (chronological
421 /// via `samp_head`), empty unless CMF_O1_RESEAL is set.
422 samp_k: Vec<f32>,
423 samp_v: Vec<f32>,
424 samp_len: usize,
425 samp_head: usize,
426 /// Evictions since the last reseal.
427 since_reseal: usize,
428}
429
430/// The part of the state that is private to one Q head: everything that
431/// touches that head's QUERIES (see `NystromState`).
432#[derive(Clone, Debug)]
433struct NystromHead {
434 /// How the indefinite skeleton is rectified (see `O1Rect`).
435 rect: O1Rect,
436 /// Far numerator `[m_eff][dv]`, stored at scale e^{-m_max[i]}.
437 t_hat: Vec<f32>,
438 /// Far denominator `[m_eff]`, same scale.
439 z_hat: Vec<f32>,
440 /// Per-landmark running max of far logits q̃_i·k_j/√d.
441 m_max: Vec<f32>,
442 /// Number of keys absorbed into the far field.
443 far_len: usize,
444 /// Query landmarks `[m_eff][d]` (segment means of the prefill).
445 q_tilde: Vec<f32>,
446 /// Regularized pseudo-inverse of Au = exp(Q̃·K̃ᵀ/√d), `[m_eff][m_eff]`.
447 mu: Vec<f32>,
448 // Scratch preallocated at prefill so skeleton-mode step() is
449 // allocation-free. Per head rather than per group: the heads of a
450 // group write it independently, and it is ~0.5 KB.
451 scr_s: Vec<f32>,
452 scr_fh: Vec<f32>,
453 scr_u: Vec<f32>,
454 scr_l: Vec<f32>,
455 /// Reseal: ring of this head's recent queries.
456 samp_q: Vec<f32>,
457 samp_q_len: usize,
458 samp_q_head: usize,
459}
460
461/// Everything `step()`/`advance()` mutate, captured before a
462/// speculative burst and restored bit-for-bit on rejection. The whole
463/// point of the O(1) operator is that this is SMALL — the window ring
464/// plus the far accumulators, ~150 KB a head-group — so speculation,
465/// which Patent 16 disclaims as impossible over the irreversible far
466/// insertion, becomes a memcpy. Immutable-after-seal parts (sinks,
467/// landmarks, mu) are not captured.
468pub struct O1Snapshot {
469 win_k: Vec<f32>,
470 win_v: Vec<f32>,
471 win_len: usize,
472 win_head: usize,
473 /// Per head: (t_hat, z_hat, m_max, far_len).
474 heads: Vec<(Vec<f32>, Vec<f32>, Vec<f32>, usize)>,
475}
476
477impl NystromState {
478 pub fn snapshot(&self) -> O1Snapshot {
479 O1Snapshot {
480 win_k: self.group.win_k.clone(),
481 win_v: self.group.win_v.clone(),
482 win_len: self.group.win_len,
483 win_head: self.group.win_head,
484 heads: self
485 .heads
486 .iter()
487 .map(|h| (h.t_hat.clone(), h.z_hat.clone(), h.m_max.clone(), h.far_len))
488 .collect(),
489 }
490 }
491
492 /// Restore a snapshot taken on THIS state (same geometry). The
493 /// exact-only window grows on decode, so the vectors are assigned,
494 /// not copied into.
495 pub fn restore(&mut self, s: &O1Snapshot) {
496 self.group.win_k = s.win_k.clone();
497 self.group.win_v = s.win_v.clone();
498 self.group.win_len = s.win_len;
499 self.group.win_head = s.win_head;
500 debug_assert_eq!(self.heads.len(), s.heads.len());
501 for (h, (t, z, m, fl)) in self.heads.iter_mut().zip(&s.heads) {
502 h.t_hat = t.clone();
503 h.z_hat = z.clone();
504 h.m_max = m.clone();
505 h.far_len = *fl;
506 }
507 }
508}
509
510/// Borrowed view of a sealed group's state for the GPU upload — every
511/// slice the device mirror needs, in the layout the kernels index.
512/// `exact_only` groups (degenerate short prompts) are not portable and
513/// make the caller refuse the GPU path for the layer.
514pub struct O1DeviceView<'a> {
515 pub m_eff: usize,
516 pub w: usize,
517 pub sink_len: usize,
518 pub d: usize,
519 pub dv: usize,
520 pub exact_only: bool,
521 pub scale: f32,
522 pub win_len: usize,
523 pub win_head: usize,
524 pub far_len: usize,
525 pub win_k: &'a [f32],
526 pub win_v: &'a [f32],
527 pub sink_k: &'a [f32],
528 pub sink_v: &'a [f32],
529 pub k_tilde: &'a [f32],
530 pub heads: Vec<O1HeadView<'a>>,
531}
532
533pub struct O1HeadView<'a> {
534 pub rect_fm: bool,
535 pub t_hat: &'a [f32],
536 pub z_hat: &'a [f32],
537 pub m_max: &'a [f32],
538 pub q_tilde: &'a [f32],
539 pub mu: &'a [f32],
540}
541
542impl NystromState {
543 pub fn device_view(&self) -> O1DeviceView<'_> {
544 let g = &self.group;
545 O1DeviceView {
546 m_eff: g.m_eff,
547 w: g.w,
548 sink_len: g.sink_len,
549 d: g.d,
550 dv: g.dv,
551 exact_only: g.exact_only,
552 scale: g.scale,
553 win_len: g.win_len,
554 win_head: g.win_head,
555 far_len: self.heads.first().map_or(0, |h| h.far_len),
556 win_k: &g.win_k,
557 win_v: &g.win_v,
558 sink_k: &g.sink_k,
559 sink_v: &g.sink_v,
560 k_tilde: &g.k_tilde,
561 heads: self
562 .heads
563 .iter()
564 .map(|h| O1HeadView {
565 rect_fm: h.rect == O1Rect::Fm,
566 t_hat: &h.t_hat,
567 z_hat: &h.z_hat,
568 m_max: &h.m_max,
569 q_tilde: &h.q_tilde,
570 mu: &h.mu,
571 })
572 .collect(),
573 }
574 }
575}
576
577impl NystromState {
578 /// Single-head state (`heads_per_kv == 1`, and the shape the kernel
579 /// unit tests use).
580 ///
581 /// `m` — landmark budget (≥ 4; see `O1_DEFAULT_M`),
582 /// `w` — exact window width (validated setting is 128),
583 /// `sink` — permanent exact sink keys (validated default is 4;
584 /// 0 reproduces the sink-free kernel bit-for-bit).
585 /// Rectifier defaults to `O1_DEFAULT_RECT`; override with
586 /// `with_rect` (the golden-parity test pins it explicitly).
587 pub fn new(m: usize, w: usize, sink: usize) -> Self {
588 Self::new_group(m, w, sink, 1)
589 }
590
591 /// State for one GQA group of `q_heads` query heads sharing a KV
592 /// head. The window/sink/K̃ are stored ONCE for the group; each Q
593 /// head keeps its own far field, Q̃ and M.
594 pub fn new_group(m: usize, w: usize, sink: usize, q_heads: usize) -> Self {
595 assert!(m >= 4, "landmark budget must be at least 4");
596 assert!(w >= 1, "window must hold at least one key");
597 assert!(q_heads >= 1, "a GQA group needs at least one query head");
598 NystromState {
599 group: NystromGroup {
600 m,
601 w,
602 base_w: w,
603 sink,
604 lm_from: 0,
605 ridge: RIDGE_REL,
606 d: 0,
607 dv: 0,
608 m_eff: 0,
609 exact_only: true,
610 scale: 0.0,
611 win_k: Vec::new(),
612 win_v: Vec::new(),
613 win_len: 0,
614 win_head: 0,
615 sink_k: Vec::new(),
616 sink_v: Vec::new(),
617 sink_len: 0,
618 k_tilde: Vec::new(),
619 samp_k: Vec::new(),
620 samp_v: Vec::new(),
621 samp_len: 0,
622 samp_head: 0,
623 since_reseal: 0,
624 },
625 heads: (0..q_heads).map(|_| NystromHead::new()).collect(),
626 calib: None,
627 }
628 }
629
630 /// Widen this group's exact window to `w` keys (builder). The
631 /// retrieval lever: a copying head reads every key of the last `w`
632 /// exactly, while the group's state stays a fixed-size ring.
633 /// Landmarks from the rows past the seal's first `from` (its sinks and the
634 /// rows it keeps exact) alone. Those rows never enter the far field, yet
635 /// with the means over every row the first segment held them all: 248
636 /// kept rows — picked for lying far from the landmarks' span — in a
637 /// segment of 816 made its landmark an outlier, the kernel matrix
638 /// ill-conditioned, and Aion's far field answered a 27k-token prompt with
639 /// garbled text from 216 kept rows on. `CMF_O1_LM_ALL=1` keeps the old means.
640 ///
641 /// A seal with such rows (`from > 0`) also takes the stronger ridge of
642 /// `RIDGE_REL_EXACT`.
643 pub fn with_landmarks_from(mut self, from: usize) -> Self {
644 if std::env::var("CMF_O1_LM_ALL").as_deref() != Ok("1") {
645 self.group.lm_from = from;
646 }
647 if from > 0 {
648 self.group.ridge = exact_ridge();
649 }
650 self
651 }
652
653 /// The ridge factor of the skeleton's pseudo-inverse (builder).
654 pub fn with_ridge(mut self, rel: f64) -> Self {
655 assert!(rel > 0.0, "the ridge factor must be positive");
656 self.group.ridge = rel;
657 self
658 }
659
660 pub fn with_window(mut self, w: usize) -> Self {
661 assert!(w >= 1, "window must hold at least one key");
662 self.group.w = w;
663 self
664 }
665
666 /// Seal against a calibrated skeleton (builder; see `O1Calib`).
667 pub fn with_calib(mut self, calib: Option<O1Calib>) -> Self {
668 self.calib = calib.filter(|c| c.q_tilde.len() == self.heads.len());
669 self
670 }
671
672 /// Select the skeleton rectifier for every head of the group
673 /// (builder; see `O1Rect`).
674 pub fn with_rect(mut self, rect: O1Rect) -> Self {
675 for h in &mut self.heads {
676 h.rect = rect;
677 }
678 self
679 }
680
681 /// Query heads in this group.
682 pub fn num_q_heads(&self) -> usize {
683 self.heads.len()
684 }
685
686 /// Keys absorbed into head `head`'s far field. Exposed for the
687 /// delayed-insertion invariant test: eviction is a GROUP event, but
688 /// each head must absorb the evicted key EXACTLY once, so this must
689 /// equal the number of evictions — never a multiple of it.
690 pub fn far_len(&self, head: usize) -> usize {
691 self.heads[head].far_len
692 }
693
694 /// Absorb the whole prompt for a single-head state — see
695 /// `prefill_group`.
696 pub fn prefill(&mut self, qs: &[f32], ks: &[f32], vs: &[f32], t: usize, d: usize, dv: usize) {
697 assert_eq!(self.heads.len(), 1, "use prefill_group for a GQA group");
698 self.prefill_group(&[qs], ks, vs, t, d, dv);
699 }
700
701 /// Absorb the whole prompt for a GQA group: freeze each head's
702 /// landmarks and M, then replay the prompt through the step() state
703 /// semantics (window fill + delayed far insertion). `qs[h]` is that
704 /// head's `[t][d]` query block; `ks` is `[t][d]` and `vs` is
705 /// `[t][dv]` — the group's shared keys/values, row-major.
706 pub fn prefill_group(
707 &mut self,
708 qs: &[&[f32]],
709 ks: &[f32],
710 vs: &[f32],
711 t: usize,
712 d: usize,
713 dv: usize,
714 ) {
715 assert_eq!(qs.len(), self.heads.len(), "one query block per head");
716 for q in qs {
717 assert_eq!(q.len(), t * d);
718 }
719 assert_eq!(ks.len(), t * d);
720 assert_eq!(vs.len(), t * dv);
721
722 let calib = self.calib.take();
723 let Some(k_tilde64) = self.group.prefill_shared(ks, vs, t, d, dv, calib.as_ref()) else {
724 // exact-only: no skeleton, no far field — nothing per head
725 // beyond the score scratch.
726 for h in &mut self.heads {
727 h.seal_exact(t);
728 }
729 return;
730 };
731 for (hi, (h, q)) in self.heads.iter_mut().zip(qs).enumerate() {
732 let fixed = calib
733 .as_ref()
734 .map(|c| (&c.q_tilde[hi][..], c.mu.as_ref().map(|m| &m[hi][..])));
735 h.seal(&self.group, q, t, &k_tilde64, fixed);
736 }
737 // Replay the post-sink prompt ONCE for the group: each key
738 // enters the shared window, evicting the (j-w)-th into every
739 // head's far field.
740 for j in self.group.sink..t {
741 Self::advance(
742 &mut self.group,
743 &mut self.heads,
744 &ks[j * d..(j + 1) * d],
745 &vs[j * dv..(j + 1) * dv],
746 );
747 }
748 }
749
750 /// `prefill_group` without the replay of the far rows: the landmarks,
751 /// each head's skeleton, the sinks and the window as the replay leaves
752 /// them (the last `w` rows, row r in slot (r - sink) % w). Returns the
753 /// rows the replay would have absorbed into the far field
754 /// (`sink..t - w`), for the caller to sum (`set_far_sums`, or
755 /// `replay_far` on the host); None when it absorbs none (exact-only, or no
756 /// row past the window, or the reseal sample ring wants the replay).
757 pub fn prefill_group_split(
758 &mut self,
759 qs: &[&[f32]],
760 ks: &[f32],
761 vs: &[f32],
762 t: usize,
763 d: usize,
764 dv: usize,
765 ) -> Option<std::ops::Range<usize>> {
766 let sink = self.group.sink;
767 if reseal_every() > 0 || t <= sink + self.group.w {
768 self.prefill_group(qs, ks, vs, t, d, dv);
769 return None;
770 }
771 assert_eq!(qs.len(), self.heads.len(), "one query block per head");
772 let calib = self.calib.take();
773 let Some(k_tilde64) = self.group.prefill_shared(ks, vs, t, d, dv, calib.as_ref()) else {
774 for h in &mut self.heads {
775 h.seal_exact(t);
776 }
777 return None;
778 };
779 for (hi, (h, q)) in self.heads.iter_mut().zip(qs).enumerate() {
780 let fixed = calib
781 .as_ref()
782 .map(|c| (&c.q_tilde[hi][..], c.mu.as_ref().map(|m| &m[hi][..])));
783 h.seal(&self.group, q, t, &k_tilde64, fixed);
784 }
785 let g = &mut self.group;
786 let w = g.w;
787 for r in t - w..t {
788 let slot = (r - sink) % w;
789 g.win_k[slot * d..(slot + 1) * d].copy_from_slice(&ks[r * d..(r + 1) * d]);
790 g.win_v[slot * dv..(slot + 1) * dv].copy_from_slice(&vs[r * dv..(r + 1) * dv]);
791 }
792 g.win_len = w;
793 g.win_head = (t - sink) % w;
794 Some(sink..t - w)
795 }
796
797 /// `CMF_O1_SEAL_DIAG=1`: what a sealed group holds, for telling an
798 /// ill-conditioned skeleton from a broken input: the largest |M| entry,
799 /// far mass, far numerator and landmark norms, and whether all are finite.
800 pub fn seal_diag(&self) -> (f32, f32, f32, f32, f32, bool) {
801 let amax = |v: &[f32]| v.iter().fold(0f32, |m, x| m.max(x.abs()));
802 let (mut mu, mut z, mut t, mut q) = (0f32, 0f32, 0f32, 0f32);
803 let mut finite = self.group.k_tilde.iter().all(|x| x.is_finite());
804 for h in &self.heads {
805 mu = mu.max(amax(&h.mu));
806 z = z.max(amax(&h.z_hat));
807 t = t.max(amax(&h.t_hat));
808 q = q.max(amax(&h.q_tilde));
809 finite &= h.mu.iter().chain(&h.z_hat).chain(&h.t_hat).chain(&h.m_max).chain(&h.q_tilde).all(|x| x.is_finite());
810 }
811 (mu, z, t, q, amax(&self.group.k_tilde), finite)
812 }
813
814 /// Landmark count, head width and score scale of a sealed group.
815 pub fn far_geometry(&self) -> (usize, usize, f32) {
816 (self.group.m_eff, self.group.d, self.group.scale)
817 }
818
819 /// Head `h`'s query landmarks `[m_eff][d]`.
820 pub fn far_q_tilde(&self, h: usize) -> &[f32] {
821 &self.heads[h].q_tilde
822 }
823
824 /// Head `h`'s far sums as the replay of `far_len` rows leaves them:
825 /// per landmark the largest logit, the mass and the numerator `[m][dv]`
826 /// at that scale.
827 pub fn set_far_sums(&mut self, h: usize, m_max: &[f32], z_hat: &[f32], t_hat: &[f32], far_len: usize) {
828 let hd = &mut self.heads[h];
829 hd.m_max.copy_from_slice(m_max);
830 hd.z_hat.copy_from_slice(z_hat);
831 hd.t_hat.copy_from_slice(t_hat);
832 hd.far_len = far_len;
833 }
834
835 /// `prefill_group_split` over rows given by index instead of copies: row j
836 /// of the seal's order is row `order[j]` of `ks`/`vs` (`[t][d]`), a head's
837 /// query that row's trace row, `q_trace[(order[j] / stride) * nh + h0 + h]`
838 /// (`[t / stride][nh][d]`). The same state as the split over the ordered
839 /// copies, without making them (on a 64 000-row prompt they were gigabytes
840 /// a layer). None, with the state untouched, where the split would not
841 /// skip the replay or a calibration is loaded: the caller seals the usual way.
842 #[allow(clippy::too_many_arguments)]
843 pub fn seal_gathered(
844 &mut self,
845 ks: &[f32],
846 vs: &[f32],
847 q_trace: &[f32],
848 stride: usize,
849 nh: usize,
850 h0: usize,
851 order: &[u32],
852 t: usize,
853 d: usize,
854 dv: usize,
855 ) -> Option<std::ops::Range<usize>> {
856 self.seal_gathered_rows(ks, d, vs, dv, q_trace, stride, nh, h0, order, t, d, dv)
857 }
858
859 /// `seal_gathered` over rows `ks_row` (`vs_row`) values apart: a group's
860 /// keys inside rows that hold every KV head (`[t][nkv][d]` from the
861 /// group's first value, Dory's slots and archive) as well as its own
862 /// `[t][d]`.
863 #[allow(clippy::too_many_arguments)]
864 pub fn seal_gathered_rows(
865 &mut self,
866 ks: &[f32],
867 ks_row: usize,
868 vs: &[f32],
869 vs_row: usize,
870 q_trace: &[f32],
871 stride: usize,
872 nh: usize,
873 h0: usize,
874 order: &[u32],
875 t: usize,
876 d: usize,
877 dv: usize,
878 ) -> Option<std::ops::Range<usize>> {
879 let (sink, w) = (self.group.sink, self.group.w);
880 let exact_only = o1_deferred_boundary(self.group.base_w, sink).map(|b| t < b).unwrap_or(true);
881 let stride = stride.max(1);
882 if self.calib.is_some()
883 || reseal_every() > 0
884 || exact_only
885 || t <= sink + w
886 || order.len() != t
887 || ks_row < d
888 || vs_row < dv
889 || ks.len() < (t - 1) * ks_row + d
890 || vs.len() < (t - 1) * vs_row + dv
891 || order.iter().any(|&r| r as usize >= t)
892 || q_trace.len() < t.div_ceil(stride) * nh * d
893 || h0 + self.heads.len() > nh
894 {
895 return None;
896 }
897 let g = &mut self.group;
898 g.d = d;
899 g.dv = dv;
900 g.scale = 1.0 / (d as f32).sqrt();
901 g.exact_only = false;
902 g.sink_len = sink;
903 let kr = |j: usize| -> &[f32] { let r = order[j] as usize; &ks[r * ks_row..r * ks_row + d] };
904 let vr = |j: usize| -> &[f32] { let r = order[j] as usize; &vs[r * vs_row..r * vs_row + dv] };
905 g.sink_k = (0..sink).flat_map(kr).copied().collect();
906 g.sink_v = (0..sink).flat_map(vr).copied().collect();
907 g.win_k = vec![0.0; w * d];
908 g.win_v = vec![0.0; w * dv];
909 let m_eff = (t / 8).clamp(4, g.m);
910 g.m_eff = m_eff;
911 let from = g.landmarks_from(t);
912 let k_tilde64 = seg_means_by(t - from, d, m_eff, |j| kr(j + from));
913 g.k_tilde = k_tilde64.iter().map(|&x| x as f32).collect();
914 for r in t - w..t {
915 let slot = (r - sink) % w;
916 g.win_k[slot * d..(slot + 1) * d].copy_from_slice(kr(r));
917 g.win_v[slot * dv..(slot + 1) * dv].copy_from_slice(vr(r));
918 }
919 g.win_len = w;
920 g.win_head = (t - sink) % w;
921 let g = &self.group;
922 for (hi, h) in self.heads.iter_mut().enumerate() {
923 let qr = |j: usize| -> &[f32] {
924 let at = ((order[j + from] as usize / stride) * nh + h0 + hi) * d;
925 &q_trace[at..at + d]
926 };
927 h.seal_tilde(g, seg_means_by(t - from, d, m_eff, qr), &k_tilde64, None);
928 }
929 Some(sink..t - w)
930 }
931
932 /// `replay_far` over rows given by index (`ks[idx[j]]`).
933 pub fn replay_far_idx(&mut self, ks: &[f32], vs: &[f32], idx: &[u32]) {
934 let (d, dv) = (self.group.d, self.group.dv);
935 self.replay_far_idx_rows(ks, d, vs, dv, idx);
936 }
937
938 /// `replay_far_idx` over rows `ks_row` (`vs_row`) values apart (see
939 /// `seal_gathered_rows`).
940 pub fn replay_far_idx_rows(&mut self, ks: &[f32], ks_row: usize, vs: &[f32], vs_row: usize, idx: &[u32]) {
941 let (m_eff, d, dv, scale) = (self.group.m_eff, self.group.d, self.group.dv, self.group.scale);
942 for &r in idx {
943 let r = r as usize;
944 for h in self.heads.iter_mut() {
945 h.far_absorb(m_eff, d, dv, scale, &ks[r * ks_row..r * ks_row + d], &vs[r * vs_row..r * vs_row + dv]);
946 }
947 }
948 }
949
950 /// The far rows of `prefill_group_split` absorbed on the host, in order.
951 pub fn replay_far(&mut self, ks: &[f32], vs: &[f32], rows: std::ops::Range<usize>) {
952 let (m_eff, d, dv, scale) = (self.group.m_eff, self.group.d, self.group.dv, self.group.scale);
953 for j in rows {
954 for h in self.heads.iter_mut() {
955 h.far_absorb(m_eff, d, dv, scale, &ks[j * d..(j + 1) * d], &vs[j * dv..(j + 1) * dv]);
956 }
957 }
958 }
959
960 /// One decode step for a single-head state — see `step_group`.
961 pub fn step(&mut self, q: &[f32], k: &[f32], v: &[f32], out: &mut [f32]) {
962 assert_eq!(self.heads.len(), 1, "use step_group for a GQA group");
963 self.step_group(q, k, v, out);
964 }
965
966 /// One decode step for the whole GQA group. Inserts the group's
967 /// (k, v) ONCE, evicting the oldest window key into every head's far
968 /// accumulators, then writes each head's attention output.
969 /// `q_all` is `[q_heads][d]`, `out_all` is `[q_heads][dv]`.
970 pub fn step_group(&mut self, q_all: &[f32], k: &[f32], v: &[f32], out_all: &mut [f32]) {
971 let (d, dv) = (self.group.d, self.group.dv);
972 assert!(d > 0, "prefill() must run before step()");
973 let nh = self.heads.len();
974 assert_eq!(q_all.len(), nh * d);
975 assert_eq!(k.len(), d);
976 assert_eq!(v.len(), dv);
977 assert_eq!(out_all.len(), nh * dv);
978 // The current token is part of its own near window (t-j = 0),
979 // so insertion happens BEFORE any output is computed.
980 Self::advance(&mut self.group, &mut self.heads, k, v);
981 let rs = reseal_every();
982 for (h, head) in self.heads.iter_mut().enumerate() {
983 let qh = &q_all[h * d..(h + 1) * d];
984 if rs > 0 && !self.group.exact_only {
985 if head.samp_q.is_empty() {
986 head.samp_q = vec![0.0; RESEAL_CAP * d];
987 }
988 let sp = head.samp_q_head;
989 head.samp_q[sp * d..(sp + 1) * d].copy_from_slice(qh);
990 head.samp_q_head = (sp + 1) % RESEAL_CAP;
991 head.samp_q_len = (head.samp_q_len + 1).min(RESEAL_CAP);
992 }
993 head.step(&self.group, qh, &mut out_all[h * dv..(h + 1) * dv]);
994 }
995 if rs > 0 && self.group.since_reseal >= rs && self.group.samp_len >= 2 * self.group.m_eff {
996 self.reseal();
997 }
998 }
999
1000 /// A later pass over the position `step_group` just took: its row is replaced in
1001 /// the window, and the far field keeps what the row's arrival evicted.
1002 pub fn restep_group(&mut self, q_all: &[f32], k: &[f32], v: &[f32], out_all: &mut [f32]) {
1003 let g = &mut self.group;
1004 let (d, dv) = (g.d, g.dv);
1005 assert!(g.win_len > 0, "step_group() must run before restep_group()");
1006 let slot = if g.exact_only || g.win_len < g.w { g.win_len - 1 } else { (g.win_head + g.w - 1) % g.w };
1007 g.win_k[slot * d..(slot + 1) * d].copy_from_slice(k);
1008 g.win_v[slot * dv..(slot + 1) * dv].copy_from_slice(v);
1009 for (h, head) in self.heads.iter_mut().enumerate() {
1010 head.step(&self.group, &q_all[h * d..(h + 1) * d], &mut out_all[h * dv..(h + 1) * dv]);
1011 }
1012 }
1013
1014 /// Rebuild the skeleton against the CURRENT stream (Patent 17):
1015 /// K-landmarks from the ring of recently evicted keys, Q-landmarks
1016 /// from each head's recent queries, M re-inverted, and the far
1017 /// accumulators re-warmed by re-inserting the ring. Sinks and the
1018 /// window are untouched — the exact stores anchor the operator
1019 /// while the approximation refreshes.
1020 fn reseal(&mut self) {
1021 let g = &mut self.group;
1022 let (d, dv, m_eff) = (g.d, g.dv, g.m_eff);
1023 let n = g.samp_len;
1024 // Chronological copies (oldest first) out of the rings.
1025 let start = if n == RESEAL_CAP { g.samp_head } else { 0 };
1026 let mut ks = vec![0.0f32; n * d];
1027 let mut vs = vec![0.0f32; n * dv];
1028 for i in 0..n {
1029 let idx = (start + i) % RESEAL_CAP;
1030 ks[i * d..(i + 1) * d].copy_from_slice(&g.samp_k[idx * d..(idx + 1) * d]);
1031 vs[i * dv..(i + 1) * dv].copy_from_slice(&g.samp_v[idx * dv..(idx + 1) * dv]);
1032 }
1033 let k_tilde64 = seg_means(&ks, n, d, m_eff);
1034 g.k_tilde = k_tilde64.iter().map(|&x| x as f32).collect();
1035 g.since_reseal = 0;
1036 for head in &mut self.heads {
1037 let qn = head.samp_q_len;
1038 if qn < m_eff {
1039 continue; // not enough queries yet — keep the old Q̃/M
1040 }
1041 let qstart = if qn == RESEAL_CAP {
1042 head.samp_q_head
1043 } else {
1044 0
1045 };
1046 let mut qs = vec![0.0f32; qn * d];
1047 for i in 0..qn {
1048 let idx = (qstart + i) % RESEAL_CAP;
1049 qs[i * d..(i + 1) * d].copy_from_slice(&head.samp_q[idx * d..(idx + 1) * d]);
1050 }
1051 let q_tilde64 = seg_means(&qs, qn, d, m_eff);
1052 head.q_tilde = q_tilde64.iter().map(|&x| x as f32).collect();
1053 let mut au = vec![0.0f64; m_eff * m_eff];
1054 for i in 0..m_eff {
1055 for j in 0..m_eff {
1056 let mut s = 0.0f64;
1057 for c in 0..d {
1058 s += q_tilde64[i * d + c] * k_tilde64[j * d + c];
1059 }
1060 au[i * m_eff + j] = (s * g.scale as f64).exp();
1061 }
1062 }
1063 let mu64 = ridge_pinv_rel(&au, m_eff, g.ridge);
1064 head.mu = mu64.iter().map(|&x| x as f32).collect();
1065 // Re-warm: the far field is rebuilt from the ring. Mass
1066 // older than the ring is dropped — under the drifted
1067 // landmarks it was mis-binned anyway.
1068 head.t_hat.iter_mut().for_each(|x| *x = 0.0);
1069 head.z_hat.iter_mut().for_each(|x| *x = 0.0);
1070 head.m_max.iter_mut().for_each(|x| *x = f32::NEG_INFINITY);
1071 head.far_len = 0;
1072 for i in 0..n {
1073 head.far_absorb(
1074 m_eff,
1075 d,
1076 dv,
1077 g.scale,
1078 &ks[i * d..(i + 1) * d],
1079 &vs[i * dv..(i + 1) * dv],
1080 );
1081 }
1082 }
1083 }
1084
1085 /// Heap bytes held by this group's state (shared window + sinks +
1086 /// K̃, plus each head's skeleton and scratch) — feeds the honest
1087 /// "KV+state" memory line, same discipline as counting
1088 /// `linear_state` for the linear core.
1089 pub fn memory_bytes(&self) -> usize {
1090 self.group.memory_bytes()
1091 + self
1092 .heads
1093 .iter()
1094 .map(NystromHead::memory_bytes)
1095 .sum::<usize>()
1096 }
1097
1098 /// Push the group's (k, v) into the shared window. In skeleton mode
1099 /// a full ring first evicts its oldest key (delayed insertion — the
1100 /// key leaves the exact window at this very step).
1101 ///
1102 /// The eviction is a GROUP event: the window is shared, so there is
1103 /// exactly ONE eviction per position, not one per Q head. The far
1104 /// accumulators are per head, though, so that single evicted key is
1105 /// absorbed once into EACH head — one eviction, `q_heads`
1106 /// insertions. Getting this wrong in either direction breaks the
1107 /// boundary invariant (a key enters the far field at exactly the
1108 /// step it leaves the window: no double count, no hole).
1109 fn advance(g: &mut NystromGroup, heads: &mut [NystromHead], k: &[f32], v: &[f32]) {
1110 let (d, dv) = (g.d, g.dv);
1111 if !g.exact_only && g.win_len == g.w {
1112 let slot = g.win_head;
1113 // Every head absorbs the outgoing key BEFORE the slot is
1114 // overwritten by the incoming one.
1115 for h in heads.iter_mut() {
1116 h.far_insert(g, slot);
1117 }
1118 // Reseal sampling: the evicted (k, v) joins the ring the
1119 // next reseal rebuilds landmarks and far mass from.
1120 if reseal_every() > 0 {
1121 if g.samp_k.is_empty() {
1122 g.samp_k = vec![0.0; RESEAL_CAP * d];
1123 g.samp_v = vec![0.0; RESEAL_CAP * dv];
1124 }
1125 let sp = g.samp_head;
1126 g.samp_k[sp * d..(sp + 1) * d].copy_from_slice(&g.win_k[slot * d..(slot + 1) * d]);
1127 g.samp_v[sp * dv..(sp + 1) * dv]
1128 .copy_from_slice(&g.win_v[slot * dv..(slot + 1) * dv]);
1129 g.samp_head = (sp + 1) % RESEAL_CAP;
1130 g.samp_len = (g.samp_len + 1).min(RESEAL_CAP);
1131 g.since_reseal += 1;
1132 }
1133 g.win_k[slot * d..(slot + 1) * d].copy_from_slice(k);
1134 g.win_v[slot * dv..(slot + 1) * dv].copy_from_slice(v);
1135 g.win_head = (g.win_head + 1) % g.w;
1136 } else if g.exact_only {
1137 g.win_k.extend_from_slice(k);
1138 g.win_v.extend_from_slice(v);
1139 g.win_len += 1;
1140 } else {
1141 g.win_k[g.win_len * d..(g.win_len + 1) * d].copy_from_slice(k);
1142 g.win_v[g.win_len * dv..(g.win_len + 1) * dv].copy_from_slice(v);
1143 g.win_len += 1;
1144 }
1145 }
1146}
1147
1148impl NystromGroup {
1149 /// Freeze the group-shared geometry from the prompt's keys/values.
1150 /// Returns the f64 key landmarks (which the heads need at full
1151 /// precision to build Au), or None in exact-only mode.
1152 fn prefill_shared(
1153 &mut self,
1154 ks: &[f32],
1155 vs: &[f32],
1156 t: usize,
1157 d: usize,
1158 dv: usize,
1159 calib: Option<&O1Calib>,
1160 ) -> Option<Vec<f64>> {
1161 self.d = d;
1162 self.dv = dv;
1163 self.scale = 1.0 / (d as f32).sqrt();
1164 self.win_len = 0;
1165 self.win_head = 0;
1166 self.sink_len = 0;
1167 // A runtime seal is only admitted at the first bounded boundary
1168 // (w + sink + slack + 1), so a converted prompt never enters the
1169 // exact-only state. Direct Nystrom users retain the historical
1170 // exact-only behavior for short prefills.
1171 self.exact_only = o1_deferred_boundary(self.base_w, self.sink)
1172 .map(|boundary| t < boundary)
1173 .unwrap_or(true);
1174 if self.exact_only {
1175 // The end of a three-hop silence: exact-only seals are not
1176 // portable to the graph (o1_views -> None), which read as
1177 // "0 of 16 layers sealed" upstairs, which read as a broken
1178 // seal, which read as a broken port. Say the arithmetic.
1179 tracing::info!(
1180 "o1 seal: exact-only (prompt t={t} <= w {} + sink {} + slack {}) — \
1181 not graph-portable; longer prompt or smaller --o1-window lifts it",
1182 self.w,
1183 self.sink,
1184 EXACT_SLACK
1185 );
1186 }
1187
1188 if self.exact_only {
1189 // Everything fits in the exact window (plus slack for a few
1190 // decode steps before Vec growth); no skeleton is built and
1191 // no separate sink buffer is needed — every key is already
1192 // a permanent exact key in this mode.
1193 self.win_k = Vec::with_capacity((t + 64) * d);
1194 self.win_v = Vec::with_capacity((t + 64) * dv);
1195 self.win_k.extend_from_slice(ks);
1196 self.win_v.extend_from_slice(vs);
1197 self.win_len = t;
1198 return None;
1199 }
1200
1201 // Sink tokens: positions 0..sink become permanent exact keys.
1202 // They bypass the ring window entirely, so the delayed-insertion
1203 // path can never move them into the far accumulators.
1204 self.sink_len = self.sink; // skeleton mode guarantees t > sink
1205 self.sink_k = ks[..self.sink * d].to_vec();
1206 self.sink_v = vs[..self.sink * dv].to_vec();
1207 self.win_k = vec![0.0; self.w * d];
1208 self.win_v = vec![0.0; self.w * dv];
1209
1210 if let Some(c) = calib {
1211 // Calibrated: the landmarks do not depend on this prompt.
1212 self.m_eff = c.m;
1213 self.k_tilde = c.k_tilde.clone();
1214 return Some(c.k_tilde.iter().map(|&x| x as f64).collect());
1215 }
1216
1217 // Landmarks: contiguous segment means of the prompt. The
1218 // integer split (i·t)/m matches the reference probe; the clamp
1219 // keeps tiny prompts from producing duplicate landmarks.
1220 let m_eff = (t / 8).clamp(4, self.m);
1221 // Say so when the budget asked for is not the budget used. A
1222 // prefill of 256 caps m_eff at 32, so `--o1-m 64`, `128` and
1223 // `256` all run as 32 and report perplexities identical to the
1224 // last digit — which reads as a saturating method rather than a
1225 // clamp, and cost a sweep before it was noticed. This file's own
1226 // discipline is that a file is either valid or open() fails
1227 // loudly; a flag that silently does nothing is the same defect
1228 // one level up.
1229 if m_eff < self.m {
1230 use std::sync::atomic::{AtomicBool, Ordering};
1231 static SAID: AtomicBool = AtomicBool::new(false);
1232 if !SAID.swap(true, Ordering::Relaxed) {
1233 tracing::warn!(
1234 "o1: landmark budget m={} clamped to m_eff={} — the prefill is {t} tokens \
1235 and the skeleton takes t/8. Prefill at least {} tokens to use the budget \
1236 you asked for.",
1237 self.m,
1238 m_eff,
1239 self.m * 8
1240 );
1241 }
1242 }
1243 self.m_eff = m_eff;
1244 let from = self.landmarks_from(t);
1245 let k_tilde64 = seg_means(&ks[from * d..], t - from, d, m_eff);
1246 self.k_tilde = k_tilde64.iter().map(|&x| x as f32).collect();
1247 Some(k_tilde64)
1248 }
1249
1250 /// The first row of the seal's order the landmark means read: `lm_from`
1251 /// while enough rows are left for `m_eff` segments, else every row.
1252 fn landmarks_from(&self, t: usize) -> usize {
1253 if self.lm_from > 0 && t >= self.lm_from + 8 * self.m_eff.max(1) { self.lm_from } else { 0 }
1254 }
1255
1256 fn memory_bytes(&self) -> usize {
1257 (self.win_k.len()
1258 + self.win_v.len()
1259 + self.sink_k.len()
1260 + self.sink_v.len()
1261 + self.k_tilde.len())
1262 * std::mem::size_of::<f32>()
1263 }
1264}
1265
1266impl NystromHead {
1267 fn new() -> Self {
1268 NystromHead {
1269 rect: O1_DEFAULT_RECT,
1270 t_hat: Vec::new(),
1271 z_hat: Vec::new(),
1272 m_max: Vec::new(),
1273 far_len: 0,
1274 q_tilde: Vec::new(),
1275 mu: Vec::new(),
1276 scr_s: Vec::new(),
1277 scr_fh: Vec::new(),
1278 scr_u: Vec::new(),
1279 scr_l: Vec::new(),
1280 samp_q: Vec::new(),
1281 samp_q_len: 0,
1282 samp_q_head: 0,
1283 }
1284 }
1285
1286 /// exact-only mode: no skeleton state at all, just room to score the
1287 /// growing window.
1288 fn seal_exact(&mut self, t: usize) {
1289 self.far_len = 0;
1290 self.scr_s = Vec::with_capacity(t + 64);
1291 }
1292
1293 /// Freeze this head's query landmarks and mixing matrix against the
1294 /// group's (already frozen) key landmarks. `fixed` = calibrated Q̃
1295 /// and, when the calibration carries one, its fitted M.
1296 fn seal(
1297 &mut self,
1298 g: &NystromGroup,
1299 qs: &[f32],
1300 t: usize,
1301 k_tilde64: &[f64],
1302 fixed: Option<(&[f32], Option<&[f32]>)>,
1303 ) {
1304 let q_tilde64 = match fixed {
1305 Some((qt, _)) => qt.iter().map(|&x| x as f64).collect(),
1306 None => {
1307 let from = g.landmarks_from(t);
1308 seg_means(&qs[from * g.d..], t - from, g.d, g.m_eff)
1309 }
1310 };
1311 self.seal_tilde(g, q_tilde64, k_tilde64, fixed.and_then(|f| f.1));
1312 }
1313
1314 /// The rest of `seal` once the query landmarks are known (`fixed_mu`: a
1315 /// calibrated M).
1316 fn seal_tilde(&mut self, g: &NystromGroup, q_tilde64: Vec<f64>, k_tilde64: &[f64], fixed_mu: Option<&[f32]>) {
1317 let (d, dv, m_eff) = (g.d, g.dv, g.m_eff);
1318 self.far_len = 0;
1319 self.q_tilde = q_tilde64.iter().map(|&x| x as f32).collect();
1320
1321 if let Some(mu) = fixed_mu {
1322 self.mu = mu.to_vec();
1323 } else {
1324 // Au and its regularized pseudo-inverse in f64 — one-off m×m
1325 // work at prefill only; the hot path stays f32.
1326 let mut au = vec![0.0f64; m_eff * m_eff];
1327 for i in 0..m_eff {
1328 for j in 0..m_eff {
1329 let mut s = 0.0f64;
1330 for c in 0..d {
1331 s += q_tilde64[i * d + c] * k_tilde64[j * d + c];
1332 }
1333 au[i * m_eff + j] = (s * g.scale as f64).exp();
1334 }
1335 }
1336 let mu64 = ridge_pinv_rel(&au, m_eff, g.ridge);
1337 self.mu = mu64.iter().map(|&x| x as f32).collect();
1338 }
1339
1340 self.t_hat = vec![0.0; m_eff * dv];
1341 self.z_hat = vec![0.0; m_eff];
1342 self.m_max = vec![f32::NEG_INFINITY; m_eff];
1343 self.scr_s = vec![0.0; g.sink + g.w];
1344 self.scr_fh = vec![0.0; m_eff];
1345 self.scr_u = vec![0.0; m_eff];
1346 self.scr_l = vec![0.0; m_eff];
1347 }
1348
1349 /// This head's output for `q` against the group's current window and
1350 /// sinks and its own far field. The window insertion for this
1351 /// position already happened at group level (`NystromState::advance`).
1352 fn step(&mut self, g: &NystromGroup, q: &[f32], out: &mut [f32]) {
1353 let (d, dv) = (g.d, g.dv);
1354 assert_eq!(q.len(), d);
1355 assert_eq!(out.len(), dv);
1356
1357 // Near field: exact logits over sinks + window, one shared
1358 // shift. Sinks are permanent exact keys (near mask §5b:
1359 // t-j < w OR j < sink); sink_len = 0 in exact-only mode.
1360 let ns = g.sink_len;
1361 let skip_win = far_only() && !g.exact_only && self.far_len > 0;
1362 let n = if skip_win { ns } else { ns + g.win_len };
1363 self.scr_s.resize(n, 0.0);
1364 let mut c = f32::NEG_INFINITY;
1365 for s in 0..ns {
1366 let lg = dot(q, &g.sink_k[s * d..(s + 1) * d]) * g.scale;
1367 self.scr_s[s] = lg;
1368 c = c.max(lg);
1369 }
1370 // Window scores are the decode hot loop — NEON dot (same
1371 // products, regrouped sums; parity-gated by the golden tests).
1372 if !skip_win {
1373 for s in 0..g.win_len {
1374 let lg = crate::attention::dot_f32(q, &g.win_k[s * d..(s + 1) * d]) * g.scale;
1375 self.scr_s[ns + s] = lg;
1376 c = c.max(lg);
1377 }
1378 }
1379
1380 // Far field: shifted skeleton (spec §3). All exp arguments are
1381 // ≤ 0 relative to the joint shift c_all, so nothing overflows.
1382 let mut far_den = 0.0f32;
1383 let mut c_all = c;
1384 let mut have_far = false;
1385 if self.far_len > 0 && !no_far() {
1386 // Per-token row shift f over landmark scores.
1387 let mut f = f32::NEG_INFINITY;
1388 for a in 0..g.m_eff {
1389 let s = crate::attention::dot_f32(q, &g.k_tilde[a * d..(a + 1) * d]) * g.scale;
1390 self.scr_fh[a] = s;
1391 f = f.max(s);
1392 }
1393 for a in 0..g.m_eff {
1394 self.scr_fh[a] = (self.scr_fh[a] - f).exp();
1395 }
1396 // u = (F·e^{-f}) · M — the landmark mixing row (= FM, up to
1397 // the positive factor e^{-f}).
1398 for b in 0..g.m_eff {
1399 let mut s = 0.0f32;
1400 for a in 0..g.m_eff {
1401 s += self.scr_fh[a] * self.mu[a * g.m_eff + b];
1402 }
1403 // FM rectifier: every far weight is Σ_b FM[b]·E[b,j]
1404 // with E ≥ 0 elementwise, so clamping this m-vector is
1405 // enough to make all of them non-negative — the per-key
1406 // guarantee the streaming form otherwise cannot state.
1407 // The row shift e^{-f} and the flash factors below are
1408 // strictly positive, so clamping here or after the
1409 // rescale is the same predicate.
1410 self.scr_u[b] = if self.rect == O1Rect::Fm {
1411 s.max(0.0)
1412 } else {
1413 s
1414 };
1415 }
1416 // Joint scale: the far term b carries e^{f + m_max[b]}, the
1417 // near term e^{c}; take the max so every factor is ≤ 1.
1418 for b in 0..g.m_eff {
1419 c_all = c_all.max(f + self.m_max[b]);
1420 }
1421 for b in 0..g.m_eff {
1422 let gain = self.scr_u[b] * (f + self.m_max[b] - c_all).exp();
1423 self.scr_u[b] = gain;
1424 far_den += gain * self.z_hat[b];
1425 }
1426 // Aggregate guard — the rectifier of `O1Rect::Aggregate`,
1427 // and a second line of defence under `Fm` (where far_den is
1428 // a sum of non-negative terms, so this can only fire on
1429 // rounding): a negative denominator means the skeleton
1430 // estimate is unusable for this row — drop the far field.
1431 if far_den >= 0.0 {
1432 have_far = true;
1433 } else {
1434 far_den = 0.0;
1435 }
1436 }
1437
1438 for o in out.iter_mut() {
1439 *o = 0.0;
1440 }
1441 if have_far {
1442 for b in 0..g.m_eff {
1443 crate::attention::axpy_f32(out, &self.t_hat[b * dv..(b + 1) * dv], self.scr_u[b]);
1444 }
1445 }
1446 let mut den = far_den;
1447 for s in 0..n {
1448 let p = (self.scr_s[s] - c_all).exp();
1449 den += p;
1450 // scr_s rows 0..ns are sinks, the rest are window entries.
1451 let vv = if s < ns {
1452 &g.sink_v[s * dv..(s + 1) * dv]
1453 } else {
1454 &g.win_v[(s - ns) * dv..(s - ns + 1) * dv]
1455 };
1456 crate::attention::axpy_f32(out, vv, p);
1457 }
1458 let den = den.max(DEN_EPS);
1459 for o in out.iter_mut() {
1460 *o /= den;
1461 }
1462 }
1463
1464 /// Absorb the group's window slot into THIS head's far accumulators
1465 /// with the per-landmark flash shift: T̂[i]/Ẑ[i] live at scale
1466 /// e^{-m_max[i]}; when a new logit raises the max, existing mass is
1467 /// rescaled by e^{old-new} (exactly 0 on first insertion, since
1468 /// m_max = -inf).
1469 fn far_insert(&mut self, g: &NystromGroup, slot: usize) {
1470 let (d, dv) = (g.d, g.dv);
1471 // SAFETY of the two slices: slot < w, buffers are w-sized.
1472 let k = &g.win_k[slot * d..(slot + 1) * d];
1473 let v = &g.win_v[slot * dv..(slot + 1) * dv];
1474 // borrow-friendly copies are avoided: far_absorb takes slices.
1475 // (g is &, self is &mut — disjoint.)
1476 let (m_eff, scale) = (g.m_eff, g.scale);
1477 // Runs once per evicted key per head — NEON dot/axpy like the
1478 // decode loop (same products, regrouped sums).
1479 self.far_absorb_slices(m_eff, d, dv, scale, k, v);
1480 }
1481
1482 /// The insertion math itself, over caller-provided (k, v) — shared
1483 /// by the streaming path (window slot) and the reseal re-warm
1484 /// (sample ring).
1485 fn far_absorb(&mut self, m_eff: usize, d: usize, dv: usize, scale: f32, k: &[f32], v: &[f32]) {
1486 self.far_absorb_slices(m_eff, d, dv, scale, k, v);
1487 }
1488
1489 fn far_absorb_slices(
1490 &mut self,
1491 m_eff: usize,
1492 d: usize,
1493 dv: usize,
1494 scale: f32,
1495 k: &[f32],
1496 v: &[f32],
1497 ) {
1498 if self.scr_l.len() < m_eff {
1499 self.scr_l.resize(m_eff, 0.0);
1500 }
1501 for i in 0..m_eff {
1502 self.scr_l[i] = crate::attention::dot_f32(&self.q_tilde[i * d..(i + 1) * d], k) * scale;
1503 }
1504 for i in 0..m_eff {
1505 let l = self.scr_l[i];
1506 if l > self.m_max[i] {
1507 let r = (self.m_max[i] - l).exp();
1508 self.z_hat[i] *= r;
1509 for e in self.t_hat[i * dv..(i + 1) * dv].iter_mut() {
1510 *e *= r;
1511 }
1512 self.m_max[i] = l;
1513 }
1514 let e = (l - self.m_max[i]).exp();
1515 self.z_hat[i] += e;
1516 crate::attention::axpy_f32(&mut self.t_hat[i * dv..(i + 1) * dv], v, e);
1517 }
1518 self.far_len += 1;
1519 }
1520
1521 fn memory_bytes(&self) -> usize {
1522 (self.t_hat.len()
1523 + self.z_hat.len()
1524 + self.m_max.len()
1525 + self.q_tilde.len()
1526 + self.mu.len()
1527 + self.scr_s.len()
1528 + self.scr_fh.len()
1529 + self.scr_u.len()
1530 + self.scr_l.len())
1531 * std::mem::size_of::<f32>()
1532 }
1533}
1534
1535/// Contiguous segment means (the Nyströmformer landmark recipe), f64
1536/// accumulation. The split (i·t)/m matches the Python reference.
1537/// `seg_means` over rows given by index: row j is `row(j)`.
1538fn seg_means_by<'a>(t: usize, d: usize, m: usize, row: impl Fn(usize) -> &'a [f32]) -> Vec<f64> {
1539 let mut out = vec![0.0f64; m * d];
1540 for i in 0..m {
1541 let lo = i * t / m;
1542 let hi = (i + 1) * t / m;
1543 let acc = &mut out[i * d..(i + 1) * d];
1544 for j in lo..hi {
1545 for (a, &x) in acc.iter_mut().zip(row(j)) {
1546 *a += x as f64;
1547 }
1548 }
1549 let inv = 1.0 / (hi - lo) as f64;
1550 for a in acc.iter_mut() {
1551 *a *= inv;
1552 }
1553 }
1554 out
1555}
1556
1557fn seg_means(xs: &[f32], t: usize, d: usize, m: usize) -> Vec<f64> {
1558 let mut out = vec![0.0f64; m * d];
1559 for i in 0..m {
1560 let lo = i * t / m;
1561 let hi = (i + 1) * t / m;
1562 for j in lo..hi {
1563 for c in 0..d {
1564 out[i * d + c] += xs[j * d + c] as f64;
1565 }
1566 }
1567 let inv = 1.0 / (hi - lo) as f64;
1568 for c in 0..d {
1569 out[i * d + c] *= inv;
1570 }
1571 }
1572 out
1573}
1574
1575fn dot(a: &[f32], b: &[f32]) -> f32 {
1576 let mut s = 0.0f32;
1577 for (x, y) in a.iter().zip(b) {
1578 s += x * y;
1579 }
1580 s
1581}
1582
1583/// Regularized pseudo-inverse M = (AᵀA + λI)⁻¹ Aᵀ of a square matrix,
1584/// λ = RIDGE_REL·mean(diag(AᵀA)), solved via Cholesky. f64 internal —
1585/// this runs once per prefill on an m×m matrix (m ≤ 32). If Cholesky
1586/// fails (Au numerically singular despite the m_eff clamp), λ grows
1587/// tenfold — the jitter fallback of the reference probe.
1588/// pub(crate): the FCD polish trainer builds its (constant-in-backward)
1589/// mixing matrix with the SAME solver the runtime seals with.
1590pub(crate) fn ridge_pinv(a: &[f64], n: usize) -> Vec<f64> {
1591 ridge_pinv_rel(a, n, RIDGE_REL)
1592}
1593
1594/// `ridge_pinv` with the ridge factor given: λ = rel·mean(diag(AᵀA)).
1595pub fn ridge_pinv_rel(a: &[f64], n: usize, rel: f64) -> Vec<f64> {
1596 let mut ata = vec![0.0f64; n * n];
1597 for i in 0..n {
1598 for j in 0..n {
1599 let mut s = 0.0;
1600 for k in 0..n {
1601 s += a[k * n + i] * a[k * n + j];
1602 }
1603 ata[i * n + j] = s;
1604 }
1605 }
1606 let mean_diag: f64 = (0..n).map(|i| ata[i * n + i]).sum::<f64>() / n as f64;
1607 let mut lambda = rel * mean_diag.max(f64::MIN_POSITIVE);
1608 for _ in 0..12 {
1609 let mut g = ata.clone();
1610 for i in 0..n {
1611 g[i * n + i] += lambda;
1612 }
1613 if let Some(l) = cholesky(&mut g, n) {
1614 // Solve G·M = Aᵀ column by column; column j of Aᵀ is row j
1615 // of A.
1616 let mut m_out = vec![0.0f64; n * n];
1617 let mut x = vec![0.0f64; n];
1618 for j in 0..n {
1619 let rhs = &a[j * n..(j + 1) * n];
1620 // Forward: L·y = rhs.
1621 for i in 0..n {
1622 let mut s = rhs[i];
1623 for k in 0..i {
1624 s -= l[i * n + k] * x[k];
1625 }
1626 x[i] = s / l[i * n + i];
1627 }
1628 // Backward: Lᵀ·x = y.
1629 for i in (0..n).rev() {
1630 let mut s = x[i];
1631 for k in i + 1..n {
1632 s -= l[k * n + i] * x[k];
1633 }
1634 x[i] = s / l[i * n + i];
1635 }
1636 for i in 0..n {
1637 m_out[i * n + j] = x[i];
1638 }
1639 }
1640 return m_out;
1641 }
1642 lambda *= 10.0;
1643 }
1644 // Unreachable in practice: λ eventually dominates the diagonal.
1645 // Degrade to a scaled identity rather than poison the output.
1646 let mut fallback = vec![0.0f64; n * n];
1647 for i in 0..n {
1648 fallback[i * n + i] = 1.0 / mean_diag.max(f64::MIN_POSITIVE);
1649 }
1650 fallback
1651}
1652
1653// ── Runtime configuration (v1: runtime-level, NOT a format change) ──
1654//
1655// A layer set + {m, w, sink}, resolved in priority order:
1656// 1. CLI flag (`--o1` on run/serve/bench) — explicit user intent;
1657// 2. env `CMF_O1` (all | deepN | i,j,k | off) with CMF_O1_M /
1658// CMF_O1_WINDOW / CMF_O1_SINK parameter overrides;
1659// 3. converter hint in the header JSON (`provenance.o1_attn`,
1660// written by `cortiq convert --o1`) — additive metadata, the
1661// binary envelope is untouched.
1662
1663/// Validated defaults (spec: m=32, W=128, sink=4; sink ablation ×2.39).
1664pub const O1_DEFAULT_M: usize = 32;
1665pub const O1_DEFAULT_W: usize = 128;
1666pub const O1_DEFAULT_SINK: usize = 4;
1667/// Rectifier default (see `O1Rect`).
1668pub const O1_DEFAULT_RECT: O1Rect = O1Rect::Aggregate;
1669
1670/// Which layers run the O(1) kernel.
1671#[derive(Clone, Debug, PartialEq, Eq)]
1672pub enum O1Layers {
1673 All,
1674 /// The N deepest layers (deep-N ladder of the price map; the
1675 /// early stack is the most sink-dependent, depth converts best).
1676 Deep(usize),
1677 /// Explicit layer indices.
1678 List(Vec<usize>),
1679}
1680
1681/// Per-model O(1)-attention setting.
1682#[derive(Clone, Debug)]
1683pub struct O1Cfg {
1684 pub layers: O1Layers,
1685 /// Landmark budget (≥ 4; m=64 measured WORSE — collinear segment
1686 /// means poison the pinv, so don't "help" by raising it).
1687 pub m: usize,
1688 /// Exact-window width — the main quality lever.
1689 pub w: usize,
1690 /// Permanent exact sink keys (StreamingLLM discipline, spec §5b).
1691 pub sink: usize,
1692 /// Skeleton rectifier (see `O1Rect`).
1693 pub rect: O1Rect,
1694}
1695
1696/// Three-state env reading: unset falls through to the header hint,
1697/// `off`/`0` force-disables even a header hint (the escape hatch).
1698pub enum O1Env {
1699 Unset,
1700 Off,
1701 On(O1Cfg),
1702}
1703
1704impl O1Cfg {
1705 /// Parse a layer spec: `all` | `deepN` | `i,j,k`. None = not a spec
1706 /// (also used for `off`/`0`/empty).
1707 pub fn parse_layers(spec: &str) -> Option<O1Layers> {
1708 let s = spec.trim();
1709 match s {
1710 "" | "off" | "0" | "none" => None,
1711 "all" => Some(O1Layers::All),
1712 _ => {
1713 if let Some(n) = s.strip_prefix("deep") {
1714 return n
1715 .parse::<usize>()
1716 .ok()
1717 .filter(|&n| n > 0)
1718 .map(O1Layers::Deep);
1719 }
1720 let idx: Result<Vec<usize>, _> =
1721 s.split(',').map(|p| p.trim().parse::<usize>()).collect();
1722 idx.ok().filter(|v| !v.is_empty()).map(O1Layers::List)
1723 }
1724 }
1725 }
1726
1727 /// Parse a rectifier spec: `agg`/`aggregate` | `fm`. None = not a
1728 /// spec.
1729 pub fn parse_rect(spec: &str) -> Option<O1Rect> {
1730 match spec.trim() {
1731 "agg" | "aggregate" => Some(O1Rect::Aggregate),
1732 "fm" => Some(O1Rect::Fm),
1733 _ => None,
1734 }
1735 }
1736
1737 /// Rectifier from an explicit value, else `CMF_O1_RECT`, else the
1738 /// default.
1739 fn rect_or_env(rect: Option<O1Rect>) -> O1Rect {
1740 rect.or_else(|| {
1741 std::env::var("CMF_O1_RECT")
1742 .ok()
1743 .as_deref()
1744 .and_then(Self::parse_rect)
1745 })
1746 .unwrap_or(O1_DEFAULT_RECT)
1747 }
1748
1749 /// Build from an explicit spec (CLI path). None = `off` or malformed.
1750 /// Explicit m/w/sink/rect beat env overrides beat validated defaults.
1751 pub fn from_spec(
1752 spec: &str,
1753 m: Option<usize>,
1754 w: Option<usize>,
1755 sink: Option<usize>,
1756 rect: Option<O1Rect>,
1757 ) -> Option<O1Cfg> {
1758 let layers = Self::parse_layers(spec)?;
1759 let env = |k: &str| std::env::var(k).ok().and_then(|v| v.parse::<usize>().ok());
1760 Some(O1Cfg {
1761 layers,
1762 // NystromState asserts m ≥ 4 and w ≥ 1 — clamp rather than
1763 // panic deep in the first prefill.
1764 m: m.or_else(|| env("CMF_O1_M")).unwrap_or(O1_DEFAULT_M).max(4),
1765 w: w.or_else(|| env("CMF_O1_WINDOW"))
1766 .unwrap_or(O1_DEFAULT_W)
1767 .max(1),
1768 sink: sink
1769 .or_else(|| env("CMF_O1_SINK"))
1770 .unwrap_or(O1_DEFAULT_SINK),
1771 rect: Self::rect_or_env(rect),
1772 })
1773 }
1774
1775 /// Converter hint from the header JSON: `{"layers": "all"|[i,…],
1776 /// "m": …, "w": …, "sink": …}`. Env parameter overrides still apply
1777 /// (the operator's knob wins over the file's suggestion).
1778 pub fn from_json(v: &serde_json::Value) -> Option<O1Cfg> {
1779 let layers = match v.get("layers") {
1780 Some(serde_json::Value::String(s)) => Self::parse_layers(s)?,
1781 Some(serde_json::Value::Array(a)) => O1Layers::List(
1782 a.iter()
1783 .filter_map(|x| x.as_u64().map(|n| n as usize))
1784 .collect(),
1785 ),
1786 _ => return None,
1787 };
1788 let f = |k: &str| v.get(k).and_then(|x| x.as_u64()).map(|n| n as usize);
1789 let env = |k: &str| std::env::var(k).ok().and_then(|s| s.parse::<usize>().ok());
1790 Some(O1Cfg {
1791 layers,
1792 m: env("CMF_O1_M")
1793 .or_else(|| f("m"))
1794 .unwrap_or(O1_DEFAULT_M)
1795 .max(4),
1796 w: env("CMF_O1_WINDOW")
1797 .or_else(|| f("w"))
1798 .unwrap_or(O1_DEFAULT_W)
1799 .max(1),
1800 sink: env("CMF_O1_SINK")
1801 .or_else(|| f("sink"))
1802 .unwrap_or(O1_DEFAULT_SINK),
1803 // The rectifier is a runtime property of the kernel, not a
1804 // property of the weights — a file hint cannot pin it.
1805 rect: Self::rect_or_env(None),
1806 })
1807 }
1808
1809 /// Per-layer flags over `num_layers` (indices past the end are
1810 /// silently dropped; the pipeline additionally filters non-Full
1811 /// layers — a linear layer keeps its own operator).
1812 pub fn layer_flags(&self, num_layers: usize) -> Vec<bool> {
1813 let mut flags = vec![false; num_layers];
1814 match &self.layers {
1815 O1Layers::All => flags.iter_mut().for_each(|f| *f = true),
1816 O1Layers::Deep(n) => {
1817 for f in flags.iter_mut().skip(num_layers.saturating_sub(*n)) {
1818 *f = true;
1819 }
1820 }
1821 O1Layers::List(idx) => {
1822 for &i in idx {
1823 if i < num_layers {
1824 flags[i] = true;
1825 }
1826 }
1827 }
1828 }
1829 flags
1830 }
1831}
1832
1833/// Read `CMF_O1` (+ parameter overrides) — the embedding-friendly path
1834/// for hosts that don't go through the CLI flags.
1835pub fn o1_from_env() -> O1Env {
1836 match std::env::var("CMF_O1") {
1837 Err(_) => O1Env::Unset,
1838 Ok(s) => match O1Cfg::from_spec(&s, None, None, None, None) {
1839 Some(cfg) => O1Env::On(cfg),
1840 None => O1Env::Off,
1841 },
1842 }
1843}
1844
1845/// In-place lower Cholesky of an SPD matrix; None if a pivot fails.
1846fn cholesky(g: &mut [f64], n: usize) -> Option<&[f64]> {
1847 for i in 0..n {
1848 for j in 0..=i {
1849 let mut s = g[i * n + j];
1850 for k in 0..j {
1851 s -= g[i * n + k] * g[j * n + k];
1852 }
1853 if i == j {
1854 if s <= 0.0 || !s.is_finite() {
1855 return None;
1856 }
1857 g[i * n + i] = s.sqrt();
1858 } else {
1859 g[i * n + j] = s / g[j * n + j];
1860 }
1861 }
1862 }
1863 Some(g)
1864}