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        card_dropped(globals, layers, cfg, state, pos, pool);
1085    }
1086    state.card = Some(false);
1087    false
1088}
1089
1090/// The card let go of a sequence it held (a call failed: an allocation, a
1091/// graph): the host rebuilds its caches from the sequence's tokens and runs
1092/// the sequence from here on. Every path off the card goes through here — a
1093/// host that took a position without its caches read rows it never wrote.
1094fn card_dropped(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, pos: usize, pool: Option<&Pool>) {
1095    tracing::warn!("inkling2_loop: the card dropped the sequence at {pos}; the host replays its {} rows", state.tokens.len());
1096    host_replay(globals, layers, cfg, state, pool);
1097    state.card = Some(false);
1098}
1099
1100/// Positions the host's caches hold: those of the first application's slot
1101/// (layer 0 runs once a position; a sliding slot's dropped rows are in its base).
1102fn host_holds(state: &State, cfg: &Cfg) -> usize {
1103    state.slots.get(cfg.slot(0, 0)).map_or(0, |s| s.base + s.k.len() / (cfg.nkv * cfg.hd).max(1))
1104}
1105
1106/// Before the host runs from `pos`: its caches must hold the sequence up to
1107/// there. A card that let go without `card_dropped` leaves them empty; the
1108/// host then replays the sequence's tokens instead of reading past its cache.
1109fn host_catch_up(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, pos: usize, pool: Option<&Pool>) {
1110    if host_behind(state, cfg, pos) {
1111        tracing::warn!("inkling2_loop: the host's caches hold {} of {pos} positions; it replays the sequence", host_holds(state, cfg));
1112        host_replay(globals, layers, cfg, state, pool);
1113    }
1114}
1115
1116/// The host's caches miss positions before `pos` that the sequence's tokens
1117/// have (so a replay of the tokens brings them to `pos`).
1118fn host_behind(state: &State, cfg: &Cfg, pos: usize) -> bool {
1119    host_holds(state, cfg) != pos && state.tokens.len() == pos
1120}
1121
1122/// The host's caches rebuilt from the sequence's tokens (after the card let go).
1123fn host_replay(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, pool: Option<&Pool>) {
1124    let toks = std::mem::take(&mut state.tokens);
1125    state.slots = (0..cfg.slots()).map(|_| SlotState::default()).collect();
1126    for (ci, part) in toks.chunks(chunk_rows()).enumerate() {
1127        let _ = host_rows(globals, layers, cfg, state, part, ci * chunk_rows(), pool);
1128    }
1129    state.pos = toks.len();
1130    state.tokens = toks;
1131}
1132
1133/// The prompt from `start` through the host stack in chunks; the last row's
1134/// logits. Returns the positions taken (all of them, or 0 when the sequence
1135/// is not at `start`).
1136#[allow(clippy::too_many_arguments)]
1137pub fn forward_prompt(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, ids: &[u32], start: usize, pool: Option<&Pool>, logits: &mut Vec<f32>) -> usize {
1138    if ids.is_empty() || std::env::var("CMF_INKLING_BATCH").as_deref() == Ok("0") {
1139        return 0;
1140    }
1141    if start == 0 {
1142        state.reset(cfg.slots());
1143    } else if state.pos != start {
1144        return 0;
1145    }
1146    let t0 = std::time::Instant::now();
1147    if on_card(globals, layers, cfg, state, ids, start, true, false, logits, pool) {
1148        tracing::info!("inkling2_loop: {} prompt rows on the card in {:.2} s", ids.len(), t0.elapsed().as_secs_f64());
1149        return ids.len();
1150    }
1151    host_catch_up(globals, layers, cfg, state, start, pool);
1152    let mut last = Vec::new();
1153    for (ci, part) in ids.chunks(chunk_rows()).enumerate() {
1154        let p0 = start + ci * chunk_rows();
1155        last = host_rows(globals, layers, cfg, state, part, p0, pool);
1156        state.tokens.extend_from_slice(part);
1157        state.pos = p0 + part.len();
1158        let n = part.len();
1159        last = last[(n - 1) * cfg.dim..].to_vec();
1160    }
1161    *logits = head_rows(globals, cfg, &last, 1, pool);
1162    tracing::info!("inkling2_loop: {} prompt rows on the host in {:.1} s", ids.len(), t0.elapsed().as_secs_f64());
1163    ids.len()
1164}
1165
1166/// A window's negative log-likelihood through the host stack in chunks (the
1167/// predictions from `from` on).
1168pub fn nll(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, ids: &[u32], from: usize, pool: Option<&Pool>) -> Option<(f64, usize)> {
1169    if ids.len() < 2 || std::env::var("CMF_INKLING_BATCH").as_deref() == Ok("0") {
1170        return None;
1171    }
1172    let n = ids.len() - 1;
1173    let t0 = std::time::Instant::now();
1174    state.reset(cfg.slots());
1175    let (mut nll, mut cnt) = (0f64, 0usize);
1176    let vocab = globals.lm_head.rows();
1177    // rows a card call scores (`CMF_INKLING_NLL_ROWS`): 16 keeps every call on
1178    // the arms' decode path, more takes CUDA's prompt path
1179    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);
1180    let mut card = None;
1181    let mut p0 = 0usize;
1182    while p0 < n {
1183        let take = if card != Some(false) { card_rows } else { chunk_rows() }.min(n - p0);
1184        let part = &ids[p0..p0 + take];
1185        let mut lg = Vec::new();
1186        if card != Some(false) {
1187            let ok = on_card(globals, layers, cfg, state, part, p0, true, true, &mut lg, pool);
1188            card = Some(ok);
1189        }
1190        if card == Some(false) {
1191            let x = host_rows(globals, layers, cfg, state, part, p0, pool);
1192            state.pos = p0 + part.len();
1193            lg = head_rows(globals, cfg, &x, part.len(), pool);
1194        }
1195        for (j, row) in lg.chunks(vocab).enumerate() {
1196            let p = p0 + j;
1197            if p < from {
1198                continue;
1199            }
1200            let target = (ids[p + 1] as usize).min(vocab - 1);
1201            let best = row.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v)) as f64;
1202            let den: f64 = row.iter().map(|&v| ((v as f64) - best).exp()).sum();
1203            nll += den.ln() - (row[target] as f64 - best);
1204            cnt += 1;
1205        }
1206        p0 += take;
1207    }
1208    state.reset(cfg.slots());
1209    tracing::info!("inkling2_loop nll: {n} rows on the {} in {:.1} s", if card == Some(true) { "card" } else { "host" }, t0.elapsed().as_secs_f64());
1210    Some((nll, cnt))
1211}
1212
1213/// One token; the logits when asked.
1214#[allow(clippy::too_many_arguments)]
1215pub 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) {
1216    if position == 0 || state.pos != position {
1217        if position != 0 && state.pos != position {
1218            tracing::warn!("inkling2_loop: position {position} after {}; the sequence restarts", state.pos);
1219        }
1220        state.reset(cfg.slots());
1221    }
1222    if on_card(globals, layers, cfg, state, &[token_id], position, want_logits, false, logits, pool) {
1223        return;
1224    }
1225    host_catch_up(globals, layers, cfg, state, position, pool);
1226    state.tokens.push(token_id);
1227    let x = host_rows(globals, layers, cfg, state, &[token_id], position, pool);
1228    state.pos = position + 1;
1229    if want_logits {
1230        *logits = head_rows(globals, cfg, &x, 1, pool);
1231    }
1232}
1233
1234/// `CMF_INKLING_SPEC`: unset or `auto` lets [`SpecPolicy`] pick each round's
1235/// drafts (`usize::MAX` here), 0 is plain decoding, a number pins the drafts a
1236/// round offers (the block's 7 at most).
1237pub fn spec_k() -> usize {
1238    static K: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1239    *K.get_or_init(|| std::env::var("CMF_INKLING_SPEC").ok().and_then(|v| v.parse::<usize>().ok()).unwrap_or(usize::MAX))
1240}
1241
1242/// A verify of `k` drafts against a plain token, NVIDIA L4 (calls of 1..8
1243/// rows: 18.4, 23.1, 25.8, 28.4, 30.7, 32.8, 34.9, 36.9 ms): the price of a
1244/// depth no round has timed yet, scaled from the nearest timed one.
1245const SPEC_REL: [f32; 8] = [1.0, 1.26, 1.40, 1.54, 1.67, 1.78, 1.90, 2.0];
1246
1247/// How often draft `j` holds once the one before it held, before a round has
1248/// shown it (DSpark's own figures for Inkling 2: a half to two thirds of
1249/// drafts kept on prose and chat).
1250const SPEC_HOLD_PRIOR: [f32; 7] = [0.70, 0.65, 0.62, 0.60, 0.58, 0.56, 0.55];
1251
1252/// A round of `k` drafts against a plain token on the Apple M4 (the draft
1253/// included): a verify's rows cost far more there (the experts' unpacking).
1254const SPEC_REL_GATE: [f32; 8] = [1.0, 1.6, 1.95, 2.3, 2.6, 2.9, 3.2, 3.5];
1255
1256/// Drafts a gated round asks for (it verifies the ones that pay).
1257const GATE_DRAFTS: usize = 3;
1258
1259/// The DSpark depth that lands the most tokens per millisecond: every round
1260/// and plain token is timed from one decode step to the next (the
1261/// pipeline's own work included), a depth's price is its running average
1262/// (one never timed is scaled from the nearest timed one by [`SPEC_REL`]),
1263/// and how often each draft holds is a running average too. 0 drafts, plain
1264/// decoding, is a depth like the others; while it wins, a round of 2 every
1265/// 32 tokens keeps the holds current.
1266#[derive(Clone, Debug)]
1267pub struct SpecPolicy {
1268    hold: [f32; 7],
1269    wall: [f32; 8],
1270    seen: [u8; 8],
1271    k: usize,
1272    dwell: u8,
1273    plain_run: u16,
1274    picked: Option<std::time::Instant>,
1275    last: Option<(std::time::Instant, usize, usize, usize)>,
1276    /// Drafts that carry their probabilities (Metal): a round verifies as many
1277    /// as pay by them, and rounds that lose to plain decoding send the policy
1278    /// to plain steps for a while (`cool` steps; Strata's realized-gain gate).
1279    gate: bool,
1280    cool: u16,
1281    cool_len: u16,
1282    gain: f32,
1283    /// The drafts the round just taken verified, and whether its draft went
1284    /// unused (that step is not timed).
1285    verified: Option<usize>,
1286    wasted: bool,
1287    t_draft: f32,
1288    /// How often a reached draft holds by the probability the drafter claimed
1289    /// for it (`CAL_EDGES` buckets): its claims run high (0.8 claimed, 0.7
1290    /// held on code; 0.63, 0.48 on prose).
1291    cal: [f32; 5],
1292}
1293
1294/// The claimed-probability buckets' upper edges of [`SpecPolicy::cal`].
1295const CAL_EDGES: [f32; 4] = [0.4, 0.6, 0.8, 0.95];
1296
1297fn cal_bucket(p: f32) -> usize {
1298    CAL_EDGES.iter().take_while(|&&e| p >= e).count()
1299}
1300
1301impl Default for SpecPolicy {
1302    fn default() -> Self {
1303        Self {
1304            hold: SPEC_HOLD_PRIOR,
1305            wall: [0.0; 8],
1306            seen: [0; 8],
1307            k: 3,
1308            dwell: 0,
1309            plain_run: 0,
1310            picked: None,
1311            last: None,
1312            gate: false,
1313            cool: 0,
1314            cool_len: 8,
1315            gain: 1.0,
1316            verified: None,
1317            wasted: false,
1318            t_draft: 0.0,
1319            cal: [0.15, 0.4, 0.5, 0.65, 0.85],
1320        }
1321    }
1322}
1323
1324impl SpecPolicy {
1325    /// The drafts for the step at `pos` (`room`: tokens the request still
1326    /// allows past the anchor). Times the previous step when it ended here.
1327    pub fn pick(&mut self, pos: usize, room: usize) -> usize {
1328        let now = std::time::Instant::now();
1329        self.picked = Some(now);
1330        if let Some((t, k, at, accepted)) = self.last.take() {
1331            if at == pos {
1332                let w = now.duration_since(t).as_secs_f32() * 1e3;
1333                // a depth's first step builds its call's graph and is not counted
1334                match self.seen[k] {
1335                    0 => self.seen[k] = 1,
1336                    1 => (self.wall[k], self.seen[k]) = (w, 2),
1337                    _ if w < self.wall[k] * 4.0 => self.wall[k] += 0.2 * (w - self.wall[k]),
1338                    _ => {}
1339                }
1340                if self.gate && k > 0 && self.seen[0] >= 2 {
1341                    self.realized((1 + accepted) as f32 * self.wall[0] / w);
1342                }
1343            }
1344        }
1345        let pinned = spec_k();
1346        if self.gate && pinned == usize::MAX {
1347            if self.cool > 0 {
1348                self.cool -= 1;
1349                return 0;
1350            }
1351            // plain decoding timed for itself before rounds are weighed against it
1352            if self.seen[0] < 2 {
1353                return 0;
1354            }
1355            return GATE_DRAFTS.min(room);
1356        }
1357        let k = if pinned != usize::MAX {
1358            pinned.min(7)
1359        } else {
1360            self.plan()
1361        };
1362        let k = if k == 0 && self.plain_run >= 32 { 2 } else { k };
1363        k.min(room)
1364    }
1365
1366    /// Record the step just taken at `pos`: `k` drafts offered, `accepted`
1367    /// kept (0 and 0 for a plain token).
1368    pub fn done(&mut self, pos: usize, k: usize, accepted: usize) {
1369        if std::mem::take(&mut self.wasted) {
1370            // a draft no row was verified for: its step is not a plain one's price
1371            self.picked = None;
1372            self.last = None;
1373            return;
1374        }
1375        // a round that did not run (k 0) leaves no verified drafts behind
1376        let verified = self.verified.take();
1377        let k = if self.gate && k > 0 { verified.unwrap_or(k) } else { k }.min(7);
1378        self.last = self.picked.take().map(|t| (t, k, pos + 1 + accepted, accepted));
1379        if k == 0 {
1380            self.plain_run = self.plain_run.saturating_add(1);
1381            return;
1382        }
1383        self.plain_run = 0;
1384        for j in 1..=k {
1385            if accepted + 1 >= j {
1386                let hit = if accepted >= j { 1.0 } else { 0.0 };
1387                self.hold[j - 1] += 0.1 * (hit - self.hold[j - 1]);
1388            }
1389        }
1390        // text this predictable is worth a deeper round now and then
1391        if k < 7 && self.hold[k - 1] >= 0.9 {
1392            for j in k + 1..=7 {
1393                self.hold[j - 1] += 0.02 * (self.hold[k - 1] - self.hold[j - 1]);
1394            }
1395        }
1396    }
1397
1398    /// The step after a reset or a new request is not timed against the last one.
1399    pub fn forget_step(&mut self) {
1400        self.last = None;
1401        self.picked = None;
1402    }
1403
1404    fn price(&self, k: usize) -> Option<f32> {
1405        if self.seen[k] >= 2 {
1406            return Some(self.wall[k]);
1407        }
1408        let rel = if self.gate { &SPEC_REL_GATE } else { &SPEC_REL };
1409        let near = (0..8usize).filter(|&j| self.seen[j] >= 2).min_by_key(|&j| j.abs_diff(k))?;
1410        Some(self.wall[near] * rel[k] / rel[near])
1411    }
1412
1413    /// A gated round's outcome: every draft it reached held or not at the
1414    /// probability claimed for it.
1415    pub fn calibrate(&mut self, p: &[f32], verified: usize, accepted: usize) {
1416        for (j, &pj) in p.iter().enumerate().take(verified.min(accepted + 1)) {
1417            let b = cal_bucket(pj);
1418            let hit = if j < accepted { 1.0 } else { 0.0 };
1419            self.cal[b] += 0.05 * (hit - self.cal[b]);
1420        }
1421    }
1422
1423    /// A round's realized gain (its tokens against plain steps of the same
1424    /// time): a run of losing rounds sends the policy to plain steps, 8 at
1425    /// first and up to 16 while they keep losing.
1426    fn realized(&mut self, r: f32) {
1427        self.gain = 0.72 * self.gain + 0.28 * r;
1428        if r >= 1.05 {
1429            self.gain = self.gain.max(1.14);
1430            self.cool_len = 8;
1431        } else if self.gain < 0.90 {
1432            self.cool = self.cool_len;
1433            self.cool_len = (self.cool_len + 4).min(16);
1434            self.gain = 0.96;
1435        }
1436    }
1437
1438    /// The drafts of a gated round worth verifying by their probabilities
1439    /// (`p[j]` the drafter's for draft j): the count whose expected tokens
1440    /// beyond the anchor, at a plain step's price, most exceed what verifying
1441    /// them adds; 0 when none does. `t_draft` the draft's time (ms).
1442    fn keep(&mut self, p: &[f32], t_draft: f32) -> usize {
1443        self.gate = true;
1444        self.t_draft += if self.t_draft == 0.0 { t_draft } else { 0.2 * (t_draft - self.t_draft) };
1445        if spec_k() != usize::MAX {
1446            return p.len();
1447        }
1448        let Some(w0) = self.price(0).filter(|_| self.seen[0] >= 2) else { return p.len() };
1449        let (mut best, mut gain) = (0usize, 0f32);
1450        let (mut reach, mut extra) = (1f32, 0f32);
1451        for m in 1..=p.len().min(7) {
1452            reach *= self.cal[cal_bucket(p[m - 1])];
1453            extra += reach;
1454            let Some(pm) = self.price(m) else { break };
1455            let net = extra * w0 - (pm - self.t_draft - w0);
1456            if net > gain {
1457                (best, gain) = (m, net);
1458            }
1459        }
1460        if best == 0 {
1461            self.wasted = true;
1462            self.realized(w0 / (w0 + self.t_draft));
1463        } else {
1464            self.verified = Some(best);
1465        }
1466        best
1467    }
1468
1469    fn plan(&mut self) -> usize {
1470        // plain decoding timed for itself once the depth in use is: its price
1471        // is not scaled from a verify's (the card's one-row path is its own)
1472        if self.seen[0] < 2 && self.seen[self.k] >= 2 {
1473            return 0;
1474        }
1475        let mut rate = [0f32; 8];
1476        let (mut tokens, mut reach) = (1.0f32, 1.0f32);
1477        for k in 0..8usize {
1478            if k > 0 {
1479                reach *= self.hold[k - 1];
1480                tokens += reach;
1481            }
1482            match self.price(k) {
1483                Some(p) if p > 0.0 => rate[k] = tokens / p,
1484                // nothing timed yet: stay
1485                _ => return self.k,
1486            }
1487        }
1488        if self.dwell > 0 {
1489            self.dwell -= 1;
1490            return self.k;
1491        }
1492        let best = (0..8usize).max_by(|&a, &b| rate[a].total_cmp(&rate[b])).unwrap_or(self.k);
1493        if best != self.k && rate[best] > rate[self.k] * 1.04 {
1494            if std::env::var("CMF_INKLING_SPEC_TIME").is_ok() {
1495                eprintln!("dspark: {} → {best} drafts (a step costs {:.1?} ms, a draft holds {:.2?})", self.k, self.wall, self.hold);
1496            }
1497            self.k = best;
1498            self.dwell = 6;
1499        }
1500        self.k
1501    }
1502}
1503
1504/// One DSpark round at the decode tip, on the card: `anchor` (the token the
1505/// sampler took for `pos`) and up to `k` drafts through the target in one
1506/// call; the drafts it agrees with (its greedy picks) are kept, the rest rolled
1507/// back. Returns the accepted drafts and leaves `logits` the last kept row's;
1508/// `None` when no round ran (no drafter, not on the card, a refusal): nothing
1509/// changed and the caller forwards the anchor itself. A card that lets go in
1510/// the round hands the sequence to the host first (`card_dropped`), so that
1511/// forward runs on caches that hold the sequence.
1512#[allow(clippy::too_many_arguments)]
1513pub fn spec_round(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, anchor: u32, pos: usize, k: usize, logits: &mut Vec<f32>, pool: Option<&Pool>) -> Option<Vec<u32>> {
1514    globals.draft.as_ref()?;
1515    if k == 0 || state.card != Some(true) || state.pos != pos || pos == 0 {
1516        return None;
1517    }
1518    let timed = std::env::var("CMF_INKLING_SPEC_TIME").is_ok();
1519    let t0 = std::time::Instant::now();
1520    let (mut drafts, probs) = crate::gpu::inkling_draft(state.sequence_id, globals, cfg, anchor, pos, k)?;
1521    if !probs.is_empty() {
1522        // drafts with their probabilities (Metal): verify the ones that pay
1523        let m = state.spec.keep(&probs, t0.elapsed().as_secs_f32() * 1e3);
1524        if m == 0 {
1525            return None;
1526        }
1527        drafts.truncate(m);
1528    }
1529    // `CMF_INKLING_SPEC_JUNK=1` (a check): drafts the model never keeps, so every
1530    // round rolls all of them back — the text must stay plain decoding's
1531    if std::env::var("CMF_INKLING_SPEC_JUNK").as_deref() == Ok("1") {
1532        drafts.iter_mut().for_each(|d| *d = 1);
1533    }
1534    if drafts.is_empty() || !crate::gpu::inkling_ring_snap(state.sequence_id) {
1535        return None;
1536    }
1537    let t1 = std::time::Instant::now();
1538    let mut ids = Vec::with_capacity(drafts.len() + 1);
1539    ids.push(anchor);
1540    ids.extend_from_slice(&drafts);
1541    // each row's greedy pick on the card; only the kept row's logits come over
1542    let mut picks = Vec::with_capacity(ids.len());
1543    if !crate::gpu::inkling_verify(state.sequence_id, globals, layers, cfg, &ids, pos, &mut picks) || picks.len() != ids.len() {
1544        // the card let go mid-round: the host replays the sequence before the round
1545        card_dropped(globals, layers, cfg, state, pos, pool);
1546        return None;
1547    }
1548    let vocab = globals.lm_head.rows();
1549    let mut acc = 0usize;
1550    while acc < drafts.len() && picks[acc] == drafts[acc] {
1551        acc += 1;
1552    }
1553    if !probs.is_empty() {
1554        state.spec.calibrate(&probs, drafts.len(), acc);
1555    }
1556    if timed && !probs.is_empty() {
1557        // the drafter's calibration: the probability a reached draft claimed
1558        // against how often it held, by position
1559        static C: std::sync::Mutex<([f64; 8], [f64; 8], [u32; 8], u32)> = std::sync::Mutex::new(([0.0; 8], [0.0; 8], [0; 8], 0));
1560        let mut c = C.lock().unwrap();
1561        for j in 0..drafts.len().min(8) {
1562            if j > acc {
1563                break;
1564            }
1565            c.0[j] += probs[j] as f64;
1566            c.1[j] += (j < acc) as u32 as f64;
1567            c.2[j] += 1;
1568        }
1569        c.3 += 1;
1570        if c.3 % 64 == 0 {
1571            let row: Vec<String> = (0..4).filter(|&j| c.2[j] > 0).map(|j| format!("d{}: p {:.2} held {:.2} (n {})", j + 1, c.0[j] / c.2[j] as f64, c.1[j] / c.2[j] as f64, c.2[j])).collect();
1572            eprintln!("dspark calibration: {}", row.join(", "));
1573        }
1574    }
1575    let keep = acc + 1;
1576    if keep < ids.len() && !crate::gpu::inkling_ring_back(state.sequence_id, keep) {
1577        card_dropped(globals, layers, cfg, state, pos, pool);
1578        return None;
1579    }
1580    if !crate::gpu::inkling_row_logits(state.sequence_id, acc, vocab, logits) {
1581        card_dropped(globals, layers, cfg, state, pos, pool);
1582        return None;
1583    }
1584    state.tokens.extend_from_slice(&ids[..keep]);
1585    state.pos = pos + keep;
1586    if timed {
1587        static T: std::sync::Mutex<(f64, f64, f64, u32)> = std::sync::Mutex::new((0.0, 0.0, 0.0, 0));
1588        let mut t = T.lock().unwrap();
1589        t.0 += (t1 - t0).as_secs_f64() * 1e3;
1590        t.1 += t1.elapsed().as_secs_f64() * 1e3;
1591        t.2 += (drafts.len() + 1) as f64;
1592        t.3 += 1;
1593        if t.3 % 64 == 0 {
1594            let n = t.3 as f64;
1595            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);
1596        }
1597    }
1598    Some(drafts[..acc].to_vec())
1599}
1600
1601#[cfg(test)]
1602mod tests {
1603    use super::*;
1604
1605    fn cfg() -> Cfg {
1606        Cfg {
1607            dim: 4,
1608            layers: 24,
1609            nh: 2,
1610            nkv: 1,
1611            hd: 2,
1612            d_rel: 2,
1613            eps: 1e-6,
1614            window: 4,
1615            rel_extent: 4,
1616            qk_clip: 22.6,
1617            rel_clip: 8.0,
1618            log_alpha: 0.1,
1619            log_floor: 8192.0,
1620            block: 6,
1621            core_start: 6,
1622            core_end: 18,
1623            passes: 3,
1624            top_k: 2,
1625            route_scale: 8.0,
1626            gate_cap: 4.0,
1627            up_cap: 25.0,
1628            logit_cap: 30.0,
1629            max_seq: 64,
1630        }
1631    }
1632
1633    #[test]
1634    fn the_plan_visits_the_core_three_times_with_its_own_slots() {
1635        let c = cfg();
1636        let plan = c.plan();
1637        assert_eq!(plan.len(), 48);
1638        assert_eq!(c.slots(), 48);
1639        assert_eq!(plan[6], (6, 0));
1640        assert_eq!(plan[18], (6, 1));
1641        assert_eq!(plan[30], (6, 2));
1642        assert_eq!(plan[42], (18, 0));
1643        assert_eq!(c.slot(6, 1), 24);
1644        assert_eq!(c.slot(17, 2), 47);
1645        let mut slots: Vec<usize> = plan.iter().map(|&(l, p)| c.slot(l, p)).collect();
1646        slots.sort();
1647        slots.dedup();
1648        assert_eq!(slots.len(), 48);
1649    }
1650
1651    #[test]
1652    fn the_dspark_depth_follows_the_holds_and_the_prices() {
1653        // L4 prices: a plain token 18.4 ms, a verify of k drafts by SPEC_REL
1654        let timed = |hold: [f32; 7]| {
1655            let mut p = SpecPolicy { hold, ..SpecPolicy::default() };
1656            for k in 0..8 {
1657                p.wall[k] = 18.4 * SPEC_REL[k] + if k > 0 { 2.0 } else { 0.0 };
1658                p.seen[k] = 2;
1659            }
1660            p.plan()
1661        };
1662        // text that holds: a deep round
1663        assert!(timed([0.95; 7]) >= 6);
1664        // drafts that rarely hold: plain decoding
1665        assert_eq!(timed([0.15; 7]), 0);
1666        // chat-like holds: a short round
1667        let k = timed([0.7, 0.65, 0.6, 0.55, 0.5, 0.5, 0.5]);
1668        assert!((1..=4).contains(&k), "{k}");
1669        // nothing timed yet: the starting depth
1670        assert_eq!(SpecPolicy::default().plan(), 3);
1671        // one timed depth prices the rest from SPEC_REL
1672        let mut p = SpecPolicy::default();
1673        p.wall[3] = 28.4;
1674        p.seen[3] = 2;
1675        assert!((p.price(0).unwrap() - 28.4 / 1.54).abs() < 1e-3);
1676        // with the depth in use timed, plain decoding is timed for itself next
1677        assert_eq!(p.plan(), 0);
1678        assert_eq!(p.k, 3);
1679    }
1680
1681    #[test]
1682    fn a_varloop_plan_runs_the_core_any_number_of_times() {
1683        for passes in [1usize, 2, 5] {
1684            let c = Cfg { passes, ..cfg() };
1685            let plan = c.plan();
1686            assert_eq!(plan.len(), 12 + 12 * passes);
1687            assert_eq!(c.slots(), 24 + 12 * (passes - 1));
1688            assert_eq!(plan.last(), Some(&(23, 0)));
1689            let mut slots: Vec<usize> = plan.iter().map(|&(l, p)| c.slot(l, p)).collect();
1690            slots.sort();
1691            slots.dedup();
1692            assert_eq!(slots.len(), c.slots());
1693            assert_eq!(slots.last(), Some(&(c.slots() - 1)));
1694        }
1695    }
1696
1697    #[test]
1698    fn the_host_knows_when_its_caches_miss_the_sequence() {
1699        // a card ran 3 073 positions, then let go without a replay: the host's
1700        // slots are a reset's, its tokens the sequence's (0.9.15 then read
1701        // row 3 073 of a one-row cache at inkling.rs:791 and panicked)
1702        let c = cfg();
1703        let row = c.nkv * c.hd;
1704        let mut st = State { pos: 3073, tokens: vec![7; 3073], slots: (0..c.slots()).map(|_| SlotState::default()).collect(), sequence_id: 0, card: Some(false), spec: SpecPolicy::default() };
1705        assert_eq!(host_holds(&st, &c), 0);
1706        assert!(host_behind(&st, &c, 3073));
1707        // a host that ran the sequence: a sliding slot keeps its last window,
1708        // the rows it dropped counted in its base
1709        let s = &mut st.slots[c.slot(0, 0)];
1710        s.base = 3073 - c.window;
1711        s.k = vec![0.0; c.window * row];
1712        assert_eq!(host_holds(&st, &c), 3073);
1713        assert!(!host_behind(&st, &c, 3073));
1714        // tokens that do not reach the position: no replay could bring the host there
1715        st.tokens.truncate(100);
1716        st.slots = (0..c.slots()).map(|_| SlotState::default()).collect();
1717        assert!(!host_behind(&st, &c, 3073));
1718        // a sequence's start: nothing to hold
1719        let fresh = State { pos: 0, tokens: Vec::new(), slots: Vec::new(), sequence_id: 0, card: None, spec: SpecPolicy::default() };
1720        assert!(!host_behind(&fresh, &c, 0));
1721    }
1722
1723    #[test]
1724    fn tau_is_one_below_the_floor() {
1725        assert_eq!(tau(0, 0.1, 8192.0), 1.0);
1726        assert_eq!(tau(8191, 0.1, 8192.0), 1.0);
1727        assert!((tau(16383, 0.1, 8192.0) - (1.0 + 0.1 * 2f32.ln())).abs() < 1e-6);
1728    }
1729
1730    #[test]
1731    fn the_mixture_of_equal_states_is_that_state_normed() {
1732        let s = [1.0f32, 2.0, 3.0, 4.0];
1733        let m = mix(&[&s, &s], &[0.3, -0.2, 0.1, 0.5], 4);
1734        let n = unit_rms(&s, 1e-6);
1735        for (a, b) in m[0].iter().zip(&n) {
1736            assert!((a - b).abs() < 1e-6);
1737        }
1738    }
1739
1740    #[test]
1741    fn a_static_conv_keeps_its_ring_newest_first() {
1742        // one channel, taps [current 1, lag1 0.5, lag2 0.25, lag3 0]
1743        let c = Conv { taps: vec![1.0, 0.5, 0.25, 0.0], channels: 1, kernel: 4, proj: None, groups: 1 };
1744        let mut ring = Vec::new();
1745        let s5 = 5f32.sqrt();
1746        let y0 = c.step_with(&[2.0], &mut ring, None);
1747        assert!((y0[0] - (2.0 + 2.0) / s5).abs() < 1e-6);
1748        let y1 = c.step_with(&[4.0], &mut ring, None);
1749        assert!((y1[0] - (4.0 + 4.0 + 1.0) / s5).abs() < 1e-6);
1750        let y2 = c.step_with(&[8.0], &mut ring, None);
1751        assert!((y2[0] - (8.0 + 8.0 + 2.0 + 0.5) / s5).abs() < 1e-6);
1752        assert_eq!(ring, vec![8.0, 4.0, 2.0]);
1753    }
1754
1755    #[test]
1756    fn the_router_picks_by_the_biased_score_and_weighs_by_the_plain_one() {
1757        let r = route_logits(&[0.0, 2.0, -1.0], &[0.9, 0.0, 0.0], 2);
1758        assert_eq!(r[0].0, 0);
1759        assert_eq!(r[1].0, 1);
1760        let (s0, s1) = (0.5f32, sigmoid(2.0));
1761        assert!((r[0].1 - s0 / (s0 + s1)).abs() < 1e-6);
1762    }
1763}