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;
11
12/// MiMo-V2 multi-token prediction (draft stack + speculative round). A
13/// child module so it runs on the pipeline's own helpers.
14#[path = "mimo_mtp.rs"]
15pub mod mimo_mtp;
16use crate::kv_cache::KvCache;
17use crate::linear_core::{
18    GdnCfg, GdnWeights, ShortConvCfg, ShortConvWeights, VmfPhaseCfg, VmfPhaseWeights, gdn_forward,
19    gdn_pair, short_conv_forward, short_conv_forward_batch, short_conv_pair, vmf_phase_forward,
20    vmf_phase_pair,
21};
22use crate::pool::Pool;
23use crate::qtensor::QTensor;
24use crate::sampler::{self, SamplerConfig, SamplerScratch, SplitMix64};
25use crate::tokenizer::Tokenizer;
26use cortiq_core::mask::TaskMask;
27use cortiq_core::types::NormStyle;
28
29pub static GLOBAL_USE_GPU: std::sync::atomic::AtomicBool =
30    std::sync::atomic::AtomicBool::new(false);
31
32/// Reusable per-pipeline forward scratch: the four norm outputs the
33/// decode paths recompute every layer (single: n1/p1; pair: all four).
34/// Plain buffers, resized once — steady-state decode reuses them.
35struct ForwardScratch {
36    n1: Vec<f32>,
37    n2: Vec<f32>,
38    p1: Vec<f32>,
39    p2: Vec<f32>,
40}
41
42impl ForwardScratch {
43    fn new(hidden: usize) -> Self {
44        Self {
45            n1: vec![0.0; hidden],
46            n2: vec![0.0; hidden],
47            p1: vec![0.0; hidden],
48            p2: vec![0.0; hidden],
49        }
50    }
51}
52
53/// Complete inference pipeline state.
54pub struct Pipeline {
55    /// In-process layer split across local GPUs: (device, first layer,
56    /// last layer) per segment, in execution order. `None` = one device.
57    /// Arc so cloning the plan out of `&mut self` does not fight the
58    /// borrow checker on the hot path.
59    gpu_plan: Option<std::sync::Arc<Vec<(usize, usize, usize)>>>,
60    /// Arc: the server shares one tokenizer handle across request
61    /// handlers without borrowing a pipeline slot.
62    pub tokenizer: std::sync::Arc<Tokenizer>,
63    pub kv_cache: KvCache,
64    pub sampler_config: SamplerConfig,
65    pub weights: PipelineWeights,
66    pub hidden_size: usize,
67    pub intermediate_size: usize,
68    pub num_heads: usize,
69    pub num_kv_heads: usize,
70    pub head_dim: usize,
71    /// Total virtual layers (num_layers × num_loops for looped models).
72    pub num_layers: usize,
73    /// Physical layers in weights.layers (≤ num_layers for looped models).
74    pub physical_layers: usize,
75    /// Looped Transformer: apply final norm after each loop iteration.
76    pub loop_final_norm: bool,
77    pub vocab_size: usize,
78    pub rms_eps: f64,
79    pub rope_base: f32,
80    pub norm_style: NormStyle,
81    /// RoPE dims actually rotated (≤ head_dim; Qwen3.5 uses head_dim/4).
82    pub rotary_dim: usize,
83    /// Optional Q-head count override for each attention layer (Laguna).
84    pub attention_heads_per_layer: Option<Vec<usize>>,
85    /// Optional KV-head count of each PHYSICAL attention layer (MiMo-V2:
86    /// 4 on full-attention layers, 8 on sliding ones). Set only through
87    /// [`Pipeline::set_attn_geometry`], which also reshapes the layer
88    /// caches. None = every layer has `num_kv_heads`.
89    pub kv_heads_per_layer: Option<Vec<usize>>,
90    /// Width of each V head when it is narrower than `head_dim` (MiMo-V2:
91    /// 128 against 192). V is zero-padded to `head_dim` inside the cache
92    /// and the attention output is compacted back to nh·v_head_dim before
93    /// o_proj (see `QwenAttnCfg::v_head_dim`). None = `head_dim`.
94    pub v_head_dim: Option<usize>,
95    /// `CMF_LAYER_DUMP=<dir>` (read once at construction; tests set it
96    /// directly): the hidden state after every layer, for every position,
97    /// as raw little-endian f32 files `p{pos:06}_l{li:02}.f32` of
98    /// `hidden_size` floats each. Written by the CPU layer walks — the
99    /// batched prefill (`prefill_batch_span`) and the single-token forward
100    /// (`forward_layers_span`) — so both prompt ingest and decode can be
101    /// diffed layer by layer against an external oracle (tools/mimo_ref).
102    /// Layers a device graph runs (wgpu token/batch graph, Metal chunk or
103    /// block graphs) and the own-stack families (DeepSeek-V4/V4.1,
104    /// Qwen3.8-Flash-Next, Gemma-3n) are not dumped: run with CMF_GPU=0
105    /// for a complete set. `li` is the virtual layer index. Final logits:
106    /// `CMF_LOGIT_DUMP=<file>` (hidden + logits of the first decode step).
107    pub layer_dump: Option<std::path::PathBuf>,
108    /// GPU-graph declines already logged for this pipeline, as (graph
109    /// site, reason) — one line each, see `graph_attn_decline_reason`.
110    graph_declines: std::cell::RefCell<Vec<(&'static str, &'static str)>>,
111    /// MiMo-V2 expert placement (prefix / dynamic bank / hybrid), decided
112    /// on the first forward — see `crate::mimo_moe`.
113    pub(crate) mimo_moe: crate::mimo_moe::Slot,
114    /// Opt-in MiniCPM q4tp expert cache for a graph-produced CPU tail.
115    /// It is deliberately separate from MiMo's placement policy because it
116    /// serves only the stock MiniCPM top-8 geometry and otherwise falls back
117    /// to the ordinary exact host MoE path.
118    pub(crate) minicpm_tail: crate::minicpm_tail::MiniCpmTail,
119    /// Linear-core geometry (present when the model has linear layers).
120    pub vmf_cfg: Option<VmfPhaseCfg>,
121    /// GatedDeltaNet geometry (faithful vendor operator).
122    pub gdn_cfg: Option<GdnCfg>,
123    /// MiniCPM-class logit scale (tied lm_head → cannot fold into weights).
124    pub logit_multiplier: Option<f32>,
125    /// Cooperative cancel: set from any thread (FFI `cortiq_cancel`,
126    /// a dropped server connection); the generate loop checks it at
127    /// every prefill chunk and decode step and finishes with
128    /// `finish_reason: "cancelled"`. Auto-cleared when honoured.
129    pub cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
130    /// A GPU graph failure is distinct from a user/request cancellation.
131    /// Graph code sets this before raising the cooperative cancel flag so the
132    /// generation API can return an error instead of reporting a successful
133    /// `finish_reason: cancelled` result.
134    graph_failed: std::sync::atomic::AtomicBool,
135    /// Token ids currently materialized in the KV cache (the forwarded
136    /// prompt + all generated tokens except the last, which is sampled
137    /// but not yet forwarded). Lets the next generate call prefill only
138    /// the suffix when a chat app resends the whole history.
139    pub kv_history: Vec<u32>,
140    /// Owner tag of `kv_history`: the resident device graph held that
141    /// sequence (true) or the host did. Reuse continues only on the owner.
142    pub kv_history_device: bool,
143    /// KDA geometry (Kimi Linear / Kimi-K3) — shared by every Kda layer.
144    pub kda_cfg: Option<crate::linear_core::KdaCfg>,
145    /// Gemma-3n stack (AltUp/LAuReL/PLE/KV-sharing): its own forward —
146    /// weights.layers stays empty, the KV caches are the shared ones.
147    pub g3n: Option<Box<(crate::g3n::G3nGlobals, Vec<crate::g3n::G3nLayer>)>>,
148    /// Gemma-4 E-series stack (dual-geometry gemma4 + PLE + shared KV):
149    /// its own per-token forward, same contract as `g3n`.
150    pub g4e: Option<Box<(crate::g4e::G4eGlobals, Vec<crate::g4e::G4eLayer>)>>,
151    /// DeepSeek-V4 runs its own stack too: its hidden state is `hc_mult`
152    /// copies of a vector, so no loop written for a single residual
153    /// stream can carry it.
154    pub dsv4: Option<
155        Box<(
156            crate::dsv4::Dsv4Globals,
157            Vec<crate::dsv4::Dsv4Layer>,
158            crate::dsv4::Dsv4Cfg,
159            crate::dsv4::Dsv4State,
160        )>,
161    >,
162    /// DeepSeek-V4.1 owns the shared CED/CSA2 attention state, raw Engram
163    /// lookup and four-stream mHC handoff. It cannot use the V4 cache
164    /// layout, so it has a dedicated executor and state tuple.
165    pub dsv41: Option<
166        Box<(
167            crate::dsv41::Dsv41Globals,
168            Vec<crate::dsv41::Dsv41Layer>,
169            crate::dsv41::Dsv41Cfg,
170            crate::dsv41::Dsv41State,
171        )>,
172    >,
173    /// Optional V4.1 vision tower. Text-only files leave this unset.
174    pub dsv41_vision: Option<crate::dsv41_vision::VisionModel>,
175    /// Prepared image rows consumed by the next V4.1 prefill.
176    dsv41_prefill: Option<(Vec<Option<Vec<f32>>>, Vec<bool>)>,
177    /// Qwen3.8-Flash-Next owns four residual streams plus QSA/PLE state;
178    /// the generic single-residual layer loop cannot represent it.
179    pub qwen4_exp: Option<
180        Box<(
181            crate::qwen4_exp::Globals,
182            Vec<crate::qwen4_exp::Layer>,
183            crate::qwen4_exp::Cfg,
184            crate::qwen4_exp::State,
185        )>,
186    >,
187    /// DeepSeek-V4's own speculation stack: three draft modules, each a full
188    /// layer, plus a confidence head on the last. Empty when the file has
189    /// none, which is the only signal the decode path needs.
190    pub dsv4_mtp: Vec<crate::dsv4::Dsv4Mtp>,
191    /// The draft's per-sequence state (KV rings, captured trunk hidden).
192    pub dspark: Option<crate::dsv4::DsparkState>,
193    /// Drafts awaiting their verdict: (position, proposals, still matching,
194    /// accepted so far).
195    pub dspark_pending: Vec<(usize, Vec<u32>, bool, usize)>,
196    /// Accepted prefix length of every graded draft.
197    pub dspark_hist: Vec<usize>,
198    /// The real tokens the drafts were graded against — a degenerate,
199    /// repeating output would make any acceptance number meaningless, and
200    /// the cheapest guard against believing one is to count them.
201    pub dspark_real: Vec<u32>,
202    /// The trunk's expert picks for the last few tokens, per layer. The
203    /// union over a window of them is what a batched verify would have to
204    /// read, and the ratio to the pick count is all it could save.
205    pub dspark_trunk_picks: Vec<Vec<(usize, Vec<usize>)>>,
206    /// (unique, total) expert picks per draft, trunk side and draft side.
207    pub dspark_exp: Vec<(usize, usize, usize, usize)>,
208    /// Wall time spent in the deliberately out-of-core draft. Kept separate
209    /// from trunk decode so block batching can be judged without conflating
210    /// it with GPU chain variance.
211    pub dspark_draft_ns: u128,
212    /// Per-layer winners of the last pooled route — the admission predictor.
213    m3_winners: Vec<Vec<u32>>,
214    /// Route frequency per (layer, expert) — the bank's prewarm profile.
215    m3_counts: Vec<u32>,
216    m3_n_exp: usize,
217    m3_tokens: u64,
218    m3_prewarmed: bool,
219    /// LFM2 short-convolution geometry (present when the model has
220    /// `ShortConv` mixer layers).
221    pub short_conv_cfg: Option<ShortConvCfg>,
222    /// Multi-token-prediction head (None = absent).
223    pub mtp: Option<MtpModule>,
224    /// MiMo-V2's draft stack (three chained MTP layers from the
225    /// `<stem>.mtp.cmf` sidecar); None = absent. Speculative greedy decode
226    /// uses it unless `CMF_MTP=0` / `CMF_MIMO_MTP=0`.
227    pub mimo_mtp: Option<mimo_mtp::MimoMtp>,
228    /// Set while the MiMo speculative verify runs `prefill_batch`: its MoE
229    /// layers take `moe_ffn_rows_exact` (each row bit-identical to decode).
230    verify_exact_moe: bool,
231    /// Speculative decode via MTP (greedy only; `CMF_MTP=0` disables).
232    pub speculative: bool,
233    /// Keep generating past end-of-sequence ids (the llama-bench contract
234    /// for a timed run). A loop flag, deliberately NOT a sampler
235    /// suppression: suppressed ids count as a penalty and switch the
236    /// speculative round and the greedy burst off, so a benchmark that
237    /// suppressed EOS never measured either.
238    pub ignore_eos: bool,
239    /// Draft-head shortlist guard: tokens left during which the draft
240    /// uses the FULL head because a recently committed id lay past the
241    /// `CMF_DRAFT_VOCAB` cut (Cyrillic and CJK ids sit above 131072 in
242    /// Qwen's table, so a prefix shortlist would draft nothing usable
243    /// there — measured on Russian prose: 2.9 → 1.6 accepted a round).
244    pub draft_full_streak: u32,
245    /// Adaptive draft depth for the speculative round (None until the
246    /// first round): grows while nearly every draft is accepted, shrinks
247    /// when fewer than half are. The verify's cost climbs with the rows on
248    /// a discrete card (RTX PRO 4000: 52 ms at 2 rows, 74 at 5, 80 at 6),
249    /// so prose wants k≈3 and code or the repetitive bench k≈5 — measured
250    /// 33.6 vs 27.6 tok/s on an essay at k=3 vs 5, 45.6 vs 38 on code.
251    /// `CMF_GRAPH_SPEC_K` pins it.
252    pub spec_k_adapt: Option<usize>,
253    /// EWMA of the accepted fraction that drives `spec_k_adapt`.
254    pub spec_acc_ewma: f32,
255    rng: SplitMix64,
256    sampler_scratch: SamplerScratch,
257    /// Speculative SAMPLING state (graph_spec_step, temperature > 0): the
258    /// correction token a rejected draft produced — committed by the loop
259    /// top in place of a fresh draw — and the per-round draft
260    /// distributions / target scratch, reused so a round allocates
261    /// nothing at the vocab size.
262    spec_forced: Option<u32>,
263    spec_q: Vec<Vec<f32>>,
264    spec_p: Vec<f32>,
265    spec_res: Vec<f32>,
266    /// The same three for the sparse chain (top-k configs).
267    spec_qs: Vec<sampler::Sparse>,
268    spec_ps: sampler::Sparse,
269    spec_ress: sampler::Sparse,
270    /// Which arm the MTP draft block runs on this generation: Some(true)
271    /// = the whole-token graph (device attention, one submit a step),
272    /// Some(false) = the per-op path; None = not decided yet. Decided
273    /// on the first draft and held, because the two arms keep the MTP
274    /// KV in different places (device mirror vs the CPU cache) and a
275    /// mid-run switch would read the wrong one.
276    mtp_graph_mode: Option<bool>,
277    /// The Metal verify graph of the round in flight, between its sync
278    /// (logits read) and the commit that replays the accepted prefix.
279    #[cfg(target_os = "macos")]
280    metal_verify: Option<MetalVerifyPending>,
281    /// Precomputed RoPE inverse frequencies [head_dim/2]. Arc: the
282    /// forward path clones a handle to escape the &mut self borrow —
283    /// cloning the table itself was a per-forward allocation.
284    pub(crate) inv_freq: std::sync::Arc<Vec<f32>>,
285    /// Reusable norm buffers for the decode hot path (roadmap §3 P0:
286    /// steady-state forward should not heap-allocate). Disjoint field
287    /// from `weights`/`kv_cache`, so split borrows keep working.
288    ws: ForwardScratch,
289    /// Persistent worker pool (None = serial; see CMF_THREADS).
290    pool: Option<std::sync::Arc<Pool>>,
291    // ── Dynamic per-token skill routing (spec §9, claim 14/16) ──
292    /// Source model, retained so a skill switch can re-resolve the
293    /// touched layers' FFN tensors (Mapped = mmap pointers, cheap).
294    pub(crate) model: Option<std::sync::Arc<cortiq_core::CmfModel>>,
295    /// Masks present → weights are dequantized f32 (rebuild path).
296    pub(crate) dyn_force_f32: bool,
297    /// Per-skill FFN layers actually replaced (derived from tensors, not
298    /// the meta `layers` field — ru2 replaces down_proj in 0..23 while
299    /// its meta says [20..23]). None = skill touches non-FFN tensors →
300    /// ineligible for cheap dynamic switching (honest refusal).
301    pub(crate) dyn_skill_layers: Vec<Option<Vec<usize>>>,
302    /// Currently overlaid skill (index into model.header.skills); None =
303    /// backbone. Set at load time to the statically-overlaid skill so
304    /// `set_active_skill(None)` correctly reverts it (else a static
305    /// skill would silently persist — the union-diff assumes dyn_active
306    /// always mirrors the live overlay). Switched by `set_active_skill`.
307    pub(crate) dyn_active: Option<usize>,
308    /// Pipeline was loaded with a soft blend (materialized working
309    /// tensors, not a single skill index) → dynamic routing refuses:
310    /// there is no single index to revert the blend from.
311    pub(crate) dyn_blend_loaded: bool,
312    /// Layer whose post-residual hidden feeds the router φ (shared by
313    /// swarm skills). None = φ capture off.
314    pub(crate) dyn_phi_layer: Option<usize>,
315    /// EMA of φ at `dyn_phi_layer` over the decode window (on-policy).
316    dyn_phi_ema: Vec<f32>,
317    dyn_phi_seen: usize,
318    /// Hysteresis router driving per-token skill switches during decode
319    /// (None = static/no dynamic routing). Taken out during generation.
320    pub dyn_router: Option<crate::swarm::DynRouter>,
321    /// O(1) Nyström attention setting (CLI/env/header-hint resolved by
322    /// the caller; None = plain cache attention everywhere).
323    o1_cfg: Option<crate::nystrom::O1Cfg>,
324    /// Bumped once per collecting→sealed transition — the GPU state mirror
325    /// re-uploads when it sees a new epoch (each fresh sealed state).
326    o1_epoch: u64,
327    /// Per-layer o1 flags derived from `o1_cfg` (Full layers only).
328    o1_flags: Vec<bool>,
329    /// Emit a structured per-token trace (B4 telemetry channel). Off by
330    /// default — the runtime is silent unless observation is requested.
331    trace: bool,
332    /// Confidence-calibration temperature (B1): reported probability is
333    /// softmax(logits / calib_temp). 1.0 = raw. Set from header.calibration.
334    calib_temp: f32,
335    /// Process-unique id keying this pipeline's device KV mirrors.
336    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
337    graph_kv_id: u64,
338    /// Decode asks the token graph to also run final-norm + lm_head on
339    /// the device (drops the separate per-op lm_head round trip).
340    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
341    graph_want_logits: bool,
342    /// NLL quality gates require the graph's fused head rather than silently
343    /// accepting a CPU head fallback. Generation keeps the historical
344    /// best-effort `graph_want_logits` behavior.
345    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
346    graph_head_required: bool,
347    /// Logits the graph produced for the token just forwarded (taken by
348    /// the decode loop; None = compute on the CPU path).
349    graph_logits: Option<Vec<f32>>,
350    /// Packed Embryo graph model, built lazily on the first eligible
351    /// resident call so other architectures pay no packing cost.
352    embryo_graph: Option<std::sync::Arc<crate::gpu::EmbryoGraphModel>>,
353    /// This pipeline's token graph refused for a STRUCTURAL reason (its
354    /// own weights / layer kinds): not retried. Per pipeline, never
355    /// process-wide: a skill lane whose pack does not build must not flip
356    /// the backbone slot mid-sequence onto the host path (and a new lane
357    /// must not clear the backbone's verdict) — R4/NF-2.
358    graph_refused: std::sync::atomic::AtomicBool,
359    /// Token embeddings are multiplied by this at input (Gemma: √hidden).
360    pub embed_multiplier: f32,
361    /// Attention score scale (1/√head_dim unless the arch overrides —
362    /// Gemma's query_pre_attn_scalar).
363    pub attn_scale: f32,
364    /// Sliding-window attention: (window, every-Nth-layer-is-global
365    /// pattern) — Gemma-3.
366    pub swa: Option<(usize, usize)>,
367    /// Sliding-window tail trimming, `(slack, align)` for
368    /// `LayerKvCache::trim_window`: every layer with a window keeps only
369    /// the rows its window can still read (Spark-X2.5: 576..639 rows per
370    /// 512-window layer instead of the whole context — 27 of the 4B's 36
371    /// layers). Set at load for Spark-X2.5 only (`CMF_SWA_TRIM=0` turns
372    /// it off); None keeps every row, as every other model always has.
373    pub swa_trim: Option<(usize, usize)>,
374    /// Explicit local/global schedule for architectures that cannot be
375    /// represented by Gemma's every-Nth-global convention.
376    pub sliding_layers: Option<Vec<bool>>,
377    /// Per-layer flag: this layer runs WITHOUT RoPE. Recursive Flint applies
378    /// position encoding only on its sliding-window layers; its 14
379    /// full-attention layers have none. The rotary dim of such a layer is 0,
380    /// which is what the attention kernel reads.
381    pub no_rope_layers: Option<Vec<bool>>,
382    /// Natively bounded anchor record (`arch.anchor_core`): the file's
383    /// operator, installed once at load. `Some` = the model is
384    /// bounded-native — `--o1`/`CMF_O1*` are refused, prefix reuse and
385    /// the penalty window are bounded, and no anchor layer stores
386    /// anything per position.
387    pub anchor_core: Option<cortiq_core::AnchorCoreConfig>,
388    /// The `[W][rd/2]` relative-rotation table every bounded layer shares
389    /// (built from `inv_freq` once the RoPE setup is final).
390    bounded_rope: Option<std::sync::Arc<crate::bounded::BoundedRope>>,
391    /// Bounded prefix-reuse key (length + rolling hash + tail) of a
392    /// bounded-native model; `kv_history` stays empty there so nothing
393    /// in the pipeline grows with the dialogue.
394    pub kv_prefix: KvPrefix,
395    /// Prompt positions the last `generate*` call actually forwarded
396    /// (prefix reuse subtracts what the cache already held).
397    pub last_prefill_tokens: usize,
398    /// RoPE table of the sliding (local) layers, when they use their
399    /// own base frequency (Gemma-3: 10k local vs 1M global).
400    pub inv_freq_local: Option<std::sync::Arc<Vec<f32>>>,
401    pub rotary_dim_local: Option<usize>,
402    pub rope_scale: f32,
403    pub rope_scale_local: f32,
404    /// Gemma-4: global layers run their own geometry — (head_dim,
405    /// num_kv_heads); sliding layers keep the base fields.
406    pub global_attn: Option<(usize, usize)>,
407    /// Gemma-4: the global layers' proportional RoPE table (len
408    /// global_head_dim/2, zero-padded tail = identity rotation).
409    pub inv_freq_global: Option<std::sync::Arc<Vec<f32>>>,
410    /// Scale-less RMS normalization of V heads before caching (Gemma-4).
411    pub attn_v_norm: bool,
412    /// HunYuan dense: per-head q/k norm runs after RoPE (see the arch flag).
413    pub qk_norm_after_rope: bool,
414    /// The per-head `self_attn.g_proj` output gate uses sigmoid
415    /// (Spark-X2.5) instead of softplus (Laguna).
416    pub proj_gate_sigmoid: bool,
417    /// Final-logit soft-capping C: logits = C·tanh(logits/C) (Gemma-4).
418    pub final_softcap: Option<f32>,
419    /// Cortiq Embryo hierarchical head: cluster matrix [C, hidden]. The
420    /// flat logits h·Eᵀ are turned into the two-level log-probabilities
421    /// log softmax_c(h·Cᵀ)[c(v)] + log softmax_{s∈c(v)}(h·E_c(v)ᵀ)[v].
422    pub head_clusters: Option<std::sync::Arc<Vec<f32>>>,
423    /// Gemma-2 attention-logit soft-capping (0.0 = off).
424    pub attn_softcap: f32,
425    /// Compute per-token confidence (a full-vocab softmax each
426    /// token). On by default; `bench --core` turns it off to match
427    /// llama-bench's core timing.
428    confidence_on: bool,
429    /// Test-only one-shot forward failure, scoped to this pipeline so
430    /// parallel scoring tests cannot consume one another's injection.
431    #[cfg(test)]
432    nll_test_fail_at: Option<usize>,
433    /// Test-only route override; avoids mutating the process-wide
434    /// `CMF_PREFILL` environment variable while forcing the serial path.
435    #[cfg(test)]
436    nll_test_force_serial: bool,
437}
438
439#[cfg(target_os = "macos")]
440impl Drop for Pipeline {
441    fn drop(&mut self) {
442        // the async replay writes into `kv_cache` Vecs about to be freed
443        let _ = crate::gpu_metal::wait_replay();
444        crate::gpu::kv_mirror_drop(self.graph_kv_id);
445    }
446}
447
448#[cfg(not(target_os = "macos"))]
449impl Drop for Pipeline {
450    fn drop(&mut self) {
451        // The wgpu resident Embryo graph owns recurrent/KV buffers keyed by
452        // this pipeline's sequence id.  Release that sequence image when a
453        // pooled pipeline is dropped; model weights stay cached for reuse.
454        crate::gpu::graph_kv_reset(self.graph_kv_id);
455    }
456}
457
458/// Model weights. Matrices are `QTensor` (owned f32 for small models
459/// and tests — bit-identical to the historical paths — or quantized
460/// bytes zero-copy from the CMF mmap for big models). 1-D norms are
461/// always small and stay f32.
462pub struct PipelineWeights {
463    /// Embedding table: [vocab_size, hidden_size]
464    pub embed_tokens: QTensor,
465    /// Per-layer weights
466    pub layers: Vec<LayerWeights>,
467    /// LM head: [vocab_size, hidden_size]
468    pub lm_head: QTensor,
469    /// Final norm: [hidden_size]
470    pub final_norm: Vec<f32>,
471}
472
473/// One transformer layer: shared norms + MLP, attention by kind.
474pub struct LayerWeights {
475    pub input_norm: Vec<f32>,
476    /// The pre-FFN norm (`post_attention_layernorm` classically;
477    /// `pre_feedforward_layernorm` on Gemma-2/3 sandwich layers).
478    pub post_norm: Vec<f32>,
479    /// Gemma-2/3 sandwich: norm applied to the ATTENTION OUTPUT before
480    /// its residual add (`post_attention_layernorm` there).
481    pub attn_out_norm: Option<Vec<f32>>,
482    /// Gemma-4: the whole layer output is multiplied by this scalar.
483    pub layer_scale: Option<f32>,
484    /// Gemma-2/3 sandwich: norm applied to the FFN OUTPUT before its
485    /// residual add (`post_feedforward_layernorm`).
486    pub ffn_out_norm: Option<Vec<f32>>,
487    pub ffn: FfnKind,
488    pub attn: AttnKind,
489}
490
491/// FFN gate activation: SiLU (SwiGLU family), tanh-GELU (Gemma's GeGLU),
492/// or a source-specific gated contract. A property of the model, carried on
493/// every FFN triple.
494#[derive(Clone, Copy, PartialEq, Debug, Default)]
495pub enum Act {
496    #[default]
497    Silu,
498    GeluTanh,
499    /// Exact erf GELU (HF `hidden_act = "gelu"`: Spark-X2.5).
500    Gelu,
501    /// Kimi-K3 SituAndMul: BOTH halves transform —
502    /// a = β·tanh(g/β)·σ(g), up' = linβ·tanh(u/linβ) (linβ>0), out = a·up'.
503    Situ {
504        beta: f32,
505        linear_beta: f32,
506    },
507    /// MiniMax M3's SwiGLU-OAI: upper-clamped gate, symmetrically clamped
508    /// up branch, `sigmoid(alpha * gate)`, and a `+1` up-branch offset.
509    /// It deliberately has no generic GPU graph arm until a matching kernel
510    /// exists; CPU uses the exact scalar reference in `inference`.
511    SwiGluOai {
512        alpha: f32,
513        limit: f32,
514    },
515}
516
517impl Act {
518    pub fn from_arch(name: &str) -> Self {
519        if name == "gelu_tanh" {
520            Self::GeluTanh
521        } else if name == "gelu" {
522            Self::Gelu
523        } else {
524            Self::Silu
525        }
526    }
527
528    /// Arch-driven constructor (activation name + situ betas).
529    pub fn from_arch_full(arch: &cortiq_core::ModelArch) -> Self {
530        match arch.hidden_act.as_str() {
531            "situ" => Self::Situ {
532                beta: arch.activation_situ_beta.unwrap_or(1.0) as f32,
533                linear_beta: arch.activation_situ_linear_beta.unwrap_or(0.0) as f32,
534            },
535            // `swigluoai` alone is deliberately not a generic activation
536            // alias.  Its alpha/limit are part of MiniMax M3's checked
537            // source contract, and accepting that string on an unrelated
538            // architecture would silently impose M3 math on its FFN.
539            "swigluoai" if arch.arch_name == "minimax_m3_vl" => Self::SwiGluOai {
540                alpha: 1.702,
541                limit: 7.0,
542            },
543            other => Self::from_arch(other),
544        }
545    }
546
547    /// Construct the MiniMax M3 SwiGLU-OAI activation from a checked model
548    /// contract. This is intentionally explicit rather than recognizing an
549    /// arbitrary `hidden_act` string: callers must validate `alpha` and
550    /// `limit` against their source architecture before enabling it.
551    #[inline]
552    pub fn swiglu_oai(alpha: f32, limit: f32) -> Self {
553        Self::SwiGluOai { alpha, limit }
554    }
555
556    #[inline]
557    pub fn apply(self, x: f32) -> f32 {
558        match self {
559            Self::Silu => inference::silu(x),
560            Self::GeluTanh => inference::gelu_tanh(x),
561            Self::Gelu => inference::gelu_erf(x),
562            Self::Situ { beta, .. } => beta * (x / beta).tanh() * (1.0 / (1.0 + (-x).exp())),
563            Self::SwiGluOai { alpha, limit } => {
564                let gate = x.min(limit);
565                gate * (1.0 / (1.0 + (-alpha * gate).exp()))
566            }
567        }
568    }
569
570    /// Gated combine — the FFN contract. Situ transforms the UP half
571    /// too, so callers must use this instead of apply(g)·u.
572    #[inline]
573    pub fn combine(self, g: f32, u: f32) -> f32 {
574        match self {
575            Self::Situ { linear_beta, .. } if linear_beta > 0.0 => {
576                self.apply(g) * (linear_beta * (u / linear_beta).tanh())
577            }
578            Self::SwiGluOai { alpha, limit } => {
579                inference::swiglu_oai(g, u, alpha, 1.0, Some(limit))
580            }
581            _ => self.apply(g) * u,
582        }
583    }
584
585    /// The wgpu graphs' arm for this activation; None = no device kernel
586    /// computes it, and the graph builder must refuse the layer (the dense
587    /// graph FFN once computed SiLU for whatever the model asked for).
588    pub fn graph_act(self) -> Option<crate::gpu::GraphAct> {
589        match self {
590            Self::Silu => Some(crate::gpu::GraphAct::Silu),
591            Self::Gelu => Some(crate::gpu::GraphAct::GeluErf),
592            Self::GeluTanh => Some(crate::gpu::GraphAct::GeluTanh),
593            Self::Situ { .. } | Self::SwiGluOai { .. } => None,
594        }
595    }
596
597    /// The WGPU graph arm.  Keep this deliberately separate from
598    /// `graph_act`: OAI needs its dedicated code rather than a generic SiLU
599    /// fallback.  Only the frozen MiniMax-M3 source constants get a device
600    /// code; a future OAI-like architecture with different constants must add
601    /// and test its own kernel contract.
602    pub(crate) fn wgpu_graph_act(self) -> Option<crate::gpu::GraphAct> {
603        self.moe_job_graph_contract().map(|(act, _)| act)
604    }
605
606    /// The exact device contract for a gate/up/down MoE job.  OAI is not a
607    /// generic "clamped SiLU": code 3 commits a backend to MiniMax M3's
608    /// alpha, asymmetric up transform, and frozen clamp.  Keep the clamp
609    /// alongside the marker so a backend cannot accidentally run code 3 with
610    /// a nearby model's limit.
611    pub(crate) fn moe_job_graph_contract(self) -> Option<(crate::gpu::GraphAct, f32)> {
612        match self {
613            Self::SwiGluOai { alpha, limit }
614                if alpha.to_bits() == 1.702f32.to_bits()
615                    && limit.to_bits() == 7.0f32.to_bits() =>
616            {
617                Some((crate::gpu::GraphAct::SwiGluOaiM3, 7.0))
618            }
619            _ => self.graph_act().map(|act| (act, 0.0)),
620        }
621    }
622}
623
624/// Dense gated triple — the FFN of a dense layer or of one expert.
625pub struct DenseFfn {
626    pub gate_proj: QTensor,
627    pub up_proj: QTensor,
628    pub down_proj: QTensor,
629    /// Gate activation (SiLU default; Gemma: tanh-GELU).
630    pub act: Act,
631    /// `down_proj` stored transposed (`[inter, hidden]`), when the file
632    /// carries it. Only the per-token sparse path reads it: a neuron's
633    /// down weights are a contiguous ROW there, so the token's chosen
634    /// neurons are the only bytes touched. `None` = the ordinary layout,
635    /// and the sparse path stays off.
636    pub down_t: Option<QTensor>,
637    /// Task tubes (spec: defragged task-conditional width). The three
638    /// matrices above are the CORE — the neurons every task computes;
639    /// each tube is an independently quantized slice of the SAME layer
640    /// holding the neurons only some tasks need. A tube is a normal
641    /// tensor triple, so every kernel runs it unchanged, and the bytes
642    /// of an inactive tube are never read. Empty = ordinary dense FFN.
643    pub segs: Vec<FfnSeg>,
644}
645
646/// One task tube: a contiguous slice of a layer's FFN neurons, stored
647/// as its own `[w, hidden]` / `[hidden, w]` triple. `start` is the
648/// neuron's index in the layer's FULL space (core first, then tubes in
649/// order) — the bit a task mask sets to switch this tube on.
650pub struct FfnSeg {
651    pub gate: QTensor,
652    pub up: QTensor,
653    pub down: QTensor,
654    pub start: usize,
655    pub width: usize,
656}
657
658/// FFN operator of a layer, decided by tensor presence at load time
659/// (router `mlp.gate.weight` in the directory = MoE layer).
660pub enum FfnKind {
661    Dense(DenseFfn),
662    /// Mixture-of-Experts (Qwen2-MoE / Qwen3-MoE): softmax over ALL
663    /// expert logits → top-k, optional renorm; experts stay quantized
664    /// in mmap — only the selected ones are touched per token.
665    Moe(MoeFfn),
666    /// Gemma-4 MoE: a dense MLP branch AND a routed-expert branch in
667    /// the SAME layer, each with its own norm sandwich. The dense
668    /// branch reads the pre-FFN-normed input; the expert branch (and
669    /// the router) read the RAW residual through `pre_norm_2`:
670    ///   d = post_norm_1(dense(x̂));  m = post_norm_2(Σwₑ·FFNₑ(pre_norm_2(h)))
671    ///   ffn_out = d + m   (the caller's ffn_out_norm + residual follow)
672    DenseMoe(Box<DenseMoeFfn>),
673}
674
675/// Gemma-4 dual-branch FFN (see `FfnKind::DenseMoe`).
676pub struct DenseMoeFfn {
677    pub dense: DenseFfn,
678    pub moe: MoeFfn,
679    /// post_feedforward_layernorm_1 — dense-branch output norm.
680    pub post_norm_1: Vec<f32>,
681    /// pre_feedforward_layernorm_2 — expert-branch input norm (applied
682    /// to the RAW residual, not the pre-FFN-normed activation).
683    pub pre_norm_2: Vec<f32>,
684    /// post_feedforward_layernorm_2 — expert-branch output norm.
685    pub post_norm_2: Vec<f32>,
686}
687
688pub struct MoeFfn {
689    /// Router `mlp.gate.weight` [num_experts, hidden].
690    pub router: QTensor,
691    pub experts: Vec<DenseFfn>,
692    pub top_k: usize,
693    pub norm_topk_prob: bool,
694    /// Router scores per-expert with a sigmoid (LFM2-MoE / DeepSeek-V3
695    /// `noaux_tc`) instead of a softmax over all experts (Qwen).
696    pub router_sigmoid: bool,
697    /// Addend in the selected-score denominator of a sigmoid router.
698    /// Most supported checkpoints use the historical `1e-6` floor; Flint's
699    /// reference routing uses `1e-20`; MiniMax M3.1 preserves the same FP32
700    /// `sum + 1e-20` law. This is per-MoE rather than a global family switch
701    /// because the same sigmoid routing law has several contracts.
702    pub sigmoid_denom_eps: f32,
703    /// Per-expert selection bias `mlp.expert_bias` [num_experts]
704    /// (LFM2-MoE): added to the sigmoid scores for the top-k CHOICE only;
705    /// the gathered weights use the unbiased scores. None = no bias.
706    pub expert_bias: Option<Vec<f32>>,
707    /// Top-k weights are multiplied by this after the optional renorm
708    /// (LFM2-MoE `routed_scaling_factor`; 1.0 = off).
709    pub routed_scaling: f32,
710    /// Adaptive routing (CMF_MOE_TAU, opt-in): keep the smallest
711    /// prefix of the top-k whose renormalized mass reaches τ —
712    /// confident tokens touch 1–2 experts, flat ones keep all k.
713    /// MoE decode is memory-bound, so skipped experts are skipped
714    /// weight traffic. None = classic fixed top-k (bit-identical).
715    pub route_tau: Option<f32>,
716    /// Always-on shared expert. Qwen2-MoE carries an additional sigmoid
717    /// gate; Laguna adds the shared expert unconditionally (`None`).
718    pub shared: Option<(DenseFfn, Option<QTensor>)>,
719    /// Expert-selection counters (truncated Fisher B-field of claim 12:
720    /// routing frequency during calibration). Filled by every forward,
721    /// read by the CLI via CMF_MOE_STATS. RefCell: decode is single-threaded.
722    pub stats: std::cell::RefCell<Vec<u64>>,
723    /// Per-CHANNEL sum of squares of this FFN's input, accumulated over a
724    /// calibration run (`CMF_RMS_TRACE`). These are the RMS activation
725    /// traces AWNP needs: raw weight magnitude says every channel matters
726    /// equally, and the question AWNP asks is whether the ACTIVATIONS
727    /// disagree. Off unless the env var is set — an f64 add per channel
728    /// per token is cheap, but not free.
729    pub act_sq: std::cell::RefCell<Vec<f64>>,
730    /// Raw FFN-input rows captured for the layers named by `CMF_ACT_DUMP`
731    /// (`"9,19"`). AWNP is nullspace PROJECTION: after dropping channels the
732    /// survivors are refitted to absorb what was removed, and how much they
733    /// can absorb depends on the activation COVARIANCE, not on per-channel
734    /// RMS. Per-channel numbers can only bound the cost from above.
735    pub act_rows: std::cell::RefCell<Vec<f32>>,
736    /// Task mask over routed experts (DTG-MA over MoE, claim-12 B-field
737    /// applied): `false` experts are excluded from selection, the
738    /// softmax renormalizes over the allowed set. Built by the loader
739    /// from CMF_MOE_MASK=<stats.json> + CMF_MOE_MASK_COVER. None = all.
740    pub mask: Option<Vec<bool>>,
741    /// Gemma-4: per-expert weight scale applied AFTER the top-k renorm
742    /// (`router.per_expert_scale`). None = 1.0 everywhere.
743    pub per_expert_scale: Option<Vec<f32>>,
744    /// Gemma-4: the router reads a SCALE-LESS rms-norm of its input
745    /// (the constant gain router.scale·√hidden is folded into the
746    /// router weights at convert time).
747    pub router_input_norm: bool,
748    /// Cortiq Embryo: resonance routing (P1) — the "logits" are
749    /// bias_e − ‖(x−μ_e) − U_eᵀU_e(x−μ_e)‖², argmax = the expert whose
750    /// descriptor reconstructs the input best. `router` is a placeholder.
751    pub resonance: Option<Resonance>,
752    /// Growth records (`kind = "expert_append"`, spec §9.5.1) mounted
753    /// behind the trunk experts, one entry per grown expert IN THE ORDER
754    /// they sit in `experts` (the tail `experts[experts.len() - grown.len()..]`).
755    /// The trunk keeps `experts.len() - grown.len()` experts. Empty on a
756    /// gated MoE, on a file without records and under `CMF_GROWTH=off`.
757    pub grown: Vec<GrownExpert>,
758}
759
760/// One grown expert of an `expert_append` record as the loader mounted it.
761#[derive(Debug, Clone, PartialEq, Eq)]
762pub struct GrownExpert {
763    /// The record's skill id.
764    pub record: String,
765    /// Position of the record in `header.skills`.
766    pub record_index: usize,
767    pub layer: usize,
768    /// The index the tensor name declares (`experts.{e}` — the chain rule
769    /// of the format); the executed position may be smaller when an
770    /// earlier record of the layer is not mounted.
771    pub expert: usize,
772}
773
774/// Per-expert resonance descriptors of one MoE layer (`mlp.desc.*`).
775pub struct Resonance {
776    /// [E, hidden]
777    pub mu: Vec<f32>,
778    /// [E, k, hidden] orthonormal directions (k may be 0)
779    pub u: Vec<f32>,
780    pub k: usize,
781    /// [E] selection bias (loss-free balancing, trained online)
782    pub bias: Vec<f32>,
783    /// [E] reconstruction-error shell: an expert whose error
784    /// `‖(x−μ)⊥U‖² = d² − proj` exceeds its shell scores `−∞` (it never
785    /// wins). `+inf` = no shell — every trunk expert; a grown expert
786    /// (`expert_append`) carries the finite `desc.shell` its record stores.
787    /// Empty = no shell anywhere (legacy constructors).
788    pub shell: Vec<f32>,
789}
790
791/// `CMF_GROWTH_SHELL` state: 0 = not yet read from the environment, 1 = on,
792/// 2 = off. Process-wide, like the environment it mirrors.
793static GROWTH_SHELL: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
794
795/// Is the growth shell applied (`Resonance::scores` −∞ rule, the resident
796/// graph's packed shell)? `CMF_GROWTH_SHELL=off` disables it for
797/// measurement; [`set_growth_shell`] overrides the environment in-process
798/// (`growth-eval --shell`). Default: on.
799pub fn growth_shell_enabled() -> bool {
800    use std::sync::atomic::Ordering;
801    match GROWTH_SHELL.load(Ordering::Relaxed) {
802        1 => true,
803        2 => false,
804        _ => {
805            let off = std::env::var("CMF_GROWTH_SHELL")
806                .map(|v| v.eq_ignore_ascii_case("off") || v == "0")
807                .unwrap_or(false);
808            GROWTH_SHELL.store(if off { 2 } else { 1 }, Ordering::Relaxed);
809            !off
810        }
811    }
812}
813
814/// Switch the growth shell on/off for this process (`None` = re-read
815/// `CMF_GROWTH_SHELL` on the next query). A pipeline packed into the
816/// resident graph BEFORE the switch keeps the shell it was packed with —
817/// build a new pipeline after switching.
818pub fn set_growth_shell(on: Option<bool>) {
819    GROWTH_SHELL.store(
820        match on {
821            Some(true) => 1,
822            Some(false) => 2,
823            None => 0,
824        },
825        std::sync::atomic::Ordering::Relaxed,
826    );
827}
828
829impl Resonance {
830    /// Does any expert carry a finite shell (a mounted growth record)?
831    pub fn has_shell(&self) -> bool {
832        self.shell.iter().any(|s| s.is_finite())
833    }
834
835    /// The shell the runtime applies right now: the stored one, or all
836    /// `+inf` when the shell is switched off (`CMF_GROWTH_SHELL=off`).
837    pub fn effective_shell(&self, ne: usize) -> Vec<f32> {
838        let mut out = vec![f32::INFINITY; ne];
839        if growth_shell_enabled() {
840            for (o, s) in out.iter_mut().zip(&self.shell) {
841                *o = *s;
842            }
843        }
844        out
845    }
846
847    /// Routing scores for one input row (higher = better). A grown
848    /// expert whose reconstruction error lies outside its shell gets
849    /// `−∞` (unless the shell is switched off); trunk rows are the exact
850    /// bit pattern they were before growth.
851    pub fn scores(&self, x: &[f32], out: &mut [f32]) {
852        let h = x.len();
853        let ne = out.len();
854        let shell_on = growth_shell_enabled() && !self.shell.is_empty();
855        for e in 0..ne {
856            let mu = &self.mu[e * h..(e + 1) * h];
857            let mut d2 = 0.0f32;
858            for j in 0..h {
859                let d = x[j] - mu[j];
860                d2 += d * d;
861            }
862            let mut proj = 0.0f32;
863            for i in 0..self.k {
864                let u = &self.u[(e * self.k + i) * h..(e * self.k + i + 1) * h];
865                let mut p = 0.0f32;
866                for j in 0..h {
867                    p += (x[j] - mu[j]) * u[j];
868                }
869                proj += p * p;
870            }
871            let err = d2 - proj;
872            out[e] = self.bias.get(e).copied().unwrap_or(0.0) - err;
873            if shell_on && err > self.shell.get(e).copied().unwrap_or(f32::INFINITY) {
874                out[e] = f32::NEG_INFINITY;
875            }
876        }
877    }
878}
879
880/// Attention operator of a layer. Extension point: new operators are
881/// new variants here + a forward in their own module.
882pub enum AttnKind {
883    /// GQA softmax attention (+ optional Qwen3.5 qk-norm / output gate).
884    Full {
885        wq: QTensor,
886        wk: QTensor,
887        wv: QTensor,
888        wo: QTensor,
889        q_norm: Option<Vec<f32>>,
890        k_norm: Option<Vec<f32>>,
891        output_gate: bool,
892        /// Laguna: a separate softplus projection applied to the attention
893        /// output before O. The bool means one scalar per head (broadcast
894        /// across head_dim); false means one scalar per element.
895        softplus_gate: Option<(QTensor, bool)>,
896        /// Qwen2-family projection biases (q, k, v).
897        bias: Option<(Vec<f32>, Vec<f32>, Vec<f32>)>,
898    },
899    /// Canonical linear core (VMF phase attention).
900    Linear(VmfPhaseWeights),
901    /// Faithful vendor linear operator (Qwen3.5 GatedDeltaNet).
902    LinearGdn(GdnWeights),
903    /// LFM2 gated short-convolution mixer (no KV cache; conv ring state
904    /// lives in the layer's `linear_state`).
905    ShortConv(ShortConvWeights),
906    /// DeepSeek-V2 Multi-head Latent Attention. v1 executes it as
907    /// expand-to-MHA: the latent is projected per token, K/V expand to
908    /// every head and live in the ordinary cache (K head layout
909    /// [rope | nope] so the standard partial rotary covers the shared
910    /// rope key; V rows are zero-padded to the K head_dim and the pad
911    /// is sliced off before O). Latent-resident cache is a later
912    /// optimization, not a semantic change.
913    Mla(Box<MlaWeights>),
914    /// Kimi Delta Attention (Kimi Linear / Kimi-K3): per-channel decayed
915    /// delta rule, separate q/k/v short convs, sigmoid-gated output norm.
916    /// State lives in the layer's `linear_state` (no KV cache).
917    Kda(Box<crate::linear_core::KdaWeights>),
918    /// Natively bounded softmax anchor `swa_sink_v1` (Embryo-O1): ring of
919    /// the last W raw keys with relative RoPE + trained NoPE sinks, one
920    /// softmax. State is the fixed-size ring in `LayerKvCache::bounded`;
921    /// nothing is stored per position (see `crate::bounded`).
922    Bounded(Box<crate::bounded::BoundedWeights>),
923}
924
925/// DeepSeek-V2 MLA projections (see `AttnKind::Mla`).
926pub struct MlaWeights {
927    /// `[nh·(rope+nope), hidden]` (or `[…, q_lora]` when compressed) —
928    /// the converter permutes each head rope-first so rotary_dim =
929    /// qk_rope works unchanged.
930    pub q_proj: QTensor,
931    /// Compressed q (K3/V3 class): x → q_a `[q_lora, hidden]` →
932    /// rms(q_a_norm) → q_proj (= q_b). None = direct q (V2-Lite).
933    pub q_a: Option<QTensor>,
934    pub q_a_norm: Option<Vec<f32>>,
935    /// `kv_a_proj_with_mqa` `[lora + rope, hidden]` (latent first).
936    pub kv_a: QTensor,
937    /// RMS-norm weights over the latent (`kv_a_layernorm`, [lora]).
938    pub kv_a_norm: Vec<f32>,
939    /// `[nh·(nope+v), lora]` — per head [k_nope | v].
940    pub kv_b: QTensor,
941    /// `[hidden, nh·v]`.
942    pub o_proj: QTensor,
943    pub nh: usize,
944    pub qk_rope: usize,
945    pub qk_nope: usize,
946    pub v_dim: usize,
947    pub lora: usize,
948    /// Softmax scale (1/√(rope+nope), YaRN-mscale-corrected at load).
949    pub scale: f32,
950    /// Kimi Linear NoPE: skip the rotary entirely (layout unchanged).
951    pub nope: bool,
952}
953
954/// Multi-token-prediction head (DeepSeek/Qwen style, spec §2.1):
955/// `x = eh_proj·[enorm(embed(next)); hnorm(hidden)]` → one transformer
956/// block over its own KV → shared lm_head. Drafts the token after next;
957/// the main model verifies, so output is exact — MTP only buys speed.
958pub struct MtpModule {
959    pub enorm: Vec<f32>,
960    pub hnorm: Vec<f32>,
961    /// [hidden, 2·hidden]
962    pub eh_proj: QTensor,
963    pub layer: LayerWeights,
964    pub final_norm: Vec<f32>,
965    pub kv: crate::kv_cache::LayerKvCache,
966}
967
968/// A Metal verify graph after its sync: what the commit needs — the
969/// graph (per-layer replay scratch), the GDN layers in encode order (their
970/// CPU states receive the replay), and the attention layers with the CPU
971/// row count they were encoded against (the accepted rows are pulled from
972/// the mirror from there).
973/// One item of the Metal rows-graph plan.
974#[cfg(target_os = "macos")]
975enum MetalRowsItem<'a> {
976    Gdn {
977        run: Vec<crate::gpu_metal::GdnGpuLayer<'a>>,
978        first: usize,
979    },
980    Attn {
981        l: crate::gpu_metal::AttnGpuLayer<'a>,
982        li: usize,
983        q_norm: Option<&'a [f32]>,
984        k_norm: Option<&'a [f32]>,
985        output_gate: bool,
986    },
987}
988
989#[cfg(target_os = "macos")]
990struct MetalVerifyPending {
991    graph: crate::gpu_metal::VerifyGraph,
992    gdn_layers: Vec<usize>,
993    attn_layers: Vec<(usize, usize)>,
994}
995
996/// A round's batched MTP warm-up, submitted but not yet waited
997/// (`mtp_warm_batch_submit` → `mtp_warm_batch_finish`): the trunk commit's
998/// GDN replay is queued between the two.
999#[cfg(target_os = "macos")]
1000struct MetalWarmPending {
1001    graph: crate::gpu_metal::VerifyGraph,
1002    cpu_stored: usize,
1003    b: usize,
1004}
1005
1006#[cfg(target_os = "macos")]
1007enum MetalRowsRun {
1008    /// Capability/preflight refusal before a command buffer was committed.
1009    Declined,
1010    /// A graph was admitted and then failed; callers must clear the sequence
1011    /// rather than replaying it through CPU/serial state.
1012    Failed,
1013    Completed(MetalVerifyPending),
1014}
1015
1016#[cfg(target_os = "macos")]
1017enum MetalPrefillOutcome {
1018    Declined,
1019    Failed,
1020    Completed(Vec<f32>),
1021}
1022
1023#[cfg(target_os = "macos")]
1024enum MetalBatchNllOutcome {
1025    Declined,
1026    Failed(String),
1027    Completed(f64, usize),
1028}
1029
1030/// The speculation trial's phases (see the decode loop): four timed
1031/// speculative rounds, eight timed plain tokens, then the faster arm
1032/// until a re-check.
1033#[derive(Clone, Copy)]
1034enum SpecTrial {
1035    Spec {
1036        t0: std::time::Instant,
1037        gen0: usize,
1038        rounds: usize,
1039    },
1040    Plain {
1041        t0: std::time::Instant,
1042        gen0: usize,
1043    },
1044    Decided {
1045        spec: bool,
1046        recheck_at: usize,
1047    },
1048}
1049
1050/// `CMF_GRAPH_SPEC_TIME`: 0 = off, 1 = one line per speculative round
1051/// plus the host stamps of any OUTLIER round (wall > 1.4× the running
1052/// median), 2 = the host stamps of every round.
1053pub(crate) fn spec_time_level() -> u8 {
1054    static L: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
1055    *L.get_or_init(|| match std::env::var("CMF_GRAPH_SPEC_TIME") {
1056        Ok(v) => v.trim().parse::<u8>().map(|n| n.max(1)).unwrap_or(1),
1057        Err(_) => 0,
1058    })
1059}
1060
1061/// The round's host stamps: `spec_stamp(name)` records the time since
1062/// the previous stamp (the section that just ended) — from anywhere on
1063/// the round's call chain (the Metal verify, the draft step, the commit),
1064/// no plumbing. Off (a single atomic load) unless `CMF_GRAPH_SPEC_TIME`
1065/// is set; one decode thread at a time is assumed (diagnostics).
1066struct SpecStampLog {
1067    t_last: std::time::Instant,
1068    items: Vec<(&'static str, f32)>,
1069}
1070
1071static SPEC_STAMPS: std::sync::Mutex<Option<SpecStampLog>> = std::sync::Mutex::new(None);
1072
1073pub(crate) fn spec_stamp(name: &'static str) {
1074    if spec_time_level() == 0 {
1075        return;
1076    }
1077    if let Ok(mut g) = SPEC_STAMPS.lock() {
1078        if let Some(log) = g.as_mut() {
1079            let now = std::time::Instant::now();
1080            log.items
1081                .push((name, (now - log.t_last).as_secs_f32() * 1e3));
1082            log.t_last = now;
1083        }
1084    }
1085}
1086
1087fn spec_stamps_begin() {
1088    if spec_time_level() == 0 {
1089        return;
1090    }
1091    if let Ok(mut g) = SPEC_STAMPS.lock() {
1092        *g = Some(SpecStampLog {
1093            t_last: std::time::Instant::now(),
1094            items: Vec::with_capacity(64),
1095        });
1096    }
1097}
1098
1099fn spec_stamps_take() -> Vec<(&'static str, f32)> {
1100    SPEC_STAMPS
1101        .lock()
1102        .ok()
1103        .and_then(|mut g| g.take())
1104        .map(|l| l.items)
1105        .unwrap_or_default()
1106}
1107
1108/// One line: every stamp name in first-seen order with its total over the
1109/// round and, when it fired more than once (the draft steps), the count.
1110fn spec_stamps_format(items: &[(&'static str, f32)]) -> String {
1111    let mut agg: Vec<(&'static str, f32, u32)> = Vec::with_capacity(items.len());
1112    for &(n, ms) in items {
1113        match agg.iter_mut().find(|e| e.0 == n) {
1114            Some(e) => {
1115                e.1 += ms;
1116                e.2 += 1;
1117            }
1118            None => agg.push((n, ms, 1)),
1119        }
1120    }
1121    let mut s = String::with_capacity(agg.len() * 16);
1122    for (n, ms, k) in agg {
1123        if k > 1 {
1124            s.push_str(&format!("{n} {ms:.1}/{k} "));
1125        } else {
1126            s.push_str(&format!("{n} {ms:.1} "));
1127        }
1128    }
1129    s
1130}
1131
1132/// The speculation monitor: exponential averages of a round's wall time
1133/// and of the tokens it produced, and the plain token's wall time — the
1134/// three numbers the keep/stop rule needs. A round pays when
1135/// `tokens_per_round · plain_ms > round_ms · 1.03`. The one-shot trial
1136/// (four rounds against eight tokens) mis-called prose: the first rounds
1137/// after a prompt are formulaic and accept well, the body does not (an
1138/// essay measured 39 against a plain 44.8 with the trial saying
1139/// "speculate"), so the rule now runs on EVERY round and stops after four
1140/// consecutive losing rounds; a stopped speculation is retried 128 tokens
1141/// later.
1142///
1143/// Native Metal (`metal: true`) does not pay the eight plain tokens up
1144/// front: on the 27B a plain token is ~150 ms, so the trial alone cost
1145/// ~1.2 s of every answer. There the plain phase is (a) skipped while the
1146/// rounds land at least `SPEC_PROXY_TOKENS` tokens each — a k=7 round on
1147/// Metal costs ~1.9 plain tokens (286 against 148 ms measured on the M4),
1148/// so 3.5 tokens/round cannot lose on any Metal round/plain ratio seen —
1149/// and (b) otherwise bounded to the fewest tokens that time it: two, or
1150/// as many as fit in `SPEC_PLAIN_MIN_MS` (a 150-ms token measures itself;
1151/// a 10-ms one needs the eight). The keep/stop rule itself is unchanged:
1152/// the moment a plain rate exists, it decides.
1153#[derive(Default, Clone, Copy)]
1154struct SpecMon {
1155    round_ms: f64,
1156    tokens: f64,
1157    plain_ms: f64,
1158    n: u32,
1159    fails: u32,
1160    metal: bool,
1161}
1162
1163/// Tokens per round at or above which a Metal round pays without a plain
1164/// measurement (see `SpecMon`).
1165const SPEC_PROXY_TOKENS: f64 = 3.5;
1166/// The Metal plain phase: at least two tokens, and more until this much
1167/// wall time has been timed (up to the eight the other backends time).
1168const SPEC_PLAIN_MIN_MS: f64 = 200.0;
1169
1170impl SpecMon {
1171    fn round(&mut self, dt_ms: f64, produced: usize) {
1172        self.n += 1;
1173        if self.n == 1 {
1174            return; // round 1 pays the batch scratch and the draft mirror
1175        }
1176        let a = if self.n == 2 { 1.0 } else { 0.3 };
1177        self.round_ms += a * (dt_ms - self.round_ms);
1178        self.tokens += a * (produced as f64 - self.tokens);
1179    }
1180    fn pays(&self) -> bool {
1181        if self.plain_ms > 0.0 {
1182            self.tokens * self.plain_ms > self.round_ms * 1.03
1183        } else {
1184            self.metal && self.tokens >= SPEC_PROXY_TOKENS
1185        }
1186    }
1187    /// Has the plain phase timed enough tokens to decide?
1188    fn plain_done(&self, t0: std::time::Instant, gen0: usize, generated: usize) -> bool {
1189        let n = generated.saturating_sub(gen0);
1190        if n >= 8 {
1191            return true;
1192        }
1193        self.metal && n >= 2 && t0.elapsed().as_secs_f64() * 1e3 >= SPEC_PLAIN_MIN_MS
1194    }
1195}
1196
1197/// Ids of the consumed prefix the bounded reuse key remembers literally
1198/// (the rest is covered by the rolling hash).
1199pub const KV_PREFIX_TAIL: usize = 128;
1200
1201/// Bounded prefix-reuse key: how many ids the cache holds, a rolling
1202/// hash of ALL of them and the last [`KV_PREFIX_TAIL`] ids literally.
1203/// Answers "does this prompt strictly extend what is cached" exactly
1204/// (hash over the whole consumed prefix + literal tail) without keeping
1205/// the dialogue — the record is a fixed size whatever the session length.
1206#[derive(Debug, Clone, Default)]
1207pub struct KvPrefix {
1208    len: usize,
1209    hash: u64,
1210    tail: Vec<u32>,
1211    /// Owner of the state this key describes: the resident device graph
1212    /// (true) or the host. A turn continues the prefix only on its owner
1213    /// (R4: a host continuation of a device sequence reads an empty host
1214    /// state; a device continuation of a host sequence has no image).
1215    device: bool,
1216}
1217
1218impl KvPrefix {
1219    #[inline]
1220    fn fold(mut h: u64, ids: &[u32]) -> u64 {
1221        for &id in ids {
1222            h ^= id as u64;
1223            h = h.wrapping_mul(0x100000001b3);
1224            h ^= h >> 29;
1225        }
1226        h
1227    }
1228
1229    pub fn clear(&mut self) {
1230        self.len = 0;
1231        self.hash = 0xcbf29ce484222325;
1232        self.tail.clear();
1233        self.device = false;
1234    }
1235
1236    /// Was the prefix built on the resident device graph?
1237    pub fn on_device(&self) -> bool {
1238        self.device
1239    }
1240
1241    /// Tag the owner of the recorded prefix.
1242    pub fn set_on_device(&mut self, device: bool) {
1243        self.device = device;
1244    }
1245
1246    /// Ids the cache holds (the forwarded prefix).
1247    pub fn len(&self) -> usize {
1248        self.len
1249    }
1250
1251    pub fn is_empty(&self) -> bool {
1252        self.len == 0
1253    }
1254
1255    /// Literal tail currently kept (≤ `KV_PREFIX_TAIL`).
1256    pub fn tail_len(&self) -> usize {
1257        self.tail.len()
1258    }
1259
1260    /// Replace the key with `ids` (a fresh sequence).
1261    pub fn set(&mut self, ids: &[u32]) {
1262        self.clear();
1263        self.extend(ids);
1264    }
1265
1266    /// Append `more` to the consumed prefix (an extension-only turn).
1267    pub fn extend(&mut self, more: &[u32]) {
1268        if self.len == 0 && self.hash == 0 {
1269            self.hash = 0xcbf29ce484222325;
1270        }
1271        self.hash = Self::fold(self.hash, more);
1272        self.len += more.len();
1273        if more.len() >= KV_PREFIX_TAIL {
1274            self.tail.clear();
1275            self.tail
1276                .extend_from_slice(&more[more.len() - KV_PREFIX_TAIL..]);
1277        } else {
1278            let drop = (self.tail.len() + more.len()).saturating_sub(KV_PREFIX_TAIL);
1279            self.tail.drain(..drop);
1280            self.tail.extend_from_slice(more);
1281        }
1282    }
1283
1284    /// Cached positions when `ids` strictly extends the consumed prefix,
1285    /// 0 otherwise. The tail is compared literally first (cheap), then
1286    /// the hash over the whole prefix must agree.
1287    pub fn extension(&self, ids: &[u32]) -> usize {
1288        if self.len == 0 || ids.len() <= self.len {
1289            return 0;
1290        }
1291        let t = self.tail.len();
1292        if ids[self.len - t..self.len] != self.tail[..] {
1293            return 0;
1294        }
1295        if Self::fold(0xcbf29ce484222325, &ids[..self.len]) != self.hash {
1296            return 0;
1297        }
1298        self.len
1299    }
1300}
1301
1302/// Result of a generation call.
1303pub struct GenerateResult {
1304    pub text: String,
1305    pub token_ids: Vec<u32>,
1306    pub prompt_tokens: usize,
1307    pub tokens_generated: usize,
1308    pub finish_reason: String,
1309    /// Speculative-decode stats (0/0 when MTP is absent or inactive).
1310    pub mtp_drafted: usize,
1311    pub mtp_accepted: usize,
1312    /// Per-generated-token confidence = softmax probability of the token
1313    /// that was actually emitted (softmax probability on the chosen state). High =
1314    /// the model was sure; low = it was guessing. Same length as the
1315    /// generated slice of `token_ids`.
1316    pub token_confidence: Vec<f32>,
1317    /// Structured per-token telemetry (B4 channel). Empty unless
1318    /// `set_trace(true)`; otherwise same length as the generated slice.
1319    pub traces: Vec<TokenTrace>,
1320}
1321
1322/// One row of the structured telemetry trace (B4): the model's internal
1323/// routing state at the moment a token was emitted. Every field is a
1324/// quantity the runtime already computes — nothing is inferred or
1325/// estimated (anti-principle: only measured bytes).
1326#[derive(Clone, Debug)]
1327pub struct TokenTrace {
1328    /// 0-based index within the generated slice.
1329    pub t: usize,
1330    /// The emitted token id.
1331    pub token_id: u32,
1332    /// Softmax probability on the emitted token — how sure the model was.
1333    pub confidence: f32,
1334    /// Skill in force while this token was generated (None = backbone).
1335    pub active_skill: Option<String>,
1336    /// Recon error E = ‖r−BBᵀr‖²/‖φ‖² at the last routing eval — coherence
1337    /// with the active skill's subspace (low = coherent). None = no router
1338    /// or not yet evaluated.
1339    pub recon: Option<f32>,
1340    /// The router changed the active skill right after this token (a
1341    /// domain boundary crossed under the hysteresis barrier).
1342    pub switched: bool,
1343}
1344
1345/// Calibrated softmax probability of `id` under `logits` (the confidence on
1346/// the emitted token) — the confidence signal, cheap from logits already
1347/// computed for sampling. `temp` is the calibration temperature (B1):
1348/// softmax(logits / temp); 1.0 = raw.
1349#[cfg_attr(not(test), allow(dead_code))]
1350fn top1_prob_t(logits: &[f32], id: u32, temp: f32) -> f32 {
1351    let t = if temp > 1e-3 { temp } else { 1.0 };
1352    let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
1353    let sum: f32 = logits.iter().map(|&v| ((v - max) / t).exp()).sum();
1354    if sum > 0.0 {
1355        (((logits[id as usize] - max) / t).exp()) / sum
1356    } else {
1357        0.0
1358    }
1359}
1360
1361/// prefill-GEMM enabled? (CMF_PREFILL=seq — emergency fallback to the
1362/// sequential path.)
1363fn prefill_batched() -> bool {
1364    std::env::var("CMF_PREFILL")
1365        .map(|v| v != "seq")
1366        .unwrap_or(true)
1367}
1368
1369/// Decide the graph NLL route without conflating graph quality with the
1370/// optional native-Metal fused head. A hidden-state graph remains a valid
1371/// quality route on Vulkan/Wgpu; only native Metal requires graph logits.
1372#[inline]
1373fn nll_graph_policy(unmasked: bool, prefer_graph: bool, native_metal: bool) -> (bool, bool) {
1374    let graph_quality = unmasked && prefer_graph;
1375    let fused_head_quality = graph_quality && native_metal;
1376    (graph_quality, fused_head_quality)
1377}
1378
1379/// Input to the layer-major batched span walk: token ids (embeds itself,
1380/// full-stack and coordinator prefill) or ready boundary hiddens (the
1381/// network worker's side of a split).
1382#[derive(Clone, Copy)]
1383enum PrefillIn<'a> {
1384    Ids(&'a [u32]),
1385    Hidden(&'a [f32]),
1386}
1387
1388/// The batched prefill walks `weights.layers`. Architectures that load
1389/// their own stack (gemma-3n's AltUp replicas, DeepSeek-V4's hyper-
1390/// connections) leave that empty and must go position by position — asking
1391/// otherwise indexes an empty vector, which is a panic rather than a
1392/// fallback. Every call site goes through here so the next such
1393/// architecture is one line, not four.
1394impl Pipeline {
1395    fn can_prefill_batched(&self) -> bool {
1396        #[cfg(test)]
1397        let force_serial = self.nll_test_force_serial;
1398        #[cfg(not(test))]
1399        let force_serial = false;
1400        prefill_batched() && !force_serial && !self.weights.layers.is_empty()
1401    }
1402
1403    /// The backend's automatic capacity split for a mapped transformer.
1404    /// Kept as a method so prefill and decode use the exact same boundary.
1405    fn automatic_gpu_prefix(&self) -> Option<usize> {
1406        let (model, _, _, _) = self.weights.embed_tokens.graph_weight()?;
1407        crate::gpu::automatic_layer_prefix(&model, self.num_layers, self.physical_layers)
1408    }
1409
1410    /// Positions per batched pass of the layer-stack prefill for THIS
1411    /// model on THIS backend (see [`prefill_chunk_rule`]). Pub: the network
1412    /// split must chunk exactly like the local path to reproduce it.
1413    pub fn prefill_chunk(&self) -> usize {
1414        let env = env_prefill_chunk();
1415        if env.is_some() || ChunkHost::here() != ChunkHost::Other {
1416            return prefill_chunk_rule(env, ChunkHost::here(), false);
1417        }
1418        prefill_chunk_rule(
1419            None,
1420            ChunkHost::Other,
1421            self.chunk_stack_facts().dense_on_discrete(),
1422        )
1423    }
1424
1425    /// Architectures that run a dedicated per-token stack (gemma-3n's
1426    /// AltUp flow, the gemma-4 E-series PLE/shared-KV body): batched
1427    /// prefill and the graphs stay off for them.
1428    fn per_token_stack(&self) -> bool {
1429        self.g3n.is_some() || self.g4e.is_some()
1430    }
1431
1432    fn chunk_stack_facts(&self) -> ChunkStackFacts {
1433        let plain_dense = !self.weights.layers.is_empty()
1434            && !self.per_token_stack()
1435            && self.dsv4.is_none()
1436            && self.dsv41.is_none()
1437            && self.qwen4_exp.is_none()
1438            && self.weights.layers.iter().all(|lw| {
1439                matches!(lw.attn, AttnKind::Full { .. }) && matches!(lw.ffn, FfnKind::Dense(_))
1440            });
1441        let gpu_on = crate::gpu::enabled();
1442        ChunkStackFacts {
1443            plain_dense,
1444            discrete: gpu_on && crate::gpu::discrete(),
1445            gpu_on,
1446            // Only asked when the rest already qualifies: it opens the
1447            // backend's capacity plan.
1448            capacity_split: std::env::var_os("CMF_GPU_LAYERS").is_some()
1449                || (plain_dense && gpu_on && self.automatic_gpu_prefix().is_some()),
1450            multi_gpu: self.gpu_plan.is_some(),
1451            o1: self.o1_active(),
1452        }
1453    }
1454}
1455
1456/// Prefill chunk (positions per batched pass), model-agnostic form. On
1457/// macOS the AMX GEMM path wants tall panels — M=48 starves the matrix
1458/// units (ggml uses ubatch 512); elsewhere the historical 48 stays.
1459/// CMF_PREFILL_CHUNK overrides. The architectures with their own stacks
1460/// (DeepSeek-V4/V4.1) chunk with this; the layer-stack prefill asks
1461/// [`Pipeline::prefill_chunk`], which also knows the model and the card.
1462/// A different chunk is a different (equally valid) generation: panel
1463/// width reorders float accumulation.
1464pub fn prefill_chunk() -> usize {
1465    prefill_chunk_rule(env_prefill_chunk(), ChunkHost::here(), false)
1466}
1467
1468fn env_prefill_chunk() -> Option<usize> {
1469    std::env::var("CMF_PREFILL_CHUNK")
1470        .ok()
1471        .and_then(|v| v.parse::<usize>().ok())
1472}
1473
1474/// The host classes the chunk width distinguishes.
1475#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1476enum ChunkHost {
1477    Macos,
1478    /// Linux/Android aarch64 (phones, SBCs).
1479    Aarch64,
1480    /// Everything else: x86-64 Linux/Windows, CPU or Vulkan/DX12.
1481    Other,
1482}
1483
1484impl ChunkHost {
1485    fn here() -> Self {
1486        if cfg!(target_os = "macos") {
1487            ChunkHost::Macos
1488        } else if cfg!(target_arch = "aarch64") {
1489            ChunkHost::Aarch64
1490        } else {
1491            ChunkHost::Other
1492        }
1493    }
1494}
1495
1496/// Chunk for a plain dense stack whose every layer lives on a discrete
1497/// card. On x86 the layer-stack prefill is host-driven: each GEMM and the
1498/// chunk attention (which re-uploads the whole KV prefix per layer) is a
1499/// separate submit + readback, so 48 positions a pass left the card idle
1500/// between them. Measured in-process on an RTX 3090 (Vulkan), 2048-token
1501/// prompt — see CHANGELOG 0.7.6 for the table.
1502const DISCRETE_DENSE_PREFILL_CHUNK: usize = 512;
1503
1504/// The chunk-width rule. `dense_on_discrete` is true only for a plain
1505/// dense transformer (full attention, dense FFN, no special stack) that
1506/// is entirely resident on one discrete card — the one case measured
1507/// here. GDN hybrids, MoE, DeepSeek stacks, capacity-split and CPU-only
1508/// runs keep the width they were tuned with.
1509fn prefill_chunk_rule(env: Option<usize>, host: ChunkHost, dense_on_discrete: bool) -> usize {
1510    if let Some(n) = env {
1511        return n.max(1);
1512    }
1513    match host {
1514        ChunkHost::Macos => 512,
1515        // Mobile: big enough to feed the batched attend (gate b ≥ 32)
1516        // and the blocked SDOT GEMM without the memory of 512.
1517        ChunkHost::Aarch64 => 256,
1518        ChunkHost::Other if dense_on_discrete => DISCRETE_DENSE_PREFILL_CHUNK,
1519        ChunkHost::Other => 48,
1520    }
1521}
1522
1523/// What the chunk rule needs to know about a loaded stack.
1524#[derive(Clone, Copy, Debug, Default)]
1525struct ChunkStackFacts {
1526    /// Every layer is `AttnKind::Full` + `FfnKind::Dense`, and no
1527    /// architecture-owned stack (g3n, DeepSeek-V4/V4.1, qwen4-exp) is set.
1528    plain_dense: bool,
1529    /// The active GPU backend is a discrete card.
1530    discrete: bool,
1531    /// The backend is up and not paused.
1532    gpu_on: bool,
1533    /// A capacity-derived device prefix: some layers run on the host.
1534    capacity_split: bool,
1535    /// An in-process multi-GPU plan is set.
1536    multi_gpu: bool,
1537    /// O(1) layers (their Q trace is recorded by the prefill).
1538    o1: bool,
1539}
1540
1541impl ChunkStackFacts {
1542    fn dense_on_discrete(self) -> bool {
1543        self.plain_dense
1544            && self.discrete
1545            && self.gpu_on
1546            && !self.capacity_split
1547            && !self.multi_gpu
1548            && !self.o1
1549    }
1550}
1551
1552/// Number of prompt rows that have a real teacher-forced next-token pair in a
1553/// prefill span.  The final prompt row has no successor token, so it must not
1554/// be handed to the MTP warm-up.  Keeping this arithmetic in one helper makes
1555/// the full-chunk and tail-chunk boundaries explicit for both the graph and
1556/// CPU implementations.
1557#[inline]
1558fn mtp_prefill_pair_count(start: usize, end: usize, input_len: usize) -> usize {
1559    if end <= start || start >= input_len {
1560        return 0;
1561    }
1562    let rows = (end.min(input_len) - start).min(input_len - start);
1563    if end < input_len {
1564        rows
1565    } else {
1566        rows.saturating_sub(1)
1567    }
1568}
1569
1570/// Callback for streaming tokens. Return `false` to cancel.
1571pub type TokenCallback = Box<dyn FnMut(&str) -> bool + Send>;
1572
1573/// One layer's cache ownership at a cross-turn KV reuse boundary.
1574#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1575pub(crate) struct ReuseLayer {
1576    /// Exact-attention layer (rows in `LayerKvCache`); otherwise a
1577    /// recurrent / latent mixer whose state cannot be rewound.
1578    pub full: bool,
1579    /// Positions the host owner cache reaches (`pos_len`: a trimmed
1580    /// sliding tail stores only the newest of them).
1581    pub host_rows: usize,
1582    /// Rows the wgpu token graph's device mirror holds (None: no mirror).
1583    pub device_rows: Option<usize>,
1584    /// A recurrent state lives on the device (advanced past the host copy).
1585    pub device_state: bool,
1586}
1587
1588/// What a reused turn must do before its tail prefill runs on the HOST.
1589#[derive(Debug, Clone, PartialEq, Eq)]
1590pub(crate) enum ReusePlan {
1591    /// Host caches already hold exactly the reused prefix.
1592    Ready,
1593    /// Copy device mirror rows `[from..to)` into the host cache of each
1594    /// listed layer (the rows decode wrote on the device only).
1595    Pull(Vec<(usize, usize, usize)>),
1596    /// The prefix cannot be continued on the host exactly: start fresh.
1597    Fresh,
1598}
1599
1600/// The wgpu whole-token graph decodes into a DEVICE K/V mirror and never
1601/// writes those rows back to the host cache, while the chunked prefill of a
1602/// pure-attention model reads (and appends to) the host cache. A reused turn
1603/// therefore found its host cache ending at the previous PROMPT, not at the
1604/// previous answer: the tail prefill attended without the model's own
1605/// answer and appended its rows at the wrong index (MiniCPM5 on Vulkan
1606/// repeated its tool call instead of reading the tool result). Every layer
1607/// must hold exactly `reuse_from` host rows before the host continues; rows
1608/// that exist only on the device are pulled back, anything else is fresh.
1609pub(crate) fn kv_reuse_plan(reuse_from: usize, layers: &[ReuseLayer]) -> ReusePlan {
1610    let mut pulls = Vec::new();
1611    for (li, l) in layers.iter().enumerate() {
1612        if !l.full {
1613            if l.device_state {
1614                return ReusePlan::Fresh;
1615            }
1616            continue;
1617        }
1618        if l.host_rows == reuse_from {
1619            continue;
1620        }
1621        if l.host_rows < reuse_from && l.device_rows.is_some_and(|d| d >= reuse_from) {
1622            pulls.push((li, l.host_rows, reuse_from));
1623            continue;
1624        }
1625        return ReusePlan::Fresh;
1626    }
1627    if pulls.is_empty() {
1628        ReusePlan::Ready
1629    } else {
1630        ReusePlan::Pull(pulls)
1631    }
1632}
1633
1634impl Pipeline {
1635    /// Clear all per-sequence state, including backend device mirrors.
1636    ///
1637    /// The host KV/history buffers are only half of the request lifecycle on
1638    /// wgpu: GDN/O(1) state and cached graph bind groups are keyed by the
1639    /// pipeline id and otherwise survive a pooled request.  Keep every fresh
1640    /// sequence entry point on this one reset path so a new request cannot
1641    /// inherit the prior request's device state.
1642    fn clear_sequence_state(&mut self) {
1643        // a replay still writing the GDN owners must land before they are
1644        // cleared or reallocated (the device holds raw pointers to them)
1645        #[cfg(target_os = "macos")]
1646        let _ = crate::gpu_metal::wait_replay();
1647        self.kv_cache.clear();
1648        // Both reuse keys (the legacy `kv_history` and the bounded
1649        // `kv_prefix`) describe the state being dropped here.
1650        self.clear_history();
1651        self.graph_logits = None;
1652        if let Some(b) = &mut self.dsv41 {
1653            b.3.clear();
1654        }
1655        crate::gpu::graph_kv_reset(self.graph_kv_id);
1656        // MTP is detached from `self` for the duration of generation, so its
1657        // device mirror is not covered by the trunk reset above.  Reset the
1658        // derived id as well: a failed/aborted warm-up must never leave a
1659        // mirror that a later request can mistake for a current MTP cache.
1660        crate::gpu::graph_kv_reset(self.mtp_kv_id());
1661    }
1662
1663    /// Make the host caches own exactly the reused prefix `[0..reuse_from)`
1664    /// before a reused turn's tail prefill runs on the host (see
1665    /// [`kv_reuse_plan`]). Returns false when the prefix cannot be continued
1666    /// exactly — the caller then starts a fresh sequence. A model whose
1667    /// prefill runs through the token graph keeps its device state as the
1668    /// authority and is left untouched.
1669    fn prepare_kv_reuse(&mut self, reuse_from: usize) -> bool {
1670        if self.graph_prefill_preferred() {
1671            return true;
1672        }
1673        let kv_id = self.graph_kv_id;
1674        let layers: Vec<ReuseLayer> = (0..self.num_layers)
1675            .map(|li| {
1676                let full = matches!(
1677                    self.weights.layers[self.phys_layer(li)].attn,
1678                    AttnKind::Full { .. }
1679                );
1680                ReuseLayer {
1681                    full,
1682                    // Absolute depth: a trimmed sliding tail stores fewer
1683                    // rows than the positions it has seen.
1684                    host_rows: self.kv_cache.layers[li].pos_len(),
1685                    device_rows: crate::gpu::graph_kv_stored(kv_id, li),
1686                    device_state: crate::gpu::graph_state_resident(kv_id, li),
1687                }
1688            })
1689            .collect();
1690        // No wgpu device state at all (CPU, Metal — whose graph appends every
1691        // decoded row to the owner cache itself): the host is the owner and
1692        // the extension check already proved the prefix.
1693        if layers
1694            .iter()
1695            .all(|l| l.device_rows.is_none() && !l.device_state)
1696        {
1697            return true;
1698        }
1699        let plan = kv_reuse_plan(reuse_from, &layers);
1700        let (what, rows, n) = match &plan {
1701            ReusePlan::Ready => ("host ready", 0, 0),
1702            ReusePlan::Fresh => ("fresh", 0, 0),
1703            ReusePlan::Pull(p) => (
1704                "pull",
1705                p.iter().map(|&(_, a, b)| b - a).max().unwrap_or(0),
1706                p.len(),
1707            ),
1708        };
1709        let t0 = std::time::Instant::now();
1710        let ok = self.apply_kv_reuse_plan(reuse_from, plan, &layers);
1711        if std::env::var("CMF_PREFILL_PROF").is_ok() {
1712            eprintln!(
1713                "kv-reuse: {what}{}: {rows} device row(s) × {n} layer(s) to the host in {:.2} ms",
1714                if ok { "" } else { " (failed → fresh)" },
1715                t0.elapsed().as_secs_f64() * 1e3
1716            );
1717        }
1718        ok
1719    }
1720
1721    fn apply_kv_reuse_plan(
1722        &mut self,
1723        reuse_from: usize,
1724        plan: ReusePlan,
1725        layers: &[ReuseLayer],
1726    ) -> bool {
1727        let kv_id = self.graph_kv_id;
1728        match plan {
1729            ReusePlan::Fresh => return false,
1730            ReusePlan::Ready => {}
1731            ReusePlan::Pull(pulls) => {
1732                // Mirrors of one uniform geometry: one batched read serves
1733                // every layer. Per-layer geometry (MiMo-V2: 4/8 KV heads,
1734                // narrow V, sliding rings) is read layer by layer in the
1735                // host layout instead.
1736                let (nkv, hd) = {
1737                    let c = &self.kv_cache.layers[pulls[0].0];
1738                    (c.num_kv_heads, c.head_dim)
1739                };
1740                let uniform = pulls.iter().all(|&(li, _, _)| {
1741                    let c = &self.kv_cache.layers[li];
1742                    (c.num_kv_heads, c.head_dim) == (nkv, hd)
1743                });
1744                let batched = if uniform {
1745                    crate::gpu::graph_kv_read_rows(kv_id, &pulls, nkv, hd)
1746                } else {
1747                    None
1748                };
1749                let rows: Vec<(Vec<f32>, Vec<f32>)> = match batched {
1750                    Some(rows) => rows,
1751                    None => {
1752                        let mut rows = Vec::with_capacity(pulls.len());
1753                        for &(li, from, to) in &pulls {
1754                            let (lnkv, lhd) = {
1755                                let c = &self.kv_cache.layers[li];
1756                                (c.num_kv_heads, c.head_dim)
1757                            };
1758                            let Some((k, v, first_valid)) =
1759                                crate::gpu::graph_kv_pull_host(kv_id, li, from, to, lnkv, lhd)
1760                            else {
1761                                return false;
1762                            };
1763                            // The host continues at `to`: a sliding layer
1764                            // reads back only its last window, a full one
1765                            // every row it lacks.
1766                            let need_from = match self.layer_window(li) {
1767                                Some(w) => from.max((to + 1).saturating_sub(w)),
1768                                None => from,
1769                            };
1770                            if first_valid > need_from {
1771                                return false;
1772                            }
1773                            rows.push((k, v));
1774                        }
1775                        rows
1776                    }
1777                };
1778                for ((li, from, to), (k, v)) in pulls.into_iter().zip(rows) {
1779                    let cache = &mut self.kv_cache.layers[li];
1780                    let row = cache.num_kv_heads * cache.head_dim;
1781                    for p in 0..to - from {
1782                        cache.append(&k[p * row..(p + 1) * row], &v[p * row..(p + 1) * row], &[]);
1783                    }
1784                    if cache.pos_len() != to {
1785                        return false;
1786                    }
1787                }
1788            }
1789        }
1790        // A mirror past the prefix (a greedy burst that ran beyond the stop)
1791        // holds rows of the OLD continuation: rewind it so the next graph
1792        // token re-syncs those positions from the host.
1793        for (li, l) in layers.iter().enumerate() {
1794            if l.full
1795                && l.device_rows.is_some_and(|d| d > reuse_from)
1796                && !crate::gpu::graph_kv_set_stored(kv_id, li, reuse_from)
1797            {
1798                return false;
1799            }
1800        }
1801        true
1802    }
1803
1804    /// Finish a generation lifecycle after the MTP/router owners were
1805    /// detached.  Every terminal path must put those owners back before the
1806    /// pooled pipeline can serve another request.  Graph side channels and
1807    /// device mirrors are cleared on errors and cancellations; a successful
1808    /// generation keeps its decode-ready host cache for KV reuse.
1809    fn finish_generation(
1810        &mut self,
1811        mtp: &mut Option<MtpModule>,
1812        router: &mut Option<crate::swarm::DynRouter>,
1813        clear_sequence: bool,
1814    ) {
1815        // A dynamic route may have switched the overlay before the terminal
1816        // path. Restore the backbone while the detached router is still
1817        // available, because set_active_skill also owns the overlay reset.
1818        if router.is_some() {
1819            let _ = self.set_active_skill(None);
1820        }
1821        // The last speculative round's replay may still be in flight on
1822        // the second queue: whoever reads the host cache after generate()
1823        // returns (session export, the network split's KV wire, a KV
1824        // reuse) must see the final states.
1825        // A replay that failed leaves the GDN owners half-written: fail
1826        // closed and drop the sequence instead of handing the cache on.
1827        #[cfg(target_os = "macos")]
1828        let clear_sequence = clear_sequence || !crate::gpu_metal::wait_replay();
1829        if clear_sequence {
1830            self.clear_sequence_state();
1831            if let Some(m) = mtp.as_mut() {
1832                // The MTP owner is detached while generation runs, so the
1833                // trunk reset above cannot clear its host cache.  Drop its
1834                // partial rows before reattaching it to the pooled pipeline;
1835                // the next request must start from the same empty anchor on
1836                // CPU and on the device mirror.
1837                m.kv.clear();
1838            }
1839            if let Some(m) = self.mtp.as_mut() {
1840                // A non-speculative request leaves the configured MTP owner
1841                // attached.  Clear that dormant cache too when a shared
1842                // generation failure/cancellation resets the sequence.
1843                m.kv.clear();
1844            }
1845        }
1846        self.graph_want_logits = false;
1847        self.graph_head_required = false;
1848        self.graph_logits = None;
1849        self.graph_failed
1850            .store(false, std::sync::atomic::Ordering::Relaxed);
1851        self.cancel
1852            .store(false, std::sync::atomic::Ordering::Relaxed);
1853        self.dyn_router = router.take().or(self.dyn_router.take());
1854        self.mtp = mtp.take().or(self.mtp.take());
1855        self.mtp_graph_mode = None;
1856        self.spec_forced = None;
1857    }
1858
1859    /// Consume a graph failure reported by a forward that returns only a
1860    /// hidden vector.  `forward_ids` is a public Result API, so it must not
1861    /// turn the graph's zero hidden sentinel into a valid lm_head result.
1862    fn check_forward_graph(&mut self, phase: &str, pos: usize) -> Result<(), String> {
1863        if self
1864            .graph_failed
1865            .swap(false, std::sync::atomic::Ordering::Relaxed)
1866        {
1867            self.cancel
1868                .store(false, std::sync::atomic::Ordering::Relaxed);
1869            self.clear_sequence_state();
1870            self.graph_logits = None;
1871            self.graph_want_logits = false;
1872            self.graph_head_required = false;
1873            return Err(format!("GPU graph failed during {phase} at position {pos}"));
1874        }
1875        Ok(())
1876    }
1877
1878    #[cfg(target_os = "macos")]
1879    fn fail_metal_graph(&mut self, reason: &str) {
1880        crate::pipeline::METAL_GRAPH_ERRORS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1881        self.clear_sequence_state();
1882        self.graph_logits = None;
1883        self.graph_failed
1884            .store(true, std::sync::atomic::Ordering::Relaxed);
1885        self.cancel
1886            .store(true, std::sync::atomic::Ordering::Relaxed);
1887        tracing::error!("native Metal TokenGraph failed closed: {reason}");
1888    }
1889
1890    /// Start an NLL/PPL request with all graph side channels in a known
1891    /// state.  A graph failure also raises the cooperative cancel bit; it is
1892    /// consumed here and that graph-induced bit is cleared so an independent
1893    /// request can be reused.  A caller-owned cancellation remains intact.
1894    fn nll_begin(&mut self) -> Result<(), String> {
1895        if self
1896            .graph_failed
1897            .swap(false, std::sync::atomic::Ordering::Relaxed)
1898        {
1899            self.cancel
1900                .store(false, std::sync::atomic::Ordering::Relaxed);
1901            self.clear_sequence_state();
1902            self.graph_logits = None;
1903            self.graph_want_logits = false;
1904            self.graph_head_required = false;
1905            return Err("GPU graph failed before NLL scoring".to_string());
1906        }
1907        self.clear_sequence_state();
1908        self.graph_logits = None;
1909        self.graph_want_logits = false;
1910        self.graph_head_required = false;
1911        Ok(())
1912    }
1913
1914    /// End an NLL/PPL request, including the side channels that are not part
1915    /// of the host KV cache.  This is intentionally explicit instead of
1916    /// relying on a tuple/sentinel return: callers must see every failure.
1917    fn nll_end(&mut self) {
1918        self.clear_sequence_state();
1919        self.graph_logits = None;
1920        self.graph_want_logits = false;
1921        self.graph_head_required = false;
1922        self.graph_failed
1923            .store(false, std::sync::atomic::Ordering::Relaxed);
1924    }
1925
1926    /// Check the graph failure channel at a scoring boundary and leave the
1927    /// pipeline reusable when the device path failed.
1928    fn nll_check_graph(&mut self, phase: &str, pos: usize) -> Result<(), String> {
1929        #[cfg(test)]
1930        if self.nll_test_fail_at == Some(pos) {
1931            self.nll_test_fail_at = None;
1932            self.graph_failed
1933                .store(true, std::sync::atomic::Ordering::Relaxed);
1934            self.cancel
1935                .store(true, std::sync::atomic::Ordering::Relaxed);
1936        }
1937        if self
1938            .graph_failed
1939            .swap(false, std::sync::atomic::Ordering::Relaxed)
1940        {
1941            self.cancel
1942                .store(false, std::sync::atomic::Ordering::Relaxed);
1943            self.clear_sequence_state();
1944            self.graph_logits = None;
1945            self.graph_want_logits = false;
1946            return Err(format!(
1947                "GPU graph failed during NLL {phase} at position {pos}"
1948            ));
1949        }
1950        Ok(())
1951    }
1952
1953    /// Map a virtual layer index to its physical weight index.
1954    /// Looped Transformer (Nanbeige 4.2): 22 physical layers × 2 loops = 44 virtual;
1955    /// virtual layer 23 maps back to physical layer 1 (23 % 22 = 1).
1956    #[inline]
1957    pub fn phys_layer(&self, virtual_idx: usize) -> usize {
1958        virtual_idx % self.physical_layers
1959    }
1960
1961    /// True when `virtual_idx` is the last layer of a loop iteration
1962    /// (used for loop_final_norm insertion).
1963    #[inline]
1964    pub fn is_loop_end(&self, virtual_idx: usize) -> bool {
1965        self.loop_final_norm && (virtual_idx + 1) % self.physical_layers == 0
1966    }
1967
1968    /// Build a pipeline from parts (used by the loader and tests).
1969    #[allow(clippy::too_many_arguments)]
1970
1971    /// Whole-block q1 token graph on the GPU (macOS/Metal): the run of
1972    /// consecutive q1 layers — GDN *and* full attention — starting at
1973    /// `start` executes as few command buffers as the CPU truly needs.
1974    /// Hidden stays device-resident across every layer; the only syncs
1975    /// are before each CPU attend (it needs q/k/v and owns the KV
1976    /// cache) and the final hidden readback. Recurrent states
1977    /// round-trip through shared memory (the CPU stays their owner, so
1978    /// every other path remains coherent). Returns the first layer
1979    /// index NOT covered (== `start` → refused, caller falls through
1980    /// to the per-layer CPU path).
1981    /// Should prefill run position-by-position through the GPU token
1982    /// graph instead of the batched CPU chunk-GEMM? True for q1 GDN
1983    /// hybrids on native Metal: their chunk prefill is walled by the
1984    /// sequential scalar recurrence, so the graph's decode rate wins.
1985    /// NOT for Looped Transformers, despite the per-chunk loop_final_norm
1986    /// sync: the chunk-GEMM amortizes each weight over the whole chunk,
1987    /// which the per-position graph cannot (Nanbeige 4.2 on M4, 512-token
1988    /// prompt: 85 tok/s chunked vs 14 through the graph).
1989    #[cfg(target_os = "macos")]
1990    fn graph_prefill_preferred(&self) -> bool {
1991        let graph_force = crate::gpu::q1_force() || crate::gpu::q2tp_gpu_opt_in();
1992        if !crate::gpu::enabled_here()
1993            || !graph_force
1994            || std::env::var("CMF_GPU_BLOCK")
1995                .map(|v| v == "0")
1996                .unwrap_or(false)
1997            // CMF_PREFILL_GRAPH=0: the chunked prefill (GEMM projections,
1998            // CPU recurrence) instead of the per-position token graph.
1999            || std::env::var("CMF_PREFILL_GRAPH").as_deref() == Ok("0")
2000        {
2001            return false;
2002        }
2003        self.weights
2004            .layers
2005            .iter()
2006            .any(|lw| {
2007                matches!(&lw.attn, AttnKind::LinearGdn(w) if w.in_proj_qkv.metal_graph_parts().is_some())
2008            })
2009    }
2010
2011    /// Prompt ingest through the batched wgpu graph in device-prefix mode:
2012    /// a MoE stack that does not fit the card runs each chunk's leading
2013    /// layers on the device (experts resident) and the rest on the host's
2014    /// batched walk. On by default for models with per-layer attention
2015    /// geometry (MiMo-V2 — its measured default); `CMF_BATCH_PREFIX=1`
2016    /// opts any other MoE model in, `=0` keeps the chunked host prefill.
2017    #[cfg(not(target_os = "macos"))]
2018    fn batch_prefix_prefill(&self) -> bool {
2019        let forced = match std::env::var("CMF_BATCH_PREFIX").as_deref() {
2020            Ok("0") => return false,
2021            Ok("1") => true,
2022            _ => false,
2023        };
2024        crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill)
2025            && crate::gpu::enabled_here()
2026            && !self.graph_refused()
2027            && (forced || self.graph_attn_decline_reason().is_some())
2028            && self.wgpu_graph_attn_decline().is_none()
2029            && self.attn_softcap == 0.0
2030            && self
2031                .weights
2032                .layers
2033                .iter()
2034                .any(|lw| matches!(&lw.ffn, FfnKind::Moe(_)))
2035            && self.automatic_gpu_prefix().is_some()
2036    }
2037
2038    /// Gemma-4's prompt through the batched wgpu graph (`gemma_batch`): a
2039    /// dense stack wholly on a discrete card, whose token graph already
2040    /// decodes it. Not `graph_prefill_preferred` — the host stays the KV
2041    /// owner for reuse and scoring; only generation's ingest changes.
2042    /// `CMF_G4_BATCH=0` keeps the chunked host prefill.
2043    fn g4_batch_prefill(&self) -> bool {
2044        #[cfg(target_os = "macos")]
2045        {
2046            false
2047        }
2048        #[cfg(not(target_os = "macos"))]
2049        {
2050            // An EMPTY layer stack (`all()` is vacuously true) plus a
2051            // gemma4 geometry flag is exactly the gemma-4 E-series
2052            // per-token stack — it has no batch graph rows to ingest.
2053            !self.weights.layers.is_empty()
2054                && !self.per_token_stack()
2055                && (self.global_attn.is_some() || self.attn_v_norm)
2056                && crate::gpu::g4_batch_on()
2057                && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill)
2058                && crate::gpu::enabled_here()
2059                && crate::gpu::discrete()
2060                && !self.graph_refused()
2061                && !self.o1_active()
2062                && self.attn_softcap == 0.0
2063                && self.wgpu_graph_attn_decline().is_none()
2064                && self.weights.layers.iter().all(|lw| {
2065                    matches!(lw.attn, AttnKind::Full { .. }) && matches!(lw.ffn, FfnKind::Dense(_))
2066                })
2067                && self.automatic_gpu_prefix().is_none()
2068        }
2069    }
2070
2071    /// Gemma-4's batched prefill of `ids` at positions `pos0..`
2072    /// (`g4_batch_prefill`): chunks of `generation_batch_k` rows through the
2073    /// batch graph. Ok((n, rows)): `n` positions ingested; `rows` = the last
2074    /// one's hidden, or every row's (`keep_all`). A refusal stops early
2075    /// (n < ids.len()) after pulling the device rows the host walk needs.
2076    /// Err: a failure after admission — the device state is undefined.
2077    #[cfg(not(target_os = "macos"))]
2078    fn g4_batch_ingest(
2079        &mut self,
2080        ids: &[u32],
2081        pos0: usize,
2082        keep_all: bool,
2083    ) -> Result<(usize, Vec<f32>), String> {
2084        let hs = self.hidden_size;
2085        let chunk = self.generation_batch_k().max(1);
2086        let end_all = pos0 + ids.len();
2087        let mut pos = pos0;
2088        let mut out = Vec::new();
2089        while pos < end_all && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
2090            let end = (pos + chunk).min(end_all);
2091            let bk = end - pos;
2092            let mut hiddens = vec![0f32; bk * hs];
2093            for (j, &id) in ids[pos - pos0..end - pos0].iter().enumerate() {
2094                hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
2095            }
2096            let positions: Vec<usize> = (pos..end).collect();
2097            let t_chunk = std::time::Instant::now();
2098            let outcome = self.try_batch_graph_wgpu(&mut hiddens, &positions, bk, None);
2099            if std::env::var("CMF_GRAPH_PROF").is_ok() {
2100                let ms = t_chunk.elapsed().as_secs_f64() * 1000.0;
2101                eprintln!(
2102                    "batch-chunk: phase=prompt mode=gemma4 k={bk} outcome={outcome:?} {ms:.1} ms ({:.1} tok/s)",
2103                    bk as f64 / (ms / 1000.0)
2104                );
2105            }
2106            match outcome {
2107                crate::gpu::BatchGraphOutcome::Completed => {
2108                    if keep_all {
2109                        out.extend_from_slice(&hiddens);
2110                    } else {
2111                        out = hiddens[(bk - 1) * hs..].to_vec();
2112                    }
2113                    pos = end;
2114                }
2115                crate::gpu::BatchGraphOutcome::Failed => {
2116                    return Err("Gemma-4 batched prefill failed after admission".into());
2117                }
2118                crate::gpu::BatchGraphOutcome::Declined => {
2119                    #[cfg(feature = "gpu")]
2120                    if pos > pos0 {
2121                        self.pull_lagging_host_kv(0, self.num_layers, pos);
2122                    }
2123                    break;
2124                }
2125            }
2126        }
2127        Ok((pos - pos0, out))
2128    }
2129
2130    /// Hidden rows of every position of `ids` through Gemma-4's batched
2131    /// prefill from a fresh sequence (the prefill's teacher-forced logits
2132    /// for parity gates: `logits_from_hidden` per row). None when the model
2133    /// or the card does not take that route, or it refused part way.
2134    pub fn g4_prefill_hidden_rows(&mut self, ids: &[u32]) -> Option<Vec<f32>> {
2135        #[cfg(not(target_os = "macos"))]
2136        {
2137            if ids.is_empty() || !self.g4_batch_prefill() {
2138                return None;
2139            }
2140            self.clear_sequence_state();
2141            match self.g4_batch_ingest(ids, 0, true) {
2142                Ok((n, rows)) if n == ids.len() => Some(rows),
2143                _ => {
2144                    self.clear_sequence_state();
2145                    None
2146                }
2147            }
2148        }
2149        #[cfg(target_os = "macos")]
2150        {
2151            let _ = ids;
2152            None
2153        }
2154    }
2155
2156    #[cfg(not(target_os = "macos"))]
2157    fn graph_prefill_preferred(&self) -> bool {
2158        // Discrete-GPU wgpu whole-token graph: GDN layers carry recurrent state
2159        // (conv ring + delta-rule S) resident on the GPU. A batched CPU prefill
2160        // builds that state on the CPU only, leaving the GPU buffers zeroed at
2161        // decode → garbage. Route GDN-hybrid prefill through the graph one
2162        // position at a time so the resident state is seeded exactly as decode
2163        // will read it. Pure-attention models keep the batched CPU prefill (its
2164        // KV mirror re-syncs from the CPU cache, so no seeding gap).
2165        let graph_on = crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill);
2166        if !graph_on || !crate::gpu::enabled_here() {
2167            return false;
2168        }
2169        // Embryo's phase state is device-owned by the resident graph during
2170        // prefill; the batched CPU path would leave decode seeing a zeroed
2171        // device recurrence.  Route the prompt position-by-position too.
2172        if self.embryo_resident_eligible() {
2173            // The resident graph owns the phase state and anchor KV on the
2174            // device.  A prefill-only graph would leave decode on the host
2175            // with no way to import that state, so keep the whole sequence
2176            // on one owner (or use the ordinary CPU prefill/decode pair).
2177            return crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode);
2178        }
2179        // The descriptor-aware Prism graph now carries both the FWHT/affine
2180        // transforms and resident GDN state, so it is also the exact prefill
2181        // path for this model.  Keeping it here (rather than falling through
2182        // to the CPU chunk walk) is required for a long prompt to seed the
2183        // same device state that decode consumes.
2184        // O(1) needs the CPU prefill: the q-trace that seals the Nyström
2185        // skeleton is recorded there and nowhere else. The GDN half of
2186        // the hybrid loses nothing — the graph's first decode creates
2187        // its (ring, S) entries seeded from `cpu_state`, the same
2188        // handoff every graph run relies on when the entry is fresh.
2189        // Without this line the two designs collide on hybrids and o1
2190        // never becomes graph-portable: prefill through the graph
2191        // records no trace, so views stay None forever.
2192        if self.o1_active() {
2193            return false;
2194        }
2195        // A model the wgpu graphs decline outright would walk its prompt
2196        // one position at a time through a graph that never runs: the
2197        // batched CPU chunk prefill is the right ingest for it.
2198        if self.wgpu_graph_attn_decline().is_some() {
2199            return false;
2200        }
2201        if self
2202            .weights
2203            .layers
2204            .iter()
2205            .any(|lw| matches!(&lw.attn, AttnKind::LinearGdn(_)))
2206        {
2207            return true;
2208        }
2209        // MoE models too: the chunked CPU prefill runs every expert on the
2210        // host (Hy-MT2-30B-A3B on a Xeon: 8 tok/s of ingest against 53 of
2211        // graph decode), while the token graph — and the batched graph under
2212        // CMF_BATCH_K — keep the experts resident. Full attention in the
2213        // graph writes the KV mirror that decode reads, exactly as it does
2214        // for the hybrids' attention layers. Only when the whole stack is
2215        // resident: with a device prefix the per-position walk finishes
2216        // every token on the host, and the chunked prefill (GEMMs on the
2217        // card, the expert loop batched on the host) is the faster ingest
2218        // (the 8 GB ladder point: 7 tok/s chunked against ~1 walked).
2219        self.weights
2220            .layers
2221            .iter()
2222            .any(|lw| matches!(&lw.ffn, FfnKind::Moe(_)))
2223            && self.automatic_gpu_prefix().is_none()
2224    }
2225
2226    #[cfg(target_os = "macos")]
2227    fn q1_graph_gpu(
2228        &mut self,
2229        start: usize,
2230        upto: Option<usize>,
2231        position: usize,
2232        h: &mut [f32],
2233    ) -> usize {
2234        let _mt0 = std::time::Instant::now(); // CMF_METAL_HOSTPROF
2235        use crate::gpu::{AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, GraphDims, MetalFfn, TokenGraph};
2236        const MOE_WORKING_SET_REASON: &str =
2237            "model weights exceed Metal working set for native MoE graph";
2238        // A prior admission check rejected this pipeline. Avoid rebuilding the
2239        // entire 40-layer graph plan at every individual host layer after the
2240        // fallback begins; the per-operation path below stays eligible.
2241        if self
2242            .graph_declines
2243            .borrow()
2244            .iter()
2245            .any(|&(site, reason)| site == "metal block graph" && reason == MOE_WORKING_SET_REASON)
2246        {
2247            return start;
2248        }
2249        let graph_force = crate::gpu::q1_force() || crate::gpu::q2tp_gpu_opt_in();
2250        if self.attn_softcap > 0.0 // capped scores: no graph kernel — CPU path
2251            || !self.metal_rope_scale_ok()
2252            || !crate::gpu::enabled_here()
2253            || !graph_force
2254            || std::env::var("CMF_GPU_BLOCK")
2255                .map(|v| v == "0")
2256                .unwrap_or(false)
2257        {
2258            if std::env::var("CMF_GRAPH_DBG").is_ok() {
2259                eprintln!(
2260                    "block-graph: front gate (softcap={} enabled_here={} graph_force={})",
2261                    self.attn_softcap > 0.0,
2262                    crate::gpu::enabled_here(),
2263                    graph_force,
2264                );
2265            }
2266            if self.graph_head_required {
2267                self.fail_metal_graph("native graph front gate refused");
2268            }
2269            return start;
2270        }
2271        // The graph encodes SiLU or exact-GELU FFNs and attention with an
2272        // explicit model scale. Sliding-window layers with their own RoPE
2273        // table / rotary width ride it too (`metal_graph_swa`): both the
2274        // device attend and the sandwich's CPU attend read each layer's
2275        // window and table. Sandwich norms and other activations fall back
2276        // to the CPU path.
2277        // Gemma-4 (`metal_gemma4`): its sliding layers ride the same door,
2278        // its global layers, V norm, sandwich norms, layer scalar and
2279        // tanh-GELU the `gpu_metal::gemma4` kernels.
2280        let gemma4 = self.metal_gemma4();
2281        let swa_graph = self.metal_graph_swa() || gemma4;
2282        // The normal native GQA kernel carries a learned, value-less
2283        // softmax column.  It also takes the exact per-layer sliding
2284        // window, but its split-K twin has no sink column.  Thus a
2285        // sink-bearing model may use this door only when the ordinary
2286        // sliding geometry has passed `metal_graph_swa` (or when it has no
2287        // sliding layers at all).
2288        let graph_attn_reason = self.graph_attn_decline_reason();
2289        let native_sink_attend = graph_attn_reason == Some("learned attention sinks")
2290            && (swa_graph || (self.swa.is_none() && self.sliding_layers.is_none()));
2291        if (self.swa.is_some() && !swa_graph)
2292            || (self.global_attn.is_some() && !gemma4)
2293            || self.attention_heads_per_layer.is_some()
2294            || (self.attn_v_norm && !gemma4)
2295            // Per-layer KV heads / narrow V stay outside this graph.  A
2296            // learned sink is admitted only through native_sink_attend.
2297            || (graph_attn_reason.is_some() && !swa_graph && !native_sink_attend)
2298            || self.weights.layers.iter().any(|lw| {
2299                ((lw.attn_out_norm.is_some()
2300                    || lw.ffn_out_norm.is_some()
2301                    || lw.layer_scale.is_some())
2302                    && !gemma4)
2303                    || matches!(&lw.ffn, FfnKind::Dense(d)
2304                        if !(matches!(d.act, Act::Silu | Act::Gelu)
2305                            || (gemma4 && d.act == Act::GeluTanh)))
2306            })
2307        {
2308            // The Metal graphs' device attend has no per-layer attention
2309            // geometry (the wgpu graphs do): say so once, by name.
2310            if let Some(reason) = graph_attn_reason.filter(|_| !swa_graph && !native_sink_attend) {
2311                self.note_graph_decline("metal block graph", reason);
2312            }
2313            if std::env::var("CMF_GRAPH_DBG").is_ok() {
2314                eprintln!(
2315                    "block-graph: arch ineligible (swa={} gattn={} hpl={} vnorm={} scale_delta={:.2e})",
2316                    self.swa.is_some(),
2317                    self.global_attn.is_some(),
2318                    self.attention_heads_per_layer.is_some(),
2319                    self.attn_v_norm,
2320                    (self.attn_scale - 1.0 / (self.head_dim as f32).sqrt()).abs(),
2321                );
2322            }
2323            if self.graph_head_required {
2324                self.fail_metal_graph("native graph architecture gate refused");
2325            }
2326            return start;
2327        }
2328        // Looped Transformer: the graph covers ALL loop iterations;
2329        // encode_loop_norm is inserted on-device at each boundary.
2330        let limit = upto
2331            .map(|u| u + 1)
2332            .unwrap_or(self.num_layers)
2333            .min(self.num_layers);
2334
2335        enum Item<'a> {
2336            Gdn {
2337                run: Vec<GdnGpuLayer<'a>>,
2338                first: usize,
2339            },
2340            Attn {
2341                l: AttnGpuLayer<'a>,
2342                li: usize,
2343                q_norm: Option<&'a [f32]>,
2344                k_norm: Option<&'a [f32]>,
2345                output_gate: bool,
2346                /// `self_attn.g_proj` output gate (per-head flag): the
2347                /// sandwich projects the device-normed input on the host
2348                /// and gates the attend's output before O.
2349                proj_gate: Option<(&'a QTensor, bool)>,
2350                /// The same gate's f32 rows `[nh × hidden]` when the device
2351                /// attend can apply it (per-head sigmoid, f32 in RAM).
2352                head_gate_w: Option<&'a [f32]>,
2353                bias: Option<(&'a [f32], &'a [f32], &'a [f32])>,
2354                /// Attend on the device too (no sync): F32 KV, no
2355                /// o1/bias, dims inside the kernels' contract.
2356                full_gpu: bool,
2357            },
2358        }
2359
2360        // Device-attend KERNEL contract, shared by every Full layer. The
2361        // hd>128 default-off POLICY is applied after the scan: it was
2362        // measured on dense models, and a MoE plan inverts it — with the
2363        // experts on device each CPU-attend sandwich costs a
2364        // commit+wait, ~30 submits/token (W2 on M4: 14.7 tok/s
2365        // sandwiched vs 27.1 device-attend vs 18.8 pure CPU).
2366        let attend_mode = std::env::var("CMF_GPU_ATTEND").unwrap_or_else(|_| "auto".into());
2367        let attend_contract = attend_mode != "0"
2368            && attend_mode != "off"
2369            && self.head_dim % 4 == 0
2370            && self.head_dim <= 256
2371            // Flint has explicit no-RoPE layers.  The device RoPE kernel
2372            // accepts rd=0 (zero rotation lanes) and binds a sentinel table;
2373            // retain the historical lane-pair requirement for nonzero rd.
2374            && (self.rotary_dim == 0
2375                || (self.rotary_dim >= 2
2376                    && self.rotary_dim <= self.head_dim
2377                    && (self.rotary_dim / 2) % 32 == 0))
2378            && self.num_kv_heads > 0
2379            && self.num_heads % self.num_kv_heads == 0;
2380
2381        let mut plan: Vec<Item> = Vec::new();
2382        let mut model_ref: Option<std::sync::Arc<cortiq_core::CmfModel>> = None;
2383        // Break-reason diagnostics ride the same env as the plan summary.
2384        let block_diag = std::env::var("CMF_GRAPH_DBG").is_ok();
2385        let mut scan = start;
2386        while scan < limit {
2387            let lw = &self.weights.layers[self.phys_layer(scan)];
2388            let ffn = match &lw.ffn {
2389                FfnKind::Dense(d) if d.segs.is_empty() => {
2390                    let (Some(g), Some(u), Some(dn)) = (
2391                        d.gate_proj.metal_graph_parts(),
2392                        d.up_proj.metal_graph_parts(),
2393                        d.down_proj.metal_graph_parts(),
2394                    ) else {
2395                        if block_diag {
2396                            eprintln!(
2397                                "block-graph: L{scan} FFN trio not graph-mappable — run ends"
2398                            );
2399                        }
2400                        break;
2401                    };
2402                    MetalFfn::Dense {
2403                        gate: g,
2404                        up: u,
2405                        down: dn,
2406                        // The front gate admitted SiLU, exact GELU and
2407                        // (Gemma-4) tanh-GELU only.
2408                        act: d.act.graph_act().map_or(0, |a| a.code() as u8),
2409                    }
2410                }
2411                FfnKind::Moe(m) => {
2412                    // Flint's detached Q4 shared expert is intentionally
2413                    // tried before the generic uniform-bank graph builder.
2414                    // The latter correctly refuses its ragged Q2/Q4 widths;
2415                    // this narrow descriptor keeps the router and selected
2416                    // routed experts device-resident inside a bounded page.
2417                    let ffn = if let Some(flint) = metal_flint_moe_graph_parts(m, self.hidden_size, scan)
2418                    {
2419                        MetalFfn::FlintMoe(flint)
2420                    } else if let Some(moe) = metal_moe_graph_parts(m, self.hidden_size) {
2421                        MetalFfn::Moe(moe)
2422                    } else {
2423                        if block_diag {
2424                            eprintln!(
2425                                "block-graph: L{scan} MoE outside the graph contract — run ends"
2426                            );
2427                        }
2428                        break;
2429                    };
2430                    if let QTensor::Mapped { model, .. } = &m.experts[0].gate_proj {
2431                        model_ref.get_or_insert_with(|| model.clone());
2432                    }
2433                    ffn
2434                }
2435                _ => {
2436                    if block_diag {
2437                        eprintln!("block-graph: L{scan} non-graph FFN — run ends");
2438                    }
2439                    break;
2440                }
2441            };
2442            match &lw.attn {
2443                AttnKind::LinearGdn(w) if self.gdn_cfg.is_some() => {
2444                    let parts = (
2445                        w.in_proj_qkv.metal_graph_parts(),
2446                        w.in_proj_z.metal_graph_parts(),
2447                        w.in_proj_a.f32_parts(),
2448                        w.in_proj_b.f32_parts(),
2449                        w.out_proj.metal_graph_parts(),
2450                    );
2451                    let (Some(qkv), Some(z), Some(a), Some(b), Some(out)) = parts else {
2452                        if block_diag {
2453                            eprintln!(
2454                                "block-graph: L{scan} GDN parts refused (qkv={} z={} a_f32={} b_f32={} out={})",
2455                                w.in_proj_qkv.metal_graph_parts().is_some(),
2456                                w.in_proj_z.metal_graph_parts().is_some(),
2457                                w.in_proj_a.f32_parts().is_some(),
2458                                w.in_proj_b.f32_parts().is_some(),
2459                                w.out_proj.metal_graph_parts().is_some(),
2460                            );
2461                        }
2462                        break;
2463                    };
2464                    if let QTensor::Mapped { model, .. } = &w.in_proj_qkv {
2465                        model_ref.get_or_insert_with(|| model.clone());
2466                    }
2467                    let gl = GdnGpuLayer {
2468                        attn_norm: &lw.input_norm,
2469                        post_norm: &lw.post_norm,
2470                        qkv,
2471                        z,
2472                        a,
2473                        b,
2474                        out,
2475                        ffn,
2476                        conv1d: &w.conv1d,
2477                        a_log: &w.a_log,
2478                        dt_bias: &w.dt_bias,
2479                        gnorm: &w.norm,
2480                    };
2481                    match plan.last_mut() {
2482                        Some(Item::Gdn { run, .. }) => run.push(gl),
2483                        _ => plan.push(Item::Gdn {
2484                            run: vec![gl],
2485                            first: scan,
2486                        }),
2487                    }
2488                }
2489                AttnKind::Full {
2490                    wq,
2491                    wk,
2492                    wv,
2493                    wo,
2494                    q_norm,
2495                    k_norm,
2496                    output_gate,
2497                    softplus_gate,
2498                    bias,
2499                } if (!self.kv_cache.layers[scan].o1_sealed()
2500                    // Sealed o1 stays plannable when the Metal o1 port
2501                    // is on: full_gpu attends through the device state,
2502                    // and any refusal falls to the sandwich, whose CPU
2503                    // core routes sealed layers through the nystrom step.
2504                    || std::env::var("CMF_O1_METAL").as_deref() == Ok("1"))
2505                    // A projected output gate: Spark-X2.5's per-head
2506                    // sigmoid form only (Laguna's softplus gate is
2507                    // unmeasured on these paths and keeps the CPU walk).
2508                    && softplus_gate
2509                        .as_ref()
2510                        .is_none_or(|(_, per_head)| *per_head && self.proj_gate_sigmoid) =>
2511                {
2512                    let parts = (
2513                        wq.metal_graph_parts(),
2514                        wk.metal_graph_parts(),
2515                        wv.metal_graph_parts(),
2516                        wo.metal_graph_parts(),
2517                    );
2518                    let (Some(pq), Some(pk), Some(pv), Some(po)) = parts else {
2519                        break;
2520                    };
2521                    if let QTensor::Mapped { model, .. } = wq {
2522                        model_ref.get_or_insert_with(|| model.clone());
2523                    }
2524                    let cache = &self.kv_cache.layers[scan];
2525                    // O(1) layer on Metal: the device attends through the
2526                    // sealed Nystrom state (opt-in while the port proves
2527                    // itself). Unsealed -> sandwich path = the CPU o1 step.
2528                    let o1_metal = cache.o1.is_some()
2529                        && std::env::var("CMF_O1_METAL").as_deref() == Ok("1")
2530                        && cache.o1_views().is_some();
2531                    // The device attend takes the layer's window and RoPE
2532                    // table, and the per-head gate from f32 rows; a gate
2533                    // held otherwise sandwiches.
2534                    let head_gate_w = softplus_gate
2535                        .as_ref()
2536                        .and_then(|(g, _)| g.f32_parts())
2537                        .filter(|&(_, r, c)| r == self.num_heads && c == self.hidden_size)
2538                        .map(|(d, _, _)| d);
2539                    // Gemma-4's global layers are 512 wide over one KV head
2540                    // (the `gemma4` 16-slot kernels, `CMF_METAL_GEMMA4_W16`).
2541                    let (nkv_g, hd_g) = if gemma4 {
2542                        let (a, b, _) = self.layer_geom(scan);
2543                        (a, b)
2544                    } else {
2545                        (self.num_kv_heads, self.head_dim)
2546                    };
2547                    let full_gpu = attend_contract
2548                        && softplus_gate.is_none() == head_gate_w.is_none()
2549                        && cache.mode == crate::kv_cache::KvMode::F32
2550                        && (cache.o1.is_none() || o1_metal)
2551                        && bias.is_none()
2552                        && (hd_g <= 256 || crate::gpu_metal::gemma4::w16_on())
2553                        && pq.1 == self.num_heads * hd_g * (1 + *output_gate as usize)
2554                        && pk.1 == nkv_g * hd_g
2555                        && pv.1 == nkv_g * hd_g
2556                        && po.2 == self.num_heads * hd_g;
2557                    plan.push(Item::Attn {
2558                        l: AttnGpuLayer {
2559                            attn_norm: &lw.input_norm,
2560                            post_norm: &lw.post_norm,
2561                            wq: pq,
2562                            wk: pk,
2563                            wv: pv,
2564                            wo: po,
2565                            ffn,
2566                            attn_out_norm: lw.attn_out_norm.as_deref(),
2567                            ffn_out_norm: lw.ffn_out_norm.as_deref(),
2568                            layer_scale: lw.layer_scale,
2569                        },
2570                        li: scan,
2571                        q_norm: q_norm.as_deref(),
2572                        k_norm: k_norm.as_deref(),
2573                        output_gate: *output_gate,
2574                        proj_gate: softplus_gate.as_ref().map(|(g, per_head)| (g, *per_head)),
2575                        head_gate_w,
2576                        bias: bias
2577                            .as_ref()
2578                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
2579                        full_gpu,
2580                    });
2581                }
2582                _ => break,
2583            }
2584            scan += 1;
2585        }
2586        let Some(model) = model_ref else {
2587            if std::env::var("CMF_GRAPH_DBG").is_ok() {
2588                eprintln!("q1-graph: no model ref (start {start}, scanned to {scan})");
2589            }
2590            if self.graph_head_required {
2591                self.fail_metal_graph("native graph has no mapped model reference");
2592            }
2593            return start;
2594        };
2595        if plan.is_empty() {
2596            if std::env::var("CMF_GRAPH_DBG").is_ok() {
2597                eprintln!("q1-graph: empty plan at layer {start}");
2598            }
2599            if self.graph_head_required {
2600                self.fail_metal_graph("native graph plan is empty");
2601            }
2602            return start;
2603        }
2604        let has_moe = plan.iter().any(|it| match it {
2605            Item::Gdn { run, .. } => run
2606                .iter()
2607                .any(|l| matches!(l.ffn, MetalFfn::Moe(_) | MetalFfn::FlintMoe(_))),
2608            Item::Attn { l, .. } => matches!(l.ffn, MetalFfn::Moe(_) | MetalFfn::FlintMoe(_)),
2609        });
2610        let has_flint_moe = plan.iter().any(|it| match it {
2611            Item::Gdn { run, .. } => run.iter().any(|l| matches!(l.ffn, MetalFfn::FlintMoe(_))),
2612            Item::Attn { l, .. } => matches!(l.ffn, MetalFfn::FlintMoe(_)),
2613        });
2614        let metal_working_set = crate::gpu_metal::working_set_bytes();
2615        let metal_max_buffer = crate::gpu_metal::max_buffer_bytes();
2616        let model_bytes = model.primary_bytes().len() as u64;
2617        // Flint q2 can sit below recommendedMaxWorkingSetSize on a 24 GB
2618        // M4 yet still exceed maxBufferLength. In that case a normal graph
2619        // would manufacture overlapping whole-file WeightArena windows;
2620        // treat it as the same bounded-page requirement rather than letting
2621        // the generic graph reintroduce broad residency.
2622        let needs_bounded_pager = (metal_working_set != 0 && model_bytes > metal_working_set)
2623            || (metal_max_buffer != 0 && model_bytes > metal_max_buffer);
2624        // An oversized MoE mmap normally has to decline: the jobs kernels
2625        // bind all WeightArena windows.  The opt-in pager takes a different,
2626        // bounded route: a *complete sequence of logical layers* is put in
2627        // one transient no-copy page, graph-finished, dropped, then the outer
2628        // layer loop calls us again for the next page.  That preserves exact
2629        // hidden/GDN/KV handoff while replacing ~40 host-routed expert waits
2630        // with a few page-boundary syncs.  Never use it for a fused-head NLL
2631        // request: that contract explicitly requires a single whole graph.
2632        let pager_cap = if !has_moe {
2633            None
2634        } else if has_flint_moe {
2635            // Do not let generic `CMF_METAL_MOE_PAGER` turn the experimental
2636            // full-bank Flint graph on. Its direct selected-view pager stays
2637            // independently automatic; this path needs its own opt-in.
2638            crate::gpu_metal::flint_moe_pager_cap_bytes(&model)
2639        } else {
2640            crate::gpu_metal::moe_pager_cap_bytes()
2641        };
2642        let pager_eligible =
2643            pager_cap.is_some() && !self.graph_head_required && needs_bounded_pager;
2644        let mut pager_span: Option<(usize, usize)> = None;
2645        if pager_eligible {
2646            let cap = pager_cap.expect("checked above");
2647            // When this page reaches the true model end, include the fused
2648            // lm_head too.  Otherwise `lm_head_ok` would correctly refuse a
2649            // binding outside the page after the layers had already run.
2650            let tail_span = (self.graph_want_logits
2651                && upto.is_none()
2652                && scan == self.num_layers
2653                && std::env::var("CMF_GPU_LMHEAD")
2654                    .map(|v| v != "0")
2655                    .unwrap_or(true))
2656            .then(|| self.weights.lm_head.metal_graph_parts())
2657            .flatten()
2658            .and_then(|lm| crate::gpu_metal::model_tensor_span(&model, lm.0));
2659            let add_layer_span = |span: Option<(usize, usize)>, li: usize| {
2660                let (lo, hi) = crate::gpu_metal::model_layer_span(&model, self.phys_layer(li))?;
2661                Some(match span {
2662                    Some((cur_lo, cur_hi)) => (cur_lo.min(lo), cur_hi.max(hi)),
2663                    None => (lo, hi),
2664                })
2665            };
2666            let page_span = |span: (usize, usize), include_tail: bool| {
2667                let (mut lo, mut hi) = span;
2668                if include_tail {
2669                    if let Some((tail_lo, tail_hi)) = tail_span {
2670                        lo = lo.min(tail_lo);
2671                        hi = hi.max(tail_hi);
2672                    }
2673                }
2674                crate::gpu_metal::page_round_span(lo, hi)
2675            };
2676            let mut selected = 0usize;
2677            let mut selected_span: Option<(usize, usize)> = None;
2678            // `Item::Gdn` is built as a maximal run so the normal resident
2679            // graph can batch its recurrent state work.  A physical CMF can
2680            // nevertheless place that whole run across a page cap while each
2681            // logical layer fits.  Split *only the final admitted run* at a
2682            // layer boundary: the next outer-loop call rebuilds the remaining
2683            // suffix, preserving hidden/state handoff and keeping the normal
2684            // long-run batching within every page.
2685            let mut gdn_prefix: Option<(usize, usize)> = None;
2686            'items: for (i, item) in plan.iter().enumerate() {
2687                match item {
2688                    Item::Attn { li, .. } => {
2689                        let Some(span) = add_layer_span(selected_span, *li) else {
2690                            break;
2691                        };
2692                        let Some((page_lo, page_hi)) = page_span(span, i + 1 == plan.len()) else {
2693                            break;
2694                        };
2695                        if page_hi - page_lo > cap {
2696                            break;
2697                        }
2698                        selected = i + 1;
2699                        selected_span = Some((page_lo, page_hi));
2700                    }
2701                    Item::Gdn { first, run } => {
2702                        // Preserve a complete recurrent run whenever it can
2703                        // occupy a page on its own.  If the preceding items
2704                        // merely used the remaining cap, close that page and
2705                        // let the next q1 invocation retain the full run.
2706                        // Prefix-splitting is only for a run that genuinely
2707                        // cannot fit an empty page.
2708                        let mut whole = None;
2709                        for take in 1..=run.len() {
2710                            whole = add_layer_span(whole, *first + take - 1);
2711                            if whole.is_none() {
2712                                break;
2713                            }
2714                        }
2715                        let whole_fits_empty_page = whole
2716                            .and_then(|span| page_span(span, false))
2717                            .is_some_and(|(lo, hi)| hi - lo <= cap);
2718                        if whole_fits_empty_page {
2719                            let mut span = selected_span;
2720                            for take in 1..=run.len() {
2721                                let Some(next) = add_layer_span(span, *first + take - 1) else {
2722                                    break 'items;
2723                                };
2724                                span = Some(next);
2725                            }
2726                            let Some(span) = span else {
2727                                break;
2728                            };
2729                            let Some((page_lo, page_hi)) = page_span(span, i + 1 == plan.len())
2730                            else {
2731                                break;
2732                            };
2733                            if page_hi - page_lo > cap {
2734                                break;
2735                            }
2736                            selected = i + 1;
2737                            selected_span = Some((page_lo, page_hi));
2738                            continue;
2739                        }
2740                        if selected != 0 {
2741                            break;
2742                        }
2743                        let mut span = None;
2744                        let mut best: Option<(usize, (usize, usize))> = None;
2745                        for take in 1..=run.len() {
2746                            let Some(next) = add_layer_span(span, *first + take - 1) else {
2747                                break;
2748                            };
2749                            // A partial final run cannot encode the lm_head;
2750                            // only its complete form above may include it.
2751                            let Some((page_lo, page_hi)) = page_span(next, false) else {
2752                                break;
2753                            };
2754                            if page_hi - page_lo > cap {
2755                                break;
2756                            }
2757                            span = Some((page_lo, page_hi));
2758                            best = Some((take, (page_lo, page_hi)));
2759                        }
2760                        let Some((take, page)) = best else {
2761                            break;
2762                        };
2763                        selected = i + 1;
2764                        selected_span = Some(page);
2765                        if take != run.len() {
2766                            gdn_prefix = Some((i, take));
2767                            break 'items;
2768                        }
2769                    }
2770                }
2771            }
2772            if selected != 0 {
2773                if let Some((item, take)) = gdn_prefix {
2774                    match &mut plan[item] {
2775                        Item::Gdn { run, .. } => run.truncate(take),
2776                        Item::Attn { .. } => unreachable!("only a GDN run is splittable"),
2777                    }
2778                }
2779                let (page_lo, page_hi) = selected_span.expect("selected page span");
2780                tracing::info!(
2781                    page_start = page_lo,
2782                    page_end = page_hi,
2783                    page_mb = (page_hi - page_lo) / (1024 * 1024),
2784                    cap_mb = cap / (1024 * 1024),
2785                    graph_items = selected,
2786                    "native Metal MoE graph uses transient bounded weight page"
2787                );
2788                plan.truncate(selected);
2789                pager_span = Some((page_lo, page_hi));
2790            } else {
2791                tracing::warn!(
2792                    cap_mb = cap / (1024 * 1024),
2793                    "native Metal MoE pager declined: one graph item does not fit its safe page cap"
2794                );
2795            }
2796        }
2797        // A native MoE graph binds every WeightArena window to its jobs
2798        // kernels. On UMA, an mmap that already exceeds the driver's
2799        // recommended working set will therefore fail after admission, when
2800        // some recurrent/KV scratch has already been touched. Decline before
2801        // allocating/encoding the graph instead; the ordinary per-operation
2802        // route remains available and only materializes the needed window.
2803        // Do not apply this to dense graphs: they bind one projection at a
2804        // time and do not have the MoE jobs' all-window lifetime.
2805        if has_moe && needs_bounded_pager && pager_span.is_none() {
2806            tracing::info!(
2807                model_bytes,
2808                metal_working_set,
2809                "native Metal MoE graph declined before allocation"
2810            );
2811            self.note_graph_decline("metal block graph", MOE_WORKING_SET_REASON);
2812            if self.graph_head_required {
2813                self.fail_metal_graph(MOE_WORKING_SET_REASON);
2814            }
2815            return start;
2816        }
2817        let has_gdn = plan.iter().any(|it| matches!(it, Item::Gdn { .. }));
2818        let dev_attend = attend_contract
2819            && (self.head_dim <= 128
2820                || has_moe
2821                // A GDN hybrid attends on a quarter of its layers: the
2822                // hd>128 caution was measured on pure-dense models where
2823                // gqa_attend dominates, and on Qwen3.8-27B (hd 256, 48
2824                // GDN + 16 attn) the sandwich costs 2x the whole decode
2825                // (1.2 vs 2.21 tok/s measured before the arena fix).
2826                || (self.head_dim <= 256 && has_gdn)
2827                // Sliding-window layers bound most attends by the window:
2828                // Spark-X2.5-1.7B q4tp on the M4 decodes 67 tok/s
2829                // device-attended against 23 sandwiched (28 syncs/token).
2830                || (self.head_dim <= 256 && swa_graph)
2831                || attend_mode == "force"
2832                || attend_mode == "256");
2833        if !dev_attend {
2834            for it in &mut plan {
2835                if let Item::Attn { li, full_gpu, .. } = it {
2836                    // The hd>128 policy is about gqa_attend; an o1 layer
2837                    // attends through its own kernel set.
2838                    let keep_o1 = self.kv_cache.layers[*li].o1.is_some()
2839                        && std::env::var("CMF_O1_METAL").as_deref() == Ok("1");
2840                    if !keep_o1 {
2841                        *full_gpu = false;
2842                    }
2843                }
2844            }
2845        }
2846        if std::env::var("CMF_GRAPH_DBG").is_ok() {
2847            use std::sync::atomic::{AtomicBool, Ordering};
2848            static SAID: AtomicBool = AtomicBool::new(false);
2849            if !SAID.swap(true, Ordering::Relaxed) {
2850                let fg = plan
2851                    .iter()
2852                    .filter(|it| matches!(it, Item::Attn { full_gpu: true, .. }))
2853                    .count();
2854                let att = plan
2855                    .iter()
2856                    .filter(|it| matches!(it, Item::Attn { .. }))
2857                    .count();
2858                eprintln!(
2859                    "q1-graph: plan of {} items from layer {start} to {scan} | dev_attend={dev_attend} full_gpu {fg}/{att} | hd={} rd={} nkv={} nh={}",
2860                    plan.len(),
2861                    self.head_dim,
2862                    self.rotary_dim,
2863                    self.num_kv_heads,
2864                    self.num_heads,
2865                );
2866            }
2867        }
2868        let dims = GraphDims {
2869            hidden: self.hidden_size,
2870            eps: self.rms_eps as f32,
2871            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
2872        };
2873        // The outer `forward_layers_span` scope is one logical token.  This
2874        // guard starts at q1_graph_gpu entry and ends after all page readback,
2875        // so a multi-page token cannot be reported as several whole tokens.
2876        let mut pager_profile_page = pager_span.map(|(page_lo, page_hi)| {
2877            crate::gpu_metal::MoePagerPageScope::new(
2878                _mt0,
2879                position,
2880                start,
2881                page_lo,
2882                page_hi,
2883                // `pager_span` is selected only after a cap was admitted;
2884                // keep the profiler observational if that invariant is ever
2885                // loosened rather than introducing a new inference panic.
2886                pager_cap.unwrap_or(0),
2887            )
2888        });
2889        let graph_new = match pager_span {
2890            Some((page_lo, page_hi)) => TokenGraph::new_paged(&model, dims, h, page_lo, page_hi),
2891            None => TokenGraph::new(&model, dims, h),
2892        };
2893        let Some(mut graph) = graph_new else {
2894            if self.graph_head_required {
2895                self.fail_metal_graph("native TokenGraph allocation refused");
2896            }
2897            return start;
2898        };
2899        if swa_graph && self.head_dim > 128 {
2900            // Spark-X2.5 (hd 256, 4 Q heads per KV head): the GQA-shared
2901            // split-K attend reads each K/V row once for the group instead
2902            // of once per head plus the importance re-read — at depth 1000
2903            // on the M4, 59.5 tok/s against 50.0 with the per-head kernel
2904            // up to the default 512 (every sliding layer sits at <= 512).
2905            graph.set_attend_blk_from(64);
2906        }
2907        let gcfg = self.gdn_cfg.map(|cfg| GdnGpuCfg {
2908            nv: cfg.num_v_heads,
2909            nk: cfg.num_k_heads,
2910            dk: cfg.key_head_dim,
2911            dv: cfg.value_head_dim,
2912            kk: cfg.conv_kernel,
2913            hidden: self.hidden_size,
2914            inter: self.intermediate_size,
2915            c_dim: cfg.conv_dim(),
2916            eps: cfg.rms_eps as f32,
2917            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
2918        });
2919        // Validate the whole plan BEFORE encoding anything: after the
2920        // first sync a refused layer would leave the token
2921        // half-executed, so truncate to the provably encodable prefix.
2922        let mut valid = 0usize;
2923        let mut end = start;
2924        crate::gpu::stageprof(1, _mt0.elapsed()); // конец планирования
2925        if std::env::var("CMF_PLAN_DUMP").is_ok() {
2926            static ONCE: std::sync::Once = std::sync::Once::new();
2927            ONCE.call_once(|| {
2928                for it in &plan {
2929                    match it {
2930                        Item::Gdn { first, run } => {
2931                            eprintln!("plan: Gdn first={first} len={}", run.len())
2932                        }
2933                        Item::Attn { li, full_gpu, .. } => {
2934                            eprintln!("plan: Attn li={li} full_gpu={full_gpu}")
2935                        }
2936                    }
2937                }
2938            });
2939        }
2940        for item in &plan {
2941            let ok = match item {
2942                Item::Gdn { run, .. } => gcfg
2943                    .as_ref()
2944                    .map(|gc| run.iter().all(|l| graph.gdn_ok(l, gc)))
2945                    .unwrap_or(false),
2946                Item::Attn { l, .. } => graph.attn_ok(l),
2947            };
2948            if !ok {
2949                if block_diag {
2950                    eprintln!(
2951                        "block-graph: plan item {} ({}) failed graph preflight",
2952                        valid,
2953                        match item {
2954                            Item::Gdn { run, first } => format!("GDN run L{first}+{}", run.len()),
2955                            Item::Attn { li, .. } => format!("Attn L{li}"),
2956                        }
2957                    );
2958                }
2959                break;
2960            }
2961            valid += 1;
2962            end += match item {
2963                Item::Gdn { run, .. } => run.len(),
2964                Item::Attn { .. } => 1,
2965            };
2966        }
2967        plan.truncate(valid);
2968        if plan.is_empty() {
2969            if self.graph_head_required {
2970                self.fail_metal_graph("native graph preflight produced no valid items");
2971            }
2972            return start;
2973        }
2974
2975        if self.graph_head_required && (upto.is_some() || end != self.num_layers) {
2976            self.fail_metal_graph("fused-head NLL requires a complete 64-layer graph");
2977            return start;
2978        }
2979
2980        // Plain dense decode (every item a device-attended full-attention
2981        // layer with a dense FFN, no O(1) state): the only plan shape the
2982        // masked-nibble q4tp matvec and the concurrent layer encoder were
2983        // measured on (MiniCPM5-2B, Qwen3-0.6B on the M4). Hybrids, MoE and
2984        // o1 layers keep the historical serial path bit for bit.
2985        // Every projection must be ONE dispatch (q1t adds an overlay pass,
2986        // Prism q2tp a transform pass — dependent pairs a concurrent
2987        // encoder would race).
2988        let one_pass = |t: (usize, usize, usize)| {
2989            use cortiq_core::TensorDtype as D;
2990            matches!(
2991                model.tensors[t.0].dtype,
2992                D::Q4TiledP | D::Q4Tiled | D::Q4Block | D::Q8Row | D::Q8_2f | D::Q1 | D::Q1G
2993            )
2994        };
2995        let dense_fast = plan.iter().all(|it| match it {
2996            Item::Attn {
2997                l, li, full_gpu, ..
2998            } => {
2999                *full_gpu
3000                    && self.kv_cache.layers[*li].o1.is_none()
3001                    && [l.wq, l.wk, l.wv, l.wo].into_iter().all(one_pass)
3002                    && match l.ffn {
3003                        MetalFfn::Dense { gate, up, down, .. } => {
3004                            one_pass(gate) && one_pass(up) && one_pass(down)
3005                        }
3006                        _ => false,
3007                    }
3008            }
3009            Item::Gdn { .. } => false,
3010        });
3011        // MoE decode with every layer device-attended (Mellum2.1): the
3012        // routed experts' jobs ladder and the q8_2f attention projections
3013        // take their measured levers (`MOE_*`, `DENSE_Q8R4`).
3014        let moe_plan = !dense_fast
3015            && plan.iter().all(|it| match it {
3016                Item::Attn {
3017                    l, li, full_gpu, ..
3018                } => {
3019                    *full_gpu
3020                        && self.kv_cache.layers[*li].o1.is_none()
3021                        && matches!(l.ffn, MetalFfn::Moe(_) | MetalFfn::FlintMoe(_))
3022                }
3023                Item::Gdn { .. } => false,
3024            });
3025        let ab = crate::gpu_metal::dense_ab_arm().filter(|_| dense_fast || moe_plan);
3026        if block_diag {
3027            use std::sync::atomic::{AtomicBool, Ordering};
3028            static SAID_AB: AtomicBool = AtomicBool::new(false);
3029            if !SAID_AB.swap(true, Ordering::Relaxed) {
3030                eprintln!("q1-graph: dense_fast={dense_fast} moe_plan={moe_plan} ab={ab:?}");
3031            }
3032        }
3033        let _mv_fast = match ab {
3034            Some((bits, _)) => {
3035                graph.set_dense_concurrent_raw(bits & crate::gpu_metal::DENSE_CONC != 0);
3036                crate::gpu_metal::MvFastGuard::set_raw(bits)
3037            }
3038            None if moe_plan => {
3039                graph.set_dense_concurrent(
3040                    crate::gpu_metal::MOE_PLAN_BITS & crate::gpu_metal::DENSE_CONC != 0,
3041                );
3042                crate::gpu_metal::MvFastGuard::set_bits(crate::gpu_metal::MOE_PLAN_BITS)
3043            }
3044            None => {
3045                graph.set_dense_concurrent(dense_fast);
3046                // Spark-X2.5 q8_2f: the four-row q8_2f matvec decodes the
3047                // 1.7B at 40.5 tok/s on the M4 against 27.7 one-row.
3048                let q8r4 = if swa_graph {
3049                    crate::gpu_metal::DENSE_Q8R4
3050                } else {
3051                    0
3052                };
3053                crate::gpu_metal::MvFastGuard::set_bits(if dense_fast {
3054                    crate::gpu_metal::DENSE_MV | crate::gpu_metal::DENSE_FUSE | q8r4
3055                } else {
3056                    0
3057                })
3058            }
3059        };
3060
3061        // RoPE table and rotary width are per layer (`layer_inv_freq`,
3062        // `layer_geom`) inside the loop below.
3063        let pool = self.pool.clone();
3064        let (nh, nkv, hd, hs, eps) = (
3065            self.num_heads,
3066            self.num_kv_heads,
3067            self.head_dim,
3068            self.hidden_size,
3069            self.rms_eps,
3070        );
3071        let norm_style = self.norm_style;
3072        let gemma = norm_style == cortiq_core::NormStyle::Gemma;
3073        let want = self.gdn_cfg.map(|c| c.state_len()).unwrap_or(0);
3074        let kv_id = self.graph_kv_id;
3075        // GDN runs whose states await readback after the next sync
3076        // (device-attended layers add no sync, so several may stack).
3077        let mut pending: Vec<(usize, usize)> = Vec::new();
3078        // Device-attended layers: their K/V/imp are pulled from the
3079        // mirror after the final sync.
3080        let mut dev_attn: Vec<(usize, usize, usize)> = Vec::new();
3081        for item in &plan {
3082            let _xt0 = std::time::Instant::now();
3083            let _xkind: u32 = match item {
3084                Item::Gdn { .. } => 2,
3085                Item::Attn { .. } => 3,
3086            };
3087            // Looped Transformer: insert on-device norm at loop boundaries.
3088            if self.loop_final_norm {
3089                let item_start = match item {
3090                    Item::Gdn { first, .. } => *first,
3091                    Item::Attn { li, .. } => *li,
3092                };
3093                if item_start > start && self.is_loop_end(item_start - 1) {
3094                    graph.encode_loop_norm(&self.weights.final_norm);
3095                }
3096            }
3097            match item {
3098                Item::Gdn { run, first } => {
3099                    for l in &mut self.kv_cache.layers[*first..*first + run.len()] {
3100                        if l.linear_state.len() != want {
3101                            l.linear_state = vec![0f32; want];
3102                        }
3103                    }
3104                    let ro: Vec<&[f32]> = self.kv_cache.layers[*first..*first + run.len()]
3105                        .iter()
3106                        .map(|l| l.linear_state.as_slice())
3107                        .collect();
3108                    let _ig = std::time::Instant::now();
3109                    if !graph.encode_gdn_run(run, &ro, gcfg.as_ref().unwrap()) {
3110                        // Unreachable: the plan was validated above.
3111                        tracing::error!("q1 graph: GDN run refused after validation");
3112                        return start;
3113                    }
3114                    // Early commit: the GPU starts the run while the
3115                    // CPU encodes the next layer (nothing to wait on).
3116                    graph.commit_kind = 2;
3117                    graph.commit();
3118                    crate::gpu::stageprof(0, _ig.elapsed());
3119                    pending.push((*first, run.len()));
3120                }
3121                Item::Attn {
3122                    l,
3123                    li,
3124                    q_norm,
3125                    k_norm,
3126                    output_gate,
3127                    proj_gate,
3128                    head_gate_w,
3129                    bias,
3130                    full_gpu,
3131                } => {
3132                    let _ia = std::time::Instant::now();
3133                    // This layer's attention geometry: its window, RoPE
3134                    // table and rotary width (Spark-X2.5 interleaves
3135                    // 512-window layers rotating all dims at θ 1e4 with
3136                    // full layers rotating a quarter at θ 5e6). Every model
3137                    // without sliding layers reads the global ones here.
3138                    let inv_freq_l = self.layer_inv_freq(*li);
3139                    let rd_l = self.layer_geom(*li).2;
3140                    let window_l = self.layer_window(*li);
3141                    let head_gate_w = *head_gate_w;
3142                    // This layer's KV heads and head width: Gemma-4's global
3143                    // layers (one 512-wide KV head) differ from the base.
3144                    let (nkv, hd) = if gemma4 {
3145                        let (a, b, _) = self.layer_geom(*li);
3146                        (a, b)
3147                    } else {
3148                        (nkv, hd)
3149                    };
3150                    // ── Fully device-resident attention: no sync at all.
3151                    if *full_gpu {
3152                        let cache = &self.kv_cache.layers[*li];
3153                        let o1p = if cache.o1.is_some() {
3154                            match cache.o1_views() {
3155                                Some(views) => Some(crate::gpu::O1AttnParams {
3156                                    views,
3157                                    epoch: self.o1_epoch,
3158                                }),
3159                                // Sealed state gone mid-run: sandwich.
3160                                None => None,
3161                            }
3162                        } else {
3163                            None
3164                        };
3165                        let o1_layer = cache.o1.is_some();
3166                        if o1_layer && o1p.is_none() {
3167                            // fall to the sandwich (CPU o1 step)
3168                        }
3169                        let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
3170                        let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
3171                        let cpu_stored = if o1_layer { 0 } else { cpu_k[0].len() / hd };
3172                        // A trimmed tail always holds the window the
3173                        // device attend reads (`first = rows + 1 − w`).
3174                        debug_assert!(
3175                            cache.base() == 0 || window_l.is_some_and(|w| cpu_stored + 1 >= w)
3176                        );
3177                        let p = crate::gpu::AttnDeviceParams {
3178                            kv_id,
3179                            layer: *li,
3180                            nh,
3181                            nkv,
3182                            hd,
3183                            rd: rd_l,
3184                            position,
3185                            scale: self.attn_scale,
3186                            eps: eps as f32,
3187                            gemma,
3188                            late_qk_norm: self.qk_norm_after_rope,
3189                            output_gate: *output_gate,
3190                            q_norm: *q_norm,
3191                            k_norm: *k_norm,
3192                            inv_freq: &inv_freq_l,
3193                            rope_scale: self.layer_rope_scale(*li),
3194                            cpu_k,
3195                            cpu_v,
3196                            cpu_stored,
3197                            cpu_gen: cache.generation(),
3198                            o1: o1p,
3199                            window: window_l,
3200                            softmax_sink: cache.sinks.as_deref(),
3201                            head_gate: head_gate_w,
3202                            v_norm: self.attn_v_norm,
3203                        };
3204                        let o1_bad = o1_layer && p.o1.is_none();
3205                        if !o1_bad && graph.attn_device_ok(l, &p) && graph.encode_attn_device(l, &p)
3206                        {
3207                            // o1 layers leave no mirror row to pull.
3208                            if p.o1.is_none() {
3209                                dev_attn.push((*li, nkv, hd));
3210                            }
3211                            graph.commit_kind = 3;
3212                            graph.commit();
3213                            // The footer below is skipped by `continue`:
3214                            // account the device-attn item here or its
3215                            // cost hides from the stage profile entirely.
3216                            crate::gpu::stageprof(_xkind, _xt0.elapsed());
3217                            continue;
3218                        }
3219                        // Mirror refused (nothing encoded) → sandwich.
3220                    }
3221                    graph.encode_attn_prefix(l);
3222                    if let Err(err) = graph.sync_checked() {
3223                        self.fail_metal_graph(&err);
3224                        return start;
3225                    }
3226                    if !pending.is_empty() {
3227                        let idxs: Vec<usize> =
3228                            pending.drain(..).flat_map(|(f, n)| f..f + n).collect();
3229                        let mut outs: Vec<&mut [f32]> = self
3230                            .kv_cache
3231                            .layers
3232                            .iter_mut()
3233                            .enumerate()
3234                            .filter(|(i, _)| idxs.binary_search(i).is_ok())
3235                            .map(|(_, s)| s.linear_state.as_mut_slice())
3236                            .collect();
3237                        graph.read_states(&mut outs);
3238                    }
3239                    let mut q_raw = attention::take_buf(l.wq.1);
3240                    let mut k = attention::take_buf(l.wk.1);
3241                    let mut v = attention::take_buf(l.wv.1);
3242                    graph.read_qkv(&mut q_raw, &mut k, &mut v);
3243                    // Projected output gate: g = G·norm(h) on the host, off
3244                    // the normed input the prefix left on the device.
3245                    let mut gate_raw = proj_gate.map(|(gp, _)| {
3246                        let mut normed = attention::take_buf(hs);
3247                        graph.read_normed(&mut normed);
3248                        let mut raw = attention::take_buf(gp.rows());
3249                        gp.matvec(&normed, &mut raw, pool.as_deref());
3250                        attention::recycle_buf(&mut normed);
3251                        raw
3252                    });
3253                    let cfg = QwenAttnCfg {
3254                        num_heads: nh,
3255                        num_kv_heads: nkv,
3256                        head_dim: hd,
3257                        hidden_size: hs,
3258                        position,
3259                        inv_freq: &inv_freq_l,
3260                        rotary_dim: rd_l,
3261                        scale: self.attn_scale,
3262                        softcap: self.attn_softcap,
3263                        window: window_l,
3264                        // Gemma-4 only (the front gate refuses V norm
3265                        // otherwise).
3266                        v_norm: self.attn_v_norm,
3267                        qk_norm_after_rope: self.qk_norm_after_rope,
3268                        gate_sigmoid: self.proj_gate_sigmoid,
3269                        q_norm: *q_norm,
3270                        k_norm: *k_norm,
3271                        output_gate: *output_gate,
3272                        softplus_gate: None,
3273                        rope_scale: self.layer_rope_scale(*li),
3274                        bias: *bias,
3275                        rms_eps: eps,
3276                        norm_style,
3277                        pool: pool.as_deref(),
3278                        v_head_dim: hd,
3279                    };
3280                    // CMF_ATTN_ORACLE=1: diff the device attend against
3281                    // this CPU attend on identical inputs (bring-up).
3282                    let oracle = std::env::var("CMF_ATTN_ORACLE").as_deref() == Ok("1")
3283                        || std::env::var("CMF_ATTN_DUMP").is_ok();
3284                    let _ = full_gpu;
3285                    let oracle_in = oracle.then(|| (q_raw.clone(), k.clone(), v.clone()));
3286                    let mut ao = attention::qwen_attention_core(
3287                        q_raw,
3288                        k,
3289                        v,
3290                        &mut self.kv_cache.layers[*li],
3291                        &cfg,
3292                    );
3293                    // CMF_ATTN_DUMP=<dir>: this token's rope'd Q and the layer's whole
3294                    // K/V cache as raw f32 (offline attention-statistics probes:
3295                    // block bounds, mass concentration). Needs CMF_GPU_ATTEND=0.
3296                    if let Ok(dir) = std::env::var("CMF_ATTN_DUMP") {
3297                        if let Some((qr0, k0, v0)) = oracle_in.clone() {
3298                            let (cq, _cg, _ck, _cv) =
3299                                attention::finish_projection_debug(qr0, k0, v0, &cfg, position);
3300                            let cache = &self.kv_cache.layers[*li];
3301                            let n = cache.head_keys(0).len() / hd;
3302                            let mut bytes: Vec<u8> = Vec::new();
3303                            for v in [nh as u32, nkv as u32, hd as u32, n as u32, position as u32] {
3304                                bytes.extend_from_slice(&v.to_le_bytes());
3305                            }
3306                            for v in &cq {
3307                                bytes.extend_from_slice(&v.to_le_bytes());
3308                            }
3309                            for g in 0..nkv {
3310                                for v in cache.head_keys(g) {
3311                                    bytes.extend_from_slice(&v.to_le_bytes());
3312                                }
3313                            }
3314                            for g in 0..nkv {
3315                                for v in cache.head_values(g) {
3316                                    bytes.extend_from_slice(&v.to_le_bytes());
3317                                }
3318                            }
3319                            let _ =
3320                                std::fs::write(format!("{dir}/L{li}_pos{position}.bin"), &bytes);
3321                        }
3322                    }
3323                    if let Some((qr0, k0, v0)) =
3324                        oracle_in.filter(|_| std::env::var("CMF_ATTN_ORACLE").as_deref() == Ok("1"))
3325                    {
3326                        let (cq, _cg, ck, cv) =
3327                            attention::finish_projection_debug(qr0, k0, v0, &cfg, position);
3328                        let mut h_now = vec![0f32; hs];
3329                        graph.read_h(&mut h_now);
3330                        let cache = &self.kv_cache.layers[*li];
3331                        let n_after = cache.head_keys(0).len() / hd;
3332                        // A sealed O(1) cache may have no dense current-row
3333                        // entry. The oracle is a debug probe, so let it see
3334                        // zero stored exact rows instead of underflowing.
3335                        let stored = n_after.saturating_sub(1);
3336                        let cpu_k: Vec<&[f32]> = (0..nkv)
3337                            .map(|g| &cache.head_keys(g)[..stored * hd])
3338                            .collect();
3339                        let cpu_v: Vec<&[f32]> = (0..nkv)
3340                            .map(|g| &cache.head_values(g)[..stored * hd])
3341                            .collect();
3342                        let p = crate::gpu::AttnDeviceParams {
3343                            kv_id,
3344                            layer: *li,
3345                            nh,
3346                            nkv,
3347                            hd,
3348                            // The layer's own geometry, as the CPU attend
3349                            // above used it (the projected gate is applied
3350                            // after this probe on both sides).
3351                            rd: rd_l,
3352                            position,
3353                            scale: self.attn_scale,
3354                            eps: eps as f32,
3355                            gemma,
3356                            late_qk_norm: self.qk_norm_after_rope,
3357                            output_gate: *output_gate,
3358                            q_norm: *q_norm,
3359                            k_norm: *k_norm,
3360                            inv_freq: &inv_freq_l,
3361                            rope_scale: self.layer_rope_scale(*li),
3362                            cpu_k,
3363                            cpu_v,
3364                            cpu_stored: stored,
3365                            cpu_gen: cache.generation(),
3366                            o1: None,
3367                            window: window_l,
3368                            softmax_sink: cache.sinks.as_deref(),
3369                            head_gate: None,
3370                            v_norm: self.attn_v_norm,
3371                        };
3372                        if let Some((dq, dk, dv, dao)) = graph.debug_attn_device(l, &p, &h_now) {
3373                            let md = |a: &[f32], b: &[f32]| {
3374                                a.iter().zip(b).fold(0f32, |m, (x, y)| m.max((x - y).abs()))
3375                            };
3376                            let nn = |a: &[f32]| a.iter().map(|x| x * x).sum::<f32>().sqrt();
3377                            eprintln!(
3378                                "attn-oracle L{li} pos {position}: |q| {:.2} max|dq| {:.4} | |k| {:.2} max|dk| {:.4} | |v| {:.2} max|dv| {:.4} | |ao| {:.2} max|dao| {:.4}",
3379                                nn(&cq),
3380                                md(&cq, &dq),
3381                                nn(&ck),
3382                                md(&ck, &dk),
3383                                nn(&cv),
3384                                md(&cv, &dv),
3385                                nn(&ao),
3386                                md(&ao, &dao)
3387                            );
3388                        } else {
3389                            eprintln!("attn-oracle L{li}: device probe declined");
3390                        }
3391                    }
3392                    if let (Some(raw), Some((_, per_head))) = (gate_raw.as_deref(), *proj_gate) {
3393                        // V is as wide as the head (the front gate), so ao
3394                        // is nh·hd here, as in `qwen_attention`.
3395                        attention::apply_projected_gate(
3396                            &mut ao,
3397                            raw,
3398                            per_head,
3399                            hd,
3400                            self.proj_gate_sigmoid,
3401                        );
3402                    }
3403                    if let Some(mut raw) = gate_raw.take() {
3404                        attention::recycle_buf(&mut raw);
3405                    }
3406                    graph.encode_attn_suffix(l, &ao);
3407                    // Early commit: the GPU starts O+FFN while the CPU
3408                    // encodes the following GDN run / attention prefix.
3409                    graph.commit();
3410                    attention::recycle_buf(&mut ao);
3411                }
3412            }
3413
3414            crate::gpu::stageprof(_xkind, _xt0.elapsed());
3415        }
3416        // Ride the final norm + lm_head in the same command buffer when
3417        // this run reaches the model's end and the caller wants logits:
3418        // the separate per-op lm_head submit (a full round trip) folds
3419        // into the sync that already happens here.
3420        let mut lm_rows = None;
3421        if self.graph_want_logits
3422            && upto.is_none()
3423            && end == self.num_layers
3424            && std::env::var("CMF_GPU_LMHEAD")
3425                .map(|v| v != "0")
3426                .unwrap_or(true)
3427        {
3428            if let Some(lm) = self.weights.lm_head.metal_graph_parts() {
3429                if graph.lm_head_ok(lm) {
3430                    graph.encode_lm_head(&self.weights.final_norm, lm);
3431                    lm_rows = Some(lm.1);
3432                }
3433            }
3434        }
3435        if self.graph_head_required && lm_rows.is_none() {
3436            METAL_GRAPH_HEAD_MISS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3437            self.fail_metal_graph("fused graph head was requested but not encodable");
3438            return start;
3439        }
3440        let _sy0 = std::time::Instant::now();
3441        if let Err(err) = graph.sync_checked() {
3442            if let Some(profile) = pager_profile_page.as_mut() {
3443                profile.finish(start, graph.pager_page_stats(), "sync-error");
3444            }
3445            self.fail_metal_graph(&err);
3446            return start;
3447        }
3448        let _rs0 = std::time::Instant::now();
3449        if !pending.is_empty() {
3450            let idxs: Vec<usize> = pending.drain(..).flat_map(|(f, n)| f..f + n).collect();
3451            let mut outs: Vec<&mut [f32]> = self
3452                .kv_cache
3453                .layers
3454                .iter_mut()
3455                .enumerate()
3456                .filter(|(i, _)| idxs.binary_search(i).is_ok())
3457                .map(|(_, s)| s.linear_state.as_mut_slice())
3458                .collect();
3459            graph.read_states(&mut outs);
3460        }
3461        if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() == Ok("1") {
3462            use std::sync::atomic::{AtomicU64, Ordering};
3463            static SY: AtomicU64 = AtomicU64::new(0);
3464            static RS: AtomicU64 = AtomicU64::new(0);
3465            static N: AtomicU64 = AtomicU64::new(0);
3466            SY.fetch_add((_rs0 - _sy0).as_nanos() as u64, Ordering::Relaxed);
3467            RS.fetch_add(_rs0.elapsed().as_nanos() as u64, Ordering::Relaxed);
3468            let n = N.fetch_add(1, Ordering::Relaxed) + 1;
3469            if n % 100 == 0 {
3470                eprintln!(
3471                    "postprof: sync-wait {:.1} ms/ток | read_states {:.1} ms/ток ({n})",
3472                    SY.load(Ordering::Relaxed) as f64 / n as f64 / 1e6,
3473                    RS.load(Ordering::Relaxed) as f64 / n as f64 / 1e6
3474                );
3475            }
3476        }
3477        if let Some(rows) = lm_rows {
3478            crate::gpu::hostprof_encode_done(_mt0);
3479            let mut lg = attention::take_buf(rows.min(self.vocab_size));
3480            graph.read_logits(&mut lg);
3481            crate::gpu::hostprof_total(_mt0);
3482            lg.resize(self.vocab_size, 0.0);
3483            if let Some(c) = self.final_softcap {
3484                softcap_in_place(&mut lg, c, self.pool.as_deref());
3485            }
3486            self.graph_logits = Some(lg);
3487        }
3488        graph.read_h(h);
3489        if self.graph_head_required && self.graph_logits.is_none() {
3490            METAL_GRAPH_HEAD_MISS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3491            self.fail_metal_graph("fused graph head completed without logits readback");
3492            return start;
3493        }
3494        METAL_GRAPH_TOK_OK.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3495        METAL_GRAPH_LAYERS.fetch_add(
3496            end.saturating_sub(start) as u64,
3497            std::sync::atomic::Ordering::Relaxed,
3498        );
3499        if self.graph_head_required {
3500            METAL_GRAPH_HEAD_OK.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3501        }
3502        // Device-attended layers: replay the CPU bookkeeping — append
3503        // the mirror's new K/V row (rope'd on the GPU) into the owner
3504        // cache, then bank this token's attention-importance mass.
3505        for (li, nkv, hd) in dev_attn {
3506            let mut krow = attention::take_buf(nkv * hd);
3507            let mut vrow = attention::take_buf(nkv * hd);
3508            if crate::gpu::kv_mirror_read_last(kv_id, li, nkv, hd, &mut krow, &mut vrow) {
3509                let cache = &mut self.kv_cache.layers[li];
3510                cache.append(&krow, &vrow, &[]);
3511                let n = cache.seq_len;
3512                let mut imp = attention::take_buf(n);
3513                crate::gpu::kv_mirror_take_imp(kv_id, li, &mut imp);
3514                cache.accumulate_imp(&imp);
3515                attention::recycle_buf(&mut imp);
3516            }
3517            attention::recycle_buf(&mut krow);
3518            attention::recycle_buf(&mut vrow);
3519        }
3520        if let Some(profile) = pager_profile_page.as_mut() {
3521            profile.finish(end, graph.pager_page_stats(), "page-complete");
3522        }
3523        if let Some((_, arm)) = ab {
3524            crate::gpu_metal::dense_ab_record(arm, _mt0.elapsed());
3525        }
3526        end
3527    }
3528
3529    pub fn new(
3530        tokenizer: Tokenizer,
3531        weights: PipelineWeights,
3532        hidden_size: usize,
3533        intermediate_size: usize,
3534        num_heads: usize,
3535        num_kv_heads: usize,
3536        head_dim: usize,
3537        num_layers: usize,
3538        physical_layers: usize,
3539        loop_final_norm: bool,
3540        vocab_size: usize,
3541        rms_eps: f64,
3542        rope_base: f32,
3543        norm_style: NormStyle,
3544        max_seq_len: usize,
3545        sampler_config: SamplerConfig,
3546    ) -> Self {
3547        let rng = match sampler_config.seed {
3548            Some(s) => SplitMix64::new(s),
3549            None => SplitMix64::from_entropy(),
3550        };
3551        let inv_freq = std::sync::Arc::new(attention::rope_inv_freq(head_dim, rope_base));
3552        let pool = Pool::from_env();
3553        if let Some(p) = &pool {
3554            tracing::info!("worker pool: {} threads", p.n_workers());
3555            // Keep the workers on the socket that holds the weights.
3556            if let Some(model) = weights
3557                .lm_head
3558                .model_arc()
3559                .or_else(|| weights.embed_tokens.model_arc())
3560            {
3561                let regions: Vec<&[u8]> =
3562                    model.tensors.iter().map(|t| model.entry_bytes(t)).collect();
3563                p.bind_numa(&regions);
3564            }
3565        }
3566        Self {
3567            gpu_plan: None,
3568            tokenizer: std::sync::Arc::new(tokenizer),
3569            kv_cache: KvCache::new(num_layers, num_kv_heads, head_dim, max_seq_len),
3570            sampler_config,
3571            weights,
3572            hidden_size,
3573            intermediate_size,
3574            num_heads,
3575            num_kv_heads,
3576            head_dim,
3577            num_layers,
3578            physical_layers,
3579            loop_final_norm,
3580            vocab_size,
3581            rms_eps,
3582            rope_base,
3583            norm_style,
3584            rotary_dim: head_dim,
3585            attention_heads_per_layer: None,
3586            kv_heads_per_layer: None,
3587            v_head_dim: None,
3588            layer_dump: std::env::var_os("CMF_LAYER_DUMP")
3589                .filter(|v| !v.is_empty())
3590                .map(std::path::PathBuf::from),
3591            graph_declines: std::cell::RefCell::new(Vec::new()),
3592            mimo_moe: Default::default(),
3593            minicpm_tail: Default::default(),
3594            vmf_cfg: None,
3595            gdn_cfg: None,
3596            kda_cfg: None,
3597            g3n: None,
3598            g4e: None,
3599            dsv4: None,
3600            dsv41: None,
3601            dsv41_vision: None,
3602            dsv41_prefill: None,
3603            qwen4_exp: None,
3604            dsv4_mtp: Vec::new(),
3605            dspark: None,
3606            dspark_pending: Vec::new(),
3607            dspark_hist: Vec::new(),
3608            dspark_real: Vec::new(),
3609            dspark_trunk_picks: Vec::new(),
3610            dspark_exp: Vec::new(),
3611            dspark_draft_ns: 0,
3612            m3_winners: Vec::new(),
3613            m3_counts: Vec::new(),
3614            m3_n_exp: 0,
3615            m3_tokens: 0,
3616            m3_prewarmed: false,
3617            logit_multiplier: None,
3618            cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
3619            graph_failed: std::sync::atomic::AtomicBool::new(false),
3620            kv_history: Vec::new(),
3621            kv_history_device: false,
3622            short_conv_cfg: None,
3623            mtp: None,
3624            mimo_mtp: None,
3625            verify_exact_moe: false,
3626            speculative: std::env::var("CMF_MTP").map(|v| v != "0").unwrap_or(true),
3627            ignore_eos: false,
3628            draft_full_streak: 0,
3629            spec_k_adapt: None,
3630            spec_acc_ewma: 0.7,
3631            rng,
3632            sampler_scratch: SamplerScratch::default(),
3633            spec_forced: None,
3634            spec_q: Vec::new(),
3635            spec_p: Vec::new(),
3636            spec_res: Vec::new(),
3637            spec_qs: Vec::new(),
3638            spec_ps: Vec::new(),
3639            spec_ress: Vec::new(),
3640            mtp_graph_mode: None,
3641            #[cfg(target_os = "macos")]
3642            metal_verify: None,
3643            inv_freq,
3644            ws: ForwardScratch::new(hidden_size),
3645            pool,
3646            model: None,
3647            dyn_force_f32: false,
3648            dyn_skill_layers: Vec::new(),
3649            dyn_active: None,
3650            dyn_blend_loaded: false,
3651            dyn_phi_layer: None,
3652            dyn_phi_ema: Vec::new(),
3653            dyn_phi_seen: 0,
3654            dyn_router: None,
3655            o1_cfg: None,
3656            o1_epoch: 0,
3657            o1_flags: Vec::new(),
3658            trace: false,
3659            calib_temp: 1.0,
3660            confidence_on: true,
3661            embed_multiplier: 1.0,
3662            attn_scale: 1.0 / (head_dim as f32).sqrt(),
3663            swa: None,
3664            swa_trim: None,
3665            sliding_layers: None,
3666            no_rope_layers: None,
3667            anchor_core: None,
3668            bounded_rope: None,
3669            kv_prefix: KvPrefix::default(),
3670            last_prefill_tokens: 0,
3671            inv_freq_local: None,
3672            rotary_dim_local: None,
3673            rope_scale: 1.0,
3674            rope_scale_local: 1.0,
3675            global_attn: None,
3676            inv_freq_global: None,
3677            attn_v_norm: false,
3678            qk_norm_after_rope: false,
3679            proj_gate_sigmoid: false,
3680            final_softcap: None,
3681            head_clusters: None,
3682            attn_softcap: 0.0,
3683            graph_want_logits: false,
3684            graph_head_required: false,
3685            graph_logits: None,
3686            embryo_graph: None,
3687            graph_refused: std::sync::atomic::AtomicBool::new(false),
3688            graph_kv_id: {
3689                static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
3690                NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
3691            },
3692            #[cfg(test)]
3693            nll_test_fail_at: None,
3694            #[cfg(test)]
3695            nll_test_force_serial: false,
3696        }
3697    }
3698
3699    /// Enable/disable per-layer O(1) Nyström attention. Only Full
3700    /// layers are eligible (a linear layer keeps its own operator).
3701    /// Applies to generation (`generate*`/`forward_ids`): the prompt
3702    /// pass stays exact, then the state seals after prefill or at the
3703    /// deferred skeleton-safe boundary for short prompts; decode runs on
3704    /// the O(1) state. Teacher-forced scoring (`ppl_ids`) intentionally
3705    /// stays exact.
3706    pub fn set_o1(&mut self, cfg: Option<crate::nystrom::O1Cfg>) {
3707        if let Err(e) = self.try_set_o1(cfg) {
3708            tracing::error!("{e}");
3709        }
3710    }
3711
3712    /// True when the file carries a native bounded anchor
3713    /// (`arch.anchor_core`): its state is a fixed record the header
3714    /// fixes, and the post-hoc O(1) override is meaningless on it.
3715    pub fn bounded_native(&self) -> bool {
3716        self.anchor_core.is_some()
3717    }
3718
3719    /// Bytes the resident device graph holds for this pipeline's sequence:
3720    /// `(recurrent state, anchor KV/ring)`; None on the host path.
3721    pub fn device_state_bytes(&self) -> Option<(u64, u64)> {
3722        crate::gpu::embryo_device_state_bytes(self.graph_kv_id)
3723    }
3724
3725    /// Why an O(1) override is refused on this pipeline, if it is.
3726    pub fn o1_refusal(&self) -> Option<String> {
3727        self.anchor_core.as_ref().map(|ac| {
3728            format!(
3729                "--o1 / CMF_O1 refused: the anchor is native bounded \
3730                 (anchor_core kind={} window={} sink={}); the file's operator \
3731                 is executed as-is and no post-hoc Nyström overlay applies",
3732                ac.kind, ac.window, ac.sink
3733            )
3734        })
3735    }
3736
3737    /// `set_o1` that reports the refusal instead of logging it.
3738    pub fn try_set_o1(&mut self, cfg: Option<crate::nystrom::O1Cfg>) -> Result<(), String> {
3739        if let Some(c) = &cfg {
3740            if let Some(why) = self.o1_refusal() {
3741                self.o1_flags = Vec::new();
3742                self.o1_cfg = None;
3743                return Err(why);
3744            }
3745            if crate::nystrom::o1_deferred_boundary(c.w, c.sink).is_none() {
3746                self.o1_flags.clear();
3747                self.o1_cfg = None;
3748                return Err(format!(
3749                    "o1 disabled: w + sink + slack + 1 overflows usize (w={}, sink={})",
3750                    c.w, c.sink
3751                ));
3752            }
3753        }
3754        self.o1_flags = match &cfg {
3755            Some(c) => {
3756                let mut flags = c.layer_flags(self.num_layers);
3757                for (li, f) in flags.iter_mut().enumerate() {
3758                    // The Nyström state replaces a full-context plain
3759                    // softmax: a sliding window or a learned sink is not
3760                    // something it can represent, and a V narrower than
3761                    // the head is not what its streaming state stores.
3762                    // Those layers keep exact cache attention.
3763                    if *f
3764                        && (!matches!(
3765                            self.weights.layers[self.phys_layer(li)].attn,
3766                            AttnKind::Full { .. }
3767                        ) || self.layer_window(li).is_some()
3768                            || self.kv_cache.layers[li].sinks.is_some()
3769                            || self.layer_v_dim(li) != self.layer_geom(li).1)
3770                    {
3771                        *f = false;
3772                    }
3773                }
3774                flags
3775            }
3776            None => Vec::new(),
3777        };
3778        if let Some(c) = &cfg {
3779            let n = self.o1_flags.iter().filter(|&&f| f).count();
3780            tracing::info!(
3781                "o1 nystrom attention: {n}/{} layer(s), m={} w={} sink={} rect={:?}",
3782                self.num_layers,
3783                c.m,
3784                c.w,
3785                c.sink,
3786                c.rect
3787            );
3788        }
3789        self.o1_cfg = cfg;
3790        Ok(())
3791    }
3792
3793    /// Install the file's bounded anchor: one fixed-size ring per
3794    /// `AttnKind::Bounded` layer (from the header, not per prompt) and
3795    /// the shared relative-rotation table. Must run after the RoPE setup
3796    /// (`set_rotary`, YaRN) so the table is built from the final
3797    /// `inv_freq`.
3798    pub fn install_bounded(&mut self, cfg: &cortiq_core::AnchorCoreConfig) -> Result<(), String> {
3799        if !cortiq_core::AnchorCoreConfig::KINDS.contains(&cfg.kind.as_str()) {
3800            return Err(format!(
3801                "anchor_core kind '{}' is not executable by this runtime",
3802                cfg.kind
3803            ));
3804        }
3805        if cfg.window == 0 {
3806            return Err("anchor_core.window must be >= 1".into());
3807        }
3808        let mut n = 0usize;
3809        for li in 0..self.num_layers {
3810            let pl = self.phys_layer(li);
3811            if let AttnKind::Bounded(w) = &self.weights.layers[pl].attn {
3812                if w.window != cfg.window || w.sink != cfg.sink {
3813                    return Err(format!(
3814                        "layer {li}: bounded weights (window {} sink {}) disagree with \
3815                         anchor_core (window {} sink {})",
3816                        w.window, w.sink, cfg.window, cfg.sink
3817                    ));
3818                }
3819                self.kv_cache.layers[li].install_bounded(cfg.window);
3820                n += 1;
3821            }
3822        }
3823        if n == 0 {
3824            return Err("anchor_core is present but no layer executes it".into());
3825        }
3826        let rope = crate::bounded::BoundedRope::new(cfg.window, &self.inv_freq, self.rope_scale);
3827        self.bounded_rope = Some(std::sync::Arc::new(rope));
3828        self.anchor_core = Some(cfg.clone());
3829        self.embryo_graph = None;
3830        tracing::info!(
3831            "bounded anchor {}: {n} layer(s), window {} sink {} — {} B of ring per layer",
3832            cfg.kind,
3833            cfg.window,
3834            cfg.sink,
3835            self.kv_cache
3836                .layers
3837                .iter()
3838                .map(|l| l.bounded_state_bytes())
3839                .max()
3840                .unwrap_or(0)
3841        );
3842        Ok(())
3843    }
3844
3845    /// Tag every layer's cache with its wire record kind and the model's
3846    /// operator identity (hash64 of `linear_core_identity` JSON) so the
3847    /// versioned state wire refuses a peer holding another operator.
3848    pub fn install_wire_identity(&mut self, identity: u64) {
3849        for li in 0..self.kv_cache.layers.len() {
3850            let pl = self.phys_layer(li);
3851            let kind = match self.weights.layers.get(pl).map(|l| &l.attn) {
3852                Some(AttnKind::Bounded(_)) => crate::kv_cache::WireKind::Bounded,
3853                Some(AttnKind::Linear(_))
3854                | Some(AttnKind::LinearGdn(_))
3855                | Some(AttnKind::ShortConv(_))
3856                | Some(AttnKind::Kda(_)) => crate::kv_cache::WireKind::Linear,
3857                _ => crate::kv_cache::WireKind::Full,
3858            };
3859            let l = &mut self.kv_cache.layers[li];
3860            l.wire_kind = kind;
3861            l.wire_identity = identity;
3862            // A per-layer geometry (`set_attn_geometry`, Gemma's global
3863            // heads) rebuilds a layer cache with index 0: re-tag it.
3864            l.wire_layer = li as u32;
3865        }
3866    }
3867
3868    /// Forget the reuse keys (legacy `kv_history` and the bounded prefix).
3869    pub fn clear_history(&mut self) {
3870        self.kv_history.clear();
3871        self.kv_history_device = false;
3872        self.kv_prefix.clear();
3873    }
3874
3875    /// Did THIS pipeline's token graph refuse for a structural reason?
3876    /// (Per pipeline: another lane's refusal, or a new pipeline of the
3877    /// same model, never changes it.)
3878    pub fn graph_refused(&self) -> bool {
3879        self.graph_refused
3880            .load(std::sync::atomic::Ordering::Relaxed)
3881    }
3882
3883    /// Remember a structural refusal of this pipeline's token graph.
3884    pub fn mark_graph_refused(&self) {
3885        if !self
3886            .graph_refused
3887            .swap(true, std::sync::atomic::Ordering::Relaxed)
3888        {
3889            tracing::info!(
3890                "token graph: unsupported for this pipeline (seq {}) — not retrying",
3891                self.graph_kv_id
3892            );
3893        }
3894    }
3895
3896    /// Position the resident Embryo graph holds for this pipeline's
3897    /// sequence (`Some(next position)`), `None` when the device holds no
3898    /// image of it (host-owned sequence, or none started).
3899    pub fn device_sequence_position(&self) -> Option<usize> {
3900        crate::gpu::embryo_device_next_position(self.graph_kv_id)
3901    }
3902
3903    /// Is the sequence this pipeline's reuse key describes owned by the
3904    /// device path it would take now? A prefix recorded on the resident
3905    /// graph continues only there (at exactly `n`), a host prefix only on
3906    /// the host; any mismatch means the next turn re-prefills from zero.
3907    fn prefix_owner_matches(&self, n: usize, recorded_on_device: bool) -> bool {
3908        let dev = self.device_sequence_position();
3909        if recorded_on_device {
3910            dev == Some(n) && self.embryo_resident_wanted()
3911        } else {
3912            dev.is_none()
3913        }
3914    }
3915
3916    /// The weights under the sequence changed (a real skill switch): every
3917    /// cached state was computed by other weights. Clear the host KV /
3918    /// ring / recurrent state AND the reuse keys — a surviving `kv_prefix`
3919    /// would let the next turn "extend" a prefix the new weights never
3920    /// saw — drop the packed resident graph (it holds the old FFN
3921    /// tensors; the next build packs the live ones under a fresh id) and
3922    /// reset its device sequence.
3923    pub(crate) fn invalidate_for_weight_change(&mut self) {
3924        self.clear_sequence_state();
3925        self.embryo_graph = None;
3926    }
3927
3928    /// Prompt positions the cache already holds when `input_ids`
3929    /// strictly EXTENDS the consumed prefix (0 otherwise). Bounded-native
3930    /// models answer from the fixed-size `kv_prefix` record; everything
3931    /// else from the legacy `kv_history` vector (which the network split
3932    /// also reads and writes).
3933    fn cached_prefix_len(&self, input_ids: &[u32]) -> usize {
3934        let (n, on_device) = if self.bounded_native() {
3935            (
3936                self.kv_prefix.extension(input_ids),
3937                self.kv_prefix.on_device(),
3938            )
3939        } else {
3940            let h = &self.kv_history;
3941            if !h.is_empty() && h.len() < input_ids.len() && input_ids[..h.len()] == h[..] {
3942                (h.len(), self.kv_history_device)
3943            } else {
3944                (0, false)
3945            }
3946        };
3947        // The owner tag: the state the key describes must live where this
3948        // turn will continue it (R4) — else a fresh sequence.
3949        if n > 0 && !self.prefix_owner_matches(n, on_device) {
3950            tracing::warn!(
3951                "kv-reuse refused: the cached prefix ({n} positions) was built on the {} path, \
3952                 the device now holds {:?} — re-prefilling from zero",
3953                if on_device { "resident device" } else { "host" },
3954                self.device_sequence_position()
3955            );
3956            return 0;
3957        }
3958        n
3959    }
3960
3961    /// Public view of the prefix-reuse decision for `input_ids` (positions
3962    /// the next `generate*` would take from the cache; 0 = fresh sequence).
3963    pub fn reusable_prefix_len(&self, input_ids: &[u32]) -> usize {
3964        self.cached_prefix_len(input_ids)
3965    }
3966
3967    /// Record the forwarded prefix as the next turn's reuse key. A
3968    /// bounded-native model extends the rolling record (`reused` = the
3969    /// positions this turn found cached); others keep the literal vector.
3970    /// Either way the key carries its OWNER: the resident device graph
3971    /// (it holds an image of this sequence) or the host.
3972    fn record_consumed_prefix(&mut self, consumed: &[u32], reused: usize) {
3973        let on_device = self.device_sequence_position().is_some();
3974        if self.bounded_native() {
3975            let keep = reused > 0 && reused == self.kv_prefix.len() && reused <= consumed.len();
3976            let prev_device = self.kv_prefix.on_device();
3977            self.kv_history.clear();
3978            self.kv_history_device = false;
3979            if keep && prev_device == on_device {
3980                self.kv_prefix.extend(&consumed[reused..]);
3981            } else {
3982                self.kv_prefix.set(consumed);
3983            }
3984            self.kv_prefix.set_on_device(on_device);
3985        } else {
3986            self.kv_history = consumed.to_vec();
3987            self.kv_history_device = on_device;
3988        }
3989    }
3990
3991    /// True when at least one layer runs the O(1) kernel.
3992    pub fn o1_active(&self) -> bool {
3993        self.o1_cfg.is_some() && self.o1_flags.iter().any(|&f| f)
3994    }
3995
3996    /// Whether generation's prompt ingest is routed through the whole-token
3997    /// graph.  The bench uses this to label the measured generation prefill
3998    /// honestly; keep the predicate in Pipeline so CLI labels cannot drift
3999    /// from the production route.
4000    /// Positions per batched-graph submit for the prompt: `CMF_BATCH_K`
4001    /// when set (0 = one position at a time through the token graph),
4002    /// otherwise 128 (32 for a MoE stack) on a discrete card whose prompt
4003    /// takes the graph route.
4004    /// The batched graph read a 2048-token prompt at 53 tok/s against 28.5
4005    /// one position at a time on an RTX PRO 4000 (Qwen3.8-27B q4tp: TTFT
4006    /// 39 s against 72), and its states are the speculative verify's,
4007    /// measured identical to the plain path. macOS keeps its own arm.
4008    /// 128, not 32: the q4tp prefill GEMM tiles 64 batch rows, so a
4009    /// 32-row chunk left half of every tile idle. Qwen3.8-27B q4tp on an
4010    /// RTX 3090, 1000-token prompt: 51 tok/s at 32, 82 at 64, 95 at 128,
4011    /// 97 at 256; greedy output byte-identical to the 32-row chunks
4012    /// (every GEMM row and the k-looped recurrences are per position).
4013    pub fn generation_batch_k(&self) -> usize {
4014        if let Some(k) = std::env::var("CMF_BATCH_K")
4015            .ok()
4016            .and_then(|v| v.parse::<usize>().ok())
4017        {
4018            return k;
4019        }
4020        // Gemma-4 (`g4_batch_prefill`): 128-row chunks, the GEMM tile's
4021        // two 64-row halves full.
4022        if self.g4_batch_prefill() {
4023            return 128;
4024        }
4025        #[cfg(not(target_os = "macos"))]
4026        if self.graph_prefill_preferred() && !self.o1_active() {
4027            // MoE stacks keep the 32 their expert-grouped prefill was
4028            // measured at; 128 is measured on the dense hybrids only.
4029            let moe = self
4030                .weights
4031                .layers
4032                .iter()
4033                .any(|lw| matches!(&lw.ffn, FfnKind::Moe(_)));
4034            // q8_2f experts (moe_q82's grouped prefill) read each expert
4035            // once per group of up to 16 of its entries, so the chunk that
4036            // fills those groups is the faster ingest: Mellum2.1 q8_2f on an
4037            // RTX 3090, 4000-token prompt, 503 tok/s at 64 rows, 542 at 128
4038            // (and 542 at 256).
4039            let q82 = crate::gpu::moe_q82_graph_on()
4040                && self.weights.layers.iter().any(|lw| {
4041                    matches!(&lw.ffn, FfnKind::Moe(m)
4042                        if m.experts.first().is_some_and(|e| e.gate_proj.mapped_q8_2f().is_some()))
4043                });
4044            return if q82 {
4045                128
4046            } else if moe {
4047                32
4048            } else {
4049                128
4050            };
4051        }
4052        0
4053    }
4054
4055    pub fn generation_graph_prefill(&self) -> bool {
4056        let graph = self.graph_prefill_preferred();
4057        // On wgpu, an active MTP head now consumes the trunk's graph batches
4058        // and warms its own block from those returned rows.  The selected
4059        // generation measurement is therefore the batched path, even though
4060        // the underlying GDN model still satisfies the graph-prefill
4061        // predicate.  Keep the CLI label tied to the actual route.  Native
4062        // Metal has a separate prefill-batch arm and retains its historical
4063        // label here.
4064        // A batched prompt (`generation_batch_k` > 0) is the batched graph
4065        // for every model on the graph route, not only those with an MTP
4066        // head — the label follows the route.
4067        #[cfg(not(target_os = "macos"))]
4068        if graph && self.generation_batch_k() > 0 && std::env::var("CMF_MTP_CHAIN_PROBE").is_err() {
4069            return false;
4070        }
4071        graph
4072    }
4073
4074    /// Device-side O(1) mirrors currently uploaded for this pipeline's
4075    /// sequence.  The count/bytes are zero before seal or after a fresh
4076    /// reset; callers use this to distinguish logical host state from the
4077    /// GPU allocation that actually serves decode.
4078    pub fn o1_device_stats(&self) -> (usize, u64) {
4079        crate::gpu::o1_device_stats(self.graph_kv_id)
4080    }
4081
4082    /// Arm query collection on the o1 layers (fresh prompt pass).
4083    /// Reset the o1 layers to Collecting for a fresh sequence. Pub for the
4084    /// network split: each side runs the o1 lifecycle over ITS OWN layers
4085    /// (begin before prefill, seal at the prefill barrier).
4086    pub fn o1_begin(&mut self) {
4087        self.o1_begin_with_prefix(None);
4088    }
4089
4090    /// Arm collection and optionally request a positive calibration prefix.
4091    /// The effective barrier is always at least the skeleton-safe floor, so
4092    /// a short requested prefix cannot create an exact-only runtime state.
4093    pub fn o1_begin_with_prefix(&mut self, requested_prefix: Option<usize>) {
4094        if let Some(c) = &self.o1_cfg {
4095            let (m, w, sink, rect) = (c.m, c.w, c.sink, c.rect);
4096            let boundary = requested_prefix.map(|p| {
4097                p.max(
4098                    crate::nystrom::o1_deferred_boundary(w, sink)
4099                        .expect("o1 config boundary validated in set_o1"),
4100                )
4101            });
4102            for (li, &f) in self.o1_flags.iter().enumerate() {
4103                if f {
4104                    self.kv_cache.layers[li].o1_begin_with_boundary(m, w, sink, rect, boundary);
4105                }
4106            }
4107        }
4108    }
4109
4110    /// Effective deferred boundary for a positive prefix request.
4111    fn o1_effective_boundary(&self, requested_prefix: usize) -> Option<usize> {
4112        self.o1_cfg.as_ref().and_then(|c| {
4113            crate::nystrom::o1_deferred_boundary(c.w, c.sink)
4114                .map(|floor| requested_prefix.max(floor))
4115        })
4116    }
4117
4118    fn o1_note_transition(&mut self) {
4119        // Drain every layer's one-shot bit before publishing one pipeline
4120        // epoch. `any()` would short-circuit on the first layer and leak the
4121        // remaining bits into later forwards, causing one epoch per layer.
4122        let mut transitioned = false;
4123        for (li, &flagged) in self.o1_flags.iter().enumerate() {
4124            if flagged {
4125                transitioned |= self.kv_cache.layers[li].take_o1_transition();
4126            }
4127        }
4128        if transitioned {
4129            self.o1_epoch = self.o1_epoch.wrapping_add(1);
4130        }
4131    }
4132
4133    fn o1_pending(&self) -> bool {
4134        self.o1_flags.iter().enumerate().any(|(li, &f)| {
4135            f && self.kv_cache.layers[li].seq_len > 0
4136                && self.kv_cache.layers[li].o1_pending_boundary().is_some()
4137        })
4138    }
4139
4140    fn o1_fail(&mut self, err: String) {
4141        tracing::error!("o1 deferred seal failed; terminating sequence: {err}");
4142        self.clear_sequence_state();
4143        self.graph_failed
4144            .store(true, std::sync::atomic::Ordering::Relaxed);
4145        self.cancel
4146            .store(true, std::sync::atomic::Ordering::Relaxed);
4147    }
4148
4149    /// Seal participating layers while retaining the exact state when the
4150    /// prompt is below the deferred boundary. A split worker may have
4151    /// collecting layers outside its owned span; zero-depth layers remain
4152    /// armed and are intentionally skipped until their peer runs them.
4153    pub fn o1_seal_checked(&mut self) -> Result<bool, String> {
4154        if self.o1_cfg.is_none() {
4155            return Ok(false);
4156        }
4157        let mut participating = false;
4158        for li in 0..self.num_layers {
4159            if !self.o1_flags.get(li).copied().unwrap_or(false) {
4160                continue;
4161            }
4162            if let Some(err) = self.kv_cache.layers[li].take_o1_error() {
4163                return Err(err);
4164            }
4165            if self.kv_cache.layers[li].seq_len == 0 {
4166                continue;
4167            }
4168            participating = true;
4169            let num_heads = self.layer_num_heads(li);
4170            self.kv_cache.layers[li].o1_seal_checked(num_heads)?;
4171        }
4172        self.o1_note_transition();
4173        for li in 0..self.num_layers {
4174            if self.o1_flags.get(li).copied().unwrap_or(false) {
4175                if let Some(err) = self.kv_cache.layers[li].take_o1_error() {
4176                    return Err(err);
4177                }
4178            }
4179        }
4180        Ok(participating
4181            && (0..self.num_layers).all(|li| {
4182                !self.o1_flags.get(li).copied().unwrap_or(false)
4183                    || self.kv_cache.layers[li].seq_len == 0
4184                    || self.kv_cache.layers[li].o1_sealed()
4185            }))
4186    }
4187
4188    /// Complete a deferred boundary after a full position/span forward.
4189    /// This is the pipeline owner for epoch publication and failure cleanup.
4190    fn o1_progress(&mut self) {
4191        if !self.o1_active() {
4192            return;
4193        }
4194        for li in 0..self.num_layers {
4195            if self.o1_flags.get(li).copied().unwrap_or(false) {
4196                if let Some(err) = self.kv_cache.layers[li].take_o1_error() {
4197                    self.o1_fail(err);
4198                    return;
4199                }
4200            }
4201        }
4202        // A qwen_attention row can seal in the middle of a complete layer
4203        // walk. Consume its transition even though the pending boundary has
4204        // already disappeared from the cache.
4205        self.o1_note_transition();
4206        if !self.o1_pending() {
4207            return;
4208        }
4209        if let Err(err) = self.o1_seal_checked() {
4210            self.o1_fail(err);
4211        }
4212    }
4213
4214    /// Turn a deferred O(1) failure raised by a hidden-only forward into the
4215    /// Result error its public batch/span caller must return. The failure
4216    /// path already cleared host/device sequence state; consume only the
4217    /// side-channel marker here and leave the pipeline reusable.
4218    fn check_o1_progress_failure(&mut self, phase: &str) -> Result<(), String> {
4219        if self
4220            .graph_failed
4221            .swap(false, std::sync::atomic::Ordering::Relaxed)
4222        {
4223            self.cancel
4224                .store(false, std::sync::atomic::Ordering::Relaxed);
4225            self.clear_sequence_state();
4226            return Err(format!("{phase}: deferred O(1) transition failed"));
4227        }
4228        Ok(())
4229    }
4230
4231    /// Freeze landmarks + skeleton state after the prompt pass and drop
4232    /// the o1 layers' full KV; decode then runs `step()` per token.
4233    /// Pub for the network split (see `o1_begin`).
4234    pub fn o1_seal(&mut self) {
4235        if let Err(err) = self.o1_seal_checked() {
4236            self.o1_fail(err);
4237        }
4238    }
4239
4240    /// Enable/disable the structured per-token telemetry trace (B4).
4241    pub fn set_trace(&mut self, on: bool) {
4242        self.trace = on;
4243    }
4244
4245    /// Replace all request-scoped sampler options and reset the random stream.
4246    /// This is required for deterministic `seed` semantics in pooled servers.
4247    pub fn set_sampler_config(&mut self, config: SamplerConfig) {
4248        self.rng = match config.seed {
4249            Some(seed) => SplitMix64::new(seed),
4250            None => SplitMix64::from_entropy(),
4251        };
4252        self.sampler_config = config;
4253    }
4254
4255    /// Toggle the per-token confidence reduction (a full-vocab
4256    /// softmax each token). `bench --core` turns it off so the timed
4257    /// loop matches llama-bench's core contract; the result's
4258    /// `confidence` vec is empty while off.
4259    pub fn set_confidence(&mut self, on: bool) {
4260        self.confidence_on = on;
4261    }
4262
4263    /// Set the confidence-calibration temperature (B1). Values ≤0 are
4264    /// clamped to raw (1.0).
4265    pub fn set_calib_temp(&mut self, t: f32) {
4266        self.calib_temp = if t > 1e-3 { t } else { 1.0 };
4267    }
4268
4269    /// The active calibration temperature (1.0 = raw probability).
4270    pub fn calib_temp(&self) -> f32 {
4271        self.calib_temp
4272    }
4273
4274    /// The primary (full-attention) RoPE inverse-frequency table selected
4275    /// from the CMF architecture.  This is read-only diagnostic state for
4276    /// parity checks; local sliding layers may use `inv_freq_local` instead.
4277    pub fn rope_inv_freq(&self) -> &[f32] {
4278        self.inv_freq.as_slice()
4279    }
4280
4281    /// Partial rotary (Qwen3.5): rotate only the first `rotary_dim` dims;
4282    /// the frequency table is rebuilt over the rotary dims.
4283    pub fn set_rotary(&mut self, rotary_dim: usize, base: f32) {
4284        self.rotary_dim = rotary_dim.min(self.head_dim);
4285        self.inv_freq = std::sync::Arc::new(attention::rope_inv_freq(self.rotary_dim, base));
4286        // The packed resident graph owns its own inverse-frequency plane;
4287        // changing RoPE after it was built must not leave a stale device
4288        // model behind the exact host configuration.
4289        self.embryo_graph = None;
4290    }
4291
4292    fn attn_cfg(&self, position: usize) -> QwenAttnCfg<'_> {
4293        QwenAttnCfg {
4294            num_heads: self.num_heads,
4295            num_kv_heads: self.num_kv_heads,
4296            head_dim: self.head_dim,
4297            hidden_size: self.hidden_size,
4298            position,
4299            inv_freq: &self.inv_freq,
4300            rotary_dim: self.rotary_dim,
4301            scale: self.attn_scale,
4302            softcap: self.attn_softcap,
4303            window: None,
4304            v_norm: false,
4305            qk_norm_after_rope: self.qk_norm_after_rope,
4306            gate_sigmoid: self.proj_gate_sigmoid,
4307            q_norm: None,
4308            k_norm: None,
4309            output_gate: false,
4310            softplus_gate: None,
4311            rope_scale: self.rope_scale,
4312            bias: None,
4313            rms_eps: self.rms_eps,
4314            norm_style: self.norm_style,
4315            pool: self.pool.as_deref(),
4316            v_head_dim: self.v_head_dim.unwrap_or(self.head_dim),
4317        }
4318    }
4319
4320    /// Generate text from a plain-text prompt. Streams tokens via `on_token`.
4321    pub fn generate(
4322        &mut self,
4323        prompt: &str,
4324        max_tokens: usize,
4325        task_mask: Option<&TaskMask>,
4326        on_token: Option<TokenCallback>,
4327    ) -> Result<GenerateResult, String> {
4328        let input_ids = self.tokenizer.with_bos(self.tokenizer.encode(prompt));
4329        self.generate_from_ids(&input_ids, max_tokens, task_mask, on_token)
4330    }
4331
4332    /// Generate from a V4.1 multimodal prompt prepared by the vision module.
4333    /// Vision rows are encoded once and fed through the same bounded token walk as text.
4334    pub fn generate_from_vl(
4335        &mut self,
4336        input: &crate::dsv41_vision::PreparedVlInputs,
4337        max_tokens: usize,
4338        task_mask: Option<&TaskMask>,
4339        on_token: Option<TokenCallback>,
4340    ) -> Result<GenerateResult, String> {
4341        let Some(dsv41) = &self.dsv41 else {
4342            return Err("V4.1 multimodal input requires a DeepSeek-V4.1 pipeline".into());
4343        };
4344        if input.token_ids.is_empty() {
4345            return Err("empty V4.1 multimodal prompt".into());
4346        }
4347        if input.token_types.len() != input.token_ids.len() {
4348            return Err(format!(
4349                "V4.1 token type count {} != token count {}",
4350                input.token_types.len(),
4351                input.token_ids.len()
4352            ));
4353        }
4354        let dim = dsv41.2.dim;
4355        let mut embeddings = vec![None; input.token_ids.len()];
4356        let mut participates = vec![true; input.token_ids.len()];
4357        if !input.images.is_empty() {
4358            let vision = self
4359                .dsv41_vision
4360                .as_ref()
4361                .ok_or_else(|| "V4.1 image prompt has no loaded vision tower".to_string())?;
4362            for image in &input.images {
4363                let end = image.start.saturating_add(image.types.len());
4364                if end > input.token_ids.len() {
4365                    return Err(format!(
4366                        "V4.1 image span {}..{} exceeds prompt length {}",
4367                        image.start,
4368                        end,
4369                        input.token_ids.len()
4370                    ));
4371                }
4372                let mut span = vec![0.0f32; image.types.len() * dim];
4373                vision.fill_image_span(image, &mut span, self.pool.as_deref())?;
4374                for (offset, &kind) in image.types.iter().enumerate() {
4375                    let pos = image.start + offset;
4376                    if input.token_types[pos] != kind {
4377                        return Err(format!(
4378                            "V4.1 image type mismatch at position {pos}: {} != {kind}",
4379                            input.token_types[pos]
4380                        ));
4381                    }
4382                    embeddings[pos] = Some(span[offset * dim..(offset + 1) * dim].to_vec());
4383                    participates[pos] = false;
4384                }
4385            }
4386        }
4387        for (pos, &kind) in input.token_types.iter().enumerate() {
4388            if kind == crate::dsv41_vision::TEXT && embeddings[pos].is_some() {
4389                return Err(format!("V4.1 text position {pos} has an image embedding"));
4390            }
4391            if kind != crate::dsv41_vision::TEXT && embeddings[pos].is_none() {
4392                return Err(format!("V4.1 image position {pos} has no image embedding"));
4393            }
4394        }
4395        self.dsv41_prefill = Some((embeddings, participates));
4396        let result = self.generate_from_ids(&input.token_ids, max_tokens, task_mask, on_token);
4397        self.dsv41_prefill = None;
4398        result
4399    }
4400
4401    /// `None` when the mask forbids nothing (see `TaskMask::fully_open`).
4402    fn drop_open_mask<'m>(&self, m: Option<&'m TaskMask>) -> Option<&'m TaskMask> {
4403        m.filter(|m| !m.fully_open(self.intermediate_size, self.num_heads))
4404    }
4405
4406    /// Generate from prepared token ids (e.g. a chat template).
4407    ///
4408    /// With an MTP head, greedy generation without a task mask takes the
4409    /// speculative path: the MTP module drafts the token after next and
4410    /// the main model verifies both in one fused two-position forward
4411    /// (weights streamed once). The output is EXACTLY the vanilla greedy
4412    /// sequence — a rejected draft is rolled back — MTP only buys speed.
4413    pub fn generate_from_ids(
4414        &mut self,
4415        input_ids: &[u32],
4416        max_tokens: usize,
4417        task_mask: Option<&TaskMask>,
4418        on_token: Option<TokenCallback>,
4419    ) -> Result<GenerateResult, String> {
4420        self.generate_with_prompt_rows(input_ids, None, max_tokens, task_mask, on_token)
4421    }
4422
4423    /// Generate from complete prompt embeddings [token_count, hidden_size].
4424    /// Text rows can be obtained with `embed_id`; media rows replace only
4425    /// their expanded placeholder positions. Rows are already scaled and
4426    /// enter `PrefillIn::Hidden`, so a device graph must not re-embed them.
4427    /// Token-only KV reuse is disabled both into and out of this request.
4428    pub fn generate_from_embeds(
4429        &mut self,
4430        input_ids: &[u32],
4431        prompt_rows: &[f32],
4432        max_tokens: usize,
4433        task_mask: Option<&TaskMask>,
4434        on_token: Option<TokenCallback>,
4435    ) -> Result<GenerateResult, String> {
4436        if input_ids.is_empty()
4437            || input_ids.len().checked_mul(self.hidden_size) != Some(prompt_rows.len())
4438        {
4439            return Err("embedded prompt dimensions must be [tokens, hidden_size]".into());
4440        }
4441        if prompt_rows.iter().any(|x| !x.is_finite()) {
4442            return Err("embedded prompt contains non-finite values".into());
4443        }
4444        if !self.can_prefill_batched()
4445            || self.dyn_router.is_some()
4446            || self.o1_active()
4447            || self.mtp.is_some()
4448            || self.gpu_plan.is_some()
4449        {
4450            return Err("embedded prompts require the ordinary transformer path without O(1), dynamic routing, GPU splitting or a generic MTP head".into());
4451        }
4452        self.generate_with_prompt_rows(
4453            input_ids,
4454            Some(prompt_rows),
4455            max_tokens,
4456            task_mask,
4457            on_token,
4458        )
4459    }
4460
4461    fn generate_with_prompt_rows(
4462        &mut self,
4463        input_ids: &[u32],
4464        prompt_rows: Option<&[f32]>,
4465        max_tokens: usize,
4466        task_mask: Option<&TaskMask>,
4467        mut on_token: Option<TokenCallback>,
4468    ) -> Result<GenerateResult, String> {
4469        #[cfg(target_os = "macos")]
4470        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
4471        if std::env::var("CMF_TRACE_H").is_ok() {
4472            eprintln!("input_ids: {input_ids:?}");
4473        }
4474        if input_ids.is_empty() {
4475            return Err("empty prompt: nothing to generate from".to_string());
4476        }
4477        // A prior graph failure is terminal for that sequence but must not
4478        // poison the next independent request.  Keep this flag separate from
4479        // the externally-owned cooperative cancel bit.
4480        self.graph_failed
4481            .store(false, std::sync::atomic::Ordering::Relaxed);
4482        // A mask that forbids nothing still costs every fused path and
4483        // whole-token graph, all of which are gated on `is_none()`. A
4484        // narrowed file whose one segment is always on carries exactly
4485        // such a mask — drop it here rather than pay 5x for a no-op.
4486        let task_mask = self.drop_open_mask(task_mask);
4487
4488        // Cross-turn KV reuse: a chat app resends the whole history
4489        // every turn; when the new ids strictly EXTEND what the cache
4490        // already holds, prefill only the tail — turn latency stays
4491        // proportional to the new text instead of the whole session.
4492        // Extension-only (no rollback), so it is exact for every layer
4493        // kind including recurrent state; MTP/o1/task-mask runs keep
4494        // the fresh-sequence path. CMF_KV_REUSE=0 disables.
4495        let mut reuse_from = {
4496            let on = !std::env::var("CMF_KV_REUSE").is_ok_and(|v| v == "0");
4497            if on
4498                && prompt_rows.is_none()
4499                && task_mask.is_none()
4500                && self.mtp.is_none()
4501                && !(self.mimo_mtp.is_some() && self.speculative)
4502                && self.o1_cfg.is_none()
4503                && self.dsv41.is_none()
4504            {
4505                self.cached_prefix_len(input_ids)
4506            } else {
4507                0
4508            }
4509        };
4510        // The device may own rows the host tail prefill needs (wgpu decode
4511        // writes only its mirror): hand them to the host, or start fresh.
4512        if reuse_from > 0 && !self.prepare_kv_reuse(reuse_from) {
4513            reuse_from = 0;
4514        }
4515        self.last_prefill_tokens = input_ids.len() - reuse_from;
4516        let bounded_native = self.bounded_native();
4517        if reuse_from == 0 {
4518            // Fresh sequence — the cache holds absolute positions.
4519            self.clear_sequence_state();
4520        } else if std::env::var("CMF_PREFILL_PROF").is_ok() {
4521            eprintln!(
4522                "kv-reuse: {} of {} prompt positions already cached",
4523                reuse_from,
4524                input_ids.len()
4525            );
4526        }
4527        crate::gpu::graph_race_begin_generation();
4528        // Optional bounded calibration prefix. Keep the requested value
4529        // even when it is longer than the prompt; the collecting layer will
4530        // defer at the effective boundary and remain exact for short input.
4531        let o1_prefill = if self.o1_active() && task_mask.is_none() {
4532            std::env::var("CMF_O1_PREFILL")
4533                .ok()
4534                .and_then(|v| v.parse::<usize>().ok())
4535                .filter(|&p| p > 0)
4536        } else {
4537            None
4538        };
4539        if task_mask.is_none() {
4540            self.o1_begin_with_prefix(o1_prefill);
4541        }
4542
4543        // Speculative decode is off under o1: a rejected draft can't be
4544        // rolled back out of the far accumulators / ring window (the
4545        // Nyström insertion is irreversible by design).
4546        // The wgpu token graph owns a device K/V mirror that speculative
4547        // rollback would desync — the two are mutually exclusive.
4548        let graph_on = crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode);
4549        // Graph speculative decode (`CMF_GRAPH_SPEC=1`): the MTP head
4550        // drafts, ONE batched graph submit verifies the whole chain.
4551        //
4552        // It now PAYS on Qwen3.6-27B / RTX 5090 — 51.1 tok/s against a
4553        // plain 49.4 at k=3, medians of three, 89% of drafts accepted,
4554        // and the greedy continuation is byte-identical to the plain
4555        // path. That took the batch matvec sharing its nibble unpack
4556        // across the batch (`CMF_MV_BK=2`); before it, the same round
4557        // measured 43.6, an 11% LOSS, which is what the earlier note
4558        // here described.
4559        //
4560        // Still opt-in. One model's win is not a default: the verify
4561        // rides `gdn_spec_restore` and a batched frame whose numerics
4562        // are the batch kernels', and that has to be shown on more than
4563        // one architecture before every greedy decode takes it.
4564        // Greedy (with or without penalties) verifies by argmax equality.
4565        // Sampling (temperature > 0) can go through speculative SAMPLING —
4566        // draft from the MTP head's own post-chain distribution, accept
4567        // with min(1, p/q), correct from max(0, p − q); the emitted stream
4568        // is distributed exactly as the plain sampler's — but it is
4569        // OPT-IN (`CMF_GRAPH_SPEC_SAMPLE=1`): measured on Qwen3.8-27B /
4570        // RTX 5090 at the instruct row (0.7 / 0.80 / 20 / presence 1.5)
4571        // it decoded 19-22 tok/s against a plain 40 — nine post-chain
4572        // distributions a round plus a lower acceptance than greedy's,
4573        // against a verify that costs 2.7 single tokens. The greedy arms
4574        // pay +10%; the sampling arm needs a cheaper verify first.
4575        // Native Metal HAS that verify: its eight-row tile is flat in b,
4576        // so a round costs ~1.9 plain tokens and the sampling arm pays at
4577        // 2.3 accepted per round — measured on Qwen3.8-27B q4tp / M4 at
4578        // the CLI defaults (0.7 / rep 1.1 / top-k 40, seed 42), a code
4579        // prompt: 9.0 tok/s against a plain 5.4 in the same window, and
4580        // the per-round watchdog turns it off where prose loses. So on
4581        // Metal the sampling arm is ON (`CMF_GRAPH_SPEC_SAMPLE=0` opts out)
4582        // — but only for a config the SPARSE chain serves (a top-k within
4583        // `sparse_ok`): without it a round builds nine 248k-float
4584        // distributions on the host, which is the 5090's measured loss and
4585        // not a cost the round-token proxy below can see. A top-k-less
4586        // sampling config keeps the plain path unless asked for by name.
4587        #[cfg(target_os = "macos")]
4588        let metal_graph = crate::gpu::q1_force()
4589            && crate::gpu::enabled_here()
4590            && std::env::var("CMF_GPU_BLOCK")
4591                .map(|v| v != "0")
4592                .unwrap_or(true);
4593        #[cfg(not(target_os = "macos"))]
4594        let metal_graph = false;
4595        let spec_sample_env = std::env::var("CMF_GRAPH_SPEC_SAMPLE").ok();
4596        // A round whose cost is the MEASURED one: greedy (argmax rows), or
4597        // sampling through the sparse chain. Anything else pays the dense
4598        // chain's host time, which no proxy can price.
4599        let spec_cheap_round =
4600            self.sampler_config.temperature < 1e-6 || sampler::sparse_ok(&self.sampler_config);
4601        let spec_sampling_ok = self.sampler_config.temperature < 1e-6
4602            || match spec_sample_env.as_deref() {
4603                Some("1") => true,
4604                Some(_) => false,
4605                None => metal_graph && spec_cheap_round,
4606            };
4607        // ON by default for greedy on the wgpu graph: with the draft on
4608        // the graph and the verify bit-exact, it measured 58.7 tok/s
4609        // against a plain 48.1 on Qwen3.8-27B q4tp / RTX 5090 (k=4) and
4610        // 51.1 against 49.4 on Qwen3.6-27B, and a round that stops
4611        // paying turns itself off below (acceptance watchdog).
4612        // `CMF_GRAPH_SPEC=0` disables; `=1` was the old opt-in spelling.
4613        // …but only where the batched verify has its register-blocked
4614        // kernel: q4tp dense FFNs (graph kind 6). q4t and q8_2f verify
4615        // through tile GEMMs today and measured a LOSS (q8_2f 22 against
4616        // 29 tok/s), the 2-bit plane the same; those stay opt-in
4617        // (`CMF_GRAPH_SPEC=1`).
4618        // …at least in nine dense FFNs of ten: a healed file carries its
4619        // last two layers at q8_2f, and two tile-GEMM verifies among 64 do
4620        // not change the arithmetic (measured: the healed q4tp file
4621        // decodes at the plain file's rate and would otherwise sit out).
4622        let (mut dense_n, mut dense_q4tp) = (0usize, 0usize);
4623        for lw in &self.weights.layers {
4624            if let FfnKind::Dense(d) = &lw.ffn {
4625                dense_n += 1;
4626                if matches!(d.gate_proj.graph_weight(), Some((_, _, 6, _)))
4627                    && matches!(d.up_proj.graph_weight(), Some((_, _, 6, _)))
4628                    && matches!(d.down_proj.graph_weight(), Some((_, _, 6, _)))
4629                {
4630                    dense_q4tp += 1;
4631                }
4632            }
4633        }
4634        let spec_default_ok = dense_n == 0 || dense_q4tp * 10 >= dense_n * 9;
4635        // Penalties break the draft head's agreement with the trunk (a
4636        // 1.1 repetition penalty measured 2 of 16 accepted): not by
4637        // default there either — off Metal that rule is untouched, and
4638        // suppressed ids keep counting as a penalty there, because no
4639        // measurement on a discrete card says otherwise.
4640        //
4641        // On native Metal the penalized arms DO pay: the draft applies
4642        // the same penalty and the verify scores the penalized rows
4643        // exactly (`greedy_pen`, the plain loop's arithmetic), so the
4644        // text is the plain path's and only the round's shape changes.
4645        // Measured on this M4 — see the report for the interleaved run.
4646        let penalized = !metal_graph
4647            && (self.sampler_config.repetition_penalty != 1.0
4648                || self.sampler_config.presence_penalty != 0.0
4649                || !self.sampler_config.suppress_tokens.is_empty());
4650        // …and not on wgpu-over-Metal: the batched verify graph there
4651        // returned 0 accepted drafts and garbage text on a GDN hybrid
4652        // (16.08, Qwen3.5-0.8B) while Vulkan is bit-exact; the Mac's
4653        // default backend is native Metal without a batch graph anyway.
4654        #[cfg(feature = "gpu")]
4655        let metal_wgpu = graph_on && crate::gpu_wgpu::wgpu_backend_is_metal();
4656        #[cfg(not(feature = "gpu"))]
4657        let metal_wgpu = false;
4658        let spec_env = std::env::var("CMF_GRAPH_SPEC").ok();
4659        let spec_wanted = match spec_env.as_deref() {
4660            Some("0") => false,
4661            Some(_) => {
4662                if metal_wgpu {
4663                    tracing::warn!(
4664                        "CMF_GRAPH_SPEC forced on wgpu/Metal: the batched verify graph is not \
4665                         verified on this backend (garbage measured on Qwen3.5-0.8B)"
4666                    );
4667                }
4668                true
4669            }
4670            None => spec_default_ok && !penalized && !metal_wgpu,
4671        };
4672        // Native Metal: the b-row verify graph (`try_batch_graph_metal`)
4673        // stands where the wgpu batch graph stands on discrete cards
4674        // (`metal_graph`, above).
4675        let graph_spec = self.speculative
4676            && (graph_on || metal_graph)
4677            && self.mtp.is_some()
4678            && task_mask.is_none()
4679            && !self.o1_active()
4680            && spec_sampling_ok
4681            && spec_wanted;
4682        // Native Metal: say the route ONCE (RUST_LOG=info), so a user can
4683        // confirm the fast path without setting a single flag — every
4684        // knob below defaults to the measured-best value on the M4.
4685        #[cfg(target_os = "macos")]
4686        if metal_graph {
4687            static SAID: std::sync::Once = std::sync::Once::new();
4688            SAID.call_once(|| {
4689                let spec = if graph_spec {
4690                    let k = std::env::var("CMF_GRAPH_SPEC_K")
4691                        .ok()
4692                        .and_then(|v| v.parse::<usize>().ok())
4693                        .filter(|&v| (1..=8).contains(&v))
4694                        .unwrap_or(7);
4695                    let arm = if self.sampler_config.temperature < 1e-6 {
4696                        "greedy"
4697                    } else {
4698                        "sampling"
4699                    };
4700                    format!(
4701                        "spec k={k} {arm} (batched verify, draft shortlist {}, trial: proxy)",
4702                        Self::draft_vocab_rows(usize::MAX)
4703                    )
4704                } else if !self.speculative {
4705                    "spec off (CMF_MTP=0)".to_string()
4706                } else if self.mtp.is_none() {
4707                    "spec off (no MTP head)".to_string()
4708                } else if !spec_sampling_ok {
4709                    if spec_cheap_round {
4710                        "spec off (CMF_GRAPH_SPEC_SAMPLE=0)".to_string()
4711                    } else {
4712                        "spec off (sampling without a top-k: the dense chain \
4713                         costs more than it saves)"
4714                            .to_string()
4715                    }
4716                } else if !spec_wanted {
4717                    "spec off (CMF_GRAPH_SPEC=0 or non-q4tp FFNs)".to_string()
4718                } else if task_mask.is_some() {
4719                    "spec off (task mask)".to_string()
4720                } else {
4721                    "spec off (O(1) attention)".to_string()
4722                };
4723                let on = |var: &str| {
4724                    if std::env::var(var).as_deref() == Ok("0") {
4725                        "off"
4726                    } else {
4727                        "on"
4728                    }
4729                };
4730                tracing::info!(
4731                    "metal native: {spec}, state4 {}, async replay {}, prefill graph {}, \
4732                     MTP graph {}, attend {}, probe {}",
4733                    if crate::gpu_metal::state4_on() {
4734                        "on"
4735                    } else {
4736                        "off"
4737                    },
4738                    if crate::gpu_metal::async_replay_on() {
4739                        "on"
4740                    } else {
4741                        "off"
4742                    },
4743                    on("CMF_METAL_PREFILL"),
4744                    on("CMF_MTP_GRAPH"),
4745                    std::env::var("CMF_GPU_ATTEND").unwrap_or_else(|_| "auto".into()),
4746                    if crate::gpu::probe_enabled() {
4747                        "bypassed (q1 force)"
4748                    } else {
4749                        "off"
4750                    },
4751                );
4752            });
4753        }
4754        // GDN hybrids sit the fused-pair speculation out by default: the
4755        // recurrence is sequential, so the pair lane cannot parallelize
4756        // (the bench's own Pair line reads fused 1.28x TWO singles on the
4757        // 35B) and the draft's full-vocab head rides on top — measured 2x
4758        // SLOWER end to end (16.1 vs 32.4 tok/s on the 48-core stand).
4759        // CMF_MTP=1 forces it back for study.
4760        let pair_pays = self.gdn_cfg.is_none() || std::env::var("CMF_MTP").as_deref() == Ok("1");
4761        let spec_active = self.speculative
4762            && self.mtp.is_some()
4763            && task_mask.is_none()
4764            && !self.o1_active()
4765            && ((!graph_on && pair_pays && self.sampler_config.temperature < 1e-6) || graph_spec);
4766        // The MTP module is detached during generation so its mutable
4767        // state does not fight the borrow on `self`.
4768        let mut mtp = if spec_active { self.mtp.take() } else { None };
4769        if std::env::var("CMF_MTP_CHAIN_PROBE").is_ok() {
4770            eprintln!(
4771                "mtp-probe gate: spec_active={spec_active} mtp={} speculative={} graph_on={graph_on} temp_ok={}",
4772                mtp.is_some(),
4773                self.speculative,
4774                self.sampler_config.temperature < 1e-6,
4775            );
4776        }
4777        if let Some(m) = &mut mtp {
4778            m.kv.clear();
4779            // The MTP block's own device mirror starts over with its cache.
4780            crate::gpu::graph_kv_reset(self.mtp_kv_id());
4781            self.mtp_graph_mode = None;
4782        }
4783        // MiMo-V2's draft stack: greedy rounds (draft K with the chained
4784        // MTP layers, verify K+1 rows in one batched forward). Sampling
4785        // decodes plain; `CMF_MTP=0` / `CMF_MIMO_MTP=0` turn it off.
4786        let mimo_spec = self.speculative
4787            && self.mimo_mtp.is_some()
4788            && task_mask.is_none()
4789            && !self.o1_active()
4790            && self.dyn_router.is_none()
4791            && self.sampler_config.temperature < 1e-6
4792            && std::env::var("CMF_MIMO_MTP").as_deref() != Ok("0");
4793        if let Some(st) = self.mimo_mtp.as_mut() {
4794            st.reset();
4795            if mimo_spec && std::env::var_os("CMF_MIMO_MTP_PROBE").is_some() {
4796                Self::mimo_mtp_hist_cap(st, input_ids.len());
4797            }
4798        }
4799        // Dynamic router detached during decode (same borrow trick as MTP).
4800        // Speculative decode and dynamic routing are mutually exclusive
4801        // for now — the fused-pair path doesn't carry per-token φ.
4802        let mut router = if mtp.is_none() {
4803            self.dyn_router.take()
4804        } else {
4805            None
4806        };
4807        let mut reuse_from = reuse_from;
4808        if let Some(r) = &mut router {
4809            r.reset(); // active=backbone, matching a fresh overlay
4810            self.dyn_phi_seen = 0; // fresh φ EMA per generation
4811            if self.dyn_active.is_some() {
4812                // A real switch back to the backbone invalidates the
4813                // cache the reuse key was computed against.
4814                let _ = self.set_active_skill(None);
4815                reuse_from = 0;
4816                self.last_prefill_tokens = input_ids.len();
4817            }
4818        }
4819
4820        let mut all_ids = input_ids.to_vec();
4821        let mut generated = 0usize;
4822        let mut finish_reason = "max_tokens".to_string();
4823        let mut drafted = 0usize;
4824        let mut accepted = 0usize;
4825        // DeepSeek-V4's draft quality is strongly content-dependent.  Two
4826        // consecutive paid rounds with no extra token put it on a bounded
4827        // cooldown; predictable text keeps batching, ordinary prose falls
4828        // back to the exact walk instead of paying a slow draft forever.
4829        // Local to one generation so one difficult request cannot poison the
4830        // next one, and deliberately automatic — this is not a user knob.
4831        let mut dsv4_spec_bad = 0usize;
4832        let mut dsv4_spec_retry_at = 0usize;
4833        let mut confidence: Vec<f32> = Vec::new();
4834        let trace_on = self.trace;
4835        let calib_temp = self.calib_temp;
4836        let mut traces: Vec<TokenTrace> = Vec::new();
4837
4838        // ── Prefill: forward each prompt token once, KEEP the last hidden.
4839        //    Dense prefill runs in fused pairs (weights streamed once per
4840        //    two positions — bit-identical to sequential, proven by the
4841        //    pair tests). With MTP: warm the draft head on
4842        //    (hidden_p, token_{p+1}) pairs.
4843        let mut hidden = vec![0.0f32; self.hidden_size];
4844        let mut pos = reuse_from;
4845        // lm_head-in-graph is only sound when the very next logits
4846        // consumer is this loop's own (MTP and skill routing interleave
4847        // other forwards / can swap lm_head between forward and sample).
4848        // CMF_GPU_LMHEAD=0 keeps lm_head off the graph: the token reads back
4849        // the 8 KB hidden instead of ~1 MB of logits, and the head runs on
4850        // the host. A probe for how much of the graph's fixed per-token cost
4851        // is the logits readback (the layer sweep puts that fixed part at
4852        // 3.88 ms of an 18.5 ms frame).
4853        let fuse_lm = mtp.is_none()
4854            && router.is_none()
4855            && std::env::var("CMF_GPU_LMHEAD").as_deref() != Ok("0");
4856        self.graph_logits = None;
4857        self.graph_want_logits = false;
4858        let _tpf = std::time::Instant::now();
4859        let batch_k = self.generation_batch_k();
4860        if let Some(rows) = prompt_rows {
4861            let hs = self.hidden_size;
4862            let chunk = self.prefill_chunk().max(1);
4863            while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
4864                let end = (pos + chunk).min(input_ids.len());
4865                let hb = match self.prefill_input_rows(
4866                    PrefillIn::Hidden(&rows[pos * hs..end * hs]),
4867                    pos,
4868                    task_mask,
4869                ) {
4870                    Ok(hb) => hb,
4871                    Err(err) => {
4872                        self.finish_generation(&mut mtp, &mut router, true);
4873                        return Err(err);
4874                    }
4875                };
4876                if mimo_spec {
4877                    self.mimo_note_rows(&hb, pos);
4878                }
4879                hidden.copy_from_slice(&hb[hb.len() - hs..]);
4880                pos = end;
4881            }
4882        }
4883        // DeepSeek-V4 owns a separate hyper-connection stack. Route it
4884        // before the generic prefill choices: those correctly reject an
4885        // empty `weights.layers`, but their final per-position fallback used
4886        // to consume the whole prompt before `dsv4::forward_chunk` could see
4887        // it. The batch implementation therefore existed without a live
4888        // production entry point.
4889        //
4890        // Bounded chunks preserve cancellation responsiveness. Only the
4891        // prompt's final chunk asks for logits; every earlier head projection
4892        // would produce 129 280 values that no caller reads.
4893        while self.qwen4_exp.is_some()
4894            && mtp.is_none()
4895            && pos < input_ids.len()
4896            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
4897        {
4898            // The device path takes several prompt tokens per layer frame;
4899            // the host path runs them one by one inside the same call.
4900            let end = (pos + crate::qwen4_exp::prefill_chunk()).min(input_ids.len());
4901            let want_logits = end == input_ids.len();
4902            let mut lg = Vec::new();
4903            if let Some(b) = &mut self.qwen4_exp {
4904                crate::qwen4_exp::forward_tokens(
4905                    &b.0,
4906                    &b.1,
4907                    &b.2,
4908                    &mut b.3,
4909                    &input_ids[pos..end],
4910                    pos,
4911                    &self.inv_freq,
4912                    self.pool.as_deref(),
4913                    &mut lg,
4914                    want_logits,
4915                );
4916            }
4917            if want_logits {
4918                self.graph_logits = Some(lg);
4919            }
4920            pos = end;
4921            hidden.fill(0.0);
4922        }
4923        while self.dsv4.is_some()
4924            && mtp.is_none()
4925            && pos < input_ids.len()
4926            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
4927        {
4928            let end = (pos + prefill_chunk()).min(input_ids.len());
4929            let ids: Vec<u32> = input_ids[pos..end].to_vec();
4930            let mut lg = Vec::new();
4931            if let Some(b) = &mut self.dsv4 {
4932                let (g, layers, cfg, st) = (&b.0, &b.1, b.2, &mut b.3);
4933                crate::dsv4::forward_chunk(
4934                    g,
4935                    layers,
4936                    &cfg,
4937                    st,
4938                    &ids,
4939                    pos,
4940                    &self.inv_freq,
4941                    self.pool.as_deref(),
4942                    &mut lg,
4943                    end == input_ids.len(),
4944                );
4945            }
4946            if end == input_ids.len() {
4947                self.graph_logits = Some(lg);
4948            }
4949            pos = end;
4950            hidden = vec![0.0; self.hidden_size];
4951        }
4952        let dsv41_prefill = self.dsv41_prefill.take();
4953        while self.dsv41.is_some()
4954            && mtp.is_none()
4955            && pos < input_ids.len()
4956            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
4957        {
4958            let end = (pos + prefill_chunk()).min(input_ids.len());
4959            let ids: Vec<u32> = input_ids[pos..end].to_vec();
4960            let mut lg = Vec::new();
4961            if let Some(b) = &mut self.dsv41 {
4962                let (g, layers, cfg, st) = (&b.0, &b.1, &b.2, &mut b.3);
4963                if let Some((embeddings, participates)) = dsv41_prefill.as_ref() {
4964                    crate::dsv41::forward_chunk_masked_with_embeddings(
4965                        g,
4966                        layers,
4967                        cfg,
4968                        st,
4969                        &ids,
4970                        pos,
4971                        &embeddings[pos..end],
4972                        &participates[pos..end],
4973                        self.pool.as_deref(),
4974                        &mut lg,
4975                    );
4976                } else {
4977                    crate::dsv41::forward_chunk(
4978                        g,
4979                        layers,
4980                        cfg,
4981                        st,
4982                        &ids,
4983                        pos,
4984                        self.pool.as_deref(),
4985                        &mut lg,
4986                    );
4987                }
4988            }
4989            if end == input_ids.len() {
4990                self.graph_logits = Some(lg);
4991            }
4992            pos = end;
4993            hidden = vec![0.0; self.hidden_size];
4994        }
4995        // With dynamic routing, prefill sequentially so the φ hook fires
4996        // over the PROMPT — the router enters decode with a warm φ (the
4997        // fused-pair path skips the per-layer φ capture). o1 layers
4998        // collect their query trace in both the single and pair paths.
4999        let dyn_prefill = router.is_some();
5000        // Optional bounded calibration prefix for generation.  The normal
5001        // O(1) path seals after the full prompt; this explicit knob instead
5002        // runs only the requested prefix through exact attention, seals the
5003        // Nyström state, and streams the rest of the prompt through the same
5004        // O(1) step used by decode.  It keeps the O(1) layers' Q trace and
5005        // temporary full KV bounded by the prefix while leaving the default
5006        // full-prompt quality profile untouched.
5007        let o1_prefill_limit = o1_prefill
5008            .and_then(|requested| self.o1_effective_boundary(requested))
5009            .map(|boundary| boundary.min(input_ids.len()));
5010        let mut o1_sealed = false;
5011        if let Some(limit) = o1_prefill_limit {
5012            // Reuse the exact batched prefix machinery when available; it
5013            // records the same per-position Q trace as the full prefill.
5014            if self.can_prefill_batched() && limit > 2 {
5015                let chunk = self.prefill_chunk();
5016                let hs = self.hidden_size;
5017                while pos < limit && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
5018                    let end = (pos + chunk).min(limit);
5019                    let hb = self.prefill_batch(&input_ids[pos..end], pos);
5020                    hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
5021                    pos = end;
5022                }
5023            } else {
5024                while pos < limit && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
5025                    hidden = self.forward_layers(&self.embed_single(input_ids[pos]), pos, None);
5026                    pos += 1;
5027                }
5028            }
5029            if pos >= limit {
5030                o1_sealed = match self.o1_seal_checked() {
5031                    Ok(sealed) => sealed,
5032                    Err(err) => {
5033                        self.finish_generation(&mut mtp, &mut router, true);
5034                        return Err(err);
5035                    }
5036                };
5037                tracing::info!(
5038                    "o1 bounded prompt prefix: requested={} effective={} processed={} of {} token(s)",
5039                    o1_prefill.unwrap_or(0),
5040                    self.o1_effective_boundary(o1_prefill.unwrap_or(0))
5041                        .unwrap_or(limit),
5042                    limit,
5043                    input_ids.len()
5044                );
5045            }
5046        }
5047        // q1 hybrids on Metal: the per-position GPU token graph beats
5048        // the CPU chunk-GEMM (whose wall is the sequential scalar GDN
5049        // recurrence), so prefill goes position-by-position through the
5050        // same graph as decode. Pure-attention models keep the batched
5051        // path — there the chunk-GEMM amortization wins.
5052        let graph_prefill = self.graph_prefill_preferred();
5053        // Native Metal, q4tp GDN hybrids: the prompt through the b-row
5054        // rows graph — projections as GEMMs over up to 512 positions, the
5055        // GDN recurrence in registers on the device, K/V rows appended by
5056        // the chunk — instead of one token-graph submit per position (the
5057        // 27B: 8 tok/s → GEMM-bound). The MTP warm-up rows come out of one
5058        // batched run of the block per chunk. Any refusal leaves the rest
5059        // of the prompt to the sequential paths below.
5060        #[cfg(target_os = "macos")]
5061        if task_mask.is_none()
5062            && !dyn_prefill
5063            && (crate::gpu::q1_force() || crate::gpu::q2tp_gpu_opt_in())
5064            && crate::gpu::enabled_here()
5065            && self.gdn_cfg.is_some()
5066            && !self.per_token_stack()
5067            && input_ids.len() > 8
5068            && std::env::var("CMF_MTP_CHAIN_PROBE").is_err()
5069            && std::env::var("CMF_METAL_PREFILL").as_deref() != Ok("0")
5070        {
5071            let chunk: usize = std::env::var("CMF_METAL_PREFILL_CHUNK")
5072                .ok()
5073                .and_then(|v| v.parse().ok())
5074                .filter(|&v| (16..=512).contains(&v))
5075                .unwrap_or(256);
5076            let hs = self.hidden_size;
5077            let _tp = std::time::Instant::now();
5078            while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
5079                let end = (pos + chunk).min(input_ids.len());
5080                let hb = match self.prefill_batch_metal(&input_ids[pos..end], pos) {
5081                    MetalPrefillOutcome::Completed(hb) => hb,
5082                    MetalPrefillOutcome::Declined => break,
5083                    MetalPrefillOutcome::Failed => {
5084                        self.finish_generation(&mut mtp, &mut router, true);
5085                        return Err("ordinary Metal prefill failed after admission".into());
5086                    }
5087                };
5088                if let Some(m) = &mut mtp {
5089                    let n_pairs = if end < input_ids.len() {
5090                        end - pos
5091                    } else {
5092                        end - pos - 1
5093                    };
5094                    if n_pairs > 0 {
5095                        let pairs: Vec<(&[f32], u32)> = (0..n_pairs)
5096                            .map(|j| (&hb[j * hs..(j + 1) * hs], input_ids[pos + j + 1]))
5097                            .collect();
5098                        if !self.mtp_warm_batch_metal(m, &pairs, pos) {
5099                            for (j, (h, t)) in pairs.iter().enumerate() {
5100                                let h = h.to_vec();
5101                                let _ = self.mtp_step(m, &h, *t, pos + j);
5102                            }
5103                        }
5104                    }
5105                }
5106                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
5107                pos = end;
5108            }
5109            if std::env::var("CMF_PREFILL_PROF").is_ok() {
5110                eprintln!(
5111                    "metal-prefill: {} of {} tokens in {:.1} ms",
5112                    pos,
5113                    input_ids.len(),
5114                    _tp.elapsed().as_secs_f64() * 1e3
5115                );
5116            }
5117        }
5118        // Gemma-4 on a discrete card: the prompt through the batched wgpu
5119        // graph (`g4_batch_ingest`); its K/V land in the device mirrors
5120        // decode reads. A refusal leaves the rest of the prompt to the
5121        // chunked host prefill below.
5122        #[cfg(not(target_os = "macos"))]
5123        if task_mask.is_none()
5124            && !dyn_prefill
5125            && mtp.is_none()
5126            && o1_prefill.is_none()
5127            && batch_k > 0
5128            && pos + 1 < input_ids.len()
5129            && self.g4_batch_prefill()
5130        {
5131            let t_g4 = std::time::Instant::now();
5132            match self.g4_batch_ingest(&input_ids[pos..], pos, false) {
5133                Ok((n, last)) => {
5134                    if n > 0 {
5135                        hidden.copy_from_slice(&last);
5136                    }
5137                    if std::env::var("CMF_PREFILL_PROF").is_ok() {
5138                        eprintln!(
5139                            "gemma4 batch prefill: {n} of {} tokens in {:.1} ms",
5140                            input_ids.len() - pos,
5141                            t_g4.elapsed().as_secs_f64() * 1e3
5142                        );
5143                    }
5144                    pos += n;
5145                }
5146                Err(e) => {
5147                    self.finish_generation(&mut mtp, &mut router, true);
5148                    return Err(e);
5149                }
5150            }
5151        }
5152        self.mimo_moe_prepare();
5153        // A MoE stack larger than the card (MiMo-V2 q4tp on 96 GB): the
5154        // batched wgpu graph runs the device prefix of every chunk — its
5155        // experts resident — and the host's batched layer walk finishes
5156        // the chunk. Any refusal leaves the rest of the prompt to the
5157        // chunked prefill below.
5158        #[cfg(not(target_os = "macos"))]
5159        if task_mask.is_none()
5160            && !dyn_prefill
5161            && !graph_prefill
5162            && mtp.is_none()
5163            && o1_prefill.is_none()
5164            && !self.o1_active()
5165            && input_ids.len() > 2
5166            && self.batch_prefix_prefill()
5167        {
5168            let chunk = self.prefill_chunk().max(1);
5169            let hs = self.hidden_size;
5170            let t_bp = std::time::Instant::now();
5171            let pos0 = pos;
5172            while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
5173                let end = (pos + chunk).min(input_ids.len());
5174                let bk = end - pos;
5175                let mut hiddens = vec![0f32; bk * hs];
5176                for (j, &id) in input_ids[pos..end].iter().enumerate() {
5177                    hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
5178                }
5179                let positions: Vec<usize> = (pos..end).collect();
5180                let mut run = 0usize;
5181                let outcome = self.try_batch_graph_wgpu_prefix(
5182                    &mut hiddens,
5183                    &positions,
5184                    bk,
5185                    None,
5186                    Some(&mut run),
5187                );
5188                match outcome {
5189                    crate::gpu::BatchGraphOutcome::Completed => {
5190                        let hb = if run < self.num_layers {
5191                            self.prefill_batch_span(
5192                                PrefillIn::Hidden(&hiddens),
5193                                pos,
5194                                None,
5195                                run,
5196                                self.num_layers,
5197                            )
5198                        } else {
5199                            hiddens
5200                        };
5201                        if mimo_spec {
5202                            self.mimo_note_rows(&hb, pos);
5203                        }
5204                        hidden.copy_from_slice(&hb[(bk - 1) * hs..]);
5205                        pos = end;
5206                    }
5207                    crate::gpu::BatchGraphOutcome::Failed => {
5208                        self.finish_generation(&mut mtp, &mut router, true);
5209                        return Err("batched prefix prefill failed after admission".into());
5210                    }
5211                    crate::gpu::BatchGraphOutcome::Declined => {
5212                        // Earlier chunks left their prefix rows on the
5213                        // device only: the host walk below needs them.
5214                        #[cfg(feature = "gpu")]
5215                        if pos > pos0 {
5216                            self.pull_lagging_host_kv(0, self.num_layers, pos);
5217                        }
5218                        break;
5219                    }
5220                }
5221            }
5222            if std::env::var("CMF_PREFILL_PROF").is_ok() {
5223                eprintln!(
5224                    "batch-prefix prefill: {} of {} tokens in {:.1} ms",
5225                    pos - pos0,
5226                    input_ids.len(),
5227                    t_bp.elapsed().as_secs_f64() * 1e3
5228                );
5229            }
5230        }
5231        if task_mask.is_none()
5232            && !dyn_prefill
5233            && !graph_prefill
5234            && self.can_prefill_batched()
5235            && !self.per_token_stack()
5236            && o1_prefill.is_none()
5237            && input_ids.len() > 2
5238        {
5239            // Production prefill = the same chunked prefill-GEMM that
5240            // bench/PPL measure (roadmap §3 P0: generation used to warm
5241            // the prompt with the slower pair path — the published
5242            // prefill number didn't match real TTFT). MTP warm-up reads
5243            // each position's hidden straight from the chunk result.
5244            let chunk = self.prefill_chunk();
5245            let hs = self.hidden_size;
5246            while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
5247                let end = (pos + chunk).min(input_ids.len());
5248                let hb = self.prefill_batch(&input_ids[pos..end], pos);
5249                if mimo_spec {
5250                    self.mimo_note_rows(&hb, pos);
5251                }
5252                if let Some(m) = &mut mtp {
5253                    let probe: usize = std::env::var("CMF_MTP_CHAIN_PROBE")
5254                        .ok()
5255                        .and_then(|v| v.parse().ok())
5256                        .unwrap_or(0);
5257                    for p in pos..end {
5258                        if p + 1 < input_ids.len() {
5259                            if probe >= 1 && p + 2 < input_ids.len() {
5260                                // Teacher-forced chain acceptance (see the
5261                                // tail loop's twin): the warm-up row stays,
5262                                // the chain's rows roll back.
5263                                let (d1, mut hx) = self.mtp_step_h(
5264                                    m,
5265                                    &hb[(p - pos) * hs..(p - pos + 1) * hs],
5266                                    input_ids[p + 1],
5267                                    p,
5268                                );
5269                                let mut ok = d1 == input_ids[p + 2];
5270                                Self::chain_probe_note(0, ok);
5271                                let mut d_prev = d1;
5272                                let mut extra = 0usize;
5273                                for j in 1..probe {
5274                                    if p + 2 + j >= input_ids.len() {
5275                                        break;
5276                                    }
5277                                    let (dj, hj) = self.mtp_step_h(m, &hx, d_prev, p + 1 + j);
5278                                    extra += 1;
5279                                    ok = ok && dj == input_ids[p + 2 + j];
5280                                    Self::chain_probe_note(j, ok);
5281                                    d_prev = dj;
5282                                    hx = hj;
5283                                }
5284                                m.kv.truncate_last(extra);
5285                            } else {
5286                                let _ = self.mtp_step(
5287                                    m,
5288                                    &hb[(p - pos) * hs..(p - pos + 1) * hs],
5289                                    input_ids[p + 1],
5290                                    p,
5291                                );
5292                            }
5293                        }
5294                    }
5295                }
5296                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
5297                pos = end;
5298            }
5299        }
5300        let pair_off = std::env::var("CMF_PAIR").is_ok_and(|v| v == "0");
5301        if task_mask.is_none()
5302            && !dyn_prefill
5303            && !graph_prefill
5304            && !pair_off
5305            && self.pair_supported()
5306            && o1_prefill.is_none()
5307        {
5308            while pos + 1 < input_ids.len()
5309                && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
5310            {
5311                let e1 = self.embed_single(input_ids[pos]);
5312                let e2 = self.embed_single(input_ids[pos + 1]);
5313                let (h1, h2) = self.forward_pair(&e1, &e2, pos);
5314                if mimo_spec {
5315                    self.mimo_note_rows(&h1, pos);
5316                    self.mimo_note_rows(&h2, pos + 1);
5317                }
5318                // Both prefill tokens are real → commit lane-2 states.
5319                self.commit_linear_scratch();
5320                if let Some(m) = &mut mtp {
5321                    let _ = self.mtp_step(m, &h1, input_ids[pos + 1], pos);
5322                    if pos + 2 < input_ids.len() {
5323                        let probe: usize = std::env::var("CMF_MTP_CHAIN_PROBE")
5324                            .ok()
5325                            .and_then(|v| v.parse().ok())
5326                            .unwrap_or(0);
5327                        if probe >= 1 && pos + 3 < input_ids.len() {
5328                            // Same teacher-forced chain table as the tail
5329                            // loop below, fed from the pair path that owns
5330                            // most prefill positions.
5331                            let (d1, mut hx) = self.mtp_step_h(m, &h2, input_ids[pos + 2], pos + 1);
5332                            let mut ok = d1 == input_ids[pos + 3];
5333                            Self::chain_probe_note(0, ok);
5334                            let mut d_prev = d1;
5335                            let mut extra = 0usize;
5336                            for j in 1..probe {
5337                                if pos + 3 + j >= input_ids.len() {
5338                                    break;
5339                                }
5340                                let (dj, hj) = self.mtp_step_h(m, &hx, d_prev, pos + 2 + j);
5341                                extra += 1;
5342                                ok = ok && dj == input_ids[pos + 3 + j];
5343                                Self::chain_probe_note(j, ok);
5344                                d_prev = dj;
5345                                hx = hj;
5346                            }
5347                            m.kv.truncate_last(extra);
5348                        } else {
5349                            let _ = self.mtp_step(m, &h2, input_ids[pos + 2], pos + 1);
5350                        }
5351                    }
5352                }
5353                hidden = h2;
5354                pos += 2;
5355            }
5356        }
5357        // Batched GPU prefill for the wgpu decode graph (GDN hybrids): K prompt
5358        // positions per submit — projections/FFN as GEMMs (weight once per K),
5359        // attention/GDN looped inside — instead of one whole-graph submit per
5360        // position. Falls through to the per-position graph on any refusal.
5361        // Batched prefill is opt-in (CMF_BATCH_K>0). Default 0 = per-position
5362        // graph prefill. (Steady-state decode is provably identical either way —
5363        // token-graph submit and lm_head both unchanged — so this only trades
5364        // prefill wall.)
5365        // A bounded O(1) prefix is the one post-seal prompt interval: only
5366        // admit its batch when the device O(1) route is explicitly enabled and
5367        // every sealed layer exposes a portable view. The same batch size and
5368        // refusal behavior remain the ordinary controls/comparator.
5369        let o1_batch_ready = o1_sealed
5370            && o1_prefill.is_some()
5371            && mtp.is_none()
5372            && std::env::var("CMF_O1_GPU").as_deref() == Ok("1")
5373            && (0..self.num_layers).all(|li| {
5374                let cache = &self.kv_cache.layers[self.phys_layer(li)];
5375                cache.o1.is_none() || cache.o1_views().is_some()
5376            });
5377        // The ordinary graph-prefill route can share each completed trunk
5378        // chunk with an attached MTP head.  Keep chain probing on its
5379        // established per-position path: the probe deliberately needs every
5380        // teacher-forced draft row and its rollback table.
5381        let mtp_batch_prefill = mtp.is_some()
5382            && graph_prefill
5383            && task_mask.is_none()
5384            && !dyn_prefill
5385            && !self.o1_active()
5386            && std::env::var("CMF_MTP_CHAIN_PROBE").is_err();
5387        if batch_k > 0
5388            && (graph_prefill || o1_batch_ready)
5389            && task_mask.is_none()
5390            && (!self.o1_active() || o1_batch_ready)
5391            && (mtp.is_none() || mtp_batch_prefill)
5392            && !dyn_prefill
5393            && pos + 1 < input_ids.len()
5394        {
5395            let hs = self.hidden_size;
5396            let chunk = batch_k;
5397            while pos < input_ids.len() {
5398                let end = (pos + chunk).min(input_ids.len());
5399                let bk = end - pos;
5400                let mut hiddens = vec![0f32; bk * hs];
5401                for (j, &id) in input_ids[pos..end].iter().enumerate() {
5402                    hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
5403                }
5404                let positions: Vec<usize> = (pos..end).collect();
5405                let t_chunk = std::time::Instant::now();
5406                let outcome = self.try_batch_graph_wgpu(&mut hiddens, &positions, bk, None);
5407                let ok_b = outcome == crate::gpu::BatchGraphOutcome::Completed;
5408                if std::env::var("CMF_GRAPH_PROF").is_ok() {
5409                    let ms = t_chunk.elapsed().as_secs_f64() * 1000.0;
5410                    eprintln!(
5411                        "batch-chunk: phase=prompt mode={} k={bk} outcome={outcome:?} {ms:.1} ms ({:.1} tok/s)",
5412                        if o1_batch_ready {
5413                            "o1"
5414                        } else if mtp_batch_prefill {
5415                            "ordinary_mtp"
5416                        } else {
5417                            "ordinary"
5418                        },
5419                        bk as f64 / (ms / 1000.0)
5420                    );
5421                }
5422                {
5423                    use std::sync::atomic::{AtomicBool, Ordering};
5424                    static SAID: AtomicBool = AtomicBool::new(false);
5425                    if !SAID.swap(true, Ordering::Relaxed) {
5426                        if ok_b {
5427                            tracing::info!(
5428                                "batched prefill: ACTIVE mode={} (k={bk})",
5429                                if o1_batch_ready {
5430                                    "o1"
5431                                } else if mtp_batch_prefill {
5432                                    "ordinary_mtp"
5433                                } else {
5434                                    "ordinary"
5435                                }
5436                            );
5437                        } else {
5438                            tracing::warn!("batched prefill {:?} — per-position graph", outcome);
5439                        }
5440                    }
5441                }
5442                if ok_b {
5443                    if mimo_spec {
5444                        self.mimo_note_rows(&hiddens, pos);
5445                    }
5446                    if mtp_batch_prefill {
5447                        let n_pairs = mtp_prefill_pair_count(pos, end, input_ids.len());
5448                        if n_pairs > 0 {
5449                            // `hiddens` is owned by this chunk, so materialize
5450                            // row slices before borrowing the detached MTP
5451                            // module.  The last prompt row has no successor;
5452                            // the helper above is the single source of that
5453                            // boundary rule.
5454                            let rows: Vec<Vec<f32>> = (0..n_pairs)
5455                                .map(|j| hiddens[j * hs..(j + 1) * hs].to_vec())
5456                                .collect();
5457                            let pairs: Vec<(&[f32], u32)> = rows
5458                                .iter()
5459                                .enumerate()
5460                                .map(|(j, row)| (row.as_slice(), input_ids[pos + j + 1]))
5461                                .collect();
5462                            if std::env::var("CMF_GRAPH_PROF").is_ok() {
5463                                eprintln!(
5464                                    "mtp-warm: phase=prompt mode=ordinary_mtp first_pos={} pairs={} last_pos={}",
5465                                    pos,
5466                                    n_pairs,
5467                                    pos + n_pairs - 1,
5468                                );
5469                            }
5470                            let warm_error = if let Some(m) = mtp.as_mut() {
5471                                self.mtp_warm_prefill_pairs(m, &pairs, pos).err()
5472                            } else {
5473                                None
5474                            };
5475                            if let Some(err) = warm_error {
5476                                // The trunk batch was already admitted.  A
5477                                // failed MTP warm-up therefore clears both
5478                                // mirrors and exits; continuing would pair a
5479                                // current trunk state with a stale MTP cache.
5480                                self.finish_generation(&mut mtp, &mut router, true);
5481                                return Err(err.to_string());
5482                            }
5483                        }
5484                    }
5485                    hidden.copy_from_slice(&hiddens[(bk - 1) * hs..]);
5486                    pos = end;
5487                } else if outcome == crate::gpu::BatchGraphOutcome::Failed {
5488                    // A failed batch may have advanced a device recurrent
5489                    // state (ordinary GDN or sealed O(1)). A CPU fallback
5490                    // would then observe stale accumulators, so clear the
5491                    // request state and make the failure explicit.
5492                    self.finish_generation(&mut mtp, &mut router, true);
5493                    return Err(if o1_batch_ready {
5494                        "sealed O(1) batch graph failed after admission".to_string()
5495                    } else {
5496                        "ordinary recurrent batch graph failed after admission".to_string()
5497                    });
5498                } else {
5499                    break; // unsupported → per-position graph handles the rest
5500                }
5501            }
5502        }
5503        // Resident Embryo graph: the prompt in chunks of one submit each
5504        // instead of one whole-graph submit per position; the last chunk
5505        // carries the logits exactly as the per-position walk would.
5506        if graph_prefill
5507            && task_mask.is_none()
5508            && mtp.is_none()
5509            && !dyn_prefill
5510            && pos == 0
5511            && input_ids.len() > 1
5512            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
5513        {
5514            if let Some(lg) = self.embryo_prefill_chunked(input_ids, 0) {
5515                self.graph_logits = Some(lg);
5516                hidden = vec![0.0; self.hidden_size];
5517                pos = input_ids.len();
5518            }
5519        }
5520        while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
5521            self.graph_want_logits = fuse_lm && pos + 1 == input_ids.len();
5522            hidden = self.forward_layers(&self.embed_single(input_ids[pos]), pos, task_mask);
5523            if mimo_spec {
5524                self.mimo_note_rows(&hidden, pos);
5525            }
5526            if let Some(m) = &mut mtp {
5527                if pos + 1 < input_ids.len() {
5528                    // `CMF_MTP_CHAIN_PROBE=k`: teacher-forced acceptance of a
5529                    // CHAINED draft — iterate the head on its own hidden k
5530                    // deep and score every depth against the prompt's real
5531                    // continuation. The economics of a k-token speculative
5532                    // round stand or fall on this table.
5533                    let probe: usize = std::env::var("CMF_MTP_CHAIN_PROBE")
5534                        .ok()
5535                        .and_then(|v| v.parse().ok())
5536                        .unwrap_or(0);
5537                    if probe >= 1 && pos + 2 < input_ids.len() {
5538                        let (d1, mut hx) = self.mtp_step_h(m, &hidden, input_ids[pos + 1], pos);
5539                        let mut ok = d1 == input_ids[pos + 2];
5540                        Self::chain_probe_note(0, ok);
5541                        let mut d_prev = d1;
5542                        let mut extra = 0usize;
5543                        for j in 1..probe {
5544                            if pos + 2 + j >= input_ids.len() {
5545                                break;
5546                            }
5547                            let (dj, hj) = self.mtp_step_h(m, &hx, d_prev, pos + 1 + j);
5548                            extra += 1;
5549                            ok = ok && dj == input_ids[pos + 2 + j];
5550                            Self::chain_probe_note(j, ok);
5551                            d_prev = dj;
5552                            hx = hj;
5553                        }
5554                        // The chain's rows are speculation, not the prompt —
5555                        // keep only the warmup row the plain path would add.
5556                        m.kv.truncate_last(extra);
5557                    } else {
5558                        let _ = self.mtp_step(m, &hidden, input_ids[pos + 1], pos);
5559                    }
5560                }
5561            }
5562            pos += 1;
5563        }
5564        if std::env::var("CMF_PREFILL_PROF").is_ok() {
5565            eprintln!(
5566                "prefill: {} tokens in {:.1} ms (batch_k={batch_k})",
5567                input_ids.len(),
5568                _tpf.elapsed().as_secs_f64() * 1000.0
5569            );
5570        }
5571        if self
5572            .graph_failed
5573            .swap(false, std::sync::atomic::Ordering::Relaxed)
5574        {
5575            // MTP is detached for speculative generation.  Restore the
5576            // module before returning the terminal graph error; otherwise a
5577            // failed request would silently remove the head from a pooled
5578            // pipeline and the next request would lose its configured route.
5579            self.finish_generation(&mut mtp, &mut router, true);
5580            return Err("GPU token graph failed during prefill".to_string());
5581        }
5582        // Cancelled mid-prefill: the cache holds a partial prompt —
5583        // drop the reuse history and return an empty generation.
5584        if self
5585            .cancel
5586            .swap(false, std::sync::atomic::Ordering::Relaxed)
5587        {
5588            // A cancelled prefill can already have advanced the device
5589            // mirror. Drop the whole partial sequence so a pooled pipeline
5590            // cannot carry that state into its next request.
5591            self.finish_generation(&mut mtp, &mut router, true);
5592            return Ok(GenerateResult {
5593                text: String::new(),
5594                token_ids: Vec::new(),
5595                prompt_tokens: input_ids.len(),
5596                tokens_generated: 0,
5597                finish_reason: "cancelled".to_string(),
5598                mtp_drafted: 0,
5599                mtp_accepted: 0,
5600                token_confidence: Vec::new(),
5601                traces: Vec::new(),
5602            });
5603        }
5604
5605        // Prompt absorbed → freeze the o1 layers' skeletons; from here
5606        // every decode step on those layers is O(W + m·dv + m²).
5607        if !o1_sealed {
5608            match self.o1_seal_checked() {
5609                Ok(_) => {}
5610                Err(err) => {
5611                    self.finish_generation(&mut mtp, &mut router, true);
5612                    return Err(err);
5613                }
5614            }
5615        }
5616
5617        // Commit one token: push, check EOS, stream. Returns false = stop.
5618        macro_rules! commit {
5619            ($id:expr) => {{
5620                all_ids.push($id);
5621                generated += 1;
5622                self.note_draft_id($id);
5623                if self.tokenizer.is_eos($id) && !self.ignore_eos {
5624                    finish_reason = "stop".to_string();
5625                    false
5626                } else {
5627                    let token_text = self.tokenizer.decode_token($id);
5628                    let mut go = true;
5629                    if let Some(ref mut cb) = on_token {
5630                        if !cb(&token_text) {
5631                            finish_reason = "cancelled".to_string();
5632                            go = false;
5633                        }
5634                    }
5635                    go
5636                }
5637            }};
5638        }
5639
5640        // Speculation is decided by MEASUREMENT, not by an acceptance
5641        // model. A k=4 round costs ~3.8 plain tokens on the 5090 (draft
5642        // 6.6 + verify 66.6 + commit 4.8 ms against a 20.6 ms token), so it
5643        // pays only when the head lands ~2.8 of 4 — predictable text (code,
5644        // structured output) does, free prose often does not, and the
5645        // ratio at which the two cross depends on the card and the context
5646        // depth. So: four speculative rounds timed, then eight plain
5647        // tokens timed, and the faster arm runs until a re-check 256
5648        // tokens later (context growth moves the balance). The trial
5649        // costs at most a few tokens of the slower arm per 256.
5650        let mut spec_trial = SpecTrial::Spec {
5651            t0: std::time::Instant::now(),
5652            gen0: generated,
5653            rounds: 0,
5654        };
5655        // The token-count proxy prices a round at ~1.9 plain tokens. That
5656        // holds for the Metal rounds whose cost was measured — greedy and
5657        // the sparse sampling chain — so an expensive round (the dense
5658        // chain, reachable only by `CMF_GRAPH_SPEC_SAMPLE=1`) still times
5659        // the plain path before it decides.
5660        let mut spec_mon = SpecMon {
5661            metal: graph_spec && crate::gpu::q1_force() && spec_cheap_round,
5662            ..SpecMon::default()
5663        };
5664        let mut spec_watchdog_off = false;
5665        // CMF_GRAPH_SPEC_TIME: the round walls so far (round 1 excluded —
5666        // it pays the scratch), for the outlier test on each new one
5667        let mut spec_walls: Vec<f32> = Vec::new();
5668        // ... and the end of the last round: the host time between rounds
5669        // (token commits, streaming, the loop top) is printed at level 2
5670        let mut spec_round_end: Option<std::time::Instant> = None;
5671        if mimo_spec {
5672            if let Ok(path) = std::env::var("CMF_MIMO_MTP_PROBE") {
5673                if let Some(mut st) = self.mimo_mtp.take() {
5674                    self.mimo_mtp_probe(&mut st, input_ids, &path);
5675                    self.mimo_mtp = Some(st);
5676                }
5677            }
5678        }
5679        // ── Decode ──
5680        let mut next_pos = input_ids.len();
5681        'decode: while generated < max_tokens {
5682            if self
5683                .graph_failed
5684                .swap(false, std::sync::atomic::Ordering::Relaxed)
5685            {
5686                // Keep the detached MTP module attached after a terminal
5687                // graph error so the pipeline can be reused for a fresh
5688                // sequence.  `clear_sequence_state` only clears mirrors and
5689                // host KV; it cannot recover a module dropped here.
5690                self.finish_generation(&mut mtp, &mut router, true);
5691                return Err("GPU token graph failed during decode".to_string());
5692            }
5693            if self
5694                .cancel
5695                .swap(false, std::sync::atomic::Ordering::Relaxed)
5696            {
5697                finish_reason = "cancelled".to_string();
5698                break 'decode;
5699            }
5700            // A rejected speculative draft already drew this position's
5701            // token from the residual distribution (graph_spec_step); it
5702            // is committed as-is — sampling again from the row's logits
5703            // would bias the stream toward the target's mode.
5704            if mimo_spec && next_pos > 0 {
5705                // Every path leaves `hidden` = the backbone output at
5706                // next_pos-1; the draft layers read it (idempotent).
5707                self.mimo_note_rows(&hidden, next_pos - 1);
5708            }
5709            let forced = self.spec_forced.take();
5710            let mut logits = match (forced, self.graph_logits.take()) {
5711                (Some(_), _) => Vec::new(),
5712                (None, Some(lg)) => lg,
5713                (None, None) => {
5714                    let _prof = crate::cpuprof::time(crate::cpuprof::Slot::Head);
5715                    // Pooled-tail mode: the head as one layer-less device
5716                    // pass (final-norm + matvec + readback). Any decline —
5717                    // no pool, unresolvable weight, backend off — keeps the
5718                    // host head exactly as before.
5719                    #[cfg(feature = "gpu")]
5720                    let logits_out = if let Some(lg) = self.m3_device_logits(&hidden) {
5721                        lg
5722                    } else {
5723                        inference::rms_norm_into(
5724                            &hidden,
5725                            &self.weights.final_norm,
5726                            self.rms_eps,
5727                            self.norm_style,
5728                            &mut self.ws.n1,
5729                        );
5730                        self.lm_head_forward(&self.ws.n1)
5731                    };
5732                    #[cfg(not(feature = "gpu"))]
5733                    let logits_out = {
5734                        inference::rms_norm_into(
5735                            &hidden,
5736                            &self.weights.final_norm,
5737                            self.rms_eps,
5738                            self.norm_style,
5739                            &mut self.ws.n1,
5740                        );
5741                        self.lm_head_forward(&self.ws.n1)
5742                    };
5743                    logits_out
5744                }
5745            };
5746            // CMF_LOGIT_DUMP=<path>: the first decode step's hidden + logits
5747            // as raw f32 (hidden first) — cross-backend numerics diffing.
5748            if generated
5749                == std::env::var("CMF_LOGIT_DUMP_STEP")
5750                    .ok()
5751                    .and_then(|v| v.parse().ok())
5752                    .unwrap_or(0)
5753            {
5754                if let Ok(path) = std::env::var("CMF_LOGIT_DUMP") {
5755                    let mut bytes: Vec<u8> = Vec::with_capacity((hidden.len() + logits.len()) * 4);
5756                    for v in hidden.iter().chain(logits.iter()) {
5757                        bytes.extend_from_slice(&v.to_le_bytes());
5758                    }
5759                    if let Err(e) = std::fs::write(&path, &bytes) {
5760                        eprintln!("logit dump: failed to write {path}: {e}");
5761                        self.finish_generation(&mut mtp, &mut router, true);
5762                        return Err(format!("logit dump write failed: {e}"));
5763                    }
5764                }
5765            }
5766            // CMF_LOGIT_DUMP_ALL=<dir>: every decode step's logits as raw
5767            // f32, `<dir>/step{n:05}.f32` — step-by-step backend diffing
5768            // (a greedy run on two backends compares until they diverge).
5769            if let Ok(dir) = std::env::var("CMF_LOGIT_DUMP_ALL") {
5770                if !logits.is_empty() {
5771                    let path = std::path::Path::new(&dir).join(format!("step{generated:05}.f32"));
5772                    let bytes: Vec<u8> = logits.iter().flat_map(|v| v.to_le_bytes()).collect();
5773                    if let Err(e) =
5774                        std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(&path, &bytes))
5775                    {
5776                        eprintln!("logit dump: failed to write {}: {e}", path.display());
5777                    }
5778                }
5779            }
5780            let t_next = match forced.or_else(|| forced_ids_at(generated)) {
5781                Some(c) => c,
5782                None => {
5783                    let _prof = crate::cpuprof::time(crate::cpuprof::Slot::Sampler);
5784                    sampler::sample_with_scratch_pool(
5785                        &logits,
5786                        &self.sampler_config,
5787                        self.sampler_config.penalty_past(&all_ids, bounded_native),
5788                        &mut self.rng,
5789                        &mut self.sampler_scratch,
5790                        self.pool.as_deref(),
5791                    )
5792                }
5793            };
5794            if self.confidence_on {
5795                confidence.push(if logits.is_empty() {
5796                    0.0
5797                } else {
5798                    sampler::top1_prob_pool(
5799                        self.pool.as_deref(),
5800                        &mut self.sampler_scratch,
5801                        &logits,
5802                        t_next,
5803                        calib_temp,
5804                    )
5805                });
5806            }
5807            if !logits.is_empty() {
5808                attention::recycle_buf(&mut logits);
5809            }
5810            if trace_on {
5811                // active_skill = the overlay in force while this token was
5812                // generated; recon/switched are filled after the post-emit
5813                // routing eval below (freshest coherence for this token).
5814                let skill = router.as_ref().and_then(|r| r.active_id());
5815                traces.push(TokenTrace {
5816                    t: generated,
5817                    token_id: t_next,
5818                    confidence: confidence.last().copied().unwrap_or(0.0),
5819                    active_skill: skill,
5820                    recon: None,
5821                    switched: false,
5822                });
5823            }
5824            if !commit!(t_next) {
5825                break 'decode;
5826            }
5827            if generated >= max_tokens {
5828                break 'decode;
5829            }
5830
5831            // Catch-all for decode paths that bypass the walks' own trim
5832            // (a graph step, a speculative round).
5833            self.swa_trim_tails();
5834            if self.dsv41.is_none() && self.kv_cache.needs_eviction() {
5835                // Say it ONCE, loudly: past this point the model keeps
5836                // talking but has lost half its context, and on a GDN
5837                // hybrid the graph's device state goes stale on top. The
5838                // Qwen3.8 bring-up spent a day reading this cliff as
5839                // three different model bugs.
5840                static SAID: std::sync::Once = std::sync::Once::new();
5841                SAID.call_once(|| {
5842                    tracing::warn!(
5843                        "KV cache full at {} positions — evicting half; quality \
5844                         will degrade. Raise CMF_MAX_SEQ.",
5845                        self.kv_cache.max_seq_len,
5846                    );
5847                });
5848                let keep = (self.kv_cache.max_seq_len / 2).max(1);
5849                self.kv_cache.evict(keep);
5850            }
5851
5852            // Advance the speculation trial: plain-phase accounting and
5853            // the periodic re-check happen here, on every token.
5854            if graph_spec {
5855                match spec_trial {
5856                    SpecTrial::Plain { t0, gen0 } if spec_mon.plain_done(t0, gen0, generated) => {
5857                        spec_mon.plain_ms =
5858                            t0.elapsed().as_secs_f64() * 1e3 / (generated - gen0) as f64;
5859                        let keep = spec_mon.pays();
5860                        tracing::info!(
5861                            "speculation trial: {:.2} tok/round in {:.1} ms vs plain {:.1} ms/tok — {}",
5862                            spec_mon.tokens,
5863                            spec_mon.round_ms,
5864                            spec_mon.plain_ms,
5865                            if keep { "speculating" } else { "plain" }
5866                        );
5867                        spec_mon.fails = 0;
5868                        spec_trial = SpecTrial::Decided {
5869                            spec: keep,
5870                            recheck_at: if keep { usize::MAX } else { generated + 128 },
5871                        };
5872                    }
5873                    SpecTrial::Decided { recheck_at, .. } if generated >= recheck_at => {
5874                        spec_mon.n = 0;
5875                        spec_trial = SpecTrial::Spec {
5876                            t0: std::time::Instant::now(),
5877                            gen0: generated,
5878                            rounds: 0,
5879                        };
5880                    }
5881                    _ => {}
5882                }
5883                spec_watchdog_off = matches!(
5884                    spec_trial,
5885                    SpecTrial::Plain { .. } | SpecTrial::Decided { spec: false, .. }
5886                );
5887            }
5888            // ── MiMo-V2 draft stack: draft K, verify K+1 rows in one batch ──
5889            if mimo_spec && generated + 1 < max_tokens && next_pos > 0 {
5890                let budget = max_tokens - generated - 1;
5891                if let Some(mut st) = self.mimo_mtp.take() {
5892                    let k = st.depth.min(budget);
5893                    let r = self.mimo_spec_round(&mut st, next_pos, &all_ids, k);
5894                    self.mimo_mtp = Some(st);
5895                    let r = match r {
5896                        Ok(r) => r,
5897                        Err(err) => {
5898                            self.finish_generation(&mut mtp, &mut router, true);
5899                            return Err(err);
5900                        }
5901                    };
5902                    if let Some(r) = r {
5903                        drafted += r.drafted;
5904                        accepted += r.accepted.len();
5905                        let mut stopped = false;
5906                        for &id in &r.accepted {
5907                            if self.confidence_on {
5908                                confidence.push(0.0);
5909                            }
5910                            if !commit!(id) {
5911                                stopped = true;
5912                                break;
5913                            }
5914                        }
5915                        if stopped {
5916                            break 'decode;
5917                        }
5918                        next_pos += r.accepted.len() + 1;
5919                        hidden = r.hidden;
5920                        // The loop top chooses the round's own token from
5921                        // these logits — the same sampler, same history.
5922                        self.graph_logits = Some(r.logits);
5923                        continue 'decode;
5924                    }
5925                }
5926            }
5927            // ── Qwen3.8-Flash-Next draft head: k greedy drafts from the MTP
5928            //    sidecar, one batched verify window on the device ──
5929            #[cfg(feature = "gpu")]
5930            if self.speculative
5931                && self.qwen4_exp.is_some()
5932                && task_mask.is_none()
5933                && self.sampler_config.temperature < 1e-6
5934                && generated + 1 < max_tokens
5935                && next_pos > 0
5936                && std::env::var("CMF_QWEN_MTP").as_deref() != Ok("0")
5937            {
5938                let r = match &mut self.qwen4_exp {
5939                    Some(b) => crate::qwen4_exp::spec_round(
5940                        &b.0,
5941                        &b.1,
5942                        &b.2,
5943                        &mut b.3,
5944                        next_pos,
5945                        &all_ids,
5946                        &self.inv_freq,
5947                        self.pool.as_deref(),
5948                    ),
5949                    None => None,
5950                };
5951                if let Some(r) = r {
5952                    drafted += r.drafted;
5953                    accepted += r.accepted.len();
5954                    let mut stopped = false;
5955                    for &id in &r.accepted {
5956                        if self.confidence_on {
5957                            confidence.push(0.0);
5958                        }
5959                        if !commit!(id) {
5960                            stopped = true;
5961                            break;
5962                        }
5963                    }
5964                    if stopped {
5965                        break 'decode;
5966                    }
5967                    next_pos += r.accepted.len() + 1;
5968                    hidden.fill(0.0);
5969                    self.graph_logits = Some(r.logits);
5970                    continue 'decode;
5971                }
5972            }
5973            match &mut mtp {
5974                // ── Graph speculation: chain-draft, batch-verify on device ──
5975                #[cfg(feature = "gpu")]
5976                Some(m)
5977                    if graph_spec
5978                        && !spec_watchdog_off
5979                        && generated + 1 < max_tokens
5980                        && next_pos > 0 =>
5981                {
5982                    let t_round = std::time::Instant::now();
5983                    if spec_time_level() >= 2 {
5984                        if let Some(t) = spec_round_end.take() {
5985                            eprintln!(
5986                                "spec-gap {:.2} ms (host between rounds)",
5987                                t.elapsed().as_secs_f64() * 1e3
5988                            );
5989                        }
5990                    }
5991                    spec_stamps_begin();
5992                    // device buffers allocated during this round: a
5993                    // first-touch Shared allocation is zero-filled inside
5994                    // the command buffer that uses it, which is what the
5995                    // long outlier rounds were
5996                    #[cfg(target_os = "macos")]
5997                    let allocs0 =
5998                        crate::gpu_metal::IO_BUF_ALLOCS.load(std::sync::atomic::Ordering::Relaxed);
5999                    #[cfg(not(target_os = "macos"))]
6000                    let allocs0 = 0u64;
6001                    if let Some((extra, n_pos, new_h)) = self.graph_spec_step(
6002                        m,
6003                        &hidden,
6004                        t_next,
6005                        next_pos,
6006                        &mut drafted,
6007                        &mut accepted,
6008                        &mut all_ids,
6009                        max_tokens - generated,
6010                    ) {
6011                        next_pos = n_pos;
6012                        hidden = new_h;
6013                        let level = spec_time_level();
6014                        if level > 0 {
6015                            let wall = t_round.elapsed().as_secs_f32() * 1e3;
6016                            let stamps = spec_stamps_take();
6017                            // the running median of the rounds before this
6018                            // one (round 1 pays the scratch: not a sample)
6019                            let median = if spec_walls.len() >= 3 {
6020                                let mut s = spec_walls.clone();
6021                                s.sort_by(|a, b| a.partial_cmp(b).unwrap());
6022                                Some(s[s.len() / 2])
6023                            } else {
6024                                None
6025                            };
6026                            let outlier = median.is_some_and(|m| wall > 1.4 * m);
6027                            #[cfg(target_os = "macos")]
6028                            let allocs = crate::gpu_metal::IO_BUF_ALLOCS
6029                                .load(std::sync::atomic::Ordering::Relaxed)
6030                                - allocs0;
6031                            #[cfg(not(target_os = "macos"))]
6032                            let allocs = allocs0;
6033                            eprintln!(
6034                                "spec-round wall {wall:.1} ms → {} tokens{}{}",
6035                                extra.len() + 1,
6036                                if allocs > 0 {
6037                                    format!(" [{allocs} new device buffers]")
6038                                } else {
6039                                    String::new()
6040                                },
6041                                match (outlier, median) {
6042                                    (true, Some(m)) => format!(" OUTLIER (median {m:.1})"),
6043                                    _ => String::new(),
6044                                }
6045                            );
6046                            if level >= 2 || outlier {
6047                                let sum: f32 = stamps.iter().map(|s| s.1).sum();
6048                                eprintln!(
6049                                    "spec-stamps: {}| untracked {:.1}",
6050                                    spec_stamps_format(&stamps),
6051                                    wall - sum
6052                                );
6053                            }
6054                            if spec_mon.n >= 1 {
6055                                spec_walls.push(wall);
6056                            }
6057                        }
6058                        // One speculative round done: the monitor counts it
6059                        // (round 1 untimed — it pays the batch scratch and
6060                        // the draft mirror), and the trial advances.
6061                        spec_mon.round(t_round.elapsed().as_secs_f64() * 1e3, extra.len() + 1);
6062                        // the round's tokens land in `generated` below; the
6063                        // plain phase must start counting AFTER them
6064                        spec_trial = Self::spec_trial_round(
6065                            spec_trial,
6066                            &mut spec_mon,
6067                            generated + extra.len() + 1,
6068                        );
6069                        let mut stopped = false;
6070                        for &id in &extra {
6071                            if self.confidence_on {
6072                                confidence.push(0.0);
6073                            }
6074                            if !commit!(id) {
6075                                stopped = true;
6076                                break;
6077                            }
6078                        }
6079                        if stopped {
6080                            break 'decode;
6081                        }
6082                        if spec_time_level() >= 2 {
6083                            spec_round_end = Some(std::time::Instant::now());
6084                        }
6085                        continue 'decode;
6086                    }
6087                    if self
6088                        .graph_failed
6089                        .swap(false, std::sync::atomic::Ordering::Relaxed)
6090                    {
6091                        // `graph_spec_step` may have detached MTP while a
6092                        // warm-up was in flight.  Do not reinterpret its
6093                        // terminal device failure as a plain decode step;
6094                        // restore the head, clear both mirrors, and surface
6095                        // one explicit error to the caller.
6096                        self.finish_generation(&mut mtp, &mut router, true);
6097                        return Err("GPU MTP graph failed during speculative decode".to_string());
6098                    }
6099                    // Declined (batch graph refused): plain forward below —
6100                    // and a round that produced one token for the trial's
6101                    // ledger, so a graph that keeps refusing is measured out
6102                    // like a head that keeps missing (it was spinning
6103                    // forever on a file whose batch graph declines).
6104                    // A declined round is not a cheap one-token round — it
6105                    // is a verify that does not exist for this file (a
6106                    // healed q8_2f tail measured 760 drafts, 0 accepted, 33
6107                    // against 48.8 tok/s while the monitor called the draft
6108                    // alone "paying"). Count it as the losing streak in one.
6109                    spec_mon.round(t_round.elapsed().as_secs_f64() * 1e3, 1);
6110                    spec_mon.tokens = 0.0;
6111                    spec_mon.fails = 3;
6112                    spec_trial = Self::spec_trial_round(spec_trial, &mut spec_mon, generated + 1);
6113                    hidden = self.forward_layers(&self.embed_single(t_next), next_pos, task_mask);
6114                    next_pos += 1;
6115                    continue 'decode;
6116                }
6117                // ── Speculative: draft t+2, verify in a fused pair ──
6118                Some(m) if !graph_spec && generated + 1 < max_tokens => {
6119                    let draft = self.mtp_step(m, &hidden, t_next, next_pos - 1);
6120                    drafted += 1;
6121                    let emb1 = self.embed_single(t_next);
6122                    let emb2 = self.embed_single(draft);
6123                    let (h1, h2) = self.forward_pair(&emb1, &emb2, next_pos);
6124
6125                    inference::rms_norm_into(
6126                        &h1,
6127                        &self.weights.final_norm,
6128                        self.rms_eps,
6129                        self.norm_style,
6130                        &mut self.ws.n1,
6131                    );
6132                    let mut logits1 = self.lm_head_forward(&self.ws.n1);
6133                    let t_after = sampler::sample_with_scratch_pool(
6134                        &logits1,
6135                        &self.sampler_config,
6136                        self.sampler_config.penalty_past(&all_ids, bounded_native),
6137                        &mut self.rng,
6138                        &mut self.sampler_scratch,
6139                        self.pool.as_deref(),
6140                    );
6141                    if self.confidence_on {
6142                        confidence.push(sampler::top1_prob_pool(
6143                            self.pool.as_deref(),
6144                            &mut self.sampler_scratch,
6145                            &logits1,
6146                            t_after,
6147                            calib_temp,
6148                        ));
6149                    }
6150                    attention::recycle_buf(&mut logits1);
6151                    if trace_on {
6152                        // Speculative decode is mutually exclusive with
6153                        // dynamic routing (router is None here) — no skill.
6154                        traces.push(TokenTrace {
6155                            t: generated,
6156                            token_id: t_after,
6157                            confidence: confidence.last().copied().unwrap_or(0.0),
6158                            active_skill: None,
6159                            recon: None,
6160                            switched: false,
6161                        });
6162                    }
6163                    let stop = !commit!(t_after);
6164
6165                    if t_after == draft {
6166                        accepted += 1;
6167                        self.commit_linear_scratch();
6168                        let _ = self.mtp_step(m, &h1, t_after, next_pos);
6169                        hidden = h2;
6170                        next_pos += 2;
6171                    } else {
6172                        // The draft lane is wrong: roll its KV entry back.
6173                        for layer in &mut self.kv_cache.layers {
6174                            layer.truncate_last(1);
6175                        }
6176                        if !stop {
6177                            let _ = self.mtp_step(m, &h1, t_after, next_pos);
6178                            hidden = self.forward_layers(
6179                                &self.embed_single(t_after),
6180                                next_pos + 1,
6181                                None,
6182                            );
6183                        }
6184                        next_pos += 2;
6185                    }
6186                    if stop {
6187                        break 'decode;
6188                    }
6189                }
6190                // ── Vanilla: forward the sampled token ──
6191                _ => {
6192                    // ── DeepSeek-V4 speculative decode (CMF_DSV4_SPEC=1):
6193                    // draft five on the card, verify batched, commit the
6194                    // accepted prefix. Greedy only; a rejected token's state
6195                    // is restored and replayed, so output equals the walk. ──
6196                    #[cfg(feature = "gpu")]
6197                    if Self::dsv4_spec_on() && self.dsv4.is_some() {
6198                        static SAID: std::sync::Once = std::sync::Once::new();
6199                        SAID.call_once(|| {
6200                            eprintln!(
6201                                "dsv4-spec гейт: mtp={} mask={} router={} trace={} temp={} rep={} ",
6202                                !self.dsv4_mtp.is_empty(),
6203                                task_mask.is_none(),
6204                                router.is_none(),
6205                                !trace_on,
6206                                self.sampler_config.temperature < 1e-6,
6207                                self.sampler_config.repetition_penalty == 1.0,
6208                            );
6209                        });
6210                    }
6211                    #[cfg(feature = "gpu")]
6212                    if Self::dsv4_spec_on()
6213                        && self.dsv4.is_some()
6214                        && !self.dsv4_mtp.is_empty()
6215                        && task_mask.is_none()
6216                        && router.is_none()
6217                        && !trace_on
6218                        && self.sampler_config.temperature < 1e-6
6219                        && self.sampler_config.repetition_penalty == 1.0
6220                        && generated + 1 < max_tokens
6221                        && all_ids.len() >= 2
6222                        && generated >= dsv4_spec_retry_at
6223                    {
6224                        let tip_token = all_ids[all_ids.len() - 2];
6225                        let drafted0 = drafted;
6226                        let round = self.dsv4_spec_step(
6227                            tip_token,
6228                            t_next,
6229                            next_pos,
6230                            max_tokens.saturating_sub(generated),
6231                            &mut drafted,
6232                            &mut accepted,
6233                        );
6234                        if drafted > drafted0 {
6235                            let useful = round.as_ref().is_some_and(|(extra, _)| !extra.is_empty());
6236                            if useful {
6237                                dsv4_spec_bad = 0;
6238                            } else {
6239                                dsv4_spec_bad += 1;
6240                                if dsv4_spec_bad >= 2 {
6241                                    dsv4_spec_bad = 0;
6242                                    dsv4_spec_retry_at = generated.saturating_add(32);
6243                                    tracing::info!(
6244                                        "dsv4: draft не окупился дважды — точный walk на 32 токена"
6245                                    );
6246                                }
6247                            }
6248                        }
6249                        if let Some((extra, n_pos)) = round {
6250                            next_pos = n_pos;
6251                            let mut stopped = false;
6252                            for &id in &extra {
6253                                if self.confidence_on {
6254                                    confidence.push(0.0);
6255                                }
6256                                if !commit!(id) {
6257                                    stopped = true;
6258                                    break;
6259                                }
6260                            }
6261                            if stopped {
6262                                break 'decode;
6263                            }
6264                            continue 'decode;
6265                        }
6266                    }
6267                    self.graph_want_logits = fuse_lm;
6268                    // Greedy burst (CMF_MULTISTEP, off unless explicitly set): while
6269                    // nothing observes per-token state — pure argmax sampling,
6270                    // no router/trace/confidence/mask — decode k tokens per
6271                    // submit and commit them wholesale. The trailing normal
6272                    // forward leaves logits for the loop top, as always.
6273                    let mut t_fwd = t_next;
6274                    let pure_greedy = self.sampler_config.temperature < 1e-6
6275                        && self.sampler_config.repetition_penalty == 1.0
6276                        && self.sampler_config.presence_penalty == 0.0
6277                        && self.sampler_config.suppress_tokens.is_empty();
6278                    // Off by default: at every k the burst measured at or
6279                    // below the plain path on this graph shape (k=1 loses
6280                    // the argmax dispatches vs a 1 MB readback, k>=8 loses
6281                    // inter-step drains vs the saved sync). Experimental.
6282                    let burst_k = std::env::var("CMF_MULTISTEP")
6283                        .ok()
6284                        .and_then(|v| v.parse::<usize>().ok())
6285                        .unwrap_or(0);
6286                    if pure_greedy
6287                        && burst_k >= 1
6288                        && fuse_lm
6289                        && task_mask.is_none()
6290                        && router.is_none()
6291                        && !trace_on
6292                        && !self.confidence_on
6293                        // Diagnostics and teacher forcing observe every
6294                        // individual logit row.  A device-only burst returns
6295                        // only ids, so decline it rather than silently
6296                        // skipping requested evidence or forced ids.
6297                        && std::env::var_os("CMF_FORCE_IDS").is_none()
6298                        && std::env::var_os("CMF_LOGIT_DUMP").is_none()
6299                        && std::env::var_os("CMF_LOGIT_DUMP_ALL").is_none()
6300                    {
6301                        let mut stopped = false;
6302                        loop {
6303                            // The outer loop checks cancellation too, but a
6304                            // long run can stay in this burst loop for many
6305                            // submits.  Bound cancellation latency to one
6306                            // exact k-token frame.
6307                            if self
6308                                .cancel
6309                                .swap(false, std::sync::atomic::Ordering::Relaxed)
6310                            {
6311                                finish_reason = "cancelled".to_string();
6312                                stopped = true;
6313                                break;
6314                            }
6315                            let room = max_tokens.saturating_sub(generated);
6316                            if room <= 2 {
6317                                break;
6318                            }
6319                            let k = burst_k.min(room - 1);
6320                            if k < 1 {
6321                                break;
6322                            }
6323                            let Some(ids) = self.try_multi_burst(t_fwd, next_pos, k) else {
6324                                if self
6325                                    .graph_failed
6326                                    .swap(false, std::sync::atomic::Ordering::Relaxed)
6327                                {
6328                                    self.finish_generation(&mut mtp, &mut router, true);
6329                                    return Err(
6330                                        "GPU token graph failed during greedy burst".to_string()
6331                                    );
6332                                }
6333                                break;
6334                            };
6335                            next_pos += k;
6336                            for &id in &ids {
6337                                if !commit!(id) {
6338                                    stopped = true;
6339                                    break;
6340                                }
6341                            }
6342                            if stopped {
6343                                break;
6344                            }
6345                            t_fwd = *ids.last().unwrap();
6346                        }
6347                        if stopped {
6348                            break 'decode;
6349                        }
6350                    }
6351                    // Metal: keep the draft head's cache in step through
6352                    // the trial's plain phase and a paused speculation —
6353                    // the pair (hidden, t_fwd) at next_pos−1, the step the
6354                    // round's draft 0 would take. Without it the head's
6355                    // cache lagged the trunk by every plain token for the
6356                    // rest of the generation: the batched warm-up declined
6357                    // every later round and its rows went one by one (a
6358                    // whole MTP step per accepted token), and the drafts
6359                    // attended a context with those tokens missing.
6360                    #[cfg(target_os = "macos")]
6361                    if graph_spec
6362                        && spec_watchdog_off
6363                        && next_pos > 0
6364                        && self.mtp_graph_mode == Some(true)
6365                        && crate::gpu::q1_force()
6366                    {
6367                        if let Some(m) = mtp.as_mut() {
6368                            let _ = self.mtp_step_metal(m, &hidden, t_fwd, next_pos - 1, false);
6369                        }
6370                    }
6371                    hidden = self.forward_layers(&self.embed_single(t_fwd), next_pos, task_mask);
6372                    next_pos += 1;
6373                    // Dynamic routing: the forward updated φ; ask the
6374                    // router whether to switch skills before the next token.
6375                    if let Some(r) = &mut router {
6376                        let phi = self.dyn_phi_ema.clone();
6377                        let decision = r.step(&phi, generated);
6378                        if let Some(new_active) = decision {
6379                            let _ = self.set_active_skill(new_active);
6380                        }
6381                        // Backfill this token's coherence + switch flag from
6382                        // the just-run eval (freshest measured values).
6383                        if trace_on {
6384                            if let Some(last) = traces.last_mut() {
6385                                let e = r.last_best_e();
6386                                last.recon = e.is_finite().then_some(e);
6387                                last.switched = decision.is_some();
6388                            }
6389                        }
6390                    }
6391                }
6392            }
6393        }
6394
6395        let cancelled = finish_reason == "cancelled";
6396        // A generation during which the router switched weights holds no
6397        // state any single overlay would produce (each switch cleared the
6398        // cache mid-sequence), so it leaves no reuse key behind either.
6399        let dyn_switched = router.as_ref().is_some_and(|r| !r.switches.is_empty());
6400        if mimo_spec {
6401            if let Some(st) = self.mimo_mtp.as_ref() {
6402                let line = st.stats.line();
6403                tracing::info!("{line}");
6404                if std::env::var_os("CMF_MIMO_MTP_STATS").is_some() {
6405                    eprintln!("{line}");
6406                }
6407            }
6408        }
6409        self.finish_generation(&mut mtp, &mut router, cancelled);
6410
6411        let output_ids = &all_ids[input_ids.len()..];
6412        // Forwarded = prompt + all generated but the LAST sampled token
6413        // (emitted without being fed back). Exact only without MTP —
6414        // reuse is gated off when MTP is active.
6415        let forwarded = input_ids.len() + output_ids.len().saturating_sub(1);
6416        // A MiMo speculative round that stopped on an accepted draft (EOS,
6417        // cancel) leaves verify rows past the committed stream in the cache:
6418        // never offer that cache for reuse. Neither does a router that
6419        // switched weights mid-sequence (no single overlay produced it).
6420        let consumed = std::mem::take(&mut all_ids);
6421        if dyn_switched {
6422            self.clear_sequence_state();
6423        } else if cancelled || mimo_spec || prompt_rows.is_some() {
6424            self.clear_history();
6425        } else {
6426            self.record_consumed_prefix(&consumed[..forwarded.min(consumed.len())], reuse_from);
6427        }
6428        all_ids = consumed;
6429        let output_ids = &all_ids[input_ids.len()..];
6430        confidence.truncate(output_ids.len()); // guard against any overshoot
6431        traces.truncate(output_ids.len());
6432        Ok(GenerateResult {
6433            text: self.tokenizer.decode(output_ids),
6434            token_ids: output_ids.to_vec(),
6435            prompt_tokens: input_ids.len(),
6436            tokens_generated: generated,
6437            finish_reason,
6438            mtp_drafted: drafted,
6439            mtp_accepted: accepted,
6440            token_confidence: confidence,
6441            traces,
6442        })
6443    }
6444
6445    /// One MTP step: feed `(hidden_p, token_{p+1})` into the draft head,
6446    /// advance its KV cache at position `p`, return the drafted token
6447    /// for position `p+2`.
6448    fn mtp_step(
6449        &mut self,
6450        m: &mut MtpModule,
6451        hidden: &[f32],
6452        next_token: u32,
6453        position: usize,
6454    ) -> u32 {
6455        self.mtp_step_h(m, hidden, next_token, position).0
6456    }
6457
6458    /// Tally for `CMF_MTP_CHAIN_PROBE`: per depth, how often the CHAIN is
6459    /// still an exact prefix of the real continuation. Printed every 128
6460    /// depth-0 samples so a killed run still shows its table.
6461    fn chain_probe_note(depth: usize, prefix_ok: bool) {
6462        use std::sync::Mutex;
6463        static T: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
6464        let mut t = T.lock().unwrap();
6465        if t.len() <= depth {
6466            t.resize(depth + 1, (0, 0));
6467        }
6468        t[depth].0 += 1;
6469        t[depth].1 += prefix_ok as u64;
6470        if depth == 0 && t[0].0 % 128 == 0 {
6471            let line: Vec<String> = t
6472                .iter()
6473                .enumerate()
6474                .map(|(d, (n, k))| {
6475                    format!(
6476                        "d{}={:.0}%({n})",
6477                        d + 1,
6478                        100.0 * *k as f64 / (*n).max(1) as f64
6479                    )
6480                })
6481                .collect();
6482            eprintln!("mtp-chain: {}", line.join(" "));
6483        }
6484    }
6485
6486    /// `mtp_step` that also hands back the block's own output hidden — the
6487    /// state a CHAINED draft feeds the next step, the way a multi-token
6488    /// speculative round iterates the head on itself.
6489    /// One MTP block step from (trunk hidden, token): the head's LOGITS
6490    /// and the block's own hidden for chaining. The draft is argmax of the
6491    /// logits on the greedy path and a draw from their post-chain
6492    /// distribution on the sampling path.
6493    fn mtp_step_hl(
6494        &mut self,
6495        m: &mut MtpModule,
6496        hidden: &[f32],
6497        next_token: u32,
6498        position: usize,
6499    ) -> (Vec<f32>, Vec<f32>) {
6500        // The graph arm: the MTP block as a one-layer token graph with the
6501        // head fused — device attention over the block's own KV mirror,
6502        // one submit for block + head, hidden and logits back together.
6503        // Decided once per generation (see `mtp_graph_mode`).
6504        #[cfg(target_os = "macos")]
6505        if self.mtp_graph_mode != Some(false) && crate::gpu::q1_force() {
6506            if let Some(r) = self.mtp_step_metal(m, hidden, next_token, position, true) {
6507                self.mtp_graph_mode = Some(true);
6508                return r;
6509            }
6510            if self.mtp_graph_mode == Some(true) {
6511                tracing::error!("mtp Metal graph failed after admission");
6512                self.clear_sequence_state();
6513                self.graph_failed
6514                    .store(true, std::sync::atomic::Ordering::Relaxed);
6515                self.cancel
6516                    .store(true, std::sync::atomic::Ordering::Relaxed);
6517                return (Vec::new(), Vec::new());
6518            }
6519            self.mtp_graph_mode = Some(false);
6520        }
6521        #[cfg(feature = "gpu")]
6522        if self.mtp_graph_mode != Some(false) {
6523            if !self.mtp_graph_ok(m) {
6524                if self.mtp_graph_mode == Some(true) {
6525                    // A mirror was already admitted, so a capability change
6526                    // cannot safely switch this request to the stale CPU
6527                    // cache.  Keep the same terminal contract as a failed
6528                    // token graph.
6529                    tracing::error!("mtp graph became unavailable after admission");
6530                    self.clear_sequence_state();
6531                    self.graph_failed
6532                        .store(true, std::sync::atomic::Ordering::Relaxed);
6533                    self.cancel
6534                        .store(true, std::sync::atomic::Ordering::Relaxed);
6535                    return (Vec::new(), Vec::new());
6536                }
6537                self.mtp_graph_mode = Some(false);
6538            } else {
6539                if let Some(r) = self.mtp_step_graph(m, hidden, next_token, position) {
6540                    self.mtp_graph_mode = Some(true);
6541                    return r;
6542                }
6543                if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
6544                    // A token graph can have admitted a persistent MTP/GDN
6545                    // mirror before its readback failed.  The CPU MTP cache
6546                    // is not a valid continuation in that state; leave the
6547                    // flag set so the generation caller returns through its
6548                    // terminal error path instead of silently switching
6549                    // arithmetic.
6550                    return (Vec::new(), Vec::new());
6551                }
6552                // `mtp_graph_ok` was true, so a None here means a refusal or
6553                // failure after graph admission.  Do not fall through to a
6554                // CPU cache whose rows may lag the device mirror.
6555                tracing::error!("mtp graph failed or declined after admission");
6556                self.clear_sequence_state();
6557                self.graph_failed
6558                    .store(true, std::sync::atomic::Ordering::Relaxed);
6559                self.cancel
6560                    .store(true, std::sync::atomic::Ordering::Relaxed);
6561                return (Vec::new(), Vec::new());
6562            }
6563        }
6564        // fc concat order is [enorm(embed); hnorm(hidden)] — EMBEDDING
6565        // FIRST. Verified by the oracle (converter/mtp_oracle.py):
6566        // [emb;hid] → 45.8% acceptance, [hid;emb] → 0.00%.
6567        let e = self.embed_single(next_token);
6568        let mut cat = vec![0.0f32; 2 * self.hidden_size];
6569        let (cat_e, cat_h) = cat.split_at_mut(self.hidden_size);
6570        inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
6571        inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
6572        let mut x = vec![0.0f32; self.hidden_size];
6573        m.eh_proj.matvec(&cat, &mut x, self.pool.as_deref());
6574
6575        // One standard transformer block over the MTP's own cache.
6576        let lw = &m.layer;
6577        inference::rms_norm_into(
6578            &x,
6579            &lw.input_norm,
6580            self.rms_eps,
6581            self.norm_style,
6582            &mut self.ws.n1,
6583        );
6584        let attn = match &lw.attn {
6585            // MLA models carry no MTP head; this path cannot see them.
6586            AttnKind::Mla(_) => unreachable!("MLA has no MTP/pair path"),
6587            AttnKind::Kda(_) => unreachable!("KDA has no MTP/pair path"),
6588            AttnKind::Full {
6589                wq,
6590                wk,
6591                wv,
6592                wo,
6593                q_norm,
6594                k_norm,
6595                output_gate,
6596                softplus_gate,
6597                bias,
6598            } => {
6599                let mut cfg = self.attn_cfg(position);
6600                cfg.q_norm = q_norm.as_deref();
6601                cfg.k_norm = k_norm.as_deref();
6602                cfg.output_gate = *output_gate;
6603                cfg.softplus_gate = softplus_gate
6604                    .as_ref()
6605                    .map(|(gate, per_head)| (gate, *per_head));
6606                cfg.bias = bias
6607                    .as_ref()
6608                    .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice()));
6609                attention::qwen_attention(&self.ws.n1, wq, wk, wv, wo, &mut m.kv, &cfg)
6610            }
6611            AttnKind::Linear(_)
6612            | AttnKind::LinearGdn(_)
6613            | AttnKind::ShortConv(_)
6614            | AttnKind::Bounded(_) => {
6615                unreachable!("MTP block is full attention")
6616            }
6617        };
6618        for (i, &a) in attn.iter().enumerate() {
6619            x[i] += a;
6620        }
6621        inference::rms_norm_into(
6622            &x,
6623            &lw.post_norm,
6624            self.rms_eps,
6625            self.norm_style,
6626            &mut self.ws.p1,
6627        );
6628        let ffn = ffn_forward(&lw.ffn, &self.ws.p1, self.pool.as_deref(), None);
6629        for (i, &f) in ffn.iter().enumerate() {
6630            x[i] += f;
6631        }
6632
6633        inference::rms_norm_into(
6634            &x,
6635            &m.final_norm,
6636            self.rms_eps,
6637            self.norm_style,
6638            &mut self.ws.n1,
6639        );
6640        let lg = self.lm_head_forward(&self.ws.n1);
6641        (lg, x)
6642    }
6643
6644    /// `mtp_step_hl` reduced to the greedy draft: argmax of the head.
6645    fn mtp_step_h(
6646        &mut self,
6647        m: &mut MtpModule,
6648        hidden: &[f32],
6649        next_token: u32,
6650        position: usize,
6651    ) -> (u32, Vec<f32>) {
6652        let (mut lg, x) = self.mtp_step_hl(m, hidden, next_token, position);
6653        let draft = sampler::argmax(&lg);
6654        attention::recycle_buf(&mut lg);
6655        (draft, x)
6656    }
6657
6658    /// One speculative round for the trial: rounds 1..5 of a `Spec` phase
6659    /// advance it (the monitor already averaged this round); after five,
6660    /// the plain phase runs (once — a known plain rate decides at once);
6661    /// a decided speculation keeps re-checking the rule every round and
6662    /// stops after four losing rounds in a row.
6663    fn spec_trial_round(trial: SpecTrial, mon: &mut SpecMon, generated: usize) -> SpecTrial {
6664        match trial {
6665            SpecTrial::Spec { t0, gen0, rounds } => {
6666                let rounds = rounds + 1;
6667                if rounds >= 5 {
6668                    if mon.plain_ms > 0.0 {
6669                        let keep = mon.pays();
6670                        mon.fails = 0;
6671                        tracing::info!(
6672                            "speculation re-check: {:.2} tok/round in {:.1} ms vs plain {:.1} ms/tok — {}",
6673                            mon.tokens,
6674                            mon.round_ms,
6675                            mon.plain_ms,
6676                            if keep { "speculating" } else { "plain" }
6677                        );
6678                        SpecTrial::Decided {
6679                            spec: keep,
6680                            recheck_at: if keep { usize::MAX } else { generated + 128 },
6681                        }
6682                    } else if mon.pays() {
6683                        // Metal: the rounds land enough tokens each that no
6684                        // plain measurement is needed — keep speculating,
6685                        // and re-check every round (a losing streak sends
6686                        // the loop to the plain phase, below).
6687                        mon.fails = 0;
6688                        tracing::info!(
6689                            "speculation trial: {:.2} tok/round in {:.1} ms — speculating (plain not timed)",
6690                            mon.tokens,
6691                            mon.round_ms,
6692                        );
6693                        SpecTrial::Decided {
6694                            spec: true,
6695                            recheck_at: usize::MAX,
6696                        }
6697                    } else {
6698                        SpecTrial::Plain {
6699                            t0: std::time::Instant::now(),
6700                            gen0: generated,
6701                        }
6702                    }
6703                } else {
6704                    SpecTrial::Spec { t0, gen0, rounds }
6705                }
6706            }
6707            SpecTrial::Decided { spec: true, .. } => {
6708                if mon.pays() {
6709                    mon.fails = 0;
6710                    trial
6711                } else {
6712                    mon.fails += 1;
6713                    if mon.fails >= 4 {
6714                        if mon.plain_ms <= 0.0 {
6715                            // Metal, plain never timed: four doubtful rounds
6716                            // buy the (bounded) plain measurement, and the
6717                            // exact rule decides from it.
6718                            tracing::info!(
6719                                "speculation doubtful: {:.2} tok/round in {:.1} ms — timing plain",
6720                                mon.tokens,
6721                                mon.round_ms,
6722                            );
6723                            return SpecTrial::Plain {
6724                                t0: std::time::Instant::now(),
6725                                gen0: generated,
6726                            };
6727                        }
6728                        tracing::info!(
6729                            "speculation stopped: {:.2} tok/round in {:.1} ms vs plain {:.1} ms/tok",
6730                            mon.tokens,
6731                            mon.round_ms,
6732                            mon.plain_ms
6733                        );
6734                        SpecTrial::Decided {
6735                            spec: false,
6736                            recheck_at: generated + 128,
6737                        }
6738                    } else {
6739                        trial
6740                    }
6741                }
6742            }
6743            other => other,
6744        }
6745    }
6746
6747    /// The MTP block's device-mirror id: the trunk's id with a high bit,
6748    /// so the (kv_id, layer) mirror keys never collide.
6749    fn mtp_kv_id(&self) -> u64 {
6750        self.graph_kv_id | (1u64 << 40)
6751    }
6752
6753    /// The MTP block's mirror layer index: 0 — its own kv_id keeps it
6754    /// apart from the trunk, and the BATCH graph (the warm-up path) keys
6755    /// its mirrors at layer 0 with no base of its own, so the draft's
6756    /// token graph must key the same slot.
6757    const MTP_LAYER_BASE: usize = 0;
6758
6759    /// The wgpu MTP draft writes speculative rows straight into its device
6760    /// mirror while the CPU owner retains only the real prompt/decode anchor.
6761    /// After verification, move that mirror cursor back to the anchor before
6762    /// replaying accepted pairs.  The next graph append then sees the same
6763    /// contiguous position as the CPU/Metal path without uploading stale
6764    /// speculative rows.
6765    #[cfg(feature = "gpu")]
6766    fn rewind_mtp_graph_mirror(&self, stored: usize) -> bool {
6767        self.mtp_graph_mode != Some(true)
6768            || crate::gpu::graph_kv_set_stored(self.mtp_kv_id(), Self::MTP_LAYER_BASE, stored)
6769    }
6770
6771    /// A speculative verify graph appends the full `k+1` trunk rows before
6772    /// the acceptance count is known.  GDN state already has a snapshot
6773    /// restore; Full-attention mirrors need the matching logical cursor
6774    /// rewind so the next graph call does not reject an ahead-of-position KV
6775    /// cache after a partial acceptance.
6776    #[cfg(feature = "gpu")]
6777    fn rewind_trunk_graph_mirrors(&self, stored: usize) -> bool {
6778        let mut ok = true;
6779        let mut expected = false;
6780        for li in 0..self.num_layers {
6781            if matches!(
6782                self.weights.layers[self.phys_layer(li)].attn,
6783                AttnKind::Full { .. }
6784            ) {
6785                expected = true;
6786                ok &= crate::gpu::graph_kv_set_stored(self.graph_kv_id, li, stored);
6787            }
6788        }
6789        !expected || ok
6790    }
6791
6792    /// Count the recurrent layers participating in the trunk verify graph.
6793    /// Snapshot restore is all-or-nothing across that set; deriving the count
6794    /// from the model keeps the restore contract valid for looped models too.
6795    fn graph_gdn_layer_count(&self) -> usize {
6796        (0..self.num_layers)
6797            .filter(|&li| {
6798                matches!(
6799                    &self.weights.layers[self.phys_layer(li)].attn,
6800                    AttnKind::LinearGdn(_)
6801                )
6802            })
6803            .count()
6804    }
6805
6806    /// The block's input from (trunk hidden, token): eh_proj · [enorm(e);
6807    /// hnorm(h)] — the same arithmetic the per-op path starts with.
6808    fn mtp_block_input(&mut self, m: &MtpModule, hidden: &[f32], next_token: u32) -> Vec<f32> {
6809        let e = self.embed_single(next_token);
6810        let mut cat = vec![0.0f32; 2 * self.hidden_size];
6811        let (cat_e, cat_h) = cat.split_at_mut(self.hidden_size);
6812        inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
6813        inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
6814        let mut x = vec![0.0f32; self.hidden_size];
6815        m.eh_proj.matvec(&cat, &mut x, self.pool.as_deref());
6816        x
6817    }
6818
6819    /// Is the MTP block graphable at all (device up, full attention
6820    /// without softplus, dense FFN)? The plan itself is built per call.
6821    #[cfg(feature = "gpu")]
6822    fn mtp_block_graph_ok(&self, m: &MtpModule) -> bool {
6823        if std::env::var("CMF_MTP_GRAPH").as_deref() == Ok("0") {
6824            return false;
6825        }
6826        if !crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)
6827            || !crate::gpu::enabled_here()
6828            || self.attn_softcap > 0.0
6829            || self.attention_heads_per_layer.is_some()
6830            // The block graph caches V as wide as K and feeds o_proj
6831            // nh·head_dim; a narrow-V model keeps its MTP block per-op.
6832            || self.v_head_dim.is_some()
6833        {
6834            return false;
6835        }
6836        matches!(
6837            &m.layer.attn,
6838            AttnKind::Full {
6839                softplus_gate: None,
6840                ..
6841            }
6842        ) && matches!(&m.layer.ffn, FfnKind::Dense(_))
6843    }
6844
6845    /// Full MTP token-graph eligibility, including the fused lm-head and all
6846    /// block projection weights.  Keep this distinct from the block-only
6847    /// check: prompt warm-up does not need the head, while a draft step does.
6848    #[cfg(feature = "gpu")]
6849    fn mtp_graph_ok(&self, m: &MtpModule) -> bool {
6850        if !self.mtp_block_graph_ok(m) {
6851            return false;
6852        }
6853        let AttnKind::Full { wq, wk, wv, wo, .. } = &m.layer.attn else {
6854            return false;
6855        };
6856        let FfnKind::Dense(d) = &m.layer.ffn else {
6857            return false;
6858        };
6859        d.segs.is_empty()
6860            && wq.graph_weight().is_some()
6861            && wk.graph_weight().is_some()
6862            && wv.graph_weight().is_some()
6863            && wo.graph_weight().is_some()
6864            && d.gate_proj.graph_weight().is_some()
6865            && d.up_proj.graph_weight().is_some()
6866            && d.down_proj.graph_weight().is_some()
6867            && self.weights.lm_head.graph_weight().is_some()
6868    }
6869
6870    /// One MTP block step on the wgpu token graph: block + fused head in
6871    /// one submit, the block hidden and the logits read back together.
6872    /// None = the graph cannot take this block (softplus gate, non-dense
6873    /// FFN, unquantized head, no device) — the caller keeps the per-op
6874    /// path for the whole generation.
6875    #[cfg(feature = "gpu")]
6876    fn mtp_step_graph(
6877        &mut self,
6878        m: &mut MtpModule,
6879        hidden: &[f32],
6880        next_token: u32,
6881        position: usize,
6882    ) -> Option<(Vec<f32>, Vec<f32>)> {
6883        if !self.mtp_graph_ok(m) {
6884            return None;
6885        }
6886        let lw = &m.layer;
6887        let AttnKind::Full {
6888            wq,
6889            wk,
6890            wv,
6891            wo,
6892            q_norm,
6893            k_norm,
6894            output_gate,
6895            softplus_gate,
6896            bias,
6897        } = &lw.attn
6898        else {
6899            return None;
6900        };
6901        if softplus_gate.is_some() {
6902            return None;
6903        }
6904        let FfnKind::Dense(d) = &lw.ffn else {
6905            return None;
6906        };
6907        if !d.segs.is_empty() {
6908            return None; // tube layers run on the segmented path
6909        }
6910        // The block's input first: it borrows `self` mutably (embed scratch,
6911        // pool), the plan below borrows the weights immutably.
6912        let mut x = self.mtp_block_input(m, hidden, next_token);
6913        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
6914            let (_, i, kind, rs) = t.graph_weight()?;
6915            Some(crate::gpu::GraphW {
6916                idx: i,
6917                kind,
6918                row_scale: rs,
6919                data: &[],
6920                prism: crate::gpu::GraphPrismOp::None,
6921                affine: false,
6922            })
6923        }
6924        let (model, _, _, _) = wq.graph_weight()?;
6925        let model = model.clone();
6926        let (lm_gw, lm_rows) = {
6927            let (_, i, kind, rs) = self.weights.lm_head.graph_weight()?;
6928            // The draft's head over the CMF_DRAFT_VOCAB shortlist (the same
6929            // cut the native Metal draft takes): 662 MB a step on Qwen3.8
6930            // becomes 170 MB at 65536; the verify keeps the full head.
6931            let rows = if kind == 6 {
6932                self.draft_head_rows(self.weights.lm_head.rows())
6933            } else {
6934                self.weights.lm_head.rows()
6935            };
6936            (
6937                crate::gpu::GraphW {
6938                    idx: i,
6939                    kind,
6940                    row_scale: rs,
6941                    data: &[],
6942                    prism: crate::gpu::GraphPrismOp::None,
6943                    affine: false,
6944                },
6945                rows,
6946            )
6947        };
6948        let layer = crate::gpu::GraphLayer {
6949            input_norm: &lw.input_norm,
6950            attn: crate::gpu::GraphAttn::Full {
6951                wq: gw(wq)?,
6952                wk: gw(wk)?,
6953                wv: gw(wv)?,
6954                wo: gw(wo)?,
6955                q_norm: q_norm.as_deref(),
6956                k_norm: k_norm.as_deref(),
6957                late_qk_norm: self.qk_norm_after_rope,
6958                bias: bias
6959                    .as_ref()
6960                    .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
6961                output_gate: *output_gate,
6962                cpu_k: m.kv.k_heads(),
6963                cpu_v: m.kv.v_heads(),
6964                cpu_base: m.kv.base(),
6965                geom: None,
6966                head_gate: None,
6967            },
6968            post_norm: &lw.post_norm,
6969            attn_out_norm: None,
6970            ffn_out_norm: None,
6971            layer_scale: None,
6972            ffn: crate::gpu::GraphFfn::Dense {
6973                gate: gw(&d.gate_proj)?,
6974                up: gw(&d.up_proj)?,
6975                down: gw(&d.down_proj)?,
6976                act: d.act.graph_act()?,
6977            },
6978        };
6979        let nh = self.num_heads;
6980        let (nkv, hd, rd) = self.layer_geom(0);
6981        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
6982        let mut logits = Vec::new();
6983        let ok = crate::gpu::forward_token_graph(
6984            &model,
6985            self.mtp_kv_id(),
6986            std::slice::from_ref(&layer),
6987            &[None],
6988            self.o1_epoch,
6989            &self.inv_freq,
6990            &mut x,
6991            nh,
6992            nkv,
6993            hd,
6994            self.attn_scale,
6995            rd,
6996            self.hidden_size,
6997            self.intermediate_size,
6998            position,
6999            self.kv_cache.max_seq_len,
7000            gemma,
7001            self.rms_eps as f32,
7002            Some((&lm_gw, lm_rows)),
7003            &m.final_norm,
7004            &mut logits,
7005            &[],
7006            1,
7007            None,
7008            None,
7009            None,
7010            Self::MTP_LAYER_BASE,
7011            true,
7012        );
7013        match ok {
7014            crate::gpu::TokenGraphOutcome::Completed => {}
7015            crate::gpu::TokenGraphOutcome::Declined => return None,
7016            crate::gpu::TokenGraphOutcome::Failed => {
7017                // The backend has already admitted persistent state.  Keep
7018                // this distinct from a capability refusal so the caller
7019                // cannot switch to the stale CPU MTP cache.
7020                self.clear_sequence_state();
7021                self.graph_failed
7022                    .store(true, std::sync::atomic::Ordering::Relaxed);
7023                self.cancel
7024                    .store(true, std::sync::atomic::Ordering::Relaxed);
7025                return None;
7026            }
7027        }
7028        logits.resize(self.vocab_size, 0.0);
7029        Some((logits, x))
7030    }
7031
7032    /// The warm-ups of one speculative round on the device: every accepted
7033    /// (hidden, token) pair as ONE batched graph run over the MTP block
7034    /// (no head) — its kv_append lands the pairs in the block's mirror.
7035    /// `pairs` are consecutive positions from `first_pos`.  The tri-state
7036    /// result is intentional: a refusal before admission may use the
7037    /// per-row/CPU route, while a failure after admission must terminate the
7038    /// sequence rather than fall through to a stale CPU cache.
7039    #[cfg(feature = "gpu")]
7040    fn mtp_warm_graph(
7041        &mut self,
7042        m: &mut MtpModule,
7043        pairs: &[(&[f32], u32)],
7044        first_pos: usize,
7045    ) -> crate::gpu::BatchGraphOutcome {
7046        if pairs.is_empty() {
7047            return crate::gpu::BatchGraphOutcome::Completed;
7048        }
7049        if !self.mtp_block_graph_ok(m) {
7050            return crate::gpu::BatchGraphOutcome::Declined;
7051        }
7052        let hs = self.hidden_size;
7053        // Block inputs for every pair (eh_proj on the per-op path, one
7054        // matvec each — the plan's own prologue).
7055        let mut hiddens = Vec::with_capacity(pairs.len() * hs);
7056        for (h, t) in pairs {
7057            hiddens.extend_from_slice(&self.mtp_block_input(m, h, *t));
7058        }
7059        let lw = &m.layer;
7060        let AttnKind::Full {
7061            wq,
7062            wk,
7063            wv,
7064            wo,
7065            q_norm,
7066            k_norm,
7067            output_gate,
7068            bias,
7069            ..
7070        } = &lw.attn
7071        else {
7072            return crate::gpu::BatchGraphOutcome::Declined;
7073        };
7074        let FfnKind::Dense(d) = &lw.ffn else {
7075            return crate::gpu::BatchGraphOutcome::Declined;
7076        };
7077        if !d.segs.is_empty() {
7078            return crate::gpu::BatchGraphOutcome::Declined; // tube layers run on the segmented path
7079        }
7080        // The graph has no arm for a projected output gate, and only the
7081        // activations `graph_act` names.
7082        let (
7083            AttnKind::Full {
7084                softplus_gate: None,
7085                ..
7086            },
7087            Some(gact),
7088        ) = (&lw.attn, d.act.graph_act())
7089        else {
7090            return crate::gpu::BatchGraphOutcome::Declined;
7091        };
7092        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
7093            let (_, i, kind, rs) = t.graph_weight()?;
7094            Some(crate::gpu::GraphW {
7095                idx: i,
7096                kind,
7097                row_scale: rs,
7098                data: &[],
7099                prism: crate::gpu::GraphPrismOp::None,
7100                affine: false,
7101            })
7102        }
7103        let Some((model, _, _, _)) = wq.graph_weight() else {
7104            return crate::gpu::BatchGraphOutcome::Declined;
7105        };
7106        let model = model.clone();
7107        let (Some(gwq), Some(gwk), Some(gwv), Some(gwo), Some(gg), Some(gu), Some(gd)) = (
7108            gw(wq),
7109            gw(wk),
7110            gw(wv),
7111            gw(wo),
7112            gw(&d.gate_proj),
7113            gw(&d.up_proj),
7114            gw(&d.down_proj),
7115        ) else {
7116            return crate::gpu::BatchGraphOutcome::Declined;
7117        };
7118        let layer = crate::gpu::GraphLayer {
7119            input_norm: &lw.input_norm,
7120            attn: crate::gpu::GraphAttn::Full {
7121                wq: gwq,
7122                wk: gwk,
7123                wv: gwv,
7124                wo: gwo,
7125                q_norm: q_norm.as_deref(),
7126                k_norm: k_norm.as_deref(),
7127                late_qk_norm: self.qk_norm_after_rope,
7128                bias: bias
7129                    .as_ref()
7130                    .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
7131                output_gate: *output_gate,
7132                cpu_k: m.kv.k_heads(),
7133                cpu_v: m.kv.v_heads(),
7134                cpu_base: m.kv.base(),
7135                geom: None,
7136                head_gate: None,
7137            },
7138            post_norm: &lw.post_norm,
7139            attn_out_norm: None,
7140            ffn_out_norm: None,
7141            layer_scale: None,
7142            ffn: crate::gpu::GraphFfn::Dense {
7143                gate: gg,
7144                up: gu,
7145                down: gd,
7146                act: gact,
7147            },
7148        };
7149        let positions: Vec<usize> = (first_pos..first_pos + pairs.len()).collect();
7150        let nh = self.num_heads;
7151        let (nkv, hd, rd) = self.layer_geom(0);
7152        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
7153        crate::gpu::forward_batch_graph(
7154            &model,
7155            self.mtp_kv_id(),
7156            std::slice::from_ref(&layer),
7157            &self.inv_freq,
7158            &mut hiddens,
7159            nh,
7160            nkv,
7161            hd,
7162            rd,
7163            hs,
7164            self.intermediate_size,
7165            &positions,
7166            self.kv_cache.max_seq_len,
7167            gemma,
7168            self.rms_eps as f32,
7169            self.attn_scale,
7170            pairs.len(),
7171            &[],
7172            0,
7173            None,
7174            None,
7175        )
7176    }
7177
7178    /// Complete an MTP warm-up after the batched graph has refused.  A
7179    /// graphable block is retried one row at a time; once any device row has
7180    /// been admitted, a CPU fallback would observe a stale mirror, so every
7181    /// token-graph refusal is terminal.  If the block is not graphable and no
7182    /// mirror exists yet, warming on the CPU is safe and records the CPU mode
7183    /// for the rest of the generation.
7184    #[cfg(feature = "gpu")]
7185    fn mtp_warm_graph_fallback(
7186        &mut self,
7187        m: &mut MtpModule,
7188        pairs: &[(&[f32], u32)],
7189        first_pos: usize,
7190    ) -> bool {
7191        if pairs.is_empty() {
7192            return true;
7193        }
7194        let graphable = self.mtp_block_graph_ok(m);
7195        if !graphable {
7196            // A previously admitted mirror cannot be made coherent by
7197            // appending to the host cache.  The caller turns this into a
7198            // terminal generation error and clears both mirrors.
7199            if self.mtp_graph_mode == Some(true) {
7200                return false;
7201            }
7202            self.mtp_graph_mode = Some(false);
7203            for (j, (h, t)) in pairs.iter().enumerate() {
7204                self.mtp_warm(m, h, *t, first_pos + j);
7205            }
7206            return true;
7207        }
7208
7209        // The batch refusal is recoverable only through the same device
7210        // state.  Keep rows owned until each token graph has completed; a
7211        // None is treated as unsafe because the token-graph API deliberately
7212        // collapses its backend refusal/failure into that result.
7213        for (j, (h, t)) in pairs.iter().enumerate() {
7214            if self.mtp_step_graph(m, h, *t, first_pos + j).is_none() {
7215                return false;
7216            }
7217        }
7218        self.mtp_graph_mode = Some(true);
7219        true
7220    }
7221
7222    /// Warm a contiguous set of MTP pairs using the existing graph seam, with
7223    /// an all-or-nothing error contract for callers that already admitted the
7224    /// trunk batch.  The non-GPU build keeps the same pair accounting while
7225    /// using the established CPU warm path.
7226    #[cfg(feature = "gpu")]
7227    fn mtp_warm_prefill_pairs(
7228        &mut self,
7229        m: &mut MtpModule,
7230        pairs: &[(&[f32], u32)],
7231        first_pos: usize,
7232    ) -> Result<(), &'static str> {
7233        // Keep unsupported token-graph heads on the established CPU MTP
7234        // route before admitting any block mirror.  Once a device mirror is
7235        // active, the same condition is terminal because CPU rows cannot
7236        // repair its state.
7237        if self.mtp_graph_mode == Some(false) || !self.mtp_graph_ok(m) {
7238            if self.mtp_graph_mode == Some(true) {
7239                return Err("MTP token graph became unavailable after admission");
7240            }
7241            self.mtp_graph_mode = Some(false);
7242            for (j, (h, t)) in pairs.iter().enumerate() {
7243                self.mtp_warm(m, h, *t, first_pos + j);
7244            }
7245            return Ok(());
7246        }
7247        match self.mtp_warm_graph(m, pairs, first_pos) {
7248            crate::gpu::BatchGraphOutcome::Completed => {
7249                if !pairs.is_empty() {
7250                    self.mtp_graph_mode = Some(true);
7251                }
7252                Ok(())
7253            }
7254            crate::gpu::BatchGraphOutcome::Declined => {
7255                if self.mtp_warm_graph_fallback(m, pairs, first_pos) {
7256                    Ok(())
7257                } else {
7258                    Err("MTP warm-up fallback failed after device admission")
7259                }
7260            }
7261            crate::gpu::BatchGraphOutcome::Failed => {
7262                Err("MTP warm batch graph failed after admission")
7263            }
7264        }
7265    }
7266
7267    #[cfg(not(feature = "gpu"))]
7268    fn mtp_warm_prefill_pairs(
7269        &mut self,
7270        m: &mut MtpModule,
7271        pairs: &[(&[f32], u32)],
7272        first_pos: usize,
7273    ) -> Result<(), &'static str> {
7274        for (j, (h, t)) in pairs.iter().enumerate() {
7275            self.mtp_warm(m, h, *t, first_pos + j);
7276        }
7277        Ok(())
7278    }
7279
7280    /// The MTP block alone — advance its KV with a (hidden, token) pair the
7281    /// verify just proved, without paying the head. What keeps the draft's
7282    /// attention context warm between speculative rounds.
7283    fn mtp_warm(&mut self, m: &mut MtpModule, hidden: &[f32], next_token: u32, position: usize) {
7284        let e = self.embed_single(next_token);
7285        let mut cat = vec![0.0f32; 2 * self.hidden_size];
7286        let (cat_e, cat_h) = cat.split_at_mut(self.hidden_size);
7287        inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
7288        inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
7289        let mut x = vec![0.0f32; self.hidden_size];
7290        m.eh_proj.matvec(&cat, &mut x, self.pool.as_deref());
7291        inference::rms_norm_into(
7292            &x,
7293            &m.layer.input_norm,
7294            self.rms_eps,
7295            self.norm_style,
7296            &mut self.ws.n1,
7297        );
7298        let attn = match &m.layer.attn {
7299            AttnKind::Full {
7300                wq,
7301                wk,
7302                wv,
7303                wo,
7304                q_norm,
7305                k_norm,
7306                output_gate,
7307                softplus_gate,
7308                bias,
7309            } => {
7310                let mut cfg = self.attn_cfg(position);
7311                cfg.q_norm = q_norm.as_deref();
7312                cfg.k_norm = k_norm.as_deref();
7313                cfg.output_gate = *output_gate;
7314                cfg.softplus_gate = softplus_gate.as_ref().map(|(g, p)| (g, *p));
7315                cfg.bias = bias
7316                    .as_ref()
7317                    .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice()));
7318                attention::qwen_attention(&self.ws.n1, wq, wk, wv, wo, &mut m.kv, &cfg)
7319            }
7320            _ => return,
7321        };
7322        let _ = attn;
7323    }
7324
7325    /// Speculative decode ON the wgpu whole-token graph: draft k with the
7326    /// MTP head, verify all of them plus the tip in ONE batched graph
7327    /// submit whose tail folds the head, commit the accepted prefix and
7328    /// roll the GDN state back to the last real position. Greedy only —
7329    /// output equals the plain graph's token for token, the way the DSV4
7330    /// verify equals the walk.
7331    #[cfg(feature = "gpu")]
7332    #[allow(clippy::too_many_arguments)]
7333    fn graph_spec_step(
7334        &mut self,
7335        m: &mut MtpModule,
7336        hidden: &[f32],
7337        t_next: u32,
7338        next_pos: usize,
7339        drafted: &mut usize,
7340        accepted: &mut usize,
7341        // The committed stream (prompt + generated so far, `t_next`
7342        // included): the sampler chain's penalties read it, and the
7343        // sampling arm extends it with the drafts position by position.
7344        all_ids: &mut Vec<u32>,
7345        // Tokens left before `max_tokens`. A round commits up to k
7346        // accepted drafts, and those positions are already in the cache,
7347        // so the depth is capped here — trimming the output afterwards
7348        // would leave cache rows the committed stream does not have.
7349        room: usize,
7350    ) -> Option<(Vec<u32>, usize, Vec<f32>)> {
7351        // 3 is the measured optimum on Qwen3.6-27B / RTX 5090 (medians
7352        // of three, greedy): 51.1 tok/s against a plain 49.4, where k=2
7353        // gives 46.1, k=4 50.0, k=5 47.4, k=6 45.2. Acceptance is 89-91%
7354        // throughout — what turns the curve over is the verify, which
7355        // costs ~7.4 ms per extra position, and the draft ~3 ms a step.
7356        // 4 since the draft moved onto the graph (Qwen3.8-27B / 5090:
7357        // k=3 51.2, k=4 51.8 with the per-op draft; the graph draft
7358        // halves the draft cost, so the extra draft is cheaper still).
7359        // 5 with the int8 verify (the default: measured 76.5 against
7360        // k=4's 72-74 and k=6's 74 on the 5090), 4 with the f32 one.
7361        #[cfg(target_os = "macos")]
7362        let metal_native = crate::gpu::q1_force();
7363        #[cfg(not(target_os = "macos"))]
7364        let metal_native = false;
7365        #[cfg(feature = "gpu")]
7366        let k_default = if metal_native {
7367            // the Metal verify's GEMM tile is 8 rows wide and flat in b:
7368            // seven drafts + the tip fill it for free
7369            7
7370        } else if crate::gpu_wgpu::verify_i8_on() {
7371            5
7372        } else {
7373            4
7374        };
7375        #[cfg(not(feature = "gpu"))]
7376        let k_default = 4;
7377        let k_env: Option<usize> = std::env::var("CMF_GRAPH_SPEC_K")
7378            .ok()
7379            .and_then(|v| v.parse().ok())
7380            .filter(|&v| (1..=8).contains(&v));
7381        // Adaptive depth: start below the card's flat-verify optimum and
7382        // let the accepted fraction move it — predictable text climbs to
7383        // the old default within a few rounds, prose settles at 2-3 where
7384        // the shorter verify pays.
7385        let (k_start, k_max) = if metal_native {
7386            (7, 7)
7387        } else {
7388            (3, k_default.max(5))
7389        };
7390        let k_full: usize = k_env.unwrap_or_else(|| self.spec_k_adapt.unwrap_or(k_start));
7391        let k_spec = k_full.min(room).max(1);
7392        // a tail round cut short by `room` says nothing about the text:
7393        // it must not move the adaptive depth the next request starts at
7394        let k_capped = k_spec < k_full;
7395        if next_pos == 0 {
7396            return None;
7397        }
7398        let t_round = std::time::Instant::now();
7399        // Submissions per phase — and they say where the round's money is.
7400        // Qwen3.6-27B on an RTX 5090, k=3:
7401        //
7402        //   draft   9.3 ms / 12 submissions   (four per MTP step)
7403        //   verify 52.8 ms /  1               (the batched graph)
7404        //   commit  5.4 ms /  6               (two per warm)
7405        //
7406        // The verify is already one submit. The draft's own work is 834 MB
7407        // a step — 0.8 ms at this card's measured 1056 GB/s — against 3.1
7408        // ms measured, so ~0.58 ms of every step is round trip, not
7409        // arithmetic, and the same holds for the warms. Eighteen round
7410        // trips a round at roughly half a millisecond each is ~11 ms of a
7411        // 68 ms round: fusing the MTP block into ONE submit the way the
7412        // trunk already is projects to ~64 tok/s against today's 50.9.
7413        // That is the largest measured item left on this path.
7414        let subs = || crate::gpu_wgpu::SUBMITS.load(std::sync::atomic::Ordering::Relaxed);
7415        let sub0 = subs();
7416        // Greedy without penalties verifies by argmax equality (bit-exact
7417        // against the plain path). Anything else is speculative SAMPLING:
7418        // each draft is a DRAW from the MTP head's post-chain distribution
7419        // q_j, kept for the accept test; the verify's rows give p_j.
7420        let cfg = self.sampler_config.clone();
7421        let penalized = !(cfg.repetition_penalty == 1.0
7422            && cfg.presence_penalty == 0.0
7423            && cfg.suppress_tokens.is_empty());
7424        // Three verify regimes: plain greedy (argmax of the raw rows),
7425        // greedy WITH penalties (argmax of the penalized rows — a single
7426        // pass each, no distributions), and sampling (draw / accept /
7427        // correct on post-chain distributions).
7428        let greedy_pen = cfg.temperature < 1e-6 && penalized;
7429        let sampling = cfg.temperature >= 1e-6;
7430        // Sampling with a top-k goes through the SPARSE chain: the dense
7431        // one builds nine 248k-float distributions a round (four drafts,
7432        // five verify rows) and measured 19-22 tok/s against a plain 40 —
7433        // the host, not the card. Sparse, the same nine cost tens of
7434        // microseconds each.
7435        let sparse = sampling && sampler::sparse_ok(&cfg);
7436        let base_len = all_ids.len();
7437        if sampling && !sparse && self.spec_q.len() < k_spec {
7438            self.spec_q.resize_with(k_spec, Vec::new);
7439        }
7440        if sparse && self.spec_qs.len() < k_spec {
7441            self.spec_qs.resize_with(k_spec, Vec::new);
7442        }
7443        // Draft the chain: first from the trunk's tip hidden, then the head
7444        // iterating on itself. Rows land in the MTP KV; the chain rows past
7445        // the first are speculation over speculative state and roll back
7446        // below, replaced by verified pairs.
7447        let mut drafts = Vec::with_capacity(k_spec);
7448        let mut hx = hidden.to_vec();
7449        // CMF_SPEC_DBG=1: draft 0 through BOTH MTP arms (graph and per-op)
7450        // from the same inputs — are the arms the difference, or the inputs?
7451        let spec_dbg = std::env::var("CMF_SPEC_DBG").is_ok();
7452        spec_stamp("pro");
7453        // Plain greedy on native Metal: the whole chain as one command
7454        // buffer (device argmax + embedding gather between the steps).
7455        // A decline before commit hands the round to the per-step loop
7456        // below; a failure after commit is terminal, like any graph
7457        // failure after admission.
7458        #[cfg(target_os = "macos")]
7459        if metal_native && !sampling && !greedy_pen && self.mtp_graph_mode != Some(false) {
7460            match self.mtp_draft_chain_metal(m, hidden, t_next, next_pos - 1, k_spec) {
7461                Ok(ids) => {
7462                    self.mtp_graph_mode = Some(true);
7463                    drafts = ids;
7464                }
7465                Err(true) => {
7466                    tracing::error!("mtp Metal draft chain failed after commit");
7467                    self.clear_sequence_state();
7468                    self.graph_failed
7469                        .store(true, std::sync::atomic::Ordering::Relaxed);
7470                    self.cancel
7471                        .store(true, std::sync::atomic::Ordering::Relaxed);
7472                    return None;
7473                }
7474                Err(false) => {}
7475            }
7476        }
7477        for j in drafts.len()..k_spec {
7478            let tok_in = if j == 0 { t_next } else { drafts[j - 1] };
7479            let mut dbg_ref: Option<(Vec<f32>, Vec<f32>)> = None;
7480            if spec_dbg {
7481                let saved = self.mtp_graph_mode;
7482                self.mtp_graph_mode = Some(false);
7483                let r = self.mtp_step_hl(m, &hx, tok_in, next_pos - 1 + j);
7484                self.mtp_graph_mode = saved;
7485                if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
7486                    return None;
7487                }
7488                m.kv.truncate_last(1);
7489                dbg_ref = Some(r);
7490            }
7491            let (mut lg, hj) = self.mtp_step_hl(m, &hx, tok_in, next_pos - 1 + j);
7492            if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
7493                return None;
7494            }
7495            if let Some((lg_cpu, h_cpu)) = dbg_ref {
7496                let n = |v: &[f32]| v.iter().map(|x| x * x).sum::<f32>().sqrt();
7497                let dl = lg
7498                    .iter()
7499                    .zip(&lg_cpu)
7500                    .fold(0f32, |m, (a, b)| m.max((a - b).abs()));
7501                let dh = hj
7502                    .iter()
7503                    .zip(&h_cpu)
7504                    .fold(0f32, |m, (a, b)| m.max((a - b).abs()));
7505                eprintln!(
7506                    "spec-dbg j={j} pos {} tok_in {tok_in}: per-op draft {} graph draft {} | max|dlogit| {dl:.3} | |h_cpu| {:.2} |h_graph| {:.2} max|dh| {dh:.3} | kv rows {}",
7507                    next_pos - 1 + j,
7508                    sampler::argmax(&lg_cpu),
7509                    sampler::argmax(&lg),
7510                    n(&h_cpu),
7511                    n(&hj),
7512                    m.kv.seq_len
7513                );
7514            }
7515            let dj = if sparse {
7516                let mut q = std::mem::take(&mut self.spec_qs[j]);
7517                let ok = sampler::sparse_distribution_into(
7518                    &lg,
7519                    &cfg,
7520                    all_ids,
7521                    &mut self.sampler_scratch,
7522                    self.pool.as_deref(),
7523                    &mut q,
7524                );
7525                let d = if ok {
7526                    sampler::draw_sparse(&q, &mut self.rng)
7527                } else {
7528                    // everything filtered: the dense chain's greedy fallback
7529                    let t = sampler::argmax(&lg);
7530                    q.clear();
7531                    q.push((t, 1.0));
7532                    t
7533                };
7534                self.spec_qs[j] = q;
7535                all_ids.push(d);
7536                d
7537            } else if sampling {
7538                let mut q = std::mem::take(&mut self.spec_q[j]);
7539                sampler::distribution_into(
7540                    &lg,
7541                    &cfg,
7542                    all_ids,
7543                    &mut self.sampler_scratch,
7544                    self.pool.as_deref(),
7545                    &mut q,
7546                );
7547                let d = sampler::draw(&q, &mut self.rng);
7548                self.spec_q[j] = q;
7549                all_ids.push(d); // the next draft's penalties see this one
7550                d
7551            } else if greedy_pen {
7552                let d = sampler::argmax_penalized(
7553                    &lg,
7554                    &cfg,
7555                    all_ids,
7556                    &mut self.sampler_scratch,
7557                    self.pool.as_deref(),
7558                );
7559                all_ids.push(d);
7560                d
7561            } else {
7562                sampler::argmax(&lg)
7563            };
7564            attention::recycle_buf(&mut lg);
7565            drafts.push(dj);
7566            hx = hj;
7567            spec_stamp("d.pick");
7568        }
7569        all_ids.truncate(base_len);
7570        *drafted += k_spec;
7571        let t_draft = t_round.elapsed();
7572        let sub_draft = subs();
7573        // Verify batch: [t_next, d1 .. d_{k-1}] at next_pos.. — every row's
7574        // logits come back from the graph's own head.
7575        let b = k_spec + 1;
7576        let mut hiddens = vec![0.0f32; b * self.hidden_size];
7577        for (i, &t) in std::iter::once(&t_next).chain(drafts.iter()).enumerate() {
7578            let e = self.embed_single(t);
7579            hiddens[i * self.hidden_size..(i + 1) * self.hidden_size].copy_from_slice(&e);
7580        }
7581        let positions: Vec<usize> = (next_pos..next_pos + b).collect();
7582        spec_stamp("v.emb");
7583        let (lm_gw, lm_rows) = {
7584            let (_, i, kind, rs) = self.weights.lm_head.graph_weight()?;
7585            (
7586                crate::gpu::GraphW {
7587                    idx: i,
7588                    kind,
7589                    row_scale: rs,
7590                    data: &[],
7591                    prism: crate::gpu::GraphPrismOp::None,
7592                    affine: false,
7593                },
7594                self.weights.lm_head.rows(),
7595            )
7596        };
7597        let mut logits = Vec::new();
7598        let final_norm = self.weights.final_norm.clone();
7599        // Plain greedy on Metal: the b argmaxes come from the device
7600        // (`argmax_rows` after the head) and the 7.9 MB logits plane is
7601        // never read back — the round's decision needs only the ids, and
7602        // the loop top takes the last verified id as `spec_forced`, which
7603        // is exactly what its argmax of the row would give. The full rows
7604        // stay for anything that reads them: sampling, penalties,
7605        // confidence, the verify oracle, the logit dump.
7606        // `CMF_METAL_DEV_ARGMAX=0` keeps the host path.
7607        #[cfg(target_os = "macos")]
7608        let greedy_dev = metal_native
7609            && !sampling
7610            && !greedy_pen
7611            && !self.confidence_on
7612            && self.final_softcap.is_none()
7613            // The host acceptance argmax scans the WHOLE head row
7614            // (`lm_rows`), the sampler's own row only `vocab_size`: they
7615            // coincide exactly when the head has no padding rows, and
7616            // only then is the device argmax (which scores `vocab_size`)
7617            // bit-identical to both.
7618            && self.vocab_size == lm_rows
7619            && std::env::var_os("CMF_METAL_VERIFY_CHECK").is_none()
7620            && std::env::var_os("CMF_LOGIT_DUMP").is_none()
7621            && std::env::var("CMF_METAL_DEV_ARGMAX").as_deref() != Ok("0");
7622        #[cfg(not(target_os = "macos"))]
7623        let greedy_dev = false;
7624        let mut dev_ids: Vec<u32> = Vec::new();
7625        #[cfg(target_os = "macos")]
7626        let verify_outcome = if metal_native {
7627            let lm = self.weights.lm_head.q1_parts()?;
7628            let n_score = self.vocab_size.min(lm_rows);
7629            self.try_batch_graph_metal(
7630                &mut hiddens,
7631                &positions,
7632                b,
7633                Some((lm, &final_norm, &mut logits)),
7634                if greedy_dev {
7635                    Some((n_score, &mut dev_ids))
7636                } else {
7637                    None
7638                },
7639            )
7640        } else {
7641            self.try_batch_graph_wgpu(
7642                &mut hiddens,
7643                &positions,
7644                b,
7645                Some(crate::gpu::SpecTail {
7646                    lm: lm_gw,
7647                    lm_rows,
7648                    final_norm: &final_norm,
7649                    logits_out: &mut logits,
7650                }),
7651            )
7652        };
7653        #[cfg(not(target_os = "macos"))]
7654        let verify_outcome = self.try_batch_graph_wgpu(
7655            &mut hiddens,
7656            &positions,
7657            b,
7658            Some(crate::gpu::SpecTail {
7659                lm: lm_gw,
7660                lm_rows,
7661                final_norm: &final_norm,
7662                logits_out: &mut logits,
7663            }),
7664        );
7665        match verify_outcome {
7666            crate::gpu::BatchGraphOutcome::Completed => {}
7667            crate::gpu::BatchGraphOutcome::Declined => {
7668                // The verifier refused before admission.  Its draft MTP
7669                // rows are still device-resident, so rewind the separate
7670                // mirror before the caller takes the exact one-token path.
7671                m.kv.truncate_last(k_spec);
7672                if !metal_native && !self.rewind_mtp_graph_mirror(next_pos) {
7673                    self.clear_sequence_state();
7674                    self.graph_failed
7675                        .store(true, std::sync::atomic::Ordering::Relaxed);
7676                    self.cancel
7677                        .store(true, std::sync::atomic::Ordering::Relaxed);
7678                    tracing::error!("MTP graph mirror rewind failed after verify decline");
7679                }
7680                return None;
7681            }
7682            crate::gpu::BatchGraphOutcome::Failed => {
7683                // A failed batch may have advanced trunk/GDN state.  Clear
7684                // both mirrors and preserve the terminal outcome rather than
7685                // falling through to stale CPU state.
7686                self.clear_sequence_state();
7687                self.graph_failed
7688                    .store(true, std::sync::atomic::Ordering::Relaxed);
7689                self.cancel
7690                    .store(true, std::sync::atomic::Ordering::Relaxed);
7691                tracing::error!("MTP verify batch graph failed after admission");
7692                return None;
7693            }
7694        }
7695        // `CMF_METAL_VERIFY_CHECK=1`: run the same b tokens through the
7696        // plain per-token path and compare each row's argmax + logits with
7697        // the verify's — the bring-up oracle for the batched graph. The
7698        // plain forwards mutate the CPU state; it is snapshotted and put
7699        // back, and the K/V mirrors re-pointed, before the round goes on.
7700        #[cfg(target_os = "macos")]
7701        if metal_native && std::env::var("CMF_METAL_VERIFY_CHECK").as_deref() == Ok("1") {
7702            let snap: Vec<Vec<f32>> = self
7703                .kv_cache
7704                .layers
7705                .iter()
7706                .map(|l| l.linear_state.clone())
7707                .collect();
7708            let attn_lens: Vec<usize> = self.kv_cache.layers.iter().map(|l| l.seq_len).collect();
7709            let toks: Vec<u32> = std::iter::once(t_next)
7710                .chain(drafts.iter().copied())
7711                .collect();
7712            let want_save = self.graph_want_logits;
7713            self.graph_want_logits = false;
7714            for (i, &t) in toks.iter().enumerate() {
7715                let hi = self.forward_layers(&self.embed_single(t), next_pos + i, None);
7716                let _ = self.graph_logits.take();
7717                // CMF_SPEC_PLAIN_HIDDEN=1: the next round drafts from the
7718                // plain path's hidden instead of the verify's (an experiment
7719                // on the chain's sensitivity to the half-GEMM noise)
7720                if std::env::var("CMF_SPEC_PLAIN_HIDDEN").as_deref() == Ok("1") {
7721                    hiddens[i * self.hidden_size..(i + 1) * self.hidden_size].copy_from_slice(&hi);
7722                }
7723                let ref_lg = self.logits_from_hidden(&hi);
7724                let row = &logits[i * lm_rows..(i + 1) * lm_rows];
7725                let ra = sampler::argmax(&ref_lg);
7726                let va = sampler::argmax(row);
7727                let mut md = 0f32;
7728                let mut rms = 0f64;
7729                for j in 0..lm_rows.min(ref_lg.len()) {
7730                    let d = (ref_lg[j] - row[j]).abs();
7731                    md = md.max(d);
7732                    rms += (d as f64) * (d as f64);
7733                }
7734                let mut hd = 0f32;
7735                for j in 0..self.hidden_size {
7736                    hd = hd.max((hi[j] - hiddens[i * self.hidden_size + j]).abs());
7737                }
7738                eprintln!(
7739                    "verify-check row {i} tok {t} pos {}: ref argmax {ra} verify argmax {va} {} | max|dlogit| {md:.3} rms {:.4} | max|dhidden| {hd:.4}",
7740                    next_pos + i,
7741                    if ra == va { "OK" } else { "MISMATCH" },
7742                    (rms / lm_rows as f64).sqrt()
7743                );
7744            }
7745            self.graph_want_logits = want_save;
7746            // restore IN PLACE: the pending verify graph wraps these very
7747            // allocations (zero-copy) — replacing the Vec would strand it
7748            for (l, st) in self.kv_cache.layers.iter_mut().zip(snap) {
7749                if l.linear_state.len() == st.len() {
7750                    l.linear_state.copy_from_slice(&st);
7751                } else {
7752                    l.linear_state = st;
7753                }
7754            }
7755            for (li, (l, n0)) in self.kv_cache.layers.iter_mut().zip(attn_lens).enumerate() {
7756                let extra = l.seq_len.saturating_sub(n0);
7757                if extra > 0 {
7758                    l.truncate_last(extra);
7759                    crate::gpu_metal::kv_mirror_set_stored(self.graph_kv_id, li, n0);
7760                }
7761            }
7762        }
7763        let t_verify = t_round.elapsed();
7764        let sub_verify = subs();
7765        // Acceptance. Greedy: row i's argmax is the trunk's token after
7766        // input i. Sampling: accept draft i with min(1, p_i/q_i), and on
7767        // the first rejection draw the correction from max(0, p_i − q_i)
7768        // — that token is committed by the loop top as-is (spec_forced).
7769        let mut a = 0usize;
7770        let mut forced: Option<u32> = None;
7771        let ids: Vec<u32> = if sparse {
7772            let mut p = std::mem::take(&mut self.spec_ps);
7773            let mut res = std::mem::take(&mut self.spec_ress);
7774            while a < k_spec {
7775                let ok = sampler::sparse_distribution_into(
7776                    &logits[a * lm_rows..(a + 1) * lm_rows],
7777                    &cfg,
7778                    all_ids,
7779                    &mut self.sampler_scratch,
7780                    self.pool.as_deref(),
7781                    &mut p,
7782                );
7783                if !ok {
7784                    let t = sampler::argmax(&logits[a * lm_rows..(a + 1) * lm_rows]);
7785                    p.clear();
7786                    p.push((t, 1.0));
7787                }
7788                match sampler::spec_accept_or_correct_sparse(
7789                    &p,
7790                    &self.spec_qs[a],
7791                    drafts[a],
7792                    &mut self.rng,
7793                    &mut res,
7794                ) {
7795                    None => {
7796                        all_ids.push(drafts[a]);
7797                        a += 1;
7798                    }
7799                    Some(c) => {
7800                        forced = Some(c);
7801                        break;
7802                    }
7803                }
7804            }
7805            all_ids.truncate(base_len);
7806            self.spec_ps = p;
7807            self.spec_ress = res;
7808            drafts.clone()
7809        } else if sampling {
7810            let mut p = std::mem::take(&mut self.spec_p);
7811            let mut res = std::mem::take(&mut self.spec_res);
7812            while a < k_spec {
7813                sampler::distribution_into(
7814                    &logits[a * lm_rows..(a + 1) * lm_rows],
7815                    &cfg,
7816                    all_ids,
7817                    &mut self.sampler_scratch,
7818                    self.pool.as_deref(),
7819                    &mut p,
7820                );
7821                match sampler::spec_accept_or_correct(
7822                    &p,
7823                    &self.spec_q[a],
7824                    drafts[a],
7825                    &mut self.rng,
7826                    &mut res,
7827                    self.pool.as_deref(),
7828                ) {
7829                    None => {
7830                        all_ids.push(drafts[a]);
7831                        a += 1;
7832                    }
7833                    Some(c) => {
7834                        forced = Some(c);
7835                        break;
7836                    }
7837                }
7838            }
7839            all_ids.truncate(base_len);
7840            self.spec_p = p;
7841            self.spec_res = res;
7842            // the accepted drafts ARE the verified tokens after inputs 0..a
7843            drafts.clone()
7844        } else if greedy_pen {
7845            // Row i's penalized argmax, penalties over the stream that
7846            // includes the accepted drafts before it — the plain loop's
7847            // exact arithmetic, one pass per row, no working copy.
7848            let mut ids: Vec<u32> = Vec::with_capacity(b);
7849            for i in 0..b {
7850                let t = sampler::argmax_penalized(
7851                    &logits[i * lm_rows..(i + 1) * lm_rows],
7852                    &cfg,
7853                    all_ids,
7854                    &mut self.sampler_scratch,
7855                    self.pool.as_deref(),
7856                );
7857                ids.push(t);
7858                if i < k_spec && t == drafts[i] {
7859                    all_ids.push(t);
7860                } else {
7861                    break;
7862                }
7863            }
7864            all_ids.truncate(base_len);
7865            while a < k_spec && a < ids.len() && ids[a] == drafts[a] {
7866                a += 1;
7867            }
7868            // rows past the first mismatch were never scored; the loop
7869            // top re-samples the last verified row itself.
7870            ids
7871        } else if greedy_dev && dev_ids.len() == b {
7872            let ids = std::mem::take(&mut dev_ids);
7873            while a < k_spec && ids[a] == drafts[a] {
7874                a += 1;
7875            }
7876            ids
7877        } else {
7878            if logits.len() < b * lm_rows {
7879                // the device argmax was asked for and came back short:
7880                // no rows to fall back on — terminal like a failed batch
7881                self.clear_sequence_state();
7882                self.graph_failed
7883                    .store(true, std::sync::atomic::Ordering::Relaxed);
7884                self.cancel
7885                    .store(true, std::sync::atomic::Ordering::Relaxed);
7886                tracing::error!("Metal verify returned neither logits nor argmax ids");
7887                return None;
7888            }
7889            let ids: Vec<u32> = (0..b)
7890                .map(|i| sampler::argmax(&logits[i * lm_rows..(i + 1) * lm_rows]))
7891                .collect();
7892            while a < k_spec && ids[a] == drafts[a] {
7893                a += 1;
7894            }
7895            ids
7896        };
7897        spec_stamp("acc");
7898        if spec_dbg {
7899            eprintln!(
7900                "spec-dbg round: t_next {t_next} drafts {:?} verified {:?} accepted {a}",
7901                drafts, ids
7902            );
7903        }
7904        // CMF_METAL_VERIFY_CHECK=2: the commit oracle — plain-forward the
7905        // a+1 accepted tokens from a snapshot, then diff the replayed GDN
7906        // states and the appended K/V rows against that.
7907        #[cfg(target_os = "macos")]
7908        let commit_ref: Option<(Vec<Vec<f32>>, Vec<(usize, Vec<f32>, Vec<f32>)>)> = if metal_native
7909            && std::env::var("CMF_METAL_VERIFY_CHECK").as_deref() == Ok("2")
7910        {
7911            let snap: Vec<Vec<f32>> = self
7912                .kv_cache
7913                .layers
7914                .iter()
7915                .map(|l| l.linear_state.clone())
7916                .collect();
7917            let attn_lens: Vec<usize> = self.kv_cache.layers.iter().map(|l| l.seq_len).collect();
7918            let toks: Vec<u32> = std::iter::once(t_next)
7919                .chain(drafts.iter().copied())
7920                .collect();
7921            let want_save = self.graph_want_logits;
7922            self.graph_want_logits = false;
7923            for (i, &t) in toks.iter().take(a + 1).enumerate() {
7924                let _ = self.forward_layers(&self.embed_single(t), next_pos + i, None);
7925                let _ = self.graph_logits.take();
7926            }
7927            self.graph_want_logits = want_save;
7928            let plain_states: Vec<Vec<f32>> = self
7929                .kv_cache
7930                .layers
7931                .iter()
7932                .map(|l| l.linear_state.clone())
7933                .collect();
7934            let (nkv, hd) = (self.num_kv_heads, self.head_dim);
7935            let mut rows = Vec::new();
7936            for (li, (l, n0)) in self
7937                .kv_cache
7938                .layers
7939                .iter_mut()
7940                .zip(attn_lens.iter())
7941                .enumerate()
7942            {
7943                let extra = l.seq_len.saturating_sub(*n0);
7944                if extra > 0 {
7945                    let mut kk = Vec::new();
7946                    let mut vv = Vec::new();
7947                    for g in 0..nkv {
7948                        kk.extend_from_slice(&l.head_keys(g)[n0 * hd..]);
7949                        vv.extend_from_slice(&l.head_values(g)[n0 * hd..]);
7950                    }
7951                    rows.push((li, kk, vv));
7952                    l.truncate_last(extra);
7953                    crate::gpu_metal::kv_mirror_set_stored(self.graph_kv_id, li, *n0);
7954                }
7955            }
7956            for (l, st) in self.kv_cache.layers.iter_mut().zip(snap) {
7957                if l.linear_state.len() == st.len() {
7958                    l.linear_state.copy_from_slice(&st);
7959                } else {
7960                    l.linear_state = st;
7961                }
7962            }
7963            Some((plain_states, rows))
7964        } else {
7965            None
7966        };
7967        let warm_off = std::env::var("CMF_SPEC_WARM").is_ok_and(|v| v == "0");
7968        // Metal: the MTP cache cut and the round's warm-up SUBMIT come
7969        // BEFORE the trunk commit, so the warm-up's command buffer is
7970        // queued ahead of the GDN replay (second queue) and its wait
7971        // below no longer sits behind the replay — measured: the warm-up's
7972        // wait grew with the accepted count exactly like the replay does
7973        // (8 ms at a=1, 17 ms at a=3, 25 ms at a=5 for ~2 ms of its own
7974        // work). The replay now overlaps the warm-up's readback, the
7975        // round's return and the next draft chain.
7976        #[cfg(target_os = "macos")]
7977        let mut warm_pending: Option<MetalWarmPending> = None;
7978        #[cfg(target_os = "macos")]
7979        if metal_native {
7980            m.kv.truncate_last(k_spec.saturating_sub(1));
7981            if self.mtp_graph_mode == Some(true) {
7982                // the mirror rows below the cut are the CPU rows: re-point,
7983                // no re-upload
7984                crate::gpu_metal::kv_mirror_set_stored(
7985                    self.mtp_kv_id(),
7986                    Self::MTP_LAYER_BASE,
7987                    m.kv.seq_len,
7988                );
7989                if !warm_off && a > 0 {
7990                    let pairs: Vec<(&[f32], u32)> = (0..a)
7991                        .map(|j| {
7992                            (
7993                                &hiddens[j * self.hidden_size..(j + 1) * self.hidden_size],
7994                                ids[j],
7995                            )
7996                        })
7997                        .collect();
7998                    warm_pending = self.mtp_warm_batch_submit(m, &pairs, next_pos);
7999                }
8000            }
8001            spec_stamp("c.wsub");
8002        }
8003        // a fully-accepted round needs no restore: every input was real.
8004        #[cfg(target_os = "macos")]
8005        if metal_native {
8006            // the Metal verify never wrote its states: the commit replays the
8007            // accepted prefix into the CPU owners and appends the K/V rows
8008            if !self.metal_verify_commit(a) {
8009                self.clear_sequence_state();
8010                self.graph_failed
8011                    .store(true, std::sync::atomic::Ordering::Relaxed);
8012                self.cancel
8013                    .store(true, std::sync::atomic::Ordering::Relaxed);
8014                tracing::error!("Metal verify state/KV handoff failed after admission");
8015                return None;
8016            }
8017            if let Some((plain_states, rows)) = commit_ref {
8018                crate::gpu_metal::queue_fence();
8019                // the commit's replay runs on the second queue: collect it
8020                // before the oracle reads the CPU owners it writes into
8021                let _ = crate::gpu_metal::wait_replay();
8022                let (nkv, hd) = (self.num_kv_heads, self.head_dim);
8023                let mut worst_s = 0f32;
8024                let mut worst_li = 0usize;
8025                for (li, (l, ps)) in self.kv_cache.layers.iter().zip(&plain_states).enumerate() {
8026                    if l.linear_state.len() != ps.len() || ps.is_empty() {
8027                        continue;
8028                    }
8029                    let d = l
8030                        .linear_state
8031                        .iter()
8032                        .zip(ps)
8033                        .fold(0f32, |m, (x, y)| m.max((x - y).abs()));
8034                    let n = ps.iter().fold(0f32, |m, y| m.max(y.abs()));
8035                    let rel = d / n.max(1e-6);
8036                    if rel > worst_s {
8037                        worst_s = rel;
8038                        worst_li = li;
8039                    }
8040                }
8041                let mut worst_k = 0f32;
8042                for (li, kk, vv) in &rows {
8043                    let l = &self.kv_cache.layers[*li];
8044                    let n0 = l.seq_len - (kk.len() / (nkv * hd));
8045                    let mut ck = Vec::new();
8046                    let mut cv = Vec::new();
8047                    for g in 0..nkv {
8048                        ck.extend_from_slice(&l.head_keys(g)[n0 * hd..]);
8049                        cv.extend_from_slice(&l.head_values(g)[n0 * hd..]);
8050                    }
8051                    if ck.len() == kk.len() {
8052                        let dk = ck
8053                            .iter()
8054                            .zip(kk)
8055                            .fold(0f32, |m, (x, y)| m.max((x - y).abs()));
8056                        let dv = cv
8057                            .iter()
8058                            .zip(vv)
8059                            .fold(0f32, |m, (x, y)| m.max((x - y).abs()));
8060                        worst_k = worst_k.max(dk).max(dv);
8061                    } else {
8062                        eprintln!(
8063                            "commit-check L{li}: kv row count mismatch {} vs {}",
8064                            ck.len(),
8065                            kk.len()
8066                        );
8067                    }
8068                }
8069                eprintln!(
8070                    "commit-check a={a}: worst GDN state rel-max diff {worst_s:.2e} (L{worst_li}) | worst K/V row abs diff {worst_k:.4}"
8071                );
8072            }
8073        }
8074        if !metal_native && a + 1 < b {
8075            let expected_gdn_layers = self.graph_gdn_layer_count();
8076            if expected_gdn_layers > 0
8077                && !crate::gpu::gdn_spec_restore(self.graph_kv_id, a, next_pos, expected_gdn_layers)
8078            {
8079                self.clear_sequence_state();
8080                self.graph_failed
8081                    .store(true, std::sync::atomic::Ordering::Relaxed);
8082                self.cancel
8083                    .store(true, std::sync::atomic::Ordering::Relaxed);
8084                tracing::error!("GDN speculative restore failed after verify");
8085                return None;
8086            }
8087        }
8088        if !metal_native && !self.rewind_trunk_graph_mirrors(next_pos + a + 1) {
8089            // The verify graph committed the full batch, but one of its
8090            // persistent Full-attention mirrors could not be re-pointed to
8091            // the accepted prefix.  Treat that as terminal state failure;
8092            // an exact CPU fallback would otherwise consume stale GDN/KV.
8093            self.clear_sequence_state();
8094            self.graph_failed
8095                .store(true, std::sync::atomic::Ordering::Relaxed);
8096            self.cancel
8097                .store(true, std::sync::atomic::Ordering::Relaxed);
8098            tracing::error!("trunk graph KV rewind failed after speculative verify");
8099            return None;
8100        }
8101        *accepted += a;
8102        // MTP cache: keep the first draft row (its inputs were real), drop
8103        // the chain's, then append the verified pairs the round produced.
8104        // Each of those is a whole MTP block on the per-op path and they
8105        // cost 5.8 ms of a 69 ms round at k=3 — a third of what the
8106        // round's own draft costs. PRICED, and they earn it: skipping
8107        // them (`CMF_SPEC_WARM=0`) drops acceptance from 89% to 81% at
8108        // k=3 and 85% to 74% at k=4, and the tok/s goes nowhere at k=3
8109        // (50.3 against 50.5) and backwards at k=4 (48.1 against 50.1).
8110        // The knob stays so the next person can re-price it after the
8111        // warms are batched instead of assuming either way.
8112        if !metal_native {
8113            // (Metal cut its MTP cache before the trunk commit, above)
8114            m.kv.truncate_last(k_spec.saturating_sub(1));
8115        }
8116        spec_stamp("c.trunc");
8117        if !metal_native
8118            && self.mtp_graph_mode == Some(true)
8119            && !self.rewind_mtp_graph_mirror(next_pos)
8120        {
8121            // The graph draft was admitted, so inability to move its cursor
8122            // back to the real anchor is a state failure, not a capability
8123            // refusal.  Do not warm or continue with a stale mirror.
8124            self.clear_sequence_state();
8125            self.graph_failed
8126                .store(true, std::sync::atomic::Ordering::Relaxed);
8127            self.cancel
8128                .store(true, std::sync::atomic::Ordering::Relaxed);
8129            tracing::error!("MTP graph mirror rewind failed after verify commit");
8130            return None;
8131        }
8132        if !warm_off && a > 0 {
8133            // Graph arm: all accepted pairs in ONE batched run over the
8134            // MTP block; the token graph one by one if the batch declines.
8135            let mut warmed = false;
8136            #[cfg(target_os = "macos")]
8137            if metal_native && self.mtp_graph_mode == Some(true) {
8138                // the batched warm-up was submitted before the trunk
8139                // commit: collect it here; one by one on the token graph
8140                // if it declined (or failed)
8141                warmed = match warm_pending.take() {
8142                    Some(p) => self.mtp_warm_batch_finish(m, p),
8143                    None => false,
8144                };
8145                if !warmed {
8146                    warmed = true;
8147                    for j in 0..a {
8148                        let row =
8149                            hiddens[j * self.hidden_size..(j + 1) * self.hidden_size].to_vec();
8150                        if self
8151                            .mtp_step_metal(m, &row, ids[j], next_pos + j, false)
8152                            .is_none()
8153                        {
8154                            warmed = false;
8155                            break;
8156                        }
8157                    }
8158                }
8159            }
8160            if !warmed && self.mtp_graph_mode != Some(false) && !metal_native {
8161                let rows: Vec<Vec<f32>> = (0..a)
8162                    .map(|j| hiddens[j * self.hidden_size..(j + 1) * self.hidden_size].to_vec())
8163                    .collect();
8164                let pairs: Vec<(&[f32], u32)> = rows
8165                    .iter()
8166                    .zip(ids.iter())
8167                    .map(|(r, &t)| (r.as_slice(), t))
8168                    .collect();
8169                match self.mtp_warm_prefill_pairs(m, &pairs, next_pos) {
8170                    Ok(()) => warmed = true,
8171                    Err(err) => {
8172                        // A warm-up failure after graph admission cannot
8173                        // fall back to `mtp_warm`: the detached CPU cache is
8174                        // not authoritative for the device mirror.  Mark it
8175                        // terminal so the generation caller clears state and
8176                        // returns instead of drafting from stale attention.
8177                        tracing::error!("{err}");
8178                        self.clear_sequence_state();
8179                        self.graph_failed
8180                            .store(true, std::sync::atomic::Ordering::Relaxed);
8181                        self.cancel
8182                            .store(true, std::sync::atomic::Ordering::Relaxed);
8183                        return None;
8184                    }
8185                }
8186            }
8187            if !warmed {
8188                for j in 0..a {
8189                    let row = &hiddens[j * self.hidden_size..(j + 1) * self.hidden_size];
8190                    let row = row.to_vec();
8191                    self.mtp_warm(m, &row, ids[j], next_pos + j);
8192                }
8193            }
8194        }
8195        // The sampler's contract: logits of the LAST verified position —
8196        // unless a rejected draft already drew the correction, in which
8197        // case the loop top commits that token and samples nothing.
8198        spec_stamp("c.warm");
8199        if let Some(c) = forced {
8200            self.spec_forced = Some(c);
8201            self.graph_logits = None;
8202        } else if greedy_dev && logits.is_empty() {
8203            // the row's argmax IS the token the loop top would pick from
8204            // it (plain greedy, no penalties): commit it as forced
8205            self.spec_forced = Some(ids[a]);
8206            self.graph_logits = None;
8207        } else {
8208            let mut row = logits[a * lm_rows..(a + 1) * lm_rows].to_vec();
8209            row.resize(self.vocab_size, 0.0);
8210            if let Some(c) = self.final_softcap {
8211                for l in row.iter_mut() {
8212                    *l = c * (*l / c).tanh();
8213                }
8214            }
8215            self.graph_logits = Some(row);
8216        }
8217        let new_hidden = hiddens[a * self.hidden_size..(a + 1) * self.hidden_size].to_vec();
8218        spec_stamp("c.row");
8219        // Three phases, not two. The round's wall clock was 4 ms longer
8220        // than draft+verify and the difference had nowhere to be seen:
8221        // the accepted prefix re-runs the MTP block once per token to
8222        // keep the draft head's attention cache warm, and the GDN state
8223        // rolls back on any rejection. Both live here, after the verify.
8224        if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
8225            let end = subs();
8226            eprintln!(
8227                "spec-round: draft {:.1} ms/{} sub | verify {:.1} ms/{} sub | \
8228                 commit {:.1} ms/{} sub (accepted {a} of {k_spec}, full-head streak {})",
8229                t_draft.as_secs_f64() * 1e3,
8230                sub_draft - sub0,
8231                (t_verify - t_draft).as_secs_f64() * 1e3,
8232                sub_verify - sub_draft,
8233                (t_round.elapsed() - t_verify).as_secs_f64() * 1e3,
8234                end - sub_verify,
8235                self.draft_full_streak,
8236            );
8237        }
8238        // Native Metal's verify tile is flat in b (eight rows for the price
8239        // of one), so a shorter round only forfeits tokens — measured on
8240        // the M4: an essay round at k=2 still verified in 260 ms. The
8241        // adaptation is for cards whose verify grows with the rows.
8242        if k_env.is_none() && !metal_native && !k_capped {
8243            // Slow average and a wide band: a fast one oscillated 2↔3 on
8244            // an essay every other round (measured), which forfeits the
8245            // draft it just paid for.
8246            let f = a as f32 / k_spec.max(1) as f32;
8247            self.spec_acc_ewma += 0.2 * (f - self.spec_acc_ewma);
8248            let mut k_next = k_spec;
8249            if self.spec_acc_ewma >= 0.75 && k_spec < k_max {
8250                k_next = k_spec + 1;
8251            } else if self.spec_acc_ewma < 0.4 && k_spec > 2 {
8252                k_next = k_spec - 1;
8253            }
8254            if k_next != k_spec {
8255                self.spec_acc_ewma = 0.6;
8256                if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
8257                    eprintln!("spec-k: {k_spec} → {k_next}");
8258                }
8259            }
8260            self.spec_k_adapt = Some(k_next);
8261        }
8262        spec_stamp("end");
8263        Some((drafts[..a].to_vec(), next_pos + a + 1, new_hidden))
8264    }
8265
8266    /// Micro-benchmark: two single-position forwards vs one fused pair
8267    /// from the current cache state (KV rewound after each probe).
8268    /// Returns (two_singles_ms, fused_pair_ms) per probe, or the (0, 0)
8269    /// sentinel when this model has no pair path to measure — the same
8270    /// answer the o1 arm gives, and the bench prints it the same way.
8271    /// (An architecture that loads its own layers leaves `weights.layers`
8272    /// empty; walking it here was an index panic, found by `bench` on
8273    /// deepseek_v4.)
8274    pub fn measure_pair_fusion(&mut self, iters: usize) -> (f64, f64) {
8275        if !self.pair_supported() {
8276            return (0.0, 0.0);
8277        }
8278        // A GDN model that needs an automatic device prefix never uses this
8279        // fused-pair path in normal generation: its recurrence is serial and
8280        // the speculative pair is disabled by default.  More importantly,
8281        // this diagnostic suppresses the token graph, so measuring it would
8282        // stream the non-resident tail through per-op Vulkan just to print a
8283        // non-production number.  Leave inference untouched and report the
8284        // established unavailable sentinel instead.
8285        if self.gdn_cfg.is_some()
8286            && self.graph_prefill_preferred()
8287            && self.automatic_gpu_prefix().is_some()
8288        {
8289            tracing::info!(
8290                "pair micro-benchmark skipped: GDN device-prefix path has no production pair route"
8291            );
8292            return (0.0, 0.0);
8293        }
8294        // This is a host-side pair micro-benchmark. It truncates the host KV
8295        // after every probe, so letting the whole-token graph participate
8296        // would leave its device GDN/KV mirror ahead of the next probe and
8297        // poison the process-wide graph verdict before the real generation
8298        // benchmark starts. Keep the existing per-op/GPU arithmetic while
8299        // suppressing only the stateful token graph for this measurement.
8300        let graph_env = std::env::var_os("CMF_GPU_WGPU_GRAPH");
8301        unsafe { std::env::set_var("CMF_GPU_WGPU_GRAPH", "0") };
8302        let emb1 = self.embed_single(1);
8303        let emb2 = self.embed_single(2);
8304        let pos = self.kv_cache.seq_len();
8305
8306        let t0 = std::time::Instant::now();
8307        for _ in 0..iters {
8308            let _ = self.forward_layers(&emb1, pos, None);
8309            let _ = self.forward_layers(&emb2, pos + 1, None);
8310            for l in &mut self.kv_cache.layers {
8311                l.truncate_last(2);
8312            }
8313        }
8314        let singles_ms = t0.elapsed().as_secs_f64() * 1000.0 / iters as f64;
8315
8316        let t1 = std::time::Instant::now();
8317        for _ in 0..iters {
8318            let _ = self.forward_pair(&emb1, &emb2, pos);
8319            for l in &mut self.kv_cache.layers {
8320                l.truncate_last(2);
8321            }
8322        }
8323        let pair_ms = t1.elapsed().as_secs_f64() * 1000.0 / iters as f64;
8324        match graph_env {
8325            Some(value) => unsafe { std::env::set_var("CMF_GPU_WGPU_GRAPH", value) },
8326            None => unsafe { std::env::remove_var("CMF_GPU_WGPU_GRAPH") },
8327        }
8328        (singles_ms, pair_ms)
8329    }
8330
8331    /// Fused two-position forward: weight rows are streamed from memory
8332    /// once per layer for both positions. Full layers → fused GQA pair;
8333    /// linear layers → vmf_phase pair (lane 2 state is tentative in the
8334    /// per-layer scratch until the draft is accepted).
8335    /// Whether the fused two-position path covers every layer kind in
8336    /// this model. MLA and KDA run per position (their pair arms are
8337    /// unreachable); the seq prefill falls back to singles for them.
8338    fn pair_supported(&self) -> bool {
8339        // An EMPTY layer stack means the architecture loaded its own and
8340        // this path has nothing to walk. Checking that directly, rather
8341        // than naming each such architecture, is what makes the guard hold
8342        // for the next one: `any()` over no layers is false, so a
8343        // feature-by-feature test says "supported" for a model that has no
8344        // layers here at all.
8345        !self.weights.layers.is_empty()
8346            && !self.per_token_stack()
8347            && !self
8348                .weights
8349                .layers
8350                .iter()
8351                .any(|lw| matches!(&lw.attn, AttnKind::Mla(_) | AttnKind::Kda(_)))
8352    }
8353
8354    fn forward_pair(
8355        &mut self,
8356        emb1: &[f32],
8357        emb2: &[f32],
8358        position: usize,
8359    ) -> (Vec<f32>, Vec<f32>) {
8360        // A two-token prompt starts here, not in the layer walk: decide the
8361        // MiMo placement before the pair's per-op MoE uploads any expert.
8362        self.mimo_moe_prepare();
8363        let mut h1 = emb1.to_vec();
8364        let mut h2 = emb2.to_vec();
8365        let (_nkv, _hd, hs, _rd, eps) = (
8366            self.num_kv_heads,
8367            self.head_dim,
8368            self.hidden_size,
8369            self.rotary_dim,
8370            self.rms_eps,
8371        );
8372        let pool = self.pool.clone();
8373        // `forward_pair` bypasses `forward_layers_span`, but its per-op
8374        // body must still obey the ordinary layer placement. In particular,
8375        // an over-capacity Vulkan model has a device prefix and a CPU tail;
8376        // letting the pair walk submit the tail's selected MoE experts would
8377        // stream the whole tail through the residency arena and defeat the
8378        // measured VRAM bound.
8379        let automatic_gpu_prefix = self.automatic_gpu_prefix();
8380
8381        for li in 0..self.num_layers {
8382            let _capacity_tail = automatic_gpu_prefix
8383                .filter(|&prefix| li >= prefix && !self.mimo_moe.is_dynamic(li, false))
8384                .map(|_| crate::gpu::enter_cpu_scope());
8385            // Also makes an explicit CMF_GPU_LAYERS split apply to fused
8386            // pairs, just as it does to the ordinary layer walk.
8387            crate::gpu::set_layer(li as i64);
8388            let lw = &self.weights.layers[self.phys_layer(li)];
8389            // Norms into pipeline scratch (4 allocs/layer on the MTP
8390            // decode hot path before this).
8391            inference::rms_norm_into(
8392                &h1,
8393                &lw.input_norm,
8394                self.rms_eps,
8395                self.norm_style,
8396                &mut self.ws.n1,
8397            );
8398            inference::rms_norm_into(
8399                &h2,
8400                &lw.input_norm,
8401                self.rms_eps,
8402                self.norm_style,
8403                &mut self.ws.n2,
8404            );
8405
8406            let (a1, a2) = match &lw.attn {
8407                AttnKind::Mla(_) => unreachable!("MLA has no MTP/pair path"),
8408                AttnKind::Kda(_) => unreachable!("KDA has no MTP/pair path"),
8409                AttnKind::Bounded(w) => {
8410                    // Two sequential positions of the bounded operator
8411                    // (the ring's causal order is the pair's order).
8412                    let rope = self
8413                        .bounded_rope
8414                        .clone()
8415                        .expect("bounded layer without an installed rotation table");
8416                    let cfg = crate::bounded::BoundedAttnCfg {
8417                        num_heads: self.num_heads,
8418                        num_kv_heads: self.num_kv_heads,
8419                        head_dim: self.head_dim,
8420                        hidden_size: hs,
8421                        scale: self.attn_scale,
8422                        rope: &rope,
8423                        pool: pool.as_deref(),
8424                    };
8425                    let a1 = crate::bounded::bounded_attention(
8426                        &self.ws.n1,
8427                        w,
8428                        &mut self.kv_cache.layers[li],
8429                        &cfg,
8430                    );
8431                    let a2 = crate::bounded::bounded_attention(
8432                        &self.ws.n2,
8433                        w,
8434                        &mut self.kv_cache.layers[li],
8435                        &cfg,
8436                    );
8437                    (a1, a2)
8438                }
8439                AttnKind::Linear(w) => {
8440                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
8441                    let layer = &mut self.kv_cache.layers[li];
8442                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
8443                    vmf_phase_pair(
8444                        &self.ws.n1,
8445                        &self.ws.n2,
8446                        w,
8447                        &cfg,
8448                        state,
8449                        scratch,
8450                        self.pool.as_deref(),
8451                    )
8452                }
8453                AttnKind::LinearGdn(w) => {
8454                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
8455                    let layer = &mut self.kv_cache.layers[li];
8456                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
8457                    gdn_pair(
8458                        &self.ws.n1,
8459                        &self.ws.n2,
8460                        w,
8461                        &cfg,
8462                        state,
8463                        scratch,
8464                        self.pool.as_deref(),
8465                    )
8466                }
8467                AttnKind::ShortConv(w) => {
8468                    let cfg = self
8469                        .short_conv_cfg
8470                        .expect("short-conv layer without short_conv_cfg");
8471                    let layer = &mut self.kv_cache.layers[li];
8472                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
8473                    short_conv_pair(
8474                        &self.ws.n1,
8475                        &self.ws.n2,
8476                        w,
8477                        &cfg,
8478                        state,
8479                        scratch,
8480                        self.pool.as_deref(),
8481                    )
8482                }
8483                AttnKind::Full {
8484                    wq,
8485                    wk,
8486                    wv,
8487                    wo,
8488                    q_norm,
8489                    k_norm,
8490                    output_gate,
8491                    softplus_gate,
8492                    bias,
8493                } => {
8494                    let inv_freq_l = self.layer_inv_freq(li);
8495                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
8496                    let cfg = QwenAttnCfg {
8497                        num_heads: self.layer_num_heads(li),
8498                        num_kv_heads: nkv_l,
8499                        head_dim: hd_l,
8500                        hidden_size: hs,
8501                        position,
8502                        inv_freq: &inv_freq_l,
8503                        rotary_dim: rd_l,
8504                        scale: self.attn_scale,
8505                        softcap: self.attn_softcap,
8506                        window: self.layer_window(li),
8507                        v_norm: self.attn_v_norm,
8508                        qk_norm_after_rope: self.qk_norm_after_rope,
8509                        gate_sigmoid: self.proj_gate_sigmoid,
8510                        q_norm: q_norm.as_deref(),
8511                        k_norm: k_norm.as_deref(),
8512                        output_gate: *output_gate,
8513                        softplus_gate: softplus_gate
8514                            .as_ref()
8515                            .map(|(gate, per_head)| (gate, *per_head)),
8516                        rope_scale: self.layer_rope_scale(li),
8517                        bias: bias
8518                            .as_ref()
8519                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
8520                        rms_eps: eps,
8521                        norm_style: self.norm_style,
8522                        pool: pool.as_deref(),
8523                        v_head_dim: self.layer_v_dim(li),
8524                    };
8525                    attention::qwen_attention_pair(
8526                        &self.ws.n1,
8527                        &self.ws.n2,
8528                        wq,
8529                        wk,
8530                        wv,
8531                        wo,
8532                        &mut self.kv_cache.layers[li],
8533                        &cfg,
8534                    )
8535                }
8536            };
8537            let (a1, a2) = match &self.weights.layers[self.phys_layer(li)].attn_out_norm {
8538                Some(w) => (
8539                    inference::rms_norm(&a1, w, self.rms_eps, self.norm_style),
8540                    inference::rms_norm(&a2, w, self.rms_eps, self.norm_style),
8541                ),
8542                None => (a1, a2),
8543            };
8544            for i in 0..self.hidden_size {
8545                h1[i] += a1[i];
8546                h2[i] += a2[i];
8547            }
8548            let (mut a1, mut a2) = (a1, a2);
8549            attention::recycle_buf(&mut a1);
8550            attention::recycle_buf(&mut a2);
8551
8552            let lw = &self.weights.layers[self.phys_layer(li)];
8553            inference::rms_norm_into(
8554                &h1,
8555                &lw.post_norm,
8556                self.rms_eps,
8557                self.norm_style,
8558                &mut self.ws.p1,
8559            );
8560            inference::rms_norm_into(
8561                &h2,
8562                &lw.post_norm,
8563                self.rms_eps,
8564                self.norm_style,
8565                &mut self.ws.p2,
8566            );
8567            let (f1, f2) = match &lw.ffn {
8568                // Dual-branch layers need the raw residuals — run the
8569                // two positions through the same fn decode uses.
8570                FfnKind::DenseMoe(dm) => (
8571                    dense_moe_ffn(
8572                        dm,
8573                        &self.ws.p1,
8574                        &h1,
8575                        self.rms_eps,
8576                        self.norm_style,
8577                        self.pool.as_deref(),
8578                    ),
8579                    dense_moe_ffn(
8580                        dm,
8581                        &self.ws.p2,
8582                        &h2,
8583                        self.rms_eps,
8584                        self.norm_style,
8585                        self.pool.as_deref(),
8586                    ),
8587                ),
8588                FfnKind::Moe(m) if self.mimo_moe.is_dynamic(li, false) => (
8589                    moe_ffn_banked(&mut self.mimo_moe, li, m, &self.ws.p1, self.pool.as_deref()),
8590                    moe_ffn_banked(&mut self.mimo_moe, li, m, &self.ws.p2, self.pool.as_deref()),
8591                ),
8592                _ => ffn_forward_pair(
8593                    &lw.ffn,
8594                    &self.ws.p1,
8595                    &self.ws.p2,
8596                    self.pool.as_deref(),
8597                    None,
8598                ),
8599            };
8600            let (f1, f2) = match &self.weights.layers[self.phys_layer(li)].ffn_out_norm {
8601                Some(w) => (
8602                    inference::rms_norm(&f1, w, self.rms_eps, self.norm_style),
8603                    inference::rms_norm(&f2, w, self.rms_eps, self.norm_style),
8604                ),
8605                None => (f1, f2),
8606            };
8607            for i in 0..self.hidden_size {
8608                h1[i] += f1[i];
8609                h2[i] += f2[i];
8610            }
8611            let (mut f1, mut f2) = (f1, f2);
8612            attention::recycle_buf(&mut f1);
8613            attention::recycle_buf(&mut f2);
8614            if let Some(sc) = self.weights.layers[self.phys_layer(li)].layer_scale {
8615                for i in 0..self.hidden_size {
8616                    h1[i] *= sc;
8617                    h2[i] *= sc;
8618                }
8619            }
8620            // Looped Transformer: apply final norm at the end of each loop iteration.
8621            if self.is_loop_end(li) && li + 1 < self.num_layers {
8622                h1 = inference::rms_norm(
8623                    &h1,
8624                    &self.weights.final_norm,
8625                    self.rms_eps,
8626                    self.norm_style,
8627                );
8628                h2 = inference::rms_norm(
8629                    &h2,
8630                    &self.weights.final_norm,
8631                    self.rms_eps,
8632                    self.norm_style,
8633                );
8634            }
8635        }
8636        crate::gpu::set_layer(-1); // final/O(1) work is outside layer placement
8637        // Real O(1) prefill pairs may also carry tentative lane-2 recurrent
8638        // state. Commit it before publishing the transition epoch so the
8639        // next serial/device row cannot observe a new attention epoch with an
8640        // old GDN state. Speculative pairs run only when O(1) is inactive and
8641        // retain their existing caller-controlled commit/rollback semantics.
8642        if self.o1_active() {
8643            self.commit_linear_scratch();
8644        }
8645        self.o1_progress();
8646        self.swa_trim_tails();
8647        (h1, h2)
8648    }
8649
8650    /// Commit lane-2 linear states after an accepted draft.
8651    fn commit_linear_scratch(&mut self) {
8652        for layer in &mut self.kv_cache.layers {
8653            if !layer.linear_scratch.is_empty() {
8654                std::mem::swap(&mut layer.linear_state, &mut layer.linear_scratch);
8655                layer.linear_scratch.clear();
8656            }
8657        }
8658    }
8659
8660    /// This is the encoder counterpart to `forward_ids`: it runs a fresh
8661    /// sequence through the existing full/GDN hybrid stack and returns the
8662    /// final RMS-normalized hidden row for *every* token.  It is used by
8663    /// component pipelines whose text tower intentionally has no LM head
8664    /// (such as an image-conditioner Qwen3.5 model).  The sequence state is
8665    /// always released before returning, so a large text tower can be dropped
8666    /// immediately after conditioning a subsequent stage.
8667    pub fn encode_hidden_states(&mut self, ids: &[u32]) -> Result<Vec<f32>, String> {
8668        #[cfg(target_os = "macos")]
8669        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
8670        if ids.is_empty() {
8671            return Err("empty id sequence".to_string());
8672        }
8673
8674        self.nll_begin()?;
8675        let result = (|| {
8676            let hidden = self.prefill_input_rows(PrefillIn::Ids(ids), 0, None)?;
8677            self.nll_check_graph("encoder prefill", 0)?;
8678            let expected = ids.len() * self.hidden_size;
8679            if hidden.len() != expected {
8680                return Err(format!(
8681                    "encoder prefill returned {} values for {} rows of hidden size {}",
8682                    hidden.len(),
8683                    ids.len(),
8684                    self.hidden_size
8685                ));
8686            }
8687
8688            let mut out = vec![0.0f32; expected];
8689            for (src, dst) in hidden
8690                .chunks_exact(self.hidden_size)
8691                .zip(out.chunks_exact_mut(self.hidden_size))
8692            {
8693                inference::rms_norm_into(
8694                    src,
8695                    &self.weights.final_norm,
8696                    self.rms_eps,
8697                    self.norm_style,
8698                    dst,
8699                );
8700            }
8701            Ok(out)
8702        })();
8703        self.nll_end();
8704        result
8705    }
8706
8707    /// Forward a full id sequence from a fresh cache and return the
8708    /// logits after the last position (golden-parity harness, bench).
8709    pub fn forward_ids(
8710        &mut self,
8711        ids: &[u32],
8712        task_mask: Option<&TaskMask>,
8713    ) -> Result<Vec<f32>, String> {
8714        #[cfg(target_os = "macos")]
8715        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
8716        if ids.is_empty() {
8717            return Err("empty id sequence".to_string());
8718        }
8719        self.clear_sequence_state();
8720        self.check_forward_graph("forward_ids setup", 0)?;
8721        if task_mask.is_none() {
8722            self.o1_begin();
8723        }
8724        let mut hidden = vec![0.0f32; self.hidden_size];
8725        let mut pos = 0usize;
8726        if let Some(b) = &mut self.dsv41 {
8727            let pool = self.pool.clone();
8728            let mut logits = Vec::new();
8729            crate::dsv41::forward_chunk(
8730                &b.0,
8731                &b.1,
8732                &b.2,
8733                &mut b.3,
8734                ids,
8735                0,
8736                pool.as_deref(),
8737                &mut logits,
8738            );
8739            if let Err(err) = self.o1_seal_checked() {
8740                self.clear_sequence_state();
8741                return Err(err);
8742            }
8743            return Ok(logits);
8744        }
8745        // Same routing predicate generation uses. Two reasons it must be
8746        // the same one: (1) a GDN hybrid's recurrent state is GPU-
8747        // resident, and a batched CPU prefill would build it on the host
8748        // only — decode then reads buffers the prefill never wrote;
8749        // (2) bench times THIS function and calls the result "prefill",
8750        // so a different path here reports a number production never
8751        // sees (W2 on 2×5090: 8.7 tok/s reported against 125 real).
8752        // Gemma-4: generation's batched-graph ingest (`g4_batch_ingest`),
8753        // so bench and the parity tools time and score the route run/serve
8754        // take; a refusal leaves the rest to the chunked host prefill.
8755        #[cfg(not(target_os = "macos"))]
8756        if task_mask.is_none() && ids.len() > 2 && self.g4_batch_prefill() {
8757            let (n, last) = match self.g4_batch_ingest(ids, 0, false) {
8758                Ok(r) => r,
8759                Err(e) => {
8760                    self.clear_sequence_state();
8761                    return Err(e);
8762                }
8763            };
8764            if n > 0 {
8765                hidden.copy_from_slice(&last);
8766                pos = n;
8767            }
8768        }
8769        if self.can_prefill_batched() && !self.graph_prefill_preferred() && ids.len() > 2 {
8770            // prefill-GEMM in chunks; only the last position's hidden is
8771            // needed. (o1-compatible: the batch path attends per position
8772            // through qwen_attention, which carries the collection hook.)
8773            let chunk = self.prefill_chunk();
8774            let hs = self.hidden_size;
8775            while pos < ids.len() {
8776                let end = (pos + chunk).min(ids.len());
8777                let hb = self.prefill_rows(&ids[pos..end], pos, task_mask)?;
8778                self.check_forward_graph("forward_ids batched prefill", end - 1)?;
8779                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
8780                pos = end;
8781            }
8782        }
8783        // Same guards as generation's prefill — INCLUDING the graph one.
8784        // The CPU pair walk was intercepting positions that the resident
8785        // token graph would have run itself: on a GDN hybrid over wgpu
8786        // that is 89 ms of host forward against 7 ms of device submit,
8787        // and it made prefill look 12× slower than it is (W2 on an RTX
8788        // 5090, ctx 512: 11.2 tok/s with the walk, 136.6 without).
8789        // CMF_PAIR=0 opts out; a model whose layers live outside
8790        // `weights.layers` has no pair walk to take.
8791        if task_mask.is_none()
8792            && !self.graph_prefill_preferred()
8793            && !std::env::var("CMF_PAIR").is_ok_and(|v| v == "0")
8794            && self.pair_supported()
8795        {
8796            while pos + 1 < ids.len() {
8797                let e1 = self.embed_single(ids[pos]);
8798                let e2 = self.embed_single(ids[pos + 1]);
8799                let (_, h2) = self.forward_pair(&e1, &e2, pos);
8800                self.check_forward_graph("forward_ids pair", pos + 1)?;
8801                self.commit_linear_scratch();
8802                hidden = h2;
8803                pos += 2;
8804            }
8805        }
8806        // Resident Embryo graph: the prompt in chunks of one submit each
8807        // (the same device state and logits as the per-position walk).
8808        if task_mask.is_none() && pos == 0 && ids.len() > 1 {
8809            if let Some(lg) = self.embryo_prefill_chunked(ids, 0) {
8810                self.graph_logits = Some(lg);
8811                hidden = vec![0.0; self.hidden_size];
8812                pos = ids.len();
8813            }
8814        }
8815        while pos < ids.len() {
8816            hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, task_mask);
8817            self.check_forward_graph("forward_ids", pos)?;
8818            pos += 1;
8819        }
8820        if let Some(logits) = self.graph_logits.take() {
8821            // Resident stacks already applied final norm and their head in
8822            // the same submit; do not run a second norm/head over the zero
8823            // hidden sentinel returned by forward_layers_span.
8824            if let Err(err) = self.o1_seal_checked() {
8825                self.clear_sequence_state();
8826                return Err(err);
8827            }
8828            return Ok(logits);
8829        }
8830        // Harness contract: after forward_ids the cache is decode-ready —
8831        // under o1 that means sealed (bench measures the seal as part of
8832        // prefill, honestly).
8833        if let Err(err) = self.o1_seal_checked() {
8834            self.clear_sequence_state();
8835            return Err(err);
8836        }
8837        let normed = inference::rms_norm(
8838            &hidden,
8839            &self.weights.final_norm,
8840            self.rms_eps,
8841            self.norm_style,
8842        );
8843        Ok(self.lm_head_forward(&normed))
8844    }
8845
8846    /// Run the V4.1 stack one token at a time and retain logits for every
8847    /// position. This is a diagnostic surface for comparing a converted
8848    /// checkpoint with a tokenwise reference implementation.
8849    #[doc(hidden)]
8850    pub fn dsv41_serial_logits(&mut self, ids: &[u32]) -> Result<Vec<Vec<f32>>, String> {
8851        #[cfg(target_os = "macos")]
8852        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
8853        if ids.is_empty() {
8854            return Err("empty id sequence".to_string());
8855        }
8856        self.clear_sequence_state();
8857        self.dsv41
8858            .as_ref()
8859            .ok_or_else(|| "dsv41 serial logits require a DeepSeek-V4.1 model".to_string())?;
8860        self.o1_begin();
8861        let rows = {
8862            let pool = self.pool.clone();
8863            let b = self
8864                .dsv41
8865                .as_mut()
8866                .expect("dsv41 checked above; state cannot change during forward");
8867            let mut rows = Vec::with_capacity(ids.len());
8868            for (position, &id) in ids.iter().enumerate() {
8869                let mut logits = Vec::new();
8870                crate::dsv41::forward_token(
8871                    &b.0,
8872                    &b.1,
8873                    &b.2,
8874                    &mut b.3,
8875                    id,
8876                    position,
8877                    pool.as_deref(),
8878                    &mut logits,
8879                );
8880                rows.push(logits);
8881            }
8882            rows
8883        };
8884        self.o1_seal();
8885        Ok(rows)
8886    }
8887
8888    /// GPTQ calibration of DeepSeek-V4.1 (`cortiq quantize-moe`): the MoE
8889    /// input rows and routed expert ids of layers `lo..hi` for `ids` (a fresh
8890    /// sequence), see [`crate::dsv41::Dsv41MoeCapture`].
8891    pub fn dsv41_moe_capture(
8892        &mut self,
8893        ids: &[u32],
8894        lo: usize,
8895        hi: usize,
8896    ) -> Result<crate::dsv41::Dsv41MoeCapture, String> {
8897        #[cfg(target_os = "macos")]
8898        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
8899        if ids.is_empty() {
8900            return Err("empty id sequence".to_string());
8901        }
8902        self.dsv41
8903            .as_ref()
8904            .ok_or_else(|| "not a DeepSeek-V4.1 model".to_string())?;
8905        self.clear_sequence_state();
8906        let res = {
8907            let pool = self.pool.clone();
8908            let b = self.dsv41.as_mut().expect("dsv41 checked above");
8909            crate::dsv41::capture_window(&b.0, &b.1, &b.2, &mut b.3, ids, lo, hi, pool.as_deref())
8910        };
8911        self.clear_sequence_state();
8912        res
8913    }
8914
8915    /// Teacher-forced perplexity over a token sequence (phase-C gate:
8916    /// honest quant comparisons instead of prompt vibes).
8917    ///
8918    /// Attention is EXACT even on a model whose layers are flagged for
8919    /// the O(1) kernel — scoring the backbone is the default on purpose
8920    /// (it is the yardstick). `nll_ids_o1` scores the CONVERTED model.
8921    pub fn ppl_ids(&mut self, ids: &[u32]) -> Result<f64, String> {
8922        let (nll, cnt) = self.nll_ids_from(ids, 0)?;
8923        Ok((nll / cnt.max(1) as f64).exp())
8924    }
8925
8926    /// GPTQ calibration forward: `ids` through layers `0..upto` only, in
8927    /// layer-major chunks of `chunk` positions, with no vocabulary head and
8928    /// no scoring. The Hessian hook (`gptq_capture`) folds every
8929    /// projection's input on the way; the layers above the captured span
8930    /// and the head would only cost time. Falls back to a scored forward
8931    /// where the batched prefill does not apply.
8932    pub fn calib_forward(&mut self, ids: &[u32], upto: usize, chunk: usize) -> Result<(), String> {
8933        if !self.can_prefill_batched() {
8934            return self.nll_ids_from(ids, 0).map(|_| ());
8935        }
8936        self.nll_begin()?;
8937        let result: Result<(), String> = (|| {
8938            let chunk = chunk.max(1);
8939            let mut pos = 0usize;
8940            while pos < ids.len() {
8941                let end = (pos + chunk).min(ids.len());
8942                let _ = self.prefill_batch_span(PrefillIn::Ids(&ids[pos..end]), pos, None, 0, upto);
8943                self.nll_check_graph("calibration prefill", pos)?;
8944                pos = end;
8945            }
8946            Ok(())
8947        })();
8948        self.nll_end();
8949        result
8950    }
8951
8952    /// Layer-streamed calibration of one fresh window: layers `from..mid` run
8953    /// on `input` (the hidden state entering layer `from`; `None` = the
8954    /// token embeddings of `ids`) and their output is returned, then layers
8955    /// `mid..upto` run on that output for the capture hooks (their output is
8956    /// dropped). A caller that keeps the returned state per window runs each
8957    /// layer once over the whole conversion instead of re-running the stack
8958    /// below every layer. With `mid == from` the input is returned as is
8959    /// (`None` input: an empty vector).
8960    pub fn calib_window_span(
8961        &mut self,
8962        ids: &[u32],
8963        input: Option<&[f32]>,
8964        from: usize,
8965        mid: usize,
8966        upto: usize,
8967    ) -> Result<Vec<f32>, String> {
8968        if !self.can_prefill_batched() {
8969            return Err("calib_window_span: this architecture has no batched prefill".into());
8970        }
8971        self.nll_begin()?;
8972        let result: Result<Vec<f32>, String> = (|| {
8973            let h = if mid > from {
8974                let inp = match input {
8975                    Some(h) => PrefillIn::Hidden(h),
8976                    None => PrefillIn::Ids(ids),
8977                };
8978                let h = self.prefill_batch_span(inp, 0, None, from, mid);
8979                self.nll_check_graph("calibration span", 0)?;
8980                h
8981            } else {
8982                input.map(<[f32]>::to_vec).unwrap_or_default()
8983            };
8984            if upto > mid {
8985                let inp = if mid > from || input.is_some() {
8986                    PrefillIn::Hidden(&h)
8987                } else {
8988                    PrefillIn::Ids(ids)
8989                };
8990                let _ = self.prefill_batch_span(inp, 0, None, mid, upto);
8991                self.nll_check_graph("calibration span", 0)?;
8992            }
8993            Ok(h)
8994        })();
8995        self.nll_end();
8996        result
8997    }
8998
8999    /// GPTQ calibration of a Flash-Next-class MoE (`qwen4_exp`): MoE input
9000    /// rows and router logits of layers `lo..hi` for `ids` (a fresh
9001    /// sequence), per layer `[ids.len()][hidden + n_experts]`.
9002    #[cfg(feature = "gpu")]
9003    pub fn qwen4_capture(
9004        &mut self,
9005        ids: &[u32],
9006        lo: usize,
9007        hi: usize,
9008    ) -> Result<Vec<Vec<f32>>, String> {
9009        let b = self.qwen4_exp.as_mut().ok_or("not a qwen4_exp model")?;
9010        crate::qwen4_exp::capture_window(
9011            &b.0,
9012            &b.1,
9013            &b.2,
9014            &mut b.3,
9015            ids,
9016            lo,
9017            hi,
9018            &self.inv_freq,
9019            self.pool.as_deref(),
9020        )
9021    }
9022
9023    /// Expert directory triples of a `qwen4_exp` layer (routed, shared).
9024    pub fn qwen4_expert_dirs(
9025        &self,
9026        li: usize,
9027    ) -> Option<(Vec<(usize, usize, usize)>, Option<(usize, usize, usize)>)> {
9028        let b = self.qwen4_exp.as_ref()?;
9029        crate::qwen4_exp::expert_dirs(&b.1, li)
9030    }
9031
9032    /// DTG-MA calibration pass (Patent 2): run `ids` through the model
9033    /// (CPU path, per position) and return each layer's per-neuron
9034    /// activation mass Σ|silu(gate)·up| — the statistic the task-guided
9035    /// FFN mask is derived from.
9036    pub fn probe_ffn_mass(&mut self, ids: &[u32]) -> Vec<Vec<f64>> {
9037        self.clear_sequence_state();
9038        FFN_PROBE.with(|p| {
9039            *p.borrow_mut() = Some(vec![vec![0f64; self.intermediate_size]; self.num_layers]);
9040        });
9041        crate::gpu::cpu_scope(|| {
9042            for (pos, &id) in ids.iter().enumerate() {
9043                let emb = self.embed_single(id);
9044                let _ = self.forward_layers(&emb, pos, None);
9045            }
9046        });
9047        self.clear_sequence_state();
9048        FFN_PROBE
9049            .with(|p| p.borrow_mut().take())
9050            .unwrap_or_default()
9051    }
9052
9053    /// `probe_ffn_mass` over the BATCHED prefill: same accumulator, one
9054    /// sweep instead of one forward per token. What makes the statistic
9055    /// affordable on a 27B.
9056    pub fn probe_ffn_mass_batch(&mut self, ids: &[u32]) -> Result<Vec<Vec<f64>>, String> {
9057        if let Err(err) = self.nll_begin() {
9058            // A recorder can be left by a caller that was interrupted before
9059            // this request entered its scoring block.  Consume it even when
9060            // the preflight failure prevents initialization of a new one.
9061            let _ = FFN_PROBE.with(|p| p.borrow_mut().take());
9062            self.nll_end();
9063            return Err(err);
9064        }
9065        FFN_PROBE.with(|p| {
9066            *p.borrow_mut() = Some(vec![vec![0f64; self.intermediate_size]; self.num_layers]);
9067        });
9068        let result: Result<(), String> = (|| {
9069            for chunk in ids.chunks(256) {
9070                if chunk.len() < 2 {
9071                    continue;
9072                }
9073                self.nll_ids_masked(chunk, 0, None)?;
9074            }
9075            Ok(())
9076        })();
9077        self.nll_end();
9078        let probe = FFN_PROBE
9079            .with(|p| p.borrow_mut().take())
9080            .unwrap_or_default();
9081        match result {
9082            Ok(()) => Ok(probe),
9083            Err(err) => {
9084                drop(probe);
9085                Err(err)
9086            }
9087        }
9088    }
9089
9090    /// Teacher-forced PPL with a task mask active (sparse execution) —
9091    /// the quality gate for a DTG-MA-masked skill. Sequential per
9092    /// position: the batched prefill path is dense-only.
9093    pub fn ppl_ids_masked(&mut self, ids: &[u32], mask: &TaskMask) -> Result<f64, String> {
9094        self.nll_begin()?;
9095        let result: Result<f64, String> = (|| {
9096            let mut nll = 0f64;
9097            let mut cnt = 0usize;
9098            let mut hidden = vec![0f32; self.hidden_size];
9099            for (pos, &id) in ids.iter().enumerate() {
9100                if pos > 0 {
9101                    inference::rms_norm_into(
9102                        &hidden,
9103                        &self.weights.final_norm,
9104                        self.rms_eps,
9105                        self.norm_style,
9106                        &mut self.ws.n1,
9107                    );
9108                    let mut logits = self.lm_head_forward(&self.ws.n1);
9109                    let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
9110                    let sum: f64 = logits.iter().map(|&v| ((v - max) as f64).exp()).sum();
9111                    let p = ((logits[id as usize] - max) as f64).exp() / sum.max(1e-300);
9112                    nll -= p.max(1e-300).ln();
9113                    cnt += 1;
9114                    attention::recycle_buf(&mut logits);
9115                }
9116                let emb = self.embed_single(id);
9117                hidden = self.forward_layers(&emb, pos, Some(mask));
9118                self.nll_check_graph("masked serial forward", pos)?;
9119                // Consume a possible graph logits side channel before the
9120                // next row.  Masked scoring normally disables that route,
9121                // but stale channel state must never survive a request.
9122                let _ = self.graph_logits.take();
9123            }
9124            Ok((nll / cnt.max(1) as f64).exp())
9125        })();
9126        self.nll_end();
9127        result
9128    }
9129
9130    /// Teacher-forced NLL sum + scored-token count over positions
9131    /// `start..len-1`, attention EXACT. Positions below `start` still
9132    /// run — they are the context — they are just not scored, so this
9133    /// pairs with `nll_ids_o1(ids, start)` over the very same tokens.
9134    ///
9135    /// Returning (nll, cnt) rather than a ppl is what lets a windowed
9136    /// caller combine windows before the exp, so every scored token
9137    /// weighs the same regardless of how the windows are cut.
9138    /// `nll_ids_from` with a task mask held active at every position.
9139    ///
9140    /// The batched prefill path does not thread masks, so this walks the
9141    /// per-position forward — slower, but it scores the file exactly the
9142    /// way `run --task` will serve it, which is the point of the gate
9143    /// that calls it. With `None` it defers to the fast path.
9144    /// Masked scoring rides the SAME batched sweep as unmasked scoring —
9145    /// the masked-inference fast path: `prefill_batch_masked` lands the
9146    /// per-visit FFN rows on the activations inside the fused arms. The
9147    /// per-position loop below remains only as the no-batch fallback.
9148    pub fn nll_ids_masked(
9149        &mut self,
9150        ids: &[u32],
9151        start: usize,
9152        task_mask: Option<&TaskMask>,
9153    ) -> Result<(f64, usize), String> {
9154        let task_mask = self.drop_open_mask(task_mask);
9155        self.nll_ids_inner(ids, start, task_mask)
9156    }
9157
9158    pub fn nll_ids_from(&mut self, ids: &[u32], start: usize) -> Result<(f64, usize), String> {
9159        self.nll_ids_inner(ids, start, None)
9160    }
9161
9162    fn nll_ids_inner(
9163        &mut self,
9164        ids: &[u32],
9165        start: usize,
9166        task_mask: Option<&TaskMask>,
9167    ) -> Result<(f64, usize), String> {
9168        self.nll_begin()?;
9169        let result: Result<(f64, usize), String> = (|| {
9170            let mut nll = 0f64;
9171            let mut cnt = 0usize;
9172            // An unmasked quality run with the resident wgpu graph must score
9173            // the same stateful path used by generation.  The layer-major
9174            // GEMM prefill below is a valid CPU/GEMM oracle, but it seeds
9175            // neither the graph's device GDN state nor its device KV mirrors;
9176            // using it here would silently score a different execution.  Keep
9177            // masked scoring on the exact per-position path as before, and
9178            // let the serial arm below drive the graph-aware scorer.
9179            // Only native Metal has a fused graph lm_head contract.  Vulkan
9180            // and other graph backends may expose hidden state without the
9181            // optional logits side channel; preserve their established CPU
9182            // norm/head fallback instead of turning that valid route into a
9183            // hard missing-logits error.
9184            let (graph_quality, fused_head_quality) = nll_graph_policy(
9185                task_mask.is_none(),
9186                self.graph_prefill_preferred(),
9187                crate::gpu::q1_force(),
9188            );
9189            self.graph_head_required = fused_head_quality;
9190            self.graph_want_logits = fused_head_quality;
9191            #[cfg(target_os = "macos")]
9192            if graph_quality && std::env::var("CMF_METAL_BATCH_NLL").as_deref() != Ok("0") {
9193                match self.nll_batch_metal(ids, start) {
9194                    MetalBatchNllOutcome::Completed(nll, count) => {
9195                        return Ok((nll, count));
9196                    }
9197                    MetalBatchNllOutcome::Declined => {}
9198                    MetalBatchNllOutcome::Failed(err) => return Err(err),
9199                }
9200            }
9201            // CMF_NLL_SERIAL=1 scores position by position through the
9202            // decode path (the wgpu token graph where it admits the model)
9203            // — the perplexity gate of a decode kernel, which the batched
9204            // prefill arm below never runs.
9205            let force_serial = std::env::var("CMF_NLL_SERIAL").as_deref() == Ok("1");
9206            if self.can_prefill_batched() && !graph_quality && !force_serial {
9207                // prefill-GEMM: layer-major position chunks, lm_head batched
9208                // (254MB lm_head read once per chunk, not per position).
9209                // The layer chunk is large (grouping positions by MoE experts
9210                // wins with size), lm_head in sub-blocks (logit buffer
9211                // 32×vocab ≈ 32MB instead of 128×).
9212                // CMF_NLL_CHUNK: positions per prefill step (default 128).
9213                // A device scorer pays one round trip per projection per
9214                // step, so a 512-position step quarters them.
9215                let chunk_len: usize = std::env::var("CMF_NLL_CHUNK")
9216                    .ok()
9217                    .and_then(|v| v.parse().ok())
9218                    .filter(|&c: &usize| c > 0)
9219                    .unwrap_or(128);
9220                const LM_SUB: usize = 32;
9221                let n = ids.len().saturating_sub(1);
9222                let hs = self.hidden_size;
9223                let rows = self.weights.lm_head.rows();
9224                let mut pos = 0usize;
9225                let state_trace = std::env::var("CMF_STATE_TRACE").is_ok();
9226                while pos < n {
9227                    let end = (pos + chunk_len).min(n);
9228                    let bsz = end - pos;
9229                    let hb = self.prefill_rows(&ids[pos..end], pos, task_mask)?;
9230                    self.nll_check_graph("batched prefill", pos)?;
9231                    if state_trace && end % 256 == 0 {
9232                        self.trace_recurrent_state(end);
9233                    }
9234                    let mut k0 = 0usize;
9235                    while k0 < bsz {
9236                        let k1 = (k0 + LM_SUB).min(bsz);
9237                        let sb = k1 - k0;
9238                        // Sub-block entirely below the scored range: the KV
9239                        // it just built is all this pass needed from it.
9240                        if pos + k1 <= start {
9241                            k0 = k1;
9242                            continue;
9243                        }
9244                        let mut normed = vec![0.0f32; sb * hs];
9245                        for k in 0..sb {
9246                            let r = inference::rms_norm(
9247                                &hb[(k0 + k) * hs..(k0 + k + 1) * hs],
9248                                &self.weights.final_norm,
9249                                self.rms_eps,
9250                                self.norm_style,
9251                            );
9252                            normed[k * hs..(k + 1) * hs].copy_from_slice(&r);
9253                        }
9254                        let mut logits = vec![0.0f32; sb * rows];
9255                        self.weights
9256                            .lm_head
9257                            .matmat(&normed, sb, &mut logits, self.pool.as_deref());
9258                        for k in 0..sb {
9259                            if pos + k0 + k < start {
9260                                continue;
9261                            }
9262                            self.nll_check_graph("batched score row", pos + k0 + k)?;
9263                            let lg = &mut logits[k * rows..k * rows + self.vocab_size.min(rows)];
9264                            if let Some(mu) = self.logit_multiplier {
9265                                for v in lg.iter_mut() {
9266                                    *v *= mu;
9267                                }
9268                            }
9269                            // Gemma-class final-logit soft-capping: the
9270                            // decode paths apply it; scoring must too, or
9271                            // the uncapped softmax misprices every token.
9272                            if let Some(c) = self.final_softcap {
9273                                softcap_in_place(lg, c, self.pool.as_deref());
9274                            }
9275                            // Cortiq Embryo hierarchical head: same correction
9276                            // the decode path applies (lm_head_forward).
9277                            if let Some(cm) = self.head_clusters.clone() {
9278                                self.hierarchical_head_logprobs(
9279                                    &normed[k * hs..(k + 1) * hs],
9280                                    &cm,
9281                                    lg,
9282                                );
9283                            }
9284                            let lg = &logits[k * rows..k * rows + self.vocab_size.min(rows)];
9285                            let target = ids[pos + k0 + k + 1] as usize;
9286                            let max = lg.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
9287                            let lse: f64 = lg
9288                                .iter()
9289                                .map(|&v| ((v - max) as f64).exp())
9290                                .sum::<f64>()
9291                                .ln()
9292                                + max as f64;
9293                            nll += lse - lg[target] as f64;
9294                            cnt += 1;
9295                            if std::env::var("CMF_PPL_TRACE").is_ok() {
9296                                let top = lg
9297                                    .iter()
9298                                    .enumerate()
9299                                    .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
9300                                    .map(|(i, _)| i)
9301                                    .unwrap_or(0);
9302                                eprintln!(
9303                                    "BTRACE pos {} target {} nll {:.4} top {} lg_t {:.3} lg_top {:.3}",
9304                                    pos + k0 + k,
9305                                    target,
9306                                    lse - lg[target] as f64,
9307                                    top,
9308                                    lg[target],
9309                                    lg[top]
9310                                );
9311                            }
9312                        }
9313                        k0 = k1;
9314                    }
9315                    pos = end;
9316                }
9317                return Ok((nll, cnt));
9318            }
9319            for pos in 0..ids.len().saturating_sub(1) {
9320                let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, task_mask);
9321                self.nll_check_graph("serial forward", pos)?;
9322                // Architectures whose head lives inside their own stack return
9323                // the logits out of band and a zero hidden — DeepSeek-V4 folds
9324                // its hyper-connection copies between the last layer and the
9325                // norm, so it cannot hand back a vector this loop could use.
9326                // Scoring the zeros gave a perplexity of exactly the vocabulary
9327                // size, which is a uniform distribution reported as a
9328                // measurement. `generate` already reads this channel.
9329                let out_of_band = self.graph_logits.take();
9330                if self.graph_head_required && out_of_band.is_none() {
9331                    METAL_GRAPH_HEAD_MISS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9332                    return Err(format!(
9333                        "fused Metal graph head did not complete at NLL position {pos}"
9334                    ));
9335                }
9336                if pos < start {
9337                    continue;
9338                }
9339                let logits = match out_of_band {
9340                    Some(lg) => lg,
9341                    None => {
9342                        let normed = inference::rms_norm(
9343                            &hidden,
9344                            &self.weights.final_norm,
9345                            self.rms_eps,
9346                            self.norm_style,
9347                        );
9348                        // lm_head_forward applies the final-logit softcap itself
9349                        // — capping again here double-squashed gemma-class
9350                        // logits (tanh∘tanh) and reported a flattered ppl.
9351                        self.lm_head_forward(&normed)
9352                    }
9353                };
9354                let target = ids[pos + 1] as usize;
9355                let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
9356                let lse: f64 = logits
9357                    .iter()
9358                    .map(|&v| ((v - max) as f64).exp())
9359                    .sum::<f64>()
9360                    .ln()
9361                    + max as f64;
9362                let tok_nll = lse - logits[target] as f64;
9363                if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 10_000 {
9364                    let top = logits
9365                        .iter()
9366                        .enumerate()
9367                        .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
9368                        .map(|(i, _)| i)
9369                        .unwrap_or(0);
9370                    eprintln!(
9371                        "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
9372                        logits[target], logits[top]
9373                    );
9374                }
9375                nll += tok_nll;
9376                cnt += 1;
9377            }
9378            Ok((nll, cnt))
9379        })();
9380        self.nll_end();
9381        result
9382    }
9383
9384    /// Score one post-layer hidden with the same final norm/head path used by
9385    /// decode. Keeping this in one helper is important for the production
9386    /// batch scorer: its rows stop before the final norm, just like the
9387    /// per-position O(1) path below.
9388    fn nll_from_hidden(&mut self, hidden: &[f32], target: u32, pos: usize) -> f64 {
9389        let normed = inference::rms_norm(
9390            hidden,
9391            &self.weights.final_norm,
9392            self.rms_eps,
9393            self.norm_style,
9394        );
9395        // lm_head_forward applies the final-logit softcap itself — capping
9396        // again here double-squashed gemma-class logits in earlier scorers.
9397        let mut logits = self.lm_head_forward(&normed);
9398        let target = target as usize;
9399        let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
9400        let lse: f64 = logits
9401            .iter()
9402            .map(|&v| ((v - max) as f64).exp())
9403            .sum::<f64>()
9404            .ln()
9405            + max as f64;
9406        let tok_nll = lse - logits[target] as f64;
9407        if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 10_000 {
9408            let top = logits
9409                .iter()
9410                .enumerate()
9411                .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
9412                .map(|(i, _)| i)
9413                .unwrap_or(0);
9414            eprintln!(
9415                "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
9416                logits[target], logits[top]
9417            );
9418        }
9419        attention::recycle_buf(&mut logits);
9420        tok_nll
9421    }
9422
9423    /// `CMF_STATE_TRACE`: per-layer magnitude of the recurrent record at
9424    /// position `pos` — the whole `linear_state` (vmf: S then the conv
9425    /// ring; GDN: conv ring then S), its recurrent S part alone, the
9426    /// bounded ring, and the last per-position KV row count.  The tool
9427    /// that separated the ~4k perplexity cliff of the 500-step exports
9428    /// (a state that keeps climbing past the trained window) from a
9429    /// runtime boundary; one line per layer, `STATE pos=… layer=…`.
9430    fn trace_recurrent_state(&self, pos: usize) {
9431        let stats = |v: &[f32]| -> (f64, f64) {
9432            if v.is_empty() {
9433                return (0.0, 0.0);
9434            }
9435            let (mut ss, mut mx) = (0f64, 0f64);
9436            for &x in v {
9437                ss += (x as f64) * (x as f64);
9438                mx = mx.max((x as f64).abs());
9439            }
9440            ((ss / v.len() as f64).sqrt(), mx)
9441        };
9442        for (li, l) in self.kv_cache.layers.iter().enumerate() {
9443            let lw = &self.weights.layers[self.phys_layer(li)];
9444            let (kind, s_len) = match &lw.attn {
9445                AttnKind::Linear(_) => ("vmf", self.vmf_cfg.map(|c| c.state_len()).unwrap_or(0)),
9446                AttnKind::LinearGdn(_) => ("gdn", self.gdn_cfg.map(|c| c.state_len()).unwrap_or(0)),
9447                AttnKind::Bounded(_) => ("bounded", 0),
9448                AttnKind::Full { .. } => ("full", 0),
9449                _ => ("other", 0),
9450            };
9451            let (rms, max) = stats(&l.linear_state);
9452            let s_part = if kind == "vmf" {
9453                &l.linear_state[..s_len.min(l.linear_state.len())]
9454            } else if kind == "gdn" {
9455                let ring = l
9456                    .linear_state
9457                    .len()
9458                    .saturating_sub(s_len)
9459                    .min(l.linear_state.len());
9460                &l.linear_state[ring..]
9461            } else {
9462                &l.linear_state[..0]
9463            };
9464            let (s_rms, s_max) = stats(s_part);
9465            let (ring_rms, ring_len) = match &l.bounded {
9466                Some(b) => (stats(&b.ring_k).0, b.ring_k.len()),
9467                None => (0.0, 0),
9468            };
9469            eprintln!(
9470                "STATE pos={pos} layer={li} kind={kind} state_len={} rms={rms:.5} max={max:.4} \
9471                 S_rms={s_rms:.5} S_max={s_max:.4} ring_k_rms={ring_rms:.5} ring_len={ring_len} kv_rows={}",
9472                l.linear_state.len(),
9473                l.seq_len
9474            );
9475        }
9476    }
9477
9478    /// Teacher-forced NLL of the CONVERTED model: the O(1) Nyström path
9479    /// is ACTIVE over the scored positions. Returns `Ok((nll sum, scored
9480    /// count))` over `prefill..len-1` and surfaces a post-mutation batch
9481    /// failure instead of returning a partial score.
9482    ///
9483    /// Runtime discipline, deliberately NOT the matrix probe's: the
9484    /// requested prefix plus any required deferred lead-in run the exact
9485    /// prompt pass — that pass is what freezes the landmarks and M — and
9486    /// every post-seal scored position goes through `NystromState::step()`,
9487    /// the same code decode runs.
9488    /// So the landmarks are PREFILL-frozen (what ships), not
9489    /// full-sequence oracles (what the published probe measured). When the
9490    /// requested prefix is shorter than the bounded transition, rows in the
9491    /// exact lead-in are still scored so the shifted target range is stable.
9492    ///
9493    /// Pair with `nll_ids_from(ids, prefill)` for the exact baseline
9494    /// over the identical token set — that ratio is the honest one.
9495    pub fn nll_ids_o1(&mut self, ids: &[u32], prefill: usize) -> Result<(f64, usize), String> {
9496        // This scorer consumes host hiddens, so never request the optional
9497        // token-graph lm_head side channel. `nll_begin` also consumes a
9498        // prior graph failure and clears only the cancel bit that failure
9499        // raised, leaving a caller-owned cancellation observable.
9500        self.nll_begin()?;
9501        let requested_prefix = (prefill > 0).then_some(prefill);
9502        self.o1_begin_with_prefix(requested_prefix);
9503        let n = ids.len().saturating_sub(1);
9504        let requested_start = prefill.min(n);
9505        // The exact prefix must reach the deferred boundary before a
9506        // collecting layer can convert. Rows between the requested start and
9507        // that boundary remain part of the public NLL range and are scored
9508        // from the same hidden pass below.
9509        let exact_end = if self.o1_active() {
9510            match requested_prefix {
9511                Some(requested) => self.o1_effective_boundary(requested),
9512                None => self
9513                    .o1_cfg
9514                    .as_ref()
9515                    .and_then(|c| crate::nystrom::o1_deferred_boundary(c.w, c.sink)),
9516            }
9517            .unwrap_or(requested_start)
9518            .min(n)
9519        } else {
9520            requested_start
9521        };
9522        let mut nll = 0f64;
9523        let mut cnt = 0usize;
9524
9525        // Exact prompt pass over ids[..exact_end]: the seal consumes its
9526        // q/k/v. Rows at or after requested_start are scored here when the
9527        // bounded lead-in is longer than the caller's requested prefix.
9528        let mut pos = 0usize;
9529        if self.can_prefill_batched() {
9530            const CHUNK: usize = 128;
9531            while pos < exact_end {
9532                let end = (pos + CHUNK).min(exact_end);
9533                let hiddens = self.prefill_batch(&ids[pos..end], pos);
9534                if self
9535                    .graph_failed
9536                    .swap(false, std::sync::atomic::Ordering::Relaxed)
9537                {
9538                    self.cancel
9539                        .store(false, std::sync::atomic::Ordering::Relaxed);
9540                    self.nll_end();
9541                    return Err("GPU graph failed during O(1) NLL prefix".into());
9542                }
9543                for row in 0..end - pos {
9544                    let score_pos = pos + row;
9545                    if score_pos >= requested_start && score_pos < n {
9546                        nll += self.nll_from_hidden(
9547                            &hiddens[row * self.hidden_size..(row + 1) * self.hidden_size],
9548                            ids[score_pos + 1],
9549                            score_pos,
9550                        );
9551                        cnt += 1;
9552                    }
9553                }
9554                pos = end;
9555            }
9556        } else {
9557            while pos < exact_end {
9558                let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
9559                if self
9560                    .graph_failed
9561                    .swap(false, std::sync::atomic::Ordering::Relaxed)
9562                {
9563                    self.cancel
9564                        .store(false, std::sync::atomic::Ordering::Relaxed);
9565                    self.nll_end();
9566                    return Err("GPU graph failed during O(1) NLL prefix".into());
9567                }
9568                if pos >= requested_start && pos < n {
9569                    nll += self.nll_from_hidden(&hidden, ids[pos + 1], pos);
9570                    cnt += 1;
9571                }
9572                pos += 1;
9573            }
9574        }
9575        self.o1_seal_checked().map_err(|err| {
9576            self.nll_end();
9577            err
9578        })?;
9579
9580        // Reuse the production whole-token batch graph for the post-seal
9581        // suffix when the caller explicitly enabled both routes. This is a
9582        // teacher-forced scorer, so every row is ids[pos] and its target is
9583        // ids[pos + 1]; no speculative tail or rollback state is involved.
9584        // A first Declined is safe to handle with the established serial O(1)
9585        // path. Once a chunk completes, however, the device recurrent state
9586        // owns the sequence and a later decline must be terminal rather than
9587        // falling back to stale CPU state.
9588        let batch_k = std::env::var("CMF_BATCH_K")
9589            .ok()
9590            .and_then(|v| v.parse::<usize>().ok())
9591            .unwrap_or(0);
9592        let batch_admitted = batch_k > 0
9593            && self.can_prefill_batched()
9594            && self.o1_active()
9595            && std::env::var("CMF_O1_GPU").as_deref() == Ok("1")
9596            && (0..self.num_layers).all(|li| {
9597                let cache = &self.kv_cache.layers[self.phys_layer(li)];
9598                cache.o1.is_none() || cache.o1_views().is_some()
9599            });
9600        if std::env::var("CMF_GRAPH_PROF").is_ok() {
9601            eprintln!(
9602                "nll-batch: phase=post-seal admission={} requested_k={} scored_rows={}",
9603                batch_admitted,
9604                batch_k,
9605                n.saturating_sub(exact_end),
9606            );
9607        }
9608        let mut batch_completed = false;
9609        if batch_admitted && exact_end < n {
9610            let hs = self.hidden_size;
9611            let mut batch_pos = exact_end;
9612            while batch_pos < n {
9613                let end = (batch_pos + batch_k).min(n);
9614                let bk = end - batch_pos;
9615                let mut hiddens = vec![0.0f32; bk * hs];
9616                for (row, &id) in ids[batch_pos..end].iter().enumerate() {
9617                    hiddens[row * hs..(row + 1) * hs].copy_from_slice(&self.embed_single(id));
9618                }
9619                let positions: Vec<usize> = (batch_pos..end).collect();
9620                let t_batch = std::time::Instant::now();
9621                let outcome = self.try_batch_graph_wgpu(&mut hiddens, &positions, bk, None);
9622                if std::env::var("CMF_GRAPH_PROF").is_ok() {
9623                    let ms = t_batch.elapsed().as_secs_f64() * 1000.0;
9624                    eprintln!(
9625                        "nll-batch: phase=post-seal mode=o1 k={bk} pos={}..{} outcome={outcome:?} {ms:.1} ms ({:.1} tok/s)",
9626                        batch_pos,
9627                        end.saturating_sub(1),
9628                        bk as f64 / (ms / 1000.0),
9629                    );
9630                }
9631                if let Err(err) = self.nll_check_graph("batch graph", batch_pos) {
9632                    self.nll_end();
9633                    return Err(err);
9634                }
9635                match outcome {
9636                    crate::gpu::BatchGraphOutcome::Completed => {
9637                        batch_completed = true;
9638                        for row in 0..bk {
9639                            nll += self.nll_from_hidden(
9640                                &hiddens[row * hs..(row + 1) * hs],
9641                                ids[batch_pos + row + 1],
9642                                batch_pos + row,
9643                            );
9644                            cnt += 1;
9645                        }
9646                        batch_pos = end;
9647                    }
9648                    crate::gpu::BatchGraphOutcome::Declined => {
9649                        if batch_completed {
9650                            self.nll_end();
9651                            return Err(format!(
9652                                "O(1) NLL batch declined after completed chunk at position {batch_pos}"
9653                            ));
9654                        }
9655                        break;
9656                    }
9657                    crate::gpu::BatchGraphOutcome::Failed => {
9658                        self.nll_end();
9659                        return Err(format!(
9660                            "O(1) NLL batch graph failed after admission at position {batch_pos}"
9661                        ));
9662                    }
9663                }
9664            }
9665            if batch_completed && cnt == n.saturating_sub(requested_start) {
9666                self.nll_end();
9667                return Ok((nll, cnt));
9668            }
9669        }
9670
9671        // Serial O(1) fallback/reference. It is intentionally retained when
9672        // batch admission declines before mutation; callers must label this
9673        // CMF_BATCH_K=0/per-position path separately from the production
9674        // whole-token batch route.
9675        for pos in exact_end..n {
9676            let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
9677            if self
9678                .graph_failed
9679                .swap(false, std::sync::atomic::Ordering::Relaxed)
9680            {
9681                self.cancel
9682                    .store(false, std::sync::atomic::Ordering::Relaxed);
9683                self.nll_end();
9684                return Err(format!(
9685                    "GPU graph failed during O(1) NLL serial scoring at position {pos}"
9686                ));
9687            }
9688            nll += self.nll_from_hidden(&hidden, ids[pos + 1], pos);
9689            cnt += 1;
9690        }
9691        self.nll_end();
9692        Ok((nll, cnt))
9693    }
9694
9695    /// Teacher-forced calibration data (B1): for each position, whether the
9696    /// argmax equals the actual next token, and the top-1 softmax prob
9697    /// (top-1 probability) under EACH temperature in `temps` — all from ONE forward
9698    /// pass (argmax/correctness are temperature-invariant; only p_max
9699    /// reshapes). Feeds `cortiq calibrate` (reliability/ECE + temperature
9700    /// fit): is the model's confidence a true property, or does it need a
9701    /// measured scaling?
9702    pub fn calib_ids(&mut self, ids: &[u32], temps: &[f32]) -> (Vec<bool>, Vec<Vec<f32>>) {
9703        self.clear_sequence_state();
9704        let n = ids.len().saturating_sub(1);
9705        let mut correct = Vec::with_capacity(n);
9706        let mut pmax = Vec::with_capacity(n);
9707        for pos in 0..n {
9708            let emb = self.embed_single(ids[pos]);
9709            let hidden = self.forward_layers(&emb, pos, None);
9710            let logits = if let Some(logits) = self.graph_logits.take() {
9711                logits
9712            } else {
9713                let normed = inference::rms_norm(
9714                    &hidden,
9715                    &self.weights.final_norm,
9716                    self.rms_eps,
9717                    self.norm_style,
9718                );
9719                // lm_head_forward applies the final-logit softcap itself —
9720                // capping again here double-squashed gemma-class logits
9721                // (tanh∘tanh) and reported a flattered ppl.
9722                self.lm_head_forward(&normed)
9723            };
9724            let target = ids[pos + 1] as usize;
9725            let (mut amax, mut mval) = (0usize, f32::NEG_INFINITY);
9726            for (i, &v) in logits.iter().enumerate() {
9727                if v > mval {
9728                    mval = v;
9729                    amax = i;
9730                }
9731            }
9732            correct.push(amax == target);
9733            let row: Vec<f32> = temps
9734                .iter()
9735                .map(|&t| {
9736                    let tt = t.max(1e-3);
9737                    let s: f32 = logits.iter().map(|&v| ((v - mval) / tt).exp()).sum();
9738                    1.0 / s.max(1e-12) // numerator at the max is exp(0)=1
9739                })
9740                .collect();
9741            pmax.push(row);
9742        }
9743        self.clear_sequence_state();
9744        (correct, pmax)
9745    }
9746
9747    /// Teacher-forced PPL with the dynamic router driving per-window
9748    /// skill switches (VMF experiment №2 measurement). Sequential (φ
9749    /// must update per token), returns (ppl, switch_count). The router
9750    /// must be enabled (`enable_dynamic_routing`); else this equals
9751    /// plain `ppl_ids`. The active skill when scoring token t shapes the
9752    /// logits for t+1 — on-policy over the held-out text itself.
9753    pub fn ppl_ids_dynamic(&mut self, ids: &[u32]) -> Result<(f64, usize), String> {
9754        if self.dyn_router.is_none() {
9755            return Ok((self.ppl_ids(ids)?, 0));
9756        }
9757        self.nll_begin()?;
9758        let saved_active = self.dyn_active;
9759        let mut router = self
9760            .dyn_router
9761            .take()
9762            .ok_or_else(|| "dynamic router disappeared before PPL scoring".to_string())?;
9763        router.reset();
9764        self.dyn_phi_seen = 0;
9765        let _ = self.set_active_skill(None);
9766
9767        let result: Result<(f64, usize), String> = (|| {
9768            let mut nll = 0f64;
9769            let mut cnt = 0usize;
9770            for pos in 0..ids.len().saturating_sub(1) {
9771                let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
9772                self.nll_check_graph("dynamic serial forward", pos)?;
9773                let out_of_band = self.graph_logits.take();
9774                let mut logits = match out_of_band {
9775                    Some(lg) => lg,
9776                    None => {
9777                        let normed = inference::rms_norm(
9778                            &hidden,
9779                            &self.weights.final_norm,
9780                            self.rms_eps,
9781                            self.norm_style,
9782                        );
9783                        // lm_head_forward applies the final-logit softcap itself —
9784                        // capping again here double-squashed gemma-class logits
9785                        // and reported a flattered ppl.
9786                        self.lm_head_forward(&normed)
9787                    }
9788                };
9789                let target = ids[pos + 1] as usize;
9790                let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
9791                let lse: f64 = logits
9792                    .iter()
9793                    .map(|&v| ((v - max) as f64).exp())
9794                    .sum::<f64>()
9795                    .ln()
9796                    + max as f64;
9797                let tok_nll = lse - logits[target] as f64;
9798                if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 10_000 {
9799                    let top = logits
9800                        .iter()
9801                        .enumerate()
9802                        .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
9803                        .map(|(i, _)| i)
9804                        .unwrap_or(0);
9805                    eprintln!(
9806                        "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
9807                        logits[target], logits[top]
9808                    );
9809                }
9810                nll += tok_nll;
9811                cnt += 1;
9812                attention::recycle_buf(&mut logits);
9813                // Route on the evolving phi (drives the NEXT token's skill).
9814                let phi = self.dyn_phi_ema.clone();
9815                if let Some(new_active) = router.step(&phi, pos) {
9816                    let _ = self.set_active_skill(new_active);
9817                }
9818            }
9819            Ok(((nll / cnt.max(1) as f64).exp(), router.switches.len()))
9820        })();
9821
9822        // Restore the detached router and the active overlay on both success
9823        // and failure. The scoring state is cleared independently below.
9824        let _ = self.set_active_skill(saved_active);
9825        self.dyn_router = Some(router);
9826        self.nll_end();
9827        result
9828    }
9829
9830    /// Routing probe φ (spec §9): mean-pooled hidden after `layer`.
9831    pub fn probe_phi(&mut self, ids: &[u32], layer: usize) -> Vec<f32> {
9832        self.clear_sequence_state();
9833        let mut acc = vec![0f32; self.hidden_size];
9834        for (pos, &id) in ids.iter().enumerate() {
9835            let h = self.forward_layers_upto(&self.embed_single(id), pos, None, Some(layer));
9836            for (a, v) in acc.iter_mut().zip(&h) {
9837                *a += v;
9838            }
9839        }
9840        let n = ids.len().max(1) as f32;
9841        for a in acc.iter_mut() {
9842            *a /= n;
9843        }
9844        self.clear_sequence_state();
9845        acc
9846    }
9847
9848    /// Router-v2 φ probe (spec §9.4, `phi.pool = "span_mean"`): the hidden
9849    /// AFTER `layer` — the same per-position walk and the same quantity as
9850    /// [`Self::probe_phi`] — averaged over the positions in `span` only
9851    /// (the user text between the template's prefix and suffix ids), NOT
9852    /// unit-normalized (the decision normalizes). The walk stops at
9853    /// `span.end`: causality makes the later positions irrelevant, so the
9854    /// result is bit-identical to probing `ids[..span.end]`. An empty span
9855    /// gives the zero vector, which the decision treats as degenerate.
9856    ///
9857    /// Every sequence state is reset before and after — the host KV/ring/
9858    /// recurrent state, the reuse keys (`kv_history`, `kv_prefix`) and the
9859    /// device graph's sequence — so run it on a pipeline that does not
9860    /// also serve a conversation (its prefix reuse would be lost).
9861    pub fn probe_phi_span(
9862        &mut self,
9863        ids: &[u32],
9864        layer: usize,
9865        span: std::ops::Range<usize>,
9866    ) -> Vec<f32> {
9867        #[cfg(target_os = "macos")]
9868        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
9869        let end = span.end.min(ids.len());
9870        let start = span.start.min(end);
9871        let reset = |p: &mut Self| p.clear_sequence_state();
9872        reset(self);
9873        let mut acc = vec![0f32; self.hidden_size];
9874        for (pos, &id) in ids[..end].iter().enumerate() {
9875            let h = self.forward_layers_upto(&self.embed_single(id), pos, None, Some(layer));
9876            if pos >= start {
9877                for (a, v) in acc.iter_mut().zip(&h) {
9878                    *a += v;
9879                }
9880            }
9881        }
9882        let n = end - start;
9883        if n > 0 {
9884            let n = n as f32;
9885            for a in acc.iter_mut() {
9886                *a /= n;
9887            }
9888        }
9889        reset(self);
9890        acc
9891    }
9892
9893    /// One decode step of the current sequence: forward `token` at
9894    /// `position` (the cache holds positions `[0, position)`, e.g. after
9895    /// [`Self::forward_ids`]) and return the next-token logits — the same
9896    /// forward and head the generation loop runs (resident-graph logits
9897    /// when the graph ran, final norm + lm_head otherwise). The logit-dump
9898    /// tools drive greedy decoding with it so every position is observable.
9899    pub fn decode_step_logits(&mut self, token: u32, position: usize) -> Vec<f32> {
9900        #[cfg(target_os = "macos")]
9901        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
9902        self.graph_logits = None;
9903        let hidden = self.forward_layers(&self.embed_single(token), position, None);
9904        if let Some(logits) = self.graph_logits.take() {
9905            return logits;
9906        }
9907        inference::rms_norm_into(
9908            &hidden,
9909            &self.weights.final_norm,
9910            self.rms_eps,
9911            self.norm_style,
9912            &mut self.ws.n1,
9913        );
9914        self.lm_head_forward(&self.ws.n1)
9915    }
9916
9917    /// Layer-major batched prefill (prefill-GEMM): full-attention —
9918    /// per-position with the existing operators (KV grows naturally,
9919    /// causality preserved), GDN projections / FFN / MoE — batched
9920    /// (a weight row is read from DRAM once per chunk, not per
9921    /// position). Returns the hidden of all positions [b × hidden].
9922    fn prefill_batch(&mut self, ids: &[u32], start_pos: usize) -> Vec<f32> {
9923        self.prefill_batch_masked(ids, start_pos, None)
9924    }
9925
9926    /// `prefill_batch` with a task mask honored on the dense-FFN panels
9927    /// (the masked-inference fast path: full fused compute, mask lands on
9928    /// the activations). The whole-chunk GPU graph is skipped for masked
9929    /// layers by the callers' arms; the per-GEMM device paths stay in
9930    /// play because the zeroing happens on the host between them.
9931    fn prefill_batch_masked(
9932        &mut self,
9933        ids: &[u32],
9934        start_pos: usize,
9935        task_mask: Option<&TaskMask>,
9936    ) -> Vec<f32> {
9937        self.prefill_batch_span(PrefillIn::Ids(ids), start_pos, task_mask, 0, usize::MAX)
9938    }
9939
9940    /// One prompt chunk through the whole stack, post-stack rows out (no
9941    /// final norm) — the ingest generation uses, shared by scoring and
9942    /// `forward_ids` so they measure the same execution: the batched wgpu
9943    /// graph's device prefix plus the host's batched walk for the rest when
9944    /// `batch_prefix_prefill` holds and the graph admits the chunk, else
9945    /// the host's chunked prefill. Err only when a graph that had mutated
9946    /// device state failed.
9947    fn prefill_rows(
9948        &mut self,
9949        ids: &[u32],
9950        pos: usize,
9951        task_mask: Option<&TaskMask>,
9952    ) -> Result<Vec<f32>, String> {
9953        self.prefill_input_rows(PrefillIn::Ids(ids), pos, task_mask)
9954    }
9955
9956    fn prefill_input_rows(
9957        &mut self,
9958        input: PrefillIn<'_>,
9959        pos: usize,
9960        task_mask: Option<&TaskMask>,
9961    ) -> Result<Vec<f32>, String> {
9962        self.mimo_moe_prepare();
9963        let hs = self.hidden_size;
9964        let bk = match input {
9965            PrefillIn::Ids(ids) => ids.len(),
9966            PrefillIn::Hidden(rows) => rows.len() / hs,
9967        };
9968        #[cfg(not(target_os = "macos"))]
9969        if task_mask.is_none()
9970            && !self.o1_active()
9971            && bk > 1
9972            && (self.batch_prefix_prefill()
9973                || (self.verify_exact_moe
9974                    && crate::gpu::enabled_here()
9975                    && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)))
9976        {
9977            let mut hiddens = match input {
9978                PrefillIn::Hidden(rows) => rows.to_vec(),
9979                PrefillIn::Ids(ids) => ids.iter().flat_map(|&id| self.embed_single(id)).collect(),
9980            };
9981            let positions: Vec<usize> = (pos..pos + bk).collect();
9982            let mut run = 0usize;
9983            match self.try_batch_graph_wgpu_prefix(
9984                &mut hiddens,
9985                &positions,
9986                bk,
9987                None,
9988                Some(&mut run),
9989            ) {
9990                crate::gpu::BatchGraphOutcome::Completed => {
9991                    let out = if run < self.num_layers {
9992                        self.prefill_batch_span(
9993                            PrefillIn::Hidden(&hiddens),
9994                            pos,
9995                            None,
9996                            run,
9997                            self.num_layers,
9998                        )
9999                    } else {
10000                        hiddens
10001                    };
10002                    return if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
10003                        Err("MiMo attention graph failed after admission".into())
10004                    } else {
10005                        Ok(out)
10006                    };
10007                }
10008                crate::gpu::BatchGraphOutcome::Failed => {
10009                    return Err("batched prefix prefill failed after admission".into());
10010                }
10011                crate::gpu::BatchGraphOutcome::Declined => {
10012                    // Rows an earlier chunk left on the device only.
10013                    #[cfg(feature = "gpu")]
10014                    self.pull_lagging_host_kv(0, self.num_layers, pos);
10015                }
10016            }
10017        }
10018        let out = self.prefill_batch_span(input, pos, task_mask, 0, usize::MAX);
10019        if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
10020            Err("batch tail graph failed after admission".into())
10021        } else {
10022            Ok(out)
10023        }
10024    }
10025
10026    /// The layer-major batched walk over a layer span [from..upto_excl):
10027    /// the whole prefill machinery (chunk graph, batched attends, GEMM
10028    /// panels) for a PARTIAL stack — the network split's prefill rides
10029    /// the same canon as the local one. Input is token ids (embeds
10030    /// itself, coordinator side) or ready boundary hiddens (worker side).
10031    fn prefill_batch_span(
10032        &mut self,
10033        input: PrefillIn<'_>,
10034        start_pos: usize,
10035        task_mask: Option<&TaskMask>,
10036        from: usize,
10037        upto_excl: usize,
10038    ) -> Vec<f32> {
10039        let hs = self.hidden_size;
10040        let b = match input {
10041            PrefillIn::Ids(ids) => ids.len(),
10042            PrefillIn::Hidden(hb) => hb.len() / hs,
10043        };
10044        let upto_excl = upto_excl.min(self.num_layers);
10045        // The CPU embed is deferred: when the chunk graph takes the run
10046        // from layer 0 it gathers the embeddings on the device instead.
10047        // A hidden input is ready by definition.
10048        let mut h: Vec<f32>;
10049        let mut h_ready;
10050        match input {
10051            PrefillIn::Ids(_) => {
10052                h = vec![0.0; b * hs];
10053                h_ready = false;
10054            }
10055            PrefillIn::Hidden(hb) => {
10056                h = hb.to_vec();
10057                h_ready = true;
10058            }
10059        }
10060        let fill_h = |h: &mut Vec<f32>, me: &Self| {
10061            if let PrefillIn::Ids(ids) = input {
10062                for (bi, &id) in ids.iter().enumerate() {
10063                    let e = me.embed_single(id);
10064                    h[bi * hs..(bi + 1) * hs].copy_from_slice(&e);
10065                }
10066                if let Ok(tp) = std::env::var("CMF_TRACE_POS") {
10067                    if let Ok(t) = tp.parse::<usize>() {
10068                        if t >= start_pos && t < start_pos + ids.len() {
10069                            let bi = t - start_pos;
10070                            let row = &h[bi * hs..(bi + 1) * hs];
10071                            let n: f32 = row.iter().map(|x| x * x).sum::<f32>().sqrt();
10072                            eprintln!(
10073                                "BATCH pos {t} embed: id {} |h| = {n:.6} h0 {:.6} h1 {:.6} | b={} start={start_pos} ids[..8]={:?}",
10074                                ids[bi],
10075                                row[0],
10076                                row[1],
10077                                ids.len(),
10078                                &ids[..ids.len().min(8)]
10079                            );
10080                        }
10081                    }
10082                }
10083            }
10084        };
10085        let (_nkv, _hd, _rd, eps) = (
10086            self.num_kv_heads,
10087            self.head_dim,
10088            self.rotary_dim,
10089            self.rms_eps,
10090        );
10091        let pool = self.pool.clone();
10092        let norm_style = self.norm_style;
10093        self.mimo_moe_prepare();
10094        let automatic_gpu_prefix = self.automatic_gpu_prefix();
10095
10096        #[cfg(target_os = "macos")]
10097        let mut chunk_skip_until = 0usize;
10098        for li in from..upto_excl {
10099            let _capacity_tail = automatic_gpu_prefix
10100                .filter(|&prefix| {
10101                    li >= prefix && !(self.verify_exact_moe && self.mimo_moe.is_dynamic(li, false))
10102                })
10103                .map(|_| crate::gpu::enter_cpu_scope());
10104            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU
10105            // Spark-X2.5: the layer's int8 matrix-unit GEMMs take the
10106            // `zi_mm` tile, bit-identical to the 64x64 kernel and about
10107            // three times its rate (`gpu_wgpu::zi_gemm_route`).
10108            #[cfg(feature = "gpu")]
10109            let _fast_gemm = self
10110                .proj_gate_sigmoid
10111                .then(crate::gpu::enter_prefill_fast_gemm);
10112            // GPU chunk graph (default-on under CMF_GPU=1): a run of
10113            // consecutive eligible layers for the whole chunk in ONE
10114            // Metal submission — norm, QKV, RoPE with fused mirror
10115            // append, causal attend, O, FFN, hidden device-resident
10116            // across the run. Any refusal falls through to the CPU path.
10117            #[cfg(target_os = "macos")]
10118            if task_mask.is_none() {
10119                if li < chunk_skip_until {
10120                    continue;
10121                }
10122                // Device-side embedding needs a q8_row embedding matrix;
10123                // with any other layout the CPU fills `h` first and the
10124                // graph starts from a ready hidden (refusing the whole
10125                // run over the embedding alone kept q4t models — the
10126                // whole Nanbeige/Bonsai class — on the CPU prefill).
10127                if !h_ready && li == 0 && self.weights.embed_tokens.q8_row_parts().is_none() {
10128                    fill_h(&mut h, self);
10129                    h_ready = true;
10130                }
10131                let ids_for_embed = match input {
10132                    PrefillIn::Ids(ids) => (!h_ready && li == 0).then_some(ids),
10133                    PrefillIn::Hidden(_) => None,
10134                };
10135                let end = self.chunk_run_gpu(li, &mut h, b, start_pos, ids_for_embed, upto_excl);
10136                if end > li {
10137                    h_ready = true;
10138                    chunk_skip_until = end;
10139                    // Looped Transformer: the graph stopped at a loop
10140                    // boundary — apply final norm before the next iteration.
10141                    if self.is_loop_end(end - 1) && end < self.num_layers {
10142                        for bi in 0..b {
10143                            let normed = inference::rms_norm(
10144                                &h[bi * hs..(bi + 1) * hs],
10145                                &self.weights.final_norm,
10146                                eps,
10147                                norm_style,
10148                            );
10149                            h[bi * hs..(bi + 1) * hs].copy_from_slice(&normed);
10150                        }
10151                    }
10152                    continue;
10153                }
10154            }
10155            if !h_ready {
10156                fill_h(&mut h, self);
10157                h_ready = true;
10158            }
10159            if task_mask.is_none() && self.verify_exact_moe {
10160                let positions: Vec<_> = (start_pos..start_pos + b).collect();
10161                match self.mimo_graph_layer_rows(li, &mut h, &positions) {
10162                    crate::gpu::BatchGraphOutcome::Completed => continue,
10163                    crate::gpu::BatchGraphOutcome::Failed => return h,
10164                    crate::gpu::BatchGraphOutcome::Declined => {}
10165                }
10166            }
10167            #[cfg(feature = "gpu")]
10168            self.pull_lagging_host_kv(li, li + 1, start_pos);
10169            let lw = &self.weights.layers[self.phys_layer(li)];
10170            let t_attn = std::time::Instant::now();
10171            // ── attention ──
10172            match &lw.attn {
10173                AttnKind::Kda(w) => {
10174                    // Projections batched, recurrence sequential.
10175                    let cfg = self.kda_cfg.expect("kda layer without kda_cfg");
10176                    let mut normed = vec![0.0f32; b * hs];
10177                    for bi in 0..b {
10178                        inference::rms_norm_into(
10179                            &h[bi * hs..(bi + 1) * hs],
10180                            &lw.input_norm,
10181                            eps,
10182                            norm_style,
10183                            &mut normed[bi * hs..(bi + 1) * hs],
10184                        );
10185                    }
10186                    let attn = crate::linear_core::kda_forward_batch(
10187                        &normed,
10188                        b,
10189                        w,
10190                        &cfg,
10191                        &mut self.kv_cache.layers[li].linear_state,
10192                        pool.as_deref(),
10193                    );
10194                    for (dst, &a) in h.iter_mut().zip(&attn) {
10195                        *dst += a;
10196                    }
10197                }
10198                AttnKind::LinearGdn(w) => {
10199                    // Projections batched, recurrence sequential.
10200                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
10201                    let mut normed = vec![0.0f32; b * hs];
10202                    for bi in 0..b {
10203                        let r = inference::rms_norm(
10204                            &h[bi * hs..(bi + 1) * hs],
10205                            &lw.input_norm,
10206                            eps,
10207                            norm_style,
10208                        );
10209                        normed[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
10210                    }
10211                    let attn = crate::linear_core::gdn_forward_batch(
10212                        &normed,
10213                        b,
10214                        w,
10215                        &cfg,
10216                        &mut self.kv_cache.layers[li].linear_state,
10217                        pool.as_deref(),
10218                    );
10219                    for (dst, &a) in h.iter_mut().zip(&attn) {
10220                        *dst += a;
10221                    }
10222                }
10223                AttnKind::ShortConv(w) => {
10224                    // Projections batched over the chunk; the conv walks the
10225                    // contiguous positions in order (same ring as decode).
10226                    let cfg = self
10227                        .short_conv_cfg
10228                        .expect("short-conv layer without short_conv_cfg");
10229                    let mut normed = vec![0.0f32; b * hs];
10230                    for bi in 0..b {
10231                        inference::rms_norm_into(
10232                            &h[bi * hs..(bi + 1) * hs],
10233                            &lw.input_norm,
10234                            eps,
10235                            norm_style,
10236                            &mut normed[bi * hs..(bi + 1) * hs],
10237                        );
10238                    }
10239                    let attn = short_conv_forward_batch(
10240                        &normed,
10241                        b,
10242                        w,
10243                        &cfg,
10244                        &mut self.kv_cache.layers[li].linear_state,
10245                        pool.as_deref(),
10246                    );
10247                    for (dst, &a) in h.iter_mut().zip(&attn) {
10248                        *dst += a;
10249                    }
10250                }
10251                AttnKind::Mla(w) => {
10252                    // Per-position prefill (correctness first; latent
10253                    // batching is a later optimization).
10254                    let inv_freq_l = self.layer_inv_freq(li);
10255                    let rs = self.layer_rope_scale(li);
10256                    let mut normed = vec![0.0f32; hs];
10257                    for bi in 0..b {
10258                        inference::rms_norm_into(
10259                            &h[bi * hs..(bi + 1) * hs],
10260                            &lw.input_norm,
10261                            eps,
10262                            norm_style,
10263                            &mut normed,
10264                        );
10265                        let ao = mla_attention(
10266                            w,
10267                            &normed,
10268                            &mut self.kv_cache.layers[li],
10269                            start_pos + bi,
10270                            &inv_freq_l,
10271                            rs,
10272                            eps,
10273                            pool.as_deref(),
10274                        );
10275                        for (dst, &a) in h[bi * hs..(bi + 1) * hs].iter_mut().zip(&ao) {
10276                            *dst += a;
10277                        }
10278                    }
10279                }
10280                AttnKind::Full {
10281                    wq,
10282                    wk,
10283                    wv,
10284                    wo,
10285                    q_norm,
10286                    k_norm,
10287                    output_gate,
10288                    softplus_gate,
10289                    bias,
10290                } => {
10291                    // Chunk-GEMM QKV/O; per-position causal attention
10292                    // inside (roadmap §3 P0 — full-attention prefill no
10293                    // longer re-reads the projection weights b times).
10294                    let mut normed = vec![0.0f32; b * hs];
10295                    for bi in 0..b {
10296                        inference::rms_norm_into(
10297                            &h[bi * hs..(bi + 1) * hs],
10298                            &lw.input_norm,
10299                            eps,
10300                            norm_style,
10301                            &mut normed[bi * hs..(bi + 1) * hs],
10302                        );
10303                    }
10304                    let inv_freq_l = self.layer_inv_freq(li);
10305                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
10306                    let cfg = QwenAttnCfg {
10307                        num_heads: self.layer_num_heads(li),
10308                        num_kv_heads: nkv_l,
10309                        head_dim: hd_l,
10310                        hidden_size: hs,
10311                        position: start_pos,
10312                        inv_freq: &inv_freq_l,
10313                        rotary_dim: rd_l,
10314                        scale: self.attn_scale,
10315                        softcap: self.attn_softcap,
10316                        window: self.layer_window(li),
10317                        v_norm: self.attn_v_norm,
10318                        qk_norm_after_rope: self.qk_norm_after_rope,
10319                        gate_sigmoid: self.proj_gate_sigmoid,
10320                        q_norm: q_norm.as_deref(),
10321                        k_norm: k_norm.as_deref(),
10322                        output_gate: *output_gate,
10323                        softplus_gate: softplus_gate
10324                            .as_ref()
10325                            .map(|(gate, per_head)| (gate, *per_head)),
10326                        rope_scale: self.layer_rope_scale(li),
10327                        bias: bias
10328                            .as_ref()
10329                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
10330                        rms_eps: eps,
10331                        norm_style,
10332                        pool: pool.as_deref(),
10333                        v_head_dim: self.layer_v_dim(li),
10334                    };
10335                    #[cfg(feature = "gpu")]
10336                    let _mirror = self
10337                        .prefill_mirror_target(li)
10338                        .map(crate::gpu::enter_prefill_mirror);
10339                    let mut attn = attention::qwen_attention_batch(
10340                        &normed,
10341                        b,
10342                        wq,
10343                        wk,
10344                        wv,
10345                        wo,
10346                        &mut self.kv_cache.layers[li],
10347                        &cfg,
10348                    );
10349                    if let Some(w) = &lw.attn_out_norm {
10350                        for bi in 0..b {
10351                            inference::rms_norm_into(
10352                                &attn[bi * hs..(bi + 1) * hs],
10353                                w,
10354                                eps,
10355                                norm_style,
10356                                &mut normed[bi * hs..(bi + 1) * hs],
10357                            );
10358                        }
10359                        attn.copy_from_slice(&normed);
10360                    }
10361                    for (dst, &a) in h.iter_mut().zip(&attn) {
10362                        *dst += a;
10363                    }
10364                }
10365                AttnKind::Bounded(w) => {
10366                    // Chunk-GEMM projections, the bounded operator per
10367                    // position over ring + chunk — never a growing KV.
10368                    let mut normed = vec![0.0f32; b * hs];
10369                    for bi in 0..b {
10370                        inference::rms_norm_into(
10371                            &h[bi * hs..(bi + 1) * hs],
10372                            &lw.input_norm,
10373                            eps,
10374                            norm_style,
10375                            &mut normed[bi * hs..(bi + 1) * hs],
10376                        );
10377                    }
10378                    let rope = self
10379                        .bounded_rope
10380                        .clone()
10381                        .expect("bounded layer without an installed rotation table");
10382                    let cfg = crate::bounded::BoundedAttnCfg {
10383                        num_heads: self.num_heads,
10384                        num_kv_heads: self.num_kv_heads,
10385                        head_dim: self.head_dim,
10386                        hidden_size: hs,
10387                        scale: self.attn_scale,
10388                        rope: &rope,
10389                        pool: pool.as_deref(),
10390                    };
10391                    let mut attn = crate::bounded::bounded_attention_batch(
10392                        &normed,
10393                        b,
10394                        w,
10395                        &mut self.kv_cache.layers[li],
10396                        &cfg,
10397                    );
10398                    if let Some(wn) = &lw.attn_out_norm {
10399                        for bi in 0..b {
10400                            inference::rms_norm_into(
10401                                &attn[bi * hs..(bi + 1) * hs],
10402                                wn,
10403                                eps,
10404                                norm_style,
10405                                &mut normed[bi * hs..(bi + 1) * hs],
10406                            );
10407                        }
10408                        attn.copy_from_slice(&normed);
10409                    }
10410                    for (dst, &a) in h.iter_mut().zip(&attn) {
10411                        *dst += a;
10412                    }
10413                    attention::recycle_buf(&mut attn);
10414                }
10415                AttnKind::Linear(w) => {
10416                    for bi in 0..b {
10417                        let normed = inference::rms_norm(
10418                            &h[bi * hs..(bi + 1) * hs],
10419                            &lw.input_norm,
10420                            eps,
10421                            norm_style,
10422                        );
10423                        vmf_phase_forward(
10424                            &normed,
10425                            w,
10426                            &self.vmf_cfg.expect("linear layer without vmf_cfg"),
10427                            &mut self.kv_cache.layers[li].linear_state,
10428                            pool.as_deref(),
10429                        )
10430                        .iter()
10431                        .enumerate()
10432                        .for_each(|(i, &a)| h[bi * hs + i] += a);
10433                    }
10434                }
10435            }
10436
10437            // ── FFN batched ──
10438            let lw = &self.weights.layers[self.phys_layer(li)];
10439            let mut post = vec![0.0f32; b * hs];
10440            for bi in 0..b {
10441                let r =
10442                    inference::rms_norm(&h[bi * hs..(bi + 1) * hs], &lw.post_norm, eps, norm_style);
10443                post[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
10444            }
10445            // A restrictive per-visit FFN row lands on the activations
10446            // inside the dense arm; an all-open row costs nothing.
10447            let mask_row = task_mask
10448                .filter(|m| m.ffn_active_count(li) < self.intermediate_size)
10449                .and_then(|m| m.ffn_masks.get(li))
10450                .map(|v| v.as_slice());
10451            let attn_ns = t_attn.elapsed().as_nanos() as u64;
10452            let t_ffn = std::time::Instant::now();
10453            let mut ffn = match &lw.ffn {
10454                FfnKind::Dense(d) if !d.segs.is_empty() => {
10455                    tube_ffn(d, &post, b, pool.as_deref(), mask_row)
10456                }
10457                FfnKind::Dense(d) => dense_ffn_batch(d, &post, b, pool.as_deref(), mask_row),
10458                FfnKind::Moe(m) if self.verify_exact_moe && self.mimo_moe.is_dynamic(li, false) => {
10459                    moe_ffn_banked_rows(&mut self.mimo_moe, li, m, &post, b, hs, pool.as_deref())
10460                }
10461                FfnKind::Moe(m) if self.verify_exact_moe => {
10462                    moe_ffn_rows_exact(m, &post, b, hs, pool.as_deref())
10463                }
10464                // Keep prompt expert panels off the projection arena and
10465                // use their routes to prime the model-wide bank.
10466                FfnKind::Moe(m) if self.mimo_moe.is_dynamic(li, false) => {
10467                    let before = m.stats.borrow().clone();
10468                    let out = crate::gpu::cpu_scope(|| {
10469                        moe_ffn_batch(m, &post, b, hs, pool.as_deref(), None)
10470                    });
10471                    self.mimo_moe.prime(li, m, &before);
10472                    out
10473                }
10474                FfnKind::Moe(m) => moe_ffn_batch(m, &post, b, hs, pool.as_deref(), None),
10475                // Dual-branch layers run per position (the expert branch
10476                // reads the raw residual — nothing to batch yet).
10477                FfnKind::DenseMoe(dm) => {
10478                    let mut out = vec![0.0f32; b * hs];
10479                    for bi in 0..b {
10480                        let r = dense_moe_ffn(
10481                            dm,
10482                            &post[bi * hs..(bi + 1) * hs],
10483                            &h[bi * hs..(bi + 1) * hs],
10484                            eps,
10485                            norm_style,
10486                            pool.as_deref(),
10487                        );
10488                        out[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
10489                    }
10490                    out
10491                }
10492            };
10493            if prefill_prof_on() {
10494                PREFILL_SPLIT[0].fetch_add(attn_ns, std::sync::atomic::Ordering::Relaxed);
10495                PREFILL_SPLIT[1].fetch_add(
10496                    t_ffn.elapsed().as_nanos() as u64,
10497                    std::sync::atomic::Ordering::Relaxed,
10498                );
10499            }
10500            if let Some(w) = &lw.ffn_out_norm {
10501                for bi in 0..b {
10502                    inference::rms_norm_into(
10503                        &ffn[bi * hs..(bi + 1) * hs],
10504                        w,
10505                        eps,
10506                        norm_style,
10507                        &mut post[bi * hs..(bi + 1) * hs],
10508                    );
10509                }
10510                ffn.copy_from_slice(&post);
10511            }
10512            for (dst, &f) in h.iter_mut().zip(&ffn) {
10513                *dst += f;
10514            }
10515            if let Some(sc) = lw.layer_scale {
10516                for v in h.iter_mut() {
10517                    *v *= sc;
10518                }
10519            }
10520            // CMF_LAYER_DUMP: every position's hidden after layer li.
10521            if self.layer_dump.is_some() {
10522                for bi in 0..b {
10523                    self.dump_layer_row(start_pos + bi, li, &h[bi * hs..(bi + 1) * hs]);
10524                }
10525            }
10526            if let Ok(tp) = std::env::var("CMF_TRACE_POS") {
10527                if let Ok(t) = tp.parse::<usize>() {
10528                    if t >= start_pos && t < start_pos + b {
10529                        let bi = t - start_pos;
10530                        let row = &h[bi * hs..(bi + 1) * hs];
10531                        let n: f32 = row.iter().map(|x| x * x).sum::<f32>().sqrt();
10532                        eprintln!(
10533                            "BATCH pos {t} after layer {li}: |h| = {n:.6} h0 {:.6} h1 {:.6}",
10534                            row[0], row[1]
10535                        );
10536                    }
10537                }
10538            }
10539            // CMF_DEBUG_LAYERS=1: per-layer hidden-state health of the
10540            // LAST prompt position — the knife for "which layer type
10541            // breaks first" on a new architecture.
10542            if std::env::var("CMF_DEBUG_LAYERS").is_ok() {
10543                let row = &h[(b - 1) * hs..b * hs];
10544                let rms =
10545                    (row.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / hs as f64).sqrt();
10546                let mx = row.iter().fold(0f32, |m, &v| m.max(v.abs()));
10547                eprintln!(
10548                    "layer {li:>3} {:>10} ffn={:<5} rms={rms:>12.4} max={mx:>12.4}",
10549                    match &self.weights.layers[self.phys_layer(li)].attn {
10550                        AttnKind::LinearGdn(_) => "gdn",
10551                        AttnKind::Linear(_) => "vmf",
10552                        AttnKind::ShortConv(_) => "conv",
10553                        _ => "attn",
10554                    },
10555                    match &lw.ffn {
10556                        FfnKind::Moe(_) => "moe",
10557                        FfnKind::Dense(_) => "dense",
10558                        FfnKind::DenseMoe(_) => "dense+moe",
10559                    },
10560                );
10561            }
10562            // Looped Transformer: apply final norm at the end of each loop iteration.
10563            if self.is_loop_end(li) && li + 1 < self.num_layers {
10564                for bi in 0..b {
10565                    let normed = inference::rms_norm(
10566                        &h[bi * hs..(bi + 1) * hs],
10567                        &self.weights.final_norm,
10568                        eps,
10569                        norm_style,
10570                    );
10571                    h[bi * hs..(bi + 1) * hs].copy_from_slice(&normed);
10572                }
10573            }
10574            if std::env::var("CMF_TRACE_H").is_ok() {
10575                let n = h[..hs].iter().map(|v| v.abs()).sum::<f32>() / hs as f32;
10576                let mx = h[..hs].iter().fold(0.0f32, |a, &v| a.max(v.abs()));
10577                eprintln!(
10578                    "layer {li}: mean|h|={n:.4} max|h|={mx:.2} scale={:?}",
10579                    lw.layer_scale
10580                );
10581            }
10582        }
10583        crate::gpu::set_layer(-1); // lm_head/final ops outside layer-split
10584        if prefill_prof_on() {
10585            let ms = |a: &std::sync::atomic::AtomicU64| {
10586                a.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6
10587            };
10588            let sp = &attention::ATTN_SPLIT;
10589            let (qkv_enq, qkv_wait, ca_wait, zi) = wgpu_prefill_counters();
10590            eprintln!(
10591                "prefill-split: attention {:.1} ms (proj {:.1} [qkv enqueue {:.1} wait {:.1}, \
10592                 host gate {:.1}], host loop {:.1}, attend {:.1} \
10593                 [q pack {:.1}, device {:.1} of which readback {:.1}], o-proj {:.1}), \
10594                 ffn {:.1} ms (cumulative; zi_mm GEMMs {zi})",
10595                ms(&PREFILL_SPLIT[0]),
10596                ms(&sp[0]),
10597                qkv_enq,
10598                qkv_wait,
10599                ms(&sp[6]),
10600                ms(&sp[1]),
10601                ms(&sp[2]),
10602                ms(&sp[4]),
10603                ms(&sp[5]),
10604                ca_wait,
10605                ms(&sp[3]),
10606                ms(&PREFILL_SPLIT[1]),
10607            );
10608            let [calls, attended, wo, ring, reseed, f16] = wgpu_mirror_counters();
10609            eprintln!(
10610                "prefill-mirror: {calls} calls, {attended} attended ({wo} with O on the card), \
10611                 {ring} ring refusals, {reseed} reseeds, {f16} f16 fallbacks, {} upload \
10612                 fallbacks (cumulative)",
10613                attention::MIRROR_UPLOADS.load(std::sync::atomic::Ordering::Relaxed),
10614            );
10615        }
10616        // A batched span owns a complete set of positions. Publish any
10617        // collecting→sealed transition only after every layer has finished;
10618        // callers that cross into serial/device work must see the new epoch
10619        // before this function returns.
10620        self.o1_progress();
10621        // Every layer of the chunk has appended and attended its rows.
10622        self.swa_trim_tails();
10623        h
10624    }
10625
10626    /// Embed a single token.
10627    fn embed_single(&self, id: u32) -> Vec<f32> {
10628        let mut out = vec![0.0f32; self.hidden_size];
10629        if (id as usize) < self.weights.embed_tokens.rows() {
10630            self.weights.embed_tokens.row_f32(id as usize, &mut out);
10631        }
10632        if self.embed_multiplier != 1.0 {
10633            for v in out.iter_mut() {
10634                *v *= self.embed_multiplier;
10635            }
10636        }
10637        // DeepSeek-V4's hash layers route by TOKEN ID, so the id has to
10638        // reach the forward. It rides in slot 0 (the forward re-reads the
10639        // real embedding itself from the table).
10640        if self.dsv4.is_some() || self.dsv41.is_some() || self.qwen4_exp.is_some() {
10641            let mut v = vec![0.0f32; self.hidden_size.max(1)];
10642            v[0] = id as f32;
10643            return v;
10644        }
10645        // Gemma-3n: the per-layer-embedding half needs the token ID, so
10646        // it rides appended to the embedding; the g3n forward splits it.
10647        // Gemma-4 E-series PLE: same contract, its own table.
10648        if let Some(b) = &self.g4e {
10649            return b.0.extend_embedding(id, &out, self.pool.as_deref());
10650        }
10651        if let Some(b) = &self.g3n {
10652            return b.0.extend_embedding(id, &out, self.pool.as_deref());
10653        }
10654        out
10655    }
10656
10657    /// A run of consecutive prefill layers on the GPU for the whole
10658    /// chunk (default-on under CMF_GPU=1; CMF_GPU_CHUNK=0 disables).
10659    /// Eligibility per layer: q8_row weights, plain full attention
10660    /// (no output gate), F32 KV, no o1/masks/gemma extras. Returns the
10661    /// first layer index NOT processed (== `li0` when the run is empty).
10662    #[cfg(target_os = "macos")]
10663    fn chunk_run_gpu(
10664        &mut self,
10665        li0: usize,
10666        h: &mut [f32],
10667        b: usize,
10668        pos0: usize,
10669        embed_ids: Option<&[u32]>,
10670        cap: usize,
10671    ) -> usize {
10672        // (The old streaming attend needed a depth bound at ~1k; the
10673        // GEMM attention scales like the CPU path and lifted it.)
10674        // CMF_GPU_CHUNK=0 disables the graph.
10675        // Gemma-4 (`metal_gemma4`) brings its own kernels for the global
10676        // layers, V norm, attention scale and sandwich (`ChunkGemma4`).
10677        // `CMF_METAL_GEMMA4_CHUNK=0` keeps its prompt on the host walk.
10678        let gemma4 =
10679            self.metal_gemma4() && std::env::var("CMF_METAL_GEMMA4_CHUNK").as_deref() != Ok("0");
10680        if !crate::gpu::enabled_here()
10681            || std::env::var("CMF_GPU_CHUNK")
10682                .map(|v| v == "0")
10683                .unwrap_or(false)
10684            || b < 32
10685            // Sliding windows with per-layer RoPE ride the chunk graph
10686            // (`metal_graph_swa`: causal_softmax_win, per-layer tables).
10687            || (self.swa.is_some() && !self.metal_graph_swa() && !gemma4)
10688            || (self.global_attn.is_some() && !gemma4)
10689            // Chunk attention has no value-less learned-sink column. q1
10690            // decode can carry it through ordinary `gqa_attend`, but prompt
10691            // chunks must stay on the exact host attention path.
10692            || self.kv_cache.layers.iter().any(|l| l.sinks.is_some())
10693            // Per-layer KV heads and narrow V remain outside this chunk
10694            // graph (the q1 sliding-native door checks the same geometry).
10695            || (self.graph_attn_decline_reason().is_some() && !self.metal_graph_swa() && !gemma4)
10696            // Collection owns the exact Q trace and boundary conversion;
10697            // this chunk graph appends dense KV without feeding that trace.
10698            || self.o1_active()
10699            || (self.attn_v_norm && !gemma4)
10700            || !self.metal_rope_scale_ok()
10701            || ((self.attn_scale - 1.0 / (self.head_dim as f32).sqrt()).abs() > 1e-9 && !gemma4)
10702        {
10703            return li0;
10704        }
10705        let Some(model) = self.model.clone() else {
10706            return li0;
10707        };
10708        let (nh, nkv, hd, hs) = (
10709            self.num_heads,
10710            self.num_kv_heads,
10711            self.head_dim,
10712            self.hidden_size,
10713        );
10714        // Collect the longest run of consecutive eligible layers.
10715        // Looped Transformer: stop at the loop boundary so the CPU can
10716        // apply loop_final_norm between iterations.
10717        let loop_end = if self.loop_final_norm {
10718            ((li0 / self.physical_layers) + 1) * self.physical_layers
10719        } else {
10720            self.num_layers
10721        };
10722        let run_end = self.num_layers.min(loop_end).min(cap);
10723        // Each layer's own RoPE table (Spark-X2.5: sliding and full layers
10724        // differ); the global one for every model without sliding layers.
10725        // Declared before `layers`, which borrows it (and drops a routing
10726        // closure on MoE layers).
10727        let tables: Vec<std::sync::Arc<Vec<f32>>> =
10728            (li0..run_end).map(|li| self.layer_inv_freq(li)).collect();
10729        let mut layers: Vec<crate::gpu_metal::ChunkLayer> = Vec::new();
10730        let mut stored_at: Vec<usize> = Vec::new();
10731        for li in li0..run_end {
10732            let lw = &self.weights.layers[self.phys_layer(li)];
10733            if (lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some())
10734                && !gemma4
10735            {
10736                break;
10737            }
10738            let AttnKind::Full {
10739                wq,
10740                wk,
10741                wv,
10742                wo,
10743                q_norm,
10744                k_norm,
10745                output_gate: false,
10746                softplus_gate,
10747                bias,
10748            } = &lw.attn
10749            else {
10750                break;
10751            };
10752            // Spark-X2.5's per-head sigmoid g_proj gate, from f32 rows.
10753            let head_gate = match softplus_gate {
10754                None => None,
10755                Some((g, true)) if self.proj_gate_sigmoid => match g.f32_parts() {
10756                    Some((d, r, c)) if r == nh && c == hs => Some(d),
10757                    _ => break,
10758                },
10759                Some(_) => break,
10760            };
10761            // The FFN: a dense SiLU/GELU trio, or routed q4tp experts
10762            // (Mellum2.1: softmax router, no shared expert) whose first
10763            // trio stands in for the shape checks.
10764            let (gate_t, up_t, down_t, ffn_act, moe) = match &lw.ffn {
10765                FfnKind::Dense(d)
10766                    if (matches!(d.act, Act::Silu | Act::Gelu)
10767                        || (gemma4 && d.act == Act::GeluTanh))
10768                        && d.segs.is_empty() =>
10769                {
10770                    (&d.gate_proj, &d.up_proj, &d.down_proj, d.act, None)
10771                }
10772                FfnKind::Moe(m) => match chunk_moe_parts(m, hs) {
10773                    Some((router, experts, q8)) => {
10774                        let e0 = &m.experts[0];
10775                        let route = Box::new(move |lg: &[f32]| {
10776                            // `moe_ffn_batch`'s routing and weights, row by row.
10777                            let (idx, p, wsum) = moe_route(lg, m, None);
10778                            let mut st = m.stats.borrow_mut();
10779                            if st.len() < m.experts.len() {
10780                                st.resize(m.experts.len(), 0);
10781                            }
10782                            for &e in &idx {
10783                                st[e] += 1;
10784                            }
10785                            let w = idx.iter().map(|&e| p[e] / wsum).collect();
10786                            (idx, w)
10787                        });
10788                        (
10789                            &e0.gate_proj,
10790                            &e0.up_proj,
10791                            &e0.down_proj,
10792                            Act::Silu,
10793                            Some(crate::gpu_metal::ChunkMoe {
10794                                router,
10795                                experts,
10796                                q8,
10797                                route,
10798                            }),
10799                        )
10800                    }
10801                    None => break,
10802                },
10803                _ => break,
10804            };
10805            // q8_row (row_scale populated), q8_2f (plus its input field),
10806            // or q4_tiled / q4tp (row_scale empty — their scales are in the
10807            // payload). Mixing across the seven projections of one layer is
10808            // fine; the encoder branches per weight on the tensor's dtype.
10809            // Anything else refuses.
10810            fn cw(t: &QTensor) -> Option<(usize, usize, usize, &[f32])> {
10811                t.q8_row_parts()
10812                    .or_else(|| t.q8_2f_parts().map(|(i, r, c, rs, _)| (i, r, c, rs)))
10813                    .or_else(|| t.q4t_parts().map(|(i, r, c)| (i, r, c, &[][..])))
10814                    .or_else(|| t.q4tp_parts().map(|(i, r, c)| (i, r, c, &[][..])))
10815            }
10816            fn cf(t: &QTensor) -> &[f32] {
10817                t.q8_2f_parts().map_or(&[][..], |(_, _, _, _, cf)| cf)
10818            }
10819            let col = [cf(wq), cf(wk), cf(wv), cf(wo)];
10820            // q8_2f projections ride the chunk graph on the MoE layers it
10821            // was measured on (Mellum2.1); dense q8_2f stacks keep the host
10822            // walk until they are measured too. That includes a q8_2f
10823            // gate/up/down behind q4/q8_row attention: the chunk FFN has no
10824            // x·col staging, so it would run those weights without their
10825            // input field (0.8.14 refused every q8_2f weight here).
10826            // Gemma-4 reads every q8_2f weight through the blob GEMM with its
10827            // own field (`ChunkGemma4`), so its dense q8_2f stack rides.
10828            if moe.is_none()
10829                && !gemma4
10830                && (col.iter().any(|c| !c.is_empty())
10831                    || [gate_t, up_t, down_t].iter().any(|t| !cf(t).is_empty()))
10832            {
10833                break;
10834            }
10835            let parts = (
10836                cw(wq),
10837                cw(wk),
10838                cw(wv),
10839                cw(wo),
10840                cw(gate_t),
10841                cw(up_t),
10842                cw(down_t),
10843            );
10844            let (Some(pq), Some(pk), Some(pv), Some(po), Some(pg), Some(pu), Some(pd)) = parts
10845            else {
10846                break;
10847            };
10848            let layer = &self.kv_cache.layers[li];
10849            if layer.mode != crate::kv_cache::KvMode::F32 || layer.o1.is_some() {
10850                break;
10851            }
10852            // A trimmed tail holds every row the chunk's first query reads.
10853            debug_assert!(
10854                layer.base() == 0
10855                    || self
10856                        .layer_window(li)
10857                        .is_some_and(|w| layer.head_len(0) + 1 >= w)
10858            );
10859            stored_at.push(layer.head_len(0));
10860            // Per-layer geometry for Gemma-4 (512-wide global layers over
10861            // one KV head); every other model keeps the pipeline-wide one.
10862            let (nkv, hd) = if gemma4 {
10863                let (a, bb, _) = self.layer_geom(li);
10864                (a, bb)
10865            } else {
10866                (nkv, hd)
10867            };
10868            layers.push(crate::gpu_metal::ChunkLayer {
10869                model: &model,
10870                kv_id: self.graph_kv_id,
10871                layer: li,
10872                wq: pq,
10873                wk: pk,
10874                wv: pv,
10875                wo: po,
10876                gate: pg,
10877                up: pu,
10878                down: pd,
10879                input_norm: &lw.input_norm,
10880                post_norm: &lw.post_norm,
10881                bias: bias
10882                    .as_ref()
10883                    .map(|(a, bb, cc)| (a.as_slice(), bb.as_slice(), cc.as_slice())),
10884                q_norm: q_norm.as_deref(),
10885                k_norm: k_norm.as_deref(),
10886                inv_freq: &tables[li - li0],
10887                rope_scale: self.layer_rope_scale(li),
10888                rd: self.layer_geom(li).2,
10889                nh,
10890                nkv,
10891                hd,
10892                hs,
10893                inter: gate_t.rows(),
10894                gemma: matches!(self.norm_style, cortiq_core::NormStyle::Gemma),
10895                late_qk_norm: self.qk_norm_after_rope,
10896                eps: self.rms_eps as f32,
10897                window: self.layer_window(li),
10898                head_gate,
10899                act: ffn_act.graph_act().map_or(0, |a| a.code() as u8),
10900                g4: gemma4.then(|| crate::gpu_metal::ChunkGemma4 {
10901                    v_norm: self.attn_v_norm,
10902                    scale: self.attn_scale,
10903                    attn_out_norm: lw.attn_out_norm.as_deref(),
10904                    ffn_out_norm: lw.ffn_out_norm.as_deref(),
10905                    layer_scale: lw.layer_scale,
10906                }),
10907                col,
10908                moe,
10909            });
10910        }
10911        if layers.is_empty() {
10912            return li0;
10913        }
10914        // KV row width per layer (uniform but for Gemma-4).
10915        let rows_kv: Vec<(usize, usize)> = layers.iter().map(|l| (l.nkv, l.nkv * l.hd)).collect();
10916        let mut store: Vec<(Vec<f32>, Vec<f32>, Vec<f32>)> = stored_at
10917            .iter()
10918            .zip(&rows_kv)
10919            .map(|(&st, &(_, row))| (vec![0f32; b * row], vec![0f32; b * row], vec![0f32; st + b]))
10920            .collect();
10921        let mut io: Vec<crate::gpu_metal::ChunkIo> = Vec::with_capacity(layers.len());
10922        for (i, (ok, ov, oi)) in store.iter_mut().enumerate() {
10923            let li = layers[i].layer;
10924            let layer = &self.kv_cache.layers[li];
10925            let nkv = rows_kv[i].0;
10926            io.push(crate::gpu_metal::ChunkIo {
10927                cpu_stored: stored_at[i],
10928                cpu_gen: layer.generation(),
10929                cpu_k: (0..nkv).map(|g| layer.head_keys(g)).collect(),
10930                cpu_v: (0..nkv).map(|g| layer.head_values(g)).collect(),
10931                out_k: ok,
10932                out_v: ov,
10933                imp: oi,
10934            });
10935        }
10936        let n_run = layers.len();
10937        let last = layers.last().map(|l| l.layer + 1).unwrap_or(li0);
10938        // Device-side embedding when the run starts the model and the
10939        // embedding matrix is q8_row-mapped.
10940        let ep = embed_ids.and_then(|ids| {
10941            self.weights
10942                .embed_tokens
10943                .q8_row_parts()
10944                .map(|(idx, rows, _c, rs)| crate::gpu_metal::ChunkEmbed {
10945                    idx,
10946                    rows,
10947                    row_scale: rs,
10948                    ids,
10949                    mult: self.embed_multiplier,
10950                })
10951        });
10952        if embed_ids.is_some() && ep.is_none() {
10953            return li0;
10954        }
10955        if !crate::gpu_metal::chunk_run_gpu(&layers, &mut io, h, b, pos0, ep.as_ref()) {
10956            return li0;
10957        }
10958        drop(io);
10959        drop(layers);
10960        // CPU caches stay the owners of record: append the chunk rows
10961        // and bank the importance masses per layer.
10962        for (i, (ok, ov, oi)) in store.iter().enumerate().take(n_run) {
10963            let li = li0 + i;
10964            let row = rows_kv[i].1;
10965            let layer = &mut self.kv_cache.layers[li];
10966            for bi in 0..b {
10967                layer.append(
10968                    &ok[bi * row..(bi + 1) * row],
10969                    &ov[bi * row..(bi + 1) * row],
10970                    &[],
10971                );
10972            }
10973            layer.accumulate_imp(oi);
10974        }
10975        last
10976    }
10977
10978    /// Is layer `li` a sliding-window (local-RoPE) layer? Gemma-3:
10979    /// every `pattern`-th layer is global, the rest are local.
10980    fn layer_is_local(&self, li: usize) -> bool {
10981        if let Some(layers) = &self.sliding_layers {
10982            return layers.get(li).copied().unwrap_or(false);
10983        }
10984        match self.swa {
10985            Some((_, pattern)) => (li + 1) % pattern.max(1) != 0,
10986            None => false,
10987        }
10988    }
10989
10990    /// The RoPE table for layer `li` (local layers may have their own;
10991    /// Gemma-4 global layers use the proportional padded table).
10992    fn layer_inv_freq(&self, li: usize) -> std::sync::Arc<Vec<f32>> {
10993        if self.layer_is_local(li) {
10994            if let Some(f) = &self.inv_freq_local {
10995                return f.clone();
10996            }
10997        } else if let Some(f) = &self.inv_freq_global {
10998            return f.clone();
10999        }
11000        self.inv_freq.clone()
11001    }
11002
11003    /// The attend window for layer `li` (None = full context).
11004    fn layer_window(&self, li: usize) -> Option<usize> {
11005        self.swa
11006            .and_then(|(w, _)| self.layer_is_local(li).then_some(w))
11007    }
11008
11009    /// Drop every sliding layer's rows its window can no longer read
11010    /// (`LayerKvCache::trim_window`). Call only at a safe point — after a
11011    /// complete position / pair / chunk walk, never between a layer's
11012    /// appends and its attend. One comparison per layer below the trigger.
11013    ///
11014    /// Off with an MTP head: its verify oracles and rollbacks snapshot and
11015    /// compare per-layer row counts as positions (`CMF_METAL_VERIFY_CHECK`,
11016    /// the MTP caches), which a trimmed tail would break.
11017    fn swa_trim_tails(&mut self) {
11018        let Some((slack, align)) = self.swa_trim else {
11019            return;
11020        };
11021        if self.mtp.is_some() || self.mimo_mtp.is_some() || !self.dsv4_mtp.is_empty() {
11022            return;
11023        }
11024        for li in 0..self.num_layers.min(self.kv_cache.layers.len()) {
11025            if let Some(w) = self.layer_window(li) {
11026                self.kv_cache.layers[li].trim_window(w, slack, align);
11027            }
11028        }
11029    }
11030
11031    fn layer_num_heads(&self, li: usize) -> usize {
11032        self.attention_heads_per_layer
11033            .as_ref()
11034            .and_then(|v| v.get(li).copied())
11035            .unwrap_or(self.num_heads)
11036    }
11037
11038    fn layer_rope_scale(&self, li: usize) -> f32 {
11039        if self.layer_is_local(li) {
11040            self.rope_scale_local
11041        } else {
11042            self.rope_scale
11043        }
11044    }
11045
11046    /// Attention geometry of layer `li`: (num_kv_heads, head_dim,
11047    /// rotary_dim). Gemma-4 global layers override all three.
11048    fn layer_geom(&self, li: usize) -> (usize, usize, usize) {
11049        if !self.layer_is_local(li) {
11050            if let Some((ghd, gkv)) = self.global_attn {
11051                return (gkv, ghd, ghd);
11052            }
11053        }
11054        let rd = if self.layer_is_local(li) {
11055            self.rotary_dim_local.unwrap_or(self.rotary_dim)
11056        } else {
11057            self.rotary_dim
11058        };
11059        // A layer without positional encoding rotates nothing.
11060        let rd = if self
11061            .no_rope_layers
11062            .as_ref()
11063            .and_then(|v| v.get(li))
11064            .copied()
11065            == Some(true)
11066        {
11067            0
11068        } else {
11069            rd
11070        };
11071        (self.layer_num_kv_heads(li), self.head_dim, rd)
11072    }
11073
11074    /// KV heads of layer `li` (virtual index): the per-layer count when the
11075    /// model has one (MiMo-V2), else the uniform `num_kv_heads`.
11076    fn layer_num_kv_heads(&self, li: usize) -> usize {
11077        self.kv_heads_per_layer
11078            .as_ref()
11079            .and_then(|v| v.get(self.phys_layer(li)).copied())
11080            .unwrap_or(self.num_kv_heads)
11081    }
11082
11083    /// V head width of layer `li` (≤ its head_dim).
11084    fn layer_v_dim(&self, li: usize) -> usize {
11085        let (_, hd, _) = self.layer_geom(li);
11086        self.v_head_dim.unwrap_or(hd).min(hd)
11087    }
11088
11089    /// Install a per-layer KV geometry: KV heads per PHYSICAL layer and/or
11090    /// a V head width narrower than `head_dim` (MiMo-V2). Validates it and
11091    /// reshapes the caches of every layer whose KV head count differs from
11092    /// `num_kv_heads`. The loader and the tests share this one path, so a
11093    /// hand-built pipeline cannot hold a geometry the loader would refuse.
11094    /// Call before the first forward (it drops cached rows of reshaped
11095    /// layers). Refuses combinations whose paths would read it wrong:
11096    /// Gemma-4 global layers and MLA carry their own geometry.
11097    pub fn set_attn_geometry(
11098        &mut self,
11099        kv_heads_per_layer: Option<Vec<usize>>,
11100        v_head_dim: Option<usize>,
11101    ) -> Result<(), String> {
11102        if kv_heads_per_layer.is_some() || v_head_dim.is_some() {
11103            if self.global_attn.is_some() {
11104                return Err(
11105                    "per-layer KV heads / v_head_dim cannot combine with Gemma-4 global \
11106                     attention geometry"
11107                        .into(),
11108                );
11109            }
11110            if self
11111                .weights
11112                .layers
11113                .iter()
11114                .any(|lw| matches!(lw.attn, AttnKind::Mla(_)))
11115            {
11116                return Err("per-layer KV heads / v_head_dim cannot combine with MLA".into());
11117            }
11118        }
11119        if let Some(vd) = v_head_dim {
11120            if vd == 0 || vd > self.head_dim {
11121                return Err(format!(
11122                    "v_head_dim {vd} must be in 1..={} (head_dim)",
11123                    self.head_dim
11124                ));
11125            }
11126        }
11127        if let Some(v) = &kv_heads_per_layer {
11128            if v.len() != self.physical_layers {
11129                return Err(format!(
11130                    "kv_heads_per_layer has {} entries, expected {} layers",
11131                    v.len(),
11132                    self.physical_layers
11133                ));
11134            }
11135            for (li, &nkv) in v.iter().enumerate() {
11136                let is_attn = matches!(
11137                    self.weights.layers.get(li).map(|lw| &lw.attn),
11138                    Some(AttnKind::Full { .. }) | None
11139                );
11140                if !is_attn {
11141                    continue;
11142                }
11143                let nh = self
11144                    .attention_heads_per_layer
11145                    .as_ref()
11146                    .and_then(|h| h.get(li).copied())
11147                    .unwrap_or(self.num_heads);
11148                if nkv == 0 || nh % nkv != 0 {
11149                    return Err(format!(
11150                        "layer {li}: {nkv} KV heads must be nonzero and divide {nh} Q heads"
11151                    ));
11152                }
11153            }
11154        }
11155        self.kv_heads_per_layer = kv_heads_per_layer;
11156        self.v_head_dim = v_head_dim.filter(|&vd| vd != self.head_dim);
11157        if self.kv_heads_per_layer.is_some() {
11158            for li in 0..self.kv_cache.layers.len() {
11159                let full = matches!(
11160                    self.weights
11161                        .layers
11162                        .get(self.phys_layer(li))
11163                        .map(|lw| &lw.attn),
11164                    Some(AttnKind::Full { .. })
11165                );
11166                let nkv = self.layer_num_kv_heads(li);
11167                let cache = &self.kv_cache.layers[li];
11168                if full && (cache.num_kv_heads != nkv || cache.head_dim != self.head_dim) {
11169                    let sinks = cache.sinks.clone();
11170                    self.kv_cache.layers[li] =
11171                        crate::kv_cache::LayerKvCache::new(nkv, self.head_dim);
11172                    self.kv_cache.layers[li].sinks = sinks;
11173                }
11174            }
11175        }
11176        Ok(())
11177    }
11178
11179    /// Attach learned attention-sink logits (one per Q head) to PHYSICAL
11180    /// layer `phys` — every virtual layer that runs it. The loader calls
11181    /// this for each `model.layers.N.self_attn.sinks` tensor.
11182    pub fn set_layer_sinks(&mut self, phys: usize, sinks: Vec<f32>) -> Result<(), String> {
11183        let Some(lw) = self.weights.layers.get(phys) else {
11184            return Err(format!("sinks for layer {phys}: no such layer"));
11185        };
11186        if !matches!(lw.attn, AttnKind::Full { .. }) {
11187            return Err(format!(
11188                "sinks for layer {phys}: only softmax (Full) attention layers take sinks"
11189            ));
11190        }
11191        let nh = self
11192            .attention_heads_per_layer
11193            .as_ref()
11194            .and_then(|h| h.get(phys).copied())
11195            .unwrap_or(self.num_heads);
11196        if sinks.len() != nh {
11197            return Err(format!(
11198                "sinks for layer {phys}: {} values, expected one per Q head ({nh})",
11199                sinks.len()
11200            ));
11201        }
11202        if let Some(bad) = sinks.iter().find(|v| !v.is_finite()) {
11203            return Err(format!("sinks for layer {phys}: non-finite value {bad}"));
11204        }
11205        for li in 0..self.kv_cache.layers.len() {
11206            if self.phys_layer(li) == phys {
11207                self.kv_cache.layers[li].sinks = Some(sinks.clone());
11208            }
11209        }
11210        Ok(())
11211    }
11212
11213    /// Why the GPU attention graphs cannot serve this model, if they
11214    /// cannot: the wgpu whole-token and batched graphs, the greedy
11215    /// multi-burst, the q1 attention dropin and the Metal block/chunk/rows
11216    /// graphs all assume ONE (num_kv_heads, head_dim) geometry, V heads as
11217    /// wide as K, a single RoPE table, full-context attention and a plain
11218    /// softmax. A model outside that contract runs on the CPU layer walk
11219    /// (and the per-op GPU matvecs) until a graph learns it — never on a
11220    /// graph that would read it wrong. None = no attention-level reason
11221    /// (the graph builders still check weights and layer kinds).
11222    pub fn graph_attn_decline_reason(&self) -> Option<&'static str> {
11223        if self.kv_heads_per_layer.is_some() {
11224            return Some("per-layer KV head counts");
11225        }
11226        if self.v_head_dim.is_some_and(|vd| vd != self.head_dim) {
11227            return Some("V heads narrower than Q/K heads");
11228        }
11229        if self.kv_cache.layers.iter().any(|l| l.sinks.is_some()) {
11230            return Some("learned attention sinks");
11231        }
11232        if self.swa.is_some() || self.sliding_layers.is_some() {
11233            return Some("sliding-window layers");
11234        }
11235        None
11236    }
11237
11238    /// Can the Metal kernels apply this model's RoPE amplitude? Every
11239    /// rotation kernel (`attn_rope_qkn[_b]`, `chunk_rope_kv`) multiplies the
11240    /// rotated pair by the layer's `rope_scale` (YaRN `attention_factor`,
11241    /// Mellum2.1's global layers) exactly where the CPU's
11242    /// `rope_rotate_scaled` does. With the Q/K norm AFTER RoPE the kernels'
11243    /// shared sum of squares would be the unscaled one, so that pairing
11244    /// (no known model) declines.
11245    #[cfg(target_os = "macos")]
11246    fn metal_rope_scale_ok(&self) -> bool {
11247        !(self.qk_norm_after_rope
11248            && (0..self.num_layers).any(|li| self.layer_rope_scale(li) != 1.0))
11249    }
11250
11251    /// Can the Metal block graph carry this model's sliding-window layers?
11252    /// Both of its attention forms take a layer's own window, RoPE table
11253    /// and rotary width: the device attend (`AttnDeviceParams::window`, the
11254    /// layer's `inv_freq`/`rd`) and the sandwich's host attend (exactly the
11255    /// CPU path's attention). True when the sliding window is the model's
11256    /// only attention-level decline (Spark-X2.5). Learned, value-less
11257    /// sinks may accompany that geometry: q1's ordinary device GQA
11258    /// includes the sink in its softmax denominator and disables split-K.
11259    /// Per-layer KV heads, narrow V and Gemma-4 global geometry still
11260    /// decline; a YaRN amplitude per layer rides along
11261    /// (`metal_rope_scale_ok`).
11262    ///
11263    /// Per-layer Q heads (Laguna) and capped scores (Gemma-2) decline here
11264    /// too, with V norm (Gemma-4): the chunk prefill's own gate checks
11265    /// neither of the first two, and before this door opened its `swa`
11266    /// refusal kept every sliding model with them off the chunk graph.
11267    #[cfg(target_os = "macos")]
11268    fn metal_graph_swa(&self) -> bool {
11269        (self.swa.is_some() || self.sliding_layers.is_some())
11270            && self.attention_heads_per_layer.is_none()
11271            && !self.attn_v_norm
11272            && self.attn_softcap == 0.0
11273            && self.kv_heads_per_layer.is_none()
11274            && self.v_head_dim.map_or(true, |vd| vd == self.head_dim)
11275            && self.global_attn.is_none()
11276            && self.inv_freq_global.is_none()
11277            && self.metal_rope_scale_ok()
11278            && !(0..self.num_layers).any(|li| {
11279                self.layer_is_local(li)
11280                    && self.inv_freq_local.is_none()
11281                    && self.rotary_dim_local.is_some_and(|r| r != self.rotary_dim)
11282            })
11283    }
11284
11285    /// Can the Metal graphs carry this Gemma-4 model (`gpu_metal::gemma4`)?
11286    /// Its sliding layers (window, local RoPE table, 256-wide heads)
11287    /// device-attend like Spark-X2.5's; the 512-wide global layers (one KV
11288    /// head, proportional RoPE in the zero-padded table) take the 16-slot
11289    /// kernels; the V norm, sandwich norms, layer scalar and tanh-GELU come
11290    /// from the Gemma-4 library. Dense FFNs only (no Gemma-4 MoE measured).
11291    /// `CMF_METAL_GEMMA4=0` declines it as before (CPU attention).
11292    #[cfg(target_os = "macos")]
11293    fn metal_gemma4(&self) -> bool {
11294        crate::gpu_metal::gemma4::enabled()
11295            && (self.global_attn.is_some() || self.attn_v_norm)
11296            && self.attention_heads_per_layer.is_none()
11297            && self.kv_heads_per_layer.is_none()
11298            && self.v_head_dim.is_none()
11299            && !self.kv_cache.layers.iter().any(|l| l.sinks.is_some())
11300            && self.attn_softcap == 0.0
11301            && !self.qk_norm_after_rope
11302            && self.metal_rope_scale_ok()
11303            && self
11304                .weights
11305                .layers
11306                .iter()
11307                .all(|lw| matches!(&lw.ffn, FfnKind::Dense(d) if d.segs.is_empty()))
11308            && !(0..self.num_layers).any(|li| {
11309                self.layer_is_local(li)
11310                    && self.inv_freq_local.is_none()
11311                    && self.rotary_dim_local.is_some_and(|r| r != self.rotary_dim)
11312            })
11313    }
11314
11315    /// Why the WGPU graphs (whole-token, batched prefill, greedy burst)
11316    /// cannot run this model's attention, if they cannot. Per-layer KV
11317    /// heads, V narrower than K, learned sinks and sliding windows ride
11318    /// their per-layer geometry (`GraphAttnGeom`, the ATTEND_X kernels);
11319    /// what that geometry does not express keeps the decline, by name.
11320    /// None for every model with one attention geometry.
11321    pub fn wgpu_graph_attn_decline(&self) -> Option<&'static str> {
11322        // Keep the ordinary (uniform) fast arms off YaRN until they carry a
11323        // scale field too. A non-uniform geometry gets a `GraphAttnGeom` and
11324        // is handled below by the generic graph kernels.
11325        let geometry_reason = self.graph_attn_decline_reason();
11326        let has_scaled_rope = (0..self.num_layers).any(|li| self.layer_rope_scale(li) != 1.0);
11327        if has_scaled_rope && geometry_reason.is_none() {
11328            return Some("scaled RoPE without per-layer geometry");
11329        }
11330        // For Q/K norm after partial RoPE, the scale changes only the rotary
11331        // slice's RMS denominator. The generic graph deliberately declines
11332        // that uncommon combination until it carries a separate rotary sum;
11333        // Mellum has q/k norm before RoPE, so it remains on this path.
11334        if has_scaled_rope && self.qk_norm_after_rope {
11335            return Some("scaled RoPE with post-RoPE Q/K norm");
11336        }
11337        geometry_reason?;
11338        // Gemma-4: global layers 512 wide over 256-wide sliding ones
11339        // (`GraphAttnGeom::hd`), the scale-less V norm (`v_norm`), and the
11340        // sandwich norms + layer scalar (`GraphLayer`) ride the TOKEN graph.
11341        // The batch graph has none of the three and refuses them itself
11342        // (`batch_graph_gemma_decline`).
11343        if self.attention_heads_per_layer.is_some() {
11344            return Some("per-layer Q head counts with per-layer geometry");
11345        }
11346        // Sandwich norms are measured on Gemma-4 only (the humanizer port,
11347        // against HF transformers); Gemma-2/3 keep the per-op path until
11348        // they are measured the same way.
11349        let gemma4 = self.global_attn.is_some() || self.attn_v_norm;
11350        if !gemma4
11351            && self.weights.layers.iter().any(|lw| {
11352                lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some()
11353            })
11354        {
11355            return Some("sandwich norms / layer scale with per-layer geometry");
11356        }
11357        // `GraphAttnGeom::rope_scale` carries YaRN's post-rotation
11358        // attention-amplitude factor to the WGPU RoPE kernel. It is not an
11359        // angular position scale, so it must not be folded into `invf`.
11360        if self.weights.layers.iter().any(|lw| {
11361            matches!(
11362                &lw.attn,
11363                AttnKind::Full {
11364                    output_gate: true,
11365                    ..
11366                }
11367            )
11368        }) && self.v_head_dim.is_some()
11369        {
11370            return Some("gated attention with V narrower than K");
11371        }
11372        if (0..self.num_layers).any(|li| {
11373            self.layer_is_local(li)
11374                && self.inv_freq_local.is_none()
11375                && self.rotary_dim_local.is_some_and(|r| r != self.rotary_dim)
11376        }) {
11377            return Some("local rotary width without a local RoPE table");
11378        }
11379        None
11380    }
11381
11382    /// What the wgpu BATCH graph (and the attention-only singleton graphs)
11383    /// cannot run of Gemma-4, which the token graph does run: per-layer
11384    /// head widths, the V norm, sandwich norms and the layer scalar.
11385    fn batch_graph_gemma_decline(&self) -> Option<&'static str> {
11386        // Gemma-4 rides `gemma_batch` (per-layer head width, V norm,
11387        // sandwich norms, layer scalar) unless CMF_G4_BATCH=0.
11388        if (self.global_attn.is_some() || self.attn_v_norm) && crate::gpu::g4_batch_on() {
11389            return None;
11390        }
11391        if self.global_attn.is_some() {
11392            return Some("per-layer head width (Gemma-4 global layers)");
11393        }
11394        if self.attn_v_norm {
11395            return Some("V norm");
11396        }
11397        if self.weights.layers.iter().any(|lw| {
11398            lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some()
11399        }) {
11400            return Some("sandwich norms / layer scale");
11401        }
11402        None
11403    }
11404
11405    /// The wgpu graphs' attention geometry for layer `li` (virtual index):
11406    /// Some only for a model whose layers do not share one (MiMo-V2) — KV
11407    /// heads, V width, rotary width and RoPE table, window and sinks of
11408    /// THIS layer, exactly what the CPU attention reads for it.
11409    fn graph_attn_geom(&self, li: usize) -> Option<crate::gpu::GraphAttnGeom<'_>> {
11410        self.graph_attn_decline_reason()?;
11411        let (nkv, hd, rd) = self.layer_geom(li);
11412        let invf: &[f32] = if self.layer_is_local(li) {
11413            match &self.inv_freq_local {
11414                Some(f) => f.as_slice(),
11415                None => self.inv_freq.as_slice(),
11416            }
11417        } else {
11418            match &self.inv_freq_global {
11419                Some(f) => f.as_slice(),
11420                None => self.inv_freq.as_slice(),
11421            }
11422        };
11423        Some(crate::gpu::GraphAttnGeom {
11424            nkv,
11425            hd,
11426            dv: self.layer_v_dim(li),
11427            rd,
11428            invf,
11429            rope_scale: self.layer_rope_scale(li),
11430            window: self.layer_window(li),
11431            sink: self.kv_cache.layers[li].sinks.as_deref(),
11432            v_norm: self.attn_v_norm,
11433        })
11434    }
11435
11436    /// The decode graph's device K/V mirror that layer `li`'s batched
11437    /// prefill appends its chunk to and attends against (wgpu), instead
11438    /// of uploading the layer's whole K/V prefix every chunk and the whole
11439    /// cache again at the first decode token. Only where the token graph
11440    /// will read that very mirror: the decode graph on, not refused, and
11441    /// this layer's geometry what it requests (`graph_attn_geom`: KV heads,
11442    /// V as wide as K, the window as a ring, no sink).
11443    ///
11444    /// Spark-X2.5 only (`proj_gate_sigmoid`), the one architecture whose
11445    /// output was measured identical on it. `CMF_PREFILL_MIRROR=0` keeps
11446    /// the host upload (A/B).
11447    #[cfg(feature = "gpu")]
11448    fn prefill_mirror_target(&self, li: usize) -> Option<crate::gpu::PrefillMirror> {
11449        if !self.proj_gate_sigmoid
11450            || std::env::var("CMF_PREFILL_MIRROR").as_deref() == Ok("0")
11451            || !crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)
11452            || self.graph_refused()
11453            || self.o1_active()
11454            || self.attn_softcap > 0.0
11455            || self.wgpu_graph_attn_decline().is_some()
11456        {
11457            return None;
11458        }
11459        let g = self.graph_attn_geom(li)?;
11460        let (nkv, hd, _) = self.layer_geom(li);
11461        // The token graph passes the call-wide head width (layer 0's).
11462        if g.nkv != nkv || g.dv != hd || g.sink.is_some() || hd != self.layer_geom(0).1 {
11463            return None;
11464        }
11465        Some(crate::gpu::PrefillMirror {
11466            kv_id: self.graph_kv_id,
11467            layer: li,
11468            limit: self.kv_cache.max_seq_len,
11469        })
11470    }
11471
11472    /// Bring the host KV cache of every Full-attention layer in
11473    /// `[from, upto)` up to `position` rows from the wgpu mirrors, where a
11474    /// device graph advanced a layer that the host is about to run: a
11475    /// device prefix that shrank since the prompt (or a batched prefill
11476    /// prefix longer than the decode one). A layer whose mirror does not
11477    /// hold the missing rows is left alone. Rows a sliding layer's ring
11478    /// no longer holds come back as zeros — outside every window that
11479    /// will read them.
11480    #[cfg(feature = "gpu")]
11481    fn pull_lagging_host_kv(&mut self, from: usize, upto: usize, position: usize) {
11482        let kv_id = self.graph_kv_id;
11483        for li in from..upto.min(self.num_layers) {
11484            if !matches!(
11485                self.weights.layers[self.phys_layer(li)].attn,
11486                AttnKind::Full { .. }
11487            ) {
11488                continue;
11489            }
11490            // Absolute: a trimmed sliding tail holds positions base.. only.
11491            let host = self.kv_cache.layers[li].pos_len();
11492            if host >= position {
11493                continue;
11494            }
11495            let Some(dev) = crate::gpu::graph_kv_stored(kv_id, li) else {
11496                continue;
11497            };
11498            let to = dev.min(position);
11499            if to <= host {
11500                continue;
11501            }
11502            let (nkv, hd) = {
11503                let c = &self.kv_cache.layers[li];
11504                (c.num_kv_heads, c.head_dim)
11505            };
11506            let Some((k, v, first_valid)) =
11507                crate::gpu::graph_kv_pull_host(kv_id, li, host, to, nkv, hd)
11508            else {
11509                continue;
11510            };
11511            // A sliding layer only ever reads its last `window` rows; a
11512            // full-context layer needs every row it did not have.
11513            let need_from = match self.layer_window(li) {
11514                Some(w) => host.max((position + 1).saturating_sub(w)),
11515                None => host,
11516            };
11517            if first_valid > need_from {
11518                tracing::warn!(
11519                    "layer {li}: device KV rows {host}..{to} no longer resident \
11520                     (from {first_valid}); host attention will miss them"
11521                );
11522            }
11523            let row = nkv * hd;
11524            let cache = &mut self.kv_cache.layers[li];
11525            for p in 0..to - host {
11526                cache.append(&k[p * row..(p + 1) * row], &v[p * row..(p + 1) * row], &[]);
11527            }
11528        }
11529    }
11530
11531    /// Log (once per graph site and pipeline) that `site` declined for
11532    /// `reason`. The lines are kept so a caller or a test can read them.
11533    fn note_graph_decline(&self, site: &'static str, reason: &'static str) {
11534        let mut seen = self.graph_declines.borrow_mut();
11535        if !seen.iter().any(|&(s, r)| s == site && r == reason) {
11536            tracing::warn!("{site} declined: {reason} (CPU attention path)");
11537            seen.push((site, reason));
11538        }
11539    }
11540
11541    /// The GPU-graph declines this pipeline has logged so far, as the
11542    /// logged lines.
11543    pub fn graph_declines(&self) -> Vec<String> {
11544        self.graph_declines
11545            .borrow()
11546            .iter()
11547            .map(|(site, reason)| format!("{site} declined: {reason} (CPU attention path)"))
11548            .collect()
11549    }
11550
11551    /// Does layer `li` have the plain attention geometry the historical
11552    /// head-masked f32 path (`multi_head_attention`) assumes — pipeline-wide
11553    /// KV heads / head_dim / RoPE table, full context, no sink, V as wide
11554    /// as K? Anything else runs the dense `qwen_attention` instead.
11555    /// `CMF_LAYER_DUMP` writer (see `Pipeline::layer_dump`): one position's
11556    /// hidden after layer `li` as raw little-endian f32 into
11557    /// `<dir>/p{pos:06}_l{li:02}.f32`. A failed write is reported once and
11558    /// never stops the forward — the dump is a diagnostic.
11559    fn dump_layer_row(&self, pos: usize, li: usize, row: &[f32]) {
11560        let Some(dir) = &self.layer_dump else {
11561            return;
11562        };
11563        let mut bytes = Vec::with_capacity(row.len() * 4);
11564        for v in row {
11565            bytes.extend_from_slice(&v.to_le_bytes());
11566        }
11567        let path = dir.join(format!("p{pos:06}_l{li:02}.f32"));
11568        if let Err(e) = std::fs::create_dir_all(dir).and_then(|_| std::fs::write(&path, &bytes)) {
11569            use std::sync::atomic::{AtomicBool, Ordering};
11570            static SAID: AtomicBool = AtomicBool::new(false);
11571            if !SAID.swap(true, Ordering::Relaxed) {
11572                tracing::error!("CMF_LAYER_DUMP: cannot write {}: {e}", path.display());
11573            }
11574        }
11575    }
11576
11577    /// Decide the MiMo-V2 expert placement once (`crate::mimo_moe`). Any
11578    /// other model turns the slot off on the first call.
11579    fn mimo_moe_prepare(&mut self) {
11580        if !self.mimo_moe.is_undecided() {
11581            return;
11582        }
11583        let slot = {
11584            let layers: Vec<(usize, &MoeFfn)> = (0..self.num_layers)
11585                .filter_map(
11586                    |li| match &self.weights.layers.get(self.phys_layer(li))?.ffn {
11587                        FfnKind::Moe(m) => Some((li, m)),
11588                        _ => None,
11589                    },
11590                )
11591                .collect();
11592            // One bank lives on one device: an in-process multi-GPU split
11593            // keeps the whole-layer path.
11594            if layers.is_empty()
11595                || self.physical_layers != self.num_layers
11596                || self.gpu_plan.is_some()
11597            {
11598                crate::mimo_moe::Slot::Off
11599            } else {
11600                // Whether a whole-token graph could run this model's layers
11601                // (then a whole-layer prefix is one submit, not per-layer
11602                // fences).
11603                let graph_prefix =
11604                    self.wgpu_graph_attn_decline().is_none() && crate::gpu::wgpu_graph_default();
11605                crate::mimo_moe::Slot::decide(&layers, self.num_layers, graph_prefix)
11606            }
11607        };
11608        self.mimo_moe = slot;
11609    }
11610
11611    #[cfg(test)]
11612    pub(crate) fn test_graph_kv_id(&self) -> u64 {
11613        self.graph_kv_id
11614    }
11615
11616    /// Dynamic MiMo layer: one device attention graph, followed by a bank
11617    /// frame. Both decode and short verification use this same attention
11618    /// path and absolute layer key; the host KV may intentionally lag.
11619    pub(crate) fn mimo_graph_layer_rows(
11620        &mut self,
11621        li: usize,
11622        h: &mut [f32],
11623        positions: &[usize],
11624    ) -> crate::gpu::BatchGraphOutcome {
11625        use crate::gpu::BatchGraphOutcome as Out;
11626        let b = positions.len();
11627        if !(1..=4).contains(&b)
11628            || h.len() != b * self.hidden_size
11629            || !self.mimo_moe.is_dynamic(li, true)
11630            || !crate::gpu::enabled_here()
11631            || !crate::gpu::wgpu_active()
11632            || self.o1_active()
11633            || self.physical_layers != self.num_layers
11634            // The pair-fusion diagnostic (and an explicit graph-off run)
11635            // rewinds only host KV. A hidden singleton attention graph here
11636            // would leave device mirrors ahead of the next host position.
11637            || std::env::var("CMF_GPU_WGPU_GRAPH").as_deref() == Ok("0")
11638            || std::env::var("CMF_MIMO_ATTN_GRAPH").as_deref() == Ok("0")
11639            || self.wgpu_graph_attn_decline().is_some()
11640        {
11641            return Out::Declined;
11642        }
11643        let attn_started = std::time::Instant::now();
11644        let outcome = {
11645            let lw = &self.weights.layers[li];
11646            if lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some() {
11647                return Out::Declined;
11648            }
11649            let FfnKind::Moe(m) = &lw.ffn else {
11650                return Out::Declined;
11651            };
11652            let AttnKind::Full {
11653                wq,
11654                wk,
11655                wv,
11656                wo,
11657                q_norm,
11658                k_norm,
11659                output_gate,
11660                softplus_gate,
11661                bias,
11662            } = &lw.attn
11663            else {
11664                return Out::Declined;
11665            };
11666            if *output_gate || softplus_gate.is_some() {
11667                return Out::Declined;
11668            }
11669            let Some(model) = wq.graph_weight().map(|(m, ..)| m.clone()).or_else(|| {
11670                m.experts
11671                    .first()?
11672                    .gate_proj
11673                    .mapped_q4tp()
11674                    .map(|(m, _)| m.clone())
11675            }) else {
11676                return Out::Declined;
11677            };
11678            fn gw<'a>(
11679                t: &'a QTensor,
11680                owner: &std::sync::Arc<cortiq_core::CmfModel>,
11681            ) -> Option<crate::gpu::GraphW<'a>> {
11682                if let Some((m, idx, kind, rs)) = t.graph_weight() {
11683                    if m.uid() != owner.uid() || t.has_prism_contract() {
11684                        return None;
11685                    }
11686                    return Some(crate::gpu::GraphW {
11687                        idx,
11688                        kind,
11689                        row_scale: rs,
11690                        data: &[],
11691                        prism: crate::gpu::GraphPrismOp::None,
11692                        affine: false,
11693                    });
11694                }
11695                t.as_f32().map(|data| crate::gpu::GraphW {
11696                    idx: 0,
11697                    kind: 4,
11698                    row_scale: &[],
11699                    data,
11700                    prism: crate::gpu::GraphPrismOp::None,
11701                    affine: false,
11702                })
11703            }
11704            let (Some(q), Some(k), Some(v), Some(o)) = (
11705                gw(wq, &model),
11706                gw(wk, &model),
11707                gw(wv, &model),
11708                gw(wo, &model),
11709            ) else {
11710                return Out::Declined;
11711            };
11712            let layer = crate::gpu::GraphLayer {
11713                input_norm: &lw.input_norm,
11714                post_norm: &lw.post_norm,
11715                attn_out_norm: None,
11716                ffn_out_norm: None,
11717                layer_scale: None,
11718                ffn: crate::gpu::GraphFfn::AttentionOnly,
11719                attn: crate::gpu::GraphAttn::Full {
11720                    wq: q,
11721                    wk: k,
11722                    wv: v,
11723                    wo: o,
11724                    q_norm: q_norm.as_deref(),
11725                    k_norm: k_norm.as_deref(),
11726                    late_qk_norm: self.qk_norm_after_rope,
11727                    bias: bias
11728                        .as_ref()
11729                        .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice())),
11730                    output_gate: false,
11731                    cpu_k: self.kv_cache.layers[li].k_heads(),
11732                    cpu_v: self.kv_cache.layers[li].v_heads(),
11733                    cpu_base: self.kv_cache.layers[li].base(),
11734                    geom: self.graph_attn_geom(li),
11735                    head_gate: None,
11736                },
11737            };
11738            let (nkv, hd, rd) = self.layer_geom(li);
11739            crate::gpu::forward_batch_graph_at(
11740                &model,
11741                self.graph_kv_id,
11742                li,
11743                &[layer],
11744                &self.inv_freq,
11745                h,
11746                self.layer_num_heads(li),
11747                nkv,
11748                hd,
11749                rd,
11750                self.hidden_size,
11751                1,
11752                positions,
11753                self.kv_cache.max_seq_len,
11754                self.norm_style == cortiq_core::NormStyle::Gemma,
11755                self.rms_eps as f32,
11756                self.attn_scale,
11757                b,
11758                &[],
11759                self.o1_epoch,
11760                None,
11761                None,
11762            )
11763        };
11764        match outcome {
11765            Out::Completed => {}
11766            Out::Declined => return Out::Declined,
11767            Out::Failed => {
11768                self.graph_failed
11769                    .store(true, std::sync::atomic::Ordering::Relaxed);
11770                return Out::Failed;
11771            }
11772        }
11773        let attn_ns = attn_started.elapsed().as_nanos() as u64;
11774        let hs = self.hidden_size;
11775        let lw = &self.weights.layers[li];
11776        let FfnKind::Moe(m) = &lw.ffn else {
11777            unreachable!()
11778        };
11779        let mut post = vec![0.0; h.len()];
11780        for (x, y) in h.chunks_exact(hs).zip(post.chunks_exact_mut(hs)) {
11781            inference::rms_norm_into(x, &lw.post_norm, self.rms_eps, self.norm_style, y);
11782        }
11783        let mut ffn = if b == 1 {
11784            moe_ffn_banked(&mut self.mimo_moe, li, m, &post, self.pool.as_deref())
11785        } else {
11786            moe_ffn_banked_rows(
11787                &mut self.mimo_moe,
11788                li,
11789                m,
11790                &post,
11791                b,
11792                hs,
11793                self.pool.as_deref(),
11794            )
11795        };
11796        for (x, &f) in h.iter_mut().zip(&ffn) {
11797            *x += f;
11798        }
11799        attention::recycle_buf(&mut ffn);
11800        if self.layer_dump.is_some() {
11801            for (&pos, row) in positions.iter().zip(h.chunks_exact(hs)) {
11802                self.dump_layer_row(pos, li, row);
11803            }
11804        }
11805        crate::mimo_moe::note_attention_graph(b, attn_ns);
11806        Out::Completed
11807    }
11808
11809    fn layer_attn_plain(&self, li: usize) -> bool {
11810        self.kv_heads_per_layer.is_none()
11811            && self.v_head_dim.is_none()
11812            && self.global_attn.is_none()
11813            && self.layer_window(li).is_none()
11814            && self.kv_cache.layers[li].sinks.is_none()
11815    }
11816
11817    /// Forward one position through all layers (hybrid dispatch).
11818    fn forward_layers(
11819        &mut self,
11820        hidden: &[f32],
11821        position: usize,
11822        task_mask: Option<&TaskMask>,
11823    ) -> Vec<f32> {
11824        let out = self.forward_layers_upto(hidden, position, task_mask, None);
11825        self.o1_progress();
11826        self.swa_trim_tails();
11827        out
11828    }
11829
11830    // ── Network pipeline-split building blocks (coordinator/worker) ──
11831    // A remote worker owns layers [from ..= upto] and their KV; the
11832    // coordinator owns the rest plus embed / final norm / head. Attention
11833    // causality is per-layer, so a whole prompt's boundary hiddens ship
11834    // as one batch and decode ships one vector per token.
11835
11836    /// Embed one token id (embed multiplier applied).
11837    pub fn embed_id(&self, id: u32) -> Vec<f32> {
11838        self.embed_single(id)
11839    }
11840
11841    /// Refuse the archs/modes whose forward cannot be cut at a layer
11842    /// boundary. Loud by design: a split that silently changed the math
11843    /// would be a chimera.
11844    pub fn split_supported(&self) -> Result<(), String> {
11845        if self.dsv4.is_some() {
11846            return Err(
11847                "network split: DeepSeek-V4 runs its own fused stack (not splittable yet)".into(),
11848            );
11849        }
11850        if self.dsv41.is_some() {
11851            return Err(
11852                "network split: DeepSeek-V4.1 owns the shared CED/CSA2 state (not splittable)"
11853                    .into(),
11854            );
11855        }
11856        if self.qwen4_exp.is_some() {
11857            return Err(
11858                "network split: Qwen3.8-Flash-Next hyper/QSA stack is not splittable yet".into(),
11859            );
11860        }
11861        if self.per_token_stack() {
11862            return Err(
11863                "network split: the per-token stack (gemma-3n AltUp / gemma-4 E-series) is not splittable yet".into(),
11864            );
11865        }
11866        Ok(())
11867    }
11868
11869    /// Forward `hidden` through layers [from ..= upto] at `position`,
11870    /// appending those layers' KV/state. Both split sides call this
11871    /// over their own range; a task mask applies to the span's own
11872    /// layers (each side masks what it runs).
11873    pub fn forward_span(
11874        &mut self,
11875        hidden: &[f32],
11876        position: usize,
11877        from: usize,
11878        upto: usize,
11879        task_mask: Option<&TaskMask>,
11880    ) -> Result<Vec<f32>, String> {
11881        self.split_supported()?;
11882        if from > upto || upto >= self.num_layers {
11883            return Err(format!(
11884                "forward_span: layer range {from}..={upto} outside 0..{}",
11885                self.num_layers
11886            ));
11887        }
11888        if hidden.len() != self.hidden_size {
11889            return Err(format!(
11890                "forward_span: hidden len {} ≠ hidden_size {}",
11891                hidden.len(),
11892                self.hidden_size
11893            ));
11894        }
11895        let out = self.forward_layers_span(hidden, position, task_mask, from, Some(upto));
11896        self.o1_progress();
11897        self.swa_trim_tails();
11898        if self
11899            .graph_failed
11900            .swap(false, std::sync::atomic::Ordering::Relaxed)
11901        {
11902            self.cancel
11903                .store(false, std::sync::atomic::Ordering::Relaxed);
11904            self.clear_sequence_state();
11905            return Err("forward_span: deferred O(1) transition failed".into());
11906        }
11907        Ok(out)
11908    }
11909
11910    /// Final norm + lm_head over a boundary hidden (the final-logit
11911    /// softcap is applied by lm_head_forward itself).
11912    pub fn logits_from_hidden(&mut self, hidden: &[f32]) -> Vec<f32> {
11913        let normed = inference::rms_norm(
11914            hidden,
11915            &self.weights.final_norm,
11916            self.rms_eps,
11917            self.norm_style,
11918        );
11919        self.lm_head_forward(&normed)
11920    }
11921
11922    /// Sample the next token with this pipeline's sampler state.
11923    pub fn sample_next(&mut self, logits: &[f32], past_tokens: &[u32]) -> u32 {
11924        sampler::sample_with_scratch(
11925            logits,
11926            &self.sampler_config,
11927            past_tokens,
11928            &mut self.rng,
11929            &mut self.sampler_scratch,
11930        )
11931    }
11932
11933    /// Fresh sequence: clear KV, reuse history and device mirrors.
11934    pub fn reset_session(&mut self) {
11935        self.clear_sequence_state();
11936    }
11937
11938    /// Batched span prefill from token ids (coordinator side): embed +
11939    /// layers [0 ..= upto]; returns the boundary hiddens of ALL positions
11940    /// (ids.len() × hidden). Rides the same layer-major machinery as the
11941    /// local prefill; falls back to the per-position walk under
11942    /// CMF_PREFILL=seq.
11943    pub fn prefill_span_ids(
11944        &mut self,
11945        ids: &[u32],
11946        start_pos: usize,
11947        upto: usize,
11948        task_mask: Option<&TaskMask>,
11949    ) -> Result<Vec<f32>, String> {
11950        self.split_supported()?;
11951        if upto >= self.num_layers {
11952            return Err(format!(
11953                "prefill_span_ids: upto {upto} outside 0..{}",
11954                self.num_layers
11955            ));
11956        }
11957        // Same predicate as the whole-stack prefill: a span whose GDN
11958        // state lives on the device must walk positions through the
11959        // graph, not through the batched CPU span.
11960        if self.can_prefill_batched() && !self.graph_prefill_preferred() {
11961            let out =
11962                self.prefill_batch_span(PrefillIn::Ids(ids), start_pos, task_mask, 0, upto + 1);
11963            self.check_o1_progress_failure("prefill_span_ids")?;
11964            Ok(out)
11965        } else {
11966            let hs = self.hidden_size;
11967            let mut out = Vec::with_capacity(ids.len() * hs);
11968            for (i, &id) in ids.iter().enumerate() {
11969                let emb = self.embed_id(id);
11970                out.extend_from_slice(&self.forward_span(
11971                    &emb,
11972                    start_pos + i,
11973                    0,
11974                    upto,
11975                    task_mask,
11976                )?);
11977            }
11978            Ok(out)
11979        }
11980    }
11981
11982    /// Batched span prefill from boundary hiddens (worker side): layers
11983    /// [from ..= upto] for every position in the batch; returns the batch.
11984    pub fn prefill_span_hidden(
11985        &mut self,
11986        hidden: &[f32],
11987        start_pos: usize,
11988        from: usize,
11989        upto: usize,
11990        task_mask: Option<&TaskMask>,
11991    ) -> Result<Vec<f32>, String> {
11992        self.split_supported()?;
11993        let hs = self.hidden_size;
11994        if hidden.is_empty() || hidden.len() % hs != 0 {
11995            return Err(format!(
11996                "prefill_span_hidden: {} floats is not a multiple of hidden {hs}",
11997                hidden.len()
11998            ));
11999        }
12000        if from > upto || upto >= self.num_layers {
12001            return Err(format!(
12002                "prefill_span_hidden: layer range {from}..={upto} outside 0..{}",
12003                self.num_layers
12004            ));
12005        }
12006        if self.can_prefill_batched() && !self.graph_prefill_preferred() {
12007            let out = self.prefill_batch_span(
12008                PrefillIn::Hidden(hidden),
12009                start_pos,
12010                task_mask,
12011                from,
12012                upto + 1,
12013            );
12014            self.check_o1_progress_failure("prefill_span_hidden")?;
12015            Ok(out)
12016        } else {
12017            let b = hidden.len() / hs;
12018            let mut out = Vec::with_capacity(hidden.len());
12019            for i in 0..b {
12020                let h = self.forward_span(
12021                    &hidden[i * hs..(i + 1) * hs],
12022                    start_pos + i,
12023                    from,
12024                    upto,
12025                    task_mask,
12026                )?;
12027                out.extend_from_slice(&h);
12028            }
12029            Ok(out)
12030        }
12031    }
12032
12033    /// Build the whole-token wgpu graph for a pure-attention q1 model (every
12034    /// layer Full q1 + dense q1 FFN, no gate/bias). Returns the post-stack
12035    /// hidden (caller does final norm + lm_head), or None to fall back.
12036    fn try_token_graph_wgpu(
12037        &self,
12038        hidden: &[f32],
12039        position: usize,
12040        logits_out: &mut Vec<f32>,
12041        layers_run: &mut usize,
12042    ) -> Option<Result<Vec<f32>, ()>> {
12043        self.try_token_graph_wgpu_steps(
12044            hidden,
12045            position,
12046            logits_out,
12047            1,
12048            None,
12049            Some(layers_run),
12050            0,
12051            self.num_layers,
12052        )
12053    }
12054
12055    /// The span twin (network split): the graph covers [from..upto_excl)
12056    /// — one submit per SEGMENT per token. lm_head folds in only when
12057    /// the span reaches the last layer.
12058    fn try_token_graph_wgpu_span(
12059        &self,
12060        hidden: &[f32],
12061        position: usize,
12062        logits_out: &mut Vec<f32>,
12063        from: usize,
12064        upto_excl: usize,
12065        layers_run: &mut usize,
12066    ) -> Option<Result<Vec<f32>, ()>> {
12067        self.try_token_graph_wgpu_steps(
12068            hidden,
12069            position,
12070            logits_out,
12071            1,
12072            None,
12073            Some(layers_run),
12074            from,
12075            upto_excl,
12076        )
12077    }
12078
12079    /// The pooled tail's device lm_head: final-norm + head as one
12080    /// layer-less graph pass, so decode stops paying the double-digit
12081    /// millisecond host matvec every token. `None` keeps the host head.
12082    #[cfg(feature = "gpu")]
12083    fn m3_device_logits(&self, hidden: &[f32]) -> Option<Vec<f32>> {
12084        if !crate::minicpm_tail::minimax_pool_on()
12085            || !crate::gpu::enabled_here()
12086            || self.head_clusters.is_some()
12087            || self.graph_failed.load(std::sync::atomic::Ordering::Relaxed)
12088            || std::env::var("CMF_GPU_LMHEAD").map(|v| v != "0") == Ok(false)
12089        {
12090            return None;
12091        }
12092        let (model, i, kind, rs) = self
12093            .weights
12094            .lm_head
12095            .graph_weight()
12096            .or_else(|| self.weights.lm_head.graph_weight_descriptor())?;
12097        let name = &model.tensors[i].name;
12098        let prism = if crate::prism::is_inverse_embedding(&model, name) {
12099            crate::gpu::GraphPrismOp::InverseEmbedding
12100        } else if crate::prism::is_forward_weight(&model, name) {
12101            crate::gpu::GraphPrismOp::Forward
12102        } else {
12103            crate::gpu::GraphPrismOp::None
12104        };
12105        let gw = crate::gpu::GraphW {
12106            idx: i,
12107            kind,
12108            row_scale: rs,
12109            data: &[],
12110            prism,
12111            affine: crate::prism::is_affine_target(&model, name),
12112        };
12113        let rows = self.weights.lm_head.rows();
12114        let mut h = hidden.to_vec();
12115        let mut lg = Vec::new();
12116        let mut layers_run = 0usize;
12117        let outcome = crate::gpu::forward_token_graph(
12118            &model,
12119            self.graph_kv_id,
12120            &[],
12121            &[],
12122            self.o1_epoch,
12123            &self.inv_freq,
12124            &mut h,
12125            self.num_heads,
12126            self.num_kv_heads,
12127            self.head_dim,
12128            self.attn_scale,
12129            self.head_dim,
12130            self.hidden_size,
12131            self.intermediate_size,
12132            0,
12133            self.kv_cache.max_seq_len,
12134            self.norm_style == cortiq_core::NormStyle::Gemma,
12135            self.rms_eps as f32,
12136            Some((&gw, rows)),
12137            &self.weights.final_norm,
12138            &mut lg,
12139            &[],
12140            1,
12141            None,
12142            None,
12143            Some(&mut layers_run),
12144            0,
12145            false,
12146        );
12147        if outcome != crate::gpu::TokenGraphOutcome::Completed || lg.is_empty() {
12148            return None;
12149        }
12150        // The same post-steps the host head applies — keep sampling
12151        // identical whichever arm produced the logits.
12152        lg.resize(self.vocab_size, 0.0);
12153        if let Some(m) = self.logit_multiplier {
12154            for l in lg.iter_mut() {
12155                *l *= m;
12156            }
12157        }
12158        if let Some(c) = self.final_softcap {
12159            softcap_in_place(&mut lg, c, self.pool.as_deref());
12160        }
12161        Some(lg)
12162    }
12163
12164    /// Record one token-layer's winners into the route-frequency profile and
12165    /// write it out every 16 tokens when `CMF_M3_PROFILE_SAVE=<path>` is set.
12166    fn m3_note_route(&mut self, li: usize, winners: &[u32]) {
12167        if winners.is_empty() {
12168            return;
12169        }
12170        if self.m3_n_exp == 0 {
12171            self.m3_n_exp = crate::minicpm_tail::minimax_n_experts(&self.weights.layers, self.phys_layer(0)).max(1);
12172            self.m3_counts = vec![0; self.num_layers * self.m3_n_exp];
12173        }
12174        for &e in winners {
12175            let e = e as usize;
12176            if e < self.m3_n_exp && li < self.num_layers {
12177                self.m3_counts[li * self.m3_n_exp + e] = self.m3_counts[li * self.m3_n_exp + e].saturating_add(1);
12178            }
12179        }
12180        if li + 1 == self.num_layers {
12181            self.m3_tokens += 1;
12182            if self.m3_tokens % 16 == 0 {
12183                if let Ok(path) = std::env::var("CMF_M3_PROFILE_SAVE") {
12184                    let bytes: Vec<u8> = self.m3_counts.iter().flat_map(|c| c.to_le_bytes()).collect();
12185                    let _ = std::fs::write(&path, bytes);
12186                }
12187            }
12188        }
12189    }
12190
12191    /// Admit the most frequent (layer, expert) pairs of a saved profile into
12192    /// the bank before the first token: `CMF_M3_PROFILE=<path>` names the
12193    /// file, `CMF_M3_PREWARM_N` (default 300) bounds how many experts go in.
12194    /// The bank's own eviction stays in charge; prewarm only chooses order.
12195    fn m3_prewarm(&mut self) {
12196        let Ok(path) = std::env::var("CMF_M3_PROFILE") else {
12197            return;
12198        };
12199        let Ok(bytes) = std::fs::read(&path) else {
12200            tracing::warn!("m3 prewarm: cannot read profile {path}");
12201            return;
12202        };
12203        let counts: Vec<u32> = bytes
12204            .chunks_exact(4)
12205            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
12206            .collect();
12207        let n_exp = crate::minicpm_tail::minimax_n_experts(&self.weights.layers, self.phys_layer(0)).max(1);
12208        if counts.len() != self.num_layers * n_exp {
12209            tracing::warn!("m3 prewarm: profile size {} does not match {}x{}", counts.len(), self.num_layers, n_exp);
12210            return;
12211        }
12212        let limit: usize = std::env::var("CMF_M3_PREWARM_N")
12213            .ok()
12214            .and_then(|v| v.parse().ok())
12215            .unwrap_or(300);
12216        let mut ranked: Vec<(u32, usize, usize)> = counts
12217            .iter()
12218            .enumerate()
12219            .filter(|(_, c)| **c > 0)
12220            .map(|(i, &c)| (c, i / n_exp, i % n_exp))
12221            .collect();
12222        ranked.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)).then(a.2.cmp(&b.2)));
12223        ranked.truncate(limit);
12224        let mut per_layer: Vec<Vec<usize>> = vec![Vec::new(); self.num_layers];
12225        for (_, li, e) in ranked {
12226            per_layer[li].push(e);
12227        }
12228        let mut admitted = 0usize;
12229        for (li, ids) in per_layer.iter().enumerate() {
12230            if ids.is_empty() {
12231                continue;
12232            }
12233            let lw = &self.weights.layers[self.phys_layer(li)];
12234            let FfnKind::Moe(m) = &lw.ffn else {
12235                continue;
12236            };
12237            // Arming installs the layer's layout; nothing predicted yet.
12238            let _ = crate::minicpm_tail::minimax_pool_arm(m, li, self.num_layers, &[]);
12239            if crate::minicpm_tail::minimax_pool_ensure(m, li, self.num_layers, ids) {
12240                admitted += ids.len();
12241            }
12242        }
12243        tracing::info!("m3 prewarm: admitted {admitted} experts from {path}");
12244    }
12245
12246    /// One MiniMax tail layer through the pooled token-graph arm: attention,
12247    /// the pre-FFN norm, device routing and the descriptor-indexed expert
12248    /// bank in ONE submit (one sync instead of host attention + a MoE
12249    /// frame), with cold experts finished on the host against the read-back
12250    /// FFN input and admitted for the next token.
12251    ///
12252    /// `Ok(true)` — the layer is done (hidden replaced). `Ok(false)` —
12253    /// decline before any device mutation; the ordinary host path owns this
12254    /// position. `Err(())` — the device failed after admission; the caller
12255    /// must stop the sequence exactly like a failed span run.
12256    #[cfg(feature = "gpu")]
12257    fn m3_pooled_layer(&mut self, li: usize, position: usize, h: &mut Vec<f32>) -> Result<bool, ()> {
12258        if self.o1_active() || self.attn_softcap > 0.0 {
12259            return Ok(false);
12260        }
12261        if !self.m3_prewarmed {
12262            self.m3_prewarmed = true;
12263            self.m3_prewarm();
12264        }
12265        let frame = {
12266            let lw = &self.weights.layers[self.phys_layer(li)];
12267            let FfnKind::Moe(m) = &lw.ffn else {
12268                return Ok(false);
12269            };
12270            if !crate::minicpm_tail::MiniCpmTail::is_requested_target(m) {
12271                return Ok(false);
12272            }
12273            let t_arm = std::time::Instant::now();
12274            if self.m3_winners.len() != self.num_layers {
12275                self.m3_winners = vec![Vec::new(); self.num_layers];
12276            }
12277            let pred = std::mem::take(&mut self.m3_winners[li]);
12278            let armed = crate::minicpm_tail::minimax_pool_arm(m, li, self.num_layers, &pred);
12279            if armed.is_none() {
12280                self.m3_winners[li] = pred; // declined before anything ran
12281            }
12282            M3_ARM_NS.fetch_add(t_arm.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
12283            match armed {
12284                Some(frame) => frame,
12285                // First-call refusal (geometry/bank): the host layer still
12286                // runs; nothing was mutated.
12287                None => return Ok(false),
12288            }
12289        };
12290        crate::gpu_wgpu::pooled_frame_enter(frame);
12291        // The pooled call must not fold lm_head: its cold experts have to
12292        // land before any final norm. The decode loop re-arms this flag for
12293        // the next position anyway.
12294        let want_logits = self.graph_want_logits;
12295        self.graph_want_logits = false;
12296        let mut lg = Vec::new();
12297        let mut gl = 0usize;
12298        let t_span = std::time::Instant::now();
12299        let span = crate::gpu::gpu_scope(|| {
12300            self.try_token_graph_wgpu_span(h, position, &mut lg, li, li + 1, &mut gl)
12301        });
12302        self.graph_want_logits = want_logits;
12303        M3_SPAN_NS.fetch_add(t_span.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
12304        let hh = match span {
12305            Some(Ok(hh)) => hh,
12306            Some(Err(())) => return Err(()),
12307            None => {
12308                // Declined before submission (seed/resolve/refusal): the
12309                // device mirror has not moved, so the host path is exact.
12310                return Ok(false);
12311            }
12312        };
12313        if gl != 1 {
12314            // A single-layer run that reports no layer mutated nothing we
12315            // may build on; anything else is a contract break.
12316            return if gl == 0 { Ok(false) } else { Err(()) };
12317        }
12318        *h = hh;
12319        let winners = crate::gpu_wgpu::pooled_frame_take_winners();
12320        self.m3_note_route(li, &winners);
12321        if self.m3_winners.len() != self.num_layers {
12322            self.m3_winners = vec![Vec::new(); self.num_layers];
12323        }
12324        self.m3_winners[li] = winners;
12325        let mut cold = crate::gpu_wgpu::pooled_frame_take_cold();
12326        // A non-finite parsed weight would poison the residual for the rest
12327        // of the sequence — drop such entries loudly instead.
12328        cold.retain(|&(_, w)| {
12329            if w.is_finite() {
12330                true
12331            } else {
12332                tracing::error!("pooled tail: non-finite cold weight from expert route");
12333                false
12334            }
12335        });
12336        if cold.is_empty() {
12337            return Ok(true);
12338        }
12339        let x = crate::gpu_wgpu::pooled_frame_take_input();
12340        if x.len() != self.hidden_size {
12341            return Err(());
12342        }
12343        // Cold experts: on the device first (admit, then one prepared frame
12344        // over exactly those slots — one submit for the layer). The host
12345        // computes them only when the device declines, and then they are
12346        // admitted for the next token. `CMF_M3_COLD_CPU=1` forces the host
12347        // arm for an A/B measurement.
12348        let lw = &self.weights.layers[self.phys_layer(li)];
12349        let FfnKind::Moe(m) = &lw.ffn else {
12350            return Err(());
12351        };
12352        let t_cold = std::time::Instant::now();
12353        let force_host = std::env::var("CMF_M3_COLD_CPU").as_deref() == Ok("1");
12354        let mut out = crate::attention::take_buf(self.hidden_size);
12355        let on_device = !force_host
12356            && crate::minicpm_tail::minimax_cold_device(m, li, self.num_layers, &cold, &x, &mut out);
12357        if !on_device {
12358            crate::attention::recycle_buf(&mut out);
12359            let jobs: Vec<(&crate::pipeline::DenseFfn, f32)> = cold
12360                .iter()
12361                .map(|&(e, w)| m.experts.get(e).map(|ex| (ex, w)).ok_or(()))
12362                .collect::<Result<_, ()>>()?;
12363            out = crate::gpu::cpu_scope(|| {
12364                crate::pipeline::moe_cold_experts_cpu(&jobs, &x, self.pool.as_deref())
12365            });
12366            let ids: Vec<usize> = cold.iter().map(|&(e, _)| e).collect();
12367            let _ = crate::minicpm_tail::minimax_pool_ensure(m, li, self.num_layers, &ids);
12368        }
12369        M3_COLD_NS.fetch_add(t_cold.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
12370        M3_COLD_N.fetch_add(cold.len() as u64, std::sync::atomic::Ordering::Relaxed);
12371        if out.len() != h.len() {
12372            crate::attention::recycle_buf(&mut out);
12373            return Err(());
12374        }
12375        for (dst, src) in h.iter_mut().zip(out.iter()) {
12376            *dst += src;
12377        }
12378        crate::attention::recycle_buf(&mut out);
12379        if on_device {
12380            M3_COLD_DEV_N.fetch_add(cold.len() as u64, std::sync::atomic::Ordering::Relaxed);
12381        }
12382        Ok(true)
12383    }
12384
12385    #[cfg(not(feature = "gpu"))]
12386    fn m3_pooled_layer(
12387        &mut self,
12388        _li: usize,
12389        _position: usize,
12390        _h: &mut Vec<f32>,
12391    ) -> Result<bool, ()> {
12392        Ok(false)
12393    }
12394
12395    /// Greedy burst: forward `t_next` and let the device pick + re-embed
12396    /// the next k−1 tokens — k frames, ONE submit, k ids back. The ZML
12397    /// trade, on wgpu. None ⇒ caller keeps the per-token path.
12398    fn try_multi_burst(&self, t_next: u32, position: usize, k: usize) -> Option<Vec<u32>> {
12399        if self.o1_active() || self.attn_softcap > 0.0 {
12400            return None;
12401        }
12402        // The burst builds the whole-token graph; attention the graph's
12403        // per-layer geometry cannot express keeps the per-token path.
12404        if let Some(reason) = self.wgpu_graph_attn_decline() {
12405            self.note_graph_decline("wgpu multi-burst", reason);
12406            return None;
12407        }
12408        let graph_on = crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode);
12409        if !graph_on || self.graph_refused() {
12410            // Same memo as the decode site: this path builds the very
12411            // same graph, so a model it cannot build for must not be
12412            // walked again here either. Missing this guard was worth
12413            // 2.5x on an Adreno — 0.361 tok/s against 0.905 — because
12414            // the burst retried per token what decode had already given
12415            // up on.
12416            return None;
12417        }
12418        let emb = self.embed_single(t_next);
12419        let mut lg = Vec::new();
12420        let mut ids = Vec::new();
12421        match self.try_token_graph_wgpu_steps(
12422            &emb,
12423            position,
12424            &mut lg,
12425            k,
12426            Some(&mut ids),
12427            None,
12428            0,
12429            self.num_layers,
12430        ) {
12431            Some(Ok(_)) => {}
12432            Some(Err(())) => {
12433                // Preserve the backend's post-admission failure through the
12434                // Option-based burst API.  The decode caller consumes this
12435                // flag and clears the sequence instead of falling through
12436                // to a stale CPU recurrent state.
12437                self.graph_failed
12438                    .store(true, std::sync::atomic::Ordering::Relaxed);
12439                return None;
12440            }
12441            None => return None,
12442        }
12443        (ids.len() == k).then_some(ids)
12444    }
12445
12446    /// Multi-step greedy: k whole frames in ONE submit, argmax and re-embed
12447    /// on the device. `ids_out` receives the k winner ids; the hidden/logits
12448    /// outputs are NOT produced in that mode.
12449    fn try_token_graph_wgpu_steps(
12450        &self,
12451        hidden: &[f32],
12452        position: usize,
12453        logits_out: &mut Vec<f32>,
12454        steps: usize,
12455        ids_out: Option<&mut Vec<u32>>,
12456        layers_run: Option<&mut usize>,
12457        from: usize,
12458        upto_excl: usize,
12459    ) -> Option<Result<Vec<f32>, ()>> {
12460        // The bank has already reserved its VRAM. Never build a second
12461        // all-expert arena across bank-owned layers (including bursts).
12462        let upto_excl = match self.mimo_moe.graph_prefix_end() {
12463            Some(end) if end < upto_excl => {
12464                if steps != 1 || layers_run.is_none() || from >= end {
12465                    return None;
12466                }
12467                end
12468            }
12469            _ => upto_excl,
12470        };
12471        // O(1) Nyström decode runs off the sealed state, not the KV cache the
12472        // graph mirrors — never take the graph while o1 is active.
12473        let o1_gpu = std::env::var("CMF_O1_GPU").as_deref() == Ok("1");
12474        if (self.o1_active() && !o1_gpu) || self.attn_softcap > 0.0 {
12475            // Softcapped scores have no graph kernel yet — CPU owns them.
12476            // o1 rides the graph only behind CMF_O1_GPU=1 while the port
12477            // proves itself; without it the CPU path owns o1 as before.
12478            return None;
12479        }
12480        // Per-layer KV heads, narrow V, sinks and sliding windows ride
12481        // `GraphAttn::Full::geom` (the ATTEND_X kernels). Anything that
12482        // geometry cannot express declines here, by name — before the
12483        // per-layer gate existed a sliding/sink model ran the graph as
12484        // full-context attention, fluent and wrong. The caller memoizes
12485        // the refusal.
12486        if let Some(reason) = self.wgpu_graph_attn_decline() {
12487            self.note_graph_decline("wgpu token graph", reason);
12488            return None;
12489        }
12490        // Per-layer sealed o1 state for the graph. During prefill the
12491        // state is still Collecting -> views are None -> the graph
12492        // refuses below and the CPU prefill records the q trace and
12493        // seals, exactly as the o1 design requires.
12494        let o1_views: Vec<Option<Vec<crate::nystrom::O1DeviceView<'_>>>> = (from..upto_excl)
12495            .map(|li| {
12496                if !o1_gpu {
12497                    return None;
12498                }
12499                self.kv_cache.layers[self.phys_layer(li)].o1_views()
12500            })
12501            .collect();
12502        if self.o1_active() && o1_gpu {
12503            // Any o1 layer not sealed (or degenerate exact-only) keeps the
12504            // whole token on the CPU: half-graph forwards would desync.
12505            let want: usize = (from..upto_excl)
12506                .filter(|li| self.kv_cache.layers[self.phys_layer(*li)].o1.is_some())
12507                .count();
12508            let have = o1_views.iter().filter(|v| v.is_some()).count();
12509            if want == 0 || have != want {
12510                // The silent twin of the gpu-side o1 gates, found the
12511                // same way: a 15x decode drop with an empty log. Views
12512                // stay None until the layer's state SEALS, so `have`
12513                // lagging `want` early in a run is the o1 design working
12514                // — but it must say so, or the next reader spends a
12515                // night proving the kernels innocent.
12516                // On CHANGE, not once: the first decline is the legal
12517                // unsealed prefill, and a once-print buries the state
12518                // that matters — what the count reads AFTER the seal.
12519                use std::sync::atomic::{AtomicUsize, Ordering};
12520                static LAST: AtomicUsize = AtomicUsize::new(usize::MAX);
12521                let code = have * 1000 + want;
12522                if LAST.swap(code, Ordering::Relaxed) != code {
12523                    tracing::warn!(
12524                        "o1 graph: {have} of {want} layers sealed — per-op until all seal"
12525                    );
12526                }
12527                return None;
12528            }
12529        }
12530        let nh = self.num_heads;
12531        let (nkv, hd, rd) = self.layer_geom(0);
12532        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
12533        let mut layers = Vec::with_capacity(upto_excl - from);
12534        let mut model = None;
12535        let dbg = std::env::var("CMF_GRAPH_DEBUG").is_ok();
12536        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
12537            // `blr` rides as GRAPH_KIND_BLR (two stage dispatches).
12538            if let Some((m, i, kind, rs)) = t.graph_weight_or_blr() {
12539                let name = &m.tensors[i].name;
12540                let prism = if crate::prism::is_inverse_embedding(m, name) {
12541                    crate::gpu::GraphPrismOp::InverseEmbedding
12542                } else if crate::prism::is_forward_weight(m, name) {
12543                    crate::gpu::GraphPrismOp::Forward
12544                } else {
12545                    crate::gpu::GraphPrismOp::None
12546                };
12547                return Some(crate::gpu::GraphW {
12548                    idx: i,
12549                    kind,
12550                    row_scale: rs,
12551                    data: &[],
12552                    prism,
12553                    affine: crate::prism::is_affine_target(m, name),
12554                });
12555            }
12556            // Small unquantized projections (GDN in_proj_a/b) stay f32.
12557            match t.as_f32() {
12558                Some(d) => Some(crate::gpu::GraphW {
12559                    idx: 0,
12560                    kind: 4,
12561                    row_scale: &[],
12562                    data: d,
12563                    prism: crate::gpu::GraphPrismOp::None,
12564                    affine: false,
12565                }),
12566                None => {
12567                    if std::env::var_os("CMF_BATCH_DEBUG").is_some() {
12568                        eprintln!("batch graph: weight has no graph/f32 representation");
12569                    }
12570                    None
12571                }
12572            }
12573        }
12574        for li in from..upto_excl {
12575            let lw = &self.weights.layers[self.phys_layer(li)];
12576            if dbg {
12577                let ak = match &lw.attn {
12578                    AttnKind::Mla(_) => "Mla".into(),
12579                    AttnKind::Full {
12580                        output_gate, bias, ..
12581                    } => format!("Full gate={output_gate} bias={}", bias.is_some()),
12582                    AttnKind::LinearGdn(_) => "LinearGdn".into(),
12583                    AttnKind::Kda(_) => "Kda".into(),
12584                    AttnKind::Linear(_) => "Linear".into(),
12585                    AttnKind::ShortConv(_) => "ShortConv".into(),
12586                    AttnKind::Bounded(_) => "Bounded".into(),
12587                };
12588                let fk = match &lw.ffn {
12589                    FfnKind::Dense(_) => "Dense",
12590                    FfnKind::Moe(_) => "Moe",
12591                    FfnKind::DenseMoe(_) => "DenseMoe",
12592                };
12593                eprintln!("graph L{li}: attn={ak} ffn={fk}");
12594            }
12595            let gffn = match &lw.ffn {
12596                FfnKind::DenseMoe(_) => return None, // dual branch: CPU path
12597                // A tube layer is several matrices, not one — the
12598                // whole-layer graph has no shape for it yet.
12599                FfnKind::Dense(d) if !d.segs.is_empty() => return None,
12600                FfnKind::Dense(d) => {
12601                    // An activation the graph has no kernel arm for keeps
12602                    // the CPU/per-op owner, by name — the dense graph FFN
12603                    // used to compute SiLU for whatever the model asked.
12604                    let Some(act) = d.act.wgpu_graph_act() else {
12605                        self.note_graph_decline(
12606                            "wgpu token graph",
12607                            "dense FFN activation without a graph kernel",
12608                        );
12609                        return None;
12610                    };
12611                    crate::gpu::GraphFfn::Dense {
12612                        gate: gw(&d.gate_proj)?,
12613                        up: gw(&d.up_proj)?,
12614                        down: gw(&d.down_proj)?,
12615                        act,
12616                    }
12617                }
12618                FfnKind::Moe(m) => {
12619                    // Adaptive τ and expert masks keep the CPU path, where
12620                    // they are implemented. Sigmoid routing with a selection
12621                    // bias (LFM2-MoE / DeepSeek noaux_tc), a routed scale ≠ 1
12622                    // and an UNGATED shared expert (HunYuan hy_v3: ×2.826 on
12623                    // the routed mix, the shared expert at weight 1) are all
12624                    // graphed — before, every such token fell to the per-op
12625                    // path whole (145 submits/token on Hy-MT2-30B-A3B).
12626                    if m.route_tau.is_some() || m.mask.is_some() {
12627                        return None;
12628                    }
12629                    let shared = m.shared.as_ref();
12630                    // The resident MoE kernels do not yet carry the
12631                    // descriptor-aware transform through router/shared-gate
12632                    // selection.  Refuse the complete layer instead of
12633                    // scoring with an untransformed Prism plane (the dense
12634                    // path has an explicit FWHT boundary below).
12635                    let inter = m.experts.first()?.gate_proj.rows();
12636                    // Flint's shared expert is a 1024-wide SwiGLU while its
12637                    // routed bank is 512-wide.  The resident MoE shader
12638                    // indexes a uniform-width packed bank, so keep that
12639                    // expert out of the routed slots and add it through the
12640                    // dense q4tp path after routed accumulation.  This is
12641                    // also the safe route for a mixed q2-routed/q4-shared
12642                    // artifact: neither layout nor row stride is faked.
12643                    let detached_shared = match shared {
12644                        Some((se, None))
12645                            if se.gate_proj.rows() != inter || se.up_proj.rows() != inter =>
12646                        {
12647                            if !matches!(se.act, Act::Silu)
12648                                || se.gate_proj.mapped_q4tp().is_none()
12649                                || se.up_proj.mapped_q4tp().is_none()
12650                                || se.down_proj.mapped_q4tp().is_none()
12651                            {
12652                                return None;
12653                            }
12654                            Some(crate::gpu::GraphMoeDetachedShared {
12655                                gate: gw(&se.gate_proj)?,
12656                                up: gw(&se.up_proj)?,
12657                                down: gw(&se.down_proj)?,
12658                                width: se.gate_proj.rows(),
12659                            })
12660                        }
12661                        // A separately shaped gated shared expert needs a
12662                        // second sigmoid gate path.  Do not turn it into an
12663                        // ungated one merely to make the graph run.
12664                        Some((se, Some(_)))
12665                            if se.gate_proj.rows() != inter || se.up_proj.rows() != inter =>
12666                        {
12667                            return None;
12668                        }
12669                        _ => None,
12670                    };
12671                    let has_shared = shared.is_some() && detached_shared.is_none();
12672                    let shared_gated = has_shared && matches!(shared, Some((_, Some(_))));
12673                    let sgate = match shared {
12674                        Some((_, Some(sg))) if has_shared => gw(sg)?,
12675                        // No gate, no shared expert, or a detached shared
12676                        // expert: the router only keeps the binding total;
12677                        // the selection shader does not read it.
12678                        _ => gw(&m.router)?,
12679                    };
12680                    let router = gw(&m.router)?;
12681                    // The resident MoE kernels do not yet carry the
12682                    // descriptor-aware transform through router/shared-gate
12683                    // selection.  Refuse the complete layer instead of
12684                    // scoring with an untransformed Prism plane (the dense
12685                    // path has an explicit FWHT boundary below).
12686                    if router.prism != crate::gpu::GraphPrismOp::None
12687                        || sgate.prism != crate::gpu::GraphPrismOp::None
12688                        || router.affine
12689                        || sgate.affine
12690                    {
12691                        tracing::warn!(
12692                            "resident MoE declined: Prism/affine router or shared gate transform is not implemented"
12693                        );
12694                        return None;
12695                    }
12696                    let mut experts = Vec::with_capacity(m.experts.len() + 1);
12697                    // q4t or q4tp, but not both in one layer — the kernels
12698                    // are picked per layer, not per expert.
12699                    let mut q4tp: Option<bool> = None;
12700                    // The mixed 2-bit profile: q2tp gate/up over a q4tp
12701                    // down. Uniform across the layer, like `q4tp` itself.
12702                    let mut gu_q2: Option<bool> = None;
12703                    // q8_2f experts (gate, up and down): their own kernels.
12704                    let mut q82: Option<bool> = None;
12705                    // One MoE gate/up kernel serves the complete packed bank.
12706                    // Bind an activation only when every routed (and in-bank
12707                    // shared) expert owns the same exact WGPU contract.
12708                    let mut moe_act = None;
12709                    for e in m
12710                        .experts
12711                        .iter()
12712                        .chain(shared.filter(|_| has_shared).map(|(se, _)| se).into_iter())
12713                    {
12714                        let Some(e_act) = e.act.wgpu_graph_act() else {
12715                            return None;
12716                        };
12717                        match moe_act {
12718                            Some(existing) if existing != e_act => return None,
12719                            None => moe_act = Some(e_act),
12720                            _ => {}
12721                        }
12722                        if e.gate_proj.rows() != inter || e.up_proj.rows() != inter {
12723                            return None;
12724                        }
12725                        // Expert tensors are packed into one resident buffer
12726                        // and the MoE kernels have no transform slot per
12727                        // expert.  Keep the CPU/per-op owner for Prism or
12728                        // affine experts rather than silently using raw bytes.
12729                        for expert_weight in [&e.gate_proj, &e.up_proj, &e.down_proj] {
12730                            let Some((em, ei, _, _)) = expert_weight
12731                                .graph_weight()
12732                                .or_else(|| expert_weight.graph_weight_descriptor())
12733                            else {
12734                                return None;
12735                            };
12736                            let name = &em.tensors[ei].name;
12737                            if crate::prism::is_forward_weight(em, name)
12738                                || crate::prism::is_inverse_embedding(em, name)
12739                                || crate::prism::is_affine_target(em, name)
12740                            {
12741                                tracing::warn!(
12742                                    "resident MoE declined: expert Prism/affine transform is not implemented"
12743                                );
12744                                return None;
12745                            }
12746                        }
12747                        let (mm, gi, ui, di, is_p, is_q2, is_8) = match e.gate_proj.mapped_q4t() {
12748                            Some((mm, gi)) => (
12749                                mm,
12750                                gi,
12751                                e.up_proj.mapped_q4t()?.1,
12752                                e.down_proj.mapped_q4t()?.1,
12753                                false,
12754                                false,
12755                                false,
12756                            ),
12757                            None => match e.gate_proj.mapped_q2tp() {
12758                                Some((mm, gi)) => (
12759                                    mm,
12760                                    gi,
12761                                    e.up_proj.mapped_q2tp()?.1,
12762                                    e.down_proj.mapped_q4tp()?.1,
12763                                    true,
12764                                    true,
12765                                    false,
12766                                ),
12767                                None => match e.gate_proj.mapped_q4tp() {
12768                                    Some((mm, gi)) => (
12769                                        mm,
12770                                        gi,
12771                                        e.up_proj.mapped_q4tp()?.1,
12772                                        e.down_proj.mapped_q4tp()?.1,
12773                                        true,
12774                                        false,
12775                                        false,
12776                                    ),
12777                                    // q8_2f experts: all three projections,
12778                                    // each with its own column field.
12779                                    None => {
12780                                        if !crate::gpu::moe_q82_graph_on() {
12781                                            return None;
12782                                        }
12783                                        let (mm, gi) = e.gate_proj.mapped_q8_2f()?;
12784                                        (
12785                                            mm,
12786                                            gi,
12787                                            e.up_proj.mapped_q8_2f()?.1,
12788                                            e.down_proj.mapped_q8_2f()?.1,
12789                                            false,
12790                                            false,
12791                                            true,
12792                                        )
12793                                    }
12794                                },
12795                            },
12796                        };
12797                        if *q4tp.get_or_insert(is_p) != is_p
12798                            || *gu_q2.get_or_insert(is_q2) != is_q2
12799                            || *q82.get_or_insert(is_8) != is_8
12800                        {
12801                            // The shared expert rides in the same packed
12802                            // buffer as the routed ones, so a layer that
12803                            // mixes layouts cannot be indexed by one stride.
12804                            // Say so: the symptom is a whole model quietly
12805                            // running its MoE on the CPU.
12806                            tracing::warn!(
12807                                "MoE layer mixes expert layouts (q4tp={is_p}, q2tp gate/up={is_q2}, q8_2f={is_8})                                  — every expert of a layer, INCLUDING the shared one, must share                                  a layout. The whole-token graph declines this layer."
12808                            );
12809                            return None;
12810                        }
12811                        model.get_or_insert_with(|| mm.clone());
12812                        experts.push((gi, ui, di));
12813                    }
12814                    crate::gpu::GraphFfn::Moe {
12815                        router,
12816                        shared_gate: sgate,
12817                        experts,
12818                        n_exp: m.experts.len(),
12819                        // CMF_TOPK_PROBE: timing probe only — output is WRONG.
12820                        // Fewer experts shrink the MoE arithmetic while the
12821                        // dispatch count stays identical, which is the only
12822                        // clean way to tell a launch-bound decode from a
12823                        // compute-bound one.
12824                        top_k: std::env::var("CMF_TOPK_PROBE")
12825                            .ok()
12826                            .and_then(|v| v.parse::<usize>().ok())
12827                            .filter(|k| *k > 0 && *k <= m.top_k)
12828                            .unwrap_or(m.top_k),
12829                        inter,
12830                        act: moe_act?,
12831                        norm_topk: m.norm_topk_prob,
12832                        q4tp: q4tp?,
12833                        gu_q2: gu_q2.unwrap_or(false),
12834                        q82: q82.unwrap_or(false),
12835                        sigmoid: m.router_sigmoid,
12836                        sigmoid_denom_eps: m.sigmoid_denom_eps,
12837                        bias: m.expert_bias.as_deref(),
12838                        has_shared,
12839                        detached_shared,
12840                        shared_gated,
12841                        route_scale: m.routed_scaling,
12842                    }
12843                }
12844            };
12845            let attn = match &lw.attn {
12846                AttnKind::Full {
12847                    wq,
12848                    wk,
12849                    wv,
12850                    wo,
12851                    q_norm,
12852                    k_norm,
12853                    output_gate,
12854                    softplus_gate,
12855                    bias,
12856                } => {
12857                    if self.attention_heads_per_layer.is_some() {
12858                        return None;
12859                    }
12860                    // A projected output gate rides the graph in one form:
12861                    // Spark-X2.5's head-wise sigmoid (one g_proj row per Q
12862                    // head). Laguna's softplus gate keeps the CPU path.
12863                    let head_gate = match softplus_gate {
12864                        None => None,
12865                        Some((g, true)) if self.proj_gate_sigmoid && !*output_gate => Some(gw(g)?),
12866                        Some(_) => {
12867                            self.note_graph_decline(
12868                                "wgpu token graph",
12869                                "projected softplus / per-element output gate",
12870                            );
12871                            return None;
12872                        }
12873                    };
12874                    let (m, _, _, _) = wq.graph_weight_or_blr()?;
12875                    model = Some(m.clone());
12876                    crate::gpu::GraphAttn::Full {
12877                        wq: gw(wq)?,
12878                        wk: gw(wk)?,
12879                        wv: gw(wv)?,
12880                        wo: gw(wo)?,
12881                        q_norm: q_norm.as_deref(),
12882                        k_norm: k_norm.as_deref(),
12883                        late_qk_norm: self.qk_norm_after_rope,
12884                        bias: bias
12885                            .as_ref()
12886                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
12887                        output_gate: *output_gate,
12888                        cpu_k: self.kv_cache.layers[li].k_heads(),
12889                        cpu_v: self.kv_cache.layers[li].v_heads(),
12890                        cpu_base: self.kv_cache.layers[li].base(),
12891                        geom: self.graph_attn_geom(li),
12892                        head_gate,
12893                    }
12894                }
12895                AttnKind::LinearGdn(w) => {
12896                    let cfg = self.gdn_cfg?;
12897                    let (m, _, _, _) = w.in_proj_qkv.graph_weight_or_blr()?;
12898                    model = Some(m.clone());
12899                    crate::gpu::GraphAttn::Gdn {
12900                        qkv: gw(&w.in_proj_qkv)?,
12901                        z: gw(&w.in_proj_z)?,
12902                        a: gw(&w.in_proj_a)?,
12903                        b: gw(&w.in_proj_b)?,
12904                        out: gw(&w.out_proj)?,
12905                        conv1d: &w.conv1d,
12906                        a_log: &w.a_log,
12907                        dt_bias: &w.dt_bias,
12908                        norm: &w.norm,
12909                        nv: cfg.num_v_heads,
12910                        nk: cfg.num_k_heads,
12911                        dk: cfg.key_head_dim,
12912                        dv: cfg.value_head_dim,
12913                        kk: cfg.conv_kernel,
12914                        cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
12915                    }
12916                }
12917                AttnKind::ShortConv(w) => {
12918                    let cfg = self.short_conv_cfg?;
12919                    let (m, _, _, _) = w
12920                        .in_proj
12921                        .graph_weight()
12922                        .or_else(|| w.in_proj.graph_weight_descriptor())?;
12923                    model = Some(m.clone());
12924                    crate::gpu::GraphAttn::ShortConv {
12925                        inp: gw(&w.in_proj)?,
12926                        out: gw(&w.out_proj)?,
12927                        taps: &w.conv,
12928                        kernel: cfg.kernel,
12929                        cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
12930                    }
12931                }
12932                _ => return None,
12933            };
12934            layers.push(crate::gpu::GraphLayer {
12935                input_norm: &lw.input_norm,
12936                attn,
12937                post_norm: &lw.post_norm,
12938                attn_out_norm: lw.attn_out_norm.as_deref(),
12939                ffn_out_norm: lw.ffn_out_norm.as_deref(),
12940                layer_scale: lw.layer_scale,
12941                ffn: gffn,
12942            });
12943        }
12944        let model = model?;
12945        // Fold final-norm + lm_head into the graph when this call wants logits
12946        // and the lm_head is a graphable (quantized) weight — the graph then
12947        // reads back logits (into logits_out) instead of the hidden, dropping
12948        // the separate CPU/GPU lm_head op + its sync. Never the f32 fallback:
12949        // an unquantized lm_head is vocab·hidden and must not be uploaded.
12950        let lm_gw = if upto_excl == self.num_layers
12951            && self.graph_want_logits
12952            && std::env::var("CMF_GPU_LMHEAD")
12953                .map(|v| v != "0")
12954                .unwrap_or(true)
12955        {
12956            self.weights
12957                .lm_head
12958                .graph_weight()
12959                .or_else(|| self.weights.lm_head.graph_weight_descriptor())
12960                .map(|(m, i, kind, rs)| {
12961                    let name = &m.tensors[i].name;
12962                    let prism = if crate::prism::is_inverse_embedding(m, name) {
12963                        crate::gpu::GraphPrismOp::InverseEmbedding
12964                    } else if crate::prism::is_forward_weight(m, name) {
12965                        crate::gpu::GraphPrismOp::Forward
12966                    } else {
12967                        crate::gpu::GraphPrismOp::None
12968                    };
12969                    (
12970                        crate::gpu::GraphW {
12971                            idx: i,
12972                            kind,
12973                            row_scale: rs,
12974                            data: &[],
12975                            prism,
12976                            affine: crate::prism::is_affine_target(m, name),
12977                        },
12978                        self.weights.lm_head.rows(),
12979                    )
12980                })
12981        } else {
12982            None
12983        };
12984        let lm = lm_gw.as_ref().map(|(gw, rows)| (gw, *rows));
12985        // Multi-step re-embeds the winner on the device.
12986        let emb_gw = if steps > 1 {
12987            self.weights
12988                .embed_tokens
12989                .graph_weight()
12990                .or_else(|| self.weights.embed_tokens.graph_weight_descriptor())
12991                .map(|(m, i, kind, rs)| {
12992                    let name = &m.tensors[i].name;
12993                    let prism = if crate::prism::is_inverse_embedding(m, name) {
12994                        crate::gpu::GraphPrismOp::InverseEmbedding
12995                    } else if crate::prism::is_forward_weight(m, name) {
12996                        crate::gpu::GraphPrismOp::Forward
12997                    } else {
12998                        crate::gpu::GraphPrismOp::None
12999                    };
13000                    (
13001                        crate::gpu::GraphW {
13002                            idx: i,
13003                            kind,
13004                            row_scale: rs,
13005                            data: &[],
13006                            prism,
13007                            affine: crate::prism::is_affine_target(m, name),
13008                        },
13009                        self.weights.embed_tokens.rows(),
13010                        self.embed_multiplier,
13011                    )
13012                })
13013        } else {
13014            None
13015        };
13016
13017        // Loop boundaries: virtual layer indices after which final_norm is
13018        // applied (mid-stack only; the GLOBAL last layer's norm folds into
13019        // lm_head). Span-relative — the executor compares its enumerate
13020        // index. A span ending mid-stack keeps its boundary norm even when
13021        // it is the span's own last layer.
13022        let loop_norm_at: Vec<usize> = if self.loop_final_norm {
13023            (from..upto_excl.min(self.num_layers - 1))
13024                .filter(|&li| (li + 1) % self.physical_layers == 0)
13025                .map(|li| li - from)
13026                .collect()
13027        } else {
13028            Vec::new()
13029        };
13030        let mut h = hidden.to_vec();
13031        // The normal decode path only needs the fused lm-head logits.  A
13032        // CMF_LOGIT_DUMP diagnostic, however, promises a prompt-boundary
13033        // post-stack hidden alongside those logits; request the existing
13034        // second readback only for that explicit probe instead of dumping
13035        // the input copy left in `h` by a folded-head graph.
13036        let dump_hidden = std::env::var_os("CMF_LOGIT_DUMP").is_some();
13037        let outcome = crate::gpu::forward_token_graph(
13038            &model,
13039            self.graph_kv_id,
13040            &layers,
13041            &o1_views,
13042            self.o1_epoch,
13043            &self.inv_freq,
13044            &mut h,
13045            nh,
13046            nkv,
13047            hd,
13048            self.attn_scale,
13049            rd,
13050            self.hidden_size,
13051            self.intermediate_size,
13052            position,
13053            self.kv_cache.max_seq_len,
13054            gemma,
13055            self.rms_eps as f32,
13056            lm,
13057            &self.weights.final_norm,
13058            logits_out,
13059            &loop_norm_at,
13060            steps,
13061            emb_gw.as_ref().map(|(gw, rows, m)| (gw, *rows, *m)),
13062            ids_out,
13063            layers_run,
13064            from,
13065            dump_hidden,
13066        );
13067        match outcome {
13068            crate::gpu::TokenGraphOutcome::Completed => Some(Ok(h)),
13069            crate::gpu::TokenGraphOutcome::Failed => Some(Err(())),
13070            crate::gpu::TokenGraphOutcome::Declined => None,
13071        }
13072    }
13073
13074    /// Batched prefill: k contiguous prompt positions through the whole wgpu
13075    /// graph in ONE submit (projections/FFN as GEMMs). `hiddens` is [k·hidden]
13076    /// in/out (embeddings in, layer output out); KV mirror / GDN state advance.
13077    /// false ⇒ unsupported → caller keeps the per-position graph.
13078    /// The b-row Metal graph plan for the whole model: every layer as a
13079    /// GDN run or a full-attention item, all-or-nothing (a layer outside the
13080    /// graph's contract → None, the caller runs plain). Shared by the
13081    /// speculative verify and the batched prefill.
13082    #[cfg(target_os = "macos")]
13083    #[allow(clippy::type_complexity)]
13084    fn metal_rows_plan(
13085        &self,
13086    ) -> Option<(
13087        Vec<MetalRowsItem<'_>>,
13088        std::sync::Arc<cortiq_core::CmfModel>,
13089        Option<crate::gpu_metal::GdnGpuCfg>,
13090    )> {
13091        use crate::gpu_metal::{AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, MetalFfn};
13092        let graph_force = crate::gpu::q1_force() || crate::gpu::q2tp_gpu_opt_in();
13093        if !graph_force
13094            || !crate::gpu::enabled_here()
13095            || std::env::var("CMF_GPU_BLOCK")
13096                .map(|v| v == "0")
13097                .unwrap_or(false)
13098            || self.attn_softcap > 0.0
13099            || self.o1_active()
13100            || self.swa.is_some()
13101            || self.global_attn.is_some()
13102            || self.attention_heads_per_layer.is_some()
13103            // per-layer KV heads, narrow V, learned sinks (MiMo-V2)
13104            || self.graph_attn_decline_reason().is_some()
13105            || self.attn_v_norm
13106            || self.loop_final_norm
13107            || !self.metal_rope_scale_ok()
13108        {
13109            return None;
13110        }
13111        let attend_contract = self.head_dim % 4 == 0
13112            && self.head_dim <= 256
13113            && self.rotary_dim >= 2
13114            && self.rotary_dim <= self.head_dim
13115            && (self.rotary_dim / 2) % 32 == 0
13116            && self.num_kv_heads > 0
13117            && self.num_heads % self.num_kv_heads == 0;
13118        if !attend_contract {
13119            return None;
13120        }
13121        let mut plan: Vec<MetalRowsItem> = Vec::new();
13122        let mut model_ref: Option<std::sync::Arc<cortiq_core::CmfModel>> = None;
13123        for li in 0..self.num_layers {
13124            let lw = &self.weights.layers[self.phys_layer(li)];
13125            if lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some() {
13126                return None;
13127            }
13128            let ffn = match &lw.ffn {
13129                FfnKind::Dense(d) if d.act == Act::Silu && d.segs.is_empty() => {
13130                    let (Some(g), Some(u), Some(dn)) = (
13131                        d.gate_proj.metal_graph_parts(),
13132                        d.up_proj.metal_graph_parts(),
13133                        d.down_proj.metal_graph_parts(),
13134                    ) else {
13135                        return None;
13136                    };
13137                    MetalFfn::Dense {
13138                        gate: g,
13139                        up: u,
13140                        down: dn,
13141                        act: 0, // SiLU only (the arm above)
13142                    }
13143                }
13144                _ => return None,
13145            };
13146            match &lw.attn {
13147                AttnKind::LinearGdn(w) if self.gdn_cfg.is_some() => {
13148                    let (Some(qkv), Some(z), Some(a), Some(bb), Some(out)) = (
13149                        w.in_proj_qkv.metal_graph_parts(),
13150                        w.in_proj_z.metal_graph_parts(),
13151                        w.in_proj_a.f32_parts(),
13152                        w.in_proj_b.f32_parts(),
13153                        w.out_proj.metal_graph_parts(),
13154                    ) else {
13155                        return None;
13156                    };
13157                    if let QTensor::Mapped { model, .. } = &w.in_proj_qkv {
13158                        model_ref.get_or_insert_with(|| model.clone());
13159                    }
13160                    let gl = GdnGpuLayer {
13161                        attn_norm: &lw.input_norm,
13162                        post_norm: &lw.post_norm,
13163                        qkv,
13164                        z,
13165                        a,
13166                        b: bb,
13167                        out,
13168                        ffn,
13169                        conv1d: &w.conv1d,
13170                        a_log: &w.a_log,
13171                        dt_bias: &w.dt_bias,
13172                        gnorm: &w.norm,
13173                    };
13174                    match plan.last_mut() {
13175                        Some(MetalRowsItem::Gdn { run, .. }) => run.push(gl),
13176                        _ => plan.push(MetalRowsItem::Gdn {
13177                            run: vec![gl],
13178                            first: li,
13179                        }),
13180                    }
13181                }
13182                AttnKind::Full {
13183                    wq,
13184                    wk,
13185                    wv,
13186                    wo,
13187                    q_norm,
13188                    k_norm,
13189                    output_gate,
13190                    softplus_gate: None,
13191                    bias: None,
13192                } => {
13193                    let (Some(pq), Some(pk), Some(pv), Some(po)) = (
13194                        wq.metal_graph_parts(),
13195                        wk.metal_graph_parts(),
13196                        wv.metal_graph_parts(),
13197                        wo.metal_graph_parts(),
13198                    ) else {
13199                        return None;
13200                    };
13201                    if let QTensor::Mapped { model, .. } = wq {
13202                        model_ref.get_or_insert_with(|| model.clone());
13203                    }
13204                    let cache = &self.kv_cache.layers[li];
13205                    if cache.mode != crate::kv_cache::KvMode::F32 || cache.o1.is_some() {
13206                        return None;
13207                    }
13208                    plan.push(MetalRowsItem::Attn {
13209                        l: AttnGpuLayer {
13210                            attn_norm: &lw.input_norm,
13211                            post_norm: &lw.post_norm,
13212                            wq: pq,
13213                            wk: pk,
13214                            wv: pv,
13215                            wo: po,
13216                            ffn,
13217                            attn_out_norm: None,
13218                            ffn_out_norm: None,
13219                            layer_scale: None,
13220                        },
13221                        li,
13222                        q_norm: q_norm.as_deref(),
13223                        k_norm: k_norm.as_deref(),
13224                        output_gate: *output_gate,
13225                    });
13226                }
13227                _ => return None,
13228            }
13229        }
13230        let model = model_ref?;
13231        let gcfg = self.gdn_cfg.map(|cfg| GdnGpuCfg {
13232            nv: cfg.num_v_heads,
13233            nk: cfg.num_k_heads,
13234            dk: cfg.key_head_dim,
13235            dv: cfg.value_head_dim,
13236            kk: cfg.conv_kernel,
13237            hidden: self.hidden_size,
13238            inter: self.intermediate_size,
13239            c_dim: cfg.conv_dim(),
13240            eps: cfg.rms_eps as f32,
13241            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
13242        });
13243        Some((plan, model, gcfg))
13244    }
13245
13246    /// `AttnDeviceParams` for a plan item over the CPU cache as it stands.
13247    #[cfg(target_os = "macos")]
13248    #[allow(clippy::too_many_arguments)]
13249    fn metal_attn_params<'a>(
13250        li: usize,
13251        cache: &'a crate::kv_cache::LayerKvCache,
13252        q_norm: Option<&'a [f32]>,
13253        k_norm: Option<&'a [f32]>,
13254        output_gate: bool,
13255        inv_freq: &'a [f32],
13256        rope_scale: f32,
13257        geom: (usize, usize, usize, usize),
13258        pos0: usize,
13259        kv_id: u64,
13260        scale: f32,
13261        eps: f32,
13262        gemma: bool,
13263        late_qk_norm: bool,
13264    ) -> (crate::gpu_metal::AttnDeviceParams<'a>, usize) {
13265        let (nh, nkv, hd, rd) = geom;
13266        let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
13267        let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
13268        let cpu_stored = cpu_k[0].len() / hd;
13269        (
13270            crate::gpu_metal::AttnDeviceParams {
13271                kv_id,
13272                layer: li,
13273                nh,
13274                nkv,
13275                hd,
13276                rd,
13277                position: pos0,
13278                scale,
13279                eps,
13280                gemma,
13281                late_qk_norm,
13282                output_gate,
13283                q_norm,
13284                k_norm,
13285                inv_freq,
13286                rope_scale,
13287                cpu_k,
13288                cpu_v,
13289                cpu_stored,
13290                cpu_gen: cache.generation(),
13291                o1: None,
13292                window: None,
13293                softmax_sink: cache.sinks.as_deref(),
13294                head_gate: None,
13295                v_norm: false,
13296            },
13297            cpu_stored,
13298        )
13299    }
13300
13301    /// Run the rows plan over `hiddens` (b rows at `pos0..`): validate,
13302    /// encode every item, optionally the head, sync. Returns the graph
13303    /// (for the commit / state finish) plus the GDN layer indices and the
13304    /// attention layers with the row count they were encoded against.
13305    #[cfg(target_os = "macos")]
13306    #[allow(clippy::type_complexity)]
13307    fn metal_rows_run(
13308        &mut self,
13309        hiddens: &mut [f32],
13310        pos0: usize,
13311        b: usize,
13312        prefill: bool,
13313        spec: Option<((usize, usize, usize), &[f32], &mut Vec<f32>)>,
13314        // Greedy verify: (row length scored, the b argmax ids out) — the
13315        // head's argmax runs on the device and the logits plane is NOT
13316        // read back (`spec.2` stays empty).
13317        mut argmax_out: Option<(usize, &mut Vec<u32>)>,
13318    ) -> MetalRowsRun {
13319        use crate::gpu_metal::{GraphDims, VerifyGraph};
13320        // The previous round's commit may still be replaying into the
13321        // trunk GDN owners on the second queue: this graph reads them
13322        // (zero-copy wraps) and may reallocate them below — collect the
13323        // replay first. Normally already complete (the draft chain ran
13324        // in between); a failed replay is terminal like a failed commit.
13325        if !crate::gpu_metal::wait_replay() {
13326            tracing::error!("Metal rows graph: the pending async replay failed");
13327            return MetalRowsRun::Failed;
13328        }
13329        spec_stamp("v.wait");
13330        // Seed the GDN recurrent records the rows graph reads — GDN layers
13331        // ONLY (the record the CPU path would allocate anyway).  Sizing
13332        // every layer here planted a zero GDN-sized record on a bounded
13333        // anchor of a natively bounded file this path then refused, and
13334        // that record counted as recurrent state on macOS.
13335        let want = self.gdn_cfg.map(|c| c.state_len()).unwrap_or(0);
13336        if want > 0 {
13337            let phys = self.physical_layers.max(1);
13338            for (li, l) in self.kv_cache.layers.iter_mut().enumerate() {
13339                let is_gdn = self
13340                    .weights
13341                    .layers
13342                    .get(li % phys)
13343                    .is_some_and(|lw| matches!(lw.attn, AttnKind::LinearGdn(_)));
13344                if is_gdn && l.linear_state.len() != want {
13345                    l.linear_state = vec![0f32; want];
13346                }
13347            }
13348        }
13349        let Some((plan, model, gcfg)) = self.metal_rows_plan() else {
13350            return MetalRowsRun::Declined;
13351        };
13352        spec_stamp("v.plan");
13353        let dims = GraphDims {
13354            hidden: self.hidden_size,
13355            eps: self.rms_eps as f32,
13356            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
13357        };
13358        let Some(mut graph) = (if prefill {
13359            VerifyGraph::new_prefill(&model, dims, hiddens, b)
13360        } else {
13361            VerifyGraph::new(&model, dims, hiddens, b)
13362        }) else {
13363            return MetalRowsRun::Declined;
13364        };
13365        let geom = (
13366            self.num_heads,
13367            self.num_kv_heads,
13368            self.head_dim,
13369            self.rotary_dim,
13370        );
13371        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
13372        let eps = self.rms_eps as f32;
13373        let kv_id = self.graph_kv_id;
13374        let inv_freq = self.inv_freq.clone();
13375        for item in &plan {
13376            let ok = match item {
13377                MetalRowsItem::Gdn { run, .. } => gcfg
13378                    .as_ref()
13379                    .map(|gc| run.iter().all(|l| graph.gdn_ok(l, gc)))
13380                    .unwrap_or(false),
13381                MetalRowsItem::Attn {
13382                    l,
13383                    li,
13384                    q_norm,
13385                    k_norm,
13386                    output_gate,
13387                } => {
13388                    let (p, _) = Self::metal_attn_params(
13389                        *li,
13390                        &self.kv_cache.layers[*li],
13391                        *q_norm,
13392                        *k_norm,
13393                        *output_gate,
13394                        &inv_freq,
13395                        self.layer_rope_scale(*li),
13396                        geom,
13397                        pos0,
13398                        kv_id,
13399                        self.attn_scale,
13400                        eps,
13401                        gemma,
13402                        self.qk_norm_after_rope,
13403                    );
13404                    graph.attn_ok(l, &p)
13405                }
13406            };
13407            if !ok {
13408                use std::sync::atomic::{AtomicBool, Ordering};
13409                static SAID: AtomicBool = AtomicBool::new(false);
13410                if !SAID.swap(true, Ordering::Relaxed) {
13411                    tracing::warn!("metal rows graph: a layer failed preflight — declining");
13412                }
13413                return MetalRowsRun::Declined;
13414            }
13415        }
13416        let lm = match &spec {
13417            Some((lm, _, _)) => {
13418                if !graph.lm_head_ok(*lm) {
13419                    return MetalRowsRun::Declined;
13420                }
13421                Some(*lm)
13422            }
13423            None => None,
13424        };
13425        let mut gdn_layers = Vec::new();
13426        let mut attn_layers = Vec::new();
13427        for item in &plan {
13428            match item {
13429                MetalRowsItem::Gdn { run, first } => {
13430                    let ro: Vec<&[f32]> = self.kv_cache.layers[*first..*first + run.len()]
13431                        .iter()
13432                        .map(|l| l.linear_state.as_slice())
13433                        .collect();
13434                    if !graph.encode_gdn_run_b(run, &ro, gcfg.as_ref().unwrap()) {
13435                        return MetalRowsRun::Declined;
13436                    }
13437                    gdn_layers.extend(*first..*first + run.len());
13438                }
13439                MetalRowsItem::Attn {
13440                    l,
13441                    li,
13442                    q_norm,
13443                    k_norm,
13444                    output_gate,
13445                } => {
13446                    let (p, cpu_stored) = Self::metal_attn_params(
13447                        *li,
13448                        &self.kv_cache.layers[*li],
13449                        *q_norm,
13450                        *k_norm,
13451                        *output_gate,
13452                        &inv_freq,
13453                        self.layer_rope_scale(*li),
13454                        geom,
13455                        pos0,
13456                        kv_id,
13457                        self.attn_scale,
13458                        eps,
13459                        gemma,
13460                        self.qk_norm_after_rope,
13461                    );
13462                    if !graph.encode_attn_b(l, &p) {
13463                        return MetalRowsRun::Declined;
13464                    }
13465                    attn_layers.push((*li, cpu_stored));
13466                }
13467            }
13468        }
13469        if let (Some(lm), Some((_, final_norm, _))) = (lm, spec.as_ref()) {
13470            if !graph.encode_lm_head_b(final_norm, lm) {
13471                return MetalRowsRun::Declined;
13472            }
13473            // The device argmax is an OPTIMISATION, never a reason to
13474            // decline the round: if it will not encode, drop it and read
13475            // the logits plane back the old way (the head is encoded
13476            // either way, so the rows are there).
13477            if let Some((n, _)) = argmax_out.as_ref() {
13478                if !graph.encode_argmax_b(*n) {
13479                    argmax_out = None;
13480                }
13481            }
13482        }
13483        spec_stamp("v.enc");
13484        if !graph.sync() {
13485            return MetalRowsRun::Failed;
13486        }
13487        spec_stamp("v.gpu");
13488        match (spec, argmax_out) {
13489            (Some(_), Some((_, ids))) => {
13490                ids.resize(b, 0);
13491                if !graph.read_argmax(ids) {
13492                    return MetalRowsRun::Failed;
13493                }
13494                spec_stamp("v.am");
13495            }
13496            (Some((lm, _, logits)), None) => {
13497                logits.resize(b * lm.1, 0.0);
13498                if !graph.read_logits(logits) {
13499                    return MetalRowsRun::Failed;
13500                }
13501                spec_stamp("v.lg");
13502            }
13503            (None, _) => {}
13504        }
13505        if !graph.read_hidden(hiddens) {
13506            return MetalRowsRun::Failed;
13507        }
13508        spec_stamp("v.hid");
13509        MetalRowsRun::Completed(MetalVerifyPending {
13510            graph,
13511            gdn_layers,
13512            attn_layers,
13513        })
13514    }
13515
13516    /// Native-Metal twin of `try_batch_graph_wgpu`: the b rows through the
13517    /// whole model on the `VerifyGraph` (one submit), the head folded in
13518    /// when `spec` asks; `hiddens` come back as the last layer's output
13519    /// rows, `spec.2` as `[b][lm_rows]` logits. The graph is parked in
13520    /// `metal_verify` for `metal_verify_commit`.
13521    #[cfg(target_os = "macos")]
13522    fn try_batch_graph_metal(
13523        &mut self,
13524        hiddens: &mut [f32],
13525        positions: &[usize],
13526        b: usize,
13527        spec: Option<((usize, usize, usize), &[f32], &mut Vec<f32>)>,
13528        argmax_out: Option<(usize, &mut Vec<u32>)>,
13529    ) -> crate::gpu::BatchGraphOutcome {
13530        let _t0 = std::time::Instant::now();
13531        if positions.len() != b
13532            || positions.windows(2).any(|w| w[1] != w[0] + 1)
13533            || hiddens.len() != b * self.hidden_size
13534        {
13535            return crate::gpu::BatchGraphOutcome::Declined;
13536        }
13537        let pending = match self.metal_rows_run(hiddens, positions[0], b, false, spec, argmax_out) {
13538            MetalRowsRun::Declined => return crate::gpu::BatchGraphOutcome::Declined,
13539            MetalRowsRun::Failed => return crate::gpu::BatchGraphOutcome::Failed,
13540            MetalRowsRun::Completed(pending) => pending,
13541        };
13542        if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
13543            eprintln!(
13544                "metal-verify: {:.1} ms | b={b}",
13545                _t0.elapsed().as_secs_f64() * 1e3
13546            );
13547        }
13548        self.metal_verify = Some(pending);
13549        crate::gpu::BatchGraphOutcome::Completed
13550    }
13551
13552    /// Batched prefill on the Metal rows graph: `ids` (≤ 512) at
13553    /// `start_pos..`, states written in place, K/V rows appended to the
13554    /// CPU caches; optional final norm/head logits are returned in `spec`.
13555    /// Declined means no command buffer was admitted; Failed is terminal.
13556    #[cfg(target_os = "macos")]
13557    fn prefill_rows_metal(
13558        &mut self,
13559        ids: &[u32],
13560        start_pos: usize,
13561        spec: Option<((usize, usize, usize), &[f32], &mut Vec<f32>)>,
13562    ) -> MetalPrefillOutcome {
13563        let b = ids.len();
13564        if b == 0 || b > 512 {
13565            return MetalPrefillOutcome::Declined;
13566        }
13567        METAL_PREFILL_CHUNKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13568        let with_head = spec.is_some();
13569        let hs = self.hidden_size;
13570        let mut hiddens = vec![0f32; b * hs];
13571        for (j, &id) in ids.iter().enumerate() {
13572            let e = self.embed_single(id);
13573            hiddens[j * hs..(j + 1) * hs].copy_from_slice(&e);
13574        }
13575        let mut pending = match self.metal_rows_run(&mut hiddens, start_pos, b, true, spec, None) {
13576            MetalRowsRun::Declined => return MetalPrefillOutcome::Declined,
13577            MetalRowsRun::Failed => {
13578                METAL_PREFILL_ERRORS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13579                return MetalPrefillOutcome::Failed;
13580            }
13581            MetalRowsRun::Completed(pending) => pending,
13582        };
13583        // states are final: copy them to the owners
13584        let idxs = pending.gdn_layers.clone();
13585        let mut outs: Vec<&mut [f32]> = self
13586            .kv_cache
13587            .layers
13588            .iter_mut()
13589            .enumerate()
13590            .filter(|(i, _)| idxs.binary_search(i).is_ok())
13591            .map(|(_, l)| l.linear_state.as_mut_slice())
13592            .collect();
13593        if !pending.graph.finish_states(&mut outs) {
13594            METAL_PREFILL_ERRORS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13595            return MetalPrefillOutcome::Failed;
13596        }
13597        let (nkv, hd) = (self.num_kv_heads, self.head_dim);
13598        // Read every layer before mutating any CPU cache.  A missing mirror
13599        // row is a terminal graph failure, not a reason to append a partial
13600        // prefix and replay the remainder serially.
13601        let mut rows = Vec::with_capacity(pending.attn_layers.len());
13602        for (li, cpu_stored) in &pending.attn_layers {
13603            let mut kbuf = vec![0f32; b * nkv * hd];
13604            let mut vbuf = vec![0f32; b * nkv * hd];
13605            if !crate::gpu_metal::kv_mirror_read_rows(
13606                self.graph_kv_id,
13607                *li,
13608                nkv,
13609                hd,
13610                *cpu_stored,
13611                b,
13612                &mut kbuf,
13613                &mut vbuf,
13614            ) {
13615                METAL_PREFILL_ERRORS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13616                return MetalPrefillOutcome::Failed;
13617            }
13618            rows.push((*li, *cpu_stored, kbuf, vbuf));
13619        }
13620        for (li, cpu_stored, kbuf, vbuf) in rows {
13621            let cache = &mut self.kv_cache.layers[li];
13622            for r in 0..b {
13623                cache.append(
13624                    &kbuf[r * nkv * hd..(r + 1) * nkv * hd],
13625                    &vbuf[r * nkv * hd..(r + 1) * nkv * hd],
13626                    &[],
13627                );
13628            }
13629            crate::gpu_metal::kv_mirror_set_stored(self.graph_kv_id, li, cpu_stored + b);
13630        }
13631        METAL_PREFILL_ROWS.fetch_add(b as u64, std::sync::atomic::Ordering::Relaxed);
13632        if with_head {
13633            METAL_PREFILL_HEAD_ROWS.fetch_add(b as u64, std::sync::atomic::Ordering::Relaxed);
13634        }
13635        MetalPrefillOutcome::Completed(hiddens)
13636    }
13637
13638    #[cfg(target_os = "macos")]
13639    fn prefill_batch_metal(&mut self, ids: &[u32], start_pos: usize) -> MetalPrefillOutcome {
13640        self.prefill_rows_metal(ids, start_pos, None)
13641    }
13642
13643    /// Exact teacher-forced NLL through the ordinary Metal rows graph.  This
13644    /// is intentionally separate from the serial TokenGraph scorer: every
13645    /// chunk owns a real b-row graph/head completion and the recurrent/KV
13646    /// handoff is committed before the next chunk begins.
13647    #[cfg(target_os = "macos")]
13648    fn nll_batch_metal(&mut self, ids: &[u32], start: usize) -> MetalBatchNllOutcome {
13649        if ids.len() < 2 || self.o1_active() || self.head_clusters.is_some() {
13650            return MetalBatchNllOutcome::Declined;
13651        }
13652        let Some(lm) = self.weights.lm_head.metal_graph_parts() else {
13653            return MetalBatchNllOutcome::Declined;
13654        };
13655        let chunk = std::env::var("CMF_METAL_PREFILL_CHUNK")
13656            .ok()
13657            .and_then(|v| v.parse::<usize>().ok())
13658            .filter(|&v| (1..=512).contains(&v))
13659            .unwrap_or(32);
13660        let final_norm = self.weights.final_norm.clone();
13661        let mut nll = 0.0f64;
13662        let mut count = 0usize;
13663        let mut pos = 0usize;
13664        let mut completed = 0usize;
13665        while pos < ids.len() {
13666            let end = (pos + chunk).min(ids.len());
13667            let mut logits = Vec::new();
13668            let outcome =
13669                self.prefill_rows_metal(&ids[pos..end], pos, Some((lm, &final_norm, &mut logits)));
13670            match outcome {
13671                MetalPrefillOutcome::Declined => {
13672                    return if completed == 0 {
13673                        MetalBatchNllOutcome::Declined
13674                    } else {
13675                        MetalBatchNllOutcome::Failed(format!(
13676                            "ordinary Metal NLL batch declined after {completed} chunks"
13677                        ))
13678                    };
13679                }
13680                MetalPrefillOutcome::Failed => {
13681                    return MetalBatchNllOutcome::Failed(
13682                        "ordinary Metal NLL batch failed after admission".to_string(),
13683                    );
13684                }
13685                MetalPrefillOutcome::Completed(_) => {}
13686            }
13687            completed += 1;
13688            let vocab = self.vocab_size.min(lm.1);
13689            if logits.len() != (end - pos) * lm.1 || vocab == 0 {
13690                return MetalBatchNllOutcome::Failed(
13691                    "ordinary Metal NLL head returned an invalid shape".to_string(),
13692                );
13693            }
13694            for row in 0..(end - pos) {
13695                let absolute = pos + row;
13696                if absolute < start || absolute + 1 >= ids.len() {
13697                    continue;
13698                }
13699                let lg = &mut logits[row * lm.1..row * lm.1 + vocab];
13700                if let Some(mu) = self.logit_multiplier {
13701                    for v in lg.iter_mut() {
13702                        *v *= mu;
13703                    }
13704                }
13705                if let Some(c) = self.final_softcap {
13706                    softcap_in_place(lg, c, self.pool.as_deref());
13707                }
13708                let target = ids[absolute + 1] as usize;
13709                if target >= vocab {
13710                    return MetalBatchNllOutcome::Failed(format!(
13711                        "target token {target} exceeds Metal head rows {vocab}"
13712                    ));
13713                }
13714                let max = lg.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
13715                let lse: f64 = lg
13716                    .iter()
13717                    .map(|&v| ((v - max) as f64).exp())
13718                    .sum::<f64>()
13719                    .ln()
13720                    + max as f64;
13721                nll += lse - lg[target] as f64;
13722                count += 1;
13723            }
13724            pos = end;
13725        }
13726        MetalBatchNllOutcome::Completed(nll, count)
13727    }
13728
13729    /// Commit a Metal verify round: replay the GDN recurrences over the
13730    /// `a + 1` accepted positions into the CPU states, append the accepted
13731    /// K/V rows from the mirrors to the CPU caches, re-point the mirrors.
13732    #[cfg(target_os = "macos")]
13733    fn metal_verify_commit(&mut self, a: usize) -> bool {
13734        let Some(mut pending) = self.metal_verify.take() else {
13735            return false;
13736        };
13737        let n = a + 1;
13738        // encode order == ascending layer order (the plan walks 0..layers)
13739        let idxs = pending.gdn_layers.clone();
13740        let mut outs: Vec<&mut [f32]> = self
13741            .kv_cache
13742            .layers
13743            .iter_mut()
13744            .enumerate()
13745            .filter(|(i, _)| idxs.binary_search(i).is_ok())
13746            .map(|(_, l)| l.linear_state.as_mut_slice())
13747            .collect();
13748        if !pending.graph.commit(n, &mut outs) {
13749            return false;
13750        }
13751        spec_stamp("c.replay");
13752        let (nkv, hd) = (self.num_kv_heads, self.head_dim);
13753        // Read every layer before mutating any CPU cache.  Missing rows are
13754        // terminal after the replay has executed; never append a partial KV
13755        // prefix and continue on a serial path.
13756        let mut rows = Vec::with_capacity(pending.attn_layers.len());
13757        for (li, cpu_stored) in &pending.attn_layers {
13758            let mut kbuf = vec![0f32; n * nkv * hd];
13759            let mut vbuf = vec![0f32; n * nkv * hd];
13760            if !crate::gpu_metal::kv_mirror_read_rows(
13761                self.graph_kv_id,
13762                *li,
13763                nkv,
13764                hd,
13765                *cpu_stored,
13766                n,
13767                &mut kbuf,
13768                &mut vbuf,
13769            ) {
13770                return false;
13771            }
13772            rows.push((*li, *cpu_stored, kbuf, vbuf));
13773        }
13774        for (li, cpu_stored, kbuf, vbuf) in rows {
13775            let cache = &mut self.kv_cache.layers[li];
13776            for r in 0..n {
13777                cache.append(
13778                    &kbuf[r * nkv * hd..(r + 1) * nkv * hd],
13779                    &vbuf[r * nkv * hd..(r + 1) * nkv * hd],
13780                    &[],
13781                );
13782            }
13783            crate::gpu_metal::kv_mirror_set_stored(self.graph_kv_id, li, cpu_stored + n);
13784        }
13785        spec_stamp("c.kv");
13786        true
13787    }
13788
13789    /// The round's warm-ups as ONE b-row graph run over the MTP block on
13790    /// Metal: `pairs` = (trunk hidden, next token) at consecutive positions
13791    /// from `first_pos`; the block's input projection is folded in. This
13792    /// half encodes and SUBMITS (no wait); `mtp_warm_batch_finish` waits
13793    /// and pulls the appended K/V rows into the CPU MTP cache. None = the
13794    /// graph declined (nothing submitted, nothing appended).
13795    #[cfg(target_os = "macos")]
13796    fn mtp_warm_batch_submit(
13797        &mut self,
13798        m: &mut MtpModule,
13799        pairs: &[(&[f32], u32)],
13800        first_pos: usize,
13801    ) -> Option<MetalWarmPending> {
13802        use crate::gpu_metal::{AttnDeviceParams, AttnGpuLayer, GraphDims, MetalFfn, VerifyGraph};
13803        let b = pairs.len();
13804        if b == 0 || b > 512 || m.kv.mode != crate::kv_cache::KvMode::F32 || m.kv.o1.is_some() {
13805            return None;
13806        }
13807        let AttnKind::Full {
13808            wq,
13809            wk,
13810            wv,
13811            wo,
13812            q_norm,
13813            k_norm,
13814            output_gate,
13815            softplus_gate: None,
13816            bias: None,
13817        } = &m.layer.attn
13818        else {
13819            return None;
13820        };
13821        let FfnKind::Dense(d) = &m.layer.ffn else {
13822            return None;
13823        };
13824        if !d.segs.is_empty() {
13825            return None;
13826        }
13827        let (Some(pq), Some(pk), Some(pv), Some(po)) =
13828            (wq.q1_parts(), wk.q1_parts(), wv.q1_parts(), wo.q1_parts())
13829        else {
13830            return None;
13831        };
13832        let (Some(g), Some(u), Some(dn)) = (
13833            d.gate_proj.q1_parts(),
13834            d.up_proj.q1_parts(),
13835            d.down_proj.q1_parts(),
13836        ) else {
13837            return None;
13838        };
13839        let Some(eh) = m.eh_proj.q1_parts() else {
13840            return None;
13841        };
13842        let QTensor::Mapped { model, .. } = wq else {
13843            return None;
13844        };
13845        let model = model.clone();
13846        let hs = self.hidden_size;
13847        // [enorm(embed(tok)); hnorm(hidden)] rows
13848        let mut cat = vec![0f32; b * 2 * hs];
13849        for (j, (h, tok)) in pairs.iter().enumerate() {
13850            let e = self.embed_single(*tok);
13851            let (ce, ch) = cat[j * 2 * hs..(j + 1) * 2 * hs].split_at_mut(hs);
13852            inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, ce);
13853            inference::rms_norm_into(h, &m.hnorm, self.rms_eps, self.norm_style, ch);
13854        }
13855        let dims = GraphDims {
13856            hidden: hs,
13857            eps: self.rms_eps as f32,
13858            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
13859        };
13860        spec_stamp("w.cat");
13861        let Some(mut graph) = VerifyGraph::new_via_proj(&model, dims, eh, &cat, b) else {
13862            return None;
13863        };
13864        spec_stamp("w.new");
13865        let l = AttnGpuLayer {
13866            attn_norm: &m.layer.input_norm,
13867            post_norm: &m.layer.post_norm,
13868            wq: pq,
13869            wk: pk,
13870            wv: pv,
13871            wo: po,
13872            ffn: MetalFfn::Dense {
13873                gate: g,
13874                up: u,
13875                down: dn,
13876                act: (d.act == Act::Gelu) as u8,
13877            },
13878            attn_out_norm: None,
13879            ffn_out_norm: None,
13880            layer_scale: None,
13881        };
13882        let (nh, nkv, hd, rd) = (
13883            self.num_heads,
13884            self.num_kv_heads,
13885            self.head_dim,
13886            self.rotary_dim,
13887        );
13888        let inv_freq = self.inv_freq.clone();
13889        let cpu_stored;
13890        {
13891            let cache = &m.kv;
13892            let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
13893            let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
13894            cpu_stored = cpu_k[0].len() / hd;
13895            // The cache may LAG the position (rows nobody warmed): the
13896            // pairs land at cpu_stored.. with their true RoPE positions
13897            // first_pos.., exactly what the one-by-one warm does. A cache
13898            // AHEAD of the position is a real inconsistency.
13899            if cpu_stored > first_pos {
13900                spec_stamp("w.decl");
13901                return None;
13902            }
13903            let p = AttnDeviceParams {
13904                kv_id: self.mtp_kv_id(),
13905                layer: Self::MTP_LAYER_BASE,
13906                nh,
13907                nkv,
13908                hd,
13909                rd,
13910                position: first_pos,
13911                scale: self.attn_scale,
13912                eps: self.rms_eps as f32,
13913                gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
13914                late_qk_norm: self.qk_norm_after_rope,
13915                output_gate: *output_gate,
13916                q_norm: q_norm.as_deref(),
13917                k_norm: k_norm.as_deref(),
13918                inv_freq: &inv_freq,
13919                rope_scale: self.rope_scale,
13920                cpu_k,
13921                cpu_v,
13922                cpu_stored,
13923                cpu_gen: cache.generation(),
13924                o1: None,
13925                window: None,
13926                softmax_sink: None,
13927                head_gate: None,
13928                v_norm: false,
13929            };
13930            if !graph.attn_ok(&l, &p) || !graph.encode_attn_b(&l, &p) {
13931                return None;
13932            }
13933        }
13934        spec_stamp("w.enc");
13935        if !graph.submit() {
13936            return None;
13937        }
13938        spec_stamp("w.sub");
13939        Some(MetalWarmPending {
13940            graph,
13941            cpu_stored,
13942            b,
13943        })
13944    }
13945
13946    /// Submit and finish in one call (the prefill's MTP warm-up, where
13947    /// nothing runs in between).
13948    #[cfg(target_os = "macos")]
13949    fn mtp_warm_batch_metal(
13950        &mut self,
13951        m: &mut MtpModule,
13952        pairs: &[(&[f32], u32)],
13953        first_pos: usize,
13954    ) -> bool {
13955        match self.mtp_warm_batch_submit(m, pairs, first_pos) {
13956            Some(p) => self.mtp_warm_batch_finish(m, p),
13957            None => false,
13958        }
13959    }
13960
13961    /// Second half of the batched warm-up: wait for the submitted graph,
13962    /// pull its b appended K/V rows into the CPU MTP cache, re-point the
13963    /// mirror. False = the command buffer failed or the rows are missing
13964    /// (nothing appended; the caller falls back to the one-by-one warm).
13965    #[cfg(target_os = "macos")]
13966    fn mtp_warm_batch_finish(&mut self, m: &mut MtpModule, pending: MetalWarmPending) -> bool {
13967        let MetalWarmPending {
13968            mut graph,
13969            cpu_stored,
13970            b,
13971        } = pending;
13972        let (nkv, hd) = (self.num_kv_heads, self.head_dim);
13973        if !graph.sync() {
13974            return false;
13975        }
13976        spec_stamp("w.gpu");
13977        let mut kbuf = vec![0f32; b * nkv * hd];
13978        let mut vbuf = vec![0f32; b * nkv * hd];
13979        if !crate::gpu_metal::kv_mirror_read_rows(
13980            self.mtp_kv_id(),
13981            Self::MTP_LAYER_BASE,
13982            nkv,
13983            hd,
13984            cpu_stored,
13985            b,
13986            &mut kbuf,
13987            &mut vbuf,
13988        ) {
13989            return false;
13990        }
13991        for r in 0..b {
13992            m.kv.append(
13993                &kbuf[r * nkv * hd..(r + 1) * nkv * hd],
13994                &vbuf[r * nkv * hd..(r + 1) * nkv * hd],
13995                &[],
13996            );
13997        }
13998        crate::gpu_metal::kv_mirror_set_stored(
13999            self.mtp_kv_id(),
14000            Self::MTP_LAYER_BASE,
14001            cpu_stored + b,
14002        );
14003        spec_stamp("w.kv");
14004        true
14005    }
14006
14007    /// A committed token id from the high table (Cyrillic, CJK and the
14008    /// like sit above 131072 in Qwen's vocabulary; Latin subwords past
14009    /// the 65536 cut are rare enough to lose as rejected drafts) switches
14010    /// the draft to the full head for the next 16 tokens; other ids count
14011    /// down. On an M4 the full 660 MB head costs 5.5 ms a draft step
14012    /// against 1.4 for the shortlist, so the streak is kept short.
14013    pub(crate) fn note_draft_id(&mut self, id: u32) {
14014        let cut = Self::draft_vocab_rows(usize::MAX).max(131_072);
14015        if (id as usize) >= cut {
14016            self.draft_full_streak = 16;
14017        } else {
14018            self.draft_full_streak = self.draft_full_streak.saturating_sub(1);
14019        }
14020    }
14021
14022    /// The draft head's rows for the next step: the shortlist, or the full
14023    /// head while `draft_full_streak` runs.
14024    fn draft_head_rows(&self, head_rows: usize) -> usize {
14025        if self.draft_full_streak > 0 {
14026            head_rows
14027        } else {
14028            Self::draft_vocab_rows(head_rows)
14029        }
14030    }
14031
14032    /// Draft-head shortlist size: `CMF_DRAFT_VOCAB` rows (default 65536,
14033    /// capped at the head; 0 = full head).
14034    fn draft_vocab_rows(head_rows: usize) -> usize {
14035        static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
14036        let n = *N.get_or_init(|| {
14037            std::env::var("CMF_DRAFT_VOCAB")
14038                .ok()
14039                .and_then(|v| v.parse().ok())
14040                .unwrap_or(65536)
14041        });
14042        if n == 0 { head_rows } else { n.min(head_rows) }
14043    }
14044
14045    /// One MTP block step on the native Metal token graph: block input on
14046    /// the host, the attention layer + FFN device-resident over the MTP
14047    /// mirror, the head folded in when `want_logits`. The appended K/V row
14048    /// is pulled into the CPU MTP cache (owner of record) after the sync.
14049    #[cfg(target_os = "macos")]
14050    fn mtp_step_metal(
14051        &mut self,
14052        m: &mut MtpModule,
14053        hidden: &[f32],
14054        next_token: u32,
14055        position: usize,
14056        want_logits: bool,
14057    ) -> Option<(Vec<f32>, Vec<f32>)> {
14058        use crate::gpu_metal::{AttnDeviceParams, AttnGpuLayer, GraphDims, MetalFfn, TokenGraph};
14059        if std::env::var("CMF_MTP_GRAPH").as_deref() == Ok("0")
14060            || !crate::gpu::q1_force()
14061            || !crate::gpu::enabled_here()
14062            || self.attn_softcap > 0.0
14063            || self.attention_heads_per_layer.is_some()
14064            || m.kv.mode != crate::kv_cache::KvMode::F32
14065            || m.kv.o1.is_some()
14066        {
14067            return None;
14068        }
14069        let AttnKind::Full {
14070            wq,
14071            wk,
14072            wv,
14073            wo,
14074            q_norm,
14075            k_norm,
14076            output_gate,
14077            softplus_gate: None,
14078            bias: None,
14079        } = &m.layer.attn
14080        else {
14081            return None;
14082        };
14083        let FfnKind::Dense(d) = &m.layer.ffn else {
14084            return None;
14085        };
14086        if d.act != Act::Silu || !d.segs.is_empty() {
14087            return None;
14088        }
14089        let (pq, pk, pv, po) = (
14090            wq.q1_parts()?,
14091            wk.q1_parts()?,
14092            wv.q1_parts()?,
14093            wo.q1_parts()?,
14094        );
14095        let (g, u, dn) = (
14096            d.gate_proj.q1_parts()?,
14097            d.up_proj.q1_parts()?,
14098            d.down_proj.q1_parts()?,
14099        );
14100        let QTensor::Mapped { model, .. } = wq else {
14101            return None;
14102        };
14103        let model = model.clone();
14104        let lm = if want_logits {
14105            Some(self.weights.lm_head.q1_parts()?)
14106        } else {
14107            None
14108        };
14109        let dims = GraphDims {
14110            hidden: self.hidden_size,
14111            eps: self.rms_eps as f32,
14112            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
14113        };
14114        // The block input `eh_proj · [enorm(e); hnorm(h)]` rides in the
14115        // graph (one submit a step); the host per-op matvec if it cannot.
14116        let hs = self.hidden_size;
14117        let mut x = vec![0f32; hs];
14118        let mut graph = TokenGraph::new(&model, dims, &x)?;
14119        let mut folded = false;
14120        if let Some(eh) = m.eh_proj.q1_parts() {
14121            let e = self.embed_single(next_token);
14122            let mut cat = vec![0.0f32; 2 * hs];
14123            let (cat_e, cat_h) = cat.split_at_mut(hs);
14124            inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
14125            inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
14126            folded = graph.encode_input_proj(eh, &cat);
14127        }
14128        if !folded {
14129            x = self.mtp_block_input(m, hidden, next_token);
14130            graph = TokenGraph::new(&model, dims, &x)?;
14131        }
14132        spec_stamp("d.in");
14133        let l = AttnGpuLayer {
14134            attn_norm: &m.layer.input_norm,
14135            post_norm: &m.layer.post_norm,
14136            wq: pq,
14137            wk: pk,
14138            wv: pv,
14139            wo: po,
14140            ffn: MetalFfn::Dense {
14141                gate: g,
14142                up: u,
14143                down: dn,
14144                act: (d.act == Act::Gelu) as u8,
14145            },
14146            attn_out_norm: None,
14147            ffn_out_norm: None,
14148            layer_scale: None,
14149        };
14150        let (nh, nkv, hd, rd) = (
14151            self.num_heads,
14152            self.num_kv_heads,
14153            self.head_dim,
14154            self.rotary_dim,
14155        );
14156        let inv_freq = self.inv_freq.clone();
14157        {
14158            let cache = &m.kv;
14159            let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
14160            let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
14161            let cpu_stored = cpu_k[0].len() / hd;
14162            let p = AttnDeviceParams {
14163                kv_id: self.mtp_kv_id(),
14164                layer: Self::MTP_LAYER_BASE,
14165                nh,
14166                nkv,
14167                hd,
14168                rd,
14169                position,
14170                scale: self.attn_scale,
14171                eps: self.rms_eps as f32,
14172                gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
14173                late_qk_norm: self.qk_norm_after_rope,
14174                output_gate: *output_gate,
14175                q_norm: q_norm.as_deref(),
14176                k_norm: k_norm.as_deref(),
14177                inv_freq: &inv_freq,
14178                rope_scale: self.rope_scale,
14179                cpu_k,
14180                cpu_v,
14181                cpu_stored,
14182                cpu_gen: cache.generation(),
14183                o1: None,
14184                window: None,
14185                softmax_sink: None,
14186                head_gate: None,
14187                v_norm: false,
14188            };
14189            if !graph.attn_device_ok(&l, &p) || !graph.encode_attn_device(&l, &p) {
14190                return None;
14191            }
14192        }
14193        // The draft's head over a vocabulary SHORTLIST (the first
14194        // CMF_DRAFT_VOCAB rows — BPE ids run roughly by merge rank, so the
14195        // low ids carry the mass): the verify keeps the full head, so a true
14196        // token past the cut is only a rejected draft, never a wrong token.
14197        // 662 MB a step on Qwen3.8 becomes 170 MB at 65536.
14198        let draft_rows = if let Some(lm) = lm {
14199            self.draft_head_rows(lm.1)
14200        } else {
14201            0
14202        };
14203        if let Some(lm) = lm {
14204            if !graph.lm_head_ok(lm) {
14205                return None;
14206            }
14207            if draft_rows < lm.1 {
14208                if !graph.encode_lm_head_part(&m.final_norm, lm, draft_rows) {
14209                    return None;
14210                }
14211            } else {
14212                graph.encode_lm_head(&m.final_norm, lm);
14213            }
14214        }
14215        spec_stamp("d.enc");
14216        if graph.sync_checked().is_err() {
14217            return None;
14218        }
14219        spec_stamp("d.gpu");
14220        let mut logits = Vec::new();
14221        if let Some(lm) = lm {
14222            let n_read = draft_rows.min(lm.1).min(self.vocab_size);
14223            logits = attention::take_buf(n_read);
14224            graph.read_logits(&mut logits);
14225            // ids past the shortlist: never drafted (−∞ in every chain)
14226            logits.resize(self.vocab_size, f32::NEG_INFINITY);
14227        }
14228        graph.finish(&mut x);
14229        let mut krow = attention::take_buf(nkv * hd);
14230        let mut vrow = attention::take_buf(nkv * hd);
14231        if crate::gpu_metal::kv_mirror_read_last(
14232            self.mtp_kv_id(),
14233            Self::MTP_LAYER_BASE,
14234            nkv,
14235            hd,
14236            &mut krow,
14237            &mut vrow,
14238        ) {
14239            m.kv.append(&krow, &vrow, &[]);
14240        }
14241        attention::recycle_buf(&mut krow);
14242        attention::recycle_buf(&mut vrow);
14243        spec_stamp("d.rd");
14244        Some((logits, x))
14245    }
14246
14247    /// `CMF_MTP_CHAIN=0` keeps the per-step draft (one submit and one
14248    /// host round trip per MTP step); the default drafts the whole chain
14249    /// in one command buffer when the round is plain greedy.
14250    ///
14251    /// Measured on an M4 (24 GB), Qwen3.8-27B q4tp, P3 at 160 tokens,
14252    /// k=7, six runs per arm alternating inside one lock window — the
14253    /// round's draft phase (median over the 34 rounds of a run) is
14254    /// 34.5 ms per round old against 30.1 new, i.e. 4.93 → 4.31 ms per
14255    /// draft step. That is the whole prize: the 7 submits cost ~0.6 ms
14256    /// each in host and submit latency and nothing else changes —
14257    /// acceptance (3.41 of 7) and tokens per round (4.41) are identical,
14258    /// and the round is 289 → 285 ms, decode 13.8 → 14.0 tok/s.
14259    fn mtp_chain_on() -> bool {
14260        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
14261        *ON.get_or_init(|| std::env::var("CMF_MTP_CHAIN").as_deref() != Ok("0"))
14262    }
14263
14264    /// The round's k greedy drafts as ONE command buffer on Metal: the MTP
14265    /// block k times back to back, each step's token embedding gathered
14266    /// on the device from the argmax the step before it wrote, the head
14267    /// over the round's shortlist (or the full head during a full-head
14268    /// streak — decided once, before the chain, exactly as the per-step
14269    /// path decides it per step, since `draft_full_streak` only moves on
14270    /// a commit). One wait, then the k ids and the k appended K/V rows
14271    /// come back; the CPU MTP cache ends where k `mtp_step_metal` calls
14272    /// would have left it. `Err(false)` = declined before anything was
14273    /// committed (the per-step path takes the round); `Err(true)` = the
14274    /// command buffer failed after commit.
14275    #[cfg(target_os = "macos")]
14276    fn mtp_draft_chain_metal(
14277        &mut self,
14278        m: &mut MtpModule,
14279        hidden: &[f32],
14280        t_next: u32,
14281        position: usize,
14282        k: usize,
14283    ) -> Result<Vec<u32>, bool> {
14284        use crate::gpu_metal::{AttnDeviceParams, AttnGpuLayer, GraphDims, MetalFfn, TokenGraph};
14285        if k == 0
14286            || k > 64
14287            || !Self::mtp_chain_on()
14288            || std::env::var("CMF_MTP_GRAPH").as_deref() == Ok("0")
14289            || !crate::gpu::q1_force()
14290            || !crate::gpu::enabled_here()
14291            || self.attn_softcap > 0.0
14292            || self.attention_heads_per_layer.is_some()
14293            || m.kv.mode != crate::kv_cache::KvMode::F32
14294            || m.kv.o1.is_some()
14295            // the chain gathers embeddings itself: only the plain table
14296            || self.dsv4.is_some()
14297            || self.dsv41.is_some()
14298            || self.qwen4_exp.is_some()
14299            || self.per_token_stack()
14300        {
14301            return Err(false);
14302        }
14303        let AttnKind::Full {
14304            wq,
14305            wk,
14306            wv,
14307            wo,
14308            q_norm,
14309            k_norm,
14310            output_gate,
14311            softplus_gate: None,
14312            bias: None,
14313        } = &m.layer.attn
14314        else {
14315            return Err(false);
14316        };
14317        let FfnKind::Dense(d) = &m.layer.ffn else {
14318            return Err(false);
14319        };
14320        if d.act != Act::Silu || !d.segs.is_empty() {
14321            return Err(false);
14322        }
14323        let (Some(pq), Some(pk), Some(pv), Some(po)) =
14324            (wq.q1_parts(), wk.q1_parts(), wv.q1_parts(), wo.q1_parts())
14325        else {
14326            return Err(false);
14327        };
14328        let (Some(g), Some(u), Some(dn)) = (
14329            d.gate_proj.q1_parts(),
14330            d.up_proj.q1_parts(),
14331            d.down_proj.q1_parts(),
14332        ) else {
14333            return Err(false);
14334        };
14335        let (Some(eh), Some(lm)) = (m.eh_proj.q1_parts(), self.weights.lm_head.q1_parts()) else {
14336            return Err(false);
14337        };
14338        let QTensor::Mapped { model, .. } = wq else {
14339            return Err(false);
14340        };
14341        let model = model.clone();
14342        // the embedding table: a q4tp tensor of the SAME blob, no Prism
14343        // inverse-embedding post-pass
14344        let QTensor::Mapped {
14345            model: em,
14346            idx: eidx,
14347            dtype: cortiq_core::TensorDtype::Q4TiledP,
14348            ..
14349        } = &self.weights.embed_tokens
14350        else {
14351            return Err(false);
14352        };
14353        if !std::sync::Arc::ptr_eq(em, &model)
14354            || crate::prism::is_inverse_embedding(&model, &model.tensors[*eidx].name)
14355        {
14356            return Err(false);
14357        }
14358        let embed = (
14359            *eidx,
14360            self.weights.embed_tokens.rows(),
14361            self.weights.embed_tokens.cols(),
14362        );
14363        if embed.2 != self.hidden_size || hidden.len() != self.hidden_size {
14364            return Err(false);
14365        }
14366        let dims = GraphDims {
14367            hidden: self.hidden_size,
14368            eps: self.rms_eps as f32,
14369            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
14370        };
14371        let Some(mut graph) = TokenGraph::new(&model, dims, hidden) else {
14372            return Err(false);
14373        };
14374        if !graph.chain_embed_ok(embed) || !graph.lm_head_ok(lm) {
14375            return Err(false);
14376        }
14377        let l = AttnGpuLayer {
14378            attn_norm: &m.layer.input_norm,
14379            post_norm: &m.layer.post_norm,
14380            wq: pq,
14381            wk: pk,
14382            wv: pv,
14383            wo: po,
14384            ffn: MetalFfn::Dense {
14385                gate: g,
14386                up: u,
14387                down: dn,
14388                act: (d.act == Act::Gelu) as u8,
14389            },
14390            attn_out_norm: None,
14391            ffn_out_norm: None,
14392            layer_scale: None,
14393        };
14394        let (nh, nkv, hd, rd) = (
14395            self.num_heads,
14396            self.num_kv_heads,
14397            self.head_dim,
14398            self.rotary_dim,
14399        );
14400        let inv_freq = self.inv_freq.clone();
14401        let draft_rows = self.draft_head_rows(lm.1);
14402        let n_arg = draft_rows.min(lm.1).min(self.vocab_size);
14403        if n_arg == 0 {
14404            return Err(false);
14405        }
14406        // `CMF_MTP_CHAIN_SPLIT=1` commits each step as it is encoded, so
14407        // the GPU starts on step 0 while the host is still encoding step
14408        // 1 — a probe for whether the host encode is on the critical
14409        // path. It is not: three runs each, draft 30.0 ms per round split
14410        // against 30.1 whole, and the whole chain's host encode measures
14411        // 0.3 ms against a 29.7 ms wait. Kept as a probe, off by default.
14412        let split = std::env::var("CMF_MTP_CHAIN_SPLIT").as_deref() == Ok("1");
14413        let t_chain = std::time::Instant::now();
14414        graph.chain_ids_init(t_next, k);
14415        let cpu_stored;
14416        {
14417            let cache = &m.kv;
14418            let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
14419            let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
14420            cpu_stored = cpu_k[0].len() / hd;
14421            for j in 0..k {
14422                if !graph.encode_chain_input(
14423                    embed,
14424                    j as u32,
14425                    &m.enorm,
14426                    &m.hnorm,
14427                    self.embed_multiplier,
14428                    eh,
14429                ) {
14430                    return Err(false);
14431                }
14432                // step j's mirror row: the mirror is re-pointed at the CPU
14433                // rows before step 0 and advances by one per step; its
14434                // resync (never taken past step 0) reads the CPU rows
14435                let p = AttnDeviceParams {
14436                    kv_id: self.mtp_kv_id(),
14437                    layer: Self::MTP_LAYER_BASE,
14438                    nh,
14439                    nkv,
14440                    hd,
14441                    rd,
14442                    position: position + j,
14443                    scale: self.attn_scale,
14444                    eps: self.rms_eps as f32,
14445                    gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
14446                    late_qk_norm: self.qk_norm_after_rope,
14447                    output_gate: *output_gate,
14448                    q_norm: q_norm.as_deref(),
14449                    k_norm: k_norm.as_deref(),
14450                    inv_freq: &inv_freq,
14451                    rope_scale: self.rope_scale,
14452                    cpu_k: cpu_k.clone(),
14453                    cpu_v: cpu_v.clone(),
14454                    cpu_stored: cpu_stored + j,
14455                    cpu_gen: cache.generation(),
14456                    o1: None,
14457                    window: None,
14458                    softmax_sink: None,
14459                    head_gate: None,
14460                    v_norm: false,
14461                };
14462                if !graph.attn_device_ok(&l, &p) || !graph.encode_attn_device(&l, &p) {
14463                    return Err(false);
14464                }
14465                if draft_rows < lm.1 {
14466                    if !graph.encode_lm_head_part(&m.final_norm, lm, draft_rows) {
14467                        return Err(false);
14468                    }
14469                } else {
14470                    graph.encode_lm_head(&m.final_norm, lm);
14471                }
14472                if !graph.encode_argmax(n_arg, j as u32 + 1) {
14473                    return Err(false);
14474                }
14475                if split {
14476                    // CMF_MTP_CHAIN_SPLIT=1: commit every step so the GPU
14477                    // starts on step 0 while the host encodes the rest
14478                    graph.commit();
14479                }
14480            }
14481        }
14482        let t_enc = t_chain.elapsed();
14483        if graph.sync_checked().is_err() {
14484            return Err(true);
14485        }
14486        if std::env::var_os("CMF_GRAPH_SPEC_TIME").is_some() {
14487            eprintln!(
14488                "mtp-chain: encode {:.1} ms | wait {:.1} ms (k={k}, head rows {draft_rows}{})",
14489                t_enc.as_secs_f64() * 1e3,
14490                (t_chain.elapsed() - t_enc).as_secs_f64() * 1e3,
14491                if split { ", split" } else { "" }
14492            );
14493        }
14494        let mut ids = vec![0u32; k];
14495        if !graph.chain_ids_read(&mut ids) {
14496            return Err(true);
14497        }
14498        let mut kbuf = vec![0f32; k * nkv * hd];
14499        let mut vbuf = vec![0f32; k * nkv * hd];
14500        if !crate::gpu_metal::kv_mirror_read_rows(
14501            self.mtp_kv_id(),
14502            Self::MTP_LAYER_BASE,
14503            nkv,
14504            hd,
14505            cpu_stored,
14506            k,
14507            &mut kbuf,
14508            &mut vbuf,
14509        ) {
14510            return Err(true);
14511        }
14512        for r in 0..k {
14513            m.kv.append(
14514                &kbuf[r * nkv * hd..(r + 1) * nkv * hd],
14515                &vbuf[r * nkv * hd..(r + 1) * nkv * hd],
14516                &[],
14517            );
14518        }
14519        Ok(ids)
14520    }
14521
14522    fn try_batch_graph_wgpu(
14523        &self,
14524        hiddens: &mut [f32],
14525        positions: &[usize],
14526        k: usize,
14527        spec: Option<crate::gpu::SpecTail<'_>>,
14528    ) -> crate::gpu::BatchGraphOutcome {
14529        self.try_batch_graph_wgpu_prefix(hiddens, positions, k, spec, None)
14530    }
14531
14532    /// `try_batch_graph_wgpu` with the device-prefix mode: `layers_run`
14533    /// Some lets a stack that does not fit run its leading layers (the
14534    /// token graph's prefix rule) and reports how many; `hiddens` then
14535    /// holds the boundary rows and the caller runs the rest on the host.
14536    fn try_batch_graph_wgpu_prefix(
14537        &self,
14538        hiddens: &mut [f32],
14539        positions: &[usize],
14540        k: usize,
14541        spec: Option<crate::gpu::SpecTail<'_>>,
14542        layers_run: Option<&mut usize>,
14543    ) -> crate::gpu::BatchGraphOutcome {
14544        let graph_end = match self.mimo_moe.graph_prefix_end() {
14545            Some(end) if end < self.num_layers => {
14546                if layers_run.is_none() || spec.is_some() || end == 0 {
14547                    return crate::gpu::BatchGraphOutcome::Declined;
14548                }
14549                end
14550            }
14551            _ => self.num_layers,
14552        };
14553        let _tb = std::time::Instant::now();
14554        let batch_debug = std::env::var_os("CMF_BATCH_DEBUG").is_some();
14555        if self.attn_softcap > 0.0 {
14556            return crate::gpu::BatchGraphOutcome::Declined; // capped scores: no graph kernel — CPU path
14557        }
14558        // Same attention contract as the token graph: per-layer geometry
14559        // rides `geom`, anything it cannot express declines by name.
14560        if let Some(reason) = self
14561            .wgpu_graph_attn_decline()
14562            .or_else(|| self.batch_graph_gemma_decline())
14563        {
14564            self.note_graph_decline("wgpu batch graph", reason);
14565            return crate::gpu::BatchGraphOutcome::Declined;
14566        }
14567        let nh = self.num_heads;
14568        let (nkv, hd, rd) = self.layer_geom(0);
14569        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
14570        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
14571            if let Some((m, i, kind, rs)) = t.graph_weight().or_else(|| t.graph_weight_descriptor())
14572            {
14573                let name = &m.tensors[i].name;
14574                let prism = if crate::prism::is_inverse_embedding(m, name) {
14575                    crate::gpu::GraphPrismOp::InverseEmbedding
14576                } else if crate::prism::is_forward_weight(m, name) {
14577                    crate::gpu::GraphPrismOp::Forward
14578                } else {
14579                    crate::gpu::GraphPrismOp::None
14580                };
14581                return Some(crate::gpu::GraphW {
14582                    idx: i,
14583                    kind,
14584                    row_scale: rs,
14585                    data: &[],
14586                    prism,
14587                    affine: crate::prism::is_affine_target(m, name),
14588                });
14589            }
14590            if std::env::var_os("CMF_BATCH_DEBUG").is_some() {
14591                eprintln!(
14592                    "batch graph: tensor has no graph descriptor/f32 fallback rows={} cols={}",
14593                    t.rows(),
14594                    t.cols()
14595                );
14596            }
14597            t.as_f32().map(|d| crate::gpu::GraphW {
14598                idx: 0,
14599                kind: 4,
14600                row_scale: &[],
14601                data: d,
14602                prism: crate::gpu::GraphPrismOp::None,
14603                affine: false,
14604            })
14605        }
14606        let built: Option<(
14607            Vec<crate::gpu::GraphLayer<'_>>,
14608            std::sync::Arc<cortiq_core::CmfModel>,
14609        )> = (|| {
14610            let mut layers = Vec::with_capacity(graph_end);
14611            let mut model = None;
14612            for li in 0..graph_end {
14613                let lw = &self.weights.layers[self.phys_layer(li)];
14614                // MoE routes per token, so its experts are encoded token by
14615                // token inside the batched submit while attention and the
14616                // projections stay GEMMs. Refusing MoE here is what left
14617                // prefill running one position at a time: 33 tok/s against
14618                // 54 on decode, i.e. reading the prompt was slower than
14619                // writing the answer.
14620                let gffn = match &lw.ffn {
14621                    FfnKind::Dense(d) if !d.segs.is_empty() => {
14622                        if batch_debug {
14623                            eprintln!("batch graph: dense segmented FFN at layer {li}");
14624                        }
14625                        return None;
14626                    }
14627                    FfnKind::Dense(d) => {
14628                        let Some(act) = d.act.wgpu_graph_act() else {
14629                            if batch_debug {
14630                                eprintln!(
14631                                    "batch graph: dense FFN activation {:?} without a graph kernel at layer {li}",
14632                                    d.act
14633                                );
14634                            }
14635                            return None;
14636                        };
14637                        crate::gpu::GraphFfn::Dense {
14638                            gate: gw(&d.gate_proj)?,
14639                            up: gw(&d.up_proj)?,
14640                            down: gw(&d.down_proj)?,
14641                            act,
14642                        }
14643                    }
14644                    FfnKind::Moe(m) => {
14645                        // Adaptive τ and expert masks stay on the CPU path.
14646                        // Sigmoid scores, the selection bias, a routed scale
14647                        // ≠ 1 and an ungated shared expert (hy_v3) ride the
14648                        // same flags word as the token graph — before, this
14649                        // refusal sent every Hy-MT2-30B prompt to the chunked
14650                        // fallback (8 tok/s of ingest against 53 of decode).
14651                        if m.route_tau.is_some() || m.mask.is_some() {
14652                            return None;
14653                        }
14654                        // A shared expert rides as slot top_k (gated or
14655                        // not is a flag on the select kernel); without one
14656                        // (MiMo-V2, LFM2-MoE) the kernels run top_k slots.
14657                        let shared = m.shared.as_ref();
14658                        let has_shared = shared.is_some();
14659                        let shared_gated = matches!(shared, Some((_, Some(_))));
14660                        let sgate = match shared {
14661                            Some((_, Some(sg))) => gw(sg)?,
14662                            // Ungated or absent: the router plane stands in
14663                            // so the plumbing stays total; the kernel pins
14664                            // weight 1 or never reads it.
14665                            _ => gw(&m.router)?,
14666                        };
14667                        let router = gw(&m.router)?;
14668                        // The batch MoE kernels still consume raw per-token
14669                        // rows and do not carry the descriptor-aware Prism
14670                        // transform/affine bit for router or shared-gate
14671                        // planes.  Refuse rather than route an untransformed
14672                        // source activation.
14673                        if router.prism != crate::gpu::GraphPrismOp::None
14674                            || router.affine
14675                            || sgate.prism != crate::gpu::GraphPrismOp::None
14676                            || sgate.affine
14677                        {
14678                            return None;
14679                        }
14680                        let inter = m.experts.first()?.gate_proj.rows();
14681                        let mut experts = Vec::with_capacity(m.experts.len() + 1);
14682                        let mut q4tp: Option<bool> = None;
14683                        let mut gu_q2: Option<bool> = None;
14684                        let mut q82: Option<bool> = None;
14685                        // The packed MoE graph has one gate/up program per
14686                        // layer, so accept only one exact activation contract
14687                        // across routed and in-bank shared experts.
14688                        let mut moe_act = None;
14689                        for e in m.experts.iter().chain(shared.map(|(se, _)| se)) {
14690                            let Some(e_act) = e.act.wgpu_graph_act() else {
14691                                return None;
14692                            };
14693                            match moe_act {
14694                                Some(existing) if existing != e_act => return None,
14695                                None => moe_act = Some(e_act),
14696                                _ => {}
14697                            }
14698                            if e.gate_proj.rows() != inter || e.up_proj.rows() != inter {
14699                                return None;
14700                            }
14701                            // Same ladder as the token graph: q4t → q2tp
14702                            // (mixed profile: 2-bit gate/up over a q4tp
14703                            // down) → q4tp → q8_2f. Uniform across the layer.
14704                            let (mm, gi, ui, di, is_p, is_q2, is_8) = match e.gate_proj.mapped_q4t()
14705                            {
14706                                Some((mm, gi)) => (
14707                                    mm,
14708                                    gi,
14709                                    e.up_proj.mapped_q4t()?.1,
14710                                    e.down_proj.mapped_q4t()?.1,
14711                                    false,
14712                                    false,
14713                                    false,
14714                                ),
14715                                None => match e.gate_proj.mapped_q2tp() {
14716                                    Some((mm, gi)) => (
14717                                        mm,
14718                                        gi,
14719                                        e.up_proj.mapped_q2tp()?.1,
14720                                        e.down_proj.mapped_q4tp()?.1,
14721                                        true,
14722                                        true,
14723                                        false,
14724                                    ),
14725                                    None => match e.gate_proj.mapped_q4tp() {
14726                                        Some((mm, gi)) => (
14727                                            mm,
14728                                            gi,
14729                                            e.up_proj.mapped_q4tp()?.1,
14730                                            e.down_proj.mapped_q4tp()?.1,
14731                                            true,
14732                                            false,
14733                                            false,
14734                                        ),
14735                                        None => {
14736                                            if !crate::gpu::moe_q82_graph_on() {
14737                                                return None;
14738                                            }
14739                                            let (mm, gi) = e.gate_proj.mapped_q8_2f()?;
14740                                            (
14741                                                mm,
14742                                                gi,
14743                                                e.up_proj.mapped_q8_2f()?.1,
14744                                                e.down_proj.mapped_q8_2f()?.1,
14745                                                false,
14746                                                false,
14747                                                true,
14748                                            )
14749                                        }
14750                                    },
14751                                },
14752                            };
14753                            if *q4tp.get_or_insert(is_p) != is_p
14754                                || *gu_q2.get_or_insert(is_q2) != is_q2
14755                                || *q82.get_or_insert(is_8) != is_8
14756                            {
14757                                return None;
14758                            }
14759                            if [gi, ui, di].into_iter().any(|idx| {
14760                                mm.tensors.get(idx).is_some_and(|t| {
14761                                    crate::prism::is_forward_weight(mm, &t.name)
14762                                        || crate::prism::is_affine_target(mm, &t.name)
14763                                })
14764                            }) {
14765                                return None;
14766                            }
14767                            model.get_or_insert_with(|| mm.clone());
14768                            experts.push((gi, ui, di));
14769                        }
14770                        crate::gpu::GraphFfn::Moe {
14771                            router,
14772                            shared_gate: sgate,
14773                            experts,
14774                            n_exp: m.experts.len(),
14775                            top_k: m.top_k,
14776                            inter,
14777                            act: moe_act?,
14778                            norm_topk: m.norm_topk_prob,
14779                            q4tp: q4tp?,
14780                            gu_q2: gu_q2.unwrap_or(false),
14781                            q82: q82.unwrap_or(false),
14782                            sigmoid: m.router_sigmoid,
14783                            sigmoid_denom_eps: m.sigmoid_denom_eps,
14784                            bias: m.expert_bias.as_deref(),
14785                            has_shared,
14786                            detached_shared: None,
14787                            shared_gated,
14788                            route_scale: m.routed_scaling,
14789                        }
14790                    }
14791                    _ => return None,
14792                };
14793                let attn = match &lw.attn {
14794                    AttnKind::Full {
14795                        wq,
14796                        wk,
14797                        wv,
14798                        wo,
14799                        q_norm,
14800                        k_norm,
14801                        output_gate,
14802                        softplus_gate,
14803                        bias,
14804                    } => {
14805                        if softplus_gate.is_some() || self.attention_heads_per_layer.is_some() {
14806                            if batch_debug {
14807                                eprintln!(
14808                                    "batch graph: unsupported Full attention gate at layer {li} softplus={} heads={}",
14809                                    softplus_gate.is_some(),
14810                                    self.attention_heads_per_layer.is_some()
14811                                );
14812                            }
14813                            return None;
14814                        }
14815                        let (m, _, _, _) =
14816                            wq.graph_weight().or_else(|| wq.graph_weight_descriptor())?;
14817                        model = Some(m.clone());
14818                        crate::gpu::GraphAttn::Full {
14819                            wq: gw(wq)?,
14820                            wk: gw(wk)?,
14821                            wv: gw(wv)?,
14822                            wo: gw(wo)?,
14823                            q_norm: q_norm.as_deref(),
14824                            k_norm: k_norm.as_deref(),
14825                            late_qk_norm: self.qk_norm_after_rope,
14826                            bias: bias
14827                                .as_ref()
14828                                .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
14829                            output_gate: *output_gate,
14830                            cpu_k: self.kv_cache.layers[li].k_heads(),
14831                            cpu_v: self.kv_cache.layers[li].v_heads(),
14832                            cpu_base: self.kv_cache.layers[li].base(),
14833                            geom: self.graph_attn_geom(li),
14834                            // The batched graph has no head-gate arm; a
14835                            // gated layer is refused above.
14836                            head_gate: None,
14837                        }
14838                    }
14839                    AttnKind::LinearGdn(w) => {
14840                        let Some(cfg) = self.gdn_cfg else {
14841                            if batch_debug {
14842                                eprintln!("batch graph: no GDN config at layer {li}");
14843                            }
14844                            return None;
14845                        };
14846                        let (m, _, _, _) = w
14847                            .in_proj_qkv
14848                            .graph_weight()
14849                            .or_else(|| w.in_proj_qkv.graph_weight_descriptor())?;
14850                        model = Some(m.clone());
14851                        crate::gpu::GraphAttn::Gdn {
14852                            qkv: gw(&w.in_proj_qkv)?,
14853                            z: gw(&w.in_proj_z)?,
14854                            a: gw(&w.in_proj_a)?,
14855                            b: gw(&w.in_proj_b)?,
14856                            out: gw(&w.out_proj)?,
14857                            conv1d: &w.conv1d,
14858                            a_log: &w.a_log,
14859                            dt_bias: &w.dt_bias,
14860                            norm: &w.norm,
14861                            nv: cfg.num_v_heads,
14862                            nk: cfg.num_k_heads,
14863                            dk: cfg.key_head_dim,
14864                            dv: cfg.value_head_dim,
14865                            kk: cfg.conv_kernel,
14866                            cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
14867                        }
14868                    }
14869                    _ => return None,
14870                };
14871                // Gemma-4's sandwich norms and layer scalar (`gemma_batch`);
14872                // every other model hands the graph none, as before.
14873                let g4 = self.global_attn.is_some() || self.attn_v_norm;
14874                layers.push(crate::gpu::GraphLayer {
14875                    input_norm: &lw.input_norm,
14876                    attn,
14877                    post_norm: &lw.post_norm,
14878                    attn_out_norm: if g4 {
14879                        lw.attn_out_norm.as_deref()
14880                    } else {
14881                        None
14882                    },
14883                    ffn_out_norm: if g4 { lw.ffn_out_norm.as_deref() } else { None },
14884                    layer_scale: if g4 { lw.layer_scale } else { None },
14885                    ffn: gffn,
14886                });
14887            }
14888            Some((layers, model?))
14889        })();
14890        let Some((layers, model)) = built else {
14891            {
14892                use std::sync::atomic::{AtomicBool, Ordering};
14893                static SAID: AtomicBool = AtomicBool::new(false);
14894                if !SAID.swap(true, Ordering::Relaxed) {
14895                    tracing::warn!("batch graph: BUILDER refused (layer weights/kinds)");
14896                }
14897            }
14898            return crate::gpu::BatchGraphOutcome::Declined;
14899        };
14900        if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
14901            eprintln!("batch-build: {:.1} ms", _tb.elapsed().as_secs_f64() * 1e3);
14902        }
14903        crate::gpu::forward_batch_graph(
14904            &model,
14905            self.graph_kv_id,
14906            &layers,
14907            &self.inv_freq,
14908            hiddens,
14909            nh,
14910            nkv,
14911            hd,
14912            rd,
14913            self.hidden_size,
14914            self.intermediate_size,
14915            positions,
14916            self.kv_cache.max_seq_len,
14917            gemma,
14918            self.rms_eps as f32,
14919            self.attn_scale,
14920            k,
14921            &(0..graph_end)
14922                .map(|li| self.kv_cache.layers[self.phys_layer(li)].o1_views())
14923                .collect::<Vec<_>>(),
14924            self.o1_epoch,
14925            spec,
14926            layers_run,
14927        )
14928    }
14929
14930    /// Same, stopping after layer `upto` inclusive (routing probe φ).
14931    /// `CMF_DSV4_DRAFT_PROBE=1` — grade the draft against what the trunk goes on
14932    /// to produce. Off by default; it runs a whole draft per decoded token.
14933    fn draft_probe() -> bool {
14934        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
14935        *ON.get_or_init(|| std::env::var("CMF_DSV4_DRAFT_PROBE").is_ok_and(|v| v != "0"))
14936    }
14937
14938    /// `CMF_DSV4_DRAFT_PROBE=1`: measure how much of the draft the trunk
14939    /// would have agreed with, WITHOUT verifying or rolling anything back.
14940    ///
14941    /// The number this produces decides the whole speculation design — at
14942    /// acceptance a, a block of B positions yields 1 + a + a² + ... tokens
14943    /// per trunk pass — so it is worth measuring before any of the machinery
14944    /// that would exploit it exists. Each draft is parked with the position
14945    /// it was made at, and graded as the real tokens arrive.
14946    /// `CMF_DSV4_SPEC=1` — the DeepSeek-V4 speculative decode: draft five
14947    /// on the card, verify them in one batched trunk pass, commit the
14948    /// accepted prefix, roll the rest back.
14949    #[cfg(feature = "gpu")]
14950    fn dsv4_spec_on() -> bool {
14951        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
14952        *ON.get_or_init(|| {
14953            // Test-only runtime gate: model loading still performs the same
14954            // reservation and trunk packing, which gives rollback parity a
14955            // topology-identical non-speculative control arm.
14956            if let Ok(v) = std::env::var("CMF_DSV4_SPEC_RUN") {
14957                return v != "0";
14958            }
14959            // An explicit value is a diagnostic force/escape hatch.  With no
14960            // knob, speculation is eligible only when model loading reserved
14961            // its bounded pack.  On small q4tp cards the geometric reserve
14962            // gate deliberately leaves this at zero: trying to build DSpark
14963            // after the exact trunk filled VRAM is both slower and a device
14964            // OOM (measured on A40).
14965            std::env::var("CMF_DSV4_SPEC")
14966                .map(|v| v != "0")
14967                .unwrap_or_else(|_| {
14968                    crate::gpu_wgpu::DRAFT_RESERVE.load(std::sync::atomic::Ordering::Relaxed) > 0
14969                })
14970        })
14971    }
14972
14973    /// One speculative round at the decode tip. `t_next` is the token the
14974    /// sampler just committed for `next_pos`. Returns the EXTRA accepted
14975    /// tokens (possibly none) and the new position, with `graph_logits`
14976    /// left holding the last accepted position's logits — exactly what the
14977    /// loop top expects. `None` means "speculate not this round": nothing
14978    /// was committed, the caller forwards normally.
14979    #[cfg(feature = "gpu")]
14980    fn dsv4_spec_step(
14981        &mut self,
14982        tip_token: u32,
14983        t_next: u32,
14984        next_pos: usize,
14985        max_extra: usize,
14986        drafted: &mut usize,
14987        accepted_ctr: &mut usize,
14988    ) -> Option<(Vec<u32>, usize)> {
14989        let t_all = std::time::Instant::now();
14990        if std::env::var("CMF_DSV4_SPEC_TIME").is_ok() {
14991            thread_local! {
14992                static LAST: std::cell::Cell<Option<std::time::Instant>> =
14993                    const { std::cell::Cell::new(None) };
14994            }
14995            LAST.with(|l| {
14996                if let Some(prev) = l.get() {
14997                    eprintln!(
14998                        "между раундами {:.1} мс",
14999                        prev.elapsed().as_secs_f64() * 1e3
15000                    );
15001                }
15002                l.set(Some(std::time::Instant::now()));
15003            });
15004        }
15005        if std::env::var("CMF_DSV4_SPEC_DEBUG").is_ok() {
15006            eprintln!("spec_step: вход pos={next_pos}");
15007        }
15008        let n_layers = self.dsv4.as_ref().map(|b| b.1.len())?;
15009        let cfg = self.dsv4.as_ref().map(|b| b.2)?;
15010        // The draft state and its capture, armed exactly as the probe does.
15011        if self.dspark.is_none() {
15012            let t = crate::dsv4::dspark_targets(&self.dsv4_mtp, &cfg, n_layers);
15013            if t.is_empty() {
15014                return None;
15015            }
15016            crate::dsv4::dspark_arm(&t, cfg.dim);
15017            self.dspark = Some(crate::dsv4::DsparkState::new(
15018                self.dsv4_mtp.len(),
15019                &cfg,
15020                t.len(),
15021            ));
15022        }
15023        let targets = crate::dsv4::dspark_targets(&self.dsv4_mtp, &cfg, n_layers);
15024        let pack = crate::dsv4::dspark_pack_get(&self.dsv4_mtp, &cfg);
15025        if pack.is_none() && std::env::var("CMF_DSV4_SPEC_DEBUG").is_ok() {
15026            eprintln!("spec_step: пак не построился (targets {targets:?})");
15027        }
15028        let pack = pack?;
15029        let block = crate::dsv4::dspark_block();
15030        let b_box = self.dsv4.as_mut()?;
15031        let (g, layers, st) = (&b_box.0, &b_box.1, &mut b_box.3);
15032        let ds = self.dspark.as_mut()?;
15033        // The tip's captures: either this token ran on a normal path that
15034        // filled the thread-local, or the previous spec round left them.
15035        let dbg = std::env::var("CMF_DSV4_SPEC_DEBUG").is_ok();
15036        if !crate::dsv4::dspark_take(&mut ds.main_hidden) && !ds.have_hidden {
15037            if dbg {
15038                eprintln!("spec_step: нет захвата");
15039            }
15040            return None;
15041        }
15042        ds.have_hidden = true;
15043        let tip_pos = next_pos.checked_sub(1)?;
15044        let draft_started = std::time::Instant::now();
15045        let mut conf = Vec::new();
15046        let props = crate::dsv4::dspark_draft_gpu(
15047            g,
15048            &self.dsv4_mtp,
15049            &cfg,
15050            ds,
15051            pack,
15052            st.kv_id,
15053            tip_token,
15054            tip_pos,
15055            self.pool.as_deref(),
15056            &mut conf,
15057        );
15058        self.dspark_draft_ns += draft_started.elapsed().as_nanos();
15059        *drafted += block;
15060        if props.is_empty() || props[0] != t_next {
15061            if dbg {
15062                eprintln!(
15063                    "spec_step: черновик {} (props0={:?} t_next={t_next})",
15064                    if props.is_empty() {
15065                        "пуст"
15066                    } else {
15067                        "мимо"
15068                    },
15069                    props.first()
15070                );
15071            }
15072            return None;
15073        }
15074        // `fed[0]` is `t_next`, which the outer loop has already committed;
15075        // only `fed[1..]` become additional output tokens. Cap the verify
15076        // transaction itself to the caller's remaining output budget instead
15077        // of merely truncating the returned vector: otherwise the KV/state
15078        // would advance past `max_tokens` and a 64-token request could return
15079        // 66 tokens (and poison a reused session with two invisible steps).
15080        let mut k_verify = crate::dsv4::dspark_verify_k()
15081            .min(props.len())
15082            .min(max_extra.saturating_add(1));
15083        // Adaptive depth: positions the draft itself doubts are paid for on
15084        // every verify and delivered almost never (natural-text survival
15085        // [.67 .50 .29 .08 .04]). `CMF_DSPARK_CONF_MIN=p` trims the fed
15086        // prefix at the first proposal whose confidence drops below p; on
15087        // predictable text the confidences stay high and nothing changes.
15088        let conf_min = {
15089            static M: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
15090            *M.get_or_init(|| {
15091                std::env::var("CMF_DSPARK_CONF_MIN")
15092                    .ok()
15093                    .and_then(|v| v.parse().ok())
15094                    .unwrap_or(0.0)
15095            })
15096        };
15097        if conf_min > 0.0 && conf.len() >= props.len() {
15098            let mut keep = 1usize;
15099            while keep < k_verify && conf.get(keep).copied().unwrap_or(0.0) >= conf_min {
15100                keep += 1;
15101            }
15102            k_verify = k_verify.min(keep.max(2));
15103        }
15104        if k_verify < 2 {
15105            return None;
15106        }
15107        let mut fed = Vec::with_capacity(k_verify);
15108        fed.push(t_next);
15109        fed.extend_from_slice(&props[1..k_verify]);
15110        let mut argmax = Vec::new();
15111        let mut logits_all = Vec::new();
15112        let mut walked = Vec::new();
15113        let txn = crate::dsv4::dsv4_verify_chunk(
15114            g,
15115            layers,
15116            &cfg,
15117            st,
15118            &fed,
15119            next_pos,
15120            &self.inv_freq,
15121            self.pool.as_deref(),
15122            &targets,
15123            &mut argmax,
15124            &mut logits_all,
15125            &mut walked,
15126        );
15127        if txn.is_none() && dbg {
15128            eprintln!("spec_step: verify отказал");
15129        }
15130        let txn = txn?;
15131        let spec_gpu_end = txn.gpu_end;
15132        let b = fed.len();
15133        let mut accepted = 1usize;
15134        while accepted < b && fed[accepted] == argmax[accepted - 1] {
15135            accepted += 1;
15136        }
15137        // `CMF_DSV4_SPEC_FORCE_REJECT=1` — accept nothing beyond the known
15138        // token, every round: the pure rollback exerciser. The output must
15139        // stay byte-identical to the plain walk; anything else is a
15140        // transaction bug, isolated from the acceptance logic.
15141        if std::env::var("CMF_DSV4_SPEC_FORCE_REJECT").is_ok_and(|v| v != "0") {
15142            accepted = 1;
15143        }
15144        if std::env::var("CMF_DSV4_SPEC_TRACE").is_ok() {
15145            eprintln!("spec@{next_pos}: fed={fed:?} argmax={argmax:?} accepted={accepted}");
15146        }
15147        let t_fin = std::time::Instant::now();
15148        if !crate::dsv4::dsv4_spec_finish(
15149            g,
15150            layers,
15151            &cfg,
15152            st,
15153            txn,
15154            accepted,
15155            &fed,
15156            &self.inv_freq,
15157            self.pool.as_deref(),
15158        ) {
15159            tracing::warn!("dsv4: спекулятивный откат не удался — состояние подозрительно");
15160            return None;
15161        }
15162        if std::env::var("CMF_DSV4_SPEC_TIME").is_ok() {
15163            eprintln!(
15164                "finish(k={accepted}): {:.1} мс",
15165                t_fin.elapsed().as_secs_f64() * 1e3
15166            );
15167        }
15168        *accepted_ctr += accepted - 1;
15169        // Captures per accepted token: device targets photographed by the
15170        // batch, host targets from the verify's own walk. The last one
15171        // becomes the new tip's draft input; every one owes the ring an
15172        // entry for its position.
15173        let (hc, dim) = (cfg.hc_mult, cfg.dim);
15174        // Complete-chain layers are photographed by the fused submission;
15175        // partial device layers overwrite that slot after exact host cold-
15176        // expert correction.  Thus every target in the contiguous device
15177        // prefix has a valid per-token capture.
15178        let dev_caps: Vec<usize> = targets
15179            .iter()
15180            .copied()
15181            .filter(|&t| t < spec_gpu_end)
15182            .collect();
15183        let mut caps_all = vec![0.0f32; dev_caps.len() * b * hc * dim];
15184        if !crate::gpu_wgpu::dsv4_spec_cap_read_all(b, dev_caps.len(), hc * dim, &mut caps_all) {
15185            return None;
15186        }
15187        for t in 0..accepted {
15188            let tip = t + 1 == accepted;
15189            for (slot, &tl) in targets.iter().enumerate() {
15190                if let Some(di) = dev_caps.iter().position(|&d| d == tl) {
15191                    let lo = (di * b + t) * hc * dim;
15192                    crate::dsv4::dspark_capture(
15193                        &caps_all[lo..lo + hc * dim],
15194                        &cfg,
15195                        slot,
15196                        &mut ds.main_hidden,
15197                    );
15198                } else if tip
15199                    && crate::dsv4::dspark_peek_slot(slot, dim, {
15200                        let lo = slot * dim;
15201                        &mut ds.main_hidden[lo..lo + dim]
15202                    })
15203                {
15204                    // The tip's host-layer captures are the walk's own
15205                    // per-layer notes — exact. (The walk that ran last ended
15206                    // on exactly this token, on both the accept-all and the
15207                    // rollback path.)
15208                } else {
15209                    // Intermediate tokens: the post-tail state stands in for
15210                    // the per-layer capture on host targets below the last
15211                    // layer. Ring-entry quality only; the tip is exact.
15212                    crate::dsv4::dspark_capture(
15213                        &walked[t * hc * dim..(t + 1) * hc * dim],
15214                        &cfg,
15215                        slot,
15216                        &mut ds.main_hidden,
15217                    );
15218                }
15219            }
15220            crate::dsv4::dspark_ring_append(
15221                g,
15222                &self.dsv4_mtp,
15223                &cfg,
15224                ds,
15225                next_pos + t,
15226                self.pool.as_deref(),
15227            );
15228        }
15229        let row = logits_all[(accepted - 1) * cfg.vocab..accepted * cfg.vocab].to_vec();
15230        self.graph_logits = Some(row);
15231        // The speculative loop never runs the probe, so the trunk tally has
15232        // no other place to cycle. Armed only when someone asked for the
15233        // dump; the host tail is the only tallying path here, which is
15234        // precisely the population a partial pack would serve.
15235        if std::env::var("CMF_DSV4_TRUNK_PICK_DUMP").is_ok() {
15236            crate::dsv4::trunk_freq_note(&crate::dsv4::pick_tally_take());
15237            crate::dsv4::pick_tally_arm();
15238        }
15239        if std::env::var("CMF_DSV4_SPEC_TIME").is_ok() {
15240            eprintln!(
15241                "spec_step total {:.1} мс (k={accepted})",
15242                t_all.elapsed().as_secs_f64() * 1e3
15243            );
15244        }
15245        Some((fed[1..accepted].to_vec(), next_pos + accepted))
15246    }
15247
15248    fn dspark_probe(&mut self, position: usize, token_id: u32) {
15249        if self.dsv4_mtp.is_empty() || !Self::draft_probe() {
15250            return;
15251        }
15252        // What the trunk just routed to, for this token.
15253        let trunk_now = crate::dsv4::pick_tally_take();
15254        crate::dsv4::trunk_freq_note(&trunk_now);
15255        if !trunk_now.is_empty() {
15256            self.dspark_trunk_picks.push(trunk_now);
15257            let keep = crate::dsv4::dspark_block();
15258            if self.dspark_trunk_picks.len() > keep {
15259                self.dspark_trunk_picks.remove(0);
15260            }
15261        }
15262        // Grade whatever is waiting: the token just decoded sits at
15263        // `position`, so it answers the draft made at `position - 1 - i`.
15264        for p in std::mem::take(&mut self.dspark_pending) {
15265            let Some(i) = position.checked_sub(p.0 + 1) else {
15266                continue;
15267            };
15268            let mut p = p;
15269            if i < p.1.len() {
15270                if p.2 && p.1[i] == token_id {
15271                    p.3 = i + 1;
15272                } else {
15273                    p.2 = false;
15274                }
15275                if i + 1 < p.1.len() {
15276                    self.dspark_pending.push(p);
15277                    continue;
15278                }
15279            }
15280            self.dspark_hist.push(p.3);
15281            self.dspark_real.push(token_id);
15282        }
15283        let Some(b) = &mut self.dsv4 else { return };
15284        let (g, layers, cfg) = (&b.0, &b.1, b.2);
15285        let n_layers = layers.len();
15286        if self.dspark.is_none() {
15287            let t = crate::dsv4::dspark_targets(&self.dsv4_mtp, &cfg, n_layers);
15288            if t.is_empty() {
15289                return;
15290            }
15291            eprintln!(
15292                "DSpark: захват со слоёв {t:?}, блок {}",
15293                crate::dsv4::dspark_block()
15294            );
15295            crate::dsv4::dspark_arm(&t, cfg.dim);
15296            self.dspark = Some(crate::dsv4::DsparkState::new(
15297                self.dsv4_mtp.len(),
15298                &cfg,
15299                t.len(),
15300            ));
15301        }
15302        let ds = self.dspark.as_mut().unwrap();
15303        if !crate::dsv4::dspark_take(&mut ds.main_hidden) {
15304            return; // this token ran on a path that captures nothing
15305        }
15306        let mut conf = Vec::new();
15307        crate::dsv4::pick_tally_arm();
15308        // The trunk has already consumed the adaptive VRAM budget. Until the
15309        // draft owns an explicit bounded device pack, its tensors are an
15310        // out-of-core CPU/disk tier by contract: never let per-op probes try
15311        // to squeeze another multi-gigabyte MTP expert cache onto the card.
15312        let draft_started = std::time::Instant::now();
15313        #[cfg(feature = "gpu")]
15314        let gpu_draft = crate::dsv4::dspark_gpu_on();
15315        #[cfg(not(feature = "gpu"))]
15316        let gpu_draft = false;
15317        let props = if gpu_draft {
15318            #[cfg(feature = "gpu")]
15319            {
15320                let kv_id = b.3.kv_id;
15321                match crate::dsv4::dspark_pack_get(&self.dsv4_mtp, &cfg) {
15322                    Some(pk) => crate::dsv4::dspark_draft_gpu(
15323                        g,
15324                        &self.dsv4_mtp,
15325                        &cfg,
15326                        ds,
15327                        pk,
15328                        kv_id,
15329                        token_id,
15330                        position,
15331                        self.pool.as_deref(),
15332                        &mut conf,
15333                    ),
15334                    None => Vec::new(),
15335                }
15336            }
15337            #[cfg(not(feature = "gpu"))]
15338            Vec::new()
15339        } else {
15340            crate::gpu::cpu_scope(|| {
15341                crate::dsv4::dspark_draft(
15342                    g,
15343                    &self.dsv4_mtp,
15344                    &cfg,
15345                    ds,
15346                    token_id,
15347                    position,
15348                    self.pool.as_deref(),
15349                    &mut conf,
15350                )
15351            })
15352        };
15353        self.dspark_draft_ns += draft_started.elapsed().as_nanos();
15354        let draft_picks = crate::dsv4::pick_tally_take();
15355        crate::dsv4::dspark_freq_note(&draft_picks);
15356        // Re-arm for the NEXT trunk token; the probe runs after the forward,
15357        // so this is the only place that can.
15358        crate::dsv4::pick_tally_arm();
15359        if !props.is_empty() {
15360            // Two ratios, side by side: what a batched verify over the trunk
15361            // would read against what it asks for, and the same for the
15362            // draft's three stages. Near 1.0 means a batch amortises nothing.
15363            let (tu, tt) = {
15364                let flat: Vec<(usize, Vec<usize>)> = self
15365                    .dspark_trunk_picks
15366                    .iter()
15367                    .flat_map(|v| v.iter().cloned())
15368                    .collect();
15369                // Per layer, across the window of tokens.
15370                let mut per: std::collections::HashMap<usize, Vec<usize>> =
15371                    std::collections::HashMap::new();
15372                for (li, picks) in flat {
15373                    per.entry(li).or_default().extend(picks);
15374                }
15375                let n = per.len().max(1);
15376                let mut u = 0usize;
15377                let mut t = 0usize;
15378                for (_, v) in per {
15379                    t += v.len();
15380                    u += v.iter().collect::<std::collections::HashSet<_>>().len();
15381                }
15382                (u / n, t / n)
15383            };
15384            let (du, dt) = crate::dsv4::tally_unique(&draft_picks);
15385            self.dspark_exp.push((tu, tt, du, dt));
15386            self.dspark_pending.push((position, props, true, 0));
15387        }
15388        if self.dspark_hist.len() >= 8 && self.dspark_hist.len() % 8 == 0 {
15389            let n = self.dspark_hist.len() as f32;
15390            let mean: f32 = self.dspark_hist.iter().sum::<usize>() as f32 / n;
15391            let block = crate::dsv4::dspark_block();
15392            let mut at = vec![0usize; block + 1];
15393            for &k in &self.dspark_hist {
15394                at[k] += 1;
15395            }
15396            // Prefix survival: S_i = P(the first i positions all held).
15397            let mut surv = Vec::with_capacity(block);
15398            for i in 1..=block {
15399                let k = at[i..].iter().sum::<usize>() as f32 / n;
15400                surv.push(format!("{k:.2}"));
15401            }
15402            let distinct = self
15403                .dspark_real
15404                .iter()
15405                .collect::<std::collections::HashSet<_>>()
15406                .len();
15407            let (tu, tt, du, dt) = self.dspark_exp.iter().fold((0, 0, 0, 0), |a, b| {
15408                (a.0 + b.0, a.1 + b.1, a.2 + b.2, a.3 + b.3)
15409            });
15410            let m = self.dspark_exp.len().max(1);
15411            eprintln!(
15412                "DSpark: черновиков {}, принято в среднем {mean:.2} из {block} \
15413                 (токенов за проход {:.2}), распределение {at:?}, выживание [{}]",
15414                self.dspark_hist.len(),
15415                mean + 1.0,
15416                surv.join(" ")
15417            );
15418            eprintln!(
15419                "DSpark: разных токенов {distinct} из {} (вырожденность), \
15420                 эксперты ствол {}/{} на слой за {block} токенов, \
15421                 черновик {}/{} за блок, draft {:.2} мс/блок",
15422                self.dspark_real.len(),
15423                tu / m,
15424                tt / m,
15425                du / m,
15426                dt / m,
15427                self.dspark_draft_ns as f64 / self.dspark_exp.len().max(1) as f64 / 1e6
15428            );
15429        }
15430    }
15431
15432    fn forward_layers_upto(
15433        &mut self,
15434        hidden: &[f32],
15435        position: usize,
15436        task_mask: Option<&TaskMask>,
15437        upto: Option<usize>,
15438    ) -> Vec<f32> {
15439        // In-process multi-GPU: each segment runs pinned to its card,
15440        // and the only thing crossing the boundary is one hidden vector
15441        // that never leaves this address space. Same layer split the
15442        // network mode does, minus the second process, the socket, the
15443        // serialization and the dir_hash handshake.
15444        if let Some(plan) = self.gpu_plan.clone() {
15445            if upto.is_none() && plan.len() > 1 {
15446                let mut h = hidden.to_vec();
15447                for &(dev, from, upto_incl) in plan.iter() {
15448                    h = crate::gpu::with_device(dev, || {
15449                        self.forward_layers_span(&h, position, task_mask, from, Some(upto_incl))
15450                    });
15451                }
15452                return h;
15453            }
15454        }
15455        self.forward_layers_span(hidden, position, task_mask, 0, upto)
15456    }
15457
15458    /// Split this pipeline's layer stack across local GPUs: segment i
15459    /// runs on `devices[i]`. Contiguous and even by layer count — the
15460    /// VRAM-weighted planner is the next step, and an uneven card pair
15461    /// is why it will be needed. `None` clears the plan.
15462    pub fn set_gpu_plan(&mut self, devices: Option<&[usize]>) -> Result<(), String> {
15463        self.set_gpu_plan_at(devices, None)
15464    }
15465
15466    /// The same, with an explicit first boundary (`--peer-split`): card
15467    /// 0 takes layers `[0..at)`, the rest split what remains. Uneven
15468    /// cards, or an attention-heavy head, are why this knob exists.
15469    pub fn set_gpu_plan_at(
15470        &mut self,
15471        devices: Option<&[usize]>,
15472        at: Option<usize>,
15473    ) -> Result<(), String> {
15474        let Some(devs) = devices.filter(|d| d.len() > 1) else {
15475            self.gpu_plan = None;
15476            return Ok(());
15477        };
15478        self.split_supported()?;
15479        let n = self.num_layers;
15480        if devs.len() > n {
15481            return Err(format!("{} devices for {n} layers", devs.len()));
15482        }
15483        if let Some(k) = at {
15484            if k == 0 || k >= n {
15485                return Err(format!("split at {k}: the model has {n} layers"));
15486            }
15487            if devs.len() == 2 {
15488                self.gpu_plan = Some(std::sync::Arc::new(vec![
15489                    (devs[0], 0, k - 1),
15490                    (devs[1], k, n - 1),
15491                ]));
15492                return Ok(());
15493            }
15494            return Err(format!(
15495                "an explicit split point takes exactly 2 devices, got {}",
15496                devs.len()
15497            ));
15498        }
15499        let per = n.div_ceil(devs.len());
15500        let mut plan = Vec::with_capacity(devs.len());
15501        let mut from = 0usize;
15502        for &d in devs {
15503            if from >= n {
15504                break;
15505            }
15506            let upto = (from + per - 1).min(n - 1);
15507            plan.push((d, from, upto));
15508            from = upto + 1;
15509        }
15510        self.gpu_plan = Some(std::sync::Arc::new(plan));
15511        Ok(())
15512    }
15513
15514    /// The active in-process split, if any: (device, first layer, last).
15515    pub fn gpu_plan(&self) -> Option<Vec<(usize, usize, usize)>> {
15516        self.gpu_plan.as_ref().map(|p| p.as_ref().clone())
15517    }
15518
15519    /// Layer span [from ..= upto] (upto None = last layer): the building
15520    /// block the network pipeline-split rides on. `from > 0` skips the
15521    /// arch escape hatches (the pub `forward_span` refuses those archs
15522    /// first) and the whole-token graph — the plain per-layer loop is
15523    /// the canonical executor for a partial stack.
15524    fn embryo_qtensor_f32(t: &QTensor) -> Vec<f32> {
15525        if let Some(x) = t.as_f32() {
15526            return x.to_vec();
15527        }
15528        let mut out = vec![0.0; t.rows() * t.cols()];
15529        for r in 0..t.rows() {
15530            t.row_f32(r, &mut out[r * t.cols()..(r + 1) * t.cols()]);
15531        }
15532        out
15533    }
15534
15535    fn embryo_resident_eligible(&self) -> bool {
15536        // One mixer family per file: vmf_phase (kind 0/1) or
15537        // gated_delta_net (kind 4); the anchors are full (2) or bounded (3).
15538        if (self.vmf_cfg.is_none() && self.gdn_cfg.is_none())
15539            || self.num_layers != self.physical_layers
15540            || self.loop_final_norm
15541            || self.weights.layers.len() != self.num_layers
15542            || self.head_clusters.is_none()
15543            || self.final_softcap.is_some()
15544            || self.logit_multiplier.is_some()
15545            || self.attn_softcap != 0.0
15546            || self.mtp.is_some()
15547            || self.per_token_stack()
15548            || self.dsv4.is_some()
15549            || self.dsv41.is_some()
15550            || self.qwen4_exp.is_some()
15551            // Dynamic routing swaps FFN weights mid-sequence under the
15552            // packed graph; a blend has no single overlay. A STATIC skill
15553            // (`from_model_with_skill`) is fine: the pack reads the live
15554            // `weights.layers[*].ffn`, i.e. the skill's tensors, and a
15555            // later `set_active_skill` change drops the pack
15556            // (`invalidate_for_weight_change`).
15557            || self.dyn_router.is_some()
15558            || self.dyn_phi_layer.is_some()
15559            || self.dyn_blend_loaded
15560            || self.o1_cfg.is_some()
15561            || self.swa.is_some()
15562            || self.sliding_layers.is_some()
15563            || self.global_attn.is_some()
15564            || self.attention_heads_per_layer.is_some()
15565            || self.attn_v_norm
15566            || self
15567                .kv_cache
15568                .layers
15569                .iter()
15570                .any(|l| l.mode != crate::kv_cache::KvMode::F32)
15571            || self.rope_scale != 1.0
15572            || self.rope_scale_local != 1.0
15573            || self.attn_scale != 1.0 / (self.head_dim as f32).sqrt()
15574            || self.hidden_size == 0
15575            || self.hidden_size > 1024
15576            || self.intermediate_size > 1024
15577            || self.num_heads == 0
15578            || self.num_kv_heads == 0
15579            || self.num_heads % self.num_kv_heads != 0
15580            || self.num_heads.saturating_mul(self.head_dim) > 1024
15581            || self.num_kv_heads.saturating_mul(self.head_dim) > 1024
15582            || self.vocab_size == 0
15583            || self.kv_cache.max_seq_len == 0
15584            || self.rotary_dim == 0
15585            || self.rotary_dim > self.head_dim
15586            || self.rotary_dim % 2 != 0
15587            || self.inv_freq.len() < self.rotary_dim / 2
15588        {
15589            return false;
15590        }
15591        // The resident shader is deliberately an f32 profile.  Dequantizing
15592        // a Q4/Q8 tensor into the packed buffer would silently change the
15593        // operator relative to the CPU quantized path, so quantized CMFs
15594        // retain the exact ordinary executor instead of claiming parity.
15595        // Measured consequence (RTX PRO 4000, S4 bounded export requantized
15596        // with `cortiq requant --quant q4tp-quantize`): `eligible=false`,
15597        // the generic wgpu whole-token graph refuses too, and the per-op
15598        // path decodes at ~73 tok/s against ~200 tok/s on the CPU q4tp
15599        // path — a q4tp Embryo-O1 file is a CPU artifact today; the
15600        // resident graph serves the f32 export.
15601        if self.weights.lm_head.as_f32().is_none()
15602            || self.weights.embed_tokens.as_f32().is_none()
15603            || self.weights.lm_head.rows() < self.vocab_size
15604            || self.weights.lm_head.cols() != self.hidden_size
15605            || self.weights.embed_tokens.rows() < self.vocab_size
15606            || self.weights.embed_tokens.cols() != self.hidden_size
15607            || self.weights.final_norm.len() != self.hidden_size
15608        {
15609            return false;
15610        }
15611        if let Some(cfg) = self.vmf_cfg {
15612            if cfg.num_heads.saturating_mul(cfg.nphase) > 1024
15613                || cfg.num_heads.saturating_mul(cfg.nphase.saturating_add(1)) > 1024
15614                || cfg.num_heads.saturating_mul(cfg.value_head_dim) > 1024
15615                || cfg.state_len() == 0
15616            {
15617                return false;
15618            }
15619        }
15620        if let Some(g) = self.gdn_cfg {
15621            // The resident GDN kernels (gpu_wgpu.rs `embryo_core_gdn_*`):
15622            // fused projection ≤ 2048 rows, nv·dv ≤ 1024, dk ≤ 128 lanes,
15623            // dv ≤ 256 lanes in vec4 rows, SiLU output gate (the Embryo
15624            // export), same rms eps as the stack.
15625            if g.num_v_heads == 0
15626                || g.num_k_heads == 0
15627                || g.num_v_heads % g.num_k_heads != 0
15628                || g.key_head_dim == 0
15629                || g.key_head_dim > 128
15630                || g.value_head_dim == 0
15631                || g.value_head_dim > 256
15632                || g.value_head_dim % 4 != 0
15633                || g.conv_kernel == 0
15634                || g.num_v_heads > 512
15635                || g.num_v_heads.saturating_mul(g.value_head_dim) > 1024
15636                || g.conv_dim() > 2048
15637                || g.conv_dim() % 4 != 0
15638                || g.hidden_size != self.hidden_size
15639                || g.output_gate_sigmoid
15640                || g.rms_eps != self.rms_eps
15641                || g.state_len() == 0
15642            {
15643                return false;
15644            }
15645        }
15646        let mut full_seen = false;
15647        for lw in &self.weights.layers {
15648            if lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some() {
15649                return false;
15650            }
15651            match &lw.attn {
15652                AttnKind::LinearGdn(w) => {
15653                    let Some(g) = self.gdn_cfg else {
15654                        return false;
15655                    };
15656                    let (nv, dv, kk) = (g.num_v_heads, g.value_head_dim, g.conv_kernel);
15657                    if w.in_proj_qkv.rows() != g.conv_dim()
15658                        || w.in_proj_qkv.cols() != self.hidden_size
15659                        || w.in_proj_qkv.as_f32().is_none()
15660                        || w.in_proj_z.rows() != nv * dv
15661                        || w.in_proj_z.cols() != self.hidden_size
15662                        || w.in_proj_z.as_f32().is_none()
15663                        || w.in_proj_a.rows() != nv
15664                        || w.in_proj_a.cols() != self.hidden_size
15665                        || w.in_proj_a.as_f32().is_none()
15666                        || w.in_proj_b.rows() != nv
15667                        || w.in_proj_b.cols() != self.hidden_size
15668                        || w.in_proj_b.as_f32().is_none()
15669                        || w.conv1d.len() != g.conv_dim() * kk
15670                        || w.a_log.len() != nv
15671                        || w.dt_bias.len() != nv
15672                        || w.norm.len() != dv
15673                        || w.out_proj.rows() != self.hidden_size
15674                        || w.out_proj.cols() != nv * dv
15675                        || w.out_proj.as_f32().is_none()
15676                    {
15677                        return false;
15678                    }
15679                }
15680                AttnKind::Linear(w) => {
15681                    let Some(cfg) = self.vmf_cfg else {
15682                        return false;
15683                    };
15684                    if w.thq.rows() != cfg.num_heads * cfg.nphase
15685                        || w.thq.cols() != self.hidden_size
15686                        || w.thq.as_f32().is_none()
15687                        || w.thk.rows() != cfg.num_heads * cfg.nphase
15688                        || w.thk.cols() != self.hidden_size
15689                        || w.thk.as_f32().is_none()
15690                        || w.v_proj.rows() != cfg.num_heads * cfg.value_head_dim
15691                        || w.v_proj.cols() != self.hidden_size
15692                        || w.v_proj.as_f32().is_none()
15693                        || w.out_proj.rows() != self.hidden_size
15694                        || w.out_proj.cols() != cfg.num_heads * cfg.value_head_dim
15695                        || w.out_proj.as_f32().is_none()
15696                        || w.decay.len() != cfg.num_heads * 2 * cfg.nphase
15697                    {
15698                        return false;
15699                    }
15700                    if let Some((kg, kb)) = &w.k_gate {
15701                        if kg.rows() != cfg.num_heads
15702                            || kg.cols() != self.hidden_size
15703                            || kg.as_f32().is_none()
15704                            || kb.len() != cfg.num_heads
15705                        {
15706                            return false;
15707                        }
15708                    }
15709                    if let Some(conv) = &w.conv {
15710                        if conv.len() % self.hidden_size != 0 || conv.len() / self.hidden_size < 2 {
15711                            return false;
15712                        }
15713                    }
15714                }
15715                AttnKind::Full {
15716                    wq,
15717                    wk,
15718                    wv,
15719                    wo,
15720                    q_norm,
15721                    k_norm,
15722                    output_gate,
15723                    softplus_gate,
15724                    bias,
15725                } => {
15726                    if full_seen
15727                        || q_norm.is_some()
15728                        || k_norm.is_some()
15729                        || *output_gate
15730                        || softplus_gate.is_some()
15731                        || bias.is_some()
15732                        || wq.as_f32().is_none()
15733                        || wk.as_f32().is_none()
15734                        || wv.as_f32().is_none()
15735                        || wo.as_f32().is_none()
15736                        || wq.rows() != self.num_heads * self.head_dim
15737                        || wk.rows() != self.num_kv_heads * self.head_dim
15738                        || wv.rows() != self.num_kv_heads * self.head_dim
15739                        || wq.cols() != self.hidden_size
15740                        || wk.cols() != self.hidden_size
15741                        || wv.cols() != self.hidden_size
15742                        || wo.rows() != self.hidden_size
15743                        || wo.cols() != self.num_heads * self.head_dim
15744                    {
15745                        return false;
15746                    }
15747                    full_seen = true;
15748                }
15749                AttnKind::Bounded(w) => {
15750                    // The resident bounded attend scores S + W lanes in one
15751                    // 256-lane chunk; the format caps S + W at 160.
15752                    let Some(ac) = self.anchor_core.as_ref() else {
15753                        return false;
15754                    };
15755                    if self.bounded_rope.is_none()
15756                        || w.window != ac.window
15757                        || w.sink != ac.sink
15758                        || w.window == 0
15759                        || w.window + w.sink > 256
15760                        || w.sink_k.len() != self.num_kv_heads * w.sink * self.head_dim
15761                        || w.sink_v.len() != self.num_kv_heads * w.sink * self.head_dim
15762                        || w.wq.as_f32().is_none()
15763                        || w.wk.as_f32().is_none()
15764                        || w.wv.as_f32().is_none()
15765                        || w.wo.as_f32().is_none()
15766                        || w.wq.rows() != self.num_heads * self.head_dim
15767                        || w.wk.rows() != self.num_kv_heads * self.head_dim
15768                        || w.wv.rows() != self.num_kv_heads * self.head_dim
15769                        || w.wq.cols() != self.hidden_size
15770                        || w.wk.cols() != self.hidden_size
15771                        || w.wv.cols() != self.hidden_size
15772                        || w.wo.rows() != self.hidden_size
15773                        || w.wo.cols() != self.num_heads * self.head_dim
15774                    {
15775                        return false;
15776                    }
15777                }
15778                _ => return false,
15779            }
15780            match &lw.ffn {
15781                FfnKind::Dense(d) => {
15782                    if d.act != Act::Silu
15783                        || !d.segs.is_empty()
15784                        || d.gate_proj.as_f32().is_none()
15785                        || d.up_proj.as_f32().is_none()
15786                        || d.down_proj.as_f32().is_none()
15787                        || d.gate_proj.rows() != self.intermediate_size
15788                        || d.gate_proj.cols() != self.hidden_size
15789                        || d.up_proj.rows() != self.intermediate_size
15790                        || d.up_proj.cols() != self.hidden_size
15791                        || d.down_proj.rows() != self.hidden_size
15792                        || d.down_proj.cols() != self.intermediate_size
15793                    {
15794                        return false;
15795                    }
15796                }
15797                FfnKind::Moe(m) => {
15798                    if m.resonance.is_none()
15799                        || m.top_k != 1
15800                        || m.router_sigmoid
15801                        || !m.norm_topk_prob
15802                        || m.expert_bias.is_some()
15803                        || m.routed_scaling != 1.0
15804                        || m.route_tau.is_some()
15805                        || m.shared.is_none()
15806                        || m.mask.is_some()
15807                        || m.per_expert_scale.is_some()
15808                        || m.router_input_norm
15809                        || m.experts.is_empty()
15810                        || m.experts.len() > 8
15811                    {
15812                        return false;
15813                    }
15814                    let r = m.resonance.as_ref().unwrap();
15815                    if r.mu.len() != m.experts.len() * self.hidden_size
15816                        || r.bias.len() != m.experts.len()
15817                        || r.u.len() != m.experts.len() * r.k * self.hidden_size
15818                        || r.k > 128
15819                    {
15820                        return false;
15821                    }
15822                    let Some((shared, gate)) = &m.shared else {
15823                        return false;
15824                    };
15825                    if gate.is_some() || shared.act != Act::Silu || !shared.segs.is_empty() {
15826                        return false;
15827                    }
15828                    if shared.gate_proj.as_f32().is_none()
15829                        || shared.up_proj.as_f32().is_none()
15830                        || shared.down_proj.as_f32().is_none()
15831                        || shared.gate_proj.rows() != self.intermediate_size
15832                        || shared.gate_proj.cols() != self.hidden_size
15833                        || shared.up_proj.rows() != self.intermediate_size
15834                        || shared.up_proj.cols() != self.hidden_size
15835                        || shared.down_proj.rows() != self.hidden_size
15836                        || shared.down_proj.cols() != self.intermediate_size
15837                    {
15838                        return false;
15839                    }
15840                    for e in &m.experts {
15841                        if e.act != Act::Silu
15842                            || !e.segs.is_empty()
15843                            || e.gate_proj.as_f32().is_none()
15844                            || e.up_proj.as_f32().is_none()
15845                            || e.down_proj.as_f32().is_none()
15846                            || e.gate_proj.rows() != self.intermediate_size
15847                            || e.gate_proj.cols() != self.hidden_size
15848                            || e.up_proj.rows() != self.intermediate_size
15849                            || e.up_proj.cols() != self.hidden_size
15850                            || e.down_proj.rows() != self.hidden_size
15851                            || e.down_proj.cols() != self.intermediate_size
15852                        {
15853                            return false;
15854                        }
15855                    }
15856                }
15857                FfnKind::DenseMoe(_) => return false,
15858            }
15859            if lw.input_norm.len() != self.hidden_size || lw.post_norm.len() != self.hidden_size {
15860                return false;
15861            }
15862        }
15863        if full_seen && self.anchor_core.is_some() {
15864            return false;
15865        }
15866        full_seen || self.num_layers > 0
15867    }
15868
15869    /// The resident Embryo graph is the owner of this pipeline's forward:
15870    /// the same gate `forward_layers_span` applies before handing a token
15871    /// to `forward_embryo_graph` (both graph phases on, the explicit
15872    /// opt-in, a wgpu device, no earlier refusal, an eligible stack).
15873    fn embryo_resident_wanted(&self) -> bool {
15874        crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)
15875            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill)
15876            && matches!(
15877                std::env::var("CMF_EMBRYO_RESIDENT").as_deref(),
15878                Ok("1") | Ok("parallel")
15879            )
15880            && crate::gpu::enabled_here()
15881            && !self.graph_refused()
15882            && self.embryo_resident_eligible()
15883    }
15884
15885    /// Chunked prefill on the resident graph: `ids` from `start` in
15886    /// chunks of `EMBRYO_CHUNK_MAX`, one submit each, projections/FFN as
15887    /// chunk GEMMs and the recurrent layers walked in time on the device.
15888    /// Returns the last position's logits when the whole span ran there.
15889    /// `None` = refused before any device work (the per-position path
15890    /// takes the span).  `CMF_EMBRYO_CHUNK=0` keeps the per-position
15891    /// prefill (A/B and the parity reference).
15892    fn embryo_prefill_chunked(&mut self, ids: &[u32], start: usize) -> Option<Vec<f32>> {
15893        if ids.len() < 2
15894            || std::env::var("CMF_EMBRYO_CHUNK").as_deref() == Ok("0")
15895            || !self.embryo_resident_wanted()
15896        {
15897            return None;
15898        }
15899        let model = self.ensure_embryo_graph()?;
15900        let cmax = std::env::var("CMF_EMBRYO_CHUNK")
15901            .ok()
15902            .and_then(|v| v.parse::<usize>().ok())
15903            .filter(|&v| v >= 1)
15904            .unwrap_or(crate::gpu::EMBRYO_CHUNK_MAX)
15905            .min(crate::gpu::EMBRYO_CHUNK_MAX);
15906        let hs = self.hidden_size;
15907        let n = ids.len();
15908        let mut pos = start;
15909        let mut last = None;
15910        let mut rows = Vec::with_capacity(cmax * hs);
15911        while pos < n {
15912            let end = (pos + cmax).min(n);
15913            rows.clear();
15914            for &id in &ids[pos..end] {
15915                rows.extend_from_slice(&self.embed_single(id));
15916            }
15917            let mut lg = Vec::new();
15918            if !crate::gpu::forward_embryo_graph_chunk(
15919                &model,
15920                self.graph_kv_id,
15921                &rows,
15922                pos,
15923                end - pos,
15924                &mut lg,
15925            ) {
15926                if pos == start {
15927                    if std::env::var("CMF_EMBRYO_DBG").as_deref() == Ok("1") {
15928                        eprintln!("embryo-dbg: chunk prefill refused at position {pos}");
15929                    }
15930                    return None;
15931                }
15932                // The device sequence advanced through the earlier chunks;
15933                // a host continuation would mix two owners of the state.
15934                // Fail this sequence alone, leaving no stale state or key.
15935                self.kv_cache.clear();
15936                self.clear_history();
15937                crate::gpu::graph_kv_reset(self.graph_kv_id);
15938                panic!(
15939                    "resident Embryo chunk prefill refused at position {pos}; refusing an in-flight host fallback"
15940                );
15941            }
15942            last = Some(lg);
15943            pos = end;
15944        }
15945        if std::env::var("CMF_EMBRYO_DBG").as_deref() == Ok("1") {
15946            eprintln!(
15947                "embryo-dbg: chunk prefill {} ids from {start} in {} submits (chunk {cmax})",
15948                n - start,
15949                (n - start).div_ceil(cmax)
15950            );
15951        }
15952        last
15953    }
15954
15955    fn ensure_embryo_graph(&mut self) -> Option<std::sync::Arc<crate::gpu::EmbryoGraphModel>> {
15956        if self.embryo_graph.is_none() && self.embryo_resident_eligible() {
15957            const UMAX: u32 = u32::MAX;
15958            const HEADER: usize = crate::gpu::EMBRYO_META_HEADER;
15959            const REC: usize = 64;
15960            struct Pack {
15961                data: Vec<f32>,
15962            }
15963            impl Pack {
15964                fn put(&mut self, x: &[f32]) -> u32 {
15965                    if x.is_empty() {
15966                        return u32::MAX;
15967                    }
15968                    let off = self.data.len();
15969                    self.data.extend_from_slice(x);
15970                    off as u32
15971                }
15972            }
15973            // The mixer family of the file: vmf_phase geometry fills the
15974            // phase header words, gated_delta_net fills words 24..29.  A
15975            // file has exactly one linear core, so at most one is live.
15976            let vmf = self.vmf_cfg;
15977            let gdn = self.gdn_cfg;
15978            let mut pack = Pack { data: Vec::new() };
15979            let mut meta = vec![0u32; HEADER];
15980            meta[0] = self.hidden_size as u32;
15981            meta[1] = self.intermediate_size as u32;
15982            meta[2] = self.vocab_size as u32;
15983            meta[3] = self.num_layers as u32;
15984            meta[4] = vmf.map(|c| c.num_heads).unwrap_or(0) as u32;
15985            meta[5] = vmf.map(|c| c.nphase).unwrap_or(0) as u32;
15986            meta[6] = vmf.map(|c| c.value_head_dim).unwrap_or(0) as u32;
15987            if let Some(g) = gdn {
15988                meta[24] = g.num_v_heads as u32;
15989                meta[25] = g.num_k_heads as u32;
15990                meta[26] = g.key_head_dim as u32;
15991                meta[27] = g.value_head_dim as u32;
15992                meta[28] = g.conv_kernel as u32;
15993                meta[29] = g.conv_dim() as u32;
15994            }
15995            meta[7] = self.num_heads as u32;
15996            meta[8] = self.num_kv_heads as u32;
15997            meta[9] = self.head_dim as u32;
15998            meta[10] = self.kv_cache.max_seq_len as u32;
15999            let clusters = self.head_clusters.as_ref().unwrap();
16000            let cluster_count = clusters.len() / self.hidden_size;
16001            if clusters.len() % self.hidden_size != 0
16002                || cluster_count == 0
16003                || cluster_count > 1024
16004                || self.vocab_size % cluster_count != 0
16005                || self.weights.lm_head.rows() < self.vocab_size
16006                || self.weights.final_norm.len() != self.hidden_size
16007            {
16008                return None;
16009            }
16010            meta[11] = cluster_count as u32;
16011            meta[12] = (self.vocab_size / cluster_count) as u32;
16012            meta[13] = vmf.map(|c| c.state_len()).unwrap_or(0) as u32;
16013            meta[16] = self.rotary_dim as u32;
16014            meta[17] = matches!(self.norm_style, NormStyle::Gemma) as u32;
16015            meta[19] = (self.rms_eps as f32).to_bits();
16016            let max_conv = self
16017                .weights
16018                .layers
16019                .iter()
16020                .filter_map(|lw| match &lw.attn {
16021                    AttnKind::Linear(w) => w.conv.as_ref().map(|v| v.len() / self.hidden_size),
16022                    _ => None,
16023                })
16024                .max()
16025                .unwrap_or(1);
16026            // One state slot per recurrent layer: the phase state plus its
16027            // hidden-wide conv ring, or the GDN record `[conv ring | S]`
16028            // (`GdnCfg::state_len`).  A file carries one mixer family, so
16029            // the stride is exactly that family's record and the device
16030            // state buffer equals the header's recurrent bytes.
16031            let phase_stride = vmf
16032                .map(|c| c.state_len() + max_conv.saturating_sub(1) * self.hidden_size)
16033                .unwrap_or(0);
16034            let gdn_stride = gdn.map(|g| g.state_len()).unwrap_or(0);
16035            let state_stride = phase_stride.max(gdn_stride);
16036            // Bounded genome: the KV plane of an anchor is its ring
16037            // `[kvh][W][hd]` K + V, and only anchors own one.  Legacy full
16038            // anchors keep the `max_seq` planes indexed by layer.
16039            let bounded = self.anchor_core.clone();
16040            let (anchor_window, anchor_sink) = bounded
16041                .as_ref()
16042                .map(|ac| (ac.window, ac.sink))
16043                .unwrap_or((0, 0));
16044            let kv_stride = if bounded.is_some() {
16045                2usize
16046                    .saturating_mul(self.num_kv_heads)
16047                    .saturating_mul(anchor_window)
16048                    .saturating_mul(self.head_dim)
16049            } else {
16050                2usize
16051                    .saturating_mul(self.num_kv_heads)
16052                    .saturating_mul(self.kv_cache.max_seq_len)
16053                    .saturating_mul(self.head_dim)
16054            };
16055            meta[14] = state_stride as u32;
16056            meta[15] = kv_stride as u32;
16057            meta[18] = anchor_window as u32;
16058            meta[20] = anchor_sink as u32;
16059            meta[21] = match &self.bounded_rope {
16060                Some(rope) => {
16061                    // [W][half] cos then [W][half] sin, one contiguous table.
16062                    let off = pack.put(&rope.cos);
16063                    let _ = pack.put(&rope.sin);
16064                    off
16065                }
16066                None => UMAX,
16067            };
16068            let mut full_seen = false;
16069            let mut bounded_seen = 0usize;
16070            // Recurrent state slots belong to mixer layers only (phase or
16071            // GDN): an anchor owns a ring, not a state stride, so the
16072            // device state buffer is exactly the header's recurrent bytes.
16073            let mut phase_seen = 0usize;
16074            let mut gdn_seen = 0usize;
16075            for (li, lw) in self.weights.layers.iter().enumerate() {
16076                let base = meta.len();
16077                meta.resize(base + REC, UMAX);
16078                meta[base] = match &lw.attn {
16079                    AttnKind::Linear(w) if w.phase_delta => 1,
16080                    AttnKind::Linear(_) => 0,
16081                    AttnKind::Full { .. } => 2,
16082                    AttnKind::Bounded(_) => 3,
16083                    AttnKind::LinearGdn(_) => 4,
16084                    _ => UMAX,
16085                };
16086                meta[base + 1] = pack.put(&lw.input_norm);
16087                meta[base + 2] = pack.put(&lw.post_norm);
16088                meta[base + 25] = match &lw.attn {
16089                    AttnKind::Linear(_) => {
16090                        let off = ((phase_seen + gdn_seen) * state_stride) as u32;
16091                        phase_seen += 1;
16092                        off
16093                    }
16094                    AttnKind::LinearGdn(_) => {
16095                        let off = ((phase_seen + gdn_seen) * state_stride) as u32;
16096                        gdn_seen += 1;
16097                        off
16098                    }
16099                    _ => UMAX,
16100                };
16101                match &lw.attn {
16102                    AttnKind::LinearGdn(w) => {
16103                        // Layer record words 56..63 + 29, as the resident
16104                        // kernels read them (gpu_wgpu.rs `embryo_core_gdn_*`).
16105                        meta[base + 56] = pack.put(&Self::embryo_qtensor_f32(&w.in_proj_qkv));
16106                        meta[base + 57] = pack.put(&Self::embryo_qtensor_f32(&w.in_proj_z));
16107                        meta[base + 58] = pack.put(&Self::embryo_qtensor_f32(&w.in_proj_a));
16108                        meta[base + 59] = pack.put(&Self::embryo_qtensor_f32(&w.in_proj_b));
16109                        meta[base + 60] = pack.put(&w.conv1d);
16110                        meta[base + 61] = pack.put(&w.a_log);
16111                        meta[base + 62] = pack.put(&w.dt_bias);
16112                        meta[base + 63] = pack.put(&w.norm);
16113                        meta[base + 29] = pack.put(&Self::embryo_qtensor_f32(&w.out_proj));
16114                        meta[base + 24] = 0;
16115                    }
16116                    AttnKind::Linear(w) => {
16117                        meta[base + 3] = pack.put(&Self::embryo_qtensor_f32(&w.thq));
16118                        meta[base + 4] = pack.put(&Self::embryo_qtensor_f32(&w.thk));
16119                        meta[base + 5] = pack.put(&Self::embryo_qtensor_f32(&w.v_proj));
16120                        meta[base + 6] = pack.put(&Self::embryo_qtensor_f32(&w.out_proj));
16121                        let decay: Vec<f32> = w.decay.iter().map(|&x| x as f32).collect();
16122                        meta[base + 7] = pack.put(&decay);
16123                        if let Some((kg, kb)) = &w.k_gate {
16124                            meta[base + 8] = pack.put(&Self::embryo_qtensor_f32(kg));
16125                            meta[base + 9] = pack.put(kb);
16126                        }
16127                        if let Some(conv) = &w.conv {
16128                            meta[base + 10] = pack.put(conv);
16129                            meta[base + 24] = (conv.len() / self.hidden_size) as u32;
16130                        } else {
16131                            meta[base + 24] = 0;
16132                        }
16133                    }
16134                    AttnKind::Full { wq, wk, wv, wo, .. } => {
16135                        full_seen = true;
16136                        meta[base + 11] = pack.put(&Self::embryo_qtensor_f32(wq));
16137                        meta[base + 12] = pack.put(&Self::embryo_qtensor_f32(wk));
16138                        meta[base + 13] = pack.put(&Self::embryo_qtensor_f32(wv));
16139                        meta[base + 14] = pack.put(&Self::embryo_qtensor_f32(wo));
16140                        meta[base + 26] = (li * kv_stride) as u32;
16141                    }
16142                    AttnKind::Bounded(w) => {
16143                        meta[base + 11] = pack.put(&Self::embryo_qtensor_f32(&w.wq));
16144                        meta[base + 12] = pack.put(&Self::embryo_qtensor_f32(&w.wk));
16145                        meta[base + 13] = pack.put(&Self::embryo_qtensor_f32(&w.wv));
16146                        meta[base + 14] = pack.put(&Self::embryo_qtensor_f32(&w.wo));
16147                        // Ring slot of this anchor (anchors only, packed).
16148                        meta[base + 26] = (bounded_seen * kv_stride) as u32;
16149                        meta[base + 27] = pack.put(&w.sink_k);
16150                        meta[base + 28] = pack.put(&w.sink_v);
16151                        bounded_seen += 1;
16152                    }
16153                    _ => return None,
16154                }
16155                match &lw.ffn {
16156                    FfnKind::Dense(d) => {
16157                        meta[base + 15] = 0;
16158                        meta[base + 16] = 0;
16159                        meta[base + 21] = pack.put(&Self::embryo_qtensor_f32(&d.gate_proj));
16160                        meta[base + 22] = pack.put(&Self::embryo_qtensor_f32(&d.up_proj));
16161                        meta[base + 23] = pack.put(&Self::embryo_qtensor_f32(&d.down_proj));
16162                    }
16163                    FfnKind::Moe(m) => {
16164                        let r = m.resonance.as_ref().unwrap();
16165                        let (shared, _) = m.shared.as_ref().unwrap();
16166                        meta[base + 15] = 1;
16167                        meta[base + 16] = m.experts.len() as u32;
16168                        meta[base + 17] = pack.put(&r.mu);
16169                        meta[base + 18] = pack.put(&r.u);
16170                        meta[base + 19] = pack.put(&r.bias);
16171                        meta[base + 20] = r.k as u32;
16172                        // Word 30: the growth shell as the runtime applies
16173                        // it now (`+inf` on trunk rows, the stored finite
16174                        // shell on grown rows, all `+inf` under
16175                        // `CMF_GROWTH_SHELL=off`), followed by one `−∞`
16176                        // sentinel at index E the kernel writes as the
16177                        // score of an expert outside its shell — WGSL has
16178                        // no infinity literal, so the value travels as
16179                        // data (`embryo_core_route_finalize`).
16180                        let mut shell = r.effective_shell(m.experts.len());
16181                        shell.push(f32::NEG_INFINITY);
16182                        meta[base + 30] = pack.put(&shell);
16183                        meta[base + 21] = pack.put(&Self::embryo_qtensor_f32(&shared.gate_proj));
16184                        meta[base + 22] = pack.put(&Self::embryo_qtensor_f32(&shared.up_proj));
16185                        meta[base + 23] = pack.put(&Self::embryo_qtensor_f32(&shared.down_proj));
16186                        for (e, ex) in m.experts.iter().enumerate() {
16187                            meta[base + 32 + e * 3] =
16188                                pack.put(&Self::embryo_qtensor_f32(&ex.gate_proj));
16189                            meta[base + 33 + e * 3] =
16190                                pack.put(&Self::embryo_qtensor_f32(&ex.up_proj));
16191                            meta[base + 34 + e * 3] =
16192                                pack.put(&Self::embryo_qtensor_f32(&ex.down_proj));
16193                        }
16194                    }
16195                    FfnKind::DenseMoe(_) => return None,
16196                }
16197            }
16198            if !full_seen && self.num_layers == 0 {
16199                return None;
16200            }
16201            let id = {
16202                static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
16203                NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
16204            };
16205            let model = crate::gpu::EmbryoGraphModel {
16206                id,
16207                hidden: self.hidden_size,
16208                intermediate: self.intermediate_size,
16209                vocab: self.vocab_size,
16210                layers: self.num_layers,
16211                phase_heads: vmf.map(|c| c.num_heads).unwrap_or(0),
16212                nphase: vmf.map(|c| c.nphase).unwrap_or(0),
16213                phase_dv: vmf.map(|c| c.value_head_dim).unwrap_or(0),
16214                anchor_q_heads: self.num_heads,
16215                anchor_kv_heads: self.num_kv_heads,
16216                anchor_head_dim: self.head_dim,
16217                rotary_dim: self.rotary_dim,
16218                max_seq: self.kv_cache.max_seq_len,
16219                cluster_count,
16220                cluster_size: self.vocab_size / cluster_count,
16221                phase_state_len: vmf.map(|c| c.state_len()).unwrap_or(0),
16222                state_stride,
16223                kv_stride,
16224                norm_gemma: matches!(self.norm_style, NormStyle::Gemma),
16225                phase_mass: vmf.map(|c| c.phase_mass).unwrap_or(0.0),
16226                weights: pack.data,
16227                meta,
16228                lm_head: Self::embryo_qtensor_f32(&self.weights.lm_head),
16229                clusters: clusters.as_ref().clone(),
16230                final_norm: self.weights.final_norm.clone(),
16231                inv_freq: self.inv_freq.as_ref().clone(),
16232                bounded: bounded.is_some(),
16233                kv_layers: if bounded.is_some() {
16234                    bounded_seen
16235                } else {
16236                    self.num_layers
16237                },
16238                state_layers: phase_seen + gdn_seen,
16239                anchor_window,
16240                anchor_sink,
16241                phase_layers: phase_seen,
16242                gdn_layers: gdn_seen,
16243                gdn_heads: gdn.map(|g| g.num_v_heads).unwrap_or(0),
16244                gdn_k_heads: gdn.map(|g| g.num_k_heads).unwrap_or(0),
16245                gdn_dk: gdn.map(|g| g.key_head_dim).unwrap_or(0),
16246                gdn_dv: gdn.map(|g| g.value_head_dim).unwrap_or(0),
16247                gdn_kk: gdn.map(|g| g.conv_kernel).unwrap_or(0),
16248            };
16249            self.embryo_graph = Some(std::sync::Arc::new(model));
16250        }
16251        self.embryo_graph.clone()
16252    }
16253
16254    fn forward_layers_span(
16255        &mut self,
16256        hidden: &[f32],
16257        position: usize,
16258        task_mask: Option<&TaskMask>,
16259        from: usize,
16260        upto: Option<usize>,
16261    ) -> Vec<f32> {
16262        #[cfg(target_os = "macos")]
16263        let _metal_pager_token_prof = crate::gpu_metal::MoePagerTokenScope::new(
16264            position,
16265            from,
16266            upto.map_or(self.num_layers, |u| u.saturating_add(1)),
16267        );
16268        debug_assert!(
16269            from == 0
16270                || (self.dsv4.is_none()
16271                    && self.dsv41.is_none()
16272                    && self.qwen4_exp.is_none()
16273                    && !self.per_token_stack())
16274        );
16275        // Every plain forward — the whole-token Metal graph (`q1_graph_gpu`
16276        // wraps the GDN owners zero-copy and reallocates them on a size
16277        // change) and the CPU layer loop (reads/swaps `linear_state`) —
16278        // must see the previous speculative commit's asynchronous replay
16279        // complete. One mutex probe when nothing is pending.
16280        #[cfg(target_os = "macos")]
16281        if !crate::gpu_metal::wait_replay() {
16282            self.fail_metal_graph("the pending async replay failed before a plain forward");
16283            return vec![0.0; self.hidden_size];
16284        }
16285        if let Some(b) = &mut self.qwen4_exp {
16286            let _ = (task_mask, upto);
16287            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
16288            let mut logits = Vec::new();
16289            crate::qwen4_exp::forward_token(
16290                &b.0,
16291                &b.1,
16292                &b.2,
16293                &mut b.3,
16294                token_id,
16295                position,
16296                &self.inv_freq,
16297                self.pool.as_deref(),
16298                &mut logits,
16299                true,
16300            );
16301            self.graph_logits = Some(logits);
16302            return vec![0.0; self.hidden_size];
16303        }
16304        // DeepSeek-V4 runs its own stack: the state is hc_mult copies, and
16305        // the forward returns LOGITS, not a hidden — the head is inside it
16306        // (the final fold sits between the last layer and the norm). The
16307        // token id rides in `hidden[0]`, written by embed_single, because
16308        // the hash layers route by id rather than by content.
16309        if let Some(b) = &mut self.dsv4 {
16310            let _ = (task_mask, upto);
16311            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
16312            let (g, layers, cfg, st) = (&b.0, &b.1, b.2, &mut b.3);
16313            st.pos = position;
16314            let mut logits = Vec::new();
16315            crate::dsv4::forward_token(
16316                g,
16317                layers,
16318                &cfg,
16319                st,
16320                token_id,
16321                &self.inv_freq,
16322                self.pool.as_deref(),
16323                &mut logits,
16324            );
16325            self.graph_logits = Some(logits);
16326            self.dspark_probe(position, token_id);
16327            // The caller expects a hidden; the logits went out of band, as
16328            // with the fused lm_head path.
16329            return vec![0.0; self.hidden_size];
16330        }
16331        // DeepSeek-V4.1 owns its complete stack and emits logits out of band.
16332        if let Some(b) = &mut self.dsv41 {
16333            let _ = (task_mask, upto);
16334            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
16335            let mut logits = Vec::new();
16336            crate::dsv41::forward_token(
16337                &b.0,
16338                &b.1,
16339                &b.2,
16340                &mut b.3,
16341                token_id,
16342                position,
16343                self.pool.as_deref(),
16344                &mut logits,
16345            );
16346            self.graph_logits = Some(logits);
16347            return vec![0.0; self.hidden_size];
16348        }
16349        // Gemma-3n runs its own stack (4 AltUp replicas don't fit this
16350        // loop); `hidden` is the extended embedding from embed_single.
16351        // Gemma-4 E-series: same hand-off — its dual-geometry attention
16352        // with shared-KV tail layers and the PLE injection live in
16353        // `g4e_forward`.
16354        if let Some(b) = &self.g4e {
16355            let _ = (task_mask, upto);
16356            return crate::g4e::g4e_forward(
16357                &b.0,
16358                &b.1,
16359                hidden,
16360                position,
16361                &mut self.kv_cache.layers,
16362                self.num_heads,
16363                self.num_kv_heads,
16364                self.pool.as_deref(),
16365            );
16366        }
16367        if let Some(b) = &self.g3n {
16368            let _ = (task_mask, upto);
16369            return crate::g3n::g3n_forward(
16370                &b.0,
16371                &b.1,
16372                hidden,
16373                position,
16374                &mut self.kv_cache.layers,
16375                self.num_heads,
16376                self.num_kv_heads,
16377                self.head_dim,
16378                self.pool.as_deref(),
16379            );
16380        }
16381        // Cortiq Embryo owns a separate resident graph: phase recurrent
16382        // state, resonance routing, the GQA anchor KV and hierarchical head
16383        // all execute in one Vulkan submit. It is limited to a complete
16384        // unmasked stack; spans and task masks retain the exact host path.
16385        // `CMF_EMBRYO_DBG=1` names the gate that keeps a token off the
16386        // resident graph — every refusal below is otherwise silent.
16387        if from == 0
16388            && upto.is_none()
16389            && task_mask.is_none()
16390            && self.anchor_core.is_some()
16391            && std::env::var("CMF_EMBRYO_DBG").as_deref() == Ok("1")
16392        {
16393            static ONCE: std::sync::Once = std::sync::Once::new();
16394            ONCE.call_once(|| {
16395                eprintln!(
16396                    "embryo-dbg: graph_on decode={} prefill={} resident_env={:?} enabled_here={} \
16397                     unsupported={} eligible={}",
16398                    crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode),
16399                    crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill),
16400                    std::env::var("CMF_EMBRYO_RESIDENT").ok(),
16401                    crate::gpu::enabled_here(),
16402                    self.graph_refused(),
16403                    self.embryo_resident_eligible(),
16404                );
16405            });
16406        }
16407        if from == 0
16408            && upto.is_none()
16409            && task_mask.is_none()
16410            // Embryo's recurrent/KV state has no host import path.  Do not
16411            // seed it for a prefill-only graph and then silently decode from
16412            // an empty CPU cache; both phases must select the resident owner.
16413            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)
16414            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill)
16415            // This whole-token Embryo path remains explicitly opt-in.
16416            // `CMF_GPU_WGPU_GRAPH=1` still enables the mature generic graph,
16417            // but must not silently select this model-specific resident path.
16418            && matches!(
16419                std::env::var("CMF_EMBRYO_RESIDENT").as_deref(),
16420                Ok("1") | Ok("parallel")
16421            )
16422            && crate::gpu::enabled_here()
16423            && !self.graph_refused()
16424            // Sequence owner: past position zero the device continues only
16425            // a sequence it holds. A host-owned sequence (the graph refused
16426            // at its start, or its prefix was prefilled on the host) keeps
16427            // the host path to its end — never a device attempt at p > 0
16428            // over an empty device image.
16429            && (position == 0 || self.device_sequence_position().is_some())
16430            && self.embryo_resident_eligible()
16431            && let Some(model) = self.ensure_embryo_graph()
16432        {
16433            let mut lg = Vec::new();
16434            if crate::gpu::forward_embryo_graph(&model, self.graph_kv_id, hidden, position, &mut lg)
16435            {
16436                self.graph_logits = Some(lg);
16437                return vec![0.0; self.hidden_size];
16438            }
16439            if std::env::var("CMF_EMBRYO_DBG").as_deref() == Ok("1") {
16440                eprintln!("embryo-dbg: forward_embryo_graph refused at position {position}");
16441            }
16442            // The refusal is THIS pipeline's: falling through once is safe
16443            // at position zero (the host owns the sequence from here),
16444            // while a refusal at a later position of a device-owned
16445            // sequence would mix a host KV/state path with a partial
16446            // device sequence.
16447            self.mark_graph_refused();
16448            if position != 0 {
16449                // Fail this sequence alone and leave nothing stale behind:
16450                // no reuse key, no host or device state for the next
16451                // request on this slot to "extend".
16452                self.kv_cache.clear();
16453                self.clear_history();
16454                crate::gpu::graph_kv_reset(self.graph_kv_id);
16455                panic!(
16456                    "resident Embryo graph refused at position {position}; refusing an in-flight host fallback"
16457                );
16458            }
16459        }
16460        let mut h = hidden.to_vec();
16461        // MiMo-V2 expert placement: decided before the graph or the per-op
16462        // arena can claim the budget the expert bank needs.
16463        self.mimo_moe_prepare();
16464        let _mimo_q8 = self
16465            .mimo_moe
16466            .is_on()
16467            .then(crate::qtensor::enter_full_gpu_q8_scope);
16468        // Split borrows: copy scalars / clone handles so the per-layer
16469        // cfg does not hold `&self` while the KV cache is `&mut`.
16470        let (nh, _nkv, _hd, hs, _rd, eps) = (
16471            self.num_heads,
16472            self.num_kv_heads,
16473            self.head_dim,
16474            self.hidden_size,
16475            self.rotary_dim,
16476            self.rms_eps,
16477        );
16478        let pool = self.pool.clone();
16479        // Opt-in wgpu token-graph attention (discrete Vulkan/DX12): the whole
16480        // attention sub-block runs resident in one submit. Off by default.
16481        // Whole-token wgpu graph: eligibility + arbitration.
16482        //  - explicit CMF_GPU_WGPU_GRAPH forces it on/off;
16483        //  - discrete adapters (4090: decode 76 -> 137 tok/s) and GDN
16484        //    hybrids (recurrent state device-resident, no CPU twin to
16485        //    race) TRUST it;
16486        //  - integrated/mobile adapters RACE it against the normal path
16487        //    at generation granularity (gpu::graph_race_*) — tiled
16488        //    mobile GPUs can turn the ~300-dispatch graph into seconds
16489        //    per token, while a fast phone GPU keeps its win.
16490        let graph_env = std::env::var("CMF_GPU_WGPU_GRAPH").ok();
16491        let graph_on = match graph_env.as_deref() {
16492            Some("0") => false,
16493            Some("prefill") => false, // decode keeps the per-op path
16494            Some(_) => true,
16495            // Unset: same discrete-only default as every other graph
16496            // site. "Is the GPU on" used to stand in here — which made
16497            // the 0.2 tok/s whole-token graph race-eligible on mobile
16498            // adapters and cost 12-14× on first tokens (cmfmobile
16499            // TUNING.md); integrated GPUs keep the per-op probe path.
16500            None => crate::gpu::wgpu_graph_default(),
16501        };
16502        let graph_trusted =
16503            graph_env.is_some() || crate::gpu::wgpu_graph_default() || self.gdn_cfg.is_some();
16504        let race_eligible =
16505            graph_on && upto.is_none() && task_mask.is_none() && from == 0 && !self.graph_refused();
16506        let mut tail_start = 0usize;
16507        if race_eligible && crate::gpu::graph_race_use_graph(graph_trusted) {
16508            let t_graph = std::time::Instant::now();
16509            let mut lg = Vec::new();
16510            let mut gl = 0usize;
16511            let built = self.try_token_graph_wgpu(hidden, position, &mut lg, &mut gl);
16512            let declined = built.is_none();
16513            let built = match built {
16514                Some(Ok(hh)) => Some(hh),
16515                Some(Err(())) => {
16516                    // O(1) state was admitted before the device failure; the
16517                    // CPU mirrors are stale by construction.  Clear the whole
16518                    // sequence and stop rather than walking that stale state.
16519                    self.clear_sequence_state();
16520                    self.graph_failed
16521                        .store(true, std::sync::atomic::Ordering::Relaxed);
16522                    self.cancel
16523                        .store(true, std::sync::atomic::Ordering::Relaxed);
16524                    tracing::error!("token graph failed after admission; sequence state cleared");
16525                    return vec![0.0; self.hidden_size];
16526                }
16527                None => None,
16528            };
16529            // Past the transient guards (o1 still collecting, a softcap)
16530            // a refusal is about the weights and will never change —
16531            // remember it instead of walking every layer again next
16532            // token.
16533            if declined && !self.o1_active() && self.attn_softcap == 0.0 {
16534                self.mark_graph_refused();
16535            }
16536            graph_note(built.is_some(), gl, self.num_layers);
16537            if let Some(hh) = built {
16538                let dur = t_graph.elapsed();
16539                if std::env::var("CMF_GRAPH_PROF").is_ok() {
16540                    eprintln!("graph-call: {:.2} ms total", dur.as_secs_f64() * 1000.0);
16541                }
16542                if gl > 0 && gl < self.num_layers {
16543                    // Device prefix: the graph ran layers 0..gl and handed
16544                    // back the boundary hidden — the loop below owns the
16545                    // tail. The prefix layers' KV/state advanced on the
16546                    // device; the tail's advances on the host below. One
16547                    // boundary crossing per token.
16548                    h = hh;
16549                    tail_start = gl;
16550                } else if graph_trusted || !crate::gpu::graph_race_first_token_hopeless(dur) {
16551                    if !graph_trusted {
16552                        crate::gpu::graph_race_record(true, dur);
16553                    }
16554                    if !lg.is_empty() {
16555                        // Graph produced logits (final-norm + lm_head folded in) —
16556                        // pad/cap to vocab and hand them to the sampler directly.
16557                        lg.resize(self.vocab_size, 0.0);
16558                        if let Some(c) = self.final_softcap {
16559                            softcap_in_place(&mut lg, c, self.pool.as_deref());
16560                        }
16561                        self.graph_logits = Some(lg);
16562                    }
16563                    return hh;
16564                }
16565                // Hopeless first graph token: discard it and fall through
16566                // to the normal path. Safe exactly here — the prompt KV is
16567                // still CPU-owned (chunked prefill), so recomputing this
16568                // position is exact; the mirror's extra row is never read
16569                // (the race just settled on the normal path).
16570            }
16571        }
16572        // KIMI-LINEAR HAS NO SPLIT BUG. The 2.6× reported from the
16573        // model rotation (12.2 tok/s on one card against 4.6 on two)
16574        // was a single measurement of a model whose arm arbitration is
16575        // borderline, and it did not survive repetition. Three runs an
16576        // arm, same binary, back to back:
16577        //   probe on : 1 GPU 9.5 / 5.7 / 5.9   2 GPU 7.8 / 13.0 / 13.3
16578        //   pinned   : 1 GPU 5.6 / 5.3 / 5.2   2 GPU 3.5 / 4.2 / 3.4
16579        // With the arms pinned the split costs about 1.45×, which is
16580        // what a layer split costs. With the probe free, TWO CARDS RUN
16581        // FASTER — because for this model the CPU arm wins some op
16582        // classes and the probe finds that.
16583        //
16584        // Two things do stand, and both are measured. The token graph
16585        // builds NOTHING here (`covered 0 of 14 layers [0..14)`), so
16586        // every layer walks per-op on either arm — that is where the
16587        // headroom is, not in the split. And this model's benchmark is
16588        // unusable without `CMF_GPU_PROBE=0`: the arbitration alone
16589        // moves it by more than 2×.
16590        //
16591        // Span runs (network split): the graph covers exactly [from..=upto]
16592        // — one submit per SEGMENT per token. No race: its state is global
16593        // and calibrated on full stacks, so spans take the graph only where
16594        // it is trusted by default (discrete adapters / CMF_GPU_WGPU_GRAPH).
16595        let span = from > 0 || upto.is_some();
16596        if span && graph_on && task_mask.is_none() && graph_trusted {
16597            let upto_excl = upto.map_or(self.num_layers, |u| u + 1);
16598            let mut lg = Vec::new();
16599            let mut gl = 0usize;
16600            let span_res =
16601                self.try_token_graph_wgpu_span(hidden, position, &mut lg, from, upto_excl, &mut gl);
16602            let span_res = match span_res {
16603                Some(Ok(hh)) => Some(hh),
16604                Some(Err(())) => {
16605                    self.clear_sequence_state();
16606                    self.graph_failed
16607                        .store(true, std::sync::atomic::Ordering::Relaxed);
16608                    self.cancel
16609                        .store(true, std::sync::atomic::Ordering::Relaxed);
16610                    tracing::error!(
16611                        "span token graph failed after admission; sequence state cleared"
16612                    );
16613                    return vec![0.0; self.hidden_size];
16614                }
16615                None => None,
16616            };
16617            graph_note(span_res.is_some(), gl, upto_excl - from);
16618            if std::env::var("CMF_GPU_DEBUG").is_ok() {
16619                // How much of the span the graph actually covered. A
16620                // prefix of nothing means every layer walks per-op and
16621                // the split's extra cost is elsewhere.
16622                static SEEN: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
16623                if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 {
16624                    eprintln!(
16625                        "span graph: covered {gl} of {} layers [{from}..{upto_excl}) res={}",
16626                        upto_excl - from,
16627                        span_res.is_some()
16628                    );
16629                }
16630            }
16631            if let Some(hh) = span_res {
16632                if gl == upto_excl - from {
16633                    if !lg.is_empty() {
16634                        lg.resize(self.vocab_size, 0.0);
16635                        if let Some(c) = self.final_softcap {
16636                            softcap_in_place(&mut lg, c, self.pool.as_deref());
16637                        }
16638                        self.graph_logits = Some(lg);
16639                    }
16640                    crate::gpu::set_layer(-1);
16641                    return hh;
16642                }
16643                // Partial device prefix of the span: CPU owns the tail.
16644                h = hh;
16645                tail_start = from + gl;
16646            }
16647        }
16648        // Layers the host is about to run whose device mirror moved ahead
16649        // of the host cache (a device prefix that shrank since the prompt,
16650        // a batched-prefill prefix longer than this token's): bring their
16651        // rows over first. One comparison per layer when nothing lags.
16652        let t_race_cpu = (race_eligible && !graph_trusted).then(std::time::Instant::now);
16653
16654        // A partial graph is an explicit GPU-prefix / CPU-tail split. Keep
16655        // the tail PURE host-side: letting its QTensor hooks re-enter the
16656        // residency arena streams every omitted layer through Vulkan and the
16657        // driver's freed-allocation cache can grow to the full model size
16658        // (25.4 GiB observed with a 14 GiB budget on Granite 30B Q8_2F).
16659        // With a MiMo expert bank the tail is not a whole-layer host
16660        // stream: its experts run from the bank (never the arena) and its
16661        // projections stay per-op on the device, which the bank's placement
16662        // left room for.
16663        let host_tail = tail_start > from;
16664        let _host_tail = (host_tail && !self.mimo_moe.is_on()).then(crate::gpu::enter_cpu_scope);
16665        let automatic_gpu_prefix = self.automatic_gpu_prefix();
16666
16667        let _prof_layers = crate::cpuprof::time(crate::cpuprof::Slot::Layers);
16668        #[cfg(target_os = "macos")]
16669        let mut gpu_skip_until = 0usize;
16670        for li in tail_start.max(from)..self.num_layers {
16671            let _capacity_tail = automatic_gpu_prefix
16672                .filter(|&prefix| li >= prefix && !self.mimo_moe.is_dynamic(li, host_tail))
16673                .map(|_| crate::gpu::enter_cpu_scope());
16674            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU (CMF_GPU_LAYERS)
16675            if let Some(u) = upto {
16676                if li > u {
16677                    break;
16678                }
16679            }
16680            if let Some(mask) = task_mask {
16681                if !mask.layer_alive(li) {
16682                    continue; // dead layer: residual pass-through
16683                }
16684            }
16685            // MiniMax's dynamic tail: attention + pooled MoE of this layer as
16686            // ONE device frame (single-layer graph call), cold experts on
16687            // the host. Any decline falls through to the ordinary host
16688            // layer; a post-admission device failure stops the sequence.
16689            if host_tail && task_mask.is_none() {
16690                match self.m3_pooled_layer(li, position, &mut h) {
16691                    Ok(true) => {
16692                        crate::gpu::set_layer(-1);
16693                        continue;
16694                    }
16695                    Ok(false) => {}
16696                    Err(()) => {
16697                        self.clear_sequence_state();
16698                        self.graph_failed
16699                            .store(true, std::sync::atomic::Ordering::Relaxed);
16700                        self.cancel
16701                            .store(true, std::sync::atomic::Ordering::Relaxed);
16702                        tracing::error!(
16703                            "pooled tail token graph failed after admission; sequence state cleared"
16704                        );
16705                        return vec![0.0; self.hidden_size];
16706                    }
16707                }
16708            }
16709            // Whole-block q1 token graph: a run of consecutive q1
16710            // layers — GDN and full attention — executes with one sync
16711            // per CPU attend instead of per op (macOS/Metal).
16712            #[cfg(target_os = "macos")]
16713            {
16714                if li < gpu_skip_until {
16715                    continue;
16716                }
16717                if task_mask.is_none() {
16718                    let end = self.q1_graph_gpu(li, upto, position, &mut h);
16719                    if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
16720                        // The graph may have mutated device state before a
16721                        // command-buffer error. Never continue with a CPU
16722                        // tail or read a stale host mirror after admission.
16723                        return vec![0.0; self.hidden_size];
16724                    }
16725                    if end > li {
16726                        gpu_skip_until = end;
16727                        // Looped Transformer: the graph stopped at a loop
16728                        // boundary — apply final norm before the next iteration.
16729                        if self.is_loop_end(end - 1) && end < self.num_layers {
16730                            h = inference::rms_norm(
16731                                &h,
16732                                &self.weights.final_norm,
16733                                self.rms_eps,
16734                                self.norm_style,
16735                            );
16736                        }
16737                        continue;
16738                    }
16739                }
16740            }
16741
16742            if task_mask.is_none() {
16743                match self.mimo_graph_layer_rows(li, &mut h, &[position]) {
16744                    crate::gpu::BatchGraphOutcome::Completed => continue,
16745                    crate::gpu::BatchGraphOutcome::Failed => return vec![0.0; self.hidden_size],
16746                    crate::gpu::BatchGraphOutcome::Declined => {}
16747                }
16748            }
16749            #[cfg(feature = "gpu")]
16750            self.pull_lagging_host_kv(li, li + 1, position);
16751            let lw = &self.weights.layers[self.phys_layer(li)];
16752            if let Ok(tp) = std::env::var("CMF_TRACE_POS") {
16753                if tp.parse::<usize>().ok() == Some(position) {
16754                    let n: f32 = h.iter().map(|x| x * x).sum::<f32>().sqrt();
16755                    eprintln!(
16756                        "TRACE pos {position} layer {li}: |h| = {n:.6} h0 {:.6} h1 {:.6}",
16757                        h[0], h[1]
16758                    );
16759                }
16760            }
16761            // Norm into the pipeline scratch — the returning rms_norm
16762            // allocated twice per layer per token (roadmap §3 P0).
16763            let prof = crate::cpuprof::time(crate::cpuprof::Slot::Norms);
16764            inference::rms_norm_into(
16765                &h,
16766                &lw.input_norm,
16767                self.rms_eps,
16768                self.norm_style,
16769                &mut self.ws.n1,
16770            );
16771            drop(prof);
16772
16773            let attn_out = match &lw.attn {
16774                AttnKind::Mla(w) => {
16775                    let inv_freq_l = self.layer_inv_freq(li);
16776                    let rs = self.layer_rope_scale(li);
16777                    let eps = self.rms_eps;
16778                    let pool = self.pool.clone();
16779                    mla_attention(
16780                        w,
16781                        &self.ws.n1,
16782                        &mut self.kv_cache.layers[li],
16783                        position,
16784                        &inv_freq_l,
16785                        rs,
16786                        eps,
16787                        pool.as_deref(),
16788                    )
16789                }
16790                AttnKind::Linear(w) => {
16791                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
16792                    vmf_phase_forward(
16793                        &self.ws.n1,
16794                        w,
16795                        &cfg,
16796                        &mut self.kv_cache.layers[li].linear_state,
16797                        self.pool.as_deref(),
16798                    )
16799                }
16800                AttnKind::Kda(w) => {
16801                    let cfg = self.kda_cfg.expect("kda layer without kda_cfg");
16802                    crate::linear_core::kda_forward(
16803                        &self.ws.n1,
16804                        w,
16805                        &cfg,
16806                        &mut self.kv_cache.layers[li].linear_state,
16807                        self.pool.as_deref(),
16808                    )
16809                }
16810                AttnKind::LinearGdn(w) => {
16811                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
16812                    gdn_forward(
16813                        &self.ws.n1,
16814                        w,
16815                        &cfg,
16816                        &mut self.kv_cache.layers[li].linear_state,
16817                        self.pool.as_deref(),
16818                    )
16819                }
16820                AttnKind::ShortConv(w) => {
16821                    let cfg = self
16822                        .short_conv_cfg
16823                        .expect("short-conv layer without short_conv_cfg");
16824                    short_conv_forward(
16825                        &self.ws.n1,
16826                        w,
16827                        &cfg,
16828                        &mut self.kv_cache.layers[li].linear_state,
16829                        self.pool.as_deref(),
16830                    )
16831                }
16832                AttnKind::Bounded(w) => {
16833                    // Natively bounded anchor: insert into the ring, attend
16834                    // over sinks ∪ window. No position, nothing appended.
16835                    let rope = self
16836                        .bounded_rope
16837                        .clone()
16838                        .expect("bounded layer without an installed rotation table");
16839                    let cfg = crate::bounded::BoundedAttnCfg {
16840                        num_heads: self.num_heads,
16841                        num_kv_heads: self.num_kv_heads,
16842                        head_dim: self.head_dim,
16843                        hidden_size: hs,
16844                        scale: self.attn_scale,
16845                        rope: &rope,
16846                        pool: pool.as_deref(),
16847                    };
16848                    crate::bounded::bounded_attention(
16849                        &self.ws.n1,
16850                        w,
16851                        &mut self.kv_cache.layers[li],
16852                        &cfg,
16853                    )
16854                }
16855                AttnKind::Full {
16856                    wq,
16857                    wk,
16858                    wv,
16859                    wo,
16860                    q_norm,
16861                    k_norm,
16862                    output_gate,
16863                    softplus_gate,
16864                    bias,
16865                } if self.kv_cache.layers[li].o1_sealed() => {
16866                    // O(1) override: decode on the sealed Nyström state
16867                    // instead of the growing KV cache.
16868                    let inv_freq_l = self.layer_inv_freq(li);
16869                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
16870                    let cfg = QwenAttnCfg {
16871                        num_heads: self.layer_num_heads(li),
16872                        num_kv_heads: nkv_l,
16873                        head_dim: hd_l,
16874                        hidden_size: hs,
16875                        position,
16876                        inv_freq: &inv_freq_l,
16877                        rotary_dim: rd_l,
16878                        scale: self.attn_scale,
16879                        softcap: self.attn_softcap,
16880                        window: None,
16881                        v_norm: self.attn_v_norm,
16882                        qk_norm_after_rope: self.qk_norm_after_rope,
16883                        gate_sigmoid: self.proj_gate_sigmoid,
16884                        q_norm: q_norm.as_deref(),
16885                        k_norm: k_norm.as_deref(),
16886                        output_gate: *output_gate,
16887                        softplus_gate: softplus_gate
16888                            .as_ref()
16889                            .map(|(gate, per_head)| (gate, *per_head)),
16890                        rope_scale: self.layer_rope_scale(li),
16891                        bias: bias
16892                            .as_ref()
16893                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
16894                        rms_eps: eps,
16895                        norm_style: self.norm_style,
16896                        pool: pool.as_deref(),
16897                        v_head_dim: self.layer_v_dim(li),
16898                    };
16899                    attention::qwen_attention_nystrom(
16900                        &self.ws.n1,
16901                        wq,
16902                        wk,
16903                        wv,
16904                        wo,
16905                        &mut self.kv_cache.layers[li],
16906                        &cfg,
16907                    )
16908                }
16909                AttnKind::Full {
16910                    wq,
16911                    wk,
16912                    wv,
16913                    wo,
16914                    q_norm,
16915                    k_norm,
16916                    output_gate,
16917                    softplus_gate,
16918                    bias,
16919                } => 'attn: {
16920                    // wgpu token-graph attention (opt-in): whole sub-block in
16921                    // one submit, device K/V mirror. q1 only, no gate/bias/mask.
16922                    // Its kernel has no window, sink or narrow-V slot and
16923                    // one mirror geometry: such models stay on the CPU attend.
16924                    let dropin_reason =
16925                        graph_on.then(|| self.graph_attn_decline_reason()).flatten();
16926                    if let Some(reason) = dropin_reason {
16927                        self.note_graph_decline("wgpu attn dropin", reason);
16928                    }
16929                    if graph_on
16930                        && dropin_reason.is_none()
16931                        && !*output_gate
16932                        && softplus_gate.is_none()
16933                        && self.attention_heads_per_layer.is_none()
16934                        && bias.is_none()
16935                        && task_mask.is_none()
16936                    {
16937                        let inv_freq_l = self.layer_inv_freq(li);
16938                        let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
16939                        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
16940                        if let (Some((gm, qi)), Some((_, ki)), Some((_, vi)), Some((_, oi))) = (
16941                            wq.mapped_q1(),
16942                            wk.mapped_q1(),
16943                            wv.mapped_q1(),
16944                            wo.mapped_q1(),
16945                        ) {
16946                            let gm = gm.clone();
16947                            let mut out = vec![0f32; hs];
16948                            let cache = &self.kv_cache.layers[li];
16949                            if crate::gpu::attn_dropin(
16950                                &gm,
16951                                self.graph_kv_id,
16952                                li,
16953                                &self.ws.n1,
16954                                qi,
16955                                ki,
16956                                vi,
16957                                oi,
16958                                q_norm.as_deref(),
16959                                k_norm.as_deref(),
16960                                self.qk_norm_after_rope,
16961                                &inv_freq_l,
16962                                nh,
16963                                nkv_l,
16964                                hd_l,
16965                                rd_l,
16966                                hs,
16967                                position,
16968                                self.kv_cache.max_seq_len,
16969                                gemma,
16970                                eps as f32,
16971                                cache.k_heads(),
16972                                cache.v_heads(),
16973                                &mut out,
16974                            ) {
16975                                break 'attn out;
16976                            }
16977                        }
16978                    }
16979                    let masked = task_mask
16980                        .map(|m| m.head_flags(li, self.num_heads).iter().any(|&a| !a))
16981                        .unwrap_or(false);
16982                    let f32_view = (wq.as_f32(), wk.as_f32(), wv.as_f32(), wo.as_f32());
16983                    // The masked kernel knows one pipeline-wide geometry and
16984                    // RoPE table, no window and no sink.
16985                    let plain = self.layer_attn_plain(li);
16986                    match (masked, f32_view) {
16987                        // Historical masked path (f32 slices; the loader
16988                        // keeps masked models in f32).
16989                        (true, (Some(q), Some(k), Some(v), Some(o))) if plain => {
16990                            let active_heads = task_mask.unwrap().head_flags(li, self.num_heads);
16991                            attention::multi_head_attention(
16992                                &self.ws.n1,
16993                                q,
16994                                k,
16995                                v,
16996                                o,
16997                                &mut self.kv_cache.layers[li],
16998                                self.num_heads,
16999                                self.num_kv_heads,
17000                                self.head_dim,
17001                                self.hidden_size,
17002                                position,
17003                                &active_heads,
17004                                &self.inv_freq,
17005                            )
17006                        }
17007                        (masked, _) => {
17008                            if masked {
17009                                tracing::warn!(
17010                                    "layer {li}: head mask on quantized weights or on a \
17011                                     window/sink/per-layer-geometry layer not supported \
17012                                     yet — executing dense"
17013                                );
17014                            }
17015                            let inv_freq_l = self.layer_inv_freq(li);
17016                            let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
17017                            let cfg = QwenAttnCfg {
17018                                num_heads: self.layer_num_heads(li),
17019                                num_kv_heads: nkv_l,
17020                                head_dim: hd_l,
17021                                hidden_size: hs,
17022                                position,
17023                                inv_freq: &inv_freq_l,
17024                                rotary_dim: rd_l,
17025                                scale: self.attn_scale,
17026                                softcap: self.attn_softcap,
17027                                window: self.layer_window(li),
17028                                v_norm: self.attn_v_norm,
17029                                qk_norm_after_rope: self.qk_norm_after_rope,
17030                                gate_sigmoid: self.proj_gate_sigmoid,
17031                                q_norm: q_norm.as_deref(),
17032                                k_norm: k_norm.as_deref(),
17033                                output_gate: *output_gate,
17034                                softplus_gate: softplus_gate
17035                                    .as_ref()
17036                                    .map(|(gate, per_head)| (gate, *per_head)),
17037                                rope_scale: self.layer_rope_scale(li),
17038                                bias: bias
17039                                    .as_ref()
17040                                    .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
17041                                rms_eps: eps,
17042                                norm_style: self.norm_style,
17043                                pool: pool.as_deref(),
17044                                v_head_dim: self.layer_v_dim(li),
17045                            };
17046                            attention::qwen_attention(
17047                                &self.ws.n1,
17048                                wq,
17049                                wk,
17050                                wv,
17051                                wo,
17052                                &mut self.kv_cache.layers[li],
17053                                &cfg,
17054                            )
17055                        }
17056                    }
17057                }
17058            };
17059            // Gemma sandwich norm: normalize the attention branch before
17060            // it joins the residual stream.
17061            let attn_out = match &self.weights.layers[self.phys_layer(li)].attn_out_norm {
17062                Some(w) => inference::rms_norm(&attn_out, w, self.rms_eps, self.norm_style),
17063                None => attn_out,
17064            };
17065            let lw = &self.weights.layers[self.phys_layer(li)];
17066            let prof = crate::cpuprof::time(crate::cpuprof::Slot::Norms);
17067            inference::add_rmsnorm_fused_into(
17068                &mut h,
17069                &attn_out,
17070                &lw.post_norm,
17071                self.rms_eps,
17072                self.norm_style,
17073                &mut self.ws.p1,
17074            );
17075            drop(prof);
17076            let mut attn_out = attn_out;
17077            attention::recycle_buf(&mut attn_out);
17078            let post_normed = &self.ws.p1;
17079
17080            let ffn_masked = task_mask
17081                .map(|m| m.ffn_active_count(li) < self.intermediate_size)
17082                .unwrap_or(false);
17083            // One masked dense CONTRACT, dispatched by cost. The
17084            // activation-zeroing arm (the batched sweep's, validated
17085            // against the replica to 0.8%) computes the FULL fused FFN
17086            // and zeroes the dead — right whenever most neurons live.
17087            // The sparse arm reads ONLY active rows and down columns —
17088            // per-row dots are slower per element than the fused kernel,
17089            // so it pays only once the mask is deep enough. The 0.5
17090            // crossover is first-principles (fused kernels run ~2x the
17091            // per-row dot throughput); a shallow specialist (95% alive)
17092            // stays fused, a --target-sparsity bake flips arms on its
17093            // own weight.
17094            let ffn_out = match (ffn_masked, &lw.ffn) {
17095                // A defragged tube layer answers its own mask: the core
17096                // always runs, each tube runs when its bit is on, and
17097                // the tubes that are off are never read from the mmap.
17098                (_, FfnKind::Dense(d)) if !d.segs.is_empty() => {
17099                    let row = task_mask
17100                        .and_then(|tm| tm.ffn_masks.get(li))
17101                        .map(|v| v.as_slice());
17102                    tube_ffn(d, post_normed, 1, self.pool.as_deref(), row)
17103                }
17104                (true, FfnKind::Dense(d)) => {
17105                    let tm = task_mask.unwrap();
17106                    let alive = tm.ffn_active_count(li);
17107                    let deep = alive * 2 <= self.intermediate_size;
17108                    if deep && d.down_proj.sparse_col_ok() && !d.gate_proj.has_prism_contract() {
17109                        let active = tm.ffn_active_indices(li);
17110                        sparse_ffn_quant(
17111                            d,
17112                            post_normed,
17113                            &active,
17114                            self.hidden_size,
17115                            self.pool.as_deref(),
17116                        )
17117                    } else if deep
17118                        && let (Some(g), Some(u), Some(dn)) = (
17119                            d.gate_proj.as_f32(),
17120                            d.up_proj.as_f32(),
17121                            d.down_proj.as_f32(),
17122                        )
17123                    {
17124                        let active = tm.ffn_active_indices(li);
17125                        inference::sparse_ffn_forward(
17126                            post_normed,
17127                            g,
17128                            u,
17129                            dn,
17130                            self.hidden_size,
17131                            self.intermediate_size,
17132                            &active,
17133                            self.pool.as_deref(),
17134                        )
17135                    } else {
17136                        let row = tm.ffn_masks.get(li).map(|v| v.as_slice());
17137                        dense_ffn_batch(d, post_normed, 1, self.pool.as_deref(), row)
17138                    }
17139                }
17140                (true, FfnKind::Moe(m)) => {
17141                    // MoE is sparse by expert selection; a task mask
17142                    // narrows the ROUTABLE set via its expert fields
17143                    // (spec §5) when it carries them.
17144                    let allowed = task_mask.and_then(|tm| tm.expert_flags(li, m.experts.len()));
17145                    ffn_forward(
17146                        &lw.ffn,
17147                        post_normed,
17148                        self.pool.as_deref(),
17149                        allowed.as_deref(),
17150                    )
17151                }
17152                (true, FfnKind::DenseMoe(dm)) => dense_moe_ffn(
17153                    dm,
17154                    post_normed,
17155                    &h,
17156                    self.rms_eps,
17157                    self.norm_style,
17158                    self.pool.as_deref(),
17159                ),
17160                (false, _) => match &lw.ffn {
17161                    FfnKind::DenseMoe(dm) => dense_moe_ffn(
17162                        dm,
17163                        post_normed,
17164                        &h,
17165                        self.rms_eps,
17166                        self.norm_style,
17167                        self.pool.as_deref(),
17168                    ),
17169                    FfnKind::Moe(m)
17170                        if task_mask.is_none()
17171                            && host_tail
17172                            && li >= tail_start
17173                            && crate::minicpm_tail::MiniCpmTail::is_requested_target(m) =>
17174                    {
17175                        moe_ffn_minicpm_tail(
17176                            &mut self.minicpm_tail,
17177                            li,
17178                            self.num_layers,
17179                            m,
17180                            post_normed,
17181                            self.pool.as_deref(),
17182                        )
17183                    }
17184                    FfnKind::Moe(m)
17185                        if task_mask.is_none() && self.mimo_moe.is_dynamic(li, host_tail) =>
17186                    {
17187                        moe_ffn_banked(&mut self.mimo_moe, li, m, post_normed, self.pool.as_deref())
17188                    }
17189                    _ => {
17190                        let allowed = match (&lw.ffn, task_mask) {
17191                            (FfnKind::Moe(m), Some(tm)) => tm.expert_flags(li, m.experts.len()),
17192                            _ => None,
17193                        };
17194                        ffn_forward(
17195                            &lw.ffn,
17196                            post_normed,
17197                            self.pool.as_deref(),
17198                            allowed.as_deref(),
17199                        )
17200                    }
17201                },
17202            };
17203            let ffn_out = match &self.weights.layers[self.phys_layer(li)].ffn_out_norm {
17204                Some(w) => inference::rms_norm(&ffn_out, w, self.rms_eps, self.norm_style),
17205                None => ffn_out,
17206            };
17207            for (i, &f) in ffn_out.iter().enumerate() {
17208                h[i] += f;
17209            }
17210            let mut ffn_out = ffn_out;
17211            attention::recycle_buf(&mut ffn_out);
17212
17213            // Gemma-4: the layer output is scaled by a learned scalar.
17214            if let Some(sc) = self.weights.layers[self.phys_layer(li)].layer_scale {
17215                for v in h.iter_mut() {
17216                    *v *= sc;
17217                }
17218            }
17219            // CMF_LAYER_DUMP: this position's hidden after layer li.
17220            if self.layer_dump.is_some() {
17221                self.dump_layer_row(position, li, &h);
17222            }
17223
17224            // Looped Transformer: apply final norm at the end of each loop iteration.
17225            // Nanbeige 4.2: after layer 21 (virtual), apply norm before looping back to layer 0.
17226            if self.is_loop_end(li) && li + 1 < self.num_layers {
17227                h = inference::rms_norm(
17228                    &h,
17229                    &self.weights.final_norm,
17230                    self.rms_eps,
17231                    self.norm_style,
17232                );
17233            }
17234
17235            // Dynamic routing φ capture (on-policy): the
17236            // EMA of the post-residual hidden at the router's phi_layer,
17237            // updated as the context evolves during decode.
17238            if self.dyn_phi_layer == Some(li) {
17239                self.update_dyn_phi(&h);
17240            }
17241        }
17242        crate::gpu::set_layer(-1); // layers done — lm_head outside layer-split
17243        if let Some(t) = t_race_cpu {
17244            crate::gpu::graph_race_record(false, t.elapsed());
17245        }
17246
17247        h
17248    }
17249
17250    /// EMA of φ at the router layer (rolling, weight 0.2 = ~5-token
17251    /// horizon). First observation seeds it exactly.
17252    fn update_dyn_phi(&mut self, h: &[f32]) {
17253        const A: f32 = 0.2;
17254        if self.dyn_phi_ema.len() != h.len() {
17255            self.dyn_phi_ema = vec![0.0; h.len()];
17256            self.dyn_phi_seen = 0;
17257        }
17258        if self.dyn_phi_seen == 0 {
17259            self.dyn_phi_ema.copy_from_slice(h);
17260        } else {
17261            for (e, &v) in self.dyn_phi_ema.iter_mut().zip(h) {
17262                *e = (1.0 - A) * *e + A * v;
17263            }
17264        }
17265        self.dyn_phi_seen += 1;
17266    }
17267
17268    /// Current router φ (EMA at phi_layer); empty until first capture.
17269    pub fn dyn_phi(&self) -> &[f32] {
17270        &self.dyn_phi_ema
17271    }
17272
17273    /// Enable/disable φ capture at the router layer, reset the EMA.
17274    pub fn set_dyn_phi_layer(&mut self, layer: Option<usize>) {
17275        self.dyn_phi_layer = layer;
17276        self.dyn_phi_ema.clear();
17277        self.dyn_phi_seen = 0;
17278    }
17279
17280    /// Skills eligible for dynamic switching: (index, id, phi_layer).
17281    pub fn dynamic_skills(&self) -> Vec<(usize, String, usize)> {
17282        let Some(model) = &self.model else {
17283            return Vec::new();
17284        };
17285        model
17286            .header
17287            .skills
17288            .iter()
17289            .enumerate()
17290            .filter_map(|(i, sk)| {
17291                // A v2 record routes only through the request-level
17292                // backbone-gated decision (its status and gate are
17293                // checked there), never per token.
17294                if sk.is_v2() {
17295                    return None;
17296                }
17297                let ok = matches!(self.dyn_skill_layers.get(i), Some(Some(_)));
17298                let sel = sk.selection.as_ref()?;
17299                (ok).then(|| (i, sk.id.clone(), sel.phi_layer))
17300            })
17301            .collect()
17302    }
17303
17304    /// Index of the currently overlaid skill (None = backbone).
17305    pub fn active_skill(&self) -> Option<usize> {
17306        self.dyn_active
17307    }
17308
17309    /// Enable dynamic per-token skill routing: build the hysteresis
17310    /// router from the container's routable skills, start φ capture at
17311    /// their (shared) phi_layer. Returns the number of routable skills
17312    /// (0 = nothing to route; router stays off). Idempotent.
17313    pub fn enable_dynamic_routing(&mut self) -> usize {
17314        use crate::swarm::{DynRouter, RoutableSkill};
17315        let Some(model) = self.model.clone() else {
17316            return 0;
17317        };
17318        // Router policy v2 (spec §9.4) routes per REQUEST: the backbone is
17319        // the default and only the backbone-gated decision may pick a
17320        // skill. A per-token switch would bypass that gate (and change
17321        // the O(1) state mid-sequence), so the hysteresis router never
17322        // runs on such a file; the caller keeps the request-level
17323        // decision.
17324        if let Some(r) = &model.header.router {
17325            tracing::warn!(
17326                "dynamic routing disabled: this file declares router policy '{}' with \
17327                 granularity \"{}\" — the request-level decision applies instead",
17328                r.policy,
17329                r.granularity
17330            );
17331            return 0;
17332        }
17333        // Format-v2 skill records (bit SKILLS_V2) without a router policy:
17334        // their status/gate contract ("auto-routing requires active +
17335        // measured") lives in the backbone-gated decision only — the
17336        // hysteresis router would switch into a quarantined record
17337        // (fail-open). Refuse the whole file, not just its v2 records.
17338        if model.required_features & cortiq_core::format::features::SKILLS_V2 != 0
17339            || model.header.skills.iter().any(|s| s.is_v2())
17340        {
17341            tracing::warn!(
17342                "dynamic routing disabled: this file carries format-v2 skill records \
17343                 (SKILLS_V2) — they route per request through a router policy only"
17344            );
17345            return 0;
17346        }
17347        // A blend materialized f32 working tensors into the layers; there
17348        // is no single skill index to revert from → refuse (honest).
17349        if self.dyn_blend_loaded {
17350            tracing::warn!("dynamic routing unavailable on a blend-loaded pipeline");
17351            return 0;
17352        }
17353        // A statically-overlaid skill that is NOT FFN-eligible can't be
17354        // cheaply reverted at generation start → refuse rather than
17355        // silently keep it overlaid.
17356        if let Some(a) = self.dyn_active {
17357            if !matches!(self.dyn_skill_layers.get(a), Some(Some(_))) {
17358                tracing::warn!("loaded skill is not FFN-eligible — dynamic routing unavailable");
17359                return 0;
17360            }
17361        }
17362        let hidden = self.hidden_size;
17363        let mut skills = Vec::new();
17364        for (idx, id, _phi) in self.dynamic_skills() {
17365            if let Some(sel) = model.header.skills[idx].selection.as_ref() {
17366                if let Some(rs) = RoutableSkill::from_descriptor(idx, id, sel, hidden) {
17367                    skills.push(rs);
17368                }
17369            }
17370        }
17371        if skills.is_empty() {
17372            return 0;
17373        }
17374        // Skills should share a phi_layer; warn (not fail) if they don't.
17375        let phi = skills[0].phi_layer;
17376        if skills.iter().any(|s| s.phi_layer != phi) {
17377            tracing::warn!("routable skills disagree on phi_layer; using {phi}");
17378        }
17379        let n = skills.len();
17380        self.set_dyn_phi_layer(Some(phi));
17381        self.dyn_router = Some(DynRouter::new(skills));
17382        n
17383    }
17384
17385    /// Human-readable switch log from the last dynamic-routed generation.
17386    pub fn route_switches(&self) -> Vec<(usize, Option<String>, Option<String>)> {
17387        self.dyn_router
17388            .as_ref()
17389            .map(|r| r.switches.clone())
17390            .unwrap_or_default()
17391    }
17392
17393    /// LM head: hidden → logits [vocab_size]. The dominant matvec of
17394    /// every decode step — row-parallel on the worker pool.
17395    fn lm_head_forward(&self, hidden: &[f32]) -> Vec<f32> {
17396        let _mimo_q8 = self
17397            .mimo_moe
17398            .is_on()
17399            .then(crate::qtensor::enter_full_gpu_q8_scope);
17400        let rows = self.weights.lm_head.rows();
17401        let mut logits = attention::take_buf(rows.min(self.vocab_size));
17402        // Banked MiMo uses the same exact projection family for the
17403        // plain/draft head and the batched verification head. Read both
17404        // scale planes in-place instead of preparing per-op scale buffers.
17405        let served = self.mimo_moe.is_on()
17406            && crate::gpu::mimo_q8_short_enabled()
17407            && rows == self.vocab_size
17408            && !self.weights.lm_head.has_prism_contract()
17409            && self
17410                .weights
17411                .lm_head
17412                .graph_weight()
17413                .is_some_and(|(model, idx, kind, _)| {
17414                    kind == 7
17415                        && crate::gpu::q82_short_rows(
17416                            model,
17417                            idx,
17418                            hidden,
17419                            1,
17420                            rows,
17421                            self.hidden_size,
17422                            &mut logits,
17423                        )
17424                });
17425        if !served {
17426            self.weights
17427                .lm_head
17428                .matvec(hidden, &mut logits, self.pool.as_deref());
17429        }
17430        logits.resize(self.vocab_size, 0.0);
17431        if let Some(m) = self.logit_multiplier {
17432            for l in logits.iter_mut() {
17433                *l *= m;
17434            }
17435        }
17436        if let Some(c) = self.final_softcap {
17437            softcap_in_place(&mut logits, c, self.pool.as_deref());
17438        }
17439        if let Some(cm) = self.head_clusters.as_ref() {
17440            self.hierarchical_head_logprobs(hidden, cm, &mut logits);
17441        }
17442        logits
17443    }
17444
17445    /// Two-level head (Cortiq Embryo): in place, logits[v] ← log p(v) =
17446    /// (lc[c] − lse(lc)) + (logit[v] − lse over v's cluster block), c = v / S.
17447    fn hierarchical_head_logprobs(&self, hidden: &[f32], cm: &[f32], logits: &mut [f32]) {
17448        let h = hidden.len();
17449        let ncl = cm.len() / h.max(1);
17450        if ncl == 0 || logits.len() % ncl != 0 {
17451            return;
17452        }
17453        let cs = logits.len() / ncl;
17454        // cluster logits + log-softmax
17455        let mut lc = vec![0.0f32; ncl];
17456        for c in 0..ncl {
17457            let row = &cm[c * h..(c + 1) * h];
17458            let mut s = 0.0f32;
17459            for j in 0..h {
17460                s += row[j] * hidden[j];
17461            }
17462            lc[c] = s;
17463        }
17464        let mx = lc.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
17465        let lse: f32 = mx + lc.iter().map(|v| (v - mx).exp()).sum::<f32>().ln();
17466        for c in 0..ncl {
17467            let blk = &mut logits[c * cs..(c + 1) * cs];
17468            let bm = blk.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
17469            let bl: f32 = bm + blk.iter().map(|v| (v - bm).exp()).sum::<f32>().ln();
17470            let add = lc[c] - lse - bl;
17471            for v in blk.iter_mut() {
17472                *v += add;
17473            }
17474        }
17475    }
17476
17477    /// Prefill `ids` and return the next-token logits — what the model
17478    /// would predict next, WITHOUT committing to generation (introspection
17479    /// for `cortiq explain`). Clears and repopulates the KV cache; leaves
17480    /// the active overlay untouched.
17481    pub fn prefill_next_logits(&mut self, ids: &[u32], task_mask: Option<&TaskMask>) -> Vec<f32> {
17482        #[cfg(target_os = "macos")]
17483        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
17484        self.clear_sequence_state();
17485        // This helper is used by the pooled classification endpoint, where
17486        // every request is a fresh sequence. The shared reset also clears the
17487        // wgpu token graph's device-side recurrent state.
17488        crate::gpu::graph_race_begin_generation();
17489        if task_mask.is_none() {
17490            self.o1_begin();
17491        }
17492        let mut hidden = vec![0.0f32; self.hidden_size];
17493        for (pos, &id) in ids.iter().enumerate() {
17494            let emb = self.embed_single(id);
17495            hidden = self.forward_layers(&emb, pos, task_mask);
17496        }
17497        if let Err(err) = self.o1_seal_checked() {
17498            self.o1_fail(err);
17499        }
17500        // Stacks that own their head (V4, V4.1, Qwen3.8-Flash-Next, GLM-5)
17501        // return a zero hidden and hand the logits out of band.
17502        if let Some(logits) = self.graph_logits.take() {
17503            return logits;
17504        }
17505        inference::rms_norm_into(
17506            &hidden,
17507            &self.weights.final_norm,
17508            self.rms_eps,
17509            self.norm_style,
17510            &mut self.ws.n1,
17511        );
17512        self.lm_head_forward(&self.ws.n1)
17513    }
17514}
17515
17516/// Convenience: deterministic tiny pipeline for tests.
17517pub fn create_test_pipeline(
17518    hidden_size: usize,
17519    intermediate_size: usize,
17520    num_heads: usize,
17521    num_kv_heads: usize,
17522    head_dim: usize,
17523    num_layers: usize,
17524    vocab_size: usize,
17525) -> Pipeline {
17526    // Small pseudo-random weights: constant weights make attention
17527    // degenerate and hide indexing bugs.
17528    let synth = |n: usize, salt: usize| -> Vec<f32> {
17529        (0..n)
17530            .map(|i| (((i * 31 + salt * 17 + 7) % 97) as f32 / 97.0 - 0.5) * 0.2)
17531            .collect()
17532    };
17533    let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
17534        QTensor::from_f32(synth(rows * cols, salt), rows, cols)
17535    };
17536    let layer_weights: Vec<LayerWeights> = (0..num_layers)
17537        .map(|li| LayerWeights {
17538            input_norm: vec![1.0; hidden_size],
17539            post_norm: vec![1.0; hidden_size],
17540            attn_out_norm: None,
17541            ffn_out_norm: None,
17542            layer_scale: None,
17543            ffn: FfnKind::Dense(DenseFfn {
17544                gate_proj: qt(intermediate_size, hidden_size, li * 10 + 5),
17545                up_proj: qt(intermediate_size, hidden_size, li * 10 + 6),
17546                down_proj: qt(hidden_size, intermediate_size, li * 10 + 7),
17547                act: Act::Silu,
17548                down_t: None,
17549                segs: Vec::new(),
17550            }),
17551            attn: AttnKind::Full {
17552                bias: None,
17553                wq: qt(num_heads * head_dim, hidden_size, li * 10 + 1),
17554                wk: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 2),
17555                wv: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 3),
17556                wo: qt(hidden_size, num_heads * head_dim, li * 10 + 4),
17557                q_norm: None,
17558                k_norm: None,
17559                output_gate: false,
17560                softplus_gate: None,
17561            },
17562        })
17563        .collect();
17564
17565    Pipeline::new(
17566        Tokenizer::byte_level(),
17567        PipelineWeights {
17568            embed_tokens: qt(vocab_size, hidden_size, 100),
17569            layers: layer_weights,
17570            lm_head: qt(vocab_size, hidden_size, 200),
17571            final_norm: vec![1.0; hidden_size],
17572        },
17573        hidden_size,
17574        intermediate_size,
17575        num_heads,
17576        num_kv_heads,
17577        head_dim,
17578        num_layers,
17579        num_layers, // physical_layers = num_layers (non-looped)
17580        false,      // loop_final_norm
17581        vocab_size,
17582        1e-6,
17583        10_000.0,
17584        NormStyle::Qwen,
17585        4096,
17586        SamplerConfig {
17587            seed: Some(42),
17588            ..Default::default()
17589        },
17590    )
17591}
17592
17593/// Batched dense-FFN: gate/up/down via matmat (element-wise the same
17594/// math as b × dense_ffn — the same dot kernels).
17595/// One mask bit, LSB-first per byte — `TaskMask::ffn_active_indices`'s
17596/// convention.
17597#[inline]
17598fn mask_bit(row: &[u8], j: usize) -> bool {
17599    (row.get(j >> 3).copied().unwrap_or(0) >> (j & 7)) & 1 != 0
17600}
17601
17602/// Zero the CLOSED neurons' activations in a [rows × inter] panel — the
17603/// masked-inference fast path's whole trick: full fused quant compute,
17604/// then the mask lands on the ACTIVATIONS, which is arithmetically the
17605/// pruned network without touching a quantized weight byte. Whole open
17606/// bytes (0xFF = 8 open neurons) skip in one test.
17607/// `CMF_FFN_MASK_GAIN` — Patent 12 FIG. 4, variance-preserving
17608/// rescaling: truncation removes a share of the layer's output energy,
17609/// so the survivors are scaled up to put the variance back where the
17610/// downstream norm expects it. A scalar here; per layer it is
17611/// `sqrt(total energy / kept energy)`.
17612fn mask_gain() -> f32 {
17613    static G: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
17614    *G.get_or_init(|| {
17615        std::env::var("CMF_FFN_MASK_GAIN")
17616            .ok()
17617            .and_then(|v| v.parse().ok())
17618            .unwrap_or(1.0)
17619    })
17620}
17621
17622fn zero_masked_cols(g: &mut [f32], rows: usize, inter: usize, row: &[u8]) {
17623    // With CMF_FFN_MEANFILL a closed neuron contributes its average
17624    // instead of nothing — same bytes read, one constant restored.
17625    let fill = meanfill().and_then(|(i, v)| {
17626        let li = crate::gpu::cur_layer();
17627        (*i == inter && li >= 0).then(|| &v[li as usize * inter..(li as usize + 1) * inter])
17628    });
17629    for r in 0..rows {
17630        let base = r * inter;
17631        for (bi, &byte) in row.iter().enumerate() {
17632            if byte == 0xFF {
17633                continue;
17634            }
17635            let j0 = bi * 8;
17636            for bit in 0..8 {
17637                let j = j0 + bit;
17638                if j < inter && byte & (1 << bit) == 0 {
17639                    g[base + j] = fill.map_or(0.0, |f| f[j]);
17640                }
17641            }
17642        }
17643    }
17644    let gain = mask_gain();
17645    if gain != 1.0 {
17646        for v in g[..rows * inter].iter_mut() {
17647            *v *= gain;
17648        }
17649    }
17650}
17651
17652/// True when neuron `i`'s bit is set (no mask = everything runs).
17653#[inline]
17654fn tube_bit(row: Option<&[u8]>, i: usize) -> bool {
17655    row.is_none_or(|r| mask_bit(r, i))
17656}
17657
17658/// Every bit below `n` set — the common case for a tube file's CORE,
17659/// where only the tube bits vary per task.
17660fn all_bits_on(row: &[u8], n: usize) -> bool {
17661    (0..n).all(|i| mask_bit(row, i))
17662}
17663
17664/// `CMF_TUBE_TOPK` — how many tubes a TOKEN may open (0 = the task mask
17665/// decides alone). This is the dense FFN read as a mixture: the tubes
17666/// are the experts a k-means over `gate_proj` rows found, and the token
17667/// picks among them. `CMF_TUBE_SCORE=gate` scores a tube by its own
17668/// gate (realizable: only `up`/`down` of the losers go unread),
17669/// `=oracle` scores by the true `silu(gate)·up` mass (the ceiling —
17670/// only `down` is saved, and the selection has read what it predicts).
17671fn tube_topk() -> usize {
17672    static K: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
17673    *K.get_or_init(|| {
17674        std::env::var("CMF_TUBE_TOPK")
17675            .ok()
17676            .and_then(|v| v.parse().ok())
17677            .unwrap_or(0)
17678    })
17679}
17680
17681fn tube_score_oracle() -> bool {
17682    static O: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
17683    *O.get_or_init(|| std::env::var("CMF_TUBE_SCORE").is_ok_and(|v| v == "oracle"))
17684}
17685
17686/// The routed arm of `tube_ffn`: a token opens only its best `k` tubes.
17687/// At `b == 1` (decode) the losers are genuinely never read — that is
17688/// the speed. At `b > 1` (the scoring sweep) every tube is computed and
17689/// the losers' activations are zeroed instead: same arithmetic, so the
17690/// perplexity is the routed model's, measured without a per-token
17691/// gather in the middle of a GEMM.
17692fn tube_ffn_routed(
17693    d: &DenseFfn,
17694    xs: &[f32],
17695    b: usize,
17696    pool: Option<&Pool>,
17697    mask_row: Option<&[u8]>,
17698    k: usize,
17699) -> Vec<f32> {
17700    let hidden = d.down_proj.rows();
17701    let core = d.gate_proj.rows();
17702    let core_full = mask_row.is_none_or(|r| all_bits_on(r, core));
17703    let mut out = match (b, core_full, mask_row) {
17704        (1, true, _) => dense_ffn(d, xs, pool),
17705        (1, false, Some(row)) => dense_ffn_masked(d, xs, pool, row),
17706        (_, true, _) => dense_ffn_batch(d, xs, b, pool, None),
17707        (_, false, row) => dense_ffn_batch(d, xs, b, pool, row),
17708    };
17709    let cand: Vec<usize> = (0..d.segs.len())
17710        .filter(|&i| tube_bit(mask_row, d.segs[i].start))
17711        .collect();
17712    if cand.is_empty() {
17713        return out;
17714    }
17715    // gate (and, where the score or the batch needs it, up) per tube.
17716    // The SCORE is taken at the point the serving path could take it:
17717    // off the gate alone, or off the finished activation for the oracle.
17718    let oracle = tube_score_oracle();
17719    let mut acts: Vec<Vec<f32>> = Vec::with_capacity(cand.len());
17720    let mut scores = vec![0f32; b * cand.len()];
17721    for (ci, &i) in cand.iter().enumerate() {
17722        let seg = &d.segs[i];
17723        let w = seg.width;
17724        let mut g = vec![0.0f32; b * w];
17725        if b == 1 {
17726            seg.gate.matvec(xs, &mut g, pool);
17727        } else {
17728            seg.gate.matmat(xs, b, &mut g, pool);
17729        }
17730        for v in g.iter_mut() {
17731            *v = Act::Silu.combine(*v, 1.0);
17732        }
17733        if !oracle {
17734            for t in 0..b {
17735                scores[t * cand.len() + ci] =
17736                    g[t * w..(t + 1) * w].iter().map(|v| v * v).sum::<f32>();
17737            }
17738        }
17739        if oracle || b > 1 {
17740            let mut u = vec![0.0f32; b * w];
17741            if b == 1 {
17742                seg.up.matvec(xs, &mut u, pool);
17743            } else {
17744                seg.up.matmat(xs, b, &mut u, pool);
17745            }
17746            for (a, &v) in g.iter_mut().zip(u.iter()) {
17747                *a *= v;
17748            }
17749            if oracle {
17750                for t in 0..b {
17751                    scores[t * cand.len() + ci] =
17752                        g[t * w..(t + 1) * w].iter().map(|v| v * v).sum::<f32>();
17753                }
17754            }
17755        }
17756        acts.push(g);
17757    }
17758    // per-token scores and the winners
17759    let keep = k.min(cand.len());
17760    let mut scratch: Vec<f32> = Vec::new();
17761    for t in 0..b {
17762        let mut sc: Vec<(f32, usize)> = (0..cand.len())
17763            .map(|ci| (scores[t * cand.len() + ci], ci))
17764            .collect();
17765        sc.sort_unstable_by(|x, y| y.0.total_cmp(&x.0));
17766        let mut alive = vec![false; cand.len()];
17767        for &(_, ci) in sc.iter().take(keep) {
17768            alive[ci] = true;
17769        }
17770        if b > 1 {
17771            for (ci, a) in acts.iter_mut().enumerate() {
17772                if !alive[ci] {
17773                    let w = d.segs[cand[ci]].width;
17774                    a[t * w..(t + 1) * w].fill(0.0);
17775                }
17776            }
17777        } else {
17778            // decode: finish only the winners — the losers' up/down
17779            // (and, with the gate score, everything but their gate)
17780            // are never touched.
17781            for (ci, &i) in cand.iter().enumerate() {
17782                if !alive[ci] {
17783                    continue;
17784                }
17785                let seg = &d.segs[i];
17786                let w = seg.width;
17787                let g = &mut acts[ci];
17788                if !tube_score_oracle() {
17789                    scratch.clear();
17790                    scratch.resize(w, 0.0);
17791                    seg.up.matvec(xs, &mut scratch, pool);
17792                    for (a, &v) in g.iter_mut().zip(scratch.iter()) {
17793                        *a *= v;
17794                    }
17795                }
17796                let mut acc = vec![0.0f32; hidden];
17797                seg.down.matvec(g, &mut acc, pool);
17798                for (o, a) in out.iter_mut().zip(&acc) {
17799                    *o += *a;
17800                }
17801            }
17802        }
17803    }
17804    if b > 1 {
17805        for (ci, &i) in cand.iter().enumerate() {
17806            let seg = &d.segs[i];
17807            let mut acc = vec![0.0f32; b * hidden];
17808            seg.down.matmat(&acts[ci], b, &mut acc, pool);
17809            for (o, a) in out.iter_mut().zip(&acc) {
17810                *o += *a;
17811            }
17812        }
17813    }
17814    out
17815}
17816
17817/// FFN of a defragged tube layer: the always-on core plus the tubes the
17818/// task mask switches on. Each tube is a normal tensor triple, so the
17819/// same kernels run it and an inactive tube's bytes are never read —
17820/// that is the whole point of the defrag (a scattered mask cannot skip
17821/// bytes; a contiguous one is just a smaller matrix).
17822fn tube_ffn(
17823    d: &DenseFfn,
17824    xs: &[f32],
17825    b: usize,
17826    pool: Option<&Pool>,
17827    mask_row: Option<&[u8]>,
17828) -> Vec<f32> {
17829    if tube_topk() > 0 {
17830        return tube_ffn_routed(d, xs, b, pool, mask_row, tube_topk());
17831    }
17832    let hidden = d.down_proj.rows();
17833    let core = d.gate_proj.rows();
17834    let core_full = mask_row.is_none_or(|r| all_bits_on(r, core));
17835    let mut out = match (b, core_full, mask_row) {
17836        (1, true, _) => dense_ffn(d, xs, pool),
17837        (1, false, Some(row)) => dense_ffn_masked(d, xs, pool, row),
17838        (_, true, _) => dense_ffn_batch(d, xs, b, pool, None),
17839        (_, false, row) => dense_ffn_batch(d, xs, b, pool, row),
17840    };
17841    TUBE_SCRATCH.with(|sc| {
17842        let mut sc = sc.borrow_mut();
17843        let [g, u, acc] = &mut *sc;
17844        for seg in &d.segs {
17845            if !tube_bit(mask_row, seg.start) {
17846                continue;
17847            }
17848            let w = seg.width;
17849            g.resize(b * w, 0.0);
17850            if b == 1
17851                && d.act == Act::Silu
17852                && QTensor::matvec_silu_mul(&seg.gate, &seg.up, xs, g, pool)
17853            {
17854                // g holds silu(gate)·up.
17855            } else {
17856                u.resize(b * w, 0.0);
17857                if b == 1 {
17858                    QTensor::matvec_many([&seg.gate, &seg.up], xs, [g, u], pool);
17859                } else {
17860                    seg.gate.matmat(xs, b, g, pool);
17861                    seg.up.matmat(xs, b, u, pool);
17862                }
17863                for i in 0..b * w {
17864                    g[i] = d.act.combine(g[i], u[i]);
17865                }
17866            }
17867            acc.resize(b * hidden, 0.0);
17868            acc.fill(0.0);
17869            if b == 1 {
17870                seg.down.matvec(g, acc, pool);
17871            } else {
17872                seg.down.matmat(g, b, acc, pool);
17873            }
17874            for (o, a) in out.iter_mut().zip(acc.iter()) {
17875                *o += *a;
17876            }
17877        }
17878        out
17879    })
17880}
17881
17882thread_local! {
17883    /// gate / up / down-accumulator scratch for the tube loop — a tube
17884    /// runs once per layer per token, and a fresh Vec each time is a
17885    /// malloc per tube per layer per token.
17886    static TUBE_SCRATCH: std::cell::RefCell<[Vec<f32>; 3]> =
17887        const { std::cell::RefCell::new([Vec::new(), Vec::new(), Vec::new()]) };
17888}
17889
17890/// CMF_PREFILL_PROF: cumulative ns of the batched walk's attention and
17891/// FFN halves (all layers, all chunks).
17892static PREFILL_SPLIT: [std::sync::atomic::AtomicU64; 2] = [
17893    std::sync::atomic::AtomicU64::new(0),
17894    std::sync::atomic::AtomicU64::new(0),
17895];
17896
17897/// The wgpu side of `CMF_PREFILL_PROF`: q|k|v GEMMs' enqueue and readback
17898/// wait, the chunk attend's readback wait (ms, cumulative) and the int8
17899/// GEMMs the `zi_mm` route took.
17900fn wgpu_prefill_counters() -> (f64, f64, f64, u64) {
17901    #[cfg(feature = "gpu")]
17902    {
17903        use std::sync::atomic::Ordering::Relaxed;
17904        let ms = |a: &std::sync::atomic::AtomicU64| a.load(Relaxed) as f64 / 1e6;
17905        (
17906            ms(&crate::gpu_wgpu::GEMM_MANY_NS[0]),
17907            ms(&crate::gpu_wgpu::GEMM_MANY_NS[1]),
17908            ms(&crate::gpu_wgpu::CHUNK_ATTEND_WAIT_NS),
17909            crate::gpu_wgpu::ZI_GEMM_CALLS.load(Relaxed),
17910        )
17911    }
17912    #[cfg(not(feature = "gpu"))]
17913    (0.0, 0.0, 0.0, 0)
17914}
17915
17916/// The wgpu prefill mirror attend's outcome counters
17917/// (`gpu_wgpu::MIRROR_EVENTS`).
17918fn wgpu_mirror_counters() -> [u64; 6] {
17919    #[cfg(feature = "gpu")]
17920    {
17921        crate::gpu_wgpu::MIRROR_EVENTS
17922            .each_ref()
17923            .map(|a| a.load(std::sync::atomic::Ordering::Relaxed))
17924    }
17925    #[cfg(not(feature = "gpu"))]
17926    [0; 6]
17927}
17928
17929fn prefill_prof_on() -> bool {
17930    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
17931    *ON.get_or_init(|| std::env::var_os("CMF_PREFILL_PROF").is_some())
17932}
17933
17934fn dense_ffn_batch(
17935    d: &DenseFfn,
17936    xs: &[f32],
17937    b: usize,
17938    pool: Option<&Pool>,
17939    mask_row: Option<&[u8]>,
17940) -> Vec<f32> {
17941    let inter = d.gate_proj.rows();
17942    let hidden = d.down_proj.rows();
17943    // Fused on-device SwiGLU when the device is in play: three separate
17944    // `matmat` calls are three round trips per layer, and the gate/up
17945    // panels (b × inter — 22 MB each at a 512-token chunk) cross the bus
17946    // twice for nothing. The kernel already existed for the image DiT;
17947    // the LLM prefill was simply never wired to it. A task mask needs the
17948    // activations on the host between the halves, so it keeps the CPU
17949    // arm below.
17950    // SiLU/GELU have device arms everywhere they are admitted.  MiniMax
17951    // M3's frozen OAI contract has an additional WGPU-only arm; callers on
17952    // native Metal still get an honest decline from `q4_ffn_act` rather than
17953    // an accidental SiLU evaluation.
17954    let fused_act = d.act.wgpu_graph_act();
17955    if mask_row.is_none()
17956        && fused_act.is_some()
17957        && b >= 32
17958        && crate::gpu::enabled_here()
17959        && !crate::gpu::mm_killed()
17960        // The refit pass needs this layer's activations on the host; the
17961        // fused chain keeps them on the device. Refusing it here costs
17962        // one round trip and keeps every GEMM on the card — the
17963        // alternative was running the whole calibration on the CPU.
17964        && refit_dir().is_none()
17965        // Same for the mass/hit probes. The accumulator at the bottom of
17966        // this function only sees `g` when `g` came back to the host, so
17967        // a fused batch would leave it summing nothing — a probe that
17968        // reports zeros rather than failing, which is worse.
17969        && !ffn_probe_active()
17970        // GPTQ calibration folds every projection's input on the host
17971        // (`QTensor::matmat`); the fused chain would hand gate/up/down
17972        // their inputs on the card and leave the FFN uncalibrated.
17973        && !crate::gptq_capture::capturing()
17974    {
17975        if let (Some((model, w1)), Some((_, w3)), Some((_, w2))) = (
17976            d.gate_proj.mapped_q4t(),
17977            d.up_proj.mapped_q4t(),
17978            d.down_proj.mapped_q4t(),
17979        ) {
17980            let mut out = vec![0.0f32; b * hidden];
17981            let act = fused_act.expect("checked above");
17982            if crate::gpu::q4_ffn_act(
17983                model, w1, w3, w2, xs, b, hidden, inter, false, act, &mut out,
17984            ) {
17985                return out;
17986            }
17987        }
17988        // The q4tp twin (same kernel family, scale from the row ladder) —
17989        // the DiT has run it in production since the pipeline containers;
17990        // the LLM prefill was simply never wired to it, so a q4tp model's
17991        // prefill panels stayed on the CPU.
17992        if let (Some((model, w1)), Some((_, w3)), Some((_, w2))) = (
17993            d.gate_proj.mapped_q4tp(),
17994            d.up_proj.mapped_q4tp(),
17995            d.down_proj.mapped_q4tp(),
17996        ) {
17997            let mut out = vec![0.0f32; b * hidden];
17998            let act = fused_act.expect("checked above");
17999            if crate::gpu::q4_ffn_act(model, w1, w3, w2, xs, b, hidden, inter, true, act, &mut out)
18000            {
18001                return out;
18002            }
18003        }
18004        // Every other device codec — int8, or gate/up and down in different
18005        // codecs: the three GEMMs with the panels kept on the card. Without
18006        // it a q8_2f prefill read both b·inter panels home, folded them on
18007        // one host thread, and sent the result back for down.
18008        // CMF_FFN_KEEP=0 keeps the per-GEMM path (A/B).
18009        if let (true, Some((model, w1)), Some((_, w3)), Some((_, w2))) = (
18010            std::env::var("CMF_FFN_KEEP").as_deref() != Ok("0"),
18011            d.gate_proj.mapped_device_gemm(),
18012            d.up_proj.mapped_device_gemm(),
18013            d.down_proj.mapped_device_gemm(),
18014        ) {
18015            let mut out = vec![0.0f32; b * hidden];
18016            let act = fused_act.expect("checked above");
18017            if crate::gpu::ffn_act_keep(model, w1, w3, w2, xs, b, hidden, inter, act, &mut out) {
18018                return out;
18019            }
18020        }
18021    }
18022    let mut g = vec![0.0f32; b * inter];
18023    d.gate_proj.matmat(xs, b, &mut g, pool);
18024    let mut u = vec![0.0f32; b * inter];
18025    d.up_proj.matmat(xs, b, &mut u, pool);
18026    if gate_topk() > 0 && d.act == Act::Silu {
18027        for t in 0..b {
18028            let row = &mut g[t * inter..(t + 1) * inter];
18029            for v in row.iter_mut() {
18030                *v = Act::Silu.combine(*v, 1.0);
18031            }
18032            keep_top_k(row, gate_topk());
18033        }
18034        for i in 0..b * inter {
18035            g[i] *= u[i];
18036        }
18037    } else {
18038        for i in 0..b * inter {
18039            g[i] = d.act.combine(g[i], u[i]);
18040        }
18041    }
18042    if let Some(row) = mask_row {
18043        zero_masked_cols(&mut g, b, inter, row);
18044    }
18045    if oracle_topk() > 0 {
18046        for t in 0..b {
18047            keep_top_k(&mut g[t * inter..(t + 1) * inter], oracle_topk());
18048        }
18049    }
18050    let mut out = vec![0.0f32; b * hidden];
18051    d.down_proj.matmat(&g, b, &mut out, pool);
18052    if refit_dir().is_some() {
18053        let li = crate::gpu::cur_layer();
18054        if li >= 0 {
18055            refit_accumulate(li as usize, &g, b, inter, &out, hidden, pool);
18056        }
18057    }
18058    // The DTG-MA probe, on the batched path: one prefill sweep gives the
18059    // same per-neuron statistic the per-position probe does, and on a 27B
18060    // that is minutes instead of hours.
18061    FFN_PROBE.with(|pr| {
18062        if let Some(acc) = pr.borrow_mut().as_mut() {
18063            let li = crate::gpu::cur_layer();
18064            if li < 0 {
18065                return;
18066            }
18067            let Some(row) = acc.get_mut(li as usize) else {
18068                return;
18069            };
18070            let sq = probe_sq();
18071            for t in 0..b {
18072                for (a, &v) in row.iter_mut().zip(&g[t * inter..(t + 1) * inter]) {
18073                    *a += if sq {
18074                        (v as f64) * (v as f64)
18075                    } else {
18076                        (v as f64).abs()
18077                    };
18078                }
18079            }
18080        }
18081    });
18082    out
18083}
18084
18085/// Batched MoE-FFN: router batched, positions are GROUPED by expert —
18086/// an expert's weights are read once for all its positions in the chunk
18087/// (the main prefill-GEMM win on MoE: 960MB/token of 35B experts).
18088/// Accumulate per-channel activation energy for `CMF_RMS_TRACE`.
18089fn accumulate_act(m: &MoeFfn, xs: &[f32], b: usize) {
18090    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
18091    static DUMP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
18092    let on = *ON.get_or_init(|| std::env::var("CMF_RMS_TRACE").is_ok());
18093    let dump = *DUMP.get_or_init(|| std::env::var("CMF_ACT_DUMP").is_ok());
18094    if (!on && !dump) || b == 0 {
18095        return;
18096    }
18097    let hidden = xs.len() / b;
18098    if on {
18099        let mut acc = m.act_sq.borrow_mut();
18100        if acc.len() < hidden {
18101            acc.resize(hidden, 0.0);
18102        }
18103        for t in 0..b {
18104            let row = &xs[t * hidden..(t + 1) * hidden];
18105            for (a, &v) in acc.iter_mut().zip(row) {
18106                *a += (v as f64) * (v as f64);
18107            }
18108        }
18109    }
18110    if dump {
18111        // Cap the capture: the covariance needs a few thousand rows, and a
18112        // whole prefill of every layer would be gigabytes for no extra rank.
18113        let cap: usize = std::env::var("CMF_ACT_DUMP_ROWS")
18114            .ok()
18115            .and_then(|v| v.parse().ok())
18116            .unwrap_or(4096);
18117        let mut rows = m.act_rows.borrow_mut();
18118        if rows.len() < cap * hidden {
18119            let take = b.min((cap * hidden - rows.len()) / hidden.max(1));
18120            rows.extend_from_slice(&xs[..take * hidden]);
18121        }
18122    }
18123}
18124
18125/// Send-able cursor over a Vec-of-Vecs: each pool worker writes only its
18126/// own slots (disjoint by construction in the caller).
18127#[derive(Clone, Copy)]
18128struct SendVecs(*mut Vec<f32>);
18129unsafe impl Send for SendVecs {}
18130unsafe impl Sync for SendVecs {}
18131impl SendVecs {
18132    #[inline]
18133    fn at(self, i: usize) -> *mut Vec<f32> {
18134        unsafe { self.0.add(i) }
18135    }
18136}
18137
18138fn moe_ffn_batch(
18139    m: &MoeFfn,
18140    xs: &[f32],
18141    b: usize,
18142    hidden: usize,
18143    pool: Option<&Pool>,
18144    allowed: Option<&[bool]>,
18145) -> Vec<f32> {
18146    accumulate_act(m, xs, b);
18147    let ne = m.experts.len();
18148    let mut logits = vec![0.0f32; b * ne];
18149    match &m.resonance {
18150        Some(r) => {
18151            let hdim = xs.len() / b.max(1);
18152            for bi in 0..b {
18153                r.scores(
18154                    &xs[bi * hdim..(bi + 1) * hdim],
18155                    &mut logits[bi * ne..(bi + 1) * ne],
18156                );
18157            }
18158        }
18159        None => m.router.matmat(xs, b, &mut logits, pool),
18160    }
18161
18162    // Assignments: expert → [(position, weight)] — same routing as
18163    // moe_ffn, per position (see `moe_route`).
18164    let mut assign: Vec<Vec<(usize, f32)>> = vec![Vec::new(); ne];
18165    {
18166        let mut st = m.stats.borrow_mut();
18167        if st.len() < ne {
18168            st.resize(ne, 0);
18169        }
18170        for bi in 0..b {
18171            let (idx, p, wsum) = moe_route(&logits[bi * ne..(bi + 1) * ne], m, allowed);
18172            for &e in &idx {
18173                st[e] += 1;
18174                assign[e].push((bi, p[e] / wsum));
18175            }
18176        }
18177    }
18178
18179    let mut out = vec![0.0f32; b * hidden];
18180    let cols = m.experts[0].gate_proj.cols();
18181    let run_expert = |d: &DenseFfn, list: &[(usize, f32)], out: &mut [f32]| {
18182        let sb = list.len();
18183        let mut sub = vec![0.0f32; sb * cols];
18184        for (k, &(bi, _)) in list.iter().enumerate() {
18185            sub[k * cols..(k + 1) * cols].copy_from_slice(&xs[bi * cols..(bi + 1) * cols]);
18186        }
18187        let eo = dense_ffn_batch(d, &sub, sb, pool, None);
18188        for (k, &(bi, w)) in list.iter().enumerate() {
18189            for i in 0..hidden {
18190                out[bi * hidden + i] += w * eo[k * hidden + i];
18191            }
18192        }
18193    };
18194    // Routed experts: the panels are TINY (b·top_k spread over every
18195    // expert — a few positions each), so a pool dispatch per expert is
18196    // pure barrier cost. Invert the parallelism: workers take WHOLE
18197    // experts (serial math inside), then one deterministic scatter in
18198    // expert order — the exact accumulation order the serial loop had.
18199    let active: Vec<usize> = (0..ne).filter(|&e| !assign[e].is_empty()).collect();
18200    if pool.is_some() && active.len() >= 8 {
18201        let mut panels: Vec<Vec<f32>> = vec![Vec::new(); active.len()];
18202        {
18203            let panel_ptr = SendVecs(panels.as_mut_ptr());
18204            // Capture only the expert table: `m` itself carries RefCell
18205            // stats and must not cross the pool boundary.
18206            let experts = &m.experts;
18207            let (active_r, assign_r) = (&active, &assign);
18208            let inherit_cpu = crate::gpu::inherit_cpu_scope();
18209            let run = |start: usize, end: usize| {
18210                let _cpu_scope = inherit_cpu();
18211                // Native Metal: the per-op device helpers (`q4tp_ffn`,
18212                // `q8_matmat`, …) stage through size-keyed shared io
18213                // buffers and are not re-entrant — two workers whose experts
18214                // drew the same row count wrote one buffer at once, so a
18215                // Mellum2.1 prompt came out different on every run. The
18216                // workers keep whole experts on the CPU there; the device
18217                // prefill is the MoE chunk graph.
18218                #[cfg(target_os = "macos")]
18219                let _metal_cpu = crate::gpu::enter_cpu_scope();
18220                for ai in start..end {
18221                    let e = active_r[ai];
18222                    let list = &assign_r[e];
18223                    let sb = list.len();
18224                    let mut sub = vec![0.0f32; sb * cols];
18225                    for (k, &(bi, _)) in list.iter().enumerate() {
18226                        sub[k * cols..(k + 1) * cols]
18227                            .copy_from_slice(&xs[bi * cols..(bi + 1) * cols]);
18228                    }
18229                    // SAFETY: each worker owns a disjoint panels[ai].
18230                    unsafe {
18231                        *panel_ptr.at(ai) = dense_ffn_batch(&experts[e], &sub, sb, None, None);
18232                    }
18233                }
18234            };
18235            match pool {
18236                Some(p) => p.run_rows(active.len(), &run),
18237                None => run(0, active.len()),
18238            }
18239        }
18240        for (ai, &e) in active.iter().enumerate() {
18241            for (k, &(bi, w)) in assign[e].iter().enumerate() {
18242                let eo = &panels[ai][k * hidden..(k + 1) * hidden];
18243                for i in 0..hidden {
18244                    out[bi * hidden + i] += w * eo[i];
18245                }
18246            }
18247        }
18248    } else {
18249        for &e in &active {
18250            run_expert(&m.experts[e], &assign[e], &mut out);
18251        }
18252    }
18253    if let Some((se, gate)) = &m.shared {
18254        let all: Vec<(usize, f32)> = if let Some(gate) = gate {
18255            let mut gl = vec![0.0f32; b];
18256            gate.matmat(xs, b, &mut gl, pool);
18257            (0..b)
18258                .map(|bi| (bi, 1.0 / (1.0 + (-gl[bi]).exp())))
18259                .collect()
18260        } else {
18261            (0..b).map(|bi| (bi, 1.0)).collect()
18262        };
18263        run_expert(se, &all, &mut out);
18264    }
18265    out
18266}
18267
18268/// Decode-exact multi-token MoE — the MiMo speculative verify's FFN. Row
18269/// `r` of the result is bit-identical to `moe_ffn(m, x_r)` on the CPU
18270/// (`moe_ffn_cpu` → `moe_ffn_cpu_batched`): router matvec per row, the same
18271/// routing, the same int8 gate/up/SiLU and down terms
18272/// (`QTensor::moe_gate_up_rows` / `moe_down_rows`), and the row's experts
18273/// summed in ITS route order from 0. What the rows share is the weight
18274/// traffic: each routed expert is read once for every row that picked it.
18275/// (`moe_ffn_batch`, the prompt path, groups the same way but sums in
18276/// expert-index order and runs blocked kernels on wide groups — close, not
18277/// bit-equal to decode.) Any layer the kernels do not cover, or a device
18278/// that could answer `moe_ffn` itself, walks `moe_ffn` row by row.
18279fn moe_ffn_rows_exact(
18280    m: &MoeFfn,
18281    xs: &[f32],
18282    b: usize,
18283    hidden: usize,
18284    pool: Option<&Pool>,
18285) -> Vec<f32> {
18286    let mut out = vec![0.0f32; b * hidden];
18287    let per_row = |out: &mut [f32]| {
18288        for r in 0..b {
18289            let o = moe_ffn(m, &xs[r * hidden..(r + 1) * hidden], pool, None);
18290            out[r * hidden..(r + 1) * hidden].copy_from_slice(&o);
18291        }
18292    };
18293    let covered = !crate::gpu::enabled_here()
18294        && moe_batch_enabled()
18295        && m.shared.is_none()
18296        && m.resonance.is_none()
18297        && FFN_PROBE.with(|pr| pr.borrow().is_none())
18298        && m.experts.iter().all(|d| d.act == Act::Silu);
18299    if !covered {
18300        per_row(&mut out);
18301        return out;
18302    }
18303    let ne = m.experts.len();
18304    // Routing, row by row, exactly as `moe_ffn`.
18305    let mut routes: Vec<(Vec<usize>, Vec<f32>)> = Vec::with_capacity(b);
18306    for r in 0..b {
18307        let x = &xs[r * hidden..(r + 1) * hidden];
18308        accumulate_act(m, x, 1);
18309        let mut logits = vec![0.0f32; ne];
18310        m.router.matvec(x, &mut logits, pool);
18311        let (idx, p, wsum) = moe_route(&logits, m, None);
18312        {
18313            let mut st = m.stats.borrow_mut();
18314            if st.len() < ne {
18315                st.resize(ne, 0);
18316            }
18317            for &e in &idx {
18318                st[e] += 1;
18319            }
18320        }
18321        let w: Vec<f32> = idx
18322            .iter()
18323            .map(|&e| p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]))
18324            .collect();
18325        routes.push((idx, w));
18326    }
18327    if routes.iter().any(|(idx, _)| idx.is_empty()) {
18328        per_row(&mut out);
18329        return out;
18330    }
18331    // Group the (row, expert) picks by expert, in first-seen order.
18332    let mut experts: Vec<usize> = Vec::new();
18333    let mut groups: Vec<Vec<usize>> = Vec::new();
18334    for (r, (idx, _)) in routes.iter().enumerate() {
18335        for &e in idx {
18336            match experts.iter().position(|&x| x == e) {
18337                Some(g) => groups[g].push(r),
18338                None => {
18339                    experts.push(e);
18340                    groups.push(vec![r]);
18341                }
18342            }
18343        }
18344    }
18345    let n_pairs: usize = groups.iter().map(|g| g.len()).sum();
18346    let inter = m.experts[experts[0]].gate_proj.rows();
18347    let pairs: Vec<(&QTensor, &QTensor)> = experts
18348        .iter()
18349        .map(|&e| (&m.experts[e].gate_proj, &m.experts[e].up_proj))
18350        .collect();
18351    let mut gs: Vec<Vec<f32>> = (0..n_pairs).map(|_| vec![0f32; inter]).collect();
18352    if !QTensor::moe_gate_up_rows(&pairs, &groups, xs, &mut gs, pool) {
18353        per_row(&mut out);
18354        return out;
18355    }
18356    let downs: Vec<&QTensor> = experts.iter().map(|&e| &m.experts[e].down_proj).collect();
18357    let lens: Vec<usize> = groups.iter().map(|g| g.len()).collect();
18358    let mut ds: Vec<Vec<f32>> = (0..n_pairs).map(|_| vec![0f32; hidden]).collect();
18359    if !QTensor::moe_down_rows(&downs, &lens, &gs, &mut ds, pool) {
18360        per_row(&mut out);
18361        return out;
18362    }
18363    // Where each (row, expert) term landed in the flat pair list.
18364    let mut slot = std::collections::HashMap::with_capacity(n_pairs);
18365    let mut p = 0usize;
18366    for (g, &e) in experts.iter().enumerate() {
18367        for &r in &groups[g] {
18368            slot.insert((r, e), p);
18369            p += 1;
18370        }
18371    }
18372    for (r, (idx, w)) in routes.iter().enumerate() {
18373        let terms: Vec<(&[f32], f32)> = idx
18374            .iter()
18375            .zip(w)
18376            .map(|(&e, &we)| (ds[slot[&(r, e)]].as_slice(), we))
18377            .collect();
18378        let row = &mut out[r * hidden..(r + 1) * hidden];
18379        for (i, dst) in row.iter_mut().enumerate() {
18380            // `moe_down_many`'s per-row sum: from 0, in route order.
18381            let mut acc = 0f32;
18382            for (d, we) in &terms {
18383                acc += we * d[i];
18384            }
18385            *dst = acc;
18386        }
18387    }
18388    out
18389}
18390
18391/// Gemma's final-logit soft-capping, `c·tanh(x/c)`, over a whole vocab row —
18392/// element for element the serial expression, split across the pool: at a
18393/// 262k vocab the serial `tanh` pass was ~5 ms of a 36 ms decode token.
18394pub(crate) fn softcap_in_place(v: &mut [f32], c: f32, pool: Option<&Pool>) {
18395    match pool {
18396        Some(p) if v.len() >= 1 << 15 => {
18397            let base = v.as_mut_ptr() as usize;
18398            p.run_rows(v.len(), &|s, e| {
18399                // SAFETY: run_rows hands out disjoint [s, e) ranges of `v`,
18400                // which outlives the (blocking) dispatch.
18401                let sl =
18402                    unsafe { std::slice::from_raw_parts_mut((base as *mut f32).add(s), e - s) };
18403                for x in sl {
18404                    *x = c * (*x / c).tanh();
18405                }
18406            });
18407        }
18408        _ => {
18409            for x in v.iter_mut() {
18410                *x = c * (*x / c).tanh();
18411            }
18412        }
18413    }
18414}
18415
18416thread_local! {
18417    /// gate/up activation scratch for the dense FFN paths (single uses
18418    /// two slots, the fused pair all four) — these were fresh
18419    /// intermediate-size Vecs on every layer of every token.
18420    static FFN_SCRATCH: std::cell::RefCell<[Vec<f32>; 4]> =
18421        const { std::cell::RefCell::new([Vec::new(), Vec::new(), Vec::new(), Vec::new()]) };
18422}
18423
18424/// Dense SwiGLU FFN through QTensor matvecs (any storage).
18425fn dense_ffn(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
18426    // Per-token sparsity, when the file was built for it: gate first,
18427    // then only the chosen neurons' up/down rows leave the mmap.
18428    if gate_topk() > 0
18429        && let Some(out) = dense_ffn_dynamic(d, x, pool, gate_topk())
18430    {
18431        return out;
18432    }
18433    // Whole-FFN GPU submit (этап 4.2 increment): gate → silu·up → down
18434    // chained in ONE command buffer with the intermediate activations
18435    // resident on the device — 3 per-op polls become 1 per layer. The
18436    // moe_block backend already implements exactly this chain; a dense
18437    // FFN is one expert with weight 1. Runtime probe: the chain still
18438    // pays one submit+poll per layer — alternate it against the pure-CPU
18439    // FFN and keep whichever is faster on this machine.
18440    // q1 FFNs offload at any practical size: the q1 CPU kernel is
18441    // compute-bound, so the UMA threshold logic does not apply — the
18442    // probe measures and decides either way.
18443    // The fused GPU block has no descriptor-aware Prism path: it would either
18444    // consume an unrotated activation or decline after inspecting the mixed
18445    // q2tp/q4tp tensors.  Do not let that structural refusal enter the FFN
18446    // probe's CPU_ONLY scope; the ordinary body below dispatches each matrix
18447    // through QTensor::matvec, which owns the signed FWHT + affine q2tp route.
18448    let prism_body = d.gate_proj.has_prism_contract()
18449        || d.up_proj.has_prism_contract()
18450        || d.down_proj.has_prism_contract();
18451    if !prism_body
18452        && crate::gpu::enabled_here()
18453        && (d.gate_proj.rows() >= crate::gpu::min_rows() || d.gate_proj.is_q1())
18454    {
18455        let arm = if d.gate_proj.is_q1() && crate::gpu::q1_force() {
18456            crate::gpu::ProbeArm::Gpu
18457        } else {
18458            crate::gpu::probe_arm(crate::gpu::OpClass::Ffn)
18459        };
18460        match arm {
18461            crate::gpu::ProbeArm::Gpu => {
18462                let t0 = std::time::Instant::now();
18463                if let Some(out) = dense_ffn_gpu(d, x, pool) {
18464                    crate::gpu::probe_record(crate::gpu::OpClass::Ffn, true, t0.elapsed());
18465                    return out;
18466                }
18467                // Declined: no timing exists, so say so. Silence here is
18468                // what left `ffn` undecided for 9000 calls and cost a
18469                // failed device attempt on half of them.
18470                crate::gpu::probe_note_decline(crate::gpu::OpClass::Ffn);
18471            }
18472            crate::gpu::ProbeArm::CpuTimed => {
18473                let t0 = std::time::Instant::now();
18474                let out = crate::gpu::cpu_scope(|| dense_ffn_cpu(d, x, pool));
18475                crate::gpu::probe_record(crate::gpu::OpClass::Ffn, false, t0.elapsed());
18476                return out;
18477            }
18478            crate::gpu::ProbeArm::Cpu => {
18479                return crate::gpu::cpu_scope(|| dense_ffn_cpu(d, x, pool));
18480            }
18481        }
18482    }
18483    dense_ffn_cpu(d, x, pool)
18484}
18485
18486/// The pure-CPU dense-FFN body (also the fallback of every GPU refusal).
18487fn dense_ffn_cpu(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
18488    let inter = d.gate_proj.rows();
18489    FFN_SCRATCH.with(|s| {
18490        let mut s = s.borrow_mut();
18491        let [g, u, ..] = &mut *s;
18492        g.resize(inter, 0.0);
18493        // Fused gate+up+silu: one dispatch, no separate silu pass.
18494        // Falls back to matvec_many + silu loop for unsupported dtypes.
18495        if gate_topk() > 0 {
18496            // Gate first, select, and only then pay for `up`: the
18497            // measurement arm computes both and zeroes the losers, which
18498            // is the same arithmetic.
18499            u.resize(inter, 0.0);
18500            QTensor::matvec_many([&d.gate_proj, &d.up_proj], x, [g, u], pool);
18501            for i in 0..inter {
18502                g[i] = Act::Silu.combine(g[i], 1.0);
18503            }
18504            keep_top_k(g, gate_topk());
18505            for i in 0..inter {
18506                g[i] *= u[i];
18507            }
18508        } else if d.act == Act::Silu && {
18509            let _prof = crate::cpuprof::time(crate::cpuprof::Slot::FfnGateUp);
18510            QTensor::matvec_silu_mul(&d.gate_proj, &d.up_proj, x, g, pool)
18511        } {
18512            // g now holds silu(gate)·up directly.
18513        } else {
18514            u.resize(inter, 0.0);
18515            // Multi-matrix job: gate+up under one pool dispatch.
18516            let _prof = crate::cpuprof::time(crate::cpuprof::Slot::FfnGateUp);
18517            QTensor::matvec_many([&d.gate_proj, &d.up_proj], x, [g, u], pool);
18518            for i in 0..inter {
18519                g[i] = d.act.combine(g[i], u[i]);
18520            }
18521        }
18522        // DTG-MA bake probe (Patent 2): accumulate this layer's
18523        // per-neuron activation mass while a probe pass is active.
18524        // `CMF_FFN_PROBE_TOPK=k` switches the statistic from mass to a
18525        // HIT COUNT — how many tokens rank the neuron in their own top
18526        // k. Mass asks "how loud is this neuron overall", the count
18527        // asks "how often does this task actually need it", and the two
18528        // rank neurons differently whenever a few tokens are loud.
18529        FFN_PROBE.with(|pr| {
18530            if let Some(acc) = pr.borrow_mut().as_mut() {
18531                let li = crate::gpu::cur_layer();
18532                if li >= 0 {
18533                    if let Some(row) = acc.get_mut(li as usize) {
18534                        match probe_topk() {
18535                            0 if probe_sq() => {
18536                                for (a, &v) in row.iter_mut().zip(g.iter()) {
18537                                    *a += (v as f64) * (v as f64);
18538                                }
18539                            }
18540                            0 if probe_signed() => {
18541                                for (a, &v) in row.iter_mut().zip(g.iter()) {
18542                                    *a += v as f64;
18543                                }
18544                            }
18545                            0 => {
18546                                for (a, &v) in row.iter_mut().zip(g.iter()) {
18547                                    *a += (v as f64).abs();
18548                                }
18549                            }
18550                            k => {
18551                                let n = g.len();
18552                                let k = k.min(n);
18553                                let mut mag: Vec<f32> = g.iter().map(|v| v.abs()).collect();
18554                                let (_, kth, _) = mag.select_nth_unstable_by(k - 1, |a, b| {
18555                                    b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
18556                                });
18557                                let thr = *kth;
18558                                for (a, &v) in row.iter_mut().zip(g.iter()) {
18559                                    if v.abs() >= thr {
18560                                        *a += 1.0;
18561                                    }
18562                                }
18563                            }
18564                        }
18565                    }
18566                }
18567            }
18568        });
18569        if oracle_topk() > 0 {
18570            keep_top_k(g, oracle_topk());
18571        }
18572        {
18573            let li = crate::gpu::cur_layer();
18574            if li >= 0 {
18575                adump_row(li as usize, g);
18576            }
18577        }
18578        let mut out = attention::take_buf(d.down_proj.rows());
18579        let _prof = crate::cpuprof::time(crate::cpuprof::Slot::FfnDown);
18580        d.down_proj.matvec(g, &mut out, pool);
18581        out
18582    })
18583}
18584
18585/// Online accumulators for the AWNP refit of a narrowed FFN.
18586///
18587/// The refit needs `Gss = A_SᵀA_S` and `YA = YᵀA_S` per layer, where `A_S`
18588/// are the calibration activations of the KEPT neurons and `Y` the full
18589/// FFN output. Both are small enough to hold; the thing that is not is
18590/// the activations they are built from — a 27B layer would dump a
18591/// gigabyte per thousand tokens. So they are accumulated as the
18592/// calibration runs and written once at the end.
18593///
18594/// `CMF_FFN_REFIT=<dir>` holds `support.<L>.u32` (a u32 count then the
18595/// kept indices) for every layer to accumulate; `CMF_FFN_REFIT_FROM/TO`
18596/// bound the layer span so the accumulators fit in RAM.
18597pub struct RefitAcc {
18598    pub support: Vec<u32>,
18599    pub gss: Vec<f32>,
18600    pub ya: Vec<f32>,
18601    pub hidden: usize,
18602    pub tokens: u64,
18603    /// Activations staged transposed ([ns, t] and [hidden, t]) until the
18604    /// batch is worth a GEMM. The product costs `ns²` to move and add
18605    /// REGARDLESS of how many tokens went into it, so folding 16 chunks
18606    /// into one call cuts that cost 16× — it was 15 TB of traffic per
18607    /// calibration pass at one call per 256 tokens.
18608    pub buf_g: Vec<f32>,
18609    pub buf_o: Vec<f32>,
18610    pub buf_t: usize,
18611}
18612
18613/// The product buffer is SHARED across layers — one 473 MB allocation,
18614/// not one per layer (that was 30 GB of nothing on a 64-layer model).
18615/// It lives under the same lock as the accumulators.
18616type RefitState = (std::collections::HashMap<usize, RefitAcc>, Vec<f32>);
18617
18618static REFIT: std::sync::OnceLock<Option<(String, std::sync::Mutex<RefitState>)>> =
18619    std::sync::OnceLock::new();
18620
18621/// Is an FFN probe accumulator installed on this thread? The fused GPU
18622/// FFN must decline while one is, or the probe silently measures zero.
18623fn ffn_probe_active() -> bool {
18624    FFN_PROBE.with(|p| p.borrow().is_some())
18625}
18626
18627fn refit_dir() -> Option<&'static (String, std::sync::Mutex<RefitState>)> {
18628    REFIT
18629        .get_or_init(|| {
18630            std::env::var("CMF_FFN_REFIT").ok().map(|d| {
18631                (
18632                    d,
18633                    std::sync::Mutex::new((std::collections::HashMap::new(), Vec::new())),
18634                )
18635            })
18636        })
18637        .as_ref()
18638}
18639
18640/// Accumulate one prefill panel into the layer's refit statistics.
18641fn refit_accumulate(
18642    li: usize,
18643    g: &[f32],
18644    b: usize,
18645    inter: usize,
18646    out: &[f32],
18647    hidden: usize,
18648    pool: Option<&Pool>,
18649) {
18650    let Some((dir, map)) = refit_dir() else {
18651        return;
18652    };
18653    static SPAN: std::sync::OnceLock<(usize, usize)> = std::sync::OnceLock::new();
18654    let (from, to) = *SPAN.get_or_init(|| {
18655        let g = |k: &str, d: usize| {
18656            std::env::var(k)
18657                .ok()
18658                .and_then(|v| v.parse().ok())
18659                .unwrap_or(d)
18660        };
18661        (
18662            g("CMF_FFN_REFIT_FROM", 0),
18663            g("CMF_FFN_REFIT_TO", usize::MAX),
18664        )
18665    });
18666    if li < from || li > to {
18667        return;
18668    }
18669    let mut guard = map.lock().unwrap();
18670    let (map, shared) = &mut *guard;
18671    let acc = match map.entry(li) {
18672        std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
18673        std::collections::hash_map::Entry::Vacant(e) => {
18674            let path = format!("{dir}/support.{li}.u32");
18675            let Ok(bytes) = std::fs::read(&path) else {
18676                eprintln!("refit: no {path} — layer {li} skipped");
18677                return;
18678            };
18679            let n = u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize;
18680            let support: Vec<u32> = bytes[4..4 + n * 4]
18681                .chunks_exact(4)
18682                .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
18683                .collect();
18684            eprintln!(
18685                "refit: layer {li} support {n} ({:.0} MB of accumulator)",
18686                (n * n + hidden * n) as f64 * 4.0 / 1e6
18687            );
18688            e.insert(RefitAcc {
18689                gss: vec![0.0; n * n],
18690                ya: vec![0.0; hidden * n],
18691                buf_g: Vec::new(),
18692                buf_o: Vec::new(),
18693                buf_t: 0,
18694                support,
18695                hidden,
18696                tokens: 0,
18697            })
18698        }
18699    };
18700    let ns = acc.support.len();
18701    // Stage this chunk transposed; the GEMM fires once the batch is full.
18702    let cap = refit_batch();
18703    if acc.buf_g.is_empty() {
18704        acc.buf_g = vec![0.0; ns * cap];
18705        acc.buf_o = vec![0.0; hidden * cap];
18706    }
18707    let take = b.min(cap - acc.buf_t);
18708    for t in 0..take {
18709        let col = acc.buf_t + t;
18710        for (j, &n) in acc.support.iter().enumerate() {
18711            acc.buf_g[j * cap + col] = g[t * inter + n as usize];
18712        }
18713        for h in 0..hidden {
18714            acc.buf_o[h * cap + col] = out[t * hidden + h];
18715        }
18716    }
18717    acc.buf_t += take;
18718    acc.tokens += take as u64;
18719    if acc.buf_t < cap {
18720        return;
18721    }
18722    let bt = acc.buf_t;
18723    acc.buf_t = 0;
18724    // The GEMM WRITES its C (it zeroes the accumulators it uses), so the
18725    // chunk product lands in scratch and is added on — the one thing that
18726    // silently turns a Gram over 13 000 tokens into a Gram over 256.
18727    // Both products are `C[n, m] += X[n, b] · Yᵀ[b, m]` with X and Y
18728    // stored row-major [·, b] — exactly `gemm_nt_f32`'s shape, so the
18729    // card does them when it is up (this is the whole calibration's
18730    // cost: O(|S|²) per token, 2.9 PFLOP for a 27B pass). The tiled CPU
18731    // loop stays as the fallback. Neither accumulates, so the product
18732    // lands in scratch and is added on.
18733    let RefitAcc {
18734        gss,
18735        ya,
18736        buf_g,
18737        buf_o,
18738        ..
18739    } = acc;
18740    let need = (ns * ns).max(hidden * ns);
18741    if shared.len() < need {
18742        shared.resize(need, 0.0);
18743    }
18744    let scratch = &mut shared[..];
18745    let _ = bt;
18746    if crate::gpu::gemm_nt_f32_transient(buf_g, buf_g, &mut scratch[..ns * ns], ns, cap, ns) {
18747        add_into(gss, &scratch[..ns * ns], pool);
18748        if crate::gpu::gemm_nt_f32_transient(
18749            buf_o,
18750            buf_g,
18751            &mut scratch[..hidden * ns],
18752            hidden,
18753            cap,
18754            ns,
18755        ) {
18756            add_into(ya, &scratch[..hidden * ns], pool);
18757        } else {
18758            accum_outer_t(ya, hidden, ns, cap, buf_o, buf_g, pool);
18759        }
18760    } else {
18761        accum_outer_t(gss, ns, ns, cap, buf_g, buf_g, pool);
18762        accum_outer_t(ya, hidden, ns, cap, buf_o, buf_g, pool);
18763    }
18764    // No zeroing: the batch is always filled exactly (cap is a multiple
18765    // of the prefill chunk), and a memset of 178 MB a layer would cost
18766    // more than the GEMM.
18767}
18768
18769/// `CMF_FFN_REFIT_BATCH` — tokens staged before each GEMM (default 4096).
18770fn refit_batch() -> usize {
18771    static B: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
18772    *B.get_or_init(|| {
18773        std::env::var("CMF_FFN_REFIT_BATCH")
18774            .ok()
18775            .and_then(|v| v.parse().ok())
18776            .unwrap_or(4096)
18777    })
18778}
18779
18780/// `c[m, n] += Σ_t left[m, t]·right[n, t]` — both operands transposed,
18781/// the CPU fallback for the staged batch.
18782fn accum_outer_t(
18783    c: &mut [f32],
18784    m: usize,
18785    n: usize,
18786    b: usize,
18787    left: &[f32],
18788    right: &[f32],
18789    pool: Option<&Pool>,
18790) {
18791    let ptr = SendMut(c.as_mut_ptr());
18792    let body = |i: usize| {
18793        let ptr = &ptr;
18794        let row = unsafe { std::slice::from_raw_parts_mut(ptr.0.add(i * n), n) };
18795        for t in 0..b {
18796            let a = left[i * b + t];
18797            if a == 0.0 {
18798                continue;
18799            }
18800            for (j, o) in row.iter_mut().enumerate() {
18801                *o += a * right[j * b + t];
18802            }
18803        }
18804    };
18805    match pool {
18806        Some(p) if m > 1 => p.run_rows(m, &|s, e| {
18807            for i in s..e {
18808                body(i);
18809            }
18810        }),
18811        _ => {
18812            for i in 0..m {
18813                body(i);
18814            }
18815        }
18816    }
18817}
18818
18819/// `dst += src`, spread over the pool — at 118 M floats a layer this is
18820/// not a loop to leave on one core.
18821fn add_into(dst: &mut [f32], src: &[f32], pool: Option<&Pool>) {
18822    let n = dst.len().min(src.len());
18823    match pool {
18824        Some(p) if n >= 1 << 16 => {
18825            let ptr = SendMut(dst.as_mut_ptr());
18826            let f = |s: usize, e: usize| {
18827                let ptr = &ptr;
18828                for blk in s..e {
18829                    let (a, b) = (blk * 4096, ((blk + 1) * 4096).min(n));
18830                    for i in a..b {
18831                        unsafe { *ptr.0.add(i) += src[i] };
18832                    }
18833                }
18834            };
18835            p.run_rows(n.div_ceil(4096), &f);
18836        }
18837        _ => {
18838            for (d, v) in dst.iter_mut().zip(&src[..n]) {
18839                *d += *v;
18840            }
18841        }
18842    }
18843}
18844
18845/// `c[m, n] += Σ_t left[t, m]·right[t, n]`, with `left` stored [m, t] and
18846/// `right` [t, n]. Tiled over the rows of `c` so a tile stays in cache
18847/// while each token's `right` row streams past it once, and parallel
18848/// over tiles.
18849fn accum_outer(
18850    c: &mut [f32],
18851    m: usize,
18852    n: usize,
18853    b: usize,
18854    left: &[f32],
18855    right: &[f32],
18856    pool: Option<&Pool>,
18857) {
18858    const TILE: usize = 32;
18859    let tiles = m.div_ceil(TILE);
18860    let cp = SendMut(c.as_mut_ptr());
18861    let body = |ti: usize| {
18862        let cp = &cp;
18863        let i0 = ti * TILE;
18864        let i1 = (i0 + TILE).min(m);
18865        for t in 0..b {
18866            let r = &right[t * n..t * n + n];
18867            for i in i0..i1 {
18868                let a = left[i * b + t];
18869                if a == 0.0 {
18870                    continue;
18871                }
18872                // SAFETY: tiles partition c's rows; workers never overlap.
18873                let row = unsafe { std::slice::from_raw_parts_mut(cp.0.add(i * n), n) };
18874                for (o, v) in row.iter_mut().zip(r) {
18875                    *o += a * *v;
18876                }
18877            }
18878        }
18879    };
18880    match pool {
18881        Some(p) if tiles > 1 => p.run_rows(tiles, &|s, e| {
18882            for ti in s..e {
18883                body(ti);
18884            }
18885        }),
18886        _ => {
18887            for ti in 0..tiles {
18888                body(ti);
18889            }
18890        }
18891    }
18892}
18893
18894/// Write what the calibration accumulated: `gss.<L>.f32` and `ya.<L>.f32`.
18895pub fn refit_flush() -> usize {
18896    let Some((dir, map)) = refit_dir() else {
18897        return 0;
18898    };
18899    let guard = map.lock().unwrap();
18900    let mut n = 0;
18901    for (li, acc) in guard.0.iter() {
18902        // A silently truncated write here is a Gram that reshapes to
18903        // nothing an hour later — say it out loud instead.
18904        let w = |name: &str, v: &[f32]| {
18905            let path = format!("{dir}/{name}.{li}.f32");
18906            let bytes: Vec<u8> = v.iter().flat_map(|x| x.to_le_bytes()).collect();
18907            match std::fs::write(&path, &bytes) {
18908                Ok(()) => {}
18909                Err(e) => eprintln!(
18910                    "refit: FAILED to write {path} ({} MB): {e}",
18911                    bytes.len() / 1_000_000
18912                ),
18913            }
18914        };
18915        w("gss", &acc.gss);
18916        w("ya", &acc.ya);
18917        println!(
18918            "refit L{li}: {} support, {} tokens, hidden {}",
18919            acc.support.len(),
18920            acc.tokens,
18921            acc.hidden
18922        );
18923        n += 1;
18924    }
18925    n
18926}
18927
18928/// `CMF_FFN_ADUMP=<prefix>` — append every probed token's FFN activation
18929/// row to `<prefix>.<layer>.f16`. The co-activation record: which
18930/// neurons fire together, which is what a tube has to group if a token
18931/// is ever going to open one tube instead of sixteen.
18932fn adump_row(li: usize, g: &[f32]) {
18933    use std::io::Write as _;
18934    static FILES: std::sync::OnceLock<
18935        Option<(
18936            String,
18937            std::sync::Mutex<std::collections::HashMap<usize, std::fs::File>>,
18938        )>,
18939    > = std::sync::OnceLock::new();
18940    let Some((prefix, map)) = FILES
18941        .get_or_init(|| {
18942            std::env::var("CMF_FFN_ADUMP")
18943                .ok()
18944                .map(|p| (p, std::sync::Mutex::new(std::collections::HashMap::new())))
18945        })
18946        .as_ref()
18947    else {
18948        return;
18949    };
18950    // `CMF_FFN_ADUMP_FROM/_TO` narrow the dump to a layer span, so a big
18951    // calibration run fits on disk in a few passes instead of one.
18952    static SPAN: std::sync::OnceLock<(usize, usize)> = std::sync::OnceLock::new();
18953    let (from, to) = *SPAN.get_or_init(|| {
18954        let g = |k: &str, d: usize| {
18955            std::env::var(k)
18956                .ok()
18957                .and_then(|v| v.parse().ok())
18958                .unwrap_or(d)
18959        };
18960        (
18961            g("CMF_FFN_ADUMP_FROM", 0),
18962            g("CMF_FFN_ADUMP_TO", usize::MAX),
18963        )
18964    });
18965    if li < from || li > to {
18966        return;
18967    }
18968    let mut map = map.lock().unwrap();
18969    let f = map.entry(li).or_insert_with(|| {
18970        std::fs::File::create(format!("{prefix}.{li}.f16")).expect("adump file")
18971    });
18972    let mut bytes = Vec::with_capacity(g.len() * 2);
18973    for v in g {
18974        bytes.extend_from_slice(&cortiq_core::quant::f32_to_f16(*v).to_le_bytes());
18975    }
18976    let _ = f.write_all(&bytes);
18977}
18978
18979/// `CMF_FFN_ORACLE_TOPK` — keep only the k largest |silu(g)·u| of each
18980/// token and zero the rest. Not a serving mode: it is the CEILING of
18981/// contextual sparsity — what a per-token router would be chasing —
18982/// measured by cheating, since the selection reads the very activations
18983/// it would have to predict.
18984fn oracle_topk() -> usize {
18985    static K: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
18986    *K.get_or_init(|| {
18987        std::env::var("CMF_FFN_ORACLE_TOPK")
18988            .ok()
18989            .and_then(|v| v.parse().ok())
18990            .unwrap_or(0)
18991    })
18992}
18993
18994/// `CMF_FFN_GATE_TOPK` — the REALIZABLE cousin of the oracle: rank the
18995/// neurons by their gate alone (which the kernel has computed anyway
18996/// before it reads `up`), keep the k best, and drop the rest. Every
18997/// dropped neuron's `up` row and `down` column stay unread, so this is
18998/// the sparsity a serving path can actually take without a router.
18999fn gate_topk() -> usize {
19000    static K: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
19001    *K.get_or_init(|| {
19002        std::env::var("CMF_FFN_GATE_TOPK")
19003            .ok()
19004            .and_then(|v| v.parse().ok())
19005            .unwrap_or(0)
19006    })
19007}
19008
19009/// `CMF_FFN_GATE_BLOCK` — select in blocks of B neurons instead of one
19010/// by one. A scattered per-neuron choice cannot be read efficiently (a
19011/// row at a time, no prefetch runway); a block of 32 is a contiguous
19012/// 32-row slab of `up` and of the transposed `down`, which the ordinary
19013/// kernels stream. The question the measurement answers is what the
19014/// block costs in quality.
19015fn gate_block() -> usize {
19016    static B: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
19017    *B.get_or_init(|| {
19018        std::env::var("CMF_FFN_GATE_BLOCK")
19019            .ok()
19020            .and_then(|v| v.parse().ok())
19021            .unwrap_or(1)
19022    })
19023}
19024
19025/// Zero all but the `k` largest BLOCKS (by summed square) of a row.
19026fn keep_top_blocks(g: &mut [f32], keep_n: usize, block: usize) {
19027    let n = g.len();
19028    let nb = n.div_ceil(block);
19029    let kb = (keep_n.div_ceil(block)).clamp(1, nb);
19030    if kb >= nb {
19031        return;
19032    }
19033    let mut score: Vec<f32> = (0..nb)
19034        .map(|b| {
19035            g[b * block..((b + 1) * block).min(n)]
19036                .iter()
19037                .map(|v| v * v)
19038                .sum::<f32>()
19039        })
19040        .collect();
19041    let mut ord = score.clone();
19042    let (_, kth, _) = ord.select_nth_unstable_by(kb - 1, |a, b| {
19043        b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
19044    });
19045    let thr = *kth;
19046    for b in 0..nb {
19047        if score[b] < thr {
19048            g[b * block..((b + 1) * block).min(n)].fill(0.0);
19049        }
19050    }
19051    score.clear();
19052}
19053
19054/// Zero all but the `k` largest magnitudes of one token's activation row.
19055fn keep_top_k(g: &mut [f32], k: usize) {
19056    if gate_block() > 1 {
19057        return keep_top_blocks(g, k, gate_block());
19058    }
19059    let n = g.len();
19060    if k == 0 || k >= n {
19061        return;
19062    }
19063    let mut mag: Vec<f32> = g.iter().map(|v| v.abs()).collect();
19064    let (_, kth, _) = mag.select_nth_unstable_by(k - 1, |a, b| {
19065        b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
19066    });
19067    let thr = *kth;
19068    for v in g.iter_mut() {
19069        if v.abs() < thr {
19070            *v = 0.0;
19071        }
19072    }
19073}
19074
19075/// `CMF_FFN_PROBE_SQ` — accumulate Σa², so the dump divided by the token
19076/// count and square-rooted is the RMS activation trace Patent 12 weights
19077/// its matrices by.
19078fn probe_sq() -> bool {
19079    static S: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
19080    *S.get_or_init(|| std::env::var("CMF_FFN_PROBE_SQ").is_ok())
19081}
19082
19083/// `CMF_FFN_PROBE_SIGNED` — accumulate the SIGNED activation sum
19084/// instead of its magnitude: what a dropped neuron contributes ON
19085/// AVERAGE, which is the bias a narrowed FFN can add back for free.
19086fn probe_signed() -> bool {
19087    static S: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
19088    *S.get_or_init(|| std::env::var("CMF_FFN_PROBE_SIGNED").is_ok())
19089}
19090
19091/// `CMF_FFN_MEANFILL=<file>` — a masked-out neuron contributes its MEAN
19092/// activation instead of zero (`u32 layers, u32 inter, f32[…]`, the mass
19093/// dump layout, holding per-neuron means). Dropping a neuron outright
19094/// also drops its average contribution, which shifts the layer output by
19095/// a constant; filling the mean back is one add per layer and costs no
19096/// bytes off the bus. This is the measurement arm — in a tube file the
19097/// same correction ships as a per-task bias vector.
19098fn meanfill() -> Option<&'static (usize, Vec<f32>)> {
19099    static M: std::sync::OnceLock<Option<(usize, Vec<f32>)>> = std::sync::OnceLock::new();
19100    M.get_or_init(|| {
19101        let p = std::env::var("CMF_FFN_MEANFILL").ok()?;
19102        let b = std::fs::read(&p).ok()?;
19103        let inter = u32::from_le_bytes(b[4..8].try_into().ok()?) as usize;
19104        let vals: Vec<f32> = b[8..]
19105            .chunks_exact(4)
19106            .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
19107            .collect();
19108        eprintln!("meanfill: {} value(s), inter {inter}", vals.len());
19109        Some((inter, vals))
19110    })
19111    .as_ref()
19112}
19113
19114/// `CMF_FFN_PROBE_TOPK` — 0 (default) = accumulate mass, k>0 = count
19115/// how often a neuron lands in a token's top k.
19116fn probe_topk() -> usize {
19117    static K: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
19118    *K.get_or_init(|| {
19119        std::env::var("CMF_FFN_PROBE_TOPK")
19120            .ok()
19121            .and_then(|v| v.parse().ok())
19122            .unwrap_or(0)
19123    })
19124}
19125
19126thread_local! {
19127    /// DTG-MA activation probe: per-layer per-neuron Σ|silu(g)·u|
19128    /// accumulator, alive only during `Pipeline::probe_ffn_mass`.
19129    static FFN_PROBE: std::cell::RefCell<Option<Vec<Vec<f64>>>> =
19130        const { std::cell::RefCell::new(None) };
19131}
19132
19133/// Per-token structured sparsity, paid for in bytes.
19134///
19135/// The gate is the cheapest third of an FFN and it already says which
19136/// neurons matter: `silu(gate)` near zero means the neuron contributes
19137/// nothing whatever `up` says. So compute every gate, keep the `k`
19138/// loudest, and read ONLY those neurons' `up` rows and `down` rows —
19139/// the latter needs `down_proj` stored transposed, otherwise a neuron's
19140/// down weights are a strided column and "reading only those" costs a
19141/// full cache line each.
19142///
19143/// Returns `None` when the file has no transposed `down` (the caller
19144/// then runs the ordinary dense path).
19145fn dense_ffn_dynamic(d: &DenseFfn, x: &[f32], pool: Option<&Pool>, k: usize) -> Option<Vec<f32>> {
19146    // The scatter path reads individual rows/columns and cannot express the
19147    // per-matrix signed FWHT boundary.  Let the descriptor-aware dense path
19148    // handle Prism files rather than silently running an unrotated sparse
19149    // approximation.
19150    if d.gate_proj.has_prism_contract()
19151        || d.up_proj.has_prism_contract()
19152        || d.down_proj.has_prism_contract()
19153    {
19154        return None;
19155    }
19156    let dt = d.down_t.as_ref()?;
19157    let inter = d.gate_proj.rows();
19158    let hidden = dt.cols();
19159    if k == 0 || k >= inter || d.act != Act::Silu {
19160        return None;
19161    }
19162    DYN_SCRATCH.with(|sc| {
19163        let mut sc = sc.borrow_mut();
19164        let DynScratch {
19165            g,
19166            mag,
19167            live,
19168            parts,
19169        } = &mut *sc;
19170        g.resize(inter, 0.0);
19171        d.gate_proj.matvec(x, g, pool);
19172        for v in g.iter_mut() {
19173            *v = inference::silu(*v);
19174        }
19175        // The k-th largest |silu(gate)| is the threshold; ties keep more,
19176        // which is the safe side.
19177        mag.clear();
19178        mag.extend(g.iter().map(|v| v.abs()));
19179        let (_, kth, _) = mag.select_nth_unstable_by(k - 1, |a, b| {
19180            b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
19181        });
19182        let thr = *kth;
19183        live.clear();
19184        live.extend((0..inter as u32).filter(|&n| g[n as usize].abs() >= thr));
19185        let mut out = vec![0.0f32; hidden];
19186        match pool {
19187            Some(p) if live.len() >= 64 => {
19188                let nw = p.n_workers() + 1;
19189                parts.clear();
19190                parts.resize(nw * hidden, 0.0);
19191                let ptr = SendMut(parts.as_mut_ptr());
19192                let n = live.len();
19193                let live_ref: &[u32] = live;
19194                let g_ref: &[f32] = g;
19195                p.run(&|w, workers| {
19196                    let chunk = n.div_ceil(workers);
19197                    let (s, e) = (w * chunk, ((w + 1) * chunk).min(n));
19198                    if s >= e {
19199                        return;
19200                    }
19201                    WORKER_SCRATCH.with(|ws| {
19202                        let mut ws = ws.borrow_mut();
19203                        let [scratch, acc] = &mut *ws;
19204                        scratch.resize(hidden.max(x.len()), 0.0);
19205                        acc.clear();
19206                        acc.resize(hidden, 0.0);
19207                        for (o, &nrm) in live_ref[s..e].iter().enumerate() {
19208                            // One neuron of runway: the next row's lines
19209                            // start moving while this one is multiplied.
19210                            if let Some(&nx) = live_ref[s..e].get(o + 1) {
19211                                d.up_proj.prefetch_row(nx as usize);
19212                                dt.prefetch_row(nx as usize);
19213                            }
19214                            let idx = nrm as usize;
19215                            let up = d.up_proj.row_dot(idx, x, scratch);
19216                            let a = g_ref[idx] * up;
19217                            if a != 0.0 {
19218                                dt.add_row_scaled(idx, a, acc, scratch);
19219                            }
19220                        }
19221                        for (j, v) in acc.iter().enumerate() {
19222                            unsafe { *ptr.at(w * hidden + j) = *v };
19223                        }
19224                    });
19225                });
19226                for w in 0..nw {
19227                    for (j, o) in out.iter_mut().enumerate() {
19228                        *o += parts[w * hidden + j];
19229                    }
19230                }
19231            }
19232            _ => {
19233                WORKER_SCRATCH.with(|ws| {
19234                    let mut ws = ws.borrow_mut();
19235                    let [scratch, _acc] = &mut *ws;
19236                    scratch.resize(hidden.max(x.len()), 0.0);
19237                    for &nrm in live.iter() {
19238                        let idx = nrm as usize;
19239                        let up = d.up_proj.row_dot(idx, x, scratch);
19240                        let a = g[idx] * up;
19241                        if a != 0.0 {
19242                            dt.add_row_scaled(idx, a, &mut out, scratch);
19243                        }
19244                    }
19245                });
19246            }
19247        }
19248        Some(out)
19249    })
19250}
19251
19252/// Caller-side scratch of the dynamic path — one allocation per thread,
19253/// not one per layer per token (that alone cost a third of the decode).
19254struct DynScratch {
19255    g: Vec<f32>,
19256    mag: Vec<f32>,
19257    live: Vec<u32>,
19258    parts: Vec<f32>,
19259}
19260
19261thread_local! {
19262    static DYN_SCRATCH: std::cell::RefCell<DynScratch> = const {
19263        std::cell::RefCell::new(DynScratch {
19264            g: Vec::new(),
19265            mag: Vec::new(),
19266            live: Vec::new(),
19267            parts: Vec::new(),
19268        })
19269    };
19270    /// Pool-worker scratch: the row buffer and this worker's partial sum.
19271    static WORKER_SCRATCH: std::cell::RefCell<[Vec<f32>; 2]> =
19272        const { std::cell::RefCell::new([Vec::new(), Vec::new()]) };
19273}
19274
19275/// `dense_ffn_cpu` with a per-visit mask landing on the activations —
19276/// the masked-inference fast path's decode arm. Full fused quant
19277/// compute, closed neurons zeroed before down: arithmetically the
19278/// pruned network, no dequant, no weight bytes touched.
19279fn dense_ffn_masked(d: &DenseFfn, x: &[f32], pool: Option<&Pool>, mask_row: &[u8]) -> Vec<f32> {
19280    let inter = d.gate_proj.rows();
19281    FFN_SCRATCH.with(|s| {
19282        let mut s = s.borrow_mut();
19283        let [g, u, ..] = &mut *s;
19284        g.resize(inter, 0.0);
19285        if d.act == Act::Silu && QTensor::matvec_silu_mul(&d.gate_proj, &d.up_proj, x, g, pool) {
19286            // g holds silu(gate)·up.
19287        } else {
19288            u.resize(inter, 0.0);
19289            QTensor::matvec_many([&d.gate_proj, &d.up_proj], x, [g, u], pool);
19290            for i in 0..inter {
19291                g[i] = d.act.combine(g[i], u[i]);
19292            }
19293        }
19294        zero_masked_cols(g, 1, inter, mask_row);
19295        let mut out = attention::take_buf(d.down_proj.rows());
19296        d.down_proj.matvec(g, &mut out, pool);
19297        out
19298    })
19299}
19300
19301/// Dense FFN as one GPU submission via the MoE block path (single
19302/// expert, weight 1.0): gate → silu·up → down chained in one command
19303/// buffer, intermediate activations device-resident. None → weights
19304/// not q8-mapped in the primary shard / over the VRAM budget / backend
19305/// refusal → honest CPU path.
19306fn dense_ffn_gpu(d: &DenseFfn, x: &[f32], _pool: Option<&Pool>) -> Option<Vec<f32>> {
19307    if d.gate_proj.has_prism_contract()
19308        || d.up_proj.has_prism_contract()
19309        || d.down_proj.has_prism_contract()
19310    {
19311        return None;
19312    }
19313    // The GPU block applies the standard graph activations plus the exact
19314    // MiniMax-M3 OAI contract; any other activation stays on the CPU.
19315    d.act.moe_job_graph_contract()?;
19316    // Threshold: tiny FFNs are not worth a submission (q1 excepted —
19317    // see the caller's gate).
19318    if d.gate_proj.rows() < crate::gpu::min_rows() && !d.gate_proj.is_q1() {
19319        return None;
19320    }
19321    let mut jobs: Vec<crate::gpu::MoeJob> = Vec::with_capacity(1);
19322    let mut model_ref = None;
19323    moe_push_job(d, x, 1.0, &mut jobs, &mut model_ref)?;
19324    let model = model_ref?;
19325    let hidden = jobs[0].down.1;
19326    let mut out = attention::take_buf(hidden);
19327    if crate::gpu::moe_block(&model, &jobs, &mut out) {
19328        Some(out)
19329    } else {
19330        let mut out = out;
19331        attention::recycle_buf(&mut out);
19332        None
19333    }
19334}
19335
19336/// q8-mapped primary-shard tensor parts for a GPU job: q8_2f carries
19337/// its column field, q8_row runs with empty col slices (the backend
19338/// skips the multiply). Shared by the MoE block and the dense-FFN
19339/// single-job path.
19340#[allow(clippy::type_complexity)]
19341#[allow(clippy::type_complexity)]
19342pub(crate) fn moe_parts(
19343    t: &QTensor,
19344) -> Option<(
19345    &std::sync::Arc<cortiq_core::CmfModel>,
19346    usize,
19347    usize,
19348    usize,
19349    &[f32],
19350    &[f32],
19351    bool,
19352    bool,
19353    bool,
19354)> {
19355    match t {
19356        QTensor::Mapped {
19357            model,
19358            idx,
19359            dtype: dt @ (cortiq_core::TensorDtype::Q8_2f | cortiq_core::TensorDtype::Q8Row),
19360            rows,
19361            cols,
19362            row_scale,
19363            col_field,
19364            ..
19365        } if (*dt == cortiq_core::TensorDtype::Q8Row) || !col_field.is_empty() => Some((
19366            model, *idx, *rows, *cols, row_scale, col_field, false, false, false,
19367        )),
19368        // q1: tile-embedded scales — empty rs/col slices, raw xs.
19369        QTensor::Mapped {
19370            model,
19371            idx,
19372            dtype: cortiq_core::TensorDtype::Q1,
19373            rows,
19374            cols,
19375            ..
19376        } => Some((
19377            model,
19378            *idx,
19379            *rows,
19380            *cols,
19381            &[][..],
19382            &[][..],
19383            true,
19384            false,
19385            false,
19386        )),
19387        // q4_tiled: 18-byte tiles with embedded f16 scales — raw xs.
19388        QTensor::Mapped {
19389            model,
19390            idx,
19391            dtype: cortiq_core::TensorDtype::Q4Tiled,
19392            rows,
19393            cols,
19394            ..
19395        } => Some((
19396            model,
19397            *idx,
19398            *rows,
19399            *cols,
19400            &[][..],
19401            &[][..],
19402            false,
19403            true,
19404            false,
19405        )),
19406        // q4tp: same raw-xs contract, different stride and scale plane.
19407        QTensor::Mapped {
19408            model,
19409            idx,
19410            dtype: cortiq_core::TensorDtype::Q4TiledP,
19411            rows,
19412            cols,
19413            ..
19414        } => Some((
19415            model,
19416            *idx,
19417            *rows,
19418            *cols,
19419            &[][..],
19420            &[][..],
19421            false,
19422            true,
19423            false,
19424        )),
19425        // q2tp: the 2-bit expert plane of the mixed profile — q4 family
19426        // for stride bookkeeping, flagged q2 so the trio validation can
19427        // demand a q4tp down.
19428        QTensor::Mapped {
19429            model,
19430            idx,
19431            dtype: cortiq_core::TensorDtype::Q2TiledP,
19432            rows,
19433            cols,
19434            ..
19435        } => Some((
19436            model,
19437            *idx,
19438            *rows,
19439            *cols,
19440            &[][..],
19441            &[][..],
19442            false,
19443            true,
19444            true,
19445        )),
19446        _ => None,
19447    }
19448}
19449
19450/// The routed experts of a MoE layer as the Metal chunk prefill takes
19451/// them: f32 router rows and every expert's q4tp (gate, up, down) tensor
19452/// indices, uniform SiLU shapes. Only the plain routed form — no shared
19453/// expert, no per-expert scale, no resonance or τ router, no router input
19454/// norm; the batched host walk keeps the rest. The routing itself stays the
19455/// host's (`moe_route`), so mask and selection bias need nothing here.
19456#[cfg(target_os = "macos")]
19457#[allow(clippy::type_complexity)]
19458fn chunk_moe_parts(
19459    m: &MoeFfn,
19460    hidden: usize,
19461) -> Option<(&[f32], Vec<(usize, usize, usize)>, bool)> {
19462    if m.shared.is_some()
19463        || m.per_expert_scale.is_some()
19464        || m.resonance.is_some()
19465        || m.route_tau.is_some()
19466        || m.router_input_norm
19467        || m.experts.is_empty()
19468        || m.top_k == 0
19469        || std::env::var("CMF_RMS_TRACE").is_ok()
19470        || std::env::var("CMF_ACT_DUMP").is_ok()
19471        || std::env::var("CMF_METAL_MOE_PREFILL").as_deref() == Ok("0")
19472    {
19473        return None;
19474    }
19475    let (rf, rr, rc) = m.router.f32_parts()?;
19476    if rr != m.experts.len() || rc != hidden {
19477        return None;
19478    }
19479    let inter = m.experts[0].gate_proj.rows();
19480    // All-q8_2f experts (Mellum2.1 q8_2f) ride the `moe_q8` GEMMs;
19481    // `CMF_METAL_MOE_Q8=0` keeps them on the host walk.
19482    let q8 = crate::gpu_metal::moe_q8::enabled() && m.experts[0].gate_proj.q8_2f_parts().is_some();
19483    let experts = m
19484        .experts
19485        .iter()
19486        .map(|e| {
19487            if e.act != Act::Silu
19488                || !e.segs.is_empty()
19489                || e.gate_proj.rows() != inter
19490                || e.up_proj.rows() != inter
19491                || e.down_proj.cols() != inter
19492                || e.gate_proj.cols() != hidden
19493                || e.down_proj.rows() != hidden
19494            {
19495                return None;
19496            }
19497            if q8 {
19498                let q8i = |t: &QTensor| t.q8_2f_parts().map(|p| p.0);
19499                return Some((q8i(&e.gate_proj)?, q8i(&e.up_proj)?, q8i(&e.down_proj)?));
19500            }
19501            Some((
19502                e.gate_proj.mapped_q4tp()?.1,
19503                e.up_proj.mapped_q4tp()?.1,
19504                e.down_proj.mapped_q4tp()?.1,
19505            ))
19506        })
19507        .collect::<Option<Vec<_>>>()?;
19508    Some((rf, experts, q8))
19509}
19510
19511/// Map a MoE onto the Metal token graph's contract: f32 router, a
19512/// shared expert (gated — Qwen — or ungated at weight 1 — DeepSeek-V3 /
19513/// HunYuan hy_v3), softmax or sigmoid scores with an optional selection
19514/// bias and routed scale, experts uniformly q4tp (or the mixed profile:
19515/// q2tp gate/up over a q4tp down). τ routers, masks, per-expert scales
19516/// and Gemma's router-input norm refuse here — those semantics stay on
19517/// the CPU path.
19518/// Map Flint's released ragged MoE into the native page graph.  This stays
19519/// separate from `metal_moe_graph_parts`: its six routed slots are Q2TP and
19520/// 512-wide, while its ungated shared SwiGLU is Q4TP and 1024-wide.  Feeding
19521/// the shared tuple into the uniform jobs descriptor would make the shader
19522/// use the routed stride on a different payload.
19523#[cfg(target_os = "macos")]
19524fn metal_flint_moe_graph_parts(
19525    m: &MoeFfn,
19526    hidden: usize,
19527    scratch_key: usize,
19528) -> Option<crate::gpu::GpuFlintMoe<'_>> {
19529    use std::sync::Arc;
19530
19531    const HIDDEN: usize = 2_048;
19532    const ROUTED_INTER: usize = 512;
19533    const SHARED_INTER: usize = 1_024;
19534    const EXPERTS: usize = 256;
19535    const TOP_K: usize = 6;
19536
19537    if hidden != HIDDEN || !strict_flint_metal_pager_candidate(m) {
19538        return None;
19539    }
19540    let routed0 = m.experts.first()?;
19541    let (model, _) = routed0.gate_proj.mapped_q2tp()?;
19542    let (router, router_rows, router_cols) = m.router.f32_parts()?;
19543    if router_rows != EXPERTS || router_cols != HIDDEN {
19544        return None;
19545    }
19546    if m.expert_bias.as_ref().is_some_and(|b| b.len() != EXPERTS) {
19547        return None;
19548    }
19549    let same_q2 = |t: &QTensor| -> Option<usize> {
19550        let (owner, idx) = t.mapped_q2tp()?;
19551        Arc::ptr_eq(&owner, &model).then_some(idx)
19552    };
19553    let same_q4 = |t: &QTensor| -> Option<usize> {
19554        let (owner, idx) = t.mapped_q4tp()?;
19555        Arc::ptr_eq(&owner, &model).then_some(idx)
19556    };
19557    let routed = |e: &DenseFfn| -> Option<(usize, usize, usize)> {
19558        if e.act != Act::Silu
19559            || !e.segs.is_empty()
19560            || e.gate_proj.rows() != ROUTED_INTER
19561            || e.gate_proj.cols() != HIDDEN
19562            || e.up_proj.rows() != ROUTED_INTER
19563            || e.up_proj.cols() != HIDDEN
19564            || e.down_proj.rows() != HIDDEN
19565            || e.down_proj.cols() != ROUTED_INTER
19566        {
19567            return None;
19568        }
19569        Some((
19570            same_q2(&e.gate_proj)?,
19571            same_q2(&e.up_proj)?,
19572            same_q4(&e.down_proj)?,
19573        ))
19574    };
19575    let shared = |e: &DenseFfn| -> Option<(usize, usize, usize)> {
19576        if e.act != Act::Silu
19577            || !e.segs.is_empty()
19578            || e.gate_proj.rows() != SHARED_INTER
19579            || e.gate_proj.cols() != HIDDEN
19580            || e.up_proj.rows() != SHARED_INTER
19581            || e.up_proj.cols() != HIDDEN
19582            || e.down_proj.rows() != HIDDEN
19583            || e.down_proj.cols() != SHARED_INTER
19584        {
19585            return None;
19586        }
19587        Some((
19588            same_q4(&e.gate_proj)?,
19589            same_q4(&e.up_proj)?,
19590            same_q4(&e.down_proj)?,
19591        ))
19592    };
19593    let experts = m.experts.iter().map(routed).collect::<Option<Vec<_>>>()?;
19594    if experts.len() != EXPERTS {
19595        return None;
19596    }
19597    let (shared_ffn, shared_gate) = m.shared.as_ref()?;
19598    if shared_gate.is_some() {
19599        return None;
19600    }
19601    Some(crate::gpu::GpuFlintMoe {
19602        router,
19603        bias: m.expert_bias.as_deref(),
19604        experts,
19605        scratch_key,
19606        shared: shared(shared_ffn)?,
19607        top_k: m.top_k,
19608        norm_topk: m.norm_topk_prob,
19609        route_scale: m.routed_scaling,
19610        sigmoid: m.router_sigmoid,
19611        sigmoid_denom_eps: m.sigmoid_denom_eps,
19612    })
19613}
19614
19615#[cfg(target_os = "macos")]
19616fn metal_moe_graph_parts(m: &MoeFfn, hidden: usize) -> Option<crate::gpu::GpuMoe<'_>> {
19617    if m.router_input_norm
19618        || m.route_tau.is_some()
19619        || m.mask.is_some()
19620        || m.per_expert_scale.is_some()
19621        || m.experts.is_empty()
19622        || m.top_k == 0
19623        || m.resonance.is_some()
19624    {
19625        return None;
19626    }
19627    // Without a shared expert the select kernel fills the k routed jobs
19628    // only (flag 32). Measured on Mellum2.1's softmax router; the sigmoid /
19629    // biased routers without one (LFM2-MoE) keep the CPU path until they
19630    // are measured too.
19631    let (sh, sg) = match &m.shared {
19632        Some((sh, sg)) => (Some(sh), sg.as_ref()),
19633        None if !m.router_sigmoid && m.expert_bias.is_none() => (None, None),
19634        None => return None,
19635    };
19636    let (rf, rr, rc) = m.router.f32_parts()?;
19637    if rr != m.experts.len() || rc != hidden {
19638        return None;
19639    }
19640    let shared_gated = sg.is_some();
19641    let sf = match sg {
19642        Some(sg) => {
19643            let (sf, sr, sc) = sg.f32_parts()?;
19644            if sr * sc != hidden {
19645                return None;
19646            }
19647            sf
19648        }
19649        // Ungated: the router's first row stands in for the gate matvec
19650        // (its logit is never read — the kernel pins weight 1).
19651        None => &rf[..hidden],
19652    };
19653    if let Some(b) = &m.expert_bias {
19654        if b.len() != m.experts.len() {
19655            return None;
19656        }
19657    }
19658    let inter = m.experts[0].gate_proj.rows();
19659    // The first expert's gate decides the profile; every trio (shared
19660    // included) must agree — the jobs ladder flips ONE kernel for all.
19661    let gu_q2 = m.experts[0].gate_proj.mapped_q2tp().is_some();
19662    // All-q8_2f routed experts (Mellum2.1 q8_2f: no shared expert, the
19663    // contract they were measured on) take the `moe_q8` kernels;
19664    // `CMF_METAL_MOE_Q8=0` keeps them off the graph (per-op path).
19665    let q8 = crate::gpu_metal::moe_q8::enabled()
19666        && m.shared.is_none()
19667        && m.experts[0].gate_proj.q8_2f_parts().is_some();
19668    let trio = |e: &DenseFfn| -> Option<(usize, usize, usize)> {
19669        if e.act != Act::Silu
19670            || e.gate_proj.rows() != inter
19671            || e.gate_proj.cols() != hidden
19672            || e.up_proj.rows() != inter
19673            || e.up_proj.cols() != hidden
19674            || e.down_proj.rows() != hidden
19675            || e.down_proj.cols() != inter
19676        {
19677            return None;
19678        }
19679        if q8 {
19680            let q8i = |t: &QTensor| t.q8_2f_parts().map(|p| p.0);
19681            return Some((q8i(&e.gate_proj)?, q8i(&e.up_proj)?, q8i(&e.down_proj)?));
19682        }
19683        let pick = |t: &QTensor| -> Option<usize> {
19684            if gu_q2 {
19685                t.mapped_q2tp().map(|(_, i)| i)
19686            } else {
19687                t.mapped_q4tp().map(|(_, i)| i)
19688            }
19689        };
19690        Some((
19691            pick(&e.gate_proj)?,
19692            pick(&e.up_proj)?,
19693            e.down_proj.mapped_q4tp().map(|(_, i)| i)?,
19694        ))
19695    };
19696    let experts = m.experts.iter().map(trio).collect::<Option<Vec<_>>>()?;
19697    let shared = match sh {
19698        Some(sh) => Some(trio(sh)?),
19699        None => None,
19700    };
19701    Some(crate::gpu::GpuMoe {
19702        router: rf,
19703        sgate: sf,
19704        experts,
19705        shared,
19706        n_exp: m.experts.len(),
19707        top_k: m.top_k,
19708        inter,
19709        norm_topk: m.norm_topk_prob,
19710        route_scale: m.routed_scaling,
19711        gu_q2,
19712        q8,
19713        sigmoid: m.router_sigmoid,
19714        sigmoid_denom_eps: m.sigmoid_denom_eps,
19715        bias: m.expert_bias.as_deref(),
19716        shared_gated,
19717    })
19718}
19719
19720/// `CMF_FORCE_IDS=<file>` (diagnostics): decode step n commits the n-th
19721/// whitespace-separated token id of the file instead of sampling, while the
19722/// logits are still computed (and dumped by `CMF_LOGIT_DUMP_ALL`) — one
19723/// backend teacher-forced along another's greedy sequence, so top-1
19724/// agreement can be counted past a near-tie divergence.
19725fn forced_ids_at(step: usize) -> Option<u32> {
19726    static IDS: std::sync::OnceLock<Vec<u32>> = std::sync::OnceLock::new();
19727    IDS.get_or_init(|| {
19728        std::env::var("CMF_FORCE_IDS")
19729            .ok()
19730            .and_then(|p| std::fs::read_to_string(p).ok())
19731            .map(|s| {
19732                s.split_whitespace()
19733                    .filter_map(|t| t.parse().ok())
19734                    .collect()
19735            })
19736            .unwrap_or_default()
19737    })
19738    .get(step)
19739    .copied()
19740}
19741
19742/// Build one gate/up/down GPU job from three tensors. `moe_push_job` is the
19743/// DenseFfn-shaped caller; architectures that keep their experts in their own
19744/// structs (DeepSeek-V4) come here directly.
19745pub(crate) fn moe_push_job_parts<'a>(
19746    gate: &'a QTensor,
19747    up: &'a QTensor,
19748    down: &'a QTensor,
19749    x: &[f32],
19750    w: f32,
19751    swiglu_limit: f32,
19752    jobs: &mut Vec<crate::gpu::MoeJob<'a>>,
19753    model_ref: &mut Option<std::sync::Arc<cortiq_core::CmfModel>>,
19754) -> Option<()> {
19755    use crate::qtensor::prescale;
19756    let (gm, gi, gr, gc, grs, gcf, gq1, gq4, gq2) = moe_parts(gate)?;
19757    let (_, ui, ur, uc, urs, ucf, uq1, uq4, uq2) = moe_parts(up)?;
19758    let (_, di, dr, dc, drs, dcf, dq1, dq4, dq2) = moe_parts(down)?;
19759    if gq1 != uq1 || uq1 != dq1 || gq4 != uq4 || uq4 != dq4 || gq2 != uq2 {
19760        return None; // mixed-dtype trio — honest CPU path
19761    }
19762    // The 2-bit profile is gate/up q2tp over a PLAIN q4tp down; any other
19763    // 2-bit arrangement stays on the CPU.
19764    if gq2 && (dq2 || !dq4 || down.mapped_q4tp().is_none()) {
19765        return None;
19766    }
19767    if !gq2 && dq2 {
19768        return None;
19769    }
19770    model_ref.get_or_insert_with(|| gm.clone());
19771    let dt = |cf: &[f32]| {
19772        if cf.is_empty() {
19773            cortiq_core::TensorDtype::Q8Row
19774        } else {
19775            cortiq_core::TensorDtype::Q8_2f
19776        }
19777    };
19778    jobs.push(crate::gpu::MoeJob {
19779        gate: (gi, gr, gc, grs),
19780        up: (ui, ur, uc, urs),
19781        down: (di, dr, dc, drs),
19782        xs_gate: prescale(x, gcf, dt(gcf)).into_owned(),
19783        xs_up: prescale(x, ucf, dt(ucf)).into_owned(),
19784        down_col: dcf,
19785        w,
19786        q1: gq1,
19787        q4t: gq4 && !gq2 && gate.mapped_q4tp().is_none(),
19788        q4tp: gq4 && (gq2 || gate.mapped_q4tp().is_some()),
19789        gu_q2: gq2,
19790        swiglu_limit,
19791        act: 0,
19792    });
19793    Some(())
19794}
19795
19796/// Build one gate/up/down GPU job (see `moe_parts`).
19797fn moe_push_job<'a>(
19798    d: &'a DenseFfn,
19799    x: &[f32],
19800    w: f32,
19801    jobs: &mut Vec<crate::gpu::MoeJob<'a>>,
19802    model_ref: &mut Option<std::sync::Arc<cortiq_core::CmfModel>>,
19803) -> Option<()> {
19804    use crate::qtensor::prescale;
19805    // The block's act(gate)·up pass takes an exact device contract.  For
19806    // ordinary SiLU/GELU this is a zero clamp; MiniMax M3 contributes its
19807    // dedicated OAI marker and frozen 7.0 source limit.  Anything without a
19808    // device contract stays on the CPU.
19809    let (graph_act, swiglu_limit) = d.act.moe_job_graph_contract()?;
19810    let act = graph_act.code();
19811    let (gm, gi, gr, gc, grs, gcf, gq1, gq4, gq2) = moe_parts(&d.gate_proj)?;
19812    let (_, ui, ur, uc, urs, ucf, uq1, uq4, uq2) = moe_parts(&d.up_proj)?;
19813    let (_, di, dr, dc, drs, dcf, dq1, dq4, dq2) = moe_parts(&d.down_proj)?;
19814    if gq1 != uq1 || uq1 != dq1 || gq4 != uq4 || uq4 != dq4 || gq2 != uq2 {
19815        return None; // mixed-dtype trio — honest CPU path
19816    }
19817    if gq2 && (dq2 || !dq4 || d.down_proj.mapped_q4tp().is_none()) {
19818        return None;
19819    }
19820    if !gq2 && dq2 {
19821        return None;
19822    }
19823    model_ref.get_or_insert_with(|| gm.clone());
19824    let gdt = if gcf.is_empty() {
19825        cortiq_core::TensorDtype::Q8Row
19826    } else {
19827        cortiq_core::TensorDtype::Q8_2f
19828    };
19829    let udt = if ucf.is_empty() {
19830        cortiq_core::TensorDtype::Q8Row
19831    } else {
19832        cortiq_core::TensorDtype::Q8_2f
19833    };
19834    jobs.push(crate::gpu::MoeJob {
19835        gate: (gi, gr, gc, grs),
19836        up: (ui, ur, uc, urs),
19837        down: (di, dr, dc, drs),
19838        xs_gate: prescale(x, gcf, gdt).into_owned(),
19839        xs_up: prescale(x, ucf, udt).into_owned(),
19840        down_col: dcf,
19841        w,
19842        q1: gq1,
19843        q4t: gq4 && !gq2 && d.gate_proj.mapped_q4tp().is_none(),
19844        q4tp: gq4 && (gq2 || d.gate_proj.mapped_q4tp().is_some()),
19845        gu_q2: gq2,
19846        swiglu_limit,
19847        act,
19848    });
19849    Some(())
19850}
19851
19852/// Sparse dense-FFN directly on QUANTIZED weights (mask × mmap): reads
19853/// ONLY the active neurons' gate/up rows and down columns from the mmap
19854/// — no full-matrix dequant, no f32 model copy. This is what lets a
19855/// masked big model run at quantized RSS (the historical mask path
19856/// forced the whole model to f32). Semantics identical to the f32
19857/// sparse path within quant tolerance.
19858fn sparse_ffn_quant(
19859    d: &DenseFfn,
19860    x: &[f32],
19861    active: &[u16],
19862    hidden: usize,
19863    pool: Option<&Pool>,
19864) -> Vec<f32> {
19865    let n = active.len();
19866    let inter = d.gate_proj.rows();
19867    let mut act = vec![0.0f32; n];
19868    // Scratch is needed if EITHER projection is group-packed (q4/vbit);
19869    // gate/up normally share a dtype but sizing on both is robust.
19870    let need_scratch = !(d.gate_proj.sparse_col_ok() && d.up_proj.sparse_col_ok());
19871    let compute = |ai: usize| -> f32 {
19872        let idx = active[ai] as usize;
19873        if idx >= inter {
19874            return 0.0; // defensive parity with the f32 sparse path
19875        }
19876        let mut s = if need_scratch {
19877            vec![0.0f32; hidden]
19878        } else {
19879            Vec::new()
19880        };
19881        let gate = d.gate_proj.row_dot(idx, x, &mut s);
19882        let up = d.up_proj.row_dot(idx, x, &mut s);
19883        d.act.combine(gate, up)
19884    };
19885    match pool {
19886        Some(p) if n >= 256 => {
19887            let ptr = SendMut(act.as_mut_ptr());
19888            p.run(&|widx, nw| {
19889                let chunk = n.div_ceil(nw);
19890                let (s, e) = (widx * chunk, ((widx + 1) * chunk).min(n));
19891                for ai in s..e {
19892                    unsafe { *ptr.at(ai) = compute(ai) };
19893                }
19894            });
19895        }
19896        _ => {
19897            for (ai, a) in act.iter_mut().enumerate() {
19898                *a = compute(ai);
19899            }
19900        }
19901    }
19902    // Scatter through active down columns (reads only those columns).
19903    let mut out = vec![0.0f32; hidden];
19904    for (ai, &idx) in active.iter().enumerate() {
19905        let w = act[ai];
19906        if w.abs() >= 1e-12 && (idx as usize) < inter {
19907            d.down_proj.add_col_scaled(idx as usize, w, &mut out);
19908        }
19909    }
19910    out
19911}
19912
19913/// Test-only re-export of the private sparse-quant FFN (mask × mmap gate).
19914#[doc(hidden)]
19915pub fn sparse_ffn_quant_for_test(
19916    d: &DenseFfn,
19917    x: &[f32],
19918    active: &[u16],
19919    hidden: usize,
19920) -> Vec<f32> {
19921    sparse_ffn_quant(d, x, active, hidden, None)
19922}
19923
19924/// Dequantize a DenseFfn's three matrices to f32 (transient; only the
19925/// q4/vbit-masked fallback uses it — the memory-lean path is
19926/// sparse_ffn_quant). Reuses row_f32 row-by-row.
19927fn dequant_dense_f32(d: &DenseFfn) -> (Vec<f32>, Vec<f32>, Vec<f32>) {
19928    let deq = |t: &QTensor| -> Vec<f32> {
19929        let (rows, cols) = (t.rows(), t.cols());
19930        let mut out = vec![0.0f32; rows * cols];
19931        for r in 0..rows {
19932            t.row_f32(r, &mut out[r * cols..(r + 1) * cols]);
19933        }
19934        out
19935    };
19936    (deq(&d.gate_proj), deq(&d.up_proj), deq(&d.down_proj))
19937}
19938
19939/// Pointer wrapper for the worker-pool scatter (same pattern as qtensor).
19940struct SendMut(*mut f32);
19941unsafe impl Send for SendMut {}
19942unsafe impl Sync for SendMut {}
19943impl SendMut {
19944    #[inline]
19945    // Deliberate unsynchronized scatter: pool workers write disjoint indices
19946    // in parallel, so returning `&mut` from `&self` is intentional here.
19947    #[allow(clippy::mut_from_ref)]
19948    unsafe fn at(&self, i: usize) -> &mut f32 {
19949        unsafe { &mut *self.0.add(i) }
19950    }
19951}
19952
19953/// Router → (selected experts in torch.topk order, per-expert score
19954/// vector, normalizer). The final weight of expert `e` is `p[e] / wsum`.
19955///
19956/// Two regimes share this. Qwen: softmax over ALL experts, top-k of the
19957/// probabilities, optional renorm — `router_sigmoid=false`, no bias,
19958/// scale 1 → bit-identical to the historical path. LFM2-MoE /
19959/// DeepSeek-V3 `noaux_tc`: per-expert sigmoid scores, an optional
19960/// selection bias (top-k CHOICE only; weights stay unbiased), an
19961/// architecture-specified renorm floor and a routed scale.  The ordinary
19962/// loader contract is `1e-6`; Flint and MiniMax M3.1 preserve their
19963/// reference runtime's selected-score `sum + 1e-20`.
19964pub(crate) fn moe_route(
19965    logits: &[f32],
19966    m: &MoeFfn,
19967    allowed: Option<&[bool]>,
19968) -> (Vec<usize>, Vec<f32>, f32) {
19969    moe_route_with_eps(logits, m, allowed, m.sigmoid_denom_eps)
19970}
19971
19972/// Router implementation with an explicit sigmoid renormalization floor.
19973///
19974/// Flint and MiniMax M3.1 reference runtimes compute
19975/// `sum(selected_scores) + 1e-20` in FP32. Using the generic 1e-6 floor is
19976/// not a harmless tolerance difference when all logits are very negative: it
19977/// collapses the routed branch toward zero instead of normalizing the selected
19978/// experts. Keeping the epsilon parameter here avoids changing the established
19979/// Qwen/LFM2 contract while allowing each architecture to preserve its own
19980/// numerical semantics.
19981pub(crate) fn moe_route_with_eps(
19982    logits: &[f32],
19983    m: &MoeFfn,
19984    allowed: Option<&[bool]>,
19985    sigmoid_denom_eps: f32,
19986) -> (Vec<usize>, Vec<f32>, f32) {
19987    let ne = logits.len();
19988    // Expert restriction: the static env mask (CMF_MOE_MASK) AND the
19989    // active task mask's expert fields (spec §5) both narrow the
19990    // candidate set; selection happens over the admitted experts only.
19991    // With norm_topk the kept weights renormalize below; without it
19992    // the excluded mass is honestly dropped.
19993    let admit = |e: usize| {
19994        m.mask.as_ref().is_none_or(|mk| mk[e])
19995            && allowed.is_none_or(|a| a.get(e).copied().unwrap_or(false))
19996    };
19997    // The resonance router (spec §9.5.1) selects by the RAW score: the
19998    // trainer (`resonance_winner`) and the resident graph
19999    // (`embryo_core_route_pick`) take the first maximum of the scores
20000    // and run the winner with weight 1.0. Selecting through the softmax
20001    // instead is not the same decision: `exp(l − max)` rounds two scores
20002    // closer than 2^-25 (possible below |score| 0.25) to the same 1.0, and
20003    // the lower index would take a token whose score is strictly smaller
20004    // — the trainer's trace and the graph would disagree with this path.
20005    // `−∞` (outside the shell) never wins; with no finite admitted expert
20006    // the generic path below degrades to uniform. The winner's
20007    // probability is 1.0 by construction (a one-hot `p`), so its
20008    // renormalized weight is `routed_scaling` on both norm_topk settings.
20009    if m.resonance.is_some() && m.top_k == 1 {
20010        let mut best: Option<usize> = None;
20011        for e in (0..ne).filter(|&e| admit(e)) {
20012            let l = logits[e];
20013            if l == f32::NEG_INFINITY || l.is_nan() {
20014                continue;
20015            }
20016            if best.is_none_or(|b| l > logits[b]) {
20017                best = Some(e);
20018            }
20019        }
20020        if let Some(b) = best {
20021            let mut p = vec![0.0f32; ne];
20022            p[b] = 1.0;
20023            return (vec![b], p, 1.0 / m.routed_scaling);
20024        }
20025    }
20026    // A `−∞` logit (a grown expert outside its shell, `Resonance::scores`)
20027    // takes probability 0 on both paths: sigmoid(−∞) = 0, exp(−∞ − max) = 0
20028    // — top-1 is the best FINITE expert, its renormalized weight exactly
20029    // 1.0. Every expert at −∞ cannot happen (trunk experts have no shell);
20030    // should it, the softmax would be NaN, so it degrades to uniform.
20031    let p: Vec<f32> = if m.router_sigmoid {
20032        logits.iter().map(|&l| 1.0 / (1.0 + (-l).exp())).collect()
20033    } else {
20034        let mx = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
20035        if mx == f32::NEG_INFINITY {
20036            vec![1.0 / ne.max(1) as f32; ne]
20037        } else {
20038            let mut e: Vec<f32> = logits.iter().map(|&l| (l - mx).exp()).collect();
20039            let s: f32 = e.iter().sum();
20040            for v in &mut e {
20041                *v /= s;
20042            }
20043            e
20044        }
20045    };
20046    let mut idx: Vec<usize> = (0..ne).filter(|&e| admit(e)).collect();
20047    // Descending by selection score, lower index wins ties (torch.topk).
20048    match &m.expert_bias {
20049        Some(b) => idx.sort_unstable_by(|&x, &y| {
20050            (p[y] + b[y])
20051                .partial_cmp(&(p[x] + b[x]))
20052                .unwrap()
20053                .then(x.cmp(&y))
20054        }),
20055        None => idx.sort_unstable_by(|&x, &y| p[y].partial_cmp(&p[x]).unwrap().then(x.cmp(&y))),
20056    }
20057    idx.truncate(m.top_k);
20058    // Adaptive τ-routing: trim the tail experts once the kept mass is
20059    // enough. wsum below renormalizes over the KEPT set, so the output
20060    // stays a proper weighted average.
20061    if let Some(tau) = m.route_tau {
20062        let total: f32 = idx.iter().map(|&e| p[e]).sum();
20063        if total > 0.0 {
20064            let mut acc = 0.0f32;
20065            let mut keep = idx.len();
20066            for (i, &e) in idx.iter().enumerate() {
20067                acc += p[e];
20068                if acc >= tau * total {
20069                    keep = i + 1;
20070                    break;
20071                }
20072            }
20073            idx.truncate(keep);
20074        }
20075    }
20076    let wsum: f32 = if m.norm_topk_prob {
20077        let s: f32 = idx.iter().map(|&e| p[e]).sum();
20078        // Sigmoid routers use their architecture's reference floor; the
20079        // softmax path's probs already sum near 1, so it stays exactly as
20080        // before.
20081        (if m.router_sigmoid {
20082            s + sigmoid_denom_eps
20083        } else {
20084            s
20085        }) / m.routed_scaling
20086    } else {
20087        1.0 / m.routed_scaling
20088    };
20089    (idx, p, wsum)
20090}
20091
20092/// See the call site: one `layer:e1,e2,…` line per routed token.
20093fn moe_trace(idx: &[usize]) {
20094    moe_trace_at(crate::gpu::cur_layer() as i32, idx)
20095}
20096
20097/// The same, for callers that know their layer (DSV4 owns its layers and
20098/// never sets the pipeline's current-layer marker).
20099pub(crate) fn moe_trace_at(li: i32, idx: &[usize]) {
20100    use std::io::Write;
20101    static F: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
20102        std::sync::OnceLock::new();
20103    let Some(f) = F.get_or_init(|| {
20104        let p = std::env::var("CMF_MOE_TRACE").ok()?;
20105        Some(std::sync::Mutex::new(
20106            std::fs::OpenOptions::new()
20107                .create(true)
20108                .append(true)
20109                .open(p)
20110                .ok()?,
20111        ))
20112    }) else {
20113        return;
20114    };
20115    let ids: Vec<String> = idx.iter().map(|e| e.to_string()).collect();
20116    let _ = writeln!(f.lock().unwrap(), "{li}:{}", ids.join(","));
20117}
20118
20119/// MoE FFN: router → top-k experts (see `moe_route`). Only selected
20120/// experts' pages are touched in mmap.
20121pub(crate) fn moe_ffn(
20122    m: &MoeFfn,
20123    x: &[f32],
20124    pool: Option<&Pool>,
20125    allowed: Option<&[bool]>,
20126) -> Vec<f32> {
20127    let r = moe_ffn_route(m, x, pool, allowed);
20128    moe_ffn_experts(m, x, &r, pool)
20129}
20130
20131/// One token's host route through a MoE layer: the chosen experts in
20132/// selection order, the per-expert scores and the normalizer (see
20133/// `moe_route`), plus the raw router logits.
20134pub(crate) struct MoeRoute {
20135    pub idx: Vec<usize>,
20136    pub p: Vec<f32>,
20137    pub wsum: f32,
20138    pub logits: Vec<f32>,
20139}
20140
20141/// The routing half of `moe_ffn`, shared by every executor of the chosen
20142/// experts (the host/per-op path below and the MiMo dynamic device cache,
20143/// `crate::mimo_moe`): activation accounting, router logits, `moe_route`,
20144/// the selection statistics and the `CMF_MOE_TRACE` line — so switching
20145/// executors can never change which experts a token gets.
20146pub(crate) fn moe_ffn_route(
20147    m: &MoeFfn,
20148    x: &[f32],
20149    pool: Option<&Pool>,
20150    allowed: Option<&[bool]>,
20151) -> MoeRoute {
20152    accumulate_act(m, x, 1);
20153    let ne = m.experts.len();
20154    let mut logits = vec![0.0f32; ne];
20155    match &m.resonance {
20156        Some(r) => r.scores(x, &mut logits),
20157        None => m.router.matvec(x, &mut logits, pool),
20158    }
20159    let (idx, p, wsum) = moe_route(&logits, m, allowed);
20160    {
20161        let mut st = m.stats.borrow_mut();
20162        if st.len() < ne {
20163            st.resize(ne, 0);
20164        }
20165        for &e in &idx {
20166            st[e] += 1;
20167        }
20168    }
20169    // `CMF_MOE_TRACE=<file>`: append one line per (layer, token) with the
20170    // selected expert ids. The cumulative `stats` above answer "which
20171    // experts are popular"; a residency design needs the question they
20172    // cannot answer — whether CONSECUTIVE tokens reuse experts (the
20173    // temporal locality an LRU cache lives on, FreeToken §4).
20174    moe_trace(&idx);
20175    MoeRoute {
20176        idx,
20177        p,
20178        wsum,
20179        logits,
20180    }
20181}
20182
20183/// Flint's released mixed MoE profile has a native-Metal selected-expert
20184/// pager with a different numerical contract from the generic CPU probe:
20185/// the pager keeps activations in f32, whereas the fast host arm normally
20186/// uses its A8W8 activation path.  Timing those two approximations against
20187/// one another can make the probe reject the exact pager even when it is the
20188/// faster exact-f32 implementation.  Keep this gate deliberately narrower
20189/// than the pager itself; the pager revalidates every selected tuple before
20190/// it binds a no-copy view and an honest refusal still takes the CPU path.
20191#[cfg(target_os = "macos")]
20192fn strict_flint_metal_pager_candidate(m: &MoeFfn) -> bool {
20193    const HIDDEN: usize = 2_048;
20194    const ROUTED_INTER: usize = 512;
20195    const SHARED_INTER: usize = 1_024;
20196    const EXPERTS: usize = 256;
20197    const TOP_K: usize = 6;
20198
20199    let Some(routed) = m.experts.first() else {
20200        return false;
20201    };
20202    let Some((model, _)) = routed.gate_proj.mapped_q2tp() else {
20203        return false;
20204    };
20205    let Some((shared, shared_gate)) = &m.shared else {
20206        return false;
20207    };
20208    if shared_gate.is_some()
20209        || model.header.arch.arch_name != "flint"
20210        || model.header.arch.prism_hadamard.is_some()
20211        || model.header.arch.hidden_size != HIDDEN
20212        || m.experts.len() != EXPERTS
20213        || m.top_k != TOP_K
20214        || !m.router_sigmoid
20215        || !m.norm_topk_prob
20216        || m.sigmoid_denom_eps.to_bits() != (1e-20f32).to_bits()
20217        || m.routed_scaling.to_bits() != 1.0f32.to_bits()
20218        || m.route_tau.is_some()
20219        || m.mask.is_some()
20220        || m.per_expert_scale.is_some()
20221        || m.router_input_norm
20222        || m.resonance.is_some()
20223        || !m.grown.is_empty()
20224    {
20225        return false;
20226    }
20227
20228    let routed_q2 = routed.act == Act::Silu
20229        && routed.segs.is_empty()
20230        && routed.gate_proj.rows() == ROUTED_INTER
20231        && routed.gate_proj.cols() == HIDDEN
20232        && routed.up_proj.rows() == ROUTED_INTER
20233        && routed.up_proj.cols() == HIDDEN
20234        && routed.down_proj.rows() == HIDDEN
20235        && routed.down_proj.cols() == ROUTED_INTER
20236        && routed.up_proj.mapped_q2tp().is_some()
20237        && routed.down_proj.mapped_q4tp().is_some();
20238    let shared_q4 = shared.act == Act::Silu
20239        && shared.segs.is_empty()
20240        && shared.gate_proj.rows() == SHARED_INTER
20241        && shared.gate_proj.cols() == HIDDEN
20242        && shared.up_proj.rows() == SHARED_INTER
20243        && shared.up_proj.cols() == HIDDEN
20244        && shared.down_proj.rows() == HIDDEN
20245        && shared.down_proj.cols() == SHARED_INTER
20246        && shared.gate_proj.mapped_q4tp().is_some()
20247        && shared.up_proj.mapped_q4tp().is_some()
20248        && shared.down_proj.mapped_q4tp().is_some();
20249    routed_q2 && shared_q4
20250}
20251
20252/// The expert half of `moe_ffn`: run a route's experts on the per-op GPU
20253/// block or the host.
20254pub(crate) fn moe_ffn_experts(
20255    m: &MoeFfn,
20256    x: &[f32],
20257    r: &MoeRoute,
20258    pool: Option<&Pool>,
20259) -> Vec<f32> {
20260    let (idx, p, wsum) = (&r.idx, &r.p, r.wsum);
20261    // D5: the whole layer MoE block in one GPU command buffer (experts — the
20262    // same mmap via a no-copy buffer; intermediate activations on the GPU).
20263    // MoE owns a separate probe class from dense FFN: its selected-span pager
20264    // has materially different residency and latency costs.
20265    if crate::gpu::enabled_here() {
20266        #[cfg(target_os = "macos")]
20267        if crate::gpu_metal::enabled() && strict_flint_metal_pager_candidate(m) {
20268            // Do not compare the pager's exact-f32 result with the CPU's
20269            // optional A8W8 activation approximation.  The strict pager is
20270            // the validated Flint path; if a directory/view/device check
20271            // declines, preserve the existing CPU fallback rather than
20272            // leaving the probe in a half-sampled state.
20273            return moe_ffn_gpu(m, x, &idx, &p, wsum, pool).unwrap_or_else(|| {
20274                crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool))
20275            });
20276        }
20277        match crate::gpu::probe_arm(crate::gpu::OpClass::Moe) {
20278            crate::gpu::ProbeArm::Gpu => {
20279                let t0 = std::time::Instant::now();
20280                if let Some(out) = moe_ffn_gpu(m, x, &idx, &p, wsum, pool) {
20281                    crate::gpu::probe_record(crate::gpu::OpClass::Moe, true, t0.elapsed());
20282                    return out;
20283                }
20284                crate::gpu::probe_note_decline(crate::gpu::OpClass::Moe);
20285            }
20286            crate::gpu::ProbeArm::CpuTimed => {
20287                let t0 = std::time::Instant::now();
20288                let out = crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool));
20289                crate::gpu::probe_record(crate::gpu::OpClass::Moe, false, t0.elapsed());
20290                return out;
20291            }
20292            crate::gpu::ProbeArm::Cpu => {
20293                return crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool));
20294            }
20295        }
20296    }
20297    moe_ffn_cpu(m, x, &idx, &p, wsum, pool)
20298}
20299
20300/// One MiniCPM CPU-tail MoE through its opt-in dynamic bank, or through the
20301/// same-route host fallback.  The route is formed exactly once so statistics,
20302/// tracing, and model semantics remain owned by `moe_ffn_route`.
20303fn moe_ffn_minicpm_tail(
20304    slot: &mut crate::minicpm_tail::MiniCpmTail,
20305    li: usize,
20306    total_layers: usize,
20307    m: &MoeFfn,
20308    x: &[f32],
20309    pool: Option<&Pool>,
20310) -> Vec<f32> {
20311    let route = moe_ffn_route(m, x, pool, None);
20312    match slot.forward(li, m, x, &route, pool, total_layers) {
20313        Some(out) => out,
20314        // A cache refusal must be observationally identical to the generic
20315        // CPU-tail path. The surrounding host-tail scope already disables the
20316        // per-op arena, so do not introduce a float-activation policy change
20317        // merely because this explicit opt-in cache declined a model/layout.
20318        None => moe_ffn_experts(m, x, &route, pool),
20319    }
20320}
20321
20322/// One MoE token through the MiMo expert bank (`crate::mimo_moe`), or —
20323/// when the bank does not serve it — through the host path with the SAME
20324/// route, so the routing statistics and `CMF_MOE_TRACE` see it once.
20325fn moe_ffn_banked(
20326    slot: &mut crate::mimo_moe::Slot,
20327    li: usize,
20328    m: &MoeFfn,
20329    x: &[f32],
20330    pool: Option<&Pool>,
20331) -> Vec<f32> {
20332    let t0 = std::time::Instant::now();
20333    let r = moe_ffn_route(m, x, pool, None);
20334    slot.note_route(t0.elapsed().as_nanos() as u64);
20335    match slot.forward(li, m, x, &r, pool) {
20336        Some(out) => out,
20337        None => crate::qtensor::float_activations_scope(|| {
20338            crate::gpu::cpu_scope(|| moe_ffn_experts(m, x, &r, pool))
20339        }),
20340    }
20341}
20342
20343/// Verify rows share a bank frame; routing and fallback are decode's.
20344fn moe_ffn_banked_rows(
20345    slot: &mut crate::mimo_moe::Slot,
20346    li: usize,
20347    m: &MoeFfn,
20348    xs: &[f32],
20349    b: usize,
20350    hidden: usize,
20351    pool: Option<&Pool>,
20352) -> Vec<f32> {
20353    let t0 = std::time::Instant::now();
20354    let routes: Vec<_> = xs
20355        .chunks_exact(hidden)
20356        .map(|x| moe_ffn_route(m, x, pool, None))
20357        .collect();
20358    slot.note_route(t0.elapsed().as_nanos() as u64);
20359    if let Some(out) = slot.forward_rows(li, m, xs, &routes, pool) {
20360        return out;
20361    }
20362    let mut out = Vec::with_capacity(b * hidden);
20363    for (x, r) in xs.chunks_exact(hidden).zip(&routes) {
20364        let row = slot.forward(li, m, x, r, pool).unwrap_or_else(|| {
20365            // A failed bank must not stream missing experts into the arena.
20366            crate::qtensor::float_activations_scope(|| {
20367                crate::gpu::cpu_scope(|| moe_ffn_experts(m, x, r, pool))
20368            })
20369        });
20370        out.extend(row);
20371    }
20372    out
20373}
20374
20375/// One-shot report of whether the whole-token wgpu graph actually formed.
20376/// A refusal silently reverts to the per-op path, which is how a model can
20377/// look "GPU-accelerated" while every layer walks the host.  A device prefix
20378/// is tracked separately because it still pays a host boundary for the tail.
20379fn graph_note(built: bool, layers_run: usize, total_layers: usize) {
20380    use std::sync::atomic::{AtomicBool, Ordering};
20381    if built {
20382        GRAPH_TOK_OK.fetch_add(1, Ordering::Relaxed);
20383        if total_layers > 0 && layers_run < total_layers {
20384            GRAPH_TOK_PREFIX.fetch_add(1, Ordering::Relaxed);
20385        } else {
20386            GRAPH_TOK_FULL.fetch_add(1, Ordering::Relaxed);
20387        }
20388    } else {
20389        GRAPH_TOK_MISS.fetch_add(1, Ordering::Relaxed);
20390    }
20391    static SAID: AtomicBool = AtomicBool::new(false);
20392    if !SAID.swap(true, Ordering::Relaxed) {
20393        if built {
20394            tracing::info!("wgpu whole-token graph: ACTIVE");
20395        } else {
20396            tracing::warn!("wgpu whole-token graph refused — per-op path");
20397        }
20398    }
20399}
20400
20401/// Whole-token graph outcomes, process-wide: a benchmark that claims a
20402/// GPU number while MISS climbs is measuring the CPU — the honest-bench
20403/// contract makes that an error, not a footnote.
20404pub static GRAPH_TOK_OK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20405pub static GRAPH_TOK_MISS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20406/// Graph calls that returned a hidden after running only a leading device
20407/// prefix.  These are valid hybrid executions but must not be reported as a
20408/// full GPU graph in benchmark evidence.
20409pub static GRAPH_TOK_PREFIX: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20410/// Graph calls that covered the complete requested layer span.
20411pub static GRAPH_TOK_FULL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20412
20413/// Native Metal TokenGraph completion counters. These are incremented only
20414/// after checked command-buffer completion and successful readback, so a
20415/// fused-head NLL report can prove the route rather than infer it from env.
20416pub static METAL_GRAPH_TOK_OK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20417pub static METAL_GRAPH_HEAD_OK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20418pub static METAL_GRAPH_HEAD_MISS: std::sync::atomic::AtomicU64 =
20419    std::sync::atomic::AtomicU64::new(0);
20420pub static METAL_GRAPH_LAYERS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20421pub static METAL_GRAPH_ERRORS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20422/// Ordinary native-Metal rows-prefill admissions and completed rows.  These
20423/// counters are separate from TokenGraph token/head counts so a batch NLL
20424/// receipt cannot accidentally claim serial execution as batched.
20425pub static METAL_PREFILL_CHUNKS: std::sync::atomic::AtomicU64 =
20426    std::sync::atomic::AtomicU64::new(0);
20427pub static METAL_PREFILL_ROWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20428pub static METAL_PREFILL_HEAD_ROWS: std::sync::atomic::AtomicU64 =
20429    std::sync::atomic::AtomicU64::new(0);
20430pub static METAL_PREFILL_ERRORS: std::sync::atomic::AtomicU64 =
20431    std::sync::atomic::AtomicU64::new(0);
20432
20433/// `CMF_MOE_BATCH=0` restores the per-expert serial loop — the A/B lever
20434/// for the batched kernel, and how its bit-identity is checked.
20435fn moe_batch_enabled() -> bool {
20436    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
20437    *ON.get_or_init(|| std::env::var("CMF_MOE_BATCH").as_deref() != Ok("0"))
20438}
20439
20440/// Two-dispatch CPU MoE: every routed expert (and the shared one) fused
20441/// into one gate/up/SiLU dispatch and one down dispatch, instead of two
20442/// pool barriers per expert. Bit-identical to the serial loop below —
20443/// see `moe_gate_up_many` / `moe_down_many`. `None` = the batched kernel
20444/// does not cover this layer, walk the serial path.
20445fn moe_ffn_cpu_batched(
20446    m: &MoeFfn,
20447    x: &[f32],
20448    idx: &[usize],
20449    p: &[f32],
20450    wsum: f32,
20451    pool: Option<&Pool>,
20452) -> Option<Vec<f32>> {
20453    if idx.is_empty() || !moe_batch_enabled() {
20454        return None;
20455    }
20456    // The bake probe reads per-neuron activation mass out of the
20457    // single-expert path; batching would skip it. Rare and offline —
20458    // hand those runs to the serial loop.
20459    if FFN_PROBE.with(|pr| pr.borrow().is_some()) {
20460        return None;
20461    }
20462    let n = idx.len() + usize::from(m.shared.is_some());
20463    let mut pairs = Vec::with_capacity(n);
20464    let mut downs = Vec::with_capacity(n);
20465    let mut ws = Vec::with_capacity(n);
20466    for &e in idx {
20467        let d = &m.experts[e];
20468        if d.act != Act::Silu {
20469            return None;
20470        }
20471        pairs.push((&d.gate_proj, &d.up_proj));
20472        downs.push(&d.down_proj);
20473        ws.push(p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]));
20474    }
20475    // The shared expert goes last, matching the serial loop's order —
20476    // the f32 accumulation order is part of the bit-identity claim.
20477    if let Some((se, gate)) = &m.shared {
20478        if se.act != Act::Silu {
20479            return None;
20480        }
20481        let g = gate.as_ref().map_or(1.0, |gate| {
20482            let mut gl = [0.0f32; 1];
20483            gate.matvec(x, &mut gl, pool);
20484            1.0 / (1.0 + (-gl[0]).exp())
20485        });
20486        pairs.push((&se.gate_proj, &se.up_proj));
20487        downs.push(&se.down_proj);
20488        ws.push(g);
20489    }
20490    let inter = pairs[0].0.rows();
20491    let mut gs: Vec<Vec<f32>> = (0..pairs.len()).map(|_| vec![0f32; inter]).collect();
20492    if !QTensor::moe_gate_up_many(&pairs, x, &mut gs, pool) {
20493        return None;
20494    }
20495    let mut out = attention::take_buf(x.len());
20496    if !QTensor::moe_down_many(&downs, &gs, &ws, &mut out, pool) {
20497        attention::recycle_buf(&mut out);
20498        return None;
20499    }
20500    Some(out)
20501}
20502
20503/// Exact CPU completion for the routed experts a dynamic device cache did
20504/// not contain. The weights are already the router's final normalized mix.
20505/// Keeping this independent of `MoeFfn` makes the job `Sync`: its routing
20506/// statistics live in a `RefCell`, while the immutable expert tensors can be
20507/// evaluated safely in parallel with the GPU's resident subset.
20508/// Pooled-tail stage timers, reported per token by the bench JSON
20509/// (`m3_span_ms_per_tok`, `m3_cold_ms_per_tok`, `m3_arm_ms_per_tok`).
20510pub static M3_SPAN_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20511pub static M3_COLD_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20512pub static M3_ARM_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20513pub static M3_COLD_N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20514pub static M3_COLD_DEV_N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
20515
20516pub(crate) fn moe_cold_experts_cpu(
20517    experts: &[(&DenseFfn, f32)],
20518    x: &[f32],
20519    pool: Option<&Pool>,
20520) -> Vec<f32> {
20521    let mut out = attention::take_buf(x.len());
20522    if experts.is_empty() {
20523        return out;
20524    }
20525    let pairs: Vec<_> = experts
20526        .iter()
20527        .map(|(e, _)| (&e.gate_proj, &e.up_proj))
20528        .collect();
20529    let downs: Vec<_> = experts.iter().map(|(e, _)| &e.down_proj).collect();
20530    let weights: Vec<_> = experts.iter().map(|(_, w)| *w).collect();
20531    let inter = experts[0].0.gate_proj.rows();
20532    let mut activations: Vec<Vec<f32>> = (0..experts.len()).map(|_| vec![0.0; inter]).collect();
20533    // The batched gate/up kernels implement PLAIN SiLU only (their legacy
20534    // helper passes limit 0 and no activation code). MiniMax's SwiGLU-OAI
20535    // (alpha 1.702, shifted up) must take the per-expert path that reads
20536    // each tensor's own activation — otherwise every cold expert computes
20537    // silu and the residual walks away from the reference (measured: the
20538    // pooled tail shipped cos 0.047 hidden while the resident path was
20539    // bit-close).
20540    let silu_only = experts
20541        .iter()
20542        .all(|(e, _)| matches!(e.act, crate::pipeline::Act::Silu));
20543    if silu_only
20544        && QTensor::moe_gate_up_many(&pairs, x, &mut activations, pool)
20545        && QTensor::moe_down_many(&downs, &activations, &weights, &mut out, pool)
20546    {
20547        return out;
20548    }
20549    out.fill(0.0);
20550    for &(expert, weight) in experts {
20551        let mut one = dense_ffn(expert, x, pool);
20552        for (o, v) in out.iter_mut().zip(&one) {
20553            *o += weight * v;
20554        }
20555        attention::recycle_buf(&mut one);
20556    }
20557    out
20558}
20559
20560/// Cold part of a short bank batch. Share each expert's weight stream
20561/// across its tokens, but reduce contributions in each token's route order.
20562/// On an unsupported CPU/layout, retain the single-token cold kernels.
20563pub(crate) fn moe_cold_experts_rows_cpu(
20564    jobs: &[Vec<(&DenseFfn, f32)>],
20565    xs: &[f32],
20566    hidden: usize,
20567    pool: Option<&Pool>,
20568) -> Vec<f32> {
20569    let mut out = vec![0.0; xs.len()];
20570    let mut experts: Vec<&DenseFfn> = Vec::new();
20571    let mut groups: Vec<Vec<usize>> = Vec::new();
20572    let mut terms = vec![Vec::new(); jobs.len()];
20573    for (r, row) in jobs.iter().enumerate() {
20574        for &(e, w) in row {
20575            let g = match experts.iter().position(|&d| std::ptr::eq(d, e)) {
20576                Some(g) => g,
20577                None => {
20578                    experts.push(e);
20579                    groups.push(Vec::new());
20580                    groups.len() - 1
20581                }
20582            };
20583            terms[r].push((g, groups[g].len(), w));
20584            groups[g].push(r);
20585        }
20586    }
20587    if experts.is_empty() {
20588        return out;
20589    }
20590    let pairs: Vec<_> = experts.iter().map(|e| (&e.gate_proj, &e.up_proj)).collect();
20591    let downs: Vec<_> = experts.iter().map(|e| &e.down_proj).collect();
20592    let lens: Vec<_> = groups.iter().map(Vec::len).collect();
20593    let count: usize = lens.iter().sum();
20594    let mut acts = vec![vec![0.0; experts[0].gate_proj.rows()]; count];
20595    let mut ds = vec![vec![0.0; hidden]; count];
20596    if QTensor::moe_gate_up_rows(&pairs, &groups, xs, &mut acts, pool)
20597        && QTensor::moe_down_rows(&downs, &lens, &acts, &mut ds, pool)
20598    {
20599        let mut offset = 0;
20600        let offsets: Vec<_> = lens
20601            .iter()
20602            .map(|&n| {
20603                let start = offset;
20604                offset += n;
20605                start
20606            })
20607            .collect();
20608        for (r, terms) in terms.iter().enumerate() {
20609            for &(g, slot, w) in terms {
20610                for (o, &v) in out[r * hidden..(r + 1) * hidden]
20611                    .iter_mut()
20612                    .zip(&ds[offsets[g] + slot])
20613                {
20614                    *o += w * v;
20615                }
20616            }
20617        }
20618    } else {
20619        for (r, jobs) in jobs.iter().enumerate() {
20620            if !jobs.is_empty() {
20621                let mut row = moe_cold_experts_cpu(jobs, &xs[r * hidden..(r + 1) * hidden], pool);
20622                out[r * hidden..(r + 1) * hidden].copy_from_slice(&row);
20623                attention::recycle_buf(&mut row);
20624            }
20625        }
20626    }
20627    out
20628}
20629
20630/// The pure-CPU MoE expert loop (also the fallback of every GPU refusal).
20631fn moe_ffn_cpu(
20632    m: &MoeFfn,
20633    x: &[f32],
20634    idx: &[usize],
20635    p: &[f32],
20636    wsum: f32,
20637    pool: Option<&Pool>,
20638) -> Vec<f32> {
20639    if let Some(out) = moe_ffn_cpu_batched(m, x, idx, p, wsum, pool) {
20640        return out;
20641    }
20642    let mut out = attention::take_buf(x.len());
20643    for &e in idx {
20644        let mut eo = dense_ffn(&m.experts[e], x, pool);
20645        let w = p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]);
20646        for i in 0..out.len() {
20647            out[i] += w * eo[i];
20648        }
20649        attention::recycle_buf(&mut eo);
20650    }
20651    if let Some((se, gate)) = &m.shared {
20652        let mut so = dense_ffn(se, x, pool);
20653        let g = gate.as_ref().map_or(1.0, |gate| {
20654            let mut gl = [0.0f32; 1];
20655            gate.matvec(x, &mut gl, pool);
20656            1.0 / (1.0 + (-gl[0]).exp())
20657        });
20658        for i in 0..out.len() {
20659            out[i] += g * so[i];
20660        }
20661        attention::recycle_buf(&mut so);
20662    }
20663    out
20664}
20665
20666/// DeepSeek-V2 MLA forward, expand-to-MHA form (see `AttnKind::Mla`):
20667/// per token the latent expands to every head's K/V and the ordinary
20668/// cache + grouped attend do the rest. K head layout is [rope | nope]
20669/// (rotary_dim = qk_rope rotates the shared rope key and each q head's
20670/// prefix); V rows are zero-padded to the K head_dim inside the cache
20671/// and the pad is sliced off before O. Attention importance is not
20672/// accumulated for MLA yet (no eviction interplay).
20673#[allow(clippy::too_many_arguments)]
20674pub(crate) fn mla_attention(
20675    w: &MlaWeights,
20676    normed: &[f32],
20677    cache: &mut crate::kv_cache::LayerKvCache,
20678    position: usize,
20679    inv_freq: &[f32],
20680    rope_scale: f32,
20681    eps: f64,
20682    pool: Option<&Pool>,
20683) -> Vec<f32> {
20684    let (nh, dr, dn, dv, lora) = (w.nh, w.qk_rope, w.qk_nope, w.v_dim, w.lora);
20685    let hd = dr + dn;
20686    let mut q = vec![0.0f32; nh * hd];
20687    match (&w.q_a, &w.q_a_norm) {
20688        (Some(qa), Some(qn)) => {
20689            let mut t = vec![0.0f32; qa.rows()];
20690            qa.matvec(normed, &mut t, pool);
20691            let tn = inference::rms_norm(&t, qn, eps, NormStyle::Qwen);
20692            w.q_proj.matvec(&tn, &mut q, pool);
20693        }
20694        _ => w.q_proj.matvec(normed, &mut q, pool),
20695    }
20696    let mut ca = vec![0.0f32; lora + dr];
20697    w.kv_a.matvec(normed, &mut ca, pool);
20698    let (c_lat, k_rope) = ca.split_at_mut(lora);
20699    let latn = inference::rms_norm(c_lat, &w.kv_a_norm, eps, NormStyle::Qwen);
20700    let mut kvb = vec![0.0f32; nh * (dn + dv)];
20701    w.kv_b.matvec(&latn, &mut kvb, pool);
20702    if !w.nope {
20703        attention::rope_rotate_scaled(k_rope, position, inv_freq, rope_scale);
20704    }
20705    for h in 0..nh {
20706        if !w.nope {
20707            attention::rope_rotate_scaled(
20708                &mut q[h * hd..h * hd + dr],
20709                position,
20710                inv_freq,
20711                rope_scale,
20712            );
20713        }
20714    }
20715    let mut k = vec![0.0f32; nh * hd];
20716    let mut v = vec![0.0f32; nh * hd];
20717    for h in 0..nh {
20718        k[h * hd..h * hd + dr].copy_from_slice(k_rope);
20719        k[h * hd + dr..(h + 1) * hd].copy_from_slice(&kvb[h * (dn + dv)..h * (dn + dv) + dn]);
20720        v[h * hd..h * hd + dv].copy_from_slice(&kvb[h * (dn + dv) + dn..(h + 1) * (dn + dv)]);
20721    }
20722    cache.append(&k, &v, &vec![true; nh]);
20723    let (ao, mut imp) = attention::attend_all_heads(&q, cache, nh, 1, hd, w.scale, None, 0.0);
20724    attention::recycle_buf(&mut imp);
20725    let mut ov = vec![0.0f32; nh * dv];
20726    for h in 0..nh {
20727        ov[h * dv..(h + 1) * dv].copy_from_slice(&ao[h * hd..h * hd + dv]);
20728    }
20729    let mut out = vec![0.0f32; w.o_proj.rows()];
20730    w.o_proj.matvec(&ov, &mut out, pool);
20731    out
20732}
20733
20734/// Gemma-4 dual-branch FFN (spec: see `FfnKind::DenseMoe`). The dense
20735/// branch reads the pre-FFN-normed activation; the router and the
20736/// expert branch read the RAW residual — the router through a
20737/// scale-less rms norm (its constant gain is folded into the weights),
20738/// the experts through `pre_norm_2`. CPU path; GPU graphs refuse the
20739/// layer kind honestly.
20740fn dense_moe_ffn(
20741    dm: &DenseMoeFfn,
20742    x_normed: &[f32],
20743    h_raw: &[f32],
20744    eps: f64,
20745    norm_style: NormStyle,
20746    pool: Option<&Pool>,
20747) -> Vec<f32> {
20748    let mut d = dense_ffn(&dm.dense, x_normed, pool);
20749    d = inference::rms_norm(&d, &dm.post_norm_1, eps, norm_style);
20750    let m = &dm.moe;
20751    let ne = m.experts.len();
20752    let mut logits = vec![0.0f32; ne];
20753    if m.router_input_norm {
20754        let ss: f32 = h_raw.iter().map(|v| v * v).sum::<f32>() / h_raw.len() as f32;
20755        let inv = 1.0 / (ss + eps as f32).sqrt();
20756        let xr: Vec<f32> = h_raw.iter().map(|v| v * inv).collect();
20757        m.router.matvec(&xr, &mut logits, pool);
20758    } else {
20759        m.router.matvec(h_raw, &mut logits, pool);
20760    }
20761    let (idx, p, wsum) = moe_route(&logits, m, None);
20762    {
20763        let mut st = m.stats.borrow_mut();
20764        if st.len() < ne {
20765            st.resize(ne, 0);
20766        }
20767        for &e in &idx {
20768            st[e] += 1;
20769        }
20770    }
20771    let x2 = inference::rms_norm(h_raw, &dm.pre_norm_2, eps, norm_style);
20772    let mo = moe_ffn_cpu(m, &x2, &idx, &p, wsum, pool);
20773    let mo = inference::rms_norm(&mo, &dm.post_norm_2, eps, norm_style);
20774    for (di, mi) in d.iter_mut().zip(&mo) {
20775        *di += mi;
20776    }
20777    d
20778}
20779
20780/// Building the MoE-layer GPU jobs: all selected experts (+shared) must
20781/// be q8_2f-Mapped from the primary mapping; otherwise None → CPU path.
20782/// One-shot report of why the MoE GPU block refused. A silent `?` here
20783/// sends every expert to the CPU with nothing in the logs to say so —
20784/// which is exactly how a q4tp MoE model looked "GPU-accelerated" while
20785/// running entirely on the host.
20786fn moe_gpu_refused(why: &'static str) {
20787    use std::sync::atomic::{AtomicBool, Ordering};
20788    static SAID: AtomicBool = AtomicBool::new(false);
20789    if !SAID.swap(true, Ordering::Relaxed) {
20790        tracing::warn!("MoE GPU block refused ({why}) — experts run on the CPU");
20791    }
20792}
20793
20794fn moe_ffn_gpu(
20795    m: &MoeFfn,
20796    x: &[f32],
20797    idx: &[usize],
20798    p: &[f32],
20799    wsum: f32,
20800    pool: Option<&Pool>,
20801) -> Option<Vec<f32>> {
20802    use crate::gpu::MoeJob;
20803
20804    let mut jobs: Vec<MoeJob> = Vec::with_capacity(idx.len() + 1);
20805    let mut model_ref = None;
20806    for &e in idx {
20807        if moe_push_job(&m.experts[e], x, p[e] / wsum, &mut jobs, &mut model_ref).is_none() {
20808            moe_gpu_refused("push_job(expert)");
20809            return None;
20810        }
20811    }
20812    if let Some((se, gate)) = &m.shared {
20813        let g = gate.as_ref().map_or(1.0, |gate| {
20814            let mut gl = [0.0f32; 1];
20815            gate.matvec(x, &mut gl, pool);
20816            1.0 / (1.0 + (-gl[0]).exp())
20817        });
20818        if moe_push_job(se, x, g, &mut jobs, &mut model_ref).is_none() {
20819            moe_gpu_refused("push_job(shared)");
20820            return None;
20821        }
20822    }
20823    let Some(model) = model_ref else {
20824        moe_gpu_refused("no model_ref");
20825        return None;
20826    };
20827    let hidden = jobs[0].down.1;
20828    let mut out = vec![0.0f32; hidden];
20829    if crate::gpu::moe_block(&model, &jobs, &mut out) {
20830        Some(out)
20831    } else {
20832        moe_gpu_refused("gpu::moe_block");
20833        None
20834    }
20835}
20836
20837/// Single-position FFN dispatch.
20838fn ffn_forward(
20839    ffn: &FfnKind,
20840    x: &[f32],
20841    pool: Option<&Pool>,
20842    experts_allowed: Option<&[bool]>,
20843) -> Vec<f32> {
20844    match ffn {
20845        FfnKind::Dense(d) if !d.segs.is_empty() => tube_ffn(d, x, 1, pool, None),
20846        FfnKind::Dense(d) => dense_ffn(d, x, pool),
20847        FfnKind::Moe(m) => moe_ffn(m, x, pool, experts_allowed),
20848        // Dual-branch layers need the raw residual — their callers
20849        // dispatch dense_moe_ffn directly; the auxiliary paths that land
20850        // here (MTP draft, o1 replay) do not co-occur with gemma-4 MoE.
20851        FfnKind::DenseMoe(_) => unreachable!("DenseMoe dispatches via dense_moe_ffn"),
20852    }
20853}
20854
20855/// Fused two-position FFN: gate/up/down streamed once (dense). MoE
20856/// falls back to two singles — expert sets differ per position, there
20857/// is nothing to fuse.
20858fn ffn_forward_pair(
20859    ffn: &FfnKind,
20860    x1: &[f32],
20861    x2: &[f32],
20862    pool: Option<&Pool>,
20863    experts_allowed: Option<&[bool]>,
20864) -> (Vec<f32>, Vec<f32>) {
20865    let d = match ffn {
20866        // A tube layer has nothing to fuse across the pair — the tubes
20867        // are separate matrices; two singles are the honest path.
20868        FfnKind::Dense(d) if !d.segs.is_empty() => {
20869            return (
20870                tube_ffn(d, x1, 1, pool, None),
20871                tube_ffn(d, x2, 1, pool, None),
20872            );
20873        }
20874        FfnKind::Dense(d) => d,
20875        FfnKind::Moe(m) => {
20876            return (
20877                moe_ffn(m, x1, pool, experts_allowed),
20878                moe_ffn(m, x2, pool, experts_allowed),
20879            );
20880        }
20881        FfnKind::DenseMoe(_) => unreachable!("DenseMoe dispatches via dense_moe_ffn"),
20882    };
20883    let inter = d.gate_proj.rows();
20884    FFN_SCRATCH.with(|s| {
20885        let mut s = s.borrow_mut();
20886        let [g1, g2, u1, u2] = &mut *s;
20887        g1.resize(inter, 0.0);
20888        g2.resize(inter, 0.0);
20889        u1.resize(inter, 0.0);
20890        u2.resize(inter, 0.0);
20891        // Multi-matrix pair job: gate+up under one pool dispatch
20892        // (o1s = lane-1 outputs across tensors, o2s = lane-2).
20893        QTensor::matvec2_many(
20894            [&d.gate_proj, &d.up_proj],
20895            x1,
20896            x2,
20897            [g1.as_mut_slice(), u1.as_mut_slice()],
20898            [g2.as_mut_slice(), u2.as_mut_slice()],
20899            pool,
20900        );
20901        for i in 0..inter {
20902            g1[i] = d.act.combine(g1[i], u1[i]);
20903            g2[i] = d.act.combine(g2[i], u2[i]);
20904        }
20905        let mut o1 = attention::take_buf(d.down_proj.rows());
20906        let mut o2 = attention::take_buf(d.down_proj.rows());
20907        d.down_proj.matvec2(g1, g2, &mut o1, &mut o2, pool);
20908        (o1, o2)
20909    })
20910}
20911
20912#[cfg(test)]
20913mod tests {
20914
20915    #[test]
20916    fn encoder_hidden_states_are_normalized_and_reusable() {
20917        let mut p = super::create_test_pipeline(8, 12, 2, 1, 4, 2, 32);
20918        let ids = [1, 7, 11, 19];
20919
20920        let first = p.encode_hidden_states(&ids).expect("encoder forward");
20921        let second = p
20922            .encode_hidden_states(&ids)
20923            .expect("reusable encoder forward");
20924        assert_eq!(first.len(), ids.len() * 8);
20925        assert!(first.iter().all(|v| v.is_finite()));
20926        assert_eq!(
20927            first, second,
20928            "encoder forward must start from a fresh state"
20929        );
20930
20931        // An encoder call must not leave stale KV/GDN state behind for the
20932        // regular generative API sharing the same Pipeline implementation.
20933        assert!(p.forward_ids(&ids, None).is_ok());
20934    }
20935
20936    /// The 0.7.6 prefill-chunk rule: a plain dense stack wholly on a
20937    /// discrete card reads the prompt in wide chunks on x86; every other
20938    /// case keeps the width it had (the GDN-hybrid, MoE and DeepSeek paths
20939    /// were tuned on hardware not measured for this change).
20940    #[test]
20941    fn prefill_chunk_rule_widens_only_dense_on_discrete() {
20942        use super::{ChunkHost, ChunkStackFacts, DISCRETE_DENSE_PREFILL_CHUNK, prefill_chunk_rule};
20943        let dense_card = ChunkStackFacts {
20944            plain_dense: true,
20945            discrete: true,
20946            gpu_on: true,
20947            ..Default::default()
20948        };
20949        assert!(dense_card.dense_on_discrete());
20950        // The bug: a dense Llama on a Vulkan RTX 3090 got 48.
20951        assert_eq!(
20952            prefill_chunk_rule(None, ChunkHost::Other, dense_card.dense_on_discrete()),
20953            DISCRETE_DENSE_PREFILL_CHUNK
20954        );
20955        assert!(DISCRETE_DENSE_PREFILL_CHUNK > 48);
20956        for (label, facts) in [
20957            (
20958                "GDN hybrid / MoE / DeepSeek stack",
20959                ChunkStackFacts {
20960                    plain_dense: false,
20961                    ..dense_card
20962                },
20963            ),
20964            (
20965                "integrated GPU",
20966                ChunkStackFacts {
20967                    discrete: false,
20968                    ..dense_card
20969                },
20970            ),
20971            (
20972                "CPU only",
20973                ChunkStackFacts {
20974                    gpu_on: false,
20975                    discrete: false,
20976                    ..dense_card
20977                },
20978            ),
20979            (
20980                "capacity split",
20981                ChunkStackFacts {
20982                    capacity_split: true,
20983                    ..dense_card
20984                },
20985            ),
20986            (
20987                "multi-GPU plan",
20988                ChunkStackFacts {
20989                    multi_gpu: true,
20990                    ..dense_card
20991                },
20992            ),
20993            (
20994                "O(1) layers",
20995                ChunkStackFacts {
20996                    o1: true,
20997                    ..dense_card
20998                },
20999            ),
21000        ] {
21001            assert!(!facts.dense_on_discrete(), "{label}");
21002            assert_eq!(
21003                prefill_chunk_rule(None, ChunkHost::Other, facts.dense_on_discrete()),
21004                48,
21005                "{label} keeps the historical x86 chunk"
21006            );
21007        }
21008        // Other hosts are untouched whatever the model.
21009        for dense in [false, true] {
21010            assert_eq!(prefill_chunk_rule(None, ChunkHost::Macos, dense), 512);
21011            assert_eq!(prefill_chunk_rule(None, ChunkHost::Aarch64, dense), 256);
21012        }
21013        // CMF_PREFILL_CHUNK still wins everywhere (and is clamped to ≥ 1).
21014        for host in [ChunkHost::Macos, ChunkHost::Aarch64, ChunkHost::Other] {
21015            for dense in [false, true] {
21016                assert_eq!(prefill_chunk_rule(Some(48), host, dense), 48);
21017                assert_eq!(prefill_chunk_rule(Some(0), host, dense), 1);
21018            }
21019        }
21020    }
21021
21022    #[test]
21023    fn kv_reuse_plan_pulls_rows_decode_wrote_only_on_the_device() {
21024        use super::{ReuseLayer, ReusePlan, kv_reuse_plan};
21025        let full = |host_rows, device_rows| ReuseLayer {
21026            full: true,
21027            host_rows,
21028            device_rows,
21029            device_state: false,
21030        };
21031        // Turn 1: 300-token prompt prefilled on the host, 40 tokens decoded
21032        // by the wgpu graph into the device mirror only. Turn 2 reuses 339.
21033        assert_eq!(
21034            kv_reuse_plan(339, &[full(300, Some(339)), full(300, Some(339))]),
21035            ReusePlan::Pull(vec![(0, 300, 339), (1, 300, 339)])
21036        );
21037        // CPU / Metal: the host owner already holds every forwarded row.
21038        assert_eq!(kv_reuse_plan(339, &[full(339, None)]), ReusePlan::Ready);
21039        // A mirror past the prefix is fine for the host (it gets rewound).
21040        assert_eq!(
21041            kv_reuse_plan(339, &[full(339, Some(345))]),
21042            ReusePlan::Ready
21043        );
21044        // GPU prefix / CPU tail: only the device layers lag.
21045        assert_eq!(
21046            kv_reuse_plan(339, &[full(300, Some(339)), full(339, None)]),
21047            ReusePlan::Pull(vec![(0, 300, 339)])
21048        );
21049        // The device cannot supply the missing rows: never continue.
21050        assert_eq!(
21051            kv_reuse_plan(339, &[full(300, Some(320))]),
21052            ReusePlan::Fresh
21053        );
21054        assert_eq!(kv_reuse_plan(339, &[full(300, None)]), ReusePlan::Fresh);
21055        assert_eq!(kv_reuse_plan(339, &[full(350, None)]), ReusePlan::Fresh);
21056        // A recurrent state advanced on the device cannot be handed to a
21057        // host prefill (it is not rewindable and the host copy is stale).
21058        let conv = |device_state| ReuseLayer {
21059            full: false,
21060            host_rows: 0,
21061            device_rows: None,
21062            device_state,
21063        };
21064        assert_eq!(
21065            kv_reuse_plan(339, &[conv(true), full(300, Some(339))]),
21066            ReusePlan::Fresh
21067        );
21068        assert_eq!(
21069            kv_reuse_plan(339, &[conv(false), full(339, None)]),
21070            ReusePlan::Ready
21071        );
21072    }
21073
21074    #[test]
21075    fn nll_graph_policy_scopes_only_the_fused_head() {
21076        for (label, unmasked, prefer_graph, native_metal, want_graph, want_head) in [
21077            // A Vulkan/Wgpu hidden-only graph remains the quality route.
21078            ("vulkan graph", true, true, false, true, false),
21079            // Native Metal adds the strict fused graph-head contract.
21080            ("native Metal graph", true, true, true, true, true),
21081            // Masked NLL and the explicit non-graph fallback remain unchanged.
21082            ("masked", false, true, false, false, false),
21083            ("graph disabled", true, false, true, false, false),
21084        ] {
21085            let (graph_quality, graph_head_required) =
21086                super::nll_graph_policy(unmasked, prefer_graph, native_metal);
21087            assert_eq!(graph_quality, want_graph, "{label}: graph quality");
21088            assert_eq!(graph_head_required, want_head, "{label}: fused head");
21089        }
21090    }
21091
21092    #[test]
21093    fn mtp_prefill_pair_boundaries_skip_only_final_prompt_row() {
21094        assert_eq!(mtp_prefill_pair_count(0, 128, 256), 128);
21095        assert_eq!(mtp_prefill_pair_count(128, 256, 256), 127);
21096        assert_eq!(mtp_prefill_pair_count(0, 256, 256), 255);
21097        assert_eq!(mtp_prefill_pair_count(256, 256, 256), 0);
21098        assert_eq!(mtp_prefill_pair_count(300, 320, 256), 0);
21099    }
21100
21101    #[test]
21102    fn cancel_flag_stops_generation() {
21103        let mut p = create_test_pipeline(16, 32, 2, 2, 8, 2, 32);
21104        // Set before the call: the prefill loops honour it, the run
21105        // returns immediately with the cancelled reason and no tokens.
21106        p.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
21107        let r = p.generate_from_ids(&[1, 2, 3], 8, None, None).unwrap();
21108        assert_eq!(r.finish_reason, "cancelled");
21109        assert!(
21110            r.token_ids.is_empty(),
21111            "no tokens after cancel: {:?}",
21112            r.token_ids
21113        );
21114        assert_eq!(p.kv_cache.seq_len(), 0);
21115        assert!(p.kv_history.is_empty());
21116        assert!(!p.graph_want_logits);
21117        assert!(p.graph_logits.is_none());
21118        // Flag auto-cleared: the next call generates normally.
21119        let r2 = p.generate_from_ids(&[1, 2, 3], 4, None, None).unwrap();
21120        assert_ne!(r2.finish_reason, "cancelled");
21121    }
21122    use super::*;
21123
21124    #[test]
21125    fn minimax_m3_arch_selects_checked_oai_activation_only() {
21126        // Keep this fixture minimal: `Act::from_arch_full` needs only the
21127        // architecture id and activation name, while serde supplies stable
21128        // defaults for unrelated CMF fields.
21129        let arch = |arch_name: &str, hidden_act: &str| {
21130            serde_json::from_value::<cortiq_core::ModelArch>(serde_json::json!({
21131                "arch_name": arch_name,
21132                "hidden_size": 8,
21133                "intermediate_size": 16,
21134                "num_layers": 1,
21135                "num_attention_heads": 1,
21136                "num_kv_heads": 1,
21137                "head_dim": 8,
21138                "vocab_size": 16,
21139                "layer_types": ["FullAttention"],
21140                "rms_norm_eps": 1e-6,
21141                "max_position_embeddings": 16,
21142                "hidden_act": hidden_act
21143            }))
21144            .expect("minimal architecture")
21145        };
21146        let minimax = arch("minimax_m3_vl", "swigluoai");
21147        assert_eq!(
21148            Act::from_arch_full(&minimax),
21149            Act::SwiGluOai {
21150                alpha: 1.702,
21151                limit: 7.0,
21152            }
21153        );
21154
21155        // The same spelling must not turn into MiniMax math on a generic
21156        // model.  Only the source-validated M3 architecture owns it.
21157        let unrelated = arch("qwen2", "swigluoai");
21158        assert_eq!(Act::from_arch_full(&unrelated), Act::Silu);
21159
21160        // Conversely, an M3-tagged header with a normal activation keeps the
21161        // normal path; this prevents the architecture id from overriding the
21162        // explicit serialized contract.
21163        let non_oai = arch("minimax_m3_vl", "gelu");
21164        assert_eq!(Act::from_arch_full(&non_oai), Act::Gelu);
21165    }
21166
21167    #[test]
21168    fn minimax_swiglu_oai_act_matches_scalar_contract() {
21169        let act = Act::swiglu_oai(1.702, 7.0);
21170        let got = act.combine(10.0, -10.0);
21171        let expected = crate::inference::swiglu_oai(10.0, -10.0, 1.702, 1.0, Some(7.0));
21172        assert!((got - expected).abs() < 1e-6);
21173        assert_eq!(act.graph_act(), None, "no inexact generic graph fallback");
21174        assert_eq!(
21175            act.wgpu_graph_act(),
21176            Some(crate::gpu::GraphAct::SwiGluOaiM3),
21177            "the WGPU-only arm accepts only the frozen M3 constants"
21178        );
21179        assert_eq!(
21180            Act::swiglu_oai(1.701, 7.0).wgpu_graph_act(),
21181            None,
21182            "nearby OAI constants must not borrow MiniMax's kernel"
21183        );
21184        assert_eq!(
21185            act.moe_job_graph_contract(),
21186            Some((crate::gpu::GraphAct::SwiGluOaiM3, 7.0)),
21187            "the direct MoE path carries the frozen clamp with the marker"
21188        );
21189        assert_eq!(
21190            Act::swiglu_oai(1.702, 6.999).moe_job_graph_contract(),
21191            None,
21192            "a nearby clamp must not borrow MiniMax's device contract"
21193        );
21194
21195        // `apply` is the gate half only; `combine` owns the up clamp and
21196        // +1 offset. The two must not accidentally collapse to ordinary SiLU.
21197        let gate_only = act.apply(-10.0);
21198        let expected_gate = -10.0 / (1.0 + (17.02f32).exp());
21199        assert!((gate_only - expected_gate).abs() < 1e-10);
21200    }
21201
21202    #[test]
21203    fn explicit_sliding_schedule_selects_local_rope_profile() {
21204        // Mellum alternates three local 1,024-token layers with one global
21205        // YaRN layer.  An explicit schedule deliberately overrides the
21206        // cadence sentinel in `swa`, so test both RoPE table and scale
21207        // dispatch rather than merely checking that the metadata loaded.
21208        let mut p = create_test_pipeline(32, 64, 4, 1, 8, 4, 32);
21209        p.swa = Some((1024, usize::MAX));
21210        p.sliding_layers = Some(vec![true, true, true, false]);
21211        p.inv_freq = std::sync::Arc::new(vec![0.125; 4]);
21212        p.inv_freq_local = Some(std::sync::Arc::new(vec![0.25; 4]));
21213        p.rope_scale = 1.277_258_9;
21214        p.rope_scale_local = 1.0;
21215
21216        for li in 0..3 {
21217            assert_eq!(p.layer_window(li), Some(1024), "local layer {li}");
21218            assert_eq!(p.layer_inv_freq(li).as_slice(), &[0.25; 4]);
21219            assert_eq!(p.layer_rope_scale(li), 1.0, "local layer {li}");
21220        }
21221        assert_eq!(p.layer_window(3), None);
21222        assert_eq!(p.layer_inv_freq(3).as_slice(), &[0.125; 4]);
21223        assert_eq!(p.layer_rope_scale(3), 1.277_258_9);
21224    }
21225
21226    /// sparse_ffn_quant must equal a dense FFN where inactive neurons are
21227    /// zeroed (mask × mmap correctness). On F32 tensors this is EXACT —
21228    /// it validates the row_dot / add_col_scaled / scatter indexing, the
21229    /// bug-prone part. The q8 branches reuse the golden-tested linear
21230    /// The per-token sparse path reads a transposed `down`; it must
21231    /// agree with the arm that computes everything and zeroes the
21232    /// losers, or the speed measurement is measuring a different model.
21233    #[test]
21234    fn dynamic_ffn_equals_the_zeroing_arm() {
21235        let (hidden, inter) = (8usize, 32usize);
21236        let synth = |n: usize, salt: usize| -> Vec<f32> {
21237            (0..n)
21238                .map(|i| (((i * 29 + salt * 13 + 7) % 89) as f32 / 89.0 - 0.5) * 0.6)
21239                .collect()
21240        };
21241        let down = synth(hidden * inter, 3);
21242        let mut down_t = vec![0.0f32; inter * hidden];
21243        for r in 0..hidden {
21244            for c in 0..inter {
21245                down_t[c * hidden + r] = down[r * inter + c];
21246            }
21247        }
21248        let d = DenseFfn {
21249            gate_proj: QTensor::from_f32(synth(inter * hidden, 1), inter, hidden),
21250            up_proj: QTensor::from_f32(synth(inter * hidden, 2), inter, hidden),
21251            down_proj: QTensor::from_f32(down.clone(), hidden, inter),
21252            act: Act::Silu,
21253            down_t: Some(QTensor::from_f32(down_t, inter, hidden)),
21254            segs: Vec::new(),
21255        };
21256        let x = synth(hidden, 11);
21257        let k = 12usize;
21258        let got = dense_ffn_dynamic(&d, &x, None, k).expect("down_t present");
21259        // Reference: full compute, keep the k loudest |silu(gate)|.
21260        let mut g = vec![0.0f32; inter];
21261        d.gate_proj.matvec(&x, &mut g, None);
21262        let mut u = vec![0.0f32; inter];
21263        d.up_proj.matvec(&x, &mut u, None);
21264        for v in g.iter_mut() {
21265            *v = inference::silu(*v);
21266        }
21267        keep_top_k(&mut g, k);
21268        for i in 0..inter {
21269            g[i] *= u[i];
21270        }
21271        let mut want = vec![0.0f32; hidden];
21272        d.down_proj.matvec(&g, &mut want, None);
21273        for (a, b) in want.iter().zip(&got) {
21274            assert!((a - b).abs() < 1e-5, "dynamic {b} vs reference {a}");
21275        }
21276    }
21277
21278    /// A tube layer is the same layer, re-cut. With every tube open the
21279    /// answer must equal the dense FFN over the concatenated neurons
21280    /// (the permutation is an identity on the layer's function); with a
21281    /// tube closed it must equal the dense FFN with those neurons
21282    /// zeroed — the mask semantics, now paid for in bytes not read.
21283    #[test]
21284    fn tube_ffn_open_equals_dense_and_closed_equals_masked() {
21285        let (hidden, core, tube) = (8usize, 12usize, 8usize);
21286        let inter = core + tube;
21287        let synth = |n: usize, salt: usize| -> Vec<f32> {
21288            (0..n)
21289                .map(|i| (((i * 41 + salt * 17 + 5) % 97) as f32 / 97.0 - 0.5) * 0.5)
21290                .collect()
21291        };
21292        let (g_all, u_all) = (synth(inter * hidden, 1), synth(inter * hidden, 2));
21293        let d_all = synth(hidden * inter, 3);
21294        // The dense layer, and the same weights cut into core + tube.
21295        let dense = DenseFfn {
21296            gate_proj: QTensor::from_f32(g_all.clone(), inter, hidden),
21297            up_proj: QTensor::from_f32(u_all.clone(), inter, hidden),
21298            down_proj: QTensor::from_f32(d_all.clone(), hidden, inter),
21299            act: Act::Silu,
21300            down_t: None,
21301            segs: Vec::new(),
21302        };
21303        let rows =
21304            |v: &[f32], a: usize, b: usize| -> Vec<f32> { v[a * hidden..b * hidden].to_vec() };
21305        let cols = |v: &[f32], a: usize, b: usize| -> Vec<f32> {
21306            let mut o = Vec::with_capacity(hidden * (b - a));
21307            for r in 0..hidden {
21308                o.extend_from_slice(&v[r * inter + a..r * inter + b]);
21309            }
21310            o
21311        };
21312        let tubed = DenseFfn {
21313            down_t: None,
21314            gate_proj: QTensor::from_f32(rows(&g_all, 0, core), core, hidden),
21315            up_proj: QTensor::from_f32(rows(&u_all, 0, core), core, hidden),
21316            down_proj: QTensor::from_f32(cols(&d_all, 0, core), hidden, core),
21317            act: Act::Silu,
21318            segs: vec![FfnSeg {
21319                gate: QTensor::from_f32(rows(&g_all, core, inter), tube, hidden),
21320                up: QTensor::from_f32(rows(&u_all, core, inter), tube, hidden),
21321                down: QTensor::from_f32(cols(&d_all, core, inter), hidden, tube),
21322                start: core,
21323                width: tube,
21324            }],
21325        };
21326        let x = synth(hidden, 7);
21327        let want = dense_ffn(&dense, &x, None);
21328        let got = tube_ffn(&tubed, &x, 1, None, None);
21329        for (a, b) in want.iter().zip(&got) {
21330            assert!((a - b).abs() < 1e-5, "open tube: {a} vs {b}");
21331        }
21332        // Closed tube: bits on for the core, off for the tube.
21333        let mut bits = vec![0u8; inter.div_ceil(8)];
21334        for n in 0..core {
21335            bits[n / 8] |= 1 << (n % 8);
21336        }
21337        let closed = tube_ffn(&tubed, &x, 1, None, Some(&bits));
21338        let masked = dense_ffn_masked(&dense, &x, None, &bits);
21339        for (a, b) in masked.iter().zip(&closed) {
21340            assert!((a - b).abs() < 1e-5, "closed tube: {a} vs {b}");
21341        }
21342        // The batched arm must agree with the single-position one.
21343        let batch = tube_ffn(&tubed, &x, 1, None, Some(&bits));
21344        for (a, b) in closed.iter().zip(&batch) {
21345            assert_eq!(a, b, "batch arm disagrees with decode arm");
21346        }
21347    }
21348
21349    /// scale, structurally identical to the matvec kernels.
21350    #[test]
21351    fn sparse_ffn_quant_equals_dense_with_inactive_zeroed() {
21352        let (hidden, inter) = (16usize, 40usize);
21353        let synth = |n: usize, salt: usize| -> Vec<f32> {
21354            (0..n)
21355                .map(|i| (((i * 37 + salt * 11 + 3) % 101) as f32 / 101.0 - 0.5) * 0.4)
21356                .collect()
21357        };
21358        let d = DenseFfn {
21359            gate_proj: QTensor::from_f32(synth(inter * hidden, 1), inter, hidden),
21360            up_proj: QTensor::from_f32(synth(inter * hidden, 2), inter, hidden),
21361            down_proj: QTensor::from_f32(synth(hidden * inter, 3), hidden, inter),
21362            act: Act::Silu,
21363            down_t: None,
21364            segs: Vec::new(),
21365        };
21366        let x = synth(hidden, 9);
21367        // Active = every 3rd neuron.
21368        let active: Vec<u16> = (0..inter as u16).filter(|i| i % 3 == 0).collect();
21369
21370        let sparse = sparse_ffn_quant(&d, &x, &active, hidden, None);
21371
21372        // Reference: full dense FFN but g[i]=0 for inactive neurons.
21373        let mut g = vec![0.0f32; inter];
21374        d.gate_proj.matvec(&x, &mut g, None);
21375        let mut u = vec![0.0f32; inter];
21376        d.up_proj.matvec(&x, &mut u, None);
21377        let act_set: std::collections::HashSet<u16> = active.iter().copied().collect();
21378        for i in 0..inter {
21379            g[i] = if act_set.contains(&(i as u16)) {
21380                inference::silu(g[i]) * u[i]
21381            } else {
21382                0.0
21383            };
21384        }
21385        let mut reference = vec![0.0f32; hidden];
21386        d.down_proj.matvec(&g, &mut reference, None);
21387
21388        let max_d = sparse
21389            .iter()
21390            .zip(&reference)
21391            .map(|(a, b)| (a - b).abs())
21392            .fold(0.0f32, f32::max);
21393        assert!(max_d < 1e-5, "sparse != dense-zeroed: max|Δ| = {max_d}");
21394    }
21395
21396    /// Attach a synthetic MTP head (same structure as a main layer).
21397    fn attach_test_mtp(p: &mut Pipeline) {
21398        let (h, inter, heads, kv, hd) = (
21399            p.hidden_size,
21400            p.intermediate_size,
21401            p.num_heads,
21402            p.num_kv_heads,
21403            p.head_dim,
21404        );
21405        let synth = |n: usize, salt: usize| -> Vec<f32> {
21406            (0..n)
21407                .map(|i| (((i * 29 + salt * 23 + 5) % 101) as f32 / 101.0 - 0.5) * 0.2)
21408                .collect()
21409        };
21410        let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
21411            QTensor::from_f32(synth(rows * cols, salt), rows, cols)
21412        };
21413        p.mtp = Some(MtpModule {
21414            enorm: vec![1.0; h],
21415            hnorm: vec![1.0; h],
21416            eh_proj: qt(h, 2 * h, 301),
21417            layer: LayerWeights {
21418                input_norm: vec![1.0; h],
21419                post_norm: vec![1.0; h],
21420                attn_out_norm: None,
21421                ffn_out_norm: None,
21422                layer_scale: None,
21423                ffn: FfnKind::Dense(DenseFfn {
21424                    gate_proj: qt(inter, h, 315),
21425                    up_proj: qt(inter, h, 316),
21426                    down_proj: qt(h, inter, 317),
21427                    act: Act::Silu,
21428                    down_t: None,
21429                    segs: Vec::new(),
21430                }),
21431                attn: AttnKind::Full {
21432                    bias: None,
21433                    wq: qt(heads * hd, h, 311),
21434                    wk: qt(kv * hd, h, 312),
21435                    wv: qt(kv * hd, h, 313),
21436                    wo: qt(h, heads * hd, 314),
21437                    q_norm: None,
21438                    k_norm: None,
21439                    output_gate: false,
21440                    softplus_gate: None,
21441                },
21442            },
21443            final_norm: vec![1.0; h],
21444            kv: crate::kv_cache::LayerKvCache::new(kv, hd),
21445        });
21446    }
21447
21448    #[test]
21449    fn speculative_equals_vanilla_greedy() {
21450        // Speculative decode and the wgpu token graph are mutually
21451        // exclusive; a leaked CMF_GPU=wgpu from a parallel gpu test
21452        // would silently disable drafting. Pin the graph off.
21453        unsafe { std::env::set_var("CMF_GPU_WGPU_GRAPH", "0") };
21454        let run = |spec: bool| {
21455            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
21456            p.sampler_config.temperature = 0.0;
21457            attach_test_mtp(&mut p);
21458            p.speculative = spec;
21459            let r = p.generate("abcdef", 12, None, None).unwrap();
21460            (r.token_ids, r.mtp_drafted, r.mtp_accepted)
21461        };
21462        let (vanilla, d0, _) = run(false);
21463        let (spec, d1, a1) = run(true);
21464        assert_eq!(d0, 0, "vanilla path must not draft");
21465        assert!(d1 > 0, "speculative path must draft");
21466        assert_eq!(
21467            vanilla, spec,
21468            "speculative must reproduce the exact greedy sequence (accepted {a1}/{d1})"
21469        );
21470    }
21471
21472    #[test]
21473    fn speculative_accepts_constant_oracle() {
21474        // See speculative_equals_vanilla_greedy: pin the wgpu graph off.
21475        unsafe { std::env::set_var("CMF_GPU_WGPU_GRAPH", "0") };
21476        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
21477        p.sampler_config.temperature = 0.0;
21478        p.sampler_config.repetition_penalty = 1.0;
21479        // Constant lm_head → every logit equal → both the main model and
21480        // the draft head argmax to token 0: acceptance must be 100%.
21481        p.weights.lm_head = QTensor::from_f32(vec![0.01; 64 * 8], 64, 8);
21482        attach_test_mtp(&mut p);
21483        p.speculative = true;
21484        let r = p.generate("abcd", 10, None, None).unwrap();
21485        assert!(r.mtp_drafted > 0);
21486        assert_eq!(
21487            r.mtp_accepted, r.mtp_drafted,
21488            "constant logits → every draft accepted"
21489        );
21490        // Ties resolve to the same token in both the main and draft
21491        // heads — the sequence is one repeated token.
21492        assert!(r.token_ids.windows(2).all(|w| w[0] == w[1]));
21493    }
21494
21495    #[test]
21496    fn empty_prompt_is_an_error_not_a_panic() {
21497        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
21498        let r = p.generate("", 4, None, None);
21499        assert!(r.is_err(), "empty prompt must be a clean error");
21500    }
21501
21502    #[test]
21503    fn every_token_enters_kv_exactly_once() {
21504        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
21505        // Greedy so no RNG variance; byte tokenizer → 3 prompt tokens.
21506        p.sampler_config.temperature = 0.0;
21507        let r = p.generate("abc", 2, None, None).unwrap();
21508        assert_eq!(r.prompt_tokens, 3);
21509        // prompt(3) + first sampled token forwarded before second logits:
21510        // step0 samples from prefill hidden (no extra forward), then
21511        // forwards t1 → cache 4; step1 samples, loop ends (max_tokens).
21512        assert_eq!(
21513            p.kv_cache.seq_len(),
21514            3 + r.tokens_generated - 1,
21515            "each token must be cached exactly once (v1 cached the last prompt token twice)"
21516        );
21517    }
21518
21519    #[test]
21520    fn generation_is_reproducible_with_seed() {
21521        let run = || {
21522            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
21523            p.generate("hello", 8, None, None).unwrap().token_ids
21524        };
21525        assert_eq!(run(), run());
21526    }
21527
21528    #[test]
21529    fn resetting_sampler_restarts_the_seeded_stream() {
21530        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
21531        let config = SamplerConfig {
21532            seed: Some(1234),
21533            ..SamplerConfig::default()
21534        };
21535        p.set_sampler_config(config.clone());
21536        let first = p.generate("hello", 8, None, None).unwrap().token_ids;
21537        p.set_sampler_config(config);
21538        let second = p.generate("hello", 8, None, None).unwrap().token_ids;
21539        assert_eq!(first, second);
21540    }
21541
21542    #[test]
21543    fn eviction_bounds_the_cache() {
21544        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
21545        p.kv_cache.max_seq_len = 6;
21546        p.sampler_config.temperature = 0.0;
21547        let _ = p.generate("abcd", 12, None, None).unwrap();
21548        assert!(
21549            p.kv_cache.seq_len() <= 6 + 1,
21550            "cache must stay bounded by max_seq_len (got {})",
21551            p.kv_cache.seq_len()
21552        );
21553    }
21554
21555    #[test]
21556    fn confidence_matches_tokens_and_is_a_probability() {
21557        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
21558        p.sampler_config.temperature = 0.0;
21559        p.sampler_config.repetition_penalty = 1.0;
21560        let r = p.generate("abcd", 10, None, None).unwrap();
21561        assert_eq!(
21562            r.token_confidence.len(),
21563            r.token_ids.len(),
21564            "one confidence per emitted token"
21565        );
21566        for &c in &r.token_confidence {
21567            assert!((0.0..=1.0).contains(&c), "confidence out of [0,1]: {c}");
21568        }
21569        // top1_prob is a valid softmax probability.
21570        let logits = [1.0f32, 3.0, 0.5, 3.0];
21571        let p0 = top1_prob_t(&logits, 1, 1.0);
21572        let p1 = top1_prob_t(&logits, 3, 1.0);
21573        assert!((p0 - p1).abs() < 1e-6, "equal logits → equal prob");
21574        assert!(p0 > 0.0 && p0 < 1.0);
21575        // Calibration temperature > 1 softens an over-confident peak.
21576        let sharp = top1_prob_t(&logits, 1, 1.0);
21577        let soft = top1_prob_t(&logits, 1, 2.0);
21578        assert!(soft < sharp, "higher temperature lowers peak confidence");
21579    }
21580
21581    #[test]
21582    fn trace_is_opt_in_and_parallels_the_output() {
21583        // Off by default: the runtime is silent unless observation asked.
21584        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
21585        p.sampler_config.temperature = 0.0;
21586        p.sampler_config.repetition_penalty = 1.0;
21587        let r = p.generate("abcd", 10, None, None).unwrap();
21588        assert!(r.traces.is_empty(), "trace must be empty unless enabled");
21589
21590        // On: exactly one row per emitted token, aligned with the output.
21591        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
21592        p.sampler_config.temperature = 0.0;
21593        p.sampler_config.repetition_penalty = 1.0;
21594        p.set_trace(true);
21595        let r = p.generate("abcd", 10, None, None).unwrap();
21596        assert_eq!(r.traces.len(), r.token_ids.len(), "one trace row per token");
21597        for (i, tr) in r.traces.iter().enumerate() {
21598            assert_eq!(tr.t, i, "trace index is sequential");
21599            assert_eq!(tr.token_id, r.token_ids[i], "trace token_id matches output");
21600            assert_eq!(
21601                tr.confidence, r.token_confidence[i],
21602                "trace confidence matches the confidence channel"
21603            );
21604            // No dynamic router in this pipeline → no skill, no coherence.
21605            assert!(tr.active_skill.is_none() && tr.recon.is_none() && !tr.switched);
21606        }
21607    }
21608
21609    #[test]
21610    fn explain_prefill_logits_match_greedy_first_token() {
21611        // `cortiq explain` shows the next-token distribution from
21612        // prefill_next_logits; its argmax must equal what greedy generate
21613        // actually emits first — otherwise explain would lie.
21614        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
21615        p.sampler_config.temperature = 0.0;
21616        p.sampler_config.repetition_penalty = 1.0;
21617        let ids = p.tokenizer.encode("abcd");
21618        let logits = p.prefill_next_logits(&ids, None);
21619        let argmax = logits
21620            .iter()
21621            .enumerate()
21622            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
21623            .unwrap()
21624            .0 as u32;
21625        let r = p.generate("abcd", 1, None, None).unwrap();
21626        assert_eq!(
21627            argmax, r.token_ids[0],
21628            "explain preview must match greedy emit"
21629        );
21630    }
21631
21632    #[test]
21633    fn laguna_shared_expert_is_unconditionally_added() {
21634        let matrix = |values: Vec<f32>| QTensor::from_f32(values, 2, 2);
21635        let identity = || matrix(vec![1.0, 0.0, 0.0, 1.0]);
21636        let zero_dense = || DenseFfn {
21637            gate_proj: matrix(vec![0.0; 4]),
21638            up_proj: matrix(vec![0.0; 4]),
21639            down_proj: matrix(vec![0.0; 4]),
21640            act: Act::Silu,
21641            down_t: None,
21642            segs: Vec::new(),
21643        };
21644        let shared = DenseFfn {
21645            gate_proj: identity(),
21646            up_proj: identity(),
21647            down_proj: identity(),
21648            act: Act::Silu,
21649            down_t: None,
21650            segs: Vec::new(),
21651        };
21652        let x = [1.0, 2.0];
21653        let expected = dense_ffn(&shared, &x, None);
21654        let moe = MoeFfn {
21655            router: QTensor::from_f32(vec![0.0, 0.0], 1, 2),
21656            experts: vec![zero_dense()],
21657            top_k: 1,
21658            norm_topk_prob: true,
21659            router_sigmoid: true,
21660            sigmoid_denom_eps: 1e-6,
21661            expert_bias: None,
21662            routed_scaling: 1.0,
21663            route_tau: None,
21664            shared: Some((shared, None)),
21665            stats: std::cell::RefCell::new(Vec::new()),
21666            act_sq: std::cell::RefCell::new(Vec::new()),
21667            act_rows: std::cell::RefCell::new(Vec::new()),
21668            mask: None,
21669            per_expert_scale: None,
21670            router_input_norm: false,
21671            resonance: None,
21672            grown: Vec::new(),
21673        };
21674        let actual = moe_ffn_cpu(&moe, &x, &[0], &[0.0], 1.0, None);
21675        for (actual, expected) in actual.iter().zip(expected) {
21676            assert!((actual - expected).abs() < 1e-6);
21677        }
21678    }
21679
21680    /// A tiny MiMo-V2-shaped stack (the M3 fixture): layers [full, sliding,
21681    /// sliding, full]; 4 Q heads over 1 (full) / 2 (sliding) KV heads;
21682    /// head_dim 8 with 4-wide V heads; partial rotary 4 at θ 1e7 (full) /
21683    /// 1e4 (sliding); window 3; learned sinks on the sliding layers; layer
21684    /// 0 a dense FFN, layers 1..3 sigmoid-routed MoE with a selection bias
21685    /// (4 experts, top-2, renormalized, no shared expert). Geometry and
21686    /// sinks go through the same `set_attn_geometry` / `set_layer_sinks`
21687    /// the loader calls.
21688    fn mimo_test_pipeline() -> Pipeline {
21689        let (hs, inter, nh, hd, vd, vocab) = (16usize, 24usize, 4usize, 8usize, 4usize, 64usize);
21690        let kvh = [1usize, 2, 2, 1];
21691        let synth = |n: usize, salt: usize| -> Vec<f32> {
21692            (0..n)
21693                .map(|i| (((i * 31 + salt * 17 + 7) % 97) as f32 / 97.0 - 0.5) * 0.4)
21694                .collect()
21695        };
21696        let qt = |rows: usize, cols: usize, salt: usize| {
21697            QTensor::from_f32(synth(rows * cols, salt), rows, cols)
21698        };
21699        let dense = |inter: usize, salt: usize| DenseFfn {
21700            gate_proj: qt(inter, hs, salt),
21701            up_proj: qt(inter, hs, salt + 1),
21702            down_proj: qt(hs, inter, salt + 2),
21703            act: Act::Silu,
21704            down_t: None,
21705            segs: Vec::new(),
21706        };
21707        let layers: Vec<LayerWeights> = (0..4)
21708            .map(|li| LayerWeights {
21709                input_norm: vec![1.0; hs],
21710                post_norm: vec![1.0; hs],
21711                attn_out_norm: None,
21712                ffn_out_norm: None,
21713                layer_scale: None,
21714                ffn: if li == 0 {
21715                    FfnKind::Dense(dense(inter, 50))
21716                } else {
21717                    FfnKind::Moe(MoeFfn {
21718                        router: qt(4, hs, 60 + li),
21719                        experts: (0..4).map(|e| dense(8, 70 + li * 10 + e * 3)).collect(),
21720                        top_k: 2,
21721                        norm_topk_prob: true,
21722                        router_sigmoid: true,
21723                        sigmoid_denom_eps: 1e-6,
21724                        expert_bias: Some(vec![0.02, -0.03, 0.01, 0.0]),
21725                        routed_scaling: 1.0,
21726                        route_tau: None,
21727                        shared: None,
21728                        stats: std::cell::RefCell::new(Vec::new()),
21729                        act_sq: std::cell::RefCell::new(Vec::new()),
21730                        act_rows: std::cell::RefCell::new(Vec::new()),
21731                        mask: None,
21732                        per_expert_scale: None,
21733                        router_input_norm: false,
21734                        resonance: None,
21735                        grown: Vec::new(),
21736                    })
21737                },
21738                attn: AttnKind::Full {
21739                    wq: qt(nh * hd, hs, li * 10 + 1),
21740                    wk: qt(kvh[li] * hd, hs, li * 10 + 2),
21741                    wv: qt(kvh[li] * vd, hs, li * 10 + 3),
21742                    wo: qt(hs, nh * vd, li * 10 + 4),
21743                    q_norm: None,
21744                    k_norm: None,
21745                    output_gate: false,
21746                    softplus_gate: None,
21747                    bias: None,
21748                },
21749            })
21750            .collect();
21751        let mut p = Pipeline::new(
21752            Tokenizer::byte_level(),
21753            PipelineWeights {
21754                embed_tokens: qt(vocab, hs, 100),
21755                layers,
21756                lm_head: qt(vocab, hs, 200),
21757                final_norm: vec![1.0; hs],
21758            },
21759            hs,
21760            inter,
21761            nh,
21762            1, // header num_kv_heads (the full layers')
21763            hd,
21764            4,
21765            4,
21766            false,
21767            vocab,
21768            1e-6,
21769            1e7,
21770            NormStyle::Qwen,
21771            4096,
21772            SamplerConfig {
21773                seed: Some(7),
21774                ..Default::default()
21775            },
21776        );
21777        // Diagnostics stay off whatever the test environment exports.
21778        p.layer_dump = None;
21779        p.set_rotary(4, 1e7);
21780        p.sliding_layers = Some(vec![false, true, true, false]);
21781        p.swa = Some((3, usize::MAX));
21782        p.rotary_dim_local = Some(4);
21783        p.inv_freq_local = Some(std::sync::Arc::new(attention::rope_inv_freq(4, 1e4)));
21784        p.set_attn_geometry(Some(kvh.to_vec()), Some(vd)).unwrap();
21785        p.set_layer_sinks(1, vec![0.5, -1.0, 1.5, 0.0]).unwrap();
21786        p.set_layer_sinks(2, vec![-0.25, 2.0, 0.75, -1.5]).unwrap();
21787        p
21788    }
21789
21790    #[test]
21791    fn mimo_embedded_prompt_uses_rows_and_never_reuses_token_only_kv() {
21792        let mut p = mimo_test_pipeline();
21793        p.speculative = false;
21794        p.ignore_eos = true;
21795        p.sampler_config.temperature = 0.0;
21796        p.sampler_config.repetition_penalty = 1.0;
21797        let a = vec![3, 5, 7, 9, 11, 13];
21798        let b = vec![4, 8, 12, 16, 20, 24];
21799        let rows: Vec<_> = b.iter().flat_map(|&id| p.embed_id(id)).collect();
21800        let expected = p.generate_from_ids(&b, 8, None, None).unwrap().token_ids;
21801        // Same placeholder IDs as an earlier request are not a cache key
21802        // for different media. The actual rows, not a re-embedding of a,
21803        // must determine the continuation.
21804        let actual = p
21805            .generate_from_embeds(&a, &rows, 8, None, None)
21806            .unwrap()
21807            .token_ids;
21808        assert_eq!(actual, expected);
21809        assert!(p.kv_history.is_empty());
21810        let mut extended = a.clone();
21811        extended.push(17);
21812        let after_media = p
21813            .generate_from_ids(&extended, 8, None, None)
21814            .unwrap()
21815            .token_ids;
21816        p.reset_session();
21817        let fresh = p
21818            .generate_from_ids(&extended, 8, None, None)
21819            .unwrap()
21820            .token_ids;
21821        assert_eq!(after_media, fresh);
21822        assert!(
21823            p.generate_from_embeds(&a, &rows[..rows.len() - 1], 1, None, None)
21824                .is_err()
21825        );
21826        // Force a real token-prefix reuse opportunity into the media call.
21827        // Those labels are unchanged, but their embeddings now describe a
21828        // different source sequence and every KV row must be rebuilt.
21829        p.reset_session();
21830        p.generate_from_ids(&a, 1, None, None).unwrap();
21831        let mut media_ids = p.kv_history.clone();
21832        assert!(!media_ids.is_empty());
21833        media_ids.extend_from_slice(&[19, 21, 23]);
21834        let source_ids: Vec<_> = (0..media_ids.len()).map(|i| b[i % b.len()]).collect();
21835        let source_rows: Vec<_> = source_ids.iter().flat_map(|&id| p.embed_id(id)).collect();
21836        let mut oracle = mimo_test_pipeline();
21837        oracle.speculative = false;
21838        oracle.ignore_eos = true;
21839        oracle.sampler_config.temperature = 0.0;
21840        oracle.sampler_config.repetition_penalty = 1.0;
21841        let expected = oracle
21842            .generate_from_ids(&source_ids, 8, None, None)
21843            .unwrap()
21844            .token_ids;
21845        assert_eq!(
21846            p.generate_from_embeds(&media_ids, &source_rows, 8, None, None)
21847                .unwrap()
21848                .token_ids,
21849            expected
21850        );
21851        assert!(p.kv_history.is_empty());
21852        let mut bad = rows;
21853        bad[0] = f32::NAN;
21854        assert!(p.generate_from_embeds(&a, &bad, 1, None, None).is_err());
21855    }
21856
21857    fn f32_bits(v: &[f32]) -> Vec<u32> {
21858        v.iter().map(|x| x.to_bits()).collect()
21859    }
21860
21861    /// M3 acceptance: on the MiMo-shaped stack the decode walk (one
21862    /// position at a time through `forward_layers`) and the batched
21863    /// prefill (`prefill_batch_span`, whole prompt and split in two
21864    /// chunks) give bit-identical logits at all 12 positions — per-layer
21865    /// KV heads, narrow V, sinks, the window and the biased sigmoid MoE all
21866    /// agree across the two walks.
21867    #[test]
21868    fn mimo_shaped_decode_matches_prefill_batch_bitwise() {
21869        let mut p = mimo_test_pipeline();
21870        let kv: Vec<usize> = p.kv_cache.layers.iter().map(|l| l.num_kv_heads).collect();
21871        assert_eq!(kv, vec![1, 2, 2, 1]);
21872        assert!(p.kv_cache.layers[0].sinks.is_none() && p.kv_cache.layers[3].sinks.is_none());
21873        assert!(p.kv_cache.layers[1].sinks.is_some() && p.kv_cache.layers[2].sinks.is_some());
21874        let ids: Vec<u32> = (0..12u32).map(|i| (i * 7 + 3) % 64).collect();
21875        let hs = p.hidden_size;
21876        let mut decode = Vec::new();
21877        for (pos, &id) in ids.iter().enumerate() {
21878            let e = p.embed_single(id);
21879            let h = p.forward_layers(&e, pos, None);
21880            decode.push(p.logits_from_hidden(&h));
21881        }
21882        for l in &p.kv_cache.layers {
21883            assert_eq!(l.seq_len, 12);
21884            // V rows are padded to head_dim inside the cache.
21885            assert_eq!(l.head_values(0).len(), 12 * 8);
21886        }
21887        assert!(decode.iter().flatten().all(|v| v.is_finite()));
21888
21889        p.clear_sequence_state();
21890        let hb = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
21891        for pos in 0..ids.len() {
21892            let lg = p.logits_from_hidden(&hb[pos * hs..(pos + 1) * hs]);
21893            assert_eq!(
21894                f32_bits(&decode[pos]),
21895                f32_bits(&lg),
21896                "whole prompt, pos {pos}"
21897            );
21898        }
21899
21900        p.clear_sequence_state();
21901        let a = p.prefill_batch_span(PrefillIn::Ids(&ids[..5]), 0, None, 0, p.num_layers);
21902        let b = p.prefill_batch_span(PrefillIn::Ids(&ids[5..]), 5, None, 0, p.num_layers);
21903        for pos in 0..ids.len() {
21904            let row = if pos < 5 {
21905                &a[pos * hs..(pos + 1) * hs]
21906            } else {
21907                &b[(pos - 5) * hs..(pos - 4) * hs]
21908            };
21909            let lg = p.logits_from_hidden(row);
21910            assert_eq!(
21911                f32_bits(&decode[pos]),
21912                f32_bits(&lg),
21913                "two chunks, pos {pos}"
21914            );
21915        }
21916
21917        // The fixture is not degenerate: the sinks and the window each
21918        // change the answer.
21919        let last = |p: &mut Pipeline| {
21920            p.clear_sequence_state();
21921            let hb = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
21922            p.logits_from_hidden(&hb[11 * hs..12 * hs])
21923        };
21924        let base = last(&mut p);
21925        let mut no_sinks = mimo_test_pipeline();
21926        for l in &mut no_sinks.kv_cache.layers {
21927            l.sinks = None;
21928        }
21929        assert_ne!(
21930            f32_bits(&last(&mut no_sinks)),
21931            f32_bits(&base),
21932            "sinks are live"
21933        );
21934        let mut wide = mimo_test_pipeline();
21935        wide.swa = Some((64, usize::MAX));
21936        assert_ne!(
21937            f32_bits(&last(&mut wide)),
21938            f32_bits(&base),
21939            "window is live"
21940        );
21941
21942        // Generation runs end to end on the same stack.
21943        p.clear_sequence_state();
21944        p.ignore_eos = true;
21945        let r = p.generate_from_ids(&ids, 4, None, None).unwrap();
21946        assert_eq!(r.token_ids.len(), 4);
21947    }
21948
21949    /// A Spark-X2.5-shaped stack: layers 0..3 slide (window 6), layer 3
21950    /// is global, every attention carries the head-wise sigmoid g_proj gate.
21951    fn spark_test_pipeline(trim: Option<(usize, usize)>) -> Pipeline {
21952        let (hs, nh) = (16usize, 4usize);
21953        let mut p = create_test_pipeline(hs, 24, nh, 2, 8, 4, 64);
21954        p.layer_dump = None;
21955        p.swa = Some((6, 4));
21956        p.proj_gate_sigmoid = true;
21957        for (li, lw) in p.weights.layers.iter_mut().enumerate() {
21958            if let AttnKind::Full { softplus_gate, .. } = &mut lw.attn {
21959                let g: Vec<f32> = (0..nh * hs)
21960                    .map(|i| (((i * 29 + li * 7) % 83) as f32 / 83.0 - 0.5) * 0.8)
21961                    .collect();
21962                *softplus_gate = Some((QTensor::from_f32(g, nh, hs), true));
21963            }
21964        }
21965        p.swa_trim = trim;
21966        p
21967    }
21968
21969    /// Trimming the sliding tails changes nothing but memory: the same
21970    /// prompt in uneven chunks, a decode walk, and fused pairs with a
21971    /// 2-row rollback give bit-identical hiddens with and without it,
21972    /// while the trimmed sliding layers stay bounded and the global layer
21973    /// keeps every row.
21974    #[test]
21975    fn swa_trim_pipeline_matches_untrimmed_bitwise() {
21976        let mut a = spark_test_pipeline(None);
21977        let mut b = spark_test_pipeline(Some((2, 4)));
21978        assert_eq!(
21979            (0..4).map(|li| b.layer_window(li)).collect::<Vec<_>>(),
21980            vec![Some(6), Some(6), Some(6), None]
21981        );
21982        let ids: Vec<u32> = (0..41u32).map(|i| (i * 11 + 5) % 64).collect();
21983        let mut pos = 0usize;
21984        for &n in [5usize, 13, 7, 16].iter().cycle() {
21985            if pos >= ids.len() {
21986                break;
21987            }
21988            let end = (pos + n).min(ids.len());
21989            let ha = a.prefill_batch_span(PrefillIn::Ids(&ids[pos..end]), pos, None, 0, 4);
21990            let hb = b.prefill_batch_span(PrefillIn::Ids(&ids[pos..end]), pos, None, 0, 4);
21991            assert_eq!(f32_bits(&ha), f32_bits(&hb), "prefill chunk at {pos}");
21992            pos = end;
21993        }
21994        for _ in 0..23 {
21995            let e = a.embed_single(((pos * 7) % 64) as u32);
21996            let ha = a.forward_layers(&e, pos, None);
21997            let hb = b.forward_layers(&e, pos, None);
21998            assert_eq!(f32_bits(&ha), f32_bits(&hb), "decode at {pos}");
21999            for li in 0..3 {
22000                assert!(b.kv_cache.layers[li].seq_len <= 12, "layer {li} bounded");
22001            }
22002            pos += 1;
22003        }
22004        for round in 0..9 {
22005            let (e1, e2) = (a.embed_single(round * 3 + 1), a.embed_single(round * 5 + 2));
22006            let (a1, a2) = a.forward_pair(&e1, &e2, pos);
22007            let (b1, b2) = b.forward_pair(&e1, &e2, pos);
22008            assert_eq!(f32_bits(&a1), f32_bits(&b1), "pair lane 1 round {round}");
22009            assert_eq!(f32_bits(&a2), f32_bits(&b2), "pair lane 2 round {round}");
22010            if round % 2 == 1 {
22011                // A rejected draft: both lanes roll back.
22012                for p in [&mut a, &mut b] {
22013                    for l in &mut p.kv_cache.layers {
22014                        l.truncate_last(2);
22015                    }
22016                }
22017            } else {
22018                pos += 2;
22019            }
22020        }
22021        let e = a.embed_single(9);
22022        let (ha, hb) = (
22023            a.forward_layers(&e, pos, None),
22024            b.forward_layers(&e, pos, None),
22025        );
22026        assert_eq!(f32_bits(&ha), f32_bits(&hb), "after the pairs");
22027        for li in 0..3 {
22028            let (la, lb) = (&a.kv_cache.layers[li], &b.kv_cache.layers[li]);
22029            assert!(lb.base() > 0, "layer {li} trimmed");
22030            assert_eq!(la.base(), 0);
22031            assert_eq!(lb.pos_len(), la.seq_len);
22032            assert_eq!(lb.head_keys(0), &la.head_keys(0)[lb.base() * 8..]);
22033        }
22034        let (ga, gb) = (&a.kv_cache.layers[3], &b.kv_cache.layers[3]);
22035        assert_eq!(
22036            (gb.base(), gb.seq_len),
22037            (0, ga.seq_len),
22038            "the global layer keeps all"
22039        );
22040        assert_eq!(b.kv_cache.seq_len(), a.kv_cache.seq_len());
22041        assert!(b.kv_cache.total_memory_bytes() < a.kv_cache.total_memory_bytes());
22042    }
22043
22044    /// The network split's KvFetch hand-off on a trimmed stack: every
22045    /// layer shipped over the wire mid-sequence (the sliding ones as
22046    /// `FullTail`) into a fresh pipeline that never ran a position, which
22047    /// then decodes on — bit for bit what the untrimmed pipeline decodes.
22048    #[test]
22049    fn swa_trim_wire_handoff_continues_bitwise() {
22050        let mut a = spark_test_pipeline(None);
22051        let mut b = spark_test_pipeline(Some((2, 4)));
22052        let ids: Vec<u32> = (0..29u32).map(|i| (i * 13 + 7) % 64).collect();
22053        let ha = a.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, 4);
22054        let hb = b.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, 4);
22055        assert_eq!(f32_bits(&ha), f32_bits(&hb));
22056        let mut pos = ids.len();
22057        for _ in 0..5 {
22058            let e = a.embed_single(((pos * 5) % 64) as u32);
22059            assert_eq!(
22060                f32_bits(&a.forward_layers(&e, pos, None)),
22061                f32_bits(&b.forward_layers(&e, pos, None))
22062            );
22063            pos += 1;
22064        }
22065        let mut c = spark_test_pipeline(Some((2, 4)));
22066        for li in 0..4 {
22067            let bytes = b.kv_cache.layers[li].export_wire(false).unwrap();
22068            c.kv_cache.layers[li].import_wire(&bytes).unwrap();
22069        }
22070        assert!(c.kv_cache.layers[0].base() > 0, "a tail travelled");
22071        assert_eq!(c.kv_cache.seq_len(), pos);
22072        for step in 0..17 {
22073            let e = a.embed_single(((pos * 3 + 1) % 64) as u32);
22074            let ha = a.forward_layers(&e, pos, None);
22075            let hc = c.forward_layers(&e, pos, None);
22076            assert_eq!(
22077                f32_bits(&ha),
22078                f32_bits(&hc),
22079                "after the hand-off, step {step}"
22080            );
22081            pos += 1;
22082        }
22083        assert!(c.kv_cache.layers[0].seq_len <= 12, "the receiver trims on");
22084    }
22085
22086    /// A synthetic MiMo draft stack of `n` layers for `mimo_test_pipeline`
22087    /// (the SWA geometry of its sliding layers: 2 KV heads, head 8 / V 4).
22088    fn mimo_test_mtp(n: usize, gain: f32) -> mimo_mtp::MimoMtp {
22089        let (hs, inter, nh, hd, vd, nkv) = (16usize, 24usize, 4usize, 8usize, 4usize, 2usize);
22090        let synth = |len: usize, salt: usize| -> Vec<f32> {
22091            (0..len)
22092                .map(|i| (((i * 37 + salt * 13 + 3) % 89) as f32 / 89.0 - 0.5) * 0.6 * gain)
22093                .collect()
22094        };
22095        let qt = |rows: usize, cols: usize, salt: usize| {
22096            QTensor::from_f32(synth(rows * cols, salt), rows, cols)
22097        };
22098        let layers = (0..n)
22099            .map(|k| {
22100                let s = 500 + k * 40;
22101                let mut kv = crate::kv_cache::LayerKvCache::new(nkv, hd);
22102                kv.sinks = Some(vec![0.3, -0.7, 1.1, 0.0]);
22103                MtpModule {
22104                    enorm: vec![1.0; hs],
22105                    hnorm: vec![1.0; hs],
22106                    eh_proj: qt(hs, 2 * hs, s),
22107                    layer: LayerWeights {
22108                        input_norm: vec![1.0; hs],
22109                        post_norm: vec![1.0; hs],
22110                        attn_out_norm: None,
22111                        ffn_out_norm: None,
22112                        layer_scale: None,
22113                        attn: AttnKind::Full {
22114                            wq: qt(nh * hd, hs, s + 1),
22115                            wk: qt(nkv * hd, hs, s + 2),
22116                            wv: qt(nkv * vd, hs, s + 3),
22117                            wo: qt(hs, nh * vd, s + 4),
22118                            q_norm: None,
22119                            k_norm: None,
22120                            output_gate: false,
22121                            softplus_gate: None,
22122                            bias: None,
22123                        },
22124                        ffn: FfnKind::Dense(DenseFfn {
22125                            gate_proj: qt(inter, hs, s + 5),
22126                            up_proj: qt(inter, hs, s + 6),
22127                            down_proj: qt(hs, inter, s + 7),
22128                            act: Act::Silu,
22129                            down_t: None,
22130                            segs: Vec::new(),
22131                        }),
22132                    },
22133                    final_norm: vec![1.0; hs],
22134                    kv,
22135                }
22136            })
22137            .collect();
22138        mimo_mtp::MimoMtp::from_layers(layers)
22139    }
22140
22141    fn mimo_greedy(p: &mut Pipeline, ids: &[u32], n: usize, spec: bool) -> GenerateResult {
22142        p.clear_sequence_state();
22143        p.speculative = spec;
22144        p.ignore_eos = true;
22145        p.sampler_config.temperature = 0.0;
22146        p.generate_from_ids(ids, n, None, None).unwrap()
22147    }
22148
22149    /// The draft stack's incremental rounds (a few rows per layer, last
22150    /// round's provisional rows dropped) give exactly the teacher-forced
22151    /// table of one causal pass per layer over the whole sequence — the
22152    /// table `tools/mimo_ref.py mtp` computes for variant A: layer k, row
22153    /// j reads (x[j+k+1], norm(h_j)) at RoPE position j.
22154    #[test]
22155    fn mimo_mtp_incremental_rounds_equal_the_teacher_forced_table() {
22156        // Both readings of the backbone hidden: pre-final-norm (default)
22157        // and post-final-norm (`CMF_MIMO_MTP_HIDDEN=post`).
22158        for post in [false, true] {
22159            let mut p = mimo_test_pipeline();
22160            // A non-trivial final norm, so the two readings differ.
22161            p.weights.final_norm = (0..p.hidden_size).map(|i| 0.5 + 0.1 * i as f32).collect();
22162            let mut st0 = mimo_test_mtp(3, 1.0);
22163            st0.post_norm_hidden = post;
22164            p.mimo_mtp = Some(st0);
22165            let ids: Vec<u32> = (0..14u32).map(|i| (i * 11 + 5) % 64).collect();
22166            let hs = p.hidden_size;
22167            let hb = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
22168            p.mimo_note_rows(&hb, 0);
22169            let mut st = p.mimo_mtp.take().unwrap();
22170            // Incremental: one round per t through the decode path (later
22171            // tokens from `ids`, the probe's teacher forcing).
22172            let k = 3;
22173            let mut inc = Vec::new();
22174            for t in 0..ids.len() - k - 1 {
22175                inc.push(p.mimo_mtp_draft(&mut st, t, &ids, k));
22176            }
22177            // Reference: per layer, ONE batched causal pass over all rows
22178            // with fresh caches.
22179            let s = ids.len();
22180            let mut reference = vec![vec![0u32; k]; s - k - 1];
22181            let mut fresh = mimo_test_mtp(3, 1.0);
22182            for (layer, m) in fresh.layers.iter_mut().enumerate() {
22183                let n = s - layer - 1;
22184                let mut cats = vec![0.0f32; n * 2 * hs];
22185                for j in 0..n {
22186                    let e = p.embed_single(ids[j + layer + 1]);
22187                    let raw = &hb[j * hs..(j + 1) * hs];
22188                    let g = if post {
22189                        inference::rms_norm(raw, &p.weights.final_norm, p.rms_eps, p.norm_style)
22190                    } else {
22191                        raw.to_vec()
22192                    };
22193                    let (ce, ch) = cats[j * 2 * hs..(j + 1) * 2 * hs].split_at_mut(hs);
22194                    inference::rms_norm_into(&e, &m.enorm, p.rms_eps, p.norm_style, ce);
22195                    inference::rms_norm_into(&g, &m.hnorm, p.rms_eps, p.norm_style, ch);
22196                }
22197                let mut x = vec![0.0f32; n * hs];
22198                m.eh_proj.matmat(&cats, n, &mut x, None);
22199                p.mimo_mtp_block(m, &mut x, n, 0);
22200                for (t, row) in reference.iter_mut().enumerate() {
22201                    let y = inference::rms_norm(
22202                        &x[t * hs..(t + 1) * hs],
22203                        &m.final_norm,
22204                        p.rms_eps,
22205                        p.norm_style,
22206                    );
22207                    row[layer] = sampler::argmax(&p.lm_head_forward(&y));
22208                }
22209            }
22210            assert_eq!(inc, reference, "post_norm_hidden = {post}");
22211            // Not a degenerate table: the drafts vary.
22212            let distinct: std::collections::HashSet<u32> = inc.iter().flatten().copied().collect();
22213            assert!(distinct.len() > 3, "{inc:?}");
22214            // Each layer's cache ends holding rows up to the last round start.
22215            let last_t = ids.len() - k - 2;
22216            for m in &st.layers {
22217                assert_eq!(m.kv.seq_len, last_t + 1);
22218            }
22219        }
22220    }
22221
22222    /// Greedy with the MiMo draft stack is the plain greedy stream, token
22223    /// for token — with the real draft layers (low acceptance) and with a
22224    /// drafter that is right most of the time (exercises accepted prefixes
22225    /// of every length, the KV truncation of the rejected rows and the
22226    /// logits hand-off to the loop top), under the default repetition
22227    /// penalty.
22228    #[test]
22229    fn mimo_speculative_greedy_equals_plain_greedy() {
22230        unsafe { std::env::set_var("CMF_GPU_WGPU_GRAPH", "0") };
22231        let ids: Vec<u32> = (0..9u32).map(|i| (i * 7 + 3) % 64).collect();
22232        let n = 24;
22233        let mut p = mimo_test_pipeline();
22234        let plain = mimo_greedy(&mut p, &ids, n, false);
22235        assert_eq!(plain.mtp_drafted, 0);
22236        assert_eq!(plain.token_ids.len(), n);
22237        let plain_kv = p.kv_cache.layers[0].seq_len;
22238
22239        // Real draft layers.
22240        p.mimo_mtp = Some(mimo_test_mtp(3, 1.0));
22241        let spec = mimo_greedy(&mut p, &ids, n, true);
22242        assert!(spec.mtp_drafted > 0, "the round must draft");
22243        assert_eq!(spec.token_ids, plain.token_ids);
22244        assert_eq!(p.kv_cache.layers[0].seq_len, plain_kv);
22245
22246        // A drafter reading the true continuation with every fifth token
22247        // wrong: accepted prefixes of 0..=3 all occur.
22248        let mut truth: Vec<u32> = ids.clone();
22249        truth.extend(&plain.token_ids);
22250        let mut noisy = truth.clone();
22251        for (i, t) in noisy.iter_mut().enumerate() {
22252            if i % 5 == 0 {
22253                *t = (*t + 1) % 64;
22254            }
22255        }
22256        let mut st = mimo_test_mtp(3, 1.0);
22257        st.draft_override = Some(noisy);
22258        p.mimo_mtp = Some(st);
22259        let spec = mimo_greedy(&mut p, &ids, n, true);
22260        assert_eq!(spec.token_ids, plain.token_ids);
22261        assert_eq!(p.kv_cache.layers[0].seq_len, plain_kv);
22262        let stats = p.mimo_mtp.as_ref().unwrap().stats.clone();
22263        assert_eq!(stats.accepted as usize, spec.mtp_accepted);
22264        assert!(spec.mtp_accepted > 0 && spec.mtp_accepted < spec.mtp_drafted);
22265        assert!(
22266            stats.accept_hist.iter().filter(|&&c| c > 0).count() >= 3,
22267            "{:?}",
22268            stats.accept_hist
22269        );
22270        assert!(stats.tokens_per_round() > 1.5, "{}", stats.line());
22271
22272        // A perfect drafter: every draft accepted, rounds of K+1 tokens,
22273        // and the budget is never overrun.
22274        let mut st = mimo_test_mtp(3, 1.0);
22275        st.draft_override = Some(truth);
22276        p.mimo_mtp = Some(st);
22277        let spec = mimo_greedy(&mut p, &ids, n, true);
22278        assert_eq!(spec.token_ids, plain.token_ids);
22279        assert_eq!(spec.mtp_accepted, spec.mtp_drafted);
22280        assert_eq!(p.kv_cache.layers[0].seq_len, plain_kv);
22281
22282        // CMF_MTP=0 path: the stack is attached but idle.
22283        let off = mimo_greedy(&mut p, &ids, n, false);
22284        assert_eq!(off.token_ids, plain.token_ids);
22285        assert_eq!(off.mtp_drafted, 0);
22286    }
22287
22288    /// The wgpu graphs carry MiMo-V2's attention per layer (KV heads,
22289    /// narrow V, sinks, windows, two RoPE tables): no attention-level
22290    /// decline for it any more, and the geometry each layer hands the
22291    /// graph is exactly what the CPU attention reads for that layer. The
22292    /// descriptive reasons stay (the Metal graphs and the q1 dropin still
22293    /// decline on them), and what the per-layer geometry cannot express
22294    /// keeps a named wgpu decline.
22295
22296    #[test]
22297    fn mimo_shaped_model_rides_the_wgpu_graph_geometry() {
22298        let p = mimo_test_pipeline();
22299        assert_eq!(
22300            p.graph_attn_decline_reason(),
22301            Some("per-layer KV head counts")
22302        );
22303        assert_eq!(p.wgpu_graph_attn_decline(), None);
22304        let g0 = p.graph_attn_geom(0).expect("full layer geometry");
22305        assert_eq!(
22306            (g0.nkv, g0.dv, g0.rd, g0.window, g0.sink.is_some()),
22307            (1, 4, 4, None, false)
22308        );
22309        assert_eq!(g0.invf, p.inv_freq.as_slice());
22310        let g1 = p.graph_attn_geom(1).expect("sliding layer geometry");
22311        assert_eq!((g1.nkv, g1.dv, g1.rd, g1.window), (2, 4, 4, Some(3)));
22312        assert_eq!(g1.sink, Some(&[0.5f32, -1.0, 1.5, 0.0][..]));
22313        assert_eq!(g1.invf, p.inv_freq_local.as_ref().unwrap().as_slice());
22314        assert_ne!(g0.invf, g1.invf, "two RoPE tables");
22315        let g3 = p.graph_attn_geom(3).expect("full layer geometry");
22316        assert_eq!((g3.nkv, g3.window, g3.sink.is_some()), (1, None, false));
22317
22318        // No wgpu device in this process: the builders run and decline on
22319        // the (f32, unmapped) experts — never with an attention line.
22320        let emb = p.embed_single(3);
22321        let mut lg = Vec::new();
22322        assert!(
22323            p.try_token_graph_wgpu_steps(&emb, 0, &mut lg, 1, None, None, 0, p.num_layers)
22324                .is_none()
22325        );
22326        let mut hid = emb.clone();
22327        assert_eq!(
22328            p.try_batch_graph_wgpu(&mut hid, &[0], 1, None),
22329            crate::gpu::BatchGraphOutcome::Declined
22330        );
22331        assert_eq!(hid, emb, "a declined batch graph leaves the rows untouched");
22332        assert!(p.try_multi_burst(3, 0, 4).is_none());
22333        assert!(
22334            p.graph_declines().is_empty(),
22335            "no attention decline logged: {:?}",
22336            p.graph_declines()
22337        );
22338        // (No assertion on graph_prefill_preferred: with no attention
22339        // decline it follows the device — a test process that brought a
22340        // wgpu adapter up routes this resident MoE through the graph.)
22341
22342        let plain = || create_test_pipeline(8, 16, 2, 1, 4, 2, 32);
22343        assert_eq!(plain().graph_attn_decline_reason(), None);
22344        assert_eq!(plain().wgpu_graph_attn_decline(), None);
22345        assert!(
22346            plain().graph_attn_geom(0).is_none(),
22347            "uniform models keep the historical arms"
22348        );
22349        let mut q = plain();
22350        q.set_layer_sinks(1, vec![0.25, -0.25]).unwrap();
22351        assert_eq!(
22352            q.graph_attn_decline_reason(),
22353            Some("learned attention sinks")
22354        );
22355        assert_eq!(
22356            q.graph_attn_geom(1).unwrap().sink,
22357            Some(&[0.25f32, -0.25][..])
22358        );
22359        let mut q = plain();
22360        q.set_attn_geometry(None, Some(2)).unwrap();
22361        assert_eq!(
22362            q.graph_attn_decline_reason(),
22363            Some("V heads narrower than Q/K heads")
22364        );
22365        assert_eq!(q.graph_attn_geom(0).unwrap().dv, 2);
22366        let mut q = plain();
22367        q.sliding_layers = Some(vec![true, false]);
22368        q.swa = Some((4, usize::MAX));
22369        assert_eq!(q.graph_attn_decline_reason(), Some("sliding-window layers"));
22370        assert_eq!(q.graph_attn_geom(0).unwrap().window, Some(4));
22371        assert_eq!(q.graph_attn_geom(1).unwrap().window, None);
22372
22373        // YaRN's post-rotation amplitude factor rides the per-layer graph
22374        // geometry. It is intentionally not an angular scale folded into
22375        // `invf`: the WGPU RoPE kernel receives it separately.
22376        let mut q = mimo_test_pipeline();
22377        q.rope_scale = 2.0;
22378        q.rope_scale_local = 1.25;
22379        assert_eq!(q.wgpu_graph_attn_decline(), None);
22380        assert_eq!(q.graph_attn_geom(0).unwrap().rope_scale, 2.0);
22381        assert_eq!(q.graph_attn_geom(1).unwrap().rope_scale, 1.25);
22382
22383        // A uniform YaRN model cannot yet pass the factor through the fused
22384        // RKV arm; decline safely instead of producing scale-1 output.
22385        let mut q = plain();
22386        q.rope_scale = 2.0;
22387        assert_eq!(
22388            q.wgpu_graph_attn_decline(),
22389            Some("scaled RoPE without per-layer geometry")
22390        );
22391    }
22392
22393    /// The native q1 attention path has a narrower contract than the WGPU
22394    /// per-layer geometry graph, but it must not discard the exact Flint
22395    /// combination of uniform GQA + sliding windows + learned sinks.  The
22396    /// actual Metal kernel is covered independently with a direct sink
22397    /// softmax test; this is the pure admission test, with no model run.
22398    #[cfg(target_os = "macos")]
22399    #[test]
22400    fn metal_swa_admits_uniform_learned_sinks_for_q1_decode() {
22401        // rd=64 is in the native rope kernel's lane-pair contract; the
22402        // synthetic stack otherwise has the same uniform K/V geometry that
22403        // Flint needs for q1 (unlike the deliberately ragged MiMo fixture).
22404        let mut p = create_test_pipeline(256, 512, 4, 1, 64, 2, 64);
22405        p.swa = Some((16, usize::MAX));
22406        p.sliding_layers = Some(vec![true, true]);
22407        p.set_layer_sinks(0, vec![0.25, -0.5, 1.0, -1.25]).unwrap();
22408        p.set_layer_sinks(1, vec![-0.75, 0.5, 0.0, 1.5]).unwrap();
22409
22410        assert_eq!(
22411            p.graph_attn_decline_reason(),
22412            Some("learned attention sinks")
22413        );
22414        let swa_graph = p.metal_graph_swa();
22415        assert!(swa_graph, "uniform sliding sink geometry must reach q1");
22416        let native_sink_attend = p.graph_attn_decline_reason() == Some("learned attention sinks")
22417            && (swa_graph || (p.swa.is_none() && p.sliding_layers.is_none()));
22418        assert!(
22419            native_sink_attend,
22420            "the q1 sink admission must follow the SWA door"
22421        );
22422        // The batched chunk softmax has no value-less sink column, so its
22423        // separate admission gate must keep this prompt on the host path.
22424        assert!(p.kv_cache.layers.iter().any(|l| l.sinks.is_some()));
22425    }
22426
22427    #[test]
22428    fn mimo_verify_rewind_preserves_lagging_host_caches() {
22429        let mut p = mimo_test_pipeline();
22430        for (li, layer) in p.kv_cache.layers.iter_mut().enumerate() {
22431            let row = vec![0.0; layer.num_kv_heads * layer.head_dim];
22432            for _ in 0..if li == 0 { 2 } else { 12 } {
22433                layer.append(&row, &row, &[]);
22434            }
22435        }
22436        p.mimo_verify_rewind(9).unwrap();
22437        assert_eq!(p.kv_cache.layers[0].seq_len, 2);
22438        for layer in &p.kv_cache.layers[1..] {
22439            assert_eq!(layer.seq_len, 9);
22440        }
22441    }
22442
22443    /// CMF_LAYER_DUMP: the decode walk and the batched prefill both write
22444    /// every (position, layer) hidden, the two sets agree byte for byte,
22445    /// and the last layer's file is the stack output.
22446    #[test]
22447    fn layer_dump_covers_every_position_and_layer_on_both_walks() {
22448        let dir = std::env::temp_dir().join(format!("cmf-layer-dump-{}", std::process::id()));
22449        let _ = std::fs::remove_dir_all(&dir);
22450        let mut p = mimo_test_pipeline();
22451        let hs = p.hidden_size;
22452        let ids = [5u32, 9, 11, 2, 40];
22453        p.layer_dump = Some(dir.join("decode"));
22454        for (pos, &id) in ids.iter().enumerate() {
22455            let e = p.embed_single(id);
22456            let _ = p.forward_layers(&e, pos, None);
22457        }
22458        p.clear_sequence_state();
22459        p.layer_dump = Some(dir.join("prefill"));
22460        let hb = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
22461        for pos in 0..ids.len() {
22462            for li in 0..p.num_layers {
22463                let name = format!("p{pos:06}_l{li:02}.f32");
22464                let a = std::fs::read(dir.join("decode").join(&name)).unwrap();
22465                let b = std::fs::read(dir.join("prefill").join(&name)).unwrap();
22466                assert_eq!(a.len(), hs * 4, "{name}");
22467                assert_eq!(a, b, "{name}");
22468            }
22469        }
22470        let last = std::fs::read(dir.join("prefill").join("p000004_l03.f32")).unwrap();
22471        let vals: Vec<f32> = last
22472            .chunks(4)
22473            .map(|c| f32::from_le_bytes(c.try_into().unwrap()))
22474            .collect();
22475        assert_eq!(f32_bits(&vals), f32_bits(&hb[4 * hs..5 * hs]));
22476        let _ = std::fs::remove_dir_all(&dir);
22477    }
22478
22479    #[test]
22480    fn attn_geometry_and_sinks_are_validated() {
22481        let mut p = create_test_pipeline(8, 16, 4, 2, 4, 2, 32);
22482        assert!(
22483            p.set_attn_geometry(Some(vec![2]), None).is_err(),
22484            "one entry per layer"
22485        );
22486        assert!(
22487            p.set_attn_geometry(Some(vec![2, 3]), None).is_err(),
22488            "3 does not divide 4"
22489        );
22490        assert!(p.set_attn_geometry(Some(vec![2, 0]), None).is_err());
22491        assert!(p.set_attn_geometry(None, Some(0)).is_err());
22492        assert!(
22493            p.set_attn_geometry(None, Some(5)).is_err(),
22494            "V wider than the head"
22495        );
22496        p.set_attn_geometry(None, Some(4)).unwrap();
22497        assert_eq!(
22498            p.v_head_dim, None,
22499            "v_head_dim == head_dim is the uniform case"
22500        );
22501        p.set_layer_sinks(1, vec![0.1; 4]).unwrap();
22502        p.set_attn_geometry(Some(vec![1, 4]), None).unwrap();
22503        assert_eq!(p.kv_cache.layers[0].num_kv_heads, 1);
22504        assert_eq!(p.kv_cache.layers[1].num_kv_heads, 4);
22505        assert!(
22506            p.kv_cache.layers[1].sinks.is_some(),
22507            "a reshape keeps the layer's sinks"
22508        );
22509        assert_eq!(p.layer_geom(1).0, 4);
22510        assert!(
22511            p.set_layer_sinks(0, vec![0.0; 3]).is_err(),
22512            "one sink per Q head"
22513        );
22514        assert!(p.set_layer_sinks(7, vec![0.0; 4]).is_err());
22515        assert!(p.set_layer_sinks(0, vec![f32::NAN, 0.0, 0.0, 0.0]).is_err());
22516    }
22517
22518    /// The O(1) Nyström state replaces a plain full-context softmax; it
22519    /// must never be armed on a sliding, sink or narrow-V layer.
22520    #[test]
22521    fn o1_is_never_armed_on_sink_window_or_narrow_v_layers() {
22522        let cfg = || {
22523            Some(crate::nystrom::O1Cfg {
22524                layers: crate::nystrom::O1Layers::All,
22525                m: 4,
22526                w: 8,
22527                sink: 2,
22528                rect: crate::nystrom::O1Rect::Aggregate,
22529            })
22530        };
22531        let mut p = mimo_test_pipeline();
22532        p.set_o1(cfg());
22533        assert!(!p.o1_active(), "every MiMo-shaped layer is ineligible");
22534        let mut q = create_test_pipeline(8, 16, 2, 1, 4, 3, 64);
22535        q.set_layer_sinks(1, vec![0.0, 0.0]).unwrap();
22536        q.sliding_layers = Some(vec![false, false, true]);
22537        q.swa = Some((4, usize::MAX));
22538        q.set_o1(cfg());
22539        assert_eq!(q.o1_flags, vec![true, false, false]);
22540    }
22541
22542    #[test]
22543    fn o1_batch_transition_publishes_one_epoch_before_serial_handoff() {
22544        const B: usize = 19;
22545        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
22546        p.set_o1(Some(crate::nystrom::O1Cfg {
22547            layers: crate::nystrom::O1Layers::All,
22548            m: 4,
22549            w: 8,
22550            sink: 2,
22551            rect: crate::nystrom::O1Rect::Aggregate,
22552        }));
22553        p.o1_begin_with_prefix(Some(B));
22554        let ids: Vec<u32> = (0..B as u32).collect();
22555        let _ = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
22556
22557        assert_eq!(p.o1_epoch, 1, "all layers publish one completed transition");
22558        assert!(p.kv_cache.layers.iter().all(|l| l.o1_sealed()));
22559        let next = p.embed_single(B as u32);
22560        let _ = p.forward_layers(&next, B, None);
22561        assert_eq!(p.o1_epoch, 1, "sealed handoff must not republish the epoch");
22562    }
22563
22564    #[test]
22565    fn o1_pair_transition_commits_scratch_before_epoch_publication() {
22566        const B: usize = 19;
22567        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
22568        // Keep a real recurrent layer ahead of the Full O(1) layer so the
22569        // pair test observes the GDN lane-2 scratch swap at the same
22570        // boundary, rather than only exercising an artificial scratch vec.
22571        let gdn_cfg = crate::linear_core::GdnCfg {
22572            num_v_heads: 2,
22573            num_k_heads: 1,
22574            key_head_dim: 2,
22575            value_head_dim: 4,
22576            conv_kernel: 3,
22577            hidden_size: 8,
22578            rms_eps: 1e-6,
22579            output_gate_sigmoid: false,
22580        };
22581        let synth = |n: usize, salt: usize| -> Vec<f32> {
22582            (0..n)
22583                .map(|i| (((i * 13 + salt * 7) % 97) as f32 / 97.0 - 0.5) * 0.4)
22584                .collect()
22585        };
22586        let qt = |rows: usize, cols: usize, salt: usize| {
22587            crate::qtensor::QTensor::from_f32(synth(rows * cols, salt), rows, cols)
22588        };
22589        let c_dim = gdn_cfg.conv_dim();
22590        let vd = gdn_cfg.num_v_heads * gdn_cfg.value_head_dim;
22591        p.weights.layers[0].attn = AttnKind::LinearGdn(crate::linear_core::GdnWeights {
22592            in_proj_qkv: qt(c_dim, 8, 1),
22593            in_proj_z: qt(vd, 8, 2),
22594            in_proj_a: qt(gdn_cfg.num_v_heads, 8, 3),
22595            in_proj_b: qt(gdn_cfg.num_v_heads, 8, 4),
22596            conv1d: synth(c_dim * gdn_cfg.conv_kernel, 5),
22597            a_log: vec![0.2, 0.5],
22598            dt_bias: synth(gdn_cfg.num_v_heads, 6),
22599            norm: vec![1.0; gdn_cfg.value_head_dim],
22600            out_proj: qt(8, vd, 7),
22601        });
22602        p.gdn_cfg = Some(gdn_cfg);
22603        p.set_o1(Some(crate::nystrom::O1Cfg {
22604            layers: crate::nystrom::O1Layers::All,
22605            m: 4,
22606            w: 8,
22607            sink: 2,
22608            rect: crate::nystrom::O1Rect::Aggregate,
22609        }));
22610        p.o1_begin_with_prefix(Some(B));
22611        for pos in 0..B - 2 {
22612            let emb = p.embed_single(pos as u32);
22613            let _ = p.forward_layers(&emb, pos, None);
22614        }
22615        let lane1_state = p.kv_cache.layers[0].linear_state.clone();
22616
22617        let e1 = p.embed_single((B - 2) as u32);
22618        let e2 = p.embed_single((B - 1) as u32);
22619        let _ = p.forward_pair(&e1, &e2, B - 2);
22620
22621        assert_eq!(p.o1_epoch, 1, "pair crossing B publishes one epoch");
22622        assert!(
22623            p.kv_cache
22624                .layers
22625                .iter()
22626                .enumerate()
22627                .all(|(li, l)| !p.o1_flags[li] || l.o1_sealed())
22628        );
22629        assert!(!p.kv_cache.layers[0].linear_state.is_empty());
22630        assert_ne!(
22631            p.kv_cache.layers[0].linear_state, lane1_state,
22632            "real pair must commit GDN lane 2 before returning"
22633        );
22634        assert!(p.kv_cache.layers[0].linear_scratch.is_empty());
22635        let next = p.embed_single(B as u32);
22636        let _ = p.forward_layers(&next, B, None);
22637        assert_eq!(p.o1_epoch, 1, "serial continuation must reuse the epoch");
22638    }
22639
22640    #[test]
22641    fn o1_error_observation_stays_terminal_until_reset() {
22642        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
22643        p.set_o1(Some(crate::nystrom::O1Cfg {
22644            layers: crate::nystrom::O1Layers::All,
22645            m: 4,
22646            w: 8,
22647            sink: 2,
22648            rect: crate::nystrom::O1Rect::Aggregate,
22649        }));
22650        p.o1_begin();
22651        p.kv_cache.layers[0].o1_abort("synthetic transition failure".into());
22652
22653        assert!(p.o1_seal_checked().is_err());
22654        assert!(
22655            p.o1_seal_checked().is_err(),
22656            "retry must see the sticky error"
22657        );
22658        let k = vec![0.2f32; 4];
22659        let v = vec![0.3f32; 4];
22660        p.kv_cache.layers[0].append(&k, &v, &[]);
22661        assert_eq!(p.kv_cache.layers[0].seq_len, 0);
22662
22663        p.reset_session();
22664        p.o1_begin();
22665        p.kv_cache.layers[0].append(&k, &v, &[]);
22666        assert_eq!(p.kv_cache.layers[0].seq_len, 1);
22667    }
22668
22669    #[test]
22670    fn nll_graph_failure_is_terminal_and_request_is_reusable() {
22671        let ids = vec![1u32, 2, 3, 4, 5, 6];
22672        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
22673        p.graph_logits = Some(vec![123.0]);
22674        p.graph_want_logits = true;
22675        p.graph_failed
22676            .store(true, std::sync::atomic::Ordering::Relaxed);
22677        p.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
22678        let err = p.nll_ids_from(&ids, 0).expect_err("prior graph failure");
22679        assert!(err.contains("before NLL"));
22680        assert!(p.graph_logits.is_none());
22681        assert!(!p.graph_want_logits);
22682        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
22683        assert!(!p.cancel.load(std::sync::atomic::Ordering::Relaxed));
22684
22685        let mut fresh = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
22686        let expected = fresh.nll_ids_from(&ids, 0).expect("fresh NLL");
22687        let actual = p.nll_ids_from(&ids, 0).expect("reused NLL");
22688        assert_eq!(actual.1, expected.1);
22689        assert!((actual.0 - expected.0).abs() < 1e-9);
22690    }
22691
22692    #[test]
22693    fn nll_forward_failure_discards_partial_score_and_clears_sidechannels() {
22694        let ids = vec![1u32, 2, 3, 4, 5, 6];
22695        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
22696        p.nll_test_fail_at = Some(1);
22697        let err = p
22698            .nll_ids_from(&ids, 0)
22699            .expect_err("one-shot forward failure");
22700        assert!(err.contains("forward") || err.contains("score row"));
22701        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
22702        assert!(!p.graph_want_logits);
22703        assert!(p.graph_logits.is_none());
22704        assert!(p.kv_history.is_empty());
22705
22706        let mut fresh = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
22707        let expected = fresh.nll_ids_from(&ids, 0).expect("fresh NLL");
22708        let actual = p.nll_ids_from(&ids, 0).expect("reused NLL");
22709        assert_eq!(actual.1, expected.1);
22710        assert!((actual.0 - expected.0).abs() < 1e-9);
22711    }
22712
22713    #[test]
22714    fn nll_serial_failure_before_first_row_is_reported() {
22715        let ids = vec![1u32, 2, 3, 4];
22716        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
22717        p.nll_test_force_serial = true;
22718        p.nll_test_fail_at = Some(0);
22719        let err = p.nll_ids_from(&ids, 0).expect_err("serial forward failure");
22720        assert!(err.contains("serial forward"));
22721        assert!(p.kv_history.is_empty());
22722        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
22723        assert!(!p.cancel.load(std::sync::atomic::Ordering::Relaxed));
22724    }
22725
22726    #[test]
22727    fn ffn_probe_failure_discards_recorder_and_state() {
22728        let ids = vec![1u32, 2, 3, 4];
22729        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
22730        p.nll_test_fail_at = Some(0);
22731        let err = p
22732            .probe_ffn_mass_batch(&ids)
22733            .expect_err("probe forward failure");
22734        assert!(err.contains("NLL"));
22735        assert!(FFN_PROBE.with(|probe| probe.borrow().is_none()));
22736        assert!(p.kv_history.is_empty());
22737        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
22738    }
22739
22740    #[test]
22741    fn nll_test_controls_are_pipeline_scoped() {
22742        let ids = vec![1u32, 2, 3, 4];
22743        let mut failing = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
22744        let mut unaffected = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
22745        failing.nll_test_force_serial = true;
22746        failing.nll_test_fail_at = Some(0);
22747
22748        assert!(!failing.can_prefill_batched());
22749        assert!(unaffected.can_prefill_batched());
22750        let expected = unaffected
22751            .nll_ids_from(&ids, 0)
22752            .expect("unaffected pipeline remains usable");
22753        let err = failing
22754            .nll_ids_from(&ids, 0)
22755            .expect_err("failure injection belongs to failing pipeline");
22756        assert!(err.contains("serial forward"));
22757        assert!(failing.nll_test_fail_at.is_none());
22758        assert!(unaffected.can_prefill_batched());
22759        let actual = unaffected
22760            .nll_ids_from(&ids, 0)
22761            .expect("unaffected pipeline remains reusable");
22762        assert_eq!(actual.1, expected.1);
22763        assert!((actual.0 - expected.0).abs() < 1e-9);
22764    }
22765
22766    #[test]
22767    fn forward_ids_failure_channel_is_terminal_and_reusable() {
22768        let ids = vec![1u32, 2, 3, 4, 5, 6];
22769        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
22770        p.graph_logits = Some(vec![123.0]);
22771        p.graph_want_logits = true;
22772        p.graph_failed
22773            .store(true, std::sync::atomic::Ordering::Relaxed);
22774        p.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
22775
22776        let err = p
22777            .forward_ids(&ids, None)
22778            .expect_err("a failed forward must not become a valid head result");
22779        assert!(err.contains("forward_ids setup"));
22780        assert!(p.graph_logits.is_none());
22781        assert!(!p.graph_want_logits);
22782        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
22783        assert!(!p.cancel.load(std::sync::atomic::Ordering::Relaxed));
22784        assert_eq!(p.kv_cache.seq_len(), 0);
22785
22786        let expected = create_test_pipeline(8, 16, 2, 1, 4, 1, 64)
22787            .forward_ids(&ids, None)
22788            .expect("fresh forward_ids");
22789        let actual = p
22790            .forward_ids(&ids, None)
22791            .expect("pipeline remains reusable after a failed forward");
22792        assert_eq!(actual.len(), expected.len());
22793        assert!(
22794            actual
22795                .iter()
22796                .zip(expected)
22797                .all(|(a, b)| (a - b).abs() < 1e-9)
22798        );
22799        assert_eq!(p.kv_cache.seq_len(), ids.len());
22800    }
22801
22802    #[test]
22803    fn sigmoid_router_floor_is_explicit_per_architecture() {
22804        // Flint and MiniMax M3.1 reference runtimes use +1e-20, while the
22805        // generic LFM2-compatible path uses +1e-6. At low (but representable)
22806        // sigmoid scores, silently sharing the latter changes expert weights by
22807        // orders of magnitude and can make a routed layer look coherent while
22808        // discarding its expert contribution.
22809        let zero = || DenseFfn {
22810            gate_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
22811            up_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
22812            down_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
22813            act: Act::Silu,
22814            down_t: None,
22815            segs: Vec::new(),
22816        };
22817        let m = MoeFfn {
22818            router: QTensor::from_f32(vec![0.0; 4], 2, 2),
22819            experts: vec![zero(), zero()],
22820            top_k: 1,
22821            norm_topk_prob: true,
22822            router_sigmoid: true,
22823            sigmoid_denom_eps: 1e-20,
22824            expert_bias: None,
22825            routed_scaling: 2.5,
22826            route_tau: None,
22827            shared: None,
22828            stats: std::cell::RefCell::new(Vec::new()),
22829            act_sq: std::cell::RefCell::new(Vec::new()),
22830            act_rows: std::cell::RefCell::new(Vec::new()),
22831            mask: None,
22832            per_expert_scale: None,
22833            router_input_norm: false,
22834            resonance: None,
22835            grown: Vec::new(),
22836        };
22837        let logits = [-20.0f32, -20.0];
22838        let (_, p, flint_wsum) = moe_route(&logits, &m, None);
22839        let (_, _, minimax_wsum) = moe_route_with_eps(&logits, &m, None, 1e-20);
22840        let (_, _, legacy_wsum) = moe_route_with_eps(&logits, &m, None, 1e-6);
22841        let reference_expected = (p[0] + 1e-20) / m.routed_scaling;
22842        assert!((flint_wsum - reference_expected).abs() < 1e-15);
22843        assert_eq!(minimax_wsum.to_bits(), reference_expected.to_bits());
22844        assert!(legacy_wsum > minimax_wsum * 100.0);
22845    }
22846
22847    #[test]
22848    fn resonance_scores_match_formula_and_stable_tie() {
22849        let r = Resonance {
22850            // Three descriptors, hidden=2, one projection row each.
22851            mu: vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0],
22852            u: vec![1.0, 0.0, 0.0, 1.0, 1.0, 1.0],
22853            k: 1,
22854            bias: vec![1.5, 0.5, 0.0],
22855            shell: Vec::new(),
22856        };
22857        let x = [1.0f32, 1.0];
22858        let mut got = vec![0.0; 3];
22859        r.scores(&x, &mut got);
22860        // Expert 0 and 1 are an exact score tie; the CPU top-1 contract uses
22861        // the lower index.  The values also check d² - (U·d)², not just tie
22862        // ordering.
22863        assert!((got[0] - 0.5).abs() < 1e-6);
22864        assert!((got[1] - 0.5).abs() < 1e-6);
22865        assert!(got[2].abs() < 1e-6);
22866        let best = got
22867            .iter()
22868            .enumerate()
22869            .max_by(|(ia, a), (ib, b)| a.partial_cmp(b).unwrap().then(ib.cmp(ia)))
22870            .map(|(i, _)| i);
22871        assert_eq!(best, Some(0));
22872        assert!(got.iter().all(|v| v.is_finite()));
22873    }
22874
22875    /// The growth shell (spec §2): a grown expert whose reconstruction
22876    /// error lies outside its shell scores −∞, one inside keeps the exact
22877    /// resonance score, trunk rows (`+inf` shell) are bit-identical to the
22878    /// shell-less computation; the process-wide switch disables it.
22879    #[test]
22880    fn resonance_shell_masks_outside_keeps_inside_and_trunk_bits() {
22881        // hidden = 2, rank 1. Experts 0/1 = trunk (shell +inf); 2 and 3 =
22882        // grown, the same descriptor (μ = (0, 1), u = (1, 1)) with shells
22883        // 6.0 and 0.25. At x' = (3, 0): d = (3, −1), d² = 10, proj =
22884        // (3 − 1)² = 4, err = 6 exactly — on the boundary of expert 2's
22885        // shell (kept: the rule is strict `>`), outside expert 3's.
22886        let plain = Resonance {
22887            mu: vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0],
22888            u: vec![1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0],
22889            k: 1,
22890            bias: vec![1.5, 0.5, 0.0, 0.0],
22891            shell: Vec::new(),
22892        };
22893        let shelled = Resonance {
22894            mu: plain.mu.clone(),
22895            u: plain.u.clone(),
22896            k: 1,
22897            bias: plain.bias.clone(),
22898            shell: vec![f32::INFINITY, f32::INFINITY, 6.0, 0.25],
22899        };
22900        assert!(!plain.has_shell());
22901        assert!(shelled.has_shell());
22902        let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
22903        let (mut a, mut b) = (vec![0.0; 4], vec![0.0; 4]);
22904        set_growth_shell(Some(true));
22905        assert!(growth_shell_enabled());
22906        // x = (1, 1): the grown experts reconstruct it exactly (err 0):
22907        // inside both shells, every row the shell-less bits.
22908        let x = [1.0f32, 1.0];
22909        plain.scores(&x, &mut a);
22910        shelled.scores(&x, &mut b);
22911        assert_eq!(bits(&a), bits(&b), "inside every shell: unchanged");
22912        assert!(a[2] == 0.0 && a[3] == 0.0);
22913        // x' = (3, 0): expert 3 → −∞, expert 2 (err == shell) and the
22914        // trunk rows keep their exact bits.
22915        let xo = [3.0f32, 0.0];
22916        plain.scores(&xo, &mut a);
22917        shelled.scores(&xo, &mut b);
22918        assert_eq!(a[2], -6.0);
22919        assert_eq!(a[3], -6.0);
22920        assert_eq!(
22921            bits(&a[..3]),
22922            bits(&b[..3]),
22923            "trunk rows + the boundary row"
22924        );
22925        assert_eq!(b[3], f32::NEG_INFINITY, "outside the shell: −∞");
22926        assert_eq!(shelled.effective_shell(4), shelled.shell);
22927        // The switch (`CMF_GROWTH_SHELL=off` / `growth-eval --shell off`):
22928        // all +inf, the shell-less bits everywhere.
22929        set_growth_shell(Some(false));
22930        assert!(!growth_shell_enabled());
22931        assert_eq!(shelled.effective_shell(4), vec![f32::INFINITY; 4]);
22932        shelled.scores(&xo, &mut b);
22933        assert_eq!(bits(&a), bits(&b));
22934        set_growth_shell(None);
22935        // A shell vector shorter than the expert count masks nothing
22936        // beyond it (a legacy layer whose tail has no shell).
22937        let short = Resonance {
22938            shell: vec![f32::INFINITY, f32::INFINITY],
22939            ..shelled
22940        };
22941        set_growth_shell(Some(true));
22942        short.scores(&xo, &mut b);
22943        assert_eq!(bits(&a), bits(&b));
22944        set_growth_shell(None);
22945    }
22946
22947    /// `moe_route` with −∞ logits (a grown expert outside its shell):
22948    /// top-1 is the best finite expert with weight exactly 1.0 on both
22949    /// the softmax and the sigmoid path; all −∞ degrades to uniform.
22950    #[test]
22951    fn moe_route_neg_inf_logits_pick_the_best_finite_expert_with_weight_one() {
22952        let zero = || DenseFfn {
22953            gate_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
22954            up_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
22955            down_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
22956            act: Act::Silu,
22957            down_t: None,
22958            segs: Vec::new(),
22959        };
22960        let moe = |sigmoid: bool| MoeFfn {
22961            router: QTensor::from_f32(vec![0.0; 8], 4, 2),
22962            experts: vec![zero(), zero(), zero(), zero()],
22963            top_k: 1,
22964            norm_topk_prob: true,
22965            router_sigmoid: sigmoid,
22966            sigmoid_denom_eps: 1e-6,
22967            expert_bias: None,
22968            routed_scaling: 1.0,
22969            route_tau: None,
22970            shared: None,
22971            stats: std::cell::RefCell::new(Vec::new()),
22972            act_sq: std::cell::RefCell::new(Vec::new()),
22973            act_rows: std::cell::RefCell::new(Vec::new()),
22974            mask: None,
22975            per_expert_scale: None,
22976            router_input_norm: false,
22977            resonance: None,
22978            grown: Vec::new(),
22979        };
22980        let logits = [-1.0f32, f32::NEG_INFINITY, -0.5, f32::NEG_INFINITY];
22981        for sigmoid in [false, true] {
22982            let m = moe(sigmoid);
22983            let (idx, p, wsum) = moe_route(&logits, &m, None);
22984            assert_eq!(idx, vec![2], "sigmoid {sigmoid}");
22985            assert_eq!(p[1], 0.0);
22986            assert_eq!(p[3], 0.0);
22987            assert!(p[2] > p[0] && p[0] > 0.0);
22988            assert!(p.iter().all(|v| v.is_finite()));
22989            let w = p[2] / wsum;
22990            if sigmoid {
22991                // The sigmoid renorm keeps its reference floor (+1e-6).
22992                assert!((w - 1.0).abs() < 1e-5, "sigmoid: weight {w}");
22993            } else {
22994                assert_eq!(
22995                    w, 1.0,
22996                    "softmax: the renormalized top-1 weight is exactly 1"
22997                );
22998            }
22999            // Masked experts stay masked even when they are the only ones
23000            // "admitted" by an allow-list that covers everything.
23001            let (idx, _, _) = moe_route(&logits, &m, Some(&[true, true, true, true]));
23002            assert_eq!(idx, vec![2]);
23003        }
23004        // A finite expert always beats −∞ whatever the bias / order.
23005        let m = moe(false);
23006        let (idx, _, _) = moe_route(
23007            &[
23008                f32::NEG_INFINITY,
23009                f32::NEG_INFINITY,
23010                f32::NEG_INFINITY,
23011                -9.0,
23012            ],
23013            &m,
23014            None,
23015        );
23016        assert_eq!(idx, vec![3]);
23017        // Every expert at −∞ (cannot happen on a grown file — trunk rows
23018        // have no shell): uniform, finite, lowest index.
23019        let (idx, p, wsum) = moe_route(&[f32::NEG_INFINITY; 4], &m, None);
23020        assert_eq!(idx, vec![0]);
23021        assert!(p.iter().all(|&v| v == 0.25));
23022        assert!(wsum.is_finite() && wsum > 0.0);
23023    }
23024
23025    /// MiniMax-M3.1's DEVICE route (the pooled token-graph arm's exact
23026    /// flags: sigmoid scoring via n's high bit, +1e-20 floor,
23027    /// routed_scaling 2.0, selection bias on the CHOICE only) must match
23028    /// the host reference in experts, ORDER and weights — the check that
23029    /// caught the flags/slot collision.
23030    #[cfg(feature = "gpu")]
23031    #[test]
23032    fn minimax_device_route_matches_host_sigmoid_contract() {
23033        match crate::gpu_wgpu::selected_and_up() {
23034            None => {
23035                crate::gpu_wgpu::skip_or_fail(module_path!());
23036                return;
23037            }
23038            // Sibling unit tests in THIS process select wgpu by writing
23039            // `CMF_GPU` (the gpu_wgpu test module does it ~70 times), so on a
23040            // headless runner the variable is already set by the time this
23041            // test reads it — "requested" here is test pollution, not an
23042            // operator's ask, and the adapter genuinely does not exist in
23043            // this process. Same treatment as the gpu_wgpu tests themselves:
23044            // a visible skip, never a silent pass.
23045            Some(false) => {
23046                eprintln!(
23047                    "SKIPPED ({}): CMF_GPU names wgpu but no adapter came up in this process",
23048                    module_path!()
23049                );
23050                return;
23051            }
23052            Some(true) => {}
23053        }
23054        let n = 128usize;
23055        let top_k = 4usize;
23056        let logits: Vec<f32> = (0..n)
23057            .map(|i| ((i as f32 * 0.61).sin() * 3.4) + ((i % 23) as f32 * 0.13))
23058            .collect();
23059        let bias: Vec<f32> = (0..n).map(|i| ((i as f32 * 2.3).cos()) * 0.5).collect();
23060        let m = MoeFfn {
23061            router: QTensor::from_f32(vec![0.0; 4], 2, 2),
23062            experts: Vec::new(),
23063            top_k,
23064            norm_topk_prob: true,
23065            router_sigmoid: true,
23066            sigmoid_denom_eps: 1e-20,
23067            expert_bias: Some(bias.clone()),
23068            routed_scaling: 2.0,
23069            route_tau: None,
23070            shared: None,
23071            stats: std::cell::RefCell::new(Vec::new()),
23072            act_sq: std::cell::RefCell::new(Vec::new()),
23073            act_rows: std::cell::RefCell::new(Vec::new()),
23074            mask: None,
23075            per_expert_scale: None,
23076            router_input_norm: false,
23077            resonance: None,
23078            grown: Vec::new(),
23079        };
23080        let (ci, p, wsum) = moe_route_with_eps(&logits, &m, None, 1e-20);
23081        let cw: Vec<f32> = ci.iter().map(|&e| p[e] / wsum).collect();
23082
23083        for shared in [Some(n as u32), None] {
23084            let mut gi = Vec::new();
23085            let mut gw = Vec::new();
23086            assert!(
23087                crate::gpu_wgpu::minimax_moe_route_for_test(
23088                    &logits,
23089                    Some(&bias),
23090                    top_k,
23091                    2.0,
23092                    shared,
23093                    &mut gi,
23094                    &mut gw,
23095                ),
23096                "устройство не поднялось — тест не проверил ничего"
23097            );
23098            let routed = if shared.is_some() { top_k } else { gi.len() };
23099            assert_eq!(
23100                &gi[..routed],
23101                &ci[..],
23102                "разные эксперты или порядок (shared={shared:?})"
23103            );
23104            let d = cw
23105                .iter()
23106                .zip(&gw[..routed])
23107                .map(|(a, b)| (a - b).abs())
23108                .fold(0.0f32, f32::max);
23109            println!("minimax route shared={shared:?}: {ci:?} max|Δw|={d:.3e}");
23110            assert!(d < 1e-6, "веса разошлись на {d:.3e}");
23111            if let Some(s) = shared {
23112                assert_eq!(gi[top_k], s as usize, "shared pin slot");
23113                assert_eq!(gw[top_k], 1.0, "shared weight");
23114            }
23115        }
23116    }
23117
23118    /// The pooled arm's COLD hand-back: `(expert, weight)` pairs for the
23119    /// picks the bank could not serve must carry the host's EXACT final
23120    /// weights — the device ships its resident sum, the host adds this on
23121    /// top of the same residual, so a weight drift compounds per layer.
23122    #[cfg(feature = "gpu")]
23123    #[test]
23124    fn minimax_device_cold_weights_match_host_contract() {
23125        match crate::gpu_wgpu::selected_and_up() {
23126            None => {
23127                crate::gpu_wgpu::skip_or_fail(module_path!());
23128                return;
23129            }
23130            // Sibling unit tests in THIS process select wgpu by writing
23131            // `CMF_GPU` (the gpu_wgpu test module does it ~70 times), so on a
23132            // headless runner the variable is already set by the time this
23133            // test reads it — "requested" here is test pollution, not an
23134            // operator's ask, and the adapter genuinely does not exist in
23135            // this process. Same treatment as the gpu_wgpu tests themselves:
23136            // a visible skip, never a silent pass.
23137            Some(false) => {
23138                eprintln!(
23139                    "SKIPPED ({}): CMF_GPU names wgpu but no adapter came up in this process",
23140                    module_path!()
23141                );
23142                return;
23143            }
23144            Some(true) => {}
23145        }
23146        let n = 128usize;
23147        let top_k = 4usize;
23148        let logits: Vec<f32> = (0..n)
23149            .map(|i| ((i as f32 * 0.61).sin() * 3.4) + ((i % 23) as f32 * 0.13))
23150            .collect();
23151        let bias: Vec<f32> = (0..n).map(|i| ((i as f32 * 2.3).cos()) * 0.5).collect();
23152        let m = MoeFfn {
23153            router: QTensor::from_f32(vec![0.0; 4], 2, 2),
23154            experts: Vec::new(),
23155            top_k,
23156            norm_topk_prob: true,
23157            router_sigmoid: true,
23158            sigmoid_denom_eps: 1e-20,
23159            expert_bias: Some(bias.clone()),
23160            routed_scaling: 2.0,
23161            route_tau: None,
23162            shared: None,
23163            stats: std::cell::RefCell::new(Vec::new()),
23164            act_sq: std::cell::RefCell::new(Vec::new()),
23165            act_rows: std::cell::RefCell::new(Vec::new()),
23166            mask: None,
23167            per_expert_scale: None,
23168            router_input_norm: false,
23169            resonance: None,
23170            grown: Vec::new(),
23171        };
23172        let (ci, p, wsum) = moe_route_with_eps(&logits, &m, None, 1e-20);
23173        assert_eq!(ci.len(), top_k);
23174
23175        // Every pick resident → no cold pairs at all.
23176        let resident: Vec<u32> = (0..n).map(|e| e as u32).collect();
23177        let mut cold = Vec::new();
23178        let mut idx = Vec::new();
23179        let mut dw = Vec::new();
23180        assert!(crate::gpu_wgpu::minimax_moe_route_cold_for_test(
23181            &logits,
23182            Some(&bias),
23183            top_k,
23184            2.0,
23185            &resident,
23186            n as u32,
23187            &mut cold,
23188            &mut idx,
23189            &mut dw,
23190        ));
23191        assert!(cold.is_empty(), "полностью резидентный банк: {cold:?}");
23192        // With subset+pin together: routed slots carry the FLAT remap value
23193        // (here identity = the expert id), weights the host contract, and
23194        // the pinned shared keeps weight 1 — this exact combination is what
23195        // the pooled arm runs with.
23196        for (r, &e) in ci.iter().enumerate() {
23197            assert_eq!(idx[r] as usize, e, "resident slot mapping r={r}");
23198            let host = p[e] / wsum;
23199            let d = (dw[r] - host).abs();
23200            assert!(
23201                d <= 1e-6 * host.abs().max(1.0),
23202                "resident weight r={r} expert {e}: device={:.9e} host={host:.9e}",
23203                dw[r]
23204            );
23205        }
23206        assert_eq!(idx[top_k] as usize, n, "shared pin slot");
23207        assert_eq!(dw[top_k], 1.0, "shared weight");
23208
23209        // Make exactly two of the CHOSEN picks cold.
23210        let mut remap = resident.clone();
23211        remap[ci[0]] = u32::MAX;
23212        remap[ci[2]] = u32::MAX;
23213        let mut cold = Vec::new();
23214        let mut idx2 = Vec::new();
23215        let mut dw2 = Vec::new();
23216        assert!(crate::gpu_wgpu::minimax_moe_route_cold_for_test(
23217            &logits,
23218            Some(&bias),
23219            top_k,
23220            2.0,
23221            &remap,
23222            n as u32,
23223            &mut cold,
23224            &mut idx2,
23225            &mut dw2,
23226        ));
23227        // The resident picks of the partial bank still carry exact weights.
23228        // A COLD rank is a placeholder the device writes as slot 0 / weight
23229        // 0.0 — its real (id, weight) pair rides in `cold` — so weight zero
23230        // is what marks it, not the slot value: reading the placeholder as
23231        // a resident expert compared 0.0 against p[0]/wsum and failed with
23232        // Δ=2.552e-1. The test logits keep every sigmoid score strictly
23233        // positive, so a resident pick can never weigh exactly zero.
23234        let mut resident_weight_checked = 0usize;
23235        for (r, &slot) in idx2.iter().enumerate().take(top_k) {
23236            if dw2[r] == 0.0 {
23237                continue; // cold rank: placeholder, not an expert id
23238            }
23239            let e = slot as usize;
23240            assert!(e < n && remap[e] != u32::MAX, "resident slot {e} escaped the remap");
23241            let host = p[e] / wsum;
23242            let d = (dw2[r] - host).abs();
23243            assert!(
23244                d <= 1e-6 * host.abs().max(1.0),
23245                "partial-bank resident weight expert {e}: Δ={d:.3e}"
23246            );
23247            resident_weight_checked += 1;
23248        }
23249        assert_eq!(resident_weight_checked, 2, "ровно два резидентных пика из четырёх");
23250        println!("partial bank: checked {resident_weight_checked} resident weights");
23251        assert_eq!(dw2.get(top_k).copied(), Some(1.0), "shared weight under subset");
23252        let mut ids: Vec<usize> = cold.iter().map(|&(e, _)| e).collect();
23253        ids.sort_unstable();
23254        let mut want = vec![ci[0], ci[2]];
23255        want.sort_unstable();
23256        assert_eq!(ids, want, "холодные эксперты разошлись: {cold:?} против {want:?}");
23257        for &(e, w) in &cold {
23258            let host = p[e] / wsum;
23259            let d = (w - host).abs();
23260            println!("cold expert {e}: device={w:.9e} host={host:.9e} Δ={d:.3e}");
23261            assert!(d <= 1e-6 * host.abs().max(1.0), "cold вес эксперта {e}: Δ={d:.3e}");
23262        }
23263    }
23264
23265    /// The resonance router (top-1) selects by the raw score as the
23266    /// trainer and the graph do — not by softmax probabilities, where two
23267    /// scores closer than 2^-25 collapse to the same `exp(l − max) = 1.0`
23268    /// and the LOWER index wins a token whose score is strictly smaller.
23269    #[test]
23270    fn resonance_route_picks_the_raw_argmax_not_the_softmax_tie() {
23271        let zero = || DenseFfn {
23272            gate_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
23273            up_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
23274            down_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
23275            act: Act::Silu,
23276            down_t: None,
23277            segs: Vec::new(),
23278        };
23279        let moe = |resonant: bool, norm_topk: bool| MoeFfn {
23280            router: QTensor::from_f32(vec![0.0; 6], 3, 2),
23281            experts: vec![zero(), zero(), zero()],
23282            top_k: 1,
23283            norm_topk_prob: norm_topk,
23284            router_sigmoid: false,
23285            sigmoid_denom_eps: 1e-6,
23286            expert_bias: None,
23287            routed_scaling: 1.0,
23288            route_tau: None,
23289            shared: None,
23290            stats: std::cell::RefCell::new(Vec::new()),
23291            act_sq: std::cell::RefCell::new(Vec::new()),
23292            act_rows: std::cell::RefCell::new(Vec::new()),
23293            mask: None,
23294            per_expert_scale: None,
23295            router_input_norm: false,
23296            resonance: resonant.then(|| Resonance {
23297                mu: vec![0.0; 6],
23298                u: Vec::new(),
23299                k: 0,
23300                bias: vec![0.0; 3],
23301                shell: Vec::new(),
23302            }),
23303            grown: Vec::new(),
23304        };
23305        // lo = −0.1, hi = the next f32 towards zero: hi − lo = 2^-27 <
23306        // 2^-25, so exp(lo − hi) rounds to exactly 1.0 — a softmax tie.
23307        let lo = -0.1f32;
23308        let hi = f32::from_bits(lo.to_bits() - 1);
23309        assert!(hi > lo && hi - lo < 2f32.powi(-25));
23310        assert_eq!((lo - hi).exp(), 1.0, "the tie this test is about");
23311        // The gated MoE (softmax) path: the tie hands the token to index 0.
23312        let (idx, _, _) = moe_route(&[lo, hi], &moe(false, true), None);
23313        assert_eq!(
23314            idx,
23315            vec![0],
23316            "softmax tie → lower index (the gated contract)"
23317        );
23318        // The resonance path: the strictly larger raw score wins, weight
23319        // exactly 1.0 with and without norm_topk.
23320        for norm in [true, false] {
23321            let m = moe(true, norm);
23322            let (idx, p, wsum) = moe_route(&[lo, hi, f32::NEG_INFINITY], &m, None);
23323            assert_eq!(idx, vec![1], "norm_topk {norm}");
23324            assert_eq!(p, vec![0.0, 1.0, 0.0]);
23325            assert_eq!(p[1] / wsum, 1.0);
23326            // An exact tie: the first maximum (as `resonance_winner` and
23327            // `embryo_core_route_pick`).
23328            let (idx, _, _) = moe_route(&[hi, hi, lo], &m, None);
23329            assert_eq!(idx, vec![0]);
23330            // `−∞` never wins; the admitted set is honoured.
23331            let (idx, _, _) = moe_route(&[f32::NEG_INFINITY, lo, hi], &m, None);
23332            assert_eq!(idx, vec![2]);
23333            let (idx, p, wsum) = moe_route(&[lo, hi, hi], &m, Some(&[true, false, false]));
23334            assert_eq!(idx, vec![0]);
23335            assert_eq!(p[0] / wsum, 1.0);
23336            // Every admitted expert at −∞: the generic path's uniform
23337            // fallback (lowest index, finite weights).
23338            let (idx, p, wsum) = moe_route(&[f32::NEG_INFINITY; 3], &m, None);
23339            assert_eq!(idx, vec![0]);
23340            assert!(p.iter().all(|v| v.is_finite()) && wsum.is_finite() && wsum > 0.0);
23341        }
23342    }
23343}