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/// Reusable per-pipeline forward scratch: the four norm outputs the
24/// decode paths recompute every layer (single: n1/p1; pair: all four).
25/// Plain buffers, resized once — steady-state decode reuses them.
26struct ForwardScratch {
27    n1: Vec<f32>,
28    n2: Vec<f32>,
29    p1: Vec<f32>,
30    p2: Vec<f32>,
31}
32
33impl ForwardScratch {
34    fn new(hidden: usize) -> Self {
35        Self {
36            n1: vec![0.0; hidden],
37            n2: vec![0.0; hidden],
38            p1: vec![0.0; hidden],
39            p2: vec![0.0; hidden],
40        }
41    }
42}
43
44/// Complete inference pipeline state.
45pub struct Pipeline {
46    /// Arc: the server shares one tokenizer handle across request
47    /// handlers without borrowing a pipeline slot.
48    pub tokenizer: std::sync::Arc<Tokenizer>,
49    pub kv_cache: KvCache,
50    pub sampler_config: SamplerConfig,
51    pub weights: PipelineWeights,
52    pub hidden_size: usize,
53    pub intermediate_size: usize,
54    pub num_heads: usize,
55    pub num_kv_heads: usize,
56    pub head_dim: usize,
57    pub num_layers: usize,
58    pub vocab_size: usize,
59    pub rms_eps: f64,
60    pub rope_base: f32,
61    pub norm_style: NormStyle,
62    /// RoPE dims actually rotated (≤ head_dim; Qwen3.5 uses head_dim/4).
63    pub rotary_dim: usize,
64    /// Linear-core geometry (present when the model has linear layers).
65    pub vmf_cfg: Option<VmfPhaseCfg>,
66    /// GatedDeltaNet geometry (faithful vendor operator).
67    pub gdn_cfg: Option<GdnCfg>,
68    /// Multi-token-prediction head (None = absent).
69    pub mtp: Option<MtpModule>,
70    /// Speculative decode via MTP (greedy only; `CMF_MTP=0` disables).
71    pub speculative: bool,
72    rng: SplitMix64,
73    /// Precomputed RoPE inverse frequencies [head_dim/2]. Arc: the
74    /// forward path clones a handle to escape the &mut self borrow —
75    /// cloning the table itself was a per-forward allocation.
76    inv_freq: std::sync::Arc<Vec<f32>>,
77    /// Reusable norm buffers for the decode hot path (roadmap §3 P0:
78    /// steady-state forward should not heap-allocate). Disjoint field
79    /// from `weights`/`kv_cache`, so split borrows keep working.
80    ws: ForwardScratch,
81    /// Persistent worker pool (None = serial; see CMF_THREADS).
82    pool: Option<std::sync::Arc<Pool>>,
83    // ── Dynamic per-token skill routing (spec §9, claim 14/16) ──
84    /// Source model, retained so a skill switch can re-resolve the
85    /// touched layers' FFN tensors (Mapped = mmap pointers, cheap).
86    pub(crate) model: Option<std::sync::Arc<cortiq_core::CmfModel>>,
87    /// Masks present → weights are dequantized f32 (rebuild path).
88    pub(crate) dyn_force_f32: bool,
89    /// Per-skill FFN layers actually replaced (derived from tensors, not
90    /// the meta `layers` field — ru2 replaces down_proj in 0..23 while
91    /// its meta says [20..23]). None = skill touches non-FFN tensors →
92    /// ineligible for cheap dynamic switching (honest refusal).
93    pub(crate) dyn_skill_layers: Vec<Option<Vec<usize>>>,
94    /// Currently overlaid skill (index into model.header.skills); None =
95    /// backbone. Set at load time to the statically-overlaid skill so
96    /// `set_active_skill(None)` correctly reverts it (else a static
97    /// skill would silently persist — the union-diff assumes dyn_active
98    /// always mirrors the live overlay). Switched by `set_active_skill`.
99    pub(crate) dyn_active: Option<usize>,
100    /// Pipeline was loaded with a soft blend (materialized working
101    /// tensors, not a single skill index) → dynamic routing refuses:
102    /// there is no single index to revert the blend from.
103    pub(crate) dyn_blend_loaded: bool,
104    /// Layer whose post-residual hidden feeds the router φ (shared by
105    /// swarm skills). None = φ capture off.
106    pub(crate) dyn_phi_layer: Option<usize>,
107    /// EMA of φ at `dyn_phi_layer` over the decode window (on-policy).
108    dyn_phi_ema: Vec<f32>,
109    dyn_phi_seen: usize,
110    /// Hysteresis router driving per-token skill switches during decode
111    /// (None = static/no dynamic routing). Taken out during generation.
112    pub dyn_router: Option<crate::swarm::DynRouter>,
113    /// O(1) Nyström attention setting (CLI/env/header-hint resolved by
114    /// the caller; None = plain cache attention everywhere).
115    o1_cfg: Option<crate::nystrom::O1Cfg>,
116    /// Per-layer o1 flags derived from `o1_cfg` (Full layers only).
117    o1_flags: Vec<bool>,
118    /// Emit a structured per-token trace (B4 telemetry channel). Off by
119    /// default — the runtime is silent unless observation is requested.
120    trace: bool,
121    /// Confidence-calibration temperature (B1): reported Born mass is
122    /// softmax(logits / calib_temp). 1.0 = raw. Set from header.calibration.
123    calib_temp: f32,
124    /// Process-unique id keying this pipeline's device KV mirrors.
125    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
126    graph_kv_id: u64,
127    /// Token embeddings are multiplied by this at input (Gemma: √hidden).
128    pub embed_multiplier: f32,
129    /// Attention score scale (1/√head_dim unless the arch overrides —
130    /// Gemma's query_pre_attn_scalar).
131    pub attn_scale: f32,
132    /// Sliding-window attention: (window, every-Nth-layer-is-global
133    /// pattern) — Gemma-3.
134    pub swa: Option<(usize, usize)>,
135    /// RoPE table of the sliding (local) layers, when they use their
136    /// own base frequency (Gemma-3: 10k local vs 1M global).
137    pub inv_freq_local: Option<std::sync::Arc<Vec<f32>>>,
138    /// Gemma-4: global layers run their own geometry — (head_dim,
139    /// num_kv_heads); sliding layers keep the base fields.
140    pub global_attn: Option<(usize, usize)>,
141    /// Gemma-4: the global layers' proportional RoPE table (len
142    /// global_head_dim/2, zero-padded tail = identity rotation).
143    pub inv_freq_global: Option<std::sync::Arc<Vec<f32>>>,
144    /// Scale-less RMS normalization of V heads before caching (Gemma-4).
145    pub attn_v_norm: bool,
146    /// Final-logit soft-capping C: logits = C·tanh(logits/C) (Gemma-4).
147    pub final_softcap: Option<f32>,
148    /// Compute per-token Born confidence (a full-vocab softmax each
149    /// token). On by default; `bench --core` turns it off to match
150    /// llama-bench's core timing.
151    confidence_on: bool,
152}
153
154#[cfg(target_os = "macos")]
155impl Drop for Pipeline {
156    fn drop(&mut self) {
157        crate::gpu::kv_mirror_drop(self.graph_kv_id);
158    }
159}
160
161/// Model weights. Matrices are `QTensor` (owned f32 for small models
162/// and tests — bit-identical to the historical paths — or quantized
163/// bytes zero-copy from the CMF mmap for big models). 1-D norms are
164/// always small and stay f32.
165pub struct PipelineWeights {
166    /// Embedding table: [vocab_size, hidden_size]
167    pub embed_tokens: QTensor,
168    /// Per-layer weights
169    pub layers: Vec<LayerWeights>,
170    /// LM head: [vocab_size, hidden_size]
171    pub lm_head: QTensor,
172    /// Final norm: [hidden_size]
173    pub final_norm: Vec<f32>,
174}
175
176/// One transformer layer: shared norms + MLP, attention by kind.
177pub struct LayerWeights {
178    pub input_norm: Vec<f32>,
179    /// The pre-FFN norm (`post_attention_layernorm` classically;
180    /// `pre_feedforward_layernorm` on Gemma-2/3 sandwich layers).
181    pub post_norm: Vec<f32>,
182    /// Gemma-2/3 sandwich: norm applied to the ATTENTION OUTPUT before
183    /// its residual add (`post_attention_layernorm` there).
184    pub attn_out_norm: Option<Vec<f32>>,
185    /// Gemma-4: the whole layer output is multiplied by this scalar.
186    pub layer_scale: Option<f32>,
187    /// Gemma-2/3 sandwich: norm applied to the FFN OUTPUT before its
188    /// residual add (`post_feedforward_layernorm`).
189    pub ffn_out_norm: Option<Vec<f32>>,
190    pub ffn: FfnKind,
191    pub attn: AttnKind,
192}
193
194/// FFN gate activation: SiLU (SwiGLU family) or tanh-GELU (Gemma's
195/// GeGLU). A property of the model, carried on every FFN triple.
196#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
197pub enum Act {
198    #[default]
199    Silu,
200    GeluTanh,
201}
202
203impl Act {
204    pub fn from_arch(name: &str) -> Self {
205        if name == "gelu_tanh" {
206            Self::GeluTanh
207        } else {
208            Self::Silu
209        }
210    }
211
212    #[inline]
213    pub fn apply(self, x: f32) -> f32 {
214        match self {
215            Self::Silu => inference::silu(x),
216            Self::GeluTanh => inference::gelu_tanh(x),
217        }
218    }
219}
220
221/// Dense gated triple — the FFN of a dense layer or of one expert.
222pub struct DenseFfn {
223    pub gate_proj: QTensor,
224    pub up_proj: QTensor,
225    pub down_proj: QTensor,
226    /// Gate activation (SiLU default; Gemma: tanh-GELU).
227    pub act: Act,
228}
229
230/// FFN operator of a layer, decided by tensor presence at load time
231/// (router `mlp.gate.weight` in the directory = MoE layer).
232pub enum FfnKind {
233    Dense(DenseFfn),
234    /// Mixture-of-Experts (Qwen2-MoE / Qwen3-MoE): softmax over ALL
235    /// expert logits → top-k, optional renorm; experts stay quantized
236    /// in mmap — only the selected ones are touched per token.
237    Moe(MoeFfn),
238}
239
240pub struct MoeFfn {
241    /// Router `mlp.gate.weight` [num_experts, hidden].
242    pub router: QTensor,
243    pub experts: Vec<DenseFfn>,
244    pub top_k: usize,
245    pub norm_topk_prob: bool,
246    /// Qwen2-MoE always-on shared expert: (FFN, sigmoid-gate [1, hidden]).
247    pub shared: Option<(DenseFfn, QTensor)>,
248    /// Expert-selection counters (truncated Fisher B-field of claim 12:
249    /// routing frequency during calibration). Filled by every forward,
250    /// read by the CLI via CMF_MOE_STATS. RefCell: decode is single-threaded.
251    pub stats: std::cell::RefCell<Vec<u64>>,
252}
253
254/// Attention operator of a layer. Extension point: new operators are
255/// new variants here + a forward in their own module.
256pub enum AttnKind {
257    /// GQA softmax attention (+ optional Qwen3.5 qk-norm / output gate).
258    Full {
259        wq: QTensor,
260        wk: QTensor,
261        wv: QTensor,
262        wo: QTensor,
263        q_norm: Option<Vec<f32>>,
264        k_norm: Option<Vec<f32>>,
265        output_gate: bool,
266        /// Qwen2-family projection biases (q, k, v).
267        bias: Option<(Vec<f32>, Vec<f32>, Vec<f32>)>,
268    },
269    /// Canonical linear core (VMF phase attention).
270    Linear(VmfPhaseWeights),
271    /// Faithful vendor linear operator (Qwen3.5 GatedDeltaNet).
272    LinearGdn(GdnWeights),
273}
274
275/// Multi-token-prediction head (DeepSeek/Qwen style, spec §2.1):
276/// `x = eh_proj·[enorm(embed(next)); hnorm(hidden)]` → one transformer
277/// block over its own KV → shared lm_head. Drafts the token after next;
278/// the main model verifies, so output is exact — MTP only buys speed.
279pub struct MtpModule {
280    pub enorm: Vec<f32>,
281    pub hnorm: Vec<f32>,
282    /// [hidden, 2·hidden]
283    pub eh_proj: QTensor,
284    pub layer: LayerWeights,
285    pub final_norm: Vec<f32>,
286    pub kv: crate::kv_cache::LayerKvCache,
287}
288
289/// Result of a generation call.
290pub struct GenerateResult {
291    pub text: String,
292    pub token_ids: Vec<u32>,
293    pub prompt_tokens: usize,
294    pub tokens_generated: usize,
295    pub finish_reason: String,
296    /// Speculative-decode stats (0/0 when MTP is absent or inactive).
297    pub mtp_drafted: usize,
298    pub mtp_accepted: usize,
299    /// Per-generated-token confidence = softmax probability of the token
300    /// that was actually emitted (Born mass on the chosen state). High =
301    /// the model was sure; low = it was guessing. Same length as the
302    /// generated slice of `token_ids`.
303    pub token_confidence: Vec<f32>,
304    /// Structured per-token telemetry (B4 channel). Empty unless
305    /// `set_trace(true)`; otherwise same length as the generated slice.
306    pub traces: Vec<TokenTrace>,
307}
308
309/// One row of the structured telemetry trace (B4): the model's internal
310/// routing state at the moment a token was emitted. Every field is a
311/// quantity the runtime already computes — nothing is inferred or
312/// estimated (anti-principle: only measured bytes).
313#[derive(Clone, Debug)]
314pub struct TokenTrace {
315    /// 0-based index within the generated slice.
316    pub t: usize,
317    /// The emitted token id.
318    pub token_id: u32,
319    /// Born mass on the emitted token (softmax prob) — how sure the model was.
320    pub confidence: f32,
321    /// Skill in force while this token was generated (None = backbone).
322    pub active_skill: Option<String>,
323    /// Recon error E = ‖r−BBᵀr‖²/‖φ‖² at the last routing eval — coherence
324    /// with the active skill's subspace (low = coherent). None = no router
325    /// or not yet evaluated.
326    pub recon: Option<f32>,
327    /// The router changed the active skill right after this token (a
328    /// domain boundary crossed under the hysteresis barrier).
329    pub switched: bool,
330}
331
332/// Calibrated softmax probability of `id` under `logits` (the Born mass on
333/// the emitted token) — the confidence signal, cheap from logits already
334/// computed for sampling. `temp` is the calibration temperature (B1):
335/// softmax(logits / temp); 1.0 = raw.
336fn top1_prob_t(logits: &[f32], id: u32, temp: f32) -> f32 {
337    let t = if temp > 1e-3 { temp } else { 1.0 };
338    let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
339    let sum: f32 = logits.iter().map(|&v| ((v - max) / t).exp()).sum();
340    if sum > 0.0 {
341        (((logits[id as usize] - max) / t).exp()) / sum
342    } else {
343        0.0
344    }
345}
346
347/// prefill-GEMM enabled? (CMF_PREFILL=seq — emergency fallback to the
348/// sequential path.)
349fn prefill_batched() -> bool {
350    std::env::var("CMF_PREFILL").map(|v| v != "seq").unwrap_or(true)
351}
352
353/// Prefill chunk (positions per batched pass). On macOS the AMX GEMM
354/// path wants tall panels — M=48 starves the matrix units (ggml uses
355/// ubatch 512); elsewhere the historical 48 stays. CMF_PREFILL_CHUNK
356/// overrides.
357fn prefill_chunk() -> usize {
358    if let Some(n) =
359        std::env::var("CMF_PREFILL_CHUNK").ok().and_then(|v| v.parse::<usize>().ok())
360    {
361        return n.max(1);
362    }
363    if cfg!(target_os = "macos") {
364        512
365    } else {
366        48
367    }
368}
369
370/// Callback for streaming tokens. Return `false` to cancel.
371pub type TokenCallback = Box<dyn FnMut(&str) -> bool + Send>;
372
373impl Pipeline {
374    /// Build a pipeline from parts (used by the loader and tests).
375    #[allow(clippy::too_many_arguments)]
376
377    /// Whole-block q1 token graph on the GPU (macOS/Metal): the run of
378    /// consecutive q1 layers — GDN *and* full attention — starting at
379    /// `start` executes as few command buffers as the CPU truly needs.
380    /// Hidden stays device-resident across every layer; the only syncs
381    /// are before each CPU attend (it needs q/k/v and owns the KV
382    /// cache) and the final hidden readback. Recurrent states
383    /// round-trip through shared memory (the CPU stays their owner, so
384    /// every other path remains coherent). Returns the first layer
385    /// index NOT covered (== `start` → refused, caller falls through
386    /// to the per-layer CPU path).
387    /// Should prefill run position-by-position through the GPU token
388    /// graph instead of the batched CPU chunk-GEMM? True for q1 GDN
389    /// hybrids on native Metal: their chunk prefill is walled by the
390    /// sequential scalar recurrence, so the graph's decode rate wins.
391    #[cfg(target_os = "macos")]
392    fn graph_prefill_preferred(&self) -> bool {
393        if !crate::gpu::enabled_here()
394            || !crate::gpu::q1_force()
395            || std::env::var("CMF_GPU_BLOCK").map(|v| v == "0").unwrap_or(false)
396        {
397            return false;
398        }
399        self.weights.layers.iter().any(
400            |lw| matches!(&lw.attn, AttnKind::LinearGdn(w) if w.in_proj_qkv.is_q1()),
401        )
402    }
403
404    #[cfg(not(target_os = "macos"))]
405    fn graph_prefill_preferred(&self) -> bool {
406        false
407    }
408
409    #[cfg(target_os = "macos")]
410    fn q1_graph_gpu(
411        &mut self,
412        start: usize,
413        upto: Option<usize>,
414        position: usize,
415        h: &mut [f32],
416    ) -> usize {
417        use crate::gpu::{AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, GraphDims, TokenGraph};
418        if !crate::gpu::enabled_here()
419            || !crate::gpu::q1_force()
420            || std::env::var("CMF_GPU_BLOCK").map(|v| v == "0").unwrap_or(false)
421        {
422            return start;
423        }
424        // The graph encodes SiLU FFN, 1/√hd attention scores and
425        // full-context attend with no branch norms — Gemma-style archs
426        // (sliding window, scale override, sandwich norms, GeLU) fall
427        // back to the CPU path.
428        if self.swa.is_some()
429            || self.global_attn.is_some()
430            || self.attn_v_norm
431            || (self.attn_scale - 1.0 / (self.head_dim as f32).sqrt()).abs() > 1e-9
432            || self.weights.layers.iter().any(|lw| {
433                lw.attn_out_norm.is_some()
434                    || lw.ffn_out_norm.is_some()
435                    || lw.layer_scale.is_some()
436                    || matches!(&lw.ffn, FfnKind::Dense(d) if d.act != Act::Silu)
437            })
438        {
439            return start;
440        }
441        let limit = upto.map(|u| u + 1).unwrap_or(self.num_layers).min(self.num_layers);
442
443        enum Item<'a> {
444            Gdn {
445                run: Vec<GdnGpuLayer<'a>>,
446                first: usize,
447            },
448            Attn {
449                l: AttnGpuLayer<'a>,
450                li: usize,
451                q_norm: Option<&'a [f32]>,
452                k_norm: Option<&'a [f32]>,
453                output_gate: bool,
454                bias: Option<(&'a [f32], &'a [f32], &'a [f32])>,
455                /// Attend on the device too (no sync): F32 KV, no
456                /// o1/bias, dims inside the kernels' contract.
457                full_gpu: bool,
458            },
459        }
460
461        // Device-attend eligibility shared by every Full layer.
462        let dev_attend = std::env::var("CMF_GPU_ATTEND").map(|v| v != "0").unwrap_or(true)
463            && self.head_dim % 4 == 0
464            && self.head_dim <= 128
465            && self.rotary_dim >= 2
466            && self.rotary_dim <= self.head_dim
467            && (self.rotary_dim / 2) % 32 == 0
468            && self.num_kv_heads > 0
469            && self.num_heads % self.num_kv_heads == 0;
470
471        let mut plan: Vec<Item> = Vec::new();
472        let mut model_ref: Option<std::sync::Arc<cortiq_core::CmfModel>> = None;
473        let mut scan = start;
474        while scan < limit {
475            let lw = &self.weights.layers[scan];
476            let FfnKind::Dense(d) = &lw.ffn else { break };
477            let (Some(g), Some(u), Some(dn)) =
478                (d.gate_proj.q1_parts(), d.up_proj.q1_parts(), d.down_proj.q1_parts())
479            else {
480                break;
481            };
482            match &lw.attn {
483                AttnKind::LinearGdn(w) if self.gdn_cfg.is_some() => {
484                    let parts = (
485                        w.in_proj_qkv.q1_parts(),
486                        w.in_proj_z.q1_parts(),
487                        w.in_proj_a.f32_parts(),
488                        w.in_proj_b.f32_parts(),
489                        w.out_proj.q1_parts(),
490                    );
491                    let (Some(qkv), Some(z), Some(a), Some(b), Some(out)) = parts else { break };
492                    if let QTensor::Mapped { model, .. } = &w.in_proj_qkv {
493                        model_ref.get_or_insert_with(|| model.clone());
494                    }
495                    let gl = GdnGpuLayer {
496                        attn_norm: &lw.input_norm,
497                        post_norm: &lw.post_norm,
498                        qkv,
499                        z,
500                        a,
501                        b,
502                        out,
503                        gate: g,
504                        up: u,
505                        down: dn,
506                        conv1d: &w.conv1d,
507                        a_log: &w.a_log,
508                        dt_bias: &w.dt_bias,
509                        gnorm: &w.norm,
510                    };
511                    match plan.last_mut() {
512                        Some(Item::Gdn { run, .. }) => run.push(gl),
513                        _ => plan.push(Item::Gdn { run: vec![gl], first: scan }),
514                    }
515                }
516                AttnKind::Full { wq, wk, wv, wo, q_norm, k_norm, output_gate, bias }
517                    if !self.kv_cache.layers[scan].o1_sealed() =>
518                {
519                    let parts = (wq.q1_parts(), wk.q1_parts(), wv.q1_parts(), wo.q1_parts());
520                    let (Some(pq), Some(pk), Some(pv), Some(po)) = parts else { break };
521                    if let QTensor::Mapped { model, .. } = wq {
522                        model_ref.get_or_insert_with(|| model.clone());
523                    }
524                    let cache = &self.kv_cache.layers[scan];
525                    let full_gpu = dev_attend
526                        && cache.mode == crate::kv_cache::KvMode::F32
527                        && cache.o1.is_none()
528                        && bias.is_none()
529                        && pq.1 == self.num_heads * self.head_dim * (1 + *output_gate as usize)
530                        && pk.1 == self.num_kv_heads * self.head_dim
531                        && pv.1 == self.num_kv_heads * self.head_dim
532                        && po.2 == self.num_heads * self.head_dim;
533                    plan.push(Item::Attn {
534                        l: AttnGpuLayer {
535                            attn_norm: &lw.input_norm,
536                            post_norm: &lw.post_norm,
537                            wq: pq,
538                            wk: pk,
539                            wv: pv,
540                            wo: po,
541                            gate: g,
542                            up: u,
543                            down: dn,
544                        },
545                        li: scan,
546                        q_norm: q_norm.as_deref(),
547                        k_norm: k_norm.as_deref(),
548                        output_gate: *output_gate,
549                        bias: bias
550                            .as_ref()
551                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
552                        full_gpu,
553                    });
554                }
555                _ => break,
556            }
557            scan += 1;
558        }
559        let Some(model) = model_ref else { return start };
560        if plan.is_empty() {
561            return start;
562        }
563        let dims = GraphDims {
564            hidden: self.hidden_size,
565            eps: self.rms_eps as f32,
566            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
567        };
568        let Some(mut graph) = TokenGraph::new(&model, dims, h) else { return start };
569        let gcfg = self.gdn_cfg.map(|cfg| GdnGpuCfg {
570            nv: cfg.num_v_heads,
571            nk: cfg.num_k_heads,
572            dk: cfg.key_head_dim,
573            dv: cfg.value_head_dim,
574            kk: cfg.conv_kernel,
575            hidden: self.hidden_size,
576            inter: self.intermediate_size,
577            c_dim: cfg.conv_dim(),
578            eps: cfg.rms_eps as f32,
579            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
580        });
581        // Validate the whole plan BEFORE encoding anything: after the
582        // first sync a refused layer would leave the token
583        // half-executed, so truncate to the provably encodable prefix.
584        let mut valid = 0usize;
585        let mut end = start;
586        for item in &plan {
587            let ok = match item {
588                Item::Gdn { run, .. } => gcfg
589                    .as_ref()
590                    .map(|gc| run.iter().all(|l| graph.gdn_ok(l, gc)))
591                    .unwrap_or(false),
592                Item::Attn { l, .. } => graph.attn_ok(l),
593            };
594            if !ok {
595                break;
596            }
597            valid += 1;
598            end += match item {
599                Item::Gdn { run, .. } => run.len(),
600                Item::Attn { .. } => 1,
601            };
602        }
603        plan.truncate(valid);
604        if plan.is_empty() {
605            return start;
606        }
607
608        let inv_freq = self.inv_freq.clone();
609        let pool = self.pool.clone();
610        let (nh, nkv, hd, hs, rd, eps) = (
611            self.num_heads,
612            self.num_kv_heads,
613            self.head_dim,
614            self.hidden_size,
615            self.rotary_dim,
616            self.rms_eps,
617        );
618        let norm_style = self.norm_style;
619        let gemma = norm_style == cortiq_core::NormStyle::Gemma;
620        let want = self.gdn_cfg.map(|c| c.state_len()).unwrap_or(0);
621        let kv_id = self.graph_kv_id;
622        // GDN runs whose states await readback after the next sync
623        // (device-attended layers add no sync, so several may stack).
624        let mut pending: Vec<(usize, usize)> = Vec::new();
625        // Device-attended layers: their K/V/imp are pulled from the
626        // mirror after the final sync.
627        let mut dev_attn: Vec<usize> = Vec::new();
628        for item in &plan {
629            match item {
630                Item::Gdn { run, first } => {
631                    for l in &mut self.kv_cache.layers[*first..*first + run.len()] {
632                        if l.linear_state.len() != want {
633                            l.linear_state = vec![0f32; want];
634                        }
635                    }
636                    let ro: Vec<&[f32]> = self.kv_cache.layers[*first..*first + run.len()]
637                        .iter()
638                        .map(|l| l.linear_state.as_slice())
639                        .collect();
640                    if !graph.encode_gdn_run(run, &ro, gcfg.as_ref().unwrap()) {
641                        // Unreachable: the plan was validated above.
642                        tracing::error!("q1 graph: GDN run refused after validation");
643                        return start;
644                    }
645                    // Early commit: the GPU starts the run while the
646                    // CPU encodes the next layer (nothing to wait on).
647                    graph.commit();
648                    pending.push((*first, run.len()));
649                }
650                Item::Attn { l, li, q_norm, k_norm, output_gate, bias, full_gpu } => {
651                    // ── Fully device-resident attention: no sync at all.
652                    if *full_gpu {
653                        let cache = &self.kv_cache.layers[*li];
654                        let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
655                        let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
656                        let cpu_stored = cpu_k[0].len() / hd;
657                        let p = crate::gpu::AttnDeviceParams {
658                            kv_id,
659                            layer: *li,
660                            nh,
661                            nkv,
662                            hd,
663                            rd,
664                            position,
665                            eps: eps as f32,
666                            gemma,
667                            output_gate: *output_gate,
668                            q_norm: *q_norm,
669                            k_norm: *k_norm,
670                            inv_freq: &inv_freq,
671                            cpu_k,
672                            cpu_v,
673                            cpu_stored,
674                        };
675                        if graph.attn_device_ok(l, &p) && graph.encode_attn_device(l, &p) {
676                            graph.commit();
677                            dev_attn.push(*li);
678                            continue;
679                        }
680                        // Mirror refused (nothing encoded) → sandwich.
681                    }
682                    graph.encode_attn_prefix(l);
683                    graph.sync();
684                    if !pending.is_empty() {
685                        let idxs: Vec<usize> =
686                            pending.drain(..).flat_map(|(f, n)| f..f + n).collect();
687                        let mut outs: Vec<&mut [f32]> = self
688                            .kv_cache
689                            .layers
690                            .iter_mut()
691                            .enumerate()
692                            .filter(|(i, _)| idxs.binary_search(i).is_ok())
693                            .map(|(_, s)| s.linear_state.as_mut_slice())
694                            .collect();
695                        graph.read_states(&mut outs);
696                    }
697                    let mut q_raw = attention::take_buf(l.wq.1);
698                    let mut k = attention::take_buf(l.wk.1);
699                    let mut v = attention::take_buf(l.wv.1);
700                    graph.read_qkv(&mut q_raw, &mut k, &mut v);
701                    let cfg = QwenAttnCfg {
702                        num_heads: nh,
703                        num_kv_heads: nkv,
704                        head_dim: hd,
705                        hidden_size: hs,
706                        position,
707                        inv_freq: &inv_freq,
708                        rotary_dim: rd,
709                        scale: self.attn_scale,
710                        window: None,
711                        v_norm: false,
712                        q_norm: *q_norm,
713                        k_norm: *k_norm,
714                        output_gate: *output_gate,
715                        bias: *bias,
716                        rms_eps: eps,
717                        norm_style,
718                        pool: pool.as_deref(),
719                    };
720                    let mut ao = attention::qwen_attention_core(
721                        q_raw,
722                        k,
723                        v,
724                        &mut self.kv_cache.layers[*li],
725                        &cfg,
726                    );
727                    graph.encode_attn_suffix(l, &ao);
728                    // Early commit: the GPU starts O+FFN while the CPU
729                    // encodes the following GDN run / attention prefix.
730                    graph.commit();
731                    attention::recycle_buf(&mut ao);
732                }
733            }
734        }
735        graph.sync();
736        if !pending.is_empty() {
737            let idxs: Vec<usize> = pending.drain(..).flat_map(|(f, n)| f..f + n).collect();
738            let mut outs: Vec<&mut [f32]> = self
739                .kv_cache
740                .layers
741                .iter_mut()
742                .enumerate()
743                .filter(|(i, _)| idxs.binary_search(i).is_ok())
744                .map(|(_, s)| s.linear_state.as_mut_slice())
745                .collect();
746            graph.read_states(&mut outs);
747        }
748        graph.finish(h);
749        // Device-attended layers: replay the CPU bookkeeping — append
750        // the mirror's new K/V row (rope'd on the GPU) into the owner
751        // cache, then bank this token's Born-importance mass.
752        for li in dev_attn {
753            let mut krow = attention::take_buf(nkv * hd);
754            let mut vrow = attention::take_buf(nkv * hd);
755            if crate::gpu::kv_mirror_read_last(kv_id, li, nkv, hd, &mut krow, &mut vrow) {
756                let cache = &mut self.kv_cache.layers[li];
757                cache.append(&krow, &vrow, &[]);
758                let n = cache.seq_len;
759                let mut imp = attention::take_buf(n);
760                crate::gpu::kv_mirror_take_imp(kv_id, li, &mut imp);
761                cache.accumulate_imp(&imp);
762                attention::recycle_buf(&mut imp);
763            }
764            attention::recycle_buf(&mut krow);
765            attention::recycle_buf(&mut vrow);
766        }
767        end
768    }
769
770    pub fn new(
771        tokenizer: Tokenizer,
772        weights: PipelineWeights,
773        hidden_size: usize,
774        intermediate_size: usize,
775        num_heads: usize,
776        num_kv_heads: usize,
777        head_dim: usize,
778        num_layers: usize,
779        vocab_size: usize,
780        rms_eps: f64,
781        rope_base: f32,
782        norm_style: NormStyle,
783        max_seq_len: usize,
784        sampler_config: SamplerConfig,
785    ) -> Self {
786        let rng = match sampler_config.seed {
787            Some(s) => SplitMix64::new(s),
788            None => SplitMix64::from_entropy(),
789        };
790        let inv_freq = std::sync::Arc::new(attention::rope_inv_freq(head_dim, rope_base));
791        let pool = Pool::from_env();
792        if let Some(p) = &pool {
793            tracing::info!("worker pool: {} threads", p.n_workers());
794        }
795        Self {
796            tokenizer: std::sync::Arc::new(tokenizer),
797            kv_cache: KvCache::new(num_layers, num_kv_heads, head_dim, max_seq_len),
798            sampler_config,
799            weights,
800            hidden_size,
801            intermediate_size,
802            num_heads,
803            num_kv_heads,
804            head_dim,
805            num_layers,
806            vocab_size,
807            rms_eps,
808            rope_base,
809            norm_style,
810            rotary_dim: head_dim,
811            vmf_cfg: None,
812            gdn_cfg: None,
813            mtp: None,
814            speculative: std::env::var("CMF_MTP").map(|v| v != "0").unwrap_or(true),
815            rng,
816            inv_freq,
817            ws: ForwardScratch::new(hidden_size),
818            pool,
819            model: None,
820            dyn_force_f32: false,
821            dyn_skill_layers: Vec::new(),
822            dyn_active: None,
823            dyn_blend_loaded: false,
824            dyn_phi_layer: None,
825            dyn_phi_ema: Vec::new(),
826            dyn_phi_seen: 0,
827            dyn_router: None,
828            o1_cfg: None,
829            o1_flags: Vec::new(),
830            trace: false,
831            calib_temp: 1.0,
832            confidence_on: true,
833            embed_multiplier: 1.0,
834            attn_scale: 1.0 / (head_dim as f32).sqrt(),
835            swa: None,
836            inv_freq_local: None,
837            global_attn: None,
838            inv_freq_global: None,
839            attn_v_norm: false,
840            final_softcap: None,
841            graph_kv_id: {
842                static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
843                NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
844            },
845        }
846    }
847
848    /// Enable/disable per-layer O(1) Nyström attention. Only Full
849    /// layers are eligible (a linear layer keeps its own operator).
850    /// Applies to generation (`generate*`/`forward_ids`): the prompt
851    /// pass stays exact, the seal happens once after prefill, decode
852    /// runs on the O(1) state. Teacher-forced scoring (`ppl_ids`)
853    /// intentionally stays exact.
854    pub fn set_o1(&mut self, cfg: Option<crate::nystrom::O1Cfg>) {
855        self.o1_flags = match &cfg {
856            Some(c) => {
857                let mut flags = c.layer_flags(self.num_layers);
858                for (li, f) in flags.iter_mut().enumerate() {
859                    if *f && !matches!(self.weights.layers[li].attn, AttnKind::Full { .. }) {
860                        *f = false;
861                    }
862                }
863                flags
864            }
865            None => Vec::new(),
866        };
867        if let Some(c) = &cfg {
868            let n = self.o1_flags.iter().filter(|&&f| f).count();
869            tracing::info!(
870                "o1 nystrom attention: {n}/{} layer(s), m={} w={} sink={} rect={:?}",
871                self.num_layers, c.m, c.w, c.sink, c.rect
872            );
873        }
874        self.o1_cfg = cfg;
875    }
876
877    /// True when at least one layer runs the O(1) kernel.
878    pub fn o1_active(&self) -> bool {
879        self.o1_cfg.is_some() && self.o1_flags.iter().any(|&f| f)
880    }
881
882    /// Arm query collection on the o1 layers (fresh prompt pass).
883    fn o1_begin(&mut self) {
884        if let Some(c) = &self.o1_cfg {
885            let (m, w, sink, rect) = (c.m, c.w, c.sink, c.rect);
886            for (li, &f) in self.o1_flags.iter().enumerate() {
887                if f {
888                    self.kv_cache.layers[li].o1_begin(m, w, sink, rect);
889                }
890            }
891        }
892    }
893
894    /// Freeze landmarks + skeleton state after the prompt pass and drop
895    /// the o1 layers' full KV; decode then runs `step()` per token.
896    fn o1_seal(&mut self) {
897        if self.o1_cfg.is_none() {
898            return;
899        }
900        for li in 0..self.num_layers {
901            if self.o1_flags.get(li).copied().unwrap_or(false) {
902                self.kv_cache.layers[li].o1_seal(self.num_heads);
903            }
904        }
905    }
906
907    /// Enable/disable the structured per-token telemetry trace (B4).
908    pub fn set_trace(&mut self, on: bool) {
909        self.trace = on;
910    }
911
912    /// Toggle the per-token Born-confidence reduction (a full-vocab
913    /// softmax each token). `bench --core` turns it off so the timed
914    /// loop matches llama-bench's core contract; the result's
915    /// `confidence` vec is empty while off.
916    pub fn set_confidence(&mut self, on: bool) {
917        self.confidence_on = on;
918    }
919
920    /// Set the confidence-calibration temperature (B1). Values ≤0 are
921    /// clamped to raw (1.0).
922    pub fn set_calib_temp(&mut self, t: f32) {
923        self.calib_temp = if t > 1e-3 { t } else { 1.0 };
924    }
925
926    /// The active calibration temperature (1.0 = raw Born mass).
927    pub fn calib_temp(&self) -> f32 {
928        self.calib_temp
929    }
930
931    /// Partial rotary (Qwen3.5): rotate only the first `rotary_dim` dims;
932    /// the frequency table is rebuilt over the rotary dims.
933    pub fn set_rotary(&mut self, rotary_dim: usize, base: f32) {
934        self.rotary_dim = rotary_dim.min(self.head_dim);
935        self.inv_freq = std::sync::Arc::new(attention::rope_inv_freq(self.rotary_dim, base));
936    }
937
938    fn attn_cfg(&self, position: usize) -> QwenAttnCfg<'_> {
939        QwenAttnCfg {
940            num_heads: self.num_heads,
941            num_kv_heads: self.num_kv_heads,
942            head_dim: self.head_dim,
943            hidden_size: self.hidden_size,
944            position,
945            inv_freq: &self.inv_freq,
946            rotary_dim: self.rotary_dim,
947            scale: self.attn_scale,
948            window: None,
949            v_norm: false,
950            q_norm: None,
951            k_norm: None,
952            output_gate: false,
953            bias: None,
954            rms_eps: self.rms_eps,
955            norm_style: self.norm_style,
956            pool: self.pool.as_deref(),
957        }
958    }
959
960    /// Generate text from a plain-text prompt. Streams tokens via `on_token`.
961    pub fn generate(
962        &mut self,
963        prompt: &str,
964        max_tokens: usize,
965        task_mask: Option<&TaskMask>,
966        on_token: Option<TokenCallback>,
967    ) -> Result<GenerateResult, String> {
968        let input_ids = self.tokenizer.with_bos(self.tokenizer.encode(prompt));
969        self.generate_from_ids(&input_ids, max_tokens, task_mask, on_token)
970    }
971
972    /// Generate from prepared token ids (e.g. a chat template).
973    ///
974    /// With an MTP head, greedy generation without a task mask takes the
975    /// speculative path: the MTP module drafts the token after next and
976    /// the main model verifies both in one fused two-position forward
977    /// (weights streamed once). The output is EXACTLY the vanilla greedy
978    /// sequence — a rejected draft is rolled back — MTP only buys speed.
979    pub fn generate_from_ids(
980        &mut self,
981        input_ids: &[u32],
982        max_tokens: usize,
983        task_mask: Option<&TaskMask>,
984        mut on_token: Option<TokenCallback>,
985    ) -> Result<GenerateResult, String> {
986        if std::env::var("CMF_TRACE_H").is_ok() {
987            eprintln!("input_ids: {input_ids:?}");
988        }
989        if input_ids.is_empty() {
990            return Err("empty prompt: nothing to generate from".to_string());
991        }
992
993        // Fresh sequence — the cache holds absolute positions.
994        self.kv_cache.clear();
995        self.o1_begin();
996
997        // Speculative decode is off under o1: a rejected draft can't be
998        // rolled back out of the far accumulators / ring window (the
999        // Nyström insertion is irreversible by design).
1000        let spec_active = self.speculative
1001            && self.mtp.is_some()
1002            && task_mask.is_none()
1003            && !self.o1_active()
1004            && self.sampler_config.temperature < 1e-6;
1005        // The MTP module is detached during generation so its mutable
1006        // state does not fight the borrow on `self`.
1007        let mut mtp = if spec_active { self.mtp.take() } else { None };
1008        if let Some(m) = &mut mtp {
1009            m.kv.clear();
1010        }
1011        // Dynamic router detached during decode (same borrow trick as MTP).
1012        // Speculative decode and dynamic routing are mutually exclusive
1013        // for now — the fused-pair path doesn't carry per-token φ.
1014        let mut router = if mtp.is_none() { self.dyn_router.take() } else { None };
1015        if let Some(r) = &mut router {
1016            r.reset(); // active=backbone, matching a fresh overlay
1017            self.dyn_phi_seen = 0; // fresh φ EMA per generation
1018            let _ = self.set_active_skill(None);
1019        }
1020
1021        let mut all_ids = input_ids.to_vec();
1022        let mut generated = 0usize;
1023        let mut finish_reason = "max_tokens".to_string();
1024        let mut drafted = 0usize;
1025        let mut accepted = 0usize;
1026        let mut confidence: Vec<f32> = Vec::new();
1027        let trace_on = self.trace;
1028        let calib_temp = self.calib_temp;
1029        let mut traces: Vec<TokenTrace> = Vec::new();
1030
1031        // ── Prefill: forward each prompt token once, KEEP the last hidden.
1032        //    Dense prefill runs in fused pairs (weights streamed once per
1033        //    two positions — bit-identical to sequential, proven by the
1034        //    pair tests). With MTP: warm the draft head on
1035        //    (hidden_p, token_{p+1}) pairs.
1036        let mut hidden = vec![0.0f32; self.hidden_size];
1037        let mut pos = 0usize;
1038        // With dynamic routing, prefill sequentially so the φ hook fires
1039        // over the PROMPT — the router enters decode with a warm φ (the
1040        // fused-pair path skips the per-layer φ capture). o1 layers
1041        // collect their query trace in both the single and pair paths.
1042        let dyn_prefill = router.is_some();
1043        // q1 hybrids on Metal: the per-position GPU token graph beats
1044        // the CPU chunk-GEMM (whose wall is the sequential scalar GDN
1045        // recurrence), so prefill goes position-by-position through the
1046        // same graph as decode. Pure-attention models keep the batched
1047        // path — there the chunk-GEMM amortization wins.
1048        let graph_prefill = self.graph_prefill_preferred();
1049        if task_mask.is_none()
1050            && !dyn_prefill
1051            && !graph_prefill
1052            && prefill_batched()
1053            && input_ids.len() > 2
1054        {
1055            // Production prefill = the same chunked prefill-GEMM that
1056            // bench/PPL measure (roadmap §3 P0: generation used to warm
1057            // the prompt with the slower pair path — the published
1058            // prefill number didn't match real TTFT). MTP warm-up reads
1059            // each position's hidden straight from the chunk result.
1060            let chunk = prefill_chunk();
1061            let hs = self.hidden_size;
1062            while pos < input_ids.len() {
1063                let end = (pos + chunk).min(input_ids.len());
1064                let hb = self.prefill_batch(&input_ids[pos..end], pos);
1065                if let Some(m) = &mut mtp {
1066                    for p in pos..end {
1067                        if p + 1 < input_ids.len() {
1068                            let _ = self.mtp_step(
1069                                m,
1070                                &hb[(p - pos) * hs..(p - pos + 1) * hs],
1071                                input_ids[p + 1],
1072                                p,
1073                            );
1074                        }
1075                    }
1076                }
1077                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
1078                pos = end;
1079            }
1080        }
1081        if task_mask.is_none() && !dyn_prefill && !graph_prefill {
1082            while pos + 1 < input_ids.len() {
1083                let e1 = self.embed_single(input_ids[pos]);
1084                let e2 = self.embed_single(input_ids[pos + 1]);
1085                let (h1, h2) = self.forward_pair(&e1, &e2, pos);
1086                // Both prefill tokens are real → commit lane-2 states.
1087                self.commit_linear_scratch();
1088                if let Some(m) = &mut mtp {
1089                    let _ = self.mtp_step(m, &h1, input_ids[pos + 1], pos);
1090                    if pos + 2 < input_ids.len() {
1091                        let _ = self.mtp_step(m, &h2, input_ids[pos + 2], pos + 1);
1092                    }
1093                }
1094                hidden = h2;
1095                pos += 2;
1096            }
1097        }
1098        while pos < input_ids.len() {
1099            hidden = self.forward_layers(&self.embed_single(input_ids[pos]), pos, task_mask);
1100            if let Some(m) = &mut mtp {
1101                if pos + 1 < input_ids.len() {
1102                    let _ = self.mtp_step(m, &hidden, input_ids[pos + 1], pos);
1103                }
1104            }
1105            pos += 1;
1106        }
1107        // Prompt absorbed → freeze the o1 layers' skeletons; from here
1108        // every decode step on those layers is O(W + m·dv + m²).
1109        self.o1_seal();
1110
1111        // Commit one token: push, check EOS, stream. Returns false = stop.
1112        macro_rules! commit {
1113            ($id:expr) => {{
1114                all_ids.push($id);
1115                generated += 1;
1116                if self.tokenizer.is_eos($id) {
1117                    finish_reason = "stop".to_string();
1118                    false
1119                } else {
1120                    let token_text = self.tokenizer.decode_token($id);
1121                    let mut go = true;
1122                    if let Some(ref mut cb) = on_token {
1123                        if !cb(&token_text) {
1124                            finish_reason = "cancelled".to_string();
1125                            go = false;
1126                        }
1127                    }
1128                    go
1129                }
1130            }};
1131        }
1132
1133        // ── Decode ──
1134        let mut next_pos = input_ids.len();
1135        'decode: while generated < max_tokens {
1136            inference::rms_norm_into(
1137                &hidden,
1138                &self.weights.final_norm,
1139                self.rms_eps,
1140                self.norm_style,
1141                &mut self.ws.n1,
1142            );
1143            let mut logits = self.lm_head_forward(&self.ws.n1);
1144            let t_next = sampler::sample(&logits, &self.sampler_config, &all_ids, &mut self.rng);
1145            if self.confidence_on {
1146                confidence.push(top1_prob_t(&logits, t_next, calib_temp));
1147            }
1148            attention::recycle_buf(&mut logits);
1149            if trace_on {
1150                // active_skill = the overlay in force while this token was
1151                // generated; recon/switched are filled after the post-emit
1152                // routing eval below (freshest coherence for this token).
1153                let skill = router.as_ref().and_then(|r| r.active_id());
1154                traces.push(TokenTrace {
1155                    t: generated,
1156                    token_id: t_next,
1157                    confidence: confidence.last().copied().unwrap_or(0.0),
1158                    active_skill: skill,
1159                    recon: None,
1160                    switched: false,
1161                });
1162            }
1163            if !commit!(t_next) {
1164                break 'decode;
1165            }
1166            if generated >= max_tokens {
1167                break 'decode;
1168            }
1169
1170            if self.kv_cache.needs_eviction() {
1171                let keep = (self.kv_cache.max_seq_len / 2).max(1);
1172                self.kv_cache.evict(keep);
1173            }
1174
1175            match &mut mtp {
1176                // ── Speculative: draft t+2, verify in a fused pair ──
1177                Some(m) if generated + 1 < max_tokens => {
1178                    let draft = self.mtp_step(m, &hidden, t_next, next_pos - 1);
1179                    drafted += 1;
1180                    let emb1 = self.embed_single(t_next);
1181                    let emb2 = self.embed_single(draft);
1182                    let (h1, h2) = self.forward_pair(&emb1, &emb2, next_pos);
1183
1184                    inference::rms_norm_into(
1185                        &h1,
1186                        &self.weights.final_norm,
1187                        self.rms_eps,
1188                        self.norm_style,
1189                        &mut self.ws.n1,
1190                    );
1191                    let mut logits1 = self.lm_head_forward(&self.ws.n1);
1192                    let t_after =
1193                        sampler::sample(&logits1, &self.sampler_config, &all_ids, &mut self.rng);
1194                    if self.confidence_on {
1195                        confidence.push(top1_prob_t(&logits1, t_after, calib_temp));
1196                    }
1197                    attention::recycle_buf(&mut logits1);
1198                    if trace_on {
1199                        // Speculative decode is mutually exclusive with
1200                        // dynamic routing (router is None here) — no skill.
1201                        traces.push(TokenTrace {
1202                            t: generated,
1203                            token_id: t_after,
1204                            confidence: confidence.last().copied().unwrap_or(0.0),
1205                            active_skill: None,
1206                            recon: None,
1207                            switched: false,
1208                        });
1209                    }
1210                    let stop = !commit!(t_after);
1211
1212                    if t_after == draft {
1213                        accepted += 1;
1214                        self.commit_linear_scratch();
1215                        let _ = self.mtp_step(m, &h1, t_after, next_pos);
1216                        hidden = h2;
1217                        next_pos += 2;
1218                    } else {
1219                        // The draft lane is wrong: roll its KV entry back.
1220                        for layer in &mut self.kv_cache.layers {
1221                            layer.truncate_last(1);
1222                        }
1223                        if !stop {
1224                            let _ = self.mtp_step(m, &h1, t_after, next_pos);
1225                            hidden = self
1226                                .forward_layers(&self.embed_single(t_after), next_pos + 1, None);
1227                        }
1228                        next_pos += 2;
1229                    }
1230                    if stop {
1231                        break 'decode;
1232                    }
1233                }
1234                // ── Vanilla: forward the sampled token ──
1235                _ => {
1236                    hidden = self.forward_layers(&self.embed_single(t_next), next_pos, task_mask);
1237                    next_pos += 1;
1238                    // Dynamic routing: the forward updated φ; ask the
1239                    // router whether to switch skills before the next token.
1240                    if let Some(r) = &mut router {
1241                        let phi = self.dyn_phi_ema.clone();
1242                        let decision = r.step(&phi, generated);
1243                        if let Some(new_active) = decision {
1244                            let _ = self.set_active_skill(new_active);
1245                        }
1246                        // Backfill this token's coherence + switch flag from
1247                        // the just-run eval (freshest measured values).
1248                        if trace_on {
1249                            if let Some(last) = traces.last_mut() {
1250                                let e = r.last_best_e();
1251                                last.recon = e.is_finite().then_some(e);
1252                                last.switched = decision.is_some();
1253                            }
1254                        }
1255                    }
1256                }
1257            }
1258        }
1259
1260        // Restore backbone overlay and re-attach the router for reuse.
1261        if router.is_some() {
1262            let _ = self.set_active_skill(None);
1263        }
1264        self.dyn_router = router.or(self.dyn_router.take());
1265        self.mtp = mtp.or(self.mtp.take());
1266
1267        let output_ids = &all_ids[input_ids.len()..];
1268        confidence.truncate(output_ids.len()); // guard against any overshoot
1269        traces.truncate(output_ids.len());
1270        Ok(GenerateResult {
1271            text: self.tokenizer.decode(output_ids),
1272            token_ids: output_ids.to_vec(),
1273            prompt_tokens: input_ids.len(),
1274            tokens_generated: generated,
1275            finish_reason,
1276            mtp_drafted: drafted,
1277            mtp_accepted: accepted,
1278            token_confidence: confidence,
1279            traces,
1280        })
1281    }
1282
1283    /// One MTP step: feed `(hidden_p, token_{p+1})` into the draft head,
1284    /// advance its KV cache at position `p`, return the drafted token
1285    /// for position `p+2`.
1286    fn mtp_step(&mut self, m: &mut MtpModule, hidden: &[f32], next_token: u32, position: usize) -> u32 {
1287        // fc concat order is [enorm(embed); hnorm(hidden)] — EMBEDDING
1288        // FIRST. Verified by the oracle (converter/mtp_oracle.py):
1289        // [emb;hid] → 45.8% acceptance, [hid;emb] → 0.00%.
1290        let e = self.embed_single(next_token);
1291        let mut cat = vec![0.0f32; 2 * self.hidden_size];
1292        let (cat_e, cat_h) = cat.split_at_mut(self.hidden_size);
1293        inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
1294        inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
1295        let mut x = vec![0.0f32; self.hidden_size];
1296        m.eh_proj.matvec(&cat, &mut x, self.pool.as_deref());
1297
1298        // One standard transformer block over the MTP's own cache.
1299        let lw = &m.layer;
1300        inference::rms_norm_into(&x, &lw.input_norm, self.rms_eps, self.norm_style, &mut self.ws.n1);
1301        let attn = match &lw.attn {
1302            AttnKind::Full {
1303                wq,
1304                wk,
1305                wv,
1306                wo,
1307                q_norm,
1308                k_norm,
1309                output_gate,
1310                bias,
1311            } => {
1312                let mut cfg = self.attn_cfg(position);
1313                cfg.q_norm = q_norm.as_deref();
1314                cfg.k_norm = k_norm.as_deref();
1315                cfg.output_gate = *output_gate;
1316                cfg.bias = bias
1317                    .as_ref()
1318                    .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice()));
1319                attention::qwen_attention(&self.ws.n1, wq, wk, wv, wo, &mut m.kv, &cfg)
1320            }
1321            AttnKind::Linear(_) | AttnKind::LinearGdn(_) => {
1322                unreachable!("MTP block is full attention")
1323            }
1324        };
1325        for (i, &a) in attn.iter().enumerate() {
1326            x[i] += a;
1327        }
1328        inference::rms_norm_into(&x, &lw.post_norm, self.rms_eps, self.norm_style, &mut self.ws.p1);
1329        let ffn = ffn_forward(&lw.ffn, &self.ws.p1, self.pool.as_deref());
1330        for (i, &f) in ffn.iter().enumerate() {
1331            x[i] += f;
1332        }
1333
1334        inference::rms_norm_into(&x, &m.final_norm, self.rms_eps, self.norm_style, &mut self.ws.n1);
1335        let mut lg = self.lm_head_forward(&self.ws.n1);
1336        let draft = sampler::argmax(&lg);
1337        attention::recycle_buf(&mut lg);
1338        draft
1339    }
1340
1341    /// Micro-benchmark: two single-position forwards vs one fused pair
1342    /// from the current cache state (KV rewound after each probe).
1343    /// Returns (two_singles_ms, fused_pair_ms) per probe.
1344    pub fn measure_pair_fusion(&mut self, iters: usize) -> (f64, f64) {
1345        let emb1 = self.embed_single(1);
1346        let emb2 = self.embed_single(2);
1347        let pos = self.kv_cache.seq_len();
1348
1349        let t0 = std::time::Instant::now();
1350        for _ in 0..iters {
1351            let _ = self.forward_layers(&emb1, pos, None);
1352            let _ = self.forward_layers(&emb2, pos + 1, None);
1353            for l in &mut self.kv_cache.layers {
1354                l.truncate_last(2);
1355            }
1356        }
1357        let singles_ms = t0.elapsed().as_secs_f64() * 1000.0 / iters as f64;
1358
1359        let t1 = std::time::Instant::now();
1360        for _ in 0..iters {
1361            let _ = self.forward_pair(&emb1, &emb2, pos);
1362            for l in &mut self.kv_cache.layers {
1363                l.truncate_last(2);
1364            }
1365        }
1366        let pair_ms = t1.elapsed().as_secs_f64() * 1000.0 / iters as f64;
1367        (singles_ms, pair_ms)
1368    }
1369
1370    /// Fused two-position forward: weight rows are streamed from memory
1371    /// once per layer for both positions. Full layers → fused GQA pair;
1372    /// linear layers → vmf_phase pair (lane 2 state is tentative in the
1373    /// per-layer scratch until the draft is accepted).
1374    fn forward_pair(&mut self, emb1: &[f32], emb2: &[f32], position: usize) -> (Vec<f32>, Vec<f32>) {
1375        let mut h1 = emb1.to_vec();
1376        let mut h2 = emb2.to_vec();
1377        let (nh, _nkv, _hd, hs, _rd, eps) = (
1378            self.num_heads,
1379            self.num_kv_heads,
1380            self.head_dim,
1381            self.hidden_size,
1382            self.rotary_dim,
1383            self.rms_eps,
1384        );
1385        let pool = self.pool.clone();
1386
1387        for li in 0..self.num_layers {
1388            let lw = &self.weights.layers[li];
1389            // Norms into pipeline scratch (4 allocs/layer on the MTP
1390            // decode hot path before this).
1391            inference::rms_norm_into(&h1, &lw.input_norm, self.rms_eps, self.norm_style, &mut self.ws.n1);
1392            inference::rms_norm_into(&h2, &lw.input_norm, self.rms_eps, self.norm_style, &mut self.ws.n2);
1393
1394            let (a1, a2) = match &lw.attn {
1395                AttnKind::Linear(w) => {
1396                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
1397                    let layer = &mut self.kv_cache.layers[li];
1398                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
1399                    vmf_phase_pair(&self.ws.n1, &self.ws.n2, w, &cfg, state, scratch, self.pool.as_deref())
1400                }
1401                AttnKind::LinearGdn(w) => {
1402                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
1403                    let layer = &mut self.kv_cache.layers[li];
1404                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
1405                    gdn_pair(&self.ws.n1, &self.ws.n2, w, &cfg, state, scratch, self.pool.as_deref())
1406                }
1407                AttnKind::Full {
1408                    wq,
1409                    wk,
1410                    wv,
1411                    wo,
1412                    q_norm,
1413                    k_norm,
1414                    output_gate,
1415                    bias,
1416                } => {
1417                    let inv_freq_l = self.layer_inv_freq(li);
1418                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
1419                    let cfg = QwenAttnCfg {
1420                        num_heads: nh,
1421                        num_kv_heads: nkv_l,
1422                        head_dim: hd_l,
1423                        hidden_size: hs,
1424                        position,
1425                        inv_freq: &inv_freq_l,
1426                        rotary_dim: rd_l,
1427                        scale: self.attn_scale,
1428                        window: self.layer_window(li),
1429                        v_norm: self.attn_v_norm,
1430                        q_norm: q_norm.as_deref(),
1431                        k_norm: k_norm.as_deref(),
1432                        output_gate: *output_gate,
1433                        bias: bias
1434                            .as_ref()
1435                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
1436                        rms_eps: eps,
1437                        norm_style: self.norm_style,
1438                        pool: pool.as_deref(),
1439                    };
1440                    attention::qwen_attention_pair(
1441                        &self.ws.n1,
1442                        &self.ws.n2,
1443                        wq,
1444                        wk,
1445                        wv,
1446                        wo,
1447                        &mut self.kv_cache.layers[li],
1448                        &cfg,
1449                    )
1450                }
1451            };
1452            let (a1, a2) = match &self.weights.layers[li].attn_out_norm {
1453                Some(w) => (
1454                    inference::rms_norm(&a1, w, self.rms_eps, self.norm_style),
1455                    inference::rms_norm(&a2, w, self.rms_eps, self.norm_style),
1456                ),
1457                None => (a1, a2),
1458            };
1459            for i in 0..self.hidden_size {
1460                h1[i] += a1[i];
1461                h2[i] += a2[i];
1462            }
1463            let (mut a1, mut a2) = (a1, a2);
1464            attention::recycle_buf(&mut a1);
1465            attention::recycle_buf(&mut a2);
1466
1467            let lw = &self.weights.layers[li];
1468            inference::rms_norm_into(&h1, &lw.post_norm, self.rms_eps, self.norm_style, &mut self.ws.p1);
1469            inference::rms_norm_into(&h2, &lw.post_norm, self.rms_eps, self.norm_style, &mut self.ws.p2);
1470            let (f1, f2) =
1471                ffn_forward_pair(&lw.ffn, &self.ws.p1, &self.ws.p2, self.pool.as_deref());
1472            let (f1, f2) = match &self.weights.layers[li].ffn_out_norm {
1473                Some(w) => (
1474                    inference::rms_norm(&f1, w, self.rms_eps, self.norm_style),
1475                    inference::rms_norm(&f2, w, self.rms_eps, self.norm_style),
1476                ),
1477                None => (f1, f2),
1478            };
1479            for i in 0..self.hidden_size {
1480                h1[i] += f1[i];
1481                h2[i] += f2[i];
1482            }
1483            let (mut f1, mut f2) = (f1, f2);
1484            attention::recycle_buf(&mut f1);
1485            attention::recycle_buf(&mut f2);
1486            if let Some(sc) = self.weights.layers[li].layer_scale {
1487                for i in 0..self.hidden_size {
1488                    h1[i] *= sc;
1489                    h2[i] *= sc;
1490                }
1491            }
1492        }
1493        (h1, h2)
1494    }
1495
1496    /// Commit lane-2 linear states after an accepted draft.
1497    fn commit_linear_scratch(&mut self) {
1498        for layer in &mut self.kv_cache.layers {
1499            if !layer.linear_scratch.is_empty() {
1500                std::mem::swap(&mut layer.linear_state, &mut layer.linear_scratch);
1501                layer.linear_scratch.clear();
1502            }
1503        }
1504    }
1505
1506    /// Forward a full id sequence from a fresh cache and return the
1507    /// logits after the last position (golden-parity harness, bench).
1508    pub fn forward_ids(
1509        &mut self,
1510        ids: &[u32],
1511        task_mask: Option<&TaskMask>,
1512    ) -> Result<Vec<f32>, String> {
1513        if ids.is_empty() {
1514            return Err("empty id sequence".to_string());
1515        }
1516        self.kv_cache.clear();
1517        self.o1_begin();
1518        let mut hidden = vec![0.0f32; self.hidden_size];
1519        let mut pos = 0usize;
1520        if task_mask.is_none() && prefill_batched() && ids.len() > 2 {
1521            // prefill-GEMM in chunks; only the last position's hidden is
1522            // needed. (o1-compatible: the batch path attends per position
1523            // through qwen_attention, which carries the collection hook.)
1524            let chunk = prefill_chunk();
1525            let hs = self.hidden_size;
1526            while pos < ids.len() {
1527                let end = (pos + chunk).min(ids.len());
1528                let hb = self.prefill_batch(&ids[pos..end], pos);
1529                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
1530                pos = end;
1531            }
1532        }
1533        if task_mask.is_none() {
1534            while pos + 1 < ids.len() {
1535                let e1 = self.embed_single(ids[pos]);
1536                let e2 = self.embed_single(ids[pos + 1]);
1537                let (_, h2) = self.forward_pair(&e1, &e2, pos);
1538                self.commit_linear_scratch();
1539                hidden = h2;
1540                pos += 2;
1541            }
1542        }
1543        while pos < ids.len() {
1544            hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, task_mask);
1545            pos += 1;
1546        }
1547        // Harness contract: after forward_ids the cache is decode-ready —
1548        // under o1 that means sealed (bench measures the seal as part of
1549        // prefill, honestly).
1550        self.o1_seal();
1551        let normed = inference::rms_norm(
1552            &hidden,
1553            &self.weights.final_norm,
1554            self.rms_eps,
1555            self.norm_style,
1556        );
1557        Ok(self.lm_head_forward(&normed))
1558    }
1559
1560    /// Teacher-forced perplexity over a token sequence (phase-C gate:
1561    /// honest quant comparisons instead of prompt vibes).
1562    ///
1563    /// Attention is EXACT even on a model whose layers are flagged for
1564    /// the O(1) kernel — scoring the backbone is the default on purpose
1565    /// (it is the yardstick). `nll_ids_o1` scores the CONVERTED model.
1566    pub fn ppl_ids(&mut self, ids: &[u32]) -> f64 {
1567        let (nll, cnt) = self.nll_ids_from(ids, 0);
1568        (nll / cnt.max(1) as f64).exp()
1569    }
1570
1571    /// DTG-MA calibration pass (Patent 2): run `ids` through the model
1572    /// (CPU path, per position) and return each layer's per-neuron
1573    /// activation mass Σ|silu(gate)·up| — the statistic the task-guided
1574    /// FFN mask is derived from.
1575    pub fn probe_ffn_mass(&mut self, ids: &[u32]) -> Vec<Vec<f64>> {
1576        self.kv_cache.clear();
1577        FFN_PROBE.with(|p| {
1578            *p.borrow_mut() =
1579                Some(vec![vec![0f64; self.intermediate_size]; self.num_layers]);
1580        });
1581        crate::gpu::cpu_scope(|| {
1582            for (pos, &id) in ids.iter().enumerate() {
1583                let emb = self.embed_single(id);
1584                let _ = self.forward_layers(&emb, pos, None);
1585            }
1586        });
1587        self.kv_cache.clear();
1588        FFN_PROBE.with(|p| p.borrow_mut().take()).unwrap_or_default()
1589    }
1590
1591    /// Teacher-forced PPL with a task mask active (sparse execution) —
1592    /// the quality gate for a DTG-MA-masked skill. Sequential per
1593    /// position: the batched prefill path is dense-only.
1594    pub fn ppl_ids_masked(&mut self, ids: &[u32], mask: &TaskMask) -> f64 {
1595        self.kv_cache.clear();
1596        let mut nll = 0f64;
1597        let mut cnt = 0usize;
1598        let mut hidden = vec![0f32; self.hidden_size];
1599        for (pos, &id) in ids.iter().enumerate() {
1600            if pos > 0 {
1601                inference::rms_norm_into(
1602                    &hidden,
1603                    &self.weights.final_norm,
1604                    self.rms_eps,
1605                    self.norm_style,
1606                    &mut self.ws.n1,
1607                );
1608                let mut logits = self.lm_head_forward(&self.ws.n1);
1609                let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
1610                let sum: f64 = logits.iter().map(|&v| ((v - max) as f64).exp()).sum();
1611                let p = ((logits[id as usize] - max) as f64).exp() / sum.max(1e-300);
1612                nll -= p.max(1e-300).ln();
1613                cnt += 1;
1614                attention::recycle_buf(&mut logits);
1615            }
1616            let emb = self.embed_single(id);
1617            hidden = self.forward_layers(&emb, pos, Some(mask));
1618        }
1619        self.kv_cache.clear();
1620        (nll / cnt.max(1) as f64).exp()
1621    }
1622
1623    /// Teacher-forced NLL sum + scored-token count over positions
1624    /// `start..len-1`, attention EXACT. Positions below `start` still
1625    /// run — they are the context — they are just not scored, so this
1626    /// pairs with `nll_ids_o1(ids, start)` over the very same tokens.
1627    ///
1628    /// Returning (nll, cnt) rather than a ppl is what lets a windowed
1629    /// caller combine windows before the exp, so every scored token
1630    /// weighs the same regardless of how the windows are cut.
1631    pub fn nll_ids_from(&mut self, ids: &[u32], start: usize) -> (f64, usize) {
1632        self.kv_cache.clear();
1633        let mut nll = 0f64;
1634        let mut cnt = 0usize;
1635        if prefill_batched() {
1636            // prefill-GEMM: layer-major position chunks, lm_head batched
1637            // (254MB lm_head read once per chunk, not per position).
1638            // The layer chunk is large (grouping positions by MoE experts
1639            // wins with size), lm_head in sub-blocks (logit buffer
1640            // 32×vocab ≈ 32MB instead of 128×).
1641            const CHUNK: usize = 128;
1642            const LM_SUB: usize = 32;
1643            let n = ids.len().saturating_sub(1);
1644            let hs = self.hidden_size;
1645            let rows = self.weights.lm_head.rows();
1646            let mut pos = 0usize;
1647            while pos < n {
1648                let end = (pos + CHUNK).min(n);
1649                let bsz = end - pos;
1650                let hb = self.prefill_batch(&ids[pos..end], pos);
1651                let mut k0 = 0usize;
1652                while k0 < bsz {
1653                    let k1 = (k0 + LM_SUB).min(bsz);
1654                    let sb = k1 - k0;
1655                    // Sub-block entirely below the scored range: the KV
1656                    // it just built is all this pass needed from it.
1657                    if pos + k1 <= start {
1658                        k0 = k1;
1659                        continue;
1660                    }
1661                    let mut normed = vec![0.0f32; sb * hs];
1662                    for k in 0..sb {
1663                        let r = inference::rms_norm(
1664                            &hb[(k0 + k) * hs..(k0 + k + 1) * hs],
1665                            &self.weights.final_norm,
1666                            self.rms_eps,
1667                            self.norm_style,
1668                        );
1669                        normed[k * hs..(k + 1) * hs].copy_from_slice(&r);
1670                    }
1671                    let mut logits = vec![0.0f32; sb * rows];
1672                    self.weights
1673                        .lm_head
1674                        .matmat(&normed, sb, &mut logits, self.pool.as_deref());
1675                    for k in 0..sb {
1676                        if pos + k0 + k < start {
1677                            continue;
1678                        }
1679                        let lg = &logits[k * rows..k * rows + self.vocab_size.min(rows)];
1680                        let target = ids[pos + k0 + k + 1] as usize;
1681                        let max = lg.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
1682                        let lse: f64 = lg
1683                            .iter()
1684                            .map(|&v| ((v - max) as f64).exp())
1685                            .sum::<f64>()
1686                            .ln()
1687                            + max as f64;
1688                        nll += lse - lg[target] as f64;
1689                        cnt += 1;
1690                    }
1691                    k0 = k1;
1692                }
1693                pos = end;
1694            }
1695            self.kv_cache.clear();
1696            return (nll, cnt);
1697        }
1698        for pos in 0..ids.len().saturating_sub(1) {
1699            let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
1700            if pos < start {
1701                continue;
1702            }
1703            let normed = inference::rms_norm(
1704                &hidden,
1705                &self.weights.final_norm,
1706                self.rms_eps,
1707                self.norm_style,
1708            );
1709            let logits = self.lm_head_forward(&normed);
1710            let target = ids[pos + 1] as usize;
1711            let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
1712            let lse: f64 = logits.iter().map(|&v| ((v - max) as f64).exp()).sum::<f64>().ln()
1713                + max as f64;
1714            nll += lse - logits[target] as f64;
1715            cnt += 1;
1716        }
1717        self.kv_cache.clear();
1718        (nll, cnt)
1719    }
1720
1721    /// Teacher-forced NLL of the CONVERTED model: the O(1) Nyström path
1722    /// is ACTIVE over the scored positions. Returns (nll sum, scored
1723    /// count) over `prefill..len-1`.
1724    ///
1725    /// Runtime discipline, deliberately NOT the matrix probe's: the
1726    /// first `prefill` tokens run the exact prompt pass — that pass is
1727    /// what freezes the landmarks and M — and every scored position then
1728    /// goes through `NystromState::step()`, the same code decode runs.
1729    /// So the landmarks are PREFILL-frozen (what ships), not
1730    /// full-sequence oracles (what the published probe measured), and
1731    /// every scored row carries a real far field rather than sitting
1732    /// inside the exact window.
1733    ///
1734    /// Pair with `nll_ids_from(ids, prefill)` for the exact baseline
1735    /// over the identical token set — that ratio is the honest one.
1736    pub fn nll_ids_o1(&mut self, ids: &[u32], prefill: usize) -> (f64, usize) {
1737        self.kv_cache.clear();
1738        self.o1_begin();
1739        let n = ids.len().saturating_sub(1);
1740        let p = prefill.min(n);
1741        // Exact prompt pass over ids[..p]: the seal consumes its q/k/v.
1742        let mut pos = 0usize;
1743        if prefill_batched() {
1744            const CHUNK: usize = 128;
1745            while pos < p {
1746                let end = (pos + CHUNK).min(p);
1747                let _ = self.prefill_batch(&ids[pos..end], pos);
1748                pos = end;
1749            }
1750        } else {
1751            while pos < p {
1752                let _ = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
1753                pos += 1;
1754            }
1755        }
1756        self.o1_seal();
1757
1758        let mut nll = 0f64;
1759        let mut cnt = 0usize;
1760        for pos in p..n {
1761            let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
1762            let normed = inference::rms_norm(
1763                &hidden,
1764                &self.weights.final_norm,
1765                self.rms_eps,
1766                self.norm_style,
1767            );
1768            let logits = self.lm_head_forward(&normed);
1769            let target = ids[pos + 1] as usize;
1770            let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
1771            let lse: f64 = logits.iter().map(|&v| ((v - max) as f64).exp()).sum::<f64>().ln()
1772                + max as f64;
1773            nll += lse - logits[target] as f64;
1774            cnt += 1;
1775        }
1776        self.kv_cache.clear();
1777        (nll, cnt)
1778    }
1779
1780    /// Teacher-forced calibration data (B1): for each position, whether the
1781    /// argmax equals the actual next token, and the top-1 softmax prob
1782    /// (Born mass) under EACH temperature in `temps` — all from ONE forward
1783    /// pass (argmax/correctness are temperature-invariant; only p_max
1784    /// reshapes). Feeds `cortiq calibrate` (reliability/ECE + temperature
1785    /// fit): is the model's confidence a true property, or does it need a
1786    /// measured scaling?
1787    pub fn calib_ids(&mut self, ids: &[u32], temps: &[f32]) -> (Vec<bool>, Vec<Vec<f32>>) {
1788        self.kv_cache.clear();
1789        let n = ids.len().saturating_sub(1);
1790        let mut correct = Vec::with_capacity(n);
1791        let mut pmax = Vec::with_capacity(n);
1792        for pos in 0..n {
1793            let emb = self.embed_single(ids[pos]);
1794            let hidden = self.forward_layers(&emb, pos, None);
1795            let normed = inference::rms_norm(
1796                &hidden,
1797                &self.weights.final_norm,
1798                self.rms_eps,
1799                self.norm_style,
1800            );
1801            let logits = self.lm_head_forward(&normed);
1802            let target = ids[pos + 1] as usize;
1803            let (mut amax, mut mval) = (0usize, f32::NEG_INFINITY);
1804            for (i, &v) in logits.iter().enumerate() {
1805                if v > mval {
1806                    mval = v;
1807                    amax = i;
1808                }
1809            }
1810            correct.push(amax == target);
1811            let row: Vec<f32> = temps
1812                .iter()
1813                .map(|&t| {
1814                    let tt = t.max(1e-3);
1815                    let s: f32 = logits.iter().map(|&v| ((v - mval) / tt).exp()).sum();
1816                    1.0 / s.max(1e-12) // numerator at the max is exp(0)=1
1817                })
1818                .collect();
1819            pmax.push(row);
1820        }
1821        self.kv_cache.clear();
1822        (correct, pmax)
1823    }
1824
1825    /// Teacher-forced PPL with the dynamic router driving per-window
1826    /// skill switches (VMF experiment №2 measurement). Sequential (φ
1827    /// must update per token), returns (ppl, switch_count). The router
1828    /// must be enabled (`enable_dynamic_routing`); else this equals
1829    /// plain `ppl_ids`. The active skill when scoring token t shapes the
1830    /// logits for t+1 — on-policy over the held-out text itself.
1831    pub fn ppl_ids_dynamic(&mut self, ids: &[u32]) -> (f64, usize) {
1832        let mut router = match self.dyn_router.take() {
1833            Some(r) => r,
1834            None => return (self.ppl_ids(ids), 0),
1835        };
1836        router.reset();
1837        self.dyn_phi_seen = 0;
1838        let _ = self.set_active_skill(None);
1839
1840        self.kv_cache.clear();
1841        let mut nll = 0f64;
1842        let mut cnt = 0usize;
1843        for pos in 0..ids.len().saturating_sub(1) {
1844            let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
1845            let normed = inference::rms_norm(
1846                &hidden,
1847                &self.weights.final_norm,
1848                self.rms_eps,
1849                self.norm_style,
1850            );
1851            let logits = self.lm_head_forward(&normed);
1852            let target = ids[pos + 1] as usize;
1853            let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
1854            let lse: f64 = logits.iter().map(|&v| ((v - max) as f64).exp()).sum::<f64>().ln()
1855                + max as f64;
1856            nll += lse - logits[target] as f64;
1857            cnt += 1;
1858            // Route on the evolving φ (drives the NEXT token's skill).
1859            let phi = self.dyn_phi_ema.clone();
1860            if let Some(new_active) = router.step(&phi, pos) {
1861                let _ = self.set_active_skill(new_active);
1862            }
1863        }
1864        let switches = router.switches.len();
1865        let _ = self.set_active_skill(None);
1866        self.dyn_router = Some(router);
1867        self.kv_cache.clear();
1868        ((nll / cnt.max(1) as f64).exp(), switches)
1869    }
1870
1871    /// Routing probe φ (spec §9): mean-pooled hidden after `layer`.
1872    pub fn probe_phi(&mut self, ids: &[u32], layer: usize) -> Vec<f32> {
1873        self.kv_cache.clear();
1874        let mut acc = vec![0f32; self.hidden_size];
1875        for (pos, &id) in ids.iter().enumerate() {
1876            let h = self.forward_layers_upto(&self.embed_single(id), pos, None, Some(layer));
1877            for (a, v) in acc.iter_mut().zip(&h) {
1878                *a += v;
1879            }
1880        }
1881        let n = ids.len().max(1) as f32;
1882        for a in acc.iter_mut() {
1883            *a /= n;
1884        }
1885        self.kv_cache.clear();
1886        acc
1887    }
1888
1889    /// Layer-major batched prefill (prefill-GEMM): full-attention —
1890    /// per-position with the existing operators (KV grows naturally,
1891    /// causality preserved), GDN projections / FFN / MoE — batched
1892    /// (a weight row is read from DRAM once per chunk, not per
1893    /// position). Returns the hidden of all positions [b × hidden].
1894    fn prefill_batch(&mut self, ids: &[u32], start_pos: usize) -> Vec<f32> {
1895        let b = ids.len();
1896        let hs = self.hidden_size;
1897        let mut h: Vec<f32> = Vec::with_capacity(b * hs);
1898        for &id in ids {
1899            h.extend_from_slice(&self.embed_single(id));
1900        }
1901        let (nh, _nkv, _hd, _rd, eps) = (
1902            self.num_heads,
1903            self.num_kv_heads,
1904            self.head_dim,
1905            self.rotary_dim,
1906            self.rms_eps,
1907        );
1908        let pool = self.pool.clone();
1909        let norm_style = self.norm_style;
1910
1911        #[cfg(target_os = "macos")]
1912        let mut chunk_skip_until = 0usize;
1913        for li in 0..self.num_layers {
1914            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU
1915            // GPU chunk graph (default-on under CMF_GPU=1): a run of
1916            // consecutive eligible layers for the whole chunk in ONE
1917            // Metal submission — norm, QKV, RoPE with fused mirror
1918            // append, causal attend, O, FFN, hidden device-resident
1919            // across the run. Any refusal falls through to the CPU path.
1920            #[cfg(target_os = "macos")]
1921            {
1922                if li < chunk_skip_until {
1923                    continue;
1924                }
1925                let end = self.chunk_run_gpu(li, &mut h, b, start_pos);
1926                if end > li {
1927                    chunk_skip_until = end;
1928                    continue;
1929                }
1930            }
1931            let lw = &self.weights.layers[li];
1932            // ── attention ──
1933            match &lw.attn {
1934                AttnKind::LinearGdn(w) => {
1935                    // Projections batched, recurrence sequential.
1936                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
1937                    let mut normed = vec![0.0f32; b * hs];
1938                    for bi in 0..b {
1939                        let r = inference::rms_norm(
1940                            &h[bi * hs..(bi + 1) * hs], &lw.input_norm, eps, norm_style);
1941                        normed[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
1942                    }
1943                    let attn = crate::linear_core::gdn_forward_batch(
1944                        &normed, b, w, &cfg,
1945                        &mut self.kv_cache.layers[li].linear_state,
1946                        pool.as_deref(),
1947                    );
1948                    for (dst, &a) in h.iter_mut().zip(&attn) {
1949                        *dst += a;
1950                    }
1951                }
1952                AttnKind::Full {
1953                    wq, wk, wv, wo, q_norm, k_norm, output_gate, bias,
1954                } => {
1955                    // Chunk-GEMM QKV/O; per-position causal attention
1956                    // inside (roadmap §3 P0 — full-attention prefill no
1957                    // longer re-reads the projection weights b times).
1958                    let mut normed = vec![0.0f32; b * hs];
1959                    for bi in 0..b {
1960                        inference::rms_norm_into(
1961                            &h[bi * hs..(bi + 1) * hs],
1962                            &lw.input_norm,
1963                            eps,
1964                            norm_style,
1965                            &mut normed[bi * hs..(bi + 1) * hs],
1966                        );
1967                    }
1968                    let inv_freq_l = self.layer_inv_freq(li);
1969                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
1970                    let cfg = QwenAttnCfg {
1971                        num_heads: nh,
1972                        num_kv_heads: nkv_l,
1973                        head_dim: hd_l,
1974                        hidden_size: hs,
1975                        position: start_pos,
1976                        inv_freq: &inv_freq_l,
1977                        rotary_dim: rd_l,
1978                        scale: self.attn_scale,
1979                        window: self.layer_window(li),
1980                        v_norm: self.attn_v_norm,
1981                        q_norm: q_norm.as_deref(),
1982                        k_norm: k_norm.as_deref(),
1983                        output_gate: *output_gate,
1984                        bias: bias.as_ref().map(|(a, b, c)| {
1985                            (a.as_slice(), b.as_slice(), c.as_slice())
1986                        }),
1987                        rms_eps: eps,
1988                        norm_style,
1989                        pool: pool.as_deref(),
1990                    };
1991                    let mut attn = attention::qwen_attention_batch(
1992                        &normed, b, wq, wk, wv, wo,
1993                        &mut self.kv_cache.layers[li], &cfg);
1994                    if let Some(w) = &lw.attn_out_norm {
1995                        for bi in 0..b {
1996                            inference::rms_norm_into(
1997                                &attn[bi * hs..(bi + 1) * hs], w, eps, norm_style,
1998                                &mut normed[bi * hs..(bi + 1) * hs]);
1999                        }
2000                        attn.copy_from_slice(&normed);
2001                    }
2002                    for (dst, &a) in h.iter_mut().zip(&attn) {
2003                        *dst += a;
2004                    }
2005                }
2006                AttnKind::Linear(w) => {
2007                    for bi in 0..b {
2008                        let normed = inference::rms_norm(
2009                            &h[bi * hs..(bi + 1) * hs], &lw.input_norm, eps, norm_style);
2010                        vmf_phase_forward(
2011                            &normed, w,
2012                            &self.vmf_cfg.expect("linear layer without vmf_cfg"),
2013                            &mut self.kv_cache.layers[li].linear_state,
2014                            pool.as_deref(),
2015                        )
2016                        .iter()
2017                        .enumerate()
2018                        .for_each(|(i, &a)| h[bi * hs + i] += a);
2019                    }
2020                }
2021            }
2022
2023            // ── FFN batched ──
2024            let lw = &self.weights.layers[li];
2025            let mut post = vec![0.0f32; b * hs];
2026            for bi in 0..b {
2027                let r = inference::rms_norm(
2028                    &h[bi * hs..(bi + 1) * hs], &lw.post_norm, eps, norm_style);
2029                post[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
2030            }
2031            let mut ffn = match &lw.ffn {
2032                FfnKind::Dense(d) => dense_ffn_batch(d, &post, b, pool.as_deref()),
2033                FfnKind::Moe(m) => moe_ffn_batch(m, &post, b, hs, pool.as_deref()),
2034            };
2035            if let Some(w) = &lw.ffn_out_norm {
2036                for bi in 0..b {
2037                    inference::rms_norm_into(
2038                        &ffn[bi * hs..(bi + 1) * hs], w, eps, norm_style,
2039                        &mut post[bi * hs..(bi + 1) * hs]);
2040                }
2041                ffn.copy_from_slice(&post);
2042            }
2043            for (dst, &f) in h.iter_mut().zip(&ffn) {
2044                *dst += f;
2045            }
2046            if let Some(sc) = lw.layer_scale {
2047                for v in h.iter_mut() {
2048                    *v *= sc;
2049                }
2050            }
2051            if std::env::var("CMF_TRACE_H").is_ok() {
2052                let n = h[..hs].iter().map(|v| v.abs()).sum::<f32>() / hs as f32;
2053                let mx = h[..hs].iter().fold(0.0f32, |a, &v| a.max(v.abs()));
2054                eprintln!("layer {li}: mean|h|={n:.4} max|h|={mx:.2} scale={:?}", lw.layer_scale);
2055            }
2056        }
2057        crate::gpu::set_layer(-1); // lm_head/final ops outside layer-split
2058        h
2059    }
2060
2061    /// Embed a single token.
2062    fn embed_single(&self, id: u32) -> Vec<f32> {
2063        let mut out = vec![0.0f32; self.hidden_size];
2064        if (id as usize) < self.weights.embed_tokens.rows() {
2065            self.weights.embed_tokens.row_f32(id as usize, &mut out);
2066        }
2067        if self.embed_multiplier != 1.0 {
2068            for v in out.iter_mut() {
2069                *v *= self.embed_multiplier;
2070            }
2071        }
2072        out
2073    }
2074
2075    /// A run of consecutive prefill layers on the GPU for the whole
2076    /// chunk (default-on under CMF_GPU=1; CMF_GPU_CHUNK=0 disables).
2077    /// Eligibility per layer: q8_row weights, plain full attention
2078    /// (no output gate), F32 KV, no o1/masks/gemma extras. Returns the
2079    /// first layer index NOT processed (== `li0` when the run is empty).
2080    #[cfg(target_os = "macos")]
2081    fn chunk_run_gpu(&mut self, li0: usize, h: &mut [f32], b: usize, pos0: usize) -> usize {
2082        // (The old streaming attend needed a depth bound at ~1k; the
2083        // GEMM attention scales like the CPU path and lifted it.)
2084        // CMF_GPU_CHUNK=0 disables the graph.
2085        if !crate::gpu::enabled_here()
2086            || std::env::var("CMF_GPU_CHUNK").map(|v| v == "0").unwrap_or(false)
2087            || b < 32
2088            || self.swa.is_some()
2089            || self.global_attn.is_some()
2090            || self.attn_v_norm
2091            || (self.attn_scale - 1.0 / (self.head_dim as f32).sqrt()).abs() > 1e-9
2092        {
2093            return li0;
2094        }
2095        let Some(model) = self.model.clone() else { return li0 };
2096        let inv_freq = self.inv_freq.clone();
2097        let (nh, nkv, hd, hs) = (self.num_heads, self.num_kv_heads, self.head_dim, self.hidden_size);
2098        // Collect the longest run of consecutive eligible layers.
2099        let mut layers: Vec<crate::gpu_metal::ChunkLayer> = Vec::new();
2100        let mut stored_at: Vec<usize> = Vec::new();
2101        for li in li0..self.num_layers {
2102            let lw = &self.weights.layers[li];
2103            if lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some()
2104            {
2105                break;
2106            }
2107            let AttnKind::Full { wq, wk, wv, wo, q_norm, k_norm, output_gate: false, bias } =
2108                &lw.attn
2109            else {
2110                break;
2111            };
2112            let FfnKind::Dense(d) = &lw.ffn else { break };
2113            if d.act != Act::Silu {
2114                break;
2115            }
2116            let parts = (
2117                wq.q8_row_parts(),
2118                wk.q8_row_parts(),
2119                wv.q8_row_parts(),
2120                wo.q8_row_parts(),
2121                d.gate_proj.q8_row_parts(),
2122                d.up_proj.q8_row_parts(),
2123                d.down_proj.q8_row_parts(),
2124            );
2125            let (Some(pq), Some(pk), Some(pv), Some(po), Some(pg), Some(pu), Some(pd)) = parts
2126            else {
2127                break;
2128            };
2129            let layer = &self.kv_cache.layers[li];
2130            if layer.mode != crate::kv_cache::KvMode::F32 || layer.o1.is_some() {
2131                break;
2132            }
2133            stored_at.push(layer.head_len(0));
2134            layers.push(crate::gpu_metal::ChunkLayer {
2135                model: &model,
2136                kv_id: self.graph_kv_id,
2137                layer: li,
2138                wq: pq,
2139                wk: pk,
2140                wv: pv,
2141                wo: po,
2142                gate: pg,
2143                up: pu,
2144                down: pd,
2145                input_norm: &lw.input_norm,
2146                post_norm: &lw.post_norm,
2147                bias: bias
2148                    .as_ref()
2149                    .map(|(a, bb, cc)| (a.as_slice(), bb.as_slice(), cc.as_slice())),
2150                q_norm: q_norm.as_deref(),
2151                k_norm: k_norm.as_deref(),
2152                inv_freq: &inv_freq,
2153                rd: self.rotary_dim,
2154                nh,
2155                nkv,
2156                hd,
2157                hs,
2158                inter: d.gate_proj.rows(),
2159                gemma: matches!(self.norm_style, cortiq_core::NormStyle::Gemma),
2160                eps: self.rms_eps as f32,
2161            });
2162        }
2163        if layers.is_empty() {
2164            return li0;
2165        }
2166        let row = nkv * hd;
2167        let mut store: Vec<(Vec<f32>, Vec<f32>, Vec<f32>)> = stored_at
2168            .iter()
2169            .map(|&st| (vec![0f32; b * row], vec![0f32; b * row], vec![0f32; st + b]))
2170            .collect();
2171        let mut io: Vec<crate::gpu_metal::ChunkIo> = Vec::with_capacity(layers.len());
2172        for (i, (ok, ov, oi)) in store.iter_mut().enumerate() {
2173            let li = layers[i].layer;
2174            let layer = &self.kv_cache.layers[li];
2175            io.push(crate::gpu_metal::ChunkIo {
2176                cpu_stored: stored_at[i],
2177                cpu_k: (0..nkv).map(|g| layer.head_keys(g)).collect(),
2178                cpu_v: (0..nkv).map(|g| layer.head_values(g)).collect(),
2179                out_k: ok,
2180                out_v: ov,
2181                imp: oi,
2182            });
2183        }
2184        let n_run = layers.len();
2185        let last = layers.last().map(|l| l.layer + 1).unwrap_or(li0);
2186        if !crate::gpu_metal::chunk_run_gpu(&layers, &mut io, h, b, pos0) {
2187            return li0;
2188        }
2189        drop(io);
2190        drop(layers);
2191        // CPU caches stay the owners of record: append the chunk rows
2192        // and bank the importance masses per layer.
2193        for (i, (ok, ov, oi)) in store.iter().enumerate().take(n_run) {
2194            let li = li0 + i;
2195            let layer = &mut self.kv_cache.layers[li];
2196            for bi in 0..b {
2197                layer.append(&ok[bi * row..(bi + 1) * row], &ov[bi * row..(bi + 1) * row], &[]);
2198            }
2199            layer.accumulate_imp(oi);
2200        }
2201        last
2202    }
2203
2204    /// Is layer `li` a sliding-window (local-RoPE) layer? Gemma-3:
2205    /// every `pattern`-th layer is global, the rest are local.
2206    fn layer_is_local(&self, li: usize) -> bool {
2207        match self.swa {
2208            Some((_, pattern)) => (li + 1) % pattern.max(1) != 0,
2209            None => false,
2210        }
2211    }
2212
2213    /// The RoPE table for layer `li` (local layers may have their own;
2214    /// Gemma-4 global layers use the proportional padded table).
2215    fn layer_inv_freq(&self, li: usize) -> std::sync::Arc<Vec<f32>> {
2216        if self.layer_is_local(li) {
2217            if let Some(f) = &self.inv_freq_local {
2218                return f.clone();
2219            }
2220        } else if let Some(f) = &self.inv_freq_global {
2221            return f.clone();
2222        }
2223        self.inv_freq.clone()
2224    }
2225
2226    /// The attend window for layer `li` (None = full context).
2227    fn layer_window(&self, li: usize) -> Option<usize> {
2228        match self.swa {
2229            Some((w, _)) if self.layer_is_local(li) => Some(w),
2230            _ => None,
2231        }
2232    }
2233
2234    /// Attention geometry of layer `li`: (num_kv_heads, head_dim,
2235    /// rotary_dim). Gemma-4 global layers override all three.
2236    fn layer_geom(&self, li: usize) -> (usize, usize, usize) {
2237        if !self.layer_is_local(li) {
2238            if let Some((ghd, gkv)) = self.global_attn {
2239                return (gkv, ghd, ghd);
2240            }
2241        }
2242        (self.num_kv_heads, self.head_dim, self.rotary_dim)
2243    }
2244
2245    /// Forward one position through all layers (hybrid dispatch).
2246    fn forward_layers(
2247        &mut self,
2248        hidden: &[f32],
2249        position: usize,
2250        task_mask: Option<&TaskMask>,
2251    ) -> Vec<f32> {
2252        self.forward_layers_upto(hidden, position, task_mask, None)
2253    }
2254
2255    /// Same, stopping after layer `upto` inclusive (routing probe φ).
2256    fn forward_layers_upto(
2257        &mut self,
2258        hidden: &[f32],
2259        position: usize,
2260        task_mask: Option<&TaskMask>,
2261        upto: Option<usize>,
2262    ) -> Vec<f32> {
2263        let mut h = hidden.to_vec();
2264        // Split borrows: copy scalars / clone handles so the per-layer
2265        // cfg does not hold `&self` while the KV cache is `&mut`.
2266        let (nh, _nkv, _hd, hs, _rd, eps) = (
2267            self.num_heads,
2268            self.num_kv_heads,
2269            self.head_dim,
2270            self.hidden_size,
2271            self.rotary_dim,
2272            self.rms_eps,
2273        );
2274        let pool = self.pool.clone();
2275
2276        #[cfg(target_os = "macos")]
2277        let mut gpu_skip_until = 0usize;
2278        for li in 0..self.num_layers {
2279            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU (CMF_GPU_LAYERS)
2280            if let Some(u) = upto {
2281                if li > u {
2282                    break;
2283                }
2284            }
2285            if let Some(mask) = task_mask {
2286                if !mask.layer_alive(li) {
2287                    continue; // dead layer: residual pass-through
2288                }
2289            }
2290            // Whole-block q1 token graph: a run of consecutive q1
2291            // layers — GDN and full attention — executes with one sync
2292            // per CPU attend instead of per op (macOS/Metal).
2293            #[cfg(target_os = "macos")]
2294            {
2295                if li < gpu_skip_until {
2296                    continue;
2297                }
2298                if task_mask.is_none() {
2299                    let end = self.q1_graph_gpu(li, upto, position, &mut h);
2300                    if end > li {
2301                        gpu_skip_until = end;
2302                        continue;
2303                    }
2304                }
2305            }
2306
2307            let lw = &self.weights.layers[li];
2308            // Norm into the pipeline scratch — the returning rms_norm
2309            // allocated twice per layer per token (roadmap §3 P0).
2310            inference::rms_norm_into(&h, &lw.input_norm, self.rms_eps, self.norm_style, &mut self.ws.n1);
2311
2312            let attn_out = match &lw.attn {
2313                AttnKind::Linear(w) => {
2314                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
2315                    vmf_phase_forward(
2316                        &self.ws.n1,
2317                        w,
2318                        &cfg,
2319                        &mut self.kv_cache.layers[li].linear_state,
2320                        self.pool.as_deref(),
2321                    )
2322                }
2323                AttnKind::LinearGdn(w) => {
2324                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
2325                    gdn_forward(
2326                        &self.ws.n1,
2327                        w,
2328                        &cfg,
2329                        &mut self.kv_cache.layers[li].linear_state,
2330                        self.pool.as_deref(),
2331                    )
2332                }
2333                AttnKind::Full {
2334                    wq,
2335                    wk,
2336                    wv,
2337                    wo,
2338                    q_norm,
2339                    k_norm,
2340                    output_gate,
2341                    bias,
2342                } if self.kv_cache.layers[li].o1_sealed() => {
2343                    // O(1) override: decode on the sealed Nyström state
2344                    // instead of the growing KV cache.
2345                    let inv_freq_l = self.layer_inv_freq(li);
2346                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
2347                    let cfg = QwenAttnCfg {
2348                        num_heads: nh,
2349                        num_kv_heads: nkv_l,
2350                        head_dim: hd_l,
2351                        hidden_size: hs,
2352                        position,
2353                        inv_freq: &inv_freq_l,
2354                        rotary_dim: rd_l,
2355                        scale: self.attn_scale,
2356                        window: None,
2357                        v_norm: self.attn_v_norm,
2358                        q_norm: q_norm.as_deref(),
2359                        k_norm: k_norm.as_deref(),
2360                        output_gate: *output_gate,
2361                        bias: bias
2362                            .as_ref()
2363                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
2364                        rms_eps: eps,
2365                        norm_style: self.norm_style,
2366                        pool: pool.as_deref(),
2367                    };
2368                    attention::qwen_attention_nystrom(
2369                        &self.ws.n1,
2370                        wq,
2371                        wk,
2372                        wv,
2373                        wo,
2374                        &mut self.kv_cache.layers[li],
2375                        &cfg,
2376                    )
2377                }
2378                AttnKind::Full {
2379                    wq,
2380                    wk,
2381                    wv,
2382                    wo,
2383                    q_norm,
2384                    k_norm,
2385                    output_gate,
2386                    bias,
2387                } => {
2388                    let masked = task_mask
2389                        .map(|m| m.head_flags(li, self.num_heads).iter().any(|&a| !a))
2390                        .unwrap_or(false);
2391                    let f32_view = (wq.as_f32(), wk.as_f32(), wv.as_f32(), wo.as_f32());
2392                    match (masked, f32_view) {
2393                        // Historical masked path (f32 slices; the loader
2394                        // keeps masked models in f32).
2395                        (true, (Some(q), Some(k), Some(v), Some(o))) => {
2396                            let active_heads = task_mask.unwrap().head_flags(li, self.num_heads);
2397                            attention::multi_head_attention(
2398                                &self.ws.n1,
2399                                q,
2400                                k,
2401                                v,
2402                                o,
2403                                &mut self.kv_cache.layers[li],
2404                                self.num_heads,
2405                                self.num_kv_heads,
2406                                self.head_dim,
2407                                self.hidden_size,
2408                                position,
2409                                &active_heads,
2410                                &self.inv_freq,
2411                            )
2412                        }
2413                        (masked, _) => {
2414                            if masked {
2415                                tracing::warn!(
2416                                    "layer {li}: head mask on quantized weights not \
2417                                     supported yet — executing dense"
2418                                );
2419                            }
2420                            let inv_freq_l = self.layer_inv_freq(li);
2421                            let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
2422                            let cfg = QwenAttnCfg {
2423                                num_heads: nh,
2424                                num_kv_heads: nkv_l,
2425                                head_dim: hd_l,
2426                                hidden_size: hs,
2427                                position,
2428                                inv_freq: &inv_freq_l,
2429                                rotary_dim: rd_l,
2430                                scale: self.attn_scale,
2431                                window: self.layer_window(li),
2432                                v_norm: self.attn_v_norm,
2433                                q_norm: q_norm.as_deref(),
2434                                k_norm: k_norm.as_deref(),
2435                                output_gate: *output_gate,
2436                        bias: bias
2437                            .as_ref()
2438                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
2439                                rms_eps: eps,
2440                                norm_style: self.norm_style,
2441                                pool: pool.as_deref(),
2442                            };
2443                            attention::qwen_attention(
2444                                &self.ws.n1,
2445                                wq,
2446                                wk,
2447                                wv,
2448                                wo,
2449                                &mut self.kv_cache.layers[li],
2450                                &cfg,
2451                            )
2452                        }
2453                    }
2454                }
2455            };
2456            // Gemma sandwich norm: normalize the attention branch before
2457            // it joins the residual stream.
2458            let attn_out = match &self.weights.layers[li].attn_out_norm {
2459                Some(w) => inference::rms_norm(&attn_out, w, self.rms_eps, self.norm_style),
2460                None => attn_out,
2461            };
2462            for (i, &a) in attn_out.iter().enumerate() {
2463                h[i] += a;
2464            }
2465            let mut attn_out = attn_out;
2466            attention::recycle_buf(&mut attn_out);
2467
2468            let lw = &self.weights.layers[li];
2469            inference::rms_norm_into(&h, &lw.post_norm, self.rms_eps, self.norm_style, &mut self.ws.p1);
2470            let post_normed = &self.ws.p1;
2471
2472            let ffn_masked = task_mask
2473                .map(|m| m.ffn_active_count(li) < self.intermediate_size)
2474                .unwrap_or(false);
2475            // Sparse mask path applies to dense f32 FFN only; MoE
2476            // layers route through the normal dispatch below.
2477            let f32_ffn = match &lw.ffn {
2478                FfnKind::Dense(d) => {
2479                    (d.gate_proj.as_f32(), d.up_proj.as_f32(), d.down_proj.as_f32())
2480                }
2481                FfnKind::Moe(_) => (None, None, None),
2482            };
2483            let ffn_out = match (ffn_masked, f32_ffn) {
2484                (true, (Some(g), Some(u), Some(d))) => {
2485                    let active = task_mask.unwrap().ffn_active_indices(li);
2486                    inference::sparse_ffn_forward(
2487                        &post_normed,
2488                        g,
2489                        u,
2490                        d,
2491                        self.hidden_size,
2492                        self.intermediate_size,
2493                        &active,
2494                        self.pool.as_deref(),
2495                    )
2496                }
2497                // Mask × quantized mmap: sparse FFN reads only active
2498                // neurons' rows/cols directly from the quant bytes — no
2499                // f32 model copy (a masked big model runs at quant RSS).
2500                (true, _) => match &lw.ffn {
2501                    FfnKind::Dense(d) if d.down_proj.sparse_col_ok() => {
2502                        let active = task_mask.unwrap().ffn_active_indices(li);
2503                        sparse_ffn_quant(
2504                            d,
2505                            &post_normed,
2506                            &active,
2507                            self.hidden_size,
2508                            self.pool.as_deref(),
2509                        )
2510                    }
2511                    // q4/vbit down_proj has no cheap column access → dequant
2512                    // the three matrices to f32 (transient) and run the f32
2513                    // sparse path. Correct (mask honored), just not
2514                    // memory-lean for those dtypes — a rare masked case.
2515                    FfnKind::Dense(d) => {
2516                        let active = task_mask.unwrap().ffn_active_indices(li);
2517                        let (gf, uf, df) = dequant_dense_f32(d);
2518                        inference::sparse_ffn_forward(
2519                            &post_normed,
2520                            &gf,
2521                            &uf,
2522                            &df,
2523                            self.hidden_size,
2524                            self.intermediate_size,
2525                            &active,
2526                            self.pool.as_deref(),
2527                        )
2528                    }
2529                    FfnKind::Moe(_) => {
2530                        // MoE is already sparse by expert selection; masks
2531                        // don't apply to routed experts.
2532                        ffn_forward(&lw.ffn, &post_normed, self.pool.as_deref())
2533                    }
2534                },
2535                (false, _) => ffn_forward(&lw.ffn, &post_normed, self.pool.as_deref()),
2536            };
2537            let ffn_out = match &self.weights.layers[li].ffn_out_norm {
2538                Some(w) => inference::rms_norm(&ffn_out, w, self.rms_eps, self.norm_style),
2539                None => ffn_out,
2540            };
2541            for (i, &f) in ffn_out.iter().enumerate() {
2542                h[i] += f;
2543            }
2544            let mut ffn_out = ffn_out;
2545            attention::recycle_buf(&mut ffn_out);
2546
2547            // Gemma-4: the layer output is scaled by a learned scalar.
2548            if let Some(sc) = self.weights.layers[li].layer_scale {
2549                for v in h.iter_mut() {
2550                    *v *= sc;
2551                }
2552            }
2553
2554            // Dynamic routing φ capture (on-policy, fireball-style): the
2555            // EMA of the post-residual hidden at the router's phi_layer,
2556            // updated as the context evolves during decode.
2557            if self.dyn_phi_layer == Some(li) {
2558                self.update_dyn_phi(&h);
2559            }
2560        }
2561        crate::gpu::set_layer(-1); // layers done — lm_head outside layer-split
2562
2563        h
2564    }
2565
2566    /// EMA of φ at the router layer (rolling, weight 0.2 = ~5-token
2567    /// horizon). First observation seeds it exactly.
2568    fn update_dyn_phi(&mut self, h: &[f32]) {
2569        const A: f32 = 0.2;
2570        if self.dyn_phi_ema.len() != h.len() {
2571            self.dyn_phi_ema = vec![0.0; h.len()];
2572            self.dyn_phi_seen = 0;
2573        }
2574        if self.dyn_phi_seen == 0 {
2575            self.dyn_phi_ema.copy_from_slice(h);
2576        } else {
2577            for (e, &v) in self.dyn_phi_ema.iter_mut().zip(h) {
2578                *e = (1.0 - A) * *e + A * v;
2579            }
2580        }
2581        self.dyn_phi_seen += 1;
2582    }
2583
2584    /// Current router φ (EMA at phi_layer); empty until first capture.
2585    pub fn dyn_phi(&self) -> &[f32] {
2586        &self.dyn_phi_ema
2587    }
2588
2589    /// Enable/disable φ capture at the router layer, reset the EMA.
2590    pub fn set_dyn_phi_layer(&mut self, layer: Option<usize>) {
2591        self.dyn_phi_layer = layer;
2592        self.dyn_phi_ema.clear();
2593        self.dyn_phi_seen = 0;
2594    }
2595
2596    /// Skills eligible for dynamic switching: (index, id, phi_layer).
2597    pub fn dynamic_skills(&self) -> Vec<(usize, String, usize)> {
2598        let Some(model) = &self.model else { return Vec::new() };
2599        model
2600            .header
2601            .skills
2602            .iter()
2603            .enumerate()
2604            .filter_map(|(i, sk)| {
2605                let ok = matches!(self.dyn_skill_layers.get(i), Some(Some(_)));
2606                let sel = sk.selection.as_ref()?;
2607                (ok).then(|| (i, sk.id.clone(), sel.phi_layer))
2608            })
2609            .collect()
2610    }
2611
2612    /// Index of the currently overlaid skill (None = backbone).
2613    pub fn active_skill(&self) -> Option<usize> {
2614        self.dyn_active
2615    }
2616
2617    /// Enable dynamic per-token skill routing: build the hysteresis
2618    /// router from the container's routable skills, start φ capture at
2619    /// their (shared) phi_layer. Returns the number of routable skills
2620    /// (0 = nothing to route; router stays off). Idempotent.
2621    pub fn enable_dynamic_routing(&mut self) -> usize {
2622        use crate::swarm::{DynRouter, RoutableSkill};
2623        let Some(model) = self.model.clone() else { return 0 };
2624        // A blend materialized f32 working tensors into the layers; there
2625        // is no single skill index to revert from → refuse (honest).
2626        if self.dyn_blend_loaded {
2627            tracing::warn!("dynamic routing unavailable on a blend-loaded pipeline");
2628            return 0;
2629        }
2630        // A statically-overlaid skill that is NOT FFN-eligible can't be
2631        // cheaply reverted at generation start → refuse rather than
2632        // silently keep it overlaid.
2633        if let Some(a) = self.dyn_active {
2634            if !matches!(self.dyn_skill_layers.get(a), Some(Some(_))) {
2635                tracing::warn!(
2636                    "loaded skill is not FFN-eligible — dynamic routing unavailable"
2637                );
2638                return 0;
2639            }
2640        }
2641        let hidden = self.hidden_size;
2642        let mut skills = Vec::new();
2643        for (idx, id, _phi) in self.dynamic_skills() {
2644            if let Some(sel) = model.header.skills[idx].selection.as_ref() {
2645                if let Some(rs) = RoutableSkill::from_descriptor(idx, id, sel, hidden) {
2646                    skills.push(rs);
2647                }
2648            }
2649        }
2650        if skills.is_empty() {
2651            return 0;
2652        }
2653        // Skills should share a phi_layer; warn (not fail) if they don't.
2654        let phi = skills[0].phi_layer;
2655        if skills.iter().any(|s| s.phi_layer != phi) {
2656            tracing::warn!("routable skills disagree on phi_layer; using {phi}");
2657        }
2658        let n = skills.len();
2659        self.set_dyn_phi_layer(Some(phi));
2660        self.dyn_router = Some(DynRouter::new(skills));
2661        n
2662    }
2663
2664    /// Human-readable switch log from the last dynamic-routed generation.
2665    pub fn route_switches(&self) -> Vec<(usize, Option<String>, Option<String>)> {
2666        self.dyn_router
2667            .as_ref()
2668            .map(|r| r.switches.clone())
2669            .unwrap_or_default()
2670    }
2671
2672    /// LM head: hidden → logits [vocab_size]. The dominant matvec of
2673    /// every decode step — row-parallel on the worker pool.
2674    fn lm_head_forward(&self, hidden: &[f32]) -> Vec<f32> {
2675        let rows = self.weights.lm_head.rows();
2676        let mut logits = attention::take_buf(rows.min(self.vocab_size));
2677        self.weights
2678            .lm_head
2679            .matvec(hidden, &mut logits, self.pool.as_deref());
2680        logits.resize(self.vocab_size, 0.0);
2681        if let Some(c) = self.final_softcap {
2682            for l in logits.iter_mut() {
2683                *l = c * (*l / c).tanh();
2684            }
2685        }
2686        logits
2687    }
2688
2689    /// Prefill `ids` and return the next-token logits — what the model
2690    /// would predict next, WITHOUT committing to generation (introspection
2691    /// for `cortiq explain`). Clears and repopulates the KV cache; leaves
2692    /// the active overlay untouched.
2693    pub fn prefill_next_logits(&mut self, ids: &[u32], task_mask: Option<&TaskMask>) -> Vec<f32> {
2694        self.kv_cache.clear();
2695        let mut hidden = vec![0.0f32; self.hidden_size];
2696        for (pos, &id) in ids.iter().enumerate() {
2697            let emb = self.embed_single(id);
2698            hidden = self.forward_layers(&emb, pos, task_mask);
2699        }
2700        inference::rms_norm_into(
2701            &hidden,
2702            &self.weights.final_norm,
2703            self.rms_eps,
2704            self.norm_style,
2705            &mut self.ws.n1,
2706        );
2707        self.lm_head_forward(&self.ws.n1)
2708    }
2709}
2710
2711/// Convenience: deterministic tiny pipeline for tests.
2712pub fn create_test_pipeline(
2713    hidden_size: usize,
2714    intermediate_size: usize,
2715    num_heads: usize,
2716    num_kv_heads: usize,
2717    head_dim: usize,
2718    num_layers: usize,
2719    vocab_size: usize,
2720) -> Pipeline {
2721    // Small pseudo-random weights: constant weights make attention
2722    // degenerate and hide indexing bugs.
2723    let synth = |n: usize, salt: usize| -> Vec<f32> {
2724        (0..n)
2725            .map(|i| (((i * 31 + salt * 17 + 7) % 97) as f32 / 97.0 - 0.5) * 0.2)
2726            .collect()
2727    };
2728    let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
2729        QTensor::from_f32(synth(rows * cols, salt), rows, cols)
2730    };
2731    let layer_weights: Vec<LayerWeights> = (0..num_layers)
2732        .map(|li| LayerWeights {
2733            input_norm: vec![1.0; hidden_size],
2734            post_norm: vec![1.0; hidden_size],
2735            attn_out_norm: None,
2736            ffn_out_norm: None,
2737            layer_scale: None,
2738            ffn: FfnKind::Dense(DenseFfn {
2739                gate_proj: qt(intermediate_size, hidden_size, li * 10 + 5),
2740                up_proj: qt(intermediate_size, hidden_size, li * 10 + 6),
2741                down_proj: qt(hidden_size, intermediate_size, li * 10 + 7),
2742                act: Act::Silu,
2743            }),
2744            attn: AttnKind::Full {
2745                bias: None,
2746                wq: qt(num_heads * head_dim, hidden_size, li * 10 + 1),
2747                wk: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 2),
2748                wv: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 3),
2749                wo: qt(hidden_size, num_heads * head_dim, li * 10 + 4),
2750                q_norm: None,
2751                k_norm: None,
2752                output_gate: false,
2753            },
2754        })
2755        .collect();
2756
2757    Pipeline::new(
2758        Tokenizer::byte_level(),
2759        PipelineWeights {
2760            embed_tokens: qt(vocab_size, hidden_size, 100),
2761            layers: layer_weights,
2762            lm_head: qt(vocab_size, hidden_size, 200),
2763            final_norm: vec![1.0; hidden_size],
2764        },
2765        hidden_size,
2766        intermediate_size,
2767        num_heads,
2768        num_kv_heads,
2769        head_dim,
2770        num_layers,
2771        vocab_size,
2772        1e-6,
2773        10_000.0,
2774        NormStyle::Qwen,
2775        4096,
2776        SamplerConfig {
2777            seed: Some(42),
2778            ..Default::default()
2779        },
2780    )
2781}
2782
2783/// Batched dense-FFN: gate/up/down via matmat (element-wise the same
2784/// math as b × dense_ffn — the same dot kernels).
2785fn dense_ffn_batch(d: &DenseFfn, xs: &[f32], b: usize, pool: Option<&Pool>) -> Vec<f32> {
2786    let inter = d.gate_proj.rows();
2787    let hidden = d.down_proj.rows();
2788    let mut g = vec![0.0f32; b * inter];
2789    d.gate_proj.matmat(xs, b, &mut g, pool);
2790    let mut u = vec![0.0f32; b * inter];
2791    d.up_proj.matmat(xs, b, &mut u, pool);
2792    for i in 0..b * inter {
2793        g[i] = d.act.apply(g[i]) * u[i];
2794    }
2795    let mut out = vec![0.0f32; b * hidden];
2796    d.down_proj.matmat(&g, b, &mut out, pool);
2797    out
2798}
2799
2800/// Batched MoE-FFN: router batched, positions are GROUPED by expert —
2801/// an expert's weights are read once for all its positions in the chunk
2802/// (the main prefill-GEMM win on MoE: 960MB/token of 35B experts).
2803fn moe_ffn_batch(m: &MoeFfn, xs: &[f32], b: usize, hidden: usize, pool: Option<&Pool>) -> Vec<f32> {
2804    let ne = m.experts.len();
2805    let mut logits = vec![0.0f32; b * ne];
2806    m.router.matmat(xs, b, &mut logits, pool);
2807
2808    // Assignments: expert → [(position, weight)] — the same top-k semantics
2809    // as moe_ffn (softmax over all, torch.topk order, optional renorm).
2810    let mut assign: Vec<Vec<(usize, f32)>> = vec![Vec::new(); ne];
2811    {
2812        let mut st = m.stats.borrow_mut();
2813        if st.len() < ne {
2814            st.resize(ne, 0);
2815        }
2816        for bi in 0..b {
2817            let lg = &logits[bi * ne..(bi + 1) * ne];
2818            let mx = lg.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
2819            let mut p: Vec<f32> = lg.iter().map(|&l| (l - mx).exp()).collect();
2820            let sum: f32 = p.iter().sum();
2821            for v in &mut p {
2822                *v /= sum;
2823            }
2824            let mut order: Vec<usize> = (0..ne).collect();
2825            order.sort_unstable_by(|&x, &y| p[y].partial_cmp(&p[x]).unwrap().then(x.cmp(&y)));
2826            order.truncate(m.top_k);
2827            let wsum: f32 = if m.norm_topk_prob {
2828                order.iter().map(|&e| p[e]).sum()
2829            } else {
2830                1.0
2831            };
2832            for &e in &order {
2833                st[e] += 1;
2834                assign[e].push((bi, p[e] / wsum));
2835            }
2836        }
2837    }
2838
2839    let mut out = vec![0.0f32; b * hidden];
2840    let cols = m.experts[0].gate_proj.cols();
2841    let mut run_expert = |d: &DenseFfn, list: &[(usize, f32)]| {
2842        let sb = list.len();
2843        let mut sub = vec![0.0f32; sb * cols];
2844        for (k, &(bi, _)) in list.iter().enumerate() {
2845            sub[k * cols..(k + 1) * cols].copy_from_slice(&xs[bi * cols..(bi + 1) * cols]);
2846        }
2847        let eo = dense_ffn_batch(d, &sub, sb, pool);
2848        for (k, &(bi, w)) in list.iter().enumerate() {
2849            for i in 0..hidden {
2850                out[bi * hidden + i] += w * eo[k * hidden + i];
2851            }
2852        }
2853    };
2854    for e in 0..ne {
2855        if !assign[e].is_empty() {
2856            run_expert(&m.experts[e], &assign[e]);
2857        }
2858    }
2859    if let Some((se, gate)) = &m.shared {
2860        let mut gl = vec![0.0f32; b];
2861        gate.matmat(xs, b, &mut gl, pool);
2862        let all: Vec<(usize, f32)> = (0..b)
2863            .map(|bi| (bi, 1.0 / (1.0 + (-gl[bi]).exp())))
2864            .collect();
2865        run_expert(se, &all);
2866    }
2867    out
2868}
2869
2870thread_local! {
2871    /// gate/up activation scratch for the dense FFN paths (single uses
2872    /// two slots, the fused pair all four) — these were fresh
2873    /// intermediate-size Vecs on every layer of every token.
2874    static FFN_SCRATCH: std::cell::RefCell<[Vec<f32>; 4]> =
2875        const { std::cell::RefCell::new([Vec::new(), Vec::new(), Vec::new(), Vec::new()]) };
2876}
2877
2878/// Dense SwiGLU FFN through QTensor matvecs (any storage).
2879fn dense_ffn(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
2880    // Whole-FFN GPU submit (этап 4.2 increment): gate → silu·up → down
2881    // chained in ONE command buffer with the intermediate activations
2882    // resident on the device — 3 per-op polls become 1 per layer. The
2883    // moe_block backend already implements exactly this chain; a dense
2884    // FFN is one expert with weight 1. Runtime probe: the chain still
2885    // pays one submit+poll per layer — alternate it against the pure-CPU
2886    // FFN and keep whichever is faster on this machine.
2887    // q1 FFNs offload at any practical size: the q1 CPU kernel is
2888    // compute-bound, so the UMA threshold logic does not apply — the
2889    // probe measures and decides either way.
2890    if crate::gpu::enabled_here()
2891        && (d.gate_proj.rows() >= crate::gpu::min_rows() || d.gate_proj.is_q1())
2892    {
2893        let arm = if d.gate_proj.is_q1() && crate::gpu::q1_force() {
2894            crate::gpu::ProbeArm::Gpu
2895        } else {
2896            crate::gpu::probe_arm(crate::gpu::OpClass::Ffn)
2897        };
2898        match arm {
2899            crate::gpu::ProbeArm::Gpu => {
2900                let t0 = std::time::Instant::now();
2901                if let Some(out) = dense_ffn_gpu(d, x, pool) {
2902                    crate::gpu::probe_record(crate::gpu::OpClass::Ffn, true, t0.elapsed());
2903                    return out;
2904                }
2905            }
2906            crate::gpu::ProbeArm::CpuTimed => {
2907                let t0 = std::time::Instant::now();
2908                let out = crate::gpu::cpu_scope(|| dense_ffn_cpu(d, x, pool));
2909                crate::gpu::probe_record(crate::gpu::OpClass::Ffn, false, t0.elapsed());
2910                return out;
2911            }
2912            crate::gpu::ProbeArm::Cpu => {
2913                return crate::gpu::cpu_scope(|| dense_ffn_cpu(d, x, pool));
2914            }
2915        }
2916    }
2917    dense_ffn_cpu(d, x, pool)
2918}
2919
2920/// The pure-CPU dense-FFN body (also the fallback of every GPU refusal).
2921fn dense_ffn_cpu(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
2922    let inter = d.gate_proj.rows();
2923    FFN_SCRATCH.with(|s| {
2924        let mut s = s.borrow_mut();
2925        let [g, u, ..] = &mut *s;
2926        g.resize(inter, 0.0);
2927        u.resize(inter, 0.0);
2928        // Multi-matrix job: gate+up under one pool dispatch.
2929        QTensor::matvec_many([&d.gate_proj, &d.up_proj], x, [g, u], pool);
2930        for i in 0..inter {
2931            g[i] = d.act.apply(g[i]) * u[i];
2932        }
2933        // DTG-MA bake probe (Patent 2): accumulate this layer's
2934        // per-neuron activation mass while a probe pass is active.
2935        FFN_PROBE.with(|pr| {
2936            if let Some(acc) = pr.borrow_mut().as_mut() {
2937                let li = crate::gpu::cur_layer();
2938                if li >= 0 {
2939                    if let Some(row) = acc.get_mut(li as usize) {
2940                        for (a, &v) in row.iter_mut().zip(g.iter()) {
2941                            *a += (v as f64).abs();
2942                        }
2943                    }
2944                }
2945            }
2946        });
2947        let mut out = attention::take_buf(d.down_proj.rows());
2948        d.down_proj.matvec(g, &mut out, pool);
2949        out
2950    })
2951}
2952
2953thread_local! {
2954    /// DTG-MA activation probe: per-layer per-neuron Σ|silu(g)·u|
2955    /// accumulator, alive only during `Pipeline::probe_ffn_mass`.
2956    static FFN_PROBE: std::cell::RefCell<Option<Vec<Vec<f64>>>> =
2957        const { std::cell::RefCell::new(None) };
2958}
2959
2960/// Dense FFN as one GPU submission via the MoE block path (single
2961/// expert, weight 1.0): gate → silu·up → down chained in one command
2962/// buffer, intermediate activations device-resident. None → weights
2963/// not q8-mapped in the primary shard / over the VRAM budget / backend
2964/// refusal → honest CPU path.
2965fn dense_ffn_gpu(d: &DenseFfn, x: &[f32], _pool: Option<&Pool>) -> Option<Vec<f32>> {
2966    // The GPU block hardcodes SiLU; GeLU FFNs (Gemma) stay on CPU.
2967    if d.act != Act::Silu {
2968        return None;
2969    }
2970    // Threshold: tiny FFNs are not worth a submission (q1 excepted —
2971    // see the caller's gate).
2972    if d.gate_proj.rows() < crate::gpu::min_rows() && !d.gate_proj.is_q1() {
2973        return None;
2974    }
2975    let mut jobs: Vec<crate::gpu::MoeJob> = Vec::with_capacity(1);
2976    let mut model_ref = None;
2977    moe_push_job(d, x, 1.0, &mut jobs, &mut model_ref)?;
2978    let model = model_ref?;
2979    let hidden = jobs[0].down.1;
2980    let mut out = attention::take_buf(hidden);
2981    if crate::gpu::moe_block(&model, &jobs, &mut out) {
2982        Some(out)
2983    } else {
2984        let mut out = out;
2985        attention::recycle_buf(&mut out);
2986        None
2987    }
2988}
2989
2990/// q8-mapped primary-shard tensor parts for a GPU job: q8_2f carries
2991/// its column field, q8_row runs with empty col slices (the backend
2992/// skips the multiply). Shared by the MoE block and the dense-FFN
2993/// single-job path.
2994#[allow(clippy::type_complexity)]
2995#[allow(clippy::type_complexity)]
2996fn moe_parts(
2997    t: &QTensor,
2998) -> Option<(&std::sync::Arc<cortiq_core::CmfModel>, usize, usize, usize, &[f32], &[f32], bool)> {
2999    match t {
3000        QTensor::Mapped {
3001            model,
3002            idx,
3003            dtype: dt @ (cortiq_core::TensorDtype::Q8_2f | cortiq_core::TensorDtype::Q8Row),
3004            rows,
3005            cols,
3006            row_scale,
3007            col_field,
3008            ..
3009        } if (*dt == cortiq_core::TensorDtype::Q8Row) || !col_field.is_empty() => {
3010            Some((model, *idx, *rows, *cols, row_scale, col_field, false))
3011        }
3012        // q1: tile-embedded scales — empty rs/col slices, raw xs.
3013        QTensor::Mapped {
3014            model,
3015            idx,
3016            dtype: cortiq_core::TensorDtype::Q1,
3017            rows,
3018            cols,
3019            ..
3020        } => Some((model, *idx, *rows, *cols, &[][..], &[][..], true)),
3021        _ => None,
3022    }
3023}
3024
3025/// Build one gate/up/down GPU job (see `moe_parts`).
3026fn moe_push_job<'a>(
3027    d: &'a DenseFfn,
3028    x: &[f32],
3029    w: f32,
3030    jobs: &mut Vec<crate::gpu::MoeJob<'a>>,
3031    model_ref: &mut Option<std::sync::Arc<cortiq_core::CmfModel>>,
3032) -> Option<()> {
3033    use crate::qtensor::prescale;
3034    if d.act != Act::Silu {
3035        return None; // GPU block hardcodes SiLU
3036    }
3037    let (gm, gi, gr, gc, grs, gcf, gq1) = moe_parts(&d.gate_proj)?;
3038    let (_, ui, ur, uc, urs, ucf, uq1) = moe_parts(&d.up_proj)?;
3039    let (_, di, dr, dc, drs, dcf, dq1) = moe_parts(&d.down_proj)?;
3040    if gq1 != uq1 || uq1 != dq1 {
3041        return None; // mixed-dtype trio — honest CPU path
3042    }
3043    model_ref.get_or_insert_with(|| gm.clone());
3044    let gdt = if gcf.is_empty() { cortiq_core::TensorDtype::Q8Row } else { cortiq_core::TensorDtype::Q8_2f };
3045    let udt = if ucf.is_empty() { cortiq_core::TensorDtype::Q8Row } else { cortiq_core::TensorDtype::Q8_2f };
3046    jobs.push(crate::gpu::MoeJob {
3047        gate: (gi, gr, gc, grs),
3048        up: (ui, ur, uc, urs),
3049        down: (di, dr, dc, drs),
3050        xs_gate: prescale(x, gcf, gdt).into_owned(),
3051        xs_up: prescale(x, ucf, udt).into_owned(),
3052        down_col: dcf,
3053        w,
3054        q1: gq1,
3055    });
3056    Some(())
3057}
3058
3059/// Sparse dense-FFN directly on QUANTIZED weights (mask × mmap): reads
3060/// ONLY the active neurons' gate/up rows and down columns from the mmap
3061/// — no full-matrix dequant, no f32 model copy. This is what lets a
3062/// masked big model run at quantized RSS (the historical mask path
3063/// forced the whole model to f32). Semantics identical to the f32
3064/// sparse path within quant tolerance.
3065fn sparse_ffn_quant(
3066    d: &DenseFfn,
3067    x: &[f32],
3068    active: &[u16],
3069    hidden: usize,
3070    pool: Option<&Pool>,
3071) -> Vec<f32> {
3072    let n = active.len();
3073    let inter = d.gate_proj.rows();
3074    let mut act = vec![0.0f32; n];
3075    // Scratch is needed if EITHER projection is group-packed (q4/vbit);
3076    // gate/up normally share a dtype but sizing on both is robust.
3077    let need_scratch = !(d.gate_proj.sparse_col_ok() && d.up_proj.sparse_col_ok());
3078    let compute = |ai: usize| -> f32 {
3079        let idx = active[ai] as usize;
3080        if idx >= inter {
3081            return 0.0; // defensive parity with the f32 sparse path
3082        }
3083        let mut s = if need_scratch { vec![0.0f32; hidden] } else { Vec::new() };
3084        let gate = d.gate_proj.row_dot(idx, x, &mut s);
3085        let up = d.up_proj.row_dot(idx, x, &mut s);
3086        d.act.apply(gate) * up
3087    };
3088    match pool {
3089        Some(p) if n >= 256 => {
3090            let ptr = SendMut(act.as_mut_ptr());
3091            p.run(&|widx, nw| {
3092                let chunk = n.div_ceil(nw);
3093                let (s, e) = (widx * chunk, ((widx + 1) * chunk).min(n));
3094                for ai in s..e {
3095                    unsafe { *ptr.at(ai) = compute(ai) };
3096                }
3097            });
3098        }
3099        _ => {
3100            for (ai, a) in act.iter_mut().enumerate() {
3101                *a = compute(ai);
3102            }
3103        }
3104    }
3105    // Scatter through active down columns (reads only those columns).
3106    let mut out = vec![0.0f32; hidden];
3107    for (ai, &idx) in active.iter().enumerate() {
3108        let w = act[ai];
3109        if w.abs() >= 1e-12 && (idx as usize) < inter {
3110            d.down_proj.add_col_scaled(idx as usize, w, &mut out);
3111        }
3112    }
3113    out
3114}
3115
3116/// Test-only re-export of the private sparse-quant FFN (mask × mmap gate).
3117#[doc(hidden)]
3118pub fn sparse_ffn_quant_for_test(
3119    d: &DenseFfn,
3120    x: &[f32],
3121    active: &[u16],
3122    hidden: usize,
3123) -> Vec<f32> {
3124    sparse_ffn_quant(d, x, active, hidden, None)
3125}
3126
3127/// Dequantize a DenseFfn's three matrices to f32 (transient; only the
3128/// q4/vbit-masked fallback uses it — the memory-lean path is
3129/// sparse_ffn_quant). Reuses row_f32 row-by-row.
3130fn dequant_dense_f32(d: &DenseFfn) -> (Vec<f32>, Vec<f32>, Vec<f32>) {
3131    let deq = |t: &QTensor| -> Vec<f32> {
3132        let (rows, cols) = (t.rows(), t.cols());
3133        let mut out = vec![0.0f32; rows * cols];
3134        for r in 0..rows {
3135            t.row_f32(r, &mut out[r * cols..(r + 1) * cols]);
3136        }
3137        out
3138    };
3139    (deq(&d.gate_proj), deq(&d.up_proj), deq(&d.down_proj))
3140}
3141
3142/// Pointer wrapper for the worker-pool scatter (same pattern as qtensor).
3143struct SendMut(*mut f32);
3144unsafe impl Send for SendMut {}
3145unsafe impl Sync for SendMut {}
3146impl SendMut {
3147    #[inline]
3148    // Deliberate unsynchronized scatter: pool workers write disjoint indices
3149    // in parallel, so returning `&mut` from `&self` is intentional here.
3150    #[allow(clippy::mut_from_ref)]
3151    unsafe fn at(&self, i: usize) -> &mut f32 {
3152        unsafe { &mut *self.0.add(i) }
3153    }
3154}
3155
3156/// MoE FFN: router softmax over ALL experts → top-k (HF Qwen2/3-MoE
3157/// semantics: probabilities BEFORE selection; optional renorm of the
3158/// selected k). Only selected experts' pages are touched in mmap.
3159fn moe_ffn(m: &MoeFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
3160    let ne = m.experts.len();
3161    let mut logits = vec![0.0f32; ne];
3162    m.router.matvec(x, &mut logits, pool);
3163    let mx = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
3164    let mut p: Vec<f32> = logits.iter().map(|&l| (l - mx).exp()).collect();
3165    let s: f32 = p.iter().sum();
3166    for v in &mut p {
3167        *v /= s;
3168    }
3169    let mut idx: Vec<usize> = (0..ne).collect();
3170    // Descending by prob, lower index wins ties — torch.topk order.
3171    idx.sort_unstable_by(|&a, &b| p[b].partial_cmp(&p[a]).unwrap().then(a.cmp(&b)));
3172    idx.truncate(m.top_k);
3173    let wsum: f32 = if m.norm_topk_prob {
3174        idx.iter().map(|&e| p[e]).sum()
3175    } else {
3176        1.0
3177    };
3178    {
3179        let mut st = m.stats.borrow_mut();
3180        if st.len() < ne {
3181            st.resize(ne, 0);
3182        }
3183        for &e in &idx {
3184            st[e] += 1;
3185        }
3186    }
3187    // D5: the whole layer MoE block in one GPU command buffer (experts — the
3188    // same mmap via a no-copy buffer; intermediate activations on the GPU).
3189    // Same Ffn probe class as the dense chain: one submit per layer
3190    // either wins on this driver stack or it doesn't.
3191    if crate::gpu::enabled_here() {
3192        match crate::gpu::probe_arm(crate::gpu::OpClass::Ffn) {
3193            crate::gpu::ProbeArm::Gpu => {
3194                let t0 = std::time::Instant::now();
3195                if let Some(out) = moe_ffn_gpu(m, x, &idx, &p, wsum, pool) {
3196                    crate::gpu::probe_record(crate::gpu::OpClass::Ffn, true, t0.elapsed());
3197                    return out;
3198                }
3199            }
3200            crate::gpu::ProbeArm::CpuTimed => {
3201                let t0 = std::time::Instant::now();
3202                let out = crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool));
3203                crate::gpu::probe_record(crate::gpu::OpClass::Ffn, false, t0.elapsed());
3204                return out;
3205            }
3206            crate::gpu::ProbeArm::Cpu => {
3207                return crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool));
3208            }
3209        }
3210    }
3211    moe_ffn_cpu(m, x, &idx, &p, wsum, pool)
3212}
3213
3214/// The pure-CPU MoE expert loop (also the fallback of every GPU refusal).
3215fn moe_ffn_cpu(
3216    m: &MoeFfn,
3217    x: &[f32],
3218    idx: &[usize],
3219    p: &[f32],
3220    wsum: f32,
3221    pool: Option<&Pool>,
3222) -> Vec<f32> {
3223    let mut out = attention::take_buf(x.len());
3224    for &e in idx {
3225        let mut eo = dense_ffn(&m.experts[e], x, pool);
3226        let w = p[e] / wsum;
3227        for i in 0..out.len() {
3228            out[i] += w * eo[i];
3229        }
3230        attention::recycle_buf(&mut eo);
3231    }
3232    if let Some((se, gate)) = &m.shared {
3233        let mut so = dense_ffn(se, x, pool);
3234        let mut gl = vec![0.0f32; 1];
3235        gate.matvec(x, &mut gl, pool);
3236        let g = 1.0 / (1.0 + (-gl[0]).exp());
3237        for i in 0..out.len() {
3238            out[i] += g * so[i];
3239        }
3240        attention::recycle_buf(&mut so);
3241    }
3242    out
3243}
3244
3245/// Building the MoE-layer GPU jobs: all selected experts (+shared) must
3246/// be q8_2f-Mapped from the primary mapping; otherwise None → CPU path.
3247fn moe_ffn_gpu(
3248    m: &MoeFfn,
3249    x: &[f32],
3250    idx: &[usize],
3251    p: &[f32],
3252    wsum: f32,
3253    pool: Option<&Pool>,
3254) -> Option<Vec<f32>> {
3255    use crate::gpu::MoeJob;
3256
3257    let mut jobs: Vec<MoeJob> = Vec::with_capacity(idx.len() + 1);
3258    let mut model_ref = None;
3259    for &e in idx {
3260        moe_push_job(&m.experts[e], x, p[e] / wsum, &mut jobs, &mut model_ref)?;
3261    }
3262    if let Some((se, gate)) = &m.shared {
3263        let mut gl = vec![0.0f32; 1];
3264        gate.matvec(x, &mut gl, pool);
3265        let g = 1.0 / (1.0 + (-gl[0]).exp());
3266        moe_push_job(se, x, g, &mut jobs, &mut model_ref)?;
3267    }
3268    let model = model_ref?;
3269    let hidden = jobs[0].down.1;
3270    let mut out = vec![0.0f32; hidden];
3271    crate::gpu::moe_block(&model, &jobs, &mut out).then_some(out)
3272}
3273
3274/// Single-position FFN dispatch.
3275fn ffn_forward(ffn: &FfnKind, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
3276    match ffn {
3277        FfnKind::Dense(d) => dense_ffn(d, x, pool),
3278        FfnKind::Moe(m) => moe_ffn(m, x, pool),
3279    }
3280}
3281
3282/// Fused two-position FFN: gate/up/down streamed once (dense). MoE
3283/// falls back to two singles — expert sets differ per position, there
3284/// is nothing to fuse.
3285fn ffn_forward_pair(
3286    ffn: &FfnKind,
3287    x1: &[f32],
3288    x2: &[f32],
3289    pool: Option<&Pool>,
3290) -> (Vec<f32>, Vec<f32>) {
3291    let d = match ffn {
3292        FfnKind::Dense(d) => d,
3293        FfnKind::Moe(m) => return (moe_ffn(m, x1, pool), moe_ffn(m, x2, pool)),
3294    };
3295    let inter = d.gate_proj.rows();
3296    FFN_SCRATCH.with(|s| {
3297        let mut s = s.borrow_mut();
3298        let [g1, g2, u1, u2] = &mut *s;
3299        g1.resize(inter, 0.0);
3300        g2.resize(inter, 0.0);
3301        u1.resize(inter, 0.0);
3302        u2.resize(inter, 0.0);
3303        // Multi-matrix pair job: gate+up under one pool dispatch
3304        // (o1s = lane-1 outputs across tensors, o2s = lane-2).
3305        QTensor::matvec2_many(
3306            [&d.gate_proj, &d.up_proj],
3307            x1,
3308            x2,
3309            [g1.as_mut_slice(), u1.as_mut_slice()],
3310            [g2.as_mut_slice(), u2.as_mut_slice()],
3311            pool,
3312        );
3313        for i in 0..inter {
3314            g1[i] = d.act.apply(g1[i]) * u1[i];
3315            g2[i] = d.act.apply(g2[i]) * u2[i];
3316        }
3317        let mut o1 = attention::take_buf(d.down_proj.rows());
3318        let mut o2 = attention::take_buf(d.down_proj.rows());
3319        d.down_proj.matvec2(g1, g2, &mut o1, &mut o2, pool);
3320        (o1, o2)
3321    })
3322}
3323
3324#[cfg(test)]
3325mod tests {
3326    use super::*;
3327
3328    /// sparse_ffn_quant must equal a dense FFN where inactive neurons are
3329    /// zeroed (mask × mmap correctness). On F32 tensors this is EXACT —
3330    /// it validates the row_dot / add_col_scaled / scatter indexing, the
3331    /// bug-prone part. The q8 branches reuse the golden-tested linear
3332    /// scale, structurally identical to the matvec kernels.
3333    #[test]
3334    fn sparse_ffn_quant_equals_dense_with_inactive_zeroed() {
3335        let (hidden, inter) = (16usize, 40usize);
3336        let synth = |n: usize, salt: usize| -> Vec<f32> {
3337            (0..n)
3338                .map(|i| (((i * 37 + salt * 11 + 3) % 101) as f32 / 101.0 - 0.5) * 0.4)
3339                .collect()
3340        };
3341        let d = DenseFfn {
3342            gate_proj: QTensor::from_f32(synth(inter * hidden, 1), inter, hidden),
3343            up_proj: QTensor::from_f32(synth(inter * hidden, 2), inter, hidden),
3344            down_proj: QTensor::from_f32(synth(hidden * inter, 3), hidden, inter),
3345            act: Act::Silu,
3346        };
3347        let x = synth(hidden, 9);
3348        // Active = every 3rd neuron.
3349        let active: Vec<u16> = (0..inter as u16).filter(|i| i % 3 == 0).collect();
3350
3351        let sparse = sparse_ffn_quant(&d, &x, &active, hidden, None);
3352
3353        // Reference: full dense FFN but g[i]=0 for inactive neurons.
3354        let mut g = vec![0.0f32; inter];
3355        d.gate_proj.matvec(&x, &mut g, None);
3356        let mut u = vec![0.0f32; inter];
3357        d.up_proj.matvec(&x, &mut u, None);
3358        let act_set: std::collections::HashSet<u16> = active.iter().copied().collect();
3359        for i in 0..inter {
3360            g[i] = if act_set.contains(&(i as u16)) {
3361                inference::silu(g[i]) * u[i]
3362            } else {
3363                0.0
3364            };
3365        }
3366        let mut reference = vec![0.0f32; hidden];
3367        d.down_proj.matvec(&g, &mut reference, None);
3368
3369        let max_d = sparse
3370            .iter()
3371            .zip(&reference)
3372            .map(|(a, b)| (a - b).abs())
3373            .fold(0.0f32, f32::max);
3374        assert!(max_d < 1e-5, "sparse != dense-zeroed: max|Δ| = {max_d}");
3375    }
3376
3377    /// Attach a synthetic MTP head (same structure as a main layer).
3378    fn attach_test_mtp(p: &mut Pipeline) {
3379        let (h, inter, heads, kv, hd) = (
3380            p.hidden_size,
3381            p.intermediate_size,
3382            p.num_heads,
3383            p.num_kv_heads,
3384            p.head_dim,
3385        );
3386        let synth = |n: usize, salt: usize| -> Vec<f32> {
3387            (0..n)
3388                .map(|i| (((i * 29 + salt * 23 + 5) % 101) as f32 / 101.0 - 0.5) * 0.2)
3389                .collect()
3390        };
3391        let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
3392            QTensor::from_f32(synth(rows * cols, salt), rows, cols)
3393        };
3394        p.mtp = Some(MtpModule {
3395            enorm: vec![1.0; h],
3396            hnorm: vec![1.0; h],
3397            eh_proj: qt(h, 2 * h, 301),
3398            layer: LayerWeights {
3399                input_norm: vec![1.0; h],
3400                post_norm: vec![1.0; h],
3401                attn_out_norm: None,
3402                ffn_out_norm: None,
3403                layer_scale: None,
3404                ffn: FfnKind::Dense(DenseFfn {
3405                    gate_proj: qt(inter, h, 315),
3406                    up_proj: qt(inter, h, 316),
3407                    down_proj: qt(h, inter, 317),
3408                    act: Act::Silu,
3409                }),
3410                attn: AttnKind::Full {
3411                bias: None,
3412                    wq: qt(heads * hd, h, 311),
3413                    wk: qt(kv * hd, h, 312),
3414                    wv: qt(kv * hd, h, 313),
3415                    wo: qt(h, heads * hd, 314),
3416                    q_norm: None,
3417                    k_norm: None,
3418                    output_gate: false,
3419                },
3420            },
3421            final_norm: vec![1.0; h],
3422            kv: crate::kv_cache::LayerKvCache::new(kv, hd),
3423        });
3424    }
3425
3426    #[test]
3427    fn speculative_equals_vanilla_greedy() {
3428        let run = |spec: bool| {
3429            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
3430            p.sampler_config.temperature = 0.0;
3431            attach_test_mtp(&mut p);
3432            p.speculative = spec;
3433            let r = p.generate("abcdef", 12, None, None).unwrap();
3434            (r.token_ids, r.mtp_drafted, r.mtp_accepted)
3435        };
3436        let (vanilla, d0, _) = run(false);
3437        let (spec, d1, a1) = run(true);
3438        assert_eq!(d0, 0, "vanilla path must not draft");
3439        assert!(d1 > 0, "speculative path must draft");
3440        assert_eq!(
3441            vanilla, spec,
3442            "speculative must reproduce the exact greedy sequence (accepted {a1}/{d1})"
3443        );
3444    }
3445
3446    #[test]
3447    fn speculative_accepts_constant_oracle() {
3448        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
3449        p.sampler_config.temperature = 0.0;
3450        p.sampler_config.repetition_penalty = 1.0;
3451        // Constant lm_head → every logit equal → both the main model and
3452        // the draft head argmax to token 0: acceptance must be 100%.
3453        p.weights.lm_head = QTensor::from_f32(vec![0.01; 64 * 8], 64, 8);
3454        attach_test_mtp(&mut p);
3455        p.speculative = true;
3456        let r = p.generate("abcd", 10, None, None).unwrap();
3457        assert!(r.mtp_drafted > 0);
3458        assert_eq!(
3459            r.mtp_accepted, r.mtp_drafted,
3460            "constant logits → every draft accepted"
3461        );
3462        // Ties resolve to the same token in both the main and draft
3463        // heads — the sequence is one repeated token.
3464        assert!(r.token_ids.windows(2).all(|w| w[0] == w[1]));
3465    }
3466
3467    #[test]
3468    fn empty_prompt_is_an_error_not_a_panic() {
3469        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
3470        let r = p.generate("", 4, None, None);
3471        assert!(r.is_err(), "empty prompt must be a clean error");
3472    }
3473
3474    #[test]
3475    fn every_token_enters_kv_exactly_once() {
3476        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
3477        // Greedy so no RNG variance; byte tokenizer → 3 prompt tokens.
3478        p.sampler_config.temperature = 0.0;
3479        let r = p.generate("abc", 2, None, None).unwrap();
3480        assert_eq!(r.prompt_tokens, 3);
3481        // prompt(3) + first sampled token forwarded before second logits:
3482        // step0 samples from prefill hidden (no extra forward), then
3483        // forwards t1 → cache 4; step1 samples, loop ends (max_tokens).
3484        assert_eq!(
3485            p.kv_cache.seq_len(),
3486            3 + r.tokens_generated - 1,
3487            "each token must be cached exactly once (v1 cached the last prompt token twice)"
3488        );
3489    }
3490
3491    #[test]
3492    fn generation_is_reproducible_with_seed() {
3493        let run = || {
3494            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
3495            p.generate("hello", 8, None, None).unwrap().token_ids
3496        };
3497        assert_eq!(run(), run());
3498    }
3499
3500    #[test]
3501    fn eviction_bounds_the_cache() {
3502        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
3503        p.kv_cache.max_seq_len = 6;
3504        p.sampler_config.temperature = 0.0;
3505        let _ = p.generate("abcd", 12, None, None).unwrap();
3506        assert!(
3507            p.kv_cache.seq_len() <= 6 + 1,
3508            "cache must stay bounded by max_seq_len (got {})",
3509            p.kv_cache.seq_len()
3510        );
3511    }
3512
3513    #[test]
3514    fn confidence_matches_tokens_and_is_a_probability() {
3515        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
3516        p.sampler_config.temperature = 0.0;
3517        p.sampler_config.repetition_penalty = 1.0;
3518        let r = p.generate("abcd", 10, None, None).unwrap();
3519        assert_eq!(
3520            r.token_confidence.len(),
3521            r.token_ids.len(),
3522            "one confidence per emitted token"
3523        );
3524        for &c in &r.token_confidence {
3525            assert!((0.0..=1.0).contains(&c), "confidence out of [0,1]: {c}");
3526        }
3527        // top1_prob is a valid softmax probability.
3528        let logits = [1.0f32, 3.0, 0.5, 3.0];
3529        let p0 = top1_prob_t(&logits, 1, 1.0);
3530        let p1 = top1_prob_t(&logits, 3, 1.0);
3531        assert!((p0 - p1).abs() < 1e-6, "equal logits → equal prob");
3532        assert!(p0 > 0.0 && p0 < 1.0);
3533        // Calibration temperature > 1 softens an over-confident peak.
3534        let sharp = top1_prob_t(&logits, 1, 1.0);
3535        let soft = top1_prob_t(&logits, 1, 2.0);
3536        assert!(soft < sharp, "higher temperature lowers peak confidence");
3537    }
3538
3539    #[test]
3540    fn trace_is_opt_in_and_parallels_the_output() {
3541        // Off by default: the runtime is silent unless observation asked.
3542        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
3543        p.sampler_config.temperature = 0.0;
3544        p.sampler_config.repetition_penalty = 1.0;
3545        let r = p.generate("abcd", 10, None, None).unwrap();
3546        assert!(r.traces.is_empty(), "trace must be empty unless enabled");
3547
3548        // On: exactly one row per emitted token, aligned with the output.
3549        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
3550        p.sampler_config.temperature = 0.0;
3551        p.sampler_config.repetition_penalty = 1.0;
3552        p.set_trace(true);
3553        let r = p.generate("abcd", 10, None, None).unwrap();
3554        assert_eq!(r.traces.len(), r.token_ids.len(), "one trace row per token");
3555        for (i, tr) in r.traces.iter().enumerate() {
3556            assert_eq!(tr.t, i, "trace index is sequential");
3557            assert_eq!(tr.token_id, r.token_ids[i], "trace token_id matches output");
3558            assert_eq!(
3559                tr.confidence, r.token_confidence[i],
3560                "trace confidence matches the confidence channel"
3561            );
3562            // No dynamic router in this pipeline → no skill, no coherence.
3563            assert!(tr.active_skill.is_none() && tr.recon.is_none() && !tr.switched);
3564        }
3565    }
3566
3567    #[test]
3568    fn explain_prefill_logits_match_greedy_first_token() {
3569        // `cortiq explain` shows the next-token distribution from
3570        // prefill_next_logits; its argmax must equal what greedy generate
3571        // actually emits first — otherwise explain would lie.
3572        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
3573        p.sampler_config.temperature = 0.0;
3574        p.sampler_config.repetition_penalty = 1.0;
3575        let ids = p.tokenizer.encode("abcd");
3576        let logits = p.prefill_next_logits(&ids, None);
3577        let argmax = logits
3578            .iter()
3579            .enumerate()
3580            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
3581            .unwrap()
3582            .0 as u32;
3583        let r = p.generate("abcd", 1, None, None).unwrap();
3584        assert_eq!(argmax, r.token_ids[0], "explain preview must match greedy emit");
3585    }
3586}