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        // Depth bound: the chunk attend streams K/V per query, so past
2083        // ~1k of context the CPU's GEMM-attend wins — deep chunks stay
2084        // on the CPU (measured: +66% at 512, +38% at 1024, parity at
2085        // 2048 unbounded). CMF_GPU_CHUNK=0 disables the graph.
2086        if !crate::gpu::enabled_here()
2087            || std::env::var("CMF_GPU_CHUNK").map(|v| v == "0").unwrap_or(false)
2088            || pos0 > 1024
2089            || b < 32
2090            || self.swa.is_some()
2091            || self.global_attn.is_some()
2092            || self.attn_v_norm
2093            || (self.attn_scale - 1.0 / (self.head_dim as f32).sqrt()).abs() > 1e-9
2094        {
2095            return li0;
2096        }
2097        let Some(model) = self.model.clone() else { return li0 };
2098        let inv_freq = self.inv_freq.clone();
2099        let (nh, nkv, hd, hs) = (self.num_heads, self.num_kv_heads, self.head_dim, self.hidden_size);
2100        // Collect the longest run of consecutive eligible layers.
2101        let mut layers: Vec<crate::gpu_metal::ChunkLayer> = Vec::new();
2102        let mut stored_at: Vec<usize> = Vec::new();
2103        for li in li0..self.num_layers {
2104            let lw = &self.weights.layers[li];
2105            if lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some()
2106            {
2107                break;
2108            }
2109            let AttnKind::Full { wq, wk, wv, wo, q_norm, k_norm, output_gate: false, bias } =
2110                &lw.attn
2111            else {
2112                break;
2113            };
2114            let FfnKind::Dense(d) = &lw.ffn else { break };
2115            if d.act != Act::Silu {
2116                break;
2117            }
2118            let parts = (
2119                wq.q8_row_parts(),
2120                wk.q8_row_parts(),
2121                wv.q8_row_parts(),
2122                wo.q8_row_parts(),
2123                d.gate_proj.q8_row_parts(),
2124                d.up_proj.q8_row_parts(),
2125                d.down_proj.q8_row_parts(),
2126            );
2127            let (Some(pq), Some(pk), Some(pv), Some(po), Some(pg), Some(pu), Some(pd)) = parts
2128            else {
2129                break;
2130            };
2131            let layer = &self.kv_cache.layers[li];
2132            if layer.mode != crate::kv_cache::KvMode::F32 || layer.o1.is_some() {
2133                break;
2134            }
2135            stored_at.push(layer.head_len(0));
2136            layers.push(crate::gpu_metal::ChunkLayer {
2137                model: &model,
2138                kv_id: self.graph_kv_id,
2139                layer: li,
2140                wq: pq,
2141                wk: pk,
2142                wv: pv,
2143                wo: po,
2144                gate: pg,
2145                up: pu,
2146                down: pd,
2147                input_norm: &lw.input_norm,
2148                post_norm: &lw.post_norm,
2149                bias: bias
2150                    .as_ref()
2151                    .map(|(a, bb, cc)| (a.as_slice(), bb.as_slice(), cc.as_slice())),
2152                q_norm: q_norm.as_deref(),
2153                k_norm: k_norm.as_deref(),
2154                inv_freq: &inv_freq,
2155                rd: self.rotary_dim,
2156                nh,
2157                nkv,
2158                hd,
2159                hs,
2160                inter: d.gate_proj.rows(),
2161                gemma: matches!(self.norm_style, cortiq_core::NormStyle::Gemma),
2162                eps: self.rms_eps as f32,
2163            });
2164        }
2165        if layers.is_empty() {
2166            return li0;
2167        }
2168        let row = nkv * hd;
2169        let mut store: Vec<(Vec<f32>, Vec<f32>, Vec<f32>)> = stored_at
2170            .iter()
2171            .map(|&st| (vec![0f32; b * row], vec![0f32; b * row], vec![0f32; st + b]))
2172            .collect();
2173        let mut io: Vec<crate::gpu_metal::ChunkIo> = Vec::with_capacity(layers.len());
2174        for (i, (ok, ov, oi)) in store.iter_mut().enumerate() {
2175            let li = layers[i].layer;
2176            let layer = &self.kv_cache.layers[li];
2177            io.push(crate::gpu_metal::ChunkIo {
2178                cpu_stored: stored_at[i],
2179                cpu_k: (0..nkv).map(|g| layer.head_keys(g)).collect(),
2180                cpu_v: (0..nkv).map(|g| layer.head_values(g)).collect(),
2181                out_k: ok,
2182                out_v: ov,
2183                imp: oi,
2184            });
2185        }
2186        let n_run = layers.len();
2187        let last = layers.last().map(|l| l.layer + 1).unwrap_or(li0);
2188        if !crate::gpu_metal::chunk_run_gpu(&layers, &mut io, h, b, pos0) {
2189            return li0;
2190        }
2191        drop(io);
2192        drop(layers);
2193        // CPU caches stay the owners of record: append the chunk rows
2194        // and bank the importance masses per layer.
2195        for (i, (ok, ov, oi)) in store.iter().enumerate().take(n_run) {
2196            let li = li0 + i;
2197            let layer = &mut self.kv_cache.layers[li];
2198            for bi in 0..b {
2199                layer.append(&ok[bi * row..(bi + 1) * row], &ov[bi * row..(bi + 1) * row], &[]);
2200            }
2201            layer.accumulate_imp(oi);
2202        }
2203        last
2204    }
2205
2206    /// Is layer `li` a sliding-window (local-RoPE) layer? Gemma-3:
2207    /// every `pattern`-th layer is global, the rest are local.
2208    fn layer_is_local(&self, li: usize) -> bool {
2209        match self.swa {
2210            Some((_, pattern)) => (li + 1) % pattern.max(1) != 0,
2211            None => false,
2212        }
2213    }
2214
2215    /// The RoPE table for layer `li` (local layers may have their own;
2216    /// Gemma-4 global layers use the proportional padded table).
2217    fn layer_inv_freq(&self, li: usize) -> std::sync::Arc<Vec<f32>> {
2218        if self.layer_is_local(li) {
2219            if let Some(f) = &self.inv_freq_local {
2220                return f.clone();
2221            }
2222        } else if let Some(f) = &self.inv_freq_global {
2223            return f.clone();
2224        }
2225        self.inv_freq.clone()
2226    }
2227
2228    /// The attend window for layer `li` (None = full context).
2229    fn layer_window(&self, li: usize) -> Option<usize> {
2230        match self.swa {
2231            Some((w, _)) if self.layer_is_local(li) => Some(w),
2232            _ => None,
2233        }
2234    }
2235
2236    /// Attention geometry of layer `li`: (num_kv_heads, head_dim,
2237    /// rotary_dim). Gemma-4 global layers override all three.
2238    fn layer_geom(&self, li: usize) -> (usize, usize, usize) {
2239        if !self.layer_is_local(li) {
2240            if let Some((ghd, gkv)) = self.global_attn {
2241                return (gkv, ghd, ghd);
2242            }
2243        }
2244        (self.num_kv_heads, self.head_dim, self.rotary_dim)
2245    }
2246
2247    /// Forward one position through all layers (hybrid dispatch).
2248    fn forward_layers(
2249        &mut self,
2250        hidden: &[f32],
2251        position: usize,
2252        task_mask: Option<&TaskMask>,
2253    ) -> Vec<f32> {
2254        self.forward_layers_upto(hidden, position, task_mask, None)
2255    }
2256
2257    /// Same, stopping after layer `upto` inclusive (routing probe φ).
2258    fn forward_layers_upto(
2259        &mut self,
2260        hidden: &[f32],
2261        position: usize,
2262        task_mask: Option<&TaskMask>,
2263        upto: Option<usize>,
2264    ) -> Vec<f32> {
2265        let mut h = hidden.to_vec();
2266        // Split borrows: copy scalars / clone handles so the per-layer
2267        // cfg does not hold `&self` while the KV cache is `&mut`.
2268        let (nh, _nkv, _hd, hs, _rd, eps) = (
2269            self.num_heads,
2270            self.num_kv_heads,
2271            self.head_dim,
2272            self.hidden_size,
2273            self.rotary_dim,
2274            self.rms_eps,
2275        );
2276        let pool = self.pool.clone();
2277
2278        #[cfg(target_os = "macos")]
2279        let mut gpu_skip_until = 0usize;
2280        for li in 0..self.num_layers {
2281            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU (CMF_GPU_LAYERS)
2282            if let Some(u) = upto {
2283                if li > u {
2284                    break;
2285                }
2286            }
2287            if let Some(mask) = task_mask {
2288                if !mask.layer_alive(li) {
2289                    continue; // dead layer: residual pass-through
2290                }
2291            }
2292            // Whole-block q1 token graph: a run of consecutive q1
2293            // layers — GDN and full attention — executes with one sync
2294            // per CPU attend instead of per op (macOS/Metal).
2295            #[cfg(target_os = "macos")]
2296            {
2297                if li < gpu_skip_until {
2298                    continue;
2299                }
2300                if task_mask.is_none() {
2301                    let end = self.q1_graph_gpu(li, upto, position, &mut h);
2302                    if end > li {
2303                        gpu_skip_until = end;
2304                        continue;
2305                    }
2306                }
2307            }
2308
2309            let lw = &self.weights.layers[li];
2310            // Norm into the pipeline scratch — the returning rms_norm
2311            // allocated twice per layer per token (roadmap §3 P0).
2312            inference::rms_norm_into(&h, &lw.input_norm, self.rms_eps, self.norm_style, &mut self.ws.n1);
2313
2314            let attn_out = match &lw.attn {
2315                AttnKind::Linear(w) => {
2316                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
2317                    vmf_phase_forward(
2318                        &self.ws.n1,
2319                        w,
2320                        &cfg,
2321                        &mut self.kv_cache.layers[li].linear_state,
2322                        self.pool.as_deref(),
2323                    )
2324                }
2325                AttnKind::LinearGdn(w) => {
2326                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
2327                    gdn_forward(
2328                        &self.ws.n1,
2329                        w,
2330                        &cfg,
2331                        &mut self.kv_cache.layers[li].linear_state,
2332                        self.pool.as_deref(),
2333                    )
2334                }
2335                AttnKind::Full {
2336                    wq,
2337                    wk,
2338                    wv,
2339                    wo,
2340                    q_norm,
2341                    k_norm,
2342                    output_gate,
2343                    bias,
2344                } if self.kv_cache.layers[li].o1_sealed() => {
2345                    // O(1) override: decode on the sealed Nyström state
2346                    // instead of the growing KV cache.
2347                    let inv_freq_l = self.layer_inv_freq(li);
2348                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
2349                    let cfg = QwenAttnCfg {
2350                        num_heads: nh,
2351                        num_kv_heads: nkv_l,
2352                        head_dim: hd_l,
2353                        hidden_size: hs,
2354                        position,
2355                        inv_freq: &inv_freq_l,
2356                        rotary_dim: rd_l,
2357                        scale: self.attn_scale,
2358                        window: None,
2359                        v_norm: self.attn_v_norm,
2360                        q_norm: q_norm.as_deref(),
2361                        k_norm: k_norm.as_deref(),
2362                        output_gate: *output_gate,
2363                        bias: bias
2364                            .as_ref()
2365                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
2366                        rms_eps: eps,
2367                        norm_style: self.norm_style,
2368                        pool: pool.as_deref(),
2369                    };
2370                    attention::qwen_attention_nystrom(
2371                        &self.ws.n1,
2372                        wq,
2373                        wk,
2374                        wv,
2375                        wo,
2376                        &mut self.kv_cache.layers[li],
2377                        &cfg,
2378                    )
2379                }
2380                AttnKind::Full {
2381                    wq,
2382                    wk,
2383                    wv,
2384                    wo,
2385                    q_norm,
2386                    k_norm,
2387                    output_gate,
2388                    bias,
2389                } => {
2390                    let masked = task_mask
2391                        .map(|m| m.head_flags(li, self.num_heads).iter().any(|&a| !a))
2392                        .unwrap_or(false);
2393                    let f32_view = (wq.as_f32(), wk.as_f32(), wv.as_f32(), wo.as_f32());
2394                    match (masked, f32_view) {
2395                        // Historical masked path (f32 slices; the loader
2396                        // keeps masked models in f32).
2397                        (true, (Some(q), Some(k), Some(v), Some(o))) => {
2398                            let active_heads = task_mask.unwrap().head_flags(li, self.num_heads);
2399                            attention::multi_head_attention(
2400                                &self.ws.n1,
2401                                q,
2402                                k,
2403                                v,
2404                                o,
2405                                &mut self.kv_cache.layers[li],
2406                                self.num_heads,
2407                                self.num_kv_heads,
2408                                self.head_dim,
2409                                self.hidden_size,
2410                                position,
2411                                &active_heads,
2412                                &self.inv_freq,
2413                            )
2414                        }
2415                        (masked, _) => {
2416                            if masked {
2417                                tracing::warn!(
2418                                    "layer {li}: head mask on quantized weights not \
2419                                     supported yet — executing dense"
2420                                );
2421                            }
2422                            let inv_freq_l = self.layer_inv_freq(li);
2423                            let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
2424                            let cfg = QwenAttnCfg {
2425                                num_heads: nh,
2426                                num_kv_heads: nkv_l,
2427                                head_dim: hd_l,
2428                                hidden_size: hs,
2429                                position,
2430                                inv_freq: &inv_freq_l,
2431                                rotary_dim: rd_l,
2432                                scale: self.attn_scale,
2433                                window: self.layer_window(li),
2434                                v_norm: self.attn_v_norm,
2435                                q_norm: q_norm.as_deref(),
2436                                k_norm: k_norm.as_deref(),
2437                                output_gate: *output_gate,
2438                        bias: bias
2439                            .as_ref()
2440                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
2441                                rms_eps: eps,
2442                                norm_style: self.norm_style,
2443                                pool: pool.as_deref(),
2444                            };
2445                            attention::qwen_attention(
2446                                &self.ws.n1,
2447                                wq,
2448                                wk,
2449                                wv,
2450                                wo,
2451                                &mut self.kv_cache.layers[li],
2452                                &cfg,
2453                            )
2454                        }
2455                    }
2456                }
2457            };
2458            // Gemma sandwich norm: normalize the attention branch before
2459            // it joins the residual stream.
2460            let attn_out = match &self.weights.layers[li].attn_out_norm {
2461                Some(w) => inference::rms_norm(&attn_out, w, self.rms_eps, self.norm_style),
2462                None => attn_out,
2463            };
2464            for (i, &a) in attn_out.iter().enumerate() {
2465                h[i] += a;
2466            }
2467            let mut attn_out = attn_out;
2468            attention::recycle_buf(&mut attn_out);
2469
2470            let lw = &self.weights.layers[li];
2471            inference::rms_norm_into(&h, &lw.post_norm, self.rms_eps, self.norm_style, &mut self.ws.p1);
2472            let post_normed = &self.ws.p1;
2473
2474            let ffn_masked = task_mask
2475                .map(|m| m.ffn_active_count(li) < self.intermediate_size)
2476                .unwrap_or(false);
2477            // Sparse mask path applies to dense f32 FFN only; MoE
2478            // layers route through the normal dispatch below.
2479            let f32_ffn = match &lw.ffn {
2480                FfnKind::Dense(d) => {
2481                    (d.gate_proj.as_f32(), d.up_proj.as_f32(), d.down_proj.as_f32())
2482                }
2483                FfnKind::Moe(_) => (None, None, None),
2484            };
2485            let ffn_out = match (ffn_masked, f32_ffn) {
2486                (true, (Some(g), Some(u), Some(d))) => {
2487                    let active = task_mask.unwrap().ffn_active_indices(li);
2488                    inference::sparse_ffn_forward(
2489                        &post_normed,
2490                        g,
2491                        u,
2492                        d,
2493                        self.hidden_size,
2494                        self.intermediate_size,
2495                        &active,
2496                        self.pool.as_deref(),
2497                    )
2498                }
2499                // Mask × quantized mmap: sparse FFN reads only active
2500                // neurons' rows/cols directly from the quant bytes — no
2501                // f32 model copy (a masked big model runs at quant RSS).
2502                (true, _) => match &lw.ffn {
2503                    FfnKind::Dense(d) if d.down_proj.sparse_col_ok() => {
2504                        let active = task_mask.unwrap().ffn_active_indices(li);
2505                        sparse_ffn_quant(
2506                            d,
2507                            &post_normed,
2508                            &active,
2509                            self.hidden_size,
2510                            self.pool.as_deref(),
2511                        )
2512                    }
2513                    // q4/vbit down_proj has no cheap column access → dequant
2514                    // the three matrices to f32 (transient) and run the f32
2515                    // sparse path. Correct (mask honored), just not
2516                    // memory-lean for those dtypes — a rare masked case.
2517                    FfnKind::Dense(d) => {
2518                        let active = task_mask.unwrap().ffn_active_indices(li);
2519                        let (gf, uf, df) = dequant_dense_f32(d);
2520                        inference::sparse_ffn_forward(
2521                            &post_normed,
2522                            &gf,
2523                            &uf,
2524                            &df,
2525                            self.hidden_size,
2526                            self.intermediate_size,
2527                            &active,
2528                            self.pool.as_deref(),
2529                        )
2530                    }
2531                    FfnKind::Moe(_) => {
2532                        // MoE is already sparse by expert selection; masks
2533                        // don't apply to routed experts.
2534                        ffn_forward(&lw.ffn, &post_normed, self.pool.as_deref())
2535                    }
2536                },
2537                (false, _) => ffn_forward(&lw.ffn, &post_normed, self.pool.as_deref()),
2538            };
2539            let ffn_out = match &self.weights.layers[li].ffn_out_norm {
2540                Some(w) => inference::rms_norm(&ffn_out, w, self.rms_eps, self.norm_style),
2541                None => ffn_out,
2542            };
2543            for (i, &f) in ffn_out.iter().enumerate() {
2544                h[i] += f;
2545            }
2546            let mut ffn_out = ffn_out;
2547            attention::recycle_buf(&mut ffn_out);
2548
2549            // Gemma-4: the layer output is scaled by a learned scalar.
2550            if let Some(sc) = self.weights.layers[li].layer_scale {
2551                for v in h.iter_mut() {
2552                    *v *= sc;
2553                }
2554            }
2555
2556            // Dynamic routing φ capture (on-policy, fireball-style): the
2557            // EMA of the post-residual hidden at the router's phi_layer,
2558            // updated as the context evolves during decode.
2559            if self.dyn_phi_layer == Some(li) {
2560                self.update_dyn_phi(&h);
2561            }
2562        }
2563        crate::gpu::set_layer(-1); // layers done — lm_head outside layer-split
2564
2565        h
2566    }
2567
2568    /// EMA of φ at the router layer (rolling, weight 0.2 = ~5-token
2569    /// horizon). First observation seeds it exactly.
2570    fn update_dyn_phi(&mut self, h: &[f32]) {
2571        const A: f32 = 0.2;
2572        if self.dyn_phi_ema.len() != h.len() {
2573            self.dyn_phi_ema = vec![0.0; h.len()];
2574            self.dyn_phi_seen = 0;
2575        }
2576        if self.dyn_phi_seen == 0 {
2577            self.dyn_phi_ema.copy_from_slice(h);
2578        } else {
2579            for (e, &v) in self.dyn_phi_ema.iter_mut().zip(h) {
2580                *e = (1.0 - A) * *e + A * v;
2581            }
2582        }
2583        self.dyn_phi_seen += 1;
2584    }
2585
2586    /// Current router φ (EMA at phi_layer); empty until first capture.
2587    pub fn dyn_phi(&self) -> &[f32] {
2588        &self.dyn_phi_ema
2589    }
2590
2591    /// Enable/disable φ capture at the router layer, reset the EMA.
2592    pub fn set_dyn_phi_layer(&mut self, layer: Option<usize>) {
2593        self.dyn_phi_layer = layer;
2594        self.dyn_phi_ema.clear();
2595        self.dyn_phi_seen = 0;
2596    }
2597
2598    /// Skills eligible for dynamic switching: (index, id, phi_layer).
2599    pub fn dynamic_skills(&self) -> Vec<(usize, String, usize)> {
2600        let Some(model) = &self.model else { return Vec::new() };
2601        model
2602            .header
2603            .skills
2604            .iter()
2605            .enumerate()
2606            .filter_map(|(i, sk)| {
2607                let ok = matches!(self.dyn_skill_layers.get(i), Some(Some(_)));
2608                let sel = sk.selection.as_ref()?;
2609                (ok).then(|| (i, sk.id.clone(), sel.phi_layer))
2610            })
2611            .collect()
2612    }
2613
2614    /// Index of the currently overlaid skill (None = backbone).
2615    pub fn active_skill(&self) -> Option<usize> {
2616        self.dyn_active
2617    }
2618
2619    /// Enable dynamic per-token skill routing: build the hysteresis
2620    /// router from the container's routable skills, start φ capture at
2621    /// their (shared) phi_layer. Returns the number of routable skills
2622    /// (0 = nothing to route; router stays off). Idempotent.
2623    pub fn enable_dynamic_routing(&mut self) -> usize {
2624        use crate::swarm::{DynRouter, RoutableSkill};
2625        let Some(model) = self.model.clone() else { return 0 };
2626        // A blend materialized f32 working tensors into the layers; there
2627        // is no single skill index to revert from → refuse (honest).
2628        if self.dyn_blend_loaded {
2629            tracing::warn!("dynamic routing unavailable on a blend-loaded pipeline");
2630            return 0;
2631        }
2632        // A statically-overlaid skill that is NOT FFN-eligible can't be
2633        // cheaply reverted at generation start → refuse rather than
2634        // silently keep it overlaid.
2635        if let Some(a) = self.dyn_active {
2636            if !matches!(self.dyn_skill_layers.get(a), Some(Some(_))) {
2637                tracing::warn!(
2638                    "loaded skill is not FFN-eligible — dynamic routing unavailable"
2639                );
2640                return 0;
2641            }
2642        }
2643        let hidden = self.hidden_size;
2644        let mut skills = Vec::new();
2645        for (idx, id, _phi) in self.dynamic_skills() {
2646            if let Some(sel) = model.header.skills[idx].selection.as_ref() {
2647                if let Some(rs) = RoutableSkill::from_descriptor(idx, id, sel, hidden) {
2648                    skills.push(rs);
2649                }
2650            }
2651        }
2652        if skills.is_empty() {
2653            return 0;
2654        }
2655        // Skills should share a phi_layer; warn (not fail) if they don't.
2656        let phi = skills[0].phi_layer;
2657        if skills.iter().any(|s| s.phi_layer != phi) {
2658            tracing::warn!("routable skills disagree on phi_layer; using {phi}");
2659        }
2660        let n = skills.len();
2661        self.set_dyn_phi_layer(Some(phi));
2662        self.dyn_router = Some(DynRouter::new(skills));
2663        n
2664    }
2665
2666    /// Human-readable switch log from the last dynamic-routed generation.
2667    pub fn route_switches(&self) -> Vec<(usize, Option<String>, Option<String>)> {
2668        self.dyn_router
2669            .as_ref()
2670            .map(|r| r.switches.clone())
2671            .unwrap_or_default()
2672    }
2673
2674    /// LM head: hidden → logits [vocab_size]. The dominant matvec of
2675    /// every decode step — row-parallel on the worker pool.
2676    fn lm_head_forward(&self, hidden: &[f32]) -> Vec<f32> {
2677        let rows = self.weights.lm_head.rows();
2678        let mut logits = attention::take_buf(rows.min(self.vocab_size));
2679        self.weights
2680            .lm_head
2681            .matvec(hidden, &mut logits, self.pool.as_deref());
2682        logits.resize(self.vocab_size, 0.0);
2683        if let Some(c) = self.final_softcap {
2684            for l in logits.iter_mut() {
2685                *l = c * (*l / c).tanh();
2686            }
2687        }
2688        logits
2689    }
2690
2691    /// Prefill `ids` and return the next-token logits — what the model
2692    /// would predict next, WITHOUT committing to generation (introspection
2693    /// for `cortiq explain`). Clears and repopulates the KV cache; leaves
2694    /// the active overlay untouched.
2695    pub fn prefill_next_logits(&mut self, ids: &[u32], task_mask: Option<&TaskMask>) -> Vec<f32> {
2696        self.kv_cache.clear();
2697        let mut hidden = vec![0.0f32; self.hidden_size];
2698        for (pos, &id) in ids.iter().enumerate() {
2699            let emb = self.embed_single(id);
2700            hidden = self.forward_layers(&emb, pos, task_mask);
2701        }
2702        inference::rms_norm_into(
2703            &hidden,
2704            &self.weights.final_norm,
2705            self.rms_eps,
2706            self.norm_style,
2707            &mut self.ws.n1,
2708        );
2709        self.lm_head_forward(&self.ws.n1)
2710    }
2711}
2712
2713/// Convenience: deterministic tiny pipeline for tests.
2714pub fn create_test_pipeline(
2715    hidden_size: usize,
2716    intermediate_size: usize,
2717    num_heads: usize,
2718    num_kv_heads: usize,
2719    head_dim: usize,
2720    num_layers: usize,
2721    vocab_size: usize,
2722) -> Pipeline {
2723    // Small pseudo-random weights: constant weights make attention
2724    // degenerate and hide indexing bugs.
2725    let synth = |n: usize, salt: usize| -> Vec<f32> {
2726        (0..n)
2727            .map(|i| (((i * 31 + salt * 17 + 7) % 97) as f32 / 97.0 - 0.5) * 0.2)
2728            .collect()
2729    };
2730    let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
2731        QTensor::from_f32(synth(rows * cols, salt), rows, cols)
2732    };
2733    let layer_weights: Vec<LayerWeights> = (0..num_layers)
2734        .map(|li| LayerWeights {
2735            input_norm: vec![1.0; hidden_size],
2736            post_norm: vec![1.0; hidden_size],
2737            attn_out_norm: None,
2738            ffn_out_norm: None,
2739            layer_scale: None,
2740            ffn: FfnKind::Dense(DenseFfn {
2741                gate_proj: qt(intermediate_size, hidden_size, li * 10 + 5),
2742                up_proj: qt(intermediate_size, hidden_size, li * 10 + 6),
2743                down_proj: qt(hidden_size, intermediate_size, li * 10 + 7),
2744                act: Act::Silu,
2745            }),
2746            attn: AttnKind::Full {
2747                bias: None,
2748                wq: qt(num_heads * head_dim, hidden_size, li * 10 + 1),
2749                wk: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 2),
2750                wv: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 3),
2751                wo: qt(hidden_size, num_heads * head_dim, li * 10 + 4),
2752                q_norm: None,
2753                k_norm: None,
2754                output_gate: false,
2755            },
2756        })
2757        .collect();
2758
2759    Pipeline::new(
2760        Tokenizer::byte_level(),
2761        PipelineWeights {
2762            embed_tokens: qt(vocab_size, hidden_size, 100),
2763            layers: layer_weights,
2764            lm_head: qt(vocab_size, hidden_size, 200),
2765            final_norm: vec![1.0; hidden_size],
2766        },
2767        hidden_size,
2768        intermediate_size,
2769        num_heads,
2770        num_kv_heads,
2771        head_dim,
2772        num_layers,
2773        vocab_size,
2774        1e-6,
2775        10_000.0,
2776        NormStyle::Qwen,
2777        4096,
2778        SamplerConfig {
2779            seed: Some(42),
2780            ..Default::default()
2781        },
2782    )
2783}
2784
2785/// Batched dense-FFN: gate/up/down via matmat (element-wise the same
2786/// math as b × dense_ffn — the same dot kernels).
2787fn dense_ffn_batch(d: &DenseFfn, xs: &[f32], b: usize, pool: Option<&Pool>) -> Vec<f32> {
2788    let inter = d.gate_proj.rows();
2789    let hidden = d.down_proj.rows();
2790    let mut g = vec![0.0f32; b * inter];
2791    d.gate_proj.matmat(xs, b, &mut g, pool);
2792    let mut u = vec![0.0f32; b * inter];
2793    d.up_proj.matmat(xs, b, &mut u, pool);
2794    for i in 0..b * inter {
2795        g[i] = d.act.apply(g[i]) * u[i];
2796    }
2797    let mut out = vec![0.0f32; b * hidden];
2798    d.down_proj.matmat(&g, b, &mut out, pool);
2799    out
2800}
2801
2802/// Batched MoE-FFN: router batched, positions are GROUPED by expert —
2803/// an expert's weights are read once for all its positions in the chunk
2804/// (the main prefill-GEMM win on MoE: 960MB/token of 35B experts).
2805fn moe_ffn_batch(m: &MoeFfn, xs: &[f32], b: usize, hidden: usize, pool: Option<&Pool>) -> Vec<f32> {
2806    let ne = m.experts.len();
2807    let mut logits = vec![0.0f32; b * ne];
2808    m.router.matmat(xs, b, &mut logits, pool);
2809
2810    // Assignments: expert → [(position, weight)] — the same top-k semantics
2811    // as moe_ffn (softmax over all, torch.topk order, optional renorm).
2812    let mut assign: Vec<Vec<(usize, f32)>> = vec![Vec::new(); ne];
2813    {
2814        let mut st = m.stats.borrow_mut();
2815        if st.len() < ne {
2816            st.resize(ne, 0);
2817        }
2818        for bi in 0..b {
2819            let lg = &logits[bi * ne..(bi + 1) * ne];
2820            let mx = lg.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
2821            let mut p: Vec<f32> = lg.iter().map(|&l| (l - mx).exp()).collect();
2822            let sum: f32 = p.iter().sum();
2823            for v in &mut p {
2824                *v /= sum;
2825            }
2826            let mut order: Vec<usize> = (0..ne).collect();
2827            order.sort_unstable_by(|&x, &y| p[y].partial_cmp(&p[x]).unwrap().then(x.cmp(&y)));
2828            order.truncate(m.top_k);
2829            let wsum: f32 = if m.norm_topk_prob {
2830                order.iter().map(|&e| p[e]).sum()
2831            } else {
2832                1.0
2833            };
2834            for &e in &order {
2835                st[e] += 1;
2836                assign[e].push((bi, p[e] / wsum));
2837            }
2838        }
2839    }
2840
2841    let mut out = vec![0.0f32; b * hidden];
2842    let cols = m.experts[0].gate_proj.cols();
2843    let mut run_expert = |d: &DenseFfn, list: &[(usize, f32)]| {
2844        let sb = list.len();
2845        let mut sub = vec![0.0f32; sb * cols];
2846        for (k, &(bi, _)) in list.iter().enumerate() {
2847            sub[k * cols..(k + 1) * cols].copy_from_slice(&xs[bi * cols..(bi + 1) * cols]);
2848        }
2849        let eo = dense_ffn_batch(d, &sub, sb, pool);
2850        for (k, &(bi, w)) in list.iter().enumerate() {
2851            for i in 0..hidden {
2852                out[bi * hidden + i] += w * eo[k * hidden + i];
2853            }
2854        }
2855    };
2856    for e in 0..ne {
2857        if !assign[e].is_empty() {
2858            run_expert(&m.experts[e], &assign[e]);
2859        }
2860    }
2861    if let Some((se, gate)) = &m.shared {
2862        let mut gl = vec![0.0f32; b];
2863        gate.matmat(xs, b, &mut gl, pool);
2864        let all: Vec<(usize, f32)> = (0..b)
2865            .map(|bi| (bi, 1.0 / (1.0 + (-gl[bi]).exp())))
2866            .collect();
2867        run_expert(se, &all);
2868    }
2869    out
2870}
2871
2872thread_local! {
2873    /// gate/up activation scratch for the dense FFN paths (single uses
2874    /// two slots, the fused pair all four) — these were fresh
2875    /// intermediate-size Vecs on every layer of every token.
2876    static FFN_SCRATCH: std::cell::RefCell<[Vec<f32>; 4]> =
2877        const { std::cell::RefCell::new([Vec::new(), Vec::new(), Vec::new(), Vec::new()]) };
2878}
2879
2880/// Dense SwiGLU FFN through QTensor matvecs (any storage).
2881fn dense_ffn(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
2882    // Whole-FFN GPU submit (этап 4.2 increment): gate → silu·up → down
2883    // chained in ONE command buffer with the intermediate activations
2884    // resident on the device — 3 per-op polls become 1 per layer. The
2885    // moe_block backend already implements exactly this chain; a dense
2886    // FFN is one expert with weight 1. Runtime probe: the chain still
2887    // pays one submit+poll per layer — alternate it against the pure-CPU
2888    // FFN and keep whichever is faster on this machine.
2889    // q1 FFNs offload at any practical size: the q1 CPU kernel is
2890    // compute-bound, so the UMA threshold logic does not apply — the
2891    // probe measures and decides either way.
2892    if crate::gpu::enabled_here()
2893        && (d.gate_proj.rows() >= crate::gpu::min_rows() || d.gate_proj.is_q1())
2894    {
2895        let arm = if d.gate_proj.is_q1() && crate::gpu::q1_force() {
2896            crate::gpu::ProbeArm::Gpu
2897        } else {
2898            crate::gpu::probe_arm(crate::gpu::OpClass::Ffn)
2899        };
2900        match arm {
2901            crate::gpu::ProbeArm::Gpu => {
2902                let t0 = std::time::Instant::now();
2903                if let Some(out) = dense_ffn_gpu(d, x, pool) {
2904                    crate::gpu::probe_record(crate::gpu::OpClass::Ffn, true, t0.elapsed());
2905                    return out;
2906                }
2907            }
2908            crate::gpu::ProbeArm::CpuTimed => {
2909                let t0 = std::time::Instant::now();
2910                let out = crate::gpu::cpu_scope(|| dense_ffn_cpu(d, x, pool));
2911                crate::gpu::probe_record(crate::gpu::OpClass::Ffn, false, t0.elapsed());
2912                return out;
2913            }
2914            crate::gpu::ProbeArm::Cpu => {
2915                return crate::gpu::cpu_scope(|| dense_ffn_cpu(d, x, pool));
2916            }
2917        }
2918    }
2919    dense_ffn_cpu(d, x, pool)
2920}
2921
2922/// The pure-CPU dense-FFN body (also the fallback of every GPU refusal).
2923fn dense_ffn_cpu(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
2924    let inter = d.gate_proj.rows();
2925    FFN_SCRATCH.with(|s| {
2926        let mut s = s.borrow_mut();
2927        let [g, u, ..] = &mut *s;
2928        g.resize(inter, 0.0);
2929        u.resize(inter, 0.0);
2930        // Multi-matrix job: gate+up under one pool dispatch.
2931        QTensor::matvec_many([&d.gate_proj, &d.up_proj], x, [g, u], pool);
2932        for i in 0..inter {
2933            g[i] = d.act.apply(g[i]) * u[i];
2934        }
2935        // DTG-MA bake probe (Patent 2): accumulate this layer's
2936        // per-neuron activation mass while a probe pass is active.
2937        FFN_PROBE.with(|pr| {
2938            if let Some(acc) = pr.borrow_mut().as_mut() {
2939                let li = crate::gpu::cur_layer();
2940                if li >= 0 {
2941                    if let Some(row) = acc.get_mut(li as usize) {
2942                        for (a, &v) in row.iter_mut().zip(g.iter()) {
2943                            *a += (v as f64).abs();
2944                        }
2945                    }
2946                }
2947            }
2948        });
2949        let mut out = attention::take_buf(d.down_proj.rows());
2950        d.down_proj.matvec(g, &mut out, pool);
2951        out
2952    })
2953}
2954
2955thread_local! {
2956    /// DTG-MA activation probe: per-layer per-neuron Σ|silu(g)·u|
2957    /// accumulator, alive only during `Pipeline::probe_ffn_mass`.
2958    static FFN_PROBE: std::cell::RefCell<Option<Vec<Vec<f64>>>> =
2959        const { std::cell::RefCell::new(None) };
2960}
2961
2962/// Dense FFN as one GPU submission via the MoE block path (single
2963/// expert, weight 1.0): gate → silu·up → down chained in one command
2964/// buffer, intermediate activations device-resident. None → weights
2965/// not q8-mapped in the primary shard / over the VRAM budget / backend
2966/// refusal → honest CPU path.
2967fn dense_ffn_gpu(d: &DenseFfn, x: &[f32], _pool: Option<&Pool>) -> Option<Vec<f32>> {
2968    // The GPU block hardcodes SiLU; GeLU FFNs (Gemma) stay on CPU.
2969    if d.act != Act::Silu {
2970        return None;
2971    }
2972    // Threshold: tiny FFNs are not worth a submission (q1 excepted —
2973    // see the caller's gate).
2974    if d.gate_proj.rows() < crate::gpu::min_rows() && !d.gate_proj.is_q1() {
2975        return None;
2976    }
2977    let mut jobs: Vec<crate::gpu::MoeJob> = Vec::with_capacity(1);
2978    let mut model_ref = None;
2979    moe_push_job(d, x, 1.0, &mut jobs, &mut model_ref)?;
2980    let model = model_ref?;
2981    let hidden = jobs[0].down.1;
2982    let mut out = attention::take_buf(hidden);
2983    if crate::gpu::moe_block(&model, &jobs, &mut out) {
2984        Some(out)
2985    } else {
2986        let mut out = out;
2987        attention::recycle_buf(&mut out);
2988        None
2989    }
2990}
2991
2992/// q8-mapped primary-shard tensor parts for a GPU job: q8_2f carries
2993/// its column field, q8_row runs with empty col slices (the backend
2994/// skips the multiply). Shared by the MoE block and the dense-FFN
2995/// single-job path.
2996#[allow(clippy::type_complexity)]
2997#[allow(clippy::type_complexity)]
2998fn moe_parts(
2999    t: &QTensor,
3000) -> Option<(&std::sync::Arc<cortiq_core::CmfModel>, usize, usize, usize, &[f32], &[f32], bool)> {
3001    match t {
3002        QTensor::Mapped {
3003            model,
3004            idx,
3005            dtype: dt @ (cortiq_core::TensorDtype::Q8_2f | cortiq_core::TensorDtype::Q8Row),
3006            rows,
3007            cols,
3008            row_scale,
3009            col_field,
3010            ..
3011        } if (*dt == cortiq_core::TensorDtype::Q8Row) || !col_field.is_empty() => {
3012            Some((model, *idx, *rows, *cols, row_scale, col_field, false))
3013        }
3014        // q1: tile-embedded scales — empty rs/col slices, raw xs.
3015        QTensor::Mapped {
3016            model,
3017            idx,
3018            dtype: cortiq_core::TensorDtype::Q1,
3019            rows,
3020            cols,
3021            ..
3022        } => Some((model, *idx, *rows, *cols, &[][..], &[][..], true)),
3023        _ => None,
3024    }
3025}
3026
3027/// Build one gate/up/down GPU job (see `moe_parts`).
3028fn moe_push_job<'a>(
3029    d: &'a DenseFfn,
3030    x: &[f32],
3031    w: f32,
3032    jobs: &mut Vec<crate::gpu::MoeJob<'a>>,
3033    model_ref: &mut Option<std::sync::Arc<cortiq_core::CmfModel>>,
3034) -> Option<()> {
3035    use crate::qtensor::prescale;
3036    if d.act != Act::Silu {
3037        return None; // GPU block hardcodes SiLU
3038    }
3039    let (gm, gi, gr, gc, grs, gcf, gq1) = moe_parts(&d.gate_proj)?;
3040    let (_, ui, ur, uc, urs, ucf, uq1) = moe_parts(&d.up_proj)?;
3041    let (_, di, dr, dc, drs, dcf, dq1) = moe_parts(&d.down_proj)?;
3042    if gq1 != uq1 || uq1 != dq1 {
3043        return None; // mixed-dtype trio — honest CPU path
3044    }
3045    model_ref.get_or_insert_with(|| gm.clone());
3046    let gdt = if gcf.is_empty() { cortiq_core::TensorDtype::Q8Row } else { cortiq_core::TensorDtype::Q8_2f };
3047    let udt = if ucf.is_empty() { cortiq_core::TensorDtype::Q8Row } else { cortiq_core::TensorDtype::Q8_2f };
3048    jobs.push(crate::gpu::MoeJob {
3049        gate: (gi, gr, gc, grs),
3050        up: (ui, ur, uc, urs),
3051        down: (di, dr, dc, drs),
3052        xs_gate: prescale(x, gcf, gdt).into_owned(),
3053        xs_up: prescale(x, ucf, udt).into_owned(),
3054        down_col: dcf,
3055        w,
3056        q1: gq1,
3057    });
3058    Some(())
3059}
3060
3061/// Sparse dense-FFN directly on QUANTIZED weights (mask × mmap): reads
3062/// ONLY the active neurons' gate/up rows and down columns from the mmap
3063/// — no full-matrix dequant, no f32 model copy. This is what lets a
3064/// masked big model run at quantized RSS (the historical mask path
3065/// forced the whole model to f32). Semantics identical to the f32
3066/// sparse path within quant tolerance.
3067fn sparse_ffn_quant(
3068    d: &DenseFfn,
3069    x: &[f32],
3070    active: &[u16],
3071    hidden: usize,
3072    pool: Option<&Pool>,
3073) -> Vec<f32> {
3074    let n = active.len();
3075    let inter = d.gate_proj.rows();
3076    let mut act = vec![0.0f32; n];
3077    // Scratch is needed if EITHER projection is group-packed (q4/vbit);
3078    // gate/up normally share a dtype but sizing on both is robust.
3079    let need_scratch = !(d.gate_proj.sparse_col_ok() && d.up_proj.sparse_col_ok());
3080    let compute = |ai: usize| -> f32 {
3081        let idx = active[ai] as usize;
3082        if idx >= inter {
3083            return 0.0; // defensive parity with the f32 sparse path
3084        }
3085        let mut s = if need_scratch { vec![0.0f32; hidden] } else { Vec::new() };
3086        let gate = d.gate_proj.row_dot(idx, x, &mut s);
3087        let up = d.up_proj.row_dot(idx, x, &mut s);
3088        d.act.apply(gate) * up
3089    };
3090    match pool {
3091        Some(p) if n >= 256 => {
3092            let ptr = SendMut(act.as_mut_ptr());
3093            p.run(&|widx, nw| {
3094                let chunk = n.div_ceil(nw);
3095                let (s, e) = (widx * chunk, ((widx + 1) * chunk).min(n));
3096                for ai in s..e {
3097                    unsafe { *ptr.at(ai) = compute(ai) };
3098                }
3099            });
3100        }
3101        _ => {
3102            for (ai, a) in act.iter_mut().enumerate() {
3103                *a = compute(ai);
3104            }
3105        }
3106    }
3107    // Scatter through active down columns (reads only those columns).
3108    let mut out = vec![0.0f32; hidden];
3109    for (ai, &idx) in active.iter().enumerate() {
3110        let w = act[ai];
3111        if w.abs() >= 1e-12 && (idx as usize) < inter {
3112            d.down_proj.add_col_scaled(idx as usize, w, &mut out);
3113        }
3114    }
3115    out
3116}
3117
3118/// Test-only re-export of the private sparse-quant FFN (mask × mmap gate).
3119#[doc(hidden)]
3120pub fn sparse_ffn_quant_for_test(
3121    d: &DenseFfn,
3122    x: &[f32],
3123    active: &[u16],
3124    hidden: usize,
3125) -> Vec<f32> {
3126    sparse_ffn_quant(d, x, active, hidden, None)
3127}
3128
3129/// Dequantize a DenseFfn's three matrices to f32 (transient; only the
3130/// q4/vbit-masked fallback uses it — the memory-lean path is
3131/// sparse_ffn_quant). Reuses row_f32 row-by-row.
3132fn dequant_dense_f32(d: &DenseFfn) -> (Vec<f32>, Vec<f32>, Vec<f32>) {
3133    let deq = |t: &QTensor| -> Vec<f32> {
3134        let (rows, cols) = (t.rows(), t.cols());
3135        let mut out = vec![0.0f32; rows * cols];
3136        for r in 0..rows {
3137            t.row_f32(r, &mut out[r * cols..(r + 1) * cols]);
3138        }
3139        out
3140    };
3141    (deq(&d.gate_proj), deq(&d.up_proj), deq(&d.down_proj))
3142}
3143
3144/// Pointer wrapper for the worker-pool scatter (same pattern as qtensor).
3145struct SendMut(*mut f32);
3146unsafe impl Send for SendMut {}
3147unsafe impl Sync for SendMut {}
3148impl SendMut {
3149    #[inline]
3150    // Deliberate unsynchronized scatter: pool workers write disjoint indices
3151    // in parallel, so returning `&mut` from `&self` is intentional here.
3152    #[allow(clippy::mut_from_ref)]
3153    unsafe fn at(&self, i: usize) -> &mut f32 {
3154        unsafe { &mut *self.0.add(i) }
3155    }
3156}
3157
3158/// MoE FFN: router softmax over ALL experts → top-k (HF Qwen2/3-MoE
3159/// semantics: probabilities BEFORE selection; optional renorm of the
3160/// selected k). Only selected experts' pages are touched in mmap.
3161fn moe_ffn(m: &MoeFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
3162    let ne = m.experts.len();
3163    let mut logits = vec![0.0f32; ne];
3164    m.router.matvec(x, &mut logits, pool);
3165    let mx = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
3166    let mut p: Vec<f32> = logits.iter().map(|&l| (l - mx).exp()).collect();
3167    let s: f32 = p.iter().sum();
3168    for v in &mut p {
3169        *v /= s;
3170    }
3171    let mut idx: Vec<usize> = (0..ne).collect();
3172    // Descending by prob, lower index wins ties — torch.topk order.
3173    idx.sort_unstable_by(|&a, &b| p[b].partial_cmp(&p[a]).unwrap().then(a.cmp(&b)));
3174    idx.truncate(m.top_k);
3175    let wsum: f32 = if m.norm_topk_prob {
3176        idx.iter().map(|&e| p[e]).sum()
3177    } else {
3178        1.0
3179    };
3180    {
3181        let mut st = m.stats.borrow_mut();
3182        if st.len() < ne {
3183            st.resize(ne, 0);
3184        }
3185        for &e in &idx {
3186            st[e] += 1;
3187        }
3188    }
3189    // D5: the whole layer MoE block in one GPU command buffer (experts — the
3190    // same mmap via a no-copy buffer; intermediate activations on the GPU).
3191    // Same Ffn probe class as the dense chain: one submit per layer
3192    // either wins on this driver stack or it doesn't.
3193    if crate::gpu::enabled_here() {
3194        match crate::gpu::probe_arm(crate::gpu::OpClass::Ffn) {
3195            crate::gpu::ProbeArm::Gpu => {
3196                let t0 = std::time::Instant::now();
3197                if let Some(out) = moe_ffn_gpu(m, x, &idx, &p, wsum, pool) {
3198                    crate::gpu::probe_record(crate::gpu::OpClass::Ffn, true, t0.elapsed());
3199                    return out;
3200                }
3201            }
3202            crate::gpu::ProbeArm::CpuTimed => {
3203                let t0 = std::time::Instant::now();
3204                let out = crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool));
3205                crate::gpu::probe_record(crate::gpu::OpClass::Ffn, false, t0.elapsed());
3206                return out;
3207            }
3208            crate::gpu::ProbeArm::Cpu => {
3209                return crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool));
3210            }
3211        }
3212    }
3213    moe_ffn_cpu(m, x, &idx, &p, wsum, pool)
3214}
3215
3216/// The pure-CPU MoE expert loop (also the fallback of every GPU refusal).
3217fn moe_ffn_cpu(
3218    m: &MoeFfn,
3219    x: &[f32],
3220    idx: &[usize],
3221    p: &[f32],
3222    wsum: f32,
3223    pool: Option<&Pool>,
3224) -> Vec<f32> {
3225    let mut out = attention::take_buf(x.len());
3226    for &e in idx {
3227        let mut eo = dense_ffn(&m.experts[e], x, pool);
3228        let w = p[e] / wsum;
3229        for i in 0..out.len() {
3230            out[i] += w * eo[i];
3231        }
3232        attention::recycle_buf(&mut eo);
3233    }
3234    if let Some((se, gate)) = &m.shared {
3235        let mut so = dense_ffn(se, x, pool);
3236        let mut gl = vec![0.0f32; 1];
3237        gate.matvec(x, &mut gl, pool);
3238        let g = 1.0 / (1.0 + (-gl[0]).exp());
3239        for i in 0..out.len() {
3240            out[i] += g * so[i];
3241        }
3242        attention::recycle_buf(&mut so);
3243    }
3244    out
3245}
3246
3247/// Building the MoE-layer GPU jobs: all selected experts (+shared) must
3248/// be q8_2f-Mapped from the primary mapping; otherwise None → CPU path.
3249fn moe_ffn_gpu(
3250    m: &MoeFfn,
3251    x: &[f32],
3252    idx: &[usize],
3253    p: &[f32],
3254    wsum: f32,
3255    pool: Option<&Pool>,
3256) -> Option<Vec<f32>> {
3257    use crate::gpu::MoeJob;
3258
3259    let mut jobs: Vec<MoeJob> = Vec::with_capacity(idx.len() + 1);
3260    let mut model_ref = None;
3261    for &e in idx {
3262        moe_push_job(&m.experts[e], x, p[e] / wsum, &mut jobs, &mut model_ref)?;
3263    }
3264    if let Some((se, gate)) = &m.shared {
3265        let mut gl = vec![0.0f32; 1];
3266        gate.matvec(x, &mut gl, pool);
3267        let g = 1.0 / (1.0 + (-gl[0]).exp());
3268        moe_push_job(se, x, g, &mut jobs, &mut model_ref)?;
3269    }
3270    let model = model_ref?;
3271    let hidden = jobs[0].down.1;
3272    let mut out = vec![0.0f32; hidden];
3273    crate::gpu::moe_block(&model, &jobs, &mut out).then_some(out)
3274}
3275
3276/// Single-position FFN dispatch.
3277fn ffn_forward(ffn: &FfnKind, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
3278    match ffn {
3279        FfnKind::Dense(d) => dense_ffn(d, x, pool),
3280        FfnKind::Moe(m) => moe_ffn(m, x, pool),
3281    }
3282}
3283
3284/// Fused two-position FFN: gate/up/down streamed once (dense). MoE
3285/// falls back to two singles — expert sets differ per position, there
3286/// is nothing to fuse.
3287fn ffn_forward_pair(
3288    ffn: &FfnKind,
3289    x1: &[f32],
3290    x2: &[f32],
3291    pool: Option<&Pool>,
3292) -> (Vec<f32>, Vec<f32>) {
3293    let d = match ffn {
3294        FfnKind::Dense(d) => d,
3295        FfnKind::Moe(m) => return (moe_ffn(m, x1, pool), moe_ffn(m, x2, pool)),
3296    };
3297    let inter = d.gate_proj.rows();
3298    FFN_SCRATCH.with(|s| {
3299        let mut s = s.borrow_mut();
3300        let [g1, g2, u1, u2] = &mut *s;
3301        g1.resize(inter, 0.0);
3302        g2.resize(inter, 0.0);
3303        u1.resize(inter, 0.0);
3304        u2.resize(inter, 0.0);
3305        // Multi-matrix pair job: gate+up under one pool dispatch
3306        // (o1s = lane-1 outputs across tensors, o2s = lane-2).
3307        QTensor::matvec2_many(
3308            [&d.gate_proj, &d.up_proj],
3309            x1,
3310            x2,
3311            [g1.as_mut_slice(), u1.as_mut_slice()],
3312            [g2.as_mut_slice(), u2.as_mut_slice()],
3313            pool,
3314        );
3315        for i in 0..inter {
3316            g1[i] = d.act.apply(g1[i]) * u1[i];
3317            g2[i] = d.act.apply(g2[i]) * u2[i];
3318        }
3319        let mut o1 = attention::take_buf(d.down_proj.rows());
3320        let mut o2 = attention::take_buf(d.down_proj.rows());
3321        d.down_proj.matvec2(g1, g2, &mut o1, &mut o2, pool);
3322        (o1, o2)
3323    })
3324}
3325
3326#[cfg(test)]
3327mod tests {
3328    use super::*;
3329
3330    /// sparse_ffn_quant must equal a dense FFN where inactive neurons are
3331    /// zeroed (mask × mmap correctness). On F32 tensors this is EXACT —
3332    /// it validates the row_dot / add_col_scaled / scatter indexing, the
3333    /// bug-prone part. The q8 branches reuse the golden-tested linear
3334    /// scale, structurally identical to the matvec kernels.
3335    #[test]
3336    fn sparse_ffn_quant_equals_dense_with_inactive_zeroed() {
3337        let (hidden, inter) = (16usize, 40usize);
3338        let synth = |n: usize, salt: usize| -> Vec<f32> {
3339            (0..n)
3340                .map(|i| (((i * 37 + salt * 11 + 3) % 101) as f32 / 101.0 - 0.5) * 0.4)
3341                .collect()
3342        };
3343        let d = DenseFfn {
3344            gate_proj: QTensor::from_f32(synth(inter * hidden, 1), inter, hidden),
3345            up_proj: QTensor::from_f32(synth(inter * hidden, 2), inter, hidden),
3346            down_proj: QTensor::from_f32(synth(hidden * inter, 3), hidden, inter),
3347            act: Act::Silu,
3348        };
3349        let x = synth(hidden, 9);
3350        // Active = every 3rd neuron.
3351        let active: Vec<u16> = (0..inter as u16).filter(|i| i % 3 == 0).collect();
3352
3353        let sparse = sparse_ffn_quant(&d, &x, &active, hidden, None);
3354
3355        // Reference: full dense FFN but g[i]=0 for inactive neurons.
3356        let mut g = vec![0.0f32; inter];
3357        d.gate_proj.matvec(&x, &mut g, None);
3358        let mut u = vec![0.0f32; inter];
3359        d.up_proj.matvec(&x, &mut u, None);
3360        let act_set: std::collections::HashSet<u16> = active.iter().copied().collect();
3361        for i in 0..inter {
3362            g[i] = if act_set.contains(&(i as u16)) {
3363                inference::silu(g[i]) * u[i]
3364            } else {
3365                0.0
3366            };
3367        }
3368        let mut reference = vec![0.0f32; hidden];
3369        d.down_proj.matvec(&g, &mut reference, None);
3370
3371        let max_d = sparse
3372            .iter()
3373            .zip(&reference)
3374            .map(|(a, b)| (a - b).abs())
3375            .fold(0.0f32, f32::max);
3376        assert!(max_d < 1e-5, "sparse != dense-zeroed: max|Δ| = {max_d}");
3377    }
3378
3379    /// Attach a synthetic MTP head (same structure as a main layer).
3380    fn attach_test_mtp(p: &mut Pipeline) {
3381        let (h, inter, heads, kv, hd) = (
3382            p.hidden_size,
3383            p.intermediate_size,
3384            p.num_heads,
3385            p.num_kv_heads,
3386            p.head_dim,
3387        );
3388        let synth = |n: usize, salt: usize| -> Vec<f32> {
3389            (0..n)
3390                .map(|i| (((i * 29 + salt * 23 + 5) % 101) as f32 / 101.0 - 0.5) * 0.2)
3391                .collect()
3392        };
3393        let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
3394            QTensor::from_f32(synth(rows * cols, salt), rows, cols)
3395        };
3396        p.mtp = Some(MtpModule {
3397            enorm: vec![1.0; h],
3398            hnorm: vec![1.0; h],
3399            eh_proj: qt(h, 2 * h, 301),
3400            layer: LayerWeights {
3401                input_norm: vec![1.0; h],
3402                post_norm: vec![1.0; h],
3403                attn_out_norm: None,
3404                ffn_out_norm: None,
3405                layer_scale: None,
3406                ffn: FfnKind::Dense(DenseFfn {
3407                    gate_proj: qt(inter, h, 315),
3408                    up_proj: qt(inter, h, 316),
3409                    down_proj: qt(h, inter, 317),
3410                    act: Act::Silu,
3411                }),
3412                attn: AttnKind::Full {
3413                bias: None,
3414                    wq: qt(heads * hd, h, 311),
3415                    wk: qt(kv * hd, h, 312),
3416                    wv: qt(kv * hd, h, 313),
3417                    wo: qt(h, heads * hd, 314),
3418                    q_norm: None,
3419                    k_norm: None,
3420                    output_gate: false,
3421                },
3422            },
3423            final_norm: vec![1.0; h],
3424            kv: crate::kv_cache::LayerKvCache::new(kv, hd),
3425        });
3426    }
3427
3428    #[test]
3429    fn speculative_equals_vanilla_greedy() {
3430        let run = |spec: bool| {
3431            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
3432            p.sampler_config.temperature = 0.0;
3433            attach_test_mtp(&mut p);
3434            p.speculative = spec;
3435            let r = p.generate("abcdef", 12, None, None).unwrap();
3436            (r.token_ids, r.mtp_drafted, r.mtp_accepted)
3437        };
3438        let (vanilla, d0, _) = run(false);
3439        let (spec, d1, a1) = run(true);
3440        assert_eq!(d0, 0, "vanilla path must not draft");
3441        assert!(d1 > 0, "speculative path must draft");
3442        assert_eq!(
3443            vanilla, spec,
3444            "speculative must reproduce the exact greedy sequence (accepted {a1}/{d1})"
3445        );
3446    }
3447
3448    #[test]
3449    fn speculative_accepts_constant_oracle() {
3450        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
3451        p.sampler_config.temperature = 0.0;
3452        p.sampler_config.repetition_penalty = 1.0;
3453        // Constant lm_head → every logit equal → both the main model and
3454        // the draft head argmax to token 0: acceptance must be 100%.
3455        p.weights.lm_head = QTensor::from_f32(vec![0.01; 64 * 8], 64, 8);
3456        attach_test_mtp(&mut p);
3457        p.speculative = true;
3458        let r = p.generate("abcd", 10, None, None).unwrap();
3459        assert!(r.mtp_drafted > 0);
3460        assert_eq!(
3461            r.mtp_accepted, r.mtp_drafted,
3462            "constant logits → every draft accepted"
3463        );
3464        // Ties resolve to the same token in both the main and draft
3465        // heads — the sequence is one repeated token.
3466        assert!(r.token_ids.windows(2).all(|w| w[0] == w[1]));
3467    }
3468
3469    #[test]
3470    fn empty_prompt_is_an_error_not_a_panic() {
3471        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
3472        let r = p.generate("", 4, None, None);
3473        assert!(r.is_err(), "empty prompt must be a clean error");
3474    }
3475
3476    #[test]
3477    fn every_token_enters_kv_exactly_once() {
3478        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
3479        // Greedy so no RNG variance; byte tokenizer → 3 prompt tokens.
3480        p.sampler_config.temperature = 0.0;
3481        let r = p.generate("abc", 2, None, None).unwrap();
3482        assert_eq!(r.prompt_tokens, 3);
3483        // prompt(3) + first sampled token forwarded before second logits:
3484        // step0 samples from prefill hidden (no extra forward), then
3485        // forwards t1 → cache 4; step1 samples, loop ends (max_tokens).
3486        assert_eq!(
3487            p.kv_cache.seq_len(),
3488            3 + r.tokens_generated - 1,
3489            "each token must be cached exactly once (v1 cached the last prompt token twice)"
3490        );
3491    }
3492
3493    #[test]
3494    fn generation_is_reproducible_with_seed() {
3495        let run = || {
3496            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
3497            p.generate("hello", 8, None, None).unwrap().token_ids
3498        };
3499        assert_eq!(run(), run());
3500    }
3501
3502    #[test]
3503    fn eviction_bounds_the_cache() {
3504        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
3505        p.kv_cache.max_seq_len = 6;
3506        p.sampler_config.temperature = 0.0;
3507        let _ = p.generate("abcd", 12, None, None).unwrap();
3508        assert!(
3509            p.kv_cache.seq_len() <= 6 + 1,
3510            "cache must stay bounded by max_seq_len (got {})",
3511            p.kv_cache.seq_len()
3512        );
3513    }
3514
3515    #[test]
3516    fn confidence_matches_tokens_and_is_a_probability() {
3517        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
3518        p.sampler_config.temperature = 0.0;
3519        p.sampler_config.repetition_penalty = 1.0;
3520        let r = p.generate("abcd", 10, None, None).unwrap();
3521        assert_eq!(
3522            r.token_confidence.len(),
3523            r.token_ids.len(),
3524            "one confidence per emitted token"
3525        );
3526        for &c in &r.token_confidence {
3527            assert!((0.0..=1.0).contains(&c), "confidence out of [0,1]: {c}");
3528        }
3529        // top1_prob is a valid softmax probability.
3530        let logits = [1.0f32, 3.0, 0.5, 3.0];
3531        let p0 = top1_prob_t(&logits, 1, 1.0);
3532        let p1 = top1_prob_t(&logits, 3, 1.0);
3533        assert!((p0 - p1).abs() < 1e-6, "equal logits → equal prob");
3534        assert!(p0 > 0.0 && p0 < 1.0);
3535        // Calibration temperature > 1 softens an over-confident peak.
3536        let sharp = top1_prob_t(&logits, 1, 1.0);
3537        let soft = top1_prob_t(&logits, 1, 2.0);
3538        assert!(soft < sharp, "higher temperature lowers peak confidence");
3539    }
3540
3541    #[test]
3542    fn trace_is_opt_in_and_parallels_the_output() {
3543        // Off by default: the runtime is silent unless observation asked.
3544        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
3545        p.sampler_config.temperature = 0.0;
3546        p.sampler_config.repetition_penalty = 1.0;
3547        let r = p.generate("abcd", 10, None, None).unwrap();
3548        assert!(r.traces.is_empty(), "trace must be empty unless enabled");
3549
3550        // On: exactly one row per emitted token, aligned with the output.
3551        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
3552        p.sampler_config.temperature = 0.0;
3553        p.sampler_config.repetition_penalty = 1.0;
3554        p.set_trace(true);
3555        let r = p.generate("abcd", 10, None, None).unwrap();
3556        assert_eq!(r.traces.len(), r.token_ids.len(), "one trace row per token");
3557        for (i, tr) in r.traces.iter().enumerate() {
3558            assert_eq!(tr.t, i, "trace index is sequential");
3559            assert_eq!(tr.token_id, r.token_ids[i], "trace token_id matches output");
3560            assert_eq!(
3561                tr.confidence, r.token_confidence[i],
3562                "trace confidence matches the confidence channel"
3563            );
3564            // No dynamic router in this pipeline → no skill, no coherence.
3565            assert!(tr.active_skill.is_none() && tr.recon.is_none() && !tr.switched);
3566        }
3567    }
3568
3569    #[test]
3570    fn explain_prefill_logits_match_greedy_first_token() {
3571        // `cortiq explain` shows the next-token distribution from
3572        // prefill_next_logits; its argmax must equal what greedy generate
3573        // actually emits first — otherwise explain would lie.
3574        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
3575        p.sampler_config.temperature = 0.0;
3576        p.sampler_config.repetition_penalty = 1.0;
3577        let ids = p.tokenizer.encode("abcd");
3578        let logits = p.prefill_next_logits(&ids, None);
3579        let argmax = logits
3580            .iter()
3581            .enumerate()
3582            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
3583            .unwrap()
3584            .0 as u32;
3585        let r = p.generate("abcd", 1, None, None).unwrap();
3586        assert_eq!(argmax, r.token_ids[0], "explain preview must match greedy emit");
3587    }
3588}