Skip to main content

cortiq_engine/
dory.rs

1//! NVIDIA Nemotron Labs Dory: a looped normalized GPT.
2//!
3//! The layer stack is three blocks, input, recurrent and output, and the
4//! recurrent block runs `loops` times per token with the input block's output
5//! mixed back in before each pass. A physical layer is one sub-layer, attention
6//! or a SwiGLU MLP, and everything lives on the unit sphere (nGPT):
7//!
8//! ```text
9//! attention  q,k,v,g = W·x; rotate q,k; q = s_q²·q̂, k = k̂ (per head)
10//!            a = softmax(q·k/√hd) over the window, y = Σ a·v (16 q heads over 4 kv heads)
11//!            y = (y ⊙ σ(g ⊙ s_g²))^ , out = O·y
12//! mlp        g,u = W·x ⊙ s·√hidden; y = (silu(g) ⊙ u)^ ; out = D·y
13//! residual   x = (x̂ + |α|·(ôut − x̂))^
14//! loop       state = input; h = (state + input)^; h = R(h); state = ĥ
15//! logits     H·h ⊙ scale / σ₀
16//! ```
17//!
18//! `per_loop` keeps a KV cache per loop; `last_loop` keeps one per recurrent
19//! attention layer, each loop overwriting this chunk's rows. Earlier rows then
20//! hold their last loop's keys, so the loop count can change from token to token
21//! and the cache has no holes.
22
23use crate::pipeline::ArchStore;
24use crate::pool::Pool;
25use crate::qtensor::QTensor;
26use cortiq_core::{CmfModel, DoryConfig, ModelArch};
27use std::sync::Arc;
28
29/// `justnorm`'s epsilon in the reference.
30pub const EPS: f32 = 1e-6;
31pub const ARCH: &str = "dory";
32/// The most loops a request may ask for.
33pub const MAX_LOOPS: usize = 16;
34/// Rows a chat turn may go back on the device: a sliding ring holds the window and
35/// this much, so a turn whose template rewrites the last answer keeps the rest.
36pub const REWIND: usize = 448;
37
38#[derive(Clone, Copy, PartialEq, Eq, Debug)]
39pub enum KvMode {
40    PerLoop,
41    LastLoop,
42}
43
44impl KvMode {
45    pub fn parse(s: &str) -> Option<Self> {
46        match s {
47            "per_loop" => Some(Self::PerLoop),
48            "last_loop" => Some(Self::LastLoop),
49            _ => None,
50        }
51    }
52}
53
54#[derive(Clone, Debug)]
55pub struct DoryCfg {
56    pub hidden: usize,
57    pub ffn: usize,
58    pub vocab: usize,
59    pub nh: usize,
60    pub nk: usize,
61    pub hd: usize,
62    pub window: usize,
63    pub n_in: usize,
64    pub n_rec: usize,
65    pub n_out: usize,
66    pub loops: usize,
67    pub kv: KvMode,
68    pub attn_scale: f32,
69    /// Full layers read at most this many keys and keep no more: a constant cost per
70    /// token and bounded memory at any context length (`CMF_DORY_FULL_WINDOW`).
71    pub full_window: Option<usize>,
72}
73
74pub struct AttnWeights {
75    pub q: QTensor,
76    pub k: QTensor,
77    pub v: QTensor,
78    pub g: QTensor,
79    pub o: QTensor,
80    /// `(sqk·√hd/σ₀)²`
81    pub sq: Vec<f32>,
82    /// `(s_gate·√g₀/σ₀)²`
83    pub sg: Vec<f32>,
84    pub alpha: Vec<f32>,
85    pub sliding: bool,
86    /// Position among the attention layers: the KV slot table's row.
87    pub ordinal: usize,
88}
89
90pub struct MlpWeights {
91    pub gate: QTensor,
92    pub up: QTensor,
93    pub down: QTensor,
94    /// `suv·√hidden`
95    pub sg: Vec<f32>,
96    pub su: Vec<f32>,
97    pub alpha: Vec<f32>,
98}
99
100pub enum Layer {
101    Attn(Box<AttnWeights>),
102    Mlp(Box<MlpWeights>),
103}
104
105pub struct Dory {
106    /// The file, for a device that binds its mapping as it is.
107    pub file: Option<Arc<CmfModel>>,
108    pub cfg: DoryCfg,
109    pub embed: QTensor,
110    pub head: QTensor,
111    /// `logit_scale/σ₀`
112    pub logit_scale: Vec<f32>,
113    pub layers: Vec<Layer>,
114    pub inv_full: Vec<f32>,
115    pub inv_sliding: Vec<f32>,
116    pub attn_layers: usize,
117    pub o1: Option<DoryO1>,
118    /// How a token leaves the loop early, on the last-loop cache.
119    pub gate: Option<Gate>,
120    /// Passes over a prompt chunk whose logits nobody reads (`CMF_DORY_PROMPT_LOOPS`):
121    /// its cache rows are all that stays of it. 0: as many as any other chunk.
122    pub prompt_loops: usize,
123    /// Rows of a sealed prompt the far field would lose (`CMF_DORY_EXACT=FILE:rows`).
124    pub exact: Option<ExactRows>,
125    /// A long prompt's rows go to files here, and to RAM without it (`CMF_O1_SPILL`).
126    pub spill: Option<std::path::PathBuf>,
127}
128
129/// Which rows of a prompt stay exact past the seal: passwords, codes and the like, found
130/// by what the layers do with them and not by what they look like. Per KV head of each
131/// full layer, the part of a key outside the span of the far field's landmarks and the
132/// value's norm, as ranks within the prompt; a linear score over them, fitted on planted
133/// facts (`scripts/dory/router/illum_budget.py`).
134#[derive(Clone)]
135pub struct ExactRows {
136    pub weights: Arc<Vec<f32>>,
137    pub budget: usize,
138}
139
140/// Keys a sealed token reads exactly, on any backend.
141pub const MAX_NEAR: usize = 8192;
142
143/// A sealed prompt's last rows read the chosen ones: a question carries what it found in
144/// the text on to the answer, so the choice comes before it.
145pub const EXACT_TAIL: usize = 512;
146
147/// Neighbours kept on each side of a chosen row: a fact is several tokens.
148const EXACT_NEIGHBOURS: usize = 2;
149
150/// One row in this many of a sealed prompt keeps its queries for the far field's rebuild:
151/// landmark queries are means over long segments, and a row's take 8 KB per full layer.
152pub const QT_STRIDE: usize = 8;
153
154fn rank_share(v: &[f32]) -> Vec<f32> {
155    let n = v.len();
156    let mut idx: Vec<u32> = (0..n as u32).collect();
157    idx.sort_unstable_by(|&a, &b| v[a as usize].total_cmp(&v[b as usize]));
158    let mut out = vec![0f32; n];
159    let d = (n.max(2) - 1) as f32;
160    for (i, &r) in idx.iter().enumerate() {
161        out[r as usize] = i as f32 / d;
162    }
163    out
164}
165
166/// One layer's rows for the choice of exact ones, however its cache lays them out.
167pub trait LayerRows: Sync {
168    fn key(&self, kh: usize, r: usize) -> &[f32];
169    fn value(&self, kh: usize, r: usize) -> &[f32];
170}
171
172/// `[row][nk][hd]`, the layout of Dory's slots.
173pub struct FlatRows<'a> {
174    pub k: &'a [f32],
175    pub v: &'a [f32],
176    pub nk: usize,
177    pub hd: usize,
178}
179
180impl LayerRows for FlatRows<'_> {
181    fn key(&self, kh: usize, r: usize) -> &[f32] {
182        &self.k[(r * self.nk + kh) * self.hd..(r * self.nk + kh + 1) * self.hd]
183    }
184    fn value(&self, kh: usize, r: usize) -> &[f32] {
185        &self.v[(r * self.nk + kh) * self.hd..(r * self.nk + kh + 1) * self.hd]
186    }
187}
188
189/// Per row, how much of a head's key lies outside the span of `m` segment means.
190fn key_residuals(l0: &dyn LayerRows, rows: usize, kh: usize, hd: usize, m: usize) -> Vec<f32> {
191    const RIDGE: f64 = 1e-4;
192    let at = |r: usize| l0.key(kh, r);
193    let mut l = vec![0f32; m * hd];
194    for a in 0..m {
195        let (lo, hi) = (a * rows / m, ((a + 1) * rows / m).max(a * rows / m + 1).min(rows));
196        let row = &mut l[a * hd..(a + 1) * hd];
197        for r in lo..hi {
198            crate::attention::axpy_f32(row, at(r), 1.0);
199        }
200        let f = 1.0 / (hi - lo) as f32;
201        row.iter_mut().for_each(|x| *x *= f);
202    }
203    // The inverse of the landmarks' Gram matrix, by Cholesky.
204    let mut g = vec![0f64; m * m];
205    for a in 0..m {
206        for b in 0..=a {
207            let v = crate::attention::dot_f32(&l[a * hd..(a + 1) * hd], &l[b * hd..(b + 1) * hd]) as f64;
208            g[a * m + b] = v + if a == b { RIDGE } else { 0.0 };
209        }
210    }
211    for a in 0..m {
212        for b in 0..=a {
213            let mut v = g[a * m + b];
214            for c in 0..b {
215                v -= g[a * m + c] * g[b * m + c];
216            }
217            g[a * m + b] = if a == b { v.max(1e-12).sqrt() } else { v / g[b * m + b] };
218        }
219    }
220    let mut inv = vec![0f32; m * m];
221    let mut col = vec![0f64; m];
222    for e in 0..m {
223        for a in 0..m {
224            let mut v = if a == e { 1.0 } else { 0.0 };
225            for c in 0..a {
226                v -= g[a * m + c] * col[c];
227            }
228            col[a] = v / g[a * m + a];
229        }
230        for a in (0..m).rev() {
231            let mut v = col[a];
232            for c in a + 1..m {
233                v -= g[c * m + a] * col[c];
234            }
235            col[a] = v / g[a * m + a];
236        }
237        for a in 0..m {
238            inv[a * m + e] = col[a] as f32;
239        }
240    }
241    let mut y = vec![0f32; m];
242    let mut c = vec![0f32; m];
243    (0..rows)
244        .map(|r| {
245            let k = at(r);
246            for a in 0..m {
247                y[a] = crate::attention::dot_f32(&l[a * hd..(a + 1) * hd], k);
248            }
249            for a in 0..m {
250                c[a] = crate::attention::dot_f32(&inv[a * m..(a + 1) * m], &y);
251            }
252            crate::attention::dot_f32(k, k) - crate::attention::dot_f32(&c, &y) - RIDGE as f32 * crate::attention::dot_f32(&c, &c)
253        })
254        .collect()
255}
256
257/// The rows to keep exact, ascending. `lo..hi` are the rows that can go, which leaves
258/// out the sinks and the window. A row goes with its neighbours until the budget is spent.
259pub fn pick_exact_rows(x: &ExactRows, layers: &[&dyn LayerRows], rows: usize, nk: usize, hd: usize, m: usize, lo: usize, hi: usize) -> Vec<usize> {
260    let hi = hi.min(rows);
261    if hi <= lo || rows < 2 {
262        return Vec::new();
263    }
264    let dump = std::env::var("CMF_DORY_EXACT_FEATURES").ok();
265    if x.weights.len() != layers.len() * 2 * nk && dump.is_none() {
266        return Vec::new();
267    }
268    let m = m.min(rows).max(1);
269    let tasks: Vec<(usize, usize)> = (0..layers.len()).flat_map(|l| (0..nk).map(move |h| (l, h))).collect();
270    let threads = std::thread::available_parallelism().map_or(4, |n| n.get()).min(16).min(tasks.len()).max(1);
271    let next = std::sync::atomic::AtomicUsize::new(0);
272    let total = std::sync::Mutex::new(vec![0f32; rows]);
273    let table = std::sync::Mutex::new(vec![0f32; if dump.is_some() { rows * tasks.len() * 2 } else { 0 }]);
274    std::thread::scope(|sc| {
275        for _ in 0..threads {
276            sc.spawn(|| loop {
277                let t = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
278                let Some(&(l, kh)) = tasks.get(t) else { break };
279                let res = rank_share(&key_residuals(layers[l], rows, kh, hd, m));
280                let vn: Vec<f32> = (0..rows)
281                    .map(|r| {
282                        let v = layers[l].value(kh, r);
283                        crate::attention::dot_f32(v, v)
284                    })
285                    .collect();
286                let vn = rank_share(&vn);
287                if dump.is_some() {
288                    let mut tb = table.lock().unwrap();
289                    let (f0, f1) = ((l * 2) * nk + kh, (l * 2 + 1) * nk + kh);
290                    let nf = tasks.len() * 2;
291                    for r in 0..rows {
292                        tb[r * nf + f0] = res[r];
293                        tb[r * nf + f1] = vn[r];
294                    }
295                }
296                if x.weights.len() == tasks.len() * 2 {
297                    let (wr, wv) = (x.weights[(l * 2) * nk + kh], x.weights[(l * 2 + 1) * nk + kh]);
298                    let mut tot = total.lock().unwrap();
299                    for r in 0..rows {
300                        tot[r] += wr * res[r] + wv * vn[r];
301                    }
302                }
303            });
304        }
305    });
306    if let Some(f) = dump {
307        let tb = table.into_inner().unwrap();
308        let b: Vec<u8> = tb.iter().flat_map(|v| v.to_le_bytes()).collect();
309        let _ = std::fs::write(f, b);
310    }
311    let score = total.into_inner().unwrap();
312    if let Ok(f) = std::env::var("CMF_DORY_EXACT_LOG") {
313        let b: Vec<u8> = score.iter().flat_map(|v| v.to_le_bytes()).collect();
314        let _ = std::fs::write(f, b);
315    }
316    let mut order: Vec<u32> = (lo as u32..hi as u32).collect();
317    order.sort_unstable_by(|&a, &b| score[b as usize].total_cmp(&score[a as usize]));
318    let mut keep = vec![false; rows];
319    let mut count = 0usize;
320    'pick: for r in order {
321        let r = r as usize;
322        for j in r.saturating_sub(EXACT_NEIGHBOURS).max(lo)..(r + EXACT_NEIGHBOURS + 1).min(hi) {
323            if count >= x.budget {
324                break 'pick;
325            }
326            if !keep[j] {
327                keep[j] = true;
328                count += 1;
329            }
330        }
331    }
332    (0..rows).filter(|&r| keep[r]).collect()
333}
334
335/// The order rows go into a seal: the sinks, the rows kept exact, then the rest as they
336/// came, so the window stays the last rows and the kept ones leave the far field.
337pub fn seal_order(rows: usize, sink: usize, keep: &[usize]) -> Vec<u32> {
338    let mut chosen = vec![false; rows];
339    keep.iter().for_each(|&r| chosen[r] = true);
340    (0..sink.min(rows))
341        .chain(keep.iter().copied())
342        .chain((sink.min(rows)..rows).filter(|&r| !chosen[r]))
343        .map(|r| r as u32)
344        .collect()
345}
346
347/// A slot's far field, one state per KV head, over its rows taken in `order`. `ks` and `vs` are
348/// `[row][nk][hd]`, `qs` `[row / stride][nh][hd]`; `kept` rows after the sinks stay exact.
349#[allow(clippy::too_many_arguments)]
350pub fn far_states(c: &DoryCfg, o1: DoryO1, ks: &[f32], vs: &[f32], qs: &[f32], stride: usize, rows: usize, order: &[u32], kept: usize) -> Vec<crate::nystrom::NystromState> {
351    far_states_geom(c.nh, c.nk, c.hd, o1, ks, vs, qs, stride, rows, order, kept)
352}
353
354/// [`far_states`] for any attention geometry: `nh` query heads over `nk` KV heads of
355/// `hd`, keys and values `[row][nk][hd]`, the query trace `[row / stride][nh][hd]`
356/// (the Flash-Next device path seals through this one).
357#[allow(clippy::too_many_arguments)]
358pub fn far_states_geom(nh: usize, nk: usize, hd: usize, o1: DoryO1, ks: &[f32], vs: &[f32], qs: &[f32], stride: usize, rows: usize, order: &[u32], kept: usize) -> Vec<crate::nystrom::NystromState> {
359    let rep = nh / nk;
360    let mut states = Vec::with_capacity(nk);
361    std::thread::scope(|sc| {
362        let mut hs = Vec::with_capacity(nk);
363        for kh in 0..nk {
364            hs.push(sc.spawn(move || {
365                let mut kg = vec![0f32; rows * hd];
366                let mut vg = vec![0f32; rows * hd];
367                let mut qg: Vec<Vec<f32>> = (0..rep).map(|_| vec![0f32; rows * hd]).collect();
368                for (r, &from) in order.iter().enumerate() {
369                    let from = from as usize;
370                    let at = (from * nk + kh) * hd;
371                    kg[r * hd..(r + 1) * hd].copy_from_slice(&ks[at..at + hd]);
372                    vg[r * hd..(r + 1) * hd].copy_from_slice(&vs[at..at + hd]);
373                    for (h, q) in qg.iter_mut().enumerate() {
374                        let at = (from / stride * nh + kh * rep + h) * hd;
375                        q[r * hd..(r + 1) * hd].copy_from_slice(&qs[at..at + hd]);
376                    }
377                }
378                let mut n = crate::nystrom::NystromState::new_group(o1.m, o1.w, o1.sink + kept, rep)
379                    .with_landmarks_from(if kept == 0 { 0 } else { o1.sink + kept });
380                let refs: Vec<&[f32]> = qg.iter().map(|q| &q[..]).collect();
381                n.prefill_group(&refs, &kg, &vg, rows, hd, hd);
382                n
383            }));
384        }
385        for h in hs {
386            states.push(h.join().expect("seal worker"));
387        }
388    });
389    states
390}
391
392/// O(1) far field for the full-attention layers (`nystrom`): `CMF_DORY_O1=m,w,sink,seal`.
393/// A slot runs exact up to position `seal`, then an exact window of `w` keys plus a
394/// skeleton of `m` landmarks. Sliding layers are bounded already.
395#[derive(Clone, Copy, Debug)]
396pub struct DoryO1 {
397    pub m: usize,
398    pub w: usize,
399    pub sink: usize,
400    pub seal: usize,
401}
402
403impl DoryO1 {
404    pub fn from_env() -> Option<Self> {
405        let v = std::env::var("CMF_DORY_O1").ok()?;
406        let n: Vec<usize> = v.split(',').filter_map(|x| x.trim().parse().ok()).collect();
407        // Below the window plus a margin the state would be exact only.
408        (n.len() == 4).then(|| Self { m: n[0], w: n[1], sink: n[2], seal: n[3].max(n[1] + n[2] + 16) })
409    }
410}
411
412/// One KV slot: rows `first..first + len` of keys and values, `[row][nk][hd]`.
413#[derive(Default)]
414pub struct KvSlot {
415    pub k: Vec<f32>,
416    pub v: Vec<f32>,
417    pub first: usize,
418    /// Sealed, and its rows still kept for the choice of exact ones.
419    pub arch: bool,
420    /// Every row's queries `[row][nh][hd]`, until the O(1) seal; past it, the chunk's.
421    pub qt: Vec<f32>,
422    /// One state per KV head after the seal.
423    pub far: Vec<crate::nystrom::NystromState>,
424    /// The rows of a sealed prompt but for the chunk being read, in RAM or in files.
425    store: Option<SlotStore>,
426}
427
428struct SlotStore {
429    k: ArchStore,
430    v: ArchStore,
431    /// One row in `QT_STRIDE`.
432    q: ArchStore,
433    rows: usize,
434}
435
436impl SlotStore {
437    fn new(dir: Option<&std::path::Path>) -> Result<Self, String> {
438        // Two sequences of one process may seal at once.
439        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
440        let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
441        let at = |kind: &str| ArchStore::new(dir, format!("dory-host-{n}-{kind}"));
442        Ok(Self { k: at("k")?, v: at("v")?, q: at("q")?, rows: 0 })
443    }
444
445    /// A chunk's rows, from position `pos`; its queries are `[row][nh][hd]`.
446    fn push(&mut self, k: &[f32], v: &[f32], q: &[f32], kv_row: usize, q_row: usize, pos: usize) -> Result<(), String> {
447        self.k.push(k)?;
448        self.v.push(v)?;
449        for (r, row) in q.chunks_exact(q_row).enumerate() {
450            if (pos + r) % QT_STRIDE == 0 {
451                self.q.push(row)?;
452            }
453        }
454        self.rows += k.len() / kv_row;
455        Ok(())
456    }
457}
458
459impl KvSlot {
460    fn rows(&self, row: usize) -> usize {
461        if row == 0 { 0 } else { self.k.len() / row }
462    }
463}
464
465/// Host KV state: `slots[attention ordinal][loop]`.
466#[derive(Default)]
467pub struct DoryState {
468    pub slots: Vec<Vec<KvSlot>>,
469    pub pos: usize,
470    scratch: Scratch,
471    /// The logits of a token whose first read-out ended it.
472    exit_logits: Option<Vec<f32>>,
473    exits: ExitRate,
474    pub gate_tokens: u64,
475    pub gate_one: u64,
476}
477
478impl DoryState {
479    pub fn clear(&mut self) {
480        for row in &mut self.slots {
481            for s in row {
482                s.k.clear();
483                s.v.clear();
484                s.first = 0;
485                s.arch = false;
486                s.store = None;
487                s.qt.clear();
488                s.far.clear();
489            }
490        }
491        self.pos = 0;
492    }
493
494    /// Forget the rows from position `n` on.
495    pub fn rollback(&mut self, n: usize, kv_row: usize) {
496        for row in &mut self.slots {
497            for s in row {
498                let end = s.first + s.rows(kv_row);
499                if end > n {
500                    let keep = n.saturating_sub(s.first) * kv_row;
501                    s.k.truncate(keep);
502                    s.v.truncate(keep);
503                }
504            }
505        }
506        self.pos = self.pos.min(n);
507    }
508}
509
510fn load_vec(model: &CmfModel, name: &str, n: usize) -> Result<Vec<f32>, String> {
511    let v = crate::loader::load_f32(model, name, &crate::loader::Overlay::None)?;
512    if v.len() != n {
513        return Err(format!("{name}: {} values, wanted {n}", v.len()));
514    }
515    Ok(v)
516}
517
518impl Dory {
519    pub fn from_model(model: &Arc<CmfModel>) -> Result<Self, String> {
520        let arch: &ModelArch = model.arch();
521        let rec: &DoryConfig = arch.dory.as_ref().ok_or("dory: no arch record")?;
522        let kv = KvMode::parse(&rec.recurrent_kv_cache_mode)
523            .ok_or_else(|| format!("dory: KV mode {}", rec.recurrent_kv_cache_mode))?;
524        let (hidden, ffn, nh, nk, hd) =
525            (arch.hidden_size, arch.intermediate_size, arch.num_attention_heads, arch.num_kv_heads, arch.head_dim);
526        let std = rec.initializer_range;
527        let alpha_f = (rec.ngpt_alpha_init / std) as f32;
528        let sqk_f = ((hd as f64).sqrt() / std) as f32;
529        let gate_f = (rec.gate_logit_scale_init.sqrt() / std) as f32;
530        let suv_f = (hidden as f64).sqrt() as f32;
531        let q_size = nh * hd;
532        let t = |name: String| QTensor::from_model(model, &name);
533        let mut layers = Vec::with_capacity(rec.layer_pattern.len());
534        let mut ordinal = 0usize;
535        for (li, kind) in rec.layer_pattern.chars().enumerate() {
536            let p = format!("model.layers.{li}");
537            let m = format!("{p}.mixer");
538            if kind == '-' {
539                let scale = |name: &str| -> Result<Vec<f32>, String> {
540                    let mut v = load_vec(model, &format!("{m}.{name}"), ffn)?;
541                    v.iter_mut().for_each(|x| *x *= suv_f);
542                    Ok(v)
543                };
544                let mut alpha = load_vec(model, &format!("{p}.mlp_alpha"), hidden)?;
545                alpha.iter_mut().for_each(|x| *x = (*x * alpha_f).abs());
546                layers.push(Layer::Mlp(Box::new(MlpWeights {
547                    gate: t(format!("{m}.gate_proj.weight"))?,
548                    up: t(format!("{m}.up_proj.weight"))?,
549                    down: t(format!("{m}.down_proj.weight"))?,
550                    sg: scale("suv_gate")?,
551                    su: scale("suv_up")?,
552                    alpha,
553                })));
554            } else {
555                let sq_vec = |name: &str, f: f32| -> Result<Vec<f32>, String> {
556                    let mut v = load_vec(model, &format!("{m}.{name}"), q_size)?;
557                    v.iter_mut().for_each(|x| {
558                        let s = *x * f;
559                        *x = s * s;
560                    });
561                    Ok(v)
562                };
563                let mut alpha = load_vec(model, &format!("{p}.attn_alpha"), hidden)?;
564                alpha.iter_mut().for_each(|x| *x = (*x * alpha_f).abs());
565                layers.push(Layer::Attn(Box::new(AttnWeights {
566                    q: t(format!("{m}.q_proj.weight"))?,
567                    k: t(format!("{m}.k_proj.weight"))?,
568                    v: t(format!("{m}.v_proj.weight"))?,
569                    g: t(format!("{m}.g_proj.weight"))?,
570                    o: t(format!("{m}.o_proj.weight"))?,
571                    sq: sq_vec("sqk", sqk_f)?,
572                    sg: sq_vec("s_gate", gate_f)?,
573                    alpha,
574                    sliding: kind == 'S',
575                    ordinal,
576                })));
577                ordinal += 1;
578            }
579        }
580        let mut logit_scale = load_vec(model, "lm_head.logit_scale", arch.vocab_size)?;
581        let inv = 1.0 / std as f32;
582        logit_scale.iter_mut().for_each(|x| *x *= inv);
583        let mut cfg = DoryCfg {
584            hidden,
585            ffn,
586            vocab: arch.vocab_size,
587            nh,
588            nk,
589            hd,
590            window: rec.sliding_window,
591            n_in: rec.n_input_layers,
592            n_rec: rec.n_recurrent_layers,
593            n_out: rec.n_output_layers,
594            loops: rec.n_recurrent_loops,
595            kv,
596            attn_scale: 1.0 / (hd as f32).sqrt(),
597            full_window: std::env::var("CMF_DORY_FULL_WINDOW").ok().and_then(|v| v.parse().ok()),
598        };
599        if let Some(n) = std::env::var("CMF_DORY_LOOPS").ok().and_then(|v| v.parse::<usize>().ok()) {
600            if n > MAX_LOOPS {
601                return Err(format!("CMF_DORY_LOOPS={n}: want at most {MAX_LOOPS}"));
602            }
603            cfg.loops = n;
604        }
605        if let Ok(v) = std::env::var("CMF_DORY_KV") {
606            cfg.kv = KvMode::parse(&v).ok_or_else(|| format!("CMF_DORY_KV={v}: want per_loop or last_loop"))?;
607        }
608        let auto = std::env::var("CMF_DORY_GATE").as_deref() == Ok("auto");
609        let mut gate = gate_from_env();
610        let mut o1 = DoryO1::from_env();
611        let mut prompt_loops: usize = std::env::var("CMF_DORY_PROMPT_LOOPS").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
612        let mut exact = exact_from_env();
613        // A turbo file runs so unless a flag says otherwise; a fixed loop count is one.
614        if let (Some(t), None) = (&rec.turbo, std::env::var_os("CMF_DORY_LOOPS")) {
615            if std::env::var_os("CMF_DORY_KV").is_none() {
616                cfg.kv = KvMode::LastLoop;
617            }
618            if gate.is_none() && cfg.kv == KvMode::LastLoop {
619                gate = Some(Gate::Recon(Arc::new(Topologies::from_model(model)?), t.exit_bias));
620            }
621            if o1.is_none() && std::env::var("CMF_DORY_O1").as_deref() != Ok("off") {
622                let [m, w, sink, seal] = t.o1;
623                o1 = Some(DoryO1 { m, w, sink, seal: seal.max(w + sink + 16) });
624            }
625            if std::env::var_os("CMF_DORY_PROMPT_LOOPS").is_none() {
626                prompt_loops = 1;
627            }
628            if t.exact_rows > 0 && std::env::var_os("CMF_DORY_EXACT").is_none() && o1.is_some() {
629                let w = crate::loader::load_f32(model, "dory.exact.weights", &crate::loader::Overlay::None)?;
630                exact = Some(ExactRows { weights: Arc::new(w), budget: t.exact_rows });
631            }
632        }
633        if let (Some(x), Some(o)) = (&exact, &o1) {
634            if o.w + o.sink + x.budget > MAX_NEAR {
635                return Err(format!("dory: window {} + sinks {} + exact rows {} go over the near field's {MAX_NEAR}", o.w, o.sink, x.budget));
636            }
637        }
638        // `--loops auto` without a router in the file: the top probability decides.
639        if auto && gate.is_none() {
640            gate = Some(Gate::Conf(0.7));
641        }
642        Ok(Self {
643            file: Some(model.clone()),
644            cfg,
645            embed: t("model.embed_tokens.weight".into())?,
646            head: t("lm_head.weight".into())?,
647            logit_scale,
648            layers,
649            inv_full: crate::attention::rope_inv_freq(hd, rec.rope_theta_full as f32),
650            inv_sliding: crate::attention::rope_inv_freq(hd, rec.rope_theta_sliding as f32),
651            attn_layers: ordinal,
652            o1,
653            gate,
654            prompt_loops,
655            exact,
656            spill: std::env::var_os("CMF_O1_SPILL").map(Into::into),
657        })
658    }
659
660    /// The passes over one chunk of a forward.
661    pub fn chunk_loops(&self, loops: usize, want: Want) -> usize {
662        if want == Want::None && self.prompt_loops > 0 && self.cfg.kv == KvMode::LastLoop {
663            loops.min(self.prompt_loops)
664        } else {
665            loops
666        }
667    }
668
669    /// Which loop's cache a layer uses.
670    #[inline]
671    fn slot_loop(&self, li: usize, loop_i: usize) -> usize {
672        let c = &self.cfg;
673        if c.kv == KvMode::PerLoop && li >= c.n_in && li < c.n_in + c.n_rec { loop_i } else { 0 }
674    }
675}
676
677/// `x / sqrt(Σx² + ε)`
678#[inline]
679pub fn justnorm(x: &mut [f32]) {
680    let r = 1.0 / (crate::attention::dot_f32(x, x) + EPS).sqrt();
681    for v in x.iter_mut() {
682        *v *= r;
683    }
684}
685
686/// The nGPT residual, written into `x`.
687fn slerp(x: &mut [f32], out: &mut [f32], alpha: &[f32]) {
688    justnorm(x);
689    justnorm(out);
690    for ((a, b), al) in x.iter_mut().zip(out.iter()).zip(alpha) {
691        *a += *al * (*b - *a);
692    }
693    justnorm(x);
694}
695
696/// `exp` on eight lanes, written so a compiler vectorizes it (Cephes `expf`, within
697/// 2e-7 on the range an activation or a softmax reaches).
698#[inline(always)]
699fn exp8(x: &[f32; 8]) -> [f32; 8] {
700    let mut r = [0f32; 8];
701    for i in 0..8 {
702        let v = x[i].clamp(-87.0, 88.0);
703        let n = (v * std::f32::consts::LOG2_E + 0.5).floor();
704        let g = v - n * 0.693_359_4 + n * 2.121_944_4e-4;
705        let p = ((((((1.987_569_1e-4 * g + 1.398_2e-3) * g + 8.333_452e-3) * g + 4.166_579_6e-2) * g + 1.666_666_5e-1) * g + 0.5) * g * g) + g + 1.0;
706        r[i] = p * f32::from_bits(((n as i32 + 127) << 23) as u32);
707    }
708    r
709}
710
711macro_rules! lanes8 {
712    ($body:ident, $avx:ident, ($($a:ident : $t:ty),*)) => {
713        #[cfg(target_arch = "x86_64")]
714        #[target_feature(enable = "avx2,fma")]
715        unsafe fn $avx($($a: $t),*) {
716            $body($($a),*)
717        }
718    };
719}
720
721/// `g[i] = silu(g[i]·a[i])·u[i]·b[i]`
722#[inline(always)]
723fn silu_body(g: &mut [f32], u: &[f32], a: &[f32], b: &[f32]) {
724    let n = g.len() & !7;
725    for i in (0..n).step_by(8) {
726        let mut x = [0f32; 8];
727        let mut m = [0f32; 8];
728        for j in 0..8 {
729            x[j] = g[i + j] * a[i + j];
730            m[j] = -x[j];
731        }
732        let e = exp8(&m);
733        for j in 0..8 {
734            g[i + j] = x[j] / (1.0 + e[j]) * (u[i + j] * b[i + j]);
735        }
736    }
737    for i in n..g.len() {
738        let x = g[i] * a[i];
739        g[i] = x / (1.0 + (-x).exp()) * (u[i] * b[i]);
740    }
741}
742lanes8!(silu_body, silu_avx2, (g: &mut [f32], u: &[f32], a: &[f32], b: &[f32]));
743
744fn silu_rows(g: &mut [f32], u: &[f32], a: &[f32], b: &[f32]) {
745    #[cfg(target_arch = "x86_64")]
746    if crate::qtensor::avx2_enabled() {
747        return unsafe { silu_avx2(g, u, a, b) };
748    }
749    silu_body(g, u, a, b)
750}
751
752/// `y[i] = y[i]·σ(g[i]·s[i])`
753#[inline(always)]
754fn gate_body(y: &mut [f32], g: &[f32], s: &[f32]) {
755    let n = y.len() & !7;
756    for i in (0..n).step_by(8) {
757        let mut m = [0f32; 8];
758        for j in 0..8 {
759            m[j] = -(g[i + j] * s[i + j]);
760        }
761        let e = exp8(&m);
762        for j in 0..8 {
763            y[i + j] /= 1.0 + e[j];
764        }
765    }
766    for i in n..y.len() {
767        y[i] /= 1.0 + (-(g[i] * s[i])).exp();
768    }
769}
770lanes8!(gate_body, gate_avx2, (y: &mut [f32], g: &[f32], s: &[f32]));
771
772fn gate_rows(y: &mut [f32], g: &[f32], s: &[f32]) {
773    #[cfg(target_arch = "x86_64")]
774    if crate::qtensor::avx2_enabled() {
775        return unsafe { gate_avx2(y, g, s) };
776    }
777    gate_body(y, g, s)
778}
779
780/// Softmax of a row of scores, in place.
781#[inline(always)]
782fn soft_body(row: &mut [f32]) {
783    let n = row.len();
784    let mut top = f32::NEG_INFINITY;
785    for v in row.iter() {
786        top = top.max(*v);
787    }
788    let mut den = 0f32;
789    let blocks = n & !7;
790    for i in (0..blocks).step_by(8) {
791        let mut m = [0f32; 8];
792        for j in 0..8 {
793            m[j] = row[i + j] - top;
794        }
795        let e = exp8(&m);
796        let mut acc = 0f32;
797        for j in 0..8 {
798            row[i + j] = e[j];
799            acc += e[j];
800        }
801        den += acc;
802    }
803    for v in row[blocks..].iter_mut() {
804        *v = (*v - top).exp();
805        den += *v;
806    }
807    let inv = 1.0 / den;
808    for v in row.iter_mut() {
809        *v *= inv;
810    }
811}
812lanes8!(soft_body, soft_avx2, (row: &mut [f32]));
813
814fn soft_row(row: &mut [f32]) {
815    #[cfg(target_arch = "x86_64")]
816    if crate::qtensor::avx2_enabled() {
817        return unsafe { soft_avx2(row) };
818    }
819    soft_body(row)
820}
821
822struct SendPtr(*mut f32);
823unsafe impl Send for SendPtr {}
824unsafe impl Sync for SendPtr {}
825impl SendPtr {
826    #[inline]
827    fn at(&self, i: usize) -> *mut f32 {
828        unsafe { self.0.add(i) }
829    }
830}
831
832fn for_rows(pool: Option<&Pool>, n: usize, f: &(dyn Fn(usize) + Sync)) {
833    match pool {
834        Some(p) if n > 1 => p.run_rows(n, &|a, b| (a..b).for_each(f)),
835        _ => (0..n).for_each(f),
836    }
837}
838
839thread_local! {
840    static SCORES: std::cell::RefCell<Vec<f32>> = const { std::cell::RefCell::new(Vec::new()) };
841}
842
843/// The chunk's scratch, kept between forwards: a token touches 112 layers.
844#[derive(Default)]
845pub struct Scratch {
846    q: Vec<f32>,
847    k: Vec<f32>,
848    v: Vec<f32>,
849    g: Vec<f32>,
850    u: Vec<f32>,
851    out: Vec<f32>,
852    /// `[kind][row][cos half | sin half]`: sliding, full.
853    rope: [Vec<f32>; 2],
854}
855
856fn fit(v: &mut Vec<f32>, n: usize) {
857    v.resize(n, 0.0);
858}
859
860/// One attention sub-layer over the rows `h[t][hidden]`, positions from `pos0`.
861#[allow(clippy::too_many_arguments)]
862fn attn_layer(
863    m: &Dory,
864    w: &AttnWeights,
865    slot: &mut KvSlot,
866    h: &[f32],
867    t: usize,
868    pos0: usize,
869    overwrite: bool,
870    pool: Option<&Pool>,
871    sc: &mut Scratch,
872) {
873    let c = &m.cfg;
874    let (nh, nk, hd, hidden) = (c.nh, c.nk, c.hd, c.hidden);
875    let q_size = nh * hd;
876    let kv_row = nk * hd;
877    fit(&mut sc.q, t * q_size);
878    fit(&mut sc.k, t * kv_row);
879    fit(&mut sc.v, t * kv_row);
880    fit(&mut sc.g, t * q_size);
881    fit(&mut sc.out, t * hidden);
882    if t == 1 && !crate::gptq_capture::capturing() {
883        QTensor::matvec_many([&w.q, &w.k, &w.v, &w.g], h, [&mut sc.q[..], &mut sc.k[..], &mut sc.v[..], &mut sc.g[..]], pool);
884    } else {
885        w.q.matmat(h, t, &mut sc.q, pool);
886        w.k.matmat(h, t, &mut sc.k, pool);
887        w.v.matmat(h, t, &mut sc.v, pool);
888        w.g.matmat(h, t, &mut sc.g, pool);
889    }
890    let half = hd / 2;
891    let rope = &sc.rope[usize::from(!w.sliding)];
892    for r in 0..t {
893        let table = &rope[r * hd..(r + 1) * hd];
894        let (cs, sn) = table.split_at(half);
895        let rotate = |row: &mut [f32]| {
896            let (a, b) = row.split_at_mut(half);
897            for j in 0..half {
898                let (x, y) = (a[j], b[j]);
899                a[j] = x * cs[j] - y * sn[j];
900                b[j] = y * cs[j] + x * sn[j];
901            }
902            justnorm(row);
903        };
904        for (hi, row) in sc.q[r * q_size..(r + 1) * q_size].chunks_exact_mut(hd).enumerate() {
905            rotate(row);
906            for (x, s) in row.iter_mut().zip(&w.sq[hi * hd..(hi + 1) * hd]) {
907                *x *= *s;
908            }
909        }
910        for row in sc.k[r * kv_row..(r + 1) * kv_row].chunks_exact_mut(hd) {
911            rotate(row);
912        }
913    }
914    let rep = nh / nk;
915    // A sealed slot: the exact window and the far skeleton, row by row.
916    if !slot.far.is_empty() {
917        if slot.arch {
918            if overwrite {
919                let keep = slot.k.len() - t * kv_row;
920                slot.k.truncate(keep);
921                slot.v.truncate(keep);
922                let keep = slot.qt.len() - t * q_size;
923                slot.qt.truncate(keep);
924            }
925            slot.k.extend_from_slice(&sc.k);
926            slot.v.extend_from_slice(&sc.v);
927            slot.qt.extend_from_slice(&sc.q);
928        }
929        let mut y = vec![0f32; rep * hd];
930        for r in 0..t {
931            for kh in 0..nk {
932                let at_q = r * q_size + kh * rep * hd;
933                let at_k = (r * nk + kh) * hd;
934                let (q, k, v) = (&sc.q[at_q..at_q + rep * hd], &sc.k[at_k..at_k + hd], &sc.v[at_k..at_k + hd]);
935                if overwrite {
936                    slot.far[kh].restep_group(q, k, v, &mut y);
937                } else {
938                    slot.far[kh].step_group(q, k, v, &mut y);
939                }
940                gate_rows(&mut y, &sc.g[at_q..at_q + rep * hd], &w.sg[kh * rep * hd..(kh + 1) * rep * hd]);
941                sc.g[at_q..at_q + rep * hd].copy_from_slice(&y);
942            }
943        }
944    } else {
945        if !w.sliding && m.o1.is_some() {
946            if overwrite {
947                let keep = slot.qt.len() - t * q_size;
948                slot.qt.truncate(keep);
949            }
950            slot.qt.extend_from_slice(&sc.q);
951        }
952        // The chunk's rows join the cache; each one attends only up to itself.
953        if overwrite {
954            let keep = slot.k.len() - t * kv_row;
955            slot.k.truncate(keep);
956            slot.v.truncate(keep);
957        }
958        slot.k.extend_from_slice(&sc.k);
959        slot.v.extend_from_slice(&sc.v);
960        let (first, keys, vals) = (slot.first, &slot.k[..], &slot.v[..]);
961        let scale = c.attn_scale;
962        let res = SendPtr(sc.g.as_mut_ptr());
963        let window = if w.sliding { c.window } else { c.full_window.unwrap_or(usize::MAX) };
964        let q_ref = &sc.q;
965        let sg = &w.sg;
966        for_rows(pool, t * nk, &|task| {
967            let (r, kh) = (task / nk, task % nk);
968            let p = pos0 + r;
969            let lo = p.saturating_add(1).saturating_sub(window).max(first);
970            let n = p + 1 - lo;
971            let at_q = r * q_size + kh * rep * hd;
972            SCORES.with(|buf| {
973                let mut buf = buf.borrow_mut();
974                buf.resize(rep * (n + hd), 0.0);
975                let (scores, ys) = buf.split_at_mut(rep * n);
976                // A key once, against each query head of its group.
977                for e in 0..n {
978                    let row = (lo + e - first) * kv_row + kh * hd;
979                    let key = &keys[row..row + hd];
980                    for h in 0..rep {
981                        let qr = &q_ref[at_q + h * hd..at_q + (h + 1) * hd];
982                        scores[h * n + e] = crate::attention::dot_f32(qr, key) * scale;
983                    }
984                }
985                ys.iter_mut().for_each(|v| *v = 0.0);
986                for h in 0..rep {
987                    soft_row(&mut scores[h * n..(h + 1) * n]);
988                }
989                for e in 0..n {
990                    let row = (lo + e - first) * kv_row + kh * hd;
991                    let val = &vals[row..row + hd];
992                    for h in 0..rep {
993                        crate::attention::axpy_f32(&mut ys[h * hd..(h + 1) * hd], val, scores[h * n + e]);
994                    }
995                }
996                // `g` becomes the gated attention output.
997                let g = unsafe { std::slice::from_raw_parts_mut(res.at(at_q), rep * hd) };
998                gate_rows(ys, g, &sg[kh * rep * hd..(kh + 1) * rep * hd]);
999                g.copy_from_slice(ys);
1000            });
1001        });
1002    }
1003    for row in sc.g.chunks_exact_mut(q_size) {
1004        justnorm(row);
1005    }
1006    if t == 1 && !crate::gptq_capture::capturing() {
1007        w.o.matvec(&sc.g, &mut sc.out, pool);
1008    } else {
1009        w.o.matmat(&sc.g, t, &mut sc.out, pool);
1010    }
1011}
1012
1013fn mlp_layer(w: &MlpWeights, h: &[f32], t: usize, ffn: usize, hidden: usize, pool: Option<&Pool>, sc: &mut Scratch) {
1014    fit(&mut sc.g, t * ffn);
1015    fit(&mut sc.u, t * ffn);
1016    fit(&mut sc.out, t * hidden);
1017    let single = t == 1 && !crate::gptq_capture::capturing();
1018    if single {
1019        QTensor::matvec_many([&w.gate, &w.up], h, [&mut sc.g[..], &mut sc.u[..]], pool);
1020    } else {
1021        w.gate.matmat(h, t, &mut sc.g, pool);
1022        w.up.matmat(h, t, &mut sc.u, pool);
1023    }
1024    for (gr, ur) in sc.g.chunks_exact_mut(ffn).zip(sc.u.chunks_exact(ffn)) {
1025        silu_rows(gr, ur, &w.sg, &w.su);
1026        justnorm(gr);
1027    }
1028    if single {
1029        w.down.matvec(&sc.g, &mut sc.out, pool);
1030    } else {
1031        w.down.matmat(&sc.g, t, &mut sc.out, pool);
1032    }
1033}
1034
1035/// The rows' final hidden states, through `loops` passes of the recurrent block.
1036#[allow(clippy::too_many_arguments)]
1037fn stack(
1038    m: &Dory,
1039    st: &mut DoryState,
1040    h: &mut Vec<f32>,
1041    t: usize,
1042    pos0: usize,
1043    loops: usize,
1044    pool: Option<&Pool>,
1045    capture: Option<&mut Capture>,
1046) {
1047    let c = &m.cfg;
1048    let hidden = c.hidden;
1049    let mut sc = std::mem::take(&mut st.scratch);
1050    let half = c.hd / 2;
1051    for (ti, inv) in [&m.inv_sliding, &m.inv_full].iter().enumerate() {
1052        fit(&mut sc.rope[ti], t * c.hd);
1053        for (r, row) in sc.rope[ti].chunks_exact_mut(c.hd).enumerate() {
1054            let at = (pos0 + r) as f64;
1055            for j in 0..half {
1056                let (sn, cs) = (at * inv[j] as f64).sin_cos();
1057                row[j] = cs as f32;
1058                row[half + j] = sn as f32;
1059            }
1060        }
1061    }
1062    let run = |li: usize, loop_i: usize, h: &mut [f32], st: &mut DoryState, sc: &mut Scratch| {
1063        match &m.layers[li] {
1064            Layer::Attn(w) => {
1065                let sl = m.slot_loop(li, loop_i);
1066                let row = &mut st.slots[w.ordinal];
1067                if row.len() <= sl {
1068                    row.resize_with(sl + 1, KvSlot::default);
1069                }
1070                let recurrent = li >= c.n_in && li < c.n_in + c.n_rec;
1071                // A second read-out replaces the first one's rows too.
1072                let overwrite = c.kv == KvMode::LastLoop && (recurrent || li >= c.n_in + c.n_rec) && loop_i > 0;
1073                attn_layer(m, w, &mut row[sl], h, t, pos0, overwrite, pool, sc);
1074                for (x, o) in h.chunks_exact_mut(hidden).zip(sc.out.chunks_exact_mut(hidden)) {
1075                    slerp(x, o, &w.alpha);
1076                }
1077            }
1078            Layer::Mlp(w) => {
1079                mlp_layer(w, h, t, c.ffn, hidden, pool, sc);
1080                for (x, o) in h.chunks_exact_mut(hidden).zip(sc.out.chunks_exact_mut(hidden)) {
1081                    slerp(x, o, &w.alpha);
1082                }
1083            }
1084        }
1085    };
1086    for li in 0..c.n_in {
1087        run(li, 0, h, st, &mut sc);
1088    }
1089    let input = h.clone();
1090    let mut capture = capture;
1091    if let Some(cp) = capture.as_deref_mut() {
1092        cp.input.extend_from_slice(&input);
1093    }
1094    let mut state = input.clone();
1095    // Under a gate one row runs its first pass here, and the rest below.
1096    let early = t == 1 && m.gate.is_some();
1097    for i in 0..if early { 1 } else { loops } {
1098        for ((x, s), a) in h.iter_mut().zip(&state).zip(&input) {
1099            *x = *s + *a;
1100        }
1101        for row in h.chunks_exact_mut(hidden) {
1102            justnorm(row);
1103        }
1104        for li in c.n_in..c.n_in + c.n_rec {
1105            run(li, i, h, st, &mut sc);
1106        }
1107        state.copy_from_slice(h);
1108        for row in state.chunks_exact_mut(hidden) {
1109            justnorm(row);
1110        }
1111        if let Some(cp) = capture.as_deref_mut() {
1112            cp.loops.extend_from_slice(&state);
1113        }
1114    }
1115    // An early exit: one pass, a decision, and the second only if it asks for one.
1116    if let (true, Some(g)) = (t == 1 && early, m.gate.clone()) {
1117        let mut stay = false;
1118        let mut readout = false;
1119        if let Gate::Recon(top, bias) = &g {
1120            stay = top.score(&state) < *bias;
1121        }
1122        h.copy_from_slice(&state);
1123        if let Gate::Conf(th) = &g {
1124            if st.exits.probe() {
1125                readout = true;
1126                for li in c.n_in + c.n_rec..c.n_in + c.n_rec + c.n_out {
1127                    run(li, 0, h, st, &mut sc);
1128                }
1129                let mut lg = Vec::with_capacity(c.vocab);
1130                head(m, h, 1, Want::Last, pool, &mut lg);
1131                stay = top_prob(&lg) < *th;
1132                st.exits.note(!stay);
1133                if !stay {
1134                    st.exit_logits = Some(lg);
1135                }
1136            } else {
1137                stay = true;
1138            }
1139        } else if !stay {
1140            for li in c.n_in + c.n_rec..c.n_in + c.n_rec + c.n_out {
1141                run(li, 0, h, st, &mut sc);
1142            }
1143        }
1144        if stay {
1145            for ((x, s), a) in h.iter_mut().zip(&state).zip(&input) {
1146                *x = *s + *a;
1147            }
1148            justnorm(h);
1149            for li in c.n_in..c.n_in + c.n_rec {
1150                run(li, 1, h, st, &mut sc);
1151            }
1152            justnorm(h);
1153            for li in c.n_in + c.n_rec..c.n_in + c.n_rec + c.n_out {
1154                run(li, usize::from(readout), h, st, &mut sc);
1155            }
1156        }
1157        st.gate_tokens += 1;
1158        st.gate_one += u64::from(!stay);
1159    } else {
1160        h.copy_from_slice(&state);
1161        for li in c.n_in + c.n_rec..c.n_in + c.n_rec + c.n_out {
1162            run(li, 0, h, st, &mut sc);
1163        }
1164    }
1165    st.scratch = sc;
1166    if st.slots.iter().flatten().any(|s| s.arch) {
1167        store_chunk(c, st, pos0);
1168    }
1169    if let Some(o1) = m.o1 {
1170        if pos0 + t >= o1.seal {
1171            seal_far(m, st, o1);
1172        }
1173    }
1174    // Sliding layers need only the window behind the next position. Trimming
1175    // waits for the chunk's end: a later last-loop pass reads what is behind it.
1176    let kv_row = c.nk * c.hd;
1177    for w in m.layers.iter().filter_map(|l| match l {
1178        Layer::Attn(w) => Some(w),
1179        _ => None,
1180    }) {
1181        let keep = if w.sliding { c.window } else { c.full_window.unwrap_or(usize::MAX / 4) };
1182        for s in st.slots[w.ordinal].iter_mut() {
1183            let n = s.rows(kv_row);
1184            if n > 2 * keep {
1185                let drop = n - keep;
1186                s.k.drain(..drop * kv_row);
1187                s.v.drain(..drop * kv_row);
1188                s.first += drop;
1189            }
1190        }
1191    }
1192}
1193
1194/// A sealed chunk's rows join the store; a later pass over the chunk has rewritten them by now.
1195fn store_chunk(c: &DoryCfg, st: &mut DoryState, pos: usize) {
1196    let (kv_row, q_row) = (c.nk * c.hd, c.nh * c.hd);
1197    let mut failed = None;
1198    for s in st.slots.iter_mut().flatten().filter(|s| s.arch) {
1199        let Some(a) = s.store.as_mut() else { continue };
1200        if let Err(e) = a.push(&s.k, &s.v, &s.qt, kv_row, q_row, pos) {
1201            failed = Some(e);
1202            break;
1203        }
1204        s.k.clear();
1205        s.v.clear();
1206        s.qt.clear();
1207    }
1208    if let Some(e) = failed {
1209        give_up_rows(st, &e);
1210    }
1211}
1212
1213/// The rows did not fit where they were going: the far field stays as first sealed, with no
1214/// exact rows.
1215fn give_up_rows(st: &mut DoryState, why: &str) {
1216    tracing::warn!("dory: {why}: the prompt's rows are dropped, and none stays exact past the seal");
1217    for s in st.slots.iter_mut().flatten().filter(|s| s.arch) {
1218        s.arch = false;
1219        s.store = None;
1220        s.k = Vec::new();
1221        s.v = Vec::new();
1222        s.qt = Vec::new();
1223    }
1224}
1225
1226/// Freeze the full-attention slots' landmarks over what they hold, and go on from them row by
1227/// row (`nystrom::NystromState::prefill_group`). Before a prompt's end, with a choice of exact
1228/// rows to make, the rows go on to a store.
1229fn seal_far(m: &Dory, st: &mut DoryState, o1: DoryO1) {
1230    let c = &m.cfg;
1231    let (nk, hd, q_row) = (c.nk, c.hd, c.nh * c.hd);
1232    let kv_row = nk * hd;
1233    let mut sealed = false;
1234    for o in full_slots(m) {
1235        for s in st.slots[o].iter_mut() {
1236            if !s.far.is_empty() || s.k.is_empty() {
1237                continue;
1238            }
1239            sealed = true;
1240            let t = s.k.len() / kv_row;
1241            let order = seal_order(t, o1.sink, &[]);
1242            s.far = far_states(c, o1, &s.k, &s.v, &s.qt, 1, t, &order, 0);
1243            if m.exact.is_some() {
1244                let mut a = match SlotStore::new(m.spill.as_deref()) {
1245                    Ok(a) => a,
1246                    Err(e) => {
1247                        tracing::warn!("dory: {e}");
1248                        s.qt = Vec::new();
1249                        s.k = Vec::new();
1250                        s.v = Vec::new();
1251                        continue;
1252                    }
1253                };
1254                match a.push(&s.k, &s.v, &s.qt, kv_row, q_row, 0) {
1255                    Ok(()) => {
1256                        s.arch = true;
1257                        s.store = Some(a);
1258                    }
1259                    Err(e) => tracing::warn!("dory: {e}"),
1260                }
1261            }
1262            s.qt = Vec::new();
1263            s.k = Vec::new();
1264            s.v = Vec::new();
1265        }
1266    }
1267    // Every slot or none: the choice of rows reads all the layers.
1268    if sealed && m.exact.is_some() && st.slots.iter().flatten().any(|s| !s.far.is_empty() && !s.arch) {
1269        give_up_rows(st, "a store failed");
1270    }
1271}
1272
1273/// The full-attention layers' slots.
1274fn full_slots(m: &Dory) -> Vec<usize> {
1275    m.layers
1276        .iter()
1277        .filter_map(|l| match l {
1278            Layer::Attn(w) if !w.sliding => Some(w.ordinal),
1279            _ => None,
1280        })
1281        .collect()
1282}
1283
1284/// A prompt's end on the host, before its last rows: the far field built anew over all the rows,
1285/// the ones it should not lose out of it. A copy of a fact there drowns the exact one.
1286fn finish_exact(m: &Dory, st: &mut DoryState) {
1287    let Some(o1) = m.o1 else { return };
1288    let Some(x) = m.exact.as_ref() else { return };
1289    if !st.slots.iter().flatten().any(|s| s.arch) {
1290        return;
1291    }
1292    let c = &m.cfg;
1293    let (nh, nk, hd) = (c.nh, c.nk, c.hd);
1294    let kv_row = nk * hd;
1295    let t0 = std::time::Instant::now();
1296    let full = full_slots(m);
1297    let mut frozen = Vec::new();
1298    let mut rows = 0;
1299    let mut fail = None;
1300    for &o in &full {
1301        for sl in 0..st.slots[o].len() {
1302            let s = &mut st.slots[o][sl];
1303            let Some(a) = s.store.take() else { continue };
1304            rows = a.rows;
1305            match (a.k.freeze(), a.v.freeze(), a.q.freeze()) {
1306                (Ok(k), Ok(v), Ok(q)) => frozen.push((o, sl, k, v, q)),
1307                (Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => fail = Some(e),
1308            }
1309        }
1310    }
1311    if let Some(e) = fail {
1312        give_up_rows(st, &e);
1313        return;
1314    }
1315    let keep = {
1316        let views: Vec<FlatRows> = frozen.iter().filter(|e| e.1 == 0).map(|e| FlatRows { k: e.2.as_slice(), v: e.3.as_slice(), nk, hd }).collect();
1317        let layers: Vec<&dyn LayerRows> = views.iter().map(|v| v as &dyn LayerRows).collect();
1318        pick_exact_rows(x, &layers, rows, nk, hd, o1.m, o1.sink, rows.saturating_sub(o1.w))
1319    };
1320    let order = seal_order(rows, o1.sink, &keep);
1321    // One slot at a time: memory holds the far field of one layer on top of the rows.
1322    for (o, sl, k, v, q) in frozen {
1323        let (ks, vs, qs) = (k.as_slice(), v.as_slice(), q.as_slice());
1324        debug_assert_eq!(qs.len(), rows.div_ceil(QT_STRIDE) * nh * hd);
1325        debug_assert_eq!(ks.len(), rows * kv_row);
1326        let s = &mut st.slots[o][sl];
1327        s.far = far_states(c, o1, ks, vs, qs, QT_STRIDE, rows, &order, keep.len());
1328        s.arch = false;
1329    }
1330    tracing::info!("dory: far field rebuilt over {rows} rows, {} kept exact, in {:.2} s", keep.len(), t0.elapsed().as_secs_f64());
1331}
1332
1333/// The host's KV bytes: `(exact rows, O(1) states)`.
1334pub fn host_kv_bytes(st: &DoryState) -> (usize, usize) {
1335    let (mut exact, mut far) = (0, 0);
1336    for s in st.slots.iter().flatten() {
1337        exact += (s.k.len() + s.v.len()) * 4;
1338        far += s.far.iter().map(|n| n.memory_bytes()).sum::<usize>();
1339    }
1340    (exact, far)
1341}
1342
1343/// Per-row signals of a forward, for the loop router.
1344#[derive(Default)]
1345pub struct Capture {
1346    pub input: Vec<f32>,
1347    pub loops: Vec<f32>,
1348}
1349
1350/// What a forward leaves in `logits`.
1351#[derive(Clone, Copy, PartialEq, Eq)]
1352pub enum Want {
1353    /// Nothing: the KV state moved, no logits are read.
1354    None,
1355    Last,
1356    All,
1357}
1358
1359/// How a token leaves the loop early: by its top probability after one pass
1360/// (`conf:0.7`), which reads the output block and the head before deciding, or by
1361/// patent-1 reconstruction over the state after one pass (`recon:FILE:bias`).
1362#[derive(Clone)]
1363pub enum Gate {
1364    Conf(f32),
1365    Recon(std::sync::Arc<Topologies>, f32),
1366}
1367
1368pub struct Topologies {
1369    dim: usize,
1370    rank: usize,
1371    me: Vec<f32>,
1372    be: Vec<f32>,
1373    mh: Vec<f32>,
1374    bh: Vec<f32>,
1375}
1376
1377impl Topologies {
1378    /// The router a turbo file carries.
1379    fn from_model(model: &CmfModel) -> Result<Self, String> {
1380        let dim = model.arch().hidden_size;
1381        let v = |n: &str| crate::loader::load_f32(model, n, &crate::loader::Overlay::None);
1382        let (me, be, mh, bh) = (v("dory.router.easy.mean")?, v("dory.router.easy.basis")?, v("dory.router.hard.mean")?, v("dory.router.hard.basis")?);
1383        if me.len() != dim || mh.len() != dim || be.is_empty() || be.len() % dim != 0 || bh.len() != be.len() {
1384            return Err("dory.router: shapes".into());
1385        }
1386        Ok(Self { dim, rank: be.len() / dim, me, be, mh, bh })
1387    }
1388
1389    fn read(path: &str) -> Option<Self> {
1390        let b = std::fs::read(path).ok()?;
1391        let w: Vec<f32> = b.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
1392        let (rank, dim) = (w[0] as usize, w[1] as usize);
1393        let mut at = 2;
1394        let mut take = |n: usize| {
1395            let v = w[at..at + n].to_vec();
1396            at += n;
1397            v
1398        };
1399        let me = take(dim);
1400        let be = take(rank * dim);
1401        let mh = take(dim);
1402        let bh = take(rank * dim);
1403        Some(Self { dim, rank, me, be, mh, bh })
1404    }
1405
1406    /// Reconstruction error of `x` by one topology.
1407    fn err(&self, x: &[f32], mu: &[f32], b: &[f32]) -> f32 {
1408        let y: Vec<f32> = x.iter().zip(mu).map(|(a, m)| a - m).collect();
1409        let mut e: f32 = y.iter().map(|v| v * v).sum();
1410        for r in b.chunks_exact(self.dim).take(self.rank) {
1411            let d: f32 = r.iter().zip(&y).map(|(a, c)| a * c).sum();
1412            e -= d * d;
1413        }
1414        e
1415    }
1416
1417    /// Positive: the easy class reconstructs it better.
1418    pub fn score(&self, x: &[f32]) -> f32 {
1419        self.err(x, &self.mh, &self.bh) - self.err(x, &self.me, &self.be)
1420    }
1421}
1422
1423fn exact_from_env() -> Option<ExactRows> {
1424    exact_from_var("CMF_DORY_EXACT")
1425}
1426
1427/// `FILE:rows` from a variable; a file that is not there gives no weights, which only
1428/// dumps the features.
1429pub fn exact_from_var(name: &str) -> Option<ExactRows> {
1430    let v = std::env::var(name).ok()?;
1431    let (file, rows) = v.rsplit_once(':')?;
1432    let b = std::fs::read(file).unwrap_or_default();
1433    let w: Vec<f32> = b.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
1434    Some(ExactRows { weights: Arc::new(w.get(1..).unwrap_or(&[]).to_vec()), budget: rows.parse().ok()? })
1435}
1436
1437fn gate_from_env() -> Option<Gate> {
1438    let v = std::env::var("CMF_DORY_GATE").ok()?;
1439    let mut it = v.split(':');
1440    match it.next()? {
1441        "conf" => Some(Gate::Conf(it.next()?.parse().ok()?)),
1442        "recon" => {
1443            let t = Topologies::read(it.next()?)?;
1444            Some(Gate::Recon(Arc::new(t), it.next()?.parse().ok()?))
1445        }
1446        _ => None,
1447    }
1448}
1449
1450/// On text where the first read-out rarely ends a token it only costs time: below this
1451/// rate of early exits a token goes straight to the second pass, and one in eight still
1452/// reads out, to notice when the text turns easy.
1453#[derive(Clone, Copy)]
1454pub struct ExitRate {
1455    rate: f32,
1456    tokens: u32,
1457}
1458
1459impl Default for ExitRate {
1460    fn default() -> Self {
1461        Self { rate: 1.0, tokens: 0 }
1462    }
1463}
1464
1465impl ExitRate {
1466    /// Is this token worth a read-out after its first pass?
1467    pub fn probe(&mut self) -> bool {
1468        self.tokens = self.tokens.wrapping_add(1);
1469        self.rate >= 0.35 || self.tokens % 8 == 0
1470    }
1471
1472    pub fn note(&mut self, exited: bool) {
1473        self.rate += 0.1 * (f32::from(u8::from(exited)) - self.rate);
1474    }
1475}
1476
1477/// The top probability of a row of logits, without an exp per entry of the vocabulary.
1478pub fn top_prob(lg: &[f32]) -> f32 {
1479    let top = lg.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
1480    let mut den = 0f64;
1481    for &x in lg {
1482        let t = x - top;
1483        if t > -20.0 {
1484            den += (t as f64).exp();
1485        }
1486    }
1487    (1.0 / den) as f32
1488}
1489
1490/// Rows of a forward on the host.
1491pub const HOST_CHUNK: usize = 64;
1492
1493/// Host forward of a chunk.
1494#[allow(clippy::too_many_arguments)]
1495pub fn forward_host(
1496    m: &Dory,
1497    st: &mut DoryState,
1498    ids: &[u32],
1499    pos0: usize,
1500    loops: usize,
1501    want: Want,
1502    pool: Option<&Pool>,
1503    capture: Option<&mut Capture>,
1504    logits: &mut Vec<f32>,
1505) {
1506    let c = &m.cfg;
1507    if st.slots.is_empty() {
1508        st.slots.resize_with(m.attn_layers, Vec::new);
1509    }
1510    let mut capture = capture;
1511    let mut done = 0usize;
1512    logits.clear();
1513    let tail_from = (pos0 + ids.len()).saturating_sub(EXACT_TAIL);
1514    // q8's batch product has no fast path on x86: a row at a time goes 8 times faster
1515    // there, through the fused matvecs.
1516    let scalar_q8 = cfg!(target_arch = "x86_64")
1517        && m.layers.iter().any(|l| matches!(l, Layer::Attn(w) if matches!(w.q, QTensor::Mapped { dtype: cortiq_core::TensorDtype::Q8_2f, .. })));
1518    for chunk in ids.chunks(if scalar_q8 { 1 } else { HOST_CHUNK }) {
1519        let t = chunk.len();
1520        if pos0 + done >= tail_from {
1521            finish_exact(m, st);
1522        }
1523        let mut h = vec![0f32; t * c.hidden];
1524        for (i, row) in h.chunks_exact_mut(c.hidden).enumerate() {
1525            if (chunk[i] as usize) < m.embed.rows() {
1526                m.embed.row_f32(chunk[i] as usize, row);
1527            }
1528        }
1529        let w = if done + t == ids.len() || want == Want::All { want } else { Want::None };
1530        stack(m, st, &mut h, t, pos0 + done, m.chunk_loops(loops, w), pool, capture.as_deref_mut());
1531        done += t;
1532        st.pos = pos0 + done;
1533        if let Some(lg) = st.exit_logits.take() {
1534            if want != Want::None {
1535                if want == Want::Last {
1536                    logits.clear();
1537                }
1538                logits.extend_from_slice(&lg);
1539            }
1540            continue;
1541        }
1542        match want {
1543            Want::All => head(m, &h, t, Want::All, pool, logits),
1544            Want::Last if done == ids.len() => {
1545                logits.clear();
1546                head(m, &h, t, Want::Last, pool, logits)
1547            }
1548            _ => {}
1549        }
1550    }
1551    finish_exact(m, st);
1552}
1553
1554/// The head over the wanted rows, with the per-token logit scale: `logits` grows.
1555pub fn head(m: &Dory, h: &[f32], t: usize, want: Want, pool: Option<&Pool>, logits: &mut Vec<f32>) {
1556    let c = &m.cfg;
1557    let (rows, from) = match want {
1558        Want::None => return,
1559        Want::Last => (1, t - 1),
1560        Want::All => (t, 0),
1561    };
1562    let at = logits.len();
1563    logits.resize(at + rows * c.vocab, 0.0);
1564    let x = &h[from * c.hidden..t * c.hidden];
1565    if rows == 1 && !crate::gptq_capture::capturing() {
1566        m.head.matvec(x, &mut logits[at..], pool);
1567    } else {
1568        m.head.matmat(x, rows, &mut logits[at..], pool);
1569    }
1570    for row in logits[at..].chunks_exact_mut(c.vocab) {
1571        for (x, s) in row.iter_mut().zip(&m.logit_scale) {
1572            *x *= *s;
1573        }
1574    }
1575}
1576
1577#[cfg(test)]
1578mod tests {
1579    use super::*;
1580
1581    fn tiny(window: usize, kv: KvMode, loops: usize) -> Dory {
1582        let (hidden, ffn, nh, nk, hd, vocab) = (16usize, 16usize, 4usize, 2usize, 8usize, 11usize);
1583        let mut seed = 1u32;
1584        let mut rnd = move |n: usize| -> Vec<f32> {
1585            (0..n)
1586                .map(|_| {
1587                    seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
1588                    ((seed >> 8) as f32 / (1u32 << 24) as f32 - 0.5) * 0.7
1589                })
1590                .collect()
1591        };
1592        let mat = |v: Vec<f32>, r: usize, c: usize| QTensor::from_f32(v, r, c);
1593        let q_size = nh * hd;
1594        let kv_row = nk * hd;
1595        let pattern = "S-*-S-*-S-*-";
1596        let mut layers = Vec::new();
1597        let mut ordinal = 0;
1598        for ch in pattern.chars() {
1599            if ch == '-' {
1600                layers.push(Layer::Mlp(Box::new(MlpWeights {
1601                    gate: mat(rnd(ffn * hidden), ffn, hidden),
1602                    up: mat(rnd(ffn * hidden), ffn, hidden),
1603                    down: mat(rnd(hidden * ffn), hidden, ffn),
1604                    sg: vec![1.5; ffn],
1605                    su: vec![1.2; ffn],
1606                    alpha: vec![0.3; hidden],
1607                })));
1608            } else {
1609                layers.push(Layer::Attn(Box::new(AttnWeights {
1610                    q: mat(rnd(q_size * hidden), q_size, hidden),
1611                    k: mat(rnd(kv_row * hidden), kv_row, hidden),
1612                    v: mat(rnd(kv_row * hidden), kv_row, hidden),
1613                    g: mat(rnd(q_size * hidden), q_size, hidden),
1614                    o: mat(rnd(hidden * q_size), hidden, q_size),
1615                    sq: vec![4.0; q_size],
1616                    sg: vec![2.0; q_size],
1617                    alpha: vec![0.2; hidden],
1618                    sliding: ch == 'S',
1619                    ordinal,
1620                })));
1621                ordinal += 1;
1622            }
1623        }
1624        Dory {
1625            file: None,
1626            cfg: DoryCfg {
1627                hidden,
1628                ffn,
1629                vocab,
1630                nh,
1631                nk,
1632                hd,
1633                window,
1634                n_in: 4,
1635                n_rec: 4,
1636                n_out: 4,
1637                loops,
1638                kv,
1639                attn_scale: 1.0 / (hd as f32).sqrt(),
1640                full_window: None,
1641            },
1642            embed: mat(rnd(vocab * hidden), vocab, hidden),
1643            head: mat(rnd(vocab * hidden), vocab, hidden),
1644            logit_scale: vec![3.0; vocab],
1645            layers,
1646            inv_full: crate::attention::rope_inv_freq(hd, 1.0e7),
1647            inv_sliding: crate::attention::rope_inv_freq(hd, 1.0e4),
1648            attn_layers: ordinal,
1649            o1: None,
1650            gate: None,
1651            prompt_loops: 0,
1652            exact: None,
1653            spill: None,
1654        }
1655    }
1656
1657    fn run(m: &Dory, ids: &[u32], chunk: usize) -> Vec<f32> {
1658        let mut st = DoryState::default();
1659        let mut logits = Vec::new();
1660        let mut at = 0;
1661        for c in ids.chunks(chunk) {
1662            logits.clear();
1663            forward_host(m, &mut st, c, at, m.cfg.loops, Want::Last, None, None, &mut logits);
1664            at += c.len();
1665        }
1666        logits
1667    }
1668
1669    #[test]
1670    fn exp8_tracks_the_library_exp() {
1671        for v in [-80.0f32, -20.0, -3.3, -1.0, -0.01, 0.0, 0.5, 2.7, 13.0, 60.0] {
1672            let e = exp8(&[v; 8])[3];
1673            assert!((e / v.exp() - 1.0).abs() < 1e-6, "{v}: {e} {}", v.exp());
1674        }
1675    }
1676
1677    #[test]
1678    fn activation_matches_the_scalar_form() {
1679        let n = 21;
1680        let mut g: Vec<f32> = (0..n).map(|i| (i as f32 - 10.0) * 0.37).collect();
1681        let g0 = g.clone();
1682        let u: Vec<f32> = (0..n).map(|i| 0.1 + i as f32 * 0.01).collect();
1683        let (a, b) = (vec![1.3f32; n], vec![0.7f32; n]);
1684        silu_rows(&mut g, &u, &a, &b);
1685        for i in 0..n {
1686            let x = g0[i] * a[i];
1687            let want = x / (1.0 + (-x).exp()) * (u[i] * b[i]);
1688            assert!((g[i] - want).abs() <= 1e-5 * want.abs().max(1.0), "{i}: {} {want}", g[i]);
1689        }
1690    }
1691
1692    #[test]
1693    fn a_chunk_and_its_rows_give_the_same_logits() {
1694        let ids: Vec<u32> = (0..23).map(|i| (i * 7 % 11) as u32).collect();
1695        // Past the window on the sliding layers, per-loop caches.
1696        let m = tiny(5, KvMode::PerLoop, 2);
1697        let (a, b, c) = (run(&m, &ids, 1), run(&m, &ids, 4), run(&m, &ids, 64));
1698        for ((x, y), z) in a.iter().zip(&b).zip(&c) {
1699            assert!((x - y).abs() < 2e-4 && (x - z).abs() < 2e-4, "{x} {y} {z}");
1700        }
1701    }
1702
1703    #[test]
1704    fn the_last_loop_cache_rewrites_a_position_in_place() {
1705        let m = tiny(5, KvMode::LastLoop, 2);
1706        let mut st = DoryState::default();
1707        let mut logits = Vec::new();
1708        forward_host(&m, &mut st, &[1, 2, 3, 4, 5, 6, 7, 8], 0, 2, Want::Last, None, None, &mut logits);
1709        let kv_row = m.cfg.nk * m.cfg.hd;
1710        for row in &st.slots {
1711            assert_eq!(row.len(), 1, "one slot per layer");
1712            assert_eq!(row[0].k.len(), 8 * kv_row);
1713        }
1714        assert!(logits.iter().all(|v| v.is_finite()));
1715    }
1716
1717    #[test]
1718    fn a_far_field_seals_and_goes_on_under_the_last_loop_cache() {
1719        let mut m = tiny(5, KvMode::LastLoop, 2);
1720        m.o1 = Some(DoryO1 { m: 4, w: 6, sink: 0, seal: 24 });
1721        let mut st = DoryState::default();
1722        let mut logits = Vec::new();
1723        let ids: Vec<u32> = (0..40).map(|i| (i * 5 % 11) as u32).collect();
1724        forward_host(&m, &mut st, &ids[..30], 0, 2, Want::Last, None, None, &mut logits);
1725        for (at, id) in ids.iter().enumerate().skip(30) {
1726            logits.clear();
1727            forward_host(&m, &mut st, std::slice::from_ref(id), at, 2, Want::Last, None, None, &mut logits);
1728            assert!(logits.iter().all(|v| v.is_finite()));
1729        }
1730        let (exact, far) = host_kv_bytes(&st);
1731        assert!(far > 0 && exact > 0, "the full layers went over to the far field");
1732    }
1733
1734    #[test]
1735    fn exact_rows_take_what_the_landmarks_cannot_span() {
1736        // Keys in a thin subspace, one row off it: the row and its neighbours come first.
1737        let (rows, nk, hd) = (400usize, 1usize, 16usize);
1738        let mut ks = vec![0f32; rows * hd];
1739        for r in 0..rows {
1740            ks[r * hd] = 1.0;
1741            ks[r * hd + 1] = (r as f32 * 0.01).sin() * 0.1;
1742        }
1743        ks[200 * hd + 7] = 1.0;
1744        let vs = vec![1f32; rows * hd];
1745        let x = ExactRows { weights: Arc::new(vec![1.0, 0.0]), budget: 5 };
1746        let keep = pick_exact_rows(&x, &[&FlatRows { k: &ks, v: &vs, nk, hd }], rows, nk, hd, 8, 4, 300);
1747        assert_eq!(keep, vec![198, 199, 200, 201, 202]);
1748    }
1749
1750    #[test]
1751    fn a_prompt_keeps_its_chosen_rows_past_the_seal() {
1752        let mut m = tiny(5, KvMode::LastLoop, 2);
1753        m.o1 = Some(DoryO1 { m: 4, w: 6, sink: 1, seal: 24 });
1754        let layers = m.layers.iter().filter(|l| matches!(l, Layer::Attn(w) if !w.sliding)).count();
1755        m.exact = Some(ExactRows { weights: Arc::new(vec![1.0; layers * 2 * m.cfg.nk]), budget: 3 });
1756        let mut st = DoryState::default();
1757        let mut logits = Vec::new();
1758        let ids: Vec<u32> = (0..40).map(|i| (i * 5 % 11) as u32).collect();
1759        forward_host(&m, &mut st, &ids, 0, 2, Want::Last, None, None, &mut logits);
1760        let mut seen = 0;
1761        for s in st.slots.iter().flatten().filter(|s| !s.far.is_empty()) {
1762            assert!(!s.arch && s.k.is_empty(), "the rows are gone from the exact store");
1763            assert_eq!(s.far[0].device_view().sink_len, 4);
1764            seen += 1;
1765        }
1766        assert!(seen > 0);
1767        logits.clear();
1768        forward_host(&m, &mut st, &[3], 40, 2, Want::Last, None, None, &mut logits);
1769        assert!(logits.iter().all(|v| v.is_finite()));
1770    }
1771
1772    #[test]
1773    fn a_prompt_past_the_seal_reads_the_same_from_ram_and_from_files() {
1774        let build = |spill: Option<std::path::PathBuf>| {
1775            let mut m = tiny(5, KvMode::LastLoop, 2);
1776            m.o1 = Some(DoryO1 { m: 4, w: 6, sink: 1, seal: 24 });
1777            let layers = m.layers.iter().filter(|l| matches!(l, Layer::Attn(w) if !w.sliding)).count();
1778            m.exact = Some(ExactRows { weights: Arc::new(vec![1.0; layers * 2 * m.cfg.nk]), budget: 3 });
1779            m.spill = spill;
1780            m
1781        };
1782        let ids: Vec<u32> = (0..700).map(|i| (i * 5 % 11) as u32).collect();
1783        let dir = std::env::temp_dir().join(format!("cortiq-dory-spill-test-{}", std::process::id()));
1784        let mut got = Vec::new();
1785        for spill in [None, Some(dir.clone())] {
1786            let m = build(spill);
1787            let mut st = DoryState::default();
1788            let mut logits = Vec::new();
1789            forward_host(&m, &mut st, &ids, 0, 2, Want::Last, None, None, &mut logits);
1790            assert!(st.slots.iter().flatten().all(|s| !s.arch && s.store.is_none()));
1791            got.push(logits);
1792        }
1793        assert!(got[0].iter().all(|v| v.is_finite()));
1794        assert_eq!(got[0], got[1]);
1795        // A store in files is gone with the rebuild.
1796        assert_eq!(std::fs::read_dir(&dir).map_or(0, |d| d.count()), 0, "files left in {}", dir.display());
1797        let _ = std::fs::remove_dir_all(&dir);
1798    }
1799
1800    #[test]
1801    fn a_spill_directory_that_cannot_be_made_leaves_the_far_field_working() {
1802        let mut m = tiny(5, KvMode::LastLoop, 2);
1803        m.o1 = Some(DoryO1 { m: 4, w: 6, sink: 1, seal: 24 });
1804        let layers = m.layers.iter().filter(|l| matches!(l, Layer::Attn(w) if !w.sliding)).count();
1805        m.exact = Some(ExactRows { weights: Arc::new(vec![1.0; layers * 2 * m.cfg.nk]), budget: 3 });
1806        let file = std::env::temp_dir().join(format!("cortiq-dory-spill-file-{}", std::process::id()));
1807        std::fs::write(&file, b"x").unwrap();
1808        m.spill = Some(file.join("no"));
1809        let mut st = DoryState::default();
1810        let mut logits = Vec::new();
1811        let ids: Vec<u32> = (0..100).map(|i| (i * 5 % 11) as u32).collect();
1812        forward_host(&m, &mut st, &ids, 0, 2, Want::Last, None, None, &mut logits);
1813        assert!(logits.iter().all(|v| v.is_finite()));
1814        assert!(st.slots.iter().flatten().all(|s| !s.arch));
1815        let _ = std::fs::remove_file(&file);
1816    }
1817
1818    #[test]
1819    fn rollback_keeps_the_prefix_a_new_turn_extends() {
1820        let m = tiny(50, KvMode::PerLoop, 2);
1821        let ids: Vec<u32> = (0..12).map(|i| (i * 3 % 11) as u32).collect();
1822        let want = run(&m, &ids, 1);
1823        let mut st = DoryState::default();
1824        let mut logits = Vec::new();
1825        forward_host(&m, &mut st, &ids[..9], 0, 2, Want::Last, None, None, &mut logits);
1826        st.rollback(5, m.cfg.nk * m.cfg.hd);
1827        forward_host(&m, &mut st, &ids[5..], 5, 2, Want::Last, None, None, &mut logits);
1828        for (x, y) in logits.iter().zip(&want) {
1829            assert!((x - y).abs() < 2e-4, "{x} {y}");
1830        }
1831    }
1832
1833    #[test]
1834    fn top_prob_of_a_sure_row() {
1835        let mut lg = vec![-30.0f32; 100];
1836        lg[7] = 30.0;
1837        assert!(top_prob(&lg) > 0.999);
1838        assert!((top_prob(&[1.0, 1.0]) - 0.5).abs() < 1e-5);
1839    }
1840}