Skip to main content

cortiq_engine/
inkling.rs

1//! Inkling-2-Mini (`inkling2_loop`) text runtime.
2//!
3//! Transcribed from the reference `modeling_inkling2_loop.py`
4//! (huggingface/transformers#51050) and checked against llama.cpp's graph
5//! (`src/models/inkling2*.cpp`), not inferred from tensor names. The stack:
6//!
7//! * 24 layers; `[core_start, core_end)` (6..18) run `passes` times (3) with
8//!   shared weights: 6 + 12·3 + 6 = 48 layer applications a token, each with
9//!   its own keys, values and convolution rings (a "slot": the physical
10//!   layer for the first pass, `layers + (pass − 1)·loop + i` after);
11//! * block attention residuals instead of a plain residual stream: every
12//!   `block` (6) layers the running sum closes into a block state; a layer's
13//!   attention input, its MoE input and the final output are softmax
14//!   mixtures, by learned queries, of the RMS-normed (no weight) block states
15//!   and the running sum. The full-attention layers mix three inputs (q, k, v);
16//! * no rotary embedding: a relative bias over the last `extent` (1024)
17//!   distances, `r · table[d]`, `r` a 16-wide per-head projection of the
18//!   query input (scaled, L2-clipped to 8, log-scaled on the full layers);
19//!   queries scaled per channel and L2-clipped to 22.63, keys L2-clipped, values
20//!   RMS-normed without weight; one sink logit per head and token; the output
21//!   gated by `σ(gate · x)`; local layers see a window of 1024 positions;
22//! * causal short convolutions (4 taps, tap 0 the current position) with a
23//!   residual: on keys and values (`(x + conv) / √5`; the full layers add
24//!   per-token taps projected from the layer input, `/ 3`), after the
25//!   attention and after the MoE (`/ √5`);
26//! * passes 2 and 3 of a loop layer read four messages (q, k, v, MLP) mixed
27//!   from the previous pass's block states and output, and gate them in:
28//!   `(1 − tanh f)·x + tanh g·m`, `f, g` from a rank-64 projection of
29//!   `[norm x, norm m]`;
30//! * MoE: σ router, top-8 of 128 by score + selection bias, weights the
31//!   chosen scores renormalized times 8; experts `4·tanh(g/4)·σ(g)·25·tanh(u/25)`;
32//! * the head over the final mixture, RMS-normed, softcapped at 30.
33//!
34//! The converter is `cortiq-cli/src/inklingpack.rs`.
35
36use crate::loader::{Overlay, load_f32, load_matrix};
37use crate::pool::Pool;
38use crate::qtensor::QTensor;
39use cortiq_core::{CmfError, CmfModel, ModelArch};
40use std::sync::Arc;
41
42pub const ARCH_NAME: &str = "inkling2_loop";
43
44fn err(s: impl Into<String>) -> CmfError {
45    CmfError::Parse(format!("inkling2_loop: {}", s.into()))
46}
47
48fn f(model: &CmfModel, name: &str) -> Result<Vec<f32>, CmfError> {
49    load_f32(model, name, &Overlay::None).map_err(err)
50}
51
52fn t(model: &Arc<CmfModel>, name: &str) -> Result<QTensor, CmfError> {
53    load_matrix(model, name, false, &Overlay::None)
54}
55
56#[inline]
57fn sigmoid(x: f32) -> f32 {
58    1.0 / (1.0 + (-x).exp())
59}
60
61/// `x / rms(x)` (no weight), the reference's `UnweightedRMSNorm`.
62fn unit_rms(x: &[f32], eps: f64) -> Vec<f32> {
63    let ms = x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64;
64    let r = (1.0 / (ms + eps).sqrt()) as f32;
65    x.iter().map(|&v| v * r).collect()
66}
67
68/// `w · x / rms(x)`.
69fn rms_w(x: &[f32], w: &[f32], eps: f64) -> Vec<f32> {
70    let ms = x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64;
71    let r = (1.0 / (ms + eps).sqrt()) as f32;
72    x.iter().zip(w).map(|(&v, &g)| g * (v * r)).collect()
73}
74
75/// Scales each `hd`-wide head down to an L2 norm of `threshold` when longer.
76fn l2_clip(x: &mut [f32], hd: usize, threshold: f32) {
77    for h in x.chunks_mut(hd) {
78        let n = h.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>().sqrt() as f32;
79        let s = (threshold / (n + 1e-6)).min(1.0);
80        for v in h.iter_mut() {
81            *v *= s;
82        }
83    }
84}
85
86fn mv(pool: Option<&Pool>, w: &[f32], x: &[f32], rows: usize) -> Vec<f32> {
87    let mut out = vec![0f32; rows];
88    crate::pool::matvec_rows(pool, w, x, &mut out);
89    out
90}
91
92/// A softmax mixture of the RMS-normed `states` by each of `queries`
93/// (`[nq, dim]`), scaled by `1/√dim`: the reference's block attention
94/// residual (keys and values are the normed states).
95pub fn mix(states: &[&[f32]], queries: &[f32], dim: usize) -> Vec<Vec<f32>> {
96    let normed: Vec<Vec<f32>> = states.iter().map(|s| unit_rms(s, 1e-6)).collect();
97    let scale = 1.0 / (dim as f64).sqrt();
98    queries
99        .chunks(dim)
100        .map(|q| {
101            let logits: Vec<f64> = normed.iter().map(|s| s.iter().zip(q).map(|(&a, &b)| a as f64 * b as f64).sum::<f64>() * scale).collect();
102            let mx = logits.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
103            let e: Vec<f64> = logits.iter().map(|l| (l - mx).exp()).collect();
104            let den: f64 = e.iter().sum();
105            let mut out = vec![0f32; dim];
106            for (s, w) in normed.iter().zip(&e) {
107                let w = (w / den) as f32;
108                for (o, v) in out.iter_mut().zip(s) {
109                    *o += w * v;
110                }
111            }
112            out
113        })
114        .collect()
115}
116
117/// The log scale of the full layers' queries and relative states at `pos`.
118pub fn tau(pos: usize, alpha: f64, floor: f64) -> f32 {
119    (1.0 + alpha * (((pos + 1) as f64 / floor).max(1.0)).ln()) as f32
120}
121
122/// A short convolution: `[channels, kernel]` taps, tap 0 on the current position.
123pub struct Conv {
124    pub taps: Vec<f32>,
125    pub channels: usize,
126    pub kernel: usize,
127    /// The full layers' per-token taps `[groups · kernel, hidden]` over the
128    /// layer input; a group spans `channels / groups` channels.
129    pub proj: Option<Vec<f32>>,
130    pub groups: usize,
131}
132
133impl Conv {
134    fn load(model: &CmfModel, stem: &str, kernel: usize, groups: usize) -> Result<Self, CmfError> {
135        let taps = f(model, &format!("{stem}.taps"))?;
136        if taps.len() % kernel != 0 {
137            return Err(err(format!("{stem}.taps: {} values for {kernel} taps", taps.len())));
138        }
139        let proj = if model.tensor(&format!("{stem}.proj")).is_some() { Some(f(model, &format!("{stem}.proj"))?) } else { None };
140        Ok(Self { channels: taps.len() / kernel, taps, kernel, proj, groups })
141    }
142
143    /// One position: `ring` holds the previous `kernel − 1` inputs (newest
144    /// first); `dynw` the per-token taps `[groups · kernel]` of the full
145    /// layers' convolutions.
146    fn step_with(&self, x: &[f32], ring: &mut Vec<f32>, dynw: Option<&[f32]>) -> Vec<f32> {
147        let (c, k) = (self.channels, self.kernel);
148        if ring.len() != (k - 1) * c {
149            *ring = vec![0f32; (k - 1) * c];
150        }
151        let per = c / self.groups.max(1);
152        let scale = 1.0 / (((if dynw.is_some() { 2 } else { 1 }) * k + 1) as f32).sqrt();
153        let mut out = vec![0f32; c];
154        for ch in 0..c {
155            let tp = &self.taps[ch * k..(ch + 1) * k];
156            let mut acc = 0f32;
157            for lag in 0..k {
158                let xv = if lag == 0 { x[ch] } else { ring[(lag - 1) * c + ch] };
159                let mut w = tp[lag];
160                if let Some(d) = dynw {
161                    w += d[(ch / per) * k + lag];
162                }
163                acc += w * xv;
164            }
165            out[ch] = (x[ch] + acc) * scale;
166        }
167        // shift the ring: newest first
168        if k > 1 {
169            ring.copy_within(0..(k - 2) * c, c);
170            ring[..c].copy_from_slice(x);
171        }
172        out
173    }
174}
175
176pub struct Attn {
177    pub q: QTensor,
178    pub k: QTensor,
179    pub v: QTensor,
180    pub o: QTensor,
181    pub gate: QTensor,
182    pub rel: QTensor,
183    pub sink: Vec<f32>,
184    pub q_scale: Vec<f32>,
185    pub rel_scale: Vec<f32>,
186    /// `[d_rel, extent]`.
187    pub rel_table: Vec<f32>,
188    pub k_conv: Conv,
189    pub v_conv: Conv,
190}
191
192pub struct Gate {
193    /// `[rank, 2·hidden]`, `[hidden, rank]`, `[hidden, rank]`.
194    pub down: Vec<f32>,
195    pub forget: Vec<f32>,
196    pub gain: Vec<f32>,
197}
198
199impl Gate {
200    fn load(model: &CmfModel, stem: &str) -> Result<Self, CmfError> {
201        Ok(Self { down: f(model, &format!("{stem}.down"))?, forget: f(model, &format!("{stem}.forget"))?, gain: f(model, &format!("{stem}.gain"))? })
202    }
203
204}
205
206pub struct Moe {
207    /// `[E, hidden]` f32 router and the selection bias.
208    pub router: Vec<f32>,
209    pub bias: Vec<f32>,
210    pub experts: Vec<[QTensor; 3]>,
211}
212
213pub struct Layer {
214    pub sliding: bool,
215    /// `[1 | 3, hidden]`; None on layer 0.
216    pub attn_query: Option<Vec<f32>>,
217    pub mlp_query: Vec<f32>,
218    /// `input_layernorm` (sliding) or the q, k, v input norms (full).
219    pub in_norm: [Vec<f32>; 3],
220    pub post_norm: Vec<f32>,
221    pub attn: Attn,
222    pub post_attn_conv: Conv,
223    pub post_mlp_conv: Conv,
224    pub moe: Moe,
225    /// The q, k, v and MLP message gates of a loop layer.
226    pub gates: Option<[Gate; 4]>,
227}
228
229/// The embedding table, a row a token (f16 / bf16 rows from the mapping).
230pub enum Embed {
231    Half { idx: usize, rows: usize, bf16: bool },
232    Matrix(QTensor),
233}
234
235impl Embed {
236    fn load(model: &Arc<CmfModel>, name: &str) -> Result<Self, CmfError> {
237        let idx = model.tensor_index(name).ok_or_else(|| err(format!("{name} missing")))?;
238        let e = &model.tensors[idx];
239        match e.dtype {
240            cortiq_core::TensorDtype::F16 | cortiq_core::TensorDtype::Bf16 if e.shape.len() == 2 => Ok(Embed::Half { idx, rows: e.shape[0], bf16: e.dtype == cortiq_core::TensorDtype::Bf16 }),
241            _ => Ok(Embed::Matrix(t(model, name)?)),
242        }
243    }
244
245    pub fn rows(&self) -> usize {
246        match self {
247            Embed::Half { rows, .. } => *rows,
248            Embed::Matrix(m) => m.rows(),
249        }
250    }
251
252    pub fn row_f32(&self, model: &CmfModel, r: usize, out: &mut [f32]) {
253        match self {
254            Embed::Half { idx, bf16, .. } => {
255                let bytes = model.entry_bytes(&model.tensors[*idx]);
256                let dim = out.len();
257                for (o, b) in out.iter_mut().zip(bytes[r * dim * 2..(r + 1) * dim * 2].chunks_exact(2)) {
258                    let h = u16::from_le_bytes([b[0], b[1]]);
259                    *o = if *bf16 { cortiq_core::quant::bf16_to_f32(h) } else { cortiq_core::quant::f16_to_f32(h) };
260                }
261            }
262            Embed::Matrix(m) => m.row_f32(r, out),
263        }
264    }
265}
266
267pub struct Globals {
268    pub model: Arc<CmfModel>,
269    pub embed: Embed,
270    pub embed_norm: Vec<f32>,
271    pub lm_head: QTensor,
272    pub norm: Vec<f32>,
273    pub final_query: Vec<f32>,
274    /// `[loop, 4, hidden]`: q, k, v, MLP message queries of each loop layer.
275    pub message_query: Vec<f32>,
276    /// The DSpark drafter, when the file carries it (`mtp.*`).
277    pub draft: Option<Draft>,
278}
279
280/// One dense layer of the DSpark drafter.
281pub struct DraftLayer {
282    pub q: QTensor,
283    pub k: QTensor,
284    pub v: QTensor,
285    pub o: QTensor,
286    pub k_ctx: QTensor,
287    pub v_ctx: QTensor,
288    pub gate: QTensor,
289    pub up: QTensor,
290    pub down: QTensor,
291    pub dflare_norm: Vec<f32>,
292    pub in_norm: Vec<f32>,
293    pub post_norm: Vec<f32>,
294    pub q_norm: Vec<f32>,
295    pub k_norm: Vec<f32>,
296    pub k_ctx_norm: Vec<f32>,
297    /// A sliding-window layer (`mtp_config.local_layer_ids`).
298    pub local: bool,
299}
300
301/// The DSpark drafter (the release's `mtp.safetensors`): dense layers over a
302/// block of the anchor and mask rows, their context keys and values made from
303/// the target's taps (`targets`: application indices, the last the final
304/// normed state), and a recurrent Markov head over the target's head.
305pub struct Draft {
306    pub layers: Vec<DraftLayer>,
307    /// softmax(fuse_weight) rows: `[mixes][targets]`, a mix per draft layer and
308    /// the Markov head's last.
309    pub alpha: Vec<f32>,
310    pub mask: Vec<f32>,
311    pub norm: Vec<f32>,
312    pub markov_norm: Vec<f32>,
313    /// The recurrence: `[3 rank][2 rank + 2 hidden]` (state, previous token,
314    /// hidden, context columns) and its bias.
315    pub rnn_w: Vec<f32>,
316    pub rnn_b: Vec<f32>,
317    /// The previous token's row `[vocab][rank]` (f16).
318    pub w1: QTensor,
319    /// head · hidden_out `[vocab][rank]` and head · hidden_out's bias.
320    pub fold: QTensor,
321    pub fold_b: Vec<f32>,
322    pub targets: Vec<usize>,
323    pub window: usize,
324    pub block: usize,
325    pub rank: usize,
326    pub rope_theta: f64,
327    pub eps: f32,
328}
329
330impl Draft {
331    fn load(model: &Arc<CmfModel>, mc: &serde_json::Value, dim: usize) -> Result<Self, CmfError> {
332        let u = |k: &str| -> Result<usize, CmfError> { mc.get(k).and_then(|v| v.as_u64()).map(|v| v as usize).ok_or_else(|| err(format!("mtp_config.{k}"))) };
333        let n = u("num_hidden_layers")?;
334        let local: Vec<usize> = mc.get("local_layer_ids").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|v| v.as_u64()).map(|v| v as usize).collect()).unwrap_or_default();
335        let targets: Vec<usize> = mc.get("target_layer_ids").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|v| v.as_u64()).map(|v| v as usize).collect()).unwrap_or_default();
336        let mut layers = Vec::with_capacity(n);
337        for l in 0..n {
338            let p = format!("mtp.layers.{l}.");
339            layers.push(DraftLayer {
340                q: t(model, &format!("{p}self_attn.q_proj.weight"))?,
341                k: t(model, &format!("{p}self_attn.k_proj.weight"))?,
342                v: t(model, &format!("{p}self_attn.v_proj.weight"))?,
343                o: t(model, &format!("{p}self_attn.o_proj.weight"))?,
344                k_ctx: t(model, &format!("{p}self_attn.k_proj_ctx.weight"))?,
345                v_ctx: t(model, &format!("{p}self_attn.v_proj_ctx.weight"))?,
346                gate: t(model, &format!("{p}mlp.gate_proj.weight"))?,
347                up: t(model, &format!("{p}mlp.up_proj.weight"))?,
348                down: t(model, &format!("{p}mlp.down_proj.weight"))?,
349                dflare_norm: f(model, &format!("{p}dflare_norm.weight"))?,
350                in_norm: f(model, &format!("{p}input_layernorm.weight"))?,
351                post_norm: f(model, &format!("{p}post_attention_layernorm.weight"))?,
352                q_norm: f(model, &format!("{p}self_attn.q_norm.weight"))?,
353                k_norm: f(model, &format!("{p}self_attn.k_norm.weight"))?,
354                k_ctx_norm: f(model, &format!("{p}self_attn.k_norm_ctx.weight"))?,
355                local: local.contains(&l),
356            });
357        }
358        // the mixes' weights, each row softmaxed over the targets
359        let fuse = f(model, "mtp.fuse_weight")?;
360        let nt = targets.len();
361        if nt == 0 || fuse.len() != (n + 1) * nt {
362            return Err(err(format!("mtp fuse_weight: {} values for {} mixes of {nt} targets", fuse.len(), n + 1)));
363        }
364        let mut alpha = fuse.clone();
365        for row in alpha.chunks_mut(nt) {
366            let m = row.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
367            let s: f32 = row.iter().map(|&x| (x - m).exp()).sum();
368            for x in row.iter_mut() {
369                *x = (*x - m).exp() / s;
370            }
371        }
372        let rank = u("markov_rank")?;
373        let d = Self {
374            layers,
375            alpha,
376            mask: f(model, "mtp.mask_embed")?,
377            norm: f(model, "mtp.norm.weight")?,
378            markov_norm: f(model, "mtp.markov_head.dflare_norm.weight")?,
379            rnn_w: f(model, "mtp.markov_head.rnn_proj.weight")?,
380            rnn_b: f(model, "mtp.markov_head.rnn_proj.bias")?,
381            w1: t(model, "mtp.markov_head.markov_w1.weight")?,
382            fold: t(model, "mtp.markov_head.fold")?,
383            fold_b: f(model, "mtp.markov_head.fold_b")?,
384            targets,
385            window: u("sliding_window_size")?,
386            block: u("block_size")?,
387            rank,
388            rope_theta: mc.get("rope_theta").and_then(|v| v.as_f64()).unwrap_or(1e6),
389            eps: mc.get("rms_norm_eps").and_then(|v| v.as_f64()).unwrap_or(1e-6) as f32,
390        };
391        if d.rnn_w.len() != 3 * rank * (2 * rank + 2 * dim) || d.mask.len() != dim {
392            return Err(err("mtp: the Markov head's or the mask's shape"));
393        }
394        Ok(d)
395    }
396}
397
398pub struct Cfg {
399    pub dim: usize,
400    pub layers: usize,
401    pub nh: usize,
402    pub nkv: usize,
403    pub hd: usize,
404    pub d_rel: usize,
405    pub eps: f64,
406    pub window: usize,
407    pub rel_extent: usize,
408    pub qk_clip: f32,
409    pub rel_clip: f32,
410    pub log_alpha: f64,
411    pub log_floor: f64,
412    pub block: usize,
413    pub core_start: usize,
414    pub core_end: usize,
415    pub passes: usize,
416    pub top_k: usize,
417    pub route_scale: f32,
418    pub gate_cap: f32,
419    pub up_cap: f32,
420    pub logit_cap: f32,
421    pub max_seq: usize,
422}
423
424impl Cfg {
425    pub fn loop_len(&self) -> usize {
426        self.core_end - self.core_start
427    }
428
429    /// Layer applications a token (= cache slots).
430    pub fn slots(&self) -> usize {
431        self.layers + (self.passes - 1) * self.loop_len()
432    }
433
434    /// The slot of physical layer `li` in pass `pass`.
435    pub fn slot(&self, li: usize, pass: usize) -> usize {
436        if pass == 0 { li } else { self.layers + (pass - 1) * self.loop_len() + (li - self.core_start) }
437    }
438
439    /// `(physical layer, pass)` of every application, in order.
440    pub fn plan(&self) -> Vec<(usize, usize)> {
441        let mut v: Vec<(usize, usize)> = (0..self.core_start).map(|l| (l, 0)).collect();
442        for p in 0..self.passes {
443            v.extend((self.core_start..self.core_end).map(|l| (l, p)));
444        }
445        v.extend((self.core_end..self.layers).map(|l| (l, 0)));
446        v
447    }
448}
449
450/// One slot's cache: keys and values (`nkv·hd` a position; a sliding slot
451/// keeps its last `window` positions, `base` the position of row 0) and the
452/// four convolution rings (k, v, after the attention, after the MoE).
453#[derive(Default)]
454struct SlotState {
455    k: Vec<f32>,
456    v: Vec<f32>,
457    base: usize,
458    rings: [Vec<f32>; 4],
459}
460
461pub struct State {
462    pub pos: usize,
463    pub tokens: Vec<u32>,
464    slots: Vec<SlotState>,
465    /// The sequence's device key (process-unique: a pipeline reuses one model
466    /// for many prompts).
467    sequence_id: u64,
468    /// The sequence runs on the card: None not tried yet, Some(false) the
469    /// host runs it, Some(true) the card holds its states.
470    card: Option<bool>,
471    /// The DSpark depth (kept across sequences: a device's prices and a
472    /// drafter's holds outlive a request).
473    pub spec: SpecPolicy,
474}
475
476static NEXT_SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
477
478impl State {
479    pub fn reset(&mut self, n_slots: usize) {
480        if self.card == Some(true) {
481            crate::gpu::inkling_reset(self.sequence_id);
482        }
483        self.card = None;
484        self.sequence_id = (3u64 << 60) | NEXT_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
485        self.pos = 0;
486        self.tokens.clear();
487        self.slots = (0..n_slots).map(|_| SlotState::default()).collect();
488        self.spec.forget_step();
489    }
490}
491
492impl Drop for State {
493    fn drop(&mut self) {
494        if self.card == Some(true) {
495            crate::gpu::inkling_reset(self.sequence_id);
496        }
497    }
498}
499
500pub fn load(model: &Arc<CmfModel>, arch: &ModelArch) -> Result<(Globals, Vec<Layer>, Cfg, State), CmfError> {
501    let prov = model.header.provenance.as_ref().and_then(|p| p.get("inkling2_loop")).ok_or_else(|| err("header has no inkling2_loop record"))?;
502    let c = prov.get("config").ok_or_else(|| err("no config"))?;
503    let u = |k: &str| -> Result<usize, CmfError> { c.get(k).and_then(|v| v.as_u64()).map(|v| v as usize).ok_or_else(|| err(format!("config.{k}"))) };
504    let fl = |k: &str| -> Result<f64, CmfError> { c.get(k).and_then(|v| v.as_f64()).ok_or_else(|| err(format!("config.{k}"))) };
505    let lc = c.get("loop_config").ok_or_else(|| err("config.loop_config"))?;
506    let lu = |k: &str| -> Result<usize, CmfError> { lc.get(k).and_then(|v| v.as_u64()).map(|v| v as usize).ok_or_else(|| err(format!("loop_config.{k}"))) };
507    let moe = arch.moe.as_ref().ok_or_else(|| err("missing MoE geometry"))?;
508    let local: Vec<usize> = c.get("local_layer_ids").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|v| v.as_u64()).map(|v| v as usize).collect()).unwrap_or_default();
509    let mut cfg = Cfg {
510        dim: arch.hidden_size,
511        layers: arch.num_layers,
512        nh: arch.num_attention_heads,
513        nkv: arch.num_kv_heads,
514        hd: arch.head_dim,
515        d_rel: u("d_rel")?,
516        eps: arch.rms_norm_eps,
517        window: u("sliding_window_size")?,
518        rel_extent: u("rel_extent")?,
519        qk_clip: fl("qk_l2_clip_threshold")? as f32,
520        rel_clip: fl("rel_l2_clip_threshold")? as f32,
521        log_alpha: fl("log_scaling_alpha")?,
522        log_floor: u("log_scaling_n_floor")? as f64,
523        block: u("n_layers_per_attn_res_block")?,
524        core_start: lu("core_start")?,
525        core_end: lu("core_end")?,
526        passes: lu("num_passes")?,
527        top_k: moe.top_k,
528        route_scale: moe.routed_scaling_factor.unwrap_or(1.0),
529        gate_cap: fl("mlp_gate_softcap")? as f32,
530        up_cap: fl("mlp_up_softcap")? as f32,
531        logit_cap: fl("final_logit_softcapping")? as f32,
532        max_seq: std::env::var("CMF_MAX_SEQ").ok().and_then(|v| v.parse::<usize>().ok()).unwrap_or(32_768).min(model.header.arch.max_position_embeddings).max(1),
533    };
534    if cfg.nkv == 0 || cfg.nh % cfg.nkv != 0 || cfg.block == 0 || cfg.core_start == 0 || cfg.core_end <= cfg.core_start || cfg.core_end > cfg.layers || cfg.passes == 0 {
535        return Err(err("geometry"));
536    }
537    // `--loops N` (CMF_INKLING_PASSES): the loop core run N times. A varloop file
538    // (TML-d24-varloop-research) was trained at 1 to 5 passes; Inkling-2-Mini at its
539    // file's count only
540    if let Some(n) = passes_override() {
541        let varloop = lc.get("is_varloop").and_then(|v| v.as_bool()) == Some(true);
542        if n != cfg.passes {
543            if varloop {
544                tracing::info!("inkling2_loop: the loop runs {n} passes (the file's default {})", cfg.passes);
545            } else {
546                tracing::warn!("inkling2_loop: the loop runs {n} passes; this file was trained at {} (a varloop file is trained for other counts)", cfg.passes);
547            }
548        }
549        cfg.passes = n;
550    }
551    let globals = Globals {
552        model: model.clone(),
553        embed: Embed::load(model, "model.embed_tokens.weight")?,
554        embed_norm: f(model, "model.embed_tokens.norm.weight")?,
555        lm_head: t(model, "lm_head.weight")?,
556        norm: f(model, "model.norm.weight")?,
557        final_query: f(model, "model.final_input.query")?,
558        message_query: f(model, "model.message_input.query")?,
559        // the drafter: kept off with CMF_INKLING_DRAFT=0
560        draft: match prov.get("mtp_config") {
561            Some(mc) if !mc.is_null() && std::env::var("CMF_INKLING_DRAFT").as_deref() != Ok("0") => match Draft::load(model, mc, cfg.dim) {
562                Ok(d) => Some(d),
563                Err(e) => {
564                    tracing::warn!("inkling2_loop: the DSpark drafter does not load ({e}); plain decoding");
565                    None
566                }
567            },
568            _ => None,
569        },
570    };
571    if globals.message_query.len() != cfg.loop_len() * 4 * cfg.dim || globals.final_query.len() != cfg.dim {
572        return Err(err("residual queries"));
573    }
574    let kernel = arch.linear_conv_kernel_dim.unwrap_or(4).max(1);
575    let mut layers = Vec::with_capacity(cfg.layers);
576    for li in 0..cfg.layers {
577        let p = format!("model.layers.{li}.");
578        let a = format!("{p}self_attn.");
579        let sliding = local.contains(&li);
580        let attn_query = if li > 0 { Some(f(model, &format!("{p}attention_input.query"))?) } else { None };
581        if attn_query.as_ref().is_some_and(|q| q.len() != (if sliding { 1 } else { 3 }) * cfg.dim) {
582            return Err(err(format!("layer {li}: attention_input.query")));
583        }
584        let in_norm = if sliding {
585            let n = f(model, &format!("{p}input_layernorm.weight"))?;
586            [n.clone(), n.clone(), n]
587        } else {
588            [f(model, &format!("{p}q_input_layernorm.weight"))?, f(model, &format!("{p}k_input_layernorm.weight"))?, f(model, &format!("{p}v_input_layernorm.weight"))?]
589        };
590        let attn = Attn {
591            q: t(model, &format!("{a}q_proj.weight"))?,
592            k: t(model, &format!("{a}k_proj.weight"))?,
593            v: t(model, &format!("{a}v_proj.weight"))?,
594            o: t(model, &format!("{a}o_proj.weight"))?,
595            gate: t(model, &format!("{a}gate_proj.weight"))?,
596            rel: t(model, &format!("{a}rel_proj.weight"))?,
597            sink: f(model, &format!("{a}sink_proj.weight"))?,
598            q_scale: f(model, &format!("{a}q_scale"))?,
599            rel_scale: f(model, &format!("{a}rel_scale"))?,
600            rel_table: f(model, &format!("{a}rel_table"))?,
601            k_conv: Conv::load(model, &format!("{a}k_conv"), kernel, cfg.nkv)?,
602            v_conv: Conv::load(model, &format!("{a}v_conv"), kernel, cfg.nkv)?,
603        };
604        let extent = if sliding { cfg.window } else { cfg.rel_extent };
605        if attn.q.rows() != cfg.nh * cfg.hd || attn.k.rows() != cfg.nkv * cfg.hd || attn.v.rows() != cfg.nkv * cfg.hd || attn.rel.rows() != cfg.nh * cfg.d_rel || attn.rel_table.len() != cfg.d_rel * extent || attn.sink.len() != cfg.nh * cfg.dim {
606            return Err(err(format!("layer {li}: attention shapes")));
607        }
608        let m = format!("{p}mlp.");
609        let mut experts = Vec::with_capacity(moe.num_experts);
610        for e in 0..moe.num_experts {
611            let x = format!("{m}experts.{e}.");
612            experts.push([t(model, &format!("{x}gate_proj.weight"))?, t(model, &format!("{x}up_proj.weight"))?, t(model, &format!("{x}down_proj.weight"))?]);
613        }
614        let mo = Moe { router: f(model, &format!("{m}gate.weight"))?, bias: f(model, &format!("{m}gate.e_score_correction_bias"))?, experts };
615        if mo.bias.len() != moe.num_experts || mo.router.len() != moe.num_experts * cfg.dim {
616            return Err(err(format!("layer {li}: router shapes")));
617        }
618        let gates = if (cfg.core_start..cfg.core_end).contains(&li) && cfg.passes > 1 {
619            Some([
620                Gate::load(model, &format!("{p}q_message_gate"))?,
621                Gate::load(model, &format!("{p}k_message_gate"))?,
622                Gate::load(model, &format!("{p}v_message_gate"))?,
623                Gate::load(model, &format!("{p}mlp_message_gate"))?,
624            ])
625        } else {
626            None
627        };
628        layers.push(Layer {
629            sliding,
630            attn_query,
631            mlp_query: f(model, &format!("{p}mlp_input.query"))?,
632            in_norm,
633            post_norm: f(model, &format!("{p}post_attention_layernorm.weight"))?,
634            attn,
635            post_attn_conv: Conv::load(model, &format!("{p}post_attention_conv"), kernel, 1)?,
636            post_mlp_conv: Conv::load(model, &format!("{p}post_mlp_conv"), kernel, 1)?,
637            moe: mo,
638            gates,
639        });
640    }
641    let mut state = State { pos: 0, tokens: Vec::new(), slots: Vec::new(), sequence_id: 0, card: None, spec: SpecPolicy::default() };
642    state.reset(cfg.slots());
643    Ok((globals, layers, cfg, state))
644}
645
646/// `rows` rows of `width` floats each, for the pool.
647fn par_rows(pool: Option<&Pool>, rows: usize, width: usize, out: &mut [f32], f: &(dyn Fn(usize, &mut [f32]) + Sync)) {
648    debug_assert_eq!(out.len(), rows * width);
649    match pool {
650        Some(p) if rows > 1 => {
651            let addr = crate::pool::SendMut::new(out.as_mut_ptr());
652            p.run_rows(rows, &|a, b| {
653                for r in a..b {
654                    f(r, unsafe { std::slice::from_raw_parts_mut(addr.at(r * width), width) });
655                }
656            });
657        }
658        _ => {
659            for (r, o) in out.chunks_mut(width).enumerate() {
660                f(r, o);
661            }
662        }
663    }
664}
665
666/// `t · x` for `n` rows of `x` (`[n, cols]` → `[n, rows]`).
667fn qmm(t: &QTensor, x: &[f32], n: usize, pool: Option<&Pool>) -> Vec<f32> {
668    let mut out = vec![0f32; n * t.rows()];
669    if n == 1 {
670        t.matvec(x, &mut out, pool);
671    } else {
672        t.matmat(x, n, &mut out, pool);
673    }
674    out
675}
676
677/// An f32 matrix `[rows, cols]` times `n` rows.
678fn fmm(pool: Option<&Pool>, w: &[f32], x: &[f32], n: usize, rows: usize) -> Vec<f32> {
679    let cols = x.len() / n.max(1);
680    let mut out = vec![0f32; n * rows];
681    if n == 1 {
682        crate::pool::matvec_rows(pool, w, x, &mut out);
683        return out;
684    }
685    // a row of the matrix against every input row: the matrix is read once
686    let mut t = vec![0f32; rows * n];
687    par_rows(pool, rows, n, &mut t, &|o, dst| {
688        let wr = &w[o * cols..(o + 1) * cols];
689        for (r, d) in dst.iter_mut().enumerate() {
690            *d = wr.iter().zip(&x[r * cols..(r + 1) * cols]).map(|(a, b)| a * b).sum();
691        }
692    });
693    for o in 0..rows {
694        for r in 0..n {
695            out[r * rows + o] = t[o * n + r];
696        }
697    }
698    out
699}
700
701impl Conv {
702    /// `n` consecutive positions (`x` `[n, channels]`); `dyn_in` `[n, hidden]`.
703    fn rows(&self, x: &[f32], n: usize, ring: &mut Vec<f32>, dyn_in: Option<&[f32]>, pool: Option<&Pool>) -> Vec<f32> {
704        let c = self.channels;
705        let dynw = match (&self.proj, dyn_in) {
706            (Some(p), Some(xi)) => Some(fmm(pool, p, xi, n, self.groups * self.kernel)),
707            _ => None,
708        };
709        let gk = self.groups * self.kernel;
710        let mut out = vec![0f32; n * c];
711        for r in 0..n {
712            let d = dynw.as_ref().map(|d| &d[r * gk..(r + 1) * gk]);
713            let y = self.step_with(&x[r * c..(r + 1) * c], ring, d);
714            out[r * c..(r + 1) * c].copy_from_slice(&y);
715        }
716        out
717    }
718}
719
720/// Unit-RMS each `hd`-wide head of every row.
721fn norm_heads(x: &mut [f32], hd: usize, eps: f64) {
722    for h in x.chunks_mut(hd) {
723        let n = unit_rms(h, eps);
724        h.copy_from_slice(&n);
725    }
726}
727
728impl Attn {
729    /// `n` positions from `p0`: q from `xq`, k from `xk`, v from `xv` (normed
730    /// inputs, `[n, hidden]`); their keys and values into the slot's cache;
731    /// each row's attention over its past with the relative bias and the
732    /// sink; the gated O projection.
733    #[allow(clippy::too_many_arguments)]
734    fn rows(&self, xq: &[f32], xk: &[f32], xv: &[f32], n: usize, ss: &mut SlotState, p0: usize, sliding: bool, cfg: &Cfg, pool: Option<&Pool>) -> Vec<f32> {
735        let (nh, nkv, hd, dr, dim) = (cfg.nh, cfg.nkv, cfg.hd, cfg.d_rel, cfg.dim);
736        let per = nh / nkv;
737        let mut q = qmm(&self.q, xq, n, pool);
738        let mut r = qmm(&self.rel, xq, n, pool);
739        for (row, (qr, rr)) in q.chunks_mut(nh * hd).zip(r.chunks_mut(nh * dr)).enumerate() {
740            for (v, s) in qr.iter_mut().zip(&self.q_scale) {
741                *v *= s;
742            }
743            l2_clip(qr, hd, cfg.qk_clip);
744            for (v, s) in rr.iter_mut().zip(&self.rel_scale) {
745                *v *= s;
746            }
747            l2_clip(rr, dr, cfg.rel_clip);
748            if !sliding {
749                let tu = tau(p0 + row, cfg.log_alpha, cfg.log_floor);
750                for v in qr.iter_mut().chain(rr.iter_mut()) {
751                    *v *= tu;
752                }
753            }
754        }
755        let sinks = fmm(pool, &self.sink, xq, n, nh);
756        let gate = qmm(&self.gate, xq, n, pool);
757        let kl = qmm(&self.k, xk, n, pool);
758        let mut k = self.k_conv.rows(&kl, n, &mut ss.rings[0], Some(xk), pool);
759        l2_clip(&mut k, hd, cfg.qk_clip);
760        let vl = qmm(&self.v, xv, n, pool);
761        let mut v = self.v_conv.rows(&vl, n, &mut ss.rings[1], Some(xv), pool);
762        norm_heads(&mut v, hd, cfg.eps);
763        let row = nkv * hd;
764        ss.k.extend_from_slice(&k);
765        ss.v.extend_from_slice(&v);
766        let base = ss.base;
767        debug_assert_eq!(base + ss.k.len() / row, p0 + n);
768
769        let extent = self.rel_table.len() / dr;
770        let scale = 1.0 / (hd as f32).sqrt();
771        let (kc, vc) = (&ss.k, &ss.v);
772        let mut out = vec![0f32; n * nh * hd];
773        let (q, r) = (&q, &r);
774        par_rows(pool, n * nh, hd, &mut out, &|i, o| {
775            let (rw, h) = (i / nh, i % nh);
776            let pos = p0 + rw;
777            let g = h / per;
778            let qh = &q[(rw * nh + h) * hd..(rw * nh + h + 1) * hd];
779            let rh = &r[(rw * nh + h) * dr..(rw * nh + h + 1) * dr];
780            let first = if sliding { base.max((pos + 1).saturating_sub(cfg.window)) } else { base };
781            // the relative bias of this row and head over the distances it sees
782            let near = extent.min(pos + 1 - first);
783            let bias: Vec<f32> = (0..near).map(|d| (0..dr).map(|j| rh[j] * self.rel_table[j * extent + d]).sum::<f32>()).collect();
784            let sk = sinks[rw * nh + h];
785            let cnt = pos + 1 - first;
786            let mut s = vec![0f32; cnt];
787            let mut mx = sk;
788            for (ii, sv) in s.iter_mut().enumerate() {
789                let tpos = first + ii;
790                let ci = tpos - base;
791                let kr = &kc[(ci * nkv + g) * hd..(ci * nkv + g + 1) * hd];
792                let mut x = kr.iter().zip(qh).map(|(a, b)| a * b).sum::<f32>() * scale;
793                let d = pos - tpos;
794                if d < near {
795                    x += bias[d];
796                }
797                *sv = x;
798                mx = mx.max(x);
799            }
800            let mut den = ((sk - mx) as f64).exp();
801            for sv in s.iter_mut() {
802                *sv = (*sv - mx).exp();
803                den += *sv as f64;
804            }
805            let inv = (1.0 / den) as f32;
806            for (ii, &w) in s.iter().enumerate() {
807                let ci = first + ii - base;
808                let vr = &vc[(ci * nkv + g) * hd..(ci * nkv + g + 1) * hd];
809                let w = w * inv;
810                for (a, b) in o.iter_mut().zip(vr) {
811                    *a += w * b;
812                }
813            }
814        });
815        // a sliding slot keeps its last `window` rows
816        if sliding && ss.k.len() > cfg.window * row {
817            let drop = ss.k.len() / row - cfg.window;
818            ss.k.drain(..drop * row);
819            ss.v.drain(..drop * row);
820            ss.base += drop;
821        }
822        for (o, g) in out.iter_mut().zip(&gate) {
823            *o *= sigmoid(*g);
824        }
825        let y = qmm(&self.o, &out, n, pool);
826        debug_assert_eq!(y.len(), n * dim);
827        y
828    }
829}
830
831impl Moe {
832    /// The selected experts and their mixing weights: the choice by
833    /// `σ(logit) + bias`, the weights the chosen scores over their sum.
834    pub fn route(&self, x: &[f32], top_k: usize, pool: Option<&Pool>) -> Vec<(usize, f32)> {
835        let ne = self.bias.len();
836        let logits = mv(pool, &self.router, x, ne);
837        route_logits(&logits, &self.bias, top_k)
838    }
839
840    /// `n` rows: each row's experts, the rows of an expert in one product.
841    fn rows(&self, x: &[f32], n: usize, cfg: &Cfg, pool: Option<&Pool>) -> Vec<f32> {
842        let dim = cfg.dim;
843        let ne = self.bias.len();
844        let logits = fmm(pool, &self.router, x, n, ne);
845        let mut by: Vec<Vec<(usize, f32)>> = vec![Vec::new(); ne];
846        for r in 0..n {
847            for (e, w) in route_logits(&logits[r * ne..(r + 1) * ne], &self.bias, cfg.top_k) {
848                by[e].push((r, w * cfg.route_scale));
849            }
850        }
851        let mut y = vec![0f32; n * dim];
852        for (e, rows) in by.iter().enumerate() {
853            if rows.is_empty() {
854                continue;
855            }
856            let m = rows.len();
857            let mut xs = vec![0f32; m * dim];
858            for (j, &(r, _)) in rows.iter().enumerate() {
859                xs[j * dim..(j + 1) * dim].copy_from_slice(&x[r * dim..(r + 1) * dim]);
860            }
861            let [gt, up, dn] = &self.experts[e];
862            let g = qmm(gt, &xs, m, pool);
863            let u = qmm(up, &xs, m, pool);
864            let a: Vec<f32> = g.iter().zip(&u).map(|(&g, &u)| softcap(g, cfg.gate_cap) * sigmoid(g) * softcap(u, cfg.up_cap)).collect();
865            let ye = qmm(dn, &a, m, pool);
866            for (j, &(r, w)) in rows.iter().enumerate() {
867                for (o, v) in y[r * dim..(r + 1) * dim].iter_mut().zip(&ye[j * dim..(j + 1) * dim]) {
868                    *o += w * v;
869                }
870            }
871        }
872        y
873    }
874}
875
876#[inline]
877pub fn softcap(x: f32, cap: f32) -> f32 {
878    (x / cap).tanh() * cap
879}
880
881/// Top-k by `σ(logit) + bias` (ties to the lower expert), weights
882/// `σ / (Σσ + 1e-20)` over the chosen ones.
883pub fn route_logits(logits: &[f32], bias: &[f32], top_k: usize) -> Vec<(usize, f32)> {
884    let scores: Vec<f32> = logits.iter().map(|&l| sigmoid(l)).collect();
885    let mut order: Vec<usize> = (0..scores.len()).collect();
886    order.sort_unstable_by(|&a, &b| (scores[b] + bias[b]).partial_cmp(&(scores[a] + bias[a])).unwrap_or(std::cmp::Ordering::Equal).then(a.cmp(&b)));
887    order.truncate(top_k);
888    let sum: f32 = order.iter().map(|&e| scores[e]).sum::<f32>() + 1e-20;
889    order.into_iter().map(|e| (e, scores[e] / sum)).collect()
890}
891
892/// `CMF_INKLING_DUMP=<dir>,<pos>,<pos>…`: the host stack writes every
893/// application's output at those positions (`<dir>/<kind>_s<slot>_p<pos>.f32`).
894fn dump_rows(slot: usize, p0: usize, kind: &str, v: &[f32], dim: usize) {
895    static CFG: std::sync::OnceLock<Option<(String, Vec<usize>)>> = std::sync::OnceLock::new();
896    let cfg = CFG.get_or_init(|| {
897        let s = std::env::var("CMF_INKLING_DUMP").ok()?;
898        let mut it = s.split(',');
899        let dir = it.next()?.to_string();
900        Some((dir, it.filter_map(|p| p.parse().ok()).collect()))
901    });
902    if let Some((dir, ps)) = cfg {
903        for (r, row) in v.chunks(dim).enumerate() {
904            if ps.contains(&(p0 + r)) {
905                let b: Vec<u8> = row.iter().flat_map(|x| x.to_le_bytes()).collect();
906                let _ = std::fs::write(format!("{dir}/{kind}_s{slot}_p{}.f32", p0 + r), b);
907            }
908        }
909    }
910}
911
912/// `x` and the closed blocks per row; the mixture of every row by `queries`.
913fn mix_rows(blocks: &[Vec<f32>], x: &[f32], queries: &[f32], n: usize, dim: usize) -> Vec<Vec<f32>> {
914    let nq = queries.len() / dim;
915    let mut out = vec![vec![0f32; n * dim]; nq];
916    for r in 0..n {
917        let mut st: Vec<&[f32]> = blocks.iter().map(|b| &b[r * dim..(r + 1) * dim]).collect();
918        st.push(&x[r * dim..(r + 1) * dim]);
919        for (qi, m) in mix(&st, queries, dim).into_iter().enumerate() {
920            out[qi][r * dim..(r + 1) * dim].copy_from_slice(&m);
921        }
922    }
923    out
924}
925
926impl Gate {
927    fn rows(&self, x: &[f32], m: &[f32], n: usize, eps: f64, pool: Option<&Pool>) -> Vec<f32> {
928        let dim = x.len() / n;
929        let rank = self.down.len() / (2 * dim);
930        let mut cat = vec![0f32; n * 2 * dim];
931        for r in 0..n {
932            cat[r * 2 * dim..r * 2 * dim + dim].copy_from_slice(&unit_rms(&x[r * dim..(r + 1) * dim], eps));
933            cat[r * 2 * dim + dim..(r + 1) * 2 * dim].copy_from_slice(&unit_rms(&m[r * dim..(r + 1) * dim], eps));
934        }
935        let d = fmm(pool, &self.down, &cat, n, rank);
936        let fg = fmm(pool, &self.forget, &d, n, dim);
937        let gn = fmm(pool, &self.gain, &d, n, dim);
938        (0..n * dim).map(|i| (1.0 - fg[i].tanh()) * x[i] + gn[i].tanh() * m[i]).collect()
939    }
940}
941
942fn rms_rows(x: &[f32], w: &[f32], eps: f64) -> Vec<f32> {
943    x.chunks(w.len()).flat_map(|r| rms_w(r, w, eps)).collect()
944}
945
946/// One layer application for `n` positions from `p0`: `h` the running sums
947/// `[n, hidden]`, `blocks` the closed block states (a boundary layer closes
948/// `h` into them), `msgs` the four messages of a loop pass after the first.
949#[allow(clippy::too_many_arguments)]
950fn layer_rows(l: &Layer, li: usize, ss: &mut SlotState, h: &[f32], n: usize, blocks: &mut Vec<Vec<f32>>, msgs: Option<&[Vec<f32>]>, p0: usize, cfg: &Cfg, pool: Option<&Pool>) -> Vec<f32> {
951    let dim = cfg.dim;
952    let boundary = li % cfg.block == 0;
953    let mut inputs: [Vec<f32>; 3] = match &l.attn_query {
954        Some(q) => {
955            let m = mix_rows(blocks, h, q, n, dim);
956            if l.sliding { [m[0].clone(), m[0].clone(), m[0].clone()] } else { [m[0].clone(), m[1].clone(), m[2].clone()] }
957        }
958        None => [h.to_vec(), h.to_vec(), h.to_vec()],
959    };
960    if let (Some(ms), Some(g)) = (msgs, &l.gates) {
961        for j in 0..3 {
962            inputs[j] = g[j].rows(&inputs[j], &ms[j], n, cfg.eps, pool);
963        }
964    }
965    let xq = rms_rows(&inputs[0], &l.in_norm[0], cfg.eps);
966    let (xk, xv) = if l.sliding && msgs.is_none() {
967        (xq.clone(), xq.clone())
968    } else {
969        (rms_rows(&inputs[1], &l.in_norm[1], cfg.eps), rms_rows(&inputs[2], &l.in_norm[2], cfg.eps))
970    };
971    let a = l.attn.rows(&xq, &xk, &xv, n, ss, p0, l.sliding, cfg, pool);
972    let a = l.post_attn_conv.rows(&a, n, &mut ss.rings[2], None, pool);
973    let r: Vec<f32> = if boundary {
974        blocks.push(h.to_vec());
975        a
976    } else {
977        h.iter().zip(&a).map(|(x, y)| x + y).collect()
978    };
979    let mut m = mix_rows(blocks, &r, &l.mlp_query, n, dim).swap_remove(0);
980    if let (Some(ms), Some(g)) = (msgs, &l.gates) {
981        m = g[3].rows(&m, &ms[3], n, cfg.eps, pool);
982    }
983    let x = rms_rows(&m, &l.post_norm, cfg.eps);
984    let y = l.moe.rows(&x, n, cfg, pool);
985    let y = l.post_mlp_conv.rows(&y, n, &mut ss.rings[3], None, pool);
986    r.iter().zip(&y).map(|(a, b)| a + b).collect()
987}
988
989/// `n` positions from `p0` through the whole stack (host): the normed final
990/// mixture of every row, ready for the head.
991fn host_rows(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, ids: &[u32], p0: usize, pool: Option<&Pool>) -> Vec<f32> {
992    let (dim, n) = (cfg.dim, ids.len());
993    let mut h = vec![0f32; n * dim];
994    for (r, &id) in ids.iter().enumerate() {
995        let mut e = vec![0f32; dim];
996        if (id as usize) < globals.embed.rows() {
997            globals.embed.row_f32(&globals.model, id as usize, &mut e);
998        }
999        h[r * dim..(r + 1) * dim].copy_from_slice(&rms_w(&e, &globals.embed_norm, cfg.eps));
1000    }
1001    let mut blocks: Vec<Vec<f32>> = Vec::new();
1002    for li in 0..cfg.core_start {
1003        h = layer_rows(&layers[li], li, &mut state.slots[li], &h, n, &mut blocks, None, p0, cfg, pool);
1004        dump_rows(li, p0, "h", &h, dim);
1005    }
1006    let (pre_h, pre_blocks) = (h.clone(), blocks.clone());
1007    for pass in 0..cfg.passes {
1008        let mut bank: Vec<Vec<f32>> = Vec::new();
1009        if pass > 0 {
1010            bank = blocks[pre_blocks.len() + 1..].to_vec();
1011            bank.push(std::mem::replace(&mut h, pre_h.clone()));
1012            blocks = pre_blocks.clone();
1013        }
1014        for li in cfg.core_start..cfg.core_end {
1015            let slot = cfg.slot(li, pass);
1016            let msgs = (pass > 0).then(|| {
1017                let i = li - cfg.core_start;
1018                let last = bank.len() - 1;
1019                mix_rows(&bank[..last], &bank[last], &globals.message_query[i * 4 * dim..(i + 1) * 4 * dim], n, dim)
1020            });
1021            h = layer_rows(&layers[li], li, &mut state.slots[slot], &h, n, &mut blocks, msgs.as_deref(), p0, cfg, pool);
1022            dump_rows(slot, p0, "h", &h, dim);
1023        }
1024    }
1025    for li in cfg.core_end..cfg.layers {
1026        h = layer_rows(&layers[li], li, &mut state.slots[li], &h, n, &mut blocks, None, p0, cfg, pool);
1027        dump_rows(li, p0, "h", &h, dim);
1028    }
1029    let fin = mix_rows(&blocks, &h, &globals.final_query, n, dim).swap_remove(0);
1030    let x = rms_rows(&fin, &globals.norm, cfg.eps);
1031    dump_rows(cfg.slots(), p0, "final", &x, dim);
1032    x
1033}
1034
1035/// The loop's pass count asked for at run time (`--loops N` sets
1036/// `CMF_INKLING_PASSES`), at least 1.
1037pub fn passes_override() -> Option<usize> {
1038    std::env::var("CMF_INKLING_PASSES").ok().and_then(|v| v.trim().parse::<usize>().ok()).filter(|&n| n >= 1)
1039}
1040
1041/// Rows of a prompt chunk on the host (`CMF_INKLING_CHUNK`, 128).
1042fn chunk_rows() -> usize {
1043    static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1044    *N.get_or_init(|| std::env::var("CMF_INKLING_CHUNK").ok().and_then(|v| v.parse::<usize>().ok()).filter(|&n| n >= 1).unwrap_or(128))
1045}
1046
1047/// The softcapped logits of `n` normed rows.
1048fn head_rows(globals: &Globals, cfg: &Cfg, x: &[f32], n: usize, pool: Option<&Pool>) -> Vec<f32> {
1049    let mut lg = qmm(&globals.lm_head, x, n, pool);
1050    if cfg.logit_cap > 0.0 {
1051        for v in lg.iter_mut() {
1052            *v = softcap(*v, cfg.logit_cap);
1053        }
1054    }
1055    lg
1056}
1057
1058/// `ids` from `pos` on the card while it holds the sequence (or takes it at
1059/// position 0); `false`: the host runs it. A card that held the sequence and
1060/// fails hands its rows to the host (`host_replay`).
1061#[allow(clippy::too_many_arguments)]
1062fn on_card(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, ids: &[u32], pos: usize, want: bool, all: bool, logits: &mut Vec<f32>, pool: Option<&Pool>) -> bool {
1063    let try_card = match state.card {
1064        Some(true) => true,
1065        None => pos == 0,
1066        Some(false) => false,
1067    };
1068    if !try_card || !(crate::gpu::cuda_active() || crate::gpu::metal_active() || crate::gpu::wgpu_active()) {
1069        if state.card.is_none() && pos == 0 {
1070            state.card = Some(false);
1071        }
1072        return false;
1073    }
1074    if crate::gpu::inkling_forward(state.sequence_id, globals, layers, cfg, ids, pos, want, all, logits) {
1075        if state.card.is_none() {
1076            tracing::info!("inkling2_loop: the sequence runs on the card");
1077        }
1078        state.card = Some(true);
1079        state.tokens.extend_from_slice(ids);
1080        state.pos = pos + ids.len();
1081        return true;
1082    }
1083    if state.card == Some(true) {
1084        tracing::warn!("inkling2_loop: the card dropped the sequence at {pos}; the host replays its {} rows", state.tokens.len());
1085        host_replay(globals, layers, cfg, state, pool);
1086    }
1087    state.card = Some(false);
1088    false
1089}
1090
1091/// The host's caches rebuilt from the sequence's tokens (after the card let go).
1092fn host_replay(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, pool: Option<&Pool>) {
1093    let toks = std::mem::take(&mut state.tokens);
1094    state.slots = (0..cfg.slots()).map(|_| SlotState::default()).collect();
1095    for (ci, part) in toks.chunks(chunk_rows()).enumerate() {
1096        let _ = host_rows(globals, layers, cfg, state, part, ci * chunk_rows(), pool);
1097    }
1098    state.pos = toks.len();
1099    state.tokens = toks;
1100}
1101
1102/// The prompt from `start` through the host stack in chunks; the last row's
1103/// logits. Returns the positions taken (all of them, or 0 when the sequence
1104/// is not at `start`).
1105#[allow(clippy::too_many_arguments)]
1106pub fn forward_prompt(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, ids: &[u32], start: usize, pool: Option<&Pool>, logits: &mut Vec<f32>) -> usize {
1107    if ids.is_empty() || std::env::var("CMF_INKLING_BATCH").as_deref() == Ok("0") {
1108        return 0;
1109    }
1110    if start == 0 {
1111        state.reset(cfg.slots());
1112    } else if state.pos != start {
1113        return 0;
1114    }
1115    let t0 = std::time::Instant::now();
1116    if on_card(globals, layers, cfg, state, ids, start, true, false, logits, pool) {
1117        tracing::info!("inkling2_loop: {} prompt rows on the card in {:.2} s", ids.len(), t0.elapsed().as_secs_f64());
1118        return ids.len();
1119    }
1120    let mut last = Vec::new();
1121    for (ci, part) in ids.chunks(chunk_rows()).enumerate() {
1122        let p0 = start + ci * chunk_rows();
1123        last = host_rows(globals, layers, cfg, state, part, p0, pool);
1124        state.tokens.extend_from_slice(part);
1125        state.pos = p0 + part.len();
1126        let n = part.len();
1127        last = last[(n - 1) * cfg.dim..].to_vec();
1128    }
1129    *logits = head_rows(globals, cfg, &last, 1, pool);
1130    tracing::info!("inkling2_loop: {} prompt rows on the host in {:.1} s", ids.len(), t0.elapsed().as_secs_f64());
1131    ids.len()
1132}
1133
1134/// A window's negative log-likelihood through the host stack in chunks (the
1135/// predictions from `from` on).
1136pub fn nll(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, ids: &[u32], from: usize, pool: Option<&Pool>) -> Option<(f64, usize)> {
1137    if ids.len() < 2 || std::env::var("CMF_INKLING_BATCH").as_deref() == Ok("0") {
1138        return None;
1139    }
1140    let n = ids.len() - 1;
1141    let t0 = std::time::Instant::now();
1142    state.reset(cfg.slots());
1143    let (mut nll, mut cnt) = (0f64, 0usize);
1144    let vocab = globals.lm_head.rows();
1145    // rows a card call scores (`CMF_INKLING_NLL_ROWS`): 16 keeps every call on
1146    // the arms' decode path, more takes CUDA's prompt path
1147    let card_rows = std::env::var("CMF_INKLING_NLL_ROWS").ok().and_then(|v| v.parse::<usize>().ok()).filter(|&r| r >= 1).unwrap_or(16);
1148    let mut card = None;
1149    let mut p0 = 0usize;
1150    while p0 < n {
1151        let take = if card != Some(false) { card_rows } else { chunk_rows() }.min(n - p0);
1152        let part = &ids[p0..p0 + take];
1153        let mut lg = Vec::new();
1154        if card != Some(false) {
1155            let ok = on_card(globals, layers, cfg, state, part, p0, true, true, &mut lg, pool);
1156            card = Some(ok);
1157        }
1158        if card == Some(false) {
1159            let x = host_rows(globals, layers, cfg, state, part, p0, pool);
1160            state.pos = p0 + part.len();
1161            lg = head_rows(globals, cfg, &x, part.len(), pool);
1162        }
1163        for (j, row) in lg.chunks(vocab).enumerate() {
1164            let p = p0 + j;
1165            if p < from {
1166                continue;
1167            }
1168            let target = (ids[p + 1] as usize).min(vocab - 1);
1169            let best = row.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v)) as f64;
1170            let den: f64 = row.iter().map(|&v| ((v as f64) - best).exp()).sum();
1171            nll += den.ln() - (row[target] as f64 - best);
1172            cnt += 1;
1173        }
1174        p0 += take;
1175    }
1176    state.reset(cfg.slots());
1177    tracing::info!("inkling2_loop nll: {n} rows on the {} in {:.1} s", if card == Some(true) { "card" } else { "host" }, t0.elapsed().as_secs_f64());
1178    Some((nll, cnt))
1179}
1180
1181/// One token; the logits when asked.
1182#[allow(clippy::too_many_arguments)]
1183pub fn forward_token(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, token_id: u32, position: usize, pool: Option<&Pool>, logits: &mut Vec<f32>, want_logits: bool) {
1184    if position == 0 || state.pos != position {
1185        if position != 0 && state.pos != position {
1186            tracing::warn!("inkling2_loop: position {position} after {}; the sequence restarts", state.pos);
1187        }
1188        state.reset(cfg.slots());
1189    }
1190    if on_card(globals, layers, cfg, state, &[token_id], position, want_logits, false, logits, pool) {
1191        return;
1192    }
1193    state.tokens.push(token_id);
1194    let x = host_rows(globals, layers, cfg, state, &[token_id], position, pool);
1195    state.pos = position + 1;
1196    if want_logits {
1197        *logits = head_rows(globals, cfg, &x, 1, pool);
1198    }
1199}
1200
1201/// `CMF_INKLING_SPEC`: unset or `auto` lets [`SpecPolicy`] pick each round's
1202/// drafts (`usize::MAX` here), 0 is plain decoding, a number pins the drafts a
1203/// round offers (the block's 7 at most).
1204pub fn spec_k() -> usize {
1205    static K: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1206    *K.get_or_init(|| std::env::var("CMF_INKLING_SPEC").ok().and_then(|v| v.parse::<usize>().ok()).unwrap_or(usize::MAX))
1207}
1208
1209/// A verify of `k` drafts against a plain token, NVIDIA L4 (calls of 1..8
1210/// rows: 18.4, 23.1, 25.8, 28.4, 30.7, 32.8, 34.9, 36.9 ms): the price of a
1211/// depth no round has timed yet, scaled from the nearest timed one.
1212const SPEC_REL: [f32; 8] = [1.0, 1.26, 1.40, 1.54, 1.67, 1.78, 1.90, 2.0];
1213
1214/// How often draft `j` holds once the one before it held, before a round has
1215/// shown it (DSpark's own figures for Inkling 2: a half to two thirds of
1216/// drafts kept on prose and chat).
1217const SPEC_HOLD_PRIOR: [f32; 7] = [0.70, 0.65, 0.62, 0.60, 0.58, 0.56, 0.55];
1218
1219/// The DSpark depth that lands the most tokens per millisecond: every round
1220/// and plain token is timed from one decode step to the next (the
1221/// pipeline's own work included), a depth's price is its running average
1222/// (one never timed is scaled from the nearest timed one by [`SPEC_REL`]),
1223/// and how often each draft holds is a running average too. 0 drafts, plain
1224/// decoding, is a depth like the others; while it wins, a round of 2 every
1225/// 32 tokens keeps the holds current.
1226#[derive(Clone, Debug)]
1227pub struct SpecPolicy {
1228    hold: [f32; 7],
1229    wall: [f32; 8],
1230    seen: [u8; 8],
1231    k: usize,
1232    dwell: u8,
1233    plain_run: u16,
1234    picked: Option<std::time::Instant>,
1235    last: Option<(std::time::Instant, usize, usize)>,
1236}
1237
1238impl Default for SpecPolicy {
1239    fn default() -> Self {
1240        Self { hold: SPEC_HOLD_PRIOR, wall: [0.0; 8], seen: [0; 8], k: 3, dwell: 0, plain_run: 0, picked: None, last: None }
1241    }
1242}
1243
1244impl SpecPolicy {
1245    /// The drafts for the step at `pos` (`room`: tokens the request still
1246    /// allows past the anchor). Times the previous step when it ended here.
1247    pub fn pick(&mut self, pos: usize, room: usize) -> usize {
1248        let now = std::time::Instant::now();
1249        self.picked = Some(now);
1250        if let Some((t, k, at)) = self.last.take() {
1251            if at == pos {
1252                let w = now.duration_since(t).as_secs_f32() * 1e3;
1253                // a depth's first step builds its call's graph and is not counted
1254                match self.seen[k] {
1255                    0 => self.seen[k] = 1,
1256                    1 => (self.wall[k], self.seen[k]) = (w, 2),
1257                    _ if w < self.wall[k] * 4.0 => self.wall[k] += 0.2 * (w - self.wall[k]),
1258                    _ => {}
1259                }
1260            }
1261        }
1262        let pinned = spec_k();
1263        let k = if pinned != usize::MAX {
1264            pinned.min(7)
1265        } else {
1266            self.plan()
1267        };
1268        let k = if k == 0 && self.plain_run >= 32 { 2 } else { k };
1269        k.min(room)
1270    }
1271
1272    /// Record the step just taken at `pos`: `k` drafts offered, `accepted`
1273    /// kept (0 and 0 for a plain token).
1274    pub fn done(&mut self, pos: usize, k: usize, accepted: usize) {
1275        let k = k.min(7);
1276        self.last = self.picked.take().map(|t| (t, k, pos + 1 + accepted));
1277        if k == 0 {
1278            self.plain_run = self.plain_run.saturating_add(1);
1279            return;
1280        }
1281        self.plain_run = 0;
1282        for j in 1..=k {
1283            if accepted + 1 >= j {
1284                let hit = if accepted >= j { 1.0 } else { 0.0 };
1285                self.hold[j - 1] += 0.1 * (hit - self.hold[j - 1]);
1286            }
1287        }
1288        // text this predictable is worth a deeper round now and then
1289        if k < 7 && self.hold[k - 1] >= 0.9 {
1290            for j in k + 1..=7 {
1291                self.hold[j - 1] += 0.02 * (self.hold[k - 1] - self.hold[j - 1]);
1292            }
1293        }
1294    }
1295
1296    /// The step after a reset or a new request is not timed against the last one.
1297    pub fn forget_step(&mut self) {
1298        self.last = None;
1299        self.picked = None;
1300    }
1301
1302    fn price(&self, k: usize) -> Option<f32> {
1303        if self.seen[k] >= 2 {
1304            return Some(self.wall[k]);
1305        }
1306        let near = (0..8usize).filter(|&j| self.seen[j] >= 2).min_by_key(|&j| j.abs_diff(k))?;
1307        Some(self.wall[near] * SPEC_REL[k] / SPEC_REL[near])
1308    }
1309
1310    fn plan(&mut self) -> usize {
1311        let mut rate = [0f32; 8];
1312        let (mut tokens, mut reach) = (1.0f32, 1.0f32);
1313        for k in 0..8usize {
1314            if k > 0 {
1315                reach *= self.hold[k - 1];
1316                tokens += reach;
1317            }
1318            match self.price(k) {
1319                Some(p) if p > 0.0 => rate[k] = tokens / p,
1320                // nothing timed yet: stay
1321                _ => return self.k,
1322            }
1323        }
1324        if self.dwell > 0 {
1325            self.dwell -= 1;
1326            return self.k;
1327        }
1328        let best = (0..8usize).max_by(|&a, &b| rate[a].total_cmp(&rate[b])).unwrap_or(self.k);
1329        if best != self.k && rate[best] > rate[self.k] * 1.04 {
1330            if std::env::var("CMF_INKLING_SPEC_TIME").is_ok() {
1331                eprintln!("dspark: {} → {best} drafts (a step costs {:.1?} ms, a draft holds {:.2?})", self.k, self.wall, self.hold);
1332            }
1333            self.k = best;
1334            self.dwell = 6;
1335        }
1336        self.k
1337    }
1338}
1339
1340/// One DSpark round at the decode tip, on the card: `anchor` (the token the
1341/// sampler took for `pos`) and up to `k` drafts through the target in one
1342/// call; the drafts it agrees with (its greedy picks) are kept, the rest rolled
1343/// back. Returns the accepted drafts and leaves `logits` the last kept row's;
1344/// `None` when no round ran (no drafter, not on the card, a refusal): nothing
1345/// changed and the caller forwards the anchor itself.
1346pub fn spec_round(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, anchor: u32, pos: usize, k: usize, logits: &mut Vec<f32>) -> Option<Vec<u32>> {
1347    globals.draft.as_ref()?;
1348    if k == 0 || state.card != Some(true) || state.pos != pos || pos == 0 {
1349        return None;
1350    }
1351    let timed = std::env::var("CMF_INKLING_SPEC_TIME").is_ok();
1352    let t0 = std::time::Instant::now();
1353    let mut drafts = crate::gpu::inkling_draft(state.sequence_id, globals, cfg, anchor, pos, k)?;
1354    // `CMF_INKLING_SPEC_JUNK=1` (a check): drafts the model never keeps, so every
1355    // round rolls all of them back — the text must stay plain decoding's
1356    if std::env::var("CMF_INKLING_SPEC_JUNK").as_deref() == Ok("1") {
1357        drafts.iter_mut().for_each(|d| *d = 1);
1358    }
1359    if drafts.is_empty() || !crate::gpu::inkling_ring_snap(state.sequence_id) {
1360        return None;
1361    }
1362    let t1 = std::time::Instant::now();
1363    let mut ids = Vec::with_capacity(drafts.len() + 1);
1364    ids.push(anchor);
1365    ids.extend_from_slice(&drafts);
1366    // each row's greedy pick on the card; only the kept row's logits come over
1367    let mut picks = Vec::with_capacity(ids.len());
1368    if !crate::gpu::inkling_verify(state.sequence_id, globals, layers, cfg, &ids, pos, &mut picks) || picks.len() != ids.len() {
1369        // the card let go mid-round: the host replays what it ran
1370        state.card = Some(false);
1371        return None;
1372    }
1373    let vocab = globals.lm_head.rows();
1374    let mut acc = 0usize;
1375    while acc < drafts.len() && picks[acc] == drafts[acc] {
1376        acc += 1;
1377    }
1378    let keep = acc + 1;
1379    if keep < ids.len() && !crate::gpu::inkling_ring_back(state.sequence_id, keep) {
1380        state.card = Some(false);
1381        return None;
1382    }
1383    if !crate::gpu::inkling_row_logits(state.sequence_id, acc, vocab, logits) {
1384        state.card = Some(false);
1385        return None;
1386    }
1387    state.tokens.extend_from_slice(&ids[..keep]);
1388    state.pos = pos + keep;
1389    if timed {
1390        static T: std::sync::Mutex<(f64, f64, f64, u32)> = std::sync::Mutex::new((0.0, 0.0, 0.0, 0));
1391        let mut t = T.lock().unwrap();
1392        t.0 += (t1 - t0).as_secs_f64() * 1e3;
1393        t.1 += t1.elapsed().as_secs_f64() * 1e3;
1394        t.2 += (drafts.len() + 1) as f64;
1395        t.3 += 1;
1396        if t.3 % 64 == 0 {
1397            let n = t.3 as f64;
1398            eprintln!("dspark: {} rounds, ms a round: drafts {:.2}, verify and rollback {:.2} ({:.1} rows)", t.3, t.0 / n, t.1 / n, t.2 / n);
1399        }
1400    }
1401    Some(drafts[..acc].to_vec())
1402}
1403
1404#[cfg(test)]
1405mod tests {
1406    use super::*;
1407
1408    fn cfg() -> Cfg {
1409        Cfg {
1410            dim: 4,
1411            layers: 24,
1412            nh: 2,
1413            nkv: 1,
1414            hd: 2,
1415            d_rel: 2,
1416            eps: 1e-6,
1417            window: 4,
1418            rel_extent: 4,
1419            qk_clip: 22.6,
1420            rel_clip: 8.0,
1421            log_alpha: 0.1,
1422            log_floor: 8192.0,
1423            block: 6,
1424            core_start: 6,
1425            core_end: 18,
1426            passes: 3,
1427            top_k: 2,
1428            route_scale: 8.0,
1429            gate_cap: 4.0,
1430            up_cap: 25.0,
1431            logit_cap: 30.0,
1432            max_seq: 64,
1433        }
1434    }
1435
1436    #[test]
1437    fn the_plan_visits_the_core_three_times_with_its_own_slots() {
1438        let c = cfg();
1439        let plan = c.plan();
1440        assert_eq!(plan.len(), 48);
1441        assert_eq!(c.slots(), 48);
1442        assert_eq!(plan[6], (6, 0));
1443        assert_eq!(plan[18], (6, 1));
1444        assert_eq!(plan[30], (6, 2));
1445        assert_eq!(plan[42], (18, 0));
1446        assert_eq!(c.slot(6, 1), 24);
1447        assert_eq!(c.slot(17, 2), 47);
1448        let mut slots: Vec<usize> = plan.iter().map(|&(l, p)| c.slot(l, p)).collect();
1449        slots.sort();
1450        slots.dedup();
1451        assert_eq!(slots.len(), 48);
1452    }
1453
1454    #[test]
1455    fn the_dspark_depth_follows_the_holds_and_the_prices() {
1456        // L4 prices: a plain token 18.4 ms, a verify of k drafts by SPEC_REL
1457        let timed = |hold: [f32; 7]| {
1458            let mut p = SpecPolicy { hold, ..SpecPolicy::default() };
1459            for k in 0..8 {
1460                p.wall[k] = 18.4 * SPEC_REL[k] + if k > 0 { 2.0 } else { 0.0 };
1461                p.seen[k] = 2;
1462            }
1463            p.plan()
1464        };
1465        // text that holds: a deep round
1466        assert!(timed([0.95; 7]) >= 6);
1467        // drafts that rarely hold: plain decoding
1468        assert_eq!(timed([0.15; 7]), 0);
1469        // chat-like holds: a short round
1470        let k = timed([0.7, 0.65, 0.6, 0.55, 0.5, 0.5, 0.5]);
1471        assert!((1..=4).contains(&k), "{k}");
1472        // nothing timed yet: the starting depth
1473        assert_eq!(SpecPolicy::default().plan(), 3);
1474        // one timed depth prices the rest from SPEC_REL
1475        let mut p = SpecPolicy::default();
1476        p.wall[3] = 28.4;
1477        p.seen[3] = 2;
1478        assert!((p.price(0).unwrap() - 28.4 / 1.54).abs() < 1e-3);
1479    }
1480
1481    #[test]
1482    fn a_varloop_plan_runs_the_core_any_number_of_times() {
1483        for passes in [1usize, 2, 5] {
1484            let c = Cfg { passes, ..cfg() };
1485            let plan = c.plan();
1486            assert_eq!(plan.len(), 12 + 12 * passes);
1487            assert_eq!(c.slots(), 24 + 12 * (passes - 1));
1488            assert_eq!(plan.last(), Some(&(23, 0)));
1489            let mut slots: Vec<usize> = plan.iter().map(|&(l, p)| c.slot(l, p)).collect();
1490            slots.sort();
1491            slots.dedup();
1492            assert_eq!(slots.len(), c.slots());
1493            assert_eq!(slots.last(), Some(&(c.slots() - 1)));
1494        }
1495    }
1496
1497    #[test]
1498    fn tau_is_one_below_the_floor() {
1499        assert_eq!(tau(0, 0.1, 8192.0), 1.0);
1500        assert_eq!(tau(8191, 0.1, 8192.0), 1.0);
1501        assert!((tau(16383, 0.1, 8192.0) - (1.0 + 0.1 * 2f32.ln())).abs() < 1e-6);
1502    }
1503
1504    #[test]
1505    fn the_mixture_of_equal_states_is_that_state_normed() {
1506        let s = [1.0f32, 2.0, 3.0, 4.0];
1507        let m = mix(&[&s, &s], &[0.3, -0.2, 0.1, 0.5], 4);
1508        let n = unit_rms(&s, 1e-6);
1509        for (a, b) in m[0].iter().zip(&n) {
1510            assert!((a - b).abs() < 1e-6);
1511        }
1512    }
1513
1514    #[test]
1515    fn a_static_conv_keeps_its_ring_newest_first() {
1516        // one channel, taps [current 1, lag1 0.5, lag2 0.25, lag3 0]
1517        let c = Conv { taps: vec![1.0, 0.5, 0.25, 0.0], channels: 1, kernel: 4, proj: None, groups: 1 };
1518        let mut ring = Vec::new();
1519        let s5 = 5f32.sqrt();
1520        let y0 = c.step_with(&[2.0], &mut ring, None);
1521        assert!((y0[0] - (2.0 + 2.0) / s5).abs() < 1e-6);
1522        let y1 = c.step_with(&[4.0], &mut ring, None);
1523        assert!((y1[0] - (4.0 + 4.0 + 1.0) / s5).abs() < 1e-6);
1524        let y2 = c.step_with(&[8.0], &mut ring, None);
1525        assert!((y2[0] - (8.0 + 8.0 + 2.0 + 0.5) / s5).abs() < 1e-6);
1526        assert_eq!(ring, vec![8.0, 4.0, 2.0]);
1527    }
1528
1529    #[test]
1530    fn the_router_picks_by_the_biased_score_and_weighs_by_the_plain_one() {
1531        let r = route_logits(&[0.0, 2.0, -1.0], &[0.9, 0.0, 0.0], 2);
1532        assert_eq!(r[0].0, 0);
1533        assert_eq!(r[1].0, 1);
1534        let (s0, s1) = (0.5f32, sigmoid(2.0));
1535        assert!((r[0].1 - s0 / (s0 + s1)).abs() < 1e-6);
1536    }
1537}