Skip to main content

cortiq_engine/
pipeline.rs

1//! Full inference pipeline: tokenize → embed → layers → lm_head → sample → decode.
2//!
3//! Prefill/decode contract: every token is forwarded exactly once and
4//! enters the KV cache exactly once. Logits for the next token are
5//! computed from the hidden state of the LAST forwarded token — the
6//! decode loop forwards the freshly sampled token, never re-embeds the
7//! prompt tail (v1 duplicated the last prompt token in the cache).
8
9use crate::attention::{self, QwenAttnCfg};
10use crate::inference;
11use crate::kv_cache::KvCache;
12use crate::linear_core::{
13    gdn_forward, gdn_pair, vmf_phase_forward, vmf_phase_pair, GdnCfg, GdnWeights, VmfPhaseCfg,
14    VmfPhaseWeights,
15};
16use crate::pool::Pool;
17use crate::qtensor::QTensor;
18use crate::sampler::{self, SamplerConfig, SplitMix64};
19use crate::tokenizer::Tokenizer;
20use cortiq_core::mask::TaskMask;
21use cortiq_core::types::NormStyle;
22
23/// Complete inference pipeline state.
24pub struct Pipeline {
25    pub tokenizer: Tokenizer,
26    pub kv_cache: KvCache,
27    pub sampler_config: SamplerConfig,
28    pub weights: PipelineWeights,
29    pub hidden_size: usize,
30    pub intermediate_size: usize,
31    pub num_heads: usize,
32    pub num_kv_heads: usize,
33    pub head_dim: usize,
34    pub num_layers: usize,
35    pub vocab_size: usize,
36    pub rms_eps: f64,
37    pub rope_base: f32,
38    pub norm_style: NormStyle,
39    /// RoPE dims actually rotated (≤ head_dim; Qwen3.5 uses head_dim/4).
40    pub rotary_dim: usize,
41    /// Linear-core geometry (present when the model has linear layers).
42    pub vmf_cfg: Option<VmfPhaseCfg>,
43    /// GatedDeltaNet geometry (faithful vendor operator).
44    pub gdn_cfg: Option<GdnCfg>,
45    /// Multi-token-prediction head (None = absent).
46    pub mtp: Option<MtpModule>,
47    /// Speculative decode via MTP (greedy only; `CMF_MTP=0` disables).
48    pub speculative: bool,
49    rng: SplitMix64,
50    /// Precomputed RoPE inverse frequencies [head_dim/2].
51    inv_freq: Vec<f32>,
52    /// Persistent worker pool (None = serial; see CMF_THREADS).
53    pool: Option<std::sync::Arc<Pool>>,
54    // ── Dynamic per-token skill routing (spec §9, claim 14/16) ──
55    /// Source model, retained so a skill switch can re-resolve the
56    /// touched layers' FFN tensors (Mapped = mmap pointers, cheap).
57    pub(crate) model: Option<std::sync::Arc<cortiq_core::CmfModel>>,
58    /// Masks present → weights are dequantized f32 (rebuild path).
59    pub(crate) dyn_force_f32: bool,
60    /// Per-skill FFN layers actually replaced (derived from tensors, not
61    /// the meta `layers` field — ru2 replaces down_proj in 0..23 while
62    /// its meta says [20..23]). None = skill touches non-FFN tensors →
63    /// ineligible for cheap dynamic switching (honest refusal).
64    pub(crate) dyn_skill_layers: Vec<Option<Vec<usize>>>,
65    /// Currently overlaid skill (index into model.header.skills); None =
66    /// backbone. Set at load time to the statically-overlaid skill so
67    /// `set_active_skill(None)` correctly reverts it (else a static
68    /// skill would silently persist — the union-diff assumes dyn_active
69    /// always mirrors the live overlay). Switched by `set_active_skill`.
70    pub(crate) dyn_active: Option<usize>,
71    /// Pipeline was loaded with a soft blend (materialized working
72    /// tensors, not a single skill index) → dynamic routing refuses:
73    /// there is no single index to revert the blend from.
74    pub(crate) dyn_blend_loaded: bool,
75    /// Layer whose post-residual hidden feeds the router φ (shared by
76    /// swarm skills). None = φ capture off.
77    pub(crate) dyn_phi_layer: Option<usize>,
78    /// EMA of φ at `dyn_phi_layer` over the decode window (on-policy).
79    dyn_phi_ema: Vec<f32>,
80    dyn_phi_seen: usize,
81    /// Hysteresis router driving per-token skill switches during decode
82    /// (None = static/no dynamic routing). Taken out during generation.
83    pub dyn_router: Option<crate::swarm::DynRouter>,
84    /// O(1) Nyström attention setting (CLI/env/header-hint resolved by
85    /// the caller; None = plain cache attention everywhere).
86    o1_cfg: Option<crate::nystrom::O1Cfg>,
87    /// Per-layer o1 flags derived from `o1_cfg` (Full layers only).
88    o1_flags: Vec<bool>,
89    /// Emit a structured per-token trace (B4 telemetry channel). Off by
90    /// default — the runtime is silent unless observation is requested.
91    trace: bool,
92    /// Confidence-calibration temperature (B1): reported Born mass is
93    /// softmax(logits / calib_temp). 1.0 = raw. Set from header.calibration.
94    calib_temp: f32,
95}
96
97/// Model weights. Matrices are `QTensor` (owned f32 for small models
98/// and tests — bit-identical to the historical paths — or quantized
99/// bytes zero-copy from the CMF mmap for big models). 1-D norms are
100/// always small and stay f32.
101pub struct PipelineWeights {
102    /// Embedding table: [vocab_size, hidden_size]
103    pub embed_tokens: QTensor,
104    /// Per-layer weights
105    pub layers: Vec<LayerWeights>,
106    /// LM head: [vocab_size, hidden_size]
107    pub lm_head: QTensor,
108    /// Final norm: [hidden_size]
109    pub final_norm: Vec<f32>,
110}
111
112/// One transformer layer: shared norms + MLP, attention by kind.
113pub struct LayerWeights {
114    pub input_norm: Vec<f32>,
115    pub post_norm: Vec<f32>,
116    pub ffn: FfnKind,
117    pub attn: AttnKind,
118}
119
120/// Dense SwiGLU triple — the FFN of a dense layer or of one expert.
121pub struct DenseFfn {
122    pub gate_proj: QTensor,
123    pub up_proj: QTensor,
124    pub down_proj: QTensor,
125}
126
127/// FFN operator of a layer, decided by tensor presence at load time
128/// (router `mlp.gate.weight` in the directory = MoE layer).
129pub enum FfnKind {
130    Dense(DenseFfn),
131    /// Mixture-of-Experts (Qwen2-MoE / Qwen3-MoE): softmax over ALL
132    /// expert logits → top-k, optional renorm; experts stay quantized
133    /// in mmap — only the selected ones are touched per token.
134    Moe(MoeFfn),
135}
136
137pub struct MoeFfn {
138    /// Router `mlp.gate.weight` [num_experts, hidden].
139    pub router: QTensor,
140    pub experts: Vec<DenseFfn>,
141    pub top_k: usize,
142    pub norm_topk_prob: bool,
143    /// Qwen2-MoE always-on shared expert: (FFN, sigmoid-gate [1, hidden]).
144    pub shared: Option<(DenseFfn, QTensor)>,
145    /// Expert-selection counters (truncated Fisher B-field of claim 12:
146    /// routing frequency during calibration). Filled by every forward,
147    /// read by the CLI via CMF_MOE_STATS. RefCell: decode is single-threaded.
148    pub stats: std::cell::RefCell<Vec<u64>>,
149}
150
151/// Attention operator of a layer. Extension point: new operators are
152/// new variants here + a forward in their own module.
153pub enum AttnKind {
154    /// GQA softmax attention (+ optional Qwen3.5 qk-norm / output gate).
155    Full {
156        wq: QTensor,
157        wk: QTensor,
158        wv: QTensor,
159        wo: QTensor,
160        q_norm: Option<Vec<f32>>,
161        k_norm: Option<Vec<f32>>,
162        output_gate: bool,
163        /// Qwen2-family projection biases (q, k, v).
164        bias: Option<(Vec<f32>, Vec<f32>, Vec<f32>)>,
165    },
166    /// Canonical linear core (VMF phase attention).
167    Linear(VmfPhaseWeights),
168    /// Faithful vendor linear operator (Qwen3.5 GatedDeltaNet).
169    LinearGdn(GdnWeights),
170}
171
172/// Multi-token-prediction head (DeepSeek/Qwen style, spec §2.1):
173/// `x = eh_proj·[enorm(embed(next)); hnorm(hidden)]` → one transformer
174/// block over its own KV → shared lm_head. Drafts the token after next;
175/// the main model verifies, so output is exact — MTP only buys speed.
176pub struct MtpModule {
177    pub enorm: Vec<f32>,
178    pub hnorm: Vec<f32>,
179    /// [hidden, 2·hidden]
180    pub eh_proj: QTensor,
181    pub layer: LayerWeights,
182    pub final_norm: Vec<f32>,
183    pub kv: crate::kv_cache::LayerKvCache,
184}
185
186/// Result of a generation call.
187pub struct GenerateResult {
188    pub text: String,
189    pub token_ids: Vec<u32>,
190    pub prompt_tokens: usize,
191    pub tokens_generated: usize,
192    pub finish_reason: String,
193    /// Speculative-decode stats (0/0 when MTP is absent or inactive).
194    pub mtp_drafted: usize,
195    pub mtp_accepted: usize,
196    /// Per-generated-token confidence = softmax probability of the token
197    /// that was actually emitted (Born mass on the chosen state). High =
198    /// the model was sure; low = it was guessing. Same length as the
199    /// generated slice of `token_ids`.
200    pub token_confidence: Vec<f32>,
201    /// Structured per-token telemetry (B4 channel). Empty unless
202    /// `set_trace(true)`; otherwise same length as the generated slice.
203    pub traces: Vec<TokenTrace>,
204}
205
206/// One row of the structured telemetry trace (B4): the model's internal
207/// routing state at the moment a token was emitted. Every field is a
208/// quantity the runtime already computes — nothing is inferred or
209/// estimated (anti-principle: only measured bytes).
210#[derive(Clone, Debug)]
211pub struct TokenTrace {
212    /// 0-based index within the generated slice.
213    pub t: usize,
214    /// The emitted token id.
215    pub token_id: u32,
216    /// Born mass on the emitted token (softmax prob) — how sure the model was.
217    pub confidence: f32,
218    /// Skill in force while this token was generated (None = backbone).
219    pub active_skill: Option<String>,
220    /// Recon error E = ‖r−BBᵀr‖²/‖φ‖² at the last routing eval — coherence
221    /// with the active skill's subspace (low = coherent). None = no router
222    /// or not yet evaluated.
223    pub recon: Option<f32>,
224    /// The router changed the active skill right after this token (a
225    /// domain boundary crossed under the hysteresis barrier).
226    pub switched: bool,
227}
228
229/// Calibrated softmax probability of `id` under `logits` (the Born mass on
230/// the emitted token) — the confidence signal, cheap from logits already
231/// computed for sampling. `temp` is the calibration temperature (B1):
232/// softmax(logits / temp); 1.0 = raw.
233fn top1_prob_t(logits: &[f32], id: u32, temp: f32) -> f32 {
234    let t = if temp > 1e-3 { temp } else { 1.0 };
235    let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
236    let sum: f32 = logits.iter().map(|&v| ((v - max) / t).exp()).sum();
237    if sum > 0.0 {
238        (((logits[id as usize] - max) / t).exp()) / sum
239    } else {
240        0.0
241    }
242}
243
244/// prefill-GEMM enabled? (CMF_PREFILL=seq — emergency fallback to the
245/// sequential path.)
246fn prefill_batched() -> bool {
247    std::env::var("CMF_PREFILL").map(|v| v != "seq").unwrap_or(true)
248}
249
250/// Callback for streaming tokens. Return `false` to cancel.
251pub type TokenCallback = Box<dyn FnMut(&str) -> bool + Send>;
252
253impl Pipeline {
254    /// Build a pipeline from parts (used by the loader and tests).
255    #[allow(clippy::too_many_arguments)]
256    pub fn new(
257        tokenizer: Tokenizer,
258        weights: PipelineWeights,
259        hidden_size: usize,
260        intermediate_size: usize,
261        num_heads: usize,
262        num_kv_heads: usize,
263        head_dim: usize,
264        num_layers: usize,
265        vocab_size: usize,
266        rms_eps: f64,
267        rope_base: f32,
268        norm_style: NormStyle,
269        max_seq_len: usize,
270        sampler_config: SamplerConfig,
271    ) -> Self {
272        let rng = match sampler_config.seed {
273            Some(s) => SplitMix64::new(s),
274            None => SplitMix64::from_entropy(),
275        };
276        let inv_freq = attention::rope_inv_freq(head_dim, rope_base);
277        let pool = Pool::from_env();
278        if let Some(p) = &pool {
279            tracing::info!("worker pool: {} threads", p.n_workers());
280        }
281        Self {
282            tokenizer,
283            kv_cache: KvCache::new(num_layers, num_kv_heads, head_dim, max_seq_len),
284            sampler_config,
285            weights,
286            hidden_size,
287            intermediate_size,
288            num_heads,
289            num_kv_heads,
290            head_dim,
291            num_layers,
292            vocab_size,
293            rms_eps,
294            rope_base,
295            norm_style,
296            rotary_dim: head_dim,
297            vmf_cfg: None,
298            gdn_cfg: None,
299            mtp: None,
300            speculative: std::env::var("CMF_MTP").map(|v| v != "0").unwrap_or(true),
301            rng,
302            inv_freq,
303            pool,
304            model: None,
305            dyn_force_f32: false,
306            dyn_skill_layers: Vec::new(),
307            dyn_active: None,
308            dyn_blend_loaded: false,
309            dyn_phi_layer: None,
310            dyn_phi_ema: Vec::new(),
311            dyn_phi_seen: 0,
312            dyn_router: None,
313            o1_cfg: None,
314            o1_flags: Vec::new(),
315            trace: false,
316            calib_temp: 1.0,
317        }
318    }
319
320    /// Enable/disable per-layer O(1) Nyström attention. Only Full
321    /// layers are eligible (a linear layer keeps its own operator).
322    /// Applies to generation (`generate*`/`forward_ids`): the prompt
323    /// pass stays exact, the seal happens once after prefill, decode
324    /// runs on the O(1) state. Teacher-forced scoring (`ppl_ids`)
325    /// intentionally stays exact.
326    pub fn set_o1(&mut self, cfg: Option<crate::nystrom::O1Cfg>) {
327        self.o1_flags = match &cfg {
328            Some(c) => {
329                let mut flags = c.layer_flags(self.num_layers);
330                for (li, f) in flags.iter_mut().enumerate() {
331                    if *f && !matches!(self.weights.layers[li].attn, AttnKind::Full { .. }) {
332                        *f = false;
333                    }
334                }
335                flags
336            }
337            None => Vec::new(),
338        };
339        if let Some(c) = &cfg {
340            let n = self.o1_flags.iter().filter(|&&f| f).count();
341            tracing::info!(
342                "o1 nystrom attention: {n}/{} layer(s), m={} w={} sink={}",
343                self.num_layers, c.m, c.w, c.sink
344            );
345        }
346        self.o1_cfg = cfg;
347    }
348
349    /// True when at least one layer runs the O(1) kernel.
350    pub fn o1_active(&self) -> bool {
351        self.o1_cfg.is_some() && self.o1_flags.iter().any(|&f| f)
352    }
353
354    /// Arm query collection on the o1 layers (fresh prompt pass).
355    fn o1_begin(&mut self) {
356        if let Some(c) = &self.o1_cfg {
357            let (m, w, sink) = (c.m, c.w, c.sink);
358            for (li, &f) in self.o1_flags.iter().enumerate() {
359                if f {
360                    self.kv_cache.layers[li].o1_begin(m, w, sink);
361                }
362            }
363        }
364    }
365
366    /// Freeze landmarks + skeleton state after the prompt pass and drop
367    /// the o1 layers' full KV; decode then runs `step()` per token.
368    fn o1_seal(&mut self) {
369        if self.o1_cfg.is_none() {
370            return;
371        }
372        for li in 0..self.num_layers {
373            if self.o1_flags.get(li).copied().unwrap_or(false) {
374                self.kv_cache.layers[li].o1_seal(self.num_heads);
375            }
376        }
377    }
378
379    /// Enable/disable the structured per-token telemetry trace (B4).
380    pub fn set_trace(&mut self, on: bool) {
381        self.trace = on;
382    }
383
384    /// Set the confidence-calibration temperature (B1). Values ≤0 are
385    /// clamped to raw (1.0).
386    pub fn set_calib_temp(&mut self, t: f32) {
387        self.calib_temp = if t > 1e-3 { t } else { 1.0 };
388    }
389
390    /// The active calibration temperature (1.0 = raw Born mass).
391    pub fn calib_temp(&self) -> f32 {
392        self.calib_temp
393    }
394
395    /// Partial rotary (Qwen3.5): rotate only the first `rotary_dim` dims;
396    /// the frequency table is rebuilt over the rotary dims.
397    pub fn set_rotary(&mut self, rotary_dim: usize, base: f32) {
398        self.rotary_dim = rotary_dim.min(self.head_dim);
399        self.inv_freq = attention::rope_inv_freq(self.rotary_dim, base);
400    }
401
402    fn attn_cfg(&self, position: usize) -> QwenAttnCfg<'_> {
403        QwenAttnCfg {
404            num_heads: self.num_heads,
405            num_kv_heads: self.num_kv_heads,
406            head_dim: self.head_dim,
407            hidden_size: self.hidden_size,
408            position,
409            inv_freq: &self.inv_freq,
410            rotary_dim: self.rotary_dim,
411            q_norm: None,
412            k_norm: None,
413            output_gate: false,
414            bias: None,
415            rms_eps: self.rms_eps,
416            norm_style: self.norm_style,
417            pool: self.pool.as_deref(),
418        }
419    }
420
421    /// Generate text from a plain-text prompt. Streams tokens via `on_token`.
422    pub fn generate(
423        &mut self,
424        prompt: &str,
425        max_tokens: usize,
426        task_mask: Option<&TaskMask>,
427        on_token: Option<TokenCallback>,
428    ) -> Result<GenerateResult, String> {
429        let input_ids = self.tokenizer.encode(prompt);
430        self.generate_from_ids(&input_ids, max_tokens, task_mask, on_token)
431    }
432
433    /// Generate from prepared token ids (e.g. a chat template).
434    ///
435    /// With an MTP head, greedy generation without a task mask takes the
436    /// speculative path: the MTP module drafts the token after next and
437    /// the main model verifies both in one fused two-position forward
438    /// (weights streamed once). The output is EXACTLY the vanilla greedy
439    /// sequence — a rejected draft is rolled back — MTP only buys speed.
440    pub fn generate_from_ids(
441        &mut self,
442        input_ids: &[u32],
443        max_tokens: usize,
444        task_mask: Option<&TaskMask>,
445        mut on_token: Option<TokenCallback>,
446    ) -> Result<GenerateResult, String> {
447        if input_ids.is_empty() {
448            return Err("empty prompt: nothing to generate from".to_string());
449        }
450
451        // Fresh sequence — the cache holds absolute positions.
452        self.kv_cache.clear();
453        self.o1_begin();
454
455        // Speculative decode is off under o1: a rejected draft can't be
456        // rolled back out of the far accumulators / ring window (the
457        // Nyström insertion is irreversible by design).
458        let spec_active = self.speculative
459            && self.mtp.is_some()
460            && task_mask.is_none()
461            && !self.o1_active()
462            && self.sampler_config.temperature < 1e-6;
463        // The MTP module is detached during generation so its mutable
464        // state does not fight the borrow on `self`.
465        let mut mtp = if spec_active { self.mtp.take() } else { None };
466        if let Some(m) = &mut mtp {
467            m.kv.clear();
468        }
469        // Dynamic router detached during decode (same borrow trick as MTP).
470        // Speculative decode and dynamic routing are mutually exclusive
471        // for now — the fused-pair path doesn't carry per-token φ.
472        let mut router = if mtp.is_none() { self.dyn_router.take() } else { None };
473        if let Some(r) = &mut router {
474            r.reset(); // active=backbone, matching a fresh overlay
475            self.dyn_phi_seen = 0; // fresh φ EMA per generation
476            let _ = self.set_active_skill(None);
477        }
478
479        let mut all_ids = input_ids.to_vec();
480        let mut generated = 0usize;
481        let mut finish_reason = "max_tokens".to_string();
482        let mut drafted = 0usize;
483        let mut accepted = 0usize;
484        let mut confidence: Vec<f32> = Vec::new();
485        let trace_on = self.trace;
486        let calib_temp = self.calib_temp;
487        let mut traces: Vec<TokenTrace> = Vec::new();
488
489        // ── Prefill: forward each prompt token once, KEEP the last hidden.
490        //    Dense prefill runs in fused pairs (weights streamed once per
491        //    two positions — bit-identical to sequential, proven by the
492        //    pair tests). With MTP: warm the draft head on
493        //    (hidden_p, token_{p+1}) pairs.
494        let mut hidden = vec![0.0f32; self.hidden_size];
495        let mut pos = 0usize;
496        // With dynamic routing, prefill sequentially so the φ hook fires
497        // over the PROMPT — the router enters decode with a warm φ (the
498        // fused-pair path skips the per-layer φ capture). o1 layers
499        // collect their query trace in both the single and pair paths.
500        let dyn_prefill = router.is_some();
501        if task_mask.is_none() && !dyn_prefill {
502            while pos + 1 < input_ids.len() {
503                let e1 = self.embed_single(input_ids[pos]);
504                let e2 = self.embed_single(input_ids[pos + 1]);
505                let (h1, h2) = self.forward_pair(&e1, &e2, pos);
506                // Both prefill tokens are real → commit lane-2 states.
507                self.commit_linear_scratch();
508                if let Some(m) = &mut mtp {
509                    let _ = self.mtp_step(m, &h1, input_ids[pos + 1], pos);
510                    if pos + 2 < input_ids.len() {
511                        let _ = self.mtp_step(m, &h2, input_ids[pos + 2], pos + 1);
512                    }
513                }
514                hidden = h2;
515                pos += 2;
516            }
517        }
518        while pos < input_ids.len() {
519            hidden = self.forward_layers(&self.embed_single(input_ids[pos]), pos, task_mask);
520            if let Some(m) = &mut mtp {
521                if pos + 1 < input_ids.len() {
522                    let _ = self.mtp_step(m, &hidden, input_ids[pos + 1], pos);
523                }
524            }
525            pos += 1;
526        }
527        // Prompt absorbed → freeze the o1 layers' skeletons; from here
528        // every decode step on those layers is O(W + m·dv + m²).
529        self.o1_seal();
530
531        // Commit one token: push, check EOS, stream. Returns false = stop.
532        macro_rules! commit {
533            ($id:expr) => {{
534                all_ids.push($id);
535                generated += 1;
536                if self.tokenizer.is_eos($id) {
537                    finish_reason = "stop".to_string();
538                    false
539                } else {
540                    let token_text = self.tokenizer.decode_token($id);
541                    let mut go = true;
542                    if let Some(ref mut cb) = on_token {
543                        if !cb(&token_text) {
544                            finish_reason = "cancelled".to_string();
545                            go = false;
546                        }
547                    }
548                    go
549                }
550            }};
551        }
552
553        // ── Decode ──
554        let mut next_pos = input_ids.len();
555        'decode: while generated < max_tokens {
556            let normed = inference::rms_norm(
557                &hidden,
558                &self.weights.final_norm,
559                self.rms_eps,
560                self.norm_style,
561            );
562            let logits = self.lm_head_forward(&normed);
563            let t_next = sampler::sample(&logits, &self.sampler_config, &all_ids, &mut self.rng);
564            confidence.push(top1_prob_t(&logits, t_next, calib_temp));
565            if trace_on {
566                // active_skill = the overlay in force while this token was
567                // generated; recon/switched are filled after the post-emit
568                // routing eval below (freshest coherence for this token).
569                let skill = router.as_ref().and_then(|r| r.active_id());
570                traces.push(TokenTrace {
571                    t: generated,
572                    token_id: t_next,
573                    confidence: *confidence.last().unwrap(),
574                    active_skill: skill,
575                    recon: None,
576                    switched: false,
577                });
578            }
579            if !commit!(t_next) {
580                break 'decode;
581            }
582            if generated >= max_tokens {
583                break 'decode;
584            }
585
586            if self.kv_cache.needs_eviction() {
587                let keep = (self.kv_cache.max_seq_len / 2).max(1);
588                self.kv_cache.evict(keep);
589            }
590
591            match &mut mtp {
592                // ── Speculative: draft t+2, verify in a fused pair ──
593                Some(m) if generated + 1 < max_tokens => {
594                    let draft = self.mtp_step(m, &hidden, t_next, next_pos - 1);
595                    drafted += 1;
596                    let emb1 = self.embed_single(t_next);
597                    let emb2 = self.embed_single(draft);
598                    let (h1, h2) = self.forward_pair(&emb1, &emb2, next_pos);
599
600                    let n1 = inference::rms_norm(
601                        &h1,
602                        &self.weights.final_norm,
603                        self.rms_eps,
604                        self.norm_style,
605                    );
606                    let logits1 = self.lm_head_forward(&n1);
607                    let t_after =
608                        sampler::sample(&logits1, &self.sampler_config, &all_ids, &mut self.rng);
609                    confidence.push(top1_prob_t(&logits1, t_after, calib_temp));
610                    if trace_on {
611                        // Speculative decode is mutually exclusive with
612                        // dynamic routing (router is None here) — no skill.
613                        traces.push(TokenTrace {
614                            t: generated,
615                            token_id: t_after,
616                            confidence: *confidence.last().unwrap(),
617                            active_skill: None,
618                            recon: None,
619                            switched: false,
620                        });
621                    }
622                    let stop = !commit!(t_after);
623
624                    if t_after == draft {
625                        accepted += 1;
626                        self.commit_linear_scratch();
627                        let _ = self.mtp_step(m, &h1, t_after, next_pos);
628                        hidden = h2;
629                        next_pos += 2;
630                    } else {
631                        // The draft lane is wrong: roll its KV entry back.
632                        for layer in &mut self.kv_cache.layers {
633                            layer.truncate_last(1);
634                        }
635                        if !stop {
636                            let _ = self.mtp_step(m, &h1, t_after, next_pos);
637                            hidden = self
638                                .forward_layers(&self.embed_single(t_after), next_pos + 1, None);
639                        }
640                        next_pos += 2;
641                    }
642                    if stop {
643                        break 'decode;
644                    }
645                }
646                // ── Vanilla: forward the sampled token ──
647                _ => {
648                    hidden = self.forward_layers(&self.embed_single(t_next), next_pos, task_mask);
649                    next_pos += 1;
650                    // Dynamic routing: the forward updated φ; ask the
651                    // router whether to switch skills before the next token.
652                    if let Some(r) = &mut router {
653                        let phi = self.dyn_phi_ema.clone();
654                        let decision = r.step(&phi, generated);
655                        if let Some(new_active) = decision {
656                            let _ = self.set_active_skill(new_active);
657                        }
658                        // Backfill this token's coherence + switch flag from
659                        // the just-run eval (freshest measured values).
660                        if trace_on {
661                            if let Some(last) = traces.last_mut() {
662                                let e = r.last_best_e();
663                                last.recon = e.is_finite().then_some(e);
664                                last.switched = decision.is_some();
665                            }
666                        }
667                    }
668                }
669            }
670        }
671
672        // Restore backbone overlay and re-attach the router for reuse.
673        if router.is_some() {
674            let _ = self.set_active_skill(None);
675        }
676        self.dyn_router = router.or(self.dyn_router.take());
677        self.mtp = mtp.or(self.mtp.take());
678
679        let output_ids = &all_ids[input_ids.len()..];
680        confidence.truncate(output_ids.len()); // guard against any overshoot
681        traces.truncate(output_ids.len());
682        Ok(GenerateResult {
683            text: self.tokenizer.decode(output_ids),
684            token_ids: output_ids.to_vec(),
685            prompt_tokens: input_ids.len(),
686            tokens_generated: generated,
687            finish_reason,
688            mtp_drafted: drafted,
689            mtp_accepted: accepted,
690            token_confidence: confidence,
691            traces,
692        })
693    }
694
695    /// One MTP step: feed `(hidden_p, token_{p+1})` into the draft head,
696    /// advance its KV cache at position `p`, return the drafted token
697    /// for position `p+2`.
698    fn mtp_step(&mut self, m: &mut MtpModule, hidden: &[f32], next_token: u32, position: usize) -> u32 {
699        let h_n = inference::rms_norm(hidden, &m.hnorm, self.rms_eps, self.norm_style);
700        let e = self.embed_single(next_token);
701        let e_n = inference::rms_norm(&e, &m.enorm, self.rms_eps, self.norm_style);
702        // fc concat order is [enorm(embed); hnorm(hidden)] — EMBEDDING
703        // FIRST. Verified by the oracle (converter/mtp_oracle.py):
704        // [emb;hid] → 45.8% acceptance, [hid;emb] → 0.00%.
705        let mut cat = Vec::with_capacity(2 * self.hidden_size);
706        cat.extend_from_slice(&e_n);
707        cat.extend_from_slice(&h_n);
708        let mut x = vec![0.0f32; self.hidden_size];
709        m.eh_proj.matvec(&cat, &mut x, self.pool.as_deref());
710
711        // One standard transformer block over the MTP's own cache.
712        let lw = &m.layer;
713        let normed = inference::rms_norm(&x, &lw.input_norm, self.rms_eps, self.norm_style);
714        let attn = match &lw.attn {
715            AttnKind::Full {
716                wq,
717                wk,
718                wv,
719                wo,
720                q_norm,
721                k_norm,
722                output_gate,
723                bias,
724            } => {
725                let mut cfg = self.attn_cfg(position);
726                cfg.q_norm = q_norm.as_deref();
727                cfg.k_norm = k_norm.as_deref();
728                cfg.output_gate = *output_gate;
729                cfg.bias = bias
730                    .as_ref()
731                    .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice()));
732                attention::qwen_attention(&normed, wq, wk, wv, wo, &mut m.kv, &cfg)
733            }
734            AttnKind::Linear(_) | AttnKind::LinearGdn(_) => {
735                unreachable!("MTP block is full attention")
736            }
737        };
738        for (i, &a) in attn.iter().enumerate() {
739            x[i] += a;
740        }
741        let post = inference::rms_norm(&x, &lw.post_norm, self.rms_eps, self.norm_style);
742        let ffn = ffn_forward(&lw.ffn, &post, self.pool.as_deref());
743        for (i, &f) in ffn.iter().enumerate() {
744            x[i] += f;
745        }
746
747        let out = inference::rms_norm(&x, &m.final_norm, self.rms_eps, self.norm_style);
748        sampler::argmax(&self.lm_head_forward(&out))
749    }
750
751    /// Micro-benchmark: two single-position forwards vs one fused pair
752    /// from the current cache state (KV rewound after each probe).
753    /// Returns (two_singles_ms, fused_pair_ms) per probe.
754    pub fn measure_pair_fusion(&mut self, iters: usize) -> (f64, f64) {
755        let emb1 = self.embed_single(1);
756        let emb2 = self.embed_single(2);
757        let pos = self.kv_cache.seq_len();
758
759        let t0 = std::time::Instant::now();
760        for _ in 0..iters {
761            let _ = self.forward_layers(&emb1, pos, None);
762            let _ = self.forward_layers(&emb2, pos + 1, None);
763            for l in &mut self.kv_cache.layers {
764                l.truncate_last(2);
765            }
766        }
767        let singles_ms = t0.elapsed().as_secs_f64() * 1000.0 / iters as f64;
768
769        let t1 = std::time::Instant::now();
770        for _ in 0..iters {
771            let _ = self.forward_pair(&emb1, &emb2, pos);
772            for l in &mut self.kv_cache.layers {
773                l.truncate_last(2);
774            }
775        }
776        let pair_ms = t1.elapsed().as_secs_f64() * 1000.0 / iters as f64;
777        (singles_ms, pair_ms)
778    }
779
780    /// Fused two-position forward: weight rows are streamed from memory
781    /// once per layer for both positions. Full layers → fused GQA pair;
782    /// linear layers → vmf_phase pair (lane 2 state is tentative in the
783    /// per-layer scratch until the draft is accepted).
784    fn forward_pair(&mut self, emb1: &[f32], emb2: &[f32], position: usize) -> (Vec<f32>, Vec<f32>) {
785        let mut h1 = emb1.to_vec();
786        let mut h2 = emb2.to_vec();
787        let (nh, nkv, hd, hs, rd, eps) = (
788            self.num_heads,
789            self.num_kv_heads,
790            self.head_dim,
791            self.hidden_size,
792            self.rotary_dim,
793            self.rms_eps,
794        );
795        let inv_freq = self.inv_freq.clone();
796        let pool = self.pool.clone();
797
798        for li in 0..self.num_layers {
799            let lw = &self.weights.layers[li];
800            let n1 = inference::rms_norm(&h1, &lw.input_norm, self.rms_eps, self.norm_style);
801            let n2 = inference::rms_norm(&h2, &lw.input_norm, self.rms_eps, self.norm_style);
802
803            let (a1, a2) = match &lw.attn {
804                AttnKind::Linear(w) => {
805                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
806                    let layer = &mut self.kv_cache.layers[li];
807                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
808                    vmf_phase_pair(&n1, &n2, w, &cfg, state, scratch, self.pool.as_deref())
809                }
810                AttnKind::LinearGdn(w) => {
811                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
812                    let layer = &mut self.kv_cache.layers[li];
813                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
814                    gdn_pair(&n1, &n2, w, &cfg, state, scratch, self.pool.as_deref())
815                }
816                AttnKind::Full {
817                    wq,
818                    wk,
819                    wv,
820                    wo,
821                    q_norm,
822                    k_norm,
823                    output_gate,
824                    bias,
825                } => {
826                    let cfg = QwenAttnCfg {
827                        num_heads: nh,
828                        num_kv_heads: nkv,
829                        head_dim: hd,
830                        hidden_size: hs,
831                        position,
832                        inv_freq: &inv_freq,
833                        rotary_dim: rd,
834                        q_norm: q_norm.as_deref(),
835                        k_norm: k_norm.as_deref(),
836                        output_gate: *output_gate,
837                        bias: bias
838                            .as_ref()
839                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
840                        rms_eps: eps,
841                        norm_style: self.norm_style,
842                        pool: pool.as_deref(),
843                    };
844                    attention::qwen_attention_pair(
845                        &n1,
846                        &n2,
847                        wq,
848                        wk,
849                        wv,
850                        wo,
851                        &mut self.kv_cache.layers[li],
852                        &cfg,
853                    )
854                }
855            };
856            for i in 0..self.hidden_size {
857                h1[i] += a1[i];
858                h2[i] += a2[i];
859            }
860
861            let lw = &self.weights.layers[li];
862            let p1 = inference::rms_norm(&h1, &lw.post_norm, self.rms_eps, self.norm_style);
863            let p2 = inference::rms_norm(&h2, &lw.post_norm, self.rms_eps, self.norm_style);
864            let (f1, f2) = ffn_forward_pair(&lw.ffn, &p1, &p2, self.pool.as_deref());
865            for i in 0..self.hidden_size {
866                h1[i] += f1[i];
867                h2[i] += f2[i];
868            }
869        }
870        (h1, h2)
871    }
872
873    /// Commit lane-2 linear states after an accepted draft.
874    fn commit_linear_scratch(&mut self) {
875        for layer in &mut self.kv_cache.layers {
876            if !layer.linear_scratch.is_empty() {
877                std::mem::swap(&mut layer.linear_state, &mut layer.linear_scratch);
878                layer.linear_scratch.clear();
879            }
880        }
881    }
882
883    /// Forward a full id sequence from a fresh cache and return the
884    /// logits after the last position (golden-parity harness, bench).
885    pub fn forward_ids(
886        &mut self,
887        ids: &[u32],
888        task_mask: Option<&TaskMask>,
889    ) -> Result<Vec<f32>, String> {
890        if ids.is_empty() {
891            return Err("empty id sequence".to_string());
892        }
893        self.kv_cache.clear();
894        self.o1_begin();
895        let mut hidden = vec![0.0f32; self.hidden_size];
896        let mut pos = 0usize;
897        if task_mask.is_none() && prefill_batched() && ids.len() > 2 {
898            // prefill-GEMM in chunks; only the last position's hidden is
899            // needed. (o1-compatible: the batch path attends per position
900            // through qwen_attention, which carries the collection hook.)
901            const CHUNK: usize = 48;
902            let hs = self.hidden_size;
903            while pos < ids.len() {
904                let end = (pos + CHUNK).min(ids.len());
905                let hb = self.prefill_batch(&ids[pos..end], pos);
906                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
907                pos = end;
908            }
909        }
910        if task_mask.is_none() {
911            while pos + 1 < ids.len() {
912                let e1 = self.embed_single(ids[pos]);
913                let e2 = self.embed_single(ids[pos + 1]);
914                let (_, h2) = self.forward_pair(&e1, &e2, pos);
915                self.commit_linear_scratch();
916                hidden = h2;
917                pos += 2;
918            }
919        }
920        while pos < ids.len() {
921            hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, task_mask);
922            pos += 1;
923        }
924        // Harness contract: after forward_ids the cache is decode-ready —
925        // under o1 that means sealed (bench measures the seal as part of
926        // prefill, honestly).
927        self.o1_seal();
928        let normed = inference::rms_norm(
929            &hidden,
930            &self.weights.final_norm,
931            self.rms_eps,
932            self.norm_style,
933        );
934        Ok(self.lm_head_forward(&normed))
935    }
936
937    /// Teacher-forced perplexity over a token sequence (phase-C gate:
938    /// honest quant comparisons instead of prompt vibes).
939    pub fn ppl_ids(&mut self, ids: &[u32]) -> f64 {
940        self.kv_cache.clear();
941        let mut nll = 0f64;
942        let mut cnt = 0usize;
943        if prefill_batched() {
944            // prefill-GEMM: layer-major position chunks, lm_head batched
945            // (254MB lm_head read once per chunk, not per position).
946            // The layer chunk is large (grouping positions by MoE experts
947            // wins with size), lm_head in sub-blocks (logit buffer
948            // 32×vocab ≈ 32MB instead of 128×).
949            const CHUNK: usize = 128;
950            const LM_SUB: usize = 32;
951            let n = ids.len().saturating_sub(1);
952            let hs = self.hidden_size;
953            let rows = self.weights.lm_head.rows();
954            let mut pos = 0usize;
955            while pos < n {
956                let end = (pos + CHUNK).min(n);
957                let bsz = end - pos;
958                let hb = self.prefill_batch(&ids[pos..end], pos);
959                let mut k0 = 0usize;
960                while k0 < bsz {
961                    let k1 = (k0 + LM_SUB).min(bsz);
962                    let sb = k1 - k0;
963                    let mut normed = vec![0.0f32; sb * hs];
964                    for k in 0..sb {
965                        let r = inference::rms_norm(
966                            &hb[(k0 + k) * hs..(k0 + k + 1) * hs],
967                            &self.weights.final_norm,
968                            self.rms_eps,
969                            self.norm_style,
970                        );
971                        normed[k * hs..(k + 1) * hs].copy_from_slice(&r);
972                    }
973                    let mut logits = vec![0.0f32; sb * rows];
974                    self.weights
975                        .lm_head
976                        .matmat(&normed, sb, &mut logits, self.pool.as_deref());
977                    for k in 0..sb {
978                        let lg = &logits[k * rows..k * rows + self.vocab_size.min(rows)];
979                        let target = ids[pos + k0 + k + 1] as usize;
980                        let max = lg.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
981                        let lse: f64 = lg
982                            .iter()
983                            .map(|&v| ((v - max) as f64).exp())
984                            .sum::<f64>()
985                            .ln()
986                            + max as f64;
987                        nll += lse - lg[target] as f64;
988                        cnt += 1;
989                    }
990                    k0 = k1;
991                }
992                pos = end;
993            }
994            self.kv_cache.clear();
995            return (nll / cnt.max(1) as f64).exp();
996        }
997        for pos in 0..ids.len().saturating_sub(1) {
998            let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
999            let normed = inference::rms_norm(
1000                &hidden,
1001                &self.weights.final_norm,
1002                self.rms_eps,
1003                self.norm_style,
1004            );
1005            let logits = self.lm_head_forward(&normed);
1006            let target = ids[pos + 1] as usize;
1007            let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
1008            let lse: f64 = logits.iter().map(|&v| ((v - max) as f64).exp()).sum::<f64>().ln()
1009                + max as f64;
1010            nll += lse - logits[target] as f64;
1011            cnt += 1;
1012        }
1013        self.kv_cache.clear();
1014        (nll / cnt.max(1) as f64).exp()
1015    }
1016
1017    /// Teacher-forced calibration data (B1): for each position, whether the
1018    /// argmax equals the actual next token, and the top-1 softmax prob
1019    /// (Born mass) under EACH temperature in `temps` — all from ONE forward
1020    /// pass (argmax/correctness are temperature-invariant; only p_max
1021    /// reshapes). Feeds `cortiq calibrate` (reliability/ECE + temperature
1022    /// fit): is the model's confidence a true property, or does it need a
1023    /// measured scaling?
1024    pub fn calib_ids(&mut self, ids: &[u32], temps: &[f32]) -> (Vec<bool>, Vec<Vec<f32>>) {
1025        self.kv_cache.clear();
1026        let n = ids.len().saturating_sub(1);
1027        let mut correct = Vec::with_capacity(n);
1028        let mut pmax = Vec::with_capacity(n);
1029        for pos in 0..n {
1030            let emb = self.embed_single(ids[pos]);
1031            let hidden = self.forward_layers(&emb, pos, None);
1032            let normed = inference::rms_norm(
1033                &hidden,
1034                &self.weights.final_norm,
1035                self.rms_eps,
1036                self.norm_style,
1037            );
1038            let logits = self.lm_head_forward(&normed);
1039            let target = ids[pos + 1] as usize;
1040            let (mut amax, mut mval) = (0usize, f32::NEG_INFINITY);
1041            for (i, &v) in logits.iter().enumerate() {
1042                if v > mval {
1043                    mval = v;
1044                    amax = i;
1045                }
1046            }
1047            correct.push(amax == target);
1048            let row: Vec<f32> = temps
1049                .iter()
1050                .map(|&t| {
1051                    let tt = t.max(1e-3);
1052                    let s: f32 = logits.iter().map(|&v| ((v - mval) / tt).exp()).sum();
1053                    1.0 / s.max(1e-12) // numerator at the max is exp(0)=1
1054                })
1055                .collect();
1056            pmax.push(row);
1057        }
1058        self.kv_cache.clear();
1059        (correct, pmax)
1060    }
1061
1062    /// Teacher-forced PPL with the dynamic router driving per-window
1063    /// skill switches (VMF experiment №2 measurement). Sequential (φ
1064    /// must update per token), returns (ppl, switch_count). The router
1065    /// must be enabled (`enable_dynamic_routing`); else this equals
1066    /// plain `ppl_ids`. The active skill when scoring token t shapes the
1067    /// logits for t+1 — on-policy over the held-out text itself.
1068    pub fn ppl_ids_dynamic(&mut self, ids: &[u32]) -> (f64, usize) {
1069        let mut router = match self.dyn_router.take() {
1070            Some(r) => r,
1071            None => return (self.ppl_ids(ids), 0),
1072        };
1073        router.reset();
1074        self.dyn_phi_seen = 0;
1075        let _ = self.set_active_skill(None);
1076
1077        self.kv_cache.clear();
1078        let mut nll = 0f64;
1079        let mut cnt = 0usize;
1080        for pos in 0..ids.len().saturating_sub(1) {
1081            let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
1082            let normed = inference::rms_norm(
1083                &hidden,
1084                &self.weights.final_norm,
1085                self.rms_eps,
1086                self.norm_style,
1087            );
1088            let logits = self.lm_head_forward(&normed);
1089            let target = ids[pos + 1] as usize;
1090            let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
1091            let lse: f64 = logits.iter().map(|&v| ((v - max) as f64).exp()).sum::<f64>().ln()
1092                + max as f64;
1093            nll += lse - logits[target] as f64;
1094            cnt += 1;
1095            // Route on the evolving φ (drives the NEXT token's skill).
1096            let phi = self.dyn_phi_ema.clone();
1097            if let Some(new_active) = router.step(&phi, pos) {
1098                let _ = self.set_active_skill(new_active);
1099            }
1100        }
1101        let switches = router.switches.len();
1102        let _ = self.set_active_skill(None);
1103        self.dyn_router = Some(router);
1104        self.kv_cache.clear();
1105        ((nll / cnt.max(1) as f64).exp(), switches)
1106    }
1107
1108    /// Routing probe φ (spec §9): mean-pooled hidden after `layer`.
1109    pub fn probe_phi(&mut self, ids: &[u32], layer: usize) -> Vec<f32> {
1110        self.kv_cache.clear();
1111        let mut acc = vec![0f32; self.hidden_size];
1112        for (pos, &id) in ids.iter().enumerate() {
1113            let h = self.forward_layers_upto(&self.embed_single(id), pos, None, Some(layer));
1114            for (a, v) in acc.iter_mut().zip(&h) {
1115                *a += v;
1116            }
1117        }
1118        let n = ids.len().max(1) as f32;
1119        for a in acc.iter_mut() {
1120            *a /= n;
1121        }
1122        self.kv_cache.clear();
1123        acc
1124    }
1125
1126    /// Layer-major batched prefill (prefill-GEMM): full-attention —
1127    /// per-position with the existing operators (KV grows naturally,
1128    /// causality preserved), GDN projections / FFN / MoE — batched
1129    /// (a weight row is read from DRAM once per chunk, not per
1130    /// position). Returns the hidden of all positions [b × hidden].
1131    fn prefill_batch(&mut self, ids: &[u32], start_pos: usize) -> Vec<f32> {
1132        let b = ids.len();
1133        let hs = self.hidden_size;
1134        let mut h: Vec<f32> = Vec::with_capacity(b * hs);
1135        for &id in ids {
1136            h.extend_from_slice(&self.embed_single(id));
1137        }
1138        let (nh, nkv, hd, rd, eps) = (
1139            self.num_heads,
1140            self.num_kv_heads,
1141            self.head_dim,
1142            self.rotary_dim,
1143            self.rms_eps,
1144        );
1145        let inv_freq = self.inv_freq.clone();
1146        let pool = self.pool.clone();
1147        let norm_style = self.norm_style;
1148
1149        for li in 0..self.num_layers {
1150            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU
1151            let lw = &self.weights.layers[li];
1152            // ── attention ──
1153            match &lw.attn {
1154                AttnKind::LinearGdn(w) => {
1155                    // Projections batched, recurrence sequential.
1156                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
1157                    let mut normed = vec![0.0f32; b * hs];
1158                    for bi in 0..b {
1159                        let r = inference::rms_norm(
1160                            &h[bi * hs..(bi + 1) * hs], &lw.input_norm, eps, norm_style);
1161                        normed[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
1162                    }
1163                    let attn = crate::linear_core::gdn_forward_batch(
1164                        &normed, b, w, &cfg,
1165                        &mut self.kv_cache.layers[li].linear_state,
1166                        pool.as_deref(),
1167                    );
1168                    for (dst, &a) in h.iter_mut().zip(&attn) {
1169                        *dst += a;
1170                    }
1171                }
1172                _ => {
1173                    for bi in 0..b {
1174                        let normed = inference::rms_norm(
1175                            &h[bi * hs..(bi + 1) * hs], &lw.input_norm, eps, norm_style);
1176                        let position = start_pos + bi;
1177                        let attn = match &lw.attn {
1178                            AttnKind::Linear(w) => {
1179                                let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
1180                                vmf_phase_forward(
1181                                    &normed, w, &cfg,
1182                                    &mut self.kv_cache.layers[li].linear_state,
1183                                    pool.as_deref(),
1184                                )
1185                            }
1186                            AttnKind::LinearGdn(_) => unreachable!(),
1187                            AttnKind::Full {
1188                                wq, wk, wv, wo, q_norm, k_norm, output_gate, bias,
1189                            } => {
1190                                let cfg = QwenAttnCfg {
1191                                    num_heads: nh,
1192                                    num_kv_heads: nkv,
1193                                    head_dim: hd,
1194                                    hidden_size: hs,
1195                                    position,
1196                                    inv_freq: &inv_freq,
1197                                    rotary_dim: rd,
1198                                    q_norm: q_norm.as_deref(),
1199                                    k_norm: k_norm.as_deref(),
1200                                    output_gate: *output_gate,
1201                                    bias: bias.as_ref().map(|(a, b, c)| {
1202                                        (a.as_slice(), b.as_slice(), c.as_slice())
1203                                    }),
1204                                    rms_eps: eps,
1205                                    norm_style,
1206                                    pool: pool.as_deref(),
1207                                };
1208                                attention::qwen_attention(
1209                                    &normed, wq, wk, wv, wo,
1210                                    &mut self.kv_cache.layers[li], &cfg)
1211                            }
1212                        };
1213                        for (i, &a) in attn.iter().enumerate() {
1214                            h[bi * hs + i] += a;
1215                        }
1216                    }
1217                }
1218            }
1219
1220            // ── FFN batched ──
1221            let lw = &self.weights.layers[li];
1222            let mut post = vec![0.0f32; b * hs];
1223            for bi in 0..b {
1224                let r = inference::rms_norm(
1225                    &h[bi * hs..(bi + 1) * hs], &lw.post_norm, eps, norm_style);
1226                post[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
1227            }
1228            let ffn = match &lw.ffn {
1229                FfnKind::Dense(d) => dense_ffn_batch(d, &post, b, pool.as_deref()),
1230                FfnKind::Moe(m) => moe_ffn_batch(m, &post, b, hs, pool.as_deref()),
1231            };
1232            for (dst, &f) in h.iter_mut().zip(&ffn) {
1233                *dst += f;
1234            }
1235        }
1236        crate::gpu::set_layer(-1); // lm_head/final ops outside layer-split
1237        h
1238    }
1239
1240    /// Embed a single token.
1241    fn embed_single(&self, id: u32) -> Vec<f32> {
1242        let mut out = vec![0.0f32; self.hidden_size];
1243        if (id as usize) < self.weights.embed_tokens.rows() {
1244            self.weights.embed_tokens.row_f32(id as usize, &mut out);
1245        }
1246        out
1247    }
1248
1249    /// Forward one position through all layers (hybrid dispatch).
1250    fn forward_layers(
1251        &mut self,
1252        hidden: &[f32],
1253        position: usize,
1254        task_mask: Option<&TaskMask>,
1255    ) -> Vec<f32> {
1256        self.forward_layers_upto(hidden, position, task_mask, None)
1257    }
1258
1259    /// Same, stopping after layer `upto` inclusive (routing probe φ).
1260    fn forward_layers_upto(
1261        &mut self,
1262        hidden: &[f32],
1263        position: usize,
1264        task_mask: Option<&TaskMask>,
1265        upto: Option<usize>,
1266    ) -> Vec<f32> {
1267        let mut h = hidden.to_vec();
1268        // Split borrows: copy scalars / clone handles so the per-layer
1269        // cfg does not hold `&self` while the KV cache is `&mut`.
1270        let (nh, nkv, hd, hs, rd, eps) = (
1271            self.num_heads,
1272            self.num_kv_heads,
1273            self.head_dim,
1274            self.hidden_size,
1275            self.rotary_dim,
1276            self.rms_eps,
1277        );
1278        let inv_freq = self.inv_freq.clone();
1279        let pool = self.pool.clone();
1280
1281        for li in 0..self.num_layers {
1282            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU (CMF_GPU_LAYERS)
1283            if let Some(u) = upto {
1284                if li > u {
1285                    break;
1286                }
1287            }
1288            if let Some(mask) = task_mask {
1289                if !mask.layer_alive(li) {
1290                    continue; // dead layer: residual pass-through
1291                }
1292            }
1293
1294            let lw = &self.weights.layers[li];
1295            let normed = inference::rms_norm(&h, &lw.input_norm, self.rms_eps, self.norm_style);
1296
1297            let attn_out = match &lw.attn {
1298                AttnKind::Linear(w) => {
1299                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
1300                    vmf_phase_forward(
1301                        &normed,
1302                        w,
1303                        &cfg,
1304                        &mut self.kv_cache.layers[li].linear_state,
1305                        self.pool.as_deref(),
1306                    )
1307                }
1308                AttnKind::LinearGdn(w) => {
1309                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
1310                    gdn_forward(
1311                        &normed,
1312                        w,
1313                        &cfg,
1314                        &mut self.kv_cache.layers[li].linear_state,
1315                        self.pool.as_deref(),
1316                    )
1317                }
1318                AttnKind::Full {
1319                    wq,
1320                    wk,
1321                    wv,
1322                    wo,
1323                    q_norm,
1324                    k_norm,
1325                    output_gate,
1326                    bias,
1327                } if self.kv_cache.layers[li].o1_sealed() => {
1328                    // O(1) override: decode on the sealed Nyström state
1329                    // instead of the growing KV cache.
1330                    let cfg = QwenAttnCfg {
1331                        num_heads: nh,
1332                        num_kv_heads: nkv,
1333                        head_dim: hd,
1334                        hidden_size: hs,
1335                        position,
1336                        inv_freq: &inv_freq,
1337                        rotary_dim: rd,
1338                        q_norm: q_norm.as_deref(),
1339                        k_norm: k_norm.as_deref(),
1340                        output_gate: *output_gate,
1341                        bias: bias
1342                            .as_ref()
1343                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
1344                        rms_eps: eps,
1345                        norm_style: self.norm_style,
1346                        pool: pool.as_deref(),
1347                    };
1348                    attention::qwen_attention_nystrom(
1349                        &normed,
1350                        wq,
1351                        wk,
1352                        wv,
1353                        wo,
1354                        &mut self.kv_cache.layers[li],
1355                        &cfg,
1356                    )
1357                }
1358                AttnKind::Full {
1359                    wq,
1360                    wk,
1361                    wv,
1362                    wo,
1363                    q_norm,
1364                    k_norm,
1365                    output_gate,
1366                    bias,
1367                } => {
1368                    let masked = task_mask
1369                        .map(|m| m.head_flags(li, self.num_heads).iter().any(|&a| !a))
1370                        .unwrap_or(false);
1371                    let f32_view = (wq.as_f32(), wk.as_f32(), wv.as_f32(), wo.as_f32());
1372                    match (masked, f32_view) {
1373                        // Historical masked path (f32 slices; the loader
1374                        // keeps masked models in f32).
1375                        (true, (Some(q), Some(k), Some(v), Some(o))) => {
1376                            let active_heads = task_mask.unwrap().head_flags(li, self.num_heads);
1377                            attention::multi_head_attention(
1378                                &normed,
1379                                q,
1380                                k,
1381                                v,
1382                                o,
1383                                &mut self.kv_cache.layers[li],
1384                                self.num_heads,
1385                                self.num_kv_heads,
1386                                self.head_dim,
1387                                self.hidden_size,
1388                                position,
1389                                &active_heads,
1390                                &self.inv_freq,
1391                            )
1392                        }
1393                        (masked, _) => {
1394                            if masked {
1395                                tracing::warn!(
1396                                    "layer {li}: head mask on quantized weights not \
1397                                     supported yet — executing dense"
1398                                );
1399                            }
1400                            let cfg = QwenAttnCfg {
1401                                num_heads: nh,
1402                                num_kv_heads: nkv,
1403                                head_dim: hd,
1404                                hidden_size: hs,
1405                                position,
1406                                inv_freq: &inv_freq,
1407                                rotary_dim: rd,
1408                                q_norm: q_norm.as_deref(),
1409                                k_norm: k_norm.as_deref(),
1410                                output_gate: *output_gate,
1411                        bias: bias
1412                            .as_ref()
1413                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
1414                                rms_eps: eps,
1415                                norm_style: self.norm_style,
1416                                pool: pool.as_deref(),
1417                            };
1418                            attention::qwen_attention(
1419                                &normed,
1420                                wq,
1421                                wk,
1422                                wv,
1423                                wo,
1424                                &mut self.kv_cache.layers[li],
1425                                &cfg,
1426                            )
1427                        }
1428                    }
1429                }
1430            };
1431            for (i, &a) in attn_out.iter().enumerate() {
1432                h[i] += a;
1433            }
1434
1435            let lw = &self.weights.layers[li];
1436            let post_normed = inference::rms_norm(&h, &lw.post_norm, self.rms_eps, self.norm_style);
1437
1438            let ffn_masked = task_mask
1439                .map(|m| m.ffn_active_count(li) < self.intermediate_size)
1440                .unwrap_or(false);
1441            // Sparse mask path applies to dense f32 FFN only; MoE
1442            // layers route through the normal dispatch below.
1443            let f32_ffn = match &lw.ffn {
1444                FfnKind::Dense(d) => {
1445                    (d.gate_proj.as_f32(), d.up_proj.as_f32(), d.down_proj.as_f32())
1446                }
1447                FfnKind::Moe(_) => (None, None, None),
1448            };
1449            let ffn_out = match (ffn_masked, f32_ffn) {
1450                (true, (Some(g), Some(u), Some(d))) => {
1451                    let active = task_mask.unwrap().ffn_active_indices(li);
1452                    inference::sparse_ffn_forward(
1453                        &post_normed,
1454                        g,
1455                        u,
1456                        d,
1457                        self.hidden_size,
1458                        self.intermediate_size,
1459                        &active,
1460                        self.pool.as_deref(),
1461                    )
1462                }
1463                // Mask × quantized mmap: sparse FFN reads only active
1464                // neurons' rows/cols directly from the quant bytes — no
1465                // f32 model copy (a masked big model runs at quant RSS).
1466                (true, _) => match &lw.ffn {
1467                    FfnKind::Dense(d) if d.down_proj.sparse_col_ok() => {
1468                        let active = task_mask.unwrap().ffn_active_indices(li);
1469                        sparse_ffn_quant(
1470                            d,
1471                            &post_normed,
1472                            &active,
1473                            self.hidden_size,
1474                            self.pool.as_deref(),
1475                        )
1476                    }
1477                    // q4/vbit down_proj has no cheap column access → dequant
1478                    // the three matrices to f32 (transient) and run the f32
1479                    // sparse path. Correct (mask honored), just not
1480                    // memory-lean for those dtypes — a rare masked case.
1481                    FfnKind::Dense(d) => {
1482                        let active = task_mask.unwrap().ffn_active_indices(li);
1483                        let (gf, uf, df) = dequant_dense_f32(d);
1484                        inference::sparse_ffn_forward(
1485                            &post_normed,
1486                            &gf,
1487                            &uf,
1488                            &df,
1489                            self.hidden_size,
1490                            self.intermediate_size,
1491                            &active,
1492                            self.pool.as_deref(),
1493                        )
1494                    }
1495                    FfnKind::Moe(_) => {
1496                        // MoE is already sparse by expert selection; masks
1497                        // don't apply to routed experts.
1498                        ffn_forward(&lw.ffn, &post_normed, self.pool.as_deref())
1499                    }
1500                },
1501                (false, _) => ffn_forward(&lw.ffn, &post_normed, self.pool.as_deref()),
1502            };
1503            for (i, &f) in ffn_out.iter().enumerate() {
1504                h[i] += f;
1505            }
1506
1507            // Dynamic routing φ capture (on-policy, fireball-style): the
1508            // EMA of the post-residual hidden at the router's phi_layer,
1509            // updated as the context evolves during decode.
1510            if self.dyn_phi_layer == Some(li) {
1511                self.update_dyn_phi(&h);
1512            }
1513        }
1514        crate::gpu::set_layer(-1); // layers done — lm_head outside layer-split
1515
1516        h
1517    }
1518
1519    /// EMA of φ at the router layer (rolling, weight 0.2 = ~5-token
1520    /// horizon). First observation seeds it exactly.
1521    fn update_dyn_phi(&mut self, h: &[f32]) {
1522        const A: f32 = 0.2;
1523        if self.dyn_phi_ema.len() != h.len() {
1524            self.dyn_phi_ema = vec![0.0; h.len()];
1525            self.dyn_phi_seen = 0;
1526        }
1527        if self.dyn_phi_seen == 0 {
1528            self.dyn_phi_ema.copy_from_slice(h);
1529        } else {
1530            for (e, &v) in self.dyn_phi_ema.iter_mut().zip(h) {
1531                *e = (1.0 - A) * *e + A * v;
1532            }
1533        }
1534        self.dyn_phi_seen += 1;
1535    }
1536
1537    /// Current router φ (EMA at phi_layer); empty until first capture.
1538    pub fn dyn_phi(&self) -> &[f32] {
1539        &self.dyn_phi_ema
1540    }
1541
1542    /// Enable/disable φ capture at the router layer, reset the EMA.
1543    pub fn set_dyn_phi_layer(&mut self, layer: Option<usize>) {
1544        self.dyn_phi_layer = layer;
1545        self.dyn_phi_ema.clear();
1546        self.dyn_phi_seen = 0;
1547    }
1548
1549    /// Skills eligible for dynamic switching: (index, id, phi_layer).
1550    pub fn dynamic_skills(&self) -> Vec<(usize, String, usize)> {
1551        let Some(model) = &self.model else { return Vec::new() };
1552        model
1553            .header
1554            .skills
1555            .iter()
1556            .enumerate()
1557            .filter_map(|(i, sk)| {
1558                let ok = matches!(self.dyn_skill_layers.get(i), Some(Some(_)));
1559                let sel = sk.selection.as_ref()?;
1560                (ok).then(|| (i, sk.id.clone(), sel.phi_layer))
1561            })
1562            .collect()
1563    }
1564
1565    /// Index of the currently overlaid skill (None = backbone).
1566    pub fn active_skill(&self) -> Option<usize> {
1567        self.dyn_active
1568    }
1569
1570    /// Enable dynamic per-token skill routing: build the hysteresis
1571    /// router from the container's routable skills, start φ capture at
1572    /// their (shared) phi_layer. Returns the number of routable skills
1573    /// (0 = nothing to route; router stays off). Idempotent.
1574    pub fn enable_dynamic_routing(&mut self) -> usize {
1575        use crate::swarm::{DynRouter, RoutableSkill};
1576        let Some(model) = self.model.clone() else { return 0 };
1577        // A blend materialized f32 working tensors into the layers; there
1578        // is no single skill index to revert from → refuse (honest).
1579        if self.dyn_blend_loaded {
1580            tracing::warn!("dynamic routing unavailable on a blend-loaded pipeline");
1581            return 0;
1582        }
1583        // A statically-overlaid skill that is NOT FFN-eligible can't be
1584        // cheaply reverted at generation start → refuse rather than
1585        // silently keep it overlaid.
1586        if let Some(a) = self.dyn_active {
1587            if !matches!(self.dyn_skill_layers.get(a), Some(Some(_))) {
1588                tracing::warn!(
1589                    "loaded skill is not FFN-eligible — dynamic routing unavailable"
1590                );
1591                return 0;
1592            }
1593        }
1594        let hidden = self.hidden_size;
1595        let mut skills = Vec::new();
1596        for (idx, id, _phi) in self.dynamic_skills() {
1597            if let Some(sel) = model.header.skills[idx].selection.as_ref() {
1598                if let Some(rs) = RoutableSkill::from_descriptor(idx, id, sel, hidden) {
1599                    skills.push(rs);
1600                }
1601            }
1602        }
1603        if skills.is_empty() {
1604            return 0;
1605        }
1606        // Skills should share a phi_layer; warn (not fail) if they don't.
1607        let phi = skills[0].phi_layer;
1608        if skills.iter().any(|s| s.phi_layer != phi) {
1609            tracing::warn!("routable skills disagree on phi_layer; using {phi}");
1610        }
1611        let n = skills.len();
1612        self.set_dyn_phi_layer(Some(phi));
1613        self.dyn_router = Some(DynRouter::new(skills));
1614        n
1615    }
1616
1617    /// Human-readable switch log from the last dynamic-routed generation.
1618    pub fn route_switches(&self) -> Vec<(usize, Option<String>, Option<String>)> {
1619        self.dyn_router
1620            .as_ref()
1621            .map(|r| r.switches.clone())
1622            .unwrap_or_default()
1623    }
1624
1625    /// LM head: hidden → logits [vocab_size]. The dominant matvec of
1626    /// every decode step — row-parallel on the worker pool.
1627    fn lm_head_forward(&self, hidden: &[f32]) -> Vec<f32> {
1628        let rows = self.weights.lm_head.rows();
1629        let mut logits = vec![0.0f32; rows.min(self.vocab_size)];
1630        self.weights
1631            .lm_head
1632            .matvec(hidden, &mut logits, self.pool.as_deref());
1633        logits.resize(self.vocab_size, 0.0);
1634        logits
1635    }
1636
1637    /// Prefill `ids` and return the next-token logits — what the model
1638    /// would predict next, WITHOUT committing to generation (introspection
1639    /// for `cortiq explain`). Clears and repopulates the KV cache; leaves
1640    /// the active overlay untouched.
1641    pub fn prefill_next_logits(&mut self, ids: &[u32], task_mask: Option<&TaskMask>) -> Vec<f32> {
1642        self.kv_cache.clear();
1643        let mut hidden = vec![0.0f32; self.hidden_size];
1644        for (pos, &id) in ids.iter().enumerate() {
1645            let emb = self.embed_single(id);
1646            hidden = self.forward_layers(&emb, pos, task_mask);
1647        }
1648        let normed = inference::rms_norm(
1649            &hidden,
1650            &self.weights.final_norm,
1651            self.rms_eps,
1652            self.norm_style,
1653        );
1654        self.lm_head_forward(&normed)
1655    }
1656}
1657
1658/// Convenience: deterministic tiny pipeline for tests.
1659pub fn create_test_pipeline(
1660    hidden_size: usize,
1661    intermediate_size: usize,
1662    num_heads: usize,
1663    num_kv_heads: usize,
1664    head_dim: usize,
1665    num_layers: usize,
1666    vocab_size: usize,
1667) -> Pipeline {
1668    // Small pseudo-random weights: constant weights make attention
1669    // degenerate and hide indexing bugs.
1670    let synth = |n: usize, salt: usize| -> Vec<f32> {
1671        (0..n)
1672            .map(|i| (((i * 31 + salt * 17 + 7) % 97) as f32 / 97.0 - 0.5) * 0.2)
1673            .collect()
1674    };
1675    let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
1676        QTensor::from_f32(synth(rows * cols, salt), rows, cols)
1677    };
1678    let layer_weights: Vec<LayerWeights> = (0..num_layers)
1679        .map(|li| LayerWeights {
1680            input_norm: vec![1.0; hidden_size],
1681            post_norm: vec![1.0; hidden_size],
1682            ffn: FfnKind::Dense(DenseFfn {
1683                gate_proj: qt(intermediate_size, hidden_size, li * 10 + 5),
1684                up_proj: qt(intermediate_size, hidden_size, li * 10 + 6),
1685                down_proj: qt(hidden_size, intermediate_size, li * 10 + 7),
1686            }),
1687            attn: AttnKind::Full {
1688                bias: None,
1689                wq: qt(num_heads * head_dim, hidden_size, li * 10 + 1),
1690                wk: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 2),
1691                wv: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 3),
1692                wo: qt(hidden_size, num_heads * head_dim, li * 10 + 4),
1693                q_norm: None,
1694                k_norm: None,
1695                output_gate: false,
1696            },
1697        })
1698        .collect();
1699
1700    Pipeline::new(
1701        Tokenizer::byte_level(),
1702        PipelineWeights {
1703            embed_tokens: qt(vocab_size, hidden_size, 100),
1704            layers: layer_weights,
1705            lm_head: qt(vocab_size, hidden_size, 200),
1706            final_norm: vec![1.0; hidden_size],
1707        },
1708        hidden_size,
1709        intermediate_size,
1710        num_heads,
1711        num_kv_heads,
1712        head_dim,
1713        num_layers,
1714        vocab_size,
1715        1e-6,
1716        10_000.0,
1717        NormStyle::Qwen,
1718        4096,
1719        SamplerConfig {
1720            seed: Some(42),
1721            ..Default::default()
1722        },
1723    )
1724}
1725
1726/// Batched dense-FFN: gate/up/down via matmat (element-wise the same
1727/// math as b × dense_ffn — the same dot kernels).
1728fn dense_ffn_batch(d: &DenseFfn, xs: &[f32], b: usize, pool: Option<&Pool>) -> Vec<f32> {
1729    let inter = d.gate_proj.rows();
1730    let hidden = d.down_proj.rows();
1731    let mut g = vec![0.0f32; b * inter];
1732    d.gate_proj.matmat(xs, b, &mut g, pool);
1733    let mut u = vec![0.0f32; b * inter];
1734    d.up_proj.matmat(xs, b, &mut u, pool);
1735    for i in 0..b * inter {
1736        g[i] = inference::silu(g[i]) * u[i];
1737    }
1738    let mut out = vec![0.0f32; b * hidden];
1739    d.down_proj.matmat(&g, b, &mut out, pool);
1740    out
1741}
1742
1743/// Batched MoE-FFN: router batched, positions are GROUPED by expert —
1744/// an expert's weights are read once for all its positions in the chunk
1745/// (the main prefill-GEMM win on MoE: 960MB/token of 35B experts).
1746fn moe_ffn_batch(m: &MoeFfn, xs: &[f32], b: usize, hidden: usize, pool: Option<&Pool>) -> Vec<f32> {
1747    let ne = m.experts.len();
1748    let mut logits = vec![0.0f32; b * ne];
1749    m.router.matmat(xs, b, &mut logits, pool);
1750
1751    // Assignments: expert → [(position, weight)] — the same top-k semantics
1752    // as moe_ffn (softmax over all, torch.topk order, optional renorm).
1753    let mut assign: Vec<Vec<(usize, f32)>> = vec![Vec::new(); ne];
1754    {
1755        let mut st = m.stats.borrow_mut();
1756        if st.len() < ne {
1757            st.resize(ne, 0);
1758        }
1759        for bi in 0..b {
1760            let lg = &logits[bi * ne..(bi + 1) * ne];
1761            let mx = lg.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
1762            let mut p: Vec<f32> = lg.iter().map(|&l| (l - mx).exp()).collect();
1763            let sum: f32 = p.iter().sum();
1764            for v in &mut p {
1765                *v /= sum;
1766            }
1767            let mut order: Vec<usize> = (0..ne).collect();
1768            order.sort_unstable_by(|&x, &y| p[y].partial_cmp(&p[x]).unwrap().then(x.cmp(&y)));
1769            order.truncate(m.top_k);
1770            let wsum: f32 = if m.norm_topk_prob {
1771                order.iter().map(|&e| p[e]).sum()
1772            } else {
1773                1.0
1774            };
1775            for &e in &order {
1776                st[e] += 1;
1777                assign[e].push((bi, p[e] / wsum));
1778            }
1779        }
1780    }
1781
1782    let mut out = vec![0.0f32; b * hidden];
1783    let cols = m.experts[0].gate_proj.cols();
1784    let mut run_expert = |d: &DenseFfn, list: &[(usize, f32)]| {
1785        let sb = list.len();
1786        let mut sub = vec![0.0f32; sb * cols];
1787        for (k, &(bi, _)) in list.iter().enumerate() {
1788            sub[k * cols..(k + 1) * cols].copy_from_slice(&xs[bi * cols..(bi + 1) * cols]);
1789        }
1790        let eo = dense_ffn_batch(d, &sub, sb, pool);
1791        for (k, &(bi, w)) in list.iter().enumerate() {
1792            for i in 0..hidden {
1793                out[bi * hidden + i] += w * eo[k * hidden + i];
1794            }
1795        }
1796    };
1797    for e in 0..ne {
1798        if !assign[e].is_empty() {
1799            run_expert(&m.experts[e], &assign[e]);
1800        }
1801    }
1802    if let Some((se, gate)) = &m.shared {
1803        let mut gl = vec![0.0f32; b];
1804        gate.matmat(xs, b, &mut gl, pool);
1805        let all: Vec<(usize, f32)> = (0..b)
1806            .map(|bi| (bi, 1.0 / (1.0 + (-gl[bi]).exp())))
1807            .collect();
1808        run_expert(se, &all);
1809    }
1810    out
1811}
1812
1813/// Dense SwiGLU FFN through QTensor matvecs (any storage).
1814fn dense_ffn(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
1815    let inter = d.gate_proj.rows();
1816    let mut g = vec![0.0f32; inter];
1817    d.gate_proj.matvec(x, &mut g, pool);
1818    let mut u = vec![0.0f32; inter];
1819    d.up_proj.matvec(x, &mut u, pool);
1820    for i in 0..inter {
1821        g[i] = inference::silu(g[i]) * u[i];
1822    }
1823    let mut out = vec![0.0f32; d.down_proj.rows()];
1824    d.down_proj.matvec(&g, &mut out, pool);
1825    out
1826}
1827
1828/// Sparse dense-FFN directly on QUANTIZED weights (mask × mmap): reads
1829/// ONLY the active neurons' gate/up rows and down columns from the mmap
1830/// — no full-matrix dequant, no f32 model copy. This is what lets a
1831/// masked big model run at quantized RSS (the historical mask path
1832/// forced the whole model to f32). Semantics identical to the f32
1833/// sparse path within quant tolerance.
1834fn sparse_ffn_quant(
1835    d: &DenseFfn,
1836    x: &[f32],
1837    active: &[u16],
1838    hidden: usize,
1839    pool: Option<&Pool>,
1840) -> Vec<f32> {
1841    let n = active.len();
1842    let inter = d.gate_proj.rows();
1843    let mut act = vec![0.0f32; n];
1844    // Scratch is needed if EITHER projection is group-packed (q4/vbit);
1845    // gate/up normally share a dtype but sizing on both is robust.
1846    let need_scratch = !(d.gate_proj.sparse_col_ok() && d.up_proj.sparse_col_ok());
1847    let compute = |ai: usize| -> f32 {
1848        let idx = active[ai] as usize;
1849        if idx >= inter {
1850            return 0.0; // defensive parity with the f32 sparse path
1851        }
1852        let mut s = if need_scratch { vec![0.0f32; hidden] } else { Vec::new() };
1853        let gate = d.gate_proj.row_dot(idx, x, &mut s);
1854        let up = d.up_proj.row_dot(idx, x, &mut s);
1855        inference::silu(gate) * up
1856    };
1857    match pool {
1858        Some(p) if n >= 256 => {
1859            let ptr = SendMut(act.as_mut_ptr());
1860            p.run(&|widx, nw| {
1861                let chunk = n.div_ceil(nw);
1862                let (s, e) = (widx * chunk, ((widx + 1) * chunk).min(n));
1863                for ai in s..e {
1864                    unsafe { *ptr.at(ai) = compute(ai) };
1865                }
1866            });
1867        }
1868        _ => {
1869            for (ai, a) in act.iter_mut().enumerate() {
1870                *a = compute(ai);
1871            }
1872        }
1873    }
1874    // Scatter through active down columns (reads only those columns).
1875    let mut out = vec![0.0f32; hidden];
1876    for (ai, &idx) in active.iter().enumerate() {
1877        let w = act[ai];
1878        if w.abs() >= 1e-12 && (idx as usize) < inter {
1879            d.down_proj.add_col_scaled(idx as usize, w, &mut out);
1880        }
1881    }
1882    out
1883}
1884
1885/// Test-only re-export of the private sparse-quant FFN (mask × mmap gate).
1886#[doc(hidden)]
1887pub fn sparse_ffn_quant_for_test(
1888    d: &DenseFfn,
1889    x: &[f32],
1890    active: &[u16],
1891    hidden: usize,
1892) -> Vec<f32> {
1893    sparse_ffn_quant(d, x, active, hidden, None)
1894}
1895
1896/// Dequantize a DenseFfn's three matrices to f32 (transient; only the
1897/// q4/vbit-masked fallback uses it — the memory-lean path is
1898/// sparse_ffn_quant). Reuses row_f32 row-by-row.
1899fn dequant_dense_f32(d: &DenseFfn) -> (Vec<f32>, Vec<f32>, Vec<f32>) {
1900    let deq = |t: &QTensor| -> Vec<f32> {
1901        let (rows, cols) = (t.rows(), t.cols());
1902        let mut out = vec![0.0f32; rows * cols];
1903        for r in 0..rows {
1904            t.row_f32(r, &mut out[r * cols..(r + 1) * cols]);
1905        }
1906        out
1907    };
1908    (deq(&d.gate_proj), deq(&d.up_proj), deq(&d.down_proj))
1909}
1910
1911/// Pointer wrapper for the worker-pool scatter (same pattern as qtensor).
1912struct SendMut(*mut f32);
1913unsafe impl Send for SendMut {}
1914unsafe impl Sync for SendMut {}
1915impl SendMut {
1916    #[inline]
1917    // Deliberate unsynchronized scatter: pool workers write disjoint indices
1918    // in parallel, so returning `&mut` from `&self` is intentional here.
1919    #[allow(clippy::mut_from_ref)]
1920    unsafe fn at(&self, i: usize) -> &mut f32 {
1921        unsafe { &mut *self.0.add(i) }
1922    }
1923}
1924
1925/// MoE FFN: router softmax over ALL experts → top-k (HF Qwen2/3-MoE
1926/// semantics: probabilities BEFORE selection; optional renorm of the
1927/// selected k). Only selected experts' pages are touched in mmap.
1928fn moe_ffn(m: &MoeFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
1929    let ne = m.experts.len();
1930    let mut logits = vec![0.0f32; ne];
1931    m.router.matvec(x, &mut logits, pool);
1932    let mx = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
1933    let mut p: Vec<f32> = logits.iter().map(|&l| (l - mx).exp()).collect();
1934    let s: f32 = p.iter().sum();
1935    for v in &mut p {
1936        *v /= s;
1937    }
1938    let mut idx: Vec<usize> = (0..ne).collect();
1939    // Descending by prob, lower index wins ties — torch.topk order.
1940    idx.sort_unstable_by(|&a, &b| p[b].partial_cmp(&p[a]).unwrap().then(a.cmp(&b)));
1941    idx.truncate(m.top_k);
1942    let wsum: f32 = if m.norm_topk_prob {
1943        idx.iter().map(|&e| p[e]).sum()
1944    } else {
1945        1.0
1946    };
1947    {
1948        let mut st = m.stats.borrow_mut();
1949        if st.len() < ne {
1950            st.resize(ne, 0);
1951        }
1952        for &e in &idx {
1953            st[e] += 1;
1954        }
1955    }
1956    // D5: the whole layer MoE block in one GPU command buffer (experts — the
1957    // same mmap via a no-copy buffer; intermediate activations on the GPU).
1958    if crate::gpu::enabled_here() {
1959        if let Some(out) = moe_ffn_gpu(m, x, &idx, &p, wsum, pool) {
1960            return out;
1961        }
1962    }
1963
1964    let mut out = vec![0.0f32; x.len()];
1965    for &e in &idx {
1966        let eo = dense_ffn(&m.experts[e], x, pool);
1967        let w = p[e] / wsum;
1968        for i in 0..out.len() {
1969            out[i] += w * eo[i];
1970        }
1971    }
1972    if let Some((se, gate)) = &m.shared {
1973        let so = dense_ffn(se, x, pool);
1974        let mut gl = vec![0.0f32; 1];
1975        gate.matvec(x, &mut gl, pool);
1976        let g = 1.0 / (1.0 + (-gl[0]).exp());
1977        for i in 0..out.len() {
1978            out[i] += g * so[i];
1979        }
1980    }
1981    out
1982}
1983
1984/// Building the MoE-layer GPU jobs: all selected experts (+shared) must
1985/// be q8_2f-Mapped from the primary mapping; otherwise None → CPU path.
1986fn moe_ffn_gpu(
1987    m: &MoeFfn,
1988    x: &[f32],
1989    idx: &[usize],
1990    p: &[f32],
1991    wsum: f32,
1992    pool: Option<&Pool>,
1993) -> Option<Vec<f32>> {
1994    use crate::gpu::MoeJob;
1995    use crate::qtensor::prescale;
1996    use cortiq_core::TensorDtype;
1997
1998    fn parts(
1999        t: &QTensor,
2000    ) -> Option<(&std::sync::Arc<cortiq_core::CmfModel>, usize, usize, usize, &[f32], &[f32])>
2001    {
2002        match t {
2003            QTensor::Mapped {
2004                model,
2005                idx,
2006                dtype: TensorDtype::Q8_2f,
2007                rows,
2008                cols,
2009                row_scale,
2010                col_field,
2011            } if !col_field.is_empty() => {
2012                Some((model, *idx, *rows, *cols, row_scale, col_field))
2013            }
2014            _ => None,
2015        }
2016    }
2017
2018    fn push<'a>(
2019        d: &'a DenseFfn,
2020        x: &[f32],
2021        w: f32,
2022        jobs: &mut Vec<MoeJob<'a>>,
2023        model_ref: &mut Option<std::sync::Arc<cortiq_core::CmfModel>>,
2024    ) -> Option<()> {
2025        let (gm, gi, gr, gc, grs, gcf) = parts(&d.gate_proj)?;
2026        let (_, ui, ur, uc, urs, ucf) = parts(&d.up_proj)?;
2027        let (_, di, dr, dc, drs, dcf) = parts(&d.down_proj)?;
2028        model_ref.get_or_insert_with(|| gm.clone());
2029        jobs.push(MoeJob {
2030            gate: (gi, gr, gc, grs),
2031            up: (ui, ur, uc, urs),
2032            down: (di, dr, dc, drs),
2033            xs_gate: prescale(x, gcf, TensorDtype::Q8_2f).into_owned(),
2034            xs_up: prescale(x, ucf, TensorDtype::Q8_2f).into_owned(),
2035            down_col: dcf,
2036            w,
2037        });
2038        Some(())
2039    }
2040
2041    let mut jobs: Vec<MoeJob> = Vec::with_capacity(idx.len() + 1);
2042    let mut model_ref = None;
2043    for &e in idx {
2044        push(&m.experts[e], x, p[e] / wsum, &mut jobs, &mut model_ref)?;
2045    }
2046    if let Some((se, gate)) = &m.shared {
2047        let mut gl = vec![0.0f32; 1];
2048        gate.matvec(x, &mut gl, pool);
2049        let g = 1.0 / (1.0 + (-gl[0]).exp());
2050        push(se, x, g, &mut jobs, &mut model_ref)?;
2051    }
2052    let model = model_ref?;
2053    let hidden = jobs[0].down.1;
2054    let mut out = vec![0.0f32; hidden];
2055    crate::gpu::moe_block(&model, &jobs, &mut out).then_some(out)
2056}
2057
2058/// Single-position FFN dispatch.
2059fn ffn_forward(ffn: &FfnKind, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
2060    match ffn {
2061        FfnKind::Dense(d) => dense_ffn(d, x, pool),
2062        FfnKind::Moe(m) => moe_ffn(m, x, pool),
2063    }
2064}
2065
2066/// Fused two-position FFN: gate/up/down streamed once (dense). MoE
2067/// falls back to two singles — expert sets differ per position, there
2068/// is nothing to fuse.
2069fn ffn_forward_pair(
2070    ffn: &FfnKind,
2071    x1: &[f32],
2072    x2: &[f32],
2073    pool: Option<&Pool>,
2074) -> (Vec<f32>, Vec<f32>) {
2075    let d = match ffn {
2076        FfnKind::Dense(d) => d,
2077        FfnKind::Moe(m) => return (moe_ffn(m, x1, pool), moe_ffn(m, x2, pool)),
2078    };
2079    let inter = d.gate_proj.rows();
2080    let mut g1 = vec![0.0f32; inter];
2081    let mut g2 = vec![0.0f32; inter];
2082    d.gate_proj.matvec2(x1, x2, &mut g1, &mut g2, pool);
2083    let mut u1 = vec![0.0f32; inter];
2084    let mut u2 = vec![0.0f32; inter];
2085    d.up_proj.matvec2(x1, x2, &mut u1, &mut u2, pool);
2086    for i in 0..inter {
2087        g1[i] = inference::silu(g1[i]) * u1[i];
2088        g2[i] = inference::silu(g2[i]) * u2[i];
2089    }
2090    let mut o1 = vec![0.0f32; d.down_proj.rows()];
2091    let mut o2 = vec![0.0f32; d.down_proj.rows()];
2092    d.down_proj.matvec2(&g1, &g2, &mut o1, &mut o2, pool);
2093    (o1, o2)
2094}
2095
2096#[cfg(test)]
2097mod tests {
2098    use super::*;
2099
2100    /// sparse_ffn_quant must equal a dense FFN where inactive neurons are
2101    /// zeroed (mask × mmap correctness). On F32 tensors this is EXACT —
2102    /// it validates the row_dot / add_col_scaled / scatter indexing, the
2103    /// bug-prone part. The q8 branches reuse the golden-tested linear
2104    /// scale, structurally identical to the matvec kernels.
2105    #[test]
2106    fn sparse_ffn_quant_equals_dense_with_inactive_zeroed() {
2107        let (hidden, inter) = (16usize, 40usize);
2108        let synth = |n: usize, salt: usize| -> Vec<f32> {
2109            (0..n)
2110                .map(|i| (((i * 37 + salt * 11 + 3) % 101) as f32 / 101.0 - 0.5) * 0.4)
2111                .collect()
2112        };
2113        let d = DenseFfn {
2114            gate_proj: QTensor::from_f32(synth(inter * hidden, 1), inter, hidden),
2115            up_proj: QTensor::from_f32(synth(inter * hidden, 2), inter, hidden),
2116            down_proj: QTensor::from_f32(synth(hidden * inter, 3), hidden, inter),
2117        };
2118        let x = synth(hidden, 9);
2119        // Active = every 3rd neuron.
2120        let active: Vec<u16> = (0..inter as u16).filter(|i| i % 3 == 0).collect();
2121
2122        let sparse = sparse_ffn_quant(&d, &x, &active, hidden, None);
2123
2124        // Reference: full dense FFN but g[i]=0 for inactive neurons.
2125        let mut g = vec![0.0f32; inter];
2126        d.gate_proj.matvec(&x, &mut g, None);
2127        let mut u = vec![0.0f32; inter];
2128        d.up_proj.matvec(&x, &mut u, None);
2129        let act_set: std::collections::HashSet<u16> = active.iter().copied().collect();
2130        for i in 0..inter {
2131            g[i] = if act_set.contains(&(i as u16)) {
2132                inference::silu(g[i]) * u[i]
2133            } else {
2134                0.0
2135            };
2136        }
2137        let mut reference = vec![0.0f32; hidden];
2138        d.down_proj.matvec(&g, &mut reference, None);
2139
2140        let max_d = sparse
2141            .iter()
2142            .zip(&reference)
2143            .map(|(a, b)| (a - b).abs())
2144            .fold(0.0f32, f32::max);
2145        assert!(max_d < 1e-5, "sparse != dense-zeroed: max|Δ| = {max_d}");
2146    }
2147
2148    /// Attach a synthetic MTP head (same structure as a main layer).
2149    fn attach_test_mtp(p: &mut Pipeline) {
2150        let (h, inter, heads, kv, hd) = (
2151            p.hidden_size,
2152            p.intermediate_size,
2153            p.num_heads,
2154            p.num_kv_heads,
2155            p.head_dim,
2156        );
2157        let synth = |n: usize, salt: usize| -> Vec<f32> {
2158            (0..n)
2159                .map(|i| (((i * 29 + salt * 23 + 5) % 101) as f32 / 101.0 - 0.5) * 0.2)
2160                .collect()
2161        };
2162        let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
2163            QTensor::from_f32(synth(rows * cols, salt), rows, cols)
2164        };
2165        p.mtp = Some(MtpModule {
2166            enorm: vec![1.0; h],
2167            hnorm: vec![1.0; h],
2168            eh_proj: qt(h, 2 * h, 301),
2169            layer: LayerWeights {
2170                input_norm: vec![1.0; h],
2171                post_norm: vec![1.0; h],
2172                ffn: FfnKind::Dense(DenseFfn {
2173                    gate_proj: qt(inter, h, 315),
2174                    up_proj: qt(inter, h, 316),
2175                    down_proj: qt(h, inter, 317),
2176                }),
2177                attn: AttnKind::Full {
2178                bias: None,
2179                    wq: qt(heads * hd, h, 311),
2180                    wk: qt(kv * hd, h, 312),
2181                    wv: qt(kv * hd, h, 313),
2182                    wo: qt(h, heads * hd, 314),
2183                    q_norm: None,
2184                    k_norm: None,
2185                    output_gate: false,
2186                },
2187            },
2188            final_norm: vec![1.0; h],
2189            kv: crate::kv_cache::LayerKvCache::new(kv, hd),
2190        });
2191    }
2192
2193    #[test]
2194    fn speculative_equals_vanilla_greedy() {
2195        let run = |spec: bool| {
2196            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
2197            p.sampler_config.temperature = 0.0;
2198            attach_test_mtp(&mut p);
2199            p.speculative = spec;
2200            let r = p.generate("abcdef", 12, None, None).unwrap();
2201            (r.token_ids, r.mtp_drafted, r.mtp_accepted)
2202        };
2203        let (vanilla, d0, _) = run(false);
2204        let (spec, d1, a1) = run(true);
2205        assert_eq!(d0, 0, "vanilla path must not draft");
2206        assert!(d1 > 0, "speculative path must draft");
2207        assert_eq!(
2208            vanilla, spec,
2209            "speculative must reproduce the exact greedy sequence (accepted {a1}/{d1})"
2210        );
2211    }
2212
2213    #[test]
2214    fn speculative_accepts_constant_oracle() {
2215        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
2216        p.sampler_config.temperature = 0.0;
2217        p.sampler_config.repetition_penalty = 1.0;
2218        // Constant lm_head → every logit equal → both the main model and
2219        // the draft head argmax to token 0: acceptance must be 100%.
2220        p.weights.lm_head = QTensor::from_f32(vec![0.01; 64 * 8], 64, 8);
2221        attach_test_mtp(&mut p);
2222        p.speculative = true;
2223        let r = p.generate("abcd", 10, None, None).unwrap();
2224        assert!(r.mtp_drafted > 0);
2225        assert_eq!(
2226            r.mtp_accepted, r.mtp_drafted,
2227            "constant logits → every draft accepted"
2228        );
2229        // Ties resolve to the same token in both the main and draft
2230        // heads — the sequence is one repeated token.
2231        assert!(r.token_ids.windows(2).all(|w| w[0] == w[1]));
2232    }
2233
2234    #[test]
2235    fn empty_prompt_is_an_error_not_a_panic() {
2236        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
2237        let r = p.generate("", 4, None, None);
2238        assert!(r.is_err(), "empty prompt must be a clean error");
2239    }
2240
2241    #[test]
2242    fn every_token_enters_kv_exactly_once() {
2243        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
2244        // Greedy so no RNG variance; byte tokenizer → 3 prompt tokens.
2245        p.sampler_config.temperature = 0.0;
2246        let r = p.generate("abc", 2, None, None).unwrap();
2247        assert_eq!(r.prompt_tokens, 3);
2248        // prompt(3) + first sampled token forwarded before second logits:
2249        // step0 samples from prefill hidden (no extra forward), then
2250        // forwards t1 → cache 4; step1 samples, loop ends (max_tokens).
2251        assert_eq!(
2252            p.kv_cache.seq_len(),
2253            3 + r.tokens_generated - 1,
2254            "each token must be cached exactly once (v1 cached the last prompt token twice)"
2255        );
2256    }
2257
2258    #[test]
2259    fn generation_is_reproducible_with_seed() {
2260        let run = || {
2261            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
2262            p.generate("hello", 8, None, None).unwrap().token_ids
2263        };
2264        assert_eq!(run(), run());
2265    }
2266
2267    #[test]
2268    fn eviction_bounds_the_cache() {
2269        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
2270        p.kv_cache.max_seq_len = 6;
2271        p.sampler_config.temperature = 0.0;
2272        let _ = p.generate("abcd", 12, None, None).unwrap();
2273        assert!(
2274            p.kv_cache.seq_len() <= 6 + 1,
2275            "cache must stay bounded by max_seq_len (got {})",
2276            p.kv_cache.seq_len()
2277        );
2278    }
2279
2280    #[test]
2281    fn confidence_matches_tokens_and_is_a_probability() {
2282        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
2283        p.sampler_config.temperature = 0.0;
2284        p.sampler_config.repetition_penalty = 1.0;
2285        let r = p.generate("abcd", 10, None, None).unwrap();
2286        assert_eq!(
2287            r.token_confidence.len(),
2288            r.token_ids.len(),
2289            "one confidence per emitted token"
2290        );
2291        for &c in &r.token_confidence {
2292            assert!((0.0..=1.0).contains(&c), "confidence out of [0,1]: {c}");
2293        }
2294        // top1_prob is a valid softmax probability.
2295        let logits = [1.0f32, 3.0, 0.5, 3.0];
2296        let p0 = top1_prob_t(&logits, 1, 1.0);
2297        let p1 = top1_prob_t(&logits, 3, 1.0);
2298        assert!((p0 - p1).abs() < 1e-6, "equal logits → equal prob");
2299        assert!(p0 > 0.0 && p0 < 1.0);
2300        // Calibration temperature > 1 softens an over-confident peak.
2301        let sharp = top1_prob_t(&logits, 1, 1.0);
2302        let soft = top1_prob_t(&logits, 1, 2.0);
2303        assert!(soft < sharp, "higher temperature lowers peak confidence");
2304    }
2305
2306    #[test]
2307    fn trace_is_opt_in_and_parallels_the_output() {
2308        // Off by default: the runtime is silent unless observation asked.
2309        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
2310        p.sampler_config.temperature = 0.0;
2311        p.sampler_config.repetition_penalty = 1.0;
2312        let r = p.generate("abcd", 10, None, None).unwrap();
2313        assert!(r.traces.is_empty(), "trace must be empty unless enabled");
2314
2315        // On: exactly one row per emitted token, aligned with the output.
2316        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
2317        p.sampler_config.temperature = 0.0;
2318        p.sampler_config.repetition_penalty = 1.0;
2319        p.set_trace(true);
2320        let r = p.generate("abcd", 10, None, None).unwrap();
2321        assert_eq!(r.traces.len(), r.token_ids.len(), "one trace row per token");
2322        for (i, tr) in r.traces.iter().enumerate() {
2323            assert_eq!(tr.t, i, "trace index is sequential");
2324            assert_eq!(tr.token_id, r.token_ids[i], "trace token_id matches output");
2325            assert_eq!(
2326                tr.confidence, r.token_confidence[i],
2327                "trace confidence matches the confidence channel"
2328            );
2329            // No dynamic router in this pipeline → no skill, no coherence.
2330            assert!(tr.active_skill.is_none() && tr.recon.is_none() && !tr.switched);
2331        }
2332    }
2333
2334    #[test]
2335    fn explain_prefill_logits_match_greedy_first_token() {
2336        // `cortiq explain` shows the next-token distribution from
2337        // prefill_next_logits; its argmax must equal what greedy generate
2338        // actually emits first — otherwise explain would lie.
2339        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
2340        p.sampler_config.temperature = 0.0;
2341        p.sampler_config.repetition_penalty = 1.0;
2342        let ids = p.tokenizer.encode("abcd");
2343        let logits = p.prefill_next_logits(&ids, None);
2344        let argmax = logits
2345            .iter()
2346            .enumerate()
2347            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
2348            .unwrap()
2349            .0 as u32;
2350        let r = p.generate("abcd", 1, None, None).unwrap();
2351        assert_eq!(argmax, r.token_ids[0], "explain preview must match greedy emit");
2352    }
2353}