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    /// In-process layer split across local GPUs: (device, first layer,
51    /// last layer) per segment, in execution order. `None` = one device.
52    /// Arc so cloning the plan out of `&mut self` does not fight the
53    /// borrow checker on the hot path.
54    gpu_plan: Option<std::sync::Arc<Vec<(usize, usize, usize)>>>,
55    /// Arc: the server shares one tokenizer handle across request
56    /// handlers without borrowing a pipeline slot.
57    pub tokenizer: std::sync::Arc<Tokenizer>,
58    pub kv_cache: KvCache,
59    pub sampler_config: SamplerConfig,
60    pub weights: PipelineWeights,
61    pub hidden_size: usize,
62    pub intermediate_size: usize,
63    pub num_heads: usize,
64    pub num_kv_heads: usize,
65    pub head_dim: usize,
66    /// Total virtual layers (num_layers × num_loops for looped models).
67    pub num_layers: usize,
68    /// Physical layers in weights.layers (≤ num_layers for looped models).
69    pub physical_layers: usize,
70    /// Looped Transformer: apply final norm after each loop iteration.
71    pub loop_final_norm: bool,
72    pub vocab_size: usize,
73    pub rms_eps: f64,
74    pub rope_base: f32,
75    pub norm_style: NormStyle,
76    /// RoPE dims actually rotated (≤ head_dim; Qwen3.5 uses head_dim/4).
77    pub rotary_dim: usize,
78    /// Optional Q-head count override for each attention layer (Laguna).
79    pub attention_heads_per_layer: Option<Vec<usize>>,
80    /// Linear-core geometry (present when the model has linear layers).
81    pub vmf_cfg: Option<VmfPhaseCfg>,
82    /// GatedDeltaNet geometry (faithful vendor operator).
83    pub gdn_cfg: Option<GdnCfg>,
84    /// MiniCPM-class logit scale (tied lm_head → cannot fold into weights).
85    pub logit_multiplier: Option<f32>,
86    /// Cooperative cancel: set from any thread (FFI `cortiq_cancel`,
87    /// a dropped server connection); the generate loop checks it at
88    /// every prefill chunk and decode step and finishes with
89    /// `finish_reason: "cancelled"`. Auto-cleared when honoured.
90    pub cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
91    /// Token ids currently materialized in the KV cache (the forwarded
92    /// prompt + all generated tokens except the last, which is sampled
93    /// but not yet forwarded). Lets the next generate call prefill only
94    /// the suffix when a chat app resends the whole history.
95    pub kv_history: Vec<u32>,
96    /// KDA geometry (Kimi Linear / Kimi-K3) — shared by every Kda layer.
97    pub kda_cfg: Option<crate::linear_core::KdaCfg>,
98    /// Gemma-3n stack (AltUp/LAuReL/PLE/KV-sharing): its own forward —
99    /// weights.layers stays empty, the KV caches are the shared ones.
100    pub g3n: Option<Box<(crate::g3n::G3nGlobals, Vec<crate::g3n::G3nLayer>)>>,
101    /// DeepSeek-V4 runs its own stack too: its hidden state is `hc_mult`
102    /// copies of a vector, so no loop written for a single residual
103    /// stream can carry it.
104    pub dsv4: Option<
105        Box<(
106            crate::dsv4::Dsv4Globals,
107            Vec<crate::dsv4::Dsv4Layer>,
108            crate::dsv4::Dsv4Cfg,
109            crate::dsv4::Dsv4State,
110        )>,
111    >,
112    /// DeepSeek-V4's own speculation stack: three draft modules, each a full
113    /// layer, plus a confidence head on the last. Empty when the file has
114    /// none, which is the only signal the decode path needs.
115    pub dsv4_mtp: Vec<crate::dsv4::Dsv4Mtp>,
116    /// The draft's per-sequence state (KV rings, captured trunk hidden).
117    pub dspark: Option<crate::dsv4::DsparkState>,
118    /// Drafts awaiting their verdict: (position, proposals, still matching,
119    /// accepted so far).
120    pub dspark_pending: Vec<(usize, Vec<u32>, bool, usize)>,
121    /// Accepted prefix length of every graded draft.
122    pub dspark_hist: Vec<usize>,
123    /// The real tokens the drafts were graded against — a degenerate,
124    /// repeating output would make any acceptance number meaningless, and
125    /// the cheapest guard against believing one is to count them.
126    pub dspark_real: Vec<u32>,
127    /// The trunk's expert picks for the last few tokens, per layer. The
128    /// union over a window of them is what a batched verify would have to
129    /// read, and the ratio to the pick count is all it could save.
130    pub dspark_trunk_picks: Vec<Vec<(usize, Vec<usize>)>>,
131    /// (unique, total) expert picks per draft, trunk side and draft side.
132    pub dspark_exp: Vec<(usize, usize, usize, usize)>,
133    /// Wall time spent in the deliberately out-of-core draft. Kept separate
134    /// from trunk decode so block batching can be judged without conflating
135    /// it with GPU chain variance.
136    pub dspark_draft_ns: u128,
137    /// LFM2 short-convolution geometry (present when the model has
138    /// `ShortConv` mixer layers).
139    pub short_conv_cfg: Option<ShortConvCfg>,
140    /// Multi-token-prediction head (None = absent).
141    pub mtp: Option<MtpModule>,
142    /// Speculative decode via MTP (greedy only; `CMF_MTP=0` disables).
143    pub speculative: bool,
144    rng: SplitMix64,
145    sampler_scratch: SamplerScratch,
146    /// Precomputed RoPE inverse frequencies [head_dim/2]. Arc: the
147    /// forward path clones a handle to escape the &mut self borrow —
148    /// cloning the table itself was a per-forward allocation.
149    pub(crate) inv_freq: std::sync::Arc<Vec<f32>>,
150    /// Reusable norm buffers for the decode hot path (roadmap §3 P0:
151    /// steady-state forward should not heap-allocate). Disjoint field
152    /// from `weights`/`kv_cache`, so split borrows keep working.
153    ws: ForwardScratch,
154    /// Persistent worker pool (None = serial; see CMF_THREADS).
155    pool: Option<std::sync::Arc<Pool>>,
156    // ── Dynamic per-token skill routing (spec §9, claim 14/16) ──
157    /// Source model, retained so a skill switch can re-resolve the
158    /// touched layers' FFN tensors (Mapped = mmap pointers, cheap).
159    pub(crate) model: Option<std::sync::Arc<cortiq_core::CmfModel>>,
160    /// Masks present → weights are dequantized f32 (rebuild path).
161    pub(crate) dyn_force_f32: bool,
162    /// Per-skill FFN layers actually replaced (derived from tensors, not
163    /// the meta `layers` field — ru2 replaces down_proj in 0..23 while
164    /// its meta says [20..23]). None = skill touches non-FFN tensors →
165    /// ineligible for cheap dynamic switching (honest refusal).
166    pub(crate) dyn_skill_layers: Vec<Option<Vec<usize>>>,
167    /// Currently overlaid skill (index into model.header.skills); None =
168    /// backbone. Set at load time to the statically-overlaid skill so
169    /// `set_active_skill(None)` correctly reverts it (else a static
170    /// skill would silently persist — the union-diff assumes dyn_active
171    /// always mirrors the live overlay). Switched by `set_active_skill`.
172    pub(crate) dyn_active: Option<usize>,
173    /// Pipeline was loaded with a soft blend (materialized working
174    /// tensors, not a single skill index) → dynamic routing refuses:
175    /// there is no single index to revert the blend from.
176    pub(crate) dyn_blend_loaded: bool,
177    /// Layer whose post-residual hidden feeds the router φ (shared by
178    /// swarm skills). None = φ capture off.
179    pub(crate) dyn_phi_layer: Option<usize>,
180    /// EMA of φ at `dyn_phi_layer` over the decode window (on-policy).
181    dyn_phi_ema: Vec<f32>,
182    dyn_phi_seen: usize,
183    /// Hysteresis router driving per-token skill switches during decode
184    /// (None = static/no dynamic routing). Taken out during generation.
185    pub dyn_router: Option<crate::swarm::DynRouter>,
186    /// O(1) Nyström attention setting (CLI/env/header-hint resolved by
187    /// the caller; None = plain cache attention everywhere).
188    o1_cfg: Option<crate::nystrom::O1Cfg>,
189    /// Bumped at every o1 seal — the GPU state mirror re-uploads when it
190    /// sees a new epoch (each generate seals fresh CPU state).
191    o1_epoch: u64,
192    /// Per-layer o1 flags derived from `o1_cfg` (Full layers only).
193    o1_flags: Vec<bool>,
194    /// Emit a structured per-token trace (B4 telemetry channel). Off by
195    /// default — the runtime is silent unless observation is requested.
196    trace: bool,
197    /// Confidence-calibration temperature (B1): reported Born mass is
198    /// softmax(logits / calib_temp). 1.0 = raw. Set from header.calibration.
199    calib_temp: f32,
200    /// Process-unique id keying this pipeline's device KV mirrors.
201    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
202    graph_kv_id: u64,
203    /// Decode asks the token graph to also run final-norm + lm_head on
204    /// the device (drops the separate per-op lm_head round trip).
205    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
206    graph_want_logits: bool,
207    /// Logits the graph produced for the token just forwarded (taken by
208    /// the decode loop; None = compute on the CPU path).
209    graph_logits: Option<Vec<f32>>,
210    /// Token embeddings are multiplied by this at input (Gemma: √hidden).
211    pub embed_multiplier: f32,
212    /// Attention score scale (1/√head_dim unless the arch overrides —
213    /// Gemma's query_pre_attn_scalar).
214    pub attn_scale: f32,
215    /// Sliding-window attention: (window, every-Nth-layer-is-global
216    /// pattern) — Gemma-3.
217    pub swa: Option<(usize, usize)>,
218    /// Explicit local/global schedule for architectures that cannot be
219    /// represented by Gemma's every-Nth-global convention.
220    pub sliding_layers: Option<Vec<bool>>,
221    /// RoPE table of the sliding (local) layers, when they use their
222    /// own base frequency (Gemma-3: 10k local vs 1M global).
223    pub inv_freq_local: Option<std::sync::Arc<Vec<f32>>>,
224    pub rotary_dim_local: Option<usize>,
225    pub rope_scale: f32,
226    pub rope_scale_local: f32,
227    /// Gemma-4: global layers run their own geometry — (head_dim,
228    /// num_kv_heads); sliding layers keep the base fields.
229    pub global_attn: Option<(usize, usize)>,
230    /// Gemma-4: the global layers' proportional RoPE table (len
231    /// global_head_dim/2, zero-padded tail = identity rotation).
232    pub inv_freq_global: Option<std::sync::Arc<Vec<f32>>>,
233    /// Scale-less RMS normalization of V heads before caching (Gemma-4).
234    pub attn_v_norm: bool,
235    /// Final-logit soft-capping C: logits = C·tanh(logits/C) (Gemma-4).
236    pub final_softcap: Option<f32>,
237    /// Gemma-2 attention-logit soft-capping (0.0 = off).
238    pub attn_softcap: f32,
239    /// Compute per-token Born confidence (a full-vocab softmax each
240    /// token). On by default; `bench --core` turns it off to match
241    /// llama-bench's core timing.
242    confidence_on: bool,
243}
244
245#[cfg(target_os = "macos")]
246impl Drop for Pipeline {
247    fn drop(&mut self) {
248        crate::gpu::kv_mirror_drop(self.graph_kv_id);
249    }
250}
251
252/// Model weights. Matrices are `QTensor` (owned f32 for small models
253/// and tests — bit-identical to the historical paths — or quantized
254/// bytes zero-copy from the CMF mmap for big models). 1-D norms are
255/// always small and stay f32.
256pub struct PipelineWeights {
257    /// Embedding table: [vocab_size, hidden_size]
258    pub embed_tokens: QTensor,
259    /// Per-layer weights
260    pub layers: Vec<LayerWeights>,
261    /// LM head: [vocab_size, hidden_size]
262    pub lm_head: QTensor,
263    /// Final norm: [hidden_size]
264    pub final_norm: Vec<f32>,
265}
266
267/// One transformer layer: shared norms + MLP, attention by kind.
268pub struct LayerWeights {
269    pub input_norm: Vec<f32>,
270    /// The pre-FFN norm (`post_attention_layernorm` classically;
271    /// `pre_feedforward_layernorm` on Gemma-2/3 sandwich layers).
272    pub post_norm: Vec<f32>,
273    /// Gemma-2/3 sandwich: norm applied to the ATTENTION OUTPUT before
274    /// its residual add (`post_attention_layernorm` there).
275    pub attn_out_norm: Option<Vec<f32>>,
276    /// Gemma-4: the whole layer output is multiplied by this scalar.
277    pub layer_scale: Option<f32>,
278    /// Gemma-2/3 sandwich: norm applied to the FFN OUTPUT before its
279    /// residual add (`post_feedforward_layernorm`).
280    pub ffn_out_norm: Option<Vec<f32>>,
281    pub ffn: FfnKind,
282    pub attn: AttnKind,
283}
284
285/// FFN gate activation: SiLU (SwiGLU family) or tanh-GELU (Gemma's
286/// GeGLU). A property of the model, carried on every FFN triple.
287#[derive(Clone, Copy, PartialEq, Debug, Default)]
288pub enum Act {
289    #[default]
290    Silu,
291    GeluTanh,
292    /// Kimi-K3 SituAndMul: BOTH halves transform —
293    /// a = β·tanh(g/β)·σ(g), up' = linβ·tanh(u/linβ) (linβ>0), out = a·up'.
294    Situ {
295        beta: f32,
296        linear_beta: f32,
297    },
298}
299
300impl Act {
301    pub fn from_arch(name: &str) -> Self {
302        if name == "gelu_tanh" {
303            Self::GeluTanh
304        } else {
305            Self::Silu
306        }
307    }
308
309    /// Arch-driven constructor (activation name + situ betas).
310    pub fn from_arch_full(arch: &cortiq_core::ModelArch) -> Self {
311        match arch.hidden_act.as_str() {
312            "situ" => Self::Situ {
313                beta: arch.activation_situ_beta.unwrap_or(1.0) as f32,
314                linear_beta: arch.activation_situ_linear_beta.unwrap_or(0.0) as f32,
315            },
316            other => Self::from_arch(other),
317        }
318    }
319
320    #[inline]
321    pub fn apply(self, x: f32) -> f32 {
322        match self {
323            Self::Silu => inference::silu(x),
324            Self::GeluTanh => inference::gelu_tanh(x),
325            Self::Situ { beta, .. } => beta * (x / beta).tanh() * (1.0 / (1.0 + (-x).exp())),
326        }
327    }
328
329    /// Gated combine — the FFN contract. Situ transforms the UP half
330    /// too, so callers must use this instead of apply(g)·u.
331    #[inline]
332    pub fn combine(self, g: f32, u: f32) -> f32 {
333        match self {
334            Self::Situ { linear_beta, .. } if linear_beta > 0.0 => {
335                self.apply(g) * (linear_beta * (u / linear_beta).tanh())
336            }
337            _ => self.apply(g) * u,
338        }
339    }
340}
341
342/// Dense gated triple — the FFN of a dense layer or of one expert.
343pub struct DenseFfn {
344    pub gate_proj: QTensor,
345    pub up_proj: QTensor,
346    pub down_proj: QTensor,
347    /// Gate activation (SiLU default; Gemma: tanh-GELU).
348    pub act: Act,
349}
350
351/// FFN operator of a layer, decided by tensor presence at load time
352/// (router `mlp.gate.weight` in the directory = MoE layer).
353pub enum FfnKind {
354    Dense(DenseFfn),
355    /// Mixture-of-Experts (Qwen2-MoE / Qwen3-MoE): softmax over ALL
356    /// expert logits → top-k, optional renorm; experts stay quantized
357    /// in mmap — only the selected ones are touched per token.
358    Moe(MoeFfn),
359    /// Gemma-4 MoE: a dense MLP branch AND a routed-expert branch in
360    /// the SAME layer, each with its own norm sandwich. The dense
361    /// branch reads the pre-FFN-normed input; the expert branch (and
362    /// the router) read the RAW residual through `pre_norm_2`:
363    ///   d = post_norm_1(dense(x̂));  m = post_norm_2(Σwₑ·FFNₑ(pre_norm_2(h)))
364    ///   ffn_out = d + m   (the caller's ffn_out_norm + residual follow)
365    DenseMoe(Box<DenseMoeFfn>),
366}
367
368/// Gemma-4 dual-branch FFN (see `FfnKind::DenseMoe`).
369pub struct DenseMoeFfn {
370    pub dense: DenseFfn,
371    pub moe: MoeFfn,
372    /// post_feedforward_layernorm_1 — dense-branch output norm.
373    pub post_norm_1: Vec<f32>,
374    /// pre_feedforward_layernorm_2 — expert-branch input norm (applied
375    /// to the RAW residual, not the pre-FFN-normed activation).
376    pub pre_norm_2: Vec<f32>,
377    /// post_feedforward_layernorm_2 — expert-branch output norm.
378    pub post_norm_2: Vec<f32>,
379}
380
381pub struct MoeFfn {
382    /// Router `mlp.gate.weight` [num_experts, hidden].
383    pub router: QTensor,
384    pub experts: Vec<DenseFfn>,
385    pub top_k: usize,
386    pub norm_topk_prob: bool,
387    /// Router scores per-expert with a sigmoid (LFM2-MoE / DeepSeek-V3
388    /// `noaux_tc`) instead of a softmax over all experts (Qwen).
389    pub router_sigmoid: bool,
390    /// Per-expert selection bias `mlp.expert_bias` [num_experts]
391    /// (LFM2-MoE): added to the sigmoid scores for the top-k CHOICE only;
392    /// the gathered weights use the unbiased scores. None = no bias.
393    pub expert_bias: Option<Vec<f32>>,
394    /// Top-k weights are multiplied by this after the optional renorm
395    /// (LFM2-MoE `routed_scaling_factor`; 1.0 = off).
396    pub routed_scaling: f32,
397    /// Adaptive routing (CMF_MOE_TAU, opt-in): keep the smallest
398    /// prefix of the top-k whose renormalized mass reaches τ —
399    /// confident tokens touch 1–2 experts, flat ones keep all k.
400    /// MoE decode is memory-bound, so skipped experts are skipped
401    /// weight traffic. None = classic fixed top-k (bit-identical).
402    pub route_tau: Option<f32>,
403    /// Always-on shared expert. Qwen2-MoE carries an additional sigmoid
404    /// gate; Laguna adds the shared expert unconditionally (`None`).
405    pub shared: Option<(DenseFfn, Option<QTensor>)>,
406    /// Expert-selection counters (truncated Fisher B-field of claim 12:
407    /// routing frequency during calibration). Filled by every forward,
408    /// read by the CLI via CMF_MOE_STATS. RefCell: decode is single-threaded.
409    pub stats: std::cell::RefCell<Vec<u64>>,
410    /// Per-CHANNEL sum of squares of this FFN's input, accumulated over a
411    /// calibration run (`CMF_RMS_TRACE`). These are the RMS activation
412    /// traces AWNP needs: raw weight magnitude says every channel matters
413    /// equally, and the question AWNP asks is whether the ACTIVATIONS
414    /// disagree. Off unless the env var is set — an f64 add per channel
415    /// per token is cheap, but not free.
416    pub act_sq: std::cell::RefCell<Vec<f64>>,
417    /// Raw FFN-input rows captured for the layers named by `CMF_ACT_DUMP`
418    /// (`"9,19"`). AWNP is nullspace PROJECTION: after dropping channels the
419    /// survivors are refitted to absorb what was removed, and how much they
420    /// can absorb depends on the activation COVARIANCE, not on per-channel
421    /// RMS. Per-channel numbers can only bound the cost from above.
422    pub act_rows: std::cell::RefCell<Vec<f32>>,
423    /// Task mask over routed experts (DTG-MA over MoE, claim-12 B-field
424    /// applied): `false` experts are excluded from selection, the
425    /// softmax renormalizes over the allowed set. Built by the loader
426    /// from CMF_MOE_MASK=<stats.json> + CMF_MOE_MASK_COVER. None = all.
427    pub mask: Option<Vec<bool>>,
428    /// Gemma-4: per-expert weight scale applied AFTER the top-k renorm
429    /// (`router.per_expert_scale`). None = 1.0 everywhere.
430    pub per_expert_scale: Option<Vec<f32>>,
431    /// Gemma-4: the router reads a SCALE-LESS rms-norm of its input
432    /// (the constant gain router.scale·√hidden is folded into the
433    /// router weights at convert time).
434    pub router_input_norm: bool,
435}
436
437/// Attention operator of a layer. Extension point: new operators are
438/// new variants here + a forward in their own module.
439pub enum AttnKind {
440    /// GQA softmax attention (+ optional Qwen3.5 qk-norm / output gate).
441    Full {
442        wq: QTensor,
443        wk: QTensor,
444        wv: QTensor,
445        wo: QTensor,
446        q_norm: Option<Vec<f32>>,
447        k_norm: Option<Vec<f32>>,
448        output_gate: bool,
449        /// Laguna: a separate softplus projection applied to the attention
450        /// output before O. The bool means one scalar per head (broadcast
451        /// across head_dim); false means one scalar per element.
452        softplus_gate: Option<(QTensor, bool)>,
453        /// Qwen2-family projection biases (q, k, v).
454        bias: Option<(Vec<f32>, Vec<f32>, Vec<f32>)>,
455    },
456    /// Canonical linear core (VMF phase attention).
457    Linear(VmfPhaseWeights),
458    /// Faithful vendor linear operator (Qwen3.5 GatedDeltaNet).
459    LinearGdn(GdnWeights),
460    /// LFM2 gated short-convolution mixer (no KV cache; conv ring state
461    /// lives in the layer's `linear_state`).
462    ShortConv(ShortConvWeights),
463    /// DeepSeek-V2 Multi-head Latent Attention. v1 executes it as
464    /// expand-to-MHA: the latent is projected per token, K/V expand to
465    /// every head and live in the ordinary cache (K head layout
466    /// [rope | nope] so the standard partial rotary covers the shared
467    /// rope key; V rows are zero-padded to the K head_dim and the pad
468    /// is sliced off before O). Latent-resident cache is a later
469    /// optimization, not a semantic change.
470    Mla(Box<MlaWeights>),
471    /// Kimi Delta Attention (Kimi Linear / Kimi-K3): per-channel decayed
472    /// delta rule, separate q/k/v short convs, sigmoid-gated output norm.
473    /// State lives in the layer's `linear_state` (no KV cache).
474    Kda(Box<crate::linear_core::KdaWeights>),
475}
476
477/// DeepSeek-V2 MLA projections (see `AttnKind::Mla`).
478pub struct MlaWeights {
479    /// `[nh·(rope+nope), hidden]` (or `[…, q_lora]` when compressed) —
480    /// the converter permutes each head rope-first so rotary_dim =
481    /// qk_rope works unchanged.
482    pub q_proj: QTensor,
483    /// Compressed q (K3/V3 class): x → q_a `[q_lora, hidden]` →
484    /// rms(q_a_norm) → q_proj (= q_b). None = direct q (V2-Lite).
485    pub q_a: Option<QTensor>,
486    pub q_a_norm: Option<Vec<f32>>,
487    /// `kv_a_proj_with_mqa` `[lora + rope, hidden]` (latent first).
488    pub kv_a: QTensor,
489    /// RMS-norm weights over the latent (`kv_a_layernorm`, [lora]).
490    pub kv_a_norm: Vec<f32>,
491    /// `[nh·(nope+v), lora]` — per head [k_nope | v].
492    pub kv_b: QTensor,
493    /// `[hidden, nh·v]`.
494    pub o_proj: QTensor,
495    pub nh: usize,
496    pub qk_rope: usize,
497    pub qk_nope: usize,
498    pub v_dim: usize,
499    pub lora: usize,
500    /// Softmax scale (1/√(rope+nope), YaRN-mscale-corrected at load).
501    pub scale: f32,
502    /// Kimi Linear NoPE: skip the rotary entirely (layout unchanged).
503    pub nope: bool,
504}
505
506/// Multi-token-prediction head (DeepSeek/Qwen style, spec §2.1):
507/// `x = eh_proj·[enorm(embed(next)); hnorm(hidden)]` → one transformer
508/// block over its own KV → shared lm_head. Drafts the token after next;
509/// the main model verifies, so output is exact — MTP only buys speed.
510pub struct MtpModule {
511    pub enorm: Vec<f32>,
512    pub hnorm: Vec<f32>,
513    /// [hidden, 2·hidden]
514    pub eh_proj: QTensor,
515    pub layer: LayerWeights,
516    pub final_norm: Vec<f32>,
517    pub kv: crate::kv_cache::LayerKvCache,
518}
519
520/// Result of a generation call.
521pub struct GenerateResult {
522    pub text: String,
523    pub token_ids: Vec<u32>,
524    pub prompt_tokens: usize,
525    pub tokens_generated: usize,
526    pub finish_reason: String,
527    /// Speculative-decode stats (0/0 when MTP is absent or inactive).
528    pub mtp_drafted: usize,
529    pub mtp_accepted: usize,
530    /// Per-generated-token confidence = softmax probability of the token
531    /// that was actually emitted (Born mass on the chosen state). High =
532    /// the model was sure; low = it was guessing. Same length as the
533    /// generated slice of `token_ids`.
534    pub token_confidence: Vec<f32>,
535    /// Structured per-token telemetry (B4 channel). Empty unless
536    /// `set_trace(true)`; otherwise same length as the generated slice.
537    pub traces: Vec<TokenTrace>,
538}
539
540/// One row of the structured telemetry trace (B4): the model's internal
541/// routing state at the moment a token was emitted. Every field is a
542/// quantity the runtime already computes — nothing is inferred or
543/// estimated (anti-principle: only measured bytes).
544#[derive(Clone, Debug)]
545pub struct TokenTrace {
546    /// 0-based index within the generated slice.
547    pub t: usize,
548    /// The emitted token id.
549    pub token_id: u32,
550    /// Born mass on the emitted token (softmax prob) — how sure the model was.
551    pub confidence: f32,
552    /// Skill in force while this token was generated (None = backbone).
553    pub active_skill: Option<String>,
554    /// Recon error E = ‖r−BBᵀr‖²/‖φ‖² at the last routing eval — coherence
555    /// with the active skill's subspace (low = coherent). None = no router
556    /// or not yet evaluated.
557    pub recon: Option<f32>,
558    /// The router changed the active skill right after this token (a
559    /// domain boundary crossed under the hysteresis barrier).
560    pub switched: bool,
561}
562
563/// Calibrated softmax probability of `id` under `logits` (the Born mass on
564/// the emitted token) — the confidence signal, cheap from logits already
565/// computed for sampling. `temp` is the calibration temperature (B1):
566/// softmax(logits / temp); 1.0 = raw.
567fn top1_prob_t(logits: &[f32], id: u32, temp: f32) -> f32 {
568    let t = if temp > 1e-3 { temp } else { 1.0 };
569    let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
570    let sum: f32 = logits.iter().map(|&v| ((v - max) / t).exp()).sum();
571    if sum > 0.0 {
572        (((logits[id as usize] - max) / t).exp()) / sum
573    } else {
574        0.0
575    }
576}
577
578/// prefill-GEMM enabled? (CMF_PREFILL=seq — emergency fallback to the
579/// sequential path.)
580fn prefill_batched() -> bool {
581    std::env::var("CMF_PREFILL")
582        .map(|v| v != "seq")
583        .unwrap_or(true)
584}
585
586/// Input to the layer-major batched span walk: token ids (embeds itself,
587/// full-stack and coordinator prefill) or ready boundary hiddens (the
588/// network worker's side of a split).
589#[derive(Clone, Copy)]
590enum PrefillIn<'a> {
591    Ids(&'a [u32]),
592    Hidden(&'a [f32]),
593}
594
595/// The batched prefill walks `weights.layers`. Architectures that load
596/// their own stack (gemma-3n's AltUp replicas, DeepSeek-V4's hyper-
597/// connections) leave that empty and must go position by position — asking
598/// otherwise indexes an empty vector, which is a panic rather than a
599/// fallback. Every call site goes through here so the next such
600/// architecture is one line, not four.
601impl Pipeline {
602    fn can_prefill_batched(&self) -> bool {
603        prefill_batched() && !self.weights.layers.is_empty()
604    }
605}
606
607/// Prefill chunk (positions per batched pass). On macOS the AMX GEMM
608/// path wants tall panels — M=48 starves the matrix units (ggml uses
609/// ubatch 512); elsewhere the historical 48 stays. CMF_PREFILL_CHUNK
610/// overrides. Pub: the network split MUST chunk identically to the
611/// local path — panel width reorders float accumulation, so a different
612/// chunk is a different (equally valid) generation.
613pub fn prefill_chunk() -> usize {
614    if let Some(n) = std::env::var("CMF_PREFILL_CHUNK")
615        .ok()
616        .and_then(|v| v.parse::<usize>().ok())
617    {
618        return n.max(1);
619    }
620    if cfg!(target_os = "macos") {
621        512
622    } else if cfg!(target_arch = "aarch64") {
623        // Mobile: big enough to feed the batched attend (gate b ≥ 32)
624        // and the blocked SDOT GEMM without the memory of 512.
625        256
626    } else {
627        48
628    }
629}
630
631/// Callback for streaming tokens. Return `false` to cancel.
632pub type TokenCallback = Box<dyn FnMut(&str) -> bool + Send>;
633
634impl Pipeline {
635    /// Map a virtual layer index to its physical weight index.
636    /// Looped Transformer (Nanbeige 4.2): 22 physical layers × 2 loops = 44 virtual;
637    /// virtual layer 23 maps back to physical layer 1 (23 % 22 = 1).
638    #[inline]
639    pub fn phys_layer(&self, virtual_idx: usize) -> usize {
640        virtual_idx % self.physical_layers
641    }
642
643    /// True when `virtual_idx` is the last layer of a loop iteration
644    /// (used for loop_final_norm insertion).
645    #[inline]
646    pub fn is_loop_end(&self, virtual_idx: usize) -> bool {
647        self.loop_final_norm && (virtual_idx + 1) % self.physical_layers == 0
648    }
649
650    /// Build a pipeline from parts (used by the loader and tests).
651    #[allow(clippy::too_many_arguments)]
652
653    /// Whole-block q1 token graph on the GPU (macOS/Metal): the run of
654    /// consecutive q1 layers — GDN *and* full attention — starting at
655    /// `start` executes as few command buffers as the CPU truly needs.
656    /// Hidden stays device-resident across every layer; the only syncs
657    /// are before each CPU attend (it needs q/k/v and owns the KV
658    /// cache) and the final hidden readback. Recurrent states
659    /// round-trip through shared memory (the CPU stays their owner, so
660    /// every other path remains coherent). Returns the first layer
661    /// index NOT covered (== `start` → refused, caller falls through
662    /// to the per-layer CPU path).
663    /// Should prefill run position-by-position through the GPU token
664    /// graph instead of the batched CPU chunk-GEMM? True for q1 GDN
665    /// hybrids on native Metal: their chunk prefill is walled by the
666    /// sequential scalar recurrence, so the graph's decode rate wins.
667    /// NOT for Looped Transformers, despite the per-chunk loop_final_norm
668    /// sync: the chunk-GEMM amortizes each weight over the whole chunk,
669    /// which the per-position graph cannot (Nanbeige 4.2 on M4, 512-token
670    /// prompt: 85 tok/s chunked vs 14 through the graph).
671    #[cfg(target_os = "macos")]
672    fn graph_prefill_preferred(&self) -> bool {
673        if !crate::gpu::enabled_here()
674            || !crate::gpu::q1_force()
675            || std::env::var("CMF_GPU_BLOCK")
676                .map(|v| v == "0")
677                .unwrap_or(false)
678        {
679            return false;
680        }
681        self.weights
682            .layers
683            .iter()
684            .any(|lw| matches!(&lw.attn, AttnKind::LinearGdn(w) if w.in_proj_qkv.is_q1()))
685    }
686
687    #[cfg(not(target_os = "macos"))]
688    fn graph_prefill_preferred(&self) -> bool {
689        // Discrete-GPU wgpu whole-token graph: GDN layers carry recurrent state
690        // (conv ring + delta-rule S) resident on the GPU. A batched CPU prefill
691        // builds that state on the CPU only, leaving the GPU buffers zeroed at
692        // decode → garbage. Route GDN-hybrid prefill through the graph one
693        // position at a time so the resident state is seeded exactly as decode
694        // will read it. Pure-attention models keep the batched CPU prefill (its
695        // KV mirror re-syncs from the CPU cache, so no seeding gap).
696        let graph_on = crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill);
697        if !graph_on || !crate::gpu::enabled_here() {
698            return false;
699        }
700        self.weights
701            .layers
702            .iter()
703            .any(|lw| matches!(&lw.attn, AttnKind::LinearGdn(_)))
704    }
705
706    #[cfg(target_os = "macos")]
707    fn q1_graph_gpu(
708        &mut self,
709        start: usize,
710        upto: Option<usize>,
711        position: usize,
712        h: &mut [f32],
713    ) -> usize {
714        use crate::gpu::{AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, GraphDims, MetalFfn, TokenGraph};
715        if self.attn_softcap > 0.0 // capped scores: no graph kernel — CPU path
716            || !crate::gpu::enabled_here()
717            || !crate::gpu::q1_force()
718            || std::env::var("CMF_GPU_BLOCK")
719                .map(|v| v == "0")
720                .unwrap_or(false)
721        {
722            if std::env::var("CMF_GRAPH_DBG").is_ok() {
723                eprintln!(
724                    "block-graph: front gate (softcap={} enabled_here={} q1_force={})",
725                    self.attn_softcap > 0.0,
726                    crate::gpu::enabled_here(),
727                    crate::gpu::q1_force(),
728                );
729            }
730            return start;
731        }
732        // The graph encodes SiLU FFN, 1/√hd attention scores and
733        // full-context attend with no branch norms — Gemma-style archs
734        // (sliding window, scale override, sandwich norms, GeLU) fall
735        // back to the CPU path.
736        if self.swa.is_some()
737            || self.global_attn.is_some()
738            || self.attention_heads_per_layer.is_some()
739            || self.attn_v_norm
740            || (self.attn_scale - 1.0 / (self.head_dim as f32).sqrt()).abs() > 1e-9
741            || self.weights.layers.iter().any(|lw| {
742                lw.attn_out_norm.is_some()
743                    || lw.ffn_out_norm.is_some()
744                    || lw.layer_scale.is_some()
745                    || matches!(&lw.ffn, FfnKind::Dense(d) if d.act != Act::Silu)
746            })
747        {
748            if std::env::var("CMF_GRAPH_DBG").is_ok() {
749                eprintln!(
750                    "block-graph: arch ineligible (swa={} gattn={} hpl={} vnorm={} scale_delta={:.2e})",
751                    self.swa.is_some(),
752                    self.global_attn.is_some(),
753                    self.attention_heads_per_layer.is_some(),
754                    self.attn_v_norm,
755                    (self.attn_scale - 1.0 / (self.head_dim as f32).sqrt()).abs(),
756                );
757            }
758            return start;
759        }
760        // Looped Transformer: the graph covers ALL loop iterations;
761        // encode_loop_norm is inserted on-device at each boundary.
762        let limit = upto
763            .map(|u| u + 1)
764            .unwrap_or(self.num_layers)
765            .min(self.num_layers);
766
767        enum Item<'a> {
768            Gdn {
769                run: Vec<GdnGpuLayer<'a>>,
770                first: usize,
771            },
772            Attn {
773                l: AttnGpuLayer<'a>,
774                li: usize,
775                q_norm: Option<&'a [f32]>,
776                k_norm: Option<&'a [f32]>,
777                output_gate: bool,
778                bias: Option<(&'a [f32], &'a [f32], &'a [f32])>,
779                /// Attend on the device too (no sync): F32 KV, no
780                /// o1/bias, dims inside the kernels' contract.
781                full_gpu: bool,
782            },
783        }
784
785        // Device-attend KERNEL contract, shared by every Full layer. The
786        // hd>128 default-off POLICY is applied after the scan: it was
787        // measured on dense models, and a MoE plan inverts it — with the
788        // experts on device each CPU-attend sandwich costs a
789        // commit+wait, ~30 submits/token (W2 on M4: 14.7 tok/s
790        // sandwiched vs 27.1 device-attend vs 18.8 pure CPU).
791        let attend_mode = std::env::var("CMF_GPU_ATTEND").unwrap_or_else(|_| "auto".into());
792        let attend_contract = attend_mode != "0"
793            && attend_mode != "off"
794            && self.head_dim % 4 == 0
795            && self.head_dim <= 256
796            && self.rotary_dim >= 2
797            && self.rotary_dim <= self.head_dim
798            && (self.rotary_dim / 2) % 32 == 0
799            && self.num_kv_heads > 0
800            && self.num_heads % self.num_kv_heads == 0;
801
802        let mut plan: Vec<Item> = Vec::new();
803        let mut model_ref: Option<std::sync::Arc<cortiq_core::CmfModel>> = None;
804        // Break-reason diagnostics ride the same env as the plan summary.
805        let block_diag = std::env::var("CMF_GRAPH_DBG").is_ok();
806        let mut scan = start;
807        while scan < limit {
808            let lw = &self.weights.layers[self.phys_layer(scan)];
809            let ffn = match &lw.ffn {
810                FfnKind::Dense(d) => {
811                    let (Some(g), Some(u), Some(dn)) = (
812                        d.gate_proj.q1_parts(),
813                        d.up_proj.q1_parts(),
814                        d.down_proj.q1_parts(),
815                    ) else {
816                        if block_diag {
817                            eprintln!(
818                                "block-graph: L{scan} FFN trio not graph-mappable — run ends"
819                            );
820                        }
821                        break;
822                    };
823                    MetalFfn::Dense {
824                        gate: g,
825                        up: u,
826                        down: dn,
827                    }
828                }
829                FfnKind::Moe(m) => {
830                    let Some(moe) = metal_moe_graph_parts(m, self.hidden_size) else {
831                        if block_diag {
832                            eprintln!(
833                                "block-graph: L{scan} MoE outside the graph contract — run ends"
834                            );
835                        }
836                        break;
837                    };
838                    if let QTensor::Mapped { model, .. } = &m.experts[0].gate_proj {
839                        model_ref.get_or_insert_with(|| model.clone());
840                    }
841                    MetalFfn::Moe(moe)
842                }
843                _ => {
844                    if block_diag {
845                        eprintln!("block-graph: L{scan} non-graph FFN — run ends");
846                    }
847                    break;
848                }
849            };
850            match &lw.attn {
851                AttnKind::LinearGdn(w) if self.gdn_cfg.is_some() => {
852                    let parts = (
853                        w.in_proj_qkv.q1_parts(),
854                        w.in_proj_z.q1_parts(),
855                        w.in_proj_a.f32_parts(),
856                        w.in_proj_b.f32_parts(),
857                        w.out_proj.q1_parts(),
858                    );
859                    let (Some(qkv), Some(z), Some(a), Some(b), Some(out)) = parts else {
860                        if block_diag {
861                            eprintln!(
862                                "block-graph: L{scan} GDN parts refused (qkv={} z={} a_f32={} b_f32={} out={})",
863                                w.in_proj_qkv.q1_parts().is_some(),
864                                w.in_proj_z.q1_parts().is_some(),
865                                w.in_proj_a.f32_parts().is_some(),
866                                w.in_proj_b.f32_parts().is_some(),
867                                w.out_proj.q1_parts().is_some(),
868                            );
869                        }
870                        break;
871                    };
872                    if let QTensor::Mapped { model, .. } = &w.in_proj_qkv {
873                        model_ref.get_or_insert_with(|| model.clone());
874                    }
875                    let gl = GdnGpuLayer {
876                        attn_norm: &lw.input_norm,
877                        post_norm: &lw.post_norm,
878                        qkv,
879                        z,
880                        a,
881                        b,
882                        out,
883                        ffn,
884                        conv1d: &w.conv1d,
885                        a_log: &w.a_log,
886                        dt_bias: &w.dt_bias,
887                        gnorm: &w.norm,
888                    };
889                    match plan.last_mut() {
890                        Some(Item::Gdn { run, .. }) => run.push(gl),
891                        _ => plan.push(Item::Gdn {
892                            run: vec![gl],
893                            first: scan,
894                        }),
895                    }
896                }
897                AttnKind::Full {
898                    wq,
899                    wk,
900                    wv,
901                    wo,
902                    q_norm,
903                    k_norm,
904                    output_gate,
905                    softplus_gate: None,
906                    bias,
907                } if !self.kv_cache.layers[scan].o1_sealed() => {
908                    let parts = (wq.q1_parts(), wk.q1_parts(), wv.q1_parts(), wo.q1_parts());
909                    let (Some(pq), Some(pk), Some(pv), Some(po)) = parts else {
910                        break;
911                    };
912                    if let QTensor::Mapped { model, .. } = wq {
913                        model_ref.get_or_insert_with(|| model.clone());
914                    }
915                    let cache = &self.kv_cache.layers[scan];
916                    let full_gpu = attend_contract
917                        && cache.mode == crate::kv_cache::KvMode::F32
918                        && cache.o1.is_none()
919                        && bias.is_none()
920                        && pq.1 == self.num_heads * self.head_dim * (1 + *output_gate as usize)
921                        && pk.1 == self.num_kv_heads * self.head_dim
922                        && pv.1 == self.num_kv_heads * self.head_dim
923                        && po.2 == self.num_heads * self.head_dim;
924                    plan.push(Item::Attn {
925                        l: AttnGpuLayer {
926                            attn_norm: &lw.input_norm,
927                            post_norm: &lw.post_norm,
928                            wq: pq,
929                            wk: pk,
930                            wv: pv,
931                            wo: po,
932                            ffn,
933                        },
934                        li: scan,
935                        q_norm: q_norm.as_deref(),
936                        k_norm: k_norm.as_deref(),
937                        output_gate: *output_gate,
938                        bias: bias
939                            .as_ref()
940                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
941                        full_gpu,
942                    });
943                }
944                _ => break,
945            }
946            scan += 1;
947        }
948        let Some(model) = model_ref else {
949            if std::env::var("CMF_GRAPH_DBG").is_ok() {
950                eprintln!("q1-graph: no model ref (start {start}, scanned to {scan})");
951            }
952            return start;
953        };
954        if plan.is_empty() {
955            if std::env::var("CMF_GRAPH_DBG").is_ok() {
956                eprintln!("q1-graph: empty plan at layer {start}");
957            }
958            return start;
959        }
960        let has_moe = plan.iter().any(|it| match it {
961            Item::Gdn { run, .. } => run.iter().any(|l| matches!(l.ffn, MetalFfn::Moe(_))),
962            Item::Attn { l, .. } => matches!(l.ffn, MetalFfn::Moe(_)),
963        });
964        let dev_attend = attend_contract
965            && (self.head_dim <= 128
966                || has_moe
967                || attend_mode == "force"
968                || attend_mode == "256");
969        if !dev_attend {
970            for it in &mut plan {
971                if let Item::Attn { full_gpu, .. } = it {
972                    *full_gpu = false;
973                }
974            }
975        }
976        if std::env::var("CMF_GRAPH_DBG").is_ok() {
977            use std::sync::atomic::{AtomicBool, Ordering};
978            static SAID: AtomicBool = AtomicBool::new(false);
979            if !SAID.swap(true, Ordering::Relaxed) {
980                let fg = plan
981                    .iter()
982                    .filter(|it| matches!(it, Item::Attn { full_gpu: true, .. }))
983                    .count();
984                let att = plan
985                    .iter()
986                    .filter(|it| matches!(it, Item::Attn { .. }))
987                    .count();
988                eprintln!(
989                    "q1-graph: plan of {} items from layer {start} to {scan} | dev_attend={dev_attend} full_gpu {fg}/{att} | hd={} rd={} nkv={} nh={}",
990                    plan.len(),
991                    self.head_dim,
992                    self.rotary_dim,
993                    self.num_kv_heads,
994                    self.num_heads,
995                );
996            }
997        }
998        let dims = GraphDims {
999            hidden: self.hidden_size,
1000            eps: self.rms_eps as f32,
1001            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
1002        };
1003        let Some(mut graph) = TokenGraph::new(&model, dims, h) else {
1004            return start;
1005        };
1006        let gcfg = self.gdn_cfg.map(|cfg| GdnGpuCfg {
1007            nv: cfg.num_v_heads,
1008            nk: cfg.num_k_heads,
1009            dk: cfg.key_head_dim,
1010            dv: cfg.value_head_dim,
1011            kk: cfg.conv_kernel,
1012            hidden: self.hidden_size,
1013            inter: self.intermediate_size,
1014            c_dim: cfg.conv_dim(),
1015            eps: cfg.rms_eps as f32,
1016            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
1017        });
1018        // Validate the whole plan BEFORE encoding anything: after the
1019        // first sync a refused layer would leave the token
1020        // half-executed, so truncate to the provably encodable prefix.
1021        let mut valid = 0usize;
1022        let mut end = start;
1023        for item in &plan {
1024            let ok = match item {
1025                Item::Gdn { run, .. } => gcfg
1026                    .as_ref()
1027                    .map(|gc| run.iter().all(|l| graph.gdn_ok(l, gc)))
1028                    .unwrap_or(false),
1029                Item::Attn { l, .. } => graph.attn_ok(l),
1030            };
1031            if !ok {
1032                if block_diag {
1033                    eprintln!(
1034                        "block-graph: plan item {} ({}) failed graph preflight",
1035                        valid,
1036                        match item {
1037                            Item::Gdn { run, first } =>
1038                                format!("GDN run L{first}+{}", run.len()),
1039                            Item::Attn { li, .. } => format!("Attn L{li}"),
1040                        }
1041                    );
1042                }
1043                break;
1044            }
1045            valid += 1;
1046            end += match item {
1047                Item::Gdn { run, .. } => run.len(),
1048                Item::Attn { .. } => 1,
1049            };
1050        }
1051        plan.truncate(valid);
1052        if plan.is_empty() {
1053            return start;
1054        }
1055
1056        let inv_freq = self.inv_freq.clone();
1057        let pool = self.pool.clone();
1058        let (nh, nkv, hd, hs, rd, eps) = (
1059            self.num_heads,
1060            self.num_kv_heads,
1061            self.head_dim,
1062            self.hidden_size,
1063            self.rotary_dim,
1064            self.rms_eps,
1065        );
1066        let norm_style = self.norm_style;
1067        let gemma = norm_style == cortiq_core::NormStyle::Gemma;
1068        let want = self.gdn_cfg.map(|c| c.state_len()).unwrap_or(0);
1069        let kv_id = self.graph_kv_id;
1070        // GDN runs whose states await readback after the next sync
1071        // (device-attended layers add no sync, so several may stack).
1072        let mut pending: Vec<(usize, usize)> = Vec::new();
1073        // Device-attended layers: their K/V/imp are pulled from the
1074        // mirror after the final sync.
1075        let mut dev_attn: Vec<usize> = Vec::new();
1076        for item in &plan {
1077            // Looped Transformer: insert on-device norm at loop boundaries.
1078            if self.loop_final_norm {
1079                let item_start = match item {
1080                    Item::Gdn { first, .. } => *first,
1081                    Item::Attn { li, .. } => *li,
1082                };
1083                if item_start > start && self.is_loop_end(item_start - 1) {
1084                    graph.encode_loop_norm(&self.weights.final_norm);
1085                }
1086            }
1087            match item {
1088                Item::Gdn { run, first } => {
1089                    for l in &mut self.kv_cache.layers[*first..*first + run.len()] {
1090                        if l.linear_state.len() != want {
1091                            l.linear_state = vec![0f32; want];
1092                        }
1093                    }
1094                    let ro: Vec<&[f32]> = self.kv_cache.layers[*first..*first + run.len()]
1095                        .iter()
1096                        .map(|l| l.linear_state.as_slice())
1097                        .collect();
1098                    if !graph.encode_gdn_run(run, &ro, gcfg.as_ref().unwrap()) {
1099                        // Unreachable: the plan was validated above.
1100                        tracing::error!("q1 graph: GDN run refused after validation");
1101                        return start;
1102                    }
1103                    // Early commit: the GPU starts the run while the
1104                    // CPU encodes the next layer (nothing to wait on).
1105                    graph.commit();
1106                    pending.push((*first, run.len()));
1107                }
1108                Item::Attn {
1109                    l,
1110                    li,
1111                    q_norm,
1112                    k_norm,
1113                    output_gate,
1114                    bias,
1115                    full_gpu,
1116                } => {
1117                    // ── Fully device-resident attention: no sync at all.
1118                    if *full_gpu {
1119                        let cache = &self.kv_cache.layers[*li];
1120                        let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
1121                        let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
1122                        let cpu_stored = cpu_k[0].len() / hd;
1123                        let p = crate::gpu::AttnDeviceParams {
1124                            kv_id,
1125                            layer: *li,
1126                            nh,
1127                            nkv,
1128                            hd,
1129                            rd,
1130                            position,
1131                            eps: eps as f32,
1132                            gemma,
1133                            output_gate: *output_gate,
1134                            q_norm: *q_norm,
1135                            k_norm: *k_norm,
1136                            inv_freq: &inv_freq,
1137                            cpu_k,
1138                            cpu_v,
1139                            cpu_stored,
1140                        };
1141                        if graph.attn_device_ok(l, &p) && graph.encode_attn_device(l, &p) {
1142                            graph.commit();
1143                            dev_attn.push(*li);
1144                            continue;
1145                        }
1146                        // Mirror refused (nothing encoded) → sandwich.
1147                    }
1148                    graph.encode_attn_prefix(l);
1149                    graph.sync();
1150                    if !pending.is_empty() {
1151                        let idxs: Vec<usize> =
1152                            pending.drain(..).flat_map(|(f, n)| f..f + n).collect();
1153                        let mut outs: Vec<&mut [f32]> = self
1154                            .kv_cache
1155                            .layers
1156                            .iter_mut()
1157                            .enumerate()
1158                            .filter(|(i, _)| idxs.binary_search(i).is_ok())
1159                            .map(|(_, s)| s.linear_state.as_mut_slice())
1160                            .collect();
1161                        graph.read_states(&mut outs);
1162                    }
1163                    let mut q_raw = attention::take_buf(l.wq.1);
1164                    let mut k = attention::take_buf(l.wk.1);
1165                    let mut v = attention::take_buf(l.wv.1);
1166                    graph.read_qkv(&mut q_raw, &mut k, &mut v);
1167                    let cfg = QwenAttnCfg {
1168                        num_heads: nh,
1169                        num_kv_heads: nkv,
1170                        head_dim: hd,
1171                        hidden_size: hs,
1172                        position,
1173                        inv_freq: &inv_freq,
1174                        rotary_dim: rd,
1175                        scale: self.attn_scale,
1176                        softcap: self.attn_softcap,
1177                        window: None,
1178                        v_norm: false,
1179                        q_norm: *q_norm,
1180                        k_norm: *k_norm,
1181                        output_gate: *output_gate,
1182                        softplus_gate: None,
1183                        rope_scale: 1.0,
1184                        bias: *bias,
1185                        rms_eps: eps,
1186                        norm_style,
1187                        pool: pool.as_deref(),
1188                    };
1189                    let mut ao = attention::qwen_attention_core(
1190                        q_raw,
1191                        k,
1192                        v,
1193                        &mut self.kv_cache.layers[*li],
1194                        &cfg,
1195                    );
1196                    graph.encode_attn_suffix(l, &ao);
1197                    // Early commit: the GPU starts O+FFN while the CPU
1198                    // encodes the following GDN run / attention prefix.
1199                    graph.commit();
1200                    attention::recycle_buf(&mut ao);
1201                }
1202            }
1203        }
1204        // Ride the final norm + lm_head in the same command buffer when
1205        // this run reaches the model's end and the caller wants logits:
1206        // the separate per-op lm_head submit (a full round trip) folds
1207        // into the sync that already happens here.
1208        let mut lm_rows = None;
1209        if self.graph_want_logits
1210            && upto.is_none()
1211            && end == self.num_layers
1212            && std::env::var("CMF_GPU_LMHEAD")
1213                .map(|v| v != "0")
1214                .unwrap_or(true)
1215        {
1216            if let Some(lm) = self.weights.lm_head.q1_parts() {
1217                if graph.lm_head_ok(lm) {
1218                    graph.encode_lm_head(&self.weights.final_norm, lm);
1219                    lm_rows = Some(lm.1);
1220                }
1221            }
1222        }
1223        graph.sync();
1224        if !pending.is_empty() {
1225            let idxs: Vec<usize> = pending.drain(..).flat_map(|(f, n)| f..f + n).collect();
1226            let mut outs: Vec<&mut [f32]> = self
1227                .kv_cache
1228                .layers
1229                .iter_mut()
1230                .enumerate()
1231                .filter(|(i, _)| idxs.binary_search(i).is_ok())
1232                .map(|(_, s)| s.linear_state.as_mut_slice())
1233                .collect();
1234            graph.read_states(&mut outs);
1235        }
1236        if let Some(rows) = lm_rows {
1237            let mut lg = attention::take_buf(rows.min(self.vocab_size));
1238            graph.read_logits(&mut lg);
1239            lg.resize(self.vocab_size, 0.0);
1240            if let Some(c) = self.final_softcap {
1241                for l in lg.iter_mut() {
1242                    *l = c * (*l / c).tanh();
1243                }
1244            }
1245            self.graph_logits = Some(lg);
1246        }
1247        graph.finish(h);
1248        // Device-attended layers: replay the CPU bookkeeping — append
1249        // the mirror's new K/V row (rope'd on the GPU) into the owner
1250        // cache, then bank this token's Born-importance mass.
1251        for li in dev_attn {
1252            let mut krow = attention::take_buf(nkv * hd);
1253            let mut vrow = attention::take_buf(nkv * hd);
1254            if crate::gpu::kv_mirror_read_last(kv_id, li, nkv, hd, &mut krow, &mut vrow) {
1255                let cache = &mut self.kv_cache.layers[li];
1256                cache.append(&krow, &vrow, &[]);
1257                let n = cache.seq_len;
1258                let mut imp = attention::take_buf(n);
1259                crate::gpu::kv_mirror_take_imp(kv_id, li, &mut imp);
1260                cache.accumulate_imp(&imp);
1261                attention::recycle_buf(&mut imp);
1262            }
1263            attention::recycle_buf(&mut krow);
1264            attention::recycle_buf(&mut vrow);
1265        }
1266        end
1267    }
1268
1269    pub fn new(
1270        tokenizer: Tokenizer,
1271        weights: PipelineWeights,
1272        hidden_size: usize,
1273        intermediate_size: usize,
1274        num_heads: usize,
1275        num_kv_heads: usize,
1276        head_dim: usize,
1277        num_layers: usize,
1278        physical_layers: usize,
1279        loop_final_norm: bool,
1280        vocab_size: usize,
1281        rms_eps: f64,
1282        rope_base: f32,
1283        norm_style: NormStyle,
1284        max_seq_len: usize,
1285        sampler_config: SamplerConfig,
1286    ) -> Self {
1287        let rng = match sampler_config.seed {
1288            Some(s) => SplitMix64::new(s),
1289            None => SplitMix64::from_entropy(),
1290        };
1291        let inv_freq = std::sync::Arc::new(attention::rope_inv_freq(head_dim, rope_base));
1292        let pool = Pool::from_env();
1293        if let Some(p) = &pool {
1294            tracing::info!("worker pool: {} threads", p.n_workers());
1295        }
1296        Self {
1297            gpu_plan: None,
1298            tokenizer: std::sync::Arc::new(tokenizer),
1299            kv_cache: KvCache::new(num_layers, num_kv_heads, head_dim, max_seq_len),
1300            sampler_config,
1301            weights,
1302            hidden_size,
1303            intermediate_size,
1304            num_heads,
1305            num_kv_heads,
1306            head_dim,
1307            num_layers,
1308            physical_layers,
1309            loop_final_norm,
1310            vocab_size,
1311            rms_eps,
1312            rope_base,
1313            norm_style,
1314            rotary_dim: head_dim,
1315            attention_heads_per_layer: None,
1316            vmf_cfg: None,
1317            gdn_cfg: None,
1318            kda_cfg: None,
1319            g3n: None,
1320            dsv4: None,
1321            dsv4_mtp: Vec::new(),
1322            dspark: None,
1323            dspark_pending: Vec::new(),
1324            dspark_hist: Vec::new(),
1325            dspark_real: Vec::new(),
1326            dspark_trunk_picks: Vec::new(),
1327            dspark_exp: Vec::new(),
1328            dspark_draft_ns: 0,
1329            logit_multiplier: None,
1330            cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
1331            kv_history: Vec::new(),
1332            short_conv_cfg: None,
1333            mtp: None,
1334            speculative: std::env::var("CMF_MTP").map(|v| v != "0").unwrap_or(true),
1335            rng,
1336            sampler_scratch: SamplerScratch::default(),
1337            inv_freq,
1338            ws: ForwardScratch::new(hidden_size),
1339            pool,
1340            model: None,
1341            dyn_force_f32: false,
1342            dyn_skill_layers: Vec::new(),
1343            dyn_active: None,
1344            dyn_blend_loaded: false,
1345            dyn_phi_layer: None,
1346            dyn_phi_ema: Vec::new(),
1347            dyn_phi_seen: 0,
1348            dyn_router: None,
1349            o1_cfg: None,
1350            o1_epoch: 0,
1351            o1_flags: Vec::new(),
1352            trace: false,
1353            calib_temp: 1.0,
1354            confidence_on: true,
1355            embed_multiplier: 1.0,
1356            attn_scale: 1.0 / (head_dim as f32).sqrt(),
1357            swa: None,
1358            sliding_layers: None,
1359            inv_freq_local: None,
1360            rotary_dim_local: None,
1361            rope_scale: 1.0,
1362            rope_scale_local: 1.0,
1363            global_attn: None,
1364            inv_freq_global: None,
1365            attn_v_norm: false,
1366            final_softcap: None,
1367            attn_softcap: 0.0,
1368            graph_want_logits: false,
1369            graph_logits: None,
1370            graph_kv_id: {
1371                static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1372                NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
1373            },
1374        }
1375    }
1376
1377    /// Enable/disable per-layer O(1) Nyström attention. Only Full
1378    /// layers are eligible (a linear layer keeps its own operator).
1379    /// Applies to generation (`generate*`/`forward_ids`): the prompt
1380    /// pass stays exact, the seal happens once after prefill, decode
1381    /// runs on the O(1) state. Teacher-forced scoring (`ppl_ids`)
1382    /// intentionally stays exact.
1383    pub fn set_o1(&mut self, cfg: Option<crate::nystrom::O1Cfg>) {
1384        self.o1_flags = match &cfg {
1385            Some(c) => {
1386                let mut flags = c.layer_flags(self.num_layers);
1387                for (li, f) in flags.iter_mut().enumerate() {
1388                    if *f
1389                        && !matches!(
1390                            self.weights.layers[self.phys_layer(li)].attn,
1391                            AttnKind::Full { .. }
1392                        )
1393                    {
1394                        *f = false;
1395                    }
1396                }
1397                flags
1398            }
1399            None => Vec::new(),
1400        };
1401        if let Some(c) = &cfg {
1402            let n = self.o1_flags.iter().filter(|&&f| f).count();
1403            tracing::info!(
1404                "o1 nystrom attention: {n}/{} layer(s), m={} w={} sink={} rect={:?}",
1405                self.num_layers,
1406                c.m,
1407                c.w,
1408                c.sink,
1409                c.rect
1410            );
1411        }
1412        self.o1_cfg = cfg;
1413    }
1414
1415    /// True when at least one layer runs the O(1) kernel.
1416    pub fn o1_active(&self) -> bool {
1417        self.o1_cfg.is_some() && self.o1_flags.iter().any(|&f| f)
1418    }
1419
1420    /// Arm query collection on the o1 layers (fresh prompt pass).
1421    /// Reset the o1 layers to Collecting for a fresh sequence. Pub for the
1422    /// network split: each side runs the o1 lifecycle over ITS OWN layers
1423    /// (begin before prefill, seal at the prefill barrier).
1424    pub fn o1_begin(&mut self) {
1425        if let Some(c) = &self.o1_cfg {
1426            let (m, w, sink, rect) = (c.m, c.w, c.sink, c.rect);
1427            for (li, &f) in self.o1_flags.iter().enumerate() {
1428                if f {
1429                    self.kv_cache.layers[li].o1_begin(m, w, sink, rect);
1430                }
1431            }
1432        }
1433    }
1434
1435    /// Freeze landmarks + skeleton state after the prompt pass and drop
1436    /// the o1 layers' full KV; decode then runs `step()` per token.
1437    /// Pub for the network split (see `o1_begin`).
1438    pub fn o1_seal(&mut self) {
1439        self.o1_epoch = self.o1_epoch.wrapping_add(1);
1440        if self.o1_cfg.is_none() {
1441            return;
1442        }
1443        for li in 0..self.num_layers {
1444            if self.o1_flags.get(li).copied().unwrap_or(false) {
1445                self.kv_cache.layers[li].o1_seal(self.num_heads);
1446            }
1447        }
1448    }
1449
1450    /// Enable/disable the structured per-token telemetry trace (B4).
1451    pub fn set_trace(&mut self, on: bool) {
1452        self.trace = on;
1453    }
1454
1455    /// Replace all request-scoped sampler options and reset the random stream.
1456    /// This is required for deterministic `seed` semantics in pooled servers.
1457    pub fn set_sampler_config(&mut self, config: SamplerConfig) {
1458        self.rng = match config.seed {
1459            Some(seed) => SplitMix64::new(seed),
1460            None => SplitMix64::from_entropy(),
1461        };
1462        self.sampler_config = config;
1463    }
1464
1465    /// Toggle the per-token Born-confidence reduction (a full-vocab
1466    /// softmax each token). `bench --core` turns it off so the timed
1467    /// loop matches llama-bench's core contract; the result's
1468    /// `confidence` vec is empty while off.
1469    pub fn set_confidence(&mut self, on: bool) {
1470        self.confidence_on = on;
1471    }
1472
1473    /// Set the confidence-calibration temperature (B1). Values ≤0 are
1474    /// clamped to raw (1.0).
1475    pub fn set_calib_temp(&mut self, t: f32) {
1476        self.calib_temp = if t > 1e-3 { t } else { 1.0 };
1477    }
1478
1479    /// The active calibration temperature (1.0 = raw Born mass).
1480    pub fn calib_temp(&self) -> f32 {
1481        self.calib_temp
1482    }
1483
1484    /// Partial rotary (Qwen3.5): rotate only the first `rotary_dim` dims;
1485    /// the frequency table is rebuilt over the rotary dims.
1486    pub fn set_rotary(&mut self, rotary_dim: usize, base: f32) {
1487        self.rotary_dim = rotary_dim.min(self.head_dim);
1488        self.inv_freq = std::sync::Arc::new(attention::rope_inv_freq(self.rotary_dim, base));
1489    }
1490
1491    fn attn_cfg(&self, position: usize) -> QwenAttnCfg<'_> {
1492        QwenAttnCfg {
1493            num_heads: self.num_heads,
1494            num_kv_heads: self.num_kv_heads,
1495            head_dim: self.head_dim,
1496            hidden_size: self.hidden_size,
1497            position,
1498            inv_freq: &self.inv_freq,
1499            rotary_dim: self.rotary_dim,
1500            scale: self.attn_scale,
1501            softcap: self.attn_softcap,
1502            window: None,
1503            v_norm: false,
1504            q_norm: None,
1505            k_norm: None,
1506            output_gate: false,
1507            softplus_gate: None,
1508            rope_scale: self.rope_scale,
1509            bias: None,
1510            rms_eps: self.rms_eps,
1511            norm_style: self.norm_style,
1512            pool: self.pool.as_deref(),
1513        }
1514    }
1515
1516    /// Generate text from a plain-text prompt. Streams tokens via `on_token`.
1517    pub fn generate(
1518        &mut self,
1519        prompt: &str,
1520        max_tokens: usize,
1521        task_mask: Option<&TaskMask>,
1522        on_token: Option<TokenCallback>,
1523    ) -> Result<GenerateResult, String> {
1524        let input_ids = self.tokenizer.with_bos(self.tokenizer.encode(prompt));
1525        self.generate_from_ids(&input_ids, max_tokens, task_mask, on_token)
1526    }
1527
1528    /// Generate from prepared token ids (e.g. a chat template).
1529    ///
1530    /// With an MTP head, greedy generation without a task mask takes the
1531    /// speculative path: the MTP module drafts the token after next and
1532    /// the main model verifies both in one fused two-position forward
1533    /// (weights streamed once). The output is EXACTLY the vanilla greedy
1534    /// sequence — a rejected draft is rolled back — MTP only buys speed.
1535    pub fn generate_from_ids(
1536        &mut self,
1537        input_ids: &[u32],
1538        max_tokens: usize,
1539        task_mask: Option<&TaskMask>,
1540        mut on_token: Option<TokenCallback>,
1541    ) -> Result<GenerateResult, String> {
1542        if std::env::var("CMF_TRACE_H").is_ok() {
1543            eprintln!("input_ids: {input_ids:?}");
1544        }
1545        if input_ids.is_empty() {
1546            return Err("empty prompt: nothing to generate from".to_string());
1547        }
1548
1549        // Cross-turn KV reuse: a chat app resends the whole history
1550        // every turn; when the new ids strictly EXTEND what the cache
1551        // already holds, prefill only the tail — turn latency stays
1552        // proportional to the new text instead of the whole session.
1553        // Extension-only (no rollback), so it is exact for every layer
1554        // kind including recurrent state; MTP/o1/task-mask runs keep
1555        // the fresh-sequence path. CMF_KV_REUSE=0 disables.
1556        let reuse_from = {
1557            let on = !std::env::var("CMF_KV_REUSE").is_ok_and(|v| v == "0");
1558            let h = &self.kv_history;
1559            if on
1560                && task_mask.is_none()
1561                && self.mtp.is_none()
1562                && self.o1_cfg.is_none()
1563                && !h.is_empty()
1564                && h.len() < input_ids.len()
1565                && input_ids[..h.len()] == h[..]
1566            {
1567                h.len()
1568            } else {
1569                0
1570            }
1571        };
1572        if reuse_from == 0 {
1573            // Fresh sequence — the cache holds absolute positions.
1574            self.kv_cache.clear();
1575            self.kv_history.clear();
1576            crate::gpu::graph_kv_reset(self.graph_kv_id);
1577        } else if std::env::var("CMF_PREFILL_PROF").is_ok() {
1578            eprintln!(
1579                "kv-reuse: {} of {} prompt positions already cached",
1580                reuse_from,
1581                input_ids.len()
1582            );
1583        }
1584        crate::gpu::graph_race_begin_generation();
1585        self.o1_begin();
1586
1587        // Speculative decode is off under o1: a rejected draft can't be
1588        // rolled back out of the far accumulators / ring window (the
1589        // Nyström insertion is irreversible by design).
1590        // The wgpu token graph owns a device K/V mirror that speculative
1591        // rollback would desync — the two are mutually exclusive.
1592        let graph_on = crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode);
1593        // Graph speculative decode (`CMF_GRAPH_SPEC=1`): the MTP head
1594        // drafts, ONE batched graph submit verifies the whole chain.
1595        //
1596        // It now PAYS on Qwen3.6-27B / RTX 5090 — 51.1 tok/s against a
1597        // plain 49.4 at k=3, medians of three, 89% of drafts accepted,
1598        // and the greedy continuation is byte-identical to the plain
1599        // path. That took the batch matvec sharing its nibble unpack
1600        // across the batch (`CMF_MV_BK=2`); before it, the same round
1601        // measured 43.6, an 11% LOSS, which is what the earlier note
1602        // here described.
1603        //
1604        // Still opt-in. One model's win is not a default: the verify
1605        // rides `gdn_spec_restore` and a batched frame whose numerics
1606        // are the batch kernels', and that has to be shown on more than
1607        // one architecture before every greedy decode takes it.
1608        let graph_spec = self.speculative
1609            && graph_on
1610            && self.mtp.is_some()
1611            && task_mask.is_none()
1612            && !self.o1_active()
1613            && self.sampler_config.temperature < 1e-6
1614            && self.sampler_config.repetition_penalty == 1.0
1615            && std::env::var("CMF_GRAPH_SPEC").is_ok_and(|v| v != "0");
1616        // GDN hybrids sit the fused-pair speculation out by default: the
1617        // recurrence is sequential, so the pair lane cannot parallelize
1618        // (the bench's own Pair line reads fused 1.28x TWO singles on the
1619        // 35B) and the draft's full-vocab head rides on top — measured 2x
1620        // SLOWER end to end (16.1 vs 32.4 tok/s on the 48-core stand).
1621        // CMF_MTP=1 forces it back for study.
1622        let pair_pays = self.gdn_cfg.is_none()
1623            || std::env::var("CMF_MTP").as_deref() == Ok("1");
1624        let spec_active = self.speculative
1625            && self.mtp.is_some()
1626            && task_mask.is_none()
1627            && !self.o1_active()
1628            && ((!graph_on && pair_pays) || graph_spec)
1629            && self.sampler_config.temperature < 1e-6;
1630        // The MTP module is detached during generation so its mutable
1631        // state does not fight the borrow on `self`.
1632        let mut mtp = if spec_active { self.mtp.take() } else { None };
1633        if std::env::var("CMF_MTP_CHAIN_PROBE").is_ok() {
1634            eprintln!(
1635                "mtp-probe gate: spec_active={spec_active} mtp={} speculative={} graph_on={graph_on} temp_ok={}",
1636                mtp.is_some(),
1637                self.speculative,
1638                self.sampler_config.temperature < 1e-6,
1639            );
1640        }
1641        if let Some(m) = &mut mtp {
1642            m.kv.clear();
1643        }
1644        // Dynamic router detached during decode (same borrow trick as MTP).
1645        // Speculative decode and dynamic routing are mutually exclusive
1646        // for now — the fused-pair path doesn't carry per-token φ.
1647        let mut router = if mtp.is_none() {
1648            self.dyn_router.take()
1649        } else {
1650            None
1651        };
1652        if let Some(r) = &mut router {
1653            r.reset(); // active=backbone, matching a fresh overlay
1654            self.dyn_phi_seen = 0; // fresh φ EMA per generation
1655            let _ = self.set_active_skill(None);
1656        }
1657
1658        let mut all_ids = input_ids.to_vec();
1659        let mut generated = 0usize;
1660        let mut finish_reason = "max_tokens".to_string();
1661        let mut drafted = 0usize;
1662        let mut accepted = 0usize;
1663        let mut confidence: Vec<f32> = Vec::new();
1664        let trace_on = self.trace;
1665        let calib_temp = self.calib_temp;
1666        let mut traces: Vec<TokenTrace> = Vec::new();
1667
1668        // ── Prefill: forward each prompt token once, KEEP the last hidden.
1669        //    Dense prefill runs in fused pairs (weights streamed once per
1670        //    two positions — bit-identical to sequential, proven by the
1671        //    pair tests). With MTP: warm the draft head on
1672        //    (hidden_p, token_{p+1}) pairs.
1673        let mut hidden = vec![0.0f32; self.hidden_size];
1674        let mut pos = reuse_from;
1675        // lm_head-in-graph is only sound when the very next logits
1676        // consumer is this loop's own (MTP and skill routing interleave
1677        // other forwards / can swap lm_head between forward and sample).
1678        // CMF_GPU_LMHEAD=0 keeps lm_head off the graph: the token reads back
1679        // the 8 KB hidden instead of ~1 MB of logits, and the head runs on
1680        // the host. A probe for how much of the graph's fixed per-token cost
1681        // is the logits readback (the layer sweep puts that fixed part at
1682        // 3.88 ms of an 18.5 ms frame).
1683        let fuse_lm = mtp.is_none()
1684            && router.is_none()
1685            && std::env::var("CMF_GPU_LMHEAD").as_deref() != Ok("0");
1686        self.graph_logits = None;
1687        self.graph_want_logits = false;
1688        let _tpf = std::time::Instant::now();
1689        let batch_k = std::env::var("CMF_BATCH_K")
1690            .ok()
1691            .and_then(|v| v.parse::<usize>().ok())
1692            .unwrap_or(0);
1693        // DeepSeek-V4 owns a separate hyper-connection stack. Route it
1694        // before the generic prefill choices: those correctly reject an
1695        // empty `weights.layers`, but their final per-position fallback used
1696        // to consume the whole prompt before `dsv4::forward_chunk` could see
1697        // it. The batch implementation therefore existed without a live
1698        // production entry point.
1699        //
1700        // Bounded chunks preserve cancellation responsiveness. Only the
1701        // prompt's final chunk asks for logits; every earlier head projection
1702        // would produce 129 280 values that no caller reads.
1703        while self.dsv4.is_some()
1704            && mtp.is_none()
1705            && pos < input_ids.len()
1706            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
1707        {
1708            let end = (pos + prefill_chunk()).min(input_ids.len());
1709            let ids: Vec<u32> = input_ids[pos..end].to_vec();
1710            let mut lg = Vec::new();
1711            if let Some(b) = &mut self.dsv4 {
1712                let (g, layers, cfg, st) = (&b.0, &b.1, b.2, &mut b.3);
1713                crate::dsv4::forward_chunk(
1714                    g,
1715                    layers,
1716                    &cfg,
1717                    st,
1718                    &ids,
1719                    pos,
1720                    &self.inv_freq,
1721                    self.pool.as_deref(),
1722                    &mut lg,
1723                    end == input_ids.len(),
1724                );
1725            }
1726            if end == input_ids.len() {
1727                self.graph_logits = Some(lg);
1728            }
1729            pos = end;
1730            hidden = vec![0.0; self.hidden_size];
1731        }
1732        // With dynamic routing, prefill sequentially so the φ hook fires
1733        // over the PROMPT — the router enters decode with a warm φ (the
1734        // fused-pair path skips the per-layer φ capture). o1 layers
1735        // collect their query trace in both the single and pair paths.
1736        let dyn_prefill = router.is_some();
1737        // q1 hybrids on Metal: the per-position GPU token graph beats
1738        // the CPU chunk-GEMM (whose wall is the sequential scalar GDN
1739        // recurrence), so prefill goes position-by-position through the
1740        // same graph as decode. Pure-attention models keep the batched
1741        // path — there the chunk-GEMM amortization wins.
1742        let graph_prefill = self.graph_prefill_preferred();
1743        if task_mask.is_none()
1744            && !dyn_prefill
1745            && !graph_prefill
1746            && self.can_prefill_batched()
1747            && self.g3n.is_none()
1748            && input_ids.len() > 2
1749        {
1750            // Production prefill = the same chunked prefill-GEMM that
1751            // bench/PPL measure (roadmap §3 P0: generation used to warm
1752            // the prompt with the slower pair path — the published
1753            // prefill number didn't match real TTFT). MTP warm-up reads
1754            // each position's hidden straight from the chunk result.
1755            let chunk = prefill_chunk();
1756            let hs = self.hidden_size;
1757            while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
1758                let end = (pos + chunk).min(input_ids.len());
1759                let hb = self.prefill_batch(&input_ids[pos..end], pos);
1760                if let Some(m) = &mut mtp {
1761                    let probe: usize = std::env::var("CMF_MTP_CHAIN_PROBE")
1762                        .ok()
1763                        .and_then(|v| v.parse().ok())
1764                        .unwrap_or(0);
1765                    for p in pos..end {
1766                        if p + 1 < input_ids.len() {
1767                            if probe >= 1 && p + 2 < input_ids.len() {
1768                                // Teacher-forced chain acceptance (see the
1769                                // tail loop's twin): the warm-up row stays,
1770                                // the chain's rows roll back.
1771                                let (d1, mut hx) = self.mtp_step_h(
1772                                    m,
1773                                    &hb[(p - pos) * hs..(p - pos + 1) * hs],
1774                                    input_ids[p + 1],
1775                                    p,
1776                                );
1777                                let mut ok = d1 == input_ids[p + 2];
1778                                Self::chain_probe_note(0, ok);
1779                                let mut d_prev = d1;
1780                                let mut extra = 0usize;
1781                                for j in 1..probe {
1782                                    if p + 2 + j >= input_ids.len() {
1783                                        break;
1784                                    }
1785                                    let (dj, hj) =
1786                                        self.mtp_step_h(m, &hx, d_prev, p + 1 + j);
1787                                    extra += 1;
1788                                    ok = ok && dj == input_ids[p + 2 + j];
1789                                    Self::chain_probe_note(j, ok);
1790                                    d_prev = dj;
1791                                    hx = hj;
1792                                }
1793                                m.kv.truncate_last(extra);
1794                            } else {
1795                                let _ = self.mtp_step(
1796                                    m,
1797                                    &hb[(p - pos) * hs..(p - pos + 1) * hs],
1798                                    input_ids[p + 1],
1799                                    p,
1800                                );
1801                            }
1802                        }
1803                    }
1804                }
1805                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
1806                pos = end;
1807            }
1808        }
1809        let pair_off = std::env::var("CMF_PAIR").is_ok_and(|v| v == "0");
1810        if task_mask.is_none()
1811            && !dyn_prefill
1812            && !graph_prefill
1813            && !pair_off
1814            && self.pair_supported()
1815        {
1816            while pos + 1 < input_ids.len()
1817                && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
1818            {
1819                let e1 = self.embed_single(input_ids[pos]);
1820                let e2 = self.embed_single(input_ids[pos + 1]);
1821                let (h1, h2) = self.forward_pair(&e1, &e2, pos);
1822                // Both prefill tokens are real → commit lane-2 states.
1823                self.commit_linear_scratch();
1824                if let Some(m) = &mut mtp {
1825                    let _ = self.mtp_step(m, &h1, input_ids[pos + 1], pos);
1826                    if pos + 2 < input_ids.len() {
1827                        let probe: usize = std::env::var("CMF_MTP_CHAIN_PROBE")
1828                            .ok()
1829                            .and_then(|v| v.parse().ok())
1830                            .unwrap_or(0);
1831                        if probe >= 1 && pos + 3 < input_ids.len() {
1832                            // Same teacher-forced chain table as the tail
1833                            // loop below, fed from the pair path that owns
1834                            // most prefill positions.
1835                            let (d1, mut hx) =
1836                                self.mtp_step_h(m, &h2, input_ids[pos + 2], pos + 1);
1837                            let mut ok = d1 == input_ids[pos + 3];
1838                            Self::chain_probe_note(0, ok);
1839                            let mut d_prev = d1;
1840                            let mut extra = 0usize;
1841                            for j in 1..probe {
1842                                if pos + 3 + j >= input_ids.len() {
1843                                    break;
1844                                }
1845                                let (dj, hj) =
1846                                    self.mtp_step_h(m, &hx, d_prev, pos + 2 + j);
1847                                extra += 1;
1848                                ok = ok && dj == input_ids[pos + 3 + j];
1849                                Self::chain_probe_note(j, ok);
1850                                d_prev = dj;
1851                                hx = hj;
1852                            }
1853                            m.kv.truncate_last(extra);
1854                        } else {
1855                            let _ = self.mtp_step(m, &h2, input_ids[pos + 2], pos + 1);
1856                        }
1857                    }
1858                }
1859                hidden = h2;
1860                pos += 2;
1861            }
1862        }
1863        // Batched GPU prefill for the wgpu decode graph (GDN hybrids): K prompt
1864        // positions per submit — projections/FFN as GEMMs (weight once per K),
1865        // attention/GDN looped inside — instead of one whole-graph submit per
1866        // position. Falls through to the per-position graph on any refusal.
1867        // Batched prefill is opt-in (CMF_BATCH_K>0). Default 0 = per-position
1868        // graph prefill. (Steady-state decode is provably identical either way —
1869        // token-graph submit and lm_head both unchanged — so this only trades
1870        // prefill wall.)
1871        if batch_k > 0
1872            && graph_prefill
1873            && task_mask.is_none()
1874            && !self.o1_active()
1875            && mtp.is_none()
1876            && !dyn_prefill
1877            && pos + 1 < input_ids.len()
1878        {
1879            let hs = self.hidden_size;
1880            let chunk = batch_k;
1881            while pos < input_ids.len() {
1882                let end = (pos + chunk).min(input_ids.len());
1883                let bk = end - pos;
1884                let mut hiddens = vec![0f32; bk * hs];
1885                for (j, &id) in input_ids[pos..end].iter().enumerate() {
1886                    hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
1887                }
1888                let positions: Vec<usize> = (pos..end).collect();
1889                let t_chunk = std::time::Instant::now();
1890                let ok_b = self.try_batch_graph_wgpu(&mut hiddens, &positions, bk, None);
1891                if std::env::var("CMF_GRAPH_PROF").is_ok() {
1892                    let ms = t_chunk.elapsed().as_secs_f64() * 1000.0;
1893                    eprintln!(
1894                        "batch-chunk: k={bk} ok={ok_b} {ms:.1} ms ({:.1} tok/s)",
1895                        bk as f64 / (ms / 1000.0)
1896                    );
1897                }
1898                {
1899                    use std::sync::atomic::{AtomicBool, Ordering};
1900                    static SAID: AtomicBool = AtomicBool::new(false);
1901                    if !SAID.swap(true, Ordering::Relaxed) {
1902                        if ok_b {
1903                            tracing::info!("batched prefill: ACTIVE (k={bk})");
1904                        } else {
1905                            tracing::warn!("batched prefill declined — per-position graph");
1906                        }
1907                    }
1908                }
1909                if ok_b {
1910                    hidden.copy_from_slice(&hiddens[(bk - 1) * hs..]);
1911                    pos = end;
1912                } else {
1913                    break; // unsupported → per-position graph handles the rest
1914                }
1915            }
1916        }
1917        while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
1918            self.graph_want_logits = fuse_lm && pos + 1 == input_ids.len();
1919            hidden = self.forward_layers(&self.embed_single(input_ids[pos]), pos, task_mask);
1920            if let Some(m) = &mut mtp {
1921                if pos + 1 < input_ids.len() {
1922                    // `CMF_MTP_CHAIN_PROBE=k`: teacher-forced acceptance of a
1923                    // CHAINED draft — iterate the head on its own hidden k
1924                    // deep and score every depth against the prompt's real
1925                    // continuation. The economics of a k-token speculative
1926                    // round stand or fall on this table.
1927                    let probe: usize = std::env::var("CMF_MTP_CHAIN_PROBE")
1928                        .ok()
1929                        .and_then(|v| v.parse().ok())
1930                        .unwrap_or(0);
1931                    if probe >= 1 && pos + 2 < input_ids.len() {
1932                        let (d1, mut hx) = self.mtp_step_h(m, &hidden, input_ids[pos + 1], pos);
1933                        let mut ok = d1 == input_ids[pos + 2];
1934                        Self::chain_probe_note(0, ok);
1935                        let mut d_prev = d1;
1936                        let mut extra = 0usize;
1937                        for j in 1..probe {
1938                            if pos + 2 + j >= input_ids.len() {
1939                                break;
1940                            }
1941                            let (dj, hj) =
1942                                self.mtp_step_h(m, &hx, d_prev, pos + 1 + j);
1943                            extra += 1;
1944                            ok = ok && dj == input_ids[pos + 2 + j];
1945                            Self::chain_probe_note(j, ok);
1946                            d_prev = dj;
1947                            hx = hj;
1948                        }
1949                        // The chain's rows are speculation, not the prompt —
1950                        // keep only the warmup row the plain path would add.
1951                        m.kv.truncate_last(extra);
1952                    } else {
1953                        let _ = self.mtp_step(m, &hidden, input_ids[pos + 1], pos);
1954                    }
1955                }
1956            }
1957            pos += 1;
1958        }
1959        if std::env::var("CMF_PREFILL_PROF").is_ok() {
1960            eprintln!(
1961                "prefill: {} tokens in {:.1} ms (batch_k={batch_k})",
1962                input_ids.len(),
1963                _tpf.elapsed().as_secs_f64() * 1000.0
1964            );
1965        }
1966        // Cancelled mid-prefill: the cache holds a partial prompt —
1967        // drop the reuse history and return an empty generation.
1968        if self
1969            .cancel
1970            .swap(false, std::sync::atomic::Ordering::Relaxed)
1971        {
1972            self.kv_history.clear();
1973            if let Some(m) = mtp {
1974                self.mtp = Some(m);
1975            }
1976            return Ok(GenerateResult {
1977                text: String::new(),
1978                token_ids: Vec::new(),
1979                prompt_tokens: input_ids.len(),
1980                tokens_generated: 0,
1981                finish_reason: "cancelled".to_string(),
1982                mtp_drafted: 0,
1983                mtp_accepted: 0,
1984                token_confidence: Vec::new(),
1985                traces: Vec::new(),
1986            });
1987        }
1988
1989        // Prompt absorbed → freeze the o1 layers' skeletons; from here
1990        // every decode step on those layers is O(W + m·dv + m²).
1991        self.o1_seal();
1992
1993        // Commit one token: push, check EOS, stream. Returns false = stop.
1994        macro_rules! commit {
1995            ($id:expr) => {{
1996                all_ids.push($id);
1997                generated += 1;
1998                if self.tokenizer.is_eos($id) {
1999                    finish_reason = "stop".to_string();
2000                    false
2001                } else {
2002                    let token_text = self.tokenizer.decode_token($id);
2003                    let mut go = true;
2004                    if let Some(ref mut cb) = on_token {
2005                        if !cb(&token_text) {
2006                            finish_reason = "cancelled".to_string();
2007                            go = false;
2008                        }
2009                    }
2010                    go
2011                }
2012            }};
2013        }
2014
2015        // ── Decode ──
2016        let mut next_pos = input_ids.len();
2017        'decode: while generated < max_tokens {
2018            if self
2019                .cancel
2020                .swap(false, std::sync::atomic::Ordering::Relaxed)
2021            {
2022                finish_reason = "cancelled".to_string();
2023                break 'decode;
2024            }
2025            let mut logits = match self.graph_logits.take() {
2026                Some(lg) => lg,
2027                None => {
2028                    inference::rms_norm_into(
2029                        &hidden,
2030                        &self.weights.final_norm,
2031                        self.rms_eps,
2032                        self.norm_style,
2033                        &mut self.ws.n1,
2034                    );
2035                    self.lm_head_forward(&self.ws.n1)
2036                }
2037            };
2038            let t_next = sampler::sample_with_scratch(
2039                &logits,
2040                &self.sampler_config,
2041                &all_ids,
2042                &mut self.rng,
2043                &mut self.sampler_scratch,
2044            );
2045            if self.confidence_on {
2046                confidence.push(top1_prob_t(&logits, t_next, calib_temp));
2047            }
2048            attention::recycle_buf(&mut logits);
2049            if trace_on {
2050                // active_skill = the overlay in force while this token was
2051                // generated; recon/switched are filled after the post-emit
2052                // routing eval below (freshest coherence for this token).
2053                let skill = router.as_ref().and_then(|r| r.active_id());
2054                traces.push(TokenTrace {
2055                    t: generated,
2056                    token_id: t_next,
2057                    confidence: confidence.last().copied().unwrap_or(0.0),
2058                    active_skill: skill,
2059                    recon: None,
2060                    switched: false,
2061                });
2062            }
2063            if !commit!(t_next) {
2064                break 'decode;
2065            }
2066            if generated >= max_tokens {
2067                break 'decode;
2068            }
2069
2070            if self.kv_cache.needs_eviction() {
2071                let keep = (self.kv_cache.max_seq_len / 2).max(1);
2072                self.kv_cache.evict(keep);
2073            }
2074
2075            match &mut mtp {
2076                // ── Graph speculation: chain-draft, batch-verify on device ──
2077                #[cfg(feature = "gpu")]
2078                Some(m) if graph_spec && generated + 1 < max_tokens && next_pos > 0 => {
2079                    if let Some((extra, n_pos, new_h)) = self.graph_spec_step(
2080                        m,
2081                        &hidden,
2082                        t_next,
2083                        next_pos,
2084                        &mut drafted,
2085                        &mut accepted,
2086                    ) {
2087                        next_pos = n_pos;
2088                        hidden = new_h;
2089                        let mut stopped = false;
2090                        for &id in &extra {
2091                            if self.confidence_on {
2092                                confidence.push(0.0);
2093                            }
2094                            if !commit!(id) {
2095                                stopped = true;
2096                                break;
2097                            }
2098                        }
2099                        if stopped {
2100                            break 'decode;
2101                        }
2102                        continue 'decode;
2103                    }
2104                    // Declined (batch graph refused): plain forward below.
2105                    hidden = self.forward_layers(&self.embed_single(t_next), next_pos, task_mask);
2106                    next_pos += 1;
2107                    continue 'decode;
2108                }
2109                // ── Speculative: draft t+2, verify in a fused pair ──
2110                Some(m) if !graph_spec && generated + 1 < max_tokens => {
2111                    let draft = self.mtp_step(m, &hidden, t_next, next_pos - 1);
2112                    drafted += 1;
2113                    let emb1 = self.embed_single(t_next);
2114                    let emb2 = self.embed_single(draft);
2115                    let (h1, h2) = self.forward_pair(&emb1, &emb2, next_pos);
2116
2117                    inference::rms_norm_into(
2118                        &h1,
2119                        &self.weights.final_norm,
2120                        self.rms_eps,
2121                        self.norm_style,
2122                        &mut self.ws.n1,
2123                    );
2124                    let mut logits1 = self.lm_head_forward(&self.ws.n1);
2125                    let t_after = sampler::sample_with_scratch(
2126                        &logits1,
2127                        &self.sampler_config,
2128                        &all_ids,
2129                        &mut self.rng,
2130                        &mut self.sampler_scratch,
2131                    );
2132                    if self.confidence_on {
2133                        confidence.push(top1_prob_t(&logits1, t_after, calib_temp));
2134                    }
2135                    attention::recycle_buf(&mut logits1);
2136                    if trace_on {
2137                        // Speculative decode is mutually exclusive with
2138                        // dynamic routing (router is None here) — no skill.
2139                        traces.push(TokenTrace {
2140                            t: generated,
2141                            token_id: t_after,
2142                            confidence: confidence.last().copied().unwrap_or(0.0),
2143                            active_skill: None,
2144                            recon: None,
2145                            switched: false,
2146                        });
2147                    }
2148                    let stop = !commit!(t_after);
2149
2150                    if t_after == draft {
2151                        accepted += 1;
2152                        self.commit_linear_scratch();
2153                        let _ = self.mtp_step(m, &h1, t_after, next_pos);
2154                        hidden = h2;
2155                        next_pos += 2;
2156                    } else {
2157                        // The draft lane is wrong: roll its KV entry back.
2158                        for layer in &mut self.kv_cache.layers {
2159                            layer.truncate_last(1);
2160                        }
2161                        if !stop {
2162                            let _ = self.mtp_step(m, &h1, t_after, next_pos);
2163                            hidden = self.forward_layers(
2164                                &self.embed_single(t_after),
2165                                next_pos + 1,
2166                                None,
2167                            );
2168                        }
2169                        next_pos += 2;
2170                    }
2171                    if stop {
2172                        break 'decode;
2173                    }
2174                }
2175                // ── Vanilla: forward the sampled token ──
2176                _ => {
2177                    // ── DeepSeek-V4 speculative decode (CMF_DSV4_SPEC=1):
2178                    // draft five on the card, verify batched, commit the
2179                    // accepted prefix. Greedy only; a rejected token's state
2180                    // is restored and replayed, so output equals the walk. ──
2181                    #[cfg(feature = "gpu")]
2182                    if Self::dsv4_spec_on() && self.dsv4.is_some() {
2183                        static SAID: std::sync::Once = std::sync::Once::new();
2184                        SAID.call_once(|| {
2185                            eprintln!(
2186                                "dsv4-spec гейт: mtp={} mask={} router={} trace={} temp={} rep={} ",
2187                                !self.dsv4_mtp.is_empty(),
2188                                task_mask.is_none(),
2189                                router.is_none(),
2190                                !trace_on,
2191                                self.sampler_config.temperature < 1e-6,
2192                                self.sampler_config.repetition_penalty == 1.0,
2193                            );
2194                        });
2195                    }
2196                    #[cfg(feature = "gpu")]
2197                    if Self::dsv4_spec_on()
2198                        && self.dsv4.is_some()
2199                        && !self.dsv4_mtp.is_empty()
2200                        && task_mask.is_none()
2201                        && router.is_none()
2202                        && !trace_on
2203                        && self.sampler_config.temperature < 1e-6
2204                        && self.sampler_config.repetition_penalty == 1.0
2205                        && generated + 1 < max_tokens
2206                        && all_ids.len() >= 2
2207                    {
2208                        let tip_token = all_ids[all_ids.len() - 2];
2209                        if let Some((extra, n_pos)) = self.dsv4_spec_step(
2210                            tip_token,
2211                            t_next,
2212                            next_pos,
2213                            &mut drafted,
2214                            &mut accepted,
2215                        ) {
2216                            next_pos = n_pos;
2217                            let mut stopped = false;
2218                            for &id in &extra {
2219                                if self.confidence_on {
2220                                    confidence.push(0.0);
2221                                }
2222                                if !commit!(id) {
2223                                    stopped = true;
2224                                    break;
2225                                }
2226                            }
2227                            if stopped {
2228                                break 'decode;
2229                            }
2230                            continue 'decode;
2231                        }
2232                    }
2233                    self.graph_want_logits = fuse_lm;
2234                    // Greedy burst (CMF_MULTISTEP, default 8, 1 = off): while
2235                    // nothing observes per-token state — pure argmax sampling,
2236                    // no router/trace/confidence/mask — decode k tokens per
2237                    // submit and commit them wholesale. The trailing normal
2238                    // forward leaves logits for the loop top, as always.
2239                    let mut t_fwd = t_next;
2240                    let pure_greedy = self.sampler_config.temperature < 1e-6
2241                        && self.sampler_config.repetition_penalty == 1.0
2242                        && self.sampler_config.suppress_tokens.is_empty();
2243                    // Off by default: at every k the burst measured at or
2244                    // below the plain path on this graph shape (k=1 loses
2245                    // the argmax dispatches vs a 1 MB readback, k>=8 loses
2246                    // inter-step drains vs the saved sync). Experimental.
2247                    let burst_k = std::env::var("CMF_MULTISTEP")
2248                        .ok()
2249                        .and_then(|v| v.parse::<usize>().ok())
2250                        .unwrap_or(0);
2251                    if pure_greedy
2252                        && burst_k >= 1
2253                        && fuse_lm
2254                        && task_mask.is_none()
2255                        && router.is_none()
2256                        && !trace_on
2257                        && !self.confidence_on
2258                    {
2259                        let mut stopped = false;
2260                        loop {
2261                            let room = max_tokens.saturating_sub(generated);
2262                            if room <= 2 {
2263                                break;
2264                            }
2265                            let k = burst_k.min(room - 1);
2266                            if k < 1 {
2267                                break;
2268                            }
2269                            let Some(ids) = self.try_multi_burst(t_fwd, next_pos, k) else {
2270                                break;
2271                            };
2272                            next_pos += k;
2273                            for &id in &ids {
2274                                if !commit!(id) {
2275                                    stopped = true;
2276                                    break;
2277                                }
2278                            }
2279                            if stopped {
2280                                break;
2281                            }
2282                            t_fwd = *ids.last().unwrap();
2283                        }
2284                        if stopped {
2285                            break 'decode;
2286                        }
2287                    }
2288                    hidden = self.forward_layers(&self.embed_single(t_fwd), next_pos, task_mask);
2289                    next_pos += 1;
2290                    // Dynamic routing: the forward updated φ; ask the
2291                    // router whether to switch skills before the next token.
2292                    if let Some(r) = &mut router {
2293                        let phi = self.dyn_phi_ema.clone();
2294                        let decision = r.step(&phi, generated);
2295                        if let Some(new_active) = decision {
2296                            let _ = self.set_active_skill(new_active);
2297                        }
2298                        // Backfill this token's coherence + switch flag from
2299                        // the just-run eval (freshest measured values).
2300                        if trace_on {
2301                            if let Some(last) = traces.last_mut() {
2302                                let e = r.last_best_e();
2303                                last.recon = e.is_finite().then_some(e);
2304                                last.switched = decision.is_some();
2305                            }
2306                        }
2307                    }
2308                }
2309            }
2310        }
2311
2312        self.graph_want_logits = false;
2313        self.graph_logits = None;
2314        // Restore backbone overlay and re-attach the router for reuse.
2315        if router.is_some() {
2316            let _ = self.set_active_skill(None);
2317        }
2318        self.dyn_router = router.or(self.dyn_router.take());
2319        self.mtp = mtp.or(self.mtp.take());
2320
2321        let output_ids = &all_ids[input_ids.len()..];
2322        // Forwarded = prompt + all generated but the LAST sampled token
2323        // (emitted without being fed back). Exact only without MTP —
2324        // reuse is gated off when MTP is active.
2325        let forwarded = input_ids.len() + output_ids.len().saturating_sub(1);
2326        self.kv_history = all_ids[..forwarded.min(all_ids.len())].to_vec();
2327        confidence.truncate(output_ids.len()); // guard against any overshoot
2328        traces.truncate(output_ids.len());
2329        Ok(GenerateResult {
2330            text: self.tokenizer.decode(output_ids),
2331            token_ids: output_ids.to_vec(),
2332            prompt_tokens: input_ids.len(),
2333            tokens_generated: generated,
2334            finish_reason,
2335            mtp_drafted: drafted,
2336            mtp_accepted: accepted,
2337            token_confidence: confidence,
2338            traces,
2339        })
2340    }
2341
2342    /// One MTP step: feed `(hidden_p, token_{p+1})` into the draft head,
2343    /// advance its KV cache at position `p`, return the drafted token
2344    /// for position `p+2`.
2345    fn mtp_step(
2346        &mut self,
2347        m: &mut MtpModule,
2348        hidden: &[f32],
2349        next_token: u32,
2350        position: usize,
2351    ) -> u32 {
2352        self.mtp_step_h(m, hidden, next_token, position).0
2353    }
2354
2355    /// Tally for `CMF_MTP_CHAIN_PROBE`: per depth, how often the CHAIN is
2356    /// still an exact prefix of the real continuation. Printed every 128
2357    /// depth-0 samples so a killed run still shows its table.
2358    fn chain_probe_note(depth: usize, prefix_ok: bool) {
2359        use std::sync::Mutex;
2360        static T: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
2361        let mut t = T.lock().unwrap();
2362        if t.len() <= depth {
2363            t.resize(depth + 1, (0, 0));
2364        }
2365        t[depth].0 += 1;
2366        t[depth].1 += prefix_ok as u64;
2367        if depth == 0 && t[0].0 % 128 == 0 {
2368            let line: Vec<String> = t
2369                .iter()
2370                .enumerate()
2371                .map(|(d, (n, k))| format!("d{}={:.0}%({n})", d + 1, 100.0 * *k as f64 / (*n).max(1) as f64))
2372                .collect();
2373            eprintln!("mtp-chain: {}", line.join(" "));
2374        }
2375    }
2376
2377    /// `mtp_step` that also hands back the block's own output hidden — the
2378    /// state a CHAINED draft feeds the next step, the way a multi-token
2379    /// speculative round iterates the head on itself.
2380    fn mtp_step_h(
2381        &mut self,
2382        m: &mut MtpModule,
2383        hidden: &[f32],
2384        next_token: u32,
2385        position: usize,
2386    ) -> (u32, Vec<f32>) {
2387        // fc concat order is [enorm(embed); hnorm(hidden)] — EMBEDDING
2388        // FIRST. Verified by the oracle (converter/mtp_oracle.py):
2389        // [emb;hid] → 45.8% acceptance, [hid;emb] → 0.00%.
2390        let e = self.embed_single(next_token);
2391        let mut cat = vec![0.0f32; 2 * self.hidden_size];
2392        let (cat_e, cat_h) = cat.split_at_mut(self.hidden_size);
2393        inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
2394        inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
2395        let mut x = vec![0.0f32; self.hidden_size];
2396        m.eh_proj.matvec(&cat, &mut x, self.pool.as_deref());
2397
2398        // One standard transformer block over the MTP's own cache.
2399        let lw = &m.layer;
2400        inference::rms_norm_into(
2401            &x,
2402            &lw.input_norm,
2403            self.rms_eps,
2404            self.norm_style,
2405            &mut self.ws.n1,
2406        );
2407        let attn = match &lw.attn {
2408            // MLA models carry no MTP head; this path cannot see them.
2409            AttnKind::Mla(_) => unreachable!("MLA has no MTP/pair path"),
2410            AttnKind::Kda(_) => unreachable!("KDA has no MTP/pair path"),
2411            AttnKind::Full {
2412                wq,
2413                wk,
2414                wv,
2415                wo,
2416                q_norm,
2417                k_norm,
2418                output_gate,
2419                softplus_gate,
2420                bias,
2421            } => {
2422                let mut cfg = self.attn_cfg(position);
2423                cfg.q_norm = q_norm.as_deref();
2424                cfg.k_norm = k_norm.as_deref();
2425                cfg.output_gate = *output_gate;
2426                cfg.softplus_gate = softplus_gate
2427                    .as_ref()
2428                    .map(|(gate, per_head)| (gate, *per_head));
2429                cfg.bias = bias
2430                    .as_ref()
2431                    .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice()));
2432                attention::qwen_attention(&self.ws.n1, wq, wk, wv, wo, &mut m.kv, &cfg)
2433            }
2434            AttnKind::Linear(_) | AttnKind::LinearGdn(_) | AttnKind::ShortConv(_) => {
2435                unreachable!("MTP block is full attention")
2436            }
2437        };
2438        for (i, &a) in attn.iter().enumerate() {
2439            x[i] += a;
2440        }
2441        inference::rms_norm_into(
2442            &x,
2443            &lw.post_norm,
2444            self.rms_eps,
2445            self.norm_style,
2446            &mut self.ws.p1,
2447        );
2448        let ffn = ffn_forward(&lw.ffn, &self.ws.p1, self.pool.as_deref(), None);
2449        for (i, &f) in ffn.iter().enumerate() {
2450            x[i] += f;
2451        }
2452
2453        inference::rms_norm_into(
2454            &x,
2455            &m.final_norm,
2456            self.rms_eps,
2457            self.norm_style,
2458            &mut self.ws.n1,
2459        );
2460        let mut lg = self.lm_head_forward(&self.ws.n1);
2461        let draft = sampler::argmax(&lg);
2462        attention::recycle_buf(&mut lg);
2463        (draft, x)
2464    }
2465
2466    /// The MTP block alone — advance its KV with a (hidden, token) pair the
2467    /// verify just proved, without paying the head. What keeps the draft's
2468    /// attention context warm between speculative rounds.
2469    fn mtp_warm(&mut self, m: &mut MtpModule, hidden: &[f32], next_token: u32, position: usize) {
2470        let e = self.embed_single(next_token);
2471        let mut cat = vec![0.0f32; 2 * self.hidden_size];
2472        let (cat_e, cat_h) = cat.split_at_mut(self.hidden_size);
2473        inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
2474        inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
2475        let mut x = vec![0.0f32; self.hidden_size];
2476        m.eh_proj.matvec(&cat, &mut x, self.pool.as_deref());
2477        inference::rms_norm_into(&x, &m.layer.input_norm, self.rms_eps, self.norm_style, &mut self.ws.n1);
2478        let attn = match &m.layer.attn {
2479            AttnKind::Full { wq, wk, wv, wo, q_norm, k_norm, output_gate, softplus_gate, bias } => {
2480                let mut cfg = self.attn_cfg(position);
2481                cfg.q_norm = q_norm.as_deref();
2482                cfg.k_norm = k_norm.as_deref();
2483                cfg.output_gate = *output_gate;
2484                cfg.softplus_gate = softplus_gate.as_ref().map(|(g, p)| (g, *p));
2485                cfg.bias = bias.as_ref().map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice()));
2486                attention::qwen_attention(&self.ws.n1, wq, wk, wv, wo, &mut m.kv, &cfg)
2487            }
2488            _ => return,
2489        };
2490        let _ = attn;
2491    }
2492
2493    /// Speculative decode ON the wgpu whole-token graph: draft k with the
2494    /// MTP head, verify all of them plus the tip in ONE batched graph
2495    /// submit whose tail folds the head, commit the accepted prefix and
2496    /// roll the GDN state back to the last real position. Greedy only —
2497    /// output equals the plain graph's token for token, the way the DSV4
2498    /// verify equals the walk.
2499    #[cfg(feature = "gpu")]
2500    #[allow(clippy::too_many_arguments)]
2501    fn graph_spec_step(
2502        &mut self,
2503        m: &mut MtpModule,
2504        hidden: &[f32],
2505        t_next: u32,
2506        next_pos: usize,
2507        drafted: &mut usize,
2508        accepted: &mut usize,
2509    ) -> Option<(Vec<u32>, usize, Vec<f32>)> {
2510        // 3 is the measured optimum on Qwen3.6-27B / RTX 5090 (medians
2511        // of three, greedy): 51.1 tok/s against a plain 49.4, where k=2
2512        // gives 46.1, k=4 50.0, k=5 47.4, k=6 45.2. Acceptance is 89-91%
2513        // throughout — what turns the curve over is the verify, which
2514        // costs ~7.4 ms per extra position, and the draft ~3 ms a step.
2515        let k_spec: usize = std::env::var("CMF_GRAPH_SPEC_K")
2516            .ok()
2517            .and_then(|v| v.parse().ok())
2518            .filter(|&v| (1..=8).contains(&v))
2519            .unwrap_or(3);
2520        if next_pos == 0 {
2521            return None;
2522        }
2523        let t_round = std::time::Instant::now();
2524        // Submissions per phase — and they say where the round's money is.
2525        // Qwen3.6-27B on an RTX 5090, k=3:
2526        //
2527        //   draft   9.3 ms / 12 submissions   (four per MTP step)
2528        //   verify 52.8 ms /  1               (the batched graph)
2529        //   commit  5.4 ms /  6               (two per warm)
2530        //
2531        // The verify is already one submit. The draft's own work is 834 MB
2532        // a step — 0.8 ms at this card's measured 1056 GB/s — against 3.1
2533        // ms measured, so ~0.58 ms of every step is round trip, not
2534        // arithmetic, and the same holds for the warms. Eighteen round
2535        // trips a round at roughly half a millisecond each is ~11 ms of a
2536        // 68 ms round: fusing the MTP block into ONE submit the way the
2537        // trunk already is projects to ~64 tok/s against today's 50.9.
2538        // That is the largest measured item left on this path.
2539        let subs = || crate::gpu_wgpu::SUBMITS.load(std::sync::atomic::Ordering::Relaxed);
2540        let sub0 = subs();
2541        // Draft the chain: first from the trunk's tip hidden, then the head
2542        // iterating on itself. Rows land in the MTP KV; the chain rows past
2543        // the first are speculation over speculative state and roll back
2544        // below, replaced by verified pairs.
2545        let mut drafts = Vec::with_capacity(k_spec);
2546        let (d1, mut hx) = self.mtp_step_h(m, hidden, t_next, next_pos - 1);
2547        drafts.push(d1);
2548        for j in 1..k_spec {
2549            let (dj, hj) = self.mtp_step_h(m, &hx, drafts[j - 1], next_pos - 1 + j);
2550            drafts.push(dj);
2551            hx = hj;
2552        }
2553        *drafted += k_spec;
2554        let t_draft = t_round.elapsed();
2555        let sub_draft = subs();
2556        // Verify batch: [t_next, d1 .. d_{k-1}] at next_pos.. — every row's
2557        // logits come back from the graph's own head.
2558        let b = k_spec + 1;
2559        let mut hiddens = vec![0.0f32; b * self.hidden_size];
2560        for (i, &t) in std::iter::once(&t_next).chain(drafts.iter()).enumerate() {
2561            let e = self.embed_single(t);
2562            hiddens[i * self.hidden_size..(i + 1) * self.hidden_size].copy_from_slice(&e);
2563        }
2564        let positions: Vec<usize> = (next_pos..next_pos + b).collect();
2565        let (lm_gw, lm_rows) = {
2566            let (_, i, kind, rs) = self.weights.lm_head.graph_weight()?;
2567            (
2568                crate::gpu::GraphW { idx: i, kind, row_scale: rs, data: &[] },
2569                self.weights.lm_head.rows(),
2570            )
2571        };
2572        let mut logits = Vec::new();
2573        let final_norm = self.weights.final_norm.clone();
2574        let ok = self.try_batch_graph_wgpu(
2575            &mut hiddens,
2576            &positions,
2577            b,
2578            Some(crate::gpu::SpecTail {
2579                lm: lm_gw,
2580                lm_rows,
2581                final_norm: &final_norm,
2582                logits_out: &mut logits,
2583            }),
2584        );
2585        if !ok {
2586            // Roll the draft rows back out of the MTP cache and decline —
2587            // the caller runs the plain path, nothing has changed.
2588            m.kv.truncate_last(k_spec);
2589            return None;
2590        }
2591        let t_verify = t_round.elapsed();
2592        let sub_verify = subs();
2593        // Acceptance: row i's argmax is the trunk's token after input i.
2594        let ids: Vec<u32> = (0..b)
2595            .map(|i| sampler::argmax(&logits[i * lm_rows..(i + 1) * lm_rows]))
2596            .collect();
2597        let mut a = 0usize;
2598        while a < k_spec && ids[a] == drafts[a] {
2599            a += 1;
2600        }
2601        // a fully-accepted round needs no restore: every input was real.
2602        if a + 1 < b {
2603            crate::gpu::gdn_spec_restore(self.graph_kv_id, a);
2604        }
2605        *accepted += a;
2606        // MTP cache: keep the first draft row (its inputs were real), drop
2607        // the chain's, then append the verified pairs the round produced.
2608        // Each of those is a whole MTP block on the per-op path and they
2609        // cost 5.8 ms of a 69 ms round at k=3 — a third of what the
2610        // round's own draft costs. PRICED, and they earn it: skipping
2611        // them (`CMF_SPEC_WARM=0`) drops acceptance from 89% to 81% at
2612        // k=3 and 85% to 74% at k=4, and the tok/s goes nowhere at k=3
2613        // (50.3 against 50.5) and backwards at k=4 (48.1 against 50.1).
2614        // The knob stays so the next person can re-price it after the
2615        // warms are batched instead of assuming either way.
2616        m.kv.truncate_last(k_spec.saturating_sub(1));
2617        let warm_off = std::env::var("CMF_SPEC_WARM").is_ok_and(|v| v == "0");
2618        if !warm_off {
2619            for j in 0..a {
2620                let row = &hiddens[j * self.hidden_size..(j + 1) * self.hidden_size];
2621                let row = row.to_vec();
2622                self.mtp_warm(m, &row, ids[j], next_pos + j);
2623            }
2624        }
2625        // The sampler's contract: logits of the LAST verified position.
2626        let mut row = logits[a * lm_rows..(a + 1) * lm_rows].to_vec();
2627        row.resize(self.vocab_size, 0.0);
2628        if let Some(c) = self.final_softcap {
2629            for l in row.iter_mut() {
2630                *l = c * (*l / c).tanh();
2631            }
2632        }
2633        self.graph_logits = Some(row);
2634        let new_hidden = hiddens[a * self.hidden_size..(a + 1) * self.hidden_size].to_vec();
2635        // Three phases, not two. The round's wall clock was 4 ms longer
2636        // than draft+verify and the difference had nowhere to be seen:
2637        // the accepted prefix re-runs the MTP block once per token to
2638        // keep the draft head's attention cache warm, and the GDN state
2639        // rolls back on any rejection. Both live here, after the verify.
2640        if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
2641            let end = subs();
2642            eprintln!(
2643                "spec-round: draft {:.1} ms/{} sub | verify {:.1} ms/{} sub | \
2644                 commit {:.1} ms/{} sub (accepted {a} of {k_spec})",
2645                t_draft.as_secs_f64() * 1e3,
2646                sub_draft - sub0,
2647                (t_verify - t_draft).as_secs_f64() * 1e3,
2648                sub_verify - sub_draft,
2649                (t_round.elapsed() - t_verify).as_secs_f64() * 1e3,
2650                end - sub_verify,
2651            );
2652        }
2653        Some((drafts[..a].to_vec(), next_pos + a + 1, new_hidden))
2654    }
2655
2656    /// Micro-benchmark: two single-position forwards vs one fused pair
2657    /// from the current cache state (KV rewound after each probe).
2658    /// Returns (two_singles_ms, fused_pair_ms) per probe, or the (0, 0)
2659    /// sentinel when this model has no pair path to measure — the same
2660    /// answer the o1 arm gives, and the bench prints it the same way.
2661    /// (An architecture that loads its own layers leaves `weights.layers`
2662    /// empty; walking it here was an index panic, found by `bench` on
2663    /// deepseek_v4.)
2664    pub fn measure_pair_fusion(&mut self, iters: usize) -> (f64, f64) {
2665        if !self.pair_supported() {
2666            return (0.0, 0.0);
2667        }
2668        let emb1 = self.embed_single(1);
2669        let emb2 = self.embed_single(2);
2670        let pos = self.kv_cache.seq_len();
2671
2672        let t0 = std::time::Instant::now();
2673        for _ in 0..iters {
2674            let _ = self.forward_layers(&emb1, pos, None);
2675            let _ = self.forward_layers(&emb2, pos + 1, None);
2676            for l in &mut self.kv_cache.layers {
2677                l.truncate_last(2);
2678            }
2679        }
2680        let singles_ms = t0.elapsed().as_secs_f64() * 1000.0 / iters as f64;
2681
2682        let t1 = std::time::Instant::now();
2683        for _ in 0..iters {
2684            let _ = self.forward_pair(&emb1, &emb2, pos);
2685            for l in &mut self.kv_cache.layers {
2686                l.truncate_last(2);
2687            }
2688        }
2689        let pair_ms = t1.elapsed().as_secs_f64() * 1000.0 / iters as f64;
2690        (singles_ms, pair_ms)
2691    }
2692
2693    /// Fused two-position forward: weight rows are streamed from memory
2694    /// once per layer for both positions. Full layers → fused GQA pair;
2695    /// linear layers → vmf_phase pair (lane 2 state is tentative in the
2696    /// per-layer scratch until the draft is accepted).
2697    /// Whether the fused two-position path covers every layer kind in
2698    /// this model. MLA and KDA run per position (their pair arms are
2699    /// unreachable); the seq prefill falls back to singles for them.
2700    fn pair_supported(&self) -> bool {
2701        // An EMPTY layer stack means the architecture loaded its own and
2702        // this path has nothing to walk. Checking that directly, rather
2703        // than naming each such architecture, is what makes the guard hold
2704        // for the next one: `any()` over no layers is false, so a
2705        // feature-by-feature test says "supported" for a model that has no
2706        // layers here at all.
2707        !self.weights.layers.is_empty()
2708            && self.g3n.is_none()
2709            && !self
2710                .weights
2711                .layers
2712                .iter()
2713                .any(|lw| matches!(&lw.attn, AttnKind::Mla(_) | AttnKind::Kda(_)))
2714    }
2715
2716    fn forward_pair(
2717        &mut self,
2718        emb1: &[f32],
2719        emb2: &[f32],
2720        position: usize,
2721    ) -> (Vec<f32>, Vec<f32>) {
2722        let mut h1 = emb1.to_vec();
2723        let mut h2 = emb2.to_vec();
2724        let (_nkv, _hd, hs, _rd, eps) = (
2725            self.num_kv_heads,
2726            self.head_dim,
2727            self.hidden_size,
2728            self.rotary_dim,
2729            self.rms_eps,
2730        );
2731        let pool = self.pool.clone();
2732
2733        for li in 0..self.num_layers {
2734            let lw = &self.weights.layers[self.phys_layer(li)];
2735            // Norms into pipeline scratch (4 allocs/layer on the MTP
2736            // decode hot path before this).
2737            inference::rms_norm_into(
2738                &h1,
2739                &lw.input_norm,
2740                self.rms_eps,
2741                self.norm_style,
2742                &mut self.ws.n1,
2743            );
2744            inference::rms_norm_into(
2745                &h2,
2746                &lw.input_norm,
2747                self.rms_eps,
2748                self.norm_style,
2749                &mut self.ws.n2,
2750            );
2751
2752            let (a1, a2) = match &lw.attn {
2753                AttnKind::Mla(_) => unreachable!("MLA has no MTP/pair path"),
2754                AttnKind::Kda(_) => unreachable!("KDA has no MTP/pair path"),
2755                AttnKind::Linear(w) => {
2756                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
2757                    let layer = &mut self.kv_cache.layers[li];
2758                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
2759                    vmf_phase_pair(
2760                        &self.ws.n1,
2761                        &self.ws.n2,
2762                        w,
2763                        &cfg,
2764                        state,
2765                        scratch,
2766                        self.pool.as_deref(),
2767                    )
2768                }
2769                AttnKind::LinearGdn(w) => {
2770                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
2771                    let layer = &mut self.kv_cache.layers[li];
2772                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
2773                    gdn_pair(
2774                        &self.ws.n1,
2775                        &self.ws.n2,
2776                        w,
2777                        &cfg,
2778                        state,
2779                        scratch,
2780                        self.pool.as_deref(),
2781                    )
2782                }
2783                AttnKind::ShortConv(w) => {
2784                    let cfg = self
2785                        .short_conv_cfg
2786                        .expect("short-conv layer without short_conv_cfg");
2787                    let layer = &mut self.kv_cache.layers[li];
2788                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
2789                    short_conv_pair(
2790                        &self.ws.n1,
2791                        &self.ws.n2,
2792                        w,
2793                        &cfg,
2794                        state,
2795                        scratch,
2796                        self.pool.as_deref(),
2797                    )
2798                }
2799                AttnKind::Full {
2800                    wq,
2801                    wk,
2802                    wv,
2803                    wo,
2804                    q_norm,
2805                    k_norm,
2806                    output_gate,
2807                    softplus_gate,
2808                    bias,
2809                } => {
2810                    let inv_freq_l = self.layer_inv_freq(li);
2811                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
2812                    let cfg = QwenAttnCfg {
2813                        num_heads: self.layer_num_heads(li),
2814                        num_kv_heads: nkv_l,
2815                        head_dim: hd_l,
2816                        hidden_size: hs,
2817                        position,
2818                        inv_freq: &inv_freq_l,
2819                        rotary_dim: rd_l,
2820                        scale: self.attn_scale,
2821                        softcap: self.attn_softcap,
2822                        window: self.layer_window(li),
2823                        v_norm: self.attn_v_norm,
2824                        q_norm: q_norm.as_deref(),
2825                        k_norm: k_norm.as_deref(),
2826                        output_gate: *output_gate,
2827                        softplus_gate: softplus_gate
2828                            .as_ref()
2829                            .map(|(gate, per_head)| (gate, *per_head)),
2830                        rope_scale: self.layer_rope_scale(li),
2831                        bias: bias
2832                            .as_ref()
2833                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
2834                        rms_eps: eps,
2835                        norm_style: self.norm_style,
2836                        pool: pool.as_deref(),
2837                    };
2838                    attention::qwen_attention_pair(
2839                        &self.ws.n1,
2840                        &self.ws.n2,
2841                        wq,
2842                        wk,
2843                        wv,
2844                        wo,
2845                        &mut self.kv_cache.layers[li],
2846                        &cfg,
2847                    )
2848                }
2849            };
2850            let (a1, a2) = match &self.weights.layers[self.phys_layer(li)].attn_out_norm {
2851                Some(w) => (
2852                    inference::rms_norm(&a1, w, self.rms_eps, self.norm_style),
2853                    inference::rms_norm(&a2, w, self.rms_eps, self.norm_style),
2854                ),
2855                None => (a1, a2),
2856            };
2857            for i in 0..self.hidden_size {
2858                h1[i] += a1[i];
2859                h2[i] += a2[i];
2860            }
2861            let (mut a1, mut a2) = (a1, a2);
2862            attention::recycle_buf(&mut a1);
2863            attention::recycle_buf(&mut a2);
2864
2865            let lw = &self.weights.layers[self.phys_layer(li)];
2866            inference::rms_norm_into(
2867                &h1,
2868                &lw.post_norm,
2869                self.rms_eps,
2870                self.norm_style,
2871                &mut self.ws.p1,
2872            );
2873            inference::rms_norm_into(
2874                &h2,
2875                &lw.post_norm,
2876                self.rms_eps,
2877                self.norm_style,
2878                &mut self.ws.p2,
2879            );
2880            let (f1, f2) = match &lw.ffn {
2881                // Dual-branch layers need the raw residuals — run the
2882                // two positions through the same fn decode uses.
2883                FfnKind::DenseMoe(dm) => (
2884                    dense_moe_ffn(
2885                        dm,
2886                        &self.ws.p1,
2887                        &h1,
2888                        self.rms_eps,
2889                        self.norm_style,
2890                        self.pool.as_deref(),
2891                    ),
2892                    dense_moe_ffn(
2893                        dm,
2894                        &self.ws.p2,
2895                        &h2,
2896                        self.rms_eps,
2897                        self.norm_style,
2898                        self.pool.as_deref(),
2899                    ),
2900                ),
2901                _ => ffn_forward_pair(
2902                    &lw.ffn,
2903                    &self.ws.p1,
2904                    &self.ws.p2,
2905                    self.pool.as_deref(),
2906                    None,
2907                ),
2908            };
2909            let (f1, f2) = match &self.weights.layers[self.phys_layer(li)].ffn_out_norm {
2910                Some(w) => (
2911                    inference::rms_norm(&f1, w, self.rms_eps, self.norm_style),
2912                    inference::rms_norm(&f2, w, self.rms_eps, self.norm_style),
2913                ),
2914                None => (f1, f2),
2915            };
2916            for i in 0..self.hidden_size {
2917                h1[i] += f1[i];
2918                h2[i] += f2[i];
2919            }
2920            let (mut f1, mut f2) = (f1, f2);
2921            attention::recycle_buf(&mut f1);
2922            attention::recycle_buf(&mut f2);
2923            if let Some(sc) = self.weights.layers[self.phys_layer(li)].layer_scale {
2924                for i in 0..self.hidden_size {
2925                    h1[i] *= sc;
2926                    h2[i] *= sc;
2927                }
2928            }
2929            // Looped Transformer: apply final norm at the end of each loop iteration.
2930            if self.is_loop_end(li) && li + 1 < self.num_layers {
2931                h1 = inference::rms_norm(
2932                    &h1,
2933                    &self.weights.final_norm,
2934                    self.rms_eps,
2935                    self.norm_style,
2936                );
2937                h2 = inference::rms_norm(
2938                    &h2,
2939                    &self.weights.final_norm,
2940                    self.rms_eps,
2941                    self.norm_style,
2942                );
2943            }
2944        }
2945        (h1, h2)
2946    }
2947
2948    /// Commit lane-2 linear states after an accepted draft.
2949    fn commit_linear_scratch(&mut self) {
2950        for layer in &mut self.kv_cache.layers {
2951            if !layer.linear_scratch.is_empty() {
2952                std::mem::swap(&mut layer.linear_state, &mut layer.linear_scratch);
2953                layer.linear_scratch.clear();
2954            }
2955        }
2956    }
2957
2958    /// Forward a full id sequence from a fresh cache and return the
2959    /// logits after the last position (golden-parity harness, bench).
2960    pub fn forward_ids(
2961        &mut self,
2962        ids: &[u32],
2963        task_mask: Option<&TaskMask>,
2964    ) -> Result<Vec<f32>, String> {
2965        if ids.is_empty() {
2966            return Err("empty id sequence".to_string());
2967        }
2968        self.kv_cache.clear();
2969        self.kv_history.clear();
2970        self.o1_begin();
2971        let mut hidden = vec![0.0f32; self.hidden_size];
2972        let mut pos = 0usize;
2973        // Same routing predicate generation uses. Two reasons it must be
2974        // the same one: (1) a GDN hybrid's recurrent state is GPU-
2975        // resident, and a batched CPU prefill would build it on the host
2976        // only — decode then reads buffers the prefill never wrote;
2977        // (2) bench times THIS function and calls the result "prefill",
2978        // so a different path here reports a number production never
2979        // sees (W2 on 2×5090: 8.7 tok/s reported against 125 real).
2980        if self.can_prefill_batched() && !self.graph_prefill_preferred() && ids.len() > 2 {
2981            // prefill-GEMM in chunks; only the last position's hidden is
2982            // needed. (o1-compatible: the batch path attends per position
2983            // through qwen_attention, which carries the collection hook.)
2984            let chunk = prefill_chunk();
2985            let hs = self.hidden_size;
2986            while pos < ids.len() {
2987                let end = (pos + chunk).min(ids.len());
2988                let hb = self.prefill_batch_masked(&ids[pos..end], pos, task_mask);
2989                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
2990                pos = end;
2991            }
2992        }
2993        // Same guards as generation's prefill — INCLUDING the graph one.
2994        // The CPU pair walk was intercepting positions that the resident
2995        // token graph would have run itself: on a GDN hybrid over wgpu
2996        // that is 89 ms of host forward against 7 ms of device submit,
2997        // and it made prefill look 12× slower than it is (W2 on an RTX
2998        // 5090, ctx 512: 11.2 tok/s with the walk, 136.6 without).
2999        // CMF_PAIR=0 opts out; a model whose layers live outside
3000        // `weights.layers` has no pair walk to take.
3001        if task_mask.is_none()
3002            && !self.graph_prefill_preferred()
3003            && !std::env::var("CMF_PAIR").is_ok_and(|v| v == "0")
3004            && self.pair_supported()
3005        {
3006            while pos + 1 < ids.len() {
3007                let e1 = self.embed_single(ids[pos]);
3008                let e2 = self.embed_single(ids[pos + 1]);
3009                let (_, h2) = self.forward_pair(&e1, &e2, pos);
3010                self.commit_linear_scratch();
3011                hidden = h2;
3012                pos += 2;
3013            }
3014        }
3015        while pos < ids.len() {
3016            hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, task_mask);
3017            pos += 1;
3018        }
3019        // Harness contract: after forward_ids the cache is decode-ready —
3020        // under o1 that means sealed (bench measures the seal as part of
3021        // prefill, honestly).
3022        self.o1_seal();
3023        let normed = inference::rms_norm(
3024            &hidden,
3025            &self.weights.final_norm,
3026            self.rms_eps,
3027            self.norm_style,
3028        );
3029        Ok(self.lm_head_forward(&normed))
3030    }
3031
3032    /// Teacher-forced perplexity over a token sequence (phase-C gate:
3033    /// honest quant comparisons instead of prompt vibes).
3034    ///
3035    /// Attention is EXACT even on a model whose layers are flagged for
3036    /// the O(1) kernel — scoring the backbone is the default on purpose
3037    /// (it is the yardstick). `nll_ids_o1` scores the CONVERTED model.
3038    pub fn ppl_ids(&mut self, ids: &[u32]) -> f64 {
3039        let (nll, cnt) = self.nll_ids_from(ids, 0);
3040        (nll / cnt.max(1) as f64).exp()
3041    }
3042
3043    /// DTG-MA calibration pass (Patent 2): run `ids` through the model
3044    /// (CPU path, per position) and return each layer's per-neuron
3045    /// activation mass Σ|silu(gate)·up| — the statistic the task-guided
3046    /// FFN mask is derived from.
3047    pub fn probe_ffn_mass(&mut self, ids: &[u32]) -> Vec<Vec<f64>> {
3048        self.kv_cache.clear();
3049        self.kv_history.clear();
3050        FFN_PROBE.with(|p| {
3051            *p.borrow_mut() = Some(vec![vec![0f64; self.intermediate_size]; self.num_layers]);
3052        });
3053        crate::gpu::cpu_scope(|| {
3054            for (pos, &id) in ids.iter().enumerate() {
3055                let emb = self.embed_single(id);
3056                let _ = self.forward_layers(&emb, pos, None);
3057            }
3058        });
3059        self.kv_cache.clear();
3060        self.kv_history.clear();
3061        FFN_PROBE
3062            .with(|p| p.borrow_mut().take())
3063            .unwrap_or_default()
3064    }
3065
3066    /// Teacher-forced PPL with a task mask active (sparse execution) —
3067    /// the quality gate for a DTG-MA-masked skill. Sequential per
3068    /// position: the batched prefill path is dense-only.
3069    pub fn ppl_ids_masked(&mut self, ids: &[u32], mask: &TaskMask) -> f64 {
3070        self.kv_cache.clear();
3071        self.kv_history.clear();
3072        let mut nll = 0f64;
3073        let mut cnt = 0usize;
3074        let mut hidden = vec![0f32; self.hidden_size];
3075        for (pos, &id) in ids.iter().enumerate() {
3076            if pos > 0 {
3077                inference::rms_norm_into(
3078                    &hidden,
3079                    &self.weights.final_norm,
3080                    self.rms_eps,
3081                    self.norm_style,
3082                    &mut self.ws.n1,
3083                );
3084                let mut logits = self.lm_head_forward(&self.ws.n1);
3085                let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
3086                let sum: f64 = logits.iter().map(|&v| ((v - max) as f64).exp()).sum();
3087                let p = ((logits[id as usize] - max) as f64).exp() / sum.max(1e-300);
3088                nll -= p.max(1e-300).ln();
3089                cnt += 1;
3090                attention::recycle_buf(&mut logits);
3091            }
3092            let emb = self.embed_single(id);
3093            hidden = self.forward_layers(&emb, pos, Some(mask));
3094        }
3095        self.kv_cache.clear();
3096        self.kv_history.clear();
3097        (nll / cnt.max(1) as f64).exp()
3098    }
3099
3100    /// Teacher-forced NLL sum + scored-token count over positions
3101    /// `start..len-1`, attention EXACT. Positions below `start` still
3102    /// run — they are the context — they are just not scored, so this
3103    /// pairs with `nll_ids_o1(ids, start)` over the very same tokens.
3104    ///
3105    /// Returning (nll, cnt) rather than a ppl is what lets a windowed
3106    /// caller combine windows before the exp, so every scored token
3107    /// weighs the same regardless of how the windows are cut.
3108    /// `nll_ids_from` with a task mask held active at every position.
3109    ///
3110    /// The batched prefill path does not thread masks, so this walks the
3111    /// per-position forward — slower, but it scores the file exactly the
3112    /// way `run --task` will serve it, which is the point of the gate
3113    /// that calls it. With `None` it defers to the fast path.
3114    /// Masked scoring rides the SAME batched sweep as unmasked scoring —
3115    /// the masked-inference fast path: `prefill_batch_masked` lands the
3116    /// per-visit FFN rows on the activations inside the fused arms. The
3117    /// per-position loop below remains only as the no-batch fallback.
3118    pub fn nll_ids_masked(
3119        &mut self,
3120        ids: &[u32],
3121        start: usize,
3122        task_mask: Option<&TaskMask>,
3123    ) -> (f64, usize) {
3124        self.nll_ids_inner(ids, start, task_mask)
3125    }
3126
3127    pub fn nll_ids_from(&mut self, ids: &[u32], start: usize) -> (f64, usize) {
3128        self.nll_ids_inner(ids, start, None)
3129    }
3130
3131    fn nll_ids_inner(
3132        &mut self,
3133        ids: &[u32],
3134        start: usize,
3135        task_mask: Option<&TaskMask>,
3136    ) -> (f64, usize) {
3137        self.kv_cache.clear();
3138        self.kv_history.clear();
3139        let mut nll = 0f64;
3140        let mut cnt = 0usize;
3141        if self.can_prefill_batched() {
3142            // prefill-GEMM: layer-major position chunks, lm_head batched
3143            // (254MB lm_head read once per chunk, not per position).
3144            // The layer chunk is large (grouping positions by MoE experts
3145            // wins with size), lm_head in sub-blocks (logit buffer
3146            // 32×vocab ≈ 32MB instead of 128×).
3147            const CHUNK: usize = 128;
3148            const LM_SUB: usize = 32;
3149            let n = ids.len().saturating_sub(1);
3150            let hs = self.hidden_size;
3151            let rows = self.weights.lm_head.rows();
3152            let mut pos = 0usize;
3153            while pos < n {
3154                let end = (pos + CHUNK).min(n);
3155                let bsz = end - pos;
3156                let hb = self.prefill_batch_masked(&ids[pos..end], pos, task_mask);
3157                let mut k0 = 0usize;
3158                while k0 < bsz {
3159                    let k1 = (k0 + LM_SUB).min(bsz);
3160                    let sb = k1 - k0;
3161                    // Sub-block entirely below the scored range: the KV
3162                    // it just built is all this pass needed from it.
3163                    if pos + k1 <= start {
3164                        k0 = k1;
3165                        continue;
3166                    }
3167                    let mut normed = vec![0.0f32; sb * hs];
3168                    for k in 0..sb {
3169                        let r = inference::rms_norm(
3170                            &hb[(k0 + k) * hs..(k0 + k + 1) * hs],
3171                            &self.weights.final_norm,
3172                            self.rms_eps,
3173                            self.norm_style,
3174                        );
3175                        normed[k * hs..(k + 1) * hs].copy_from_slice(&r);
3176                    }
3177                    let mut logits = vec![0.0f32; sb * rows];
3178                    self.weights
3179                        .lm_head
3180                        .matmat(&normed, sb, &mut logits, self.pool.as_deref());
3181                    for k in 0..sb {
3182                        if pos + k0 + k < start {
3183                            continue;
3184                        }
3185                        let lg = &mut logits[k * rows..k * rows + self.vocab_size.min(rows)];
3186                        if let Some(mu) = self.logit_multiplier {
3187                            for v in lg.iter_mut() {
3188                                *v *= mu;
3189                            }
3190                        }
3191                        // Gemma-class final-logit soft-capping: the
3192                        // decode paths apply it; scoring must too, or
3193                        // the uncapped softmax misprices every token.
3194                        if let Some(c) = self.final_softcap {
3195                            for v in lg.iter_mut() {
3196                                *v = c * (*v / c).tanh();
3197                            }
3198                        }
3199                        let lg = &logits[k * rows..k * rows + self.vocab_size.min(rows)];
3200                        let target = ids[pos + k0 + k + 1] as usize;
3201                        let max = lg.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
3202                        let lse: f64 = lg
3203                            .iter()
3204                            .map(|&v| ((v - max) as f64).exp())
3205                            .sum::<f64>()
3206                            .ln()
3207                            + max as f64;
3208                        nll += lse - lg[target] as f64;
3209                        cnt += 1;
3210                        if std::env::var("CMF_PPL_TRACE").is_ok() {
3211                            let top = lg
3212                                .iter()
3213                                .enumerate()
3214                                .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
3215                                .map(|(i, _)| i)
3216                                .unwrap_or(0);
3217                            eprintln!(
3218                                "BTRACE pos {} target {} nll {:.4} top {} lg_t {:.3} lg_top {:.3}",
3219                                pos + k0 + k,
3220                                target,
3221                                lse - lg[target] as f64,
3222                                top,
3223                                lg[target],
3224                                lg[top]
3225                            );
3226                        }
3227                    }
3228                    k0 = k1;
3229                }
3230                pos = end;
3231            }
3232            self.kv_cache.clear();
3233            self.kv_history.clear();
3234            return (nll, cnt);
3235        }
3236        for pos in 0..ids.len().saturating_sub(1) {
3237            let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, task_mask);
3238            // Architectures whose head lives inside their own stack return
3239            // the logits out of band and a zero hidden — DeepSeek-V4 folds
3240            // its hyper-connection copies between the last layer and the
3241            // norm, so it cannot hand back a vector this loop could use.
3242            // Scoring the zeros gave a perplexity of exactly the vocabulary
3243            // size, which is a uniform distribution reported as a
3244            // measurement. `generate` already reads this channel.
3245            let out_of_band = self.graph_logits.take();
3246            if pos < start {
3247                continue;
3248            }
3249            let logits = match out_of_band {
3250                Some(lg) => lg,
3251                None => {
3252                    let normed = inference::rms_norm(
3253                        &hidden,
3254                        &self.weights.final_norm,
3255                        self.rms_eps,
3256                        self.norm_style,
3257                    );
3258                    // lm_head_forward applies the final-logit softcap itself
3259                    // — capping again here double-squashed gemma-class
3260                    // logits (tanh∘tanh) and reported a flattered ppl.
3261                    self.lm_head_forward(&normed)
3262                }
3263            };
3264            let target = ids[pos + 1] as usize;
3265            let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
3266            let lse: f64 = logits
3267                .iter()
3268                .map(|&v| ((v - max) as f64).exp())
3269                .sum::<f64>()
3270                .ln()
3271                + max as f64;
3272            let tok_nll = lse - logits[target] as f64;
3273            if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 48 {
3274                let top = logits
3275                    .iter()
3276                    .enumerate()
3277                    .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
3278                    .map(|(i, _)| i)
3279                    .unwrap_or(0);
3280                eprintln!(
3281                    "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
3282                    logits[target], logits[top]
3283                );
3284            }
3285            nll += tok_nll;
3286            cnt += 1;
3287        }
3288        self.kv_cache.clear();
3289        self.kv_history.clear();
3290        (nll, cnt)
3291    }
3292
3293    /// Teacher-forced NLL of the CONVERTED model: the O(1) Nyström path
3294    /// is ACTIVE over the scored positions. Returns (nll sum, scored
3295    /// count) over `prefill..len-1`.
3296    ///
3297    /// Runtime discipline, deliberately NOT the matrix probe's: the
3298    /// first `prefill` tokens run the exact prompt pass — that pass is
3299    /// what freezes the landmarks and M — and every scored position then
3300    /// goes through `NystromState::step()`, the same code decode runs.
3301    /// So the landmarks are PREFILL-frozen (what ships), not
3302    /// full-sequence oracles (what the published probe measured), and
3303    /// every scored row carries a real far field rather than sitting
3304    /// inside the exact window.
3305    ///
3306    /// Pair with `nll_ids_from(ids, prefill)` for the exact baseline
3307    /// over the identical token set — that ratio is the honest one.
3308    pub fn nll_ids_o1(&mut self, ids: &[u32], prefill: usize) -> (f64, usize) {
3309        self.kv_cache.clear();
3310        self.kv_history.clear();
3311        self.o1_begin();
3312        let n = ids.len().saturating_sub(1);
3313        let p = prefill.min(n);
3314        // Exact prompt pass over ids[..p]: the seal consumes its q/k/v.
3315        let mut pos = 0usize;
3316        if self.can_prefill_batched() {
3317            const CHUNK: usize = 128;
3318            while pos < p {
3319                let end = (pos + CHUNK).min(p);
3320                let _ = self.prefill_batch(&ids[pos..end], pos);
3321                pos = end;
3322            }
3323        } else {
3324            while pos < p {
3325                let _ = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
3326                pos += 1;
3327            }
3328        }
3329        self.o1_seal();
3330
3331        let mut nll = 0f64;
3332        let mut cnt = 0usize;
3333        for pos in p..n {
3334            let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
3335            let normed = inference::rms_norm(
3336                &hidden,
3337                &self.weights.final_norm,
3338                self.rms_eps,
3339                self.norm_style,
3340            );
3341            // lm_head_forward applies the final-logit softcap itself —
3342            // capping again here double-squashed gemma-class logits
3343            // (tanh∘tanh) and reported a flattered ppl.
3344            let logits = self.lm_head_forward(&normed);
3345            let target = ids[pos + 1] as usize;
3346            let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
3347            let lse: f64 = logits
3348                .iter()
3349                .map(|&v| ((v - max) as f64).exp())
3350                .sum::<f64>()
3351                .ln()
3352                + max as f64;
3353            let tok_nll = lse - logits[target] as f64;
3354            if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 48 {
3355                let top = logits
3356                    .iter()
3357                    .enumerate()
3358                    .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
3359                    .map(|(i, _)| i)
3360                    .unwrap_or(0);
3361                eprintln!(
3362                    "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
3363                    logits[target], logits[top]
3364                );
3365            }
3366            nll += tok_nll;
3367            cnt += 1;
3368        }
3369        self.kv_cache.clear();
3370        self.kv_history.clear();
3371        (nll, cnt)
3372    }
3373
3374    /// Teacher-forced calibration data (B1): for each position, whether the
3375    /// argmax equals the actual next token, and the top-1 softmax prob
3376    /// (Born mass) under EACH temperature in `temps` — all from ONE forward
3377    /// pass (argmax/correctness are temperature-invariant; only p_max
3378    /// reshapes). Feeds `cortiq calibrate` (reliability/ECE + temperature
3379    /// fit): is the model's confidence a true property, or does it need a
3380    /// measured scaling?
3381    pub fn calib_ids(&mut self, ids: &[u32], temps: &[f32]) -> (Vec<bool>, Vec<Vec<f32>>) {
3382        self.kv_cache.clear();
3383        self.kv_history.clear();
3384        let n = ids.len().saturating_sub(1);
3385        let mut correct = Vec::with_capacity(n);
3386        let mut pmax = Vec::with_capacity(n);
3387        for pos in 0..n {
3388            let emb = self.embed_single(ids[pos]);
3389            let hidden = self.forward_layers(&emb, pos, None);
3390            let normed = inference::rms_norm(
3391                &hidden,
3392                &self.weights.final_norm,
3393                self.rms_eps,
3394                self.norm_style,
3395            );
3396            // lm_head_forward applies the final-logit softcap itself —
3397            // capping again here double-squashed gemma-class logits
3398            // (tanh∘tanh) and reported a flattered ppl.
3399            let logits = self.lm_head_forward(&normed);
3400            let target = ids[pos + 1] as usize;
3401            let (mut amax, mut mval) = (0usize, f32::NEG_INFINITY);
3402            for (i, &v) in logits.iter().enumerate() {
3403                if v > mval {
3404                    mval = v;
3405                    amax = i;
3406                }
3407            }
3408            correct.push(amax == target);
3409            let row: Vec<f32> = temps
3410                .iter()
3411                .map(|&t| {
3412                    let tt = t.max(1e-3);
3413                    let s: f32 = logits.iter().map(|&v| ((v - mval) / tt).exp()).sum();
3414                    1.0 / s.max(1e-12) // numerator at the max is exp(0)=1
3415                })
3416                .collect();
3417            pmax.push(row);
3418        }
3419        self.kv_cache.clear();
3420        self.kv_history.clear();
3421        (correct, pmax)
3422    }
3423
3424    /// Teacher-forced PPL with the dynamic router driving per-window
3425    /// skill switches (VMF experiment №2 measurement). Sequential (φ
3426    /// must update per token), returns (ppl, switch_count). The router
3427    /// must be enabled (`enable_dynamic_routing`); else this equals
3428    /// plain `ppl_ids`. The active skill when scoring token t shapes the
3429    /// logits for t+1 — on-policy over the held-out text itself.
3430    pub fn ppl_ids_dynamic(&mut self, ids: &[u32]) -> (f64, usize) {
3431        let mut router = match self.dyn_router.take() {
3432            Some(r) => r,
3433            None => return (self.ppl_ids(ids), 0),
3434        };
3435        router.reset();
3436        self.dyn_phi_seen = 0;
3437        let _ = self.set_active_skill(None);
3438
3439        self.kv_cache.clear();
3440
3441        self.kv_history.clear();
3442        let mut nll = 0f64;
3443        let mut cnt = 0usize;
3444        for pos in 0..ids.len().saturating_sub(1) {
3445            let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
3446            let normed = inference::rms_norm(
3447                &hidden,
3448                &self.weights.final_norm,
3449                self.rms_eps,
3450                self.norm_style,
3451            );
3452            // lm_head_forward applies the final-logit softcap itself —
3453            // capping again here double-squashed gemma-class logits
3454            // (tanh∘tanh) and reported a flattered ppl.
3455            let logits = self.lm_head_forward(&normed);
3456            let target = ids[pos + 1] as usize;
3457            let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
3458            let lse: f64 = logits
3459                .iter()
3460                .map(|&v| ((v - max) as f64).exp())
3461                .sum::<f64>()
3462                .ln()
3463                + max as f64;
3464            let tok_nll = lse - logits[target] as f64;
3465            if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 48 {
3466                let top = logits
3467                    .iter()
3468                    .enumerate()
3469                    .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
3470                    .map(|(i, _)| i)
3471                    .unwrap_or(0);
3472                eprintln!(
3473                    "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
3474                    logits[target], logits[top]
3475                );
3476            }
3477            nll += tok_nll;
3478            cnt += 1;
3479            // Route on the evolving φ (drives the NEXT token's skill).
3480            let phi = self.dyn_phi_ema.clone();
3481            if let Some(new_active) = router.step(&phi, pos) {
3482                let _ = self.set_active_skill(new_active);
3483            }
3484        }
3485        let switches = router.switches.len();
3486        let _ = self.set_active_skill(None);
3487        self.dyn_router = Some(router);
3488        self.kv_cache.clear();
3489        self.kv_history.clear();
3490        ((nll / cnt.max(1) as f64).exp(), switches)
3491    }
3492
3493    /// Routing probe φ (spec §9): mean-pooled hidden after `layer`.
3494    pub fn probe_phi(&mut self, ids: &[u32], layer: usize) -> Vec<f32> {
3495        self.kv_cache.clear();
3496        self.kv_history.clear();
3497        let mut acc = vec![0f32; self.hidden_size];
3498        for (pos, &id) in ids.iter().enumerate() {
3499            let h = self.forward_layers_upto(&self.embed_single(id), pos, None, Some(layer));
3500            for (a, v) in acc.iter_mut().zip(&h) {
3501                *a += v;
3502            }
3503        }
3504        let n = ids.len().max(1) as f32;
3505        for a in acc.iter_mut() {
3506            *a /= n;
3507        }
3508        self.kv_cache.clear();
3509        self.kv_history.clear();
3510        acc
3511    }
3512
3513    /// Layer-major batched prefill (prefill-GEMM): full-attention —
3514    /// per-position with the existing operators (KV grows naturally,
3515    /// causality preserved), GDN projections / FFN / MoE — batched
3516    /// (a weight row is read from DRAM once per chunk, not per
3517    /// position). Returns the hidden of all positions [b × hidden].
3518    fn prefill_batch(&mut self, ids: &[u32], start_pos: usize) -> Vec<f32> {
3519        self.prefill_batch_masked(ids, start_pos, None)
3520    }
3521
3522    /// `prefill_batch` with a task mask honored on the dense-FFN panels
3523    /// (the masked-inference fast path: full fused compute, mask lands on
3524    /// the activations). The whole-chunk GPU graph is skipped for masked
3525    /// layers by the callers' arms; the per-GEMM device paths stay in
3526    /// play because the zeroing happens on the host between them.
3527    fn prefill_batch_masked(
3528        &mut self,
3529        ids: &[u32],
3530        start_pos: usize,
3531        task_mask: Option<&TaskMask>,
3532    ) -> Vec<f32> {
3533        self.prefill_batch_span(PrefillIn::Ids(ids), start_pos, task_mask, 0, usize::MAX)
3534    }
3535
3536    /// The layer-major batched walk over a layer span [from..upto_excl):
3537    /// the whole prefill machinery (chunk graph, batched attends, GEMM
3538    /// panels) for a PARTIAL stack — the network split's prefill rides
3539    /// the same canon as the local one. Input is token ids (embeds
3540    /// itself, coordinator side) or ready boundary hiddens (worker side).
3541    fn prefill_batch_span(
3542        &mut self,
3543        input: PrefillIn<'_>,
3544        start_pos: usize,
3545        task_mask: Option<&TaskMask>,
3546        from: usize,
3547        upto_excl: usize,
3548    ) -> Vec<f32> {
3549        let hs = self.hidden_size;
3550        let b = match input {
3551            PrefillIn::Ids(ids) => ids.len(),
3552            PrefillIn::Hidden(hb) => hb.len() / hs,
3553        };
3554        let upto_excl = upto_excl.min(self.num_layers);
3555        // The CPU embed is deferred: when the chunk graph takes the run
3556        // from layer 0 it gathers the embeddings on the device instead.
3557        // A hidden input is ready by definition.
3558        let mut h: Vec<f32>;
3559        let mut h_ready;
3560        match input {
3561            PrefillIn::Ids(_) => {
3562                h = vec![0.0; b * hs];
3563                h_ready = false;
3564            }
3565            PrefillIn::Hidden(hb) => {
3566                h = hb.to_vec();
3567                h_ready = true;
3568            }
3569        }
3570        let fill_h = |h: &mut Vec<f32>, me: &Self| {
3571            if let PrefillIn::Ids(ids) = input {
3572                for (bi, &id) in ids.iter().enumerate() {
3573                    let e = me.embed_single(id);
3574                    h[bi * hs..(bi + 1) * hs].copy_from_slice(&e);
3575                }
3576            }
3577        };
3578        let (_nkv, _hd, _rd, eps) = (
3579            self.num_kv_heads,
3580            self.head_dim,
3581            self.rotary_dim,
3582            self.rms_eps,
3583        );
3584        let pool = self.pool.clone();
3585        let norm_style = self.norm_style;
3586
3587        #[cfg(target_os = "macos")]
3588        let mut chunk_skip_until = 0usize;
3589        for li in from..upto_excl {
3590            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU
3591            // GPU chunk graph (default-on under CMF_GPU=1): a run of
3592            // consecutive eligible layers for the whole chunk in ONE
3593            // Metal submission — norm, QKV, RoPE with fused mirror
3594            // append, causal attend, O, FFN, hidden device-resident
3595            // across the run. Any refusal falls through to the CPU path.
3596            #[cfg(target_os = "macos")]
3597            if task_mask.is_none() {
3598                if li < chunk_skip_until {
3599                    continue;
3600                }
3601                // Device-side embedding needs a q8_row embedding matrix;
3602                // with any other layout the CPU fills `h` first and the
3603                // graph starts from a ready hidden (refusing the whole
3604                // run over the embedding alone kept q4t models — the
3605                // whole Nanbeige/Bonsai class — on the CPU prefill).
3606                if !h_ready && li == 0 && self.weights.embed_tokens.q8_row_parts().is_none() {
3607                    fill_h(&mut h, self);
3608                    h_ready = true;
3609                }
3610                let ids_for_embed = match input {
3611                    PrefillIn::Ids(ids) => (!h_ready && li == 0).then_some(ids),
3612                    PrefillIn::Hidden(_) => None,
3613                };
3614                let end = self.chunk_run_gpu(li, &mut h, b, start_pos, ids_for_embed, upto_excl);
3615                if end > li {
3616                    h_ready = true;
3617                    chunk_skip_until = end;
3618                    // Looped Transformer: the graph stopped at a loop
3619                    // boundary — apply final norm before the next iteration.
3620                    if self.is_loop_end(end - 1) && end < self.num_layers {
3621                        for bi in 0..b {
3622                            let normed = inference::rms_norm(
3623                                &h[bi * hs..(bi + 1) * hs],
3624                                &self.weights.final_norm,
3625                                eps,
3626                                norm_style,
3627                            );
3628                            h[bi * hs..(bi + 1) * hs].copy_from_slice(&normed);
3629                        }
3630                    }
3631                    continue;
3632                }
3633            }
3634            if !h_ready {
3635                fill_h(&mut h, self);
3636                h_ready = true;
3637            }
3638            let lw = &self.weights.layers[self.phys_layer(li)];
3639            // ── attention ──
3640            match &lw.attn {
3641                AttnKind::Kda(w) => {
3642                    // Projections batched, recurrence sequential.
3643                    let cfg = self.kda_cfg.expect("kda layer without kda_cfg");
3644                    let mut normed = vec![0.0f32; b * hs];
3645                    for bi in 0..b {
3646                        inference::rms_norm_into(
3647                            &h[bi * hs..(bi + 1) * hs],
3648                            &lw.input_norm,
3649                            eps,
3650                            norm_style,
3651                            &mut normed[bi * hs..(bi + 1) * hs],
3652                        );
3653                    }
3654                    let attn = crate::linear_core::kda_forward_batch(
3655                        &normed,
3656                        b,
3657                        w,
3658                        &cfg,
3659                        &mut self.kv_cache.layers[li].linear_state,
3660                        pool.as_deref(),
3661                    );
3662                    for (dst, &a) in h.iter_mut().zip(&attn) {
3663                        *dst += a;
3664                    }
3665                }
3666                AttnKind::LinearGdn(w) => {
3667                    // Projections batched, recurrence sequential.
3668                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
3669                    let mut normed = vec![0.0f32; b * hs];
3670                    for bi in 0..b {
3671                        let r = inference::rms_norm(
3672                            &h[bi * hs..(bi + 1) * hs],
3673                            &lw.input_norm,
3674                            eps,
3675                            norm_style,
3676                        );
3677                        normed[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
3678                    }
3679                    let attn = crate::linear_core::gdn_forward_batch(
3680                        &normed,
3681                        b,
3682                        w,
3683                        &cfg,
3684                        &mut self.kv_cache.layers[li].linear_state,
3685                        pool.as_deref(),
3686                    );
3687                    for (dst, &a) in h.iter_mut().zip(&attn) {
3688                        *dst += a;
3689                    }
3690                }
3691                AttnKind::ShortConv(w) => {
3692                    // Projections batched over the chunk; the conv walks the
3693                    // contiguous positions in order (same ring as decode).
3694                    let cfg = self
3695                        .short_conv_cfg
3696                        .expect("short-conv layer without short_conv_cfg");
3697                    let mut normed = vec![0.0f32; b * hs];
3698                    for bi in 0..b {
3699                        inference::rms_norm_into(
3700                            &h[bi * hs..(bi + 1) * hs],
3701                            &lw.input_norm,
3702                            eps,
3703                            norm_style,
3704                            &mut normed[bi * hs..(bi + 1) * hs],
3705                        );
3706                    }
3707                    let attn = short_conv_forward_batch(
3708                        &normed,
3709                        b,
3710                        w,
3711                        &cfg,
3712                        &mut self.kv_cache.layers[li].linear_state,
3713                        pool.as_deref(),
3714                    );
3715                    for (dst, &a) in h.iter_mut().zip(&attn) {
3716                        *dst += a;
3717                    }
3718                }
3719                AttnKind::Mla(w) => {
3720                    // Per-position prefill (correctness first; latent
3721                    // batching is a later optimization).
3722                    let inv_freq_l = self.layer_inv_freq(li);
3723                    let rs = self.layer_rope_scale(li);
3724                    let mut normed = vec![0.0f32; hs];
3725                    for bi in 0..b {
3726                        inference::rms_norm_into(
3727                            &h[bi * hs..(bi + 1) * hs],
3728                            &lw.input_norm,
3729                            eps,
3730                            norm_style,
3731                            &mut normed,
3732                        );
3733                        let ao = mla_attention(
3734                            w,
3735                            &normed,
3736                            &mut self.kv_cache.layers[li],
3737                            start_pos + bi,
3738                            &inv_freq_l,
3739                            rs,
3740                            eps,
3741                            pool.as_deref(),
3742                        );
3743                        for (dst, &a) in h[bi * hs..(bi + 1) * hs].iter_mut().zip(&ao) {
3744                            *dst += a;
3745                        }
3746                    }
3747                }
3748                AttnKind::Full {
3749                    wq,
3750                    wk,
3751                    wv,
3752                    wo,
3753                    q_norm,
3754                    k_norm,
3755                    output_gate,
3756                    softplus_gate,
3757                    bias,
3758                } => {
3759                    // Chunk-GEMM QKV/O; per-position causal attention
3760                    // inside (roadmap §3 P0 — full-attention prefill no
3761                    // longer re-reads the projection weights b times).
3762                    let mut normed = vec![0.0f32; b * hs];
3763                    for bi in 0..b {
3764                        inference::rms_norm_into(
3765                            &h[bi * hs..(bi + 1) * hs],
3766                            &lw.input_norm,
3767                            eps,
3768                            norm_style,
3769                            &mut normed[bi * hs..(bi + 1) * hs],
3770                        );
3771                    }
3772                    let inv_freq_l = self.layer_inv_freq(li);
3773                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
3774                    let cfg = QwenAttnCfg {
3775                        num_heads: self.layer_num_heads(li),
3776                        num_kv_heads: nkv_l,
3777                        head_dim: hd_l,
3778                        hidden_size: hs,
3779                        position: start_pos,
3780                        inv_freq: &inv_freq_l,
3781                        rotary_dim: rd_l,
3782                        scale: self.attn_scale,
3783                        softcap: self.attn_softcap,
3784                        window: self.layer_window(li),
3785                        v_norm: self.attn_v_norm,
3786                        q_norm: q_norm.as_deref(),
3787                        k_norm: k_norm.as_deref(),
3788                        output_gate: *output_gate,
3789                        softplus_gate: softplus_gate
3790                            .as_ref()
3791                            .map(|(gate, per_head)| (gate, *per_head)),
3792                        rope_scale: self.layer_rope_scale(li),
3793                        bias: bias
3794                            .as_ref()
3795                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
3796                        rms_eps: eps,
3797                        norm_style,
3798                        pool: pool.as_deref(),
3799                    };
3800                    let mut attn = attention::qwen_attention_batch(
3801                        &normed,
3802                        b,
3803                        wq,
3804                        wk,
3805                        wv,
3806                        wo,
3807                        &mut self.kv_cache.layers[li],
3808                        &cfg,
3809                    );
3810                    if let Some(w) = &lw.attn_out_norm {
3811                        for bi in 0..b {
3812                            inference::rms_norm_into(
3813                                &attn[bi * hs..(bi + 1) * hs],
3814                                w,
3815                                eps,
3816                                norm_style,
3817                                &mut normed[bi * hs..(bi + 1) * hs],
3818                            );
3819                        }
3820                        attn.copy_from_slice(&normed);
3821                    }
3822                    for (dst, &a) in h.iter_mut().zip(&attn) {
3823                        *dst += a;
3824                    }
3825                }
3826                AttnKind::Linear(w) => {
3827                    for bi in 0..b {
3828                        let normed = inference::rms_norm(
3829                            &h[bi * hs..(bi + 1) * hs],
3830                            &lw.input_norm,
3831                            eps,
3832                            norm_style,
3833                        );
3834                        vmf_phase_forward(
3835                            &normed,
3836                            w,
3837                            &self.vmf_cfg.expect("linear layer without vmf_cfg"),
3838                            &mut self.kv_cache.layers[li].linear_state,
3839                            pool.as_deref(),
3840                        )
3841                        .iter()
3842                        .enumerate()
3843                        .for_each(|(i, &a)| h[bi * hs + i] += a);
3844                    }
3845                }
3846            }
3847
3848            // ── FFN batched ──
3849            let lw = &self.weights.layers[self.phys_layer(li)];
3850            let mut post = vec![0.0f32; b * hs];
3851            for bi in 0..b {
3852                let r =
3853                    inference::rms_norm(&h[bi * hs..(bi + 1) * hs], &lw.post_norm, eps, norm_style);
3854                post[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
3855            }
3856            // A restrictive per-visit FFN row lands on the activations
3857            // inside the dense arm; an all-open row costs nothing.
3858            let mask_row = task_mask
3859                .filter(|m| m.ffn_active_count(li) < self.intermediate_size)
3860                .and_then(|m| m.ffn_masks.get(li))
3861                .map(|v| v.as_slice());
3862            let mut ffn = match &lw.ffn {
3863                FfnKind::Dense(d) => dense_ffn_batch(d, &post, b, pool.as_deref(), mask_row),
3864                FfnKind::Moe(m) => moe_ffn_batch(m, &post, b, hs, pool.as_deref(), None),
3865                // Dual-branch layers run per position (the expert branch
3866                // reads the raw residual — nothing to batch yet).
3867                FfnKind::DenseMoe(dm) => {
3868                    let mut out = vec![0.0f32; b * hs];
3869                    for bi in 0..b {
3870                        let r = dense_moe_ffn(
3871                            dm,
3872                            &post[bi * hs..(bi + 1) * hs],
3873                            &h[bi * hs..(bi + 1) * hs],
3874                            eps,
3875                            norm_style,
3876                            pool.as_deref(),
3877                        );
3878                        out[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
3879                    }
3880                    out
3881                }
3882            };
3883            if let Some(w) = &lw.ffn_out_norm {
3884                for bi in 0..b {
3885                    inference::rms_norm_into(
3886                        &ffn[bi * hs..(bi + 1) * hs],
3887                        w,
3888                        eps,
3889                        norm_style,
3890                        &mut post[bi * hs..(bi + 1) * hs],
3891                    );
3892                }
3893                ffn.copy_from_slice(&post);
3894            }
3895            for (dst, &f) in h.iter_mut().zip(&ffn) {
3896                *dst += f;
3897            }
3898            if let Some(sc) = lw.layer_scale {
3899                for v in h.iter_mut() {
3900                    *v *= sc;
3901                }
3902            }
3903            if let Ok(tp) = std::env::var("CMF_TRACE_POS") {
3904                if let Some(t) = tp.parse::<usize>().ok() {
3905                    if t >= start_pos && t < start_pos + b {
3906                        let bi = t - start_pos;
3907                        let row = &h[bi * hs..(bi + 1) * hs];
3908                        let n: f32 = row.iter().map(|x| x * x).sum::<f32>().sqrt();
3909                        eprintln!(
3910                            "BATCH pos {t} after layer {li}: |h| = {n:.6} h0 {:.6} h1 {:.6}",
3911                            row[0], row[1]
3912                        );
3913                    }
3914                }
3915            }
3916            // CMF_DEBUG_LAYERS=1: per-layer hidden-state health of the
3917            // LAST prompt position — the knife for "which layer type
3918            // breaks first" on a new architecture.
3919            if std::env::var("CMF_DEBUG_LAYERS").is_ok() {
3920                let row = &h[(b - 1) * hs..b * hs];
3921                let rms =
3922                    (row.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / hs as f64).sqrt();
3923                let mx = row.iter().fold(0f32, |m, &v| m.max(v.abs()));
3924                eprintln!(
3925                    "layer {li:>3} {:>10} ffn={:<5} rms={rms:>12.4} max={mx:>12.4}",
3926                    match &self.weights.layers[self.phys_layer(li)].attn {
3927                        AttnKind::LinearGdn(_) => "gdn",
3928                        AttnKind::Linear(_) => "vmf",
3929                        AttnKind::ShortConv(_) => "conv",
3930                        _ => "attn",
3931                    },
3932                    match &lw.ffn {
3933                        FfnKind::Moe(_) => "moe",
3934                        FfnKind::Dense(_) => "dense",
3935                        FfnKind::DenseMoe(_) => "dense+moe",
3936                    },
3937                );
3938            }
3939            // Looped Transformer: apply final norm at the end of each loop iteration.
3940            if self.is_loop_end(li) && li + 1 < self.num_layers {
3941                for bi in 0..b {
3942                    let normed = inference::rms_norm(
3943                        &h[bi * hs..(bi + 1) * hs],
3944                        &self.weights.final_norm,
3945                        eps,
3946                        norm_style,
3947                    );
3948                    h[bi * hs..(bi + 1) * hs].copy_from_slice(&normed);
3949                }
3950            }
3951            if std::env::var("CMF_TRACE_H").is_ok() {
3952                let n = h[..hs].iter().map(|v| v.abs()).sum::<f32>() / hs as f32;
3953                let mx = h[..hs].iter().fold(0.0f32, |a, &v| a.max(v.abs()));
3954                eprintln!(
3955                    "layer {li}: mean|h|={n:.4} max|h|={mx:.2} scale={:?}",
3956                    lw.layer_scale
3957                );
3958            }
3959        }
3960        crate::gpu::set_layer(-1); // lm_head/final ops outside layer-split
3961        h
3962    }
3963
3964    /// Embed a single token.
3965    fn embed_single(&self, id: u32) -> Vec<f32> {
3966        let mut out = vec![0.0f32; self.hidden_size];
3967        if (id as usize) < self.weights.embed_tokens.rows() {
3968            self.weights.embed_tokens.row_f32(id as usize, &mut out);
3969        }
3970        if self.embed_multiplier != 1.0 {
3971            for v in out.iter_mut() {
3972                *v *= self.embed_multiplier;
3973            }
3974        }
3975        // DeepSeek-V4's hash layers route by TOKEN ID, so the id has to
3976        // reach the forward. It rides in slot 0 (the forward re-reads the
3977        // real embedding itself from the table).
3978        if self.dsv4.is_some() {
3979            let mut v = vec![0.0f32; self.hidden_size.max(1)];
3980            v[0] = id as f32;
3981            return v;
3982        }
3983        // Gemma-3n: the per-layer-embedding half needs the token ID, so
3984        // it rides appended to the embedding; the g3n forward splits it.
3985        if let Some(b) = &self.g3n {
3986            return b.0.extend_embedding(id, &out, self.pool.as_deref());
3987        }
3988        out
3989    }
3990
3991    /// A run of consecutive prefill layers on the GPU for the whole
3992    /// chunk (default-on under CMF_GPU=1; CMF_GPU_CHUNK=0 disables).
3993    /// Eligibility per layer: q8_row weights, plain full attention
3994    /// (no output gate), F32 KV, no o1/masks/gemma extras. Returns the
3995    /// first layer index NOT processed (== `li0` when the run is empty).
3996    #[cfg(target_os = "macos")]
3997    fn chunk_run_gpu(
3998        &mut self,
3999        li0: usize,
4000        h: &mut [f32],
4001        b: usize,
4002        pos0: usize,
4003        embed_ids: Option<&[u32]>,
4004        cap: usize,
4005    ) -> usize {
4006        // (The old streaming attend needed a depth bound at ~1k; the
4007        // GEMM attention scales like the CPU path and lifted it.)
4008        // CMF_GPU_CHUNK=0 disables the graph.
4009        if !crate::gpu::enabled_here()
4010            || std::env::var("CMF_GPU_CHUNK")
4011                .map(|v| v == "0")
4012                .unwrap_or(false)
4013            || b < 32
4014            || self.swa.is_some()
4015            || self.global_attn.is_some()
4016            || self.attn_v_norm
4017            || (self.attn_scale - 1.0 / (self.head_dim as f32).sqrt()).abs() > 1e-9
4018        {
4019            return li0;
4020        }
4021        let Some(model) = self.model.clone() else {
4022            return li0;
4023        };
4024        let inv_freq = self.inv_freq.clone();
4025        let (nh, nkv, hd, hs) = (
4026            self.num_heads,
4027            self.num_kv_heads,
4028            self.head_dim,
4029            self.hidden_size,
4030        );
4031        // Collect the longest run of consecutive eligible layers.
4032        // Looped Transformer: stop at the loop boundary so the CPU can
4033        // apply loop_final_norm between iterations.
4034        let loop_end = if self.loop_final_norm {
4035            ((li0 / self.physical_layers) + 1) * self.physical_layers
4036        } else {
4037            self.num_layers
4038        };
4039        let mut layers: Vec<crate::gpu_metal::ChunkLayer> = Vec::new();
4040        let mut stored_at: Vec<usize> = Vec::new();
4041        for li in li0..self.num_layers.min(loop_end).min(cap) {
4042            let lw = &self.weights.layers[self.phys_layer(li)];
4043            if lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some() {
4044                break;
4045            }
4046            let AttnKind::Full {
4047                wq,
4048                wk,
4049                wv,
4050                wo,
4051                q_norm,
4052                k_norm,
4053                output_gate: false,
4054                softplus_gate: None,
4055                bias,
4056            } = &lw.attn
4057            else {
4058                break;
4059            };
4060            let FfnKind::Dense(d) = &lw.ffn else { break };
4061            if d.act != Act::Silu {
4062                break;
4063            }
4064            // q8_row (row_scale populated), or q4_tiled / q4tp (row_scale
4065            // empty — their scales are in the payload). Mixing across the
4066            // seven projections of one layer is fine; the encoder branches
4067            // per weight on the tensor's dtype. Anything else refuses.
4068            fn cw(t: &QTensor) -> Option<(usize, usize, usize, &[f32])> {
4069                t.q8_row_parts()
4070                    .or_else(|| t.q4t_parts().map(|(i, r, c)| (i, r, c, &[][..])))
4071                    .or_else(|| t.q4tp_parts().map(|(i, r, c)| (i, r, c, &[][..])))
4072            }
4073            let parts = (
4074                cw(wq),
4075                cw(wk),
4076                cw(wv),
4077                cw(wo),
4078                cw(&d.gate_proj),
4079                cw(&d.up_proj),
4080                cw(&d.down_proj),
4081            );
4082            let (Some(pq), Some(pk), Some(pv), Some(po), Some(pg), Some(pu), Some(pd)) = parts
4083            else {
4084                break;
4085            };
4086            let layer = &self.kv_cache.layers[li];
4087            if layer.mode != crate::kv_cache::KvMode::F32 || layer.o1.is_some() {
4088                break;
4089            }
4090            stored_at.push(layer.head_len(0));
4091            layers.push(crate::gpu_metal::ChunkLayer {
4092                model: &model,
4093                kv_id: self.graph_kv_id,
4094                layer: li,
4095                wq: pq,
4096                wk: pk,
4097                wv: pv,
4098                wo: po,
4099                gate: pg,
4100                up: pu,
4101                down: pd,
4102                input_norm: &lw.input_norm,
4103                post_norm: &lw.post_norm,
4104                bias: bias
4105                    .as_ref()
4106                    .map(|(a, bb, cc)| (a.as_slice(), bb.as_slice(), cc.as_slice())),
4107                q_norm: q_norm.as_deref(),
4108                k_norm: k_norm.as_deref(),
4109                inv_freq: &inv_freq,
4110                rd: self.rotary_dim,
4111                nh,
4112                nkv,
4113                hd,
4114                hs,
4115                inter: d.gate_proj.rows(),
4116                gemma: matches!(self.norm_style, cortiq_core::NormStyle::Gemma),
4117                eps: self.rms_eps as f32,
4118            });
4119        }
4120        if layers.is_empty() {
4121            return li0;
4122        }
4123        let row = nkv * hd;
4124        let mut store: Vec<(Vec<f32>, Vec<f32>, Vec<f32>)> = stored_at
4125            .iter()
4126            .map(|&st| (vec![0f32; b * row], vec![0f32; b * row], vec![0f32; st + b]))
4127            .collect();
4128        let mut io: Vec<crate::gpu_metal::ChunkIo> = Vec::with_capacity(layers.len());
4129        for (i, (ok, ov, oi)) in store.iter_mut().enumerate() {
4130            let li = layers[i].layer;
4131            let layer = &self.kv_cache.layers[li];
4132            io.push(crate::gpu_metal::ChunkIo {
4133                cpu_stored: stored_at[i],
4134                cpu_k: (0..nkv).map(|g| layer.head_keys(g)).collect(),
4135                cpu_v: (0..nkv).map(|g| layer.head_values(g)).collect(),
4136                out_k: ok,
4137                out_v: ov,
4138                imp: oi,
4139            });
4140        }
4141        let n_run = layers.len();
4142        let last = layers.last().map(|l| l.layer + 1).unwrap_or(li0);
4143        // Device-side embedding when the run starts the model and the
4144        // embedding matrix is q8_row-mapped.
4145        let ep = embed_ids.and_then(|ids| {
4146            self.weights
4147                .embed_tokens
4148                .q8_row_parts()
4149                .map(|(idx, rows, _c, rs)| crate::gpu_metal::ChunkEmbed {
4150                    idx,
4151                    rows,
4152                    row_scale: rs,
4153                    ids,
4154                    mult: self.embed_multiplier,
4155                })
4156        });
4157        if embed_ids.is_some() && ep.is_none() {
4158            return li0;
4159        }
4160        if !crate::gpu_metal::chunk_run_gpu(&layers, &mut io, h, b, pos0, ep.as_ref()) {
4161            return li0;
4162        }
4163        drop(io);
4164        drop(layers);
4165        // CPU caches stay the owners of record: append the chunk rows
4166        // and bank the importance masses per layer.
4167        for (i, (ok, ov, oi)) in store.iter().enumerate().take(n_run) {
4168            let li = li0 + i;
4169            let layer = &mut self.kv_cache.layers[li];
4170            for bi in 0..b {
4171                layer.append(
4172                    &ok[bi * row..(bi + 1) * row],
4173                    &ov[bi * row..(bi + 1) * row],
4174                    &[],
4175                );
4176            }
4177            layer.accumulate_imp(oi);
4178        }
4179        last
4180    }
4181
4182    /// Is layer `li` a sliding-window (local-RoPE) layer? Gemma-3:
4183    /// every `pattern`-th layer is global, the rest are local.
4184    fn layer_is_local(&self, li: usize) -> bool {
4185        if let Some(layers) = &self.sliding_layers {
4186            return layers.get(li).copied().unwrap_or(false);
4187        }
4188        match self.swa {
4189            Some((_, pattern)) => (li + 1) % pattern.max(1) != 0,
4190            None => false,
4191        }
4192    }
4193
4194    /// The RoPE table for layer `li` (local layers may have their own;
4195    /// Gemma-4 global layers use the proportional padded table).
4196    fn layer_inv_freq(&self, li: usize) -> std::sync::Arc<Vec<f32>> {
4197        if self.layer_is_local(li) {
4198            if let Some(f) = &self.inv_freq_local {
4199                return f.clone();
4200            }
4201        } else if let Some(f) = &self.inv_freq_global {
4202            return f.clone();
4203        }
4204        self.inv_freq.clone()
4205    }
4206
4207    /// The attend window for layer `li` (None = full context).
4208    fn layer_window(&self, li: usize) -> Option<usize> {
4209        self.swa
4210            .and_then(|(w, _)| self.layer_is_local(li).then_some(w))
4211    }
4212
4213    fn layer_num_heads(&self, li: usize) -> usize {
4214        self.attention_heads_per_layer
4215            .as_ref()
4216            .and_then(|v| v.get(li).copied())
4217            .unwrap_or(self.num_heads)
4218    }
4219
4220    fn layer_rope_scale(&self, li: usize) -> f32 {
4221        if self.layer_is_local(li) {
4222            self.rope_scale_local
4223        } else {
4224            self.rope_scale
4225        }
4226    }
4227
4228    /// Attention geometry of layer `li`: (num_kv_heads, head_dim,
4229    /// rotary_dim). Gemma-4 global layers override all three.
4230    fn layer_geom(&self, li: usize) -> (usize, usize, usize) {
4231        if !self.layer_is_local(li) {
4232            if let Some((ghd, gkv)) = self.global_attn {
4233                return (gkv, ghd, ghd);
4234            }
4235        }
4236        (
4237            self.num_kv_heads,
4238            self.head_dim,
4239            if self.layer_is_local(li) {
4240                self.rotary_dim_local.unwrap_or(self.rotary_dim)
4241            } else {
4242                self.rotary_dim
4243            },
4244        )
4245    }
4246
4247    /// Forward one position through all layers (hybrid dispatch).
4248    fn forward_layers(
4249        &mut self,
4250        hidden: &[f32],
4251        position: usize,
4252        task_mask: Option<&TaskMask>,
4253    ) -> Vec<f32> {
4254        self.forward_layers_upto(hidden, position, task_mask, None)
4255    }
4256
4257    // ── Network pipeline-split building blocks (coordinator/worker) ──
4258    // A remote worker owns layers [from ..= upto] and their KV; the
4259    // coordinator owns the rest plus embed / final norm / head. Attention
4260    // causality is per-layer, so a whole prompt's boundary hiddens ship
4261    // as one batch and decode ships one vector per token.
4262
4263    /// Embed one token id (embed multiplier applied).
4264    pub fn embed_id(&self, id: u32) -> Vec<f32> {
4265        self.embed_single(id)
4266    }
4267
4268    /// Refuse the archs/modes whose forward cannot be cut at a layer
4269    /// boundary. Loud by design: a split that silently changed the math
4270    /// would be a chimera.
4271    pub fn split_supported(&self) -> Result<(), String> {
4272        if self.dsv4.is_some() {
4273            return Err(
4274                "network split: DeepSeek-V4 runs its own fused stack (not splittable yet)".into(),
4275            );
4276        }
4277        if self.g3n.is_some() {
4278            return Err(
4279                "network split: Gemma-3n runs its own AltUp stack (not splittable yet)".into(),
4280            );
4281        }
4282        Ok(())
4283    }
4284
4285    /// Forward `hidden` through layers [from ..= upto] at `position`,
4286    /// appending those layers' KV/state. Both split sides call this
4287    /// over their own range; a task mask applies to the span's own
4288    /// layers (each side masks what it runs).
4289    pub fn forward_span(
4290        &mut self,
4291        hidden: &[f32],
4292        position: usize,
4293        from: usize,
4294        upto: usize,
4295        task_mask: Option<&TaskMask>,
4296    ) -> Result<Vec<f32>, String> {
4297        self.split_supported()?;
4298        if from > upto || upto >= self.num_layers {
4299            return Err(format!(
4300                "forward_span: layer range {from}..={upto} outside 0..{}",
4301                self.num_layers
4302            ));
4303        }
4304        if hidden.len() != self.hidden_size {
4305            return Err(format!(
4306                "forward_span: hidden len {} ≠ hidden_size {}",
4307                hidden.len(),
4308                self.hidden_size
4309            ));
4310        }
4311        Ok(self.forward_layers_span(hidden, position, task_mask, from, Some(upto)))
4312    }
4313
4314    /// Final norm + lm_head over a boundary hidden (the final-logit
4315    /// softcap is applied by lm_head_forward itself).
4316    pub fn logits_from_hidden(&mut self, hidden: &[f32]) -> Vec<f32> {
4317        let normed = inference::rms_norm(
4318            hidden,
4319            &self.weights.final_norm,
4320            self.rms_eps,
4321            self.norm_style,
4322        );
4323        self.lm_head_forward(&normed)
4324    }
4325
4326    /// Sample the next token with this pipeline's sampler state.
4327    pub fn sample_next(&mut self, logits: &[f32], past_tokens: &[u32]) -> u32 {
4328        sampler::sample_with_scratch(
4329            logits,
4330            &self.sampler_config,
4331            past_tokens,
4332            &mut self.rng,
4333            &mut self.sampler_scratch,
4334        )
4335    }
4336
4337    /// Fresh sequence: clear KV, reuse history and device mirrors.
4338    pub fn reset_session(&mut self) {
4339        self.kv_cache.clear();
4340        self.kv_history.clear();
4341        crate::gpu::graph_kv_reset(self.graph_kv_id);
4342    }
4343
4344    /// Batched span prefill from token ids (coordinator side): embed +
4345    /// layers [0 ..= upto]; returns the boundary hiddens of ALL positions
4346    /// (ids.len() × hidden). Rides the same layer-major machinery as the
4347    /// local prefill; falls back to the per-position walk under
4348    /// CMF_PREFILL=seq.
4349    pub fn prefill_span_ids(
4350        &mut self,
4351        ids: &[u32],
4352        start_pos: usize,
4353        upto: usize,
4354        task_mask: Option<&TaskMask>,
4355    ) -> Result<Vec<f32>, String> {
4356        self.split_supported()?;
4357        if upto >= self.num_layers {
4358            return Err(format!(
4359                "prefill_span_ids: upto {upto} outside 0..{}",
4360                self.num_layers
4361            ));
4362        }
4363        // Same predicate as the whole-stack prefill: a span whose GDN
4364        // state lives on the device must walk positions through the
4365        // graph, not through the batched CPU span.
4366        if self.can_prefill_batched() && !self.graph_prefill_preferred() {
4367            Ok(self.prefill_batch_span(PrefillIn::Ids(ids), start_pos, task_mask, 0, upto + 1))
4368        } else {
4369            let hs = self.hidden_size;
4370            let mut out = Vec::with_capacity(ids.len() * hs);
4371            for (i, &id) in ids.iter().enumerate() {
4372                let emb = self.embed_id(id);
4373                out.extend_from_slice(&self.forward_span(
4374                    &emb,
4375                    start_pos + i,
4376                    0,
4377                    upto,
4378                    task_mask,
4379                )?);
4380            }
4381            Ok(out)
4382        }
4383    }
4384
4385    /// Batched span prefill from boundary hiddens (worker side): layers
4386    /// [from ..= upto] for every position in the batch; returns the batch.
4387    pub fn prefill_span_hidden(
4388        &mut self,
4389        hidden: &[f32],
4390        start_pos: usize,
4391        from: usize,
4392        upto: usize,
4393        task_mask: Option<&TaskMask>,
4394    ) -> Result<Vec<f32>, String> {
4395        self.split_supported()?;
4396        let hs = self.hidden_size;
4397        if hidden.is_empty() || hidden.len() % hs != 0 {
4398            return Err(format!(
4399                "prefill_span_hidden: {} floats is not a multiple of hidden {hs}",
4400                hidden.len()
4401            ));
4402        }
4403        if from > upto || upto >= self.num_layers {
4404            return Err(format!(
4405                "prefill_span_hidden: layer range {from}..={upto} outside 0..{}",
4406                self.num_layers
4407            ));
4408        }
4409        if self.can_prefill_batched() && !self.graph_prefill_preferred() {
4410            Ok(self.prefill_batch_span(
4411                PrefillIn::Hidden(hidden),
4412                start_pos,
4413                task_mask,
4414                from,
4415                upto + 1,
4416            ))
4417        } else {
4418            let b = hidden.len() / hs;
4419            let mut out = Vec::with_capacity(hidden.len());
4420            for i in 0..b {
4421                let h = self.forward_span(
4422                    &hidden[i * hs..(i + 1) * hs],
4423                    start_pos + i,
4424                    from,
4425                    upto,
4426                    task_mask,
4427                )?;
4428                out.extend_from_slice(&h);
4429            }
4430            Ok(out)
4431        }
4432    }
4433
4434    /// Build the whole-token wgpu graph for a pure-attention q1 model (every
4435    /// layer Full q1 + dense q1 FFN, no gate/bias). Returns the post-stack
4436    /// hidden (caller does final norm + lm_head), or None to fall back.
4437    fn try_token_graph_wgpu(
4438        &self,
4439        hidden: &[f32],
4440        position: usize,
4441        logits_out: &mut Vec<f32>,
4442        layers_run: &mut usize,
4443    ) -> Option<Vec<f32>> {
4444        self.try_token_graph_wgpu_steps(
4445            hidden,
4446            position,
4447            logits_out,
4448            1,
4449            None,
4450            Some(layers_run),
4451            0,
4452            self.num_layers,
4453        )
4454    }
4455
4456    /// The span twin (network split): the graph covers [from..upto_excl)
4457    /// — one submit per SEGMENT per token. lm_head folds in only when
4458    /// the span reaches the last layer.
4459    fn try_token_graph_wgpu_span(
4460        &self,
4461        hidden: &[f32],
4462        position: usize,
4463        logits_out: &mut Vec<f32>,
4464        from: usize,
4465        upto_excl: usize,
4466        layers_run: &mut usize,
4467    ) -> Option<Vec<f32>> {
4468        self.try_token_graph_wgpu_steps(
4469            hidden,
4470            position,
4471            logits_out,
4472            1,
4473            None,
4474            Some(layers_run),
4475            from,
4476            upto_excl,
4477        )
4478    }
4479
4480    /// Greedy burst: forward `t_next` and let the device pick + re-embed
4481    /// the next k−1 tokens — k frames, ONE submit, k ids back. The ZML
4482    /// trade, on wgpu. None ⇒ caller keeps the per-token path.
4483    fn try_multi_burst(&self, t_next: u32, position: usize, k: usize) -> Option<Vec<u32>> {
4484        if self.o1_active() || self.attn_softcap > 0.0 {
4485            return None;
4486        }
4487        let graph_on = crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode);
4488        if !graph_on || crate::gpu::graph_unsupported() {
4489            // Same memo as the decode site: this path builds the very
4490            // same graph, so a model it cannot build for must not be
4491            // walked again here either. Missing this guard was worth
4492            // 2.5x on an Adreno — 0.361 tok/s against 0.905 — because
4493            // the burst retried per token what decode had already given
4494            // up on.
4495            return None;
4496        }
4497        let emb = self.embed_single(t_next);
4498        let mut lg = Vec::new();
4499        let mut ids = Vec::new();
4500        self.try_token_graph_wgpu_steps(
4501            &emb,
4502            position,
4503            &mut lg,
4504            k,
4505            Some(&mut ids),
4506            None,
4507            0,
4508            self.num_layers,
4509        )?;
4510        (ids.len() == k).then_some(ids)
4511    }
4512
4513    /// Multi-step greedy: k whole frames in ONE submit, argmax and re-embed
4514    /// on the device. `ids_out` receives the k winner ids; the hidden/logits
4515    /// outputs are NOT produced in that mode.
4516    fn try_token_graph_wgpu_steps(
4517        &self,
4518        hidden: &[f32],
4519        position: usize,
4520        logits_out: &mut Vec<f32>,
4521        steps: usize,
4522        ids_out: Option<&mut Vec<u32>>,
4523        layers_run: Option<&mut usize>,
4524        from: usize,
4525        upto_excl: usize,
4526    ) -> Option<Vec<f32>> {
4527        // O(1) Nyström decode runs off the sealed state, not the KV cache the
4528        // graph mirrors — never take the graph while o1 is active.
4529        let o1_gpu = std::env::var("CMF_O1_GPU").as_deref() == Ok("1");
4530        if (self.o1_active() && !o1_gpu) || self.attn_softcap > 0.0 {
4531            // Softcapped scores have no graph kernel yet — CPU owns them.
4532            // o1 rides the graph only behind CMF_O1_GPU=1 while the port
4533            // proves itself; without it the CPU path owns o1 as before.
4534            return None;
4535        }
4536        // Per-layer sealed o1 state for the graph. During prefill the
4537        // state is still Collecting -> views are None -> the graph
4538        // refuses below and the CPU prefill records the q trace and
4539        // seals, exactly as the o1 design requires.
4540        let o1_views: Vec<Option<Vec<crate::nystrom::O1DeviceView<'_>>>> = (from..upto_excl)
4541            .map(|li| {
4542                if !o1_gpu {
4543                    return None;
4544                }
4545                self.kv_cache.layers[self.phys_layer(li)].o1_views()
4546            })
4547            .collect();
4548        if self.o1_active() && o1_gpu {
4549            // Any o1 layer not sealed (or degenerate exact-only) keeps the
4550            // whole token on the CPU: half-graph forwards would desync.
4551            let want: usize = (from..upto_excl)
4552                .filter(|li| !matches!(self.kv_cache.layers[self.phys_layer(*li)].o1, None))
4553                .count();
4554            let have = o1_views.iter().filter(|v| v.is_some()).count();
4555            if want == 0 || have != want {
4556                return None;
4557            }
4558        }
4559        let nh = self.num_heads;
4560        let (nkv, hd, rd) = self.layer_geom(0);
4561        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
4562        let mut layers = Vec::with_capacity(upto_excl - from);
4563        let mut model = None;
4564        let dbg = std::env::var("CMF_GRAPH_DEBUG").is_ok();
4565        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
4566            if let Some((_, i, kind, rs)) = t.graph_weight() {
4567                return Some(crate::gpu::GraphW {
4568                    idx: i,
4569                    kind,
4570                    row_scale: rs,
4571                    data: &[],
4572                });
4573            }
4574            // Small unquantized projections (GDN in_proj_a/b) stay f32.
4575            t.as_f32().map(|d| crate::gpu::GraphW {
4576                idx: 0,
4577                kind: 4,
4578                row_scale: &[],
4579                data: d,
4580            })
4581        }
4582        for li in from..upto_excl {
4583            let lw = &self.weights.layers[self.phys_layer(li)];
4584            if dbg {
4585                let ak = match &lw.attn {
4586                    AttnKind::Mla(_) => "Mla".into(),
4587                    AttnKind::Full {
4588                        output_gate, bias, ..
4589                    } => format!("Full gate={output_gate} bias={}", bias.is_some()),
4590                    AttnKind::LinearGdn(_) => "LinearGdn".into(),
4591                    AttnKind::Kda(_) => "Kda".into(),
4592                    AttnKind::Linear(_) => "Linear".into(),
4593                    AttnKind::ShortConv(_) => "ShortConv".into(),
4594                };
4595                let fk = match &lw.ffn {
4596                    FfnKind::Dense(_) => "Dense",
4597                    FfnKind::Moe(_) => "Moe",
4598                    FfnKind::DenseMoe(_) => "DenseMoe",
4599                };
4600                eprintln!("graph L{li}: attn={ak} ffn={fk}");
4601            }
4602            let gffn = match &lw.ffn {
4603                FfnKind::DenseMoe(_) => return None, // dual branch: CPU path
4604                FfnKind::Dense(d) => crate::gpu::GraphFfn::Dense {
4605                    gate: gw(&d.gate_proj)?,
4606                    up: gw(&d.up_proj)?,
4607                    down: gw(&d.down_proj)?,
4608                },
4609                FfnKind::Moe(m) => {
4610                    // v1 scope: softmax router + shared expert + uniform
4611                    // q4t expert trios (the MoE-hybrid coder class). The
4612                    // biased/sigmoid routers and adaptive τ keep the CPU
4613                    // path, where they are implemented.
4614                    if m.router_sigmoid
4615                        || m.expert_bias.is_some()
4616                        || m.route_tau.is_some()
4617                        || m.mask.is_some()
4618                    {
4619                        return None;
4620                    }
4621                    let (se, sg) = m.shared.as_ref()?;
4622                    let sgate = gw(sg.as_ref()?)?;
4623                    let router = gw(&m.router)?;
4624                    let inter = m.experts.first()?.gate_proj.rows();
4625                    let mut experts = Vec::with_capacity(m.experts.len() + 1);
4626                    // q4t or q4tp, but not both in one layer — the kernels
4627                    // are picked per layer, not per expert.
4628                    let mut q4tp: Option<bool> = None;
4629                    // The mixed 2-bit profile: q2tp gate/up over a q4tp
4630                    // down. Uniform across the layer, like `q4tp` itself.
4631                    let mut gu_q2: Option<bool> = None;
4632                    for e in m.experts.iter().chain(std::iter::once(se)) {
4633                        if !matches!(e.act, Act::Silu)
4634                            || e.gate_proj.rows() != inter
4635                            || e.up_proj.rows() != inter
4636                        {
4637                            return None;
4638                        }
4639                        let (mm, gi, ui, di, is_p, is_q2) = match e.gate_proj.mapped_q4t() {
4640                            Some((mm, gi)) => (
4641                                mm,
4642                                gi,
4643                                e.up_proj.mapped_q4t()?.1,
4644                                e.down_proj.mapped_q4t()?.1,
4645                                false,
4646                                false,
4647                            ),
4648                            None => match e.gate_proj.mapped_q2tp() {
4649                                Some((mm, gi)) => (
4650                                    mm,
4651                                    gi,
4652                                    e.up_proj.mapped_q2tp()?.1,
4653                                    e.down_proj.mapped_q4tp()?.1,
4654                                    true,
4655                                    true,
4656                                ),
4657                                None => {
4658                                    let (mm, gi) = e.gate_proj.mapped_q4tp()?;
4659                                    (
4660                                        mm,
4661                                        gi,
4662                                        e.up_proj.mapped_q4tp()?.1,
4663                                        e.down_proj.mapped_q4tp()?.1,
4664                                        true,
4665                                        false,
4666                                    )
4667                                }
4668                            },
4669                        };
4670                        if *q4tp.get_or_insert(is_p) != is_p || *gu_q2.get_or_insert(is_q2) != is_q2
4671                        {
4672                            // The shared expert rides in the same packed
4673                            // buffer as the routed ones, so a layer that
4674                            // mixes layouts cannot be indexed by one stride.
4675                            // Say so: the symptom is a whole model quietly
4676                            // running its MoE on the CPU.
4677                            tracing::warn!(
4678                                "MoE layer mixes expert layouts (q4tp={is_p}, q2tp gate/up={is_q2})                                  — every expert of a layer, INCLUDING the shared one, must share                                  a layout. The whole-token graph declines this layer."
4679                            );
4680                            return None;
4681                        }
4682                        model.get_or_insert_with(|| mm.clone());
4683                        experts.push((gi, ui, di));
4684                    }
4685                    crate::gpu::GraphFfn::Moe {
4686                        router,
4687                        shared_gate: sgate,
4688                        experts,
4689                        n_exp: m.experts.len(),
4690                        // CMF_TOPK_PROBE: timing probe only — output is WRONG.
4691                        // Fewer experts shrink the MoE arithmetic while the
4692                        // dispatch count stays identical, which is the only
4693                        // clean way to tell a launch-bound decode from a
4694                        // compute-bound one.
4695                        top_k: std::env::var("CMF_TOPK_PROBE")
4696                            .ok()
4697                            .and_then(|v| v.parse::<usize>().ok())
4698                            .filter(|k| *k > 0 && *k <= m.top_k)
4699                            .unwrap_or(m.top_k),
4700                        inter,
4701                        norm_topk: m.norm_topk_prob,
4702                        q4tp: q4tp?,
4703                        gu_q2: gu_q2.unwrap_or(false),
4704                    }
4705                }
4706            };
4707            let attn = match &lw.attn {
4708                AttnKind::Full {
4709                    wq,
4710                    wk,
4711                    wv,
4712                    wo,
4713                    q_norm,
4714                    k_norm,
4715                    output_gate,
4716                    softplus_gate,
4717                    bias,
4718                } => {
4719                    if softplus_gate.is_some() || self.attention_heads_per_layer.is_some() {
4720                        return None;
4721                    }
4722                    let (m, _, _, _) = wq.graph_weight()?;
4723                    model = Some(m.clone());
4724                    crate::gpu::GraphAttn::Full {
4725                        wq: gw(wq)?,
4726                        wk: gw(wk)?,
4727                        wv: gw(wv)?,
4728                        wo: gw(wo)?,
4729                        q_norm: q_norm.as_deref(),
4730                        k_norm: k_norm.as_deref(),
4731                        bias: bias
4732                            .as_ref()
4733                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
4734                        output_gate: *output_gate,
4735                        cpu_k: self.kv_cache.layers[li].k_heads(),
4736                        cpu_v: self.kv_cache.layers[li].v_heads(),
4737                    }
4738                }
4739                AttnKind::LinearGdn(w) => {
4740                    let cfg = self.gdn_cfg?;
4741                    let (m, _, _, _) = w.in_proj_qkv.graph_weight()?;
4742                    model = Some(m.clone());
4743                    crate::gpu::GraphAttn::Gdn {
4744                        qkv: gw(&w.in_proj_qkv)?,
4745                        z: gw(&w.in_proj_z)?,
4746                        a: gw(&w.in_proj_a)?,
4747                        b: gw(&w.in_proj_b)?,
4748                        out: gw(&w.out_proj)?,
4749                        conv1d: &w.conv1d,
4750                        a_log: &w.a_log,
4751                        dt_bias: &w.dt_bias,
4752                        norm: &w.norm,
4753                        nv: cfg.num_v_heads,
4754                        nk: cfg.num_k_heads,
4755                        dk: cfg.key_head_dim,
4756                        dv: cfg.value_head_dim,
4757                        kk: cfg.conv_kernel,
4758                        cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
4759                    }
4760                }
4761                _ => return None,
4762            };
4763            layers.push(crate::gpu::GraphLayer {
4764                input_norm: &lw.input_norm,
4765                attn,
4766                post_norm: &lw.post_norm,
4767                ffn: gffn,
4768            });
4769        }
4770        let model = model?;
4771        // Fold final-norm + lm_head into the graph when this call wants logits
4772        // and the lm_head is a graphable (quantized) weight — the graph then
4773        // reads back logits (into logits_out) instead of the hidden, dropping
4774        // the separate CPU/GPU lm_head op + its sync. Never the f32 fallback:
4775        // an unquantized lm_head is vocab·hidden and must not be uploaded.
4776        let lm_gw = if upto_excl == self.num_layers
4777            && self.graph_want_logits
4778            && std::env::var("CMF_GPU_LMHEAD")
4779                .map(|v| v != "0")
4780                .unwrap_or(true)
4781        {
4782            self.weights.lm_head.graph_weight().map(|(_, i, kind, rs)| {
4783                (
4784                    crate::gpu::GraphW {
4785                        idx: i,
4786                        kind,
4787                        row_scale: rs,
4788                        data: &[],
4789                    },
4790                    self.weights.lm_head.rows(),
4791                )
4792            })
4793        } else {
4794            None
4795        };
4796        let lm = lm_gw.as_ref().map(|(gw, rows)| (gw, *rows));
4797        // Multi-step re-embeds the winner on the device.
4798        let emb_gw = if steps > 1 {
4799            self.weights
4800                .embed_tokens
4801                .graph_weight()
4802                .map(|(_, i, kind, rs)| {
4803                    (
4804                        crate::gpu::GraphW {
4805                            idx: i,
4806                            kind,
4807                            row_scale: rs,
4808                            data: &[],
4809                        },
4810                        self.weights.embed_tokens.rows(),
4811                        self.embed_multiplier as f32,
4812                    )
4813                })
4814        } else {
4815            None
4816        };
4817
4818        // Loop boundaries: virtual layer indices after which final_norm is
4819        // applied (mid-stack only; the GLOBAL last layer's norm folds into
4820        // lm_head). Span-relative — the executor compares its enumerate
4821        // index. A span ending mid-stack keeps its boundary norm even when
4822        // it is the span's own last layer.
4823        let loop_norm_at: Vec<usize> = if self.loop_final_norm {
4824            (from..upto_excl.min(self.num_layers - 1))
4825                .filter(|&li| (li + 1) % self.physical_layers == 0)
4826                .map(|li| li - from)
4827                .collect()
4828        } else {
4829            Vec::new()
4830        };
4831        let mut h = hidden.to_vec();
4832        crate::gpu::forward_token_graph(
4833            &model,
4834            self.graph_kv_id,
4835            &layers,
4836            &o1_views,
4837            self.o1_epoch,
4838            &self.inv_freq,
4839            &mut h,
4840            nh,
4841            nkv,
4842            hd,
4843            rd,
4844            self.hidden_size,
4845            self.intermediate_size,
4846            position,
4847            self.kv_cache.max_seq_len,
4848            gemma,
4849            self.rms_eps as f32,
4850            lm,
4851            &self.weights.final_norm,
4852            logits_out,
4853            &loop_norm_at,
4854            steps,
4855            emb_gw.as_ref().map(|(gw, rows, m)| (gw, *rows, *m)),
4856            ids_out,
4857            layers_run,
4858            from,
4859        )
4860        .then_some(h)
4861    }
4862
4863    /// Batched prefill: k contiguous prompt positions through the whole wgpu
4864    /// graph in ONE submit (projections/FFN as GEMMs). `hiddens` is [k·hidden]
4865    /// in/out (embeddings in, layer output out); KV mirror / GDN state advance.
4866    /// false ⇒ unsupported → caller keeps the per-position graph.
4867    fn try_batch_graph_wgpu(
4868        &self,
4869        hiddens: &mut [f32],
4870        positions: &[usize],
4871        k: usize,
4872        spec: Option<crate::gpu::SpecTail<'_>>,
4873    ) -> bool {
4874        let _tb = std::time::Instant::now();
4875        if self.attn_softcap > 0.0 {
4876            return false; // capped scores: no graph kernel — CPU path
4877        }
4878        if self.o1_active() {
4879            return false;
4880        }
4881        let nh = self.num_heads;
4882        let (nkv, hd, rd) = self.layer_geom(0);
4883        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
4884        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
4885            if let Some((_, i, kind, rs)) = t.graph_weight() {
4886                return Some(crate::gpu::GraphW {
4887                    idx: i,
4888                    kind,
4889                    row_scale: rs,
4890                    data: &[],
4891                });
4892            }
4893            t.as_f32().map(|d| crate::gpu::GraphW {
4894                idx: 0,
4895                kind: 4,
4896                row_scale: &[],
4897                data: d,
4898            })
4899        }
4900        let built: Option<(
4901            Vec<crate::gpu::GraphLayer<'_>>,
4902            std::sync::Arc<cortiq_core::CmfModel>,
4903        )> = (|| {
4904            let mut layers = Vec::with_capacity(self.num_layers);
4905            let mut model = None;
4906            for li in 0..self.num_layers {
4907                let lw = &self.weights.layers[self.phys_layer(li)];
4908                // MoE routes per token, so its experts are encoded token by
4909                // token inside the batched submit while attention and the
4910                // projections stay GEMMs. Refusing MoE here is what left
4911                // prefill running one position at a time: 33 tok/s against
4912                // 54 on decode, i.e. reading the prompt was slower than
4913                // writing the answer.
4914                let gffn = match &lw.ffn {
4915                    FfnKind::Dense(d) => crate::gpu::GraphFfn::Dense {
4916                        gate: gw(&d.gate_proj)?,
4917                        up: gw(&d.up_proj)?,
4918                        down: gw(&d.down_proj)?,
4919                    },
4920                    FfnKind::Moe(m) => {
4921                        if m.router_sigmoid
4922                            || m.expert_bias.is_some()
4923                            || m.route_tau.is_some()
4924                            || m.mask.is_some()
4925                        {
4926                            return None;
4927                        }
4928                        let (se, sg) = m.shared.as_ref()?;
4929                        let sgate = gw(sg.as_ref()?)?;
4930                        let router = gw(&m.router)?;
4931                        let inter = m.experts.first()?.gate_proj.rows();
4932                        let mut experts = Vec::with_capacity(m.experts.len() + 1);
4933                        let mut q4tp: Option<bool> = None;
4934                        let mut gu_q2: Option<bool> = None;
4935                        for e in m.experts.iter().chain(std::iter::once(se)) {
4936                            if !matches!(e.act, Act::Silu)
4937                                || e.gate_proj.rows() != inter
4938                                || e.up_proj.rows() != inter
4939                            {
4940                                return None;
4941                            }
4942                            // Same ladder as the token graph: q4t → q2tp
4943                            // (mixed profile: 2-bit gate/up over a q4tp
4944                            // down) → q4tp. Uniform across the layer.
4945                            let (mm, gi, ui, di, is_p, is_q2) = match e.gate_proj.mapped_q4t() {
4946                                Some((mm, gi)) => (
4947                                    mm,
4948                                    gi,
4949                                    e.up_proj.mapped_q4t()?.1,
4950                                    e.down_proj.mapped_q4t()?.1,
4951                                    false,
4952                                    false,
4953                                ),
4954                                None => match e.gate_proj.mapped_q2tp() {
4955                                    Some((mm, gi)) => (
4956                                        mm,
4957                                        gi,
4958                                        e.up_proj.mapped_q2tp()?.1,
4959                                        e.down_proj.mapped_q4tp()?.1,
4960                                        true,
4961                                        true,
4962                                    ),
4963                                    None => {
4964                                        let (mm, gi) = e.gate_proj.mapped_q4tp()?;
4965                                        (
4966                                            mm,
4967                                            gi,
4968                                            e.up_proj.mapped_q4tp()?.1,
4969                                            e.down_proj.mapped_q4tp()?.1,
4970                                            true,
4971                                            false,
4972                                        )
4973                                    }
4974                                },
4975                            };
4976                            if *q4tp.get_or_insert(is_p) != is_p
4977                                || *gu_q2.get_or_insert(is_q2) != is_q2
4978                            {
4979                                return None;
4980                            }
4981                            model.get_or_insert_with(|| mm.clone());
4982                            experts.push((gi, ui, di));
4983                        }
4984                        crate::gpu::GraphFfn::Moe {
4985                            router,
4986                            shared_gate: sgate,
4987                            experts,
4988                            n_exp: m.experts.len(),
4989                            top_k: m.top_k,
4990                            inter,
4991                            norm_topk: m.norm_topk_prob,
4992                            q4tp: q4tp?,
4993                            gu_q2: gu_q2.unwrap_or(false),
4994                        }
4995                    }
4996                    _ => return None,
4997                };
4998                let attn = match &lw.attn {
4999                    AttnKind::Full {
5000                        wq,
5001                        wk,
5002                        wv,
5003                        wo,
5004                        q_norm,
5005                        k_norm,
5006                        output_gate,
5007                        softplus_gate,
5008                        bias,
5009                    } => {
5010                        if softplus_gate.is_some() || self.attention_heads_per_layer.is_some() {
5011                            return None;
5012                        }
5013                        let (m, _, _, _) = wq.graph_weight()?;
5014                        model = Some(m.clone());
5015                        crate::gpu::GraphAttn::Full {
5016                            wq: gw(wq)?,
5017                            wk: gw(wk)?,
5018                            wv: gw(wv)?,
5019                            wo: gw(wo)?,
5020                            q_norm: q_norm.as_deref(),
5021                            k_norm: k_norm.as_deref(),
5022                            bias: bias
5023                                .as_ref()
5024                                .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
5025                            output_gate: *output_gate,
5026                            cpu_k: self.kv_cache.layers[li].k_heads(),
5027                            cpu_v: self.kv_cache.layers[li].v_heads(),
5028                        }
5029                    }
5030                    AttnKind::LinearGdn(w) => {
5031                        let cfg = self.gdn_cfg?;
5032                        let (m, _, _, _) = w.in_proj_qkv.graph_weight()?;
5033                        model = Some(m.clone());
5034                        crate::gpu::GraphAttn::Gdn {
5035                            qkv: gw(&w.in_proj_qkv)?,
5036                            z: gw(&w.in_proj_z)?,
5037                            a: gw(&w.in_proj_a)?,
5038                            b: gw(&w.in_proj_b)?,
5039                            out: gw(&w.out_proj)?,
5040                            conv1d: &w.conv1d,
5041                            a_log: &w.a_log,
5042                            dt_bias: &w.dt_bias,
5043                            norm: &w.norm,
5044                            nv: cfg.num_v_heads,
5045                            nk: cfg.num_k_heads,
5046                            dk: cfg.key_head_dim,
5047                            dv: cfg.value_head_dim,
5048                            kk: cfg.conv_kernel,
5049                            cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
5050                        }
5051                    }
5052                    _ => return None,
5053                };
5054                layers.push(crate::gpu::GraphLayer {
5055                    input_norm: &lw.input_norm,
5056                    attn,
5057                    post_norm: &lw.post_norm,
5058                    ffn: gffn,
5059                });
5060            }
5061            Some((layers, model?))
5062        })();
5063        let Some((layers, model)) = built else {
5064            {
5065                use std::sync::atomic::{AtomicBool, Ordering};
5066                static SAID: AtomicBool = AtomicBool::new(false);
5067                if !SAID.swap(true, Ordering::Relaxed) {
5068                    tracing::warn!("batch graph: BUILDER refused (layer weights/kinds)");
5069                }
5070            }
5071            return false;
5072        };
5073        if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
5074            eprintln!("batch-build: {:.1} ms", _tb.elapsed().as_secs_f64() * 1e3);
5075        }
5076        crate::gpu::forward_batch_graph(
5077            &model,
5078            self.graph_kv_id,
5079            &layers,
5080            &self.inv_freq,
5081            hiddens,
5082            nh,
5083            nkv,
5084            hd,
5085            rd,
5086            self.hidden_size,
5087            self.intermediate_size,
5088            positions,
5089            self.kv_cache.max_seq_len,
5090            gemma,
5091            self.rms_eps as f32,
5092            k,
5093            spec,
5094        )
5095    }
5096
5097    /// Same, stopping after layer `upto` inclusive (routing probe φ).
5098/// `CMF_DSV4_DRAFT_PROBE=1` — grade the draft against what the trunk goes on
5099/// to produce. Off by default; it runs a whole draft per decoded token.
5100fn draft_probe() -> bool {
5101    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5102    *ON.get_or_init(|| std::env::var("CMF_DSV4_DRAFT_PROBE").is_ok_and(|v| v != "0"))
5103}
5104
5105    /// `CMF_DSV4_DRAFT_PROBE=1`: measure how much of the draft the trunk
5106    /// would have agreed with, WITHOUT verifying or rolling anything back.
5107    ///
5108    /// The number this produces decides the whole speculation design — at
5109    /// acceptance a, a block of B positions yields 1 + a + a² + ... tokens
5110    /// per trunk pass — so it is worth measuring before any of the machinery
5111    /// that would exploit it exists. Each draft is parked with the position
5112    /// it was made at, and graded as the real tokens arrive.
5113    /// `CMF_DSV4_SPEC=1` — the DeepSeek-V4 speculative decode: draft five
5114    /// on the card, verify them in one batched trunk pass, commit the
5115    /// accepted prefix, roll the rest back.
5116    #[cfg(feature = "gpu")]
5117    fn dsv4_spec_on() -> bool {
5118        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5119        *ON.get_or_init(|| std::env::var("CMF_DSV4_SPEC").map(|v| v != "0").unwrap_or(true))
5120    }
5121
5122    /// One speculative round at the decode tip. `t_next` is the token the
5123    /// sampler just committed for `next_pos`. Returns the EXTRA accepted
5124    /// tokens (possibly none) and the new position, with `graph_logits`
5125    /// left holding the last accepted position's logits — exactly what the
5126    /// loop top expects. `None` means "speculate not this round": nothing
5127    /// was committed, the caller forwards normally.
5128    #[cfg(feature = "gpu")]
5129    fn dsv4_spec_step(
5130        &mut self,
5131        tip_token: u32,
5132        t_next: u32,
5133        next_pos: usize,
5134        drafted: &mut usize,
5135        accepted_ctr: &mut usize,
5136    ) -> Option<(Vec<u32>, usize)> {
5137        let t_all = std::time::Instant::now();
5138        if std::env::var("CMF_DSV4_SPEC_TIME").is_ok() {
5139            thread_local! {
5140                static LAST: std::cell::Cell<Option<std::time::Instant>> =
5141                    const { std::cell::Cell::new(None) };
5142            }
5143            LAST.with(|l| {
5144                if let Some(prev) = l.get() {
5145                    eprintln!("между раундами {:.1} мс", prev.elapsed().as_secs_f64() * 1e3);
5146                }
5147                l.set(Some(std::time::Instant::now()));
5148            });
5149        }
5150        if std::env::var("CMF_DSV4_SPEC_DEBUG").is_ok() {
5151            eprintln!("spec_step: вход pos={next_pos}");
5152        }
5153        let n_layers = self.dsv4.as_ref().map(|b| b.1.len())?;
5154        let cfg = self.dsv4.as_ref().map(|b| b.2)?;
5155        // The draft state and its capture, armed exactly as the probe does.
5156        if self.dspark.is_none() {
5157            let t = crate::dsv4::dspark_targets(&self.dsv4_mtp, &cfg, n_layers);
5158            if t.is_empty() {
5159                return None;
5160            }
5161            crate::dsv4::dspark_arm(&t, cfg.dim);
5162            self.dspark = Some(crate::dsv4::DsparkState::new(
5163                self.dsv4_mtp.len(),
5164                &cfg,
5165                t.len(),
5166            ));
5167        }
5168        let targets = crate::dsv4::dspark_targets(&self.dsv4_mtp, &cfg, n_layers);
5169        let pack = crate::dsv4::dspark_pack_get(&self.dsv4_mtp, &cfg);
5170        if pack.is_none() && std::env::var("CMF_DSV4_SPEC_DEBUG").is_ok() {
5171            eprintln!("spec_step: пак не построился (targets {targets:?})");
5172        }
5173        let pack = pack?;
5174        let block = crate::dsv4::dspark_block();
5175        let b_box = self.dsv4.as_mut()?;
5176        let (g, layers, st) = (&b_box.0, &b_box.1, &mut b_box.3);
5177        let ds = self.dspark.as_mut()?;
5178        // The tip's captures: either this token ran on a normal path that
5179        // filled the thread-local, or the previous spec round left them.
5180        let dbg = std::env::var("CMF_DSV4_SPEC_DEBUG").is_ok();
5181        if !crate::dsv4::dspark_take(&mut ds.main_hidden) && !ds.have_hidden {
5182            if dbg {
5183                eprintln!("spec_step: нет захвата");
5184            }
5185            return None;
5186        }
5187        ds.have_hidden = true;
5188        let tip_pos = next_pos.checked_sub(1)?;
5189        let draft_started = std::time::Instant::now();
5190        let mut conf = Vec::new();
5191        let props = crate::dsv4::dspark_draft_gpu(
5192            g,
5193            &self.dsv4_mtp,
5194            &cfg,
5195            ds,
5196            pack,
5197            st.kv_id,
5198            tip_token,
5199            tip_pos,
5200            self.pool.as_deref(),
5201            &mut conf,
5202        );
5203        self.dspark_draft_ns += draft_started.elapsed().as_nanos();
5204        *drafted += block;
5205        if props.is_empty() || props[0] != t_next {
5206            if dbg {
5207                eprintln!(
5208                    "spec_step: черновик {} (props0={:?} t_next={t_next})",
5209                    if props.is_empty() { "пуст" } else { "мимо" },
5210                    props.first()
5211                );
5212            }
5213            return None;
5214        }
5215        let mut k_verify = crate::dsv4::dspark_verify_k().min(props.len());
5216        // Adaptive depth: positions the draft itself doubts are paid for on
5217        // every verify and delivered almost never (natural-text survival
5218        // [.67 .50 .29 .08 .04]). `CMF_DSPARK_CONF_MIN=p` trims the fed
5219        // prefix at the first proposal whose confidence drops below p; on
5220        // predictable text the confidences stay high and nothing changes.
5221        let conf_min = {
5222            static M: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
5223            *M.get_or_init(|| {
5224                std::env::var("CMF_DSPARK_CONF_MIN")
5225                    .ok()
5226                    .and_then(|v| v.parse().ok())
5227                    .unwrap_or(0.0)
5228            })
5229        };
5230        if conf_min > 0.0 && conf.len() >= props.len() {
5231            let mut keep = 1usize;
5232            while keep < k_verify && conf.get(keep).copied().unwrap_or(0.0) >= conf_min {
5233                keep += 1;
5234            }
5235            k_verify = k_verify.min(keep.max(2));
5236        }
5237        if k_verify < 2 {
5238            return None;
5239        }
5240        let mut fed = Vec::with_capacity(k_verify);
5241        fed.push(t_next);
5242        fed.extend_from_slice(&props[1..k_verify]);
5243        let mut argmax = Vec::new();
5244        let mut logits_all = Vec::new();
5245        let mut walked = Vec::new();
5246        let txn = crate::dsv4::dsv4_verify_chunk(
5247            g,
5248            layers,
5249            &cfg,
5250            st,
5251            &fed,
5252            next_pos,
5253            &self.inv_freq,
5254            self.pool.as_deref(),
5255            &targets,
5256            &mut argmax,
5257            &mut logits_all,
5258            &mut walked,
5259        );
5260        if txn.is_none() && dbg {
5261            eprintln!("spec_step: verify отказал");
5262        }
5263        let txn = txn?;
5264        let b = fed.len();
5265        let mut accepted = 1usize;
5266        while accepted < b && fed[accepted] == argmax[accepted - 1] {
5267            accepted += 1;
5268        }
5269        // `CMF_DSV4_SPEC_FORCE_REJECT=1` — accept nothing beyond the known
5270        // token, every round: the pure rollback exerciser. The output must
5271        // stay byte-identical to the plain walk; anything else is a
5272        // transaction bug, isolated from the acceptance logic.
5273        if std::env::var("CMF_DSV4_SPEC_FORCE_REJECT").is_ok_and(|v| v != "0") {
5274            accepted = 1;
5275        }
5276        if std::env::var("CMF_DSV4_SPEC_TRACE").is_ok() {
5277            eprintln!(
5278                "spec@{next_pos}: fed={fed:?} argmax={argmax:?} accepted={accepted}"
5279            );
5280        }
5281        let t_fin = std::time::Instant::now();
5282        if !crate::dsv4::dsv4_spec_finish(
5283            g,
5284            layers,
5285            &cfg,
5286            st,
5287            txn,
5288            accepted,
5289            &fed,
5290            &self.inv_freq,
5291            self.pool.as_deref(),
5292        ) {
5293            tracing::warn!("dsv4: спекулятивный откат не удался — состояние подозрительно");
5294            return None;
5295        }
5296        if std::env::var("CMF_DSV4_SPEC_TIME").is_ok() {
5297            eprintln!("finish(k={accepted}): {:.1} мс", t_fin.elapsed().as_secs_f64() * 1e3);
5298        }
5299        *accepted_ctr += accepted - 1;
5300        // Captures per accepted token: device targets photographed by the
5301        // batch, host targets from the verify's own walk. The last one
5302        // becomes the new tip's draft input; every one owes the ring an
5303        // entry for its position.
5304        let (hc, dim) = (cfg.hc_mult, cfg.dim);
5305        // A PARTIAL capture layer never rides the chain, so the batch has
5306        // no photograph of it — its tip capture comes from the walk's own
5307        // note like any host layer's. Filtering on the device set alone
5308        // handed the draft a never-written photo slot for exactly the
5309        // most important input (the last layer feeds main_proj), and the
5310        // split configurations drafted at 27% no matter the residency.
5311        let dev_caps: Vec<usize> = targets
5312            .iter()
5313            .copied()
5314            .filter(|&t| {
5315                st.dev_set.get(t).copied().unwrap_or(false)
5316                    && !st.partial_set.get(t).copied().unwrap_or(false)
5317            })
5318            .collect();
5319        let mut caps_all = vec![0.0f32; dev_caps.len() * b * hc * dim];
5320        if !crate::gpu_wgpu::dsv4_spec_cap_read_all(b, dev_caps.len(), hc * dim, &mut caps_all) {
5321            return None;
5322        }
5323        for t in 0..accepted {
5324            let tip = t + 1 == accepted;
5325            for (slot, &tl) in targets.iter().enumerate() {
5326                if let Some(di) = dev_caps.iter().position(|&d| d == tl) {
5327                    let lo = (di * b + t) * hc * dim;
5328                    crate::dsv4::dspark_capture(
5329                        &caps_all[lo..lo + hc * dim],
5330                        &cfg,
5331                        slot,
5332                        &mut ds.main_hidden,
5333                    );
5334                } else if tip
5335                    && crate::dsv4::dspark_peek_slot(slot, dim, {
5336                        let lo = slot * dim;
5337                        &mut ds.main_hidden[lo..lo + dim]
5338                    })
5339                {
5340                    // The tip's host-layer captures are the walk's own
5341                    // per-layer notes — exact. (The walk that ran last ended
5342                    // on exactly this token, on both the accept-all and the
5343                    // rollback path.)
5344                } else {
5345                    // Intermediate tokens: the post-tail state stands in for
5346                    // the per-layer capture on host targets below the last
5347                    // layer. Ring-entry quality only; the tip is exact.
5348                    crate::dsv4::dspark_capture(
5349                        &walked[t * hc * dim..(t + 1) * hc * dim],
5350                        &cfg,
5351                        slot,
5352                        &mut ds.main_hidden,
5353                    );
5354                }
5355            }
5356            crate::dsv4::dspark_ring_append(g, &self.dsv4_mtp, &cfg, ds, next_pos + t, self.pool.as_deref());
5357        }
5358        let row = logits_all[(accepted - 1) * cfg.vocab..accepted * cfg.vocab].to_vec();
5359        self.graph_logits = Some(row);
5360        // The speculative loop never runs the probe, so the trunk tally has
5361        // no other place to cycle. Armed only when someone asked for the
5362        // dump; the host tail is the only tallying path here, which is
5363        // precisely the population a partial pack would serve.
5364        if std::env::var("CMF_DSV4_TRUNK_PICK_DUMP").is_ok() {
5365            crate::dsv4::trunk_freq_note(&crate::dsv4::pick_tally_take());
5366            crate::dsv4::pick_tally_arm();
5367        }
5368        if std::env::var("CMF_DSV4_SPEC_TIME").is_ok() {
5369            eprintln!("spec_step total {:.1} мс (k={accepted})", t_all.elapsed().as_secs_f64() * 1e3);
5370        }
5371        Some((fed[1..accepted].to_vec(), next_pos + accepted))
5372    }
5373
5374    fn dspark_probe(&mut self, position: usize, token_id: u32) {
5375        if self.dsv4_mtp.is_empty() || !Self::draft_probe() {
5376            return;
5377        }
5378        // What the trunk just routed to, for this token.
5379        let trunk_now = crate::dsv4::pick_tally_take();
5380        crate::dsv4::trunk_freq_note(&trunk_now);
5381        if !trunk_now.is_empty() {
5382            self.dspark_trunk_picks.push(trunk_now);
5383            let keep = crate::dsv4::dspark_block();
5384            if self.dspark_trunk_picks.len() > keep {
5385                self.dspark_trunk_picks.remove(0);
5386            }
5387        }
5388        // Grade whatever is waiting: the token just decoded sits at
5389        // `position`, so it answers the draft made at `position - 1 - i`.
5390        for p in std::mem::take(&mut self.dspark_pending) {
5391            let Some(i) = position.checked_sub(p.0 + 1) else {
5392                continue;
5393            };
5394            let mut p = p;
5395            if i < p.1.len() {
5396                if p.2 && p.1[i] == token_id {
5397                    p.3 = i + 1;
5398                } else {
5399                    p.2 = false;
5400                }
5401                if i + 1 < p.1.len() {
5402                    self.dspark_pending.push(p);
5403                    continue;
5404                }
5405            }
5406            self.dspark_hist.push(p.3);
5407            self.dspark_real.push(token_id);
5408        }
5409        let Some(b) = &mut self.dsv4 else { return };
5410        let (g, layers, cfg) = (&b.0, &b.1, b.2);
5411        let n_layers = layers.len();
5412        if self.dspark.is_none() {
5413            let t = crate::dsv4::dspark_targets(&self.dsv4_mtp, &cfg, n_layers);
5414            if t.is_empty() {
5415                return;
5416            }
5417            eprintln!("DSpark: захват со слоёв {t:?}, блок {}", crate::dsv4::dspark_block());
5418            crate::dsv4::dspark_arm(&t, cfg.dim);
5419            self.dspark = Some(crate::dsv4::DsparkState::new(
5420                self.dsv4_mtp.len(),
5421                &cfg,
5422                t.len(),
5423            ));
5424        }
5425        let ds = self.dspark.as_mut().unwrap();
5426        if !crate::dsv4::dspark_take(&mut ds.main_hidden) {
5427            return; // this token ran on a path that captures nothing
5428        }
5429        let mut conf = Vec::new();
5430        crate::dsv4::pick_tally_arm();
5431        // The trunk has already consumed the adaptive VRAM budget. Until the
5432        // draft owns an explicit bounded device pack, its tensors are an
5433        // out-of-core CPU/disk tier by contract: never let per-op probes try
5434        // to squeeze another multi-gigabyte MTP expert cache onto the card.
5435        let draft_started = std::time::Instant::now();
5436        #[cfg(feature = "gpu")]
5437        let gpu_draft = crate::dsv4::dspark_gpu_on();
5438        #[cfg(not(feature = "gpu"))]
5439        let gpu_draft = false;
5440        let props = if gpu_draft {
5441            #[cfg(feature = "gpu")]
5442            {
5443                let kv_id = b.3.kv_id;
5444                match crate::dsv4::dspark_pack_get(&self.dsv4_mtp, &cfg) {
5445                    Some(pk) => crate::dsv4::dspark_draft_gpu(
5446                        g,
5447                        &self.dsv4_mtp,
5448                        &cfg,
5449                        ds,
5450                        pk,
5451                        kv_id,
5452                        token_id,
5453                        position,
5454                        self.pool.as_deref(),
5455                        &mut conf,
5456                    ),
5457                    None => Vec::new(),
5458                }
5459            }
5460            #[cfg(not(feature = "gpu"))]
5461            Vec::new()
5462        } else {
5463            crate::gpu::cpu_scope(|| {
5464                crate::dsv4::dspark_draft(
5465                    g,
5466                    &self.dsv4_mtp,
5467                    &cfg,
5468                    ds,
5469                    token_id,
5470                    position,
5471                    self.pool.as_deref(),
5472                    &mut conf,
5473                )
5474            })
5475        };
5476        self.dspark_draft_ns += draft_started.elapsed().as_nanos();
5477        let draft_picks = crate::dsv4::pick_tally_take();
5478        crate::dsv4::dspark_freq_note(&draft_picks);
5479        // Re-arm for the NEXT trunk token; the probe runs after the forward,
5480        // so this is the only place that can.
5481        crate::dsv4::pick_tally_arm();
5482        if !props.is_empty() {
5483            // Two ratios, side by side: what a batched verify over the trunk
5484            // would read against what it asks for, and the same for the
5485            // draft's three stages. Near 1.0 means a batch amortises nothing.
5486            let (tu, tt) = {
5487                let flat: Vec<(usize, Vec<usize>)> = self
5488                    .dspark_trunk_picks
5489                    .iter()
5490                    .flat_map(|v| v.iter().cloned())
5491                    .collect();
5492                // Per layer, across the window of tokens.
5493                let mut per: std::collections::HashMap<usize, Vec<usize>> =
5494                    std::collections::HashMap::new();
5495                for (li, picks) in flat {
5496                    per.entry(li).or_default().extend(picks);
5497                }
5498                let n = per.len().max(1);
5499                let mut u = 0usize;
5500                let mut t = 0usize;
5501                for (_, v) in per {
5502                    t += v.len();
5503                    u += v.iter().collect::<std::collections::HashSet<_>>().len();
5504                }
5505                (u / n, t / n)
5506            };
5507            let (du, dt) = crate::dsv4::tally_unique(&draft_picks);
5508            self.dspark_exp.push((tu, tt, du, dt));
5509            self.dspark_pending.push((position, props, true, 0));
5510        }
5511        if self.dspark_hist.len() >= 8 && self.dspark_hist.len() % 8 == 0 {
5512            let n = self.dspark_hist.len() as f32;
5513            let mean: f32 = self.dspark_hist.iter().sum::<usize>() as f32 / n;
5514            let block = crate::dsv4::dspark_block();
5515            let mut at = vec![0usize; block + 1];
5516            for &k in &self.dspark_hist {
5517                at[k] += 1;
5518            }
5519            // Prefix survival: S_i = P(the first i positions all held).
5520            let mut surv = Vec::with_capacity(block);
5521            for i in 1..=block {
5522                let k = at[i..].iter().sum::<usize>() as f32 / n;
5523                surv.push(format!("{k:.2}"));
5524            }
5525            let distinct = self
5526                .dspark_real
5527                .iter()
5528                .collect::<std::collections::HashSet<_>>()
5529                .len();
5530            let (tu, tt, du, dt) = self.dspark_exp.iter().fold((0, 0, 0, 0), |a, b| {
5531                (a.0 + b.0, a.1 + b.1, a.2 + b.2, a.3 + b.3)
5532            });
5533            let m = self.dspark_exp.len().max(1);
5534            eprintln!(
5535                "DSpark: черновиков {}, принято в среднем {mean:.2} из {block} \
5536                 (токенов за проход {:.2}), распределение {at:?}, выживание [{}]",
5537                self.dspark_hist.len(),
5538                mean + 1.0,
5539                surv.join(" ")
5540            );
5541            eprintln!(
5542                "DSpark: разных токенов {distinct} из {} (вырожденность), \
5543                 эксперты ствол {}/{} на слой за {block} токенов, \
5544                 черновик {}/{} за блок, draft {:.2} мс/блок",
5545                self.dspark_real.len(),
5546                tu / m,
5547                tt / m,
5548                du / m,
5549                dt / m,
5550                self.dspark_draft_ns as f64 / self.dspark_exp.len().max(1) as f64 / 1e6
5551            );
5552        }
5553    }
5554
5555    fn forward_layers_upto(
5556        &mut self,
5557        hidden: &[f32],
5558        position: usize,
5559        task_mask: Option<&TaskMask>,
5560        upto: Option<usize>,
5561    ) -> Vec<f32> {
5562        // In-process multi-GPU: each segment runs pinned to its card,
5563        // and the only thing crossing the boundary is one hidden vector
5564        // that never leaves this address space. Same layer split the
5565        // network mode does, minus the second process, the socket, the
5566        // serialization and the dir_hash handshake.
5567        if let Some(plan) = self.gpu_plan.clone() {
5568            if upto.is_none() && plan.len() > 1 {
5569                let mut h = hidden.to_vec();
5570                for &(dev, from, upto_incl) in plan.iter() {
5571                    h = crate::gpu::with_device(dev, || {
5572                        self.forward_layers_span(&h, position, task_mask, from, Some(upto_incl))
5573                    });
5574                }
5575                return h;
5576            }
5577        }
5578        self.forward_layers_span(hidden, position, task_mask, 0, upto)
5579    }
5580
5581    /// Split this pipeline's layer stack across local GPUs: segment i
5582    /// runs on `devices[i]`. Contiguous and even by layer count — the
5583    /// VRAM-weighted planner is the next step, and an uneven card pair
5584    /// is why it will be needed. `None` clears the plan.
5585    pub fn set_gpu_plan(&mut self, devices: Option<&[usize]>) -> Result<(), String> {
5586        self.set_gpu_plan_at(devices, None)
5587    }
5588
5589    /// The same, with an explicit first boundary (`--peer-split`): card
5590    /// 0 takes layers `[0..at)`, the rest split what remains. Uneven
5591    /// cards, or an attention-heavy head, are why this knob exists.
5592    pub fn set_gpu_plan_at(
5593        &mut self,
5594        devices: Option<&[usize]>,
5595        at: Option<usize>,
5596    ) -> Result<(), String> {
5597        let Some(devs) = devices.filter(|d| d.len() > 1) else {
5598            self.gpu_plan = None;
5599            return Ok(());
5600        };
5601        self.split_supported()?;
5602        let n = self.num_layers;
5603        if devs.len() > n {
5604            return Err(format!("{} devices for {n} layers", devs.len()));
5605        }
5606        if let Some(k) = at {
5607            if k == 0 || k >= n {
5608                return Err(format!("split at {k}: the model has {n} layers"));
5609            }
5610            if devs.len() == 2 {
5611                self.gpu_plan = Some(std::sync::Arc::new(vec![
5612                    (devs[0], 0, k - 1),
5613                    (devs[1], k, n - 1),
5614                ]));
5615                return Ok(());
5616            }
5617            return Err(format!(
5618                "an explicit split point takes exactly 2 devices, got {}",
5619                devs.len()
5620            ));
5621        }
5622        let per = n.div_ceil(devs.len());
5623        let mut plan = Vec::with_capacity(devs.len());
5624        let mut from = 0usize;
5625        for &d in devs {
5626            if from >= n {
5627                break;
5628            }
5629            let upto = (from + per - 1).min(n - 1);
5630            plan.push((d, from, upto));
5631            from = upto + 1;
5632        }
5633        self.gpu_plan = Some(std::sync::Arc::new(plan));
5634        Ok(())
5635    }
5636
5637    /// The active in-process split, if any: (device, first layer, last).
5638    pub fn gpu_plan(&self) -> Option<Vec<(usize, usize, usize)>> {
5639        self.gpu_plan.as_ref().map(|p| p.as_ref().clone())
5640    }
5641
5642    /// Layer span [from ..= upto] (upto None = last layer): the building
5643    /// block the network pipeline-split rides on. `from > 0` skips the
5644    /// arch escape hatches (the pub `forward_span` refuses those archs
5645    /// first) and the whole-token graph — the plain per-layer loop is
5646    /// the canonical executor for a partial stack.
5647    fn forward_layers_span(
5648        &mut self,
5649        hidden: &[f32],
5650        position: usize,
5651        task_mask: Option<&TaskMask>,
5652        from: usize,
5653        upto: Option<usize>,
5654    ) -> Vec<f32> {
5655        debug_assert!(from == 0 || (self.dsv4.is_none() && self.g3n.is_none()));
5656        // DeepSeek-V4 runs its own stack: the state is hc_mult copies, and
5657        // the forward returns LOGITS, not a hidden — the head is inside it
5658        // (the final fold sits between the last layer and the norm). The
5659        // token id rides in `hidden[0]`, written by embed_single, because
5660        // the hash layers route by id rather than by content.
5661        if let Some(b) = &mut self.dsv4 {
5662            let _ = (task_mask, upto);
5663            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
5664            let (g, layers, cfg, st) = (&b.0, &b.1, b.2, &mut b.3);
5665            st.pos = position;
5666            let mut logits = Vec::new();
5667            crate::dsv4::forward_token(
5668                g,
5669                layers,
5670                &cfg,
5671                st,
5672                token_id,
5673                &self.inv_freq,
5674                self.pool.as_deref(),
5675                &mut logits,
5676            );
5677            self.graph_logits = Some(logits);
5678            self.dspark_probe(position, token_id);
5679            // The caller expects a hidden; the logits went out of band, as
5680            // with the fused lm_head path.
5681            return vec![0.0; self.hidden_size];
5682        }
5683        // Gemma-3n runs its own stack (4 AltUp replicas don't fit this
5684        // loop); `hidden` is the extended embedding from embed_single.
5685        if let Some(b) = &self.g3n {
5686            let _ = (task_mask, upto);
5687            return crate::g3n::g3n_forward(
5688                &b.0,
5689                &b.1,
5690                hidden,
5691                position,
5692                &mut self.kv_cache.layers,
5693                self.num_heads,
5694                self.num_kv_heads,
5695                self.head_dim,
5696                self.pool.as_deref(),
5697            );
5698        }
5699        let mut h = hidden.to_vec();
5700        // Split borrows: copy scalars / clone handles so the per-layer
5701        // cfg does not hold `&self` while the KV cache is `&mut`.
5702        let (nh, _nkv, _hd, hs, _rd, eps) = (
5703            self.num_heads,
5704            self.num_kv_heads,
5705            self.head_dim,
5706            self.hidden_size,
5707            self.rotary_dim,
5708            self.rms_eps,
5709        );
5710        let pool = self.pool.clone();
5711        // Opt-in wgpu token-graph attention (discrete Vulkan/DX12): the whole
5712        // attention sub-block runs resident in one submit. Off by default.
5713        // Whole-token wgpu graph: eligibility + arbitration.
5714        //  - explicit CMF_GPU_WGPU_GRAPH forces it on/off;
5715        //  - discrete adapters (4090: decode 76 -> 137 tok/s) and GDN
5716        //    hybrids (recurrent state device-resident, no CPU twin to
5717        //    race) TRUST it;
5718        //  - integrated/mobile adapters RACE it against the normal path
5719        //    at generation granularity (gpu::graph_race_*) — tiled
5720        //    mobile GPUs can turn the ~300-dispatch graph into seconds
5721        //    per token, while a fast phone GPU keeps its win.
5722        let graph_env = std::env::var("CMF_GPU_WGPU_GRAPH").ok();
5723        let graph_on = match graph_env.as_deref() {
5724            Some("0") => false,
5725            Some("prefill") => false, // decode keeps the per-op path
5726            Some(_) => true,
5727            // Unset: same discrete-only default as every other graph
5728            // site. "Is the GPU on" used to stand in here — which made
5729            // the 0.2 tok/s whole-token graph race-eligible on mobile
5730            // adapters and cost 12-14× on first tokens (cmfmobile
5731            // TUNING.md); integrated GPUs keep the per-op probe path.
5732            None => crate::gpu::wgpu_graph_default(),
5733        };
5734        let graph_trusted =
5735            graph_env.is_some() || crate::gpu::wgpu_graph_default() || self.gdn_cfg.is_some();
5736        let race_eligible = graph_on
5737            && upto.is_none()
5738            && task_mask.is_none()
5739            && from == 0
5740            && !crate::gpu::graph_unsupported();
5741        let mut tail_start = 0usize;
5742        if race_eligible && crate::gpu::graph_race_use_graph(graph_trusted) {
5743            let t_graph = std::time::Instant::now();
5744            let mut lg = Vec::new();
5745            let mut gl = 0usize;
5746            let built = self.try_token_graph_wgpu(hidden, position, &mut lg, &mut gl);
5747            // Past the transient guards (o1 still collecting, a softcap)
5748            // a refusal is about the weights and will never change —
5749            // remember it instead of walking every layer again next
5750            // token.
5751            if built.is_none() && !self.o1_active() && self.attn_softcap == 0.0 {
5752                crate::gpu::graph_mark_unsupported();
5753            }
5754            graph_note(built.is_some());
5755            if let Some(hh) = built {
5756                let dur = t_graph.elapsed();
5757                if std::env::var("CMF_GRAPH_PROF").is_ok() {
5758                    eprintln!("graph-call: {:.2} ms total", dur.as_secs_f64() * 1000.0);
5759                }
5760                if gl > 0 && gl < self.num_layers {
5761                    // Device prefix: the graph ran layers 0..gl and handed
5762                    // back the boundary hidden — the loop below owns the
5763                    // tail. The prefix layers' KV/state advanced on the
5764                    // device; the tail's advances on the host below. One
5765                    // boundary crossing per token.
5766                    h = hh;
5767                    tail_start = gl;
5768                } else if graph_trusted || !crate::gpu::graph_race_first_token_hopeless(dur) {
5769                    if !graph_trusted {
5770                        crate::gpu::graph_race_record(true, dur);
5771                    }
5772                    if !lg.is_empty() {
5773                        // Graph produced logits (final-norm + lm_head folded in) —
5774                        // pad/cap to vocab and hand them to the sampler directly.
5775                        lg.resize(self.vocab_size, 0.0);
5776                        if let Some(c) = self.final_softcap {
5777                            for l in lg.iter_mut() {
5778                                *l = c * (*l / c).tanh();
5779                            }
5780                        }
5781                        self.graph_logits = Some(lg);
5782                    }
5783                    return hh;
5784                }
5785                // Hopeless first graph token: discard it and fall through
5786                // to the normal path. Safe exactly here — the prompt KV is
5787                // still CPU-owned (chunked prefill), so recomputing this
5788                // position is exact; the mirror's extra row is never read
5789                // (the race just settled on the normal path).
5790            }
5791        }
5792        // KIMI-LINEAR HAS NO SPLIT BUG. The 2.6× reported from the
5793        // model rotation (12.2 tok/s on one card against 4.6 on two)
5794        // was a single measurement of a model whose arm arbitration is
5795        // borderline, and it did not survive repetition. Three runs an
5796        // arm, same binary, back to back:
5797        //   probe on : 1 GPU 9.5 / 5.7 / 5.9   2 GPU 7.8 / 13.0 / 13.3
5798        //   pinned   : 1 GPU 5.6 / 5.3 / 5.2   2 GPU 3.5 / 4.2 / 3.4
5799        // With the arms pinned the split costs about 1.45×, which is
5800        // what a layer split costs. With the probe free, TWO CARDS RUN
5801        // FASTER — because for this model the CPU arm wins some op
5802        // classes and the probe finds that.
5803        //
5804        // Two things do stand, and both are measured. The token graph
5805        // builds NOTHING here (`covered 0 of 14 layers [0..14)`), so
5806        // every layer walks per-op on either arm — that is where the
5807        // headroom is, not in the split. And this model's benchmark is
5808        // unusable without `CMF_GPU_PROBE=0`: the arbitration alone
5809        // moves it by more than 2×.
5810        //
5811        // Span runs (network split): the graph covers exactly [from..=upto]
5812        // — one submit per SEGMENT per token. No race: its state is global
5813        // and calibrated on full stacks, so spans take the graph only where
5814        // it is trusted by default (discrete adapters / CMF_GPU_WGPU_GRAPH).
5815        let span = from > 0 || upto.is_some();
5816        if span && graph_on && task_mask.is_none() && graph_trusted {
5817            let upto_excl = upto.map_or(self.num_layers, |u| u + 1);
5818            let mut lg = Vec::new();
5819            let mut gl = 0usize;
5820            let span_res =
5821                self.try_token_graph_wgpu_span(hidden, position, &mut lg, from, upto_excl, &mut gl);
5822            graph_note(span_res.is_some() && gl == upto_excl - from);
5823            if std::env::var("CMF_GPU_DEBUG").is_ok() {
5824                // How much of the span the graph actually covered. A
5825                // prefix of nothing means every layer walks per-op and
5826                // the split's extra cost is elsewhere.
5827                static SEEN: std::sync::atomic::AtomicU32 =
5828                    std::sync::atomic::AtomicU32::new(0);
5829                if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 {
5830                    eprintln!(
5831                        "span graph: covered {gl} of {} layers [{from}..{upto_excl}) res={}",
5832                        upto_excl - from,
5833                        span_res.is_some()
5834                    );
5835                }
5836            }
5837            if let Some(hh) = span_res {
5838                if gl == upto_excl - from {
5839                    if !lg.is_empty() {
5840                        lg.resize(self.vocab_size, 0.0);
5841                        if let Some(c) = self.final_softcap {
5842                            for l in lg.iter_mut() {
5843                                *l = c * (*l / c).tanh();
5844                            }
5845                        }
5846                        self.graph_logits = Some(lg);
5847                    }
5848                    crate::gpu::set_layer(-1);
5849                    return hh;
5850                }
5851                // Partial device prefix of the span: CPU owns the tail.
5852                h = hh;
5853                tail_start = from + gl;
5854            }
5855        }
5856        let t_race_cpu = (race_eligible && !graph_trusted).then(std::time::Instant::now);
5857
5858        #[cfg(target_os = "macos")]
5859        let mut gpu_skip_until = 0usize;
5860        for li in tail_start.max(from)..self.num_layers {
5861            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU (CMF_GPU_LAYERS)
5862            if let Some(u) = upto {
5863                if li > u {
5864                    break;
5865                }
5866            }
5867            if let Some(mask) = task_mask {
5868                if !mask.layer_alive(li) {
5869                    continue; // dead layer: residual pass-through
5870                }
5871            }
5872            // Whole-block q1 token graph: a run of consecutive q1
5873            // layers — GDN and full attention — executes with one sync
5874            // per CPU attend instead of per op (macOS/Metal).
5875            #[cfg(target_os = "macos")]
5876            {
5877                if li < gpu_skip_until {
5878                    continue;
5879                }
5880                if task_mask.is_none() {
5881                    let end = self.q1_graph_gpu(li, upto, position, &mut h);
5882                    if end > li {
5883                        gpu_skip_until = end;
5884                        // Looped Transformer: the graph stopped at a loop
5885                        // boundary — apply final norm before the next iteration.
5886                        if self.is_loop_end(end - 1) && end < self.num_layers {
5887                            h = inference::rms_norm(
5888                                &h,
5889                                &self.weights.final_norm,
5890                                self.rms_eps,
5891                                self.norm_style,
5892                            );
5893                        }
5894                        continue;
5895                    }
5896                }
5897            }
5898
5899            let lw = &self.weights.layers[self.phys_layer(li)];
5900            if let Ok(tp) = std::env::var("CMF_TRACE_POS") {
5901                if tp.parse::<usize>().ok() == Some(position) {
5902                    let n: f32 = h.iter().map(|x| x * x).sum::<f32>().sqrt();
5903                    eprintln!(
5904                        "TRACE pos {position} layer {li}: |h| = {n:.6} h0 {:.6} h1 {:.6}",
5905                        h[0], h[1]
5906                    );
5907                }
5908            }
5909            // Norm into the pipeline scratch — the returning rms_norm
5910            // allocated twice per layer per token (roadmap §3 P0).
5911            inference::rms_norm_into(
5912                &h,
5913                &lw.input_norm,
5914                self.rms_eps,
5915                self.norm_style,
5916                &mut self.ws.n1,
5917            );
5918
5919            let attn_out = match &lw.attn {
5920                AttnKind::Mla(w) => {
5921                    let inv_freq_l = self.layer_inv_freq(li);
5922                    let rs = self.layer_rope_scale(li);
5923                    let eps = self.rms_eps;
5924                    let pool = self.pool.clone();
5925                    mla_attention(
5926                        w,
5927                        &self.ws.n1,
5928                        &mut self.kv_cache.layers[li],
5929                        position,
5930                        &inv_freq_l,
5931                        rs,
5932                        eps,
5933                        pool.as_deref(),
5934                    )
5935                }
5936                AttnKind::Linear(w) => {
5937                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
5938                    vmf_phase_forward(
5939                        &self.ws.n1,
5940                        w,
5941                        &cfg,
5942                        &mut self.kv_cache.layers[li].linear_state,
5943                        self.pool.as_deref(),
5944                    )
5945                }
5946                AttnKind::Kda(w) => {
5947                    let cfg = self.kda_cfg.expect("kda layer without kda_cfg");
5948                    crate::linear_core::kda_forward(
5949                        &self.ws.n1,
5950                        w,
5951                        &cfg,
5952                        &mut self.kv_cache.layers[li].linear_state,
5953                        self.pool.as_deref(),
5954                    )
5955                }
5956                AttnKind::LinearGdn(w) => {
5957                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
5958                    gdn_forward(
5959                        &self.ws.n1,
5960                        w,
5961                        &cfg,
5962                        &mut self.kv_cache.layers[li].linear_state,
5963                        self.pool.as_deref(),
5964                    )
5965                }
5966                AttnKind::ShortConv(w) => {
5967                    let cfg = self
5968                        .short_conv_cfg
5969                        .expect("short-conv layer without short_conv_cfg");
5970                    short_conv_forward(
5971                        &self.ws.n1,
5972                        w,
5973                        &cfg,
5974                        &mut self.kv_cache.layers[li].linear_state,
5975                        self.pool.as_deref(),
5976                    )
5977                }
5978                AttnKind::Full {
5979                    wq,
5980                    wk,
5981                    wv,
5982                    wo,
5983                    q_norm,
5984                    k_norm,
5985                    output_gate,
5986                    softplus_gate,
5987                    bias,
5988                } if self.kv_cache.layers[li].o1_sealed() => {
5989                    // O(1) override: decode on the sealed Nyström state
5990                    // instead of the growing KV cache.
5991                    let inv_freq_l = self.layer_inv_freq(li);
5992                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
5993                    let cfg = QwenAttnCfg {
5994                        num_heads: self.layer_num_heads(li),
5995                        num_kv_heads: nkv_l,
5996                        head_dim: hd_l,
5997                        hidden_size: hs,
5998                        position,
5999                        inv_freq: &inv_freq_l,
6000                        rotary_dim: rd_l,
6001                        scale: self.attn_scale,
6002                        softcap: self.attn_softcap,
6003                        window: None,
6004                        v_norm: self.attn_v_norm,
6005                        q_norm: q_norm.as_deref(),
6006                        k_norm: k_norm.as_deref(),
6007                        output_gate: *output_gate,
6008                        softplus_gate: softplus_gate
6009                            .as_ref()
6010                            .map(|(gate, per_head)| (gate, *per_head)),
6011                        rope_scale: self.layer_rope_scale(li),
6012                        bias: bias
6013                            .as_ref()
6014                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
6015                        rms_eps: eps,
6016                        norm_style: self.norm_style,
6017                        pool: pool.as_deref(),
6018                    };
6019                    attention::qwen_attention_nystrom(
6020                        &self.ws.n1,
6021                        wq,
6022                        wk,
6023                        wv,
6024                        wo,
6025                        &mut self.kv_cache.layers[li],
6026                        &cfg,
6027                    )
6028                }
6029                AttnKind::Full {
6030                    wq,
6031                    wk,
6032                    wv,
6033                    wo,
6034                    q_norm,
6035                    k_norm,
6036                    output_gate,
6037                    softplus_gate,
6038                    bias,
6039                } => 'attn: {
6040                    // wgpu token-graph attention (opt-in): whole sub-block in
6041                    // one submit, device K/V mirror. q1 only, no gate/bias/mask.
6042                    if graph_on
6043                        && !*output_gate
6044                        && softplus_gate.is_none()
6045                        && self.attention_heads_per_layer.is_none()
6046                        && bias.is_none()
6047                        && task_mask.is_none()
6048                    {
6049                        let inv_freq_l = self.layer_inv_freq(li);
6050                        let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
6051                        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
6052                        if let (Some((gm, qi)), Some((_, ki)), Some((_, vi)), Some((_, oi))) = (
6053                            wq.mapped_q1(),
6054                            wk.mapped_q1(),
6055                            wv.mapped_q1(),
6056                            wo.mapped_q1(),
6057                        ) {
6058                            let gm = gm.clone();
6059                            let mut out = vec![0f32; hs];
6060                            let cache = &self.kv_cache.layers[li];
6061                            if crate::gpu::attn_dropin(
6062                                &gm,
6063                                self.graph_kv_id,
6064                                li,
6065                                &self.ws.n1,
6066                                qi,
6067                                ki,
6068                                vi,
6069                                oi,
6070                                q_norm.as_deref(),
6071                                k_norm.as_deref(),
6072                                &inv_freq_l,
6073                                nh,
6074                                nkv_l,
6075                                hd_l,
6076                                rd_l,
6077                                hs,
6078                                position,
6079                                self.kv_cache.max_seq_len,
6080                                gemma,
6081                                eps as f32,
6082                                cache.k_heads(),
6083                                cache.v_heads(),
6084                                &mut out,
6085                            ) {
6086                                break 'attn out;
6087                            }
6088                        }
6089                    }
6090                    let masked = task_mask
6091                        .map(|m| m.head_flags(li, self.num_heads).iter().any(|&a| !a))
6092                        .unwrap_or(false);
6093                    let f32_view = (wq.as_f32(), wk.as_f32(), wv.as_f32(), wo.as_f32());
6094                    match (masked, f32_view) {
6095                        // Historical masked path (f32 slices; the loader
6096                        // keeps masked models in f32).
6097                        (true, (Some(q), Some(k), Some(v), Some(o))) => {
6098                            let active_heads = task_mask.unwrap().head_flags(li, self.num_heads);
6099                            attention::multi_head_attention(
6100                                &self.ws.n1,
6101                                q,
6102                                k,
6103                                v,
6104                                o,
6105                                &mut self.kv_cache.layers[li],
6106                                self.num_heads,
6107                                self.num_kv_heads,
6108                                self.head_dim,
6109                                self.hidden_size,
6110                                position,
6111                                &active_heads,
6112                                &self.inv_freq,
6113                            )
6114                        }
6115                        (masked, _) => {
6116                            if masked {
6117                                tracing::warn!(
6118                                    "layer {li}: head mask on quantized weights not \
6119                                     supported yet — executing dense"
6120                                );
6121                            }
6122                            let inv_freq_l = self.layer_inv_freq(li);
6123                            let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
6124                            let cfg = QwenAttnCfg {
6125                                num_heads: self.layer_num_heads(li),
6126                                num_kv_heads: nkv_l,
6127                                head_dim: hd_l,
6128                                hidden_size: hs,
6129                                position,
6130                                inv_freq: &inv_freq_l,
6131                                rotary_dim: rd_l,
6132                                scale: self.attn_scale,
6133                                softcap: self.attn_softcap,
6134                                window: self.layer_window(li),
6135                                v_norm: self.attn_v_norm,
6136                                q_norm: q_norm.as_deref(),
6137                                k_norm: k_norm.as_deref(),
6138                                output_gate: *output_gate,
6139                                softplus_gate: softplus_gate
6140                                    .as_ref()
6141                                    .map(|(gate, per_head)| (gate, *per_head)),
6142                                rope_scale: self.layer_rope_scale(li),
6143                                bias: bias
6144                                    .as_ref()
6145                                    .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
6146                                rms_eps: eps,
6147                                norm_style: self.norm_style,
6148                                pool: pool.as_deref(),
6149                            };
6150                            attention::qwen_attention(
6151                                &self.ws.n1,
6152                                wq,
6153                                wk,
6154                                wv,
6155                                wo,
6156                                &mut self.kv_cache.layers[li],
6157                                &cfg,
6158                            )
6159                        }
6160                    }
6161                }
6162            };
6163            // Gemma sandwich norm: normalize the attention branch before
6164            // it joins the residual stream.
6165            let attn_out = match &self.weights.layers[self.phys_layer(li)].attn_out_norm {
6166                Some(w) => inference::rms_norm(&attn_out, w, self.rms_eps, self.norm_style),
6167                None => attn_out,
6168            };
6169            let lw = &self.weights.layers[self.phys_layer(li)];
6170            inference::add_rmsnorm_fused_into(
6171                &mut h,
6172                &attn_out,
6173                &lw.post_norm,
6174                self.rms_eps,
6175                self.norm_style,
6176                &mut self.ws.p1,
6177            );
6178            let mut attn_out = attn_out;
6179            attention::recycle_buf(&mut attn_out);
6180            let post_normed = &self.ws.p1;
6181
6182            let ffn_masked = task_mask
6183                .map(|m| m.ffn_active_count(li) < self.intermediate_size)
6184                .unwrap_or(false);
6185            // One masked dense CONTRACT, dispatched by cost. The
6186            // activation-zeroing arm (the batched sweep's, validated
6187            // against the replica to 0.8%) computes the FULL fused FFN
6188            // and zeroes the dead — right whenever most neurons live.
6189            // The sparse arm reads ONLY active rows and down columns —
6190            // per-row dots are slower per element than the fused kernel,
6191            // so it pays only once the mask is deep enough. The 0.5
6192            // crossover is first-principles (fused kernels run ~2x the
6193            // per-row dot throughput); a shallow specialist (95% alive)
6194            // stays fused, a --target-sparsity bake flips arms on its
6195            // own weight.
6196            let ffn_out = match (ffn_masked, &lw.ffn) {
6197                (true, FfnKind::Dense(d)) => {
6198                    let tm = task_mask.unwrap();
6199                    let alive = tm.ffn_active_count(li);
6200                    let deep = alive * 2 <= self.intermediate_size;
6201                    if deep && d.down_proj.sparse_col_ok() {
6202                        let active = tm.ffn_active_indices(li);
6203                        sparse_ffn_quant(
6204                            d,
6205                            post_normed,
6206                            &active,
6207                            self.hidden_size,
6208                            self.pool.as_deref(),
6209                        )
6210                    } else if deep
6211                        && let (Some(g), Some(u), Some(dn)) = (
6212                            d.gate_proj.as_f32(),
6213                            d.up_proj.as_f32(),
6214                            d.down_proj.as_f32(),
6215                        )
6216                    {
6217                        let active = tm.ffn_active_indices(li);
6218                        inference::sparse_ffn_forward(
6219                            post_normed,
6220                            g,
6221                            u,
6222                            dn,
6223                            self.hidden_size,
6224                            self.intermediate_size,
6225                            &active,
6226                            self.pool.as_deref(),
6227                        )
6228                    } else {
6229                        let row = tm.ffn_masks.get(li).map(|v| v.as_slice());
6230                        dense_ffn_batch(d, post_normed, 1, self.pool.as_deref(), row)
6231                    }
6232                }
6233                (true, FfnKind::Moe(m)) => {
6234                    // MoE is sparse by expert selection; a task mask
6235                    // narrows the ROUTABLE set via its expert fields
6236                    // (spec §5) when it carries them.
6237                    let allowed = task_mask.and_then(|tm| tm.expert_flags(li, m.experts.len()));
6238                    ffn_forward(
6239                        &lw.ffn,
6240                        post_normed,
6241                        self.pool.as_deref(),
6242                        allowed.as_deref(),
6243                    )
6244                }
6245                (true, FfnKind::DenseMoe(dm)) => dense_moe_ffn(
6246                    dm,
6247                    post_normed,
6248                    &h,
6249                    self.rms_eps,
6250                    self.norm_style,
6251                    self.pool.as_deref(),
6252                ),
6253                (false, _) => match &lw.ffn {
6254                    FfnKind::DenseMoe(dm) => dense_moe_ffn(
6255                        dm,
6256                        post_normed,
6257                        &h,
6258                        self.rms_eps,
6259                        self.norm_style,
6260                        self.pool.as_deref(),
6261                    ),
6262                    _ => {
6263                        let allowed = match (&lw.ffn, task_mask) {
6264                            (FfnKind::Moe(m), Some(tm)) => tm.expert_flags(li, m.experts.len()),
6265                            _ => None,
6266                        };
6267                        ffn_forward(
6268                            &lw.ffn,
6269                            post_normed,
6270                            self.pool.as_deref(),
6271                            allowed.as_deref(),
6272                        )
6273                    }
6274                },
6275            };
6276            let ffn_out = match &self.weights.layers[self.phys_layer(li)].ffn_out_norm {
6277                Some(w) => inference::rms_norm(&ffn_out, w, self.rms_eps, self.norm_style),
6278                None => ffn_out,
6279            };
6280            for (i, &f) in ffn_out.iter().enumerate() {
6281                h[i] += f;
6282            }
6283            let mut ffn_out = ffn_out;
6284            attention::recycle_buf(&mut ffn_out);
6285
6286            // Gemma-4: the layer output is scaled by a learned scalar.
6287            if let Some(sc) = self.weights.layers[self.phys_layer(li)].layer_scale {
6288                for v in h.iter_mut() {
6289                    *v *= sc;
6290                }
6291            }
6292
6293            // Looped Transformer: apply final norm at the end of each loop iteration.
6294            // Nanbeige 4.2: after layer 21 (virtual), apply norm before looping back to layer 0.
6295            if self.is_loop_end(li) && li + 1 < self.num_layers {
6296                h = inference::rms_norm(
6297                    &h,
6298                    &self.weights.final_norm,
6299                    self.rms_eps,
6300                    self.norm_style,
6301                );
6302            }
6303
6304            // Dynamic routing φ capture (on-policy, fireball-style): the
6305            // EMA of the post-residual hidden at the router's phi_layer,
6306            // updated as the context evolves during decode.
6307            if self.dyn_phi_layer == Some(li) {
6308                self.update_dyn_phi(&h);
6309            }
6310        }
6311        crate::gpu::set_layer(-1); // layers done — lm_head outside layer-split
6312        if let Some(t) = t_race_cpu {
6313            crate::gpu::graph_race_record(false, t.elapsed());
6314        }
6315
6316        h
6317    }
6318
6319    /// EMA of φ at the router layer (rolling, weight 0.2 = ~5-token
6320    /// horizon). First observation seeds it exactly.
6321    fn update_dyn_phi(&mut self, h: &[f32]) {
6322        const A: f32 = 0.2;
6323        if self.dyn_phi_ema.len() != h.len() {
6324            self.dyn_phi_ema = vec![0.0; h.len()];
6325            self.dyn_phi_seen = 0;
6326        }
6327        if self.dyn_phi_seen == 0 {
6328            self.dyn_phi_ema.copy_from_slice(h);
6329        } else {
6330            for (e, &v) in self.dyn_phi_ema.iter_mut().zip(h) {
6331                *e = (1.0 - A) * *e + A * v;
6332            }
6333        }
6334        self.dyn_phi_seen += 1;
6335    }
6336
6337    /// Current router φ (EMA at phi_layer); empty until first capture.
6338    pub fn dyn_phi(&self) -> &[f32] {
6339        &self.dyn_phi_ema
6340    }
6341
6342    /// Enable/disable φ capture at the router layer, reset the EMA.
6343    pub fn set_dyn_phi_layer(&mut self, layer: Option<usize>) {
6344        self.dyn_phi_layer = layer;
6345        self.dyn_phi_ema.clear();
6346        self.dyn_phi_seen = 0;
6347    }
6348
6349    /// Skills eligible for dynamic switching: (index, id, phi_layer).
6350    pub fn dynamic_skills(&self) -> Vec<(usize, String, usize)> {
6351        let Some(model) = &self.model else {
6352            return Vec::new();
6353        };
6354        model
6355            .header
6356            .skills
6357            .iter()
6358            .enumerate()
6359            .filter_map(|(i, sk)| {
6360                let ok = matches!(self.dyn_skill_layers.get(i), Some(Some(_)));
6361                let sel = sk.selection.as_ref()?;
6362                (ok).then(|| (i, sk.id.clone(), sel.phi_layer))
6363            })
6364            .collect()
6365    }
6366
6367    /// Index of the currently overlaid skill (None = backbone).
6368    pub fn active_skill(&self) -> Option<usize> {
6369        self.dyn_active
6370    }
6371
6372    /// Enable dynamic per-token skill routing: build the hysteresis
6373    /// router from the container's routable skills, start φ capture at
6374    /// their (shared) phi_layer. Returns the number of routable skills
6375    /// (0 = nothing to route; router stays off). Idempotent.
6376    pub fn enable_dynamic_routing(&mut self) -> usize {
6377        use crate::swarm::{DynRouter, RoutableSkill};
6378        let Some(model) = self.model.clone() else {
6379            return 0;
6380        };
6381        // A blend materialized f32 working tensors into the layers; there
6382        // is no single skill index to revert from → refuse (honest).
6383        if self.dyn_blend_loaded {
6384            tracing::warn!("dynamic routing unavailable on a blend-loaded pipeline");
6385            return 0;
6386        }
6387        // A statically-overlaid skill that is NOT FFN-eligible can't be
6388        // cheaply reverted at generation start → refuse rather than
6389        // silently keep it overlaid.
6390        if let Some(a) = self.dyn_active {
6391            if !matches!(self.dyn_skill_layers.get(a), Some(Some(_))) {
6392                tracing::warn!("loaded skill is not FFN-eligible — dynamic routing unavailable");
6393                return 0;
6394            }
6395        }
6396        let hidden = self.hidden_size;
6397        let mut skills = Vec::new();
6398        for (idx, id, _phi) in self.dynamic_skills() {
6399            if let Some(sel) = model.header.skills[idx].selection.as_ref() {
6400                if let Some(rs) = RoutableSkill::from_descriptor(idx, id, sel, hidden) {
6401                    skills.push(rs);
6402                }
6403            }
6404        }
6405        if skills.is_empty() {
6406            return 0;
6407        }
6408        // Skills should share a phi_layer; warn (not fail) if they don't.
6409        let phi = skills[0].phi_layer;
6410        if skills.iter().any(|s| s.phi_layer != phi) {
6411            tracing::warn!("routable skills disagree on phi_layer; using {phi}");
6412        }
6413        let n = skills.len();
6414        self.set_dyn_phi_layer(Some(phi));
6415        self.dyn_router = Some(DynRouter::new(skills));
6416        n
6417    }
6418
6419    /// Human-readable switch log from the last dynamic-routed generation.
6420    pub fn route_switches(&self) -> Vec<(usize, Option<String>, Option<String>)> {
6421        self.dyn_router
6422            .as_ref()
6423            .map(|r| r.switches.clone())
6424            .unwrap_or_default()
6425    }
6426
6427    /// LM head: hidden → logits [vocab_size]. The dominant matvec of
6428    /// every decode step — row-parallel on the worker pool.
6429    fn lm_head_forward(&self, hidden: &[f32]) -> Vec<f32> {
6430        let rows = self.weights.lm_head.rows();
6431        let mut logits = attention::take_buf(rows.min(self.vocab_size));
6432        self.weights
6433            .lm_head
6434            .matvec(hidden, &mut logits, self.pool.as_deref());
6435        logits.resize(self.vocab_size, 0.0);
6436        if let Some(m) = self.logit_multiplier {
6437            for l in logits.iter_mut() {
6438                *l *= m;
6439            }
6440        }
6441        if let Some(c) = self.final_softcap {
6442            for l in logits.iter_mut() {
6443                *l = c * (*l / c).tanh();
6444            }
6445        }
6446        logits
6447    }
6448
6449    /// Prefill `ids` and return the next-token logits — what the model
6450    /// would predict next, WITHOUT committing to generation (introspection
6451    /// for `cortiq explain`). Clears and repopulates the KV cache; leaves
6452    /// the active overlay untouched.
6453    pub fn prefill_next_logits(&mut self, ids: &[u32], task_mask: Option<&TaskMask>) -> Vec<f32> {
6454        self.kv_cache.clear();
6455        self.kv_history.clear();
6456        let mut hidden = vec![0.0f32; self.hidden_size];
6457        for (pos, &id) in ids.iter().enumerate() {
6458            let emb = self.embed_single(id);
6459            hidden = self.forward_layers(&emb, pos, task_mask);
6460        }
6461        inference::rms_norm_into(
6462            &hidden,
6463            &self.weights.final_norm,
6464            self.rms_eps,
6465            self.norm_style,
6466            &mut self.ws.n1,
6467        );
6468        self.lm_head_forward(&self.ws.n1)
6469    }
6470}
6471
6472/// Convenience: deterministic tiny pipeline for tests.
6473pub fn create_test_pipeline(
6474    hidden_size: usize,
6475    intermediate_size: usize,
6476    num_heads: usize,
6477    num_kv_heads: usize,
6478    head_dim: usize,
6479    num_layers: usize,
6480    vocab_size: usize,
6481) -> Pipeline {
6482    // Small pseudo-random weights: constant weights make attention
6483    // degenerate and hide indexing bugs.
6484    let synth = |n: usize, salt: usize| -> Vec<f32> {
6485        (0..n)
6486            .map(|i| (((i * 31 + salt * 17 + 7) % 97) as f32 / 97.0 - 0.5) * 0.2)
6487            .collect()
6488    };
6489    let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
6490        QTensor::from_f32(synth(rows * cols, salt), rows, cols)
6491    };
6492    let layer_weights: Vec<LayerWeights> = (0..num_layers)
6493        .map(|li| LayerWeights {
6494            input_norm: vec![1.0; hidden_size],
6495            post_norm: vec![1.0; hidden_size],
6496            attn_out_norm: None,
6497            ffn_out_norm: None,
6498            layer_scale: None,
6499            ffn: FfnKind::Dense(DenseFfn {
6500                gate_proj: qt(intermediate_size, hidden_size, li * 10 + 5),
6501                up_proj: qt(intermediate_size, hidden_size, li * 10 + 6),
6502                down_proj: qt(hidden_size, intermediate_size, li * 10 + 7),
6503                act: Act::Silu,
6504            }),
6505            attn: AttnKind::Full {
6506                bias: None,
6507                wq: qt(num_heads * head_dim, hidden_size, li * 10 + 1),
6508                wk: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 2),
6509                wv: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 3),
6510                wo: qt(hidden_size, num_heads * head_dim, li * 10 + 4),
6511                q_norm: None,
6512                k_norm: None,
6513                output_gate: false,
6514                softplus_gate: None,
6515            },
6516        })
6517        .collect();
6518
6519    Pipeline::new(
6520        Tokenizer::byte_level(),
6521        PipelineWeights {
6522            embed_tokens: qt(vocab_size, hidden_size, 100),
6523            layers: layer_weights,
6524            lm_head: qt(vocab_size, hidden_size, 200),
6525            final_norm: vec![1.0; hidden_size],
6526        },
6527        hidden_size,
6528        intermediate_size,
6529        num_heads,
6530        num_kv_heads,
6531        head_dim,
6532        num_layers,
6533        num_layers, // physical_layers = num_layers (non-looped)
6534        false,      // loop_final_norm
6535        vocab_size,
6536        1e-6,
6537        10_000.0,
6538        NormStyle::Qwen,
6539        4096,
6540        SamplerConfig {
6541            seed: Some(42),
6542            ..Default::default()
6543        },
6544    )
6545}
6546
6547/// Batched dense-FFN: gate/up/down via matmat (element-wise the same
6548/// math as b × dense_ffn — the same dot kernels).
6549/// One mask bit, LSB-first per byte — `TaskMask::ffn_active_indices`'s
6550/// convention.
6551#[inline]
6552fn mask_bit(row: &[u8], j: usize) -> bool {
6553    (row.get(j >> 3).copied().unwrap_or(0) >> (j & 7)) & 1 != 0
6554}
6555
6556/// Zero the CLOSED neurons' activations in a [rows × inter] panel — the
6557/// masked-inference fast path's whole trick: full fused quant compute,
6558/// then the mask lands on the ACTIVATIONS, which is arithmetically the
6559/// pruned network without touching a quantized weight byte. Whole open
6560/// bytes (0xFF = 8 open neurons) skip in one test.
6561fn zero_masked_cols(g: &mut [f32], rows: usize, inter: usize, row: &[u8]) {
6562    for r in 0..rows {
6563        let base = r * inter;
6564        for (bi, &byte) in row.iter().enumerate() {
6565            if byte == 0xFF {
6566                continue;
6567            }
6568            let j0 = bi * 8;
6569            for bit in 0..8 {
6570                let j = j0 + bit;
6571                if j < inter && byte & (1 << bit) == 0 {
6572                    g[base + j] = 0.0;
6573                }
6574            }
6575        }
6576    }
6577}
6578
6579fn dense_ffn_batch(
6580    d: &DenseFfn,
6581    xs: &[f32],
6582    b: usize,
6583    pool: Option<&Pool>,
6584    mask_row: Option<&[u8]>,
6585) -> Vec<f32> {
6586    let inter = d.gate_proj.rows();
6587    let hidden = d.down_proj.rows();
6588    // Fused on-device SwiGLU when the device is in play: three separate
6589    // `matmat` calls are three round trips per layer, and the gate/up
6590    // panels (b × inter — 22 MB each at a 512-token chunk) cross the bus
6591    // twice for nothing. The kernel already existed for the image DiT;
6592    // the LLM prefill was simply never wired to it. A task mask needs the
6593    // activations on the host between the halves, so it keeps the CPU
6594    // arm below.
6595    if mask_row.is_none()
6596        && d.act == Act::Silu
6597        && b >= 32
6598        && crate::gpu::enabled_here()
6599        && !crate::gpu::mm_killed()
6600    {
6601        if let (Some((model, w1)), Some((_, w3)), Some((_, w2))) = (
6602            d.gate_proj.mapped_q4t(),
6603            d.up_proj.mapped_q4t(),
6604            d.down_proj.mapped_q4t(),
6605        ) {
6606            let mut out = vec![0.0f32; b * hidden];
6607            if crate::gpu::q4t_ffn(model, w1, w3, w2, xs, b, hidden, inter, &mut out) {
6608                return out;
6609            }
6610        }
6611        // The q4tp twin (same kernel family, scale from the row ladder) —
6612        // the DiT has run it in production since the pipeline containers;
6613        // the LLM prefill was simply never wired to it, so a q4tp model's
6614        // prefill panels stayed on the CPU.
6615        if let (Some((model, w1)), Some((_, w3)), Some((_, w2))) = (
6616            d.gate_proj.mapped_q4tp(),
6617            d.up_proj.mapped_q4tp(),
6618            d.down_proj.mapped_q4tp(),
6619        ) {
6620            let mut out = vec![0.0f32; b * hidden];
6621            if crate::gpu::q4tp_ffn(model, w1, w3, w2, xs, b, hidden, inter, &mut out) {
6622                return out;
6623            }
6624        }
6625    }
6626    let mut g = vec![0.0f32; b * inter];
6627    d.gate_proj.matmat(xs, b, &mut g, pool);
6628    let mut u = vec![0.0f32; b * inter];
6629    d.up_proj.matmat(xs, b, &mut u, pool);
6630    for i in 0..b * inter {
6631        g[i] = d.act.combine(g[i], u[i]);
6632    }
6633    if let Some(row) = mask_row {
6634        zero_masked_cols(&mut g, b, inter, row);
6635    }
6636    let mut out = vec![0.0f32; b * hidden];
6637    d.down_proj.matmat(&g, b, &mut out, pool);
6638    out
6639}
6640
6641/// Batched MoE-FFN: router batched, positions are GROUPED by expert —
6642/// an expert's weights are read once for all its positions in the chunk
6643/// (the main prefill-GEMM win on MoE: 960MB/token of 35B experts).
6644/// Accumulate per-channel activation energy for `CMF_RMS_TRACE`.
6645fn accumulate_act(m: &MoeFfn, xs: &[f32], b: usize) {
6646    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6647    static DUMP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6648    let on = *ON.get_or_init(|| std::env::var("CMF_RMS_TRACE").is_ok());
6649    let dump = *DUMP.get_or_init(|| std::env::var("CMF_ACT_DUMP").is_ok());
6650    if (!on && !dump) || b == 0 {
6651        return;
6652    }
6653    let hidden = xs.len() / b;
6654    if on {
6655        let mut acc = m.act_sq.borrow_mut();
6656        if acc.len() < hidden {
6657            acc.resize(hidden, 0.0);
6658        }
6659        for t in 0..b {
6660            let row = &xs[t * hidden..(t + 1) * hidden];
6661            for (a, &v) in acc.iter_mut().zip(row) {
6662                *a += (v as f64) * (v as f64);
6663            }
6664        }
6665    }
6666    if dump {
6667        // Cap the capture: the covariance needs a few thousand rows, and a
6668        // whole prefill of every layer would be gigabytes for no extra rank.
6669        let cap: usize = std::env::var("CMF_ACT_DUMP_ROWS")
6670            .ok()
6671            .and_then(|v| v.parse().ok())
6672            .unwrap_or(4096);
6673        let mut rows = m.act_rows.borrow_mut();
6674        if rows.len() < cap * hidden {
6675            let take = b.min((cap * hidden - rows.len()) / hidden.max(1));
6676            rows.extend_from_slice(&xs[..take * hidden]);
6677        }
6678    }
6679}
6680
6681/// Send-able cursor over a Vec-of-Vecs: each pool worker writes only its
6682/// own slots (disjoint by construction in the caller).
6683#[derive(Clone, Copy)]
6684struct SendVecs(*mut Vec<f32>);
6685unsafe impl Send for SendVecs {}
6686unsafe impl Sync for SendVecs {}
6687impl SendVecs {
6688    #[inline]
6689    fn at(self, i: usize) -> *mut Vec<f32> {
6690        unsafe { self.0.add(i) }
6691    }
6692}
6693
6694fn moe_ffn_batch(
6695    m: &MoeFfn,
6696    xs: &[f32],
6697    b: usize,
6698    hidden: usize,
6699    pool: Option<&Pool>,
6700    allowed: Option<&[bool]>,
6701) -> Vec<f32> {
6702    accumulate_act(m, xs, b);
6703    let ne = m.experts.len();
6704    let mut logits = vec![0.0f32; b * ne];
6705    m.router.matmat(xs, b, &mut logits, pool);
6706
6707    // Assignments: expert → [(position, weight)] — same routing as
6708    // moe_ffn, per position (see `moe_route`).
6709    let mut assign: Vec<Vec<(usize, f32)>> = vec![Vec::new(); ne];
6710    {
6711        let mut st = m.stats.borrow_mut();
6712        if st.len() < ne {
6713            st.resize(ne, 0);
6714        }
6715        for bi in 0..b {
6716            let (idx, p, wsum) = moe_route(&logits[bi * ne..(bi + 1) * ne], m, allowed);
6717            for &e in &idx {
6718                st[e] += 1;
6719                assign[e].push((bi, p[e] / wsum));
6720            }
6721        }
6722    }
6723
6724    let mut out = vec![0.0f32; b * hidden];
6725    let cols = m.experts[0].gate_proj.cols();
6726    let run_expert = |d: &DenseFfn, list: &[(usize, f32)], out: &mut [f32]| {
6727        let sb = list.len();
6728        let mut sub = vec![0.0f32; sb * cols];
6729        for (k, &(bi, _)) in list.iter().enumerate() {
6730            sub[k * cols..(k + 1) * cols].copy_from_slice(&xs[bi * cols..(bi + 1) * cols]);
6731        }
6732        let eo = dense_ffn_batch(d, &sub, sb, pool, None);
6733        for (k, &(bi, w)) in list.iter().enumerate() {
6734            for i in 0..hidden {
6735                out[bi * hidden + i] += w * eo[k * hidden + i];
6736            }
6737        }
6738    };
6739    // Routed experts: the panels are TINY (b·top_k spread over every
6740    // expert — a few positions each), so a pool dispatch per expert is
6741    // pure barrier cost. Invert the parallelism: workers take WHOLE
6742    // experts (serial math inside), then one deterministic scatter in
6743    // expert order — the exact accumulation order the serial loop had.
6744    let active: Vec<usize> = (0..ne).filter(|&e| !assign[e].is_empty()).collect();
6745    if pool.is_some() && active.len() >= 8 {
6746        let mut panels: Vec<Vec<f32>> = vec![Vec::new(); active.len()];
6747        {
6748            let panel_ptr = SendVecs(panels.as_mut_ptr());
6749            // Capture only the expert table: `m` itself carries RefCell
6750            // stats and must not cross the pool boundary.
6751            let experts = &m.experts;
6752            let (active_r, assign_r) = (&active, &assign);
6753            let run = |start: usize, end: usize| {
6754                for ai in start..end {
6755                    let e = active_r[ai];
6756                    let list = &assign_r[e];
6757                    let sb = list.len();
6758                    let mut sub = vec![0.0f32; sb * cols];
6759                    for (k, &(bi, _)) in list.iter().enumerate() {
6760                        sub[k * cols..(k + 1) * cols]
6761                            .copy_from_slice(&xs[bi * cols..(bi + 1) * cols]);
6762                    }
6763                    // SAFETY: each worker owns a disjoint panels[ai].
6764                    unsafe {
6765                        *panel_ptr.at(ai) =
6766                            dense_ffn_batch(&experts[e], &sub, sb, None, None);
6767                    }
6768                }
6769            };
6770            match pool {
6771                Some(p) => p.run_rows(active.len(), &run),
6772                None => run(0, active.len()),
6773            }
6774        }
6775        for (ai, &e) in active.iter().enumerate() {
6776            for (k, &(bi, w)) in assign[e].iter().enumerate() {
6777                let eo = &panels[ai][k * hidden..(k + 1) * hidden];
6778                for i in 0..hidden {
6779                    out[bi * hidden + i] += w * eo[i];
6780                }
6781            }
6782        }
6783    } else {
6784        for &e in &active {
6785            run_expert(&m.experts[e], &assign[e], &mut out);
6786        }
6787    }
6788    if let Some((se, gate)) = &m.shared {
6789        let all: Vec<(usize, f32)> = if let Some(gate) = gate {
6790            let mut gl = vec![0.0f32; b];
6791            gate.matmat(xs, b, &mut gl, pool);
6792            (0..b)
6793                .map(|bi| (bi, 1.0 / (1.0 + (-gl[bi]).exp())))
6794                .collect()
6795        } else {
6796            (0..b).map(|bi| (bi, 1.0)).collect()
6797        };
6798        run_expert(se, &all, &mut out);
6799    }
6800    out
6801}
6802
6803thread_local! {
6804    /// gate/up activation scratch for the dense FFN paths (single uses
6805    /// two slots, the fused pair all four) — these were fresh
6806    /// intermediate-size Vecs on every layer of every token.
6807    static FFN_SCRATCH: std::cell::RefCell<[Vec<f32>; 4]> =
6808        const { std::cell::RefCell::new([Vec::new(), Vec::new(), Vec::new(), Vec::new()]) };
6809}
6810
6811/// Dense SwiGLU FFN through QTensor matvecs (any storage).
6812fn dense_ffn(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
6813    // Whole-FFN GPU submit (этап 4.2 increment): gate → silu·up → down
6814    // chained in ONE command buffer with the intermediate activations
6815    // resident on the device — 3 per-op polls become 1 per layer. The
6816    // moe_block backend already implements exactly this chain; a dense
6817    // FFN is one expert with weight 1. Runtime probe: the chain still
6818    // pays one submit+poll per layer — alternate it against the pure-CPU
6819    // FFN and keep whichever is faster on this machine.
6820    // q1 FFNs offload at any practical size: the q1 CPU kernel is
6821    // compute-bound, so the UMA threshold logic does not apply — the
6822    // probe measures and decides either way.
6823    if crate::gpu::enabled_here()
6824        && (d.gate_proj.rows() >= crate::gpu::min_rows() || d.gate_proj.is_q1())
6825    {
6826        let arm = if d.gate_proj.is_q1() && crate::gpu::q1_force() {
6827            crate::gpu::ProbeArm::Gpu
6828        } else {
6829            crate::gpu::probe_arm(crate::gpu::OpClass::Ffn)
6830        };
6831        match arm {
6832            crate::gpu::ProbeArm::Gpu => {
6833                let t0 = std::time::Instant::now();
6834                if let Some(out) = dense_ffn_gpu(d, x, pool) {
6835                    crate::gpu::probe_record(crate::gpu::OpClass::Ffn, true, t0.elapsed());
6836                    return out;
6837                }
6838            }
6839            crate::gpu::ProbeArm::CpuTimed => {
6840                let t0 = std::time::Instant::now();
6841                let out = crate::gpu::cpu_scope(|| dense_ffn_cpu(d, x, pool));
6842                crate::gpu::probe_record(crate::gpu::OpClass::Ffn, false, t0.elapsed());
6843                return out;
6844            }
6845            crate::gpu::ProbeArm::Cpu => {
6846                return crate::gpu::cpu_scope(|| dense_ffn_cpu(d, x, pool));
6847            }
6848        }
6849    }
6850    dense_ffn_cpu(d, x, pool)
6851}
6852
6853/// The pure-CPU dense-FFN body (also the fallback of every GPU refusal).
6854fn dense_ffn_cpu(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
6855    let inter = d.gate_proj.rows();
6856    FFN_SCRATCH.with(|s| {
6857        let mut s = s.borrow_mut();
6858        let [g, u, ..] = &mut *s;
6859        g.resize(inter, 0.0);
6860        // Fused gate+up+silu: one dispatch, no separate silu pass.
6861        // Falls back to matvec_many + silu loop for unsupported dtypes.
6862        if d.act == Act::Silu && QTensor::matvec_silu_mul(&d.gate_proj, &d.up_proj, x, g, pool) {
6863            // g now holds silu(gate)·up directly.
6864        } else {
6865            u.resize(inter, 0.0);
6866            // Multi-matrix job: gate+up under one pool dispatch.
6867            QTensor::matvec_many([&d.gate_proj, &d.up_proj], x, [g, u], pool);
6868            for i in 0..inter {
6869                g[i] = d.act.combine(g[i], u[i]);
6870            }
6871        }
6872        // DTG-MA bake probe (Patent 2): accumulate this layer's
6873        // per-neuron activation mass while a probe pass is active.
6874        FFN_PROBE.with(|pr| {
6875            if let Some(acc) = pr.borrow_mut().as_mut() {
6876                let li = crate::gpu::cur_layer();
6877                if li >= 0 {
6878                    if let Some(row) = acc.get_mut(li as usize) {
6879                        for (a, &v) in row.iter_mut().zip(g.iter()) {
6880                            *a += (v as f64).abs();
6881                        }
6882                    }
6883                }
6884            }
6885        });
6886        let mut out = attention::take_buf(d.down_proj.rows());
6887        d.down_proj.matvec(g, &mut out, pool);
6888        out
6889    })
6890}
6891
6892thread_local! {
6893    /// DTG-MA activation probe: per-layer per-neuron Σ|silu(g)·u|
6894    /// accumulator, alive only during `Pipeline::probe_ffn_mass`.
6895    static FFN_PROBE: std::cell::RefCell<Option<Vec<Vec<f64>>>> =
6896        const { std::cell::RefCell::new(None) };
6897}
6898
6899/// `dense_ffn_cpu` with a per-visit mask landing on the activations —
6900/// the masked-inference fast path's decode arm. Full fused quant
6901/// compute, closed neurons zeroed before down: arithmetically the
6902/// pruned network, no dequant, no weight bytes touched.
6903fn dense_ffn_masked(
6904    d: &DenseFfn,
6905    x: &[f32],
6906    pool: Option<&Pool>,
6907    mask_row: &[u8],
6908) -> Vec<f32> {
6909    let inter = d.gate_proj.rows();
6910    FFN_SCRATCH.with(|s| {
6911        let mut s = s.borrow_mut();
6912        let [g, u, ..] = &mut *s;
6913        g.resize(inter, 0.0);
6914        if d.act == Act::Silu && QTensor::matvec_silu_mul(&d.gate_proj, &d.up_proj, x, g, pool) {
6915            // g holds silu(gate)·up.
6916        } else {
6917            u.resize(inter, 0.0);
6918            QTensor::matvec_many([&d.gate_proj, &d.up_proj], x, [g, u], pool);
6919            for i in 0..inter {
6920                g[i] = d.act.combine(g[i], u[i]);
6921            }
6922        }
6923        zero_masked_cols(g, 1, inter, mask_row);
6924        let mut out = attention::take_buf(d.down_proj.rows());
6925        d.down_proj.matvec(g, &mut out, pool);
6926        out
6927    })
6928}
6929
6930/// Dense FFN as one GPU submission via the MoE block path (single
6931/// expert, weight 1.0): gate → silu·up → down chained in one command
6932/// buffer, intermediate activations device-resident. None → weights
6933/// not q8-mapped in the primary shard / over the VRAM budget / backend
6934/// refusal → honest CPU path.
6935fn dense_ffn_gpu(d: &DenseFfn, x: &[f32], _pool: Option<&Pool>) -> Option<Vec<f32>> {
6936    // The GPU block hardcodes SiLU; GeLU FFNs (Gemma) stay on CPU.
6937    if d.act != Act::Silu {
6938        return None;
6939    }
6940    // Threshold: tiny FFNs are not worth a submission (q1 excepted —
6941    // see the caller's gate).
6942    if d.gate_proj.rows() < crate::gpu::min_rows() && !d.gate_proj.is_q1() {
6943        return None;
6944    }
6945    let mut jobs: Vec<crate::gpu::MoeJob> = Vec::with_capacity(1);
6946    let mut model_ref = None;
6947    moe_push_job(d, x, 1.0, &mut jobs, &mut model_ref)?;
6948    let model = model_ref?;
6949    let hidden = jobs[0].down.1;
6950    let mut out = attention::take_buf(hidden);
6951    if crate::gpu::moe_block(&model, &jobs, &mut out) {
6952        Some(out)
6953    } else {
6954        let mut out = out;
6955        attention::recycle_buf(&mut out);
6956        None
6957    }
6958}
6959
6960/// q8-mapped primary-shard tensor parts for a GPU job: q8_2f carries
6961/// its column field, q8_row runs with empty col slices (the backend
6962/// skips the multiply). Shared by the MoE block and the dense-FFN
6963/// single-job path.
6964#[allow(clippy::type_complexity)]
6965#[allow(clippy::type_complexity)]
6966pub(crate) fn moe_parts(
6967    t: &QTensor,
6968) -> Option<(
6969    &std::sync::Arc<cortiq_core::CmfModel>,
6970    usize,
6971    usize,
6972    usize,
6973    &[f32],
6974    &[f32],
6975    bool,
6976    bool,
6977    bool,
6978)> {
6979    match t {
6980        QTensor::Mapped {
6981            model,
6982            idx,
6983            dtype: dt @ (cortiq_core::TensorDtype::Q8_2f | cortiq_core::TensorDtype::Q8Row),
6984            rows,
6985            cols,
6986            row_scale,
6987            col_field,
6988            ..
6989        } if (*dt == cortiq_core::TensorDtype::Q8Row) || !col_field.is_empty() => Some((
6990            model, *idx, *rows, *cols, row_scale, col_field, false, false, false,
6991        )),
6992        // q1: tile-embedded scales — empty rs/col slices, raw xs.
6993        QTensor::Mapped {
6994            model,
6995            idx,
6996            dtype: cortiq_core::TensorDtype::Q1,
6997            rows,
6998            cols,
6999            ..
7000        } => Some((model, *idx, *rows, *cols, &[][..], &[][..], true, false, false)),
7001        // q4_tiled: 18-byte tiles with embedded f16 scales — raw xs.
7002        QTensor::Mapped {
7003            model,
7004            idx,
7005            dtype: cortiq_core::TensorDtype::Q4Tiled,
7006            rows,
7007            cols,
7008            ..
7009        } => Some((model, *idx, *rows, *cols, &[][..], &[][..], false, true, false)),
7010        // q4tp: same raw-xs contract, different stride and scale plane.
7011        QTensor::Mapped {
7012            model,
7013            idx,
7014            dtype: cortiq_core::TensorDtype::Q4TiledP,
7015            rows,
7016            cols,
7017            ..
7018        } => Some((model, *idx, *rows, *cols, &[][..], &[][..], false, true, false)),
7019        // q2tp: the 2-bit expert plane of the mixed profile — q4 family
7020        // for stride bookkeeping, flagged q2 so the trio validation can
7021        // demand a q4tp down.
7022        QTensor::Mapped {
7023            model,
7024            idx,
7025            dtype: cortiq_core::TensorDtype::Q2TiledP,
7026            rows,
7027            cols,
7028            ..
7029        } => Some((model, *idx, *rows, *cols, &[][..], &[][..], false, true, true)),
7030        _ => None,
7031    }
7032}
7033
7034/// Map a softmax-router MoE onto the Metal token graph's contract:
7035/// f32 router, gated shared expert, experts uniformly q4tp (or the
7036/// mixed profile: q2tp gate/up over a q4tp down). Sigmoid/bias/τ
7037/// routers, masks, per-expert scales and Gemma's router-input norm
7038/// refuse here — those semantics stay on the CPU path.
7039#[cfg(target_os = "macos")]
7040fn metal_moe_graph_parts(m: &MoeFfn, hidden: usize) -> Option<crate::gpu::GpuMoe<'_>> {
7041    if m.router_sigmoid
7042        || m.router_input_norm
7043        || m.expert_bias.is_some()
7044        || m.route_tau.is_some()
7045        || m.mask.is_some()
7046        || m.per_expert_scale.is_some()
7047        || m.experts.is_empty()
7048        || m.top_k == 0
7049    {
7050        return None;
7051    }
7052    // The select kernel hard-codes the gated shared expert; an
7053    // ungated one would need its own weight-1 slot.
7054    let (sh, sg) = match &m.shared {
7055        Some((sh, Some(sg))) => (sh, sg),
7056        _ => return None,
7057    };
7058    let (rf, rr, rc) = m.router.f32_parts()?;
7059    if rr != m.experts.len() || rc != hidden {
7060        return None;
7061    }
7062    let (sf, sr, sc) = sg.f32_parts()?;
7063    if sr * sc != hidden {
7064        return None;
7065    }
7066    let inter = m.experts[0].gate_proj.rows();
7067    // The first expert's gate decides the profile; every trio (shared
7068    // included) must agree — the jobs ladder flips ONE kernel for all.
7069    let gu_q2 = m.experts[0].gate_proj.mapped_q2tp().is_some();
7070    let trio = |e: &DenseFfn| -> Option<(usize, usize, usize)> {
7071        if e.act != Act::Silu
7072            || e.gate_proj.rows() != inter
7073            || e.gate_proj.cols() != hidden
7074            || e.up_proj.rows() != inter
7075            || e.up_proj.cols() != hidden
7076            || e.down_proj.rows() != hidden
7077            || e.down_proj.cols() != inter
7078        {
7079            return None;
7080        }
7081        let pick = |t: &QTensor| -> Option<usize> {
7082            if gu_q2 {
7083                t.mapped_q2tp().map(|(_, i)| i)
7084            } else {
7085                t.mapped_q4tp().map(|(_, i)| i)
7086            }
7087        };
7088        Some((
7089            pick(&e.gate_proj)?,
7090            pick(&e.up_proj)?,
7091            e.down_proj.mapped_q4tp().map(|(_, i)| i)?,
7092        ))
7093    };
7094    let experts = m
7095        .experts
7096        .iter()
7097        .map(trio)
7098        .collect::<Option<Vec<_>>>()?;
7099    let shared = trio(sh)?;
7100    Some(crate::gpu::GpuMoe {
7101        router: rf,
7102        sgate: sf,
7103        experts,
7104        shared,
7105        n_exp: m.experts.len(),
7106        top_k: m.top_k,
7107        inter,
7108        norm_topk: m.norm_topk_prob,
7109        route_scale: m.routed_scaling,
7110        gu_q2,
7111    })
7112}
7113
7114/// Build one gate/up/down GPU job from three tensors. `moe_push_job` is the
7115/// DenseFfn-shaped caller; architectures that keep their experts in their own
7116/// structs (DeepSeek-V4) come here directly.
7117pub(crate) fn moe_push_job_parts<'a>(
7118    gate: &'a QTensor,
7119    up: &'a QTensor,
7120    down: &'a QTensor,
7121    x: &[f32],
7122    w: f32,
7123    swiglu_limit: f32,
7124    jobs: &mut Vec<crate::gpu::MoeJob<'a>>,
7125    model_ref: &mut Option<std::sync::Arc<cortiq_core::CmfModel>>,
7126) -> Option<()> {
7127    use crate::qtensor::prescale;
7128    let (gm, gi, gr, gc, grs, gcf, gq1, gq4, gq2) = moe_parts(gate)?;
7129    let (_, ui, ur, uc, urs, ucf, uq1, uq4, uq2) = moe_parts(up)?;
7130    let (_, di, dr, dc, drs, dcf, dq1, dq4, dq2) = moe_parts(down)?;
7131    if gq1 != uq1 || uq1 != dq1 || gq4 != uq4 || uq4 != dq4 || gq2 != uq2 {
7132        return None; // mixed-dtype trio — honest CPU path
7133    }
7134    // The 2-bit profile is gate/up q2tp over a PLAIN q4tp down; any other
7135    // 2-bit arrangement stays on the CPU.
7136    if gq2 && (dq2 || !dq4 || down.mapped_q4tp().is_none()) {
7137        return None;
7138    }
7139    if !gq2 && dq2 {
7140        return None;
7141    }
7142    model_ref.get_or_insert_with(|| gm.clone());
7143    let dt = |cf: &[f32]| {
7144        if cf.is_empty() {
7145            cortiq_core::TensorDtype::Q8Row
7146        } else {
7147            cortiq_core::TensorDtype::Q8_2f
7148        }
7149    };
7150    jobs.push(crate::gpu::MoeJob {
7151        gate: (gi, gr, gc, grs),
7152        up: (ui, ur, uc, urs),
7153        down: (di, dr, dc, drs),
7154        xs_gate: prescale(x, gcf, dt(gcf)).into_owned(),
7155        xs_up: prescale(x, ucf, dt(ucf)).into_owned(),
7156        down_col: dcf,
7157        w,
7158        q1: gq1,
7159        q4t: gq4 && !gq2 && gate.mapped_q4tp().is_none(),
7160        q4tp: gq4 && (gq2 || gate.mapped_q4tp().is_some()),
7161        gu_q2: gq2,
7162        swiglu_limit,
7163    });
7164    Some(())
7165}
7166
7167/// Build one gate/up/down GPU job (see `moe_parts`).
7168fn moe_push_job<'a>(
7169    d: &'a DenseFfn,
7170    x: &[f32],
7171    w: f32,
7172    jobs: &mut Vec<crate::gpu::MoeJob<'a>>,
7173    model_ref: &mut Option<std::sync::Arc<cortiq_core::CmfModel>>,
7174) -> Option<()> {
7175    use crate::qtensor::prescale;
7176    if d.act != Act::Silu {
7177        return None; // GPU block hardcodes SiLU
7178    }
7179    let (gm, gi, gr, gc, grs, gcf, gq1, gq4, gq2) = moe_parts(&d.gate_proj)?;
7180    let (_, ui, ur, uc, urs, ucf, uq1, uq4, uq2) = moe_parts(&d.up_proj)?;
7181    let (_, di, dr, dc, drs, dcf, dq1, dq4, dq2) = moe_parts(&d.down_proj)?;
7182    if gq1 != uq1 || uq1 != dq1 || gq4 != uq4 || uq4 != dq4 || gq2 != uq2 {
7183        return None; // mixed-dtype trio — honest CPU path
7184    }
7185    if gq2 && (dq2 || !dq4 || d.down_proj.mapped_q4tp().is_none()) {
7186        return None;
7187    }
7188    if !gq2 && dq2 {
7189        return None;
7190    }
7191    model_ref.get_or_insert_with(|| gm.clone());
7192    let gdt = if gcf.is_empty() {
7193        cortiq_core::TensorDtype::Q8Row
7194    } else {
7195        cortiq_core::TensorDtype::Q8_2f
7196    };
7197    let udt = if ucf.is_empty() {
7198        cortiq_core::TensorDtype::Q8Row
7199    } else {
7200        cortiq_core::TensorDtype::Q8_2f
7201    };
7202    jobs.push(crate::gpu::MoeJob {
7203        gate: (gi, gr, gc, grs),
7204        up: (ui, ur, uc, urs),
7205        down: (di, dr, dc, drs),
7206        xs_gate: prescale(x, gcf, gdt).into_owned(),
7207        xs_up: prescale(x, ucf, udt).into_owned(),
7208        down_col: dcf,
7209        w,
7210        q1: gq1,
7211        q4t: gq4 && !gq2 && d.gate_proj.mapped_q4tp().is_none(),
7212        q4tp: gq4 && (gq2 || d.gate_proj.mapped_q4tp().is_some()),
7213        gu_q2: gq2,
7214        swiglu_limit: 0.0,
7215    });
7216    Some(())
7217}
7218
7219/// Sparse dense-FFN directly on QUANTIZED weights (mask × mmap): reads
7220/// ONLY the active neurons' gate/up rows and down columns from the mmap
7221/// — no full-matrix dequant, no f32 model copy. This is what lets a
7222/// masked big model run at quantized RSS (the historical mask path
7223/// forced the whole model to f32). Semantics identical to the f32
7224/// sparse path within quant tolerance.
7225fn sparse_ffn_quant(
7226    d: &DenseFfn,
7227    x: &[f32],
7228    active: &[u16],
7229    hidden: usize,
7230    pool: Option<&Pool>,
7231) -> Vec<f32> {
7232    let n = active.len();
7233    let inter = d.gate_proj.rows();
7234    let mut act = vec![0.0f32; n];
7235    // Scratch is needed if EITHER projection is group-packed (q4/vbit);
7236    // gate/up normally share a dtype but sizing on both is robust.
7237    let need_scratch = !(d.gate_proj.sparse_col_ok() && d.up_proj.sparse_col_ok());
7238    let compute = |ai: usize| -> f32 {
7239        let idx = active[ai] as usize;
7240        if idx >= inter {
7241            return 0.0; // defensive parity with the f32 sparse path
7242        }
7243        let mut s = if need_scratch {
7244            vec![0.0f32; hidden]
7245        } else {
7246            Vec::new()
7247        };
7248        let gate = d.gate_proj.row_dot(idx, x, &mut s);
7249        let up = d.up_proj.row_dot(idx, x, &mut s);
7250        d.act.combine(gate, up)
7251    };
7252    match pool {
7253        Some(p) if n >= 256 => {
7254            let ptr = SendMut(act.as_mut_ptr());
7255            p.run(&|widx, nw| {
7256                let chunk = n.div_ceil(nw);
7257                let (s, e) = (widx * chunk, ((widx + 1) * chunk).min(n));
7258                for ai in s..e {
7259                    unsafe { *ptr.at(ai) = compute(ai) };
7260                }
7261            });
7262        }
7263        _ => {
7264            for (ai, a) in act.iter_mut().enumerate() {
7265                *a = compute(ai);
7266            }
7267        }
7268    }
7269    // Scatter through active down columns (reads only those columns).
7270    let mut out = vec![0.0f32; hidden];
7271    for (ai, &idx) in active.iter().enumerate() {
7272        let w = act[ai];
7273        if w.abs() >= 1e-12 && (idx as usize) < inter {
7274            d.down_proj.add_col_scaled(idx as usize, w, &mut out);
7275        }
7276    }
7277    out
7278}
7279
7280/// Test-only re-export of the private sparse-quant FFN (mask × mmap gate).
7281#[doc(hidden)]
7282pub fn sparse_ffn_quant_for_test(
7283    d: &DenseFfn,
7284    x: &[f32],
7285    active: &[u16],
7286    hidden: usize,
7287) -> Vec<f32> {
7288    sparse_ffn_quant(d, x, active, hidden, None)
7289}
7290
7291/// Dequantize a DenseFfn's three matrices to f32 (transient; only the
7292/// q4/vbit-masked fallback uses it — the memory-lean path is
7293/// sparse_ffn_quant). Reuses row_f32 row-by-row.
7294fn dequant_dense_f32(d: &DenseFfn) -> (Vec<f32>, Vec<f32>, Vec<f32>) {
7295    let deq = |t: &QTensor| -> Vec<f32> {
7296        let (rows, cols) = (t.rows(), t.cols());
7297        let mut out = vec![0.0f32; rows * cols];
7298        for r in 0..rows {
7299            t.row_f32(r, &mut out[r * cols..(r + 1) * cols]);
7300        }
7301        out
7302    };
7303    (deq(&d.gate_proj), deq(&d.up_proj), deq(&d.down_proj))
7304}
7305
7306/// Pointer wrapper for the worker-pool scatter (same pattern as qtensor).
7307struct SendMut(*mut f32);
7308unsafe impl Send for SendMut {}
7309unsafe impl Sync for SendMut {}
7310impl SendMut {
7311    #[inline]
7312    // Deliberate unsynchronized scatter: pool workers write disjoint indices
7313    // in parallel, so returning `&mut` from `&self` is intentional here.
7314    #[allow(clippy::mut_from_ref)]
7315    unsafe fn at(&self, i: usize) -> &mut f32 {
7316        unsafe { &mut *self.0.add(i) }
7317    }
7318}
7319
7320/// Router → (selected experts in torch.topk order, per-expert score
7321/// vector, normalizer). The final weight of expert `e` is `p[e] / wsum`.
7322///
7323/// Two regimes share this. Qwen: softmax over ALL experts, top-k of the
7324/// probabilities, optional renorm — `router_sigmoid=false`, no bias,
7325/// scale 1 → bit-identical to the historical path. LFM2-MoE /
7326/// DeepSeek-V3 `noaux_tc`: per-expert sigmoid scores, an optional
7327/// selection bias (top-k CHOICE only; weights stay unbiased), a 1e-6 renorm
7328/// floor and a routed scale.
7329fn moe_route(logits: &[f32], m: &MoeFfn, allowed: Option<&[bool]>) -> (Vec<usize>, Vec<f32>, f32) {
7330    let ne = logits.len();
7331    let p: Vec<f32> = if m.router_sigmoid {
7332        logits.iter().map(|&l| 1.0 / (1.0 + (-l).exp())).collect()
7333    } else {
7334        let mx = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
7335        let mut e: Vec<f32> = logits.iter().map(|&l| (l - mx).exp()).collect();
7336        let s: f32 = e.iter().sum();
7337        for v in &mut e {
7338            *v /= s;
7339        }
7340        e
7341    };
7342    // Expert restriction: the static env mask (CMF_MOE_MASK) AND the
7343    // active task mask's expert fields (spec §5) both narrow the
7344    // candidate set; selection happens over the admitted experts only.
7345    // With norm_topk the kept weights renormalize below; without it
7346    // the excluded mass is honestly dropped.
7347    let admit = |e: usize| {
7348        m.mask.as_ref().is_none_or(|mk| mk[e])
7349            && allowed.is_none_or(|a| a.get(e).copied().unwrap_or(false))
7350    };
7351    let mut idx: Vec<usize> = (0..ne).filter(|&e| admit(e)).collect();
7352    // Descending by selection score, lower index wins ties (torch.topk).
7353    match &m.expert_bias {
7354        Some(b) => idx.sort_unstable_by(|&x, &y| {
7355            (p[y] + b[y])
7356                .partial_cmp(&(p[x] + b[x]))
7357                .unwrap()
7358                .then(x.cmp(&y))
7359        }),
7360        None => idx.sort_unstable_by(|&x, &y| p[y].partial_cmp(&p[x]).unwrap().then(x.cmp(&y))),
7361    }
7362    idx.truncate(m.top_k);
7363    // Adaptive τ-routing: trim the tail experts once the kept mass is
7364    // enough. wsum below renormalizes over the KEPT set, so the output
7365    // stays a proper weighted average.
7366    if let Some(tau) = m.route_tau {
7367        let total: f32 = idx.iter().map(|&e| p[e]).sum();
7368        if total > 0.0 {
7369            let mut acc = 0.0f32;
7370            let mut keep = idx.len();
7371            for (i, &e) in idx.iter().enumerate() {
7372                acc += p[e];
7373                if acc >= tau * total {
7374                    keep = i + 1;
7375                    break;
7376                }
7377            }
7378            idx.truncate(keep);
7379        }
7380    }
7381    let wsum: f32 = if m.norm_topk_prob {
7382        let s: f32 = idx.iter().map(|&e| p[e]).sum();
7383        // LFM2 floors the denom (matches HF `+ 1e-6`); the softmax path's
7384        // probs already sum near 1, so it stays exactly as before.
7385        (if m.router_sigmoid { s + 1e-6 } else { s }) / m.routed_scaling
7386    } else {
7387        1.0 / m.routed_scaling
7388    };
7389    (idx, p, wsum)
7390}
7391
7392/// MoE FFN: router → top-k experts (see `moe_route`). Only selected
7393/// experts' pages are touched in mmap.
7394fn moe_ffn(m: &MoeFfn, x: &[f32], pool: Option<&Pool>, allowed: Option<&[bool]>) -> Vec<f32> {
7395    accumulate_act(m, x, 1);
7396    let ne = m.experts.len();
7397    let mut logits = vec![0.0f32; ne];
7398    m.router.matvec(x, &mut logits, pool);
7399    let (idx, p, wsum) = moe_route(&logits, m, allowed);
7400    {
7401        let mut st = m.stats.borrow_mut();
7402        if st.len() < ne {
7403            st.resize(ne, 0);
7404        }
7405        for &e in &idx {
7406            st[e] += 1;
7407        }
7408    }
7409    // D5: the whole layer MoE block in one GPU command buffer (experts — the
7410    // same mmap via a no-copy buffer; intermediate activations on the GPU).
7411    // Same Ffn probe class as the dense chain: one submit per layer
7412    // either wins on this driver stack or it doesn't.
7413    if crate::gpu::enabled_here() {
7414        match crate::gpu::probe_arm(crate::gpu::OpClass::Ffn) {
7415            crate::gpu::ProbeArm::Gpu => {
7416                let t0 = std::time::Instant::now();
7417                if let Some(out) = moe_ffn_gpu(m, x, &idx, &p, wsum, pool) {
7418                    crate::gpu::probe_record(crate::gpu::OpClass::Ffn, true, t0.elapsed());
7419                    return out;
7420                }
7421            }
7422            crate::gpu::ProbeArm::CpuTimed => {
7423                let t0 = std::time::Instant::now();
7424                let out = crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool));
7425                crate::gpu::probe_record(crate::gpu::OpClass::Ffn, false, t0.elapsed());
7426                return out;
7427            }
7428            crate::gpu::ProbeArm::Cpu => {
7429                return crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool));
7430            }
7431        }
7432    }
7433    moe_ffn_cpu(m, x, &idx, &p, wsum, pool)
7434}
7435
7436/// One-shot report of whether the whole-token wgpu graph actually formed.
7437/// A refusal silently reverts to the per-op path, which is how a model can
7438/// look "GPU-accelerated" while every layer walks the host.
7439fn graph_note(built: bool) {
7440    use std::sync::atomic::{AtomicBool, Ordering};
7441    if built {
7442        GRAPH_TOK_OK.fetch_add(1, Ordering::Relaxed);
7443    } else {
7444        GRAPH_TOK_MISS.fetch_add(1, Ordering::Relaxed);
7445    }
7446    static SAID: AtomicBool = AtomicBool::new(false);
7447    if !SAID.swap(true, Ordering::Relaxed) {
7448        if built {
7449            tracing::info!("wgpu whole-token graph: ACTIVE");
7450        } else {
7451            tracing::warn!("wgpu whole-token graph refused — per-op path");
7452        }
7453    }
7454}
7455
7456/// Whole-token graph outcomes, process-wide: a benchmark that claims a
7457/// GPU number while MISS climbs is measuring the CPU — the honest-bench
7458/// contract makes that an error, not a footnote.
7459pub static GRAPH_TOK_OK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
7460pub static GRAPH_TOK_MISS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
7461
7462/// `CMF_MOE_BATCH=0` restores the per-expert serial loop — the A/B lever
7463/// for the batched kernel, and how its bit-identity is checked.
7464fn moe_batch_enabled() -> bool {
7465    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
7466    *ON.get_or_init(|| std::env::var("CMF_MOE_BATCH").as_deref() != Ok("0"))
7467}
7468
7469/// Two-dispatch CPU MoE: every routed expert (and the shared one) fused
7470/// into one gate/up/SiLU dispatch and one down dispatch, instead of two
7471/// pool barriers per expert. Bit-identical to the serial loop below —
7472/// see `moe_gate_up_many` / `moe_down_many`. `None` = the batched kernel
7473/// does not cover this layer, walk the serial path.
7474fn moe_ffn_cpu_batched(
7475    m: &MoeFfn,
7476    x: &[f32],
7477    idx: &[usize],
7478    p: &[f32],
7479    wsum: f32,
7480    pool: Option<&Pool>,
7481) -> Option<Vec<f32>> {
7482    if idx.is_empty() || !moe_batch_enabled() {
7483        return None;
7484    }
7485    // The bake probe reads per-neuron activation mass out of the
7486    // single-expert path; batching would skip it. Rare and offline —
7487    // hand those runs to the serial loop.
7488    if FFN_PROBE.with(|pr| pr.borrow().is_some()) {
7489        return None;
7490    }
7491    let n = idx.len() + usize::from(m.shared.is_some());
7492    let mut pairs = Vec::with_capacity(n);
7493    let mut downs = Vec::with_capacity(n);
7494    let mut ws = Vec::with_capacity(n);
7495    for &e in idx {
7496        let d = &m.experts[e];
7497        if d.act != Act::Silu {
7498            return None;
7499        }
7500        pairs.push((&d.gate_proj, &d.up_proj));
7501        downs.push(&d.down_proj);
7502        ws.push(p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]));
7503    }
7504    // The shared expert goes last, matching the serial loop's order —
7505    // the f32 accumulation order is part of the bit-identity claim.
7506    if let Some((se, gate)) = &m.shared {
7507        if se.act != Act::Silu {
7508            return None;
7509        }
7510        let g = gate.as_ref().map_or(1.0, |gate| {
7511            let mut gl = [0.0f32; 1];
7512            gate.matvec(x, &mut gl, pool);
7513            1.0 / (1.0 + (-gl[0]).exp())
7514        });
7515        pairs.push((&se.gate_proj, &se.up_proj));
7516        downs.push(&se.down_proj);
7517        ws.push(g);
7518    }
7519    let inter = pairs[0].0.rows();
7520    let mut gs: Vec<Vec<f32>> = (0..pairs.len()).map(|_| vec![0f32; inter]).collect();
7521    if !QTensor::moe_gate_up_many(&pairs, x, &mut gs, pool) {
7522        return None;
7523    }
7524    let mut out = attention::take_buf(x.len());
7525    if !QTensor::moe_down_many(&downs, &gs, &ws, &mut out, pool) {
7526        attention::recycle_buf(&mut out);
7527        return None;
7528    }
7529    Some(out)
7530}
7531
7532/// The pure-CPU MoE expert loop (also the fallback of every GPU refusal).
7533fn moe_ffn_cpu(
7534    m: &MoeFfn,
7535    x: &[f32],
7536    idx: &[usize],
7537    p: &[f32],
7538    wsum: f32,
7539    pool: Option<&Pool>,
7540) -> Vec<f32> {
7541    if let Some(out) = moe_ffn_cpu_batched(m, x, idx, p, wsum, pool) {
7542        return out;
7543    }
7544    let mut out = attention::take_buf(x.len());
7545    for &e in idx {
7546        let mut eo = dense_ffn(&m.experts[e], x, pool);
7547        let w = p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]);
7548        for i in 0..out.len() {
7549            out[i] += w * eo[i];
7550        }
7551        attention::recycle_buf(&mut eo);
7552    }
7553    if let Some((se, gate)) = &m.shared {
7554        let mut so = dense_ffn(se, x, pool);
7555        let g = gate.as_ref().map_or(1.0, |gate| {
7556            let mut gl = [0.0f32; 1];
7557            gate.matvec(x, &mut gl, pool);
7558            1.0 / (1.0 + (-gl[0]).exp())
7559        });
7560        for i in 0..out.len() {
7561            out[i] += g * so[i];
7562        }
7563        attention::recycle_buf(&mut so);
7564    }
7565    out
7566}
7567
7568/// DeepSeek-V2 MLA forward, expand-to-MHA form (see `AttnKind::Mla`):
7569/// per token the latent expands to every head's K/V and the ordinary
7570/// cache + grouped attend do the rest. K head layout is [rope | nope]
7571/// (rotary_dim = qk_rope rotates the shared rope key and each q head's
7572/// prefix); V rows are zero-padded to the K head_dim inside the cache
7573/// and the pad is sliced off before O. Born importance is not
7574/// accumulated for MLA yet (no eviction interplay).
7575#[allow(clippy::too_many_arguments)]
7576fn mla_attention(
7577    w: &MlaWeights,
7578    normed: &[f32],
7579    cache: &mut crate::kv_cache::LayerKvCache,
7580    position: usize,
7581    inv_freq: &[f32],
7582    rope_scale: f32,
7583    eps: f64,
7584    pool: Option<&Pool>,
7585) -> Vec<f32> {
7586    let (nh, dr, dn, dv, lora) = (w.nh, w.qk_rope, w.qk_nope, w.v_dim, w.lora);
7587    let hd = dr + dn;
7588    let mut q = vec![0.0f32; nh * hd];
7589    match (&w.q_a, &w.q_a_norm) {
7590        (Some(qa), Some(qn)) => {
7591            let mut t = vec![0.0f32; qa.rows()];
7592            qa.matvec(normed, &mut t, pool);
7593            let tn = inference::rms_norm(&t, qn, eps, NormStyle::Qwen);
7594            w.q_proj.matvec(&tn, &mut q, pool);
7595        }
7596        _ => w.q_proj.matvec(normed, &mut q, pool),
7597    }
7598    let mut ca = vec![0.0f32; lora + dr];
7599    w.kv_a.matvec(normed, &mut ca, pool);
7600    let (c_lat, k_rope) = ca.split_at_mut(lora);
7601    let latn = inference::rms_norm(c_lat, &w.kv_a_norm, eps, NormStyle::Qwen);
7602    let mut kvb = vec![0.0f32; nh * (dn + dv)];
7603    w.kv_b.matvec(&latn, &mut kvb, pool);
7604    if !w.nope {
7605        attention::rope_rotate_scaled(k_rope, position, inv_freq, rope_scale);
7606    }
7607    for h in 0..nh {
7608        if !w.nope {
7609            attention::rope_rotate_scaled(
7610                &mut q[h * hd..h * hd + dr],
7611                position,
7612                inv_freq,
7613                rope_scale,
7614            );
7615        }
7616    }
7617    let mut k = vec![0.0f32; nh * hd];
7618    let mut v = vec![0.0f32; nh * hd];
7619    for h in 0..nh {
7620        k[h * hd..h * hd + dr].copy_from_slice(k_rope);
7621        k[h * hd + dr..(h + 1) * hd].copy_from_slice(&kvb[h * (dn + dv)..h * (dn + dv) + dn]);
7622        v[h * hd..h * hd + dv].copy_from_slice(&kvb[h * (dn + dv) + dn..(h + 1) * (dn + dv)]);
7623    }
7624    cache.append(&k, &v, &vec![true; nh]);
7625    let (ao, mut imp) = attention::attend_all_heads(&q, cache, nh, 1, hd, w.scale, None, 0.0);
7626    attention::recycle_buf(&mut imp);
7627    let mut ov = vec![0.0f32; nh * dv];
7628    for h in 0..nh {
7629        ov[h * dv..(h + 1) * dv].copy_from_slice(&ao[h * hd..h * hd + dv]);
7630    }
7631    let mut out = vec![0.0f32; w.o_proj.rows()];
7632    w.o_proj.matvec(&ov, &mut out, pool);
7633    out
7634}
7635
7636/// Gemma-4 dual-branch FFN (spec: see `FfnKind::DenseMoe`). The dense
7637/// branch reads the pre-FFN-normed activation; the router and the
7638/// expert branch read the RAW residual — the router through a
7639/// scale-less rms norm (its constant gain is folded into the weights),
7640/// the experts through `pre_norm_2`. CPU path; GPU graphs refuse the
7641/// layer kind honestly.
7642fn dense_moe_ffn(
7643    dm: &DenseMoeFfn,
7644    x_normed: &[f32],
7645    h_raw: &[f32],
7646    eps: f64,
7647    norm_style: NormStyle,
7648    pool: Option<&Pool>,
7649) -> Vec<f32> {
7650    let mut d = dense_ffn(&dm.dense, x_normed, pool);
7651    d = inference::rms_norm(&d, &dm.post_norm_1, eps, norm_style);
7652    let m = &dm.moe;
7653    let ne = m.experts.len();
7654    let mut logits = vec![0.0f32; ne];
7655    if m.router_input_norm {
7656        let ss: f32 = h_raw.iter().map(|v| v * v).sum::<f32>() / h_raw.len() as f32;
7657        let inv = 1.0 / (ss + eps as f32).sqrt();
7658        let xr: Vec<f32> = h_raw.iter().map(|v| v * inv).collect();
7659        m.router.matvec(&xr, &mut logits, pool);
7660    } else {
7661        m.router.matvec(h_raw, &mut logits, pool);
7662    }
7663    let (idx, p, wsum) = moe_route(&logits, m, None);
7664    {
7665        let mut st = m.stats.borrow_mut();
7666        if st.len() < ne {
7667            st.resize(ne, 0);
7668        }
7669        for &e in &idx {
7670            st[e] += 1;
7671        }
7672    }
7673    let x2 = inference::rms_norm(h_raw, &dm.pre_norm_2, eps, norm_style);
7674    let mo = moe_ffn_cpu(m, &x2, &idx, &p, wsum, pool);
7675    let mo = inference::rms_norm(&mo, &dm.post_norm_2, eps, norm_style);
7676    for (di, mi) in d.iter_mut().zip(&mo) {
7677        *di += mi;
7678    }
7679    d
7680}
7681
7682/// Building the MoE-layer GPU jobs: all selected experts (+shared) must
7683/// be q8_2f-Mapped from the primary mapping; otherwise None → CPU path.
7684/// One-shot report of why the MoE GPU block refused. A silent `?` here
7685/// sends every expert to the CPU with nothing in the logs to say so —
7686/// which is exactly how a q4tp MoE model looked "GPU-accelerated" while
7687/// running entirely on the host.
7688fn moe_gpu_refused(why: &'static str) {
7689    use std::sync::atomic::{AtomicBool, Ordering};
7690    static SAID: AtomicBool = AtomicBool::new(false);
7691    if !SAID.swap(true, Ordering::Relaxed) {
7692        tracing::warn!("MoE GPU block refused ({why}) — experts run on the CPU");
7693    }
7694}
7695
7696fn moe_ffn_gpu(
7697    m: &MoeFfn,
7698    x: &[f32],
7699    idx: &[usize],
7700    p: &[f32],
7701    wsum: f32,
7702    pool: Option<&Pool>,
7703) -> Option<Vec<f32>> {
7704    use crate::gpu::MoeJob;
7705
7706    let mut jobs: Vec<MoeJob> = Vec::with_capacity(idx.len() + 1);
7707    let mut model_ref = None;
7708    for &e in idx {
7709        if moe_push_job(&m.experts[e], x, p[e] / wsum, &mut jobs, &mut model_ref).is_none() {
7710            moe_gpu_refused("push_job(expert)");
7711            return None;
7712        }
7713    }
7714    if let Some((se, gate)) = &m.shared {
7715        let g = gate.as_ref().map_or(1.0, |gate| {
7716            let mut gl = [0.0f32; 1];
7717            gate.matvec(x, &mut gl, pool);
7718            1.0 / (1.0 + (-gl[0]).exp())
7719        });
7720        if moe_push_job(se, x, g, &mut jobs, &mut model_ref).is_none() {
7721            moe_gpu_refused("push_job(shared)");
7722            return None;
7723        }
7724    }
7725    let Some(model) = model_ref else {
7726        moe_gpu_refused("no model_ref");
7727        return None;
7728    };
7729    let hidden = jobs[0].down.1;
7730    let mut out = vec![0.0f32; hidden];
7731    if crate::gpu::moe_block(&model, &jobs, &mut out) {
7732        Some(out)
7733    } else {
7734        moe_gpu_refused("gpu::moe_block");
7735        None
7736    }
7737}
7738
7739/// Single-position FFN dispatch.
7740fn ffn_forward(
7741    ffn: &FfnKind,
7742    x: &[f32],
7743    pool: Option<&Pool>,
7744    experts_allowed: Option<&[bool]>,
7745) -> Vec<f32> {
7746    match ffn {
7747        FfnKind::Dense(d) => dense_ffn(d, x, pool),
7748        FfnKind::Moe(m) => moe_ffn(m, x, pool, experts_allowed),
7749        // Dual-branch layers need the raw residual — their callers
7750        // dispatch dense_moe_ffn directly; the auxiliary paths that land
7751        // here (MTP draft, o1 replay) do not co-occur with gemma-4 MoE.
7752        FfnKind::DenseMoe(_) => unreachable!("DenseMoe dispatches via dense_moe_ffn"),
7753    }
7754}
7755
7756/// Fused two-position FFN: gate/up/down streamed once (dense). MoE
7757/// falls back to two singles — expert sets differ per position, there
7758/// is nothing to fuse.
7759fn ffn_forward_pair(
7760    ffn: &FfnKind,
7761    x1: &[f32],
7762    x2: &[f32],
7763    pool: Option<&Pool>,
7764    experts_allowed: Option<&[bool]>,
7765) -> (Vec<f32>, Vec<f32>) {
7766    let d = match ffn {
7767        FfnKind::Dense(d) => d,
7768        FfnKind::Moe(m) => {
7769            return (
7770                moe_ffn(m, x1, pool, experts_allowed),
7771                moe_ffn(m, x2, pool, experts_allowed),
7772            );
7773        }
7774        FfnKind::DenseMoe(_) => unreachable!("DenseMoe dispatches via dense_moe_ffn"),
7775    };
7776    let inter = d.gate_proj.rows();
7777    FFN_SCRATCH.with(|s| {
7778        let mut s = s.borrow_mut();
7779        let [g1, g2, u1, u2] = &mut *s;
7780        g1.resize(inter, 0.0);
7781        g2.resize(inter, 0.0);
7782        u1.resize(inter, 0.0);
7783        u2.resize(inter, 0.0);
7784        // Multi-matrix pair job: gate+up under one pool dispatch
7785        // (o1s = lane-1 outputs across tensors, o2s = lane-2).
7786        QTensor::matvec2_many(
7787            [&d.gate_proj, &d.up_proj],
7788            x1,
7789            x2,
7790            [g1.as_mut_slice(), u1.as_mut_slice()],
7791            [g2.as_mut_slice(), u2.as_mut_slice()],
7792            pool,
7793        );
7794        for i in 0..inter {
7795            g1[i] = d.act.combine(g1[i], u1[i]);
7796            g2[i] = d.act.combine(g2[i], u2[i]);
7797        }
7798        let mut o1 = attention::take_buf(d.down_proj.rows());
7799        let mut o2 = attention::take_buf(d.down_proj.rows());
7800        d.down_proj.matvec2(g1, g2, &mut o1, &mut o2, pool);
7801        (o1, o2)
7802    })
7803}
7804
7805#[cfg(test)]
7806mod tests {
7807
7808    #[test]
7809    fn cancel_flag_stops_generation() {
7810        let mut p = create_test_pipeline(16, 32, 2, 2, 8, 2, 32);
7811        // Set before the call: the prefill loops honour it, the run
7812        // returns immediately with the cancelled reason and no tokens.
7813        p.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
7814        let r = p.generate_from_ids(&[1, 2, 3], 8, None, None).unwrap();
7815        assert_eq!(r.finish_reason, "cancelled");
7816        assert!(
7817            r.token_ids.is_empty(),
7818            "no tokens after cancel: {:?}",
7819            r.token_ids
7820        );
7821        // Flag auto-cleared: the next call generates normally.
7822        let r2 = p.generate_from_ids(&[1, 2, 3], 4, None, None).unwrap();
7823        assert_ne!(r2.finish_reason, "cancelled");
7824    }
7825    use super::*;
7826
7827    /// sparse_ffn_quant must equal a dense FFN where inactive neurons are
7828    /// zeroed (mask × mmap correctness). On F32 tensors this is EXACT —
7829    /// it validates the row_dot / add_col_scaled / scatter indexing, the
7830    /// bug-prone part. The q8 branches reuse the golden-tested linear
7831    /// scale, structurally identical to the matvec kernels.
7832    #[test]
7833    fn sparse_ffn_quant_equals_dense_with_inactive_zeroed() {
7834        let (hidden, inter) = (16usize, 40usize);
7835        let synth = |n: usize, salt: usize| -> Vec<f32> {
7836            (0..n)
7837                .map(|i| (((i * 37 + salt * 11 + 3) % 101) as f32 / 101.0 - 0.5) * 0.4)
7838                .collect()
7839        };
7840        let d = DenseFfn {
7841            gate_proj: QTensor::from_f32(synth(inter * hidden, 1), inter, hidden),
7842            up_proj: QTensor::from_f32(synth(inter * hidden, 2), inter, hidden),
7843            down_proj: QTensor::from_f32(synth(hidden * inter, 3), hidden, inter),
7844            act: Act::Silu,
7845        };
7846        let x = synth(hidden, 9);
7847        // Active = every 3rd neuron.
7848        let active: Vec<u16> = (0..inter as u16).filter(|i| i % 3 == 0).collect();
7849
7850        let sparse = sparse_ffn_quant(&d, &x, &active, hidden, None);
7851
7852        // Reference: full dense FFN but g[i]=0 for inactive neurons.
7853        let mut g = vec![0.0f32; inter];
7854        d.gate_proj.matvec(&x, &mut g, None);
7855        let mut u = vec![0.0f32; inter];
7856        d.up_proj.matvec(&x, &mut u, None);
7857        let act_set: std::collections::HashSet<u16> = active.iter().copied().collect();
7858        for i in 0..inter {
7859            g[i] = if act_set.contains(&(i as u16)) {
7860                inference::silu(g[i]) * u[i]
7861            } else {
7862                0.0
7863            };
7864        }
7865        let mut reference = vec![0.0f32; hidden];
7866        d.down_proj.matvec(&g, &mut reference, None);
7867
7868        let max_d = sparse
7869            .iter()
7870            .zip(&reference)
7871            .map(|(a, b)| (a - b).abs())
7872            .fold(0.0f32, f32::max);
7873        assert!(max_d < 1e-5, "sparse != dense-zeroed: max|Δ| = {max_d}");
7874    }
7875
7876    /// Attach a synthetic MTP head (same structure as a main layer).
7877    fn attach_test_mtp(p: &mut Pipeline) {
7878        let (h, inter, heads, kv, hd) = (
7879            p.hidden_size,
7880            p.intermediate_size,
7881            p.num_heads,
7882            p.num_kv_heads,
7883            p.head_dim,
7884        );
7885        let synth = |n: usize, salt: usize| -> Vec<f32> {
7886            (0..n)
7887                .map(|i| (((i * 29 + salt * 23 + 5) % 101) as f32 / 101.0 - 0.5) * 0.2)
7888                .collect()
7889        };
7890        let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
7891            QTensor::from_f32(synth(rows * cols, salt), rows, cols)
7892        };
7893        p.mtp = Some(MtpModule {
7894            enorm: vec![1.0; h],
7895            hnorm: vec![1.0; h],
7896            eh_proj: qt(h, 2 * h, 301),
7897            layer: LayerWeights {
7898                input_norm: vec![1.0; h],
7899                post_norm: vec![1.0; h],
7900                attn_out_norm: None,
7901                ffn_out_norm: None,
7902                layer_scale: None,
7903                ffn: FfnKind::Dense(DenseFfn {
7904                    gate_proj: qt(inter, h, 315),
7905                    up_proj: qt(inter, h, 316),
7906                    down_proj: qt(h, inter, 317),
7907                    act: Act::Silu,
7908                }),
7909                attn: AttnKind::Full {
7910                    bias: None,
7911                    wq: qt(heads * hd, h, 311),
7912                    wk: qt(kv * hd, h, 312),
7913                    wv: qt(kv * hd, h, 313),
7914                    wo: qt(h, heads * hd, 314),
7915                    q_norm: None,
7916                    k_norm: None,
7917                    output_gate: false,
7918                    softplus_gate: None,
7919                },
7920            },
7921            final_norm: vec![1.0; h],
7922            kv: crate::kv_cache::LayerKvCache::new(kv, hd),
7923        });
7924    }
7925
7926    #[test]
7927    fn speculative_equals_vanilla_greedy() {
7928        // Speculative decode and the wgpu token graph are mutually
7929        // exclusive; a leaked CMF_GPU=wgpu from a parallel gpu test
7930        // would silently disable drafting. Pin the graph off.
7931        unsafe { std::env::set_var("CMF_GPU_WGPU_GRAPH", "0") };
7932        let run = |spec: bool| {
7933            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
7934            p.sampler_config.temperature = 0.0;
7935            attach_test_mtp(&mut p);
7936            p.speculative = spec;
7937            let r = p.generate("abcdef", 12, None, None).unwrap();
7938            (r.token_ids, r.mtp_drafted, r.mtp_accepted)
7939        };
7940        let (vanilla, d0, _) = run(false);
7941        let (spec, d1, a1) = run(true);
7942        assert_eq!(d0, 0, "vanilla path must not draft");
7943        assert!(d1 > 0, "speculative path must draft");
7944        assert_eq!(
7945            vanilla, spec,
7946            "speculative must reproduce the exact greedy sequence (accepted {a1}/{d1})"
7947        );
7948    }
7949
7950    #[test]
7951    fn speculative_accepts_constant_oracle() {
7952        // See speculative_equals_vanilla_greedy: pin the wgpu graph off.
7953        unsafe { std::env::set_var("CMF_GPU_WGPU_GRAPH", "0") };
7954        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
7955        p.sampler_config.temperature = 0.0;
7956        p.sampler_config.repetition_penalty = 1.0;
7957        // Constant lm_head → every logit equal → both the main model and
7958        // the draft head argmax to token 0: acceptance must be 100%.
7959        p.weights.lm_head = QTensor::from_f32(vec![0.01; 64 * 8], 64, 8);
7960        attach_test_mtp(&mut p);
7961        p.speculative = true;
7962        let r = p.generate("abcd", 10, None, None).unwrap();
7963        assert!(r.mtp_drafted > 0);
7964        assert_eq!(
7965            r.mtp_accepted, r.mtp_drafted,
7966            "constant logits → every draft accepted"
7967        );
7968        // Ties resolve to the same token in both the main and draft
7969        // heads — the sequence is one repeated token.
7970        assert!(r.token_ids.windows(2).all(|w| w[0] == w[1]));
7971    }
7972
7973    #[test]
7974    fn empty_prompt_is_an_error_not_a_panic() {
7975        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
7976        let r = p.generate("", 4, None, None);
7977        assert!(r.is_err(), "empty prompt must be a clean error");
7978    }
7979
7980    #[test]
7981    fn every_token_enters_kv_exactly_once() {
7982        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
7983        // Greedy so no RNG variance; byte tokenizer → 3 prompt tokens.
7984        p.sampler_config.temperature = 0.0;
7985        let r = p.generate("abc", 2, None, None).unwrap();
7986        assert_eq!(r.prompt_tokens, 3);
7987        // prompt(3) + first sampled token forwarded before second logits:
7988        // step0 samples from prefill hidden (no extra forward), then
7989        // forwards t1 → cache 4; step1 samples, loop ends (max_tokens).
7990        assert_eq!(
7991            p.kv_cache.seq_len(),
7992            3 + r.tokens_generated - 1,
7993            "each token must be cached exactly once (v1 cached the last prompt token twice)"
7994        );
7995    }
7996
7997    #[test]
7998    fn generation_is_reproducible_with_seed() {
7999        let run = || {
8000            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
8001            p.generate("hello", 8, None, None).unwrap().token_ids
8002        };
8003        assert_eq!(run(), run());
8004    }
8005
8006    #[test]
8007    fn resetting_sampler_restarts_the_seeded_stream() {
8008        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
8009        let config = SamplerConfig {
8010            seed: Some(1234),
8011            ..SamplerConfig::default()
8012        };
8013        p.set_sampler_config(config.clone());
8014        let first = p.generate("hello", 8, None, None).unwrap().token_ids;
8015        p.set_sampler_config(config);
8016        let second = p.generate("hello", 8, None, None).unwrap().token_ids;
8017        assert_eq!(first, second);
8018    }
8019
8020    #[test]
8021    fn eviction_bounds_the_cache() {
8022        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
8023        p.kv_cache.max_seq_len = 6;
8024        p.sampler_config.temperature = 0.0;
8025        let _ = p.generate("abcd", 12, None, None).unwrap();
8026        assert!(
8027            p.kv_cache.seq_len() <= 6 + 1,
8028            "cache must stay bounded by max_seq_len (got {})",
8029            p.kv_cache.seq_len()
8030        );
8031    }
8032
8033    #[test]
8034    fn confidence_matches_tokens_and_is_a_probability() {
8035        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
8036        p.sampler_config.temperature = 0.0;
8037        p.sampler_config.repetition_penalty = 1.0;
8038        let r = p.generate("abcd", 10, None, None).unwrap();
8039        assert_eq!(
8040            r.token_confidence.len(),
8041            r.token_ids.len(),
8042            "one confidence per emitted token"
8043        );
8044        for &c in &r.token_confidence {
8045            assert!((0.0..=1.0).contains(&c), "confidence out of [0,1]: {c}");
8046        }
8047        // top1_prob is a valid softmax probability.
8048        let logits = [1.0f32, 3.0, 0.5, 3.0];
8049        let p0 = top1_prob_t(&logits, 1, 1.0);
8050        let p1 = top1_prob_t(&logits, 3, 1.0);
8051        assert!((p0 - p1).abs() < 1e-6, "equal logits → equal prob");
8052        assert!(p0 > 0.0 && p0 < 1.0);
8053        // Calibration temperature > 1 softens an over-confident peak.
8054        let sharp = top1_prob_t(&logits, 1, 1.0);
8055        let soft = top1_prob_t(&logits, 1, 2.0);
8056        assert!(soft < sharp, "higher temperature lowers peak confidence");
8057    }
8058
8059    #[test]
8060    fn trace_is_opt_in_and_parallels_the_output() {
8061        // Off by default: the runtime is silent unless observation asked.
8062        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
8063        p.sampler_config.temperature = 0.0;
8064        p.sampler_config.repetition_penalty = 1.0;
8065        let r = p.generate("abcd", 10, None, None).unwrap();
8066        assert!(r.traces.is_empty(), "trace must be empty unless enabled");
8067
8068        // On: exactly one row per emitted token, aligned with the output.
8069        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
8070        p.sampler_config.temperature = 0.0;
8071        p.sampler_config.repetition_penalty = 1.0;
8072        p.set_trace(true);
8073        let r = p.generate("abcd", 10, None, None).unwrap();
8074        assert_eq!(r.traces.len(), r.token_ids.len(), "one trace row per token");
8075        for (i, tr) in r.traces.iter().enumerate() {
8076            assert_eq!(tr.t, i, "trace index is sequential");
8077            assert_eq!(tr.token_id, r.token_ids[i], "trace token_id matches output");
8078            assert_eq!(
8079                tr.confidence, r.token_confidence[i],
8080                "trace confidence matches the confidence channel"
8081            );
8082            // No dynamic router in this pipeline → no skill, no coherence.
8083            assert!(tr.active_skill.is_none() && tr.recon.is_none() && !tr.switched);
8084        }
8085    }
8086
8087    #[test]
8088    fn explain_prefill_logits_match_greedy_first_token() {
8089        // `cortiq explain` shows the next-token distribution from
8090        // prefill_next_logits; its argmax must equal what greedy generate
8091        // actually emits first — otherwise explain would lie.
8092        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
8093        p.sampler_config.temperature = 0.0;
8094        p.sampler_config.repetition_penalty = 1.0;
8095        let ids = p.tokenizer.encode("abcd");
8096        let logits = p.prefill_next_logits(&ids, None);
8097        let argmax = logits
8098            .iter()
8099            .enumerate()
8100            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
8101            .unwrap()
8102            .0 as u32;
8103        let r = p.generate("abcd", 1, None, None).unwrap();
8104        assert_eq!(
8105            argmax, r.token_ids[0],
8106            "explain preview must match greedy emit"
8107        );
8108    }
8109
8110    #[test]
8111    fn laguna_shared_expert_is_unconditionally_added() {
8112        let matrix = |values: Vec<f32>| QTensor::from_f32(values, 2, 2);
8113        let identity = || matrix(vec![1.0, 0.0, 0.0, 1.0]);
8114        let zero_dense = || DenseFfn {
8115            gate_proj: matrix(vec![0.0; 4]),
8116            up_proj: matrix(vec![0.0; 4]),
8117            down_proj: matrix(vec![0.0; 4]),
8118            act: Act::Silu,
8119        };
8120        let shared = DenseFfn {
8121            gate_proj: identity(),
8122            up_proj: identity(),
8123            down_proj: identity(),
8124            act: Act::Silu,
8125        };
8126        let x = [1.0, 2.0];
8127        let expected = dense_ffn(&shared, &x, None);
8128        let moe = MoeFfn {
8129            router: QTensor::from_f32(vec![0.0, 0.0], 1, 2),
8130            experts: vec![zero_dense()],
8131            top_k: 1,
8132            norm_topk_prob: true,
8133            router_sigmoid: true,
8134            expert_bias: None,
8135            routed_scaling: 1.0,
8136            route_tau: None,
8137            shared: Some((shared, None)),
8138            stats: std::cell::RefCell::new(Vec::new()),
8139            act_sq: std::cell::RefCell::new(Vec::new()),
8140            act_rows: std::cell::RefCell::new(Vec::new()),
8141            mask: None,
8142            per_expert_scale: None,
8143            router_input_norm: false,
8144        };
8145        let actual = moe_ffn_cpu(&moe, &x, &[0], &[0.0], 1.0, None);
8146        for (actual, expected) in actual.iter().zip(expected) {
8147            assert!((actual - expected).abs() < 1e-6);
8148        }
8149    }
8150}