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    GdnCfg, GdnWeights, ShortConvCfg, ShortConvWeights, VmfPhaseCfg, VmfPhaseWeights, gdn_forward,
14    gdn_pair, short_conv_forward, short_conv_forward_batch, short_conv_pair, vmf_phase_forward,
15    vmf_phase_pair,
16};
17use crate::pool::Pool;
18use crate::qtensor::QTensor;
19use crate::sampler::{self, SamplerConfig, SamplerScratch, SplitMix64};
20use crate::tokenizer::Tokenizer;
21use cortiq_core::mask::TaskMask;
22use cortiq_core::types::NormStyle;
23
24pub static GLOBAL_USE_GPU: std::sync::atomic::AtomicBool =
25    std::sync::atomic::AtomicBool::new(false);
26
27/// Reusable per-pipeline forward scratch: the four norm outputs the
28/// decode paths recompute every layer (single: n1/p1; pair: all four).
29/// Plain buffers, resized once — steady-state decode reuses them.
30struct ForwardScratch {
31    n1: Vec<f32>,
32    n2: Vec<f32>,
33    p1: Vec<f32>,
34    p2: Vec<f32>,
35}
36
37impl ForwardScratch {
38    fn new(hidden: usize) -> Self {
39        Self {
40            n1: vec![0.0; hidden],
41            n2: vec![0.0; hidden],
42            p1: vec![0.0; hidden],
43            p2: vec![0.0; hidden],
44        }
45    }
46}
47
48/// Complete inference pipeline state.
49pub struct Pipeline {
50    /// Arc: the server shares one tokenizer handle across request
51    /// handlers without borrowing a pipeline slot.
52    pub tokenizer: std::sync::Arc<Tokenizer>,
53    pub kv_cache: KvCache,
54    pub sampler_config: SamplerConfig,
55    pub weights: PipelineWeights,
56    pub hidden_size: usize,
57    pub intermediate_size: usize,
58    pub num_heads: usize,
59    pub num_kv_heads: usize,
60    pub head_dim: usize,
61    /// Total virtual layers (num_layers × num_loops for looped models).
62    pub num_layers: usize,
63    /// Physical layers in weights.layers (≤ num_layers for looped models).
64    pub physical_layers: usize,
65    /// Looped Transformer: apply final norm after each loop iteration.
66    pub loop_final_norm: bool,
67    pub vocab_size: usize,
68    pub rms_eps: f64,
69    pub rope_base: f32,
70    pub norm_style: NormStyle,
71    /// RoPE dims actually rotated (≤ head_dim; Qwen3.5 uses head_dim/4).
72    pub rotary_dim: usize,
73    /// Optional Q-head count override for each attention layer (Laguna).
74    pub attention_heads_per_layer: Option<Vec<usize>>,
75    /// Linear-core geometry (present when the model has linear layers).
76    pub vmf_cfg: Option<VmfPhaseCfg>,
77    /// GatedDeltaNet geometry (faithful vendor operator).
78    pub gdn_cfg: Option<GdnCfg>,
79    /// MiniCPM-class logit scale (tied lm_head → cannot fold into weights).
80    pub logit_multiplier: Option<f32>,
81    /// Cooperative cancel: set from any thread (FFI `cortiq_cancel`,
82    /// a dropped server connection); the generate loop checks it at
83    /// every prefill chunk and decode step and finishes with
84    /// `finish_reason: "cancelled"`. Auto-cleared when honoured.
85    pub cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
86    /// Token ids currently materialized in the KV cache (the forwarded
87    /// prompt + all generated tokens except the last, which is sampled
88    /// but not yet forwarded). Lets the next generate call prefill only
89    /// the suffix when a chat app resends the whole history.
90    pub kv_history: Vec<u32>,
91    /// KDA geometry (Kimi Linear / Kimi-K3) — shared by every Kda layer.
92    pub kda_cfg: Option<crate::linear_core::KdaCfg>,
93    /// Gemma-3n stack (AltUp/LAuReL/PLE/KV-sharing): its own forward —
94    /// weights.layers stays empty, the KV caches are the shared ones.
95    pub g3n: Option<Box<(crate::g3n::G3nGlobals, Vec<crate::g3n::G3nLayer>)>>,
96    /// LFM2 short-convolution geometry (present when the model has
97    /// `ShortConv` mixer layers).
98    pub short_conv_cfg: Option<ShortConvCfg>,
99    /// Multi-token-prediction head (None = absent).
100    pub mtp: Option<MtpModule>,
101    /// Speculative decode via MTP (greedy only; `CMF_MTP=0` disables).
102    pub speculative: bool,
103    rng: SplitMix64,
104    sampler_scratch: SamplerScratch,
105    /// Precomputed RoPE inverse frequencies [head_dim/2]. Arc: the
106    /// forward path clones a handle to escape the &mut self borrow —
107    /// cloning the table itself was a per-forward allocation.
108    pub(crate) inv_freq: std::sync::Arc<Vec<f32>>,
109    /// Reusable norm buffers for the decode hot path (roadmap §3 P0:
110    /// steady-state forward should not heap-allocate). Disjoint field
111    /// from `weights`/`kv_cache`, so split borrows keep working.
112    ws: ForwardScratch,
113    /// Persistent worker pool (None = serial; see CMF_THREADS).
114    pool: Option<std::sync::Arc<Pool>>,
115    // ── Dynamic per-token skill routing (spec §9, claim 14/16) ──
116    /// Source model, retained so a skill switch can re-resolve the
117    /// touched layers' FFN tensors (Mapped = mmap pointers, cheap).
118    pub(crate) model: Option<std::sync::Arc<cortiq_core::CmfModel>>,
119    /// Masks present → weights are dequantized f32 (rebuild path).
120    pub(crate) dyn_force_f32: bool,
121    /// Per-skill FFN layers actually replaced (derived from tensors, not
122    /// the meta `layers` field — ru2 replaces down_proj in 0..23 while
123    /// its meta says [20..23]). None = skill touches non-FFN tensors →
124    /// ineligible for cheap dynamic switching (honest refusal).
125    pub(crate) dyn_skill_layers: Vec<Option<Vec<usize>>>,
126    /// Currently overlaid skill (index into model.header.skills); None =
127    /// backbone. Set at load time to the statically-overlaid skill so
128    /// `set_active_skill(None)` correctly reverts it (else a static
129    /// skill would silently persist — the union-diff assumes dyn_active
130    /// always mirrors the live overlay). Switched by `set_active_skill`.
131    pub(crate) dyn_active: Option<usize>,
132    /// Pipeline was loaded with a soft blend (materialized working
133    /// tensors, not a single skill index) → dynamic routing refuses:
134    /// there is no single index to revert the blend from.
135    pub(crate) dyn_blend_loaded: bool,
136    /// Layer whose post-residual hidden feeds the router φ (shared by
137    /// swarm skills). None = φ capture off.
138    pub(crate) dyn_phi_layer: Option<usize>,
139    /// EMA of φ at `dyn_phi_layer` over the decode window (on-policy).
140    dyn_phi_ema: Vec<f32>,
141    dyn_phi_seen: usize,
142    /// Hysteresis router driving per-token skill switches during decode
143    /// (None = static/no dynamic routing). Taken out during generation.
144    pub dyn_router: Option<crate::swarm::DynRouter>,
145    /// O(1) Nyström attention setting (CLI/env/header-hint resolved by
146    /// the caller; None = plain cache attention everywhere).
147    o1_cfg: Option<crate::nystrom::O1Cfg>,
148    /// Bumped at every o1 seal — the GPU state mirror re-uploads when it
149    /// sees a new epoch (each generate seals fresh CPU state).
150    o1_epoch: u64,
151    /// Per-layer o1 flags derived from `o1_cfg` (Full layers only).
152    o1_flags: Vec<bool>,
153    /// Emit a structured per-token trace (B4 telemetry channel). Off by
154    /// default — the runtime is silent unless observation is requested.
155    trace: bool,
156    /// Confidence-calibration temperature (B1): reported Born mass is
157    /// softmax(logits / calib_temp). 1.0 = raw. Set from header.calibration.
158    calib_temp: f32,
159    /// Process-unique id keying this pipeline's device KV mirrors.
160    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
161    graph_kv_id: u64,
162    /// Decode asks the token graph to also run final-norm + lm_head on
163    /// the device (drops the separate per-op lm_head round trip).
164    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
165    graph_want_logits: bool,
166    /// Logits the graph produced for the token just forwarded (taken by
167    /// the decode loop; None = compute on the CPU path).
168    graph_logits: Option<Vec<f32>>,
169    /// Token embeddings are multiplied by this at input (Gemma: √hidden).
170    pub embed_multiplier: f32,
171    /// Attention score scale (1/√head_dim unless the arch overrides —
172    /// Gemma's query_pre_attn_scalar).
173    pub attn_scale: f32,
174    /// Sliding-window attention: (window, every-Nth-layer-is-global
175    /// pattern) — Gemma-3.
176    pub swa: Option<(usize, usize)>,
177    /// Explicit local/global schedule for architectures that cannot be
178    /// represented by Gemma's every-Nth-global convention.
179    pub sliding_layers: Option<Vec<bool>>,
180    /// RoPE table of the sliding (local) layers, when they use their
181    /// own base frequency (Gemma-3: 10k local vs 1M global).
182    pub inv_freq_local: Option<std::sync::Arc<Vec<f32>>>,
183    pub rotary_dim_local: Option<usize>,
184    pub rope_scale: f32,
185    pub rope_scale_local: f32,
186    /// Gemma-4: global layers run their own geometry — (head_dim,
187    /// num_kv_heads); sliding layers keep the base fields.
188    pub global_attn: Option<(usize, usize)>,
189    /// Gemma-4: the global layers' proportional RoPE table (len
190    /// global_head_dim/2, zero-padded tail = identity rotation).
191    pub inv_freq_global: Option<std::sync::Arc<Vec<f32>>>,
192    /// Scale-less RMS normalization of V heads before caching (Gemma-4).
193    pub attn_v_norm: bool,
194    /// Final-logit soft-capping C: logits = C·tanh(logits/C) (Gemma-4).
195    pub final_softcap: Option<f32>,
196    /// Gemma-2 attention-logit soft-capping (0.0 = off).
197    pub attn_softcap: f32,
198    /// Compute per-token Born confidence (a full-vocab softmax each
199    /// token). On by default; `bench --core` turns it off to match
200    /// llama-bench's core timing.
201    confidence_on: bool,
202}
203
204#[cfg(target_os = "macos")]
205impl Drop for Pipeline {
206    fn drop(&mut self) {
207        crate::gpu::kv_mirror_drop(self.graph_kv_id);
208    }
209}
210
211/// Model weights. Matrices are `QTensor` (owned f32 for small models
212/// and tests — bit-identical to the historical paths — or quantized
213/// bytes zero-copy from the CMF mmap for big models). 1-D norms are
214/// always small and stay f32.
215pub struct PipelineWeights {
216    /// Embedding table: [vocab_size, hidden_size]
217    pub embed_tokens: QTensor,
218    /// Per-layer weights
219    pub layers: Vec<LayerWeights>,
220    /// LM head: [vocab_size, hidden_size]
221    pub lm_head: QTensor,
222    /// Final norm: [hidden_size]
223    pub final_norm: Vec<f32>,
224}
225
226/// One transformer layer: shared norms + MLP, attention by kind.
227pub struct LayerWeights {
228    pub input_norm: Vec<f32>,
229    /// The pre-FFN norm (`post_attention_layernorm` classically;
230    /// `pre_feedforward_layernorm` on Gemma-2/3 sandwich layers).
231    pub post_norm: Vec<f32>,
232    /// Gemma-2/3 sandwich: norm applied to the ATTENTION OUTPUT before
233    /// its residual add (`post_attention_layernorm` there).
234    pub attn_out_norm: Option<Vec<f32>>,
235    /// Gemma-4: the whole layer output is multiplied by this scalar.
236    pub layer_scale: Option<f32>,
237    /// Gemma-2/3 sandwich: norm applied to the FFN OUTPUT before its
238    /// residual add (`post_feedforward_layernorm`).
239    pub ffn_out_norm: Option<Vec<f32>>,
240    pub ffn: FfnKind,
241    pub attn: AttnKind,
242}
243
244/// FFN gate activation: SiLU (SwiGLU family) or tanh-GELU (Gemma's
245/// GeGLU). A property of the model, carried on every FFN triple.
246#[derive(Clone, Copy, PartialEq, Debug, Default)]
247pub enum Act {
248    #[default]
249    Silu,
250    GeluTanh,
251    /// Kimi-K3 SituAndMul: BOTH halves transform —
252    /// a = β·tanh(g/β)·σ(g), up' = linβ·tanh(u/linβ) (linβ>0), out = a·up'.
253    Situ { beta: f32, linear_beta: f32 },
254}
255
256impl Act {
257    pub fn from_arch(name: &str) -> Self {
258        if name == "gelu_tanh" {
259            Self::GeluTanh
260        } else {
261            Self::Silu
262        }
263    }
264
265    /// Arch-driven constructor (activation name + situ betas).
266    pub fn from_arch_full(arch: &cortiq_core::ModelArch) -> Self {
267        match arch.hidden_act.as_str() {
268            "situ" => Self::Situ {
269                beta: arch.activation_situ_beta.unwrap_or(1.0) as f32,
270                linear_beta: arch.activation_situ_linear_beta.unwrap_or(0.0) as f32,
271            },
272            other => Self::from_arch(other),
273        }
274    }
275
276    #[inline]
277    pub fn apply(self, x: f32) -> f32 {
278        match self {
279            Self::Silu => inference::silu(x),
280            Self::GeluTanh => inference::gelu_tanh(x),
281            Self::Situ { beta, .. } => beta * (x / beta).tanh() * (1.0 / (1.0 + (-x).exp())),
282        }
283    }
284
285    /// Gated combine — the FFN contract. Situ transforms the UP half
286    /// too, so callers must use this instead of apply(g)·u.
287    #[inline]
288    pub fn combine(self, g: f32, u: f32) -> f32 {
289        match self {
290            Self::Situ { linear_beta, .. } if linear_beta > 0.0 => {
291                self.apply(g) * (linear_beta * (u / linear_beta).tanh())
292            }
293            _ => self.apply(g) * u,
294        }
295    }
296}
297
298/// Dense gated triple — the FFN of a dense layer or of one expert.
299pub struct DenseFfn {
300    pub gate_proj: QTensor,
301    pub up_proj: QTensor,
302    pub down_proj: QTensor,
303    /// Gate activation (SiLU default; Gemma: tanh-GELU).
304    pub act: Act,
305}
306
307/// FFN operator of a layer, decided by tensor presence at load time
308/// (router `mlp.gate.weight` in the directory = MoE layer).
309pub enum FfnKind {
310    Dense(DenseFfn),
311    /// Mixture-of-Experts (Qwen2-MoE / Qwen3-MoE): softmax over ALL
312    /// expert logits → top-k, optional renorm; experts stay quantized
313    /// in mmap — only the selected ones are touched per token.
314    Moe(MoeFfn),
315    /// Gemma-4 MoE: a dense MLP branch AND a routed-expert branch in
316    /// the SAME layer, each with its own norm sandwich. The dense
317    /// branch reads the pre-FFN-normed input; the expert branch (and
318    /// the router) read the RAW residual through `pre_norm_2`:
319    ///   d = post_norm_1(dense(x̂));  m = post_norm_2(Σwₑ·FFNₑ(pre_norm_2(h)))
320    ///   ffn_out = d + m   (the caller's ffn_out_norm + residual follow)
321    DenseMoe(Box<DenseMoeFfn>),
322}
323
324/// Gemma-4 dual-branch FFN (see `FfnKind::DenseMoe`).
325pub struct DenseMoeFfn {
326    pub dense: DenseFfn,
327    pub moe: MoeFfn,
328    /// post_feedforward_layernorm_1 — dense-branch output norm.
329    pub post_norm_1: Vec<f32>,
330    /// pre_feedforward_layernorm_2 — expert-branch input norm (applied
331    /// to the RAW residual, not the pre-FFN-normed activation).
332    pub pre_norm_2: Vec<f32>,
333    /// post_feedforward_layernorm_2 — expert-branch output norm.
334    pub post_norm_2: Vec<f32>,
335}
336
337pub struct MoeFfn {
338    /// Router `mlp.gate.weight` [num_experts, hidden].
339    pub router: QTensor,
340    pub experts: Vec<DenseFfn>,
341    pub top_k: usize,
342    pub norm_topk_prob: bool,
343    /// Router scores per-expert with a sigmoid (LFM2-MoE / DeepSeek-V3
344    /// `noaux_tc`) instead of a softmax over all experts (Qwen).
345    pub router_sigmoid: bool,
346    /// Per-expert selection bias `mlp.expert_bias` [num_experts]
347    /// (LFM2-MoE): added to the sigmoid scores for the top-k CHOICE only;
348    /// the gathered weights use the unbiased scores. None = no bias.
349    pub expert_bias: Option<Vec<f32>>,
350    /// Top-k weights are multiplied by this after the optional renorm
351    /// (LFM2-MoE `routed_scaling_factor`; 1.0 = off).
352    pub routed_scaling: f32,
353    /// Adaptive routing (CMF_MOE_TAU, opt-in): keep the smallest
354    /// prefix of the top-k whose renormalized mass reaches τ —
355    /// confident tokens touch 1–2 experts, flat ones keep all k.
356    /// MoE decode is memory-bound, so skipped experts are skipped
357    /// weight traffic. None = classic fixed top-k (bit-identical).
358    pub route_tau: Option<f32>,
359    /// Always-on shared expert. Qwen2-MoE carries an additional sigmoid
360    /// gate; Laguna adds the shared expert unconditionally (`None`).
361    pub shared: Option<(DenseFfn, Option<QTensor>)>,
362    /// Expert-selection counters (truncated Fisher B-field of claim 12:
363    /// routing frequency during calibration). Filled by every forward,
364    /// read by the CLI via CMF_MOE_STATS. RefCell: decode is single-threaded.
365    pub stats: std::cell::RefCell<Vec<u64>>,
366    /// Per-CHANNEL sum of squares of this FFN's input, accumulated over a
367    /// calibration run (`CMF_RMS_TRACE`). These are the RMS activation
368    /// traces AWNP needs: raw weight magnitude says every channel matters
369    /// equally, and the question AWNP asks is whether the ACTIVATIONS
370    /// disagree. Off unless the env var is set — an f64 add per channel
371    /// per token is cheap, but not free.
372    pub act_sq: std::cell::RefCell<Vec<f64>>,
373    /// Raw FFN-input rows captured for the layers named by `CMF_ACT_DUMP`
374    /// (`"9,19"`). AWNP is nullspace PROJECTION: after dropping channels the
375    /// survivors are refitted to absorb what was removed, and how much they
376    /// can absorb depends on the activation COVARIANCE, not on per-channel
377    /// RMS. Per-channel numbers can only bound the cost from above.
378    pub act_rows: std::cell::RefCell<Vec<f32>>,
379    /// Task mask over routed experts (DTG-MA over MoE, claim-12 B-field
380    /// applied): `false` experts are excluded from selection, the
381    /// softmax renormalizes over the allowed set. Built by the loader
382    /// from CMF_MOE_MASK=<stats.json> + CMF_MOE_MASK_COVER. None = all.
383    pub mask: Option<Vec<bool>>,
384    /// Gemma-4: per-expert weight scale applied AFTER the top-k renorm
385    /// (`router.per_expert_scale`). None = 1.0 everywhere.
386    pub per_expert_scale: Option<Vec<f32>>,
387    /// Gemma-4: the router reads a SCALE-LESS rms-norm of its input
388    /// (the constant gain router.scale·√hidden is folded into the
389    /// router weights at convert time).
390    pub router_input_norm: bool,
391}
392
393/// Attention operator of a layer. Extension point: new operators are
394/// new variants here + a forward in their own module.
395pub enum AttnKind {
396    /// GQA softmax attention (+ optional Qwen3.5 qk-norm / output gate).
397    Full {
398        wq: QTensor,
399        wk: QTensor,
400        wv: QTensor,
401        wo: QTensor,
402        q_norm: Option<Vec<f32>>,
403        k_norm: Option<Vec<f32>>,
404        output_gate: bool,
405        /// Laguna: a separate softplus projection applied to the attention
406        /// output before O. The bool means one scalar per head (broadcast
407        /// across head_dim); false means one scalar per element.
408        softplus_gate: Option<(QTensor, bool)>,
409        /// Qwen2-family projection biases (q, k, v).
410        bias: Option<(Vec<f32>, Vec<f32>, Vec<f32>)>,
411    },
412    /// Canonical linear core (VMF phase attention).
413    Linear(VmfPhaseWeights),
414    /// Faithful vendor linear operator (Qwen3.5 GatedDeltaNet).
415    LinearGdn(GdnWeights),
416    /// LFM2 gated short-convolution mixer (no KV cache; conv ring state
417    /// lives in the layer's `linear_state`).
418    ShortConv(ShortConvWeights),
419    /// DeepSeek-V2 Multi-head Latent Attention. v1 executes it as
420    /// expand-to-MHA: the latent is projected per token, K/V expand to
421    /// every head and live in the ordinary cache (K head layout
422    /// [rope | nope] so the standard partial rotary covers the shared
423    /// rope key; V rows are zero-padded to the K head_dim and the pad
424    /// is sliced off before O). Latent-resident cache is a later
425    /// optimization, not a semantic change.
426    Mla(Box<MlaWeights>),
427    /// Kimi Delta Attention (Kimi Linear / Kimi-K3): per-channel decayed
428    /// delta rule, separate q/k/v short convs, sigmoid-gated output norm.
429    /// State lives in the layer's `linear_state` (no KV cache).
430    Kda(Box<crate::linear_core::KdaWeights>),
431}
432
433/// DeepSeek-V2 MLA projections (see `AttnKind::Mla`).
434pub struct MlaWeights {
435    /// `[nh·(rope+nope), hidden]` (or `[…, q_lora]` when compressed) —
436    /// the converter permutes each head rope-first so rotary_dim =
437    /// qk_rope works unchanged.
438    pub q_proj: QTensor,
439    /// Compressed q (K3/V3 class): x → q_a `[q_lora, hidden]` →
440    /// rms(q_a_norm) → q_proj (= q_b). None = direct q (V2-Lite).
441    pub q_a: Option<QTensor>,
442    pub q_a_norm: Option<Vec<f32>>,
443    /// `kv_a_proj_with_mqa` `[lora + rope, hidden]` (latent first).
444    pub kv_a: QTensor,
445    /// RMS-norm weights over the latent (`kv_a_layernorm`, [lora]).
446    pub kv_a_norm: Vec<f32>,
447    /// `[nh·(nope+v), lora]` — per head [k_nope | v].
448    pub kv_b: QTensor,
449    /// `[hidden, nh·v]`.
450    pub o_proj: QTensor,
451    pub nh: usize,
452    pub qk_rope: usize,
453    pub qk_nope: usize,
454    pub v_dim: usize,
455    pub lora: usize,
456    /// Softmax scale (1/√(rope+nope), YaRN-mscale-corrected at load).
457    pub scale: f32,
458    /// Kimi Linear NoPE: skip the rotary entirely (layout unchanged).
459    pub nope: bool,
460}
461
462/// Multi-token-prediction head (DeepSeek/Qwen style, spec §2.1):
463/// `x = eh_proj·[enorm(embed(next)); hnorm(hidden)]` → one transformer
464/// block over its own KV → shared lm_head. Drafts the token after next;
465/// the main model verifies, so output is exact — MTP only buys speed.
466pub struct MtpModule {
467    pub enorm: Vec<f32>,
468    pub hnorm: Vec<f32>,
469    /// [hidden, 2·hidden]
470    pub eh_proj: QTensor,
471    pub layer: LayerWeights,
472    pub final_norm: Vec<f32>,
473    pub kv: crate::kv_cache::LayerKvCache,
474}
475
476/// Result of a generation call.
477pub struct GenerateResult {
478    pub text: String,
479    pub token_ids: Vec<u32>,
480    pub prompt_tokens: usize,
481    pub tokens_generated: usize,
482    pub finish_reason: String,
483    /// Speculative-decode stats (0/0 when MTP is absent or inactive).
484    pub mtp_drafted: usize,
485    pub mtp_accepted: usize,
486    /// Per-generated-token confidence = softmax probability of the token
487    /// that was actually emitted (Born mass on the chosen state). High =
488    /// the model was sure; low = it was guessing. Same length as the
489    /// generated slice of `token_ids`.
490    pub token_confidence: Vec<f32>,
491    /// Structured per-token telemetry (B4 channel). Empty unless
492    /// `set_trace(true)`; otherwise same length as the generated slice.
493    pub traces: Vec<TokenTrace>,
494}
495
496/// One row of the structured telemetry trace (B4): the model's internal
497/// routing state at the moment a token was emitted. Every field is a
498/// quantity the runtime already computes — nothing is inferred or
499/// estimated (anti-principle: only measured bytes).
500#[derive(Clone, Debug)]
501pub struct TokenTrace {
502    /// 0-based index within the generated slice.
503    pub t: usize,
504    /// The emitted token id.
505    pub token_id: u32,
506    /// Born mass on the emitted token (softmax prob) — how sure the model was.
507    pub confidence: f32,
508    /// Skill in force while this token was generated (None = backbone).
509    pub active_skill: Option<String>,
510    /// Recon error E = ‖r−BBᵀr‖²/‖φ‖² at the last routing eval — coherence
511    /// with the active skill's subspace (low = coherent). None = no router
512    /// or not yet evaluated.
513    pub recon: Option<f32>,
514    /// The router changed the active skill right after this token (a
515    /// domain boundary crossed under the hysteresis barrier).
516    pub switched: bool,
517}
518
519/// Calibrated softmax probability of `id` under `logits` (the Born mass on
520/// the emitted token) — the confidence signal, cheap from logits already
521/// computed for sampling. `temp` is the calibration temperature (B1):
522/// softmax(logits / temp); 1.0 = raw.
523fn top1_prob_t(logits: &[f32], id: u32, temp: f32) -> f32 {
524    let t = if temp > 1e-3 { temp } else { 1.0 };
525    let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
526    let sum: f32 = logits.iter().map(|&v| ((v - max) / t).exp()).sum();
527    if sum > 0.0 {
528        (((logits[id as usize] - max) / t).exp()) / sum
529    } else {
530        0.0
531    }
532}
533
534/// prefill-GEMM enabled? (CMF_PREFILL=seq — emergency fallback to the
535/// sequential path.)
536fn prefill_batched() -> bool {
537    std::env::var("CMF_PREFILL")
538        .map(|v| v != "seq")
539        .unwrap_or(true)
540}
541
542/// Prefill chunk (positions per batched pass). On macOS the AMX GEMM
543/// path wants tall panels — M=48 starves the matrix units (ggml uses
544/// ubatch 512); elsewhere the historical 48 stays. CMF_PREFILL_CHUNK
545/// overrides.
546fn prefill_chunk() -> usize {
547    if let Some(n) = std::env::var("CMF_PREFILL_CHUNK")
548        .ok()
549        .and_then(|v| v.parse::<usize>().ok())
550    {
551        return n.max(1);
552    }
553    if cfg!(target_os = "macos") {
554        512
555    } else if cfg!(target_arch = "aarch64") {
556        // Mobile: big enough to feed the batched attend (gate b ≥ 32)
557        // and the blocked SDOT GEMM without the memory of 512.
558        256
559    } else {
560        48
561    }
562}
563
564/// Callback for streaming tokens. Return `false` to cancel.
565pub type TokenCallback = Box<dyn FnMut(&str) -> bool + Send>;
566
567impl Pipeline {
568    /// Map a virtual layer index to its physical weight index.
569    /// Looped Transformer (Nanbeige 4.2): 22 physical layers × 2 loops = 44 virtual;
570    /// virtual layer 23 maps back to physical layer 1 (23 % 22 = 1).
571    #[inline]
572    pub fn phys_layer(&self, virtual_idx: usize) -> usize {
573        virtual_idx % self.physical_layers
574    }
575
576    /// True when `virtual_idx` is the last layer of a loop iteration
577    /// (used for loop_final_norm insertion).
578    #[inline]
579    pub fn is_loop_end(&self, virtual_idx: usize) -> bool {
580        self.loop_final_norm && (virtual_idx + 1) % self.physical_layers == 0
581    }
582
583    /// Build a pipeline from parts (used by the loader and tests).
584    #[allow(clippy::too_many_arguments)]
585
586    /// Whole-block q1 token graph on the GPU (macOS/Metal): the run of
587    /// consecutive q1 layers — GDN *and* full attention — starting at
588    /// `start` executes as few command buffers as the CPU truly needs.
589    /// Hidden stays device-resident across every layer; the only syncs
590    /// are before each CPU attend (it needs q/k/v and owns the KV
591    /// cache) and the final hidden readback. Recurrent states
592    /// round-trip through shared memory (the CPU stays their owner, so
593    /// every other path remains coherent). Returns the first layer
594    /// index NOT covered (== `start` → refused, caller falls through
595    /// to the per-layer CPU path).
596    /// Should prefill run position-by-position through the GPU token
597    /// graph instead of the batched CPU chunk-GEMM? True for q1 GDN
598    /// hybrids on native Metal: their chunk prefill is walled by the
599    /// sequential scalar recurrence, so the graph's decode rate wins.
600    /// NOT for Looped Transformers, despite the per-chunk loop_final_norm
601    /// sync: the chunk-GEMM amortizes each weight over the whole chunk,
602    /// which the per-position graph cannot (Nanbeige 4.2 on M4, 512-token
603    /// prompt: 85 tok/s chunked vs 14 through the graph).
604    #[cfg(target_os = "macos")]
605    fn graph_prefill_preferred(&self) -> bool {
606        if !crate::gpu::enabled_here()
607            || !crate::gpu::q1_force()
608            || std::env::var("CMF_GPU_BLOCK")
609                .map(|v| v == "0")
610                .unwrap_or(false)
611        {
612            return false;
613        }
614        self.weights
615            .layers
616            .iter()
617            .any(|lw| matches!(&lw.attn, AttnKind::LinearGdn(w) if w.in_proj_qkv.is_q1()))
618    }
619
620    #[cfg(not(target_os = "macos"))]
621    fn graph_prefill_preferred(&self) -> bool {
622        // Discrete-GPU wgpu whole-token graph: GDN layers carry recurrent state
623        // (conv ring + delta-rule S) resident on the GPU. A batched CPU prefill
624        // builds that state on the CPU only, leaving the GPU buffers zeroed at
625        // decode → garbage. Route GDN-hybrid prefill through the graph one
626        // position at a time so the resident state is seeded exactly as decode
627        // will read it. Pure-attention models keep the batched CPU prefill (its
628        // KV mirror re-syncs from the CPU cache, so no seeding gap).
629        let graph_on = std::env::var("CMF_GPU_WGPU_GRAPH")
630            .map(|v| v != "0")
631            .unwrap_or_else(|_| {
632                // Default ON for wgpu on DISCRETE adapters (4090:
633                // decode 76 -> 137 tok/s); integrated/mobile GPUs keep
634                // the per-op probe path — see gpu::wgpu_graph_default.
635                crate::gpu::wgpu_graph_default()
636            });
637        if !graph_on || !crate::gpu::enabled_here() {
638            return false;
639        }
640        self.weights
641            .layers
642            .iter()
643            .any(|lw| matches!(&lw.attn, AttnKind::LinearGdn(_)))
644    }
645
646    #[cfg(target_os = "macos")]
647    fn q1_graph_gpu(
648        &mut self,
649        start: usize,
650        upto: Option<usize>,
651        position: usize,
652        h: &mut [f32],
653    ) -> usize {
654        use crate::gpu::{AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, GraphDims, TokenGraph};
655        if self.attn_softcap > 0.0 // capped scores: no graph kernel — CPU path
656            || !crate::gpu::enabled_here()
657            || !crate::gpu::q1_force()
658            || std::env::var("CMF_GPU_BLOCK")
659                .map(|v| v == "0")
660                .unwrap_or(false)
661        {
662            return start;
663        }
664        // The graph encodes SiLU FFN, 1/√hd attention scores and
665        // full-context attend with no branch norms — Gemma-style archs
666        // (sliding window, scale override, sandwich norms, GeLU) fall
667        // back to the CPU path.
668        if self.swa.is_some()
669            || self.global_attn.is_some()
670            || self.attention_heads_per_layer.is_some()
671            || self.attn_v_norm
672            || (self.attn_scale - 1.0 / (self.head_dim as f32).sqrt()).abs() > 1e-9
673            || self.weights.layers.iter().any(|lw| {
674                lw.attn_out_norm.is_some()
675                    || lw.ffn_out_norm.is_some()
676                    || lw.layer_scale.is_some()
677                    || matches!(&lw.ffn, FfnKind::Dense(d) if d.act != Act::Silu)
678            })
679        {
680            return start;
681        }
682        // Looped Transformer: the graph covers ALL loop iterations;
683        // encode_loop_norm is inserted on-device at each boundary.
684        let limit = upto
685            .map(|u| u + 1)
686            .unwrap_or(self.num_layers)
687            .min(self.num_layers);
688
689        enum Item<'a> {
690            Gdn {
691                run: Vec<GdnGpuLayer<'a>>,
692                first: usize,
693            },
694            Attn {
695                l: AttnGpuLayer<'a>,
696                li: usize,
697                q_norm: Option<&'a [f32]>,
698                k_norm: Option<&'a [f32]>,
699                output_gate: bool,
700                bias: Option<(&'a [f32], &'a [f32], &'a [f32])>,
701                /// Attend on the device too (no sync): F32 KV, no
702                /// o1/bias, dims inside the kernels' contract.
703                full_gpu: bool,
704            },
705        }
706
707        // Device-attend eligibility shared by every Full layer.
708        let attend_mode = std::env::var("CMF_GPU_ATTEND").unwrap_or_else(|_| "auto".into());
709        let dev_attend = attend_mode != "0"
710            && attend_mode != "off"
711            // hd=256 is correct on the widened kernel but measured slower
712            // than the CPU sandwich on M4 at decode depths. Keep it as an
713            // explicit research lever without regressing Qwopus by default.
714            && (self.head_dim <= 128 || attend_mode == "force" || attend_mode == "256")
715            && self.head_dim % 4 == 0
716            && self.head_dim <= 256
717            && self.rotary_dim >= 2
718            && self.rotary_dim <= self.head_dim
719            && (self.rotary_dim / 2) % 32 == 0
720            && self.num_kv_heads > 0
721            && self.num_heads % self.num_kv_heads == 0;
722
723        let mut plan: Vec<Item> = Vec::new();
724        let mut model_ref: Option<std::sync::Arc<cortiq_core::CmfModel>> = None;
725        let mut scan = start;
726        while scan < limit {
727            let lw = &self.weights.layers[self.phys_layer(scan)];
728            let FfnKind::Dense(d) = &lw.ffn else { break };
729            let (Some(g), Some(u), Some(dn)) = (
730                d.gate_proj.q1_parts(),
731                d.up_proj.q1_parts(),
732                d.down_proj.q1_parts(),
733            ) else {
734                break;
735            };
736            match &lw.attn {
737                AttnKind::LinearGdn(w) if self.gdn_cfg.is_some() => {
738                    let parts = (
739                        w.in_proj_qkv.q1_parts(),
740                        w.in_proj_z.q1_parts(),
741                        w.in_proj_a.f32_parts(),
742                        w.in_proj_b.f32_parts(),
743                        w.out_proj.q1_parts(),
744                    );
745                    let (Some(qkv), Some(z), Some(a), Some(b), Some(out)) = parts else {
746                        break;
747                    };
748                    if let QTensor::Mapped { model, .. } = &w.in_proj_qkv {
749                        model_ref.get_or_insert_with(|| model.clone());
750                    }
751                    let gl = GdnGpuLayer {
752                        attn_norm: &lw.input_norm,
753                        post_norm: &lw.post_norm,
754                        qkv,
755                        z,
756                        a,
757                        b,
758                        out,
759                        gate: g,
760                        up: u,
761                        down: dn,
762                        conv1d: &w.conv1d,
763                        a_log: &w.a_log,
764                        dt_bias: &w.dt_bias,
765                        gnorm: &w.norm,
766                    };
767                    match plan.last_mut() {
768                        Some(Item::Gdn { run, .. }) => run.push(gl),
769                        _ => plan.push(Item::Gdn {
770                            run: vec![gl],
771                            first: scan,
772                        }),
773                    }
774                }
775                AttnKind::Full {
776                    wq,
777                    wk,
778                    wv,
779                    wo,
780                    q_norm,
781                    k_norm,
782                    output_gate,
783                    softplus_gate: None,
784                    bias,
785                } if !self.kv_cache.layers[scan].o1_sealed() => {
786                    let parts = (wq.q1_parts(), wk.q1_parts(), wv.q1_parts(), wo.q1_parts());
787                    let (Some(pq), Some(pk), Some(pv), Some(po)) = parts else {
788                        break;
789                    };
790                    if let QTensor::Mapped { model, .. } = wq {
791                        model_ref.get_or_insert_with(|| model.clone());
792                    }
793                    let cache = &self.kv_cache.layers[scan];
794                    let full_gpu = dev_attend
795                        && cache.mode == crate::kv_cache::KvMode::F32
796                        && cache.o1.is_none()
797                        && bias.is_none()
798                        && pq.1 == self.num_heads * self.head_dim * (1 + *output_gate as usize)
799                        && pk.1 == self.num_kv_heads * self.head_dim
800                        && pv.1 == self.num_kv_heads * self.head_dim
801                        && po.2 == self.num_heads * self.head_dim;
802                    plan.push(Item::Attn {
803                        l: AttnGpuLayer {
804                            attn_norm: &lw.input_norm,
805                            post_norm: &lw.post_norm,
806                            wq: pq,
807                            wk: pk,
808                            wv: pv,
809                            wo: po,
810                            gate: g,
811                            up: u,
812                            down: dn,
813                        },
814                        li: scan,
815                        q_norm: q_norm.as_deref(),
816                        k_norm: k_norm.as_deref(),
817                        output_gate: *output_gate,
818                        bias: bias
819                            .as_ref()
820                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
821                        full_gpu,
822                    });
823                }
824                _ => break,
825            }
826            scan += 1;
827        }
828        let Some(model) = model_ref else { return start };
829        if plan.is_empty() {
830            return start;
831        }
832        let dims = GraphDims {
833            hidden: self.hidden_size,
834            eps: self.rms_eps as f32,
835            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
836        };
837        let Some(mut graph) = TokenGraph::new(&model, dims, h) else {
838            return start;
839        };
840        let gcfg = self.gdn_cfg.map(|cfg| GdnGpuCfg {
841            nv: cfg.num_v_heads,
842            nk: cfg.num_k_heads,
843            dk: cfg.key_head_dim,
844            dv: cfg.value_head_dim,
845            kk: cfg.conv_kernel,
846            hidden: self.hidden_size,
847            inter: self.intermediate_size,
848            c_dim: cfg.conv_dim(),
849            eps: cfg.rms_eps as f32,
850            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
851        });
852        // Validate the whole plan BEFORE encoding anything: after the
853        // first sync a refused layer would leave the token
854        // half-executed, so truncate to the provably encodable prefix.
855        let mut valid = 0usize;
856        let mut end = start;
857        for item in &plan {
858            let ok = match item {
859                Item::Gdn { run, .. } => gcfg
860                    .as_ref()
861                    .map(|gc| run.iter().all(|l| graph.gdn_ok(l, gc)))
862                    .unwrap_or(false),
863                Item::Attn { l, .. } => graph.attn_ok(l),
864            };
865            if !ok {
866                break;
867            }
868            valid += 1;
869            end += match item {
870                Item::Gdn { run, .. } => run.len(),
871                Item::Attn { .. } => 1,
872            };
873        }
874        plan.truncate(valid);
875        if plan.is_empty() {
876            return start;
877        }
878
879        let inv_freq = self.inv_freq.clone();
880        let pool = self.pool.clone();
881        let (nh, nkv, hd, hs, rd, eps) = (
882            self.num_heads,
883            self.num_kv_heads,
884            self.head_dim,
885            self.hidden_size,
886            self.rotary_dim,
887            self.rms_eps,
888        );
889        let norm_style = self.norm_style;
890        let gemma = norm_style == cortiq_core::NormStyle::Gemma;
891        let want = self.gdn_cfg.map(|c| c.state_len()).unwrap_or(0);
892        let kv_id = self.graph_kv_id;
893        // GDN runs whose states await readback after the next sync
894        // (device-attended layers add no sync, so several may stack).
895        let mut pending: Vec<(usize, usize)> = Vec::new();
896        // Device-attended layers: their K/V/imp are pulled from the
897        // mirror after the final sync.
898        let mut dev_attn: Vec<usize> = Vec::new();
899        for item in &plan {
900            // Looped Transformer: insert on-device norm at loop boundaries.
901            if self.loop_final_norm {
902                let item_start = match item {
903                    Item::Gdn { first, .. } => *first,
904                    Item::Attn { li, .. } => *li,
905                };
906                if item_start > start && self.is_loop_end(item_start - 1) {
907                    graph.encode_loop_norm(&self.weights.final_norm);
908                }
909            }
910            match item {
911                Item::Gdn { run, first } => {
912                    for l in &mut self.kv_cache.layers[*first..*first + run.len()] {
913                        if l.linear_state.len() != want {
914                            l.linear_state = vec![0f32; want];
915                        }
916                    }
917                    let ro: Vec<&[f32]> = self.kv_cache.layers[*first..*first + run.len()]
918                        .iter()
919                        .map(|l| l.linear_state.as_slice())
920                        .collect();
921                    if !graph.encode_gdn_run(run, &ro, gcfg.as_ref().unwrap()) {
922                        // Unreachable: the plan was validated above.
923                        tracing::error!("q1 graph: GDN run refused after validation");
924                        return start;
925                    }
926                    // Early commit: the GPU starts the run while the
927                    // CPU encodes the next layer (nothing to wait on).
928                    graph.commit();
929                    pending.push((*first, run.len()));
930                }
931                Item::Attn {
932                    l,
933                    li,
934                    q_norm,
935                    k_norm,
936                    output_gate,
937                    bias,
938                    full_gpu,
939                } => {
940                    // ── Fully device-resident attention: no sync at all.
941                    if *full_gpu {
942                        let cache = &self.kv_cache.layers[*li];
943                        let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
944                        let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
945                        let cpu_stored = cpu_k[0].len() / hd;
946                        let p = crate::gpu::AttnDeviceParams {
947                            kv_id,
948                            layer: *li,
949                            nh,
950                            nkv,
951                            hd,
952                            rd,
953                            position,
954                            eps: eps as f32,
955                            gemma,
956                            output_gate: *output_gate,
957                            q_norm: *q_norm,
958                            k_norm: *k_norm,
959                            inv_freq: &inv_freq,
960                            cpu_k,
961                            cpu_v,
962                            cpu_stored,
963                        };
964                        if graph.attn_device_ok(l, &p) && graph.encode_attn_device(l, &p) {
965                            graph.commit();
966                            dev_attn.push(*li);
967                            continue;
968                        }
969                        // Mirror refused (nothing encoded) → sandwich.
970                    }
971                    graph.encode_attn_prefix(l);
972                    graph.sync();
973                    if !pending.is_empty() {
974                        let idxs: Vec<usize> =
975                            pending.drain(..).flat_map(|(f, n)| f..f + n).collect();
976                        let mut outs: Vec<&mut [f32]> = self
977                            .kv_cache
978                            .layers
979                            .iter_mut()
980                            .enumerate()
981                            .filter(|(i, _)| idxs.binary_search(i).is_ok())
982                            .map(|(_, s)| s.linear_state.as_mut_slice())
983                            .collect();
984                        graph.read_states(&mut outs);
985                    }
986                    let mut q_raw = attention::take_buf(l.wq.1);
987                    let mut k = attention::take_buf(l.wk.1);
988                    let mut v = attention::take_buf(l.wv.1);
989                    graph.read_qkv(&mut q_raw, &mut k, &mut v);
990                    let cfg = QwenAttnCfg {
991                        num_heads: nh,
992                        num_kv_heads: nkv,
993                        head_dim: hd,
994                        hidden_size: hs,
995                        position,
996                        inv_freq: &inv_freq,
997                        rotary_dim: rd,
998                        scale: self.attn_scale,
999            softcap: self.attn_softcap,
1000                        window: None,
1001                        v_norm: false,
1002                        q_norm: *q_norm,
1003                        k_norm: *k_norm,
1004                        output_gate: *output_gate,
1005                        softplus_gate: None,
1006                        rope_scale: 1.0,
1007                        bias: *bias,
1008                        rms_eps: eps,
1009                        norm_style,
1010                        pool: pool.as_deref(),
1011                    };
1012                    let mut ao = attention::qwen_attention_core(
1013                        q_raw,
1014                        k,
1015                        v,
1016                        &mut self.kv_cache.layers[*li],
1017                        &cfg,
1018                    );
1019                    graph.encode_attn_suffix(l, &ao);
1020                    // Early commit: the GPU starts O+FFN while the CPU
1021                    // encodes the following GDN run / attention prefix.
1022                    graph.commit();
1023                    attention::recycle_buf(&mut ao);
1024                }
1025            }
1026        }
1027        // Ride the final norm + lm_head in the same command buffer when
1028        // this run reaches the model's end and the caller wants logits:
1029        // the separate per-op lm_head submit (a full round trip) folds
1030        // into the sync that already happens here.
1031        let mut lm_rows = None;
1032        if self.graph_want_logits
1033            && upto.is_none()
1034            && end == self.num_layers
1035            && std::env::var("CMF_GPU_LMHEAD")
1036                .map(|v| v != "0")
1037                .unwrap_or(true)
1038        {
1039            if let Some(lm) = self.weights.lm_head.q1_parts() {
1040                if graph.lm_head_ok(lm) {
1041                    graph.encode_lm_head(&self.weights.final_norm, lm);
1042                    lm_rows = Some(lm.1);
1043                }
1044            }
1045        }
1046        graph.sync();
1047        if !pending.is_empty() {
1048            let idxs: Vec<usize> = pending.drain(..).flat_map(|(f, n)| f..f + n).collect();
1049            let mut outs: Vec<&mut [f32]> = self
1050                .kv_cache
1051                .layers
1052                .iter_mut()
1053                .enumerate()
1054                .filter(|(i, _)| idxs.binary_search(i).is_ok())
1055                .map(|(_, s)| s.linear_state.as_mut_slice())
1056                .collect();
1057            graph.read_states(&mut outs);
1058        }
1059        if let Some(rows) = lm_rows {
1060            let mut lg = attention::take_buf(rows.min(self.vocab_size));
1061            graph.read_logits(&mut lg);
1062            lg.resize(self.vocab_size, 0.0);
1063            if let Some(c) = self.final_softcap {
1064                for l in lg.iter_mut() {
1065                    *l = c * (*l / c).tanh();
1066                }
1067            }
1068            self.graph_logits = Some(lg);
1069        }
1070        graph.finish(h);
1071        // Device-attended layers: replay the CPU bookkeeping — append
1072        // the mirror's new K/V row (rope'd on the GPU) into the owner
1073        // cache, then bank this token's Born-importance mass.
1074        for li in dev_attn {
1075            let mut krow = attention::take_buf(nkv * hd);
1076            let mut vrow = attention::take_buf(nkv * hd);
1077            if crate::gpu::kv_mirror_read_last(kv_id, li, nkv, hd, &mut krow, &mut vrow) {
1078                let cache = &mut self.kv_cache.layers[li];
1079                cache.append(&krow, &vrow, &[]);
1080                let n = cache.seq_len;
1081                let mut imp = attention::take_buf(n);
1082                crate::gpu::kv_mirror_take_imp(kv_id, li, &mut imp);
1083                cache.accumulate_imp(&imp);
1084                attention::recycle_buf(&mut imp);
1085            }
1086            attention::recycle_buf(&mut krow);
1087            attention::recycle_buf(&mut vrow);
1088        }
1089        end
1090    }
1091
1092    pub fn new(
1093        tokenizer: Tokenizer,
1094        weights: PipelineWeights,
1095        hidden_size: usize,
1096        intermediate_size: usize,
1097        num_heads: usize,
1098        num_kv_heads: usize,
1099        head_dim: usize,
1100        num_layers: usize,
1101        physical_layers: usize,
1102        loop_final_norm: bool,
1103        vocab_size: usize,
1104        rms_eps: f64,
1105        rope_base: f32,
1106        norm_style: NormStyle,
1107        max_seq_len: usize,
1108        sampler_config: SamplerConfig,
1109    ) -> Self {
1110        let rng = match sampler_config.seed {
1111            Some(s) => SplitMix64::new(s),
1112            None => SplitMix64::from_entropy(),
1113        };
1114        let inv_freq = std::sync::Arc::new(attention::rope_inv_freq(head_dim, rope_base));
1115        let pool = Pool::from_env();
1116        if let Some(p) = &pool {
1117            tracing::info!("worker pool: {} threads", p.n_workers());
1118        }
1119        Self {
1120            tokenizer: std::sync::Arc::new(tokenizer),
1121            kv_cache: KvCache::new(num_layers, num_kv_heads, head_dim, max_seq_len),
1122            sampler_config,
1123            weights,
1124            hidden_size,
1125            intermediate_size,
1126            num_heads,
1127            num_kv_heads,
1128            head_dim,
1129            num_layers,
1130            physical_layers,
1131            loop_final_norm,
1132            vocab_size,
1133            rms_eps,
1134            rope_base,
1135            norm_style,
1136            rotary_dim: head_dim,
1137            attention_heads_per_layer: None,
1138            vmf_cfg: None,
1139            gdn_cfg: None,
1140            kda_cfg: None,
1141            g3n: None,
1142            logit_multiplier: None,
1143            cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
1144            kv_history: Vec::new(),
1145            short_conv_cfg: None,
1146            mtp: None,
1147            speculative: std::env::var("CMF_MTP").map(|v| v != "0").unwrap_or(true),
1148            rng,
1149            sampler_scratch: SamplerScratch::default(),
1150            inv_freq,
1151            ws: ForwardScratch::new(hidden_size),
1152            pool,
1153            model: None,
1154            dyn_force_f32: false,
1155            dyn_skill_layers: Vec::new(),
1156            dyn_active: None,
1157            dyn_blend_loaded: false,
1158            dyn_phi_layer: None,
1159            dyn_phi_ema: Vec::new(),
1160            dyn_phi_seen: 0,
1161            dyn_router: None,
1162            o1_cfg: None,
1163            o1_epoch: 0,
1164            o1_flags: Vec::new(),
1165            trace: false,
1166            calib_temp: 1.0,
1167            confidence_on: true,
1168            embed_multiplier: 1.0,
1169            attn_scale: 1.0 / (head_dim as f32).sqrt(),
1170            swa: None,
1171            sliding_layers: None,
1172            inv_freq_local: None,
1173            rotary_dim_local: None,
1174            rope_scale: 1.0,
1175            rope_scale_local: 1.0,
1176            global_attn: None,
1177            inv_freq_global: None,
1178            attn_v_norm: false,
1179            final_softcap: None,
1180            attn_softcap: 0.0,
1181            graph_want_logits: false,
1182            graph_logits: None,
1183            graph_kv_id: {
1184                static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1185                NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
1186            },
1187        }
1188    }
1189
1190    /// Enable/disable per-layer O(1) Nyström attention. Only Full
1191    /// layers are eligible (a linear layer keeps its own operator).
1192    /// Applies to generation (`generate*`/`forward_ids`): the prompt
1193    /// pass stays exact, the seal happens once after prefill, decode
1194    /// runs on the O(1) state. Teacher-forced scoring (`ppl_ids`)
1195    /// intentionally stays exact.
1196    pub fn set_o1(&mut self, cfg: Option<crate::nystrom::O1Cfg>) {
1197        self.o1_flags = match &cfg {
1198            Some(c) => {
1199                let mut flags = c.layer_flags(self.num_layers);
1200                for (li, f) in flags.iter_mut().enumerate() {
1201                    if *f
1202                        && !matches!(
1203                            self.weights.layers[self.phys_layer(li)].attn,
1204                            AttnKind::Full { .. }
1205                        )
1206                    {
1207                        *f = false;
1208                    }
1209                }
1210                flags
1211            }
1212            None => Vec::new(),
1213        };
1214        if let Some(c) = &cfg {
1215            let n = self.o1_flags.iter().filter(|&&f| f).count();
1216            tracing::info!(
1217                "o1 nystrom attention: {n}/{} layer(s), m={} w={} sink={} rect={:?}",
1218                self.num_layers,
1219                c.m,
1220                c.w,
1221                c.sink,
1222                c.rect
1223            );
1224        }
1225        self.o1_cfg = cfg;
1226    }
1227
1228    /// True when at least one layer runs the O(1) kernel.
1229    pub fn o1_active(&self) -> bool {
1230        self.o1_cfg.is_some() && self.o1_flags.iter().any(|&f| f)
1231    }
1232
1233    /// Arm query collection on the o1 layers (fresh prompt pass).
1234    fn o1_begin(&mut self) {
1235        if let Some(c) = &self.o1_cfg {
1236            let (m, w, sink, rect) = (c.m, c.w, c.sink, c.rect);
1237            for (li, &f) in self.o1_flags.iter().enumerate() {
1238                if f {
1239                    self.kv_cache.layers[li].o1_begin(m, w, sink, rect);
1240                }
1241            }
1242        }
1243    }
1244
1245    /// Freeze landmarks + skeleton state after the prompt pass and drop
1246    /// the o1 layers' full KV; decode then runs `step()` per token.
1247    fn o1_seal(&mut self) {
1248        self.o1_epoch = self.o1_epoch.wrapping_add(1);
1249        if self.o1_cfg.is_none() {
1250            return;
1251        }
1252        for li in 0..self.num_layers {
1253            if self.o1_flags.get(li).copied().unwrap_or(false) {
1254                self.kv_cache.layers[li].o1_seal(self.num_heads);
1255            }
1256        }
1257    }
1258
1259    /// Enable/disable the structured per-token telemetry trace (B4).
1260    pub fn set_trace(&mut self, on: bool) {
1261        self.trace = on;
1262    }
1263
1264    /// Replace all request-scoped sampler options and reset the random stream.
1265    /// This is required for deterministic `seed` semantics in pooled servers.
1266    pub fn set_sampler_config(&mut self, config: SamplerConfig) {
1267        self.rng = match config.seed {
1268            Some(seed) => SplitMix64::new(seed),
1269            None => SplitMix64::from_entropy(),
1270        };
1271        self.sampler_config = config;
1272    }
1273
1274    /// Toggle the per-token Born-confidence reduction (a full-vocab
1275    /// softmax each token). `bench --core` turns it off so the timed
1276    /// loop matches llama-bench's core contract; the result's
1277    /// `confidence` vec is empty while off.
1278    pub fn set_confidence(&mut self, on: bool) {
1279        self.confidence_on = on;
1280    }
1281
1282    /// Set the confidence-calibration temperature (B1). Values ≤0 are
1283    /// clamped to raw (1.0).
1284    pub fn set_calib_temp(&mut self, t: f32) {
1285        self.calib_temp = if t > 1e-3 { t } else { 1.0 };
1286    }
1287
1288    /// The active calibration temperature (1.0 = raw Born mass).
1289    pub fn calib_temp(&self) -> f32 {
1290        self.calib_temp
1291    }
1292
1293    /// Partial rotary (Qwen3.5): rotate only the first `rotary_dim` dims;
1294    /// the frequency table is rebuilt over the rotary dims.
1295    pub fn set_rotary(&mut self, rotary_dim: usize, base: f32) {
1296        self.rotary_dim = rotary_dim.min(self.head_dim);
1297        self.inv_freq = std::sync::Arc::new(attention::rope_inv_freq(self.rotary_dim, base));
1298    }
1299
1300    fn attn_cfg(&self, position: usize) -> QwenAttnCfg<'_> {
1301        QwenAttnCfg {
1302            num_heads: self.num_heads,
1303            num_kv_heads: self.num_kv_heads,
1304            head_dim: self.head_dim,
1305            hidden_size: self.hidden_size,
1306            position,
1307            inv_freq: &self.inv_freq,
1308            rotary_dim: self.rotary_dim,
1309            scale: self.attn_scale,
1310            softcap: self.attn_softcap,
1311            window: None,
1312            v_norm: false,
1313            q_norm: None,
1314            k_norm: None,
1315            output_gate: false,
1316            softplus_gate: None,
1317            rope_scale: self.rope_scale,
1318            bias: None,
1319            rms_eps: self.rms_eps,
1320            norm_style: self.norm_style,
1321            pool: self.pool.as_deref(),
1322        }
1323    }
1324
1325    /// Generate text from a plain-text prompt. Streams tokens via `on_token`.
1326    pub fn generate(
1327        &mut self,
1328        prompt: &str,
1329        max_tokens: usize,
1330        task_mask: Option<&TaskMask>,
1331        on_token: Option<TokenCallback>,
1332    ) -> Result<GenerateResult, String> {
1333        let input_ids = self.tokenizer.with_bos(self.tokenizer.encode(prompt));
1334        self.generate_from_ids(&input_ids, max_tokens, task_mask, on_token)
1335    }
1336
1337    /// Generate from prepared token ids (e.g. a chat template).
1338    ///
1339    /// With an MTP head, greedy generation without a task mask takes the
1340    /// speculative path: the MTP module drafts the token after next and
1341    /// the main model verifies both in one fused two-position forward
1342    /// (weights streamed once). The output is EXACTLY the vanilla greedy
1343    /// sequence — a rejected draft is rolled back — MTP only buys speed.
1344    pub fn generate_from_ids(
1345        &mut self,
1346        input_ids: &[u32],
1347        max_tokens: usize,
1348        task_mask: Option<&TaskMask>,
1349        mut on_token: Option<TokenCallback>,
1350    ) -> Result<GenerateResult, String> {
1351        if std::env::var("CMF_TRACE_H").is_ok() {
1352            eprintln!("input_ids: {input_ids:?}");
1353        }
1354        if input_ids.is_empty() {
1355            return Err("empty prompt: nothing to generate from".to_string());
1356        }
1357
1358        // Cross-turn KV reuse: a chat app resends the whole history
1359        // every turn; when the new ids strictly EXTEND what the cache
1360        // already holds, prefill only the tail — turn latency stays
1361        // proportional to the new text instead of the whole session.
1362        // Extension-only (no rollback), so it is exact for every layer
1363        // kind including recurrent state; MTP/o1/task-mask runs keep
1364        // the fresh-sequence path. CMF_KV_REUSE=0 disables.
1365        let reuse_from = {
1366            let on = !std::env::var("CMF_KV_REUSE").is_ok_and(|v| v == "0");
1367            let h = &self.kv_history;
1368            if on
1369                && task_mask.is_none()
1370                && self.mtp.is_none()
1371                && self.o1_cfg.is_none()
1372                && !h.is_empty()
1373                && h.len() < input_ids.len()
1374                && input_ids[..h.len()] == h[..]
1375            {
1376                h.len()
1377            } else {
1378                0
1379            }
1380        };
1381        if reuse_from == 0 {
1382            // Fresh sequence — the cache holds absolute positions.
1383            self.kv_cache.clear();
1384            self.kv_history.clear();
1385            crate::gpu::graph_kv_reset(self.graph_kv_id);
1386        } else if std::env::var("CMF_PREFILL_PROF").is_ok() {
1387            eprintln!(
1388                "kv-reuse: {} of {} prompt positions already cached",
1389                reuse_from,
1390                input_ids.len()
1391            );
1392        }
1393        crate::gpu::graph_race_begin_generation();
1394        self.o1_begin();
1395
1396        // Speculative decode is off under o1: a rejected draft can't be
1397        // rolled back out of the far accumulators / ring window (the
1398        // Nyström insertion is irreversible by design).
1399        // The wgpu token graph owns a device K/V mirror that speculative
1400        // rollback would desync — the two are mutually exclusive.
1401        let graph_on = std::env::var("CMF_GPU_WGPU_GRAPH")
1402            .map(|v| v != "0")
1403            .unwrap_or_else(|_| {
1404                // Default ON for wgpu on DISCRETE adapters (4090:
1405                // decode 76 -> 137 tok/s); integrated/mobile GPUs keep
1406                // the per-op probe path — see gpu::wgpu_graph_default.
1407                crate::gpu::wgpu_graph_default()
1408            });
1409        let spec_active = self.speculative
1410            && self.mtp.is_some()
1411            && task_mask.is_none()
1412            && !self.o1_active()
1413            && !graph_on
1414            && self.sampler_config.temperature < 1e-6;
1415        // The MTP module is detached during generation so its mutable
1416        // state does not fight the borrow on `self`.
1417        let mut mtp = if spec_active { self.mtp.take() } else { None };
1418        if let Some(m) = &mut mtp {
1419            m.kv.clear();
1420        }
1421        // Dynamic router detached during decode (same borrow trick as MTP).
1422        // Speculative decode and dynamic routing are mutually exclusive
1423        // for now — the fused-pair path doesn't carry per-token φ.
1424        let mut router = if mtp.is_none() {
1425            self.dyn_router.take()
1426        } else {
1427            None
1428        };
1429        if let Some(r) = &mut router {
1430            r.reset(); // active=backbone, matching a fresh overlay
1431            self.dyn_phi_seen = 0; // fresh φ EMA per generation
1432            let _ = self.set_active_skill(None);
1433        }
1434
1435        let mut all_ids = input_ids.to_vec();
1436        let mut generated = 0usize;
1437        let mut finish_reason = "max_tokens".to_string();
1438        let mut drafted = 0usize;
1439        let mut accepted = 0usize;
1440        let mut confidence: Vec<f32> = Vec::new();
1441        let trace_on = self.trace;
1442        let calib_temp = self.calib_temp;
1443        let mut traces: Vec<TokenTrace> = Vec::new();
1444
1445        // ── Prefill: forward each prompt token once, KEEP the last hidden.
1446        //    Dense prefill runs in fused pairs (weights streamed once per
1447        //    two positions — bit-identical to sequential, proven by the
1448        //    pair tests). With MTP: warm the draft head on
1449        //    (hidden_p, token_{p+1}) pairs.
1450        let mut hidden = vec![0.0f32; self.hidden_size];
1451        let mut pos = reuse_from;
1452        // lm_head-in-graph is only sound when the very next logits
1453        // consumer is this loop's own (MTP and skill routing interleave
1454        // other forwards / can swap lm_head between forward and sample).
1455        // CMF_GPU_LMHEAD=0 keeps lm_head off the graph: the token reads back
1456        // the 8 KB hidden instead of ~1 MB of logits, and the head runs on
1457        // the host. A probe for how much of the graph's fixed per-token cost
1458        // is the logits readback (the layer sweep puts that fixed part at
1459        // 3.88 ms of an 18.5 ms frame).
1460        let fuse_lm = mtp.is_none()
1461            && router.is_none()
1462            && std::env::var("CMF_GPU_LMHEAD").as_deref() != Ok("0");
1463        self.graph_logits = None;
1464        self.graph_want_logits = false;
1465        // With dynamic routing, prefill sequentially so the φ hook fires
1466        // over the PROMPT — the router enters decode with a warm φ (the
1467        // fused-pair path skips the per-layer φ capture). o1 layers
1468        // collect their query trace in both the single and pair paths.
1469        let dyn_prefill = router.is_some();
1470        // q1 hybrids on Metal: the per-position GPU token graph beats
1471        // the CPU chunk-GEMM (whose wall is the sequential scalar GDN
1472        // recurrence), so prefill goes position-by-position through the
1473        // same graph as decode. Pure-attention models keep the batched
1474        // path — there the chunk-GEMM amortization wins.
1475        let graph_prefill = self.graph_prefill_preferred();
1476        if task_mask.is_none()
1477            && !dyn_prefill
1478            && !graph_prefill
1479            && prefill_batched()
1480            && self.g3n.is_none()
1481            && input_ids.len() > 2
1482        {
1483            // Production prefill = the same chunked prefill-GEMM that
1484            // bench/PPL measure (roadmap §3 P0: generation used to warm
1485            // the prompt with the slower pair path — the published
1486            // prefill number didn't match real TTFT). MTP warm-up reads
1487            // each position's hidden straight from the chunk result.
1488            let chunk = prefill_chunk();
1489            let hs = self.hidden_size;
1490            while pos < input_ids.len()
1491                && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
1492            {
1493                let end = (pos + chunk).min(input_ids.len());
1494                let hb = self.prefill_batch(&input_ids[pos..end], pos);
1495                if let Some(m) = &mut mtp {
1496                    for p in pos..end {
1497                        if p + 1 < input_ids.len() {
1498                            let _ = self.mtp_step(
1499                                m,
1500                                &hb[(p - pos) * hs..(p - pos + 1) * hs],
1501                                input_ids[p + 1],
1502                                p,
1503                            );
1504                        }
1505                    }
1506                }
1507                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
1508                pos = end;
1509            }
1510        }
1511        let pair_off = std::env::var("CMF_PAIR").is_ok_and(|v| v == "0");
1512        if task_mask.is_none() && !dyn_prefill && !graph_prefill && !pair_off && self.pair_supported()
1513        {
1514            while pos + 1 < input_ids.len()
1515                && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
1516            {
1517                let e1 = self.embed_single(input_ids[pos]);
1518                let e2 = self.embed_single(input_ids[pos + 1]);
1519                let (h1, h2) = self.forward_pair(&e1, &e2, pos);
1520                // Both prefill tokens are real → commit lane-2 states.
1521                self.commit_linear_scratch();
1522                if let Some(m) = &mut mtp {
1523                    let _ = self.mtp_step(m, &h1, input_ids[pos + 1], pos);
1524                    if pos + 2 < input_ids.len() {
1525                        let _ = self.mtp_step(m, &h2, input_ids[pos + 2], pos + 1);
1526                    }
1527                }
1528                hidden = h2;
1529                pos += 2;
1530            }
1531        }
1532        // Batched GPU prefill for the wgpu decode graph (GDN hybrids): K prompt
1533        // positions per submit — projections/FFN as GEMMs (weight once per K),
1534        // attention/GDN looped inside — instead of one whole-graph submit per
1535        // position. Falls through to the per-position graph on any refusal.
1536        // Batched prefill is opt-in (CMF_BATCH_K>0). Default 0 = per-position
1537        // graph prefill. (Steady-state decode is provably identical either way —
1538        // token-graph submit and lm_head both unchanged — so this only trades
1539        // prefill wall.)
1540        let _tpf = std::time::Instant::now();
1541        let batch_k = std::env::var("CMF_BATCH_K")
1542            .ok()
1543            .and_then(|v| v.parse::<usize>().ok())
1544            .unwrap_or(0);
1545        if batch_k > 0
1546            && graph_prefill
1547            && task_mask.is_none()
1548            && !self.o1_active()
1549            && mtp.is_none()
1550            && !dyn_prefill
1551            && pos + 1 < input_ids.len()
1552        {
1553            let hs = self.hidden_size;
1554            let chunk = batch_k;
1555            while pos < input_ids.len() {
1556                let end = (pos + chunk).min(input_ids.len());
1557                let bk = end - pos;
1558                let mut hiddens = vec![0f32; bk * hs];
1559                for (j, &id) in input_ids[pos..end].iter().enumerate() {
1560                    hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
1561                }
1562                let positions: Vec<usize> = (pos..end).collect();
1563                let t_chunk = std::time::Instant::now();
1564                let ok_b = self.try_batch_graph_wgpu(&mut hiddens, &positions, bk);
1565                if std::env::var("CMF_GRAPH_PROF").is_ok() {
1566                    let ms = t_chunk.elapsed().as_secs_f64() * 1000.0;
1567                    eprintln!(
1568                        "batch-chunk: k={bk} ok={ok_b} {ms:.1} ms ({:.1} tok/s)",
1569                        bk as f64 / (ms / 1000.0)
1570                    );
1571                }
1572                {
1573                    use std::sync::atomic::{AtomicBool, Ordering};
1574                    static SAID: AtomicBool = AtomicBool::new(false);
1575                    if !SAID.swap(true, Ordering::Relaxed) {
1576                        if ok_b {
1577                            tracing::info!("batched prefill: ACTIVE (k={bk})");
1578                        } else {
1579                            tracing::warn!("batched prefill declined — per-position graph");
1580                        }
1581                    }
1582                }
1583                if ok_b {
1584                    hidden.copy_from_slice(&hiddens[(bk - 1) * hs..]);
1585                    pos = end;
1586                } else {
1587                    break; // unsupported → per-position graph handles the rest
1588                }
1589            }
1590        }
1591        while pos < input_ids.len()
1592            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
1593        {
1594            self.graph_want_logits = fuse_lm && pos + 1 == input_ids.len();
1595            hidden = self.forward_layers(&self.embed_single(input_ids[pos]), pos, task_mask);
1596            if let Some(m) = &mut mtp {
1597                if pos + 1 < input_ids.len() {
1598                    let _ = self.mtp_step(m, &hidden, input_ids[pos + 1], pos);
1599                }
1600            }
1601            pos += 1;
1602        }
1603        if std::env::var("CMF_PREFILL_PROF").is_ok() {
1604            eprintln!(
1605                "prefill: {} tokens in {:.1} ms (batch_k={batch_k})",
1606                input_ids.len(),
1607                _tpf.elapsed().as_secs_f64() * 1000.0
1608            );
1609        }
1610        // Cancelled mid-prefill: the cache holds a partial prompt —
1611        // drop the reuse history and return an empty generation.
1612        if self.cancel.swap(false, std::sync::atomic::Ordering::Relaxed) {
1613            self.kv_history.clear();
1614            if let Some(m) = mtp {
1615                self.mtp = Some(m);
1616            }
1617            return Ok(GenerateResult {
1618                text: String::new(),
1619                token_ids: Vec::new(),
1620                prompt_tokens: input_ids.len(),
1621                tokens_generated: 0,
1622                finish_reason: "cancelled".to_string(),
1623                mtp_drafted: 0,
1624                mtp_accepted: 0,
1625                token_confidence: Vec::new(),
1626                traces: Vec::new(),
1627            });
1628        }
1629
1630        // Prompt absorbed → freeze the o1 layers' skeletons; from here
1631        // every decode step on those layers is O(W + m·dv + m²).
1632        self.o1_seal();
1633
1634        // Commit one token: push, check EOS, stream. Returns false = stop.
1635        macro_rules! commit {
1636            ($id:expr) => {{
1637                all_ids.push($id);
1638                generated += 1;
1639                if self.tokenizer.is_eos($id) {
1640                    finish_reason = "stop".to_string();
1641                    false
1642                } else {
1643                    let token_text = self.tokenizer.decode_token($id);
1644                    let mut go = true;
1645                    if let Some(ref mut cb) = on_token {
1646                        if !cb(&token_text) {
1647                            finish_reason = "cancelled".to_string();
1648                            go = false;
1649                        }
1650                    }
1651                    go
1652                }
1653            }};
1654        }
1655
1656        // ── Decode ──
1657        let mut next_pos = input_ids.len();
1658        'decode: while generated < max_tokens {
1659            if self.cancel.swap(false, std::sync::atomic::Ordering::Relaxed) {
1660                finish_reason = "cancelled".to_string();
1661                break 'decode;
1662            }
1663            let mut logits = match self.graph_logits.take() {
1664                Some(lg) => lg,
1665                None => {
1666                    inference::rms_norm_into(
1667                        &hidden,
1668                        &self.weights.final_norm,
1669                        self.rms_eps,
1670                        self.norm_style,
1671                        &mut self.ws.n1,
1672                    );
1673                    self.lm_head_forward(&self.ws.n1)
1674                }
1675            };
1676            let t_next = sampler::sample_with_scratch(
1677                &logits,
1678                &self.sampler_config,
1679                &all_ids,
1680                &mut self.rng,
1681                &mut self.sampler_scratch,
1682            );
1683            if self.confidence_on {
1684                confidence.push(top1_prob_t(&logits, t_next, calib_temp));
1685            }
1686            attention::recycle_buf(&mut logits);
1687            if trace_on {
1688                // active_skill = the overlay in force while this token was
1689                // generated; recon/switched are filled after the post-emit
1690                // routing eval below (freshest coherence for this token).
1691                let skill = router.as_ref().and_then(|r| r.active_id());
1692                traces.push(TokenTrace {
1693                    t: generated,
1694                    token_id: t_next,
1695                    confidence: confidence.last().copied().unwrap_or(0.0),
1696                    active_skill: skill,
1697                    recon: None,
1698                    switched: false,
1699                });
1700            }
1701            if !commit!(t_next) {
1702                break 'decode;
1703            }
1704            if generated >= max_tokens {
1705                break 'decode;
1706            }
1707
1708            if self.kv_cache.needs_eviction() {
1709                let keep = (self.kv_cache.max_seq_len / 2).max(1);
1710                self.kv_cache.evict(keep);
1711            }
1712
1713            match &mut mtp {
1714                // ── Speculative: draft t+2, verify in a fused pair ──
1715                Some(m) if generated + 1 < max_tokens => {
1716                    let draft = self.mtp_step(m, &hidden, t_next, next_pos - 1);
1717                    drafted += 1;
1718                    let emb1 = self.embed_single(t_next);
1719                    let emb2 = self.embed_single(draft);
1720                    let (h1, h2) = self.forward_pair(&emb1, &emb2, next_pos);
1721
1722                    inference::rms_norm_into(
1723                        &h1,
1724                        &self.weights.final_norm,
1725                        self.rms_eps,
1726                        self.norm_style,
1727                        &mut self.ws.n1,
1728                    );
1729                    let mut logits1 = self.lm_head_forward(&self.ws.n1);
1730                    let t_after = sampler::sample_with_scratch(
1731                        &logits1,
1732                        &self.sampler_config,
1733                        &all_ids,
1734                        &mut self.rng,
1735                        &mut self.sampler_scratch,
1736                    );
1737                    if self.confidence_on {
1738                        confidence.push(top1_prob_t(&logits1, t_after, calib_temp));
1739                    }
1740                    attention::recycle_buf(&mut logits1);
1741                    if trace_on {
1742                        // Speculative decode is mutually exclusive with
1743                        // dynamic routing (router is None here) — no skill.
1744                        traces.push(TokenTrace {
1745                            t: generated,
1746                            token_id: t_after,
1747                            confidence: confidence.last().copied().unwrap_or(0.0),
1748                            active_skill: None,
1749                            recon: None,
1750                            switched: false,
1751                        });
1752                    }
1753                    let stop = !commit!(t_after);
1754
1755                    if t_after == draft {
1756                        accepted += 1;
1757                        self.commit_linear_scratch();
1758                        let _ = self.mtp_step(m, &h1, t_after, next_pos);
1759                        hidden = h2;
1760                        next_pos += 2;
1761                    } else {
1762                        // The draft lane is wrong: roll its KV entry back.
1763                        for layer in &mut self.kv_cache.layers {
1764                            layer.truncate_last(1);
1765                        }
1766                        if !stop {
1767                            let _ = self.mtp_step(m, &h1, t_after, next_pos);
1768                            hidden = self.forward_layers(
1769                                &self.embed_single(t_after),
1770                                next_pos + 1,
1771                                None,
1772                            );
1773                        }
1774                        next_pos += 2;
1775                    }
1776                    if stop {
1777                        break 'decode;
1778                    }
1779                }
1780                // ── Vanilla: forward the sampled token ──
1781                _ => {
1782                    self.graph_want_logits = fuse_lm;
1783                    hidden = self.forward_layers(&self.embed_single(t_next), next_pos, task_mask);
1784                    next_pos += 1;
1785                    // Dynamic routing: the forward updated φ; ask the
1786                    // router whether to switch skills before the next token.
1787                    if let Some(r) = &mut router {
1788                        let phi = self.dyn_phi_ema.clone();
1789                        let decision = r.step(&phi, generated);
1790                        if let Some(new_active) = decision {
1791                            let _ = self.set_active_skill(new_active);
1792                        }
1793                        // Backfill this token's coherence + switch flag from
1794                        // the just-run eval (freshest measured values).
1795                        if trace_on {
1796                            if let Some(last) = traces.last_mut() {
1797                                let e = r.last_best_e();
1798                                last.recon = e.is_finite().then_some(e);
1799                                last.switched = decision.is_some();
1800                            }
1801                        }
1802                    }
1803                }
1804            }
1805        }
1806
1807        self.graph_want_logits = false;
1808        self.graph_logits = None;
1809        // Restore backbone overlay and re-attach the router for reuse.
1810        if router.is_some() {
1811            let _ = self.set_active_skill(None);
1812        }
1813        self.dyn_router = router.or(self.dyn_router.take());
1814        self.mtp = mtp.or(self.mtp.take());
1815
1816        let output_ids = &all_ids[input_ids.len()..];
1817        // Forwarded = prompt + all generated but the LAST sampled token
1818        // (emitted without being fed back). Exact only without MTP —
1819        // reuse is gated off when MTP is active.
1820        let forwarded = input_ids.len() + output_ids.len().saturating_sub(1);
1821        self.kv_history = all_ids[..forwarded.min(all_ids.len())].to_vec();
1822        confidence.truncate(output_ids.len()); // guard against any overshoot
1823        traces.truncate(output_ids.len());
1824        Ok(GenerateResult {
1825            text: self.tokenizer.decode(output_ids),
1826            token_ids: output_ids.to_vec(),
1827            prompt_tokens: input_ids.len(),
1828            tokens_generated: generated,
1829            finish_reason,
1830            mtp_drafted: drafted,
1831            mtp_accepted: accepted,
1832            token_confidence: confidence,
1833            traces,
1834        })
1835    }
1836
1837    /// One MTP step: feed `(hidden_p, token_{p+1})` into the draft head,
1838    /// advance its KV cache at position `p`, return the drafted token
1839    /// for position `p+2`.
1840    fn mtp_step(
1841        &mut self,
1842        m: &mut MtpModule,
1843        hidden: &[f32],
1844        next_token: u32,
1845        position: usize,
1846    ) -> u32 {
1847        // fc concat order is [enorm(embed); hnorm(hidden)] — EMBEDDING
1848        // FIRST. Verified by the oracle (converter/mtp_oracle.py):
1849        // [emb;hid] → 45.8% acceptance, [hid;emb] → 0.00%.
1850        let e = self.embed_single(next_token);
1851        let mut cat = vec![0.0f32; 2 * self.hidden_size];
1852        let (cat_e, cat_h) = cat.split_at_mut(self.hidden_size);
1853        inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
1854        inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
1855        let mut x = vec![0.0f32; self.hidden_size];
1856        m.eh_proj.matvec(&cat, &mut x, self.pool.as_deref());
1857
1858        // One standard transformer block over the MTP's own cache.
1859        let lw = &m.layer;
1860        inference::rms_norm_into(
1861            &x,
1862            &lw.input_norm,
1863            self.rms_eps,
1864            self.norm_style,
1865            &mut self.ws.n1,
1866        );
1867        let attn = match &lw.attn {
1868            // MLA models carry no MTP head; this path cannot see them.
1869            AttnKind::Mla(_) => unreachable!("MLA has no MTP/pair path"),
1870            AttnKind::Kda(_) => unreachable!("KDA has no MTP/pair path"),
1871            AttnKind::Full {
1872                wq,
1873                wk,
1874                wv,
1875                wo,
1876                q_norm,
1877                k_norm,
1878                output_gate,
1879                softplus_gate,
1880                bias,
1881            } => {
1882                let mut cfg = self.attn_cfg(position);
1883                cfg.q_norm = q_norm.as_deref();
1884                cfg.k_norm = k_norm.as_deref();
1885                cfg.output_gate = *output_gate;
1886                cfg.softplus_gate = softplus_gate
1887                    .as_ref()
1888                    .map(|(gate, per_head)| (gate, *per_head));
1889                cfg.bias = bias
1890                    .as_ref()
1891                    .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice()));
1892                attention::qwen_attention(&self.ws.n1, wq, wk, wv, wo, &mut m.kv, &cfg)
1893            }
1894            AttnKind::Linear(_) | AttnKind::LinearGdn(_) | AttnKind::ShortConv(_) => {
1895                unreachable!("MTP block is full attention")
1896            }
1897        };
1898        for (i, &a) in attn.iter().enumerate() {
1899            x[i] += a;
1900        }
1901        inference::rms_norm_into(
1902            &x,
1903            &lw.post_norm,
1904            self.rms_eps,
1905            self.norm_style,
1906            &mut self.ws.p1,
1907        );
1908        let ffn = ffn_forward(&lw.ffn, &self.ws.p1, self.pool.as_deref(), None);
1909        for (i, &f) in ffn.iter().enumerate() {
1910            x[i] += f;
1911        }
1912
1913        inference::rms_norm_into(
1914            &x,
1915            &m.final_norm,
1916            self.rms_eps,
1917            self.norm_style,
1918            &mut self.ws.n1,
1919        );
1920        let mut lg = self.lm_head_forward(&self.ws.n1);
1921        let draft = sampler::argmax(&lg);
1922        attention::recycle_buf(&mut lg);
1923        draft
1924    }
1925
1926    /// Micro-benchmark: two single-position forwards vs one fused pair
1927    /// from the current cache state (KV rewound after each probe).
1928    /// Returns (two_singles_ms, fused_pair_ms) per probe.
1929    pub fn measure_pair_fusion(&mut self, iters: usize) -> (f64, f64) {
1930        let emb1 = self.embed_single(1);
1931        let emb2 = self.embed_single(2);
1932        let pos = self.kv_cache.seq_len();
1933
1934        let t0 = std::time::Instant::now();
1935        for _ in 0..iters {
1936            let _ = self.forward_layers(&emb1, pos, None);
1937            let _ = self.forward_layers(&emb2, pos + 1, None);
1938            for l in &mut self.kv_cache.layers {
1939                l.truncate_last(2);
1940            }
1941        }
1942        let singles_ms = t0.elapsed().as_secs_f64() * 1000.0 / iters as f64;
1943
1944        let t1 = std::time::Instant::now();
1945        for _ in 0..iters {
1946            let _ = self.forward_pair(&emb1, &emb2, pos);
1947            for l in &mut self.kv_cache.layers {
1948                l.truncate_last(2);
1949            }
1950        }
1951        let pair_ms = t1.elapsed().as_secs_f64() * 1000.0 / iters as f64;
1952        (singles_ms, pair_ms)
1953    }
1954
1955    /// Fused two-position forward: weight rows are streamed from memory
1956    /// once per layer for both positions. Full layers → fused GQA pair;
1957    /// linear layers → vmf_phase pair (lane 2 state is tentative in the
1958    /// per-layer scratch until the draft is accepted).
1959    /// Whether the fused two-position path covers every layer kind in
1960    /// this model. MLA and KDA run per position (their pair arms are
1961    /// unreachable); the seq prefill falls back to singles for them.
1962    fn pair_supported(&self) -> bool {
1963        self.g3n.is_none()
1964            && !self
1965                .weights
1966                .layers
1967                .iter()
1968                .any(|lw| matches!(&lw.attn, AttnKind::Mla(_) | AttnKind::Kda(_)))
1969    }
1970
1971    fn forward_pair(
1972        &mut self,
1973        emb1: &[f32],
1974        emb2: &[f32],
1975        position: usize,
1976    ) -> (Vec<f32>, Vec<f32>) {
1977        let mut h1 = emb1.to_vec();
1978        let mut h2 = emb2.to_vec();
1979        let (_nkv, _hd, hs, _rd, eps) = (
1980            self.num_kv_heads,
1981            self.head_dim,
1982            self.hidden_size,
1983            self.rotary_dim,
1984            self.rms_eps,
1985        );
1986        let pool = self.pool.clone();
1987
1988        for li in 0..self.num_layers {
1989            let lw = &self.weights.layers[self.phys_layer(li)];
1990            // Norms into pipeline scratch (4 allocs/layer on the MTP
1991            // decode hot path before this).
1992            inference::rms_norm_into(
1993                &h1,
1994                &lw.input_norm,
1995                self.rms_eps,
1996                self.norm_style,
1997                &mut self.ws.n1,
1998            );
1999            inference::rms_norm_into(
2000                &h2,
2001                &lw.input_norm,
2002                self.rms_eps,
2003                self.norm_style,
2004                &mut self.ws.n2,
2005            );
2006
2007            let (a1, a2) = match &lw.attn {
2008                AttnKind::Mla(_) => unreachable!("MLA has no MTP/pair path"),
2009                AttnKind::Kda(_) => unreachable!("KDA has no MTP/pair path"),
2010            AttnKind::Kda(_) => unreachable!("KDA has no MTP/pair path"),
2011                AttnKind::Linear(w) => {
2012                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
2013                    let layer = &mut self.kv_cache.layers[li];
2014                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
2015                    vmf_phase_pair(
2016                        &self.ws.n1,
2017                        &self.ws.n2,
2018                        w,
2019                        &cfg,
2020                        state,
2021                        scratch,
2022                        self.pool.as_deref(),
2023                    )
2024                }
2025                AttnKind::LinearGdn(w) => {
2026                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
2027                    let layer = &mut self.kv_cache.layers[li];
2028                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
2029                    gdn_pair(
2030                        &self.ws.n1,
2031                        &self.ws.n2,
2032                        w,
2033                        &cfg,
2034                        state,
2035                        scratch,
2036                        self.pool.as_deref(),
2037                    )
2038                }
2039                AttnKind::ShortConv(w) => {
2040                    let cfg = self
2041                        .short_conv_cfg
2042                        .expect("short-conv layer without short_conv_cfg");
2043                    let layer = &mut self.kv_cache.layers[li];
2044                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
2045                    short_conv_pair(
2046                        &self.ws.n1,
2047                        &self.ws.n2,
2048                        w,
2049                        &cfg,
2050                        state,
2051                        scratch,
2052                        self.pool.as_deref(),
2053                    )
2054                }
2055                AttnKind::Full {
2056                    wq,
2057                    wk,
2058                    wv,
2059                    wo,
2060                    q_norm,
2061                    k_norm,
2062                    output_gate,
2063                    softplus_gate,
2064                    bias,
2065                } => {
2066                    let inv_freq_l = self.layer_inv_freq(li);
2067                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
2068                    let cfg = QwenAttnCfg {
2069                        num_heads: self.layer_num_heads(li),
2070                        num_kv_heads: nkv_l,
2071                        head_dim: hd_l,
2072                        hidden_size: hs,
2073                        position,
2074                        inv_freq: &inv_freq_l,
2075                        rotary_dim: rd_l,
2076                        scale: self.attn_scale,
2077            softcap: self.attn_softcap,
2078                        window: self.layer_window(li),
2079                        v_norm: self.attn_v_norm,
2080                        q_norm: q_norm.as_deref(),
2081                        k_norm: k_norm.as_deref(),
2082                        output_gate: *output_gate,
2083                        softplus_gate: softplus_gate
2084                            .as_ref()
2085                            .map(|(gate, per_head)| (gate, *per_head)),
2086                        rope_scale: self.layer_rope_scale(li),
2087                        bias: bias
2088                            .as_ref()
2089                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
2090                        rms_eps: eps,
2091                        norm_style: self.norm_style,
2092                        pool: pool.as_deref(),
2093                    };
2094                    attention::qwen_attention_pair(
2095                        &self.ws.n1,
2096                        &self.ws.n2,
2097                        wq,
2098                        wk,
2099                        wv,
2100                        wo,
2101                        &mut self.kv_cache.layers[li],
2102                        &cfg,
2103                    )
2104                }
2105            };
2106            let (a1, a2) = match &self.weights.layers[self.phys_layer(li)].attn_out_norm {
2107                Some(w) => (
2108                    inference::rms_norm(&a1, w, self.rms_eps, self.norm_style),
2109                    inference::rms_norm(&a2, w, self.rms_eps, self.norm_style),
2110                ),
2111                None => (a1, a2),
2112            };
2113            for i in 0..self.hidden_size {
2114                h1[i] += a1[i];
2115                h2[i] += a2[i];
2116            }
2117            let (mut a1, mut a2) = (a1, a2);
2118            attention::recycle_buf(&mut a1);
2119            attention::recycle_buf(&mut a2);
2120
2121            let lw = &self.weights.layers[self.phys_layer(li)];
2122            inference::rms_norm_into(
2123                &h1,
2124                &lw.post_norm,
2125                self.rms_eps,
2126                self.norm_style,
2127                &mut self.ws.p1,
2128            );
2129            inference::rms_norm_into(
2130                &h2,
2131                &lw.post_norm,
2132                self.rms_eps,
2133                self.norm_style,
2134                &mut self.ws.p2,
2135            );
2136            let (f1, f2) = match &lw.ffn {
2137                // Dual-branch layers need the raw residuals — run the
2138                // two positions through the same fn decode uses.
2139                FfnKind::DenseMoe(dm) => (
2140                    dense_moe_ffn(
2141                        dm,
2142                        &self.ws.p1,
2143                        &h1,
2144                        self.rms_eps,
2145                        self.norm_style,
2146                        self.pool.as_deref(),
2147                    ),
2148                    dense_moe_ffn(
2149                        dm,
2150                        &self.ws.p2,
2151                        &h2,
2152                        self.rms_eps,
2153                        self.norm_style,
2154                        self.pool.as_deref(),
2155                    ),
2156                ),
2157                _ => ffn_forward_pair(&lw.ffn, &self.ws.p1, &self.ws.p2, self.pool.as_deref(), None),
2158            };
2159            let (f1, f2) = match &self.weights.layers[self.phys_layer(li)].ffn_out_norm {
2160                Some(w) => (
2161                    inference::rms_norm(&f1, w, self.rms_eps, self.norm_style),
2162                    inference::rms_norm(&f2, w, self.rms_eps, self.norm_style),
2163                ),
2164                None => (f1, f2),
2165            };
2166            for i in 0..self.hidden_size {
2167                h1[i] += f1[i];
2168                h2[i] += f2[i];
2169            }
2170            let (mut f1, mut f2) = (f1, f2);
2171            attention::recycle_buf(&mut f1);
2172            attention::recycle_buf(&mut f2);
2173            if let Some(sc) = self.weights.layers[self.phys_layer(li)].layer_scale {
2174                for i in 0..self.hidden_size {
2175                    h1[i] *= sc;
2176                    h2[i] *= sc;
2177                }
2178            }
2179            // Looped Transformer: apply final norm at the end of each loop iteration.
2180            if self.is_loop_end(li) && li + 1 < self.num_layers {
2181                h1 = inference::rms_norm(
2182                    &h1,
2183                    &self.weights.final_norm,
2184                    self.rms_eps,
2185                    self.norm_style,
2186                );
2187                h2 = inference::rms_norm(
2188                    &h2,
2189                    &self.weights.final_norm,
2190                    self.rms_eps,
2191                    self.norm_style,
2192                );
2193            }
2194        }
2195        (h1, h2)
2196    }
2197
2198    /// Commit lane-2 linear states after an accepted draft.
2199    fn commit_linear_scratch(&mut self) {
2200        for layer in &mut self.kv_cache.layers {
2201            if !layer.linear_scratch.is_empty() {
2202                std::mem::swap(&mut layer.linear_state, &mut layer.linear_scratch);
2203                layer.linear_scratch.clear();
2204            }
2205        }
2206    }
2207
2208    /// Forward a full id sequence from a fresh cache and return the
2209    /// logits after the last position (golden-parity harness, bench).
2210    pub fn forward_ids(
2211        &mut self,
2212        ids: &[u32],
2213        task_mask: Option<&TaskMask>,
2214    ) -> Result<Vec<f32>, String> {
2215        if ids.is_empty() {
2216            return Err("empty id sequence".to_string());
2217        }
2218        self.kv_cache.clear();
2219        self.kv_history.clear();
2220        self.o1_begin();
2221        let mut hidden = vec![0.0f32; self.hidden_size];
2222        let mut pos = 0usize;
2223        if task_mask.is_none() && prefill_batched() && ids.len() > 2 {
2224            // prefill-GEMM in chunks; only the last position's hidden is
2225            // needed. (o1-compatible: the batch path attends per position
2226            // through qwen_attention, which carries the collection hook.)
2227            let chunk = prefill_chunk();
2228            let hs = self.hidden_size;
2229            while pos < ids.len() {
2230                let end = (pos + chunk).min(ids.len());
2231                let hb = self.prefill_batch(&ids[pos..end], pos);
2232                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
2233                pos = end;
2234            }
2235        }
2236        if task_mask.is_none() {
2237            while pos + 1 < ids.len() {
2238                let e1 = self.embed_single(ids[pos]);
2239                let e2 = self.embed_single(ids[pos + 1]);
2240                let (_, h2) = self.forward_pair(&e1, &e2, pos);
2241                self.commit_linear_scratch();
2242                hidden = h2;
2243                pos += 2;
2244            }
2245        }
2246        while pos < ids.len() {
2247            hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, task_mask);
2248            pos += 1;
2249        }
2250        // Harness contract: after forward_ids the cache is decode-ready —
2251        // under o1 that means sealed (bench measures the seal as part of
2252        // prefill, honestly).
2253        self.o1_seal();
2254        let normed = inference::rms_norm(
2255            &hidden,
2256            &self.weights.final_norm,
2257            self.rms_eps,
2258            self.norm_style,
2259        );
2260        Ok(self.lm_head_forward(&normed))
2261    }
2262
2263    /// Teacher-forced perplexity over a token sequence (phase-C gate:
2264    /// honest quant comparisons instead of prompt vibes).
2265    ///
2266    /// Attention is EXACT even on a model whose layers are flagged for
2267    /// the O(1) kernel — scoring the backbone is the default on purpose
2268    /// (it is the yardstick). `nll_ids_o1` scores the CONVERTED model.
2269    pub fn ppl_ids(&mut self, ids: &[u32]) -> f64 {
2270        let (nll, cnt) = self.nll_ids_from(ids, 0);
2271        (nll / cnt.max(1) as f64).exp()
2272    }
2273
2274    /// DTG-MA calibration pass (Patent 2): run `ids` through the model
2275    /// (CPU path, per position) and return each layer's per-neuron
2276    /// activation mass Σ|silu(gate)·up| — the statistic the task-guided
2277    /// FFN mask is derived from.
2278    pub fn probe_ffn_mass(&mut self, ids: &[u32]) -> Vec<Vec<f64>> {
2279        self.kv_cache.clear();
2280        self.kv_history.clear();
2281        FFN_PROBE.with(|p| {
2282            *p.borrow_mut() = Some(vec![vec![0f64; self.intermediate_size]; self.num_layers]);
2283        });
2284        crate::gpu::cpu_scope(|| {
2285            for (pos, &id) in ids.iter().enumerate() {
2286                let emb = self.embed_single(id);
2287                let _ = self.forward_layers(&emb, pos, None);
2288            }
2289        });
2290        self.kv_cache.clear();
2291        self.kv_history.clear();
2292        FFN_PROBE
2293            .with(|p| p.borrow_mut().take())
2294            .unwrap_or_default()
2295    }
2296
2297    /// Teacher-forced PPL with a task mask active (sparse execution) —
2298    /// the quality gate for a DTG-MA-masked skill. Sequential per
2299    /// position: the batched prefill path is dense-only.
2300    pub fn ppl_ids_masked(&mut self, ids: &[u32], mask: &TaskMask) -> f64 {
2301        self.kv_cache.clear();
2302        self.kv_history.clear();
2303        let mut nll = 0f64;
2304        let mut cnt = 0usize;
2305        let mut hidden = vec![0f32; self.hidden_size];
2306        for (pos, &id) in ids.iter().enumerate() {
2307            if pos > 0 {
2308                inference::rms_norm_into(
2309                    &hidden,
2310                    &self.weights.final_norm,
2311                    self.rms_eps,
2312                    self.norm_style,
2313                    &mut self.ws.n1,
2314                );
2315                let mut logits = self.lm_head_forward(&self.ws.n1);
2316                let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
2317                let sum: f64 = logits.iter().map(|&v| ((v - max) as f64).exp()).sum();
2318                let p = ((logits[id as usize] - max) as f64).exp() / sum.max(1e-300);
2319                nll -= p.max(1e-300).ln();
2320                cnt += 1;
2321                attention::recycle_buf(&mut logits);
2322            }
2323            let emb = self.embed_single(id);
2324            hidden = self.forward_layers(&emb, pos, Some(mask));
2325        }
2326        self.kv_cache.clear();
2327        self.kv_history.clear();
2328        (nll / cnt.max(1) as f64).exp()
2329    }
2330
2331    /// Teacher-forced NLL sum + scored-token count over positions
2332    /// `start..len-1`, attention EXACT. Positions below `start` still
2333    /// run — they are the context — they are just not scored, so this
2334    /// pairs with `nll_ids_o1(ids, start)` over the very same tokens.
2335    ///
2336    /// Returning (nll, cnt) rather than a ppl is what lets a windowed
2337    /// caller combine windows before the exp, so every scored token
2338    /// weighs the same regardless of how the windows are cut.
2339    pub fn nll_ids_from(&mut self, ids: &[u32], start: usize) -> (f64, usize) {
2340        self.kv_cache.clear();
2341        self.kv_history.clear();
2342        let mut nll = 0f64;
2343        let mut cnt = 0usize;
2344        if prefill_batched() && self.g3n.is_none() {
2345            // prefill-GEMM: layer-major position chunks, lm_head batched
2346            // (254MB lm_head read once per chunk, not per position).
2347            // The layer chunk is large (grouping positions by MoE experts
2348            // wins with size), lm_head in sub-blocks (logit buffer
2349            // 32×vocab ≈ 32MB instead of 128×).
2350            const CHUNK: usize = 128;
2351            const LM_SUB: usize = 32;
2352            let n = ids.len().saturating_sub(1);
2353            let hs = self.hidden_size;
2354            let rows = self.weights.lm_head.rows();
2355            let mut pos = 0usize;
2356            while pos < n {
2357                let end = (pos + CHUNK).min(n);
2358                let bsz = end - pos;
2359                let hb = self.prefill_batch(&ids[pos..end], pos);
2360                let mut k0 = 0usize;
2361                while k0 < bsz {
2362                    let k1 = (k0 + LM_SUB).min(bsz);
2363                    let sb = k1 - k0;
2364                    // Sub-block entirely below the scored range: the KV
2365                    // it just built is all this pass needed from it.
2366                    if pos + k1 <= start {
2367                        k0 = k1;
2368                        continue;
2369                    }
2370                    let mut normed = vec![0.0f32; sb * hs];
2371                    for k in 0..sb {
2372                        let r = inference::rms_norm(
2373                            &hb[(k0 + k) * hs..(k0 + k + 1) * hs],
2374                            &self.weights.final_norm,
2375                            self.rms_eps,
2376                            self.norm_style,
2377                        );
2378                        normed[k * hs..(k + 1) * hs].copy_from_slice(&r);
2379                    }
2380                    let mut logits = vec![0.0f32; sb * rows];
2381                    self.weights
2382                        .lm_head
2383                        .matmat(&normed, sb, &mut logits, self.pool.as_deref());
2384                    for k in 0..sb {
2385                        if pos + k0 + k < start {
2386                            continue;
2387                        }
2388                        let lg = &mut logits[k * rows..k * rows + self.vocab_size.min(rows)];
2389                        if let Some(mu) = self.logit_multiplier {
2390                            for v in lg.iter_mut() {
2391                                *v *= mu;
2392                            }
2393                        }
2394                        // Gemma-class final-logit soft-capping: the
2395                        // decode paths apply it; scoring must too, or
2396                        // the uncapped softmax misprices every token.
2397                        if let Some(c) = self.final_softcap {
2398                            for v in lg.iter_mut() {
2399                                *v = c * (*v / c).tanh();
2400                            }
2401                        }
2402                        let lg = &logits[k * rows..k * rows + self.vocab_size.min(rows)];
2403                        let target = ids[pos + k0 + k + 1] as usize;
2404                        let max = lg.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
2405                        let lse: f64 = lg
2406                            .iter()
2407                            .map(|&v| ((v - max) as f64).exp())
2408                            .sum::<f64>()
2409                            .ln()
2410                            + max as f64;
2411                        nll += lse - lg[target] as f64;
2412                        cnt += 1;
2413                        if std::env::var("CMF_PPL_TRACE").is_ok() {
2414                            let top = lg
2415                                .iter()
2416                                .enumerate()
2417                                .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
2418                                .map(|(i, _)| i)
2419                                .unwrap_or(0);
2420                            eprintln!(
2421                                "BTRACE pos {} target {} nll {:.4} top {} lg_t {:.3} lg_top {:.3}",
2422                                pos + k0 + k, target, lse - lg[target] as f64, top, lg[target], lg[top]
2423                            );
2424                        }
2425                    }
2426                    k0 = k1;
2427                }
2428                pos = end;
2429            }
2430            self.kv_cache.clear();
2431            self.kv_history.clear();
2432            return (nll, cnt);
2433        }
2434        for pos in 0..ids.len().saturating_sub(1) {
2435            let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
2436            if pos < start {
2437                continue;
2438            }
2439            let normed = inference::rms_norm(
2440                &hidden,
2441                &self.weights.final_norm,
2442                self.rms_eps,
2443                self.norm_style,
2444            );
2445            // lm_head_forward applies the final-logit softcap itself —
2446            // capping again here double-squashed gemma-class logits
2447            // (tanh∘tanh) and reported a flattered ppl.
2448            let logits = self.lm_head_forward(&normed);
2449            let target = ids[pos + 1] as usize;
2450            let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
2451            let lse: f64 = logits
2452                .iter()
2453                .map(|&v| ((v - max) as f64).exp())
2454                .sum::<f64>()
2455                .ln()
2456                + max as f64;
2457            let tok_nll = lse - logits[target] as f64;
2458            if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 48 {
2459                let top = logits
2460                    .iter()
2461                    .enumerate()
2462                    .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
2463                    .map(|(i, _)| i)
2464                    .unwrap_or(0);
2465                eprintln!(
2466                    "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
2467                    logits[target], logits[top]
2468                );
2469            }
2470            nll += tok_nll;
2471            cnt += 1;
2472        }
2473        self.kv_cache.clear();
2474        self.kv_history.clear();
2475        (nll, cnt)
2476    }
2477
2478    /// Teacher-forced NLL of the CONVERTED model: the O(1) Nyström path
2479    /// is ACTIVE over the scored positions. Returns (nll sum, scored
2480    /// count) over `prefill..len-1`.
2481    ///
2482    /// Runtime discipline, deliberately NOT the matrix probe's: the
2483    /// first `prefill` tokens run the exact prompt pass — that pass is
2484    /// what freezes the landmarks and M — and every scored position then
2485    /// goes through `NystromState::step()`, the same code decode runs.
2486    /// So the landmarks are PREFILL-frozen (what ships), not
2487    /// full-sequence oracles (what the published probe measured), and
2488    /// every scored row carries a real far field rather than sitting
2489    /// inside the exact window.
2490    ///
2491    /// Pair with `nll_ids_from(ids, prefill)` for the exact baseline
2492    /// over the identical token set — that ratio is the honest one.
2493    pub fn nll_ids_o1(&mut self, ids: &[u32], prefill: usize) -> (f64, usize) {
2494        self.kv_cache.clear();
2495        self.kv_history.clear();
2496        self.o1_begin();
2497        let n = ids.len().saturating_sub(1);
2498        let p = prefill.min(n);
2499        // Exact prompt pass over ids[..p]: the seal consumes its q/k/v.
2500        let mut pos = 0usize;
2501        if prefill_batched() {
2502            const CHUNK: usize = 128;
2503            while pos < p {
2504                let end = (pos + CHUNK).min(p);
2505                let _ = self.prefill_batch(&ids[pos..end], pos);
2506                pos = end;
2507            }
2508        } else {
2509            while pos < p {
2510                let _ = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
2511                pos += 1;
2512            }
2513        }
2514        self.o1_seal();
2515
2516        let mut nll = 0f64;
2517        let mut cnt = 0usize;
2518        for pos in p..n {
2519            let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
2520            let normed = inference::rms_norm(
2521                &hidden,
2522                &self.weights.final_norm,
2523                self.rms_eps,
2524                self.norm_style,
2525            );
2526            // lm_head_forward applies the final-logit softcap itself —
2527            // capping again here double-squashed gemma-class logits
2528            // (tanh∘tanh) and reported a flattered ppl.
2529            let logits = self.lm_head_forward(&normed);
2530            let target = ids[pos + 1] as usize;
2531            let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
2532            let lse: f64 = logits
2533                .iter()
2534                .map(|&v| ((v - max) as f64).exp())
2535                .sum::<f64>()
2536                .ln()
2537                + max as f64;
2538            let tok_nll = lse - logits[target] as f64;
2539            if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 48 {
2540                let top = logits
2541                    .iter()
2542                    .enumerate()
2543                    .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
2544                    .map(|(i, _)| i)
2545                    .unwrap_or(0);
2546                eprintln!(
2547                    "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
2548                    logits[target], logits[top]
2549                );
2550            }
2551            nll += tok_nll;
2552            cnt += 1;
2553        }
2554        self.kv_cache.clear();
2555        self.kv_history.clear();
2556        (nll, cnt)
2557    }
2558
2559    /// Teacher-forced calibration data (B1): for each position, whether the
2560    /// argmax equals the actual next token, and the top-1 softmax prob
2561    /// (Born mass) under EACH temperature in `temps` — all from ONE forward
2562    /// pass (argmax/correctness are temperature-invariant; only p_max
2563    /// reshapes). Feeds `cortiq calibrate` (reliability/ECE + temperature
2564    /// fit): is the model's confidence a true property, or does it need a
2565    /// measured scaling?
2566    pub fn calib_ids(&mut self, ids: &[u32], temps: &[f32]) -> (Vec<bool>, Vec<Vec<f32>>) {
2567        self.kv_cache.clear();
2568        self.kv_history.clear();
2569        let n = ids.len().saturating_sub(1);
2570        let mut correct = Vec::with_capacity(n);
2571        let mut pmax = Vec::with_capacity(n);
2572        for pos in 0..n {
2573            let emb = self.embed_single(ids[pos]);
2574            let hidden = self.forward_layers(&emb, pos, None);
2575            let normed = inference::rms_norm(
2576                &hidden,
2577                &self.weights.final_norm,
2578                self.rms_eps,
2579                self.norm_style,
2580            );
2581            // lm_head_forward applies the final-logit softcap itself —
2582            // capping again here double-squashed gemma-class logits
2583            // (tanh∘tanh) and reported a flattered ppl.
2584            let logits = self.lm_head_forward(&normed);
2585            let target = ids[pos + 1] as usize;
2586            let (mut amax, mut mval) = (0usize, f32::NEG_INFINITY);
2587            for (i, &v) in logits.iter().enumerate() {
2588                if v > mval {
2589                    mval = v;
2590                    amax = i;
2591                }
2592            }
2593            correct.push(amax == target);
2594            let row: Vec<f32> = temps
2595                .iter()
2596                .map(|&t| {
2597                    let tt = t.max(1e-3);
2598                    let s: f32 = logits.iter().map(|&v| ((v - mval) / tt).exp()).sum();
2599                    1.0 / s.max(1e-12) // numerator at the max is exp(0)=1
2600                })
2601                .collect();
2602            pmax.push(row);
2603        }
2604        self.kv_cache.clear();
2605        self.kv_history.clear();
2606        (correct, pmax)
2607    }
2608
2609    /// Teacher-forced PPL with the dynamic router driving per-window
2610    /// skill switches (VMF experiment №2 measurement). Sequential (φ
2611    /// must update per token), returns (ppl, switch_count). The router
2612    /// must be enabled (`enable_dynamic_routing`); else this equals
2613    /// plain `ppl_ids`. The active skill when scoring token t shapes the
2614    /// logits for t+1 — on-policy over the held-out text itself.
2615    pub fn ppl_ids_dynamic(&mut self, ids: &[u32]) -> (f64, usize) {
2616        let mut router = match self.dyn_router.take() {
2617            Some(r) => r,
2618            None => return (self.ppl_ids(ids), 0),
2619        };
2620        router.reset();
2621        self.dyn_phi_seen = 0;
2622        let _ = self.set_active_skill(None);
2623
2624        self.kv_cache.clear();
2625
2626        self.kv_history.clear();
2627        let mut nll = 0f64;
2628        let mut cnt = 0usize;
2629        for pos in 0..ids.len().saturating_sub(1) {
2630            let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
2631            let normed = inference::rms_norm(
2632                &hidden,
2633                &self.weights.final_norm,
2634                self.rms_eps,
2635                self.norm_style,
2636            );
2637            // lm_head_forward applies the final-logit softcap itself —
2638            // capping again here double-squashed gemma-class logits
2639            // (tanh∘tanh) and reported a flattered ppl.
2640            let logits = self.lm_head_forward(&normed);
2641            let target = ids[pos + 1] as usize;
2642            let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
2643            let lse: f64 = logits
2644                .iter()
2645                .map(|&v| ((v - max) as f64).exp())
2646                .sum::<f64>()
2647                .ln()
2648                + max as f64;
2649            let tok_nll = lse - logits[target] as f64;
2650            if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 48 {
2651                let top = logits
2652                    .iter()
2653                    .enumerate()
2654                    .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
2655                    .map(|(i, _)| i)
2656                    .unwrap_or(0);
2657                eprintln!(
2658                    "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
2659                    logits[target], logits[top]
2660                );
2661            }
2662            nll += tok_nll;
2663            cnt += 1;
2664            // Route on the evolving φ (drives the NEXT token's skill).
2665            let phi = self.dyn_phi_ema.clone();
2666            if let Some(new_active) = router.step(&phi, pos) {
2667                let _ = self.set_active_skill(new_active);
2668            }
2669        }
2670        let switches = router.switches.len();
2671        let _ = self.set_active_skill(None);
2672        self.dyn_router = Some(router);
2673        self.kv_cache.clear();
2674        self.kv_history.clear();
2675        ((nll / cnt.max(1) as f64).exp(), switches)
2676    }
2677
2678    /// Routing probe φ (spec §9): mean-pooled hidden after `layer`.
2679    pub fn probe_phi(&mut self, ids: &[u32], layer: usize) -> Vec<f32> {
2680        self.kv_cache.clear();
2681        self.kv_history.clear();
2682        let mut acc = vec![0f32; self.hidden_size];
2683        for (pos, &id) in ids.iter().enumerate() {
2684            let h = self.forward_layers_upto(&self.embed_single(id), pos, None, Some(layer));
2685            for (a, v) in acc.iter_mut().zip(&h) {
2686                *a += v;
2687            }
2688        }
2689        let n = ids.len().max(1) as f32;
2690        for a in acc.iter_mut() {
2691            *a /= n;
2692        }
2693        self.kv_cache.clear();
2694        self.kv_history.clear();
2695        acc
2696    }
2697
2698    /// Layer-major batched prefill (prefill-GEMM): full-attention —
2699    /// per-position with the existing operators (KV grows naturally,
2700    /// causality preserved), GDN projections / FFN / MoE — batched
2701    /// (a weight row is read from DRAM once per chunk, not per
2702    /// position). Returns the hidden of all positions [b × hidden].
2703    fn prefill_batch(&mut self, ids: &[u32], start_pos: usize) -> Vec<f32> {
2704        let b = ids.len();
2705        let hs = self.hidden_size;
2706        // The CPU embed is deferred: when the chunk graph takes the run
2707        // from layer 0 it gathers the embeddings on the device instead.
2708        let mut h: Vec<f32> = vec![0.0; b * hs];
2709        let mut h_ready = false;
2710        let fill_h = |h: &mut Vec<f32>, me: &Self| {
2711            for (bi, &id) in ids.iter().enumerate() {
2712                let e = me.embed_single(id);
2713                h[bi * hs..(bi + 1) * hs].copy_from_slice(&e);
2714            }
2715        };
2716        let (_nkv, _hd, _rd, eps) = (
2717            self.num_kv_heads,
2718            self.head_dim,
2719            self.rotary_dim,
2720            self.rms_eps,
2721        );
2722        let pool = self.pool.clone();
2723        let norm_style = self.norm_style;
2724
2725        #[cfg(target_os = "macos")]
2726        let mut chunk_skip_until = 0usize;
2727        for li in 0..self.num_layers {
2728            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU
2729            // GPU chunk graph (default-on under CMF_GPU=1): a run of
2730            // consecutive eligible layers for the whole chunk in ONE
2731            // Metal submission — norm, QKV, RoPE with fused mirror
2732            // append, causal attend, O, FFN, hidden device-resident
2733            // across the run. Any refusal falls through to the CPU path.
2734            #[cfg(target_os = "macos")]
2735            {
2736                if li < chunk_skip_until {
2737                    continue;
2738                }
2739                // Device-side embedding needs a q8_row embedding matrix;
2740                // with any other layout the CPU fills `h` first and the
2741                // graph starts from a ready hidden (refusing the whole
2742                // run over the embedding alone kept q4t models — the
2743                // whole Nanbeige/Bonsai class — on the CPU prefill).
2744                if !h_ready && li == 0 && self.weights.embed_tokens.q8_row_parts().is_none() {
2745                    fill_h(&mut h, self);
2746                    h_ready = true;
2747                }
2748                let ids_for_embed = (!h_ready && li == 0).then_some(ids);
2749                let end = self.chunk_run_gpu(li, &mut h, b, start_pos, ids_for_embed);
2750                if end > li {
2751                    h_ready = true;
2752                    chunk_skip_until = end;
2753                    // Looped Transformer: the graph stopped at a loop
2754                    // boundary — apply final norm before the next iteration.
2755                    if self.is_loop_end(end - 1) && end < self.num_layers {
2756                        for bi in 0..b {
2757                            let normed = inference::rms_norm(
2758                                &h[bi * hs..(bi + 1) * hs],
2759                                &self.weights.final_norm,
2760                                eps,
2761                                norm_style,
2762                            );
2763                            h[bi * hs..(bi + 1) * hs].copy_from_slice(&normed);
2764                        }
2765                    }
2766                    continue;
2767                }
2768            }
2769            if !h_ready {
2770                fill_h(&mut h, self);
2771                h_ready = true;
2772            }
2773            let lw = &self.weights.layers[self.phys_layer(li)];
2774            // ── attention ──
2775            match &lw.attn {
2776                AttnKind::Kda(w) => {
2777                    // Projections batched, recurrence sequential.
2778                    let cfg = self.kda_cfg.expect("kda layer without kda_cfg");
2779                    let mut normed = vec![0.0f32; b * hs];
2780                    for bi in 0..b {
2781                        inference::rms_norm_into(
2782                            &h[bi * hs..(bi + 1) * hs],
2783                            &lw.input_norm,
2784                            eps,
2785                            norm_style,
2786                            &mut normed[bi * hs..(bi + 1) * hs],
2787                        );
2788                    }
2789                    let attn = crate::linear_core::kda_forward_batch(
2790                        &normed,
2791                        b,
2792                        w,
2793                        &cfg,
2794                        &mut self.kv_cache.layers[li].linear_state,
2795                        pool.as_deref(),
2796                    );
2797                    for (dst, &a) in h.iter_mut().zip(&attn) {
2798                        *dst += a;
2799                    }
2800                }
2801                AttnKind::LinearGdn(w) => {
2802                    // Projections batched, recurrence sequential.
2803                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
2804                    let mut normed = vec![0.0f32; b * hs];
2805                    for bi in 0..b {
2806                        let r = inference::rms_norm(
2807                            &h[bi * hs..(bi + 1) * hs],
2808                            &lw.input_norm,
2809                            eps,
2810                            norm_style,
2811                        );
2812                        normed[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
2813                    }
2814                    let attn = crate::linear_core::gdn_forward_batch(
2815                        &normed,
2816                        b,
2817                        w,
2818                        &cfg,
2819                        &mut self.kv_cache.layers[li].linear_state,
2820                        pool.as_deref(),
2821                    );
2822                    for (dst, &a) in h.iter_mut().zip(&attn) {
2823                        *dst += a;
2824                    }
2825                }
2826                AttnKind::ShortConv(w) => {
2827                    // Projections batched over the chunk; the conv walks the
2828                    // contiguous positions in order (same ring as decode).
2829                    let cfg = self
2830                        .short_conv_cfg
2831                        .expect("short-conv layer without short_conv_cfg");
2832                    let mut normed = vec![0.0f32; b * hs];
2833                    for bi in 0..b {
2834                        inference::rms_norm_into(
2835                            &h[bi * hs..(bi + 1) * hs],
2836                            &lw.input_norm,
2837                            eps,
2838                            norm_style,
2839                            &mut normed[bi * hs..(bi + 1) * hs],
2840                        );
2841                    }
2842                    let attn = short_conv_forward_batch(
2843                        &normed,
2844                        b,
2845                        w,
2846                        &cfg,
2847                        &mut self.kv_cache.layers[li].linear_state,
2848                        pool.as_deref(),
2849                    );
2850                    for (dst, &a) in h.iter_mut().zip(&attn) {
2851                        *dst += a;
2852                    }
2853                }
2854                AttnKind::Mla(w) => {
2855                    // Per-position prefill (correctness first; latent
2856                    // batching is a later optimization).
2857                    let inv_freq_l = self.layer_inv_freq(li);
2858                    let rs = self.layer_rope_scale(li);
2859                    let mut normed = vec![0.0f32; hs];
2860                    for bi in 0..b {
2861                        inference::rms_norm_into(
2862                            &h[bi * hs..(bi + 1) * hs],
2863                            &lw.input_norm,
2864                            eps,
2865                            norm_style,
2866                            &mut normed,
2867                        );
2868                        let ao = mla_attention(
2869                            w,
2870                            &normed,
2871                            &mut self.kv_cache.layers[li],
2872                            start_pos + bi,
2873                            &inv_freq_l,
2874                            rs,
2875                            eps,
2876                            pool.as_deref(),
2877                        );
2878                        for (dst, &a) in h[bi * hs..(bi + 1) * hs].iter_mut().zip(&ao) {
2879                            *dst += a;
2880                        }
2881                    }
2882                }
2883                AttnKind::Full {
2884                    wq,
2885                    wk,
2886                    wv,
2887                    wo,
2888                    q_norm,
2889                    k_norm,
2890                    output_gate,
2891                    softplus_gate,
2892                    bias,
2893                } => {
2894                    // Chunk-GEMM QKV/O; per-position causal attention
2895                    // inside (roadmap §3 P0 — full-attention prefill no
2896                    // longer re-reads the projection weights b times).
2897                    let mut normed = vec![0.0f32; b * hs];
2898                    for bi in 0..b {
2899                        inference::rms_norm_into(
2900                            &h[bi * hs..(bi + 1) * hs],
2901                            &lw.input_norm,
2902                            eps,
2903                            norm_style,
2904                            &mut normed[bi * hs..(bi + 1) * hs],
2905                        );
2906                    }
2907                    let inv_freq_l = self.layer_inv_freq(li);
2908                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
2909                    let cfg = QwenAttnCfg {
2910                        num_heads: self.layer_num_heads(li),
2911                        num_kv_heads: nkv_l,
2912                        head_dim: hd_l,
2913                        hidden_size: hs,
2914                        position: start_pos,
2915                        inv_freq: &inv_freq_l,
2916                        rotary_dim: rd_l,
2917                        scale: self.attn_scale,
2918            softcap: self.attn_softcap,
2919                        window: self.layer_window(li),
2920                        v_norm: self.attn_v_norm,
2921                        q_norm: q_norm.as_deref(),
2922                        k_norm: k_norm.as_deref(),
2923                        output_gate: *output_gate,
2924                        softplus_gate: softplus_gate
2925                            .as_ref()
2926                            .map(|(gate, per_head)| (gate, *per_head)),
2927                        rope_scale: self.layer_rope_scale(li),
2928                        bias: bias
2929                            .as_ref()
2930                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
2931                        rms_eps: eps,
2932                        norm_style,
2933                        pool: pool.as_deref(),
2934                    };
2935                    let mut attn = attention::qwen_attention_batch(
2936                        &normed,
2937                        b,
2938                        wq,
2939                        wk,
2940                        wv,
2941                        wo,
2942                        &mut self.kv_cache.layers[li],
2943                        &cfg,
2944                    );
2945                    if let Some(w) = &lw.attn_out_norm {
2946                        for bi in 0..b {
2947                            inference::rms_norm_into(
2948                                &attn[bi * hs..(bi + 1) * hs],
2949                                w,
2950                                eps,
2951                                norm_style,
2952                                &mut normed[bi * hs..(bi + 1) * hs],
2953                            );
2954                        }
2955                        attn.copy_from_slice(&normed);
2956                    }
2957                    for (dst, &a) in h.iter_mut().zip(&attn) {
2958                        *dst += a;
2959                    }
2960                }
2961                AttnKind::Linear(w) => {
2962                    for bi in 0..b {
2963                        let normed = inference::rms_norm(
2964                            &h[bi * hs..(bi + 1) * hs],
2965                            &lw.input_norm,
2966                            eps,
2967                            norm_style,
2968                        );
2969                        vmf_phase_forward(
2970                            &normed,
2971                            w,
2972                            &self.vmf_cfg.expect("linear layer without vmf_cfg"),
2973                            &mut self.kv_cache.layers[li].linear_state,
2974                            pool.as_deref(),
2975                        )
2976                        .iter()
2977                        .enumerate()
2978                        .for_each(|(i, &a)| h[bi * hs + i] += a);
2979                    }
2980                }
2981            }
2982
2983            // ── FFN batched ──
2984            let lw = &self.weights.layers[self.phys_layer(li)];
2985            let mut post = vec![0.0f32; b * hs];
2986            for bi in 0..b {
2987                let r =
2988                    inference::rms_norm(&h[bi * hs..(bi + 1) * hs], &lw.post_norm, eps, norm_style);
2989                post[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
2990            }
2991            let mut ffn = match &lw.ffn {
2992                FfnKind::Dense(d) => dense_ffn_batch(d, &post, b, pool.as_deref()),
2993                FfnKind::Moe(m) => moe_ffn_batch(m, &post, b, hs, pool.as_deref(), None),
2994                // Dual-branch layers run per position (the expert branch
2995                // reads the raw residual — nothing to batch yet).
2996                FfnKind::DenseMoe(dm) => {
2997                    let mut out = vec![0.0f32; b * hs];
2998                    for bi in 0..b {
2999                        let r = dense_moe_ffn(
3000                            dm,
3001                            &post[bi * hs..(bi + 1) * hs],
3002                            &h[bi * hs..(bi + 1) * hs],
3003                            eps,
3004                            norm_style,
3005                            pool.as_deref(),
3006                        );
3007                        out[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
3008                    }
3009                    out
3010                }
3011            };
3012            if let Some(w) = &lw.ffn_out_norm {
3013                for bi in 0..b {
3014                    inference::rms_norm_into(
3015                        &ffn[bi * hs..(bi + 1) * hs],
3016                        w,
3017                        eps,
3018                        norm_style,
3019                        &mut post[bi * hs..(bi + 1) * hs],
3020                    );
3021                }
3022                ffn.copy_from_slice(&post);
3023            }
3024            for (dst, &f) in h.iter_mut().zip(&ffn) {
3025                *dst += f;
3026            }
3027            if let Some(sc) = lw.layer_scale {
3028                for v in h.iter_mut() {
3029                    *v *= sc;
3030                }
3031            }
3032            if let Ok(tp) = std::env::var("CMF_TRACE_POS") {
3033                if let Some(t) = tp.parse::<usize>().ok() {
3034                    if t >= start_pos && t < start_pos + b {
3035                        let bi = t - start_pos;
3036                        let row = &h[bi * hs..(bi + 1) * hs];
3037                        let n: f32 = row.iter().map(|x| x * x).sum::<f32>().sqrt();
3038                        eprintln!(
3039                            "BATCH pos {t} after layer {li}: |h| = {n:.6} h0 {:.6} h1 {:.6}",
3040                            row[0], row[1]
3041                        );
3042                    }
3043                }
3044            }
3045            // CMF_DEBUG_LAYERS=1: per-layer hidden-state health of the
3046            // LAST prompt position — the knife for "which layer type
3047            // breaks first" on a new architecture.
3048            if std::env::var("CMF_DEBUG_LAYERS").is_ok() {
3049                let row = &h[(b - 1) * hs..b * hs];
3050                let rms =
3051                    (row.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / hs as f64).sqrt();
3052                let mx = row.iter().fold(0f32, |m, &v| m.max(v.abs()));
3053                eprintln!(
3054                    "layer {li:>3} {:>10} ffn={:<5} rms={rms:>12.4} max={mx:>12.4}",
3055                    match &self.weights.layers[self.phys_layer(li)].attn {
3056                        AttnKind::LinearGdn(_) => "gdn",
3057                        AttnKind::Linear(_) => "vmf",
3058                        AttnKind::ShortConv(_) => "conv",
3059                        _ => "attn",
3060                    },
3061                    match &lw.ffn {
3062                        FfnKind::Moe(_) => "moe",
3063                        FfnKind::Dense(_) => "dense",
3064                        FfnKind::DenseMoe(_) => "dense+moe",
3065                    },
3066                );
3067            }
3068            // Looped Transformer: apply final norm at the end of each loop iteration.
3069            if self.is_loop_end(li) && li + 1 < self.num_layers {
3070                for bi in 0..b {
3071                    let normed = inference::rms_norm(
3072                        &h[bi * hs..(bi + 1) * hs],
3073                        &self.weights.final_norm,
3074                        eps,
3075                        norm_style,
3076                    );
3077                    h[bi * hs..(bi + 1) * hs].copy_from_slice(&normed);
3078                }
3079            }
3080            if std::env::var("CMF_TRACE_H").is_ok() {
3081                let n = h[..hs].iter().map(|v| v.abs()).sum::<f32>() / hs as f32;
3082                let mx = h[..hs].iter().fold(0.0f32, |a, &v| a.max(v.abs()));
3083                eprintln!(
3084                    "layer {li}: mean|h|={n:.4} max|h|={mx:.2} scale={:?}",
3085                    lw.layer_scale
3086                );
3087            }
3088        }
3089        crate::gpu::set_layer(-1); // lm_head/final ops outside layer-split
3090        h
3091    }
3092
3093    /// Embed a single token.
3094    fn embed_single(&self, id: u32) -> Vec<f32> {
3095        let mut out = vec![0.0f32; self.hidden_size];
3096        if (id as usize) < self.weights.embed_tokens.rows() {
3097            self.weights.embed_tokens.row_f32(id as usize, &mut out);
3098        }
3099        if self.embed_multiplier != 1.0 {
3100            for v in out.iter_mut() {
3101                *v *= self.embed_multiplier;
3102            }
3103        }
3104        // Gemma-3n: the per-layer-embedding half needs the token ID, so
3105        // it rides appended to the embedding; the g3n forward splits it.
3106        if let Some(b) = &self.g3n {
3107            return b.0.extend_embedding(id, &out, self.pool.as_deref());
3108        }
3109        out
3110    }
3111
3112    /// A run of consecutive prefill layers on the GPU for the whole
3113    /// chunk (default-on under CMF_GPU=1; CMF_GPU_CHUNK=0 disables).
3114    /// Eligibility per layer: q8_row weights, plain full attention
3115    /// (no output gate), F32 KV, no o1/masks/gemma extras. Returns the
3116    /// first layer index NOT processed (== `li0` when the run is empty).
3117    #[cfg(target_os = "macos")]
3118    fn chunk_run_gpu(
3119        &mut self,
3120        li0: usize,
3121        h: &mut [f32],
3122        b: usize,
3123        pos0: usize,
3124        embed_ids: Option<&[u32]>,
3125    ) -> usize {
3126        // (The old streaming attend needed a depth bound at ~1k; the
3127        // GEMM attention scales like the CPU path and lifted it.)
3128        // CMF_GPU_CHUNK=0 disables the graph.
3129        if !crate::gpu::enabled_here()
3130            || std::env::var("CMF_GPU_CHUNK")
3131                .map(|v| v == "0")
3132                .unwrap_or(false)
3133            || b < 32
3134            || self.swa.is_some()
3135            || self.global_attn.is_some()
3136            || self.attn_v_norm
3137            || (self.attn_scale - 1.0 / (self.head_dim as f32).sqrt()).abs() > 1e-9
3138        {
3139            return li0;
3140        }
3141        let Some(model) = self.model.clone() else {
3142            return li0;
3143        };
3144        let inv_freq = self.inv_freq.clone();
3145        let (nh, nkv, hd, hs) = (
3146            self.num_heads,
3147            self.num_kv_heads,
3148            self.head_dim,
3149            self.hidden_size,
3150        );
3151        // Collect the longest run of consecutive eligible layers.
3152        // Looped Transformer: stop at the loop boundary so the CPU can
3153        // apply loop_final_norm between iterations.
3154        let loop_end = if self.loop_final_norm {
3155            ((li0 / self.physical_layers) + 1) * self.physical_layers
3156        } else {
3157            self.num_layers
3158        };
3159        let mut layers: Vec<crate::gpu_metal::ChunkLayer> = Vec::new();
3160        let mut stored_at: Vec<usize> = Vec::new();
3161        for li in li0..self.num_layers.min(loop_end) {
3162            let lw = &self.weights.layers[self.phys_layer(li)];
3163            if lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some() {
3164                break;
3165            }
3166            let AttnKind::Full {
3167                wq,
3168                wk,
3169                wv,
3170                wo,
3171                q_norm,
3172                k_norm,
3173                output_gate: false,
3174                softplus_gate: None,
3175                bias,
3176            } = &lw.attn
3177            else {
3178                break;
3179            };
3180            let FfnKind::Dense(d) = &lw.ffn else { break };
3181            if d.act != Act::Silu {
3182                break;
3183            }
3184            // q8_row (row_scale populated), or q4_tiled / q4tp (row_scale
3185            // empty — their scales are in the payload). Mixing across the
3186            // seven projections of one layer is fine; the encoder branches
3187            // per weight on the tensor's dtype. Anything else refuses.
3188            fn cw(t: &QTensor) -> Option<(usize, usize, usize, &[f32])> {
3189                t.q8_row_parts()
3190                    .or_else(|| t.q4t_parts().map(|(i, r, c)| (i, r, c, &[][..])))
3191                    .or_else(|| t.q4tp_parts().map(|(i, r, c)| (i, r, c, &[][..])))
3192            }
3193            let parts = (
3194                cw(wq),
3195                cw(wk),
3196                cw(wv),
3197                cw(wo),
3198                cw(&d.gate_proj),
3199                cw(&d.up_proj),
3200                cw(&d.down_proj),
3201            );
3202            let (Some(pq), Some(pk), Some(pv), Some(po), Some(pg), Some(pu), Some(pd)) = parts
3203            else {
3204                break;
3205            };
3206            let layer = &self.kv_cache.layers[li];
3207            if layer.mode != crate::kv_cache::KvMode::F32 || layer.o1.is_some() {
3208                break;
3209            }
3210            stored_at.push(layer.head_len(0));
3211            layers.push(crate::gpu_metal::ChunkLayer {
3212                model: &model,
3213                kv_id: self.graph_kv_id,
3214                layer: li,
3215                wq: pq,
3216                wk: pk,
3217                wv: pv,
3218                wo: po,
3219                gate: pg,
3220                up: pu,
3221                down: pd,
3222                input_norm: &lw.input_norm,
3223                post_norm: &lw.post_norm,
3224                bias: bias
3225                    .as_ref()
3226                    .map(|(a, bb, cc)| (a.as_slice(), bb.as_slice(), cc.as_slice())),
3227                q_norm: q_norm.as_deref(),
3228                k_norm: k_norm.as_deref(),
3229                inv_freq: &inv_freq,
3230                rd: self.rotary_dim,
3231                nh,
3232                nkv,
3233                hd,
3234                hs,
3235                inter: d.gate_proj.rows(),
3236                gemma: matches!(self.norm_style, cortiq_core::NormStyle::Gemma),
3237                eps: self.rms_eps as f32,
3238            });
3239        }
3240        if layers.is_empty() {
3241            return li0;
3242        }
3243        let row = nkv * hd;
3244        let mut store: Vec<(Vec<f32>, Vec<f32>, Vec<f32>)> = stored_at
3245            .iter()
3246            .map(|&st| (vec![0f32; b * row], vec![0f32; b * row], vec![0f32; st + b]))
3247            .collect();
3248        let mut io: Vec<crate::gpu_metal::ChunkIo> = Vec::with_capacity(layers.len());
3249        for (i, (ok, ov, oi)) in store.iter_mut().enumerate() {
3250            let li = layers[i].layer;
3251            let layer = &self.kv_cache.layers[li];
3252            io.push(crate::gpu_metal::ChunkIo {
3253                cpu_stored: stored_at[i],
3254                cpu_k: (0..nkv).map(|g| layer.head_keys(g)).collect(),
3255                cpu_v: (0..nkv).map(|g| layer.head_values(g)).collect(),
3256                out_k: ok,
3257                out_v: ov,
3258                imp: oi,
3259            });
3260        }
3261        let n_run = layers.len();
3262        let last = layers.last().map(|l| l.layer + 1).unwrap_or(li0);
3263        // Device-side embedding when the run starts the model and the
3264        // embedding matrix is q8_row-mapped.
3265        let ep = embed_ids.and_then(|ids| {
3266            self.weights
3267                .embed_tokens
3268                .q8_row_parts()
3269                .map(|(idx, rows, _c, rs)| crate::gpu_metal::ChunkEmbed {
3270                    idx,
3271                    rows,
3272                    row_scale: rs,
3273                    ids,
3274                    mult: self.embed_multiplier,
3275                })
3276        });
3277        if embed_ids.is_some() && ep.is_none() {
3278            return li0;
3279        }
3280        if !crate::gpu_metal::chunk_run_gpu(&layers, &mut io, h, b, pos0, ep.as_ref()) {
3281            return li0;
3282        }
3283        drop(io);
3284        drop(layers);
3285        // CPU caches stay the owners of record: append the chunk rows
3286        // and bank the importance masses per layer.
3287        for (i, (ok, ov, oi)) in store.iter().enumerate().take(n_run) {
3288            let li = li0 + i;
3289            let layer = &mut self.kv_cache.layers[li];
3290            for bi in 0..b {
3291                layer.append(
3292                    &ok[bi * row..(bi + 1) * row],
3293                    &ov[bi * row..(bi + 1) * row],
3294                    &[],
3295                );
3296            }
3297            layer.accumulate_imp(oi);
3298        }
3299        last
3300    }
3301
3302    /// Is layer `li` a sliding-window (local-RoPE) layer? Gemma-3:
3303    /// every `pattern`-th layer is global, the rest are local.
3304    fn layer_is_local(&self, li: usize) -> bool {
3305        if let Some(layers) = &self.sliding_layers {
3306            return layers.get(li).copied().unwrap_or(false);
3307        }
3308        match self.swa {
3309            Some((_, pattern)) => (li + 1) % pattern.max(1) != 0,
3310            None => false,
3311        }
3312    }
3313
3314    /// The RoPE table for layer `li` (local layers may have their own;
3315    /// Gemma-4 global layers use the proportional padded table).
3316    fn layer_inv_freq(&self, li: usize) -> std::sync::Arc<Vec<f32>> {
3317        if self.layer_is_local(li) {
3318            if let Some(f) = &self.inv_freq_local {
3319                return f.clone();
3320            }
3321        } else if let Some(f) = &self.inv_freq_global {
3322            return f.clone();
3323        }
3324        self.inv_freq.clone()
3325    }
3326
3327    /// The attend window for layer `li` (None = full context).
3328    fn layer_window(&self, li: usize) -> Option<usize> {
3329        self.swa
3330            .and_then(|(w, _)| self.layer_is_local(li).then_some(w))
3331    }
3332
3333    fn layer_num_heads(&self, li: usize) -> usize {
3334        self.attention_heads_per_layer
3335            .as_ref()
3336            .and_then(|v| v.get(li).copied())
3337            .unwrap_or(self.num_heads)
3338    }
3339
3340    fn layer_rope_scale(&self, li: usize) -> f32 {
3341        if self.layer_is_local(li) {
3342            self.rope_scale_local
3343        } else {
3344            self.rope_scale
3345        }
3346    }
3347
3348    /// Attention geometry of layer `li`: (num_kv_heads, head_dim,
3349    /// rotary_dim). Gemma-4 global layers override all three.
3350    fn layer_geom(&self, li: usize) -> (usize, usize, usize) {
3351        if !self.layer_is_local(li) {
3352            if let Some((ghd, gkv)) = self.global_attn {
3353                return (gkv, ghd, ghd);
3354            }
3355        }
3356        (
3357            self.num_kv_heads,
3358            self.head_dim,
3359            if self.layer_is_local(li) {
3360                self.rotary_dim_local.unwrap_or(self.rotary_dim)
3361            } else {
3362                self.rotary_dim
3363            },
3364        )
3365    }
3366
3367    /// Forward one position through all layers (hybrid dispatch).
3368    fn forward_layers(
3369        &mut self,
3370        hidden: &[f32],
3371        position: usize,
3372        task_mask: Option<&TaskMask>,
3373    ) -> Vec<f32> {
3374        self.forward_layers_upto(hidden, position, task_mask, None)
3375    }
3376
3377    /// Build the whole-token wgpu graph for a pure-attention q1 model (every
3378    /// layer Full q1 + dense q1 FFN, no gate/bias). Returns the post-stack
3379    /// hidden (caller does final norm + lm_head), or None to fall back.
3380    fn try_token_graph_wgpu(
3381        &self,
3382        hidden: &[f32],
3383        position: usize,
3384        logits_out: &mut Vec<f32>,
3385    ) -> Option<Vec<f32>> {
3386        // O(1) Nyström decode runs off the sealed state, not the KV cache the
3387        // graph mirrors — never take the graph while o1 is active.
3388        let o1_gpu = std::env::var("CMF_O1_GPU").as_deref() == Ok("1");
3389        if (self.o1_active() && !o1_gpu) || self.attn_softcap > 0.0 {
3390            // Softcapped scores have no graph kernel yet — CPU owns them.
3391            // o1 rides the graph only behind CMF_O1_GPU=1 while the port
3392            // proves itself; without it the CPU path owns o1 as before.
3393            return None;
3394        }
3395        // Per-layer sealed o1 state for the graph. During prefill the
3396        // state is still Collecting -> views are None -> the graph
3397        // refuses below and the CPU prefill records the q trace and
3398        // seals, exactly as the o1 design requires.
3399        let o1_views: Vec<Option<Vec<crate::nystrom::O1DeviceView<'_>>>> = (0..self.num_layers)
3400            .map(|li| {
3401                if !o1_gpu {
3402                    return None;
3403                }
3404                self.kv_cache.layers[self.phys_layer(li)].o1_views()
3405            })
3406            .collect();
3407        if self.o1_active() && o1_gpu {
3408            // Any o1 layer not sealed (or degenerate exact-only) keeps the
3409            // whole token on the CPU: half-graph forwards would desync.
3410            let want: usize = (0..self.num_layers)
3411                .filter(|li| {
3412                    !matches!(self.kv_cache.layers[self.phys_layer(*li)].o1, None)
3413                })
3414                .count();
3415            let have = o1_views.iter().filter(|v| v.is_some()).count();
3416            if want == 0 || have != want {
3417                return None;
3418            }
3419        }
3420        let nh = self.num_heads;
3421        let (nkv, hd, rd) = self.layer_geom(0);
3422        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
3423        let mut layers = Vec::with_capacity(self.num_layers);
3424        let mut model = None;
3425        let dbg = std::env::var("CMF_GRAPH_DEBUG").is_ok();
3426        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
3427            if let Some((_, i, kind, rs)) = t.graph_weight() {
3428                return Some(crate::gpu::GraphW {
3429                    idx: i,
3430                    kind,
3431                    row_scale: rs,
3432                    data: &[],
3433                });
3434            }
3435            // Small unquantized projections (GDN in_proj_a/b) stay f32.
3436            t.as_f32().map(|d| crate::gpu::GraphW {
3437                idx: 0,
3438                kind: 4,
3439                row_scale: &[],
3440                data: d,
3441            })
3442        }
3443        for li in 0..self.num_layers {
3444            let lw = &self.weights.layers[self.phys_layer(li)];
3445            if dbg {
3446                let ak = match &lw.attn {
3447                    AttnKind::Mla(_) => "Mla".into(),
3448                    AttnKind::Full {
3449                        output_gate, bias, ..
3450                    } => format!("Full gate={output_gate} bias={}", bias.is_some()),
3451                    AttnKind::LinearGdn(_) => "LinearGdn".into(),
3452                    AttnKind::Kda(_) => "Kda".into(),
3453                    AttnKind::Linear(_) => "Linear".into(),
3454                    AttnKind::ShortConv(_) => "ShortConv".into(),
3455                };
3456                let fk = match &lw.ffn {
3457                    FfnKind::Dense(_) => "Dense",
3458                    FfnKind::Moe(_) => "Moe",
3459                    FfnKind::DenseMoe(_) => "DenseMoe",
3460                };
3461                eprintln!("graph L{li}: attn={ak} ffn={fk}");
3462            }
3463            let gffn = match &lw.ffn {
3464                FfnKind::DenseMoe(_) => return None, // dual branch: CPU path
3465                FfnKind::Dense(d) => crate::gpu::GraphFfn::Dense {
3466                    gate: gw(&d.gate_proj)?,
3467                    up: gw(&d.up_proj)?,
3468                    down: gw(&d.down_proj)?,
3469                },
3470                FfnKind::Moe(m) => {
3471                    // v1 scope: softmax router + shared expert + uniform
3472                    // q4t expert trios (the MoE-hybrid coder class). The
3473                    // biased/sigmoid routers and adaptive τ keep the CPU
3474                    // path, where they are implemented.
3475                    if m.router_sigmoid
3476                        || m.expert_bias.is_some()
3477                        || m.route_tau.is_some()
3478                        || m.mask.is_some()
3479                    {
3480                        return None;
3481                    }
3482                    let (se, sg) = m.shared.as_ref()?;
3483                    let sgate = gw(sg.as_ref()?)?;
3484                    let router = gw(&m.router)?;
3485                    let inter = m.experts.first()?.gate_proj.rows();
3486                    let mut experts = Vec::with_capacity(m.experts.len() + 1);
3487                    // q4t or q4tp, but not both in one layer — the kernels
3488                    // are picked per layer, not per expert.
3489                    let mut q4tp: Option<bool> = None;
3490                    for e in m.experts.iter().chain(std::iter::once(se)) {
3491                        if !matches!(e.act, Act::Silu)
3492                            || e.gate_proj.rows() != inter
3493                            || e.up_proj.rows() != inter
3494                        {
3495                            return None;
3496                        }
3497                        let (mm, gi, ui, di, is_p) = match e.gate_proj.mapped_q4t() {
3498                            Some((mm, gi)) => (
3499                                mm,
3500                                gi,
3501                                e.up_proj.mapped_q4t()?.1,
3502                                e.down_proj.mapped_q4t()?.1,
3503                                false,
3504                            ),
3505                            None => {
3506                                let (mm, gi) = e.gate_proj.mapped_q4tp()?;
3507                                (
3508                                    mm,
3509                                    gi,
3510                                    e.up_proj.mapped_q4tp()?.1,
3511                                    e.down_proj.mapped_q4tp()?.1,
3512                                    true,
3513                                )
3514                            }
3515                        };
3516                        if *q4tp.get_or_insert(is_p) != is_p {
3517                            return None;
3518                        }
3519                        model.get_or_insert_with(|| mm.clone());
3520                        experts.push((gi, ui, di));
3521                    }
3522                    crate::gpu::GraphFfn::Moe {
3523                        router,
3524                        shared_gate: sgate,
3525                        experts,
3526                        n_exp: m.experts.len(),
3527                        // CMF_TOPK_PROBE: timing probe only — output is WRONG.
3528                        // Fewer experts shrink the MoE arithmetic while the
3529                        // dispatch count stays identical, which is the only
3530                        // clean way to tell a launch-bound decode from a
3531                        // compute-bound one.
3532                        top_k: std::env::var("CMF_TOPK_PROBE")
3533                            .ok()
3534                            .and_then(|v| v.parse::<usize>().ok())
3535                            .filter(|k| *k > 0 && *k <= m.top_k)
3536                            .unwrap_or(m.top_k),
3537                        inter,
3538                        norm_topk: m.norm_topk_prob,
3539                        q4tp: q4tp?,
3540                    }
3541                }
3542            };
3543            let attn = match &lw.attn {
3544                AttnKind::Full {
3545                    wq,
3546                    wk,
3547                    wv,
3548                    wo,
3549                    q_norm,
3550                    k_norm,
3551                    output_gate,
3552                    softplus_gate,
3553                    bias,
3554                } => {
3555                    if softplus_gate.is_some() || self.attention_heads_per_layer.is_some() {
3556                        return None;
3557                    }
3558                    let (m, _, _, _) = wq.graph_weight()?;
3559                    model = Some(m.clone());
3560                    crate::gpu::GraphAttn::Full {
3561                        wq: gw(wq)?,
3562                        wk: gw(wk)?,
3563                        wv: gw(wv)?,
3564                        wo: gw(wo)?,
3565                        q_norm: q_norm.as_deref(),
3566                        k_norm: k_norm.as_deref(),
3567                        bias: bias
3568                            .as_ref()
3569                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
3570                        output_gate: *output_gate,
3571                        cpu_k: self.kv_cache.layers[li].k_heads(),
3572                        cpu_v: self.kv_cache.layers[li].v_heads(),
3573                    }
3574                }
3575                AttnKind::LinearGdn(w) => {
3576                    let cfg = self.gdn_cfg?;
3577                    let (m, _, _, _) = w.in_proj_qkv.graph_weight()?;
3578                    model = Some(m.clone());
3579                    crate::gpu::GraphAttn::Gdn {
3580                        qkv: gw(&w.in_proj_qkv)?,
3581                        z: gw(&w.in_proj_z)?,
3582                        a: gw(&w.in_proj_a)?,
3583                        b: gw(&w.in_proj_b)?,
3584                        out: gw(&w.out_proj)?,
3585                        conv1d: &w.conv1d,
3586                        a_log: &w.a_log,
3587                        dt_bias: &w.dt_bias,
3588                        norm: &w.norm,
3589                        nv: cfg.num_v_heads,
3590                        nk: cfg.num_k_heads,
3591                        dk: cfg.key_head_dim,
3592                        dv: cfg.value_head_dim,
3593                        kk: cfg.conv_kernel,
3594                        cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
3595                    }
3596                }
3597                _ => return None,
3598            };
3599            layers.push(crate::gpu::GraphLayer {
3600                input_norm: &lw.input_norm,
3601                attn,
3602                post_norm: &lw.post_norm,
3603                ffn: gffn,
3604            });
3605        }
3606        let model = model?;
3607        // Fold final-norm + lm_head into the graph when this call wants logits
3608        // and the lm_head is a graphable (quantized) weight — the graph then
3609        // reads back logits (into logits_out) instead of the hidden, dropping
3610        // the separate CPU/GPU lm_head op + its sync. Never the f32 fallback:
3611        // an unquantized lm_head is vocab·hidden and must not be uploaded.
3612        let lm_gw = if self.graph_want_logits
3613            && std::env::var("CMF_GPU_LMHEAD")
3614                .map(|v| v != "0")
3615                .unwrap_or(true)
3616        {
3617            self.weights.lm_head.graph_weight().map(|(_, i, kind, rs)| {
3618                (
3619                    crate::gpu::GraphW {
3620                        idx: i,
3621                        kind,
3622                        row_scale: rs,
3623                        data: &[],
3624                    },
3625                    self.weights.lm_head.rows(),
3626                )
3627            })
3628        } else {
3629            None
3630        };
3631        let lm = lm_gw.as_ref().map(|(gw, rows)| (gw, *rows));
3632        // Loop boundaries: virtual layer indices after which final_norm is applied
3633        // (mid-stack only; the last layer's norm folds into lm_head).
3634        let loop_norm_at: Vec<usize> = if self.loop_final_norm {
3635            (0..self.num_layers - 1)
3636                .filter(|&li| (li + 1) % self.physical_layers == 0)
3637                .collect()
3638        } else {
3639            Vec::new()
3640        };
3641        let mut h = hidden.to_vec();
3642        crate::gpu::forward_token_graph(
3643            &model,
3644            self.graph_kv_id,
3645            &layers,
3646            &o1_views,
3647            self.o1_epoch,
3648            &self.inv_freq,
3649            &mut h,
3650            nh,
3651            nkv,
3652            hd,
3653            rd,
3654            self.hidden_size,
3655            self.intermediate_size,
3656            position,
3657            self.kv_cache.max_seq_len,
3658            gemma,
3659            self.rms_eps as f32,
3660            lm,
3661            &self.weights.final_norm,
3662            logits_out,
3663            &loop_norm_at,
3664        )
3665        .then_some(h)
3666    }
3667
3668    /// Batched prefill: k contiguous prompt positions through the whole wgpu
3669    /// graph in ONE submit (projections/FFN as GEMMs). `hiddens` is [k·hidden]
3670    /// in/out (embeddings in, layer output out); KV mirror / GDN state advance.
3671    /// false ⇒ unsupported → caller keeps the per-position graph.
3672    fn try_batch_graph_wgpu(&self, hiddens: &mut [f32], positions: &[usize], k: usize) -> bool {
3673        if self.attn_softcap > 0.0 {
3674            return false; // capped scores: no graph kernel — CPU path
3675        }
3676        if self.o1_active() {
3677            return false;
3678        }
3679        let nh = self.num_heads;
3680        let (nkv, hd, rd) = self.layer_geom(0);
3681        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
3682        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
3683            if let Some((_, i, kind, rs)) = t.graph_weight() {
3684                return Some(crate::gpu::GraphW {
3685                    idx: i,
3686                    kind,
3687                    row_scale: rs,
3688                    data: &[],
3689                });
3690            }
3691            t.as_f32().map(|d| crate::gpu::GraphW {
3692                idx: 0,
3693                kind: 4,
3694                row_scale: &[],
3695                data: d,
3696            })
3697        }
3698        let built: Option<(
3699            Vec<crate::gpu::GraphLayer<'_>>,
3700            std::sync::Arc<cortiq_core::CmfModel>,
3701        )> = (|| {
3702            let mut layers = Vec::with_capacity(self.num_layers);
3703            let mut model = None;
3704            for li in 0..self.num_layers {
3705                let lw = &self.weights.layers[self.phys_layer(li)];
3706                // MoE routes per token, so its experts are encoded token by
3707                // token inside the batched submit while attention and the
3708                // projections stay GEMMs. Refusing MoE here is what left
3709                // prefill running one position at a time: 33 tok/s against
3710                // 54 on decode, i.e. reading the prompt was slower than
3711                // writing the answer.
3712                let gffn = match &lw.ffn {
3713                    FfnKind::Dense(d) => crate::gpu::GraphFfn::Dense {
3714                        gate: gw(&d.gate_proj)?,
3715                        up: gw(&d.up_proj)?,
3716                        down: gw(&d.down_proj)?,
3717                    },
3718                    FfnKind::Moe(m) => {
3719                        if m.router_sigmoid
3720                            || m.expert_bias.is_some()
3721                            || m.route_tau.is_some()
3722                            || m.mask.is_some()
3723                        {
3724                            return None;
3725                        }
3726                        let (se, sg) = m.shared.as_ref()?;
3727                        let sgate = gw(sg.as_ref()?)?;
3728                        let router = gw(&m.router)?;
3729                        let inter = m.experts.first()?.gate_proj.rows();
3730                        let mut experts = Vec::with_capacity(m.experts.len() + 1);
3731                        let mut q4tp: Option<bool> = None;
3732                        for e in m.experts.iter().chain(std::iter::once(se)) {
3733                            if !matches!(e.act, Act::Silu)
3734                                || e.gate_proj.rows() != inter
3735                                || e.up_proj.rows() != inter
3736                            {
3737                                return None;
3738                            }
3739                            let (mm, gi, ui, di, is_p) = match e.gate_proj.mapped_q4t() {
3740                                Some((mm, gi)) => (
3741                                    mm,
3742                                    gi,
3743                                    e.up_proj.mapped_q4t()?.1,
3744                                    e.down_proj.mapped_q4t()?.1,
3745                                    false,
3746                                ),
3747                                None => {
3748                                    let (mm, gi) = e.gate_proj.mapped_q4tp()?;
3749                                    (
3750                                        mm,
3751                                        gi,
3752                                        e.up_proj.mapped_q4tp()?.1,
3753                                        e.down_proj.mapped_q4tp()?.1,
3754                                        true,
3755                                    )
3756                                }
3757                            };
3758                            if *q4tp.get_or_insert(is_p) != is_p {
3759                                return None;
3760                            }
3761                            model.get_or_insert_with(|| mm.clone());
3762                            experts.push((gi, ui, di));
3763                        }
3764                        crate::gpu::GraphFfn::Moe {
3765                            router,
3766                            shared_gate: sgate,
3767                            experts,
3768                            n_exp: m.experts.len(),
3769                            top_k: m.top_k,
3770                            inter,
3771                            norm_topk: m.norm_topk_prob,
3772                            q4tp: q4tp?,
3773                        }
3774                    }
3775                    _ => return None,
3776                };
3777                let attn = match &lw.attn {
3778                    AttnKind::Full {
3779                        wq,
3780                        wk,
3781                        wv,
3782                        wo,
3783                        q_norm,
3784                        k_norm,
3785                        output_gate,
3786                        softplus_gate,
3787                        bias,
3788                    } => {
3789                        if softplus_gate.is_some() || self.attention_heads_per_layer.is_some() {
3790                            return None;
3791                        }
3792                        let (m, _, _, _) = wq.graph_weight()?;
3793                        model = Some(m.clone());
3794                        crate::gpu::GraphAttn::Full {
3795                            wq: gw(wq)?,
3796                            wk: gw(wk)?,
3797                            wv: gw(wv)?,
3798                            wo: gw(wo)?,
3799                            q_norm: q_norm.as_deref(),
3800                            k_norm: k_norm.as_deref(),
3801                            bias: bias
3802                                .as_ref()
3803                                .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
3804                            output_gate: *output_gate,
3805                            cpu_k: self.kv_cache.layers[li].k_heads(),
3806                            cpu_v: self.kv_cache.layers[li].v_heads(),
3807                        }
3808                    }
3809                    AttnKind::LinearGdn(w) => {
3810                        let cfg = self.gdn_cfg?;
3811                        let (m, _, _, _) = w.in_proj_qkv.graph_weight()?;
3812                        model = Some(m.clone());
3813                        crate::gpu::GraphAttn::Gdn {
3814                            qkv: gw(&w.in_proj_qkv)?,
3815                            z: gw(&w.in_proj_z)?,
3816                            a: gw(&w.in_proj_a)?,
3817                            b: gw(&w.in_proj_b)?,
3818                            out: gw(&w.out_proj)?,
3819                            conv1d: &w.conv1d,
3820                            a_log: &w.a_log,
3821                            dt_bias: &w.dt_bias,
3822                            norm: &w.norm,
3823                            nv: cfg.num_v_heads,
3824                            nk: cfg.num_k_heads,
3825                            dk: cfg.key_head_dim,
3826                            dv: cfg.value_head_dim,
3827                            kk: cfg.conv_kernel,
3828                            cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
3829                        }
3830                    }
3831                    _ => return None,
3832                };
3833                layers.push(crate::gpu::GraphLayer {
3834                    input_norm: &lw.input_norm,
3835                    attn,
3836                    post_norm: &lw.post_norm,
3837                    ffn: gffn,
3838                });
3839            }
3840            Some((layers, model?))
3841        })();
3842        let Some((layers, model)) = built else {
3843            {
3844                use std::sync::atomic::{AtomicBool, Ordering};
3845                static SAID: AtomicBool = AtomicBool::new(false);
3846                if !SAID.swap(true, Ordering::Relaxed) {
3847                    tracing::warn!("batch graph: BUILDER refused (layer weights/kinds)");
3848                }
3849            }
3850            return false;
3851        };
3852        crate::gpu::forward_batch_graph(
3853            &model,
3854            self.graph_kv_id,
3855            &layers,
3856            &self.inv_freq,
3857            hiddens,
3858            nh,
3859            nkv,
3860            hd,
3861            rd,
3862            self.hidden_size,
3863            self.intermediate_size,
3864            positions,
3865            self.kv_cache.max_seq_len,
3866            gemma,
3867            self.rms_eps as f32,
3868            k,
3869        )
3870    }
3871
3872    /// Same, stopping after layer `upto` inclusive (routing probe φ).
3873    fn forward_layers_upto(
3874        &mut self,
3875        hidden: &[f32],
3876        position: usize,
3877        task_mask: Option<&TaskMask>,
3878        upto: Option<usize>,
3879    ) -> Vec<f32> {
3880        // Gemma-3n runs its own stack (4 AltUp replicas don't fit this
3881        // loop); `hidden` is the extended embedding from embed_single.
3882        if let Some(b) = &self.g3n {
3883            let _ = (task_mask, upto);
3884            return crate::g3n::g3n_forward(
3885                &b.0,
3886                &b.1,
3887                hidden,
3888                position,
3889                &mut self.kv_cache.layers,
3890                self.num_heads,
3891                self.num_kv_heads,
3892                self.head_dim,
3893                self.pool.as_deref(),
3894            );
3895        }
3896        let mut h = hidden.to_vec();
3897        // Split borrows: copy scalars / clone handles so the per-layer
3898        // cfg does not hold `&self` while the KV cache is `&mut`.
3899        let (nh, _nkv, _hd, hs, _rd, eps) = (
3900            self.num_heads,
3901            self.num_kv_heads,
3902            self.head_dim,
3903            self.hidden_size,
3904            self.rotary_dim,
3905            self.rms_eps,
3906        );
3907        let pool = self.pool.clone();
3908        // Opt-in wgpu token-graph attention (discrete Vulkan/DX12): the whole
3909        // attention sub-block runs resident in one submit. Off by default.
3910        // Whole-token wgpu graph: eligibility + arbitration.
3911        //  - explicit CMF_GPU_WGPU_GRAPH forces it on/off;
3912        //  - discrete adapters (4090: decode 76 -> 137 tok/s) and GDN
3913        //    hybrids (recurrent state device-resident, no CPU twin to
3914        //    race) TRUST it;
3915        //  - integrated/mobile adapters RACE it against the normal path
3916        //    at generation granularity (gpu::graph_race_*) — tiled
3917        //    mobile GPUs can turn the ~300-dispatch graph into seconds
3918        //    per token, while a fast phone GPU keeps its win.
3919        let graph_env = std::env::var("CMF_GPU_WGPU_GRAPH").ok();
3920        let graph_on = match graph_env.as_deref() {
3921            Some("0") => false,
3922            Some(_) => true,
3923            // Unset: same discrete-only default as every other graph
3924            // site. "Is the GPU on" used to stand in here — which made
3925            // the 0.2 tok/s whole-token graph race-eligible on mobile
3926            // adapters and cost 12-14× on first tokens (cmfmobile
3927            // TUNING.md); integrated GPUs keep the per-op probe path.
3928            None => crate::gpu::wgpu_graph_default(),
3929        };
3930        let graph_trusted =
3931            graph_env.is_some() || crate::gpu::wgpu_graph_default() || self.gdn_cfg.is_some();
3932        let race_eligible = graph_on && upto.is_none() && task_mask.is_none();
3933        if race_eligible && crate::gpu::graph_race_use_graph(graph_trusted) {
3934            let t_graph = std::time::Instant::now();
3935            let mut lg = Vec::new();
3936            let built = self.try_token_graph_wgpu(hidden, position, &mut lg);
3937            graph_note(built.is_some());
3938            if let Some(hh) = built {
3939                let dur = t_graph.elapsed();
3940                if std::env::var("CMF_GRAPH_PROF").is_ok() {
3941                    eprintln!("graph-call: {:.2} ms total", dur.as_secs_f64() * 1000.0);
3942                }
3943                if graph_trusted || !crate::gpu::graph_race_first_token_hopeless(dur) {
3944                    if !graph_trusted {
3945                        crate::gpu::graph_race_record(true, dur);
3946                    }
3947                    if !lg.is_empty() {
3948                        // Graph produced logits (final-norm + lm_head folded in) —
3949                        // pad/cap to vocab and hand them to the sampler directly.
3950                        lg.resize(self.vocab_size, 0.0);
3951                        if let Some(c) = self.final_softcap {
3952                            for l in lg.iter_mut() {
3953                                *l = c * (*l / c).tanh();
3954                            }
3955                        }
3956                        self.graph_logits = Some(lg);
3957                    }
3958                    return hh;
3959                }
3960                // Hopeless first graph token: discard it and fall through
3961                // to the normal path. Safe exactly here — the prompt KV is
3962                // still CPU-owned (chunked prefill), so recomputing this
3963                // position is exact; the mirror's extra row is never read
3964                // (the race just settled on the normal path).
3965            }
3966        }
3967        let t_race_cpu = (race_eligible && !graph_trusted).then(std::time::Instant::now);
3968
3969        #[cfg(target_os = "macos")]
3970        let mut gpu_skip_until = 0usize;
3971        for li in 0..self.num_layers {
3972            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU (CMF_GPU_LAYERS)
3973            if let Some(u) = upto {
3974                if li > u {
3975                    break;
3976                }
3977            }
3978            if let Some(mask) = task_mask {
3979                if !mask.layer_alive(li) {
3980                    continue; // dead layer: residual pass-through
3981                }
3982            }
3983            // Whole-block q1 token graph: a run of consecutive q1
3984            // layers — GDN and full attention — executes with one sync
3985            // per CPU attend instead of per op (macOS/Metal).
3986            #[cfg(target_os = "macos")]
3987            {
3988                if li < gpu_skip_until {
3989                    continue;
3990                }
3991                if task_mask.is_none() {
3992                    let end = self.q1_graph_gpu(li, upto, position, &mut h);
3993                    if end > li {
3994                        gpu_skip_until = end;
3995                        // Looped Transformer: the graph stopped at a loop
3996                        // boundary — apply final norm before the next iteration.
3997                        if self.is_loop_end(end - 1) && end < self.num_layers {
3998                            h = inference::rms_norm(
3999                                &h,
4000                                &self.weights.final_norm,
4001                                self.rms_eps,
4002                                self.norm_style,
4003                            );
4004                        }
4005                        continue;
4006                    }
4007                }
4008            }
4009
4010            let lw = &self.weights.layers[self.phys_layer(li)];
4011            if let Ok(tp) = std::env::var("CMF_TRACE_POS") {
4012                if tp.parse::<usize>().ok() == Some(position) {
4013                    let n: f32 = h.iter().map(|x| x * x).sum::<f32>().sqrt();
4014                    eprintln!(
4015                        "TRACE pos {position} layer {li}: |h| = {n:.6} h0 {:.6} h1 {:.6}",
4016                        h[0], h[1]
4017                    );
4018                }
4019            }
4020            // Norm into the pipeline scratch — the returning rms_norm
4021            // allocated twice per layer per token (roadmap §3 P0).
4022            inference::rms_norm_into(
4023                &h,
4024                &lw.input_norm,
4025                self.rms_eps,
4026                self.norm_style,
4027                &mut self.ws.n1,
4028            );
4029
4030            let attn_out = match &lw.attn {
4031                AttnKind::Mla(w) => {
4032                    let inv_freq_l = self.layer_inv_freq(li);
4033                    let rs = self.layer_rope_scale(li);
4034                    let eps = self.rms_eps;
4035                    let pool = self.pool.clone();
4036                    mla_attention(
4037                        w,
4038                        &self.ws.n1,
4039                        &mut self.kv_cache.layers[li],
4040                        position,
4041                        &inv_freq_l,
4042                        rs,
4043                        eps,
4044                        pool.as_deref(),
4045                    )
4046                }
4047                AttnKind::Linear(w) => {
4048                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
4049                    vmf_phase_forward(
4050                        &self.ws.n1,
4051                        w,
4052                        &cfg,
4053                        &mut self.kv_cache.layers[li].linear_state,
4054                        self.pool.as_deref(),
4055                    )
4056                }
4057                AttnKind::Kda(w) => {
4058                    let cfg = self.kda_cfg.expect("kda layer without kda_cfg");
4059                    crate::linear_core::kda_forward(
4060                        &self.ws.n1,
4061                        w,
4062                        &cfg,
4063                        &mut self.kv_cache.layers[li].linear_state,
4064                        self.pool.as_deref(),
4065                    )
4066                }
4067                AttnKind::LinearGdn(w) => {
4068                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
4069                    gdn_forward(
4070                        &self.ws.n1,
4071                        w,
4072                        &cfg,
4073                        &mut self.kv_cache.layers[li].linear_state,
4074                        self.pool.as_deref(),
4075                    )
4076                }
4077                AttnKind::ShortConv(w) => {
4078                    let cfg = self
4079                        .short_conv_cfg
4080                        .expect("short-conv layer without short_conv_cfg");
4081                    short_conv_forward(
4082                        &self.ws.n1,
4083                        w,
4084                        &cfg,
4085                        &mut self.kv_cache.layers[li].linear_state,
4086                        self.pool.as_deref(),
4087                    )
4088                }
4089                AttnKind::Full {
4090                    wq,
4091                    wk,
4092                    wv,
4093                    wo,
4094                    q_norm,
4095                    k_norm,
4096                    output_gate,
4097                    softplus_gate,
4098                    bias,
4099                } if self.kv_cache.layers[li].o1_sealed() => {
4100                    // O(1) override: decode on the sealed Nyström state
4101                    // instead of the growing KV cache.
4102                    let inv_freq_l = self.layer_inv_freq(li);
4103                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
4104                    let cfg = QwenAttnCfg {
4105                        num_heads: self.layer_num_heads(li),
4106                        num_kv_heads: nkv_l,
4107                        head_dim: hd_l,
4108                        hidden_size: hs,
4109                        position,
4110                        inv_freq: &inv_freq_l,
4111                        rotary_dim: rd_l,
4112                        scale: self.attn_scale,
4113            softcap: self.attn_softcap,
4114                        window: None,
4115                        v_norm: self.attn_v_norm,
4116                        q_norm: q_norm.as_deref(),
4117                        k_norm: k_norm.as_deref(),
4118                        output_gate: *output_gate,
4119                        softplus_gate: softplus_gate
4120                            .as_ref()
4121                            .map(|(gate, per_head)| (gate, *per_head)),
4122                        rope_scale: self.layer_rope_scale(li),
4123                        bias: bias
4124                            .as_ref()
4125                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
4126                        rms_eps: eps,
4127                        norm_style: self.norm_style,
4128                        pool: pool.as_deref(),
4129                    };
4130                    attention::qwen_attention_nystrom(
4131                        &self.ws.n1,
4132                        wq,
4133                        wk,
4134                        wv,
4135                        wo,
4136                        &mut self.kv_cache.layers[li],
4137                        &cfg,
4138                    )
4139                }
4140                AttnKind::Full {
4141                    wq,
4142                    wk,
4143                    wv,
4144                    wo,
4145                    q_norm,
4146                    k_norm,
4147                    output_gate,
4148                    softplus_gate,
4149                    bias,
4150                } => 'attn: {
4151                    // wgpu token-graph attention (opt-in): whole sub-block in
4152                    // one submit, device K/V mirror. q1 only, no gate/bias/mask.
4153                    if graph_on
4154                        && !*output_gate
4155                        && softplus_gate.is_none()
4156                        && self.attention_heads_per_layer.is_none()
4157                        && bias.is_none()
4158                        && task_mask.is_none()
4159                    {
4160                        let inv_freq_l = self.layer_inv_freq(li);
4161                        let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
4162                        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
4163                        if let (Some((gm, qi)), Some((_, ki)), Some((_, vi)), Some((_, oi))) = (
4164                            wq.mapped_q1(),
4165                            wk.mapped_q1(),
4166                            wv.mapped_q1(),
4167                            wo.mapped_q1(),
4168                        ) {
4169                            let gm = gm.clone();
4170                            let mut out = vec![0f32; hs];
4171                            let cache = &self.kv_cache.layers[li];
4172                            if crate::gpu::attn_dropin(
4173                                &gm,
4174                                self.graph_kv_id,
4175                                li,
4176                                &self.ws.n1,
4177                                qi,
4178                                ki,
4179                                vi,
4180                                oi,
4181                                q_norm.as_deref(),
4182                                k_norm.as_deref(),
4183                                &inv_freq_l,
4184                                nh,
4185                                nkv_l,
4186                                hd_l,
4187                                rd_l,
4188                                hs,
4189                                position,
4190                                self.kv_cache.max_seq_len,
4191                                gemma,
4192                                eps as f32,
4193                                cache.k_heads(),
4194                                cache.v_heads(),
4195                                &mut out,
4196                            ) {
4197                                break 'attn out;
4198                            }
4199                        }
4200                    }
4201                    let masked = task_mask
4202                        .map(|m| m.head_flags(li, self.num_heads).iter().any(|&a| !a))
4203                        .unwrap_or(false);
4204                    let f32_view = (wq.as_f32(), wk.as_f32(), wv.as_f32(), wo.as_f32());
4205                    match (masked, f32_view) {
4206                        // Historical masked path (f32 slices; the loader
4207                        // keeps masked models in f32).
4208                        (true, (Some(q), Some(k), Some(v), Some(o))) => {
4209                            let active_heads = task_mask.unwrap().head_flags(li, self.num_heads);
4210                            attention::multi_head_attention(
4211                                &self.ws.n1,
4212                                q,
4213                                k,
4214                                v,
4215                                o,
4216                                &mut self.kv_cache.layers[li],
4217                                self.num_heads,
4218                                self.num_kv_heads,
4219                                self.head_dim,
4220                                self.hidden_size,
4221                                position,
4222                                &active_heads,
4223                                &self.inv_freq,
4224                            )
4225                        }
4226                        (masked, _) => {
4227                            if masked {
4228                                tracing::warn!(
4229                                    "layer {li}: head mask on quantized weights not \
4230                                     supported yet — executing dense"
4231                                );
4232                            }
4233                            let inv_freq_l = self.layer_inv_freq(li);
4234                            let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
4235                            let cfg = QwenAttnCfg {
4236                                num_heads: self.layer_num_heads(li),
4237                                num_kv_heads: nkv_l,
4238                                head_dim: hd_l,
4239                                hidden_size: hs,
4240                                position,
4241                                inv_freq: &inv_freq_l,
4242                                rotary_dim: rd_l,
4243                                scale: self.attn_scale,
4244            softcap: self.attn_softcap,
4245                                window: self.layer_window(li),
4246                                v_norm: self.attn_v_norm,
4247                                q_norm: q_norm.as_deref(),
4248                                k_norm: k_norm.as_deref(),
4249                                output_gate: *output_gate,
4250                                softplus_gate: softplus_gate
4251                                    .as_ref()
4252                                    .map(|(gate, per_head)| (gate, *per_head)),
4253                                rope_scale: self.layer_rope_scale(li),
4254                                bias: bias
4255                                    .as_ref()
4256                                    .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
4257                                rms_eps: eps,
4258                                norm_style: self.norm_style,
4259                                pool: pool.as_deref(),
4260                            };
4261                            attention::qwen_attention(
4262                                &self.ws.n1,
4263                                wq,
4264                                wk,
4265                                wv,
4266                                wo,
4267                                &mut self.kv_cache.layers[li],
4268                                &cfg,
4269                            )
4270                        }
4271                    }
4272                }
4273            };
4274            // Gemma sandwich norm: normalize the attention branch before
4275            // it joins the residual stream.
4276            let attn_out = match &self.weights.layers[self.phys_layer(li)].attn_out_norm {
4277                Some(w) => inference::rms_norm(&attn_out, w, self.rms_eps, self.norm_style),
4278                None => attn_out,
4279            };
4280            let lw = &self.weights.layers[self.phys_layer(li)];
4281            inference::add_rmsnorm_fused_into(
4282                &mut h,
4283                &attn_out,
4284                &lw.post_norm,
4285                self.rms_eps,
4286                self.norm_style,
4287                &mut self.ws.p1,
4288            );
4289            let mut attn_out = attn_out;
4290            attention::recycle_buf(&mut attn_out);
4291            let post_normed = &self.ws.p1;
4292
4293            let ffn_masked = task_mask
4294                .map(|m| m.ffn_active_count(li) < self.intermediate_size)
4295                .unwrap_or(false);
4296            // Sparse mask path applies to dense f32 FFN only; MoE
4297            // layers route through the normal dispatch below.
4298            let f32_ffn = match &lw.ffn {
4299                FfnKind::Dense(d) => (
4300                    d.gate_proj.as_f32(),
4301                    d.up_proj.as_f32(),
4302                    d.down_proj.as_f32(),
4303                ),
4304                FfnKind::Moe(_) | FfnKind::DenseMoe(_) => (None, None, None),
4305            };
4306            let ffn_out = match (ffn_masked, f32_ffn) {
4307                (true, (Some(g), Some(u), Some(d))) => {
4308                    let active = task_mask.unwrap().ffn_active_indices(li);
4309                    inference::sparse_ffn_forward(
4310                        post_normed,
4311                        g,
4312                        u,
4313                        d,
4314                        self.hidden_size,
4315                        self.intermediate_size,
4316                        &active,
4317                        self.pool.as_deref(),
4318                    )
4319                }
4320                // Mask × quantized mmap: sparse FFN reads only active
4321                // neurons' rows/cols directly from the quant bytes — no
4322                // f32 model copy (a masked big model runs at quant RSS).
4323                (true, _) => match &lw.ffn {
4324                    FfnKind::Dense(d) if d.down_proj.sparse_col_ok() => {
4325                        let active = task_mask.unwrap().ffn_active_indices(li);
4326                        sparse_ffn_quant(
4327                            d,
4328                            post_normed,
4329                            &active,
4330                            self.hidden_size,
4331                            self.pool.as_deref(),
4332                        )
4333                    }
4334                    // q4/vbit down_proj has no cheap column access → dequant
4335                    // the three matrices to f32 (transient) and run the f32
4336                    // sparse path. Correct (mask honored), just not
4337                    // memory-lean for those dtypes — a rare masked case.
4338                    FfnKind::Dense(d) => {
4339                        let active = task_mask.unwrap().ffn_active_indices(li);
4340                        let (gf, uf, df) = dequant_dense_f32(d);
4341                        inference::sparse_ffn_forward(
4342                            post_normed,
4343                            &gf,
4344                            &uf,
4345                            &df,
4346                            self.hidden_size,
4347                            self.intermediate_size,
4348                            &active,
4349                            self.pool.as_deref(),
4350                        )
4351                    }
4352                    FfnKind::Moe(m) => {
4353                        // MoE is sparse by expert selection; a task mask
4354                        // narrows the ROUTABLE set via its expert fields
4355                        // (spec §5) when it carries them.
4356                        let allowed = task_mask
4357                            .and_then(|tm| tm.expert_flags(li, m.experts.len()));
4358                        ffn_forward(&lw.ffn, post_normed, self.pool.as_deref(), allowed.as_deref())
4359                    }
4360                    FfnKind::DenseMoe(dm) => dense_moe_ffn(
4361                        dm,
4362                        post_normed,
4363                        &h,
4364                        self.rms_eps,
4365                        self.norm_style,
4366                        self.pool.as_deref(),
4367                    ),
4368                },
4369                (false, _) => match &lw.ffn {
4370                    FfnKind::DenseMoe(dm) => dense_moe_ffn(
4371                        dm,
4372                        post_normed,
4373                        &h,
4374                        self.rms_eps,
4375                        self.norm_style,
4376                        self.pool.as_deref(),
4377                    ),
4378                    _ => {
4379                        let allowed = match (&lw.ffn, task_mask) {
4380                            (FfnKind::Moe(m), Some(tm)) => tm.expert_flags(li, m.experts.len()),
4381                            _ => None,
4382                        };
4383                        ffn_forward(&lw.ffn, post_normed, self.pool.as_deref(), allowed.as_deref())
4384                    }
4385                },
4386            };
4387            let ffn_out = match &self.weights.layers[self.phys_layer(li)].ffn_out_norm {
4388                Some(w) => inference::rms_norm(&ffn_out, w, self.rms_eps, self.norm_style),
4389                None => ffn_out,
4390            };
4391            for (i, &f) in ffn_out.iter().enumerate() {
4392                h[i] += f;
4393            }
4394            let mut ffn_out = ffn_out;
4395            attention::recycle_buf(&mut ffn_out);
4396
4397            // Gemma-4: the layer output is scaled by a learned scalar.
4398            if let Some(sc) = self.weights.layers[self.phys_layer(li)].layer_scale {
4399                for v in h.iter_mut() {
4400                    *v *= sc;
4401                }
4402            }
4403
4404            // Looped Transformer: apply final norm at the end of each loop iteration.
4405            // Nanbeige 4.2: after layer 21 (virtual), apply norm before looping back to layer 0.
4406            if self.is_loop_end(li) && li + 1 < self.num_layers {
4407                h = inference::rms_norm(
4408                    &h,
4409                    &self.weights.final_norm,
4410                    self.rms_eps,
4411                    self.norm_style,
4412                );
4413            }
4414
4415            // Dynamic routing φ capture (on-policy, fireball-style): the
4416            // EMA of the post-residual hidden at the router's phi_layer,
4417            // updated as the context evolves during decode.
4418            if self.dyn_phi_layer == Some(li) {
4419                self.update_dyn_phi(&h);
4420            }
4421        }
4422        crate::gpu::set_layer(-1); // layers done — lm_head outside layer-split
4423        if let Some(t) = t_race_cpu {
4424            crate::gpu::graph_race_record(false, t.elapsed());
4425        }
4426
4427        h
4428    }
4429
4430    /// EMA of φ at the router layer (rolling, weight 0.2 = ~5-token
4431    /// horizon). First observation seeds it exactly.
4432    fn update_dyn_phi(&mut self, h: &[f32]) {
4433        const A: f32 = 0.2;
4434        if self.dyn_phi_ema.len() != h.len() {
4435            self.dyn_phi_ema = vec![0.0; h.len()];
4436            self.dyn_phi_seen = 0;
4437        }
4438        if self.dyn_phi_seen == 0 {
4439            self.dyn_phi_ema.copy_from_slice(h);
4440        } else {
4441            for (e, &v) in self.dyn_phi_ema.iter_mut().zip(h) {
4442                *e = (1.0 - A) * *e + A * v;
4443            }
4444        }
4445        self.dyn_phi_seen += 1;
4446    }
4447
4448    /// Current router φ (EMA at phi_layer); empty until first capture.
4449    pub fn dyn_phi(&self) -> &[f32] {
4450        &self.dyn_phi_ema
4451    }
4452
4453    /// Enable/disable φ capture at the router layer, reset the EMA.
4454    pub fn set_dyn_phi_layer(&mut self, layer: Option<usize>) {
4455        self.dyn_phi_layer = layer;
4456        self.dyn_phi_ema.clear();
4457        self.dyn_phi_seen = 0;
4458    }
4459
4460    /// Skills eligible for dynamic switching: (index, id, phi_layer).
4461    pub fn dynamic_skills(&self) -> Vec<(usize, String, usize)> {
4462        let Some(model) = &self.model else {
4463            return Vec::new();
4464        };
4465        model
4466            .header
4467            .skills
4468            .iter()
4469            .enumerate()
4470            .filter_map(|(i, sk)| {
4471                let ok = matches!(self.dyn_skill_layers.get(i), Some(Some(_)));
4472                let sel = sk.selection.as_ref()?;
4473                (ok).then(|| (i, sk.id.clone(), sel.phi_layer))
4474            })
4475            .collect()
4476    }
4477
4478    /// Index of the currently overlaid skill (None = backbone).
4479    pub fn active_skill(&self) -> Option<usize> {
4480        self.dyn_active
4481    }
4482
4483    /// Enable dynamic per-token skill routing: build the hysteresis
4484    /// router from the container's routable skills, start φ capture at
4485    /// their (shared) phi_layer. Returns the number of routable skills
4486    /// (0 = nothing to route; router stays off). Idempotent.
4487    pub fn enable_dynamic_routing(&mut self) -> usize {
4488        use crate::swarm::{DynRouter, RoutableSkill};
4489        let Some(model) = self.model.clone() else {
4490            return 0;
4491        };
4492        // A blend materialized f32 working tensors into the layers; there
4493        // is no single skill index to revert from → refuse (honest).
4494        if self.dyn_blend_loaded {
4495            tracing::warn!("dynamic routing unavailable on a blend-loaded pipeline");
4496            return 0;
4497        }
4498        // A statically-overlaid skill that is NOT FFN-eligible can't be
4499        // cheaply reverted at generation start → refuse rather than
4500        // silently keep it overlaid.
4501        if let Some(a) = self.dyn_active {
4502            if !matches!(self.dyn_skill_layers.get(a), Some(Some(_))) {
4503                tracing::warn!("loaded skill is not FFN-eligible — dynamic routing unavailable");
4504                return 0;
4505            }
4506        }
4507        let hidden = self.hidden_size;
4508        let mut skills = Vec::new();
4509        for (idx, id, _phi) in self.dynamic_skills() {
4510            if let Some(sel) = model.header.skills[idx].selection.as_ref() {
4511                if let Some(rs) = RoutableSkill::from_descriptor(idx, id, sel, hidden) {
4512                    skills.push(rs);
4513                }
4514            }
4515        }
4516        if skills.is_empty() {
4517            return 0;
4518        }
4519        // Skills should share a phi_layer; warn (not fail) if they don't.
4520        let phi = skills[0].phi_layer;
4521        if skills.iter().any(|s| s.phi_layer != phi) {
4522            tracing::warn!("routable skills disagree on phi_layer; using {phi}");
4523        }
4524        let n = skills.len();
4525        self.set_dyn_phi_layer(Some(phi));
4526        self.dyn_router = Some(DynRouter::new(skills));
4527        n
4528    }
4529
4530    /// Human-readable switch log from the last dynamic-routed generation.
4531    pub fn route_switches(&self) -> Vec<(usize, Option<String>, Option<String>)> {
4532        self.dyn_router
4533            .as_ref()
4534            .map(|r| r.switches.clone())
4535            .unwrap_or_default()
4536    }
4537
4538    /// LM head: hidden → logits [vocab_size]. The dominant matvec of
4539    /// every decode step — row-parallel on the worker pool.
4540    fn lm_head_forward(&self, hidden: &[f32]) -> Vec<f32> {
4541        let rows = self.weights.lm_head.rows();
4542        let mut logits = attention::take_buf(rows.min(self.vocab_size));
4543        self.weights
4544            .lm_head
4545            .matvec(hidden, &mut logits, self.pool.as_deref());
4546        logits.resize(self.vocab_size, 0.0);
4547        if let Some(m) = self.logit_multiplier {
4548            for l in logits.iter_mut() {
4549                *l *= m;
4550            }
4551        }
4552        if let Some(c) = self.final_softcap {
4553            for l in logits.iter_mut() {
4554                *l = c * (*l / c).tanh();
4555            }
4556        }
4557        logits
4558    }
4559
4560    /// Prefill `ids` and return the next-token logits — what the model
4561    /// would predict next, WITHOUT committing to generation (introspection
4562    /// for `cortiq explain`). Clears and repopulates the KV cache; leaves
4563    /// the active overlay untouched.
4564    pub fn prefill_next_logits(&mut self, ids: &[u32], task_mask: Option<&TaskMask>) -> Vec<f32> {
4565        self.kv_cache.clear();
4566        self.kv_history.clear();
4567        let mut hidden = vec![0.0f32; self.hidden_size];
4568        for (pos, &id) in ids.iter().enumerate() {
4569            let emb = self.embed_single(id);
4570            hidden = self.forward_layers(&emb, pos, task_mask);
4571        }
4572        inference::rms_norm_into(
4573            &hidden,
4574            &self.weights.final_norm,
4575            self.rms_eps,
4576            self.norm_style,
4577            &mut self.ws.n1,
4578        );
4579        self.lm_head_forward(&self.ws.n1)
4580    }
4581}
4582
4583/// Convenience: deterministic tiny pipeline for tests.
4584pub fn create_test_pipeline(
4585    hidden_size: usize,
4586    intermediate_size: usize,
4587    num_heads: usize,
4588    num_kv_heads: usize,
4589    head_dim: usize,
4590    num_layers: usize,
4591    vocab_size: usize,
4592) -> Pipeline {
4593    // Small pseudo-random weights: constant weights make attention
4594    // degenerate and hide indexing bugs.
4595    let synth = |n: usize, salt: usize| -> Vec<f32> {
4596        (0..n)
4597            .map(|i| (((i * 31 + salt * 17 + 7) % 97) as f32 / 97.0 - 0.5) * 0.2)
4598            .collect()
4599    };
4600    let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
4601        QTensor::from_f32(synth(rows * cols, salt), rows, cols)
4602    };
4603    let layer_weights: Vec<LayerWeights> = (0..num_layers)
4604        .map(|li| LayerWeights {
4605            input_norm: vec![1.0; hidden_size],
4606            post_norm: vec![1.0; hidden_size],
4607            attn_out_norm: None,
4608            ffn_out_norm: None,
4609            layer_scale: None,
4610            ffn: FfnKind::Dense(DenseFfn {
4611                gate_proj: qt(intermediate_size, hidden_size, li * 10 + 5),
4612                up_proj: qt(intermediate_size, hidden_size, li * 10 + 6),
4613                down_proj: qt(hidden_size, intermediate_size, li * 10 + 7),
4614                act: Act::Silu,
4615            }),
4616            attn: AttnKind::Full {
4617                bias: None,
4618                wq: qt(num_heads * head_dim, hidden_size, li * 10 + 1),
4619                wk: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 2),
4620                wv: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 3),
4621                wo: qt(hidden_size, num_heads * head_dim, li * 10 + 4),
4622                q_norm: None,
4623                k_norm: None,
4624                output_gate: false,
4625                softplus_gate: None,
4626            },
4627        })
4628        .collect();
4629
4630    Pipeline::new(
4631        Tokenizer::byte_level(),
4632        PipelineWeights {
4633            embed_tokens: qt(vocab_size, hidden_size, 100),
4634            layers: layer_weights,
4635            lm_head: qt(vocab_size, hidden_size, 200),
4636            final_norm: vec![1.0; hidden_size],
4637        },
4638        hidden_size,
4639        intermediate_size,
4640        num_heads,
4641        num_kv_heads,
4642        head_dim,
4643        num_layers,
4644        num_layers, // physical_layers = num_layers (non-looped)
4645        false,      // loop_final_norm
4646        vocab_size,
4647        1e-6,
4648        10_000.0,
4649        NormStyle::Qwen,
4650        4096,
4651        SamplerConfig {
4652            seed: Some(42),
4653            ..Default::default()
4654        },
4655    )
4656}
4657
4658/// Batched dense-FFN: gate/up/down via matmat (element-wise the same
4659/// math as b × dense_ffn — the same dot kernels).
4660fn dense_ffn_batch(d: &DenseFfn, xs: &[f32], b: usize, pool: Option<&Pool>) -> Vec<f32> {
4661    let inter = d.gate_proj.rows();
4662    let hidden = d.down_proj.rows();
4663    // Fused on-device SwiGLU when the device is in play: three separate
4664    // `matmat` calls are three round trips per layer, and the gate/up
4665    // panels (b × inter — 22 MB each at a 512-token chunk) cross the bus
4666    // twice for nothing. The kernel already existed for the image DiT;
4667    // the LLM prefill was simply never wired to it.
4668    if d.act == Act::Silu && b >= 32 && crate::gpu::enabled_here() && !crate::gpu::mm_killed() {
4669        if let (Some((model, w1)), Some((_, w3)), Some((_, w2))) = (
4670            d.gate_proj.mapped_q4t(),
4671            d.up_proj.mapped_q4t(),
4672            d.down_proj.mapped_q4t(),
4673        ) {
4674            let mut out = vec![0.0f32; b * hidden];
4675            if crate::gpu::q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, &mut out) {
4676                return out;
4677            }
4678        }
4679    }
4680    let mut g = vec![0.0f32; b * inter];
4681    d.gate_proj.matmat(xs, b, &mut g, pool);
4682    let mut u = vec![0.0f32; b * inter];
4683    d.up_proj.matmat(xs, b, &mut u, pool);
4684    for i in 0..b * inter {
4685        g[i] = d.act.combine(g[i], u[i]);
4686    }
4687    let mut out = vec![0.0f32; b * hidden];
4688    d.down_proj.matmat(&g, b, &mut out, pool);
4689    out
4690}
4691
4692/// Batched MoE-FFN: router batched, positions are GROUPED by expert —
4693/// an expert's weights are read once for all its positions in the chunk
4694/// (the main prefill-GEMM win on MoE: 960MB/token of 35B experts).
4695/// Accumulate per-channel activation energy for `CMF_RMS_TRACE`.
4696fn accumulate_act(m: &MoeFfn, xs: &[f32], b: usize) {
4697    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4698    static DUMP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4699    let on = *ON.get_or_init(|| std::env::var("CMF_RMS_TRACE").is_ok());
4700    let dump = *DUMP.get_or_init(|| std::env::var("CMF_ACT_DUMP").is_ok());
4701    if (!on && !dump) || b == 0 {
4702        return;
4703    }
4704    let hidden = xs.len() / b;
4705    if on {
4706        let mut acc = m.act_sq.borrow_mut();
4707        if acc.len() < hidden {
4708            acc.resize(hidden, 0.0);
4709        }
4710        for t in 0..b {
4711            let row = &xs[t * hidden..(t + 1) * hidden];
4712            for (a, &v) in acc.iter_mut().zip(row) {
4713                *a += (v as f64) * (v as f64);
4714            }
4715        }
4716    }
4717    if dump {
4718        // Cap the capture: the covariance needs a few thousand rows, and a
4719        // whole prefill of every layer would be gigabytes for no extra rank.
4720        let cap: usize = std::env::var("CMF_ACT_DUMP_ROWS")
4721            .ok()
4722            .and_then(|v| v.parse().ok())
4723            .unwrap_or(4096);
4724        let mut rows = m.act_rows.borrow_mut();
4725        if rows.len() < cap * hidden {
4726            let take = b.min((cap * hidden - rows.len()) / hidden.max(1));
4727            rows.extend_from_slice(&xs[..take * hidden]);
4728        }
4729    }
4730}
4731
4732fn moe_ffn_batch(
4733    m: &MoeFfn,
4734    xs: &[f32],
4735    b: usize,
4736    hidden: usize,
4737    pool: Option<&Pool>,
4738    allowed: Option<&[bool]>,
4739) -> Vec<f32> {
4740    accumulate_act(m, xs, b);
4741    let ne = m.experts.len();
4742    let mut logits = vec![0.0f32; b * ne];
4743    m.router.matmat(xs, b, &mut logits, pool);
4744
4745    // Assignments: expert → [(position, weight)] — same routing as
4746    // moe_ffn, per position (see `moe_route`).
4747    let mut assign: Vec<Vec<(usize, f32)>> = vec![Vec::new(); ne];
4748    {
4749        let mut st = m.stats.borrow_mut();
4750        if st.len() < ne {
4751            st.resize(ne, 0);
4752        }
4753        for bi in 0..b {
4754            let (idx, p, wsum) = moe_route(&logits[bi * ne..(bi + 1) * ne], m, allowed);
4755            for &e in &idx {
4756                st[e] += 1;
4757                assign[e].push((bi, p[e] / wsum));
4758            }
4759        }
4760    }
4761
4762    let mut out = vec![0.0f32; b * hidden];
4763    let cols = m.experts[0].gate_proj.cols();
4764    let mut run_expert = |d: &DenseFfn, list: &[(usize, f32)]| {
4765        let sb = list.len();
4766        let mut sub = vec![0.0f32; sb * cols];
4767        for (k, &(bi, _)) in list.iter().enumerate() {
4768            sub[k * cols..(k + 1) * cols].copy_from_slice(&xs[bi * cols..(bi + 1) * cols]);
4769        }
4770        let eo = dense_ffn_batch(d, &sub, sb, pool);
4771        for (k, &(bi, w)) in list.iter().enumerate() {
4772            for i in 0..hidden {
4773                out[bi * hidden + i] += w * eo[k * hidden + i];
4774            }
4775        }
4776    };
4777    for (e, a) in assign.iter().enumerate().take(ne) {
4778        if !a.is_empty() {
4779            run_expert(&m.experts[e], a);
4780        }
4781    }
4782    if let Some((se, gate)) = &m.shared {
4783        let all: Vec<(usize, f32)> = if let Some(gate) = gate {
4784            let mut gl = vec![0.0f32; b];
4785            gate.matmat(xs, b, &mut gl, pool);
4786            (0..b)
4787                .map(|bi| (bi, 1.0 / (1.0 + (-gl[bi]).exp())))
4788                .collect()
4789        } else {
4790            (0..b).map(|bi| (bi, 1.0)).collect()
4791        };
4792        run_expert(se, &all);
4793    }
4794    out
4795}
4796
4797thread_local! {
4798    /// gate/up activation scratch for the dense FFN paths (single uses
4799    /// two slots, the fused pair all four) — these were fresh
4800    /// intermediate-size Vecs on every layer of every token.
4801    static FFN_SCRATCH: std::cell::RefCell<[Vec<f32>; 4]> =
4802        const { std::cell::RefCell::new([Vec::new(), Vec::new(), Vec::new(), Vec::new()]) };
4803}
4804
4805/// Dense SwiGLU FFN through QTensor matvecs (any storage).
4806fn dense_ffn(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
4807    // Whole-FFN GPU submit (этап 4.2 increment): gate → silu·up → down
4808    // chained in ONE command buffer with the intermediate activations
4809    // resident on the device — 3 per-op polls become 1 per layer. The
4810    // moe_block backend already implements exactly this chain; a dense
4811    // FFN is one expert with weight 1. Runtime probe: the chain still
4812    // pays one submit+poll per layer — alternate it against the pure-CPU
4813    // FFN and keep whichever is faster on this machine.
4814    // q1 FFNs offload at any practical size: the q1 CPU kernel is
4815    // compute-bound, so the UMA threshold logic does not apply — the
4816    // probe measures and decides either way.
4817    if crate::gpu::enabled_here()
4818        && (d.gate_proj.rows() >= crate::gpu::min_rows() || d.gate_proj.is_q1())
4819    {
4820        let arm = if d.gate_proj.is_q1() && crate::gpu::q1_force() {
4821            crate::gpu::ProbeArm::Gpu
4822        } else {
4823            crate::gpu::probe_arm(crate::gpu::OpClass::Ffn)
4824        };
4825        match arm {
4826            crate::gpu::ProbeArm::Gpu => {
4827                let t0 = std::time::Instant::now();
4828                if let Some(out) = dense_ffn_gpu(d, x, pool) {
4829                    crate::gpu::probe_record(crate::gpu::OpClass::Ffn, true, t0.elapsed());
4830                    return out;
4831                }
4832            }
4833            crate::gpu::ProbeArm::CpuTimed => {
4834                let t0 = std::time::Instant::now();
4835                let out = crate::gpu::cpu_scope(|| dense_ffn_cpu(d, x, pool));
4836                crate::gpu::probe_record(crate::gpu::OpClass::Ffn, false, t0.elapsed());
4837                return out;
4838            }
4839            crate::gpu::ProbeArm::Cpu => {
4840                return crate::gpu::cpu_scope(|| dense_ffn_cpu(d, x, pool));
4841            }
4842        }
4843    }
4844    dense_ffn_cpu(d, x, pool)
4845}
4846
4847/// The pure-CPU dense-FFN body (also the fallback of every GPU refusal).
4848fn dense_ffn_cpu(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
4849    let inter = d.gate_proj.rows();
4850    FFN_SCRATCH.with(|s| {
4851        let mut s = s.borrow_mut();
4852        let [g, u, ..] = &mut *s;
4853        g.resize(inter, 0.0);
4854        // Fused gate+up+silu: one dispatch, no separate silu pass.
4855        // Falls back to matvec_many + silu loop for unsupported dtypes.
4856        if d.act == Act::Silu && QTensor::matvec_silu_mul(&d.gate_proj, &d.up_proj, x, g, pool) {
4857            // g now holds silu(gate)·up directly.
4858        } else {
4859            u.resize(inter, 0.0);
4860            // Multi-matrix job: gate+up under one pool dispatch.
4861            QTensor::matvec_many([&d.gate_proj, &d.up_proj], x, [g, u], pool);
4862            for i in 0..inter {
4863                g[i] = d.act.combine(g[i], u[i]);
4864            }
4865        }
4866        // DTG-MA bake probe (Patent 2): accumulate this layer's
4867        // per-neuron activation mass while a probe pass is active.
4868        FFN_PROBE.with(|pr| {
4869            if let Some(acc) = pr.borrow_mut().as_mut() {
4870                let li = crate::gpu::cur_layer();
4871                if li >= 0 {
4872                    if let Some(row) = acc.get_mut(li as usize) {
4873                        for (a, &v) in row.iter_mut().zip(g.iter()) {
4874                            *a += (v as f64).abs();
4875                        }
4876                    }
4877                }
4878            }
4879        });
4880        let mut out = attention::take_buf(d.down_proj.rows());
4881        d.down_proj.matvec(g, &mut out, pool);
4882        out
4883    })
4884}
4885
4886thread_local! {
4887    /// DTG-MA activation probe: per-layer per-neuron Σ|silu(g)·u|
4888    /// accumulator, alive only during `Pipeline::probe_ffn_mass`.
4889    static FFN_PROBE: std::cell::RefCell<Option<Vec<Vec<f64>>>> =
4890        const { std::cell::RefCell::new(None) };
4891}
4892
4893/// Dense FFN as one GPU submission via the MoE block path (single
4894/// expert, weight 1.0): gate → silu·up → down chained in one command
4895/// buffer, intermediate activations device-resident. None → weights
4896/// not q8-mapped in the primary shard / over the VRAM budget / backend
4897/// refusal → honest CPU path.
4898fn dense_ffn_gpu(d: &DenseFfn, x: &[f32], _pool: Option<&Pool>) -> Option<Vec<f32>> {
4899    // The GPU block hardcodes SiLU; GeLU FFNs (Gemma) stay on CPU.
4900    if d.act != Act::Silu {
4901        return None;
4902    }
4903    // Threshold: tiny FFNs are not worth a submission (q1 excepted —
4904    // see the caller's gate).
4905    if d.gate_proj.rows() < crate::gpu::min_rows() && !d.gate_proj.is_q1() {
4906        return None;
4907    }
4908    let mut jobs: Vec<crate::gpu::MoeJob> = Vec::with_capacity(1);
4909    let mut model_ref = None;
4910    moe_push_job(d, x, 1.0, &mut jobs, &mut model_ref)?;
4911    let model = model_ref?;
4912    let hidden = jobs[0].down.1;
4913    let mut out = attention::take_buf(hidden);
4914    if crate::gpu::moe_block(&model, &jobs, &mut out) {
4915        Some(out)
4916    } else {
4917        let mut out = out;
4918        attention::recycle_buf(&mut out);
4919        None
4920    }
4921}
4922
4923/// q8-mapped primary-shard tensor parts for a GPU job: q8_2f carries
4924/// its column field, q8_row runs with empty col slices (the backend
4925/// skips the multiply). Shared by the MoE block and the dense-FFN
4926/// single-job path.
4927#[allow(clippy::type_complexity)]
4928#[allow(clippy::type_complexity)]
4929fn moe_parts(
4930    t: &QTensor,
4931) -> Option<(
4932    &std::sync::Arc<cortiq_core::CmfModel>,
4933    usize,
4934    usize,
4935    usize,
4936    &[f32],
4937    &[f32],
4938    bool,
4939    bool,
4940)> {
4941    match t {
4942        QTensor::Mapped {
4943            model,
4944            idx,
4945            dtype: dt @ (cortiq_core::TensorDtype::Q8_2f | cortiq_core::TensorDtype::Q8Row),
4946            rows,
4947            cols,
4948            row_scale,
4949            col_field,
4950            ..
4951        } if (*dt == cortiq_core::TensorDtype::Q8Row) || !col_field.is_empty() => {
4952            Some((model, *idx, *rows, *cols, row_scale, col_field, false, false))
4953        }
4954        // q1: tile-embedded scales — empty rs/col slices, raw xs.
4955        QTensor::Mapped {
4956            model,
4957            idx,
4958            dtype: cortiq_core::TensorDtype::Q1,
4959            rows,
4960            cols,
4961            ..
4962        } => Some((model, *idx, *rows, *cols, &[][..], &[][..], true, false)),
4963        // q4_tiled: 18-byte tiles with embedded f16 scales — raw xs.
4964        QTensor::Mapped {
4965            model,
4966            idx,
4967            dtype: cortiq_core::TensorDtype::Q4Tiled,
4968            rows,
4969            cols,
4970            ..
4971        } => Some((model, *idx, *rows, *cols, &[][..], &[][..], false, true)),
4972        // q4tp: same raw-xs contract, different stride and scale plane.
4973        QTensor::Mapped {
4974            model,
4975            idx,
4976            dtype: cortiq_core::TensorDtype::Q4TiledP,
4977            rows,
4978            cols,
4979            ..
4980        } => Some((model, *idx, *rows, *cols, &[][..], &[][..], false, true)),
4981        _ => None,
4982    }
4983}
4984
4985/// Build one gate/up/down GPU job (see `moe_parts`).
4986fn moe_push_job<'a>(
4987    d: &'a DenseFfn,
4988    x: &[f32],
4989    w: f32,
4990    jobs: &mut Vec<crate::gpu::MoeJob<'a>>,
4991    model_ref: &mut Option<std::sync::Arc<cortiq_core::CmfModel>>,
4992) -> Option<()> {
4993    use crate::qtensor::prescale;
4994    if d.act != Act::Silu {
4995        return None; // GPU block hardcodes SiLU
4996    }
4997    let (gm, gi, gr, gc, grs, gcf, gq1, gq4) = moe_parts(&d.gate_proj)?;
4998    let (_, ui, ur, uc, urs, ucf, uq1, uq4) = moe_parts(&d.up_proj)?;
4999    let (_, di, dr, dc, drs, dcf, dq1, dq4) = moe_parts(&d.down_proj)?;
5000    if gq1 != uq1 || uq1 != dq1 || gq4 != uq4 || uq4 != dq4 {
5001        return None; // mixed-dtype trio — honest CPU path
5002    }
5003    model_ref.get_or_insert_with(|| gm.clone());
5004    let gdt = if gcf.is_empty() {
5005        cortiq_core::TensorDtype::Q8Row
5006    } else {
5007        cortiq_core::TensorDtype::Q8_2f
5008    };
5009    let udt = if ucf.is_empty() {
5010        cortiq_core::TensorDtype::Q8Row
5011    } else {
5012        cortiq_core::TensorDtype::Q8_2f
5013    };
5014    jobs.push(crate::gpu::MoeJob {
5015        gate: (gi, gr, gc, grs),
5016        up: (ui, ur, uc, urs),
5017        down: (di, dr, dc, drs),
5018        xs_gate: prescale(x, gcf, gdt).into_owned(),
5019        xs_up: prescale(x, ucf, udt).into_owned(),
5020        down_col: dcf,
5021        w,
5022        q1: gq1,
5023        q4t: gq4 && d.gate_proj.mapped_q4tp().is_none(),
5024        q4tp: gq4 && d.gate_proj.mapped_q4tp().is_some(),
5025    });
5026    Some(())
5027}
5028
5029/// Sparse dense-FFN directly on QUANTIZED weights (mask × mmap): reads
5030/// ONLY the active neurons' gate/up rows and down columns from the mmap
5031/// — no full-matrix dequant, no f32 model copy. This is what lets a
5032/// masked big model run at quantized RSS (the historical mask path
5033/// forced the whole model to f32). Semantics identical to the f32
5034/// sparse path within quant tolerance.
5035fn sparse_ffn_quant(
5036    d: &DenseFfn,
5037    x: &[f32],
5038    active: &[u16],
5039    hidden: usize,
5040    pool: Option<&Pool>,
5041) -> Vec<f32> {
5042    let n = active.len();
5043    let inter = d.gate_proj.rows();
5044    let mut act = vec![0.0f32; n];
5045    // Scratch is needed if EITHER projection is group-packed (q4/vbit);
5046    // gate/up normally share a dtype but sizing on both is robust.
5047    let need_scratch = !(d.gate_proj.sparse_col_ok() && d.up_proj.sparse_col_ok());
5048    let compute = |ai: usize| -> f32 {
5049        let idx = active[ai] as usize;
5050        if idx >= inter {
5051            return 0.0; // defensive parity with the f32 sparse path
5052        }
5053        let mut s = if need_scratch {
5054            vec![0.0f32; hidden]
5055        } else {
5056            Vec::new()
5057        };
5058        let gate = d.gate_proj.row_dot(idx, x, &mut s);
5059        let up = d.up_proj.row_dot(idx, x, &mut s);
5060        d.act.combine(gate, up)
5061    };
5062    match pool {
5063        Some(p) if n >= 256 => {
5064            let ptr = SendMut(act.as_mut_ptr());
5065            p.run(&|widx, nw| {
5066                let chunk = n.div_ceil(nw);
5067                let (s, e) = (widx * chunk, ((widx + 1) * chunk).min(n));
5068                for ai in s..e {
5069                    unsafe { *ptr.at(ai) = compute(ai) };
5070                }
5071            });
5072        }
5073        _ => {
5074            for (ai, a) in act.iter_mut().enumerate() {
5075                *a = compute(ai);
5076            }
5077        }
5078    }
5079    // Scatter through active down columns (reads only those columns).
5080    let mut out = vec![0.0f32; hidden];
5081    for (ai, &idx) in active.iter().enumerate() {
5082        let w = act[ai];
5083        if w.abs() >= 1e-12 && (idx as usize) < inter {
5084            d.down_proj.add_col_scaled(idx as usize, w, &mut out);
5085        }
5086    }
5087    out
5088}
5089
5090/// Test-only re-export of the private sparse-quant FFN (mask × mmap gate).
5091#[doc(hidden)]
5092pub fn sparse_ffn_quant_for_test(
5093    d: &DenseFfn,
5094    x: &[f32],
5095    active: &[u16],
5096    hidden: usize,
5097) -> Vec<f32> {
5098    sparse_ffn_quant(d, x, active, hidden, None)
5099}
5100
5101/// Dequantize a DenseFfn's three matrices to f32 (transient; only the
5102/// q4/vbit-masked fallback uses it — the memory-lean path is
5103/// sparse_ffn_quant). Reuses row_f32 row-by-row.
5104fn dequant_dense_f32(d: &DenseFfn) -> (Vec<f32>, Vec<f32>, Vec<f32>) {
5105    let deq = |t: &QTensor| -> Vec<f32> {
5106        let (rows, cols) = (t.rows(), t.cols());
5107        let mut out = vec![0.0f32; rows * cols];
5108        for r in 0..rows {
5109            t.row_f32(r, &mut out[r * cols..(r + 1) * cols]);
5110        }
5111        out
5112    };
5113    (deq(&d.gate_proj), deq(&d.up_proj), deq(&d.down_proj))
5114}
5115
5116/// Pointer wrapper for the worker-pool scatter (same pattern as qtensor).
5117struct SendMut(*mut f32);
5118unsafe impl Send for SendMut {}
5119unsafe impl Sync for SendMut {}
5120impl SendMut {
5121    #[inline]
5122    // Deliberate unsynchronized scatter: pool workers write disjoint indices
5123    // in parallel, so returning `&mut` from `&self` is intentional here.
5124    #[allow(clippy::mut_from_ref)]
5125    unsafe fn at(&self, i: usize) -> &mut f32 {
5126        unsafe { &mut *self.0.add(i) }
5127    }
5128}
5129
5130/// Router → (selected experts in torch.topk order, per-expert score
5131/// vector, normalizer). The final weight of expert `e` is `p[e] / wsum`.
5132///
5133/// Two regimes share this. Qwen: softmax over ALL experts, top-k of the
5134/// probabilities, optional renorm — `router_sigmoid=false`, no bias,
5135/// scale 1 → bit-identical to the historical path. LFM2-MoE /
5136/// DeepSeek-V3 `noaux_tc`: per-expert sigmoid scores, an optional
5137/// selection bias (top-k CHOICE only; weights stay unbiased), a 1e-6 renorm
5138/// floor and a routed scale.
5139fn moe_route(
5140    logits: &[f32],
5141    m: &MoeFfn,
5142    allowed: Option<&[bool]>,
5143) -> (Vec<usize>, Vec<f32>, f32) {
5144    let ne = logits.len();
5145    let p: Vec<f32> = if m.router_sigmoid {
5146        logits.iter().map(|&l| 1.0 / (1.0 + (-l).exp())).collect()
5147    } else {
5148        let mx = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
5149        let mut e: Vec<f32> = logits.iter().map(|&l| (l - mx).exp()).collect();
5150        let s: f32 = e.iter().sum();
5151        for v in &mut e {
5152            *v /= s;
5153        }
5154        e
5155    };
5156    // Expert restriction: the static env mask (CMF_MOE_MASK) AND the
5157    // active task mask's expert fields (spec §5) both narrow the
5158    // candidate set; selection happens over the admitted experts only.
5159    // With norm_topk the kept weights renormalize below; without it
5160    // the excluded mass is honestly dropped.
5161    let admit = |e: usize| {
5162        m.mask.as_ref().is_none_or(|mk| mk[e]) && allowed.is_none_or(|a| a.get(e).copied().unwrap_or(false))
5163    };
5164    let mut idx: Vec<usize> = (0..ne).filter(|&e| admit(e)).collect();
5165    // Descending by selection score, lower index wins ties (torch.topk).
5166    match &m.expert_bias {
5167        Some(b) => idx.sort_unstable_by(|&x, &y| {
5168            (p[y] + b[y])
5169                .partial_cmp(&(p[x] + b[x]))
5170                .unwrap()
5171                .then(x.cmp(&y))
5172        }),
5173        None => idx.sort_unstable_by(|&x, &y| p[y].partial_cmp(&p[x]).unwrap().then(x.cmp(&y))),
5174    }
5175    idx.truncate(m.top_k);
5176    // Adaptive τ-routing: trim the tail experts once the kept mass is
5177    // enough. wsum below renormalizes over the KEPT set, so the output
5178    // stays a proper weighted average.
5179    if let Some(tau) = m.route_tau {
5180        let total: f32 = idx.iter().map(|&e| p[e]).sum();
5181        if total > 0.0 {
5182            let mut acc = 0.0f32;
5183            let mut keep = idx.len();
5184            for (i, &e) in idx.iter().enumerate() {
5185                acc += p[e];
5186                if acc >= tau * total {
5187                    keep = i + 1;
5188                    break;
5189                }
5190            }
5191            idx.truncate(keep);
5192        }
5193    }
5194    let wsum: f32 = if m.norm_topk_prob {
5195        let s: f32 = idx.iter().map(|&e| p[e]).sum();
5196        // LFM2 floors the denom (matches HF `+ 1e-6`); the softmax path's
5197        // probs already sum near 1, so it stays exactly as before.
5198        (if m.router_sigmoid { s + 1e-6 } else { s }) / m.routed_scaling
5199    } else {
5200        1.0 / m.routed_scaling
5201    };
5202    (idx, p, wsum)
5203}
5204
5205/// MoE FFN: router → top-k experts (see `moe_route`). Only selected
5206/// experts' pages are touched in mmap.
5207fn moe_ffn(m: &MoeFfn, x: &[f32], pool: Option<&Pool>, allowed: Option<&[bool]>) -> Vec<f32> {
5208    accumulate_act(m, x, 1);
5209    let ne = m.experts.len();
5210    let mut logits = vec![0.0f32; ne];
5211    m.router.matvec(x, &mut logits, pool);
5212    let (idx, p, wsum) = moe_route(&logits, m, allowed);
5213    {
5214        let mut st = m.stats.borrow_mut();
5215        if st.len() < ne {
5216            st.resize(ne, 0);
5217        }
5218        for &e in &idx {
5219            st[e] += 1;
5220        }
5221    }
5222    // D5: the whole layer MoE block in one GPU command buffer (experts — the
5223    // same mmap via a no-copy buffer; intermediate activations on the GPU).
5224    // Same Ffn probe class as the dense chain: one submit per layer
5225    // either wins on this driver stack or it doesn't.
5226    if crate::gpu::enabled_here() {
5227        match crate::gpu::probe_arm(crate::gpu::OpClass::Ffn) {
5228            crate::gpu::ProbeArm::Gpu => {
5229                let t0 = std::time::Instant::now();
5230                if let Some(out) = moe_ffn_gpu(m, x, &idx, &p, wsum, pool) {
5231                    crate::gpu::probe_record(crate::gpu::OpClass::Ffn, true, t0.elapsed());
5232                    return out;
5233                }
5234            }
5235            crate::gpu::ProbeArm::CpuTimed => {
5236                let t0 = std::time::Instant::now();
5237                let out = crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool));
5238                crate::gpu::probe_record(crate::gpu::OpClass::Ffn, false, t0.elapsed());
5239                return out;
5240            }
5241            crate::gpu::ProbeArm::Cpu => {
5242                return crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool));
5243            }
5244        }
5245    }
5246    moe_ffn_cpu(m, x, &idx, &p, wsum, pool)
5247}
5248
5249/// One-shot report of whether the whole-token wgpu graph actually formed.
5250/// A refusal silently reverts to the per-op path, which is how a model can
5251/// look "GPU-accelerated" while every layer walks the host.
5252fn graph_note(built: bool) {
5253    use std::sync::atomic::{AtomicBool, Ordering};
5254    static SAID: AtomicBool = AtomicBool::new(false);
5255    if !SAID.swap(true, Ordering::Relaxed) {
5256        if built {
5257            tracing::info!("wgpu whole-token graph: ACTIVE");
5258        } else {
5259            tracing::warn!("wgpu whole-token graph refused — per-op path");
5260        }
5261    }
5262}
5263
5264/// `CMF_MOE_BATCH=0` restores the per-expert serial loop — the A/B lever
5265/// for the batched kernel, and how its bit-identity is checked.
5266fn moe_batch_enabled() -> bool {
5267    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5268    *ON.get_or_init(|| std::env::var("CMF_MOE_BATCH").as_deref() != Ok("0"))
5269}
5270
5271/// Two-dispatch CPU MoE: every routed expert (and the shared one) fused
5272/// into one gate/up/SiLU dispatch and one down dispatch, instead of two
5273/// pool barriers per expert. Bit-identical to the serial loop below —
5274/// see `moe_gate_up_many` / `moe_down_many`. `None` = the batched kernel
5275/// does not cover this layer, walk the serial path.
5276fn moe_ffn_cpu_batched(
5277    m: &MoeFfn,
5278    x: &[f32],
5279    idx: &[usize],
5280    p: &[f32],
5281    wsum: f32,
5282    pool: Option<&Pool>,
5283) -> Option<Vec<f32>> {
5284    if idx.is_empty() || !moe_batch_enabled() {
5285        return None;
5286    }
5287    // The bake probe reads per-neuron activation mass out of the
5288    // single-expert path; batching would skip it. Rare and offline —
5289    // hand those runs to the serial loop.
5290    if FFN_PROBE.with(|pr| pr.borrow().is_some()) {
5291        return None;
5292    }
5293    let n = idx.len() + usize::from(m.shared.is_some());
5294    let mut pairs = Vec::with_capacity(n);
5295    let mut downs = Vec::with_capacity(n);
5296    let mut ws = Vec::with_capacity(n);
5297    for &e in idx {
5298        let d = &m.experts[e];
5299        if d.act != Act::Silu {
5300            return None;
5301        }
5302        pairs.push((&d.gate_proj, &d.up_proj));
5303        downs.push(&d.down_proj);
5304        ws.push(p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]));
5305    }
5306    // The shared expert goes last, matching the serial loop's order —
5307    // the f32 accumulation order is part of the bit-identity claim.
5308    if let Some((se, gate)) = &m.shared {
5309        if se.act != Act::Silu {
5310            return None;
5311        }
5312        let g = gate.as_ref().map_or(1.0, |gate| {
5313            let mut gl = [0.0f32; 1];
5314            gate.matvec(x, &mut gl, pool);
5315            1.0 / (1.0 + (-gl[0]).exp())
5316        });
5317        pairs.push((&se.gate_proj, &se.up_proj));
5318        downs.push(&se.down_proj);
5319        ws.push(g);
5320    }
5321    let inter = pairs[0].0.rows();
5322    let mut gs: Vec<Vec<f32>> = (0..pairs.len()).map(|_| vec![0f32; inter]).collect();
5323    if !QTensor::moe_gate_up_many(&pairs, x, &mut gs, pool) {
5324        return None;
5325    }
5326    let mut out = attention::take_buf(x.len());
5327    if !QTensor::moe_down_many(&downs, &gs, &ws, &mut out, pool) {
5328        attention::recycle_buf(&mut out);
5329        return None;
5330    }
5331    Some(out)
5332}
5333
5334/// The pure-CPU MoE expert loop (also the fallback of every GPU refusal).
5335fn moe_ffn_cpu(
5336    m: &MoeFfn,
5337    x: &[f32],
5338    idx: &[usize],
5339    p: &[f32],
5340    wsum: f32,
5341    pool: Option<&Pool>,
5342) -> Vec<f32> {
5343    if let Some(out) = moe_ffn_cpu_batched(m, x, idx, p, wsum, pool) {
5344        return out;
5345    }
5346    let mut out = attention::take_buf(x.len());
5347    for &e in idx {
5348        let mut eo = dense_ffn(&m.experts[e], x, pool);
5349        let w = p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]);
5350        for i in 0..out.len() {
5351            out[i] += w * eo[i];
5352        }
5353        attention::recycle_buf(&mut eo);
5354    }
5355    if let Some((se, gate)) = &m.shared {
5356        let mut so = dense_ffn(se, x, pool);
5357        let g = gate.as_ref().map_or(1.0, |gate| {
5358            let mut gl = [0.0f32; 1];
5359            gate.matvec(x, &mut gl, pool);
5360            1.0 / (1.0 + (-gl[0]).exp())
5361        });
5362        for i in 0..out.len() {
5363            out[i] += g * so[i];
5364        }
5365        attention::recycle_buf(&mut so);
5366    }
5367    out
5368}
5369
5370/// DeepSeek-V2 MLA forward, expand-to-MHA form (see `AttnKind::Mla`):
5371/// per token the latent expands to every head's K/V and the ordinary
5372/// cache + grouped attend do the rest. K head layout is [rope | nope]
5373/// (rotary_dim = qk_rope rotates the shared rope key and each q head's
5374/// prefix); V rows are zero-padded to the K head_dim inside the cache
5375/// and the pad is sliced off before O. Born importance is not
5376/// accumulated for MLA yet (no eviction interplay).
5377#[allow(clippy::too_many_arguments)]
5378fn mla_attention(
5379    w: &MlaWeights,
5380    normed: &[f32],
5381    cache: &mut crate::kv_cache::LayerKvCache,
5382    position: usize,
5383    inv_freq: &[f32],
5384    rope_scale: f32,
5385    eps: f64,
5386    pool: Option<&Pool>,
5387) -> Vec<f32> {
5388    let (nh, dr, dn, dv, lora) = (w.nh, w.qk_rope, w.qk_nope, w.v_dim, w.lora);
5389    let hd = dr + dn;
5390    let mut q = vec![0.0f32; nh * hd];
5391    match (&w.q_a, &w.q_a_norm) {
5392        (Some(qa), Some(qn)) => {
5393            let mut t = vec![0.0f32; qa.rows()];
5394            qa.matvec(normed, &mut t, pool);
5395            let tn = inference::rms_norm(&t, qn, eps, NormStyle::Qwen);
5396            w.q_proj.matvec(&tn, &mut q, pool);
5397        }
5398        _ => w.q_proj.matvec(normed, &mut q, pool),
5399    }
5400    let mut ca = vec![0.0f32; lora + dr];
5401    w.kv_a.matvec(normed, &mut ca, pool);
5402    let (c_lat, k_rope) = ca.split_at_mut(lora);
5403    let latn = inference::rms_norm(c_lat, &w.kv_a_norm, eps, NormStyle::Qwen);
5404    let mut kvb = vec![0.0f32; nh * (dn + dv)];
5405    w.kv_b.matvec(&latn, &mut kvb, pool);
5406    if !w.nope {
5407        attention::rope_rotate_scaled(k_rope, position, inv_freq, rope_scale);
5408    }
5409    for h in 0..nh {
5410        if !w.nope {
5411            attention::rope_rotate_scaled(
5412                &mut q[h * hd..h * hd + dr],
5413                position,
5414                inv_freq,
5415                rope_scale,
5416            );
5417        }
5418    }
5419    let mut k = vec![0.0f32; nh * hd];
5420    let mut v = vec![0.0f32; nh * hd];
5421    for h in 0..nh {
5422        k[h * hd..h * hd + dr].copy_from_slice(k_rope);
5423        k[h * hd + dr..(h + 1) * hd].copy_from_slice(&kvb[h * (dn + dv)..h * (dn + dv) + dn]);
5424        v[h * hd..h * hd + dv].copy_from_slice(&kvb[h * (dn + dv) + dn..(h + 1) * (dn + dv)]);
5425    }
5426    cache.append(&k, &v, &vec![true; nh]);
5427    let (ao, mut imp) = attention::attend_all_heads(&q, cache, nh, 1, hd, w.scale, None, 0.0);
5428    attention::recycle_buf(&mut imp);
5429    let mut ov = vec![0.0f32; nh * dv];
5430    for h in 0..nh {
5431        ov[h * dv..(h + 1) * dv].copy_from_slice(&ao[h * hd..h * hd + dv]);
5432    }
5433    let mut out = vec![0.0f32; w.o_proj.rows()];
5434    w.o_proj.matvec(&ov, &mut out, pool);
5435    out
5436}
5437
5438/// Gemma-4 dual-branch FFN (spec: see `FfnKind::DenseMoe`). The dense
5439/// branch reads the pre-FFN-normed activation; the router and the
5440/// expert branch read the RAW residual — the router through a
5441/// scale-less rms norm (its constant gain is folded into the weights),
5442/// the experts through `pre_norm_2`. CPU path; GPU graphs refuse the
5443/// layer kind honestly.
5444fn dense_moe_ffn(
5445    dm: &DenseMoeFfn,
5446    x_normed: &[f32],
5447    h_raw: &[f32],
5448    eps: f64,
5449    norm_style: NormStyle,
5450    pool: Option<&Pool>,
5451) -> Vec<f32> {
5452    let mut d = dense_ffn(&dm.dense, x_normed, pool);
5453    d = inference::rms_norm(&d, &dm.post_norm_1, eps, norm_style);
5454    let m = &dm.moe;
5455    let ne = m.experts.len();
5456    let mut logits = vec![0.0f32; ne];
5457    if m.router_input_norm {
5458        let ss: f32 = h_raw.iter().map(|v| v * v).sum::<f32>() / h_raw.len() as f32;
5459        let inv = 1.0 / (ss + eps as f32).sqrt();
5460        let xr: Vec<f32> = h_raw.iter().map(|v| v * inv).collect();
5461        m.router.matvec(&xr, &mut logits, pool);
5462    } else {
5463        m.router.matvec(h_raw, &mut logits, pool);
5464    }
5465    let (idx, p, wsum) = moe_route(&logits, m, None);
5466    {
5467        let mut st = m.stats.borrow_mut();
5468        if st.len() < ne {
5469            st.resize(ne, 0);
5470        }
5471        for &e in &idx {
5472            st[e] += 1;
5473        }
5474    }
5475    let x2 = inference::rms_norm(h_raw, &dm.pre_norm_2, eps, norm_style);
5476    let mo = moe_ffn_cpu(m, &x2, &idx, &p, wsum, pool);
5477    let mo = inference::rms_norm(&mo, &dm.post_norm_2, eps, norm_style);
5478    for (di, mi) in d.iter_mut().zip(&mo) {
5479        *di += mi;
5480    }
5481    d
5482}
5483
5484/// Building the MoE-layer GPU jobs: all selected experts (+shared) must
5485/// be q8_2f-Mapped from the primary mapping; otherwise None → CPU path.
5486/// One-shot report of why the MoE GPU block refused. A silent `?` here
5487/// sends every expert to the CPU with nothing in the logs to say so —
5488/// which is exactly how a q4tp MoE model looked "GPU-accelerated" while
5489/// running entirely on the host.
5490fn moe_gpu_refused(why: &'static str) {
5491    use std::sync::atomic::{AtomicBool, Ordering};
5492    static SAID: AtomicBool = AtomicBool::new(false);
5493    if !SAID.swap(true, Ordering::Relaxed) {
5494        tracing::warn!("MoE GPU block refused ({why}) — experts run on the CPU");
5495    }
5496}
5497
5498fn moe_ffn_gpu(
5499    m: &MoeFfn,
5500    x: &[f32],
5501    idx: &[usize],
5502    p: &[f32],
5503    wsum: f32,
5504    pool: Option<&Pool>,
5505) -> Option<Vec<f32>> {
5506    use crate::gpu::MoeJob;
5507
5508    let mut jobs: Vec<MoeJob> = Vec::with_capacity(idx.len() + 1);
5509    let mut model_ref = None;
5510    for &e in idx {
5511        if moe_push_job(&m.experts[e], x, p[e] / wsum, &mut jobs, &mut model_ref).is_none() {
5512            moe_gpu_refused("push_job(expert)");
5513            return None;
5514        }
5515    }
5516    if let Some((se, gate)) = &m.shared {
5517        let g = gate.as_ref().map_or(1.0, |gate| {
5518            let mut gl = [0.0f32; 1];
5519            gate.matvec(x, &mut gl, pool);
5520            1.0 / (1.0 + (-gl[0]).exp())
5521        });
5522        if moe_push_job(se, x, g, &mut jobs, &mut model_ref).is_none() {
5523            moe_gpu_refused("push_job(shared)");
5524            return None;
5525        }
5526    }
5527    let Some(model) = model_ref else {
5528        moe_gpu_refused("no model_ref");
5529        return None;
5530    };
5531    let hidden = jobs[0].down.1;
5532    let mut out = vec![0.0f32; hidden];
5533    if crate::gpu::moe_block(&model, &jobs, &mut out) {
5534        Some(out)
5535    } else {
5536        moe_gpu_refused("gpu::moe_block");
5537        None
5538    }
5539}
5540
5541/// Single-position FFN dispatch.
5542fn ffn_forward(
5543    ffn: &FfnKind,
5544    x: &[f32],
5545    pool: Option<&Pool>,
5546    experts_allowed: Option<&[bool]>,
5547) -> Vec<f32> {
5548    match ffn {
5549        FfnKind::Dense(d) => dense_ffn(d, x, pool),
5550        FfnKind::Moe(m) => moe_ffn(m, x, pool, experts_allowed),
5551        // Dual-branch layers need the raw residual — their callers
5552        // dispatch dense_moe_ffn directly; the auxiliary paths that land
5553        // here (MTP draft, o1 replay) do not co-occur with gemma-4 MoE.
5554        FfnKind::DenseMoe(_) => unreachable!("DenseMoe dispatches via dense_moe_ffn"),
5555    }
5556}
5557
5558/// Fused two-position FFN: gate/up/down streamed once (dense). MoE
5559/// falls back to two singles — expert sets differ per position, there
5560/// is nothing to fuse.
5561fn ffn_forward_pair(
5562    ffn: &FfnKind,
5563    x1: &[f32],
5564    x2: &[f32],
5565    pool: Option<&Pool>,
5566    experts_allowed: Option<&[bool]>,
5567) -> (Vec<f32>, Vec<f32>) {
5568    let d = match ffn {
5569        FfnKind::Dense(d) => d,
5570        FfnKind::Moe(m) => {
5571            return (
5572                moe_ffn(m, x1, pool, experts_allowed),
5573                moe_ffn(m, x2, pool, experts_allowed),
5574            );
5575        }
5576        FfnKind::DenseMoe(_) => unreachable!("DenseMoe dispatches via dense_moe_ffn"),
5577    };
5578    let inter = d.gate_proj.rows();
5579    FFN_SCRATCH.with(|s| {
5580        let mut s = s.borrow_mut();
5581        let [g1, g2, u1, u2] = &mut *s;
5582        g1.resize(inter, 0.0);
5583        g2.resize(inter, 0.0);
5584        u1.resize(inter, 0.0);
5585        u2.resize(inter, 0.0);
5586        // Multi-matrix pair job: gate+up under one pool dispatch
5587        // (o1s = lane-1 outputs across tensors, o2s = lane-2).
5588        QTensor::matvec2_many(
5589            [&d.gate_proj, &d.up_proj],
5590            x1,
5591            x2,
5592            [g1.as_mut_slice(), u1.as_mut_slice()],
5593            [g2.as_mut_slice(), u2.as_mut_slice()],
5594            pool,
5595        );
5596        for i in 0..inter {
5597            g1[i] = d.act.combine(g1[i], u1[i]);
5598            g2[i] = d.act.combine(g2[i], u2[i]);
5599        }
5600        let mut o1 = attention::take_buf(d.down_proj.rows());
5601        let mut o2 = attention::take_buf(d.down_proj.rows());
5602        d.down_proj.matvec2(g1, g2, &mut o1, &mut o2, pool);
5603        (o1, o2)
5604    })
5605}
5606
5607#[cfg(test)]
5608mod tests {
5609
5610    #[test]
5611    fn cancel_flag_stops_generation() {
5612        let mut p = create_test_pipeline(16, 32, 2, 2, 8, 2, 32);
5613        // Set before the call: the prefill loops honour it, the run
5614        // returns immediately with the cancelled reason and no tokens.
5615        p.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
5616        let r = p.generate_from_ids(&[1, 2, 3], 8, None, None).unwrap();
5617        assert_eq!(r.finish_reason, "cancelled");
5618        assert!(r.token_ids.is_empty(), "no tokens after cancel: {:?}", r.token_ids);
5619        // Flag auto-cleared: the next call generates normally.
5620        let r2 = p.generate_from_ids(&[1, 2, 3], 4, None, None).unwrap();
5621        assert_ne!(r2.finish_reason, "cancelled");
5622    }
5623    use super::*;
5624
5625    /// sparse_ffn_quant must equal a dense FFN where inactive neurons are
5626    /// zeroed (mask × mmap correctness). On F32 tensors this is EXACT —
5627    /// it validates the row_dot / add_col_scaled / scatter indexing, the
5628    /// bug-prone part. The q8 branches reuse the golden-tested linear
5629    /// scale, structurally identical to the matvec kernels.
5630    #[test]
5631    fn sparse_ffn_quant_equals_dense_with_inactive_zeroed() {
5632        let (hidden, inter) = (16usize, 40usize);
5633        let synth = |n: usize, salt: usize| -> Vec<f32> {
5634            (0..n)
5635                .map(|i| (((i * 37 + salt * 11 + 3) % 101) as f32 / 101.0 - 0.5) * 0.4)
5636                .collect()
5637        };
5638        let d = DenseFfn {
5639            gate_proj: QTensor::from_f32(synth(inter * hidden, 1), inter, hidden),
5640            up_proj: QTensor::from_f32(synth(inter * hidden, 2), inter, hidden),
5641            down_proj: QTensor::from_f32(synth(hidden * inter, 3), hidden, inter),
5642            act: Act::Silu,
5643        };
5644        let x = synth(hidden, 9);
5645        // Active = every 3rd neuron.
5646        let active: Vec<u16> = (0..inter as u16).filter(|i| i % 3 == 0).collect();
5647
5648        let sparse = sparse_ffn_quant(&d, &x, &active, hidden, None);
5649
5650        // Reference: full dense FFN but g[i]=0 for inactive neurons.
5651        let mut g = vec![0.0f32; inter];
5652        d.gate_proj.matvec(&x, &mut g, None);
5653        let mut u = vec![0.0f32; inter];
5654        d.up_proj.matvec(&x, &mut u, None);
5655        let act_set: std::collections::HashSet<u16> = active.iter().copied().collect();
5656        for i in 0..inter {
5657            g[i] = if act_set.contains(&(i as u16)) {
5658                inference::silu(g[i]) * u[i]
5659            } else {
5660                0.0
5661            };
5662        }
5663        let mut reference = vec![0.0f32; hidden];
5664        d.down_proj.matvec(&g, &mut reference, None);
5665
5666        let max_d = sparse
5667            .iter()
5668            .zip(&reference)
5669            .map(|(a, b)| (a - b).abs())
5670            .fold(0.0f32, f32::max);
5671        assert!(max_d < 1e-5, "sparse != dense-zeroed: max|Δ| = {max_d}");
5672    }
5673
5674    /// Attach a synthetic MTP head (same structure as a main layer).
5675    fn attach_test_mtp(p: &mut Pipeline) {
5676        let (h, inter, heads, kv, hd) = (
5677            p.hidden_size,
5678            p.intermediate_size,
5679            p.num_heads,
5680            p.num_kv_heads,
5681            p.head_dim,
5682        );
5683        let synth = |n: usize, salt: usize| -> Vec<f32> {
5684            (0..n)
5685                .map(|i| (((i * 29 + salt * 23 + 5) % 101) as f32 / 101.0 - 0.5) * 0.2)
5686                .collect()
5687        };
5688        let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
5689            QTensor::from_f32(synth(rows * cols, salt), rows, cols)
5690        };
5691        p.mtp = Some(MtpModule {
5692            enorm: vec![1.0; h],
5693            hnorm: vec![1.0; h],
5694            eh_proj: qt(h, 2 * h, 301),
5695            layer: LayerWeights {
5696                input_norm: vec![1.0; h],
5697                post_norm: vec![1.0; h],
5698                attn_out_norm: None,
5699                ffn_out_norm: None,
5700                layer_scale: None,
5701                ffn: FfnKind::Dense(DenseFfn {
5702                    gate_proj: qt(inter, h, 315),
5703                    up_proj: qt(inter, h, 316),
5704                    down_proj: qt(h, inter, 317),
5705                    act: Act::Silu,
5706                }),
5707                attn: AttnKind::Full {
5708                    bias: None,
5709                    wq: qt(heads * hd, h, 311),
5710                    wk: qt(kv * hd, h, 312),
5711                    wv: qt(kv * hd, h, 313),
5712                    wo: qt(h, heads * hd, 314),
5713                    q_norm: None,
5714                    k_norm: None,
5715                    output_gate: false,
5716                    softplus_gate: None,
5717                },
5718            },
5719            final_norm: vec![1.0; h],
5720            kv: crate::kv_cache::LayerKvCache::new(kv, hd),
5721        });
5722    }
5723
5724    #[test]
5725    fn speculative_equals_vanilla_greedy() {
5726        // Speculative decode and the wgpu token graph are mutually
5727        // exclusive; a leaked CMF_GPU=wgpu from a parallel gpu test
5728        // would silently disable drafting. Pin the graph off.
5729        unsafe { std::env::set_var("CMF_GPU_WGPU_GRAPH", "0") };
5730        let run = |spec: bool| {
5731            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
5732            p.sampler_config.temperature = 0.0;
5733            attach_test_mtp(&mut p);
5734            p.speculative = spec;
5735            let r = p.generate("abcdef", 12, None, None).unwrap();
5736            (r.token_ids, r.mtp_drafted, r.mtp_accepted)
5737        };
5738        let (vanilla, d0, _) = run(false);
5739        let (spec, d1, a1) = run(true);
5740        assert_eq!(d0, 0, "vanilla path must not draft");
5741        assert!(d1 > 0, "speculative path must draft");
5742        assert_eq!(
5743            vanilla, spec,
5744            "speculative must reproduce the exact greedy sequence (accepted {a1}/{d1})"
5745        );
5746    }
5747
5748    #[test]
5749    fn speculative_accepts_constant_oracle() {
5750        // See speculative_equals_vanilla_greedy: pin the wgpu graph off.
5751        unsafe { std::env::set_var("CMF_GPU_WGPU_GRAPH", "0") };
5752        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
5753        p.sampler_config.temperature = 0.0;
5754        p.sampler_config.repetition_penalty = 1.0;
5755        // Constant lm_head → every logit equal → both the main model and
5756        // the draft head argmax to token 0: acceptance must be 100%.
5757        p.weights.lm_head = QTensor::from_f32(vec![0.01; 64 * 8], 64, 8);
5758        attach_test_mtp(&mut p);
5759        p.speculative = true;
5760        let r = p.generate("abcd", 10, None, None).unwrap();
5761        assert!(r.mtp_drafted > 0);
5762        assert_eq!(
5763            r.mtp_accepted, r.mtp_drafted,
5764            "constant logits → every draft accepted"
5765        );
5766        // Ties resolve to the same token in both the main and draft
5767        // heads — the sequence is one repeated token.
5768        assert!(r.token_ids.windows(2).all(|w| w[0] == w[1]));
5769    }
5770
5771    #[test]
5772    fn empty_prompt_is_an_error_not_a_panic() {
5773        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
5774        let r = p.generate("", 4, None, None);
5775        assert!(r.is_err(), "empty prompt must be a clean error");
5776    }
5777
5778    #[test]
5779    fn every_token_enters_kv_exactly_once() {
5780        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
5781        // Greedy so no RNG variance; byte tokenizer → 3 prompt tokens.
5782        p.sampler_config.temperature = 0.0;
5783        let r = p.generate("abc", 2, None, None).unwrap();
5784        assert_eq!(r.prompt_tokens, 3);
5785        // prompt(3) + first sampled token forwarded before second logits:
5786        // step0 samples from prefill hidden (no extra forward), then
5787        // forwards t1 → cache 4; step1 samples, loop ends (max_tokens).
5788        assert_eq!(
5789            p.kv_cache.seq_len(),
5790            3 + r.tokens_generated - 1,
5791            "each token must be cached exactly once (v1 cached the last prompt token twice)"
5792        );
5793    }
5794
5795    #[test]
5796    fn generation_is_reproducible_with_seed() {
5797        let run = || {
5798            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
5799            p.generate("hello", 8, None, None).unwrap().token_ids
5800        };
5801        assert_eq!(run(), run());
5802    }
5803
5804    #[test]
5805    fn resetting_sampler_restarts_the_seeded_stream() {
5806        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
5807        let config = SamplerConfig {
5808            seed: Some(1234),
5809            ..SamplerConfig::default()
5810        };
5811        p.set_sampler_config(config.clone());
5812        let first = p.generate("hello", 8, None, None).unwrap().token_ids;
5813        p.set_sampler_config(config);
5814        let second = p.generate("hello", 8, None, None).unwrap().token_ids;
5815        assert_eq!(first, second);
5816    }
5817
5818    #[test]
5819    fn eviction_bounds_the_cache() {
5820        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
5821        p.kv_cache.max_seq_len = 6;
5822        p.sampler_config.temperature = 0.0;
5823        let _ = p.generate("abcd", 12, None, None).unwrap();
5824        assert!(
5825            p.kv_cache.seq_len() <= 6 + 1,
5826            "cache must stay bounded by max_seq_len (got {})",
5827            p.kv_cache.seq_len()
5828        );
5829    }
5830
5831    #[test]
5832    fn confidence_matches_tokens_and_is_a_probability() {
5833        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
5834        p.sampler_config.temperature = 0.0;
5835        p.sampler_config.repetition_penalty = 1.0;
5836        let r = p.generate("abcd", 10, None, None).unwrap();
5837        assert_eq!(
5838            r.token_confidence.len(),
5839            r.token_ids.len(),
5840            "one confidence per emitted token"
5841        );
5842        for &c in &r.token_confidence {
5843            assert!((0.0..=1.0).contains(&c), "confidence out of [0,1]: {c}");
5844        }
5845        // top1_prob is a valid softmax probability.
5846        let logits = [1.0f32, 3.0, 0.5, 3.0];
5847        let p0 = top1_prob_t(&logits, 1, 1.0);
5848        let p1 = top1_prob_t(&logits, 3, 1.0);
5849        assert!((p0 - p1).abs() < 1e-6, "equal logits → equal prob");
5850        assert!(p0 > 0.0 && p0 < 1.0);
5851        // Calibration temperature > 1 softens an over-confident peak.
5852        let sharp = top1_prob_t(&logits, 1, 1.0);
5853        let soft = top1_prob_t(&logits, 1, 2.0);
5854        assert!(soft < sharp, "higher temperature lowers peak confidence");
5855    }
5856
5857    #[test]
5858    fn trace_is_opt_in_and_parallels_the_output() {
5859        // Off by default: the runtime is silent unless observation asked.
5860        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
5861        p.sampler_config.temperature = 0.0;
5862        p.sampler_config.repetition_penalty = 1.0;
5863        let r = p.generate("abcd", 10, None, None).unwrap();
5864        assert!(r.traces.is_empty(), "trace must be empty unless enabled");
5865
5866        // On: exactly one row per emitted token, aligned with the output.
5867        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
5868        p.sampler_config.temperature = 0.0;
5869        p.sampler_config.repetition_penalty = 1.0;
5870        p.set_trace(true);
5871        let r = p.generate("abcd", 10, None, None).unwrap();
5872        assert_eq!(r.traces.len(), r.token_ids.len(), "one trace row per token");
5873        for (i, tr) in r.traces.iter().enumerate() {
5874            assert_eq!(tr.t, i, "trace index is sequential");
5875            assert_eq!(tr.token_id, r.token_ids[i], "trace token_id matches output");
5876            assert_eq!(
5877                tr.confidence, r.token_confidence[i],
5878                "trace confidence matches the confidence channel"
5879            );
5880            // No dynamic router in this pipeline → no skill, no coherence.
5881            assert!(tr.active_skill.is_none() && tr.recon.is_none() && !tr.switched);
5882        }
5883    }
5884
5885    #[test]
5886    fn explain_prefill_logits_match_greedy_first_token() {
5887        // `cortiq explain` shows the next-token distribution from
5888        // prefill_next_logits; its argmax must equal what greedy generate
5889        // actually emits first — otherwise explain would lie.
5890        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
5891        p.sampler_config.temperature = 0.0;
5892        p.sampler_config.repetition_penalty = 1.0;
5893        let ids = p.tokenizer.encode("abcd");
5894        let logits = p.prefill_next_logits(&ids, None);
5895        let argmax = logits
5896            .iter()
5897            .enumerate()
5898            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
5899            .unwrap()
5900            .0 as u32;
5901        let r = p.generate("abcd", 1, None, None).unwrap();
5902        assert_eq!(
5903            argmax, r.token_ids[0],
5904            "explain preview must match greedy emit"
5905        );
5906    }
5907
5908    #[test]
5909    fn laguna_shared_expert_is_unconditionally_added() {
5910        let matrix = |values: Vec<f32>| QTensor::from_f32(values, 2, 2);
5911        let identity = || matrix(vec![1.0, 0.0, 0.0, 1.0]);
5912        let zero_dense = || DenseFfn {
5913            gate_proj: matrix(vec![0.0; 4]),
5914            up_proj: matrix(vec![0.0; 4]),
5915            down_proj: matrix(vec![0.0; 4]),
5916            act: Act::Silu,
5917        };
5918        let shared = DenseFfn {
5919            gate_proj: identity(),
5920            up_proj: identity(),
5921            down_proj: identity(),
5922            act: Act::Silu,
5923        };
5924        let x = [1.0, 2.0];
5925        let expected = dense_ffn(&shared, &x, None);
5926        let moe = MoeFfn {
5927            router: QTensor::from_f32(vec![0.0, 0.0], 1, 2),
5928            experts: vec![zero_dense()],
5929            top_k: 1,
5930            norm_topk_prob: true,
5931            router_sigmoid: true,
5932            expert_bias: None,
5933            routed_scaling: 1.0,
5934            route_tau: None,
5935            shared: Some((shared, None)),
5936            stats: std::cell::RefCell::new(Vec::new()),
5937            act_sq: std::cell::RefCell::new(Vec::new()),
5938            act_rows: std::cell::RefCell::new(Vec::new()),
5939            mask: None,
5940            per_expert_scale: None,
5941            router_input_norm: false,
5942        };
5943        let actual = moe_ffn_cpu(&moe, &x, &[0], &[0.0], 1.0, None);
5944        for (actual, expected) in actual.iter().zip(expected) {
5945            assert!((actual - expected).abs() < 1e-6);
5946        }
5947    }
5948}