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;
16#[path = "clover.rs"]
17pub mod clover;
18/// d1's non-causal forward over a packed state and question set.
19#[path = "pipeline_masked.rs"]
20pub mod masked;
21#[path = "pipeline_speech.rs"]
22pub mod speech;
23use crate::kv_cache::KvCache;
24use crate::linear_core::{
25    GdnCfg, GdnWeights, ShortConvCfg, ShortConvWeights, VmfPhaseCfg, VmfPhaseWeights, gdn_forward,
26    gdn_pair, short_conv_forward, short_conv_forward_batch, short_conv_pair, vmf_phase_forward,
27    vmf_phase_pair,
28};
29use crate::pool::Pool;
30use crate::qtensor::QTensor;
31use crate::sampler::{self, SamplerConfig, SamplerScratch, SplitMix64};
32use crate::tokenizer::Tokenizer;
33use cortiq_core::mask::TaskMask;
34use cortiq_core::types::NormStyle;
35
36pub static GLOBAL_USE_GPU: std::sync::atomic::AtomicBool =
37    std::sync::atomic::AtomicBool::new(false);
38
39/// One MoE layer's expert bank as the resident token graph reads it: the
40/// `(gate, up, down)` tensor indices in routing order (the in-bank shared
41/// expert last), the layer's uniform layout flags and activation, and the
42/// file that holds them. A pure function of the layer's weights — walking
43/// 257 experts × 3 matrices per layer per token was ~2 ms of host time a
44/// token on a 40-layer 256-expert stack, so the walk runs once a layer.
45#[derive(Clone)]
46struct GraphMoeBank {
47    experts: Vec<(usize, usize, usize)>,
48    q4tp: Option<bool>,
49    gu_q2: Option<bool>,
50    q82: Option<bool>,
51    act: Option<crate::gpu::GraphAct>,
52    model: Option<std::sync::Arc<cortiq_core::CmfModel>>,
53}
54
55/// Identity of the weights a `GraphMoeBank` was built from: the physical
56/// layer, the expert table's storage and length, the in-bank shared expert,
57/// and the first and last expert tensors' (file, index) — so a table
58/// rebuilt at a reused address (a skill, a grown expert) cannot alias an
59/// old entry.
60type GraphMoeKey = (usize, usize, usize, usize, usize, usize, usize);
61
62// MTP compaction statistics must describe the dense draft that will be
63// serialized, not an ambient serving experiment such as gate/oracle top-k.
64// A thread-local nesting counter keeps the guard local to calibration and
65// avoids mutating process-global environment variables mid-command.
66thread_local! {
67    static EXACT_MTP_CALIBRATION: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
68}
69
70struct ExactMtpCalibrationGuard;
71
72impl ExactMtpCalibrationGuard {
73    fn enter() -> Self {
74        EXACT_MTP_CALIBRATION.with(|depth| depth.set(depth.get().saturating_add(1)));
75        Self
76    }
77}
78
79impl Drop for ExactMtpCalibrationGuard {
80    fn drop(&mut self) {
81        EXACT_MTP_CALIBRATION.with(|depth| {
82            debug_assert!(depth.get() > 0, "unbalanced MTP calibration guard");
83            depth.set(depth.get().saturating_sub(1));
84        });
85    }
86}
87
88fn exact_mtp_calibration_active() -> bool {
89    EXACT_MTP_CALIBRATION.with(|depth| depth.get() != 0)
90}
91
92/// Extend an MTP draft-head shortlist to the model vocabulary.  Rows outside
93/// the shortlist were deliberately not evaluated, so they must be impossible
94/// draft candidates rather than neutral zero logits.
95fn pad_mtp_draft_logits(logits: &mut Vec<f32>, vocab_size: usize) {
96    logits.resize(vocab_size, f32::NEG_INFINITY);
97}
98
99/// Reusable per-pipeline forward scratch: the four norm outputs the
100/// decode paths recompute every layer (single: n1/p1; pair: all four).
101/// Plain buffers, resized once — steady-state decode reuses them.
102struct ForwardScratch {
103    n1: Vec<f32>,
104    n2: Vec<f32>,
105    p1: Vec<f32>,
106    p2: Vec<f32>,
107}
108
109impl ForwardScratch {
110    fn new(hidden: usize) -> Self {
111        Self {
112            n1: vec![0.0; hidden],
113            n2: vec![0.0; hidden],
114            p1: vec![0.0; hidden],
115            p2: vec![0.0; hidden],
116        }
117    }
118}
119
120/// Complete inference pipeline state.
121pub struct Pipeline {
122    /// In-process layer split across local GPUs: (device, first layer,
123    /// last layer) per segment, in execution order. `None` = one device.
124    /// Arc so cloning the plan out of `&mut self` does not fight the
125    /// borrow checker on the hot path.
126    gpu_plan: Option<std::sync::Arc<Vec<(usize, usize, usize)>>>,
127    /// Arc: the server shares one tokenizer handle across request
128    /// handlers without borrowing a pipeline slot.
129    pub tokenizer: std::sync::Arc<Tokenizer>,
130    pub kv_cache: KvCache,
131    pub sampler_config: SamplerConfig,
132    pub weights: PipelineWeights,
133    pub hidden_size: usize,
134    pub intermediate_size: usize,
135    pub num_heads: usize,
136    pub num_kv_heads: usize,
137    pub head_dim: usize,
138    /// Total virtual layers (num_layers × num_loops for looped models).
139    pub num_layers: usize,
140    /// Physical layers in weights.layers (≤ num_layers for looped models).
141    pub physical_layers: usize,
142    /// Looped Transformer: apply final norm after each loop iteration.
143    pub loop_final_norm: bool,
144    /// SenseNova-Loop: virtual → physical layer order (None: `v %
145    /// physical_layers`, the whole-stack loop of Nanbeige).
146    pub layer_map: Option<Vec<usize>>,
147    /// SenseNova-Loop: the mHC routers (`sensenova::Mhc`).
148    pub mhc: Option<Box<crate::sensenova::Mhc>>,
149    /// Unlimited-OCR: the DASH router and page state (`uocr::Dash`).
150    pub dash: Option<Box<crate::uocr::Dash>>,
151    /// Its prompt chunks ride the batch graph until that declines.
152    dash_batch_on: bool,
153    /// The decode token's mHC streams, `[streams · hidden]`.
154    mhc_r: Vec<f32>,
155    /// Interleaved-MRoPE sections and the prompt rows' (t, h, w) positions
156    /// for the prefill of an image prompt (SenseNova-Loop); cleared when
157    /// the prefill ends.
158    pub mrope_sections: Option<[usize; 3]>,
159    pub prompt_mrope: Option<Vec<[i64; 3]>>,
160    pub vocab_size: usize,
161    pub rms_eps: f64,
162    pub rope_base: f32,
163    pub norm_style: NormStyle,
164    /// RoPE dims actually rotated (≤ head_dim; Qwen3.5 uses head_dim/4).
165    pub rotary_dim: usize,
166    /// Optional Q-head count override for each attention layer (Laguna).
167    pub attention_heads_per_layer: Option<Vec<usize>>,
168    /// Optional KV-head count of each PHYSICAL attention layer (MiMo-V2:
169    /// 4 on full-attention layers, 8 on sliding ones). Set only through
170    /// [`Pipeline::set_attn_geometry`], which also reshapes the layer
171    /// caches. None = every layer has `num_kv_heads`.
172    pub kv_heads_per_layer: Option<Vec<usize>>,
173    /// Width of each V head when it is narrower than `head_dim` (MiMo-V2:
174    /// 128 against 192). V is zero-padded to `head_dim` inside the cache
175    /// and the attention output is compacted back to nh·v_head_dim before
176    /// o_proj (see `QwenAttnCfg::v_head_dim`). None = `head_dim`.
177    pub v_head_dim: Option<usize>,
178    /// `CMF_LAYER_DUMP=<dir>` (read once at construction; tests set it
179    /// directly): the hidden state after every layer, for every position,
180    /// as raw little-endian f32 files `p{pos:06}_l{li:02}.f32` of
181    /// `hidden_size` floats each. Written by the CPU layer walks — the
182    /// batched prefill (`prefill_batch_span`) and the single-token forward
183    /// (`forward_layers_span`) — so both prompt ingest and decode can be
184    /// diffed layer by layer against an external oracle (tools/mimo_ref).
185    /// Layers a device graph runs (wgpu token/batch graph, Metal chunk or
186    /// block graphs) and the own-stack families (DeepSeek-V4/V4.1,
187    /// Qwen3.8-Flash-Next, Gemma-3n) are not dumped: run with CMF_GPU=0
188    /// for a complete set. `li` is the virtual layer index. Final logits:
189    /// `CMF_LOGIT_DUMP=<file>` (hidden + logits of the first decode step).
190    pub layer_dump: Option<std::path::PathBuf>,
191    /// GPU-graph declines already logged for this pipeline, as (graph
192    /// site, reason) — one line each, see `graph_attn_decline_reason`.
193    graph_declines: std::cell::RefCell<Vec<(&'static str, &'static str)>>,
194    /// MiMo-V2 expert placement (prefix / dynamic bank / hybrid), decided
195    /// on the first forward — see `crate::mimo_moe`.
196    pub(crate) mimo_moe: crate::mimo_moe::Slot,
197    /// Opt-in MiniCPM q4tp expert cache for a graph-produced CPU tail.
198    /// It is deliberately separate from MiMo's placement policy because it
199    /// serves only the stock MiniCPM top-8 geometry and otherwise falls back
200    /// to the ordinary exact host MoE path.
201    pub(crate) minicpm_tail: crate::minicpm_tail::MiniCpmTail,
202    /// Linear-core geometry (present when the model has linear layers).
203    pub vmf_cfg: Option<VmfPhaseCfg>,
204    /// GatedDeltaNet geometry (faithful vendor operator).
205    pub gdn_cfg: Option<GdnCfg>,
206    /// MiniCPM-class logit scale (tied lm_head → cannot fold into weights).
207    pub logit_multiplier: Option<f32>,
208    /// Cooperative cancel: set from any thread (FFI `cortiq_cancel`,
209    /// a dropped server connection); the generate loop checks it at
210    /// every prefill chunk and decode step and finishes with
211    /// `finish_reason: "cancelled"`. Auto-cleared when honoured.
212    pub cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
213    /// A GPU graph failure is distinct from a user/request cancellation.
214    /// Graph code sets this before raising the cooperative cancel flag so the
215    /// generation API can return an error instead of reporting a successful
216    /// `finish_reason: cancelled` result.
217    graph_failed: std::sync::atomic::AtomicBool,
218    /// Resident-graph MoE expert banks, built once per layer
219    /// (`GraphMoeBank`). `CMF_GRAPH_MOE_BANK=0` rebuilds them every token.
220    graph_moe_banks: std::sync::Mutex<std::collections::HashMap<GraphMoeKey, GraphMoeBank>>,
221    /// Token ids currently materialized in the KV cache (the forwarded
222    /// prompt + all generated tokens except the last, which is sampled
223    /// but not yet forwarded). Lets the next generate call prefill only
224    /// the suffix when a chat app resends the whole history.
225    pub kv_history: Vec<u32>,
226    /// Owner tag of `kv_history`: the resident device graph held that
227    /// sequence (true) or the host did. Reuse continues only on the owner.
228    pub kv_history_device: bool,
229    /// KDA geometry (Kimi Linear / Kimi-K3) — shared by every Kda layer.
230    pub kda_cfg: Option<crate::linear_core::KdaCfg>,
231    /// Gemma-3n stack (AltUp/LAuReL/PLE/KV-sharing): its own forward —
232    /// weights.layers stays empty, the KV caches are the shared ones.
233    pub g3n: Option<Box<(crate::g3n::G3nGlobals, Vec<crate::g3n::G3nLayer>)>>,
234    /// Gemma-4 E-series stack (dual-geometry gemma4 + PLE + shared KV):
235    /// its own per-token forward, same contract as `g3n`.
236    pub g4e: Option<Box<(crate::g4e::G4eGlobals, Vec<crate::g4e::G4eLayer>)>>,
237    /// DeepSeek-V4 runs its own stack too: its hidden state is `hc_mult`
238    /// copies of a vector, so no loop written for a single residual
239    /// stream can carry it.
240    pub dsv4: Option<
241        Box<(
242            crate::dsv4::Dsv4Globals,
243            Vec<crate::dsv4::Dsv4Layer>,
244            crate::dsv4::Dsv4Cfg,
245            crate::dsv4::Dsv4State,
246        )>,
247    >,
248    /// DeepSeek-V4.1 owns the shared CED/CSA2 attention state, raw Engram
249    /// lookup and four-stream mHC handoff. It cannot use the V4 cache
250    /// layout, so it has a dedicated executor and state tuple.
251    /// Dory: a looped normalized GPT, its weights and KV state (`dory`).
252    pub dory: Option<Box<(crate::dory::Dory, crate::dory::DoryState)>>,
253    pub dsv41: Option<
254        Box<(
255            crate::dsv41::Dsv41Globals,
256            Vec<crate::dsv41::Dsv41Layer>,
257            crate::dsv41::Dsv41Cfg,
258            crate::dsv41::Dsv41State,
259        )>,
260    >,
261    /// Optional V4.1 vision tower. Text-only files leave this unset.
262    pub dsv41_vision: Option<crate::dsv41_vision::VisionModel>,
263    /// Prepared image rows consumed by the next V4.1 prefill.
264    dsv41_prefill: Option<(Vec<Option<Vec<f32>>>, Vec<bool>)>,
265    /// Qwen3.8-Flash-Next owns four residual streams plus QSA/PLE state;
266    /// the generic single-residual layer loop cannot represent it.
267    /// Block-diffusion generation (Clover): preview weights and the
268    /// decoding controls; `None` on every causal model.
269    pub(crate) clover: Option<std::sync::Arc<clover::Clover>>,
270    clover_stats: clover::CloverStats,
271    /// The causal decode's response penalties (`clover_causal_logits`).
272    clover_pen: clover::Penalties,
273    pub qwen4_exp: Option<
274        Box<(
275            crate::qwen4_exp::Globals,
276            Vec<crate::qwen4_exp::Layer>,
277            crate::qwen4_exp::Cfg,
278            crate::qwen4_exp::State,
279        )>,
280    >,
281    /// Hy4-flash owns four iHC streams, gated MLA/indexer state and Engram.
282    pub hy4: Option<
283        Box<(
284            crate::hy4::Globals,
285            Vec<crate::hy4::Layer>,
286            crate::hy4::Cfg,
287            crate::hy4::State,
288        )>,
289    >,
290    /// Maxwell-V1-Flash owns four mHC streams, its block router and a
291    /// sigmoid-routed MoE.
292    pub maxwell: Option<
293        Box<(
294            crate::maxwell::Globals,
295            Vec<crate::maxwell::Layer>,
296            crate::maxwell::Cfg,
297            crate::maxwell::State,
298        )>,
299    >,
300    /// Inkling-2-Mini owns its looped stack: block attention residuals,
301    /// short convolutions, per-pass caches.
302    pub inkling: Option<
303        Box<(
304            crate::inkling::Globals,
305            Vec<crate::inkling::Layer>,
306            crate::inkling::Cfg,
307            crate::inkling::State,
308        )>,
309    >,
310    /// GLM-5.3-Flash owns four mHC streams plus KDA/DSA state.
311    pub glm5_next: Option<
312        Box<(
313            crate::glm5_next::Globals,
314            Vec<crate::glm5_next::Layer>,
315            crate::glm5_next::Cfg,
316            crate::glm5_next::State,
317        )>,
318    >,
319    /// DeepSeek-V4's own speculation stack: three draft modules, each a full
320    /// layer, plus a confidence head on the last. Empty when the file has
321    /// none, which is the only signal the decode path needs.
322    pub dsv4_mtp: Vec<crate::dsv4::Dsv4Mtp>,
323    /// The draft's per-sequence state (KV rings, captured trunk hidden).
324    pub dspark: Option<crate::dsv4::DsparkState>,
325    /// Drafts awaiting their verdict: (position, proposals, still matching,
326    /// accepted so far).
327    pub dspark_pending: Vec<(usize, Vec<u32>, bool, usize)>,
328    /// Accepted prefix length of every graded draft.
329    pub dspark_hist: Vec<usize>,
330    /// The real tokens the drafts were graded against — a degenerate,
331    /// repeating output would make any acceptance number meaningless, and
332    /// the cheapest guard against believing one is to count them.
333    pub dspark_real: Vec<u32>,
334    /// The trunk's expert picks for the last few tokens, per layer. The
335    /// union over a window of them is what a batched verify would have to
336    /// read, and the ratio to the pick count is all it could save.
337    pub dspark_trunk_picks: Vec<Vec<(usize, Vec<usize>)>>,
338    /// (unique, total) expert picks per draft, trunk side and draft side.
339    pub dspark_exp: Vec<(usize, usize, usize, usize)>,
340    /// Wall time spent in the deliberately out-of-core draft. Kept separate
341    /// from trunk decode so block batching can be judged without conflating
342    /// it with GPU chain variance.
343    pub dspark_draft_ns: u128,
344    /// Per-layer winners of the last pooled route — the admission predictor.
345    m3_winners: Vec<Vec<u32>>,
346    /// Route frequency per (layer, expert) — the bank's prewarm profile.
347    m3_counts: Vec<u32>,
348    m3_n_exp: usize,
349    m3_tokens: u64,
350    m3_prewarmed: bool,
351    /// LFM2 short-convolution geometry (present when the model has
352    /// `ShortConv` mixer layers).
353    pub short_conv_cfg: Option<ShortConvCfg>,
354    /// Multi-token-prediction head (None = absent).
355    pub mtp: Option<MtpModule>,
356    /// MiMo-V2's draft stack (three chained MTP layers from the
357    /// `<stem>.mtp.cmf` sidecar); None = absent. Speculative greedy decode
358    /// uses it unless `CMF_MTP=0` / `CMF_MIMO_MTP=0`.
359    pub mimo_mtp: Option<mimo_mtp::MimoMtp>,
360    /// Set while the MiMo speculative verify runs `prefill_batch`: its MoE
361    /// layers take `moe_ffn_rows_exact` (each row bit-identical to decode).
362    verify_exact_moe: bool,
363    /// Speculative decode via MTP (greedy only; `CMF_MTP=0` disables).
364    pub speculative: bool,
365    /// Keep generating past end-of-sequence ids (the llama-bench contract
366    /// for a timed run). A loop flag, deliberately NOT a sampler
367    /// suppression: suppressed ids count as a penalty and switch the
368    /// speculative round and the greedy burst off, so a benchmark that
369    /// suppressed EOS never measured either.
370    pub ignore_eos: bool,
371    /// Draft-head shortlist guard: tokens left during which the draft
372    /// uses the FULL head because a recently committed id lay past the
373    /// `CMF_DRAFT_VOCAB` cut (Cyrillic and CJK ids sit above 131072 in
374    /// Qwen's table, so a prefix shortlist would draft nothing usable
375    /// there — measured on Russian prose: 2.9 → 1.6 accepted a round).
376    pub draft_full_streak: u32,
377    /// Adaptive draft depth for the speculative round (None until the
378    /// first round): grows while nearly every draft is accepted, shrinks
379    /// when fewer than half are. The verify's cost climbs with the rows on
380    /// a discrete card (RTX PRO 4000: 52 ms at 2 rows, 74 at 5, 80 at 6),
381    /// so prose wants k≈3 and code or the repetitive bench k≈5 — measured
382    /// 33.6 vs 27.6 tok/s on an essay at k=3 vs 5, 45.6 vs 38 on code.
383    /// `CMF_GRAPH_SPEC_K` pins it.
384    pub spec_k_adapt: Option<usize>,
385    /// EWMA of the accepted fraction that drives `spec_k_adapt`.
386    pub spec_acc_ewma: f32,
387    /// Native Metal over a q4tp trunk: how often draft `j` holds once the
388    /// one before it held, a running average (see `metal_spec_depth`).
389    pub spec_hold: [f32; 7],
390    /// wgpu: what a round of k drafts costs on this device, a running
391    /// average of its wall in ms (0 until a depth has run twice), the rounds
392    /// each depth has run, and the rounds the depth still stays where the
393    /// last change put it (`wgpu_spec_depth`).
394    spec_wall: [f32; 7],
395    spec_wall_n: [u8; 7],
396    spec_k_dwell: u8,
397    /// wgpu: a plain token's time as a speculation trial last measured it,
398    /// and the position it was measured at. A later request's trial decides
399    /// from it instead of decoding eight plain tokens again.
400    spec_plain_ms: (f64, usize),
401    /// The same for the DFlash drafter's rounds, and whether the last round
402    /// was one of them.
403    pub dflash_hold: [f32; 7],
404    dflash_last: bool,
405    /// Rounds the DFlash block still sits out, the wait its next lost turn
406    /// costs, and the rounds of its turn so far.
407    dflash_wait: u32,
408    dflash_back: u32,
409    dflash_turn: u32,
410    /// The tokens the turn's rounds landed and what they cost, in plain tokens.
411    dflash_turn_sum: (f32, f32),
412    /// The sidecar's router: how far the target's last rows lean to the
413    /// block's rounds (a running average of `Route::margin`).
414    dflash_lean: f32,
415    /// The depth of the block's rounds on a card whose verify grows with its
416    /// rows, and the running share of drafts they keep (`spec_k_adapt`'s twin).
417    dflash_k_adapt: Option<usize>,
418    dflash_acc_ewma: f32,
419    /// Prompt lookup on native Metal: the drafts it added to a round that
420    /// held, a running average, and the rounds it sits out after that fell
421    /// under `LOOKUP_PAYS`.
422    pub spec_lookup_gain: f32,
423    /// CUDA: the context lookup may fill a 16-row verify window (after a
424    /// lookup round whose drafts all held), else 8 rows (one price there).
425    pub spec_lookup_wide: bool,
426    pub spec_lookup_rest: u32,
427    rng: SplitMix64,
428    sampler_scratch: SamplerScratch,
429    /// Speculative SAMPLING state (graph_spec_step, temperature > 0): the
430    /// correction token a rejected draft produced — committed by the loop
431    /// top in place of a fresh draw — and the per-round draft
432    /// distributions / target scratch, reused so a round allocates
433    /// nothing at the vocab size.
434    spec_forced: Option<u32>,
435    spec_q: Vec<Vec<f32>>,
436    spec_p: Vec<f32>,
437    spec_res: Vec<f32>,
438    /// The same three for the sparse chain (top-k configs).
439    spec_qs: Vec<sampler::Sparse>,
440    spec_ps: sampler::Sparse,
441    spec_ress: sampler::Sparse,
442    /// Which arm the MTP draft block runs on this generation: Some(true)
443    /// = the whole-token graph (device attention, one submit a step),
444    /// Some(false) = the per-op path; None = not decided yet. Decided
445    /// on the first draft and held, because the two arms keep the MTP
446    /// KV in different places (device mirror vs the CPU cache) and a
447    /// mid-run switch would read the wrong one.
448    mtp_graph_mode: Option<bool>,
449    /// The DFlash block drafter of the model's sidecar (`CMF_DFLASH=1`): it
450    /// drafts a round in one block from the trunk's tapped layer outputs.
451    pub dflash: Option<Box<crate::dflash::Drafter>>,
452    /// The tapped rows of the verify in flight, joined a row at a time, and
453    /// their first position: the accepted ones become the drafter's context.
454    dflash_rows: Option<(usize, Vec<f32>)>,
455    /// Rows the wgpu graphs kept for the drafter, `(first position, rows as
456    /// [row][layer][hidden])` in the order the graphs ran: a prompt's and a
457    /// plain token's become context at the next round, a verify's are taken
458    /// by the round that ran it.
459    dflash_taps: std::sync::Mutex<Vec<(usize, Vec<f32>)>>,
460    /// The sidecar's block is the trunk's only drafter (the model has no MTP
461    /// block): the wgpu graphs keep its rows without being asked to.
462    pub(crate) dflash_solo: bool,
463    /// The first position whose tapped rows a DFlash drafter can still
464    /// read once the prompt is in (its layers' widest window back from the
465    /// prompt's end): the prompt's chunks before it keep none.
466    dflash_tap_from: usize,
467    /// The Metal verify graph of the round in flight, between its sync
468    /// (logits read) and the commit that replays the accepted prefix.
469    #[cfg(target_os = "macos")]
470    metal_verify: Option<MetalVerifyPending>,
471    /// Precomputed RoPE inverse frequencies [head_dim/2]. Arc: the
472    /// forward path clones a handle to escape the &mut self borrow —
473    /// cloning the table itself was a per-forward allocation.
474    pub(crate) inv_freq: std::sync::Arc<Vec<f32>>,
475    /// Reusable norm buffers for the decode hot path (roadmap §3 P0:
476    /// steady-state forward should not heap-allocate). Disjoint field
477    /// from `weights`/`kv_cache`, so split borrows keep working.
478    ws: ForwardScratch,
479    /// Persistent worker pool (None = serial; see CMF_THREADS).
480    pool: Option<std::sync::Arc<Pool>>,
481    // ── Dynamic per-token skill routing (spec §9, claim 14/16) ──
482    /// Source model, retained so a skill switch can re-resolve the
483    /// touched layers' FFN tensors (Mapped = mmap pointers, cheap).
484    pub(crate) model: Option<std::sync::Arc<cortiq_core::CmfModel>>,
485    /// Masks present → weights are dequantized f32 (rebuild path).
486    pub(crate) dyn_force_f32: bool,
487    /// Per-skill FFN layers actually replaced (derived from tensors, not
488    /// the meta `layers` field — ru2 replaces down_proj in 0..23 while
489    /// its meta says [20..23]). None = skill touches non-FFN tensors →
490    /// ineligible for cheap dynamic switching (honest refusal).
491    pub(crate) dyn_skill_layers: Vec<Option<Vec<usize>>>,
492    /// Currently overlaid skill (index into model.header.skills); None =
493    /// backbone. Set at load time to the statically-overlaid skill so
494    /// `set_active_skill(None)` correctly reverts it (else a static
495    /// skill would silently persist — the union-diff assumes dyn_active
496    /// always mirrors the live overlay). Switched by `set_active_skill`.
497    pub(crate) dyn_active: Option<usize>,
498    /// Pipeline was loaded with a soft blend (materialized working
499    /// tensors, not a single skill index) → dynamic routing refuses:
500    /// there is no single index to revert the blend from.
501    pub(crate) dyn_blend_loaded: bool,
502    /// Layer whose post-residual hidden feeds the router φ (shared by
503    /// swarm skills). None = φ capture off.
504    pub(crate) dyn_phi_layer: Option<usize>,
505    /// EMA of φ at `dyn_phi_layer` over the decode window (on-policy).
506    dyn_phi_ema: Vec<f32>,
507    dyn_phi_seen: usize,
508    /// φ rows a device token graph kept at `dyn_phi_layer` (its layer taps):
509    /// the graph runs the router's layer on the card, so the host loop's φ
510    /// hook never sees it; `forward_layers_upto` folds these into the EMA.
511    dyn_phi_tap: std::sync::Mutex<Option<Vec<f32>>>,
512    /// Hysteresis router driving per-token skill switches during decode
513    /// (None = static/no dynamic routing). Taken out during generation.
514    pub dyn_router: Option<crate::swarm::DynRouter>,
515    /// O(1) Nyström attention setting (CLI/env/header-hint resolved by
516    /// the caller; None = plain cache attention everywhere).
517    o1_cfg: Option<crate::nystrom::O1Cfg>,
518    /// A turbo file: the far field on long prompts only (`cortiq far-turbo`).
519    pub(crate) o1_turbo: Option<O1Turbo>,
520    /// Over a far field the draft head starts at this prompt row, and counts from it.
521    mtp_pos_base: usize,
522    /// A whole prompt's tail rows read by the far field's prefix (the draft
523    /// head is warmed over them).
524    o1_prefix_tail: Vec<f32>,
525    /// The CUDA hybrid arm's chat snapshot: the prompt ids before the last
526    /// turn's assistant header, whose GDN states the card keeps a copy of
527    /// (`gpu::gdn_snapshot`). The next turn that starts with them goes back
528    /// there and reads only what follows.
529    gdn_snap: Option<Vec<u32>>,
530    /// The draft head's base position when the last turn warmed it over
531    /// its whole prompt on the batched path (None otherwise): its rows from
532    /// there to that prompt's end are prompt rows a chat snapshot keeps.
533    mtp_warm_base: Option<usize>,
534    /// Bumped once per collecting→sealed transition — the GPU state mirror
535    /// re-uploads when it sees a new epoch (each fresh sealed state).
536    o1_epoch: u64,
537    /// Per-layer o1 flags derived from `o1_cfg` (Full layers only).
538    o1_flags: Vec<bool>,
539    /// Emit a structured per-token trace (B4 telemetry channel). Off by
540    /// default — the runtime is silent unless observation is requested.
541    trace: bool,
542    /// Confidence-calibration temperature (B1): reported probability is
543    /// softmax(logits / calib_temp). 1.0 = raw. Set from header.calibration.
544    calib_temp: f32,
545    /// Process-unique id keying this pipeline's device KV mirrors.
546    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
547    graph_kv_id: u64,
548    /// Decode asks the token graph to also run final-norm + lm_head on
549    /// the device (drops the separate per-op lm_head round trip).
550    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
551    graph_want_logits: bool,
552    /// NLL quality gates require the graph's fused head rather than silently
553    /// accepting a CPU head fallback. Generation keeps the historical
554    /// best-effort `graph_want_logits` behavior.
555    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
556    graph_head_required: bool,
557    /// Logits the graph produced for the token just forwarded (taken by
558    /// the decode loop; None = compute on the CPU path).
559    graph_logits: Option<Vec<f32>>,
560    /// Packed Embryo graph model, built lazily on the first eligible
561    /// resident call so other architectures pay no packing cost.
562    embryo_graph: Option<std::sync::Arc<crate::gpu::EmbryoGraphModel>>,
563    /// The wide token path refused this file: a matrix is not exactly f16.
564    embryo_wide_refused: bool,
565    /// This pipeline's token graph refused for a STRUCTURAL reason (its
566    /// own weights / layer kinds): not retried. Per pipeline, never
567    /// process-wide: a skill lane whose pack does not build must not flip
568    /// the backbone slot mid-sequence onto the host path (and a new lane
569    /// must not clear the backbone's verdict) — R4/NF-2.
570    graph_refused: std::sync::atomic::AtomicBool,
571    /// Token embeddings are multiplied by this at input (Gemma: √hidden).
572    pub embed_multiplier: f32,
573    /// Attention score scale (1/√head_dim unless the arch overrides —
574    /// Gemma's query_pre_attn_scalar).
575    pub attn_scale: f32,
576    /// Sliding-window attention: (window, every-Nth-layer-is-global
577    /// pattern) — Gemma-3.
578    pub swa: Option<(usize, usize)>,
579    /// Sliding-window tail trimming, `(slack, align)` for
580    /// `LayerKvCache::trim_window`: every layer with a window keeps only
581    /// the rows its window can still read (Spark-X2.5: 576..639 rows per
582    /// 512-window layer instead of the whole context — 27 of the 4B's 36
583    /// layers). Set at load for Spark-X2.5 only (`CMF_SWA_TRIM=0` turns
584    /// it off); None keeps every row, as every other model always has.
585    pub swa_trim: Option<(usize, usize)>,
586    /// On the wgpu graphs a full-attention layer of the call's own geometry
587    /// takes the uniform arms (f16 mirror rows, the flash-decoding attend)
588    /// beside sliding layers on their rings, instead of every layer going
589    /// the per-layer-geometry kernels because one of them slides. Set at
590    /// load for Aion (`CMF_MIXED_GEOM=0` turns it off).
591    pub uniform_full_layers: bool,
592    /// Prompt end of the current turn: the tail trim keeps every row a
593    /// rollback to it still reads (`LayerKvCache::trim_window_anchored`),
594    /// so the next chat turn can drop this turn's answer.
595    swa_trim_anchor: usize,
596    /// Fewest prompt rows the Metal chunk prefill graph takes; a shorter
597    /// chunk walks the layers on the host. 32 since the graph landed
598    /// (measured on Qwen2.5-0.5B); Spark-X2.5/X2.6 take 8 (`loader`).
599    pub chunk_min_rows: usize,
600    /// A far field's exact prefix rides the Metal chunk graph, which then also
601    /// keeps the collecting layers' queries (`o1_prefix_on_metal`).
602    o1_chunk_prefix: bool,
603    /// The batched wgpu graph declined this dense stack's prompt: later
604    /// prompts read chunked on the host walk (`graph_prefill_preferred`).
605    dense_batch_declined: std::sync::atomic::AtomicBool,
606    /// Explicit local/global schedule for architectures that cannot be
607    /// represented by Gemma's every-Nth-global convention.
608    pub sliding_layers: Option<Vec<bool>>,
609    /// Per-layer flag: this layer runs WITHOUT RoPE. Recursive Flint applies
610    /// position encoding only on its sliding-window layers; its 14
611    /// full-attention layers have none. The rotary dim of such a layer is 0,
612    /// which is what the attention kernel reads.
613    pub no_rope_layers: Option<Vec<bool>>,
614    /// Ripple's value residual: per layer, the blend `sigmoid(value_res_lambda)` of the lerp
615    /// that feeds V, `lerp(embedding, normed, blend)`. None = V reads the normed input.
616    pub value_blend: Option<Vec<f32>>,
617    /// The scaled embedding rows of the positions in flight (one, a pair's two, a chunk's).
618    vres_e0: Vec<f32>,
619    /// The rows V projects in the layer being run.
620    vres_in: Vec<f32>,
621    /// Natively bounded anchor record (`arch.anchor_core`): the file's
622    /// operator, installed once at load. `Some` = the model is
623    /// bounded-native — `--o1`/`CMF_O1*` are refused, prefix reuse and
624    /// the penalty window are bounded, and no anchor layer stores
625    /// anything per position.
626    pub anchor_core: Option<cortiq_core::AnchorCoreConfig>,
627    /// The `[W][rd/2]` relative-rotation table every bounded layer shares
628    /// (built from `inv_freq` once the RoPE setup is final).
629    bounded_rope: Option<std::sync::Arc<crate::bounded::BoundedRope>>,
630    /// Bounded prefix-reuse key (length + rolling hash + tail) of a
631    /// bounded-native model; `kv_history` stays empty there so nothing
632    /// in the pipeline grows with the dialogue.
633    pub kv_prefix: KvPrefix,
634    /// Prompt positions the last `generate*` call actually forwarded
635    /// (prefix reuse subtracts what the cache already held).
636    pub last_prefill_tokens: usize,
637    /// RoPE table of the sliding (local) layers, when they use their
638    /// own base frequency (Gemma-3: 10k local vs 1M global).
639    pub inv_freq_local: Option<std::sync::Arc<Vec<f32>>>,
640    pub rotary_dim_local: Option<usize>,
641    pub rope_scale: f32,
642    pub rope_scale_local: f32,
643    /// Gemma-4: global layers run their own geometry — (head_dim,
644    /// num_kv_heads); sliding layers keep the base fields.
645    pub global_attn: Option<(usize, usize)>,
646    /// Gemma-4: the global layers' proportional RoPE table (len
647    /// global_head_dim/2, zero-padded tail = identity rotation).
648    pub inv_freq_global: Option<std::sync::Arc<Vec<f32>>>,
649    /// Scale-less RMS normalization of V heads before caching (Gemma-4).
650    pub attn_v_norm: bool,
651    /// HunYuan dense: per-head q/k norm runs after RoPE (see the arch flag).
652    pub qk_norm_after_rope: bool,
653    /// The per-head `self_attn.g_proj` output gate uses sigmoid
654    /// (Spark-X2.5) instead of softplus (Laguna).
655    pub proj_gate_sigmoid: bool,
656    /// Final-logit soft-capping C: logits = C·tanh(logits/C) (Gemma-4).
657    pub final_softcap: Option<f32>,
658    /// Cortiq Embryo hierarchical head: cluster matrix [C, hidden]. The
659    /// flat logits h·Eᵀ are turned into the two-level log-probabilities
660    /// log softmax_c(h·Cᵀ)[c(v)] + log softmax_{s∈c(v)}(h·E_c(v)ᵀ)[v].
661    pub head_clusters: Option<std::sync::Arc<Vec<f32>>>,
662    /// Gemma-2 attention-logit soft-capping (0.0 = off).
663    pub attn_softcap: f32,
664    /// Compute per-token confidence (a full-vocab softmax each
665    /// token). On by default; `bench --core` turns it off to match
666    /// llama-bench's core timing.
667    confidence_on: bool,
668    /// Test-only one-shot forward failure, scoped to this pipeline so
669    /// parallel scoring tests cannot consume one another's injection.
670    #[cfg(test)]
671    nll_test_fail_at: Option<usize>,
672    /// Test-only route override; avoids mutating the process-wide
673    /// `CMF_PREFILL` environment variable while forcing the serial path.
674    #[cfg(test)]
675    nll_test_force_serial: bool,
676}
677
678#[cfg(target_os = "macos")]
679impl Drop for Pipeline {
680    fn drop(&mut self) {
681        // the async replay writes into `kv_cache` Vecs about to be freed
682        let _ = crate::gpu_metal::wait_replay();
683        crate::gpu::kv_mirror_drop(self.graph_kv_id);
684    }
685}
686
687#[cfg(not(target_os = "macos"))]
688impl Drop for Pipeline {
689    fn drop(&mut self) {
690        // The wgpu resident Embryo graph owns recurrent/KV buffers keyed by
691        // this pipeline's sequence id.  Release that sequence image when a
692        // pooled pipeline is dropped; model weights stay cached for reuse.
693        crate::gpu::graph_kv_reset(self.graph_kv_id);
694    }
695}
696
697/// Model weights. Matrices are `QTensor` (owned f32 for small models
698/// and tests — bit-identical to the historical paths — or quantized
699/// bytes zero-copy from the CMF mmap for big models). 1-D norms are
700/// always small and stay f32.
701pub struct PipelineWeights {
702    /// Embedding table: [vocab_size, hidden_size]
703    pub embed_tokens: QTensor,
704    /// Per-layer weights
705    pub layers: Vec<LayerWeights>,
706    /// LM head: [vocab_size, hidden_size]
707    pub lm_head: QTensor,
708    /// Final norm: [hidden_size]
709    pub final_norm: Vec<f32>,
710}
711
712/// One transformer layer: shared norms + MLP, attention by kind.
713pub struct LayerWeights {
714    pub input_norm: Vec<f32>,
715    /// The pre-FFN norm (`post_attention_layernorm` classically;
716    /// `pre_feedforward_layernorm` on Gemma-2/3 sandwich layers).
717    pub post_norm: Vec<f32>,
718    /// Gemma-2/3 sandwich: norm applied to the ATTENTION OUTPUT before
719    /// its residual add (`post_attention_layernorm` there).
720    pub attn_out_norm: Option<Vec<f32>>,
721    /// Gemma-4: the whole layer output is multiplied by this scalar.
722    pub layer_scale: Option<f32>,
723    /// Gemma-2/3 sandwich: norm applied to the FFN OUTPUT before its
724    /// residual add (`post_feedforward_layernorm`).
725    pub ffn_out_norm: Option<Vec<f32>>,
726    pub ffn: FfnKind,
727    pub attn: AttnKind,
728}
729
730/// FFN gate activation: SiLU (SwiGLU family), tanh-GELU (Gemma's GeGLU),
731/// or a source-specific gated contract. A property of the model, carried on
732/// every FFN triple.
733#[derive(Clone, Copy, PartialEq, Debug, Default)]
734pub enum Act {
735    #[default]
736    Silu,
737    GeluTanh,
738    /// Exact erf GELU (HF `hidden_act = "gelu"`: Spark-X2.5).
739    Gelu,
740    /// Kimi-K3 SituAndMul: BOTH halves transform —
741    /// a = β·tanh(g/β)·σ(g), up' = linβ·tanh(u/linβ) (linβ>0), out = a·up'.
742    Situ {
743        beta: f32,
744        linear_beta: f32,
745    },
746    /// MiniMax M3's SwiGLU-OAI: upper-clamped gate, symmetrically clamped
747    /// up branch, `sigmoid(alpha * gate)`, and a `+1` up-branch offset.
748    /// It deliberately has no generic GPU graph arm until a matching kernel
749    /// exists; CPU uses the exact scalar reference in `inference`.
750    SwiGluOai {
751        alpha: f32,
752        limit: f32,
753    },
754    /// Ripple's clamped SwiGLU (`ModelArch::ffn_clamp`): the gate is cut from above and the up
755    /// branch on both sides at `limit`, then `silu(gate)·up`. The contract of the
756    /// `swiglu_limit` kernels.
757    SiluClamp {
758        limit: f32,
759    },
760}
761
762impl Act {
763    pub fn from_arch(name: &str) -> Self {
764        if name == "gelu_tanh" {
765            Self::GeluTanh
766        } else if name == "gelu" {
767            Self::Gelu
768        } else {
769            Self::Silu
770        }
771    }
772
773    /// Arch-driven constructor (activation name + situ betas).
774    pub fn from_arch_full(arch: &cortiq_core::ModelArch) -> Self {
775        match arch.hidden_act.as_str() {
776            "situ" => Self::Situ {
777                beta: arch.activation_situ_beta.unwrap_or(1.0) as f32,
778                linear_beta: arch.activation_situ_linear_beta.unwrap_or(0.0) as f32,
779            },
780            // `swigluoai` alone is deliberately not a generic activation
781            // alias.  Its alpha/limit are part of MiniMax M3's checked
782            // source contract, and accepting that string on an unrelated
783            // architecture would silently impose M3 math on its FFN.
784            "swigluoai" if arch.arch_name == "minimax_m3_vl" => Self::SwiGluOai {
785                alpha: 1.702,
786                limit: 7.0,
787            },
788            "silu" if arch.ffn_clamp.is_some_and(|l| l > 0.0) => Self::SiluClamp {
789                limit: arch.ffn_clamp.unwrap_or(0.0),
790            },
791            other => Self::from_arch(other),
792        }
793    }
794
795    /// The clamp of a dense FFN's pre-activations (0 = none).
796    #[inline]
797    pub fn clamp_limit(self) -> f32 {
798        match self {
799            Self::SiluClamp { limit } => limit,
800            _ => 0.0,
801        }
802    }
803
804    /// The wgpu graphs' dense FFN: an arm and the clamp its kernels take beside it. Only the
805    /// builders that hand the clamp on may ask; every other door reads `graph_act`, which has
806    /// no arm for a clamped SiLU.
807    pub(crate) fn dense_graph_contract(self) -> Option<(crate::gpu::GraphAct, f32)> {
808        match self {
809            Self::SiluClamp { limit } => Some((crate::gpu::GraphAct::Silu, limit)),
810            // The M3 arm carries its frozen clamp inside its code.
811            _ => self.wgpu_graph_act().map(|a| (a, 0.0)),
812        }
813    }
814
815    /// Construct the MiniMax M3 SwiGLU-OAI activation from a checked model
816    /// contract. This is intentionally explicit rather than recognizing an
817    /// arbitrary `hidden_act` string: callers must validate `alpha` and
818    /// `limit` against their source architecture before enabling it.
819    #[inline]
820    pub fn swiglu_oai(alpha: f32, limit: f32) -> Self {
821        Self::SwiGluOai { alpha, limit }
822    }
823
824    #[inline]
825    pub fn apply(self, x: f32) -> f32 {
826        match self {
827            Self::Silu => inference::silu(x),
828            Self::GeluTanh => inference::gelu_tanh(x),
829            Self::Gelu => inference::gelu_erf(x),
830            Self::Situ { beta, .. } => beta * (x / beta).tanh() * (1.0 / (1.0 + (-x).exp())),
831            Self::SwiGluOai { alpha, limit } => {
832                let gate = x.min(limit);
833                gate * (1.0 / (1.0 + (-alpha * gate).exp()))
834            }
835            Self::SiluClamp { limit } => inference::silu(x.min(limit)),
836        }
837    }
838
839    /// Gated combine — the FFN contract. Situ transforms the UP half
840    /// too, so callers must use this instead of apply(g)·u.
841    #[inline]
842    pub fn combine(self, g: f32, u: f32) -> f32 {
843        match self {
844            Self::Situ { linear_beta, .. } if linear_beta > 0.0 => {
845                self.apply(g) * (linear_beta * (u / linear_beta).tanh())
846            }
847            Self::SwiGluOai { alpha, limit } => {
848                inference::swiglu_oai(g, u, alpha, 1.0, Some(limit))
849            }
850            Self::SiluClamp { limit } => self.apply(g) * u.clamp(-limit, limit),
851            _ => self.apply(g) * u,
852        }
853    }
854
855    /// The wgpu graphs' arm for this activation; None = no device kernel
856    /// computes it, and the graph builder must refuse the layer (the dense
857    /// graph FFN once computed SiLU for whatever the model asked for).
858    pub fn graph_act(self) -> Option<crate::gpu::GraphAct> {
859        match self {
860            Self::Silu => Some(crate::gpu::GraphAct::Silu),
861            Self::Gelu => Some(crate::gpu::GraphAct::GeluErf),
862            Self::GeluTanh => Some(crate::gpu::GraphAct::GeluTanh),
863            Self::Situ { .. } | Self::SwiGluOai { .. } | Self::SiluClamp { .. } => None,
864        }
865    }
866
867    /// The WGPU graph arm.  Keep this deliberately separate from
868    /// `graph_act`: OAI needs its dedicated code rather than a generic SiLU
869    /// fallback.  Only the frozen MiniMax-M3 source constants get a device
870    /// code; a future OAI-like architecture with different constants must add
871    /// and test its own kernel contract.
872    pub(crate) fn wgpu_graph_act(self) -> Option<crate::gpu::GraphAct> {
873        // A clamped SiLU is an arm AND a limit: a door that reads the arm alone would run it
874        // unclamped, so it gets none here (`dense_graph_contract` hands both on).
875        if matches!(self, Self::SiluClamp { .. }) {
876            return None;
877        }
878        self.moe_job_graph_contract().map(|(act, _)| act)
879    }
880
881    /// The exact device contract for a gate/up/down MoE job.  OAI is not a
882    /// generic "clamped SiLU": code 3 commits a backend to MiniMax M3's
883    /// alpha, asymmetric up transform, and frozen clamp.  Keep the clamp
884    /// alongside the marker so a backend cannot accidentally run code 3 with
885    /// a nearby model's limit.
886    pub(crate) fn moe_job_graph_contract(self) -> Option<(crate::gpu::GraphAct, f32)> {
887        match self {
888            Self::SwiGluOai { alpha, limit }
889                if alpha.to_bits() == 1.702f32.to_bits()
890                    && limit.to_bits() == 7.0f32.to_bits() =>
891            {
892                Some((crate::gpu::GraphAct::SwiGluOaiM3, 7.0))
893            }
894            // The `swiglu_limit` kernels' own contract: gate from above, up on both sides.
895            Self::SiluClamp { limit } => Some((crate::gpu::GraphAct::Silu, limit)),
896            _ => self.graph_act().map(|act| (act, 0.0)),
897        }
898    }
899}
900
901/// Dense gated triple — the FFN of a dense layer or of one expert.
902pub struct DenseFfn {
903    pub gate_proj: QTensor,
904    pub up_proj: QTensor,
905    pub down_proj: QTensor,
906    /// Gate activation (SiLU default; Gemma: tanh-GELU).
907    pub act: Act,
908    /// `down_proj` stored transposed (`[inter, hidden]`), when the file
909    /// carries it. Only the per-token sparse path reads it: a neuron's
910    /// down weights are a contiguous ROW there, so the token's chosen
911    /// neurons are the only bytes touched. `None` = the ordinary layout,
912    /// and the sparse path stays off.
913    pub down_t: Option<QTensor>,
914    /// Task tubes (spec: defragged task-conditional width). The three
915    /// matrices above are the CORE — the neurons every task computes;
916    /// each tube is an independently quantized slice of the SAME layer
917    /// holding the neurons only some tasks need. A tube is a normal
918    /// tensor triple, so every kernel runs it unchanged, and the bytes
919    /// of an inactive tube are never read. Empty = ordinary dense FFN.
920    pub segs: Vec<FfnSeg>,
921}
922
923/// One task tube: a contiguous slice of a layer's FFN neurons, stored
924/// as its own `[w, hidden]` / `[hidden, w]` triple. `start` is the
925/// neuron's index in the layer's FULL space (core first, then tubes in
926/// order) — the bit a task mask sets to switch this tube on.
927pub struct FfnSeg {
928    pub gate: QTensor,
929    pub up: QTensor,
930    pub down: QTensor,
931    pub start: usize,
932    pub width: usize,
933}
934
935/// FFN operator of a layer, decided by tensor presence at load time
936/// (router `mlp.gate.weight` in the directory = MoE layer).
937pub enum FfnKind {
938    Dense(DenseFfn),
939    /// Mixture-of-Experts (Qwen2-MoE / Qwen3-MoE): softmax over ALL
940    /// expert logits → top-k, optional renorm; experts stay quantized
941    /// in mmap — only the selected ones are touched per token.
942    Moe(MoeFfn),
943    /// Gemma-4 MoE: a dense MLP branch AND a routed-expert branch in
944    /// the SAME layer, each with its own norm sandwich. The dense
945    /// branch reads the pre-FFN-normed input; the expert branch (and
946    /// the router) read the RAW residual through `pre_norm_2`:
947    ///   d = post_norm_1(dense(x̂));  m = post_norm_2(Σwₑ·FFNₑ(pre_norm_2(h)))
948    ///   ffn_out = d + m   (the caller's ffn_out_norm + residual follow)
949    DenseMoe(Box<DenseMoeFfn>),
950}
951
952/// Gemma-4 dual-branch FFN (see `FfnKind::DenseMoe`).
953pub struct DenseMoeFfn {
954    pub dense: DenseFfn,
955    pub moe: MoeFfn,
956    /// post_feedforward_layernorm_1 — dense-branch output norm.
957    pub post_norm_1: Vec<f32>,
958    /// pre_feedforward_layernorm_2 — expert-branch input norm (applied
959    /// to the RAW residual, not the pre-FFN-normed activation).
960    pub pre_norm_2: Vec<f32>,
961    /// post_feedforward_layernorm_2 — expert-branch output norm.
962    pub post_norm_2: Vec<f32>,
963}
964
965pub struct MoeFfn {
966    /// Router `mlp.gate.weight` [num_experts, hidden].
967    pub router: QTensor,
968    pub experts: Vec<DenseFfn>,
969    pub top_k: usize,
970    pub norm_topk_prob: bool,
971    /// Router scores per-expert with a sigmoid (LFM2-MoE / DeepSeek-V3
972    /// `noaux_tc`) instead of a softmax over all experts (Qwen).
973    pub router_sigmoid: bool,
974    /// Addend in the selected-score denominator of a sigmoid router.
975    /// Most supported checkpoints use the historical `1e-6` floor; Flint's
976    /// reference routing uses `1e-20`; MiniMax M3.1 preserves the same FP32
977    /// `sum + 1e-20` law. This is per-MoE rather than a global family switch
978    /// because the same sigmoid routing law has several contracts.
979    pub sigmoid_denom_eps: f32,
980    /// Per-expert selection bias `mlp.expert_bias` [num_experts]
981    /// (LFM2-MoE): added to the sigmoid scores for the top-k CHOICE only;
982    /// the gathered weights use the unbiased scores. None = no bias.
983    pub expert_bias: Option<Vec<f32>>,
984    /// Top-k weights are multiplied by this after the optional renorm
985    /// (LFM2-MoE `routed_scaling_factor`; 1.0 = off).
986    pub routed_scaling: f32,
987    /// Adaptive routing (CMF_MOE_TAU, opt-in): keep the smallest
988    /// prefix of the top-k whose renormalized mass reaches τ —
989    /// confident tokens touch 1–2 experts, flat ones keep all k.
990    /// MoE decode is memory-bound, so skipped experts are skipped
991    /// weight traffic. None = classic fixed top-k (bit-identical).
992    pub route_tau: Option<f32>,
993    /// Always-on shared expert. Qwen2-MoE carries an additional sigmoid
994    /// gate; Laguna adds the shared expert unconditionally (`None`).
995    pub shared: Option<(DenseFfn, Option<QTensor>)>,
996    /// Expert-selection counters (truncated Fisher B-field of claim 12:
997    /// routing frequency during calibration). Filled by every forward,
998    /// read by the CLI via CMF_MOE_STATS. RefCell: decode is single-threaded.
999    pub stats: std::cell::RefCell<Vec<u64>>,
1000    /// Per-CHANNEL sum of squares of this FFN's input, accumulated over a
1001    /// calibration run (`CMF_RMS_TRACE`). These are the RMS activation
1002    /// traces AWNP needs: raw weight magnitude says every channel matters
1003    /// equally, and the question AWNP asks is whether the ACTIVATIONS
1004    /// disagree. Off unless the env var is set — an f64 add per channel
1005    /// per token is cheap, but not free.
1006    pub act_sq: std::cell::RefCell<Vec<f64>>,
1007    /// Raw FFN-input rows captured for the layers named by `CMF_ACT_DUMP`
1008    /// (`"9,19"`). AWNP is nullspace PROJECTION: after dropping channels the
1009    /// survivors are refitted to absorb what was removed, and how much they
1010    /// can absorb depends on the activation COVARIANCE, not on per-channel
1011    /// RMS. Per-channel numbers can only bound the cost from above.
1012    pub act_rows: std::cell::RefCell<Vec<f32>>,
1013    /// Task mask over routed experts (DTG-MA over MoE, claim-12 B-field
1014    /// applied): `false` experts are excluded from selection, the
1015    /// softmax renormalizes over the allowed set. Built by the loader
1016    /// from CMF_MOE_MASK=<stats.json> + CMF_MOE_MASK_COVER. None = all.
1017    pub mask: Option<Vec<bool>>,
1018    /// Gemma-4: per-expert weight scale applied AFTER the top-k renorm
1019    /// (`router.per_expert_scale`). None = 1.0 everywhere.
1020    pub per_expert_scale: Option<Vec<f32>>,
1021    /// Gemma-4: the router reads a SCALE-LESS rms-norm of its input
1022    /// (the constant gain router.scale·√hidden is folded into the
1023    /// router weights at convert time).
1024    pub router_input_norm: bool,
1025    /// Cortiq Embryo: resonance routing (P1) — the "logits" are
1026    /// bias_e − ‖(x−μ_e) − U_eᵀU_e(x−μ_e)‖², argmax = the expert whose
1027    /// descriptor reconstructs the input best. `router` is a placeholder.
1028    pub resonance: Option<Resonance>,
1029    /// Growth records (`kind = "expert_append"`, spec §9.5.1) mounted
1030    /// behind the trunk experts, one entry per grown expert IN THE ORDER
1031    /// they sit in `experts` (the tail `experts[experts.len() - grown.len()..]`).
1032    /// The trunk keeps `experts.len() - grown.len()` experts. Empty on a
1033    /// gated MoE, on a file without records and under `CMF_GROWTH=off`.
1034    pub grown: Vec<GrownExpert>,
1035}
1036
1037/// One grown expert of an `expert_append` record as the loader mounted it.
1038#[derive(Debug, Clone, PartialEq, Eq)]
1039pub struct GrownExpert {
1040    /// The record's skill id.
1041    pub record: String,
1042    /// Position of the record in `header.skills`.
1043    pub record_index: usize,
1044    pub layer: usize,
1045    /// The index the tensor name declares (`experts.{e}` — the chain rule
1046    /// of the format); the executed position may be smaller when an
1047    /// earlier record of the layer is not mounted.
1048    pub expert: usize,
1049}
1050
1051/// Per-expert resonance descriptors of one MoE layer (`mlp.desc.*`).
1052pub struct Resonance {
1053    /// [E, hidden]
1054    pub mu: Vec<f32>,
1055    /// [E, k, hidden] orthonormal directions (k may be 0)
1056    pub u: Vec<f32>,
1057    pub k: usize,
1058    /// [E] selection bias (loss-free balancing, trained online)
1059    pub bias: Vec<f32>,
1060    /// [E] reconstruction-error shell: an expert whose error
1061    /// `‖(x−μ)⊥U‖² = d² − proj` exceeds its shell scores `−∞` (it never
1062    /// wins). `+inf` = no shell — every trunk expert; a grown expert
1063    /// (`expert_append`) carries the finite `desc.shell` its record stores.
1064    /// Empty = no shell anywhere (legacy constructors).
1065    pub shell: Vec<f32>,
1066}
1067
1068/// `CMF_GROWTH_SHELL` state: 0 = not yet read from the environment, 1 = on,
1069/// 2 = off. Process-wide, like the environment it mirrors.
1070static GROWTH_SHELL: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1071
1072/// Is the growth shell applied (`Resonance::scores` −∞ rule, the resident
1073/// graph's packed shell)? `CMF_GROWTH_SHELL=off` disables it for
1074/// measurement; [`set_growth_shell`] overrides the environment in-process
1075/// (`growth-eval --shell`). Default: on.
1076pub fn growth_shell_enabled() -> bool {
1077    use std::sync::atomic::Ordering;
1078    match GROWTH_SHELL.load(Ordering::Relaxed) {
1079        1 => true,
1080        2 => false,
1081        _ => {
1082            let off = std::env::var("CMF_GROWTH_SHELL")
1083                .map(|v| v.eq_ignore_ascii_case("off") || v == "0")
1084                .unwrap_or(false);
1085            GROWTH_SHELL.store(if off { 2 } else { 1 }, Ordering::Relaxed);
1086            !off
1087        }
1088    }
1089}
1090
1091/// Switch the growth shell on/off for this process (`None` = re-read
1092/// `CMF_GROWTH_SHELL` on the next query). A pipeline packed into the
1093/// resident graph BEFORE the switch keeps the shell it was packed with —
1094/// build a new pipeline after switching.
1095pub fn set_growth_shell(on: Option<bool>) {
1096    GROWTH_SHELL.store(
1097        match on {
1098            Some(true) => 1,
1099            Some(false) => 2,
1100            None => 0,
1101        },
1102        std::sync::atomic::Ordering::Relaxed,
1103    );
1104}
1105
1106impl Resonance {
1107    /// Does any expert carry a finite shell (a mounted growth record)?
1108    pub fn has_shell(&self) -> bool {
1109        self.shell.iter().any(|s| s.is_finite())
1110    }
1111
1112    /// The shell the runtime applies right now: the stored one, or all
1113    /// `+inf` when the shell is switched off (`CMF_GROWTH_SHELL=off`).
1114    pub fn effective_shell(&self, ne: usize) -> Vec<f32> {
1115        let mut out = vec![f32::INFINITY; ne];
1116        if growth_shell_enabled() {
1117            for (o, s) in out.iter_mut().zip(&self.shell) {
1118                *o = *s;
1119            }
1120        }
1121        out
1122    }
1123
1124    /// Routing scores for one input row (higher = better). A grown
1125    /// expert whose reconstruction error lies outside its shell gets
1126    /// `−∞` (unless the shell is switched off); trunk rows are the exact
1127    /// bit pattern they were before growth.
1128    pub fn scores(&self, x: &[f32], out: &mut [f32]) {
1129        let h = x.len();
1130        let ne = out.len();
1131        let shell_on = growth_shell_enabled() && !self.shell.is_empty();
1132        for e in 0..ne {
1133            let mu = &self.mu[e * h..(e + 1) * h];
1134            let mut d2 = 0.0f32;
1135            for j in 0..h {
1136                let d = x[j] - mu[j];
1137                d2 += d * d;
1138            }
1139            let mut proj = 0.0f32;
1140            for i in 0..self.k {
1141                let u = &self.u[(e * self.k + i) * h..(e * self.k + i + 1) * h];
1142                let mut p = 0.0f32;
1143                for j in 0..h {
1144                    p += (x[j] - mu[j]) * u[j];
1145                }
1146                proj += p * p;
1147            }
1148            let err = d2 - proj;
1149            out[e] = self.bias.get(e).copied().unwrap_or(0.0) - err;
1150            if shell_on && err > self.shell.get(e).copied().unwrap_or(f32::INFINITY) {
1151                out[e] = f32::NEG_INFINITY;
1152            }
1153        }
1154    }
1155}
1156
1157/// Attention operator of a layer. Extension point: new operators are
1158/// new variants here + a forward in their own module.
1159pub enum AttnKind {
1160    /// GQA softmax attention (+ optional Qwen3.5 qk-norm / output gate).
1161    Full {
1162        wq: QTensor,
1163        wk: QTensor,
1164        wv: QTensor,
1165        wo: QTensor,
1166        q_norm: Option<Vec<f32>>,
1167        k_norm: Option<Vec<f32>>,
1168        output_gate: bool,
1169        /// Laguna: a separate softplus projection applied to the attention
1170        /// output before O. The bool means one scalar per head (broadcast
1171        /// across head_dim); false means one scalar per element.
1172        softplus_gate: Option<(QTensor, bool)>,
1173        /// Qwen2-family projection biases (q, k, v).
1174        bias: Option<(Vec<f32>, Vec<f32>, Vec<f32>)>,
1175    },
1176    /// Canonical linear core (VMF phase attention).
1177    Linear(VmfPhaseWeights),
1178    /// Faithful vendor linear operator (Qwen3.5 GatedDeltaNet).
1179    LinearGdn(GdnWeights),
1180    /// LFM2 gated short-convolution mixer (no KV cache; conv ring state
1181    /// lives in the layer's `linear_state`).
1182    ShortConv(ShortConvWeights),
1183    /// DeepSeek-V2 Multi-head Latent Attention. v1 executes it as
1184    /// expand-to-MHA: the latent is projected per token, K/V expand to
1185    /// every head and live in the ordinary cache (K head layout
1186    /// [rope | nope] so the standard partial rotary covers the shared
1187    /// rope key; V rows are zero-padded to the K head_dim and the pad
1188    /// is sliced off before O). Latent-resident cache is a later
1189    /// optimization, not a semantic change.
1190    Mla(Box<MlaWeights>),
1191    /// Kimi Delta Attention (Kimi Linear / Kimi-K3): per-channel decayed
1192    /// delta rule, separate q/k/v short convs, sigmoid-gated output norm.
1193    /// State lives in the layer's `linear_state` (no KV cache).
1194    Kda(Box<crate::linear_core::KdaWeights>),
1195    /// Natively bounded softmax anchor `swa_sink_v1` (Embryo-O1): ring of
1196    /// the last W raw keys with relative RoPE + trained NoPE sinks, one
1197    /// softmax. State is the fixed-size ring in `LayerKvCache::bounded`;
1198    /// nothing is stored per position (see `crate::bounded`).
1199    Bounded(Box<crate::bounded::BoundedWeights>),
1200}
1201
1202/// DeepSeek-V2 MLA projections (see `AttnKind::Mla`).
1203pub struct MlaWeights {
1204    /// `[nh·(rope+nope), hidden]` (or `[…, q_lora]` when compressed) —
1205    /// the converter permutes each head rope-first so rotary_dim =
1206    /// qk_rope works unchanged.
1207    pub q_proj: QTensor,
1208    /// Compressed q (K3/V3 class): x → q_a `[q_lora, hidden]` →
1209    /// rms(q_a_norm) → q_proj (= q_b). None = direct q (V2-Lite).
1210    pub q_a: Option<QTensor>,
1211    pub q_a_norm: Option<Vec<f32>>,
1212    /// `kv_a_proj_with_mqa` `[lora + rope, hidden]` (latent first).
1213    pub kv_a: QTensor,
1214    /// RMS-norm weights over the latent (`kv_a_layernorm`, [lora]).
1215    pub kv_a_norm: Vec<f32>,
1216    /// `[nh·(nope+v), lora]` — per head [k_nope | v].
1217    pub kv_b: QTensor,
1218    /// `[hidden, nh·v]`.
1219    pub o_proj: QTensor,
1220    pub nh: usize,
1221    pub qk_rope: usize,
1222    pub qk_nope: usize,
1223    pub v_dim: usize,
1224    pub lora: usize,
1225    /// Softmax scale (1/√(rope+nope), YaRN-mscale-corrected at load).
1226    pub scale: f32,
1227    /// Kimi Linear NoPE: skip the rotary entirely (layout unchanged).
1228    pub nope: bool,
1229}
1230
1231/// Multi-token-prediction head (DeepSeek/Qwen style, spec §2.1):
1232/// `x = eh_proj·[enorm(embed(next)); hnorm(hidden)]` → one transformer
1233/// block over its own KV → shared lm_head. Drafts the token after next;
1234/// the main model verifies, so output is exact — MTP only buys speed.
1235pub struct MtpModule {
1236    pub enorm: Vec<f32>,
1237    pub hnorm: Vec<f32>,
1238    /// [hidden, 2·hidden]
1239    pub eh_proj: QTensor,
1240    pub layer: LayerWeights,
1241    pub final_norm: Vec<f32>,
1242    pub kv: crate::kv_cache::LayerKvCache,
1243}
1244
1245/// Teacher-forced activation statistics for one MTP draft FFN.
1246///
1247/// `mass[i]` is `Σ_rows |activation_i|`; `squared_mass[i]` is
1248/// `Σ_rows activation_i²`, where `activation = act(gate) · up` immediately
1249/// before the draft layer's down projection. `observed_positions` is the
1250/// number of teacher-forced rows that contributed to both arrays.
1251///
1252/// Rows of FFN input the canonical draft probe measures in one batch.
1253const MTP_PROBE_FFN_ROWS: usize = 128;
1254
1255/// [`Pipeline::probe_mtp_ffn`] returns one of these for each actual draft
1256/// layer.  It intentionally has a separate type/API from
1257/// [`Pipeline::probe_ffn_mass`] so a compactor cannot accidentally substitute
1258/// trunk statistics for an MTP sidecar whose FFN has a different width.
1259#[derive(Clone, Debug, PartialEq)]
1260pub struct MtpFfnProbe {
1261    pub mass: Vec<f64>,
1262    pub squared_mass: Vec<f64>,
1263    pub observed_positions: usize,
1264}
1265
1266/// A Metal verify graph after its sync: what the commit needs — the
1267/// graph (per-layer replay scratch), the GDN layers in encode order (their
1268/// CPU states receive the replay), and the attention layers with the CPU
1269/// row count they were encoded against (the accepted rows are pulled from
1270/// the mirror from there).
1271/// One item of the Metal rows-graph plan.
1272#[cfg(target_os = "macos")]
1273enum MetalRowsItem<'a> {
1274    Gdn {
1275        run: Vec<crate::gpu_metal::GdnGpuLayer<'a>>,
1276        first: usize,
1277    },
1278    Attn {
1279        l: crate::gpu_metal::AttnGpuLayer<'a>,
1280        li: usize,
1281        q_norm: Option<&'a [f32]>,
1282        k_norm: Option<&'a [f32]>,
1283        output_gate: bool,
1284        /// Spark-X2.6's per-head gate `[nh × hidden]`.
1285        head_gate: Option<&'a [f32]>,
1286    },
1287}
1288
1289#[cfg(target_os = "macos")]
1290struct MetalVerifyPending {
1291    graph: crate::gpu_metal::VerifyGraph,
1292    gdn_layers: Vec<usize>,
1293    attn_layers: Vec<(usize, usize)>,
1294}
1295
1296/// A round's batched MTP warm-up, submitted but not yet waited
1297/// (`mtp_warm_batch_submit` → `mtp_warm_batch_finish`): the trunk commit's
1298/// GDN replay is queued between the two.
1299#[cfg(target_os = "macos")]
1300struct MetalWarmPending {
1301    graph: crate::gpu_metal::VerifyGraph,
1302    cpu_stored: usize,
1303    b: usize,
1304}
1305
1306#[cfg(target_os = "macos")]
1307enum MetalRowsRun {
1308    /// Capability/preflight refusal before a command buffer was committed.
1309    Declined,
1310    /// A graph was admitted and then failed; callers must clear the sequence
1311    /// rather than replaying it through CPU/serial state.
1312    Failed,
1313    Completed(MetalVerifyPending),
1314}
1315
1316#[cfg(target_os = "macos")]
1317enum MetalPrefillOutcome {
1318    Declined,
1319    Failed,
1320    Completed(Vec<f32>),
1321}
1322
1323#[cfg(target_os = "macos")]
1324enum MetalBatchNllOutcome {
1325    Declined,
1326    Failed(String),
1327    Completed(f64, usize),
1328}
1329
1330/// The speculation trial's phases (see the decode loop): up to five timed
1331/// speculative rounds, eight timed plain tokens, then the faster arm until a
1332/// re-check. Two consecutive rounds with no accepted draft skip directly to
1333/// the plain measurement: another speculative round cannot pay when it emits
1334/// exactly the one token the plain loop would have produced.
1335#[derive(Clone, Copy)]
1336enum SpecTrial {
1337    Spec {
1338        t0: std::time::Instant,
1339        gen0: usize,
1340        rounds: usize,
1341    },
1342    Plain {
1343        t0: std::time::Instant,
1344        gen0: usize,
1345    },
1346    Decided {
1347        spec: bool,
1348        recheck_at: usize,
1349    },
1350}
1351
1352/// `CMF_GRAPH_SPEC_TIME`: 0 = off, 1 = one line per speculative round
1353/// plus the host stamps of any OUTLIER round (wall > 1.4× the running
1354/// median), 2 = the host stamps of every round.
1355pub(crate) fn spec_time_level() -> u8 {
1356    static L: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
1357    *L.get_or_init(|| match std::env::var("CMF_GRAPH_SPEC_TIME") {
1358        Ok(v) => v.trim().parse::<u8>().map(|n| n.max(1)).unwrap_or(1),
1359        Err(_) => 0,
1360    })
1361}
1362
1363/// `GraphMoeBank` reuse across tokens (`CMF_GRAPH_MOE_BANK=0` rebuilds
1364/// every layer's bank on every token, the route before the cache).
1365fn graph_moe_bank_on() -> bool {
1366    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1367    *ON.get_or_init(|| std::env::var("CMF_GRAPH_MOE_BANK").as_deref() != Ok("0"))
1368}
1369
1370/// Decide whether the batched speculative verifier is admitted by the
1371/// user/backend policy, before capability checks.  Native Metal's row-batch
1372/// verifier is deliberately fail-closed by default: it has produced a
1373/// different *emitted* greedy token than the serial path on a real model.
1374/// It remains available only through the documented explicit experiment
1375/// spelling, `CMF_GRAPH_SPEC=1`; other backends retain their historical
1376/// nonzero override behaviour.
1377fn graph_spec_wanted_by_policy(
1378    spec_env: Option<&str>,
1379    spec_default_ok: bool,
1380    penalized: bool,
1381    metal_wgpu: bool,
1382    native_metal: bool,
1383) -> bool {
1384    match spec_env {
1385        Some("0") => false,
1386        Some("1") => true,
1387        // Off native Metal any other value still forces the drafts on, as it
1388        // always did; on native Metal it means the default below.
1389        Some(_) if !native_metal => true,
1390        // Native Metal shares the default since the batched verify passed the
1391        // exact-ID gate over q4tp trunks (`spec_default_ok`): MacBook Air M4,
1392        // Qwen3.8-27B Turbo and OrcaCyber-Nano-1.0, five prompts each, the
1393        // same token ids with drafts and without, 1.45-2.3x the plain decode.
1394        _ => spec_default_ok && !penalized && !metal_wgpu,
1395    }
1396}
1397
1398/// The round's host stamps: `spec_stamp(name)` records the time since
1399/// the previous stamp (the section that just ended) — from anywhere on
1400/// the round's call chain (the Metal verify, the draft step, the commit),
1401/// no plumbing. Off (a single atomic load) unless `CMF_GRAPH_SPEC_TIME`
1402/// is set; one decode thread at a time is assumed (diagnostics).
1403struct SpecStampLog {
1404    t_last: std::time::Instant,
1405    items: Vec<(&'static str, f32)>,
1406}
1407
1408static SPEC_STAMPS: std::sync::Mutex<Option<SpecStampLog>> = std::sync::Mutex::new(None);
1409
1410pub(crate) fn spec_stamp(name: &'static str) {
1411    if spec_time_level() == 0 {
1412        return;
1413    }
1414    if let Ok(mut g) = SPEC_STAMPS.lock() {
1415        if let Some(log) = g.as_mut() {
1416            let now = std::time::Instant::now();
1417            log.items
1418                .push((name, (now - log.t_last).as_secs_f32() * 1e3));
1419            log.t_last = now;
1420        }
1421    }
1422}
1423
1424fn spec_stamps_begin() {
1425    if spec_time_level() == 0 {
1426        return;
1427    }
1428    if let Ok(mut g) = SPEC_STAMPS.lock() {
1429        *g = Some(SpecStampLog {
1430            t_last: std::time::Instant::now(),
1431            items: Vec::with_capacity(64),
1432        });
1433    }
1434}
1435
1436fn spec_stamps_take() -> Vec<(&'static str, f32)> {
1437    SPEC_STAMPS
1438        .lock()
1439        .ok()
1440        .and_then(|mut g| g.take())
1441        .map(|l| l.items)
1442        .unwrap_or_default()
1443}
1444
1445/// One line: every stamp name in first-seen order with its total over the
1446/// round and, when it fired more than once (the draft steps), the count.
1447fn spec_stamps_format(items: &[(&'static str, f32)]) -> String {
1448    let mut agg: Vec<(&'static str, f32, u32)> = Vec::with_capacity(items.len());
1449    for &(n, ms) in items {
1450        match agg.iter_mut().find(|e| e.0 == n) {
1451            Some(e) => {
1452                e.1 += ms;
1453                e.2 += 1;
1454            }
1455            None => agg.push((n, ms, 1)),
1456        }
1457    }
1458    let mut s = String::with_capacity(agg.len() * 16);
1459    for (n, ms, k) in agg {
1460        if k > 1 {
1461            s.push_str(&format!("{n} {ms:.1}/{k} "));
1462        } else {
1463            s.push_str(&format!("{n} {ms:.1} "));
1464        }
1465    }
1466    s
1467}
1468
1469/// The speculation monitor: exponential averages of a round's wall time
1470/// and of the tokens it produced, and the plain token's wall time — the
1471/// three numbers the keep/stop rule needs. A round pays when
1472/// `tokens_per_round · plain_ms > round_ms · 1.03`. The one-shot trial
1473/// (four rounds against eight tokens) mis-called prose: the first rounds
1474/// after a prompt are formulaic and accept well, the body does not (an
1475/// essay measured 39 against a plain 44.8 with the trial saying
1476/// "speculate"), so the rule now runs on EVERY round and stops after four
1477/// consecutive losing rounds; a stopped speculation is retried 128 tokens
1478/// later.
1479///
1480/// Native Metal (`metal: true`) does not pay the eight plain tokens up
1481/// front: on the 27B a plain token is ~150 ms, so the trial alone cost
1482/// ~1.2 s of every answer. There the plain phase is (a) skipped while the
1483/// rounds land at least `SPEC_PROXY_TOKENS` tokens each — a k=7 round on
1484/// Metal costs ~1.9 plain tokens (286 against 148 ms measured on the M4),
1485/// so 3.5 tokens/round cannot lose on any Metal round/plain ratio seen —
1486/// and (b) otherwise bounded to the fewest tokens that time it: two, or
1487/// as many as fit in `SPEC_PLAIN_MIN_MS` (a 150-ms token measures itself;
1488/// a 10-ms one needs the eight). The keep/stop rule itself is unchanged:
1489/// the moment a plain rate exists, it decides.
1490#[derive(Default, Clone, Copy)]
1491struct SpecMon {
1492    round_ms: f64,
1493    tokens: f64,
1494    plain_ms: f64,
1495    n: u32,
1496    fails: u32,
1497    /// Consecutive rounds that produced only their verifier-tip token (zero
1498    /// accepted MTP drafts). This is deliberately counted before the warm-up
1499    /// round is excluded from timing: `SPEC_ZERO_ROUNDS` real zero-acceptance
1500    /// rounds stop charging an obviously losing speculative arm.
1501    zero_accept_rounds: u8,
1502    metal: bool,
1503    /// The CUDA hybrid arm: a round costs about 1.25 plain tokens (a verify
1504    /// of five rows 1.1x a token, the drafts a tenth more), so rounds that
1505    /// land `SPEC_PROXY_TOKENS_CUDA` pay without timing plain tokens.
1506    cuda: bool,
1507}
1508
1509/// What a speculative round of k drafts costs on native Metal over a q4tp
1510/// trunk, in plain tokens. One and two drafts verify on the small-batch
1511/// matvec (`q4tp_matvec_b2` / `_b3`), three and more on the narrow GEMM at
1512/// one flat price. MacBook Air M4, Qwen3.8-27B: a plain token 160 ms, a
1513/// round of one draft 176, of two 204, of three 246, of seven 281.
1514const METAL_ROUND_COST: [f32; 7] = [1.10, 1.275, 1.54, 1.59, 1.65, 1.70, 1.76];
1515/// The same on the CUDA hybrid arm, verify and commit of a round of k
1516/// drafts: RTX 3090, Qwen3.8-27B q4tp, a plain token 20.4 ms, a round of
1517/// four chain drafts 24.3 ms past its drafts, of seven block drafts 25.1.
1518const CUDA_ROUND_COST: [f32; 7] = [1.12, 1.15, 1.17, 1.19, 1.21, 1.22, 1.24];
1519/// A DFlash block on the CUDA arm with its context rows and head (3.9 ms),
1520/// and a step of the MTP chain (0.62 ms), in plain tokens.
1521const CUDA_BLOCK_DRAFT: f32 = 0.19;
1522const CUDA_DRAFT_STEP: f32 = 0.03;
1523/// How often a draft holds once the one before it held, before any round has
1524/// shown it: the 27B's chain on code and on prose holds its first draft in
1525/// four rounds of five, the second in three of four after that, the third in
1526/// one of two.
1527const SPEC_HOLD_PRIOR: [f32; 7] = [0.80, 0.75, 0.50, 0.67, 0.65, 0.69, 0.67];
1528
1529/// The draft depth that lands the most tokens in a unit of time: a round of
1530/// k drafts gives its tip and every draft the chain held, for the cost of
1531/// that depth's verify.
1532fn metal_spec_depth(hold: &[f32; 7]) -> usize {
1533    metal_spec_plan(hold, 0.0).0
1534}
1535
1536/// `metal_spec_depth` for a drafter whose drafts cost `draft` plain tokens a
1537/// round whatever the depth (a DFlash block; an MTP chain's steps are small
1538/// change beside the verify and count as nothing): the depth, and the tokens
1539/// it lands in the time of a plain one.
1540fn metal_spec_plan(hold: &[f32; 7], draft: f32) -> (usize, f32) {
1541    spec_plan_at(&METAL_ROUND_COST, hold, draft, 0.0)
1542}
1543
1544/// `metal_spec_plan` over any device's price list: `cost[k - 1]` plain tokens
1545/// for a round of k drafts, `draft` a round and `step` a draft on top.
1546fn spec_plan_at(cost: &[f32; 7], hold: &[f32; 7], draft: f32, step: f32) -> (usize, f32) {
1547    let mut best = (1usize, 0f32);
1548    let (mut tokens, mut reach) = (1.0f32, 1.0f32);
1549    for k in 1..=7 {
1550        reach *= hold[k - 1];
1551        tokens += reach;
1552        let rate = tokens / (cost[k - 1] + draft + step * k as f32);
1553        // a longer chain has to win by more than the averages' noise
1554        if rate > best.1 * 1.04 {
1555            best = (k, rate);
1556        }
1557    }
1558    best
1559}
1560
1561/// The depth of the MTP chain's rounds on wgpu, from what a round costs on
1562/// this device: `wall[k - 1]` is the measured wall of a round of k drafts in
1563/// ms (0: not timed yet), and a depth between or past the timed ones is
1564/// priced on the line through the two nearest. A verify's price climbs with
1565/// its rows by a card's own slope (Qwen3.8-27B Turbo, a round of 3 / 4 / 5
1566/// drafts: RTX 2000 Ada 111 / 126 / 145 ms against a plain token's 75), so
1567/// the acceptance alone does not say where a deeper round stops paying.
1568/// `None` until two depths are timed: the acceptance rule moves the depth
1569/// until then. The depth in turn stays unless another lands 4 % more tokens
1570/// in a unit of time.
1571fn wgpu_spec_depth(hold: &[f32; 7], wall: &[f32; 7], k_now: usize, k_min: usize, k_max: usize) -> Option<usize> {
1572    let mut timed = (1..=7usize).filter(|&k| wall[k - 1] > 0.0);
1573    let (first, second) = (timed.next()?, timed.next()?);
1574    let price = |k: usize| -> f32 {
1575        if wall[k - 1] > 0.0 {
1576            return wall[k - 1];
1577        }
1578        // the two timed depths nearest to k
1579        let (mut a, mut b) = (first, second);
1580        for j in (1..=7usize).filter(|&j| wall[j - 1] > 0.0 && j != first && j != second) {
1581            let far = if a.abs_diff(k) >= b.abs_diff(k) { &mut a } else { &mut b };
1582            if j.abs_diff(k) < far.abs_diff(k) {
1583                *far = j;
1584            }
1585        }
1586        let (a, b) = (a.min(b), a.max(b));
1587        let slope = ((wall[b - 1] - wall[a - 1]) / (b - a) as f32).max(0.0);
1588        (wall[a - 1] + slope * (k as f32 - a as f32)).max(wall[a - 1] * 0.5)
1589    };
1590    let (k_min, k_max) = (k_min.clamp(1, 7), k_max.clamp(1, 7));
1591    let (mut tokens, mut reach) = (1.0f32, 1.0f32);
1592    let mut rate = [0f32; 7];
1593    for k in 1..=7 {
1594        reach *= hold[k - 1];
1595        tokens += reach;
1596        rate[k - 1] = tokens / price(k);
1597    }
1598    let k_now = k_now.clamp(k_min, k_max);
1599    let best = (k_min..=k_max).max_by(|&a, &b| rate[a - 1].total_cmp(&rate[b - 1]))?;
1600    Some(if rate[best - 1] > rate[k_now - 1] * 1.04 { best } else { k_now })
1601}
1602
1603/// A DFlash block with its head and selector on native Metal, in plain
1604/// tokens: one price a round, every draft of the block at once. MacBook Air
1605/// M4, the DFlash 2 drafter of Qwen3.8-27B as q4tp: 70 ms against a plain
1606/// token's 160.
1607const DFLASH_ROUND_DRAFT: f32 = 0.44;
1608/// How often a DFlash draft holds once the one before it held, before any
1609/// round has shown it: the 27B's drafter keeps 3.4 drafts of seven from every
1610/// start of mixed text.
1611const DFLASH_HOLD_PRIOR: [f32; 7] = [0.85, 0.82, 0.80, 0.80, 0.80, 0.80, 0.80];
1612/// Rounds the DFlash block sits out after a turn that the MTP chain took
1613/// back, and the most it ever sits out: a turn of fewer than `DFLASH_TURN`
1614/// rounds doubles the wait, a longer one starts it over. A turn that landed
1615/// more tokens over all its rounds than the chain was landing lost them to a
1616/// hard stretch (the block holds a whole round or none of it, so a few empty
1617/// rounds in a row say little): it sits out `DFLASH_WAIT_DIP` rounds only.
1618const DFLASH_WAIT: u32 = 48;
1619const DFLASH_WAIT_MOST: u32 = 768;
1620/// The router's margin of a round enters the running average with this
1621/// weight, and the drafter in turn keeps the rounds while the average is
1622/// inside this band (the margin is a difference of squared errors of unit
1623/// rows).
1624pub const DFLASH_LEAN_STEP: f32 = 0.5;
1625pub const DFLASH_LEAN_BAND: f32 = 0.0;
1626/// A stretch being copied from the context is the chain's whatever the router
1627/// says: this many of the last tokens repeating an earlier stretch (see
1628/// `tail_repeat`). Its short round and the lookup after it draft such text
1629/// for less than a block (edits and quotes: 8 keeps the code's rounds, where
1630/// three or four tokens repeat all the time).
1631pub const DFLASH_COPY_MIN: usize = 8;
1632/// The running gain of the chain's lookups (`spec_lookup_gain`) past which a
1633/// CUDA round stays the chain's: an edit of 512 tokens lost 15 % to the
1634/// block's rounds between its copies.
1635const DFLASH_LOOKUP_KEEPS: f32 = 5.0;
1636const DFLASH_WAIT_DIP: u32 = 8;
1637const DFLASH_TURN: u32 = 16;
1638
1639/// One logged start of a sequence, for `dflash_round_values`.
1640pub struct DflashStart<'a> {
1641    /// The committed stream through the round's first token.
1642    pub seq: &'a [u32],
1643    /// What the trunk went on to say after it (seven tokens or more).
1644    pub after: &'a [u32],
1645    /// The block's seven drafts there.
1646    pub block: &'a [u32],
1647    /// The chain's seven.
1648    pub chain: &'a [u32],
1649}
1650
1651/// For `cortiq dflash-route-fit`: what a round at each of a sequence's logged
1652/// starts lands and what it costs in plain tokens, `(tokens, cost)` under the
1653/// block and under the chain, each at the depth its own rule picks from the
1654/// starts before it, a prompt lookup going on after the drafts as it does in
1655/// a round (`METAL_ROUND_COST`, `DFLASH_ROUND_DRAFT`: the price of a round on
1656/// a MacBook Air M4).
1657pub fn dflash_round_values(starts: &[DflashStart<'_>]) -> Vec<((f32, f32), (f32, f32))> {
1658    dflash_round_values_at(starts, &METAL_ROUND_COST, DFLASH_ROUND_DRAFT, 0.0)
1659}
1660
1661/// `dflash_round_values` at another device's prices: `cost[k - 1]` plain
1662/// tokens for the verify and commit of a round of k drafts, `block_draft`
1663/// for a block, `chain_step` for each draft of the chain.
1664pub fn dflash_round_values_at(
1665    starts: &[DflashStart<'_>],
1666    cost: &[f32; 7],
1667    block_draft: f32,
1668    chain_step: f32,
1669) -> Vec<((f32, f32), (f32, f32))> {
1670    // a drafter's account of what holds, and what its lookups have paid
1671    struct Side {
1672        hold: [f32; 7],
1673        gain: f32,
1674        rest: u32,
1675        draft: f32,
1676        step: f32,
1677    }
1678    let mut seq: Vec<u32> = Vec::new();
1679    let mut round = |side: &mut Side, s: &DflashStart<'_>, own: &[u32]| -> (f32, f32) {
1680        let k = spec_plan_at(cost, &side.hold, side.draft, side.step).0.min(own.len()).max(1);
1681        let mut drafts = own[..k.min(own.len())].to_vec();
1682        if k < 7 && drafts.len() == k {
1683            if side.rest > 0 {
1684                side.rest -= 1;
1685            } else {
1686                seq.clear();
1687                seq.extend_from_slice(s.seq);
1688                seq.extend_from_slice(&drafts);
1689                let more = lookup_continuation(&seq, k + LOOKUP_MIN_REAL, 7 - k).to_vec();
1690                drafts.extend(more);
1691            }
1692        }
1693        let kept = drafts.iter().zip(s.after).take_while(|(d, t)| d == t).count();
1694        if drafts.len() > k {
1695            side.gain += 0.2 * (kept.saturating_sub(k) as f32 - side.gain);
1696            if side.gain < LOOKUP_PAYS {
1697                (side.rest, side.gain) = (24, 1.6);
1698            }
1699        }
1700        spec_hold_update(&mut side.hold, k, kept.min(k));
1701        ((1 + kept) as f32, cost[drafts.len().clamp(1, 7) - 1] + side.draft + side.step * k as f32)
1702    };
1703    let mut block = Side { hold: DFLASH_HOLD_PRIOR, gain: 2.0, rest: 0, draft: block_draft, step: 0.0 };
1704    let mut chain = Side { hold: SPEC_HOLD_PRIOR, gain: 2.0, rest: 0, draft: 0.0, step: chain_step };
1705    starts.iter().map(|s| (round(&mut block, s, s.block), round(&mut chain, s, s.chain))).collect()
1706}
1707
1708/// `CMF_DFLASH_ROWS=FILE`: every round of the DFlash block is written there
1709/// for `cortiq dflash-route-fit`, and the MTP chain drafts the same round
1710/// beside it, unverified. A record is 24 u32 and the target's row at the
1711/// tip (hidden f32), little-endian: the position of the round's first
1712/// token, that token, drafts verified, drafts accepted, the block's seven
1713/// drafts, the chain's seven, the lookup's count and its five after the
1714/// chain's first two (`u32::MAX` where there is none). `FILE.ids` holds the
1715/// stream through the first logged round's first token (u32).
1716fn dflash_rows_log() -> Option<&'static std::sync::Mutex<std::fs::File>> {
1717    static LOG: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> = std::sync::OnceLock::new();
1718    LOG.get_or_init(|| {
1719        let path = std::env::var("CMF_DFLASH_ROWS").ok()?;
1720        match std::fs::OpenOptions::new().create(true).append(true).open(&path) {
1721            Ok(f) => Some(std::sync::Mutex::new(f)),
1722            Err(e) => {
1723                tracing::warn!("CMF_DFLASH_ROWS: {path}: {e}");
1724                None
1725            }
1726        }
1727    })
1728    .as_ref()
1729}
1730
1731/// Rows of the trunk's tapped layers that may wait for the drafter
1732/// (`dflash_taps`): 100 KB a row on five layers of 5120.
1733const DFLASH_TAPS_ROWS: usize = 16384;
1734
1735/// `CMF_SPEC_SCRIPT=FILE`: token ids (the whole sequence, prompt first) that a
1736/// round of a trunk without a draft block takes its drafts from, in place of
1737/// a drafter. For tests of the verify and the rewind: with the plain greedy
1738/// sequence in the file every draft holds, and an id changed there is a
1739/// draft that does not.
1740#[cfg(feature = "gpu")]
1741fn solo_script() -> Option<&'static [u32]> {
1742    static IDS: std::sync::OnceLock<Option<Vec<u32>>> = std::sync::OnceLock::new();
1743    IDS.get_or_init(|| {
1744        let path = std::env::var("CMF_SPEC_SCRIPT").ok()?;
1745        match std::fs::read_to_string(&path) {
1746            Ok(s) => Some(s.split_whitespace().filter_map(|t| t.parse().ok()).collect()),
1747            Err(e) => {
1748                tracing::warn!("CMF_SPEC_SCRIPT: {path}: {e}");
1749                None
1750            }
1751        }
1752    })
1753    .as_deref()
1754}
1755
1756/// Little-endian bytes of f32 values (`Pipeline::dflash_dump`).
1757fn f32_bytes(v: &[f32]) -> Vec<u8> {
1758    v.iter().flat_map(|x| x.to_le_bytes()).collect()
1759}
1760
1761/// What a round of a trunk without a draft block leaves the decode loop
1762/// (`Pipeline::solo_spec_round`): the drafts that held, the trunk's row and
1763/// logits after the last of them.
1764#[cfg(feature = "gpu")]
1765struct SoloRound {
1766    accepted: Vec<u32>,
1767    drafted: usize,
1768    hidden: Vec<f32>,
1769    logits: Vec<f32>,
1770}
1771
1772/// The decode loop's account of those rounds: how deep the next one drafts,
1773/// and whether rounds land tokens faster than plain steps do.
1774#[cfg(feature = "gpu")]
1775struct SoloSpec {
1776    k: usize,
1777    /// Plain tokens to go before the next round, and the wait a losing
1778    /// stretch of rounds gets next time.
1779    rest: u32,
1780    back: u32,
1781    /// A plain token's time and a round's time per token it lands, ms
1782    /// (the first plain token of a sequence pays the warm-up: not a sample).
1783    plain_ms: f32,
1784    plain_n: u32,
1785    round_ms: f32,
1786    rounds: u32,
1787    /// The judging window: the rounds' summed wall and summed tokens (a
1788    /// ratio of sums — a mean of per-round ratios misrates a drafter).
1789    win_ms: f32,
1790    win_tok: u32,
1791    /// The step in flight: its start, and the tokens it lands (0: a plain one).
1792    last: Option<(std::time::Instant, usize)>,
1793    /// The sequence's first round is still to come: it pays the drafter's
1794    /// read of the prompt (and, on a device block, the kernels' warm-up),
1795    /// so like the first plain token it is not a sample. Before this the
1796    /// 700 ms of that round sat in the EWMA for a dozen rounds and sent a
1797    /// drafter that was winning 40 against 30 tok/s on code to rest.
1798    first: bool,
1799}
1800
1801/// The deepest round of a trunk without a draft block (the tip and seven
1802/// drafts: the batch graph's narrow kernels take eight rows, and a ninth
1803/// row costs a plane-wide GEMM a layer — 660 ms a verify against 120 on
1804/// the A40), the rounds a stretch is judged over, and the waits of a
1805/// stretch that lost.
1806#[cfg(feature = "gpu")]
1807const SOLO_K_MOST: usize = 7;
1808/// The deepest round the pay-off monitor picks on its own. The verify's
1809/// int8 batch kernels grow with the rows (eight rows 108 ms, five 70 on
1810/// Ripple-65B / RTX PRO 6000), so seven drafts at 80 % kept gave 36 tok/s
1811/// where four gave 47; `CMF_GRAPH_SPEC_K` still pins any depth to 7.
1812#[cfg(feature = "gpu")]
1813const SOLO_K_AUTO: usize = 5;
1814#[cfg(feature = "gpu")]
1815const SOLO_TRIAL: u32 = 6;
1816/// The rounds a judging window holds before its first verdict.
1817#[cfg(feature = "gpu")]
1818const SOLO_JUDGE: u32 = 3;
1819#[cfg(feature = "gpu")]
1820const SOLO_REST: u32 = 32;
1821#[cfg(feature = "gpu")]
1822const SOLO_REST_MOST: u32 = 512;
1823
1824/// Which drafter takes rounds when a DFlash sidecar sits beside the model's
1825/// own MTP block: `CMF_DFLASH_PICK=dflash` / `mtp` pins one, anything else
1826/// leaves it to what each of them holds.
1827fn dflash_pick() -> Option<bool> {
1828    static PICK: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
1829    *PICK.get_or_init(|| match std::env::var("CMF_DFLASH_PICK").as_deref() {
1830        Ok("dflash") => Some(true),
1831        Ok("mtp") => Some(false),
1832        _ => None,
1833    })
1834}
1835
1836/// A round of `k` drafts held its first `accepted`: move every depth the
1837/// round put to the test. Depths past `k` keep their last value, except
1838/// while the deepest one shown holds in nine rounds of ten: text that
1839/// predictable is worth a longer chain now and then, so they drift towards
1840/// it until a deeper round measures them.
1841fn spec_hold_update(hold: &mut [f32; 7], k: usize, accepted: usize) {
1842    let k = k.clamp(1, 7);
1843    for j in 1..=k {
1844        if accepted + 1 >= j {
1845            let hit = if accepted >= j { 1.0 } else { 0.0 };
1846            hold[j - 1] += 0.1 * (hit - hold[j - 1]);
1847        }
1848    }
1849    if k < 7 && hold[k - 1] >= 0.9 {
1850        for j in k + 1..=7 {
1851            hold[j - 1] += 0.005 * (hold[k - 1] - hold[j - 1]);
1852        }
1853    }
1854}
1855
1856/// Real tokens before the head's drafts that have to repeat with them for a
1857/// lookup to continue the chain.
1858const LOOKUP_MIN_REAL: usize = 3;
1859/// Drafts a lookup has to add to a round on average to pay for the wider
1860/// verify (a round of two drafts against one of seven on the M4: 204 and
1861/// 281 ms).
1862const LOOKUP_PAYS: f32 = 1.0;
1863
1864/// Prompt lookup: where the tail of `seq`, its last `min_len` tokens or
1865/// more, repeats an earlier stretch, the tokens that followed that stretch
1866/// there, at most `want` of them. The longest repeat wins, the latest of
1867/// equal ones.
1868fn lookup_continuation(seq: &[u32], min_len: usize, want: usize) -> &[u32] {
1869    const CAP: usize = 32;
1870    let n = seq.len();
1871    if want == 0 || min_len == 0 || n <= min_len {
1872        return &[];
1873    }
1874    let last = seq[n - 1];
1875    let mut best = (0usize, 0usize);
1876    for p in (0..n - 1).rev() {
1877        if seq[p] != last {
1878            continue;
1879        }
1880        let mut l = 1;
1881        while l < CAP && l <= p && seq[p - l] == seq[n - 1 - l] {
1882            l += 1;
1883        }
1884        if l > best.0 {
1885            best = (l, p);
1886            if l == CAP {
1887                break;
1888            }
1889        }
1890    }
1891    if best.0 < min_len {
1892        return &[];
1893    }
1894    let from = best.1 + 1;
1895    &seq[from..(from + want).min(n)]
1896}
1897
1898/// How many of the last tokens of `seq` repeat an earlier stretch of it (the
1899/// longest such repeat, 32 at most): text that is being copied from the
1900/// context. A lookup drafts such a stretch for nothing after the chain's
1901/// short round, so a round there is not worth a DFlash block.
1902pub fn tail_repeat(seq: &[u32]) -> usize {
1903    const CAP: usize = 32;
1904    let n = seq.len();
1905    if n < 2 {
1906        return 0;
1907    }
1908    let last = seq[n - 1];
1909    let mut best = 0usize;
1910    for p in (0..n - 1).rev() {
1911        if seq[p] != last {
1912            continue;
1913        }
1914        let mut l = 1;
1915        while l < CAP && l <= p && seq[p - l] == seq[n - 1 - l] {
1916            l += 1;
1917        }
1918        if l > best {
1919            best = l;
1920            if l == CAP {
1921                break;
1922            }
1923        }
1924    }
1925    best
1926}
1927
1928/// Zero-acceptance rounds in a row that end a speculation trial early. Two
1929/// was too few: a good head meets two empty rounds in a row now and then
1930/// (OrcaCyber-Nano-1.0 on an RTX 2000 Ada, 95 pinned rounds of code and a
1931/// review: four such pairs, no triple), and at the start of a chat turn a
1932/// pair sent the whole 200-token turn to plain decode, 13.4 tok/s against
1933/// 25.9 with the drafts. A head that never holds costs one more round.
1934const SPEC_ZERO_ROUNDS: u8 = 3;
1935/// Tokens a plain decision taken on thin evidence (fewer than five timed
1936/// rounds) stands before the rounds are tried again; one taken on a full
1937/// trial stands for `SPEC_RECHECK_PLAIN`.
1938const SPEC_RECHECK_THIN: usize = 32;
1939const SPEC_RECHECK_PLAIN: usize = 128;
1940
1941/// Tokens per round at or above which a Metal round pays without a plain
1942/// measurement (see `SpecMon`).
1943const SPEC_PROXY_TOKENS: f64 = 3.5;
1944/// The CUDA hybrid arm's proxy (see `SpecMon::cuda`): RTX 3090, Qwen3.8-27B,
1945/// a round 24.5-26.8 ms against a plain token's 20.4.
1946const SPEC_PROXY_TOKENS_CUDA: f64 = 2.0;
1947/// The Metal plain phase: at least two tokens, and more until this much
1948/// wall time has been timed (up to the eight the other backends time).
1949const SPEC_PLAIN_MIN_MS: f64 = 200.0;
1950
1951impl SpecMon {
1952    fn round(&mut self, dt_ms: f64, produced: usize) {
1953        if produced <= 1 {
1954            self.zero_accept_rounds = self.zero_accept_rounds.saturating_add(1);
1955        } else {
1956            self.zero_accept_rounds = 0;
1957        }
1958        self.n += 1;
1959        if self.n == 1 {
1960            return; // round 1 pays the batch scratch and the draft mirror
1961        }
1962        let a = if self.n == 2 { 1.0 } else { 0.3 };
1963        self.round_ms += a * (dt_ms - self.round_ms);
1964        self.tokens += a * (produced as f64 - self.tokens);
1965    }
1966    fn pays(&self) -> bool {
1967        if self.plain_ms > 0.0 {
1968            self.tokens * self.plain_ms > self.round_ms * 1.03
1969        } else {
1970            (self.metal && self.tokens >= SPEC_PROXY_TOKENS) || (self.cuda && self.tokens >= SPEC_PROXY_TOKENS_CUDA)
1971        }
1972    }
1973    fn repeated_zero_acceptance(&self) -> bool {
1974        self.zero_accept_rounds >= SPEC_ZERO_ROUNDS
1975    }
1976    /// When a plain decision is tried again: soon if the rounds behind it
1977    /// were few (round 1 is not timed, so `n` counts one more).
1978    fn recheck_plain_at(&self, generated: usize) -> usize {
1979        generated + if self.n < 6 { SPEC_RECHECK_THIN } else { SPEC_RECHECK_PLAIN }
1980    }
1981    /// Has the plain phase timed enough tokens to decide?
1982    fn plain_done(&self, t0: std::time::Instant, gen0: usize, generated: usize) -> bool {
1983        let n = generated.saturating_sub(gen0);
1984        if n >= 8 {
1985            return true;
1986        }
1987        self.metal && n >= 2 && t0.elapsed().as_secs_f64() * 1e3 >= SPEC_PLAIN_MIN_MS
1988    }
1989}
1990
1991/// Ids of the consumed prefix the bounded reuse key remembers literally
1992/// (the rest is covered by the rolling hash).
1993pub const KV_PREFIX_TAIL: usize = 128;
1994
1995/// Bounded prefix-reuse key: how many ids the cache holds, a rolling
1996/// hash of ALL of them and the last [`KV_PREFIX_TAIL`] ids literally.
1997/// Answers "does this prompt strictly extend what is cached" exactly
1998/// (hash over the whole consumed prefix + literal tail) without keeping
1999/// the dialogue — the record is a fixed size whatever the session length.
2000#[derive(Debug, Clone, Default)]
2001pub struct KvPrefix {
2002    len: usize,
2003    hash: u64,
2004    tail: Vec<u32>,
2005    /// Owner of the state this key describes: the resident device graph
2006    /// (true) or the host. A turn continues the prefix only on its owner
2007    /// (R4: a host continuation of a device sequence reads an empty host
2008    /// state; a device continuation of a host sequence has no image).
2009    device: bool,
2010}
2011
2012impl KvPrefix {
2013    #[inline]
2014    fn fold(mut h: u64, ids: &[u32]) -> u64 {
2015        for &id in ids {
2016            h ^= id as u64;
2017            h = h.wrapping_mul(0x100000001b3);
2018            h ^= h >> 29;
2019        }
2020        h
2021    }
2022
2023    pub fn clear(&mut self) {
2024        self.len = 0;
2025        self.hash = 0xcbf29ce484222325;
2026        self.tail.clear();
2027        self.device = false;
2028    }
2029
2030    /// Was the prefix built on the resident device graph?
2031    pub fn on_device(&self) -> bool {
2032        self.device
2033    }
2034
2035    /// Tag the owner of the recorded prefix.
2036    pub fn set_on_device(&mut self, device: bool) {
2037        self.device = device;
2038    }
2039
2040    /// Ids the cache holds (the forwarded prefix).
2041    pub fn len(&self) -> usize {
2042        self.len
2043    }
2044
2045    pub fn is_empty(&self) -> bool {
2046        self.len == 0
2047    }
2048
2049    /// Literal tail currently kept (≤ `KV_PREFIX_TAIL`).
2050    pub fn tail_len(&self) -> usize {
2051        self.tail.len()
2052    }
2053
2054    /// Replace the key with `ids` (a fresh sequence).
2055    pub fn set(&mut self, ids: &[u32]) {
2056        self.clear();
2057        self.extend(ids);
2058    }
2059
2060    /// Append `more` to the consumed prefix (an extension-only turn).
2061    pub fn extend(&mut self, more: &[u32]) {
2062        if self.len == 0 && self.hash == 0 {
2063            self.hash = 0xcbf29ce484222325;
2064        }
2065        self.hash = Self::fold(self.hash, more);
2066        self.len += more.len();
2067        if more.len() >= KV_PREFIX_TAIL {
2068            self.tail.clear();
2069            self.tail
2070                .extend_from_slice(&more[more.len() - KV_PREFIX_TAIL..]);
2071        } else {
2072            let drop = (self.tail.len() + more.len()).saturating_sub(KV_PREFIX_TAIL);
2073            self.tail.drain(..drop);
2074            self.tail.extend_from_slice(more);
2075        }
2076    }
2077
2078    /// Cached positions when `ids` strictly extends the consumed prefix,
2079    /// 0 otherwise. The tail is compared literally first (cheap), then
2080    /// the hash over the whole prefix must agree.
2081    pub fn extension(&self, ids: &[u32]) -> usize {
2082        if self.len == 0 || ids.len() <= self.len {
2083            return 0;
2084        }
2085        let t = self.tail.len();
2086        if ids[self.len - t..self.len] != self.tail[..] {
2087            return 0;
2088        }
2089        if Self::fold(0xcbf29ce484222325, &ids[..self.len]) != self.hash {
2090            return 0;
2091        }
2092        self.len
2093    }
2094}
2095
2096/// Result of a generation call.
2097pub struct GenerateResult {
2098    pub text: String,
2099    pub token_ids: Vec<u32>,
2100    pub prompt_tokens: usize,
2101    pub tokens_generated: usize,
2102    pub finish_reason: String,
2103    /// Speculative-decode stats (0/0 when MTP is absent or inactive).
2104    pub mtp_drafted: usize,
2105    pub mtp_accepted: usize,
2106    /// Per-generated-token confidence = softmax probability of the token
2107    /// that was actually emitted (softmax probability on the chosen state). High =
2108    /// the model was sure; low = it was guessing. Same length as the
2109    /// generated slice of `token_ids`.
2110    pub token_confidence: Vec<f32>,
2111    /// Structured per-token telemetry (B4 channel). Empty unless
2112    /// `set_trace(true)`; otherwise same length as the generated slice.
2113    pub traces: Vec<TokenTrace>,
2114}
2115
2116/// One row of the structured telemetry trace (B4): the model's internal
2117/// routing state at the moment a token was emitted. Every field is a
2118/// quantity the runtime already computes — nothing is inferred or
2119/// estimated (anti-principle: only measured bytes).
2120#[derive(Clone, Debug)]
2121pub struct TokenTrace {
2122    /// 0-based index within the generated slice.
2123    pub t: usize,
2124    /// The emitted token id.
2125    pub token_id: u32,
2126    /// Softmax probability on the emitted token — how sure the model was.
2127    pub confidence: f32,
2128    /// Skill in force while this token was generated (None = backbone).
2129    pub active_skill: Option<String>,
2130    /// Recon error E = ‖r−BBᵀr‖²/‖φ‖² at the last routing eval — coherence
2131    /// with the active skill's subspace (low = coherent). None = no router
2132    /// or not yet evaluated.
2133    pub recon: Option<f32>,
2134    /// The router changed the active skill right after this token (a
2135    /// domain boundary crossed under the hysteresis barrier).
2136    pub switched: bool,
2137}
2138
2139/// Calibrated softmax probability of `id` under `logits` (the confidence on
2140/// the emitted token) — the confidence signal, cheap from logits already
2141/// computed for sampling. `temp` is the calibration temperature (B1):
2142/// softmax(logits / temp); 1.0 = raw.
2143#[cfg_attr(not(test), allow(dead_code))]
2144fn top1_prob_t(logits: &[f32], id: u32, temp: f32) -> f32 {
2145    let t = if temp > 1e-3 { temp } else { 1.0 };
2146    let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
2147    let sum: f32 = logits.iter().map(|&v| ((v - max) / t).exp()).sum();
2148    if sum > 0.0 {
2149        (((logits[id as usize] - max) / t).exp()) / sum
2150    } else {
2151        0.0
2152    }
2153}
2154
2155/// prefill-GEMM enabled? (CMF_PREFILL=seq — emergency fallback to the
2156/// sequential path.)
2157fn prefill_batched() -> bool {
2158    std::env::var("CMF_PREFILL")
2159        .map(|v| v != "seq")
2160        .unwrap_or(true)
2161}
2162
2163/// Decide the graph NLL route without conflating graph quality with the
2164/// optional native-Metal fused head. A hidden-state graph remains a valid
2165/// quality route on Vulkan/Wgpu; only native Metal requires graph logits.
2166#[inline]
2167/// ‖a − b‖ / ‖b‖ (infinite when the lengths differ).
2168fn rel_l2(a: &[f32], b: &[f32]) -> f64 {
2169    if a.len() != b.len() {
2170        return f64::INFINITY;
2171    }
2172    let (mut d, mut r) = (0f64, 0f64);
2173    for (&x, &y) in a.iter().zip(b) {
2174        let e = (x - y) as f64;
2175        d += e * e;
2176        r += y as f64 * y as f64;
2177    }
2178    (d / r.max(1e-30)).sqrt()
2179}
2180
2181fn nll_graph_policy(unmasked: bool, prefer_graph: bool, native_metal: bool) -> (bool, bool) {
2182    let graph_quality = unmasked && prefer_graph;
2183    let fused_head_quality = graph_quality && native_metal;
2184    (graph_quality, fused_head_quality)
2185}
2186
2187/// Input to the layer-major batched span walk: token ids (embeds itself,
2188/// full-stack and coordinator prefill) or ready boundary hiddens (the
2189/// network worker's side of a split).
2190#[derive(Clone, Copy)]
2191enum PrefillIn<'a> {
2192    Ids(&'a [u32]),
2193    Hidden(&'a [f32]),
2194}
2195
2196/// The batched prefill walks `weights.layers`. Architectures that load
2197/// their own stack (gemma-3n's AltUp replicas, DeepSeek-V4's hyper-
2198/// connections) leave that empty and must go position by position — asking
2199/// otherwise indexes an empty vector, which is a panic rather than a
2200/// fallback. Every call site goes through here so the next such
2201/// architecture is one line, not four.
2202/// What a turbo file's header asks for.
2203#[derive(Clone)]
2204pub(crate) struct O1Turbo {
2205    pub(crate) cfg: crate::nystrom::O1Cfg,
2206    /// A prompt this long goes over to the far field; a shorter one stays exact.
2207    pub(crate) seal: usize,
2208    pub(crate) exact: crate::dory::ExactRows,
2209}
2210
2211/// Rows of a prompt read exactly on the card before the first seal, at most. Past them
2212/// the rows leave the card as they are read.
2213const O1_PREFIX_MAX: usize = 8192;
2214
2215/// Where a turbo file seals on this card. Exact rows take about 190 KB each on Qwen3.8-27B,
2216/// and the state, the scratch and the draft head about 1.8 GB beside the weights: a 16 GB card
2217/// has no room for 8192 rows, and gives up a little prompt speed to keep the ceiling.
2218/// `CMF_O1_PREFIX_MAX` chooses by hand.
2219pub(crate) fn o1_seal_for_card(seal: usize, weight_bytes: u64) -> usize {
2220    o1_seal_for_card_rows(seal, weight_bytes, 190 << 10)
2221}
2222
2223/// `o1_seal_for_card` for rows of `row_bytes` on the card (Dory's full layers: 54 KB).
2224pub(crate) fn o1_seal_for_card_rows(seal: usize, weight_bytes: u64, row_bytes: u64) -> usize {
2225    if let Some(s) = std::env::var("CMF_O1_PREFIX_MAX").ok().and_then(|v| v.parse().ok()) {
2226        return s;
2227    }
2228    let mut budget = crate::gpu::vram_budget();
2229    // Unified memory: what the system lets the GPU keep, and a row there lives twice, in the
2230    // host's cache and in the mirror.
2231    let mut row = row_bytes.max(1);
2232    #[cfg(target_os = "macos")]
2233    if budget == u64::MAX {
2234        budget = crate::gpu_metal::working_set_bytes();
2235        row *= 2;
2236    }
2237    if budget == 0 || budget == u64::MAX {
2238        return seal;
2239    }
2240    let room = budget.saturating_sub(weight_bytes + (1800 << 20));
2241    seal.min(((room / row) as usize).max(O1_PREFIX_MAX / 2))
2242}
2243
2244/// Rows of an archive as they come in: in RAM, or in a file (`CMF_O1_SPILL=DIR`) when
2245/// RAM is short and a disk is not.
2246pub(crate) enum ArchStore {
2247    Ram(Vec<f32>),
2248    Disk { path: std::path::PathBuf, file: std::io::BufWriter<std::fs::File> },
2249}
2250
2251impl ArchStore {
2252    pub(crate) fn new(dir: Option<&std::path::Path>, name: String) -> Result<Self, String> {
2253        let Some(dir) = dir else { return Ok(Self::Ram(Vec::new())) };
2254        std::fs::create_dir_all(dir).map_err(|e| format!("O(1) spill {}: {e}", dir.display()))?;
2255        let path = dir.join(format!("cortiq-o1-{}-{name}.rows", std::process::id()));
2256        let file = std::fs::File::create(&path).map_err(|e| format!("O(1) spill {}: {e}", path.display()))?;
2257        Ok(Self::Disk { path, file: std::io::BufWriter::with_capacity(1 << 22, file) })
2258    }
2259
2260    pub(crate) fn push(&mut self, rows: &[f32]) -> Result<(), String> {
2261        match self {
2262            Self::Ram(v) => {
2263                v.extend_from_slice(rows);
2264                Ok(())
2265            }
2266            Self::Disk { path, file } => {
2267                use std::io::Write;
2268                // SAFETY: an `f32` slice is valid as bytes of four times its length.
2269                let bytes = unsafe { std::slice::from_raw_parts(rows.as_ptr().cast::<u8>(), rows.len() * 4) };
2270                file.write_all(bytes).map_err(|e| format!("O(1) spill {}: {e}", path.display()))
2271            }
2272        }
2273    }
2274
2275    pub(crate) fn freeze(mut self) -> Result<ArchRows, String> {
2276        match self {
2277            Self::Ram(ref mut v) => Ok(ArchRows::Ram(std::mem::take(v))),
2278            Self::Disk { ref mut path, ref mut file } => {
2279                use std::io::Write;
2280                file.flush().map_err(|e| format!("O(1) spill {}: {e}", path.display()))?;
2281                let f = std::fs::File::open(&*path).map_err(|e| format!("O(1) spill {}: {e}", path.display()))?;
2282                // SAFETY: the file is this process's own and no one writes it any more.
2283                let map = unsafe { memmap2::Mmap::map(&f) }.map_err(|e| format!("O(1) spill {}: {e}", path.display()))?;
2284                Ok(ArchRows::Disk { map: Some(map), path: std::mem::take(path) })
2285            }
2286        }
2287    }
2288}
2289
2290impl Drop for ArchStore {
2291    fn drop(&mut self) {
2292        if let Self::Disk { path, .. } = self {
2293            // A store that was frozen hands its file over; the file is gone only here if not.
2294            if !path.as_os_str().is_empty() {
2295                let _ = std::fs::remove_file(&*path);
2296            }
2297        }
2298    }
2299}
2300
2301pub(crate) enum ArchRows {
2302    Ram(Vec<f32>),
2303    Disk { map: Option<memmap2::Mmap>, path: std::path::PathBuf },
2304}
2305
2306impl ArchRows {
2307    pub(crate) fn as_slice(&self) -> &[f32] {
2308        match self {
2309            Self::Ram(v) => v,
2310            Self::Disk { map, .. } => {
2311                let b = map.as_ref().map_or(&[][..], |m| &m[..]);
2312                // SAFETY: a page-aligned map of what `push` wrote, whole `f32`s.
2313                unsafe { std::slice::from_raw_parts(b.as_ptr().cast::<f32>(), b.len() / 4) }
2314            }
2315        }
2316    }
2317}
2318
2319impl Drop for ArchRows {
2320    fn drop(&mut self) {
2321        if let Self::Disk { map, path } = self {
2322            *map = None;
2323            let _ = std::fs::remove_file(&*path);
2324        }
2325    }
2326}
2327
2328/// The rows of a prompt past its first seal, off the card until the far field is built
2329/// anew over all of them.
2330struct O1Archive {
2331    dir: Option<std::path::PathBuf>,
2332    layers: Vec<O1ArchLayer>,
2333    rows: usize,
2334    stride: usize,
2335    nh: usize,
2336    nk: usize,
2337    hd: usize,
2338}
2339
2340impl O1Archive {
2341    fn new() -> Self {
2342        Self { dir: std::env::var_os("CMF_O1_SPILL").map(Into::into), layers: Vec::new(), rows: 0, stride: 1, nh: 0, nk: 0, hd: 0 }
2343    }
2344}
2345
2346struct O1ArchLayer {
2347    li: usize,
2348    k: ArchStore,
2349    v: ArchStore,
2350    q: ArchStore,
2351}
2352
2353impl Pipeline {
2354    pub(crate) fn can_prefill_batched(&self) -> bool {
2355        #[cfg(test)]
2356        let force_serial = self.nll_test_force_serial;
2357        #[cfg(not(test))]
2358        let force_serial = false;
2359        prefill_batched() && !force_serial && !self.weights.layers.is_empty()
2360    }
2361
2362    /// The backend's automatic capacity split for a mapped transformer.
2363    /// Kept as a method so prefill and decode use the exact same boundary.
2364    fn automatic_gpu_prefix(&self) -> Option<usize> {
2365        let (model, _, _, _) = self.weights.embed_tokens.graph_weight()?;
2366        crate::gpu::automatic_layer_prefix(&model, self.num_layers, self.physical_layers)
2367    }
2368
2369    /// Positions per batched pass of the layer-stack prefill for THIS
2370    /// model on THIS backend (see [`prefill_chunk_rule`]). Pub: the network
2371    /// split must chunk exactly like the local path to reproduce it.
2372    pub fn prefill_chunk(&self) -> usize {
2373        let env = env_prefill_chunk();
2374        if env.is_some() || ChunkHost::here() != ChunkHost::Other {
2375            return prefill_chunk_rule(env, ChunkHost::here(), false);
2376        }
2377        let facts = self.chunk_stack_facts();
2378        if facts.dense_on_cpu() {
2379            return CPU_DENSE_PREFILL_CHUNK;
2380        }
2381        prefill_chunk_rule(None, ChunkHost::Other, facts.dense_on_discrete())
2382    }
2383
2384    /// Prompt lookup in a speculative round (`CMF_SPEC_LOOKUP=0` leaves the
2385    /// chain to the draft head alone).
2386    fn spec_lookup_on() -> bool {
2387        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2388        *ON.get_or_init(|| std::env::var("CMF_SPEC_LOOKUP").as_deref() != Ok("0"))
2389    }
2390
2391    /// Whether a verify of two or three rows runs on the small-batch matvec:
2392    /// native Metal, a dense q4tp FFN in the trunk, the kernel not switched
2393    /// off (`CMF_METAL_MVS=0`).
2394    fn metal_small_batch_verify(&self) -> bool {
2395        #[cfg(target_os = "macos")]
2396        {
2397            crate::gpu::q1_force()
2398                && crate::gpu_metal::small_batch_mv()
2399                && self.weights.layers.first().is_some_and(|l| match &l.ffn {
2400                    FfnKind::Dense(d) => d.gate_proj.mapped_q4tp().is_some(),
2401                    _ => false,
2402                })
2403        }
2404        #[cfg(not(target_os = "macos"))]
2405        {
2406            false
2407        }
2408    }
2409
2410    /// Architectures that run a dedicated per-token stack (gemma-3n's
2411    /// AltUp flow, the gemma-4 E-series PLE/shared-KV body): batched
2412    /// prefill and the graphs stay off for them.
2413    fn per_token_stack(&self) -> bool {
2414        self.g3n.is_some() || self.g4e.is_some()
2415    }
2416
2417    fn chunk_stack_facts(&self) -> ChunkStackFacts {
2418        let plain_dense = !self.weights.layers.is_empty()
2419            && !self.per_token_stack()
2420            && self.dsv4.is_none()
2421            && self.dsv41.is_none()
2422            && self.dory.is_none()
2423            && self.qwen4_exp.is_none()
2424            && self.glm5_next.is_none()
2425            && self.hy4.is_none()
2426            && self.maxwell.is_none()
2427            && self.inkling.is_none()
2428            && self.weights.layers.iter().all(|lw| {
2429                // LFM2/LFM3's short-conv mixer is two projection GEMMs and
2430                // an elementwise conv: the host-driven chunk walk starves
2431                // the card the same way (LFM3-1.7B q8_2f on an A40, 2048
2432                // positions: 137 tok/s at 48, 460-640 at 512).
2433                matches!(lw.attn, AttnKind::Full { .. } | AttnKind::ShortConv(_))
2434                    && matches!(lw.ffn, FfnKind::Dense(_))
2435            });
2436        let gpu_on = crate::gpu::enabled();
2437        ChunkStackFacts {
2438            plain_dense,
2439            discrete: gpu_on && crate::gpu::discrete(),
2440            gpu_on,
2441            // Only asked when the rest already qualifies: it opens the
2442            // backend's capacity plan.
2443            capacity_split: std::env::var_os("CMF_GPU_LAYERS").is_some()
2444                || (plain_dense && gpu_on && self.automatic_gpu_prefix().is_some()),
2445            multi_gpu: self.gpu_plan.is_some(),
2446            o1: self.o1_active(),
2447        }
2448    }
2449}
2450
2451/// Prefill chunk (positions per batched pass), model-agnostic form. On
2452/// macOS the AMX GEMM path wants tall panels — M=48 starves the matrix
2453/// units (ggml uses ubatch 512); elsewhere the historical 48 stays.
2454/// CMF_PREFILL_CHUNK overrides. The architectures with their own stacks
2455/// (DeepSeek-V4/V4.1) chunk with this; the layer-stack prefill asks
2456/// [`Pipeline::prefill_chunk`], which also knows the model and the card.
2457/// A different chunk is a different (equally valid) generation: panel
2458/// width reorders float accumulation.
2459pub fn prefill_chunk() -> usize {
2460    prefill_chunk_rule(env_prefill_chunk(), ChunkHost::here(), false)
2461}
2462
2463fn env_prefill_chunk() -> Option<usize> {
2464    std::env::var("CMF_PREFILL_CHUNK")
2465        .ok()
2466        .and_then(|v| v.parse::<usize>().ok())
2467}
2468
2469/// The host classes the chunk width distinguishes.
2470#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2471enum ChunkHost {
2472    Macos,
2473    /// Linux/Android aarch64 (phones, SBCs).
2474    Aarch64,
2475    /// Everything else: x86-64 Linux/Windows, CPU or Vulkan/DX12.
2476    Other,
2477}
2478
2479impl ChunkHost {
2480    fn here() -> Self {
2481        if cfg!(target_os = "macos") {
2482            ChunkHost::Macos
2483        } else if cfg!(target_arch = "aarch64") {
2484            ChunkHost::Aarch64
2485        } else {
2486            ChunkHost::Other
2487        }
2488    }
2489}
2490
2491/// Chunk for a plain dense stack whose every layer lives on a discrete
2492/// card. On x86 the layer-stack prefill is host-driven: each GEMM and the
2493/// chunk attention (which re-uploads the whole KV prefix per layer) is a
2494/// separate submit + readback, so 48 positions a pass left the card idle
2495/// between them. Measured in-process on an RTX 3090 (Vulkan), 2048-token
2496/// prompt — see CHANGELOG 0.7.6 for the table.
2497const DISCRETE_DENSE_PREFILL_CHUNK: usize = 512;
2498
2499/// Chunk for a plain dense stack with no GPU at all on x86-64: the AVX2
2500/// q4tp batch kernel and the micro-GEMM chunk attend feed on wider
2501/// panels. Spark-X2.6-4B q4tp, 1000-token prompt on 8 Zen 2 cores: 20.7
2502/// tok/s at 48, 24.7 at 128, 25.0 at 256.
2503const CPU_DENSE_PREFILL_CHUNK: usize = 128;
2504
2505/// The chunk-width rule. `dense_on_discrete` is true only for a plain
2506/// dense transformer (full attention, dense FFN, no special stack) that
2507/// is entirely resident on one discrete card — the one case measured
2508/// here. GDN hybrids, MoE, DeepSeek stacks, capacity-split and CPU-only
2509/// runs keep the width they were tuned with.
2510fn prefill_chunk_rule(env: Option<usize>, host: ChunkHost, dense_on_discrete: bool) -> usize {
2511    if let Some(n) = env {
2512        return n.max(1);
2513    }
2514    match host {
2515        ChunkHost::Macos => 512,
2516        // Mobile: big enough to feed the batched attend (gate b ≥ 32)
2517        // and the blocked SDOT GEMM without the memory of 512.
2518        ChunkHost::Aarch64 => 256,
2519        ChunkHost::Other if dense_on_discrete => DISCRETE_DENSE_PREFILL_CHUNK,
2520        ChunkHost::Other => 48,
2521    }
2522}
2523
2524/// What the chunk rule needs to know about a loaded stack.
2525#[derive(Clone, Copy, Debug, Default)]
2526struct ChunkStackFacts {
2527    /// Every layer is `AttnKind::Full` or `AttnKind::ShortConv` +
2528    /// `FfnKind::Dense`, and no architecture-owned stack (g3n,
2529    /// DeepSeek-V4/V4.1, qwen4-exp) is set.
2530    plain_dense: bool,
2531    /// The active GPU backend is a discrete card.
2532    discrete: bool,
2533    /// The backend is up and not paused.
2534    gpu_on: bool,
2535    /// A capacity-derived device prefix: some layers run on the host.
2536    capacity_split: bool,
2537    /// An in-process multi-GPU plan is set.
2538    multi_gpu: bool,
2539    /// O(1) layers (their Q trace is recorded by the prefill).
2540    o1: bool,
2541}
2542
2543impl ChunkStackFacts {
2544    /// A plain dense stack on an x86-64 host with no GPU backend up
2545    /// (O(1) stacks keep the width their trace was measured with).
2546    fn dense_on_cpu(self) -> bool {
2547        cfg!(target_arch = "x86_64")
2548            && self.plain_dense
2549            && !self.gpu_on
2550            && !self.multi_gpu
2551            && !self.o1
2552    }
2553
2554    fn dense_on_discrete(self) -> bool {
2555        self.plain_dense
2556            && self.discrete
2557            && self.gpu_on
2558            && !self.capacity_split
2559            && !self.multi_gpu
2560            && !self.o1
2561    }
2562}
2563
2564/// Number of prompt rows that have a real teacher-forced next-token pair in a
2565/// prefill span.  The final prompt row has no successor token, so it must not
2566/// be handed to the MTP warm-up.  Keeping this arithmetic in one helper makes
2567/// the full-chunk and tail-chunk boundaries explicit for both the graph and
2568/// CPU implementations.
2569#[inline]
2570fn mtp_prefill_pair_count(start: usize, end: usize, input_len: usize) -> usize {
2571    if end <= start || start >= input_len {
2572        return 0;
2573    }
2574    let rows = (end.min(input_len) - start).min(input_len - start);
2575    if end < input_len {
2576        rows
2577    } else {
2578        rows.saturating_sub(1)
2579    }
2580}
2581
2582/// Callback for streaming tokens. Return `false` to cancel.
2583pub type TokenCallback = Box<dyn FnMut(&str) -> bool + Send>;
2584
2585/// One layer's cache ownership at a cross-turn KV reuse boundary.
2586#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2587pub(crate) struct ReuseLayer {
2588    /// Exact-attention layer (rows in `LayerKvCache`); otherwise a
2589    /// recurrent / latent mixer whose state cannot be rewound.
2590    pub full: bool,
2591    /// Positions the host owner cache reaches (`pos_len`: a trimmed
2592    /// sliding tail stores only the newest of them).
2593    pub host_rows: usize,
2594    /// Rows the wgpu token graph's device mirror holds (None: no mirror).
2595    pub device_rows: Option<usize>,
2596    /// A recurrent state lives on the device (advanced past the host copy).
2597    pub device_state: bool,
2598}
2599
2600/// What a reused turn must do before its tail prefill runs on the HOST.
2601#[derive(Debug, Clone, PartialEq, Eq)]
2602pub(crate) enum ReusePlan {
2603    /// Host caches already hold exactly the reused prefix.
2604    Ready,
2605    /// Copy device mirror rows `[from..to)` into the host cache of each
2606    /// listed layer (the rows decode wrote on the device only).
2607    Pull(Vec<(usize, usize, usize)>),
2608    /// The prefix cannot be continued on the host exactly: start fresh.
2609    Fresh,
2610}
2611
2612/// The wgpu whole-token graph decodes into a DEVICE K/V mirror and never
2613/// writes those rows back to the host cache, while the chunked prefill of a
2614/// pure-attention model reads (and appends to) the host cache. A reused turn
2615/// therefore found its host cache ending at the previous PROMPT, not at the
2616/// previous answer: the tail prefill attended without the model's own
2617/// answer and appended its rows at the wrong index (MiniCPM5 on Vulkan
2618/// repeated its tool call instead of reading the tool result). Every layer
2619/// must hold exactly `reuse_from` host rows before the host continues; rows
2620/// that exist only on the device are pulled back, anything else is fresh.
2621pub(crate) fn kv_reuse_plan(reuse_from: usize, layers: &[ReuseLayer]) -> ReusePlan {
2622    let mut pulls = Vec::new();
2623    for (li, l) in layers.iter().enumerate() {
2624        if !l.full {
2625            if l.device_state {
2626                return ReusePlan::Fresh;
2627            }
2628            continue;
2629        }
2630        if l.host_rows == reuse_from {
2631            continue;
2632        }
2633        if l.host_rows < reuse_from && l.device_rows.is_some_and(|d| d >= reuse_from) {
2634            pulls.push((li, l.host_rows, reuse_from));
2635            continue;
2636        }
2637        return ReusePlan::Fresh;
2638    }
2639    if pulls.is_empty() {
2640        ReusePlan::Ready
2641    } else {
2642        ReusePlan::Pull(pulls)
2643    }
2644}
2645
2646impl Pipeline {
2647    /// Reset state whose meaning is local to a single MTP draft sequence.
2648    /// Unlike ordinary KV reuse, MTP is always rebuilt from the prompt.
2649    fn reset_fresh_mtp_draft_state(&mut self) {
2650        self.draft_full_streak = 0;
2651    }
2652
2653    /// Clear all per-sequence state, including backend device mirrors.
2654    ///
2655    /// The host KV/history buffers are only half of the request lifecycle on
2656    /// wgpu: GDN/O(1) state and cached graph bind groups are keyed by the
2657    /// pipeline id and otherwise survive a pooled request.  Keep every fresh
2658    /// sequence entry point on this one reset path so a new request cannot
2659    /// inherit the prior request's device state.
2660    fn clear_sequence_state(&mut self) {
2661        // a replay still writing the GDN owners must land before they are
2662        // cleared or reallocated (the device holds raw pointers to them)
2663        #[cfg(target_os = "macos")]
2664        let _ = crate::gpu_metal::wait_replay();
2665        self.kv_cache.clear();
2666        // Both reuse keys (the legacy `kv_history` and the bounded
2667        // `kv_prefix`) describe the state being dropped here.
2668        self.clear_history();
2669        self.graph_logits = None;
2670        if let Some(d) = &mut self.dflash {
2671            d.reset();
2672        }
2673        self.dflash_rows = None;
2674        self.dflash_taps.lock().unwrap().clear();
2675        // a new sequence owes the DFlash block nothing of the last one's turns
2676        self.dflash_hold = DFLASH_HOLD_PRIOR;
2677        (self.dflash_last, self.dflash_wait, self.dflash_back, self.dflash_turn) = (false, 0, DFLASH_WAIT, 0);
2678        self.dflash_turn_sum = (0.0, 0.0);
2679        self.dflash_lean = 0.0;
2680        if let Some(b) = &mut self.dsv41 {
2681            b.3.clear();
2682        }
2683        if let Some(b) = &mut self.dory {
2684            b.1.clear();
2685            crate::gpu::dory_reset(self.graph_kv_id);
2686        }
2687        crate::gpu::graph_kv_reset(self.graph_kv_id);
2688        // the card's GDN snapshot went with the sequence's states
2689        self.gdn_snap = None;
2690        self.mtp_warm_base = None;
2691        // MTP is detached from `self` for the duration of generation, so its
2692        // device mirror is not covered by the trunk reset above.  Reset the
2693        // derived id as well: a failed/aborted warm-up must never leave a
2694        // mirror that a later request can mistake for a current MTP cache.
2695        crate::gpu::graph_kv_reset(self.mtp_kv_id());
2696    }
2697
2698    /// Make the host caches own exactly the reused prefix `[0..reuse_from)`
2699    /// before a reused turn's tail prefill runs on the host (see
2700    /// [`kv_reuse_plan`]). Returns false when the prefix cannot be continued
2701    /// exactly — the caller then starts a fresh sequence. A model whose
2702    /// prefill runs through the token graph keeps its device state as the
2703    /// authority and is left untouched.
2704    fn prepare_kv_reuse(&mut self, reuse_from: usize) -> bool {
2705        if self.dory.is_some() || self.graph_prefill_preferred() {
2706            return true;
2707        }
2708        let kv_id = self.graph_kv_id;
2709        let layers: Vec<ReuseLayer> = (0..self.num_layers)
2710            .map(|li| {
2711                let full = matches!(
2712                    self.weights.layers[self.phys_layer(li)].attn,
2713                    AttnKind::Full { .. }
2714                );
2715                ReuseLayer {
2716                    full,
2717                    // Absolute depth: a trimmed sliding tail stores fewer
2718                    // rows than the positions it has seen.
2719                    host_rows: self.kv_cache.layers[li].pos_len(),
2720                    device_rows: crate::gpu::graph_kv_stored(kv_id, li),
2721                    device_state: crate::gpu::graph_state_resident(kv_id, li),
2722                }
2723            })
2724            .collect();
2725        // No wgpu device state at all (CPU, Metal — whose graph appends every
2726        // decoded row to the owner cache itself): the host is the owner and
2727        // the extension check already proved the prefix.
2728        if layers
2729            .iter()
2730            .all(|l| l.device_rows.is_none() && !l.device_state)
2731        {
2732            return true;
2733        }
2734        let plan = kv_reuse_plan(reuse_from, &layers);
2735        let (what, rows, n) = match &plan {
2736            ReusePlan::Ready => ("host ready", 0, 0),
2737            ReusePlan::Fresh => ("fresh", 0, 0),
2738            ReusePlan::Pull(p) => (
2739                "pull",
2740                p.iter().map(|&(_, a, b)| b - a).max().unwrap_or(0),
2741                p.len(),
2742            ),
2743        };
2744        let t0 = std::time::Instant::now();
2745        let ok = self.apply_kv_reuse_plan(reuse_from, plan, &layers);
2746        if std::env::var("CMF_PREFILL_PROF").is_ok() {
2747            eprintln!(
2748                "kv-reuse: {what}{}: {rows} device row(s) × {n} layer(s) to the host in {:.2} ms",
2749                if ok { "" } else { " (failed → fresh)" },
2750                t0.elapsed().as_secs_f64() * 1e3
2751            );
2752        }
2753        ok
2754    }
2755
2756    fn apply_kv_reuse_plan(
2757        &mut self,
2758        reuse_from: usize,
2759        plan: ReusePlan,
2760        layers: &[ReuseLayer],
2761    ) -> bool {
2762        let kv_id = self.graph_kv_id;
2763        match plan {
2764            ReusePlan::Fresh => return false,
2765            ReusePlan::Ready => {}
2766            ReusePlan::Pull(pulls) => {
2767                // Mirrors of one uniform geometry: one batched read serves
2768                // every layer. Per-layer geometry (MiMo-V2: 4/8 KV heads,
2769                // narrow V, sliding rings) is read layer by layer in the
2770                // host layout instead.
2771                let (nkv, hd) = {
2772                    let c = &self.kv_cache.layers[pulls[0].0];
2773                    (c.num_kv_heads, c.head_dim)
2774                };
2775                let uniform = pulls.iter().all(|&(li, _, _)| {
2776                    let c = &self.kv_cache.layers[li];
2777                    (c.num_kv_heads, c.head_dim) == (nkv, hd)
2778                });
2779                let batched = if uniform {
2780                    crate::gpu::graph_kv_read_rows(kv_id, &pulls, nkv, hd)
2781                } else {
2782                    None
2783                };
2784                let rows: Vec<(Vec<f32>, Vec<f32>)> = match batched {
2785                    Some(rows) => rows,
2786                    None => {
2787                        let mut rows = Vec::with_capacity(pulls.len());
2788                        for &(li, from, to) in &pulls {
2789                            let (lnkv, lhd) = {
2790                                let c = &self.kv_cache.layers[li];
2791                                (c.num_kv_heads, c.head_dim)
2792                            };
2793                            let Some((k, v, first_valid)) =
2794                                crate::gpu::graph_kv_pull_host(kv_id, li, from, to, lnkv, lhd)
2795                            else {
2796                                return false;
2797                            };
2798                            // The host continues at `to`: a sliding layer
2799                            // reads back only its last window, a full one
2800                            // every row it lacks.
2801                            let need_from = match self.layer_window(li) {
2802                                Some(w) => from.max((to + 1).saturating_sub(w)),
2803                                None => from,
2804                            };
2805                            if first_valid > need_from {
2806                                return false;
2807                            }
2808                            rows.push((k, v));
2809                        }
2810                        rows
2811                    }
2812                };
2813                for ((li, from, to), (k, v)) in pulls.into_iter().zip(rows) {
2814                    let cache = &mut self.kv_cache.layers[li];
2815                    let row = cache.num_kv_heads * cache.head_dim;
2816                    for p in 0..to - from {
2817                        cache.append(&k[p * row..(p + 1) * row], &v[p * row..(p + 1) * row], &[]);
2818                    }
2819                    if cache.pos_len() != to {
2820                        return false;
2821                    }
2822                }
2823            }
2824        }
2825        // A mirror past the prefix (a greedy burst that ran beyond the stop)
2826        // holds rows of the OLD continuation: rewind it so the next graph
2827        // token re-syncs those positions from the host.
2828        for (li, l) in layers.iter().enumerate() {
2829            if l.full
2830                && l.device_rows.is_some_and(|d| d > reuse_from)
2831                && !crate::gpu::graph_kv_set_stored(kv_id, li, reuse_from)
2832            {
2833                return false;
2834            }
2835        }
2836        true
2837    }
2838
2839    /// Finish a generation lifecycle after the MTP/router owners were
2840    /// detached.  Every terminal path must put those owners back before the
2841    /// pooled pipeline can serve another request.  Graph side channels and
2842    /// device mirrors are cleared on errors and cancellations; a successful
2843    /// generation keeps its decode-ready host cache for KV reuse.
2844    fn finish_generation(
2845        &mut self,
2846        mtp: &mut Option<MtpModule>,
2847        router: &mut Option<crate::swarm::DynRouter>,
2848        clear_sequence: bool,
2849    ) {
2850        // A dynamic route may have switched the overlay before the terminal
2851        // path. Restore the backbone while the detached router is still
2852        // available, because set_active_skill also owns the overlay reset.
2853        if router.is_some() {
2854            let _ = self.set_active_skill(None);
2855        }
2856        // The last speculative round's replay may still be in flight on
2857        // the second queue: whoever reads the host cache after generate()
2858        // returns (session export, the network split's KV wire, a KV
2859        // reuse) must see the final states.
2860        // A replay that failed leaves the GDN owners half-written: fail
2861        // closed and drop the sequence instead of handing the cache on.
2862        #[cfg(target_os = "macos")]
2863        let clear_sequence = clear_sequence || !crate::gpu_metal::wait_replay();
2864        if clear_sequence {
2865            self.clear_sequence_state();
2866            if let Some(m) = mtp.as_mut() {
2867                // The MTP owner is detached while generation runs, so the
2868                // trunk reset above cannot clear its host cache.  Drop its
2869                // partial rows before reattaching it to the pooled pipeline;
2870                // the next request must start from the same empty anchor on
2871                // CPU and on the device mirror.
2872                m.kv.clear();
2873            }
2874            if let Some(m) = self.mtp.as_mut() {
2875                // A non-speculative request leaves the configured MTP owner
2876                // attached.  Clear that dormant cache too when a shared
2877                // generation failure/cancellation resets the sequence.
2878                m.kv.clear();
2879            }
2880        }
2881        self.graph_want_logits = false;
2882        self.graph_head_required = false;
2883        self.graph_logits = None;
2884        self.graph_failed
2885            .store(false, std::sync::atomic::Ordering::Relaxed);
2886        self.cancel
2887            .store(false, std::sync::atomic::Ordering::Relaxed);
2888        self.dyn_router = router.take().or(self.dyn_router.take());
2889        self.mtp = mtp.take().or(self.mtp.take());
2890        self.mtp_graph_mode = None;
2891        self.spec_forced = None;
2892    }
2893
2894    /// Consume a graph failure reported by a forward that returns only a
2895    /// hidden vector.  `forward_ids` is a public Result API, so it must not
2896    /// turn the graph's zero hidden sentinel into a valid lm_head result.
2897    fn check_forward_graph(&mut self, phase: &str, pos: usize) -> Result<(), String> {
2898        if self
2899            .graph_failed
2900            .swap(false, std::sync::atomic::Ordering::Relaxed)
2901        {
2902            self.cancel
2903                .store(false, std::sync::atomic::Ordering::Relaxed);
2904            self.clear_sequence_state();
2905            self.graph_logits = None;
2906            self.graph_want_logits = false;
2907            self.graph_head_required = false;
2908            return Err(format!("GPU graph failed during {phase} at position {pos}"));
2909        }
2910        Ok(())
2911    }
2912
2913    #[cfg(target_os = "macos")]
2914    fn fail_metal_graph(&mut self, reason: &str) {
2915        crate::pipeline::METAL_GRAPH_ERRORS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2916        self.clear_sequence_state();
2917        self.graph_logits = None;
2918        self.graph_failed
2919            .store(true, std::sync::atomic::Ordering::Relaxed);
2920        self.cancel
2921            .store(true, std::sync::atomic::Ordering::Relaxed);
2922        tracing::error!("native Metal TokenGraph failed closed: {reason}");
2923    }
2924
2925    /// Start an NLL/PPL request with all graph side channels in a known
2926    /// state.  A graph failure also raises the cooperative cancel bit; it is
2927    /// consumed here and that graph-induced bit is cleared so an independent
2928    /// request can be reused.  A caller-owned cancellation remains intact.
2929    fn nll_begin(&mut self) -> Result<(), String> {
2930        if self
2931            .graph_failed
2932            .swap(false, std::sync::atomic::Ordering::Relaxed)
2933        {
2934            self.cancel
2935                .store(false, std::sync::atomic::Ordering::Relaxed);
2936            self.clear_sequence_state();
2937            self.graph_logits = None;
2938            self.graph_want_logits = false;
2939            self.graph_head_required = false;
2940            return Err("GPU graph failed before NLL scoring".to_string());
2941        }
2942        self.clear_sequence_state();
2943        self.graph_logits = None;
2944        self.graph_want_logits = false;
2945        self.graph_head_required = false;
2946        Ok(())
2947    }
2948
2949    /// End an NLL/PPL request, including the side channels that are not part
2950    /// of the host KV cache.  This is intentionally explicit instead of
2951    /// relying on a tuple/sentinel return: callers must see every failure.
2952    fn nll_end(&mut self) {
2953        self.clear_sequence_state();
2954        self.graph_logits = None;
2955        self.graph_want_logits = false;
2956        self.graph_head_required = false;
2957        self.graph_failed
2958            .store(false, std::sync::atomic::Ordering::Relaxed);
2959    }
2960
2961    /// Check the graph failure channel at a scoring boundary and leave the
2962    /// pipeline reusable when the device path failed.
2963    fn nll_check_graph(&mut self, phase: &str, pos: usize) -> Result<(), String> {
2964        #[cfg(test)]
2965        if self.nll_test_fail_at == Some(pos) {
2966            self.nll_test_fail_at = None;
2967            self.graph_failed
2968                .store(true, std::sync::atomic::Ordering::Relaxed);
2969            self.cancel
2970                .store(true, std::sync::atomic::Ordering::Relaxed);
2971        }
2972        if self
2973            .graph_failed
2974            .swap(false, std::sync::atomic::Ordering::Relaxed)
2975        {
2976            self.cancel
2977                .store(false, std::sync::atomic::Ordering::Relaxed);
2978            self.clear_sequence_state();
2979            self.graph_logits = None;
2980            self.graph_want_logits = false;
2981            return Err(format!(
2982                "GPU graph failed during NLL {phase} at position {pos}"
2983            ));
2984        }
2985        Ok(())
2986    }
2987
2988    /// Map a virtual layer index to its physical weight index.
2989    /// Looped Transformer (Nanbeige 4.2): 22 physical layers × 2 loops = 44 virtual;
2990    /// virtual layer 23 maps back to physical layer 1 (23 % 22 = 1).
2991    #[inline]
2992    pub fn phys_layer(&self, virtual_idx: usize) -> usize {
2993        match &self.layer_map {
2994            Some(m) => m[virtual_idx],
2995            None => virtual_idx % self.physical_layers,
2996        }
2997    }
2998
2999    /// Mage-VL (`llava_onevision2`) and MiniCPM-OCR prompt ingest through the batched wgpu
3000    /// graph (`CMF_GRAPH_PREFILL=0` keeps the chunked host prefill).
3001    fn onevision2_prefill(&self) -> bool {
3002        self.model.as_ref().is_some_and(|m| matches!(m.header.arch.arch_name.as_str(), "llava_onevision2" | "minicpm_ocr"))
3003            && std::env::var("CMF_GRAPH_PREFILL").as_deref() != Ok("0")
3004    }
3005
3006    /// SenseNova-Loop: whether virtual layer `li` runs inside the mHC
3007    /// streams (the device graphs decline such layers).
3008    #[inline]
3009    pub fn mhc_layer(&self, li: usize) -> bool {
3010        self.mhc.as_ref().is_some_and(|m| m.on(self.phys_layer(li)))
3011    }
3012
3013    /// mHC before a sub-layer of the decode token: route its streams into
3014    /// `h` (entering the range copies `h` into every stream first).
3015    fn mhc_pre(&mut self, li: usize, ffn: bool, h: &mut [f32]) -> crate::sensenova::MhcCoef {
3016        let p = self.phys_layer(li);
3017        let m = self.mhc.as_deref().expect("mhc layer");
3018        let n = m.s.streams * m.dim;
3019        if self.mhc_r.len() != n {
3020            self.mhc_r.resize(n, 0.0);
3021        }
3022        if !ffn && m.enters(p) {
3023            m.enter(&mut self.mhc_r, h);
3024        }
3025        m.route(p, ffn, &self.mhc_r, h)
3026    }
3027
3028    /// mHC after a sub-layer: fold its output `y` into the streams; after
3029    /// the range's last FFN, `h` becomes the streams' mean.
3030    fn mhc_post(&mut self, li: usize, ffn: bool, y: &[f32], c: &crate::sensenova::MhcCoef, h: &mut [f32]) {
3031        let p = self.phys_layer(li);
3032        let m = self.mhc.as_deref().expect("mhc layer");
3033        m.merge(&mut self.mhc_r, y, c);
3034        if ffn && m.leaves(p) {
3035            m.leave(&self.mhc_r, h);
3036        }
3037    }
3038
3039    /// True when `virtual_idx` is the last layer of a loop iteration
3040    /// (used for loop_final_norm insertion).
3041    #[inline]
3042    pub fn is_loop_end(&self, virtual_idx: usize) -> bool {
3043        self.loop_final_norm && (virtual_idx + 1) % self.physical_layers == 0
3044    }
3045
3046    /// Build a pipeline from parts (used by the loader and tests).
3047    #[allow(clippy::too_many_arguments)]
3048
3049    /// Whole-block q1 token graph on the GPU (macOS/Metal): the run of
3050    /// consecutive q1 layers — GDN *and* full attention — starting at
3051    /// `start` executes as few command buffers as the CPU truly needs.
3052    /// Hidden stays device-resident across every layer; the only syncs
3053    /// are before each CPU attend (it needs q/k/v and owns the KV
3054    /// cache) and the final hidden readback. Recurrent states
3055    /// round-trip through shared memory (the CPU stays their owner, so
3056    /// every other path remains coherent). Returns the first layer
3057    /// index NOT covered (== `start` → refused, caller falls through
3058    /// to the per-layer CPU path).
3059    /// Should prefill run position-by-position through the GPU token
3060    /// graph instead of the batched CPU chunk-GEMM? True for q1 GDN
3061    /// hybrids on native Metal: their chunk prefill is walled by the
3062    /// sequential scalar recurrence, so the graph's decode rate wins.
3063    /// NOT for Looped Transformers, despite the per-chunk loop_final_norm
3064    /// sync: the chunk-GEMM amortizes each weight over the whole chunk,
3065    /// which the per-position graph cannot (Nanbeige 4.2 on M4, 512-token
3066    /// prompt: 85 tok/s chunked vs 14 through the graph).
3067    #[cfg(target_os = "macos")]
3068    fn graph_prefill_preferred(&self) -> bool {
3069        // The resident Embryo graph owns the phase state and the anchor KV on
3070        // the device: the prompt must seed them there (wgpu over Metal).
3071        if crate::gpu::enabled_here()
3072            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)
3073            && matches!(std::env::var("CMF_EMBRYO_RESIDENT").as_deref(), Ok("1") | Ok("parallel"))
3074            && self.embryo_resident_eligible()
3075        {
3076            return true;
3077        }
3078        let graph_force = crate::gpu::q1_force() || crate::gpu::q2tp_gpu_opt_in();
3079        if !crate::gpu::enabled_here()
3080            || !graph_force
3081            || std::env::var("CMF_GPU_BLOCK")
3082                .map(|v| v == "0")
3083                .unwrap_or(false)
3084            // CMF_PREFILL_GRAPH=0: the chunked prefill (GEMM projections,
3085            // CPU recurrence) instead of the per-position token graph.
3086            || std::env::var("CMF_PREFILL_GRAPH").as_deref() == Ok("0")
3087        {
3088            return false;
3089        }
3090        self.weights
3091            .layers
3092            .iter()
3093            .any(|lw| {
3094                matches!(&lw.attn, AttnKind::LinearGdn(w) if w.in_proj_qkv.metal_graph_parts().is_some())
3095            })
3096    }
3097
3098    /// Prompt ingest through the batched wgpu graph in device-prefix mode:
3099    /// a MoE stack that does not fit the card runs each chunk's leading
3100    /// layers on the device (experts resident) and the rest on the host's
3101    /// batched walk. On by default for models with per-layer attention
3102    /// geometry (MiMo-V2 — its measured default); `CMF_BATCH_PREFIX=1`
3103    /// opts any other MoE model in, `=0` keeps the chunked host prefill.
3104    #[cfg(not(target_os = "macos"))]
3105    fn batch_prefix_prefill(&self) -> bool {
3106        let forced = match std::env::var("CMF_BATCH_PREFIX").as_deref() {
3107            Ok("0") => return false,
3108            Ok("1") => true,
3109            _ => false,
3110        };
3111        crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill)
3112            && crate::gpu::enabled_here()
3113            && !self.graph_refused()
3114            && (forced || self.graph_attn_decline_reason().is_some())
3115            && self.wgpu_graph_attn_decline().is_none()
3116            && self.attn_softcap == 0.0
3117            && self
3118                .weights
3119                .layers
3120                .iter()
3121                .any(|lw| matches!(&lw.ffn, FfnKind::Moe(_)))
3122            && self.automatic_gpu_prefix().is_some()
3123    }
3124
3125    /// Gemma-4's prompt through the batched wgpu graph (`gemma_batch`): a
3126    /// dense stack wholly on a discrete card, whose token graph already
3127    /// decodes it. Not `graph_prefill_preferred` — the host stays the KV
3128    /// owner for reuse and scoring; only generation's ingest changes.
3129    /// `CMF_G4_BATCH=0` keeps the chunked host prefill.
3130    fn g4_batch_prefill(&self) -> bool {
3131        #[cfg(target_os = "macos")]
3132        {
3133            false
3134        }
3135        #[cfg(not(target_os = "macos"))]
3136        {
3137            // An EMPTY layer stack (`all()` is vacuously true) plus a
3138            // gemma4 geometry flag is exactly the gemma-4 E-series
3139            // per-token stack — it has no batch graph rows to ingest.
3140            !self.weights.layers.is_empty()
3141                && !self.per_token_stack()
3142                // Gemma-4, and Ripple: a dense stack with per-layer geometry
3143                // whose host walk attends 80 heads a row on the CPU.
3144                && (self.global_attn.is_some() || self.attn_v_norm || self.value_blend.is_some())
3145                && crate::gpu::g4_batch_on()
3146                && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill)
3147                && crate::gpu::enabled_here()
3148                && crate::gpu::discrete()
3149                && !self.graph_refused()
3150                && !self.o1_active()
3151                && self.attn_softcap == 0.0
3152                && self.wgpu_graph_attn_decline().is_none()
3153                && self.weights.layers.iter().all(|lw| {
3154                    matches!(lw.attn, AttnKind::Full { .. }) && matches!(lw.ffn, FfnKind::Dense(_))
3155                })
3156                && self.automatic_gpu_prefix().is_none()
3157        }
3158    }
3159
3160    /// Gemma-4's batched prefill of `ids` at positions `pos0..`
3161    /// (`g4_batch_prefill`): chunks of `generation_batch_k` rows through the
3162    /// batch graph. Ok((n, rows)): `n` positions ingested; `rows` = the last
3163    /// one's hidden, or every row's (`keep_all`). A refusal stops early
3164    /// (n < ids.len()) after pulling the device rows the host walk needs.
3165    /// Err: a failure after admission — the device state is undefined.
3166    #[cfg(not(target_os = "macos"))]
3167    fn g4_batch_ingest(
3168        &mut self,
3169        ids: &[u32],
3170        pos0: usize,
3171        keep_all: bool,
3172    ) -> Result<(usize, Vec<f32>), String> {
3173        let hs = self.hidden_size;
3174        let chunk = self.generation_batch_k().max(1);
3175        let end_all = pos0 + ids.len();
3176        let mut pos = pos0;
3177        let mut out = Vec::new();
3178        while pos < end_all && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
3179            let end = (pos + chunk).min(end_all);
3180            let bk = end - pos;
3181            let mut hiddens = vec![0f32; bk * hs];
3182            for (j, &id) in ids[pos - pos0..end - pos0].iter().enumerate() {
3183                hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
3184            }
3185            let positions: Vec<usize> = (pos..end).collect();
3186            let t_chunk = std::time::Instant::now();
3187            let outcome = self.try_batch_graph_wgpu(&mut hiddens, &positions, bk, None);
3188            if std::env::var("CMF_GRAPH_PROF").is_ok() {
3189                let ms = t_chunk.elapsed().as_secs_f64() * 1000.0;
3190                eprintln!(
3191                    "batch-chunk: phase=prompt mode=gemma4 k={bk} outcome={outcome:?} {ms:.1} ms ({:.1} tok/s)",
3192                    bk as f64 / (ms / 1000.0)
3193                );
3194            }
3195            match outcome {
3196                crate::gpu::BatchGraphOutcome::Completed => {
3197                    if keep_all {
3198                        out.extend_from_slice(&hiddens);
3199                    } else {
3200                        out = hiddens[(bk - 1) * hs..].to_vec();
3201                    }
3202                    pos = end;
3203                }
3204                crate::gpu::BatchGraphOutcome::Failed => {
3205                    return Err("Gemma-4 batched prefill failed after admission".into());
3206                }
3207                crate::gpu::BatchGraphOutcome::Declined => {
3208                    #[cfg(feature = "gpu")]
3209                    if pos > pos0 {
3210                        self.pull_lagging_host_kv(0, self.num_layers, pos);
3211                    }
3212                    break;
3213                }
3214            }
3215        }
3216        Ok((pos - pos0, out))
3217    }
3218
3219    /// Hidden rows of every position of `ids` through Gemma-4's batched
3220    /// prefill from a fresh sequence (the prefill's teacher-forced logits
3221    /// for parity gates: `logits_from_hidden` per row). None when the model
3222    /// or the card does not take that route, or it refused part way.
3223    pub fn g4_prefill_hidden_rows(&mut self, ids: &[u32]) -> Option<Vec<f32>> {
3224        #[cfg(not(target_os = "macos"))]
3225        {
3226            if ids.is_empty() || !self.g4_batch_prefill() {
3227                return None;
3228            }
3229            self.clear_sequence_state();
3230            match self.g4_batch_ingest(ids, 0, true) {
3231                Ok((n, rows)) if n == ids.len() => Some(rows),
3232                _ => {
3233                    self.clear_sequence_state();
3234                    None
3235                }
3236            }
3237        }
3238        #[cfg(target_os = "macos")]
3239        {
3240            let _ = ids;
3241            None
3242        }
3243    }
3244
3245    #[cfg(not(target_os = "macos"))]
3246    fn graph_prefill_preferred(&self) -> bool {
3247        // Discrete-GPU wgpu whole-token graph: GDN layers carry recurrent state
3248        // (conv ring + delta-rule S) resident on the GPU. A batched CPU prefill
3249        // builds that state on the CPU only, leaving the GPU buffers zeroed at
3250        // decode → garbage. Route GDN-hybrid prefill through the graph one
3251        // position at a time so the resident state is seeded exactly as decode
3252        // will read it. Fully resident pure-attention models take the batched
3253        // graph as well (see the end of this function).
3254        let graph_on = crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill);
3255        if !graph_on || !crate::gpu::enabled_here() {
3256            return false;
3257        }
3258        // Embryo's phase state is device-owned by the resident graph during
3259        // prefill; the batched CPU path would leave decode seeing a zeroed
3260        // device recurrence.  Route the prompt position-by-position too.
3261        if self.embryo_resident_eligible() {
3262            // The resident graph owns the phase state and anchor KV on the
3263            // device.  A prefill-only graph would leave decode on the host
3264            // with no way to import that state, so keep the whole sequence
3265            // on one owner (or use the ordinary CPU prefill/decode pair).
3266            return crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode);
3267        }
3268        // The descriptor-aware Prism graph now carries both the FWHT/affine
3269        // transforms and resident GDN state, so it is also the exact prefill
3270        // path for this model.  Keeping it here (rather than falling through
3271        // to the CPU chunk walk) is required for a long prompt to seed the
3272        // same device state that decode consumes.
3273        // O(1) needs the CPU prefill: the q-trace that seals the Nyström
3274        // skeleton is recorded there and nowhere else. The GDN half of
3275        // the hybrid loses nothing — the graph's first decode creates
3276        // its (ring, S) entries seeded from `cpu_state`, the same
3277        // handoff every graph run relies on when the entry is fresh.
3278        // Without this line the two designs collide on hybrids and o1
3279        // never becomes graph-portable: prefill through the graph
3280        // records no trace, so views stay None forever.
3281        if self.o1_active() {
3282            return false;
3283        }
3284        // A model the wgpu graphs decline outright would walk its prompt
3285        // one position at a time through a graph that never runs: the
3286        // batched CPU chunk prefill is the right ingest for it.
3287        if self.wgpu_graph_attn_decline().is_some() {
3288            return false;
3289        }
3290        if self
3291            .weights
3292            .layers
3293            .iter()
3294            .any(|lw| matches!(&lw.attn, AttnKind::LinearGdn(_)))
3295            // Mage-VL: its screenshot prompts (~2k rows) go through the
3296            // batched graph, 4× the chunked host ingest on an A40 (2048
3297            // tokens: 806 tok/s at 128 rows, 893 at 256, against 196).
3298            || self.onevision2_prefill()
3299        {
3300            return true;
3301        }
3302        // MoE models too: the chunked CPU prefill runs every expert on the
3303        // host (Hy-MT2-30B-A3B on a Xeon: 8 tok/s of ingest against 53 of
3304        // graph decode), while the token graph — and the batched graph under
3305        // CMF_BATCH_K — keep the experts resident. Full attention in the
3306        // graph writes the KV mirror that decode reads, exactly as it does
3307        // for the hybrids' attention layers. Only when the whole stack is
3308        // resident: with a device prefix the per-position walk finishes
3309        // every token on the host, and the chunked prefill (GEMMs on the
3310        // card, the expert loop batched on the host) is the faster ingest
3311        // (the 8 GB ladder point: 7 tok/s chunked against ~1 walked).
3312        // Dense stacks too: the chunked walk paid a submit, a wait and a
3313        // readback per projection and per attend, so a resident 2B read its
3314        // prompt at the host's pace (CherryPit-1.2-2B on an RTX 5090, 2048
3315        // tokens: 10.6 s chunked, 1.2 s through the batched graph, the same
3316        // greedy text). `CMF_DENSE_GRAPH_PREFILL=0` keeps the chunked walk.
3317        // A dense stack the batched graph declined once (Spark-X2.6) keeps the
3318        // chunked walk: the per-position graph read its prompt at decode pace,
3319        // 65 tok/s against 350 on an RTX 2000 Ada.
3320        (self
3321            .weights
3322            .layers
3323            .iter()
3324            .any(|lw| matches!(&lw.ffn, FfnKind::Moe(_)))
3325            || (std::env::var("CMF_DENSE_GRAPH_PREFILL").as_deref() != Ok("0")
3326                && !self.dense_batch_declined.load(std::sync::atomic::Ordering::Relaxed)
3327                // Sliding-window stacks take the graph where its whole-run
3328                // attend is tiled: Spark-X2.6 q4tp on an RTX 2000 Ada,
3329                // 16 000 tokens, 182 tok/s chunked, 135 through the per-token
3330                // batched arm, 390+ tiled. `CMF_DENSE_GRAPH_PREFILL=1` sends
3331                // them through the graph regardless.
3332                && ((self.sliding_layers.is_none() && self.swa.is_none())
3333                    || crate::gpu::batched_attend_tiled()
3334                    || std::env::var("CMF_DENSE_GRAPH_PREFILL").as_deref() == Ok("1"))))
3335            && self.automatic_gpu_prefix().is_none()
3336    }
3337
3338    #[cfg(target_os = "macos")]
3339    fn q1_graph_gpu(
3340        &mut self,
3341        start: usize,
3342        upto: Option<usize>,
3343        position: usize,
3344        h: &mut [f32],
3345    ) -> usize {
3346        let _mt0 = std::time::Instant::now(); // CMF_METAL_HOSTPROF
3347        use crate::gpu::{
3348            AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, GraphDims, MetalFfn, SconvGpuLayer, TokenGraph,
3349        };
3350        const MOE_WORKING_SET_REASON: &str =
3351            "model weights exceed Metal working set for native MoE graph";
3352        // A prior admission check rejected this pipeline. Avoid rebuilding the
3353        // entire 40-layer graph plan at every individual host layer after the
3354        // fallback begins; the per-operation path below stays eligible.
3355        if self
3356            .graph_declines
3357            .borrow()
3358            .iter()
3359            .any(|&(site, reason)| site == "metal block graph" && reason == MOE_WORKING_SET_REASON)
3360        {
3361            return start;
3362        }
3363        let graph_force = crate::gpu::q1_force() || crate::gpu::q2tp_gpu_opt_in();
3364        if self.attn_softcap > 0.0 // capped scores: no graph kernel — CPU path
3365            // V with rows of its own (Ripple's value residual): no Metal kernel blends them.
3366            || self.value_blend.is_some()
3367            || !self.metal_rope_scale_ok()
3368            || !crate::gpu::enabled_here()
3369            || !graph_force
3370            || std::env::var("CMF_GPU_BLOCK")
3371                .map(|v| v == "0")
3372                .unwrap_or(false)
3373        {
3374            if std::env::var("CMF_GRAPH_DBG").is_ok() {
3375                eprintln!(
3376                    "block-graph: front gate (softcap={} enabled_here={} graph_force={})",
3377                    self.attn_softcap > 0.0,
3378                    crate::gpu::enabled_here(),
3379                    graph_force,
3380                );
3381            }
3382            if self.graph_head_required {
3383                self.fail_metal_graph("native graph front gate refused");
3384            }
3385            return start;
3386        }
3387        // The graph encodes SiLU or exact-GELU FFNs and attention with an
3388        // explicit model scale. Sliding-window layers with their own RoPE
3389        // table / rotary width ride it too (`metal_graph_swa`): both the
3390        // device attend and the sandwich's CPU attend read each layer's
3391        // window and table. Sandwich norms and other activations fall back
3392        // to the CPU path.
3393        // Gemma-4 (`metal_gemma4`): its sliding layers ride the same door,
3394        // its global layers, V norm, sandwich norms, layer scalar and
3395        // tanh-GELU the `gpu_metal::gemma4` kernels.
3396        let gemma4 = self.metal_gemma4();
3397        let swa_graph = self.metal_graph_swa() || gemma4;
3398        // The normal native GQA kernel carries a learned, value-less
3399        // softmax column.  It also takes the exact per-layer sliding
3400        // window, but its split-K twin has no sink column.  Thus a
3401        // sink-bearing model may use this door only when the ordinary
3402        // sliding geometry has passed `metal_graph_swa` (or when it has no
3403        // sliding layers at all).
3404        let graph_attn_reason = self.graph_attn_decline_reason();
3405        let native_sink_attend = graph_attn_reason == Some("learned attention sinks")
3406            && (swa_graph || (self.swa.is_none() && self.sliding_layers.is_none()));
3407        // Plain-weight (x̂·w) sandwich norms (LFM3) take the generic norm
3408        // kernels, as on the wgpu graph; Gemma-2/3's (1+w) norms and the
3409        // layer scalar stay Gemma-4's.
3410        let plain_norms = self.norm_style == cortiq_core::NormStyle::Qwen;
3411        if (self.swa.is_some() && !swa_graph)
3412            || (self.global_attn.is_some() && !gemma4)
3413            || self.attention_heads_per_layer.is_some()
3414            || (self.attn_v_norm && !gemma4)
3415            // Per-layer KV heads / narrow V stay outside this graph.  A
3416            // learned sink is admitted only through native_sink_attend.
3417            || (graph_attn_reason.is_some() && !swa_graph && !native_sink_attend)
3418            || self.weights.layers.iter().any(|lw| {
3419                ((lw.layer_scale.is_some()
3420                    || (!plain_norms && (lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some())))
3421                    && !gemma4)
3422                    || matches!(&lw.ffn, FfnKind::Dense(d)
3423                        if !(matches!(d.act, Act::Silu | Act::Gelu)
3424                            || (gemma4 && d.act == Act::GeluTanh)))
3425            })
3426        {
3427            // The Metal graphs' device attend has no per-layer attention
3428            // geometry (the wgpu graphs do): say so once, by name.
3429            if let Some(reason) = graph_attn_reason.filter(|_| !swa_graph && !native_sink_attend) {
3430                self.note_graph_decline("metal block graph", reason);
3431            }
3432            if std::env::var("CMF_GRAPH_DBG").is_ok() {
3433                eprintln!(
3434                    "block-graph: arch ineligible (swa={} gattn={} hpl={} vnorm={} scale_delta={:.2e})",
3435                    self.swa.is_some(),
3436                    self.global_attn.is_some(),
3437                    self.attention_heads_per_layer.is_some(),
3438                    self.attn_v_norm,
3439                    (self.attn_scale - 1.0 / (self.head_dim as f32).sqrt()).abs(),
3440                );
3441            }
3442            if self.graph_head_required {
3443                self.fail_metal_graph("native graph architecture gate refused");
3444            }
3445            return start;
3446        }
3447        // Looped Transformer: the graph covers ALL loop iterations;
3448        // encode_loop_norm is inserted on-device at each boundary.
3449        let limit = upto
3450            .map(|u| u + 1)
3451            .unwrap_or(self.num_layers)
3452            .min(self.num_layers);
3453
3454        enum Item<'a> {
3455            Gdn {
3456                run: Vec<GdnGpuLayer<'a>>,
3457                first: usize,
3458            },
3459            /// A run of LFM2/LFM3 short-conv layers (conv ring on device).
3460            Sconv {
3461                run: Vec<SconvGpuLayer<'a>>,
3462                first: usize,
3463            },
3464            Attn {
3465                l: AttnGpuLayer<'a>,
3466                li: usize,
3467                q_norm: Option<&'a [f32]>,
3468                k_norm: Option<&'a [f32]>,
3469                output_gate: bool,
3470                /// `self_attn.g_proj` output gate (per-head flag): the
3471                /// sandwich projects the device-normed input on the host
3472                /// and gates the attend's output before O.
3473                proj_gate: Option<(&'a QTensor, bool)>,
3474                /// The same gate's f32 rows `[nh × hidden]` when the device
3475                /// attend can apply it (per-head sigmoid, f32 in RAM).
3476                head_gate_w: Option<&'a [f32]>,
3477                bias: Option<(&'a [f32], &'a [f32], &'a [f32])>,
3478                /// Attend on the device too (no sync): F32 KV, no
3479                /// o1/bias, dims inside the kernels' contract.
3480                full_gpu: bool,
3481            },
3482        }
3483
3484        // Device-attend KERNEL contract, shared by every Full layer. The
3485        // hd>128 default-off POLICY is applied after the scan: it was
3486        // measured on dense models, and a MoE plan inverts it — with the
3487        // experts on device each CPU-attend sandwich costs a
3488        // commit+wait, ~30 submits/token (W2 on M4: 14.7 tok/s
3489        // sandwiched vs 27.1 device-attend vs 18.8 pure CPU).
3490        let attend_mode = std::env::var("CMF_GPU_ATTEND").unwrap_or_else(|_| "auto".into());
3491        let attend_contract = attend_mode != "0"
3492            && attend_mode != "off"
3493            && self.head_dim % 4 == 0
3494            && self.head_dim <= 256
3495            // Flint has explicit no-RoPE layers.  The device RoPE kernel
3496            // accepts rd=0 (zero rotation lanes) and binds a sentinel table;
3497            // retain the historical lane-pair requirement for nonzero rd.
3498            && (self.rotary_dim == 0
3499                || (self.rotary_dim >= 2
3500                    && self.rotary_dim <= self.head_dim
3501                    && (self.rotary_dim / 2) % 32 == 0))
3502            && self.num_kv_heads > 0
3503            && self.num_heads % self.num_kv_heads == 0;
3504
3505        let mut plan: Vec<Item> = Vec::new();
3506        let mut model_ref: Option<std::sync::Arc<cortiq_core::CmfModel>> = None;
3507        // Break-reason diagnostics ride the same env as the plan summary.
3508        let block_diag = std::env::var("CMF_GRAPH_DBG").is_ok();
3509        let mut scan = start;
3510        while scan < limit {
3511            // SenseNova-Loop: MRoPE prompt rows rotate on the host; an mHC
3512            // layer rides the graph when its kernels compiled (two streams,
3513            // dense FFN, device attend — checked below).
3514            if self.prompt_mrope.is_some()
3515                || (self.mhc_layer(scan)
3516                    && (!crate::gpu_metal::mhc::available()
3517                        || std::env::var("CMF_MHC_GRAPH").as_deref() == Ok("0")
3518                        || self.mhc.as_ref().is_some_and(|m| m.s.streams != 2 || m.s.fixed_identity)
3519                        || !matches!(self.weights.layers[self.phys_layer(scan)].ffn, FfnKind::Dense(_))))
3520            {
3521                break;
3522            }
3523            let lw = &self.weights.layers[self.phys_layer(scan)];
3524            let ffn = match &lw.ffn {
3525                FfnKind::Dense(d) if d.segs.is_empty() => {
3526                    let (Some(g), Some(u), Some(dn)) = (
3527                        d.gate_proj.metal_graph_parts(),
3528                        d.up_proj.metal_graph_parts(),
3529                        d.down_proj.metal_graph_parts(),
3530                    ) else {
3531                        if block_diag {
3532                            eprintln!(
3533                                "block-graph: L{scan} FFN trio not graph-mappable — run ends"
3534                            );
3535                        }
3536                        break;
3537                    };
3538                    MetalFfn::Dense {
3539                        gate: g,
3540                        up: u,
3541                        down: dn,
3542                        // The front gate admitted SiLU, exact GELU and
3543                        // (Gemma-4) tanh-GELU only.
3544                        act: d.act.graph_act().map_or(0, |a| a.code() as u8),
3545                    }
3546                }
3547                FfnKind::Moe(m) => {
3548                    // Flint's detached Q4 shared expert is intentionally
3549                    // tried before the generic uniform-bank graph builder.
3550                    // The latter correctly refuses its ragged Q2/Q4 widths;
3551                    // this narrow descriptor keeps the router and selected
3552                    // routed experts device-resident inside a bounded page.
3553                    let ffn = if let Some(flint) = metal_flint_moe_graph_parts(m, self.hidden_size, scan)
3554                    {
3555                        MetalFfn::FlintMoe(flint)
3556                    } else if let Some(moe) = metal_moe_graph_parts(m, self.hidden_size) {
3557                        MetalFfn::Moe(moe)
3558                    } else {
3559                        if block_diag {
3560                            eprintln!(
3561                                "block-graph: L{scan} MoE outside the graph contract — run ends"
3562                            );
3563                        }
3564                        break;
3565                    };
3566                    if let QTensor::Mapped { model, .. } = &m.experts[0].gate_proj {
3567                        model_ref.get_or_insert_with(|| model.clone());
3568                    }
3569                    ffn
3570                }
3571                _ => {
3572                    if block_diag {
3573                        eprintln!("block-graph: L{scan} non-graph FFN — run ends");
3574                    }
3575                    break;
3576                }
3577            };
3578            match &lw.attn {
3579                AttnKind::LinearGdn(w) if self.gdn_cfg.is_some() => {
3580                    let parts = (
3581                        w.in_proj_qkv.metal_graph_parts(),
3582                        w.in_proj_z.metal_graph_parts(),
3583                        w.in_proj_a.f32_parts(),
3584                        w.in_proj_b.f32_parts(),
3585                        w.out_proj.metal_graph_parts(),
3586                    );
3587                    let (Some(qkv), Some(z), Some(a), Some(b), Some(out)) = parts else {
3588                        if block_diag {
3589                            eprintln!(
3590                                "block-graph: L{scan} GDN parts refused (qkv={} z={} a_f32={} b_f32={} out={})",
3591                                w.in_proj_qkv.metal_graph_parts().is_some(),
3592                                w.in_proj_z.metal_graph_parts().is_some(),
3593                                w.in_proj_a.f32_parts().is_some(),
3594                                w.in_proj_b.f32_parts().is_some(),
3595                                w.out_proj.metal_graph_parts().is_some(),
3596                            );
3597                        }
3598                        break;
3599                    };
3600                    if let QTensor::Mapped { model, .. } = &w.in_proj_qkv {
3601                        model_ref.get_or_insert_with(|| model.clone());
3602                    }
3603                    let gl = GdnGpuLayer {
3604                        mhc: crate::sensenova::graph_mhc(self.mhc.as_deref(), self.phys_layer(scan)),
3605                        attn_norm: &lw.input_norm,
3606                        post_norm: &lw.post_norm,
3607                        qkv,
3608                        z,
3609                        a,
3610                        b,
3611                        out,
3612                        ffn,
3613                        conv1d: &w.conv1d,
3614                        a_log: &w.a_log,
3615                        dt_bias: &w.dt_bias,
3616                        gnorm: &w.norm,
3617                    };
3618                    // a run ends at a layer a DFlash drafter reads: its output is kept there
3619                    let cut = scan > 0 && self.dflash.as_ref().is_some_and(|d| d.g.taps.contains(&(scan - 1)));
3620                    match plan.last_mut() {
3621                        Some(Item::Gdn { run, .. }) if !cut => run.push(gl),
3622                        _ => plan.push(Item::Gdn {
3623                            run: vec![gl],
3624                            first: scan,
3625                        }),
3626                    }
3627                }
3628                AttnKind::ShortConv(w) if self.short_conv_cfg.is_some() => {
3629                    let (Some(inp), Some(out)) =
3630                        (w.in_proj.metal_graph_parts(), w.out_proj.metal_graph_parts())
3631                    else {
3632                        if block_diag {
3633                            eprintln!("block-graph: L{scan} short-conv parts refused");
3634                        }
3635                        break;
3636                    };
3637                    if let QTensor::Mapped { model, .. } = &w.in_proj {
3638                        model_ref.get_or_insert_with(|| model.clone());
3639                    }
3640                    let sl = SconvGpuLayer {
3641                        attn_norm: &lw.input_norm,
3642                        post_norm: &lw.post_norm,
3643                        in_proj: inp,
3644                        taps: &w.conv,
3645                        out,
3646                        attn_out_norm: lw.attn_out_norm.as_deref(),
3647                        ffn_out_norm: lw.ffn_out_norm.as_deref(),
3648                        ffn,
3649                    };
3650                    match plan.last_mut() {
3651                        Some(Item::Sconv { run, .. }) => run.push(sl),
3652                        _ => plan.push(Item::Sconv {
3653                            run: vec![sl],
3654                            first: scan,
3655                        }),
3656                    }
3657                }
3658                AttnKind::Full {
3659                    wq,
3660                    wk,
3661                    wv,
3662                    wo,
3663                    q_norm,
3664                    k_norm,
3665                    output_gate,
3666                    softplus_gate,
3667                    bias,
3668                } if (!self.kv_cache.layers[scan].o1_sealed()
3669                    // Sealed o1 stays plannable when the Metal o1 port
3670                    // is on: full_gpu attends through the device state,
3671                    // and any refusal falls to the sandwich, whose CPU
3672                    // core routes sealed layers through the nystrom step.
3673                    || std::env::var("CMF_O1_METAL").as_deref() == Ok("1")
3674                    || self.o1_on_graph())
3675                    // A projected output gate: Spark-X2.5's per-head
3676                    // sigmoid form only (Laguna's softplus gate is
3677                    // unmeasured on these paths and keeps the CPU walk).
3678                    && softplus_gate
3679                        .as_ref()
3680                        .is_none_or(|(_, per_head)| *per_head && self.proj_gate_sigmoid) =>
3681                {
3682                    let parts = (
3683                        wq.metal_graph_parts(),
3684                        wk.metal_graph_parts(),
3685                        wv.metal_graph_parts(),
3686                        wo.metal_graph_parts(),
3687                    );
3688                    let (Some(pq), Some(pk), Some(pv), Some(po)) = parts else {
3689                        break;
3690                    };
3691                    if let QTensor::Mapped { model, .. } = wq {
3692                        model_ref.get_or_insert_with(|| model.clone());
3693                    }
3694                    let cache = &self.kv_cache.layers[scan];
3695                    // O(1) layer on Metal: the device attends through the
3696                    // sealed Nystrom state (opt-in while the port proves
3697                    // itself). Unsealed -> sandwich path = the CPU o1 step.
3698                    let o1_metal = cache.o1.is_some()
3699                        && (std::env::var("CMF_O1_METAL").as_deref() == Ok("1") || self.o1_on_graph())
3700                        && cache.o1_views().is_some();
3701                    // The device attend takes the layer's window and RoPE
3702                    // table, and the per-head gate from f32 rows; a gate
3703                    // held otherwise sandwiches.
3704                    let head_gate_w = softplus_gate
3705                        .as_ref()
3706                        .and_then(|(g, _)| g.f32_parts())
3707                        .filter(|&(_, r, c)| r == self.num_heads && c == self.hidden_size)
3708                        .map(|(d, _, _)| d);
3709                    // Gemma-4's global layers are 512 wide over one KV head
3710                    // (the `gemma4` 16-slot kernels, `CMF_METAL_GEMMA4_W16`).
3711                    let (nkv_g, hd_g) = if gemma4 {
3712                        let (a, b, _) = self.layer_geom(scan);
3713                        (a, b)
3714                    } else {
3715                        (self.num_kv_heads, self.head_dim)
3716                    };
3717                    let full_gpu = attend_contract
3718                        && softplus_gate.is_none() == head_gate_w.is_none()
3719                        && cache.mode == crate::kv_cache::KvMode::F32
3720                        && (cache.o1.is_none() || o1_metal)
3721                        && bias.is_none()
3722                        && (hd_g <= 256 || crate::gpu_metal::gemma4::w16_on())
3723                        && pq.1 == self.num_heads * hd_g * (1 + *output_gate as usize)
3724                        && pk.1 == nkv_g * hd_g
3725                        && pv.1 == nkv_g * hd_g
3726                        && po.2 == self.num_heads * hd_g;
3727                    // An mHC layer needs the device attend (the CPU-attend
3728                    // sandwich has no stream hand-off), and so does a DASH
3729                    // layer: its router state lives on the device.
3730                    if !full_gpu && (self.mhc_layer(scan) || self.dash.is_some()) {
3731                        break;
3732                    }
3733                    plan.push(Item::Attn {
3734                        l: AttnGpuLayer {
3735                            mhc: crate::sensenova::graph_mhc(self.mhc.as_deref(), self.phys_layer(scan)),
3736                            attn_norm: &lw.input_norm,
3737                            post_norm: &lw.post_norm,
3738                            wq: pq,
3739                            wk: pk,
3740                            wv: pv,
3741                            wo: po,
3742                            ffn,
3743                            attn_out_norm: lw.attn_out_norm.as_deref(),
3744                            ffn_out_norm: lw.ffn_out_norm.as_deref(),
3745                            layer_scale: lw.layer_scale,
3746                        },
3747                        li: scan,
3748                        q_norm: q_norm.as_deref(),
3749                        k_norm: k_norm.as_deref(),
3750                        output_gate: *output_gate,
3751                        proj_gate: softplus_gate.as_ref().map(|(g, per_head)| (g, *per_head)),
3752                        head_gate_w,
3753                        bias: bias
3754                            .as_ref()
3755                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
3756                        full_gpu,
3757                    });
3758                }
3759                _ => break,
3760            }
3761            scan += 1;
3762        }
3763        // SenseNova-Loop: the mHC streams live on the device only inside one
3764        // graph, so a graph may neither enter a range midway nor stop
3765        // inside one (the host walks such a stretch with its own streams).
3766        if let Some(m) = self.mhc.as_deref() {
3767            let inside = |li: usize| m.on(self.phys_layer(li));
3768            let starts_mid = inside(start) && !m.enters(self.phys_layer(start));
3769            let stops_mid = scan > start && inside(scan - 1) && !m.leaves(self.phys_layer(scan - 1));
3770            if starts_mid || stops_mid {
3771                if std::env::var("CMF_GRAPH_DBG").is_ok() {
3772                    eprintln!("q1-graph: [{start}, {scan}) would split an mHC range — host path");
3773                }
3774                return start;
3775            }
3776        }
3777        // Unlimited-OCR: all of it or none of it, the host's router state and
3778        // the device's are not interchangeable (`CMF_GPU=wgpu` keeps the host's).
3779        if self.dash.is_some()
3780            && (start != 0 || scan != self.num_layers || crate::gpu::backend_name() != "metal")
3781        {
3782            return start;
3783        }
3784        let Some(model) = model_ref else {
3785            if std::env::var("CMF_GRAPH_DBG").is_ok() {
3786                eprintln!("q1-graph: no model ref (start {start}, scanned to {scan})");
3787            }
3788            if self.graph_head_required {
3789                self.fail_metal_graph("native graph has no mapped model reference");
3790            }
3791            return start;
3792        };
3793        if plan.is_empty() {
3794            if std::env::var("CMF_GRAPH_DBG").is_ok() {
3795                eprintln!("q1-graph: empty plan at layer {start}");
3796            }
3797            if self.graph_head_required {
3798                self.fail_metal_graph("native graph plan is empty");
3799            }
3800            return start;
3801        }
3802        let has_moe = plan.iter().any(|it| match it {
3803            Item::Gdn { run, .. } => run
3804                .iter()
3805                .any(|l| matches!(l.ffn, MetalFfn::Moe(_) | MetalFfn::FlintMoe(_))),
3806            Item::Sconv { run, .. } => run
3807                .iter()
3808                .any(|l| matches!(l.ffn, MetalFfn::Moe(_) | MetalFfn::FlintMoe(_))),
3809            Item::Attn { l, .. } => matches!(l.ffn, MetalFfn::Moe(_) | MetalFfn::FlintMoe(_)),
3810        });
3811        let has_flint_moe = plan.iter().any(|it| match it {
3812            Item::Gdn { run, .. } => run.iter().any(|l| matches!(l.ffn, MetalFfn::FlintMoe(_))),
3813            Item::Sconv { run, .. } => run.iter().any(|l| matches!(l.ffn, MetalFfn::FlintMoe(_))),
3814            Item::Attn { l, .. } => matches!(l.ffn, MetalFfn::FlintMoe(_)),
3815        });
3816        let metal_working_set = crate::gpu_metal::working_set_bytes();
3817        let metal_max_buffer = crate::gpu_metal::max_buffer_bytes();
3818        let model_bytes = model.primary_bytes().len() as u64;
3819        // Flint q2 can sit below recommendedMaxWorkingSetSize on a 24 GB
3820        // M4 yet still exceed maxBufferLength. In that case a normal graph
3821        // would manufacture overlapping whole-file WeightArena windows;
3822        // treat it as the same bounded-page requirement rather than letting
3823        // the generic graph reintroduce broad residency.
3824        let needs_bounded_pager = (metal_working_set != 0 && model_bytes > metal_working_set)
3825            || (metal_max_buffer != 0 && model_bytes > metal_max_buffer);
3826        // An oversized MoE mmap normally has to decline: the jobs kernels
3827        // bind all WeightArena windows.  The opt-in pager takes a different,
3828        // bounded route: a *complete sequence of logical layers* is put in
3829        // one transient no-copy page, graph-finished, dropped, then the outer
3830        // layer loop calls us again for the next page.  That preserves exact
3831        // hidden/GDN/KV handoff while replacing ~40 host-routed expert waits
3832        // with a few page-boundary syncs.  Never use it for a fused-head NLL
3833        // request: that contract explicitly requires a single whole graph.
3834        let pager_cap = if !has_moe {
3835            None
3836        } else if has_flint_moe {
3837            // Do not let generic `CMF_METAL_MOE_PAGER` turn the experimental
3838            // full-bank Flint graph on. Its direct selected-view pager stays
3839            // independently automatic; this path needs its own opt-in.
3840            crate::gpu_metal::flint_moe_pager_cap_bytes(&model)
3841        } else {
3842            crate::gpu_metal::moe_pager_cap_bytes()
3843        };
3844        let pager_eligible =
3845            pager_cap.is_some() && !self.graph_head_required && needs_bounded_pager;
3846        let mut pager_span: Option<(usize, usize)> = None;
3847        if pager_eligible {
3848            let cap = pager_cap.expect("checked above");
3849            // When this page reaches the true model end, include the fused
3850            // lm_head too.  Otherwise `lm_head_ok` would correctly refuse a
3851            // binding outside the page after the layers had already run.
3852            let tail_span = (self.graph_want_logits
3853                && upto.is_none()
3854                && scan == self.num_layers
3855                && std::env::var("CMF_GPU_LMHEAD")
3856                    .map(|v| v != "0")
3857                    .unwrap_or(true))
3858            .then(|| self.weights.lm_head.metal_graph_parts())
3859            .flatten()
3860            .and_then(|lm| crate::gpu_metal::model_tensor_span(&model, lm.0));
3861            let add_layer_span = |span: Option<(usize, usize)>, li: usize| {
3862                let (lo, hi) = crate::gpu_metal::model_layer_span(&model, self.phys_layer(li))?;
3863                Some(match span {
3864                    Some((cur_lo, cur_hi)) => (cur_lo.min(lo), cur_hi.max(hi)),
3865                    None => (lo, hi),
3866                })
3867            };
3868            let page_span = |span: (usize, usize), include_tail: bool| {
3869                let (mut lo, mut hi) = span;
3870                if include_tail {
3871                    if let Some((tail_lo, tail_hi)) = tail_span {
3872                        lo = lo.min(tail_lo);
3873                        hi = hi.max(tail_hi);
3874                    }
3875                }
3876                crate::gpu_metal::page_round_span(lo, hi)
3877            };
3878            let mut selected = 0usize;
3879            let mut selected_span: Option<(usize, usize)> = None;
3880            // `Item::Gdn` is built as a maximal run so the normal resident
3881            // graph can batch its recurrent state work.  A physical CMF can
3882            // nevertheless place that whole run across a page cap while each
3883            // logical layer fits.  Split *only the final admitted run* at a
3884            // layer boundary: the next outer-loop call rebuilds the remaining
3885            // suffix, preserving hidden/state handoff and keeping the normal
3886            // long-run batching within every page.
3887            let mut gdn_prefix: Option<(usize, usize)> = None;
3888            'items: for (i, item) in plan.iter().enumerate() {
3889                match item {
3890                    // Short-conv runs are not paged (no oversized
3891                    // short-conv MoE has been measured): the page ends.
3892                    Item::Sconv { .. } => break,
3893                    Item::Attn { li, .. } => {
3894                        let Some(span) = add_layer_span(selected_span, *li) else {
3895                            break;
3896                        };
3897                        let Some((page_lo, page_hi)) = page_span(span, i + 1 == plan.len()) else {
3898                            break;
3899                        };
3900                        if page_hi - page_lo > cap {
3901                            break;
3902                        }
3903                        selected = i + 1;
3904                        selected_span = Some((page_lo, page_hi));
3905                    }
3906                    Item::Gdn { first, run } => {
3907                        // Preserve a complete recurrent run whenever it can
3908                        // occupy a page on its own.  If the preceding items
3909                        // merely used the remaining cap, close that page and
3910                        // let the next q1 invocation retain the full run.
3911                        // Prefix-splitting is only for a run that genuinely
3912                        // cannot fit an empty page.
3913                        let mut whole = None;
3914                        for take in 1..=run.len() {
3915                            whole = add_layer_span(whole, *first + take - 1);
3916                            if whole.is_none() {
3917                                break;
3918                            }
3919                        }
3920                        let whole_fits_empty_page = whole
3921                            .and_then(|span| page_span(span, false))
3922                            .is_some_and(|(lo, hi)| hi - lo <= cap);
3923                        if whole_fits_empty_page {
3924                            let mut span = selected_span;
3925                            for take in 1..=run.len() {
3926                                let Some(next) = add_layer_span(span, *first + take - 1) else {
3927                                    break 'items;
3928                                };
3929                                span = Some(next);
3930                            }
3931                            let Some(span) = span else {
3932                                break;
3933                            };
3934                            let Some((page_lo, page_hi)) = page_span(span, i + 1 == plan.len())
3935                            else {
3936                                break;
3937                            };
3938                            if page_hi - page_lo > cap {
3939                                break;
3940                            }
3941                            selected = i + 1;
3942                            selected_span = Some((page_lo, page_hi));
3943                            continue;
3944                        }
3945                        if selected != 0 {
3946                            break;
3947                        }
3948                        let mut span = None;
3949                        let mut best: Option<(usize, (usize, usize))> = None;
3950                        for take in 1..=run.len() {
3951                            let Some(next) = add_layer_span(span, *first + take - 1) else {
3952                                break;
3953                            };
3954                            // A partial final run cannot encode the lm_head;
3955                            // only its complete form above may include it.
3956                            let Some((page_lo, page_hi)) = page_span(next, false) else {
3957                                break;
3958                            };
3959                            if page_hi - page_lo > cap {
3960                                break;
3961                            }
3962                            span = Some((page_lo, page_hi));
3963                            best = Some((take, (page_lo, page_hi)));
3964                        }
3965                        let Some((take, page)) = best else {
3966                            break;
3967                        };
3968                        selected = i + 1;
3969                        selected_span = Some(page);
3970                        if take != run.len() {
3971                            gdn_prefix = Some((i, take));
3972                            break 'items;
3973                        }
3974                    }
3975                }
3976            }
3977            if selected != 0 {
3978                if let Some((item, take)) = gdn_prefix {
3979                    match &mut plan[item] {
3980                        Item::Gdn { run, .. } => run.truncate(take),
3981                        Item::Sconv { .. } | Item::Attn { .. } => {
3982                            unreachable!("only a GDN run is splittable")
3983                        }
3984                    }
3985                }
3986                let (page_lo, page_hi) = selected_span.expect("selected page span");
3987                tracing::info!(
3988                    page_start = page_lo,
3989                    page_end = page_hi,
3990                    page_mb = (page_hi - page_lo) / (1024 * 1024),
3991                    cap_mb = cap / (1024 * 1024),
3992                    graph_items = selected,
3993                    "native Metal MoE graph uses transient bounded weight page"
3994                );
3995                plan.truncate(selected);
3996                pager_span = Some((page_lo, page_hi));
3997            } else {
3998                tracing::warn!(
3999                    cap_mb = cap / (1024 * 1024),
4000                    "native Metal MoE pager declined: one graph item does not fit its safe page cap"
4001                );
4002            }
4003        }
4004        // A native MoE graph binds every WeightArena window to its jobs
4005        // kernels. On UMA, an mmap that already exceeds the driver's
4006        // recommended working set will therefore fail after admission, when
4007        // some recurrent/KV scratch has already been touched. Decline before
4008        // allocating/encoding the graph instead; the ordinary per-operation
4009        // route remains available and only materializes the needed window.
4010        // Do not apply this to dense graphs: they bind one projection at a
4011        // time and do not have the MoE jobs' all-window lifetime.
4012        if has_moe && needs_bounded_pager && pager_span.is_none() {
4013            tracing::info!(
4014                model_bytes,
4015                metal_working_set,
4016                "native Metal MoE graph declined before allocation"
4017            );
4018            self.note_graph_decline("metal block graph", MOE_WORKING_SET_REASON);
4019            if self.graph_head_required {
4020                self.fail_metal_graph(MOE_WORKING_SET_REASON);
4021            }
4022            return start;
4023        }
4024        let has_gdn = plan.iter().any(|it| matches!(it, Item::Gdn { .. }));
4025        let dev_attend = attend_contract
4026            && (self.head_dim <= 128
4027                || has_moe
4028                // A GDN hybrid attends on a quarter of its layers: the
4029                // hd>128 caution was measured on pure-dense models where
4030                // gqa_attend dominates, and on Qwen3.8-27B (hd 256, 48
4031                // GDN + 16 attn) the sandwich costs 2x the whole decode
4032                // (1.2 vs 2.21 tok/s measured before the arena fix).
4033                || (self.head_dim <= 256 && has_gdn)
4034                // Sliding-window layers bound most attends by the window:
4035                // Spark-X2.5-1.7B q4tp on the M4 decodes 67 tok/s
4036                // device-attended against 23 sandwiched (28 syncs/token).
4037                || (self.head_dim <= 256 && swa_graph)
4038                || attend_mode == "force"
4039                || attend_mode == "256");
4040        if !dev_attend {
4041            for it in &mut plan {
4042                if let Item::Attn { li, full_gpu, .. } = it {
4043                    // The hd>128 policy is about gqa_attend; an o1 layer
4044                    // attends through its own kernel set.
4045                    let keep_o1 = self.kv_cache.layers[*li].o1.is_some()
4046                        && std::env::var("CMF_O1_METAL").as_deref() == Ok("1");
4047                    if !keep_o1 {
4048                        *full_gpu = false;
4049                    }
4050                }
4051            }
4052        }
4053        if std::env::var("CMF_GRAPH_DBG").is_ok() {
4054            use std::sync::atomic::{AtomicBool, Ordering};
4055            static SAID: AtomicBool = AtomicBool::new(false);
4056            if !SAID.swap(true, Ordering::Relaxed) {
4057                let fg = plan
4058                    .iter()
4059                    .filter(|it| matches!(it, Item::Attn { full_gpu: true, .. }))
4060                    .count();
4061                let att = plan
4062                    .iter()
4063                    .filter(|it| matches!(it, Item::Attn { .. }))
4064                    .count();
4065                eprintln!(
4066                    "q1-graph: plan of {} items from layer {start} to {scan} | dev_attend={dev_attend} full_gpu {fg}/{att} | hd={} rd={} nkv={} nh={}",
4067                    plan.len(),
4068                    self.head_dim,
4069                    self.rotary_dim,
4070                    self.num_kv_heads,
4071                    self.num_heads,
4072                );
4073            }
4074        }
4075        let dims = GraphDims {
4076            hidden: self.hidden_size,
4077            eps: self.rms_eps as f32,
4078            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
4079        };
4080        // The outer `forward_layers_span` scope is one logical token.  This
4081        // guard starts at q1_graph_gpu entry and ends after all page readback,
4082        // so a multi-page token cannot be reported as several whole tokens.
4083        let mut pager_profile_page = pager_span.map(|(page_lo, page_hi)| {
4084            crate::gpu_metal::MoePagerPageScope::new(
4085                _mt0,
4086                position,
4087                start,
4088                page_lo,
4089                page_hi,
4090                // `pager_span` is selected only after a cap was admitted;
4091                // keep the profiler observational if that invariant is ever
4092                // loosened rather than introducing a new inference panic.
4093                pager_cap.unwrap_or(0),
4094            )
4095        });
4096        let graph_new = match pager_span {
4097            Some((page_lo, page_hi)) => TokenGraph::new_paged(&model, dims, h, page_lo, page_hi),
4098            None => TokenGraph::new(&model, dims, h),
4099        };
4100        let Some(mut graph) = graph_new else {
4101            if self.graph_head_required {
4102                self.fail_metal_graph("native TokenGraph allocation refused");
4103            }
4104            return start;
4105        };
4106        if swa_graph && self.head_dim > 128 {
4107            // Spark-X2.5 (hd 256, 4 Q heads per KV head): the GQA-shared
4108            // split-K attend reads each K/V row once for the group instead
4109            // of once per head plus the importance re-read — at depth 1000
4110            // on the M4, 59.5 tok/s against 50.0 with the per-head kernel
4111            // up to the default 512 (every sliding layer sits at <= 512).
4112            // From the second position on and in 32-position blocks (more
4113            // threadgroups in flight for a latency-bound walk): Spark-X2.6
4114            // q4tp decode 0.86x the GPU time short and 0.88x at depth 1000,
4115            // q8_2f 0.91x / 0.92x (in-process A/B, M4).
4116            graph.set_attend_blk(1, 32);
4117        }
4118        let gcfg = self.gdn_cfg.map(|cfg| GdnGpuCfg {
4119            nv: cfg.num_v_heads,
4120            nk: cfg.num_k_heads,
4121            dk: cfg.key_head_dim,
4122            dv: cfg.value_head_dim,
4123            kk: cfg.conv_kernel,
4124            hidden: self.hidden_size,
4125            inter: self.intermediate_size,
4126            c_dim: cfg.conv_dim(),
4127            eps: cfg.rms_eps as f32,
4128            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
4129        });
4130        // Validate the whole plan BEFORE encoding anything: after the
4131        // first sync a refused layer would leave the token
4132        // half-executed, so truncate to the provably encodable prefix.
4133        let mut valid = 0usize;
4134        let mut end = start;
4135        crate::gpu::stageprof(1, _mt0.elapsed()); // конец планирования
4136        if std::env::var("CMF_PLAN_DUMP").is_ok() {
4137            static ONCE: std::sync::Once = std::sync::Once::new();
4138            ONCE.call_once(|| {
4139                for it in &plan {
4140                    match it {
4141                        Item::Gdn { first, run } => {
4142                            eprintln!("plan: Gdn first={first} len={}", run.len())
4143                        }
4144                        Item::Sconv { first, run } => {
4145                            eprintln!("plan: Sconv first={first} len={}", run.len())
4146                        }
4147                        Item::Attn { li, full_gpu, .. } => {
4148                            eprintln!("plan: Attn li={li} full_gpu={full_gpu}")
4149                        }
4150                    }
4151                }
4152            });
4153        }
4154        for item in &plan {
4155            let ok = match item {
4156                Item::Gdn { run, .. } => gcfg
4157                    .as_ref()
4158                    .map(|gc| run.iter().all(|l| graph.gdn_ok(l, gc)))
4159                    .unwrap_or(false),
4160                Item::Sconv { run, .. } => self
4161                    .short_conv_cfg
4162                    .is_some_and(|sc| run.iter().all(|l| graph.sconv_ok(l, sc.kernel))),
4163                Item::Attn { l, .. } => graph.attn_ok(l),
4164            };
4165            if !ok {
4166                if block_diag {
4167                    eprintln!(
4168                        "block-graph: plan item {} ({}) failed graph preflight",
4169                        valid,
4170                        match item {
4171                            Item::Gdn { run, first } => format!("GDN run L{first}+{}", run.len()),
4172                            Item::Sconv { run, first } => {
4173                                format!("short-conv run L{first}+{}", run.len())
4174                            }
4175                            Item::Attn { li, .. } => format!("Attn L{li}"),
4176                        }
4177                    );
4178                }
4179                break;
4180            }
4181            valid += 1;
4182            end += match item {
4183                Item::Gdn { run, .. } => run.len(),
4184                Item::Sconv { run, .. } => run.len(),
4185                Item::Attn { .. } => 1,
4186            };
4187        }
4188        plan.truncate(valid);
4189        if plan.is_empty() {
4190            if self.graph_head_required {
4191                self.fail_metal_graph("native graph preflight produced no valid items");
4192            }
4193            return start;
4194        }
4195
4196        if self.graph_head_required && (upto.is_some() || end != self.num_layers) {
4197            self.fail_metal_graph("fused-head NLL requires a complete 64-layer graph");
4198            return start;
4199        }
4200
4201        // Plain dense decode (every item a device-attended full-attention
4202        // layer with a dense FFN, no O(1) state): the only plan shape the
4203        // masked-nibble q4tp matvec and the concurrent layer encoder were
4204        // measured on (MiniCPM5-2B, Qwen3-0.6B on the M4). Hybrids, MoE and
4205        // o1 layers keep the historical serial path bit for bit.
4206        // Every projection must be ONE dispatch (q1t adds an overlay pass,
4207        // Prism q2tp a transform pass — dependent pairs a concurrent
4208        // encoder would race).
4209        let one_pass = |t: (usize, usize, usize)| {
4210            use cortiq_core::TensorDtype as D;
4211            matches!(
4212                model.tensors[t.0].dtype,
4213                D::Q4TiledP | D::Q4Tiled | D::Q4Block | D::Q8Row | D::Q8_2f | D::Q1 | D::Q1G
4214            )
4215        };
4216        let dense_fast = plan.iter().all(|it| match it {
4217            Item::Attn {
4218                l, li, full_gpu, ..
4219            } => {
4220                *full_gpu
4221                    && self.kv_cache.layers[*li].o1.is_none()
4222                    && [l.wq, l.wk, l.wv, l.wo].into_iter().all(one_pass)
4223                    && match l.ffn {
4224                        MetalFfn::Dense { gate, up, down, .. } => {
4225                            one_pass(gate) && one_pass(up) && one_pass(down)
4226                        }
4227                        _ => false,
4228                    }
4229            }
4230            // A short-conv run encodes serially in its own encoder: its
4231            // one-pass projections take the same matvec levers.
4232            Item::Sconv { run, .. } => run.iter().all(|l| {
4233                one_pass(l.in_proj)
4234                    && one_pass(l.out)
4235                    && match l.ffn {
4236                        MetalFfn::Dense { gate, up, down, .. } => {
4237                            one_pass(gate) && one_pass(up) && one_pass(down)
4238                        }
4239                        _ => false,
4240                    }
4241            }),
4242            Item::Gdn { .. } => false,
4243        });
4244        // MoE decode with every layer device-attended (Mellum2.1): the
4245        // routed experts' jobs ladder and the q8_2f attention projections
4246        // take their measured levers (`MOE_*`, `DENSE_Q8R4`).
4247        let moe_plan = !dense_fast
4248            && plan.iter().all(|it| match it {
4249                Item::Attn {
4250                    l, li, full_gpu, ..
4251                } => {
4252                    *full_gpu
4253                        && self.kv_cache.layers[*li].o1.is_none()
4254                        && (matches!(l.ffn, MetalFfn::Moe(_) | MetalFfn::FlintMoe(_))
4255                            || self.dash.is_some())
4256                }
4257                Item::Gdn { .. } | Item::Sconv { .. } => false,
4258            });
4259        let ab = crate::gpu_metal::dense_ab_arm().filter(|_| dense_fast || moe_plan);
4260        if block_diag {
4261            use std::sync::atomic::{AtomicBool, Ordering};
4262            static SAID_AB: AtomicBool = AtomicBool::new(false);
4263            if !SAID_AB.swap(true, Ordering::Relaxed) {
4264                eprintln!("q1-graph: dense_fast={dense_fast} moe_plan={moe_plan} ab={ab:?}");
4265            }
4266        }
4267        let _mv_fast = match ab {
4268            Some((bits, _)) => {
4269                graph.set_dense_concurrent_raw(bits & crate::gpu_metal::DENSE_CONC != 0);
4270                crate::gpu_metal::MvFastGuard::set_raw(bits)
4271            }
4272            None if moe_plan => {
4273                graph.set_dense_concurrent(
4274                    crate::gpu_metal::MOE_PLAN_BITS & crate::gpu_metal::DENSE_CONC != 0,
4275                );
4276                crate::gpu_metal::MvFastGuard::set_bits(crate::gpu_metal::MOE_PLAN_BITS)
4277            }
4278            None => {
4279                graph.set_dense_concurrent(dense_fast);
4280                // The four-row q8_2f matvec (same per-row sum order, text
4281                // unchanged): in-process A/B on the M4, token time 0.81x on
4282                // MiniCPM5-2B, 0.78x on Minico-M1, 0.85x on MNN-Pocket-0.3B;
4283                // Spark-X2.5 1.7B 40.5 against 27.7 tok/s. `CMF_Q8_R4=0` closes it.
4284                let _ = swa_graph;
4285                crate::gpu_metal::MvFastGuard::set_bits(if dense_fast {
4286                    crate::gpu_metal::DENSE_MV | crate::gpu_metal::DENSE_FUSE | crate::gpu_metal::DENSE_Q8R4
4287                } else {
4288                    0
4289                })
4290            }
4291        };
4292
4293        // RoPE table and rotary width are per layer (`layer_inv_freq`,
4294        // `layer_geom`) inside the loop below.
4295        let pool = self.pool.clone();
4296        let (nh, nkv, hd, hs, eps) = (
4297            self.num_heads,
4298            self.num_kv_heads,
4299            self.head_dim,
4300            self.hidden_size,
4301            self.rms_eps,
4302        );
4303        let norm_style = self.norm_style;
4304        let gemma = norm_style == cortiq_core::NormStyle::Gemma;
4305        let want = self.gdn_cfg.map(|c| c.state_len()).unwrap_or(0);
4306        let kv_id = self.graph_kv_id;
4307        // GDN runs whose states await readback after the next sync
4308        // (device-attended layers add no sync, so several may stack).
4309        let mut pending: Vec<(usize, usize)> = Vec::new();
4310        // Device-attended layers: their K/V/imp are pulled from the
4311        // mirror after the final sync.
4312        let mut dev_attn: Vec<(usize, usize, usize)> = Vec::new();
4313        // The layers a DFlash drafter reads, kept as the token passes them
4314        // (a whole token in one graph only).
4315        let taps: Vec<usize> = match &self.dflash {
4316            Some(d) if start == 0 && end == self.num_layers => d.g.taps.clone(),
4317            _ => Vec::new(),
4318        };
4319        let mut tapped = 0usize;
4320        for item in &plan {
4321            let _xt0 = std::time::Instant::now();
4322            let _xkind: u32 = match item {
4323                Item::Gdn { .. } | Item::Sconv { .. } => 2,
4324                Item::Attn { .. } => 3,
4325            };
4326            // Looped Transformer: insert on-device norm at loop boundaries.
4327            if self.loop_final_norm {
4328                let item_start = match item {
4329                    Item::Gdn { first, .. } | Item::Sconv { first, .. } => *first,
4330                    Item::Attn { li, .. } => *li,
4331                };
4332                if item_start > start && self.is_loop_end(item_start - 1) {
4333                    graph.encode_loop_norm(&self.weights.final_norm);
4334                }
4335            }
4336            match item {
4337                Item::Gdn { run, first } => {
4338                    for l in &mut self.kv_cache.layers[*first..*first + run.len()] {
4339                        if l.linear_state.len() != want {
4340                            l.linear_state = vec![0f32; want];
4341                        }
4342                    }
4343                    let ro: Vec<&[f32]> = self.kv_cache.layers[*first..*first + run.len()]
4344                        .iter()
4345                        .map(|l| l.linear_state.as_slice())
4346                        .collect();
4347                    let _ig = std::time::Instant::now();
4348                    if !graph.encode_gdn_run(run, &ro, gcfg.as_ref().unwrap()) {
4349                        // Unreachable: the plan was validated above.
4350                        tracing::error!("q1 graph: GDN run refused after validation");
4351                        return start;
4352                    }
4353                    if let Some(slot) = taps.iter().position(|t| *t + 1 == *first + run.len()) {
4354                        tapped += graph.tap(slot, taps.len()) as usize;
4355                    }
4356                    // Early commit: the GPU starts the run while the
4357                    // CPU encodes the next layer (nothing to wait on).
4358                    graph.commit_kind = 2;
4359                    graph.commit();
4360                    crate::gpu::stageprof(0, _ig.elapsed());
4361                    pending.push((*first, run.len()));
4362                }
4363                Item::Sconv { run, first } => {
4364                    let sc = self.short_conv_cfg.expect("validated short-conv run");
4365                    for l in &mut self.kv_cache.layers[*first..*first + run.len()] {
4366                        if l.linear_state.len() != sc.state_len() {
4367                            l.linear_state = vec![0f32; sc.state_len()];
4368                        }
4369                    }
4370                    let ro: Vec<&[f32]> = self.kv_cache.layers[*first..*first + run.len()]
4371                        .iter()
4372                        .map(|l| l.linear_state.as_slice())
4373                        .collect();
4374                    if !graph.encode_sconv_run(run, &ro, sc.kernel) {
4375                        tracing::error!("q1 graph: short-conv run refused after validation");
4376                        return start;
4377                    }
4378                    graph.commit_kind = 2;
4379                    graph.commit();
4380                    pending.push((*first, run.len()));
4381                }
4382                Item::Attn {
4383                    l,
4384                    li,
4385                    q_norm,
4386                    k_norm,
4387                    output_gate,
4388                    proj_gate,
4389                    head_gate_w,
4390                    bias,
4391                    full_gpu,
4392                } => {
4393                    let _ia = std::time::Instant::now();
4394                    // This layer's attention geometry: its window, RoPE
4395                    // table and rotary width (Spark-X2.5 interleaves
4396                    // 512-window layers rotating all dims at θ 1e4 with
4397                    // full layers rotating a quarter at θ 5e6). Every model
4398                    // without sliding layers reads the global ones here.
4399                    let inv_freq_l = self.layer_inv_freq(*li);
4400                    let rd_l = self.layer_geom(*li).2;
4401                    let window_l = self.layer_window(*li);
4402                    let head_gate_w = *head_gate_w;
4403                    // This layer's KV heads and head width: Gemma-4's global
4404                    // layers (one 512-wide KV head) differ from the base.
4405                    let (nkv, hd) = if gemma4 {
4406                        let (a, b, _) = self.layer_geom(*li);
4407                        (a, b)
4408                    } else {
4409                        (nkv, hd)
4410                    };
4411                    // ── Fully device-resident attention: no sync at all.
4412                    if *full_gpu {
4413                        let cache = &self.kv_cache.layers[*li];
4414                        let o1p = if cache.o1.is_some() {
4415                            match cache.o1_views() {
4416                                Some(views) => Some(crate::gpu::O1AttnParams {
4417                                    views,
4418                                    epoch: self.o1_epoch,
4419                                }),
4420                                // Sealed state gone mid-run: sandwich.
4421                                None => None,
4422                            }
4423                        } else {
4424                            None
4425                        };
4426                        let o1_layer = cache.o1.is_some();
4427                        if o1_layer && o1p.is_none() {
4428                            // fall to the sandwich (CPU o1 step)
4429                        }
4430                        let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
4431                        let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
4432                        let cpu_stored = if o1_layer { 0 } else { cpu_k[0].len() / hd };
4433                        // A trimmed tail always holds the window the
4434                        // device attend reads (`first = rows + 1 − w`).
4435                        debug_assert!(
4436                            cache.base() == 0 || window_l.is_some_and(|w| cpu_stored + 1 >= w)
4437                        );
4438                        let dash_l = self.graph_dash(*li);
4439                        // A DASH row carries its own angles: position 1 over
4440                        // them is the rotation (`uocr::rope_angles`).
4441                        let (rope_at, rope_invf, rope_sc): (usize, &[f32], f32) = match self.dash.as_deref() {
4442                            Some(d) => (1, &d.angles, 1.0),
4443                            None => (position, &inv_freq_l, self.layer_rope_scale(*li)),
4444                        };
4445                        let p = crate::gpu::AttnDeviceParams {
4446                            kv_id,
4447                            layer: *li,
4448                            nh,
4449                            nkv,
4450                            hd,
4451                            rd: rd_l,
4452                            position: rope_at,
4453                            scale: self.attn_scale,
4454                            eps: eps as f32,
4455                            gemma,
4456                            late_qk_norm: self.qk_norm_after_rope,
4457                            output_gate: *output_gate,
4458                            q_norm: *q_norm,
4459                            k_norm: *k_norm,
4460                            inv_freq: rope_invf,
4461                            rope_scale: rope_sc,
4462                            cpu_k,
4463                            cpu_v,
4464                            cpu_stored,
4465                            cpu_gen: cache.generation(),
4466                            o1: o1p,
4467                            window: window_l,
4468                            softmax_sink: cache.sinks.as_deref(),
4469                            head_gate: head_gate_w,
4470                            v_norm: self.attn_v_norm,
4471                            dash: dash_l.as_ref(),
4472                        };
4473                        let o1_bad = o1_layer && p.o1.is_none();
4474                        if !o1_bad && graph.attn_device_ok(l, &p) && graph.encode_attn_device(l, &p)
4475                        {
4476                            // o1 layers leave no mirror row to pull.
4477                            if p.o1.is_none() {
4478                                dev_attn.push((*li, nkv, hd));
4479                            }
4480                            if let Some(slot) = taps.iter().position(|t| t == li) {
4481                                tapped += graph.tap(slot, taps.len()) as usize;
4482                            }
4483                            graph.commit_kind = 3;
4484                            graph.commit();
4485                            // The footer below is skipped by `continue`:
4486                            // account the device-attn item here or its
4487                            // cost hides from the stage profile entirely.
4488                            crate::gpu::stageprof(_xkind, _xt0.elapsed());
4489                            continue;
4490                        }
4491                        // Mirror refused (nothing encoded) → sandwich.
4492                    }
4493                    graph.encode_attn_prefix(l);
4494                    if let Err(err) = graph.sync_checked() {
4495                        self.fail_metal_graph(&err);
4496                        return start;
4497                    }
4498                    if !pending.is_empty() {
4499                        let idxs: Vec<usize> =
4500                            pending.drain(..).flat_map(|(f, n)| f..f + n).collect();
4501                        let mut outs: Vec<&mut [f32]> = self
4502                            .kv_cache
4503                            .layers
4504                            .iter_mut()
4505                            .enumerate()
4506                            .filter(|(i, _)| idxs.binary_search(i).is_ok())
4507                            .map(|(_, s)| s.linear_state.as_mut_slice())
4508                            .collect();
4509                        graph.read_states(&mut outs);
4510                    }
4511                    let mut q_raw = attention::take_buf(l.wq.1);
4512                    let mut k = attention::take_buf(l.wk.1);
4513                    let mut v = attention::take_buf(l.wv.1);
4514                    graph.read_qkv(&mut q_raw, &mut k, &mut v);
4515                    // Projected output gate: g = G·norm(h) on the host, off
4516                    // the normed input the prefix left on the device.
4517                    let mut gate_raw = proj_gate.map(|(gp, _)| {
4518                        let mut normed = attention::take_buf(hs);
4519                        graph.read_normed(&mut normed);
4520                        let mut raw = attention::take_buf(gp.rows());
4521                        gp.matvec(&normed, &mut raw, pool.as_deref());
4522                        attention::recycle_buf(&mut normed);
4523                        raw
4524                    });
4525                    let cfg = QwenAttnCfg {
4526                        mrope: None,
4527                        num_heads: nh,
4528                        num_kv_heads: nkv,
4529                        head_dim: hd,
4530                        hidden_size: hs,
4531                        position,
4532                        inv_freq: &inv_freq_l,
4533                        rotary_dim: rd_l,
4534                        scale: self.attn_scale,
4535                        softcap: self.attn_softcap,
4536                        window: window_l,
4537                        // Gemma-4 only (the front gate refuses V norm
4538                        // otherwise).
4539                        v_norm: self.attn_v_norm,
4540                        qk_norm_after_rope: self.qk_norm_after_rope,
4541                        gate_sigmoid: self.proj_gate_sigmoid,
4542                        q_norm: *q_norm,
4543                        k_norm: *k_norm,
4544                        output_gate: *output_gate,
4545                        softplus_gate: None,
4546                        rope_scale: self.layer_rope_scale(*li),
4547                        bias: *bias,
4548                        rms_eps: eps,
4549                        norm_style,
4550                        pool: pool.as_deref(),
4551                        v_head_dim: hd,
4552                        value_in: None,
4553                    };
4554                    // CMF_ATTN_ORACLE=1: diff the device attend against
4555                    // this CPU attend on identical inputs (bring-up).
4556                    let oracle = std::env::var("CMF_ATTN_ORACLE").as_deref() == Ok("1")
4557                        || std::env::var("CMF_ATTN_DUMP").is_ok();
4558                    let _ = full_gpu;
4559                    let oracle_in = oracle.then(|| (q_raw.clone(), k.clone(), v.clone()));
4560                    let mut ao = attention::qwen_attention_core(
4561                        q_raw,
4562                        k,
4563                        v,
4564                        &mut self.kv_cache.layers[*li],
4565                        &cfg,
4566                    );
4567                    // CMF_ATTN_DUMP=<dir>: this token's rope'd Q and the layer's whole
4568                    // K/V cache as raw f32 (offline attention-statistics probes:
4569                    // block bounds, mass concentration). Needs CMF_GPU_ATTEND=0.
4570                    if let Ok(dir) = std::env::var("CMF_ATTN_DUMP") {
4571                        if let Some((qr0, k0, v0)) = oracle_in.clone() {
4572                            let (cq, _cg, _ck, _cv) =
4573                                attention::finish_projection_debug(qr0, k0, v0, &cfg, position);
4574                            let cache = &self.kv_cache.layers[*li];
4575                            let n = cache.head_keys(0).len() / hd;
4576                            let mut bytes: Vec<u8> = Vec::new();
4577                            for v in [nh as u32, nkv as u32, hd as u32, n as u32, position as u32] {
4578                                bytes.extend_from_slice(&v.to_le_bytes());
4579                            }
4580                            for v in &cq {
4581                                bytes.extend_from_slice(&v.to_le_bytes());
4582                            }
4583                            for g in 0..nkv {
4584                                for v in cache.head_keys(g) {
4585                                    bytes.extend_from_slice(&v.to_le_bytes());
4586                                }
4587                            }
4588                            for g in 0..nkv {
4589                                for v in cache.head_values(g) {
4590                                    bytes.extend_from_slice(&v.to_le_bytes());
4591                                }
4592                            }
4593                            let _ =
4594                                std::fs::write(format!("{dir}/L{li}_pos{position}.bin"), &bytes);
4595                        }
4596                    }
4597                    if let Some((qr0, k0, v0)) =
4598                        oracle_in.filter(|_| std::env::var("CMF_ATTN_ORACLE").as_deref() == Ok("1"))
4599                    {
4600                        let (cq, _cg, ck, cv) =
4601                            attention::finish_projection_debug(qr0, k0, v0, &cfg, position);
4602                        let mut h_now = vec![0f32; hs];
4603                        graph.read_h(&mut h_now);
4604                        let cache = &self.kv_cache.layers[*li];
4605                        let n_after = cache.head_keys(0).len() / hd;
4606                        // A sealed O(1) cache may have no dense current-row
4607                        // entry. The oracle is a debug probe, so let it see
4608                        // zero stored exact rows instead of underflowing.
4609                        let stored = n_after.saturating_sub(1);
4610                        let cpu_k: Vec<&[f32]> = (0..nkv)
4611                            .map(|g| &cache.head_keys(g)[..stored * hd])
4612                            .collect();
4613                        let cpu_v: Vec<&[f32]> = (0..nkv)
4614                            .map(|g| &cache.head_values(g)[..stored * hd])
4615                            .collect();
4616                        let p = crate::gpu::AttnDeviceParams {
4617                            kv_id,
4618                            layer: *li,
4619                            nh,
4620                            nkv,
4621                            hd,
4622                            // The layer's own geometry, as the CPU attend
4623                            // above used it (the projected gate is applied
4624                            // after this probe on both sides).
4625                            rd: rd_l,
4626                            position,
4627                            scale: self.attn_scale,
4628                            eps: eps as f32,
4629                            gemma,
4630                            late_qk_norm: self.qk_norm_after_rope,
4631                            output_gate: *output_gate,
4632                            q_norm: *q_norm,
4633                            k_norm: *k_norm,
4634                            inv_freq: &inv_freq_l,
4635                            rope_scale: self.layer_rope_scale(*li),
4636                            cpu_k,
4637                            cpu_v,
4638                            cpu_stored: stored,
4639                            cpu_gen: cache.generation(),
4640                            o1: None,
4641                            window: window_l,
4642                            softmax_sink: cache.sinks.as_deref(),
4643                            head_gate: None,
4644                            v_norm: self.attn_v_norm,
4645                            dash: None,
4646                        };
4647                        if let Some((dq, dk, dv, dao)) = graph.debug_attn_device(l, &p, &h_now) {
4648                            let md = |a: &[f32], b: &[f32]| {
4649                                a.iter().zip(b).fold(0f32, |m, (x, y)| m.max((x - y).abs()))
4650                            };
4651                            let nn = |a: &[f32]| a.iter().map(|x| x * x).sum::<f32>().sqrt();
4652                            eprintln!(
4653                                "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}",
4654                                nn(&cq),
4655                                md(&cq, &dq),
4656                                nn(&ck),
4657                                md(&ck, &dk),
4658                                nn(&cv),
4659                                md(&cv, &dv),
4660                                nn(&ao),
4661                                md(&ao, &dao)
4662                            );
4663                        } else {
4664                            eprintln!("attn-oracle L{li}: device probe declined");
4665                        }
4666                    }
4667                    if let (Some(raw), Some((_, per_head))) = (gate_raw.as_deref(), *proj_gate) {
4668                        // V is as wide as the head (the front gate), so ao
4669                        // is nh·hd here, as in `qwen_attention`.
4670                        attention::apply_projected_gate(
4671                            &mut ao,
4672                            raw,
4673                            per_head,
4674                            hd,
4675                            self.proj_gate_sigmoid,
4676                        );
4677                    }
4678                    if let Some(mut raw) = gate_raw.take() {
4679                        attention::recycle_buf(&mut raw);
4680                    }
4681                    graph.encode_attn_suffix(l, &ao);
4682                    if let Some(slot) = taps.iter().position(|t| t == li) {
4683                        tapped += graph.tap(slot, taps.len()) as usize;
4684                    }
4685                    // Early commit: the GPU starts O+FFN while the CPU
4686                    // encodes the following GDN run / attention prefix.
4687                    graph.commit();
4688                    attention::recycle_buf(&mut ao);
4689                }
4690            }
4691
4692            crate::gpu::stageprof(_xkind, _xt0.elapsed());
4693        }
4694        // Ride the final norm + lm_head in the same command buffer when
4695        // this run reaches the model's end and the caller wants logits:
4696        // the separate per-op lm_head submit (a full round trip) folds
4697        // into the sync that already happens here.
4698        let mut lm_rows = None;
4699        if self.graph_want_logits
4700            && upto.is_none()
4701            && end == self.num_layers
4702            && std::env::var("CMF_GPU_LMHEAD")
4703                .map(|v| v != "0")
4704                .unwrap_or(true)
4705        {
4706            if let Some(lm) = self.weights.lm_head.metal_graph_parts() {
4707                if graph.lm_head_ok(lm) {
4708                    graph.encode_lm_head(&self.weights.final_norm, lm);
4709                    lm_rows = Some(lm.1);
4710                }
4711            }
4712        }
4713        if self.graph_head_required && lm_rows.is_none() {
4714            METAL_GRAPH_HEAD_MISS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4715            self.fail_metal_graph("fused graph head was requested but not encodable");
4716            return start;
4717        }
4718        let _sy0 = std::time::Instant::now();
4719        if let Err(err) = graph.sync_checked() {
4720            if let Some(profile) = pager_profile_page.as_mut() {
4721                profile.finish(start, graph.pager_page_stats(), "sync-error");
4722            }
4723            self.fail_metal_graph(&err);
4724            return start;
4725        }
4726        let _rs0 = std::time::Instant::now();
4727        if !pending.is_empty() {
4728            let idxs: Vec<usize> = pending.drain(..).flat_map(|(f, n)| f..f + n).collect();
4729            let mut outs: Vec<&mut [f32]> = self
4730                .kv_cache
4731                .layers
4732                .iter_mut()
4733                .enumerate()
4734                .filter(|(i, _)| idxs.binary_search(i).is_ok())
4735                .map(|(_, s)| s.linear_state.as_mut_slice())
4736                .collect();
4737            graph.read_states(&mut outs);
4738        }
4739        if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() == Ok("1") {
4740            use std::sync::atomic::{AtomicU64, Ordering};
4741            static SY: AtomicU64 = AtomicU64::new(0);
4742            static RS: AtomicU64 = AtomicU64::new(0);
4743            static N: AtomicU64 = AtomicU64::new(0);
4744            SY.fetch_add((_rs0 - _sy0).as_nanos() as u64, Ordering::Relaxed);
4745            RS.fetch_add(_rs0.elapsed().as_nanos() as u64, Ordering::Relaxed);
4746            let n = N.fetch_add(1, Ordering::Relaxed) + 1;
4747            if n % 100 == 0 {
4748                eprintln!(
4749                    "postprof: sync-wait {:.1} ms/tok | read_states {:.1} ms/tok ({n})",
4750                    SY.load(Ordering::Relaxed) as f64 / n as f64 / 1e6,
4751                    RS.load(Ordering::Relaxed) as f64 / n as f64 / 1e6
4752                );
4753            }
4754        }
4755        if let Some(rows) = lm_rows {
4756            crate::gpu::hostprof_encode_done(_mt0);
4757            let mut lg = attention::take_buf(rows.min(self.vocab_size));
4758            graph.read_logits(&mut lg);
4759            crate::gpu::hostprof_total(_mt0);
4760            lg.resize(self.vocab_size, 0.0);
4761            if let Some(c) = self.final_softcap {
4762                softcap_in_place(&mut lg, c, self.pool.as_deref());
4763            }
4764            self.graph_logits = Some(lg);
4765        }
4766        graph.read_h(h);
4767        // the token's row of the drafter's context
4768        if !taps.is_empty() && tapped == taps.len() {
4769            let mut row = vec![0f32; taps.len() * self.hidden_size];
4770            if graph.read_taps(&mut row) {
4771                if let Some(d) = self.dflash.as_mut() {
4772                    d.queue_context(position, &row, self.pool.as_deref());
4773                }
4774            }
4775        }
4776        if self.graph_head_required && self.graph_logits.is_none() {
4777            METAL_GRAPH_HEAD_MISS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4778            self.fail_metal_graph("fused graph head completed without logits readback");
4779            return start;
4780        }
4781        METAL_GRAPH_TOK_OK.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4782        METAL_GRAPH_LAYERS.fetch_add(
4783            end.saturating_sub(start) as u64,
4784            std::sync::atomic::Ordering::Relaxed,
4785        );
4786        if self.graph_head_required {
4787            METAL_GRAPH_HEAD_OK.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4788        }
4789        // Device-attended layers: replay the CPU bookkeeping — append
4790        // the mirror's new K/V row (rope'd on the GPU) into the owner
4791        // cache, then bank this token's attention-importance mass.
4792        for (li, nkv, hd) in dev_attn {
4793            let mut krow = attention::take_buf(nkv * hd);
4794            let mut vrow = attention::take_buf(nkv * hd);
4795            if crate::gpu::kv_mirror_read_last(kv_id, li, nkv, hd, &mut krow, &mut vrow) {
4796                let cache = &mut self.kv_cache.layers[li];
4797                cache.append(&krow, &vrow, &[]);
4798                let n = cache.seq_len;
4799                let mut imp = attention::take_buf(n);
4800                crate::gpu::kv_mirror_take_imp(kv_id, li, &mut imp);
4801                cache.accumulate_imp(&imp);
4802                attention::recycle_buf(&mut imp);
4803            }
4804            attention::recycle_buf(&mut krow);
4805            attention::recycle_buf(&mut vrow);
4806        }
4807        if let Some(profile) = pager_profile_page.as_mut() {
4808            profile.finish(end, graph.pager_page_stats(), "page-complete");
4809        }
4810        if let Some((_, arm)) = ab {
4811            crate::gpu_metal::dense_ab_record(arm, _mt0.elapsed());
4812        }
4813        end
4814    }
4815
4816    pub fn new(
4817        tokenizer: Tokenizer,
4818        weights: PipelineWeights,
4819        hidden_size: usize,
4820        intermediate_size: usize,
4821        num_heads: usize,
4822        num_kv_heads: usize,
4823        head_dim: usize,
4824        num_layers: usize,
4825        physical_layers: usize,
4826        loop_final_norm: bool,
4827        vocab_size: usize,
4828        rms_eps: f64,
4829        rope_base: f32,
4830        norm_style: NormStyle,
4831        max_seq_len: usize,
4832        sampler_config: SamplerConfig,
4833    ) -> Self {
4834        let rng = match sampler_config.seed {
4835            Some(s) => SplitMix64::new(s),
4836            None => SplitMix64::from_entropy(),
4837        };
4838        let inv_freq = std::sync::Arc::new(attention::rope_inv_freq(head_dim, rope_base));
4839        let pool = Pool::from_env();
4840        if let Some(p) = &pool {
4841            tracing::info!("worker pool: {} threads", p.n_workers());
4842            // Keep the workers on the socket that holds the weights.
4843            if let Some(model) = weights
4844                .lm_head
4845                .model_arc()
4846                .or_else(|| weights.embed_tokens.model_arc())
4847            {
4848                let regions: Vec<&[u8]> =
4849                    model.tensors.iter().map(|t| model.entry_bytes(t)).collect();
4850                p.bind_numa(&regions);
4851            }
4852        }
4853        Self {
4854            gpu_plan: None,
4855            tokenizer: std::sync::Arc::new(tokenizer),
4856            kv_cache: KvCache::new(num_layers, num_kv_heads, head_dim, max_seq_len),
4857            sampler_config,
4858            weights,
4859            hidden_size,
4860            intermediate_size,
4861            num_heads,
4862            num_kv_heads,
4863            head_dim,
4864            num_layers,
4865            physical_layers,
4866            loop_final_norm,
4867            layer_map: None,
4868            dash: None,
4869            dash_batch_on: true,
4870            mhc: None,
4871            mhc_r: Vec::new(),
4872            mrope_sections: None,
4873            prompt_mrope: None,
4874            vocab_size,
4875            rms_eps,
4876            rope_base,
4877            norm_style,
4878            rotary_dim: head_dim,
4879            attention_heads_per_layer: None,
4880            kv_heads_per_layer: None,
4881            v_head_dim: None,
4882            layer_dump: std::env::var_os("CMF_LAYER_DUMP")
4883                .filter(|v| !v.is_empty())
4884                .map(std::path::PathBuf::from),
4885            graph_declines: std::cell::RefCell::new(Vec::new()),
4886            mimo_moe: Default::default(),
4887            minicpm_tail: Default::default(),
4888            vmf_cfg: None,
4889            gdn_cfg: None,
4890            kda_cfg: None,
4891            g3n: None,
4892            g4e: None,
4893            dsv4: None,
4894            dory: None,
4895            dsv41: None,
4896            dsv41_vision: None,
4897            dsv41_prefill: None,
4898            qwen4_exp: None,
4899            glm5_next: None,
4900            hy4: None,
4901            maxwell: None,
4902            inkling: None,
4903            clover: None,
4904            clover_stats: clover::CloverStats::default(),
4905            clover_pen: Default::default(),
4906            dsv4_mtp: Vec::new(),
4907            dspark: None,
4908            dspark_pending: Vec::new(),
4909            dspark_hist: Vec::new(),
4910            dspark_real: Vec::new(),
4911            dspark_trunk_picks: Vec::new(),
4912            dspark_exp: Vec::new(),
4913            dspark_draft_ns: 0,
4914            m3_winners: Vec::new(),
4915            m3_counts: Vec::new(),
4916            m3_n_exp: 0,
4917            m3_tokens: 0,
4918            m3_prewarmed: false,
4919            logit_multiplier: None,
4920            cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
4921            graph_failed: std::sync::atomic::AtomicBool::new(false),
4922            graph_moe_banks: std::sync::Mutex::new(std::collections::HashMap::new()),
4923            kv_history: Vec::new(),
4924            kv_history_device: false,
4925            short_conv_cfg: None,
4926            mtp: None,
4927            mimo_mtp: None,
4928            verify_exact_moe: false,
4929            speculative: std::env::var("CMF_MTP").map(|v| v != "0").unwrap_or(true),
4930            ignore_eos: false,
4931            draft_full_streak: 0,
4932            spec_k_adapt: None,
4933            spec_acc_ewma: 0.7,
4934            spec_hold: SPEC_HOLD_PRIOR,
4935            spec_wall: [0.0; 7],
4936            spec_wall_n: [0; 7],
4937            spec_k_dwell: 0,
4938            spec_plain_ms: (0.0, 0),
4939            dflash_hold: DFLASH_HOLD_PRIOR,
4940            dflash_last: false,
4941            dflash_wait: 0,
4942            dflash_back: DFLASH_WAIT,
4943            dflash_turn: 0,
4944            dflash_turn_sum: (0.0, 0.0),
4945            dflash_lean: 0.0,
4946            dflash_k_adapt: None,
4947            dflash_acc_ewma: 0.6,
4948            spec_lookup_gain: 2.0,
4949            spec_lookup_wide: false,
4950            spec_lookup_rest: 0,
4951            rng,
4952            sampler_scratch: SamplerScratch::default(),
4953            spec_forced: None,
4954            spec_q: Vec::new(),
4955            spec_p: Vec::new(),
4956            spec_res: Vec::new(),
4957            spec_qs: Vec::new(),
4958            spec_ps: Vec::new(),
4959            spec_ress: Vec::new(),
4960            mtp_graph_mode: None,
4961            dflash: None,
4962            dflash_rows: None,
4963            dflash_taps: std::sync::Mutex::new(Vec::new()),
4964            dflash_solo: false,
4965            dflash_tap_from: 0,
4966            #[cfg(target_os = "macos")]
4967            metal_verify: None,
4968            inv_freq,
4969            ws: ForwardScratch::new(hidden_size),
4970            pool,
4971            model: None,
4972            dyn_force_f32: false,
4973            dyn_skill_layers: Vec::new(),
4974            dyn_active: None,
4975            dyn_blend_loaded: false,
4976            dyn_phi_layer: None,
4977            dyn_phi_ema: Vec::new(),
4978            dyn_phi_seen: 0,
4979            dyn_phi_tap: std::sync::Mutex::new(None),
4980            dyn_router: None,
4981            o1_cfg: None,
4982            o1_turbo: None,
4983            mtp_pos_base: 0,
4984            o1_prefix_tail: Vec::new(),
4985            gdn_snap: None,
4986            mtp_warm_base: None,
4987            o1_epoch: 0,
4988            o1_flags: Vec::new(),
4989            trace: false,
4990            calib_temp: 1.0,
4991            confidence_on: true,
4992            embed_multiplier: 1.0,
4993            attn_scale: 1.0 / (head_dim as f32).sqrt(),
4994            swa: None,
4995            swa_trim: None,
4996            uniform_full_layers: false,
4997            swa_trim_anchor: usize::MAX,
4998            chunk_min_rows: 32,
4999            o1_chunk_prefix: false,
5000            dense_batch_declined: std::sync::atomic::AtomicBool::new(false),
5001            sliding_layers: None,
5002            no_rope_layers: None,
5003            value_blend: None,
5004            vres_e0: Vec::new(),
5005            vres_in: Vec::new(),
5006            anchor_core: None,
5007            bounded_rope: None,
5008            kv_prefix: KvPrefix::default(),
5009            last_prefill_tokens: 0,
5010            inv_freq_local: None,
5011            rotary_dim_local: None,
5012            rope_scale: 1.0,
5013            rope_scale_local: 1.0,
5014            global_attn: None,
5015            inv_freq_global: None,
5016            attn_v_norm: false,
5017            qk_norm_after_rope: false,
5018            proj_gate_sigmoid: false,
5019            final_softcap: None,
5020            head_clusters: None,
5021            attn_softcap: 0.0,
5022            graph_want_logits: false,
5023            graph_head_required: false,
5024            graph_logits: None,
5025            embryo_graph: None,
5026            embryo_wide_refused: false,
5027            graph_refused: std::sync::atomic::AtomicBool::new(false),
5028            graph_kv_id: {
5029                static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
5030                NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
5031            },
5032            #[cfg(test)]
5033            nll_test_fail_at: None,
5034            #[cfg(test)]
5035            nll_test_force_serial: false,
5036        }
5037    }
5038
5039    /// Enable/disable per-layer O(1) Nyström attention. Only Full
5040    /// layers are eligible (a linear layer keeps its own operator).
5041    /// Applies to generation (`generate*`/`forward_ids`): the prompt
5042    /// pass stays exact, then the state seals after prefill or at the
5043    /// deferred skeleton-safe boundary for short prompts; decode runs on
5044    /// the O(1) state. Teacher-forced scoring (`ppl_ids`) intentionally
5045    /// stays exact.
5046    pub fn set_o1(&mut self, cfg: Option<crate::nystrom::O1Cfg>) {
5047        if let Err(e) = self.try_set_o1(cfg) {
5048            tracing::error!("{e}");
5049        }
5050    }
5051
5052    /// True when the file carries a native bounded anchor
5053    /// (`arch.anchor_core`): its state is a fixed record the header
5054    /// fixes, and the post-hoc O(1) override is meaningless on it.
5055    pub fn bounded_native(&self) -> bool {
5056        self.anchor_core.is_some()
5057    }
5058
5059    /// Bytes the resident device graph holds for this pipeline's sequence:
5060    /// `(recurrent state, anchor KV/ring)`; None on the host path.
5061    pub fn device_state_bytes(&self) -> Option<(u64, u64)> {
5062        if self.dory.is_some() {
5063            return crate::gpu::dory_kv_bytes(self.graph_kv_id).map(|b| (0, b));
5064        }
5065        crate::gpu::embryo_device_state_bytes(self.graph_kv_id)
5066    }
5067
5068    /// Why an O(1) override is refused on this pipeline, if it is.
5069    pub fn o1_refusal(&self) -> Option<String> {
5070        self.anchor_core.as_ref().map(|ac| {
5071            format!(
5072                "--o1 / CMF_O1 refused: the anchor is native bounded \
5073                 (anchor_core kind={} window={} sink={}); the file's operator \
5074                 is executed as-is and no post-hoc Nyström overlay applies",
5075                ac.kind, ac.window, ac.sink
5076            )
5077        })
5078    }
5079
5080    /// `set_o1` that reports the refusal instead of logging it.
5081    pub fn try_set_o1(&mut self, cfg: Option<crate::nystrom::O1Cfg>) -> Result<(), String> {
5082        // Dory runs its own stack: the far field goes on its full layers.
5083        if let Some(b) = &mut self.dory {
5084            b.0.o1 = cfg.map(|c| crate::dory::DoryO1 { m: c.m, w: c.w, sink: c.sink, seal: (c.w + c.sink + 16).max(8192) });
5085            return Ok(());
5086        }
5087        if let Some(c) = &cfg {
5088            if let Some(why) = self.o1_refusal() {
5089                self.o1_flags = Vec::new();
5090                self.o1_cfg = None;
5091                return Err(why);
5092            }
5093            if crate::nystrom::o1_deferred_boundary(c.w, c.sink).is_none() {
5094                self.o1_flags.clear();
5095                self.o1_cfg = None;
5096                return Err(format!(
5097                    "o1 disabled: w + sink + slack + 1 overflows usize (w={}, sink={})",
5098                    c.w, c.sink
5099                ));
5100            }
5101        }
5102        self.o1_flags = match &cfg {
5103            Some(c) => {
5104                let mut flags = c.layer_flags(self.num_layers);
5105                for (li, f) in flags.iter_mut().enumerate() {
5106                    // The Nyström state replaces a full-context plain
5107                    // softmax: a sliding window or a learned sink is not
5108                    // something it can represent, and a V narrower than
5109                    // the head is not what its streaming state stores.
5110                    // Those layers keep exact cache attention.
5111                    if *f
5112                        && (!matches!(
5113                            self.weights.layers[self.phys_layer(li)].attn,
5114                            AttnKind::Full { .. }
5115                        ) || self.layer_window(li).is_some()
5116                            || self.kv_cache.layers[li].sinks.is_some()
5117                            || self.layer_v_dim(li) != self.layer_geom(li).1)
5118                    {
5119                        *f = false;
5120                    }
5121                }
5122                flags
5123            }
5124            None => Vec::new(),
5125        };
5126        if let Some(c) = &cfg {
5127            let n = self.o1_flags.iter().filter(|&&f| f).count();
5128            tracing::info!(
5129                "o1 nystrom attention: {n}/{} layer(s), m={} w={} sink={} rect={:?}",
5130                self.num_layers,
5131                c.m,
5132                c.w,
5133                c.sink,
5134                c.rect
5135            );
5136        }
5137        self.o1_cfg = cfg;
5138        Ok(())
5139    }
5140
5141    /// Install the file's bounded anchor: one fixed-size ring per
5142    /// `AttnKind::Bounded` layer (from the header, not per prompt) and
5143    /// the shared relative-rotation table. Must run after the RoPE setup
5144    /// (`set_rotary`, YaRN) so the table is built from the final
5145    /// `inv_freq`.
5146    pub fn install_bounded(&mut self, cfg: &cortiq_core::AnchorCoreConfig) -> Result<(), String> {
5147        if !cortiq_core::AnchorCoreConfig::KINDS.contains(&cfg.kind.as_str()) {
5148            return Err(format!(
5149                "anchor_core kind '{}' is not executable by this runtime",
5150                cfg.kind
5151            ));
5152        }
5153        if cfg.window == 0 {
5154            return Err("anchor_core.window must be >= 1".into());
5155        }
5156        let mut n = 0usize;
5157        for li in 0..self.num_layers {
5158            let pl = self.phys_layer(li);
5159            if let AttnKind::Bounded(w) = &self.weights.layers[pl].attn {
5160                if w.window != cfg.window
5161                    || w.sink != cfg.sink
5162                    || w.group_windows != cfg.group_windows
5163                {
5164                    return Err(format!(
5165                        "layer {li}: bounded weights (window {} sink {} groups {:?}) disagree \
5166                         with anchor_core (window {} sink {} groups {:?})",
5167                        w.window, w.sink, w.group_windows, cfg.window, cfg.sink, cfg.group_windows
5168                    ));
5169                }
5170                self.kv_cache.layers[li].install_bounded(cfg.window);
5171                n += 1;
5172            }
5173        }
5174        if n == 0 {
5175            return Err("anchor_core is present but no layer executes it".into());
5176        }
5177        let rope = crate::bounded::BoundedRope::new(cfg.window, &self.inv_freq, self.rope_scale);
5178        self.bounded_rope = Some(std::sync::Arc::new(rope));
5179        self.anchor_core = Some(cfg.clone());
5180        self.embryo_graph = None;
5181        tracing::info!(
5182            "bounded anchor {}: {n} layer(s), window {} sink {} — {} B of ring per layer",
5183            cfg.kind,
5184            cfg.window,
5185            cfg.sink,
5186            self.kv_cache
5187                .layers
5188                .iter()
5189                .map(|l| l.bounded_state_bytes())
5190                .max()
5191                .unwrap_or(0)
5192        );
5193        Ok(())
5194    }
5195
5196    /// Tag every layer's cache with its wire record kind and the model's
5197    /// operator identity (hash64 of `linear_core_identity` JSON) so the
5198    /// versioned state wire refuses a peer holding another operator.
5199    pub fn install_wire_identity(&mut self, identity: u64) {
5200        for li in 0..self.kv_cache.layers.len() {
5201            let pl = self.phys_layer(li);
5202            let kind = match self.weights.layers.get(pl).map(|l| &l.attn) {
5203                Some(AttnKind::Bounded(_)) => crate::kv_cache::WireKind::Bounded,
5204                Some(AttnKind::Linear(_))
5205                | Some(AttnKind::LinearGdn(_))
5206                | Some(AttnKind::ShortConv(_))
5207                | Some(AttnKind::Kda(_)) => crate::kv_cache::WireKind::Linear,
5208                _ => crate::kv_cache::WireKind::Full,
5209            };
5210            let l = &mut self.kv_cache.layers[li];
5211            l.wire_kind = kind;
5212            l.wire_identity = identity;
5213            // A per-layer geometry (`set_attn_geometry`, Gemma's global
5214            // heads) rebuilds a layer cache with index 0: re-tag it.
5215            l.wire_layer = li as u32;
5216        }
5217    }
5218
5219    /// Forget the reuse keys (legacy `kv_history` and the bounded prefix).
5220    pub fn clear_history(&mut self) {
5221        self.kv_history.clear();
5222        self.kv_history_device = false;
5223        self.kv_prefix.clear();
5224    }
5225
5226    /// Did THIS pipeline's token graph refuse for a structural reason?
5227    /// (Per pipeline: another lane's refusal, or a new pipeline of the
5228    /// same model, never changes it.)
5229    pub fn graph_refused(&self) -> bool {
5230        self.graph_refused
5231            .load(std::sync::atomic::Ordering::Relaxed)
5232    }
5233
5234    /// Remember a structural refusal of this pipeline's token graph.
5235    pub fn mark_graph_refused(&self) {
5236        if !self
5237            .graph_refused
5238            .swap(true, std::sync::atomic::Ordering::Relaxed)
5239        {
5240            tracing::info!(
5241                "token graph: unsupported for this pipeline (seq {}) — not retrying",
5242                self.graph_kv_id
5243            );
5244        }
5245    }
5246
5247    /// Position the resident Embryo graph holds for this pipeline's
5248    /// sequence (`Some(next position)`), `None` when the device holds no
5249    /// image of it (host-owned sequence, or none started).
5250    pub fn device_sequence_position(&self) -> Option<usize> {
5251        crate::gpu::embryo_device_next_position(self.graph_kv_id)
5252    }
5253
5254    /// Is the sequence this pipeline's reuse key describes owned by the
5255    /// device path it would take now? A prefix recorded on the resident
5256    /// graph continues only there (at exactly `n`), a host prefix only on
5257    /// the host; any mismatch means the next turn re-prefills from zero.
5258    fn prefix_owner_matches(&self, n: usize, recorded_on_device: bool) -> bool {
5259        let dev = self.device_sequence_position();
5260        if recorded_on_device {
5261            dev == Some(n) && self.embryo_resident_wanted()
5262        } else {
5263            dev.is_none()
5264        }
5265    }
5266
5267    /// The weights under the sequence changed (a real skill switch): every
5268    /// cached state was computed by other weights. Clear the host KV /
5269    /// ring / recurrent state AND the reuse keys — a surviving `kv_prefix`
5270    /// would let the next turn "extend" a prefix the new weights never
5271    /// saw — drop the packed resident graph (it holds the old FFN
5272    /// tensors; the next build packs the live ones under a fresh id) and
5273    /// reset its device sequence.
5274    pub(crate) fn invalidate_for_weight_change(&mut self) {
5275        self.clear_sequence_state();
5276        self.embryo_graph = None;
5277    }
5278
5279    /// The CUDA hybrid arm keeps a chat snapshot (GDN states copied on the
5280    /// card): a GDN stack with exact attention, no far field, reuse on.
5281    fn gdn_snap_ok(&self) -> bool {
5282        crate::gpu::cuda_active()
5283            && self.gdn_cfg.is_some()
5284            && self.o1_cfg.is_none()
5285            && self.dory.is_none()
5286            && self.dsv41.is_none()
5287            && self.qwen4_exp.is_none()
5288            && self.glm5_next.is_none()
5289            && self.hy4.is_none()
5290            && self.maxwell.is_none()
5291            && self.inkling.is_none()
5292            && std::env::var("CMF_KV_REUSE").as_deref() != Ok("0")
5293    }
5294
5295    /// Where this prompt's snapshot goes: its last `<|im_start|>`, the
5296    /// assistant header the next turn renders differently (a previous
5297    /// answer loses its think block there), past `from` and before the
5298    /// prompt's last row.
5299    fn gdn_snap_target(&self, input_ids: &[u32], from: usize) -> Option<usize> {
5300        if !self.gdn_snap_ok() {
5301            return None;
5302        }
5303        let id = self.tokenizer.token_to_id("<|im_start|>")?;
5304        let s = input_ids.iter().rposition(|&t| t == id)?;
5305        (s > from && s + 1 < input_ids.len()).then_some(s)
5306    }
5307
5308    /// Positions a turn takes back from the chat snapshot (0: none). The
5309    /// card's states go back to it here, all layers or none.
5310    fn gdn_snap_reuse(&mut self, input_ids: &[u32]) -> usize {
5311        let n = match &self.gdn_snap {
5312            Some(s) if !s.is_empty() && s.len() < input_ids.len() && input_ids[..s.len()] == s[..] => s.len(),
5313            _ => return 0,
5314        };
5315        if !self.gdn_snap_ok() || !crate::gpu::gdn_snapshot_restore(self.graph_kv_id, n) {
5316            self.gdn_snap = None;
5317            return 0;
5318        }
5319        n
5320    }
5321
5322    /// Prompt positions the cache already holds when `input_ids`
5323    /// strictly EXTENDS the consumed prefix (0 otherwise). Bounded-native
5324    /// models answer from the fixed-size `kv_prefix` record; everything
5325    /// else from the legacy `kv_history` vector (which the network split
5326    /// also reads and writes).
5327    fn cached_prefix_len(&self, input_ids: &[u32]) -> usize {
5328        let (n, on_device) = if self.bounded_native() {
5329            (
5330                self.kv_prefix.extension(input_ids),
5331                self.kv_prefix.on_device(),
5332            )
5333        } else {
5334            let h = &self.kv_history;
5335            if !h.is_empty() && h.len() < input_ids.len() && input_ids[..h.len()] == h[..] {
5336                (h.len(), self.kv_history_device)
5337            } else if !h.is_empty() && !self.kv_history_device {
5338                (self.rollback_prefix_len(input_ids), false)
5339            } else {
5340                (0, false)
5341            }
5342        };
5343        // The owner tag: the state the key describes must live where this
5344        // turn will continue it (R4) — else a fresh sequence.
5345        if n > 0 && !self.prefix_owner_matches(n, on_device) {
5346            tracing::warn!(
5347                "kv-reuse refused: the cached prefix ({n} positions) was built on the {} path, \
5348                 the device now holds {:?} — re-prefilling from zero",
5349                if on_device { "resident device" } else { "host" },
5350                self.device_sequence_position()
5351            );
5352            return 0;
5353        }
5354        n
5355    }
5356
5357    /// Positions a turn whose ids DIVERGE from the consumed prefix keeps:
5358    /// their longest common prefix, when every layer can drop its rows past
5359    /// it exactly — full attention whose f32 rows the host owns (no wgpu
5360    /// mirror ahead of the host, no recurrent, O(1) or bounded state) and
5361    /// every trimmed sliding tail still holding the window the query at the
5362    /// cut reads. A chat app re-renders the previous answer through the
5363    /// template (a thinking model's history drops its `<think>` block), so a
5364    /// conversation almost never extends token for token: extension-only
5365    /// reuse re-prefilled the whole history every turn. One id at least is
5366    /// left to prefill. `CMF_KV_ROLLBACK=0` keeps extension-only reuse.
5367    fn rollback_prefix_len(&self, input_ids: &[u32]) -> usize {
5368        if std::env::var("CMF_KV_ROLLBACK").as_deref() == Ok("0")
5369            || self.device_sequence_position().is_some()
5370        {
5371            return 0;
5372        }
5373        let h = &self.kv_history;
5374        let lcp = h.iter().zip(input_ids).take_while(|(a, b)| a == b).count();
5375        let n = lcp.min(input_ids.len().saturating_sub(1));
5376        // Stacks that keep their own layers (qwen4, DSV4) leave the generic
5377        // ones empty: nothing here can roll back, the prompt is read again.
5378        if n == 0
5379            || self.kv_cache.layers.len() < self.num_layers
5380            || self.weights.layers.len() < self.num_layers
5381        {
5382            return 0;
5383        }
5384        let kv_id = self.graph_kv_id;
5385        for li in 0..self.num_layers {
5386            let l = &self.kv_cache.layers[li];
5387            let tail_ok = l.base() == 0
5388                || self
5389                    .layer_window(li)
5390                    .is_some_and(|w| l.base() + w <= n + 1);
5391            if !matches!(self.weights.layers[self.phys_layer(li)].attn, AttnKind::Full { .. })
5392                || l.o1.is_some()
5393                || l.bounded.is_some()
5394                || !l.linear_state.is_empty()
5395                || l.mode != crate::kv_cache::KvMode::F32
5396                || l.pos_len() != h.len()
5397                || !tail_ok
5398                || crate::gpu::graph_kv_stored(kv_id, li).is_some()
5399                || crate::gpu::graph_state_resident(kv_id, li)
5400            {
5401                return 0;
5402            }
5403        }
5404        n
5405    }
5406
5407    /// Public view of the prefix-reuse decision for `input_ids` (positions
5408    /// the next `generate*` would take from the cache; 0 = fresh sequence).
5409    pub fn reusable_prefix_len(&self, input_ids: &[u32]) -> usize {
5410        self.cached_prefix_len(input_ids)
5411    }
5412
5413    /// Record the forwarded prefix as the next turn's reuse key. A
5414    /// bounded-native model extends the rolling record (`reused` = the
5415    /// positions this turn found cached); others keep the literal vector.
5416    /// Either way the key carries its OWNER: the resident device graph
5417    /// (it holds an image of this sequence) or the host.
5418    fn record_consumed_prefix(&mut self, consumed: &[u32], reused: usize) {
5419        let on_device = self.device_sequence_position().is_some();
5420        if self.bounded_native() {
5421            let keep = reused > 0 && reused == self.kv_prefix.len() && reused <= consumed.len();
5422            let prev_device = self.kv_prefix.on_device();
5423            self.kv_history.clear();
5424            self.kv_history_device = false;
5425            if keep && prev_device == on_device {
5426                self.kv_prefix.extend(&consumed[reused..]);
5427            } else {
5428                self.kv_prefix.set(consumed);
5429            }
5430            self.kv_prefix.set_on_device(on_device);
5431        } else {
5432            self.kv_history = consumed.to_vec();
5433            self.kv_history_device = on_device;
5434        }
5435    }
5436
5437    /// True when at least one layer runs the O(1) kernel.
5438    pub fn o1_active(&self) -> bool {
5439        self.o1_cfg.is_some() && self.o1_flags.iter().any(|&f| f)
5440    }
5441
5442    /// Whether generation's prompt ingest is routed through the whole-token
5443    /// graph.  The bench uses this to label the measured generation prefill
5444    /// honestly; keep the predicate in Pipeline so CLI labels cannot drift
5445    /// from the production route.
5446    /// Positions per batched-graph submit for the prompt: `CMF_BATCH_K`
5447    /// when set (0 = one position at a time through the token graph),
5448    /// otherwise 128 (32 for a MoE stack) on a discrete card whose prompt
5449    /// takes the graph route.
5450    /// The batched graph read a 2048-token prompt at 53 tok/s against 28.5
5451    /// one position at a time on an RTX PRO 4000 (Qwen3.8-27B q4tp: TTFT
5452    /// 39 s against 72), and its states are the speculative verify's,
5453    /// measured identical to the plain path. macOS keeps its own arm.
5454    /// 128, not 32: the q4tp prefill GEMM tiles 64 batch rows, so a
5455    /// 32-row chunk left half of every tile idle. Qwen3.8-27B q4tp on an
5456    /// RTX 3090, 1000-token prompt: 51 tok/s at 32, 82 at 64, 95 at 128,
5457    /// 97 at 256; greedy output byte-identical to the 32-row chunks
5458    /// (every GEMM row and the k-looped recurrences are per position).
5459    /// A dense sliding-window stack whose batched prefill attends with the
5460    /// query-tiled kernels (the Spark-X2.6 class on a discrete wgpu card).
5461    #[cfg(not(target_os = "macos"))]
5462    fn tiled_sliding_batch(&self) -> bool {
5463        (self.sliding_layers.is_some() || self.swa.is_some())
5464            && !self.weights.layers.iter().any(|lw| matches!(&lw.ffn, FfnKind::Moe(_)))
5465            && crate::gpu::batched_attend_tiled()
5466    }
5467
5468    pub fn generation_batch_k(&self) -> usize {
5469        if let Some(k) = std::env::var("CMF_BATCH_K")
5470            .ok()
5471            .and_then(|v| v.parse::<usize>().ok())
5472        {
5473            return k;
5474        }
5475        // Gemma-4 (`g4_batch_prefill`): 128-row chunks, the GEMM tile's
5476        // two 64-row halves full. The CUDA batch graph expands each weight
5477        // once a chunk: its own chunk (`CMF_CUDA_BATCH`, 1024) — Ripple-65B
5478        // q4tp on an A40, a 4096-token prompt, 141 tok/s at 128 rows, 422 at
5479        // 1024.
5480        if self.g4_batch_prefill() {
5481            #[cfg(not(target_os = "macos"))]
5482            if let Some(k) = crate::gpu::cuda_batch_rows() {
5483                return k;
5484            }
5485            return 128;
5486        }
5487        #[cfg(target_os = "macos")]
5488        if self.o1_active() && self.o1_on_graph() && crate::gpu::q1_force() && crate::gpu::enabled_here() {
5489            return if crate::gpu_metal::ane::wanted() { 512 } else { 128 };
5490        }
5491        // The sealed O(1) suffix of a bounded prompt (`CMF_O1_PREFILL`) on
5492        // the device route rides the batch graph, whose O(1) kernels take
5493        // the chunk in 64-row sub-chunks (`o1_batch`); 128 as the exact
5494        // prompt below. Without it the suffix went one position at a time.
5495        #[cfg(not(target_os = "macos"))]
5496        if self.o1_active()
5497            && self.o1_on_graph()
5498            && crate::gpu::enabled_here()
5499            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill)
5500        {
5501            if let Some(k) = crate::gpu::cuda_batch_rows() {
5502                return k;
5503            }
5504            return if self.tiled_sliding_batch() { 512 } else { 128 };
5505        }
5506        #[cfg(not(target_os = "macos"))]
5507        if self.graph_prefill_preferred() && !self.o1_active() {
5508            // The CUDA batch graph expands each weight once a chunk and
5509            // multiplies with cuBLAS: its own, larger chunk (`CMF_CUDA_BATCH`).
5510            if let Some(k) = crate::gpu::cuda_batch_rows() {
5511                return k;
5512            }
5513            // A dense sliding-window stack on the tiled whole-run attend:
5514            // 512 rows a submit (Spark-X2.6 q4tp on an RTX 2000 Ada, 4096
5515            // tokens: 288 tok/s at 128, 317 at 512, the same greedy text;
5516            // the tile holds 16 tokens, and a chunk is read against its K/V
5517            // once per sub-run of whole tiles).
5518            if self.tiled_sliding_batch() {
5519                return 512;
5520            }
5521            // 128 is measured on the dense hybrids; MoE stacks other than
5522            // the two expert codecs below keep the 32 their expert-grouped
5523            // prefill was measured at.
5524            let moe = self
5525                .weights
5526                .layers
5527                .iter()
5528                .any(|lw| matches!(&lw.ffn, FfnKind::Moe(_)));
5529            // The dense GDN hybrids (Qwen3.5 / 3.6 / 3.8) on the tiled
5530            // attend: 512 rows a submit, each weight unpacked to its f16
5531            // plane once a chunk. Qwen3.5-4B q4tp on an RTX A5000, prompt
5532            // tok/s at 4 000 / 16 000 / 32 000 tokens: 1223 / 1122 / 977
5533            // at 128 rows, 1669 / 1550 / - at 256, 1833 / 1897 / 1539 at 512.
5534            if !moe && self.graph_gdn_layer_count() > 0 && crate::gpu::batched_attend_tiled() {
5535                return 512;
5536            }
5537            // q8_2f experts (moe_q82's grouped prefill) read each expert
5538            // once per group of up to 16 of its entries, so the chunk that
5539            // fills those groups is the faster ingest: Mellum2.1 q8_2f on an
5540            // RTX 3090, 4000-token prompt, 503 tok/s at 64 rows, 542 at 128
5541            // (and 542 at 256).
5542            let q82 = crate::gpu::moe_q82_graph_on()
5543                && self.weights.layers.iter().any(|lw| {
5544                    matches!(&lw.ffn, FfnKind::Moe(m)
5545                        if m.experts.first().is_some_and(|e| e.gate_proj.mapped_q8_2f().is_some()))
5546                });
5547            // q4tp experts: the grouped GEMM reads every routed expert once
5548            // per chunk, and 32 rows (256 entries over 256 experts, about
5549            // one row each) re-read nearly the whole expert set every 32
5550            // tokens. Apex-35B q4tp on an A40, 4096-token prompt, MTP off:
5551            // 295 tok/s at 32 rows, 357 at 64, 385 at 128, 401 at 256,
5552            // 396 at 512.
5553            let q4tp_moe = self.weights.layers.iter().any(|lw| {
5554                matches!(&lw.ffn, FfnKind::Moe(m)
5555                    if m.experts.first().is_some_and(|e| e.gate_proj.mapped_q4tp().is_some()))
5556            });
5557            // q4_tiled experts on wgpu take the split layout (`moe_q4ts`),
5558            // whose grouped prefill reads each expert once a chunk as q4tp's
5559            // does: Kimi-Linear-48B on an RTX A5000, 4096-token prompt, 302
5560            // tok/s at 32 rows, 464-503 at 256.
5561            let q4ts_moe = crate::gpu::wgpu_active()
5562                && std::env::var("CMF_MOE_Q4TS").as_deref() != Ok("0")
5563                && self.weights.layers.iter().any(|lw| {
5564                    matches!(&lw.ffn, FfnKind::Moe(m)
5565                        if m.experts.first().is_some_and(|e| e.gate_proj.mapped_q4t().is_some()))
5566                });
5567            // A file past a discrete card on wgpu keeps banks in system
5568            // memory, and a chunk copies each of them to the card once
5569            // (`moe_cache::staging`): at 32 rows Ornith-122B q2tp-v2 within
5570            // 32 GB copied 43 banks every 32 tokens (512 in 30 s). q8_2f
5571            // banks have no system-memory arm.
5572            let banked = crate::gpu::wgpu_active()
5573                && crate::gpu::discrete()
5574                && self.model.as_ref().is_some_and(|m| m.primary_bytes().len() as u64 > crate::gpu::vram_budget());
5575            // banks streamed or staged from system memory: a chunk reads every
5576            // bank of the stack once, so the widest chunk the scratch takes
5577            // (GLM-5.3 on Vulkan streamed 108 GB of experts every 256 rows)
5578            if moe && banked && !q82 {
5579                return 512;
5580            }
5581            return if q82 {
5582                128
5583            } else if q4tp_moe || q4ts_moe || self.onevision2_prefill() {
5584                256
5585            } else if moe {
5586                32
5587            } else {
5588                128
5589            };
5590        }
5591        0
5592    }
5593
5594    pub fn generation_graph_prefill(&self) -> bool {
5595        let graph = self.graph_prefill_preferred();
5596        // On wgpu, an active MTP head now consumes the trunk's graph batches
5597        // and warms its own block from those returned rows.  The selected
5598        // generation measurement is therefore the batched path, even though
5599        // the underlying GDN model still satisfies the graph-prefill
5600        // predicate.  Keep the CLI label tied to the actual route.  Native
5601        // Metal has a separate prefill-batch arm and retains its historical
5602        // label here.
5603        // A batched prompt (`generation_batch_k` > 0) is the batched graph
5604        // for every model on the graph route, not only those with an MTP
5605        // head — the label follows the route.
5606        #[cfg(not(target_os = "macos"))]
5607        if graph && self.generation_batch_k() > 0 && std::env::var("CMF_MTP_CHAIN_PROBE").is_err() {
5608            return false;
5609        }
5610        graph
5611    }
5612
5613    /// Device-side O(1) mirrors currently uploaded for this pipeline's
5614    /// sequence.  The count/bytes are zero before seal or after a fresh
5615    /// reset; callers use this to distinguish logical host state from the
5616    /// GPU allocation that actually serves decode.
5617    pub fn o1_device_stats(&self) -> (usize, u64) {
5618        crate::gpu::o1_device_stats(self.graph_kv_id)
5619    }
5620
5621    /// Arm query collection on the o1 layers (fresh prompt pass).
5622    /// Reset the o1 layers to Collecting for a fresh sequence. Pub for the
5623    /// network split: each side runs the o1 lifecycle over ITS OWN layers
5624    /// (begin before prefill, seal at the prefill barrier).
5625    pub fn o1_begin(&mut self) {
5626        self.o1_begin_with_prefix(None);
5627    }
5628
5629    /// Arm collection and optionally request a positive calibration prefix.
5630    /// The effective barrier is always at least the skeleton-safe floor, so
5631    /// a short requested prefix cannot create an exact-only runtime state.
5632    pub fn o1_begin_with_prefix(&mut self, requested_prefix: Option<usize>) {
5633        if let Some(c) = &self.o1_cfg {
5634            let (m, w, sink, rect) = (c.m, c.w, c.sink, c.rect);
5635            let boundary = requested_prefix.map(|p| {
5636                p.max(
5637                    crate::nystrom::o1_deferred_boundary(w, sink)
5638                        .expect("o1 config boundary validated in set_o1"),
5639                )
5640            });
5641            // Exact rows are chosen across every far-field layer at the boundary:
5642            // a layer that reached it first must not seal without them.
5643            let await_keep = boundary.is_some() && self.o1_exact_cfg().is_some();
5644            for (li, &f) in self.o1_flags.iter().enumerate() {
5645                if f {
5646                    let cache = &mut self.kv_cache.layers[li];
5647                    cache.o1_begin_with_boundary(m, w, sink, rect, boundary);
5648                    cache.o1_await_keep = await_keep;
5649                }
5650            }
5651        }
5652    }
5653
5654    /// Effective deferred boundary for a positive prefix request.
5655    fn o1_effective_boundary(&self, requested_prefix: usize) -> Option<usize> {
5656        self.o1_cfg.as_ref().and_then(|c| {
5657            crate::nystrom::o1_deferred_boundary(c.w, c.sink)
5658                .map(|floor| requested_prefix.max(floor))
5659        })
5660    }
5661
5662    fn o1_note_transition(&mut self) {
5663        // Drain every layer's one-shot bit before publishing one pipeline
5664        // epoch. `any()` would short-circuit on the first layer and leak the
5665        // remaining bits into later forwards, causing one epoch per layer.
5666        let mut transitioned = false;
5667        for (li, &flagged) in self.o1_flags.iter().enumerate() {
5668            if flagged {
5669                transitioned |= self.kv_cache.layers[li].take_o1_transition();
5670            }
5671        }
5672        if transitioned {
5673            self.o1_epoch = self.o1_epoch.wrapping_add(1);
5674        }
5675    }
5676
5677    fn o1_pending(&self) -> bool {
5678        self.o1_flags.iter().enumerate().any(|(li, &f)| {
5679            f && self.kv_cache.layers[li].seq_len > 0
5680                && self.kv_cache.layers[li].o1_pending_boundary().is_some()
5681        })
5682    }
5683
5684    fn o1_fail(&mut self, err: String) {
5685        tracing::error!("o1 deferred seal failed; terminating sequence: {err}");
5686        self.clear_sequence_state();
5687        self.graph_failed
5688            .store(true, std::sync::atomic::Ordering::Relaxed);
5689        self.cancel
5690            .store(true, std::sync::atomic::Ordering::Relaxed);
5691    }
5692
5693    /// Seal participating layers while retaining the exact state when the
5694    /// prompt is below the deferred boundary. A split worker may have
5695    /// collecting layers outside its owned span; zero-depth layers remain
5696    /// armed and are intentionally skipped until their peer runs them.
5697    pub fn o1_seal_checked(&mut self) -> Result<bool, String> {
5698        if self.o1_cfg.is_none() {
5699            return Ok(false);
5700        }
5701        self.o1_choose_exact_rows();
5702        let (t_seal, mut sealed_now, epoch) = (std::time::Instant::now(), 0usize, self.o1_epoch);
5703        let mut todo: Vec<(usize, usize)> = Vec::new();
5704        for li in 0..self.num_layers {
5705            if !self.o1_flags.get(li).copied().unwrap_or(false) {
5706                continue;
5707            }
5708            if let Some(err) = self.kv_cache.layers[li].take_o1_error() {
5709                return Err(err);
5710            }
5711            if self.kv_cache.layers[li].seq_len == 0 {
5712                continue;
5713            }
5714            todo.push((li, self.layer_num_heads(li)));
5715        }
5716        let participating = !todo.is_empty();
5717        // A layer's seal depends on that layer's rows alone, and its groups
5718        // already seal on their own threads: a few layers go at a time, as
5719        // many as the cores carry (`CMF_O1_SEAL_PAR=N` sets the number). Each
5720        // holds its queries per group while it seals, so not all at once —
5721        // and one after another on a Mac, where that memory is the model's
5722        // too.
5723        let par = std::env::var("CMF_O1_SEAL_PAR")
5724            .ok()
5725            .and_then(|v| v.parse::<usize>().ok())
5726            .unwrap_or_else(|| {
5727                if cfg!(target_os = "macos") {
5728                    return 1;
5729                }
5730                let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
5731                let groups = todo.first().map_or(1, |&(li, _)| self.kv_cache.layers[li].num_kv_heads.max(1));
5732                cores.div_ceil(groups).clamp(1, 3)
5733            })
5734            .max(1);
5735        let mut slots: Vec<Option<&mut crate::kv_cache::LayerKvCache>> = self.kv_cache.layers.iter_mut().map(Some).collect();
5736        let mut jobs: Vec<(&mut crate::kv_cache::LayerKvCache, usize)> =
5737            todo.iter().filter_map(|&(li, nh)| slots[li].take().map(|c| (c, nh))).collect();
5738        for run in jobs.chunks_mut(par) {
5739            let done: Vec<Result<bool, String>> = if run.len() == 1 {
5740                let (c, nh) = &mut run[0];
5741                let was = c.o1_sealed();
5742                vec![c.o1_seal_checked(*nh).map(|ok| ok && !was)]
5743            } else {
5744                std::thread::scope(|s| {
5745                    let hs: Vec<_> = run
5746                        .iter_mut()
5747                        .map(|(c, nh)| {
5748                            let nh = *nh;
5749                            s.spawn(move || {
5750                                let was = c.o1_sealed();
5751                                c.o1_seal_checked(nh).map(|ok| ok && !was)
5752                            })
5753                        })
5754                        .collect();
5755                    hs.into_iter()
5756                        .map(|h| h.join().unwrap_or_else(|_| Err("o1 seal: a layer's thread panicked".into())))
5757                        .collect()
5758                })
5759            };
5760            for r in done {
5761                sealed_now += r? as usize;
5762            }
5763        }
5764        drop(jobs);
5765        drop(slots);
5766        self.o1_note_transition();
5767        if self.o1_epoch != epoch && sealed_now > 0 {
5768            tracing::info!("o1: {sealed_now} layer(s) sealed in {:.2} s", t_seal.elapsed().as_secs_f64());
5769        }
5770        for li in 0..self.num_layers {
5771            if self.o1_flags.get(li).copied().unwrap_or(false) {
5772                if let Some(err) = self.kv_cache.layers[li].take_o1_error() {
5773                    return Err(err);
5774                }
5775            }
5776        }
5777        Ok(participating
5778            && (0..self.num_layers).all(|li| {
5779                !self.o1_flags.get(li).copied().unwrap_or(false)
5780                    || self.kv_cache.layers[li].seq_len == 0
5781                    || self.kv_cache.layers[li].o1_sealed()
5782            }))
5783    }
5784
5785    /// A sealed chunk's rows join the archive.
5786    fn o1_archive_chunk(&self, a: &mut O1Archive, pos: usize, bk: usize, entries: Option<usize>) -> Result<(), String> {
5787        let got = match entries {
5788            Some(n) => crate::gpu::o1_acap_take_first(n),
5789            None => crate::gpu::o1_acap_take(),
5790        }
5791        .ok_or("O(1) archive: readback failed")?;
5792        let qrow = a.nh * a.hd;
5793        let stride = a.stride;
5794        // a backend may hand back the kept query rows alone (CUDA)
5795        let kept = (pos..pos + bk).filter(|p| p % stride == 0).count();
5796        for (gl, q, k, v) in got {
5797            let Some(l) = a.layers.iter_mut().find(|l| l.li == gl) else { continue };
5798            l.k.push(&k)?;
5799            l.v.push(&v)?;
5800            if q.len() == kept * qrow && kept != bk {
5801                l.q.push(&q)?;
5802                continue;
5803            }
5804            if q.len() != bk * qrow {
5805                return Err(format!("O(1) archive: layer {gl} handed back {} query values", q.len()));
5806            }
5807            for p in pos..pos + bk {
5808                if p % stride == 0 {
5809                    l.q.push(&q[(p - pos) * qrow..(p - pos + 1) * qrow])?;
5810                }
5811            }
5812        }
5813        a.rows = pos + bk;
5814        Ok(())
5815    }
5816
5817    /// The far field built anew over all the rows read so far, the chosen ones out of it.
5818    /// One layer at a time, so RAM holds one layer's rows.
5819    fn o1_seal_archive(&mut self, a: O1Archive) -> Result<bool, String> {
5820        let t0 = std::time::Instant::now();
5821        let (rows, stride, nk, hd) = (a.rows, a.stride, a.nk, a.hd);
5822        let mut layers = Vec::with_capacity(a.layers.len());
5823        for l in a.layers {
5824            layers.push((l.li, l.k.freeze()?, l.v.freeze()?, l.q.freeze()?));
5825        }
5826        let keep = match (self.o1_exact_cfg().cloned(), self.o1_cfg.clone()) {
5827            (Some(x), Some(c)) => {
5828                let views: Vec<crate::dory::FlatRows> = layers.iter().map(|l| crate::dory::FlatRows { k: l.1.as_slice(), v: l.2.as_slice(), nk, hd }).collect();
5829                let refs: Vec<&dyn crate::dory::LayerRows> = views.iter().map(|v| v as &dyn crate::dory::LayerRows).collect();
5830                crate::dory::pick_exact_rows(&x, &refs, rows, nk, hd, c.m, c.sink, rows.saturating_sub(c.w))
5831            }
5832            _ => Vec::new(),
5833        };
5834        let t_pick = t0.elapsed().as_secs_f64();
5835        let mut all = !layers.is_empty();
5836        let prof = std::env::var("CMF_PREFILL_PROF").is_ok();
5837        let t_layers = std::time::Instant::now();
5838        // a few layers at a time (`CMF_O1_SEAL_PAR`), each on its own thread: a
5839        // layer's rows into its cache, then its seal (its groups on threads of
5840        // their own); RAM holds those layers' rows twice meanwhile
5841        let par = std::env::var("CMF_O1_SEAL_PAR")
5842            .ok()
5843            .and_then(|v| v.parse::<usize>().ok())
5844            .unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |p| p.get()).div_ceil(8).clamp(1, 4));
5845        let heads: Vec<usize> = (0..self.kv_cache.layers.len()).map(|li| self.layer_num_heads(li)).collect();
5846        let mut by_li: Vec<Option<_>> = (0..self.kv_cache.layers.len()).map(|_| None).collect();
5847        for (li, k, v, q) in layers {
5848            if li < by_li.len() {
5849                by_li[li] = Some((k, v, q));
5850            }
5851        }
5852        let mut jobs: Vec<(usize, &mut crate::kv_cache::LayerKvCache, _)> = Vec::new();
5853        for (li, cache) in self.kv_cache.layers.iter_mut().enumerate() {
5854            if let Some(d) = by_li[li].take() {
5855                jobs.push((li, cache, d));
5856            }
5857        }
5858        let keep_ref = &keep;
5859        let heads = &heads;
5860        let results: Vec<Result<bool, String>> = std::thread::scope(|sc| {
5861            let mut out = Vec::new();
5862            let mut jobs = jobs.into_iter();
5863            loop {
5864                let wave: Vec<_> = jobs.by_ref().take(par.max(1)).collect();
5865                if wave.is_empty() {
5866                    break;
5867                }
5868                let hs: Vec<_> = wave
5869                    .into_iter()
5870                    .map(|(li, cache, (k, v, q))| {
5871                        sc.spawn(move || -> Result<bool, String> {
5872                            if !cache.o1_recollect(k.as_slice(), v.as_slice(), q.as_slice().to_vec(), stride, rows) {
5873                                return Err(format!("O(1) archive: layer {li} is not sealed"));
5874                            }
5875                            drop((k, v, q));
5876                            cache.o1_keep = keep_ref.clone();
5877                            cache.o1_seal_checked(heads[li])
5878                        })
5879                    })
5880                    .collect();
5881                for h in hs {
5882                    out.push(h.join().unwrap_or_else(|_| Err("O(1) archive: a layer's seal panicked".into())));
5883                }
5884            }
5885            out
5886        });
5887        for r in results {
5888            all &= r?;
5889        }
5890        if prof {
5891            eprintln!("o1 archive seal: {} layers {par} at a time in {:.2} s", by_li.len(), t_layers.elapsed().as_secs_f64());
5892        }
5893        self.o1_note_transition();
5894        tracing::info!(
5895            "o1: far field rebuilt over {rows} rows, {} kept exact, chosen in {t_pick:.2} s, {:.2} s in all",
5896            keep.len(),
5897            t0.elapsed().as_secs_f64()
5898        );
5899        Ok(all)
5900    }
5901
5902    /// A sealed prompt chunk on the device: wgpu's batch graph, or Metal's rows graph.
5903    fn o1_prompt_chunk(&mut self, hiddens: &mut Vec<f32>, positions: &[usize], bk: usize) -> crate::gpu::BatchGraphOutcome {
5904        #[cfg(target_os = "macos")]
5905        if crate::gpu::q1_force() && self.o1_active() {
5906            return match self.prefill_hiddens_metal(hiddens.clone(), positions[0], None) {
5907                MetalPrefillOutcome::Completed(h) => {
5908                    *hiddens = h;
5909                    crate::gpu::BatchGraphOutcome::Completed
5910                }
5911                MetalPrefillOutcome::Declined => crate::gpu::BatchGraphOutcome::Declined,
5912                MetalPrefillOutcome::Failed => crate::gpu::BatchGraphOutcome::Failed,
5913            };
5914        }
5915        self.try_batch_graph_wgpu(hiddens, positions, bk, None)
5916    }
5917
5918    /// `o1_prefix_on_graph` on Metal: the prompt's exact part on the rows graph, which leaves its
5919    /// rows in the host cache and the mirror. Queries come from the graph, one row in `QT_STRIDE`.
5920    #[cfg(target_os = "macos")]
5921    fn o1_prefix_on_metal(
5922        &mut self,
5923        ids: &[u32],
5924        chunk: usize,
5925        mut arch: Option<&mut O1Archive>,
5926    ) -> Result<Option<Vec<f32>>, String> {
5927        const QT_STRIDE: usize = 8;
5928        let o1_layers: Vec<usize> = (0..self.num_layers)
5929            .filter(|&li| self.o1_flags.get(li).copied().unwrap_or(false))
5930            .collect();
5931        let Some(&first) = o1_layers.first() else {
5932            return Ok(None);
5933        };
5934        let (nkv, hd) = {
5935            let c = &self.kv_cache.layers[first];
5936            (c.num_kv_heads, c.head_dim)
5937        };
5938        let nh = self.num_heads;
5939        if chunk == 0
5940            || o1_layers.iter().any(|&li| {
5941                let c = &self.kv_cache.layers[li];
5942                self.layer_num_heads(li) != nh
5943                    || (c.num_kv_heads, c.head_dim) != (nkv, hd)
5944                    || c.seq_len != 0
5945                    || c.o1_pending_boundary().is_none()
5946            })
5947        {
5948            return Ok(None);
5949        }
5950        let hs = self.hidden_size;
5951        let n = ids.len();
5952        let mut last = vec![0f32; hs];
5953        let qrow = nh * hd;
5954        let mut qs: Vec<Vec<f32>> = vec![Vec::new(); o1_layers.len()];
5955        crate::gpu_metal::o1c::qcap_begin(&o1_layers);
5956        for &li in &o1_layers {
5957            self.kv_cache.layers[li].o1_set_q_stride(QT_STRIDE);
5958        }
5959        let mut pos = 0;
5960        // Layers the rows graph does not hold (Spark-X2.6: GELU, per-head
5961        // gates, sliding windows) read the prefix on the chunk graph, which
5962        // keeps the collecting layers' queries too. Without it the prefix
5963        // went to the host walk: 14 000 tokens in 155 s against 53 s exact.
5964        let mut on_chunks = false;
5965        let mut step = chunk;
5966        while pos < n {
5967            let end = (pos + step).min(n);
5968            let bk = end - pos;
5969            let mut hiddens = vec![0f32; bk * hs];
5970            for (j, &id) in ids[pos..end].iter().enumerate() {
5971                hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
5972            }
5973            let rows = if on_chunks {
5974                MetalPrefillOutcome::Declined
5975            } else {
5976                self.prefill_hiddens_metal(hiddens.clone(), pos, None)
5977            };
5978            match rows {
5979                MetalPrefillOutcome::Completed(h) => last.copy_from_slice(&h[(bk - 1) * hs..]),
5980                MetalPrefillOutcome::Declined if pos == 0 || on_chunks => {
5981                    if !on_chunks {
5982                        on_chunks = true;
5983                        // The chunk graph's own prompt chunk.
5984                        let want = self.prefill_chunk().max(chunk);
5985                        if want != step {
5986                            step = want;
5987                            continue;
5988                        }
5989                    }
5990                    self.o1_chunk_prefix = true;
5991                    let got = self.chunk_run_gpu(0, &mut hiddens, bk, pos, None, self.num_layers);
5992                    self.o1_chunk_prefix = false;
5993                    if got != self.num_layers {
5994                        crate::gpu_metal::o1c::cap_end();
5995                        if pos == 0 && got == 0 {
5996                            for &li in &o1_layers {
5997                                self.kv_cache.layers[li].o1_set_q_stride(1);
5998                            }
5999                            return Ok(None);
6000                        }
6001                        return Err("O(1) prefix: the Metal chunk graph stopped after admission".into());
6002                    }
6003                    // Every layer appended the chunk: sliding layers keep their tails only.
6004                    self.swa_trim_tails();
6005                    last.copy_from_slice(&hiddens[(bk - 1) * hs..]);
6006                }
6007                _ => {
6008                    crate::gpu_metal::o1c::cap_end();
6009                    return Err("O(1) prefix: the Metal rows graph stopped after admission".into());
6010                }
6011            }
6012            for (li, q, _, _) in crate::gpu_metal::o1c::cap_take() {
6013                let Some(i) = o1_layers.iter().position(|&l| l == li) else { continue };
6014                if q.len() != bk * qrow {
6015                    crate::gpu_metal::o1c::cap_end();
6016                    return Err(format!("O(1) prefix: {} query values, expected {}", q.len(), bk * qrow));
6017                }
6018                for p in pos..end {
6019                    if p % QT_STRIDE == 0 {
6020                        qs[i].extend_from_slice(&q[(p - pos) * qrow..(p - pos + 1) * qrow]);
6021                    }
6022                }
6023            }
6024            pos = end;
6025        }
6026        crate::gpu_metal::o1c::cap_end();
6027        let row = nkv * hd;
6028        for (&li, q) in o1_layers.iter().zip(qs) {
6029            if q.len() != n.div_ceil(QT_STRIDE) * qrow {
6030                return Err(format!("O(1) prefix: layer {li} kept {} query values", q.len()));
6031            }
6032            if let Some(a) = arch.as_deref_mut() {
6033                let (mut k, mut v) = (vec![0f32; n * row], vec![0f32; n * row]);
6034                if !crate::gpu_metal::kv_mirror_read_rows(self.graph_kv_id, li, nkv, hd, 0, n, &mut k, &mut v) {
6035                    return Err("O(1) prefix: K/V readback failed".into());
6036                }
6037                let dir = a.dir.clone();
6038                let mut layer = O1ArchLayer {
6039                    li,
6040                    k: ArchStore::new(dir.as_deref(), format!("{li}-k"))?,
6041                    v: ArchStore::new(dir.as_deref(), format!("{li}-v"))?,
6042                    q: ArchStore::new(dir.as_deref(), format!("{li}-q"))?,
6043                };
6044                layer.k.push(&k)?;
6045                layer.v.push(&v)?;
6046                layer.q.push(&q)?;
6047                a.layers.push(layer);
6048                a.rows = n;
6049                a.stride = QT_STRIDE;
6050                a.nh = nh;
6051                a.nk = nkv;
6052                a.hd = hd;
6053            }
6054            self.kv_cache.layers[li].o1_set_q_trace(q);
6055        }
6056        Ok(Some(last))
6057    }
6058
6059    fn o1_exact_cfg(&self) -> Option<&crate::dory::ExactRows> {
6060        static EXACT: std::sync::OnceLock<Option<crate::dory::ExactRows>> = std::sync::OnceLock::new();
6061        EXACT
6062            .get_or_init(|| crate::dory::exact_from_var("CMF_O1_EXACT"))
6063            .as_ref()
6064            .or(self.o1_turbo.as_ref().map(|t| &t.exact))
6065    }
6066
6067    pub fn is_far_turbo(&self) -> bool {
6068        self.o1_turbo.is_some() && self.o1_graph_backend()
6069    }
6070
6071    /// A backend with the far field's prompt path and stages.
6072    fn o1_graph_backend(&self) -> bool {
6073        crate::gpu::wgpu_active() || crate::gpu::cuda_active() || crate::gpu::backend_name() == "metal"
6074    }
6075
6076    /// The whole prompt is read exact on the card, and one seal after it
6077    /// chooses among all of its rows, with the question's queries in the
6078    /// trace. The CUDA graph's way where it has no sealed-chunk kernels (the
6079    /// dense arm); its hybrid arm reads a prompt past the first seal in chunks
6080    /// as the wgpu graph does, so memory stays at the seal's
6081    /// (`CMF_O1_CHUNKS=0` reads it whole there too). `CMF_O1_WHOLE=1` takes
6082    /// either graph the whole way, so the two can be compared row for row.
6083    #[cfg(not(target_os = "macos"))]
6084    fn o1_whole_prompt(&self) -> bool {
6085        match std::env::var("CMF_O1_WHOLE").as_deref() {
6086            Ok("1") => return true,
6087            Ok("0") => return false,
6088            _ => {}
6089        }
6090        crate::gpu::cuda_active() && (self.graph_gdn_layer_count() == 0 || std::env::var("CMF_O1_CHUNKS").as_deref() == Ok("0"))
6091    }
6092
6093    pub fn far_turbo_seal(&self) -> usize {
6094        self.o1_turbo.as_ref().map_or(usize::MAX, |t| t.seal)
6095    }
6096
6097    /// The draft head on top of a far field: a verify's rows attend, and the state moves
6098    /// over the accepted ones only. On the wgpu graph; `CMF_O1_SPEC=0` turns it off.
6099    fn o1_spec(&self) -> bool {
6100        self.o1_active()
6101            && self.o1_on_graph()
6102            && self.o1_graph_backend()
6103            && (self.o1_turbo.is_some() || std::env::var("CMF_O1_SPEC").as_deref() == Ok("1"))
6104            && std::env::var("CMF_O1_SPEC").as_deref() != Ok("0")
6105    }
6106
6107    /// The far field rides the device graph: asked for, or a turbo file's way.
6108    fn o1_on_graph(&self) -> bool {
6109        self.o1_turbo.is_some() || std::env::var("CMF_O1_GPU").as_deref() == Ok("1")
6110    }
6111
6112    /// A turbo file takes the far field for a long prompt and leaves it for a short one,
6113    /// where exact attention and speculation are the faster way.
6114    fn o1_turbo_gate(&mut self, prompt_rows: usize) {
6115        // Off the wgpu and Metal graphs the far field would run on the host, so a turbo file
6116        // runs as the plain file it holds.
6117        if !self.is_far_turbo() {
6118            return;
6119        }
6120        let Some(t) = self.o1_turbo.clone() else { return };
6121        let want = prompt_rows >= t.seal;
6122        if want != self.o1_active() {
6123            self.clear_sequence_state();
6124            if let Err(e) = self.try_set_o1(want.then(|| t.cfg.clone())) {
6125                tracing::warn!("turbo file: the far field is off: {e}");
6126                self.o1_turbo = None;
6127            }
6128        }
6129    }
6130
6131    /// The rows this seal keeps exact (`CMF_O1_EXACT=FILE:rows`), the same in every layer.
6132    fn o1_choose_exact_rows(&mut self) {
6133        let Some(x) = self.o1_exact_cfg().cloned() else { return };
6134        let Some(c) = self.o1_cfg.clone() else { return };
6135        let layers: Vec<usize> = (0..self.num_layers)
6136            .filter(|&li| self.o1_flags.get(li).copied().unwrap_or(false) && self.kv_cache.layers[li].seq_len > 0 && self.kv_cache.layers[li].o1_is_collecting())
6137            .collect();
6138        let Some(&first) = layers.first() else { return };
6139        let rows = self.kv_cache.layers[first].seq_len;
6140        let floor = crate::nystrom::o1_deferred_boundary(c.w, c.sink).unwrap_or(usize::MAX);
6141        let target = self.kv_cache.layers[first].o1_pending_boundary().unwrap_or(floor).max(floor);
6142        if rows < target || layers.iter().any(|&li| self.kv_cache.layers[li].seq_len != rows) {
6143            return;
6144        }
6145        let t0 = std::time::Instant::now();
6146        let (nk, hd) = (self.kv_cache.layers[first].num_kv_heads, self.kv_cache.layers[first].head_dim);
6147        let keep = {
6148            let views: Vec<_> = layers.iter().map(|&li| self.kv_cache.layers[li].group_rows()).collect();
6149            let refs: Vec<&dyn crate::dory::LayerRows> = views.iter().map(|v| v as &dyn crate::dory::LayerRows).collect();
6150            crate::dory::pick_exact_rows(&x, &refs, rows, nk, hd, c.m, c.sink, rows.saturating_sub(c.w))
6151        };
6152        tracing::info!("o1: {} exact rows of {rows} chosen in {:.2} s", keep.len(), t0.elapsed().as_secs_f64());
6153        for &li in &layers {
6154            self.kv_cache.layers[li].o1_keep = keep.clone();
6155        }
6156    }
6157
6158    /// Complete a deferred boundary after a full position/span forward.
6159    /// This is the pipeline owner for epoch publication and failure cleanup.
6160    fn o1_progress(&mut self) {
6161        if !self.o1_active() {
6162            return;
6163        }
6164        for li in 0..self.num_layers {
6165            if self.o1_flags.get(li).copied().unwrap_or(false) {
6166                if let Some(err) = self.kv_cache.layers[li].take_o1_error() {
6167                    self.o1_fail(err);
6168                    return;
6169                }
6170            }
6171        }
6172        // A qwen_attention row can seal in the middle of a complete layer
6173        // walk. Consume its transition even though the pending boundary has
6174        // already disappeared from the cache.
6175        self.o1_note_transition();
6176        if !self.o1_pending() {
6177            return;
6178        }
6179        if let Err(err) = self.o1_seal_checked() {
6180            self.o1_fail(err);
6181        }
6182    }
6183
6184    /// Turn a deferred O(1) failure raised by a hidden-only forward into the
6185    /// Result error its public batch/span caller must return. The failure
6186    /// path already cleared host/device sequence state; consume only the
6187    /// side-channel marker here and leave the pipeline reusable.
6188    fn check_o1_progress_failure(&mut self, phase: &str) -> Result<(), String> {
6189        if self
6190            .graph_failed
6191            .swap(false, std::sync::atomic::Ordering::Relaxed)
6192        {
6193            self.cancel
6194                .store(false, std::sync::atomic::Ordering::Relaxed);
6195            self.clear_sequence_state();
6196            return Err(format!("{phase}: deferred O(1) transition failed"));
6197        }
6198        Ok(())
6199    }
6200
6201    /// Freeze landmarks + skeleton state after the prompt pass and drop
6202    /// the o1 layers' full KV; decode then runs `step()` per token.
6203    /// Pub for the network split (see `o1_begin`).
6204    pub fn o1_seal(&mut self) {
6205        if let Err(err) = self.o1_seal_checked() {
6206            self.o1_fail(err);
6207        }
6208    }
6209
6210    /// Run a bounded O(1) prefix (`ids`, positions 0..) through the batch
6211    /// graph instead of the host prefill: the same exact attention, with the
6212    /// O(1) layers' rotated queries captured on the device and their K/V rows
6213    /// read back from the mirror, so each layer's collector holds what the
6214    /// host walk would have given its seal. The recurrent and exact layers'
6215    /// state stays on the device for the sealed suffix batches.
6216    /// `Ok(None)`: declined before any device state moved — the caller runs
6217    /// the host prefill. `Ok(Some(h))`: the last prefix row's hidden.
6218    fn o1_prefix_on_graph(
6219        &mut self,
6220        ids: &[u32],
6221        chunk: usize,
6222        mut arch: Option<&mut O1Archive>,
6223    ) -> Result<Option<Vec<f32>>, String> {
6224        let o1_layers: Vec<usize> = (0..self.num_layers)
6225            .filter(|&li| self.o1_flags.get(li).copied().unwrap_or(false))
6226            .collect();
6227        let Some(&first) = o1_layers.first() else {
6228            return Ok(None);
6229        };
6230        let (nkv, hd) = {
6231            let c = &self.kv_cache.layers[first];
6232            (c.num_kv_heads, c.head_dim)
6233        };
6234        let nh = self.num_heads;
6235        if chunk == 0
6236            || o1_layers.iter().any(|&li| {
6237                let c = &self.kv_cache.layers[li];
6238                self.layer_num_heads(li) != nh
6239                    || (c.num_kv_heads, c.head_dim) != (nkv, hd)
6240                    || c.seq_len != 0
6241                    || c.o1_pending_boundary().is_none()
6242            })
6243            || !crate::gpu::o1_qcap_begin(&o1_layers)
6244        {
6245            return Ok(None);
6246        }
6247        let hs = self.hidden_size;
6248        let n = ids.len();
6249        let mut last = vec![0f32; hs];
6250        let mut pos = 0;
6251        self.o1_prefix_tail.clear();
6252        // `CMF_PREFILL_PROF`: where the prefix's time goes (the chunks, the
6253        // queries off the card, the K/V rows off the card, their way into the cache).
6254        let prof = std::env::var("CMF_PREFILL_PROF").is_ok();
6255        let (mut t_chunks, mut t_q) = (0f64, 0f64);
6256        // The seal's queries leave the card chunk by chunk, one row in `QT_STRIDE`: its
6257        // landmarks are means over long segments.
6258        const QT_STRIDE: usize = 8;
6259        let qrow = nh * hd;
6260        // A backend may hand back the kept rows alone (CUDA gathers them on the card).
6261        let strided = crate::gpu::o1_qcap_stride(QT_STRIDE);
6262        let mut qs: Vec<Vec<f32>> = vec![Vec::new(); o1_layers.len()];
6263        // the prompt's tail for the draft head over the far field
6264        let tail_from = n.saturating_sub(crate::dory::EXACT_TAIL);
6265        // A chunk whose rows nobody reads (before the last and the tail) is submitted
6266        // while the next one is encoded, and the queries leave the card every
6267        // `CMF_O1_QCAP_DRAIN` chunks (8; 1 = every chunk, waiting for each): a drain
6268        // waits for the card. SenseNova-Loop-9B over Vulkan, 8192 rows in 128-row
6269        // chunks: one wait a chunk spent half the prefix with the card idle.
6270        let drain_every = std::env::var("CMF_O1_QCAP_DRAIN").ok().and_then(|v| v.parse().ok()).unwrap_or(8usize).max(1);
6271        let (mut drain_from, mut undrained) = (0usize, 0usize);
6272        while pos < n {
6273            let end = o1_chunk_end(pos, chunk, n);
6274            let bk = end - pos;
6275            let mut hiddens = vec![0f32; bk * hs];
6276            for (j, &id) in ids[pos..end].iter().enumerate() {
6277                hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
6278            }
6279            let positions: Vec<usize> = (pos..end).collect();
6280            let t_c = std::time::Instant::now();
6281            let defer = drain_every > 1 && end < n && end <= tail_from;
6282            #[cfg(not(target_os = "macos"))]
6283            crate::gpu::set_batch_defer(defer);
6284            let outcome = self.try_batch_graph_wgpu(&mut hiddens, &positions, bk, None);
6285            #[cfg(not(target_os = "macos"))]
6286            crate::gpu::set_batch_defer(false);
6287            t_chunks += t_c.elapsed().as_secs_f64();
6288            let t_d = std::time::Instant::now();
6289            match outcome {
6290                crate::gpu::BatchGraphOutcome::Completed => {
6291                    if !defer {
6292                        last.copy_from_slice(&hiddens[(bk - 1) * hs..]);
6293                    }
6294                    if end > tail_from {
6295                        let from = pos.max(tail_from);
6296                        self.o1_prefix_tail.extend_from_slice(&hiddens[(from - pos) * hs..]);
6297                    }
6298                }
6299                crate::gpu::BatchGraphOutcome::Declined if pos == 0 => {
6300                    let _ = crate::gpu::o1_qcap_take();
6301                    return Ok(None);
6302                }
6303                _ => {
6304                    let _ = crate::gpu::o1_qcap_take();
6305                    return Err("O(1) prefix batch graph stopped after admission".into());
6306                }
6307            }
6308            undrained += 1;
6309            pos = end;
6310            if defer && undrained < drain_every {
6311                continue;
6312            }
6313            let Some(drained) = crate::gpu::o1_qcap_drain() else {
6314                let _ = crate::gpu::o1_qcap_take();
6315                return Err("O(1) prefix: query readback failed".into());
6316            };
6317            // the rows since the last drain
6318            let rows_n = end - drain_from;
6319            for (i, (_, rows)) in drained.iter().enumerate() {
6320                if strided {
6321                    let kept = (drain_from..end).filter(|p| p % QT_STRIDE == 0).count();
6322                    if rows.len() != kept * qrow {
6323                        let _ = crate::gpu::o1_qcap_take();
6324                        return Err(format!("O(1) prefix: {} query values, expected {}", rows.len(), kept * qrow));
6325                    }
6326                    qs[i].extend_from_slice(rows);
6327                    continue;
6328                }
6329                if rows.len() != rows_n * qrow {
6330                    let _ = crate::gpu::o1_qcap_take();
6331                    return Err(format!("O(1) prefix: {} query values, expected {}", rows.len(), rows_n * qrow));
6332                }
6333                for p in drain_from..end {
6334                    if p % QT_STRIDE == 0 {
6335                        qs[i].extend_from_slice(&rows[(p - drain_from) * qrow..(p - drain_from + 1) * qrow]);
6336                    }
6337                }
6338            }
6339            drain_from = end;
6340            undrained = 0;
6341            t_q += t_d.elapsed().as_secs_f64();
6342        }
6343        let _ = crate::gpu::o1_qcap_take();
6344        let t_kv = std::time::Instant::now();
6345        let pulls: Vec<(usize, usize, usize)> = o1_layers.iter().map(|&li| (li, 0, n)).collect();
6346        let kv = crate::gpu::graph_kv_read_rows(self.graph_kv_id, &pulls, nkv, hd)
6347            .ok_or("O(1) prefix: K/V readback failed")?;
6348        let (t_kv, t_app) = (t_kv.elapsed().as_secs_f64(), std::time::Instant::now());
6349        let row = nkv * hd;
6350        if arch.is_none() {
6351            // without an archive each layer's rows go into its own cache: the
6352            // layers side by side
6353            for ((&li, q), (k, v)) in o1_layers.iter().zip(&qs).zip(&kv) {
6354                if k.len() != n * row || v.len() != n * row || q.len() != n.div_ceil(QT_STRIDE) * qrow {
6355                    return Err(format!(
6356                        "O(1) prefix: layer {li} read back {}/{}/{} values, expected {}/{}/{}",
6357                        k.len(),
6358                        v.len(),
6359                        q.len(),
6360                        n * row,
6361                        n * row,
6362                        n.div_ceil(QT_STRIDE) * qrow
6363                    ));
6364                }
6365            }
6366            let mut work: Vec<(&mut crate::kv_cache::LayerKvCache, Vec<f32>, (Vec<f32>, Vec<f32>))> = Vec::new();
6367            let mut by_layer: Vec<Option<(Vec<f32>, (Vec<f32>, Vec<f32>))>> = (0..self.kv_cache.layers.len()).map(|_| None).collect();
6368            for ((&li, q), kvp) in o1_layers.iter().zip(qs).zip(kv) {
6369                by_layer[li] = Some((q, kvp));
6370            }
6371            for (cache, slot) in self.kv_cache.layers.iter_mut().zip(by_layer) {
6372                if let Some((q, kvp)) = slot {
6373                    work.push((cache, q, kvp));
6374                }
6375            }
6376            let par = std::thread::available_parallelism().map_or(1, |p| p.get()).clamp(1, 8);
6377            let per = work.len().div_ceil(par).max(1);
6378            std::thread::scope(|sc| {
6379                for part in work.chunks_mut(per) {
6380                    sc.spawn(move || {
6381                        for (cache, q, (k, v)) in part.iter_mut() {
6382                            cache.o1_set_q_stride(QT_STRIDE);
6383                            cache.reserve_rows(n);
6384                            for p in 0..n {
6385                                cache.append(&k[p * row..(p + 1) * row], &v[p * row..(p + 1) * row], &[]);
6386                            }
6387                            cache.o1_set_q_trace(std::mem::take(q));
6388                        }
6389                    });
6390                }
6391            });
6392            if prof {
6393                eprintln!(
6394                    "o1 prefix: {n} rows, chunks {t_chunks:.2} s, queries off the card {t_q:.2} s, K/V off the card {t_kv:.2} s, into the cache {:.2} s",
6395                    t_app.elapsed().as_secs_f64()
6396                );
6397            }
6398            return Ok(Some(last));
6399        }
6400        for ((&li, q), (k, v)) in o1_layers.iter().zip(qs).zip(kv) {
6401            if k.len() != n * row || v.len() != n * row || q.len() != n.div_ceil(QT_STRIDE) * qrow {
6402                return Err(format!(
6403                    "O(1) prefix: layer {li} read back {}/{}/{} values, expected {}/{}/{}",
6404                    k.len(),
6405                    v.len(),
6406                    q.len(),
6407                    n * row,
6408                    n * row,
6409                    n.div_ceil(QT_STRIDE) * qrow
6410                ));
6411            }
6412            let cache = &mut self.kv_cache.layers[li];
6413            cache.o1_set_q_stride(QT_STRIDE);
6414            cache.reserve_rows(n);
6415            for p in 0..n {
6416                cache.append(&k[p * row..(p + 1) * row], &v[p * row..(p + 1) * row], &[]);
6417            }
6418            if let Some(a) = arch.as_deref_mut() {
6419                let dir = a.dir.clone();
6420                let mut layer = O1ArchLayer {
6421                    li,
6422                    k: ArchStore::new(dir.as_deref(), format!("{li}-k"))?,
6423                    v: ArchStore::new(dir.as_deref(), format!("{li}-v"))?,
6424                    q: ArchStore::new(dir.as_deref(), format!("{li}-q"))?,
6425                };
6426                layer.k.push(&k)?;
6427                layer.v.push(&v)?;
6428                layer.q.push(&q)?;
6429                a.layers.push(layer);
6430                a.rows = n;
6431                a.stride = QT_STRIDE;
6432                a.nh = nh;
6433                a.nk = nkv;
6434                a.hd = hd;
6435            }
6436            cache.o1_set_q_trace(q);
6437        }
6438        if prof {
6439            eprintln!(
6440                "o1 prefix: {n} rows, chunks {t_chunks:.2} s, queries off the card {t_q:.2} s, K/V off the card {t_kv:.2} s, into the cache {:.2} s",
6441                t_app.elapsed().as_secs_f64()
6442            );
6443        }
6444        Ok(Some(last))
6445    }
6446
6447    /// Enable/disable the structured per-token telemetry trace (B4).
6448    pub fn set_trace(&mut self, on: bool) {
6449        self.trace = on;
6450    }
6451
6452    /// Replace all request-scoped sampler options and reset the random stream.
6453    /// This is required for deterministic `seed` semantics in pooled servers.
6454    pub fn set_sampler_config(&mut self, config: SamplerConfig) {
6455        self.rng = match config.seed {
6456            Some(seed) => SplitMix64::new(seed),
6457            None => SplitMix64::from_entropy(),
6458        };
6459        self.sampler_config = config;
6460    }
6461
6462    /// Toggle the per-token confidence reduction (a full-vocab
6463    /// softmax each token). `bench --core` turns it off so the timed
6464    /// loop matches llama-bench's core contract; the result's
6465    /// `confidence` vec is empty while off.
6466    pub fn set_confidence(&mut self, on: bool) {
6467        self.confidence_on = on;
6468    }
6469
6470    /// Set the confidence-calibration temperature (B1). Values ≤0 are
6471    /// clamped to raw (1.0).
6472    pub fn set_calib_temp(&mut self, t: f32) {
6473        self.calib_temp = if t > 1e-3 { t } else { 1.0 };
6474    }
6475
6476    /// The active calibration temperature (1.0 = raw probability).
6477    pub fn calib_temp(&self) -> f32 {
6478        self.calib_temp
6479    }
6480
6481    /// The primary (full-attention) RoPE inverse-frequency table selected
6482    /// from the CMF architecture.  This is read-only diagnostic state for
6483    /// parity checks; local sliding layers may use `inv_freq_local` instead.
6484    pub fn rope_inv_freq(&self) -> &[f32] {
6485        self.inv_freq.as_slice()
6486    }
6487
6488    /// Partial rotary (Qwen3.5): rotate only the first `rotary_dim` dims;
6489    /// the frequency table is rebuilt over the rotary dims.
6490    pub fn set_rotary(&mut self, rotary_dim: usize, base: f32) {
6491        self.rotary_dim = rotary_dim.min(self.head_dim);
6492        self.inv_freq = std::sync::Arc::new(attention::rope_inv_freq(self.rotary_dim, base));
6493        // The packed resident graph owns its own inverse-frequency plane;
6494        // changing RoPE after it was built must not leave a stale device
6495        // model behind the exact host configuration.
6496        self.embryo_graph = None;
6497    }
6498
6499    fn attn_cfg(&self, position: usize) -> QwenAttnCfg<'_> {
6500        QwenAttnCfg {
6501            mrope: None,
6502            num_heads: self.num_heads,
6503            num_kv_heads: self.num_kv_heads,
6504            head_dim: self.head_dim,
6505            hidden_size: self.hidden_size,
6506            position,
6507            inv_freq: &self.inv_freq,
6508            rotary_dim: self.rotary_dim,
6509            scale: self.attn_scale,
6510            softcap: self.attn_softcap,
6511            window: None,
6512            v_norm: false,
6513            qk_norm_after_rope: self.qk_norm_after_rope,
6514            gate_sigmoid: self.proj_gate_sigmoid,
6515            q_norm: None,
6516            k_norm: None,
6517            output_gate: false,
6518            softplus_gate: None,
6519            rope_scale: self.rope_scale,
6520            bias: None,
6521            rms_eps: self.rms_eps,
6522            norm_style: self.norm_style,
6523            pool: self.pool.as_deref(),
6524            v_head_dim: self.v_head_dim.unwrap_or(self.head_dim),
6525            value_in: None,
6526        }
6527    }
6528
6529    /// Generate text from a plain-text prompt. Streams tokens via `on_token`.
6530    pub fn generate(
6531        &mut self,
6532        prompt: &str,
6533        max_tokens: usize,
6534        task_mask: Option<&TaskMask>,
6535        on_token: Option<TokenCallback>,
6536    ) -> Result<GenerateResult, String> {
6537        let input_ids = self.tokenizer.with_bos(self.tokenizer.encode(prompt));
6538        self.generate_from_ids(&input_ids, max_tokens, task_mask, on_token)
6539    }
6540
6541    /// Generate from a V4.1 multimodal prompt prepared by the vision module.
6542    /// Vision rows are encoded once and fed through the same bounded token walk as text.
6543    pub fn generate_from_vl(
6544        &mut self,
6545        input: &crate::dsv41_vision::PreparedVlInputs,
6546        max_tokens: usize,
6547        task_mask: Option<&TaskMask>,
6548        on_token: Option<TokenCallback>,
6549    ) -> Result<GenerateResult, String> {
6550        let Some(dsv41) = &self.dsv41 else {
6551            return Err("V4.1 multimodal input requires a DeepSeek-V4.1 pipeline".into());
6552        };
6553        if input.token_ids.is_empty() {
6554            return Err("empty V4.1 multimodal prompt".into());
6555        }
6556        if input.token_types.len() != input.token_ids.len() {
6557            return Err(format!(
6558                "V4.1 token type count {} != token count {}",
6559                input.token_types.len(),
6560                input.token_ids.len()
6561            ));
6562        }
6563        let dim = dsv41.2.dim;
6564        let mut embeddings = vec![None; input.token_ids.len()];
6565        let mut participates = vec![true; input.token_ids.len()];
6566        if !input.images.is_empty() {
6567            let vision = self
6568                .dsv41_vision
6569                .as_ref()
6570                .ok_or_else(|| "V4.1 image prompt has no loaded vision tower".to_string())?;
6571            for image in &input.images {
6572                let end = image.start.saturating_add(image.types.len());
6573                if end > input.token_ids.len() {
6574                    return Err(format!(
6575                        "V4.1 image span {}..{} exceeds prompt length {}",
6576                        image.start,
6577                        end,
6578                        input.token_ids.len()
6579                    ));
6580                }
6581                let mut span = vec![0.0f32; image.types.len() * dim];
6582                vision.fill_image_span(image, &mut span, self.pool.as_deref())?;
6583                for (offset, &kind) in image.types.iter().enumerate() {
6584                    let pos = image.start + offset;
6585                    if input.token_types[pos] != kind {
6586                        return Err(format!(
6587                            "V4.1 image type mismatch at position {pos}: {} != {kind}",
6588                            input.token_types[pos]
6589                        ));
6590                    }
6591                    embeddings[pos] = Some(span[offset * dim..(offset + 1) * dim].to_vec());
6592                    participates[pos] = false;
6593                }
6594            }
6595        }
6596        for (pos, &kind) in input.token_types.iter().enumerate() {
6597            if kind == crate::dsv41_vision::TEXT && embeddings[pos].is_some() {
6598                return Err(format!("V4.1 text position {pos} has an image embedding"));
6599            }
6600            if kind != crate::dsv41_vision::TEXT && embeddings[pos].is_none() {
6601                return Err(format!("V4.1 image position {pos} has no image embedding"));
6602            }
6603        }
6604        self.dsv41_prefill = Some((embeddings, participates));
6605        let result = self.generate_from_ids(&input.token_ids, max_tokens, task_mask, on_token);
6606        self.dsv41_prefill = None;
6607        result
6608    }
6609
6610    /// `None` when the mask forbids nothing (see `TaskMask::fully_open`).
6611    fn drop_open_mask<'m>(&self, m: Option<&'m TaskMask>) -> Option<&'m TaskMask> {
6612        m.filter(|m| !m.fully_open(self.intermediate_size, self.num_heads))
6613    }
6614
6615    /// Generate from prepared token ids (e.g. a chat template).
6616    ///
6617    /// With an MTP head, greedy generation without a task mask takes the
6618    /// speculative path: the MTP module drafts the token after next and
6619    /// the main model verifies both in one fused two-position forward
6620    /// (weights streamed once). The output is EXACTLY the vanilla greedy
6621    /// sequence — a rejected draft is rolled back — MTP only buys speed.
6622    pub fn generate_from_ids(
6623        &mut self,
6624        input_ids: &[u32],
6625        max_tokens: usize,
6626        task_mask: Option<&TaskMask>,
6627        on_token: Option<TokenCallback>,
6628    ) -> Result<GenerateResult, String> {
6629        let out = self.generate_with_prompt_rows(input_ids, None, max_tokens, task_mask, on_token);
6630        crate::gpu::generation_end();
6631        out
6632    }
6633
6634    /// Generate from complete prompt embeddings [token_count, hidden_size].
6635    /// Text rows can be obtained with `embed_id`; media rows replace only
6636    /// their expanded placeholder positions. Rows are already scaled and
6637    /// enter `PrefillIn::Hidden`, so a device graph must not re-embed them.
6638    /// Token-only KV reuse is disabled both into and out of this request.
6639    pub fn generate_from_embeds(
6640        &mut self,
6641        input_ids: &[u32],
6642        prompt_rows: &[f32],
6643        max_tokens: usize,
6644        task_mask: Option<&TaskMask>,
6645        on_token: Option<TokenCallback>,
6646    ) -> Result<GenerateResult, String> {
6647        if input_ids.is_empty()
6648            || input_ids.len().checked_mul(self.hidden_size) != Some(prompt_rows.len())
6649        {
6650            return Err("embedded prompt dimensions must be [tokens, hidden_size]".into());
6651        }
6652        if prompt_rows.iter().any(|x| !x.is_finite()) {
6653            return Err("embedded prompt contains non-finite values".into());
6654        }
6655        // A turbo file picks its far field by the prompt's length: an image prompt
6656        // under the seal reads exact, whatever the previous request held.
6657        self.o1_turbo_gate(input_ids.len());
6658        if !self.can_prefill_batched()
6659            || self.dyn_router.is_some()
6660            || self.o1_active()
6661            || self.gpu_plan.is_some()
6662        {
6663            return Err("embedded prompts require the ordinary transformer path without O(1), dynamic routing or GPU splitting".into());
6664        }
6665        // The MTP head drafts over token rows: an embedded prompt decodes
6666        // without it (the greedy text is the same; MTP state is rebuilt from
6667        // the next prompt, and token reuse out of this request is off).
6668        // SenseNova-Loop-9B's release ships the head, and its image prompts
6669        // were refused before.
6670        let mtp = self.mtp.take();
6671        let out = self.generate_with_prompt_rows(
6672            input_ids,
6673            Some(prompt_rows),
6674            max_tokens,
6675            task_mask,
6676            on_token,
6677        );
6678        self.mtp = mtp;
6679        out
6680    }
6681
6682    fn generate_with_prompt_rows(
6683        &mut self,
6684        input_ids: &[u32],
6685        prompt_rows: Option<&[f32]>,
6686        max_tokens: usize,
6687        task_mask: Option<&TaskMask>,
6688        mut on_token: Option<TokenCallback>,
6689    ) -> Result<GenerateResult, String> {
6690        #[cfg(target_os = "macos")]
6691        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
6692        if std::env::var("CMF_TRACE_H").is_ok() {
6693            eprintln!("input_ids: {input_ids:?}");
6694        }
6695        if input_ids.is_empty() {
6696            return Err("empty prompt: nothing to generate from".to_string());
6697        }
6698        // A prior graph failure is terminal for that sequence but must not
6699        // poison the next independent request.  Keep this flag separate from
6700        // the externally-owned cooperative cancel bit.
6701        self.graph_failed
6702            .store(false, std::sync::atomic::Ordering::Relaxed);
6703        // A mask that forbids nothing still costs every fused path and
6704        // whole-token graph, all of which are gated on `is_none()`. A
6705        // narrowed file whose one segment is always on carries exactly
6706        // such a mask — drop it here rather than pay 5x for a no-op.
6707        self.o1_turbo_gate(input_ids.len());
6708        self.mtp_pos_base = 0;
6709        let prev_mtp_warm = self.mtp_warm_base.take();
6710        // the draft head's rows a chat snapshot keeps (counted from its base)
6711        let mut mtp_keep: Option<usize> = None;
6712        let task_mask = self.drop_open_mask(task_mask);
6713        // Unlimited-OCR: the page coordinates of this prompt.
6714        if self.dash.is_some() {
6715            if prompt_rows.is_none() {
6716                return Err("Unlimited-OCR reads images: pass at least one".into());
6717            }
6718            let eos = self.tokenizer.eos_token_id.unwrap_or(1);
6719            if let Some(d) = self.dash.as_mut() {
6720                d.begin(input_ids, eos)?;
6721            }
6722        }
6723        // A block-diffusion model generates whole blocks by denoising
6724        // previews, unless the request asks for the causal decode.
6725        if self.clover.is_some() && !self.clover_causal_request() {
6726            if prompt_rows.is_some() || task_mask.is_some() {
6727                return Err("block-diffusion generation takes token prompts without task masks".into());
6728            }
6729            return self.clover_generate(input_ids, max_tokens, on_token);
6730        }
6731
6732        // Cross-turn KV reuse: a chat app resends the whole history
6733        // every turn; when the new ids strictly EXTEND what the cache
6734        // already holds, prefill only the tail — turn latency stays
6735        // proportional to the new text instead of the whole session.
6736        // Extension-only (no rollback), so it is exact for every layer
6737        // kind including recurrent state; MTP/o1/task-mask runs keep
6738        // the fresh-sequence path. CMF_KV_REUSE=0 disables.
6739        let mut reuse_from = if self.dory.is_some() {
6740            self.dory_cached_prefix(input_ids)
6741        } else {
6742            let on = !std::env::var("CMF_KV_REUSE").is_ok_and(|v| v == "0");
6743            if on
6744                && prompt_rows.is_none()
6745                && task_mask.is_none()
6746                && self.mtp.is_none()
6747                && !(self.mimo_mtp.is_some() && self.speculative)
6748                && self.o1_cfg.is_none()
6749                && self.dsv41.is_none()
6750            {
6751                self.cached_prefix_len(input_ids)
6752            } else {
6753                0
6754            }
6755        };
6756        // The device may own rows the host tail prefill needs (wgpu decode
6757        // writes only its mirror): hand them to the host, or start fresh.
6758        if reuse_from > 0 && !self.prepare_kv_reuse(reuse_from) {
6759            reuse_from = 0;
6760        }
6761        // The CUDA hybrid arm: a chat turn that starts with the ids before
6762        // the last turn's assistant header goes back to the GDN snapshot the
6763        // card took there; the attention mirrors rewind with it. The rows
6764        // before it are prompt rows no decode wrote, so this is exact after
6765        // any speculative round, and the draft head reads from there on.
6766        if reuse_from == 0 && prompt_rows.is_none() && task_mask.is_none() {
6767            let n = self.gdn_snap_reuse(input_ids);
6768            if n > 0 {
6769                reuse_from = n;
6770                self.kv_history.truncate(n);
6771                for l in &mut self.kv_cache.layers {
6772                    let d = l.pos_len().saturating_sub(n);
6773                    if d > 0 {
6774                        l.truncate_last(d);
6775                    }
6776                }
6777                self.graph_logits = None;
6778                // The draft head's rows before `n` are the last prompt's
6779                // rows when it was warmed over that whole prompt: they stay,
6780                // and it reads the conversation, not just the new turn.
6781                if self.mtp.is_some() {
6782                    match prev_mtp_warm {
6783                        Some(b) if b <= n => {
6784                            self.mtp_pos_base = b;
6785                            mtp_keep = Some(n - b);
6786                        }
6787                        _ => self.mtp_pos_base = n,
6788                    }
6789                }
6790                if std::env::var("CMF_PREFILL_PROF").is_ok() {
6791                    eprintln!("kv-reuse: GDN snapshot at {n} of {} prompt positions", input_ids.len());
6792                }
6793            }
6794        }
6795        // A diverging turn (`rollback_prefix_len`): drop every row past the
6796        // common prefix, so the tail prefill appends at `reuse_from`.
6797        if reuse_from > 0 && self.dory.is_some() && reuse_from < self.kv_history.len() {
6798            // The device's rings are addressed by position, so going back there
6799            // is only this: the next rows overwrite the rolled-back ones.
6800            if let Some(b) = &mut self.dory {
6801                let kv_row = b.0.cfg.nk * b.0.cfg.hd;
6802                b.1.rollback(reuse_from, kv_row);
6803            }
6804            self.kv_history.truncate(reuse_from);
6805            self.graph_logits = None;
6806        }
6807        if reuse_from > 0 && self.dory.is_none() && !self.bounded_native() && reuse_from < self.kv_history.len() {
6808            for l in &mut self.kv_cache.layers {
6809                let d = l.pos_len() - reuse_from;
6810                l.truncate_last(d);
6811            }
6812            if std::env::var("CMF_PREFILL_PROF").is_ok() {
6813                eprintln!(
6814                    "kv-reuse: rolled back {} answer position(s) to the common prefix",
6815                    self.kv_history.len() - reuse_from
6816                );
6817            }
6818            self.kv_history.truncate(reuse_from);
6819            self.graph_logits = None;
6820        }
6821        self.swa_trim_anchor = input_ids.len();
6822        self.dflash_tap_from = match &self.dflash {
6823            Some(d) if (0..d.g.layers).all(|l| d.g.window_of(l) > 0) => {
6824                let w = (0..d.g.layers).map(|l| d.g.window_of(l)).max().unwrap_or(0);
6825                input_ids.len().saturating_sub(w + crate::dflash::BLOCK_SLACK)
6826            }
6827            _ => 0,
6828        };
6829        self.last_prefill_tokens = input_ids.len() - reuse_from;
6830        let bounded_native = self.bounded_native();
6831        if reuse_from == 0 {
6832            // Fresh sequence — the cache holds absolute positions.
6833            // MTP never participates in cross-turn KV reuse, so a
6834            // high-vocabulary token from the previous request must not keep
6835            // this request on its expensive full draft head.
6836            self.reset_fresh_mtp_draft_state();
6837            self.clear_sequence_state();
6838        } else if std::env::var("CMF_PREFILL_PROF").is_ok() {
6839            eprintln!(
6840                "kv-reuse: {} of {} prompt positions already cached",
6841                reuse_from,
6842                input_ids.len()
6843            );
6844        }
6845        crate::gpu::graph_race_begin_generation();
6846        // Optional bounded calibration prefix. Keep the requested value
6847        // even when it is longer than the prompt; the collecting layer will
6848        // defer at the effective boundary and remain exact for short input.
6849        let o1_prefill = if self.o1_active() && task_mask.is_none() {
6850            std::env::var("CMF_O1_PREFILL")
6851                .ok()
6852                .and_then(|v| v.parse::<usize>().ok())
6853                .filter(|&p| p > 0)
6854                // Exact rows are chosen before the prompt's last rows, which then read them.
6855                .or_else(|| {
6856                    self.o1_exact_cfg()
6857                        .map(|_| {
6858                            let max = std::env::var("CMF_O1_PREFIX_MAX")
6859                                .ok()
6860                                .and_then(|v| v.parse().ok())
6861                                .or(self.o1_turbo.as_ref().map(|t| t.seal))
6862                                .unwrap_or(O1_PREFIX_MAX);
6863                            input_ids.len().saturating_sub(crate::dory::EXACT_TAIL).min(max)
6864                        })
6865                        .filter(|&p| p > 0)
6866                })
6867        } else {
6868            None
6869        };
6870        if task_mask.is_none() {
6871            self.o1_begin_with_prefix(o1_prefill);
6872        }
6873        if let Ok(f) = std::env::var("CMF_O1_TOKENS_DUMP") {
6874            let b: Vec<u8> = input_ids.iter().flat_map(|v| v.to_le_bytes()).collect();
6875            let _ = std::fs::write(f, b);
6876        }
6877
6878        // Speculative decode is off under o1: a rejected draft can't be
6879        // rolled back out of the far accumulators / ring window (the
6880        // Nyström insertion is irreversible by design).
6881        // The wgpu token graph owns a device K/V mirror that speculative
6882        // rollback would desync — the two are mutually exclusive.
6883        let graph_on = crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode);
6884        // Graph speculative decode (`CMF_GRAPH_SPEC=1`): the MTP head
6885        // drafts, ONE batched graph submit verifies the whole chain.
6886        //
6887        // It now PAYS on Qwen3.6-27B / RTX 5090 — 51.1 tok/s against a
6888        // plain 49.4 at k=3, medians of three, 89% of drafts accepted,
6889        // and the greedy continuation is byte-identical to the plain
6890        // path. That took the batch matvec sharing its nibble unpack
6891        // across the batch (`CMF_MV_BK=2`); before it, the same round
6892        // measured 43.6, an 11% LOSS, which is what the earlier note
6893        // here described.
6894        //
6895        // Still opt-in. One model's win is not a default: the verify
6896        // rides `gdn_spec_restore` and a batched frame whose numerics
6897        // are the batch kernels', and that has to be shown on more than
6898        // one architecture before every greedy decode takes it.
6899        // Greedy (with or without penalties) verifies by argmax equality.
6900        // Sampling (temperature > 0) can go through speculative SAMPLING —
6901        // draft from the MTP head's own post-chain distribution, accept
6902        // with min(1, p/q), correct from max(0, p − q); the emitted stream
6903        // is distributed exactly as the plain sampler's — but it is
6904        // OPT-IN (`CMF_GRAPH_SPEC_SAMPLE=1`): measured on Qwen3.8-27B /
6905        // RTX 5090 at the instruct row (0.7 / 0.80 / 20 / presence 1.5)
6906        // it decoded 19-22 tok/s against a plain 40 — nine post-chain
6907        // distributions a round plus a lower acceptance than greedy's,
6908        // against a verify that costs 2.7 single tokens. The greedy arms
6909        // pay +10%; the sampling arm needs a cheaper verify first.
6910        // Native Metal has a fast row-batch verify, but it is NOT admitted
6911        // by default: a real-model exactness check found an emitted greedy
6912        // divergence from the serial path.  Every native-Metal speculative
6913        // arm therefore requires the explicit `CMF_GRAPH_SPEC=1` experiment
6914        // gate until the batch kernels are numerically qualified.  If it is
6915        // explicitly enabled, its sampling arm is useful only for a config
6916        // the SPARSE chain serves (a top-k within `sparse_ok`): without it a
6917        // round builds nine 248k-float distributions on the host, which is
6918        // the 5090's measured loss and not a cost the round-token proxy
6919        // below can see. A top-k-less sampling config keeps the plain path
6920        // unless asked for by name.
6921        #[cfg(target_os = "macos")]
6922        let metal_graph = crate::gpu::q1_force()
6923            && crate::gpu::enabled_here()
6924            && std::env::var("CMF_GPU_BLOCK")
6925                .map(|v| v != "0")
6926                .unwrap_or(true);
6927        // `CMF_GPU_BLOCK=0` declines the ordinary native block route but
6928        // does not change the backend identity: a separately requested wgpu
6929        // graph can still reach `graph_spec_step`, whose native branch uses
6930        // VerifyGraph. Keep the quality policy tied to that identity, not to
6931        // the particular block-route admission above.
6932        #[cfg(target_os = "macos")]
6933        let native_metal_backend = crate::gpu::q1_force();
6934        #[cfg(not(target_os = "macos"))]
6935        let metal_graph = false;
6936        #[cfg(not(target_os = "macos"))]
6937        let native_metal_backend = false;
6938        let spec_sample_env = std::env::var("CMF_GRAPH_SPEC_SAMPLE").ok();
6939        // A round whose cost is the MEASURED one: greedy (argmax rows), or
6940        // sampling through the sparse chain. Anything else pays the dense
6941        // chain's host time, which no proxy can price.
6942        let spec_cheap_round =
6943            self.sampler_config.temperature < 1e-6 || sampler::sparse_ok(&self.sampler_config);
6944        let spec_sampling_ok = self.sampler_config.temperature < 1e-6
6945            || match spec_sample_env.as_deref() {
6946                Some("1") => true,
6947                Some(_) => false,
6948                None => metal_graph && spec_cheap_round,
6949            };
6950        // ON by default for greedy on the wgpu graph: with the draft on
6951        // the graph and the verify bit-exact, it measured 58.7 tok/s
6952        // against a plain 48.1 on Qwen3.8-27B q4tp / RTX 5090 (k=4) and
6953        // 51.1 against 49.4 on Qwen3.6-27B, and a round that stops
6954        // paying turns itself off below (acceptance watchdog).
6955        // `CMF_GRAPH_SPEC=0` disables; `=1` is the explicit opt-in spelling.
6956        // …but only where the batched verify has its register-blocked
6957        // kernel: q4tp dense FFNs (graph kind 6). q4t and q8_2f verify
6958        // through tile GEMMs today and measured a LOSS (q8_2f 22 against
6959        // 29 tok/s), the 2-bit plane the same; those stay opt-in
6960        // (`CMF_GRAPH_SPEC=1`).
6961        // …at least in nine dense FFNs of ten: a healed file carries its
6962        // last two layers at q8_2f, and two tile-GEMM verifies among 64 do
6963        // not change the arithmetic (measured: the healed q4tp file
6964        // decodes at the plain file's rate and would otherwise sit out).
6965        let (mut dense_n, mut dense_q4tp) = (0usize, 0usize);
6966        for lw in &self.weights.layers {
6967            if let FfnKind::Dense(d) = &lw.ffn {
6968                dense_n += 1;
6969                if matches!(d.gate_proj.graph_weight(), Some((_, _, 6, _)))
6970                    && matches!(d.up_proj.graph_weight(), Some((_, _, 6, _)))
6971                    && matches!(d.down_proj.graph_weight(), Some((_, _, 6, _)))
6972                {
6973                    dense_q4tp += 1;
6974                }
6975            }
6976        }
6977        // …and only where the MTP block itself runs on the graph. A MoE
6978        // draft block (Qwen3.6-35B-A3B, Apex-35B: 256 experts in the MTP
6979        // layer) fails `mtp_graph_ok`, so it drafts — and warms its cache
6980        // over the whole prompt — op by op on the host. Apex-35B q4tp on an
6981        // A40 + Xeon Gold 6342: greedy 51.8 against 65.6 tok/s plain (300
6982        // tokens, 57 % accepted), and 2.5 ms per prompt position (a
6983        // 4096-token ingest 171 against 295 tok/s); the published
6984        // Qwen3.6-35B-A3B 79.7 against 86.6. `CMF_GRAPH_SPEC=1` opts in.
6985        // Native Metal has no wgpu graph: its draft step is `mtp_step_metal`,
6986        // which takes the same block shape.
6987        #[cfg(feature = "gpu")]
6988        let mtp_on_graph = self.mtp.as_ref().is_none_or(|m| {
6989            if native_metal_backend {
6990                self.mtp_block_shape_ok(m)
6991            } else {
6992                self.mtp_graph_ok(m)
6993            }
6994        });
6995        #[cfg(not(feature = "gpu"))]
6996        let mtp_on_graph = self.mtp.as_ref().is_none_or(|m| !native_metal_backend || self.mtp_block_shape_ok(m));
6997        let spec_default_ok = (dense_n == 0 || dense_q4tp * 10 >= dense_n * 9) && mtp_on_graph;
6998        // Penalties break the draft head's agreement with the trunk (a
6999        // 1.1 repetition penalty measured 2 of 16 accepted): not by
7000        // default there either — off Metal that rule is untouched, and
7001        // suppressed ids keep counting as a penalty there, because no
7002        // measurement on a discrete card says otherwise.
7003        //
7004        // On native Metal the penalized arms DO pay: the draft applies
7005        // the same penalty and the verify scores the penalized rows
7006        // exactly (`greedy_pen`, the plain loop's arithmetic), so the
7007        // text is the plain path's and only the round's shape changes.
7008        // Measured on this M4 — see the report for the interleaved run.
7009        //
7010        // On the CUDA hybrid arm a suppress list alone (a no-think chat
7011        // masks `<think>`) does not count: it reads no history, the draft
7012        // and the verify rows mask the same ids, and the verify rows are
7013        // the plain rows bit for bit, so the round (`greedy_pen`) keeps the
7014        // plain text. Qwen3.8-27B q4tp, RTX 3090, a no-think chat over
7015        // `cortiq serve`: 44.8 tok/s plain before this.
7016        let suppress_only_ok = crate::gpu::cuda_active()
7017            && self.sampler_config.repetition_penalty == 1.0
7018            && self.sampler_config.presence_penalty == 0.0;
7019        let penalized = !metal_graph
7020            && (self.sampler_config.repetition_penalty != 1.0
7021                || self.sampler_config.presence_penalty != 0.0
7022                || (!self.sampler_config.suppress_tokens.is_empty() && !suppress_only_ok));
7023        // …and not on wgpu-over-Metal: the batched verify graph there
7024        // returned 0 accepted drafts and garbage text on a GDN hybrid
7025        // (16.08, Qwen3.5-0.8B) while Vulkan is bit-exact; the Mac's
7026        // default backend is native Metal without a batch graph anyway.
7027        #[cfg(feature = "gpu")]
7028        let metal_wgpu = graph_on && crate::gpu_wgpu::wgpu_backend_is_metal();
7029        #[cfg(not(feature = "gpu"))]
7030        let metal_wgpu = false;
7031        let spec_env = std::env::var("CMF_GRAPH_SPEC").ok();
7032        let spec_wanted = graph_spec_wanted_by_policy(
7033            spec_env.as_deref(),
7034            spec_default_ok,
7035            penalized,
7036            metal_wgpu,
7037            native_metal_backend,
7038        );
7039        if spec_wanted && metal_wgpu {
7040            tracing::warn!(
7041                "CMF_GRAPH_SPEC forced on wgpu/Metal: the batched verify graph is not \
7042                 verified on this backend (garbage measured on Qwen3.5-0.8B)"
7043            );
7044        }
7045        // Native Metal: the b-row verify graph (`try_batch_graph_metal`)
7046        // stands where the wgpu batch graph stands on discrete cards
7047        // (`metal_graph`, above).
7048        // A dynamic router reads φ and may switch skills after every token;
7049        // a speculative round commits several tokens per φ, so the router
7050        // wins (on the host the drafts are off for it already: no graph).
7051        let graph_spec = self.speculative
7052            && (graph_on || metal_graph)
7053            && self.mtp.is_some()
7054            && task_mask.is_none()
7055            && self.dyn_router.is_none()
7056            && (!self.o1_active() || self.o1_spec())
7057            && spec_sampling_ok
7058            && spec_wanted;
7059        // A trunk without a draft block of its own (Ripple): a DFlash sidecar
7060        // drafts a round in one block and the batch graph verifies it, the
7061        // rows of drafts that did not hold let go. Plain greedy only, so the
7062        // text is the plain path's. `CMF_GRAPH_SPEC=0` keeps plain tokens.
7063        #[cfg(feature = "gpu")]
7064        let solo_spec = self.speculative
7065            && graph_on
7066            && !metal_wgpu
7067            && self.mtp.is_none()
7068            && task_mask.is_none()
7069            && self.dyn_router.is_none()
7070            && (!self.o1_active() || self.o1_spec())
7071            && self.sampler_config.temperature < 1e-6
7072            && !penalized
7073            && spec_env.as_deref() != Some("0")
7074            && (self.dflash.is_some() || solo_script().is_some());
7075        #[cfg(feature = "gpu")]
7076        let solo_pin: Option<usize> =
7077            std::env::var("CMF_GRAPH_SPEC_K").ok().and_then(|v| v.parse().ok()).filter(|k| (1..=SOLO_K_MOST).contains(k));
7078        #[cfg(feature = "gpu")]
7079        let mut solo =
7080            SoloSpec { k: solo_pin.unwrap_or(4), rest: 3, back: SOLO_REST, plain_ms: 0.0, plain_n: 0, round_ms: 0.0, rounds: 0, win_ms: 0.0, win_tok: 0, last: None, first: true };
7081        // The host fused pair is an optimization, not a verifier. On real
7082        // q4tp Qwen3.5 a near-tied row produced a different greedy argmax
7083        // from two serial target forwards. That makes a seemingly accepted
7084        // draft change text, which is worse than losing speculative speed.
7085        // Keep it explicitly experimental until a model/backend has passed
7086        // a long exact-ID gate; the native Metal batch verifier has its own
7087        // separate graph admission and is not controlled by this switch.
7088        //
7089        // GDN hybrids are also excluded by default: their recurrence is
7090        // sequential, so the pair lane cannot parallelize and measured 2x
7091        // slower on the 35B. `CMF_MTP_PAIR=1` is deliberately the only
7092        // opt-in for the host fused-pair experiment (not `CMF_MTP=1`).
7093        let host_pair_opt_in = std::env::var("CMF_MTP_PAIR").as_deref() == Ok("1");
7094        let pair_pays = host_pair_opt_in
7095            && (self.gdn_cfg.is_none() || std::env::var("CMF_MTP").as_deref() == Ok("1"));
7096        // Native Metal: say the route ONCE (RUST_LOG=info), including why
7097        // the drafts are off when they are (`graph_spec_wanted_by_policy`).
7098        #[cfg(target_os = "macos")]
7099        if metal_graph {
7100            static SAID: std::sync::Once = std::sync::Once::new();
7101            SAID.call_once(|| {
7102                let spec = if graph_spec {
7103                    let k = std::env::var("CMF_GRAPH_SPEC_K")
7104                        .ok()
7105                        .and_then(|v| v.parse::<usize>().ok())
7106                        .filter(|&v| (1..=8).contains(&v))
7107                        .map(|v| v.to_string())
7108                        .unwrap_or_else(|| {
7109                            if self.metal_small_batch_verify() {
7110                                "auto".to_string()
7111                            } else {
7112                                "7".to_string()
7113                            }
7114                        });
7115                    let arm = if self.sampler_config.temperature < 1e-6 {
7116                        "greedy"
7117                    } else {
7118                        "sampling"
7119                    };
7120                    format!(
7121                        "spec k={k} {arm} (batched verify, draft shortlist {}, trial: proxy)",
7122                        Self::draft_vocab_rows(usize::MAX)
7123                    )
7124                } else if !self.speculative {
7125                    "spec off (CMF_MTP=0)".to_string()
7126                } else if self.mtp.is_none() {
7127                    "spec off (no MTP head)".to_string()
7128                } else if !spec_sampling_ok {
7129                    if spec_cheap_round {
7130                        "spec off (CMF_GRAPH_SPEC_SAMPLE=0)".to_string()
7131                    } else {
7132                        "spec off (sampling without a top-k: the dense chain \
7133                         costs more than it saves)"
7134                            .to_string()
7135                    }
7136                } else if !spec_wanted {
7137                    if spec_env.as_deref() == Some("0") {
7138                        "spec off (CMF_GRAPH_SPEC=0)".to_string()
7139                    } else {
7140                        "spec off (drafts by default only over a q4tp trunk; CMF_GRAPH_SPEC=1 asks for them)".to_string()
7141                    }
7142                } else if task_mask.is_some() {
7143                    "spec off (task mask)".to_string()
7144                } else if !graph_spec && !pair_pays {
7145                    "spec off (host fused pair requires CMF_MTP_PAIR=1 after exact-ID validation)"
7146                        .to_string()
7147                } else {
7148                    "spec off (O(1) attention)".to_string()
7149                };
7150                let on = |var: &str| {
7151                    if std::env::var(var).as_deref() == Ok("0") {
7152                        "off"
7153                    } else {
7154                        "on"
7155                    }
7156                };
7157                tracing::info!(
7158                    "metal native: {spec}, state4 {}, async replay {}, prefill graph {}, \
7159                     MTP graph {}, attend {}, probe {}",
7160                    if crate::gpu_metal::state4_on() {
7161                        "on"
7162                    } else {
7163                        "off"
7164                    },
7165                    if crate::gpu_metal::async_replay_on() {
7166                        "on"
7167                    } else {
7168                        "off"
7169                    },
7170                    on("CMF_METAL_PREFILL"),
7171                    on("CMF_MTP_GRAPH"),
7172                    std::env::var("CMF_GPU_ATTEND").unwrap_or_else(|_| "auto".into()),
7173                    if crate::gpu::probe_enabled() {
7174                        "bypassed (q1 force)"
7175                    } else {
7176                        "off"
7177                    },
7178                );
7179            });
7180        }
7181        let spec_active = self.speculative
7182            && self.mtp.is_some()
7183            && task_mask.is_none()
7184            && self.dyn_router.is_none()
7185            && (!self.o1_active() || self.o1_spec())
7186            && ((!graph_on && pair_pays && self.sampler_config.temperature < 1e-6) || graph_spec);
7187        // The MTP module is detached during generation so its mutable
7188        // state does not fight the borrow on `self`.
7189        let mut mtp = if spec_active { self.mtp.take() } else { None };
7190        if std::env::var("CMF_MTP_CHAIN_PROBE").is_ok() {
7191            eprintln!(
7192                "mtp-probe gate: spec_active={spec_active} mtp={} speculative={} graph_on={graph_on} temp_ok={}",
7193                mtp.is_some(),
7194                self.speculative,
7195                self.sampler_config.temperature < 1e-6,
7196            );
7197        }
7198        if let Some(m) = &mut mtp {
7199            let kept = mtp_keep.is_some_and(|rows| {
7200                crate::gpu::graph_kv_set_stored(self.mtp_kv_id(), Self::MTP_LAYER_BASE, rows)
7201            });
7202            if kept {
7203                let rows = mtp_keep.unwrap_or(0);
7204                let d = m.kv.pos_len().saturating_sub(rows);
7205                if d > 0 {
7206                    m.kv.truncate_last(d);
7207                }
7208            } else {
7209                m.kv.clear();
7210                // The MTP block's own device mirror starts over with its cache.
7211                crate::gpu::graph_kv_reset(self.mtp_kv_id());
7212                if mtp_keep.is_some() {
7213                    // nothing kept: the head reads from the snapshot on
7214                    self.mtp_pos_base = reuse_from;
7215                }
7216            }
7217            self.mtp_graph_mode = None;
7218        }
7219        // MiMo-V2's draft stack: greedy rounds (draft K with the chained
7220        // MTP layers, verify K+1 rows in one batched forward). Sampling
7221        // decodes plain; `CMF_MTP=0` / `CMF_MIMO_MTP=0` turn it off.
7222        let mimo_spec = self.speculative
7223            && self.mimo_mtp.is_some()
7224            && task_mask.is_none()
7225            && !self.o1_active()
7226            && self.dyn_router.is_none()
7227            && self.sampler_config.temperature < 1e-6
7228            && std::env::var("CMF_MIMO_MTP").as_deref() != Ok("0");
7229        if let Some(st) = self.mimo_mtp.as_mut() {
7230            st.reset();
7231            if mimo_spec && std::env::var_os("CMF_MIMO_MTP_PROBE").is_some() {
7232                Self::mimo_mtp_hist_cap(st, input_ids.len());
7233            }
7234        }
7235        // Dynamic router detached during decode (same borrow trick as MTP).
7236        // Speculative decode and dynamic routing are mutually exclusive
7237        // for now — the fused-pair path doesn't carry per-token φ.
7238        let mut router = if mtp.is_none() {
7239            self.dyn_router.take()
7240        } else {
7241            None
7242        };
7243        let mut reuse_from = reuse_from;
7244        if let Some(r) = &mut router {
7245            r.reset(); // active=backbone, matching a fresh overlay
7246            self.dyn_phi_seen = 0; // fresh φ EMA per generation
7247            if self.dyn_active.is_some() {
7248                // A real switch back to the backbone invalidates the
7249                // cache the reuse key was computed against.
7250                let _ = self.set_active_skill(None);
7251                reuse_from = 0;
7252                self.last_prefill_tokens = input_ids.len();
7253            }
7254        }
7255
7256        let mut all_ids = input_ids.to_vec();
7257        // A block-diffusion model's response penalties count the response
7258        // only (`CloverPenaltyState`), never the prompt.
7259        let penalty_from = if self.clover.is_some() { input_ids.len() } else { 0 };
7260        let mut generated = 0usize;
7261        let mut finish_reason = "max_tokens".to_string();
7262        let mut drafted = 0usize;
7263        let mut accepted = 0usize;
7264        // DeepSeek-V4's draft quality is strongly content-dependent.  Two
7265        // consecutive paid rounds with no extra token put it on a bounded
7266        // cooldown; predictable text keeps batching, ordinary prose falls
7267        // back to the exact walk instead of paying a slow draft forever.
7268        // Local to one generation so one difficult request cannot poison the
7269        // next one, and deliberately automatic — this is not a user knob.
7270        let mut dsv4_spec_bad = 0usize;
7271        let mut dsv4_spec_retry_at = 0usize;
7272        let mut confidence: Vec<f32> = Vec::new();
7273        let trace_on = self.trace;
7274        let calib_temp = self.calib_temp;
7275        let mut traces: Vec<TokenTrace> = Vec::new();
7276
7277        // ── Prefill: forward each prompt token once, KEEP the last hidden.
7278        //    Dense prefill runs in fused pairs (weights streamed once per
7279        //    two positions — bit-identical to sequential, proven by the
7280        //    pair tests). With MTP: warm the draft head on
7281        //    (hidden_p, token_{p+1}) pairs.
7282        let mut hidden = vec![0.0f32; self.hidden_size];
7283        let mut pos = reuse_from;
7284        // lm_head-in-graph is only sound when the very next logits
7285        // consumer is this loop's own (MTP and skill routing interleave
7286        // other forwards / can swap lm_head between forward and sample).
7287        // CMF_GPU_LMHEAD=0 keeps lm_head off the graph: the token reads back
7288        // the 8 KB hidden instead of ~1 MB of logits, and the head runs on
7289        // the host. A probe for how much of the graph's fixed per-token cost
7290        // is the logits readback (the layer sweep puts that fixed part at
7291        // 3.88 ms of an 18.5 ms frame).
7292        let fuse_lm = mtp.is_none()
7293            && router.is_none()
7294            && std::env::var("CMF_GPU_LMHEAD").as_deref() != Ok("0");
7295        self.graph_logits = None;
7296        self.graph_want_logits = false;
7297        let _tpf = std::time::Instant::now();
7298        let batch_k = self.generation_batch_k();
7299        if let Some(rows) = prompt_rows {
7300            let hs = self.hidden_size;
7301            // The batched graph's row count when the prompt rides it.
7302            let chunk = if batch_k > 0 { batch_k } else { self.prefill_chunk().max(1) };
7303            while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
7304                let end = (pos + chunk).min(input_ids.len());
7305                let hb = match self.prefill_input_rows(
7306                    PrefillIn::Hidden(&rows[pos * hs..end * hs]),
7307                    pos,
7308                    task_mask,
7309                ) {
7310                    Ok(hb) => hb,
7311                    Err(err) => {
7312                        self.prompt_mrope = None;
7313                        self.finish_generation(&mut mtp, &mut router, true);
7314                        return Err(err);
7315                    }
7316                };
7317                if mimo_spec {
7318                    self.mimo_note_rows(&hb, pos);
7319                }
7320                hidden.copy_from_slice(&hb[hb.len() - hs..]);
7321                pos = end;
7322            }
7323        }
7324        // The prompt's MRoPE rows are in the cache; decode positions are
7325        // plain (`sensenova::mrope_positions` shifted them so).
7326        self.prompt_mrope = None;
7327        // DeepSeek-V4 owns a separate hyper-connection stack. Route it
7328        // before the generic prefill choices: those correctly reject an
7329        // empty `weights.layers`, but their final per-position fallback used
7330        // to consume the whole prompt before `dsv4::forward_chunk` could see
7331        // it. The batch implementation therefore existed without a live
7332        // production entry point.
7333        //
7334        // Bounded chunks preserve cancellation responsiveness. Only the
7335        // prompt's final chunk asks for logits; every earlier head projection
7336        // would produce 129 280 values that no caller reads.
7337        // GLM-5.3-Flash runs its own mHC / KDA / DSA stack: the prompt on the
7338        // card's batch graph when it takes it, else a token at a time.
7339        if mtp.is_none() && pos + 1 < input_ids.len() {
7340            let mut lg = Vec::new();
7341            let taken = match &mut self.glm5_next {
7342                Some(b) => crate::glm5_next::forward_prompt(&b.0, &b.1, &b.2, &mut b.3, &input_ids[pos..], pos, self.pool.as_deref(), &mut lg),
7343                None => 0,
7344            };
7345            if taken > 0 {
7346                pos += taken;
7347                if pos == input_ids.len() {
7348                    self.graph_logits = Some(lg);
7349                }
7350                hidden.fill(0.0);
7351            }
7352        }
7353        while self.glm5_next.is_some()
7354            && mtp.is_none()
7355            && pos < input_ids.len()
7356            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
7357        {
7358            let token_id = input_ids[pos];
7359            let want_logits = pos + 1 == input_ids.len();
7360            let mut lg = Vec::new();
7361            if let Some(b) = &mut self.glm5_next {
7362                crate::glm5_next::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, pos, self.pool.as_deref(), &mut lg, want_logits);
7363            }
7364            if want_logits {
7365                self.graph_logits = Some(lg);
7366            }
7367            pos += 1;
7368            hidden.fill(0.0);
7369        }
7370        // Hy4-flash: its own iHC / MLA / Engram stack; the prompt on the
7371        // card's batch graph when it takes it, else a token at a time.
7372        if mtp.is_none() && pos + 1 < input_ids.len() {
7373            let mut lg = Vec::new();
7374            let taken = match &mut self.hy4 {
7375                Some(b) => crate::hy4::forward_prompt(&b.0, &b.1, &b.2, &mut b.3, &input_ids[pos..], pos, self.pool.as_deref(), &mut lg),
7376                None => 0,
7377            };
7378            if taken > 0 {
7379                pos += taken;
7380                if pos == input_ids.len() {
7381                    self.graph_logits = Some(lg);
7382                }
7383                hidden.fill(0.0);
7384            }
7385        }
7386        while self.hy4.is_some()
7387            && mtp.is_none()
7388            && pos < input_ids.len()
7389            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
7390        {
7391            let token_id = input_ids[pos];
7392            let want_logits = pos + 1 == input_ids.len();
7393            let mut lg = Vec::new();
7394            if let Some(b) = &mut self.hy4 {
7395                crate::hy4::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, pos, self.pool.as_deref(), &mut lg, want_logits);
7396            }
7397            if want_logits {
7398                self.graph_logits = Some(lg);
7399            }
7400            pos += 1;
7401            hidden.fill(0.0);
7402        }
7403        // Maxwell-V1-Flash: its own mHC stack; the prompt on the card's
7404        // batch graph when it takes it, else a token at a time.
7405        if mtp.is_none() && pos + 1 < input_ids.len() {
7406            let mut lg = Vec::new();
7407            let taken = match &mut self.maxwell {
7408                Some(b) => crate::maxwell::forward_prompt(&b.0, &b.1, &b.2, &mut b.3, &input_ids[pos..], pos, self.pool.as_deref(), &mut lg),
7409                None => 0,
7410            };
7411            if taken > 0 {
7412                pos += taken;
7413                if pos == input_ids.len() {
7414                    self.graph_logits = Some(lg);
7415                }
7416                hidden.fill(0.0);
7417            }
7418        }
7419        while self.maxwell.is_some()
7420            && mtp.is_none()
7421            && pos < input_ids.len()
7422            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
7423        {
7424            let token_id = input_ids[pos];
7425            let want_logits = pos + 1 == input_ids.len();
7426            let mut lg = Vec::new();
7427            if let Some(b) = &mut self.maxwell {
7428                crate::maxwell::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, pos, self.pool.as_deref(), &mut lg, want_logits);
7429            }
7430            if want_logits {
7431                self.graph_logits = Some(lg);
7432            }
7433            pos += 1;
7434            hidden.fill(0.0);
7435        }
7436        // Inkling-2-Mini: its own looped stack; the prompt on the
7437        // card's batch graph when it takes it, else a token at a time.
7438        if mtp.is_none() && pos + 1 < input_ids.len() {
7439            let mut lg = Vec::new();
7440            let taken = match &mut self.inkling {
7441                Some(b) => crate::inkling::forward_prompt(&b.0, &b.1, &b.2, &mut b.3, &input_ids[pos..], pos, self.pool.as_deref(), &mut lg),
7442                None => 0,
7443            };
7444            if taken > 0 {
7445                pos += taken;
7446                if pos == input_ids.len() {
7447                    self.graph_logits = Some(lg);
7448                }
7449                hidden.fill(0.0);
7450            }
7451        }
7452        while self.inkling.is_some()
7453            && mtp.is_none()
7454            && pos < input_ids.len()
7455            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
7456        {
7457            let token_id = input_ids[pos];
7458            let want_logits = pos + 1 == input_ids.len();
7459            let mut lg = Vec::new();
7460            if let Some(b) = &mut self.inkling {
7461                crate::inkling::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, pos, self.pool.as_deref(), &mut lg, want_logits);
7462            }
7463            if want_logits {
7464                self.graph_logits = Some(lg);
7465            }
7466            pos += 1;
7467            hidden.fill(0.0);
7468        }
7469        while self.qwen4_exp.is_some()
7470            && mtp.is_none()
7471            && pos < input_ids.len()
7472            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
7473        {
7474            // The device path takes several prompt tokens per layer frame;
7475            // the host path runs them one by one inside the same call.
7476            let end = (pos + crate::qwen4_exp::prefill_chunk()).min(input_ids.len());
7477            let want_logits = end == input_ids.len();
7478            let mut lg = Vec::new();
7479            if let Some(b) = &mut self.qwen4_exp {
7480                crate::qwen4_exp::forward_tokens(
7481                    &b.0,
7482                    &b.1,
7483                    &b.2,
7484                    &mut b.3,
7485                    &input_ids[pos..end],
7486                    pos,
7487                    &self.inv_freq,
7488                    self.pool.as_deref(),
7489                    &mut lg,
7490                    want_logits,
7491                );
7492            }
7493            if want_logits {
7494                self.graph_logits = Some(lg);
7495            }
7496            pos = end;
7497            hidden.fill(0.0);
7498        }
7499        while self.dsv4.is_some()
7500            && mtp.is_none()
7501            && pos < input_ids.len()
7502            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
7503        {
7504            let end = (pos + prefill_chunk()).min(input_ids.len());
7505            let ids: Vec<u32> = input_ids[pos..end].to_vec();
7506            let mut lg = Vec::new();
7507            if let Some(b) = &mut self.dsv4 {
7508                let (g, layers, cfg, st) = (&b.0, &b.1, b.2, &mut b.3);
7509                crate::dsv4::forward_chunk(
7510                    g,
7511                    layers,
7512                    &cfg,
7513                    st,
7514                    &ids,
7515                    pos,
7516                    &self.inv_freq,
7517                    self.pool.as_deref(),
7518                    &mut lg,
7519                    end == input_ids.len(),
7520                );
7521            }
7522            if end == input_ids.len() {
7523                self.graph_logits = Some(lg);
7524            }
7525            pos = end;
7526            hidden = vec![0.0; self.hidden_size];
7527        }
7528        if self.dory.is_some() && mtp.is_none() && pos < input_ids.len() {
7529            let lg = self.dory_forward(&input_ids[pos..], pos, crate::dory::Want::Last);
7530            self.graph_logits = Some(lg);
7531            pos = input_ids.len();
7532            hidden = vec![0.0; self.hidden_size];
7533        }
7534        let dsv41_prefill = self.dsv41_prefill.take();
7535        while self.dsv41.is_some()
7536            && mtp.is_none()
7537            && pos < input_ids.len()
7538            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
7539        {
7540            let end = (pos + prefill_chunk()).min(input_ids.len());
7541            let ids: Vec<u32> = input_ids[pos..end].to_vec();
7542            let mut lg = Vec::new();
7543            if let Some(b) = &mut self.dsv41 {
7544                let (g, layers, cfg, st) = (&b.0, &b.1, &b.2, &mut b.3);
7545                if let Some((embeddings, participates)) = dsv41_prefill.as_ref() {
7546                    crate::dsv41::forward_chunk_masked_with_embeddings(
7547                        g,
7548                        layers,
7549                        cfg,
7550                        st,
7551                        &ids,
7552                        pos,
7553                        &embeddings[pos..end],
7554                        &participates[pos..end],
7555                        self.pool.as_deref(),
7556                        &mut lg,
7557                    );
7558                } else {
7559                    crate::dsv41::forward_chunk(
7560                        g,
7561                        layers,
7562                        cfg,
7563                        st,
7564                        &ids,
7565                        pos,
7566                        self.pool.as_deref(),
7567                        &mut lg,
7568                    );
7569                }
7570            }
7571            if end == input_ids.len() {
7572                self.graph_logits = Some(lg);
7573            }
7574            pos = end;
7575            hidden = vec![0.0; self.hidden_size];
7576        }
7577        // With dynamic routing, prefill sequentially so the φ hook fires
7578        // over the PROMPT — the router enters decode with a warm φ (the
7579        // fused-pair path skips the per-layer φ capture). o1 layers
7580        // collect their query trace in both the single and pair paths.
7581        let dyn_prefill = router.is_some();
7582        // On CUDA the batch graph keeps the router layer's rows of every
7583        // prompt chunk (`dyn_phi_tap`): the prompt reads batched and φ still
7584        // takes every position in order.
7585        let dyn_batch = dyn_prefill && crate::gpu::cuda_active();
7586        // Optional bounded calibration prefix for generation.  The normal
7587        // O(1) path seals after the full prompt; this explicit knob instead
7588        // runs only the requested prefix through exact attention, seals the
7589        // Nyström state, and streams the rest of the prompt through the same
7590        // O(1) step used by decode.  It keeps the O(1) layers' Q trace and
7591        // temporary full KV bounded by the prefix while leaving the default
7592        // full-prompt quality profile untouched.
7593        let o1_prefill_limit = o1_prefill
7594            .and_then(|requested| self.o1_effective_boundary(requested))
7595            .map(|boundary| boundary.min(input_ids.len()));
7596        let mut o1_sealed = false;
7597        let mut o1_arch: Option<O1Archive> = None;
7598        if let Some(limit) = o1_prefill_limit {
7599            // On the device route the prefix takes the batch graph and its
7600            // sealed suffix the O(1) batches after it (`o1_prefix_on_graph`):
7601            // the host walk read it at 16 tok/s on Qwen3.8-27B / A40, 33 s
7602            // of a 72 s TTFT at 4k. Only when a suffix follows — a prompt
7603            // inside the boundary stays exact on the host as before.
7604            // `CMF_O1_PREFIX_GPU=0` keeps the host prefill.
7605            if pos == 0
7606                && limit < input_ids.len()
7607                && batch_k > 0
7608                && task_mask.is_none()
7609                && (mtp.is_none() || self.o1_spec())
7610                && !dyn_prefill
7611                && self.o1_on_graph()
7612                && std::env::var("CMF_O1_PREFIX_GPU").as_deref() != Ok("0")
7613                // One cache per executed layer: a looped stack whose visits keep
7614                // their own rows (SenseNova-Loop) indexes caches, mirrors and the
7615                // query capture by the visit, as a plain stack does by the layer.
7616                && self.kv_cache.layers.len() == self.num_layers
7617            {
7618                let t_px = std::time::Instant::now();
7619                // More of the prompt than the first seal covers: its rows stay in host
7620                // memory, and the far field is built anew before the prompt's last rows.
7621                let tail_from = input_ids.len().saturating_sub(crate::dory::EXACT_TAIL);
7622                if limit < tail_from && self.o1_exact_cfg().is_some() {
7623                    o1_arch = Some(O1Archive::new());
7624                }
7625                // Without a Metal rows graph (Spark-X2.6: GELU, per-head gates, sliding
7626                // windows) the sealed rows would go one position at a time: 14 000 tokens
7627                // on the M4 took 219 s. The chunk graph reads the whole prompt exact
7628                // instead, and the seal after it chooses among all of its rows, with the
7629                // question's queries in the trace.
7630                #[cfg(target_os = "macos")]
7631                let px_len = if crate::gpu::q1_force() && o1_arch.is_some() && self.metal_rows_plan().is_none() {
7632                    o1_arch = None;
7633                    let n = input_ids.len();
7634                    for li in 0..self.num_layers {
7635                        if self.o1_flags.get(li).copied().unwrap_or(false) {
7636                            self.kv_cache.layers[li].o1_set_boundary(n);
7637                        }
7638                    }
7639                    n
7640                } else {
7641                    limit
7642                };
7643                #[cfg(not(target_os = "macos"))]
7644                let px_len = if self.o1_whole_prompt() {
7645                    o1_arch = None;
7646                    let n = input_ids.len();
7647                    for li in 0..self.num_layers {
7648                        if self.o1_flags.get(li).copied().unwrap_or(false) {
7649                            self.kv_cache.layers[li].o1_set_boundary(n);
7650                        }
7651                    }
7652                    n
7653                } else {
7654                    limit
7655                };
7656                #[cfg(target_os = "macos")]
7657                let prefix = if crate::gpu::q1_force() {
7658                    self.o1_prefix_on_metal(&input_ids[..px_len], batch_k, o1_arch.as_mut())
7659                } else {
7660                    self.o1_prefix_on_graph(&input_ids[..px_len], batch_k, o1_arch.as_mut())
7661                };
7662                #[cfg(not(target_os = "macos"))]
7663                let prefix = {
7664                    // the CUDA mirrors take the whole prompt at the first chunk
7665                    let hint = crate::gpu::cuda_active();
7666                    if hint {
7667                        crate::gpu::set_batch_kv_hint(px_len + 1);
7668                    }
7669                    let r = self.o1_prefix_on_graph(&input_ids[..px_len], batch_k, o1_arch.as_mut());
7670                    if hint {
7671                        crate::gpu::set_batch_kv_hint(0);
7672                    }
7673                    r
7674                };
7675                match prefix {
7676                    Ok(Some(last)) => {
7677                        hidden.copy_from_slice(&last);
7678                        pos = px_len;
7679                        // the whole prompt went by the prefix (CUDA): the draft head
7680                        // reads its tail, as over the wgpu path's far field
7681                        let tail = std::mem::take(&mut self.o1_prefix_tail);
7682                        if px_len == input_ids.len() && mtp.is_some() && !tail.is_empty() {
7683                            let hs = self.hidden_size;
7684                            let from = px_len - tail.len() / hs;
7685                            self.mtp_pos_base = from;
7686                            let n_pairs = mtp_prefill_pair_count(from, px_len, input_ids.len());
7687                            let pairs: Vec<(&[f32], u32)> = (0..n_pairs).map(|j| (&tail[j * hs..(j + 1) * hs], input_ids[from + j + 1])).collect();
7688                            let warm_error = if let Some(m) = mtp.as_mut() { self.mtp_warm_prefill_pairs(m, &pairs, from).err() } else { None };
7689                            if let Some(err) = warm_error {
7690                                self.finish_generation(&mut mtp, &mut router, true);
7691                                return Err(err.to_string());
7692                            }
7693                            self.mtp_warm_base = Some(from);
7694                        }
7695                        if std::env::var("CMF_PREFILL_PROF").is_ok() {
7696                            eprintln!(
7697                                "o1 prefix on the batch graph: {px_len} rows in {:.1} ms",
7698                                t_px.elapsed().as_secs_f64() * 1e3
7699                            );
7700                        }
7701                    }
7702                    Ok(None) => {}
7703                    Err(err) => {
7704                        self.finish_generation(&mut mtp, &mut router, true);
7705                        return Err(err);
7706                    }
7707                }
7708            }
7709            // Without the device route (LFM2's short convolutions on Metal) the rows
7710            // past the first seal would stream into the far field unchosen. With exact
7711            // rows wanted, the host keeps the prompt exact up to its last rows and
7712            // chooses among all of them there, as the archive does on the device.
7713            let tail_from = input_ids.len().saturating_sub(crate::dory::EXACT_TAIL);
7714            let limit = if pos == 0 && limit < tail_from && self.o1_exact_cfg().is_some() {
7715                o1_arch = None;
7716                for li in 0..self.num_layers {
7717                    if self.o1_flags.get(li).copied().unwrap_or(false) {
7718                        self.kv_cache.layers[li].o1_set_boundary(tail_from);
7719                    }
7720                }
7721                tracing::info!("o1: no device prefix; exact on the host up to row {tail_from}, then the seal");
7722                tail_from
7723            } else {
7724                limit
7725            };
7726            // Reuse the exact batched prefix machinery when available; it
7727            // records the same per-position Q trace as the full prefill.
7728            if pos < limit && self.can_prefill_batched() && limit > 2 {
7729                let chunk = self.prefill_chunk();
7730                let hs = self.hidden_size;
7731                while pos < limit && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
7732                    let end = (pos + chunk).min(limit);
7733                    let hb = self.prefill_batch(&input_ids[pos..end], pos);
7734                    hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
7735                    pos = end;
7736                }
7737            } else {
7738                while pos < limit && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
7739                    hidden = self.forward_layers(&self.embed_single(input_ids[pos]), pos, None);
7740                    pos += 1;
7741                }
7742            }
7743            if pos >= limit {
7744                o1_sealed = match self.o1_seal_checked() {
7745                    Ok(sealed) => sealed,
7746                    Err(err) => {
7747                        self.finish_generation(&mut mtp, &mut router, true);
7748                        return Err(err);
7749                    }
7750                };
7751                // Sealed layers read no mirror again: their rows leave the memory they share
7752                // with everything else on a Mac.
7753                #[cfg(target_os = "macos")]
7754                if o1_sealed && crate::gpu::q1_force() {
7755                    crate::gpu_metal::kv_mirror_drop(self.graph_kv_id);
7756                }
7757                tracing::info!(
7758                    "o1 bounded prompt prefix: requested={} effective={} processed={} of {} token(s)",
7759                    o1_prefill.unwrap_or(0),
7760                    self.o1_effective_boundary(o1_prefill.unwrap_or(0))
7761                        .unwrap_or(limit),
7762                    limit,
7763                    input_ids.len()
7764                );
7765            }
7766        }
7767        // q1 hybrids on Metal: the per-position GPU token graph beats
7768        // the CPU chunk-GEMM (whose wall is the sequential scalar GDN
7769        // recurrence), so prefill goes position-by-position through the
7770        // same graph as decode. Pure-attention models keep the batched
7771        // path — there the chunk-GEMM amortization wins.
7772        let graph_prefill = self.graph_prefill_preferred();
7773        // Native Metal, q4tp GDN hybrids: the prompt through the b-row
7774        // rows graph — projections as GEMMs over up to 512 positions, the
7775        // GDN recurrence in registers on the device, K/V rows appended by
7776        // the chunk — instead of one token-graph submit per position (the
7777        // 27B: 8 tok/s → GEMM-bound). The MTP warm-up rows come out of one
7778        // batched run of the block per chunk. Any refusal leaves the rest
7779        // of the prompt to the sequential paths below. Pure-attention
7780        // models take it too (the plan admits their layers): CherryPit-1.2-2B
7781        // read an 8 192-token prompt on the M4 in 31 s instead of the host
7782        // walk's 58 s (q4tp; q8_2f 34 s against 55), at the same WikiText-2
7783        // ppl. `CMF_METAL_PREFILL=0` keeps the host walk.
7784        #[cfg(target_os = "macos")]
7785        if task_mask.is_none()
7786            && !dyn_prefill
7787            && !o1_sealed
7788            && (crate::gpu::q1_force() || crate::gpu::q2tp_gpu_opt_in())
7789            && crate::gpu::enabled_here()
7790            && !self.per_token_stack()
7791            && input_ids.len() > 8
7792            && std::env::var("CMF_MTP_CHAIN_PROBE").is_err()
7793            && std::env::var("CMF_METAL_PREFILL").as_deref() != Ok("0")
7794        {
7795            let chunk: usize = std::env::var("CMF_METAL_PREFILL_CHUNK")
7796                .ok()
7797                .and_then(|v| v.parse().ok())
7798                .filter(|&v| (16..=512).contains(&v))
7799                // The ANE's weights go once a chunk: a larger one pays them over more rows.
7800                .unwrap_or(if crate::gpu_metal::ane::wanted() { 512 } else { 256 });
7801            let hs = self.hidden_size;
7802            let _tp = std::time::Instant::now();
7803            while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
7804                let end = (pos + chunk).min(input_ids.len());
7805                let hb = match self.prefill_batch_metal(&input_ids[pos..end], pos) {
7806                    MetalPrefillOutcome::Completed(hb) => hb,
7807                    MetalPrefillOutcome::Declined => break,
7808                    MetalPrefillOutcome::Failed => {
7809                        self.finish_generation(&mut mtp, &mut router, true);
7810                        return Err("ordinary Metal prefill failed after admission".into());
7811                    }
7812                };
7813                if let Some(m) = &mut mtp {
7814                    let n_pairs = if end < input_ids.len() {
7815                        end - pos
7816                    } else {
7817                        end - pos - 1
7818                    };
7819                    if n_pairs > 0 {
7820                        let pairs: Vec<(&[f32], u32)> = (0..n_pairs)
7821                            .map(|j| (&hb[j * hs..(j + 1) * hs], input_ids[pos + j + 1]))
7822                            .collect();
7823                        if !self.mtp_warm_batch_metal(m, &pairs, pos) {
7824                            for (j, (h, t)) in pairs.iter().enumerate() {
7825                                let h = h.to_vec();
7826                                let _ = self.mtp_step(m, &h, *t, pos + j);
7827                            }
7828                        }
7829                    }
7830                }
7831                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
7832                pos = end;
7833            }
7834            if std::env::var("CMF_PREFILL_PROF").is_ok() {
7835                eprintln!(
7836                    "metal-prefill: {} of {} tokens in {:.1} ms",
7837                    pos,
7838                    input_ids.len(),
7839                    _tp.elapsed().as_secs_f64() * 1e3
7840                );
7841                // Per-stage GPU time of the rows graph (`CMF_VERIFY_CUT=1`).
7842                crate::gpu_metal::cut_report();
7843            }
7844        }
7845        // Gemma-4 on a discrete card: the prompt through the batched wgpu
7846        // graph (`g4_batch_ingest`); its K/V land in the device mirrors
7847        // decode reads. A refusal leaves the rest of the prompt to the
7848        // chunked host prefill below.
7849        #[cfg(not(target_os = "macos"))]
7850        if task_mask.is_none()
7851            && !dyn_prefill
7852            && mtp.is_none()
7853            && o1_prefill.is_none()
7854            && batch_k > 0
7855            && pos + 1 < input_ids.len()
7856            && self.g4_batch_prefill()
7857        {
7858            let t_g4 = std::time::Instant::now();
7859            match self.g4_batch_ingest(&input_ids[pos..], pos, false) {
7860                Ok((n, last)) => {
7861                    if n > 0 {
7862                        hidden.copy_from_slice(&last);
7863                    }
7864                    if std::env::var("CMF_PREFILL_PROF").is_ok() {
7865                        eprintln!(
7866                            "gemma4 batch prefill: {n} of {} tokens in {:.1} ms",
7867                            input_ids.len() - pos,
7868                            t_g4.elapsed().as_secs_f64() * 1e3
7869                        );
7870                    }
7871                    pos += n;
7872                }
7873                Err(e) => {
7874                    self.finish_generation(&mut mtp, &mut router, true);
7875                    return Err(e);
7876                }
7877            }
7878        }
7879        self.mimo_moe_prepare();
7880        // A MoE stack larger than the card (MiMo-V2 q4tp on 96 GB): the
7881        // batched wgpu graph runs the device prefix of every chunk — its
7882        // experts resident — and the host's batched layer walk finishes
7883        // the chunk. Any refusal leaves the rest of the prompt to the
7884        // chunked prefill below.
7885        #[cfg(not(target_os = "macos"))]
7886        if task_mask.is_none()
7887            && !dyn_prefill
7888            && !graph_prefill
7889            && mtp.is_none()
7890            && o1_prefill.is_none()
7891            && !self.o1_active()
7892            && input_ids.len() > 2
7893            && self.batch_prefix_prefill()
7894        {
7895            let chunk = self.prefill_chunk().max(1);
7896            let hs = self.hidden_size;
7897            let t_bp = std::time::Instant::now();
7898            let pos0 = pos;
7899            while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
7900                let end = (pos + chunk).min(input_ids.len());
7901                let bk = end - pos;
7902                let mut hiddens = vec![0f32; bk * hs];
7903                for (j, &id) in input_ids[pos..end].iter().enumerate() {
7904                    hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
7905                }
7906                let positions: Vec<usize> = (pos..end).collect();
7907                let mut run = 0usize;
7908                let outcome = self.try_batch_graph_wgpu_prefix(
7909                    &mut hiddens,
7910                    &positions,
7911                    bk,
7912                    None,
7913                    Some(&mut run),
7914                );
7915                match outcome {
7916                    crate::gpu::BatchGraphOutcome::Completed => {
7917                        let hb = if run < self.num_layers {
7918                            self.prefill_batch_span(
7919                                PrefillIn::Hidden(&hiddens),
7920                                pos,
7921                                None,
7922                                run,
7923                                self.num_layers,
7924                            )
7925                        } else {
7926                            hiddens
7927                        };
7928                        if mimo_spec {
7929                            self.mimo_note_rows(&hb, pos);
7930                        }
7931                        hidden.copy_from_slice(&hb[(bk - 1) * hs..]);
7932                        pos = end;
7933                    }
7934                    crate::gpu::BatchGraphOutcome::Failed => {
7935                        self.finish_generation(&mut mtp, &mut router, true);
7936                        return Err("batched prefix prefill failed after admission".into());
7937                    }
7938                    crate::gpu::BatchGraphOutcome::Declined => {
7939                        // Earlier chunks left their prefix rows on the
7940                        // device only: the host walk below needs them.
7941                        #[cfg(feature = "gpu")]
7942                        if pos > pos0 {
7943                            self.pull_lagging_host_kv(0, self.num_layers, pos);
7944                        }
7945                        break;
7946                    }
7947                }
7948            }
7949            if std::env::var("CMF_PREFILL_PROF").is_ok() {
7950                eprintln!(
7951                    "batch-prefix prefill: {} of {} tokens in {:.1} ms",
7952                    pos - pos0,
7953                    input_ids.len(),
7954                    t_bp.elapsed().as_secs_f64() * 1e3
7955                );
7956            }
7957        }
7958        if task_mask.is_none()
7959            && !dyn_prefill
7960            && !graph_prefill
7961            && self.can_prefill_batched()
7962            && !self.per_token_stack()
7963            && o1_prefill.is_none()
7964            && input_ids.len() > 2
7965        {
7966            // Production prefill = the same chunked prefill-GEMM that
7967            // bench/PPL measure (roadmap §3 P0: generation used to warm
7968            // the prompt with the slower pair path — the published
7969            // prefill number didn't match real TTFT). MTP warm-up reads
7970            // each position's hidden straight from the chunk result.
7971            let chunk = self.prefill_chunk();
7972            let hs = self.hidden_size;
7973            while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
7974                let end = (pos + chunk).min(input_ids.len());
7975                let hb = self.prefill_batch(&input_ids[pos..end], pos);
7976                if mimo_spec {
7977                    self.mimo_note_rows(&hb, pos);
7978                }
7979                if let Some(m) = &mut mtp {
7980                    let probe: usize = std::env::var("CMF_MTP_CHAIN_PROBE")
7981                        .ok()
7982                        .and_then(|v| v.parse().ok())
7983                        .unwrap_or(0);
7984                    for p in pos..end {
7985                        if p + 1 < input_ids.len() {
7986                            if probe >= 1 && p + 2 < input_ids.len() {
7987                                // Teacher-forced chain acceptance (see the
7988                                // tail loop's twin): the warm-up row stays,
7989                                // the chain's rows roll back.
7990                                let (d1, mut hx) = self.mtp_step_h(
7991                                    m,
7992                                    &hb[(p - pos) * hs..(p - pos + 1) * hs],
7993                                    input_ids[p + 1],
7994                                    p,
7995                                );
7996                                let mut ok = d1 == input_ids[p + 2];
7997                                Self::chain_probe_note(0, ok);
7998                                let mut d_prev = d1;
7999                                let mut extra = 0usize;
8000                                for j in 1..probe {
8001                                    if p + 2 + j >= input_ids.len() {
8002                                        break;
8003                                    }
8004                                    let (dj, hj) = self.mtp_step_h(m, &hx, d_prev, p + 1 + j);
8005                                    extra += 1;
8006                                    ok = ok && dj == input_ids[p + 2 + j];
8007                                    Self::chain_probe_note(j, ok);
8008                                    d_prev = dj;
8009                                    hx = hj;
8010                                }
8011                                m.kv.truncate_last(extra);
8012                            } else {
8013                                let _ = self.mtp_step(
8014                                    m,
8015                                    &hb[(p - pos) * hs..(p - pos + 1) * hs],
8016                                    input_ids[p + 1],
8017                                    p,
8018                                );
8019                            }
8020                        }
8021                    }
8022                }
8023                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
8024                pos = end;
8025            }
8026        }
8027        let pair_off = std::env::var("CMF_PAIR").is_ok_and(|v| v == "0");
8028        if task_mask.is_none()
8029            && !dyn_prefill
8030            && !graph_prefill
8031            && !pair_off
8032            && self.pair_supported()
8033            && o1_prefill.is_none()
8034        {
8035            while pos + 1 < input_ids.len()
8036                && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
8037            {
8038                let e1 = self.embed_single(input_ids[pos]);
8039                let e2 = self.embed_single(input_ids[pos + 1]);
8040                let (h1, h2) = self.forward_pair(&e1, &e2, pos);
8041                if mimo_spec {
8042                    self.mimo_note_rows(&h1, pos);
8043                    self.mimo_note_rows(&h2, pos + 1);
8044                }
8045                // Both prefill tokens are real → commit lane-2 states.
8046                self.commit_linear_scratch();
8047                if let Some(m) = &mut mtp {
8048                    let _ = self.mtp_step(m, &h1, input_ids[pos + 1], pos);
8049                    if pos + 2 < input_ids.len() {
8050                        let probe: usize = std::env::var("CMF_MTP_CHAIN_PROBE")
8051                            .ok()
8052                            .and_then(|v| v.parse().ok())
8053                            .unwrap_or(0);
8054                        if probe >= 1 && pos + 3 < input_ids.len() {
8055                            // Same teacher-forced chain table as the tail
8056                            // loop below, fed from the pair path that owns
8057                            // most prefill positions.
8058                            let (d1, mut hx) = self.mtp_step_h(m, &h2, input_ids[pos + 2], pos + 1);
8059                            let mut ok = d1 == input_ids[pos + 3];
8060                            Self::chain_probe_note(0, ok);
8061                            let mut d_prev = d1;
8062                            let mut extra = 0usize;
8063                            for j in 1..probe {
8064                                if pos + 3 + j >= input_ids.len() {
8065                                    break;
8066                                }
8067                                let (dj, hj) = self.mtp_step_h(m, &hx, d_prev, pos + 2 + j);
8068                                extra += 1;
8069                                ok = ok && dj == input_ids[pos + 3 + j];
8070                                Self::chain_probe_note(j, ok);
8071                                d_prev = dj;
8072                                hx = hj;
8073                            }
8074                            m.kv.truncate_last(extra);
8075                        } else {
8076                            let _ = self.mtp_step(m, &h2, input_ids[pos + 2], pos + 1);
8077                        }
8078                    }
8079                }
8080                hidden = h2;
8081                pos += 2;
8082            }
8083        }
8084        // Batched GPU prefill for the wgpu decode graph (GDN hybrids): K prompt
8085        // positions per submit — projections/FFN as GEMMs (weight once per K),
8086        // attention/GDN looped inside — instead of one whole-graph submit per
8087        // position. Falls through to the per-position graph on any refusal.
8088        // Batched prefill is opt-in (CMF_BATCH_K>0). Default 0 = per-position
8089        // graph prefill. (Steady-state decode is provably identical either way —
8090        // token-graph submit and lm_head both unchanged — so this only trades
8091        // prefill wall.)
8092        // A bounded O(1) prefix is the one post-seal prompt interval: only
8093        // admit its batch when the device O(1) route is explicitly enabled and
8094        // every sealed layer exposes a portable view. The same batch size and
8095        // refusal behavior remain the ordinary controls/comparator.
8096        let o1_batch_ready = o1_sealed
8097            && o1_prefill.is_some()
8098            && (mtp.is_none() || self.o1_spec())
8099            && self.o1_on_graph()
8100            && (0..self.num_layers).all(|li| {
8101                let cache = &self.kv_cache.layers[self.phys_layer(li)];
8102                cache.o1.is_none() || cache.o1_views().is_some()
8103            });
8104        // The ordinary graph-prefill route can share each completed trunk
8105        // chunk with an attached MTP head.  Keep chain probing on its
8106        // established per-position path: the probe deliberately needs every
8107        // teacher-forced draft row and its rollback table.
8108        let mtp_batch_prefill = mtp.is_some()
8109            && graph_prefill
8110            && task_mask.is_none()
8111            && !dyn_prefill
8112            && !self.o1_active()
8113            && std::env::var("CMF_MTP_CHAIN_PROBE").is_err();
8114        // A hint a failed earlier prompt left behind must not size this one.
8115        #[cfg(not(target_os = "macos"))]
8116        crate::gpu::set_batch_kv_hint(0);
8117        if batch_k > 0
8118            && (graph_prefill || o1_batch_ready)
8119            && task_mask.is_none()
8120            && (!self.o1_active() || o1_batch_ready)
8121            && (mtp.is_none() || mtp_batch_prefill || o1_batch_ready)
8122            && (!dyn_prefill || dyn_batch)
8123            && pos + 1 < input_ids.len()
8124        {
8125            let hs = self.hidden_size;
8126            let chunk = batch_k;
8127            let pos_start = pos;
8128            let tail_from = input_ids.len().saturating_sub(crate::dory::EXACT_TAIL);
8129            // The K/V mirrors take the whole prompt (and its first token) at
8130            // the first chunk instead of growing on the way; cleared below.
8131            // Not under O(1): its exact mirror must stay the tail it keeps.
8132            #[cfg(not(target_os = "macos"))]
8133            if !self.o1_active() && o1_arch.is_none() && !o1_batch_ready {
8134                crate::gpu::set_batch_kv_hint(input_ids.len() + 1);
8135            }
8136            if let Some(a) = o1_arch.as_ref() {
8137                crate::gpu::o1_acap_begin(a.stride);
8138            }
8139            let o1_arch_lag = o1_arch.is_some()
8140                && o1_batch_ready
8141                && crate::gpu::wgpu_active()
8142                && std::env::var("CMF_O1_ARCH_LAG").as_deref() != Ok("0");
8143            let mut arch_lag: Option<(usize, usize, usize)> = None;
8144            if o1_batch_ready && mtp.is_some() {
8145                self.mtp_pos_base = tail_from.max(pos);
8146            }
8147            // a chunk ends at the chat snapshot's row, the card copies the
8148            // GDN states there before the next chunk runs
8149            let snap_at = if o1_arch.is_none() && !o1_batch_ready { self.gdn_snap_target(input_ids, pos) } else { None };
8150            while pos < input_ids.len() {
8151                // The prompt's last rows read the rows chosen just before them.
8152                if pos >= tail_from {
8153                    if let Some(mut a) = o1_arch.take() {
8154                        // the deferred chunk before the tail joins the archive first
8155                        if let Some((p0, b0, n0)) = arch_lag.take() {
8156                            if let Err(err) = self.o1_archive_chunk(&mut a, p0, b0, Some(n0)) {
8157                                self.finish_generation(&mut mtp, &mut router, true);
8158                                return Err(err);
8159                            }
8160                        }
8161                        crate::gpu::o1_acap_end();
8162                        if let Err(err) = self.o1_seal_archive(a) {
8163                            self.finish_generation(&mut mtp, &mut router, true);
8164                            return Err(err);
8165                        }
8166                    }
8167                }
8168                let stop = if o1_arch.is_some() { tail_from } else { input_ids.len() };
8169                let end = match snap_at {
8170                    Some(s) if pos < s => (pos + chunk).min(stop).min(s),
8171                    _ if o1_arch.is_some() => o1_chunk_end(pos, chunk, stop),
8172                    _ => (pos + chunk).min(stop),
8173                };
8174                let bk = end - pos;
8175                let mut hiddens = vec![0f32; bk * hs];
8176                for (j, &id) in input_ids[pos..end].iter().enumerate() {
8177                    hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
8178                }
8179                let positions: Vec<usize> = (pos..end).collect();
8180                let t_chunk = std::time::Instant::now();
8181                // A chunk before the last whose rows nothing reads: the
8182                // graph submits it and returns, and this loop encodes the
8183                // next chunk while the card runs it.
8184                // A sealed chunk before the last whose rows nothing reads (wgpu) is
8185                // deferred too: its rows for the archive are read once the next chunk
8186                // is on the card (`arch_lag`). `CMF_O1_ARCH_LAG=0`: each chunk waits.
8187                let sealed_defer = o1_arch_lag
8188                    && end < input_ids.len()
8189                    && !mimo_spec
8190                    && !dyn_prefill
8191                    && !(mtp.is_some() && end > self.mtp_pos_base);
8192                #[cfg(not(target_os = "macos"))]
8193                crate::gpu::set_batch_defer(
8194                    sealed_defer
8195                        || (end < input_ids.len()
8196                            && o1_arch.is_none()
8197                            && !o1_batch_ready
8198                            && !mimo_spec
8199                            && !mtp_batch_prefill
8200                            && !dyn_prefill),
8201                );
8202                let acap_before = crate::gpu::o1_acap_pending();
8203                let outcome = self.o1_prompt_chunk(&mut hiddens, &positions, bk);
8204                #[cfg(not(target_os = "macos"))]
8205                crate::gpu::set_batch_defer(false);
8206                // this chunk's entries, counted before the chunk before it leaves the queue
8207                let acap_new = crate::gpu::o1_acap_pending().saturating_sub(acap_before);
8208                if let (Some(a), crate::gpu::BatchGraphOutcome::Completed) = (o1_arch.as_mut(), outcome) {
8209                    // the chunk before this one first: its command is done
8210                    let mut res = match arch_lag.take() {
8211                        Some((p0, b0, n0)) => self.o1_archive_chunk(a, p0, b0, Some(n0)),
8212                        None => Ok(()),
8213                    };
8214                    if res.is_ok() {
8215                        if sealed_defer {
8216                            arch_lag = Some((pos, bk, acap_new));
8217                        } else {
8218                            res = self.o1_archive_chunk(a, pos, bk, None);
8219                        }
8220                    }
8221                    if let Err(err) = res {
8222                        self.finish_generation(&mut mtp, &mut router, true);
8223                        return Err(err);
8224                    }
8225                }
8226                let ok_b = outcome == crate::gpu::BatchGraphOutcome::Completed;
8227                if ok_b && dyn_prefill {
8228                    self.absorb_phi_tap(0..self.num_layers);
8229                }
8230                // The draft head over a far field reads the prompt's tail only.
8231                if ok_b && o1_batch_ready && end > self.mtp_pos_base && mtp.is_some() {
8232                    let first = pos.max(self.mtp_pos_base);
8233                    let n_pairs = mtp_prefill_pair_count(first, end, input_ids.len());
8234                    if n_pairs > 0 {
8235                        let rows: Vec<Vec<f32>> = (0..n_pairs).map(|j| hiddens[(first - pos + j) * hs..(first - pos + j + 1) * hs].to_vec()).collect();
8236                        let pairs: Vec<(&[f32], u32)> = rows.iter().enumerate().map(|(j, row)| (row.as_slice(), input_ids[first + j + 1])).collect();
8237                        #[cfg(target_os = "macos")]
8238                        let warmed = crate::gpu::q1_force() && {
8239                            if let Some(m) = mtp.as_mut() {
8240                                if !self.mtp_warm_batch_metal(m, &pairs, first) {
8241                                    for (j, (h, t)) in pairs.iter().enumerate() {
8242                                        let h = h.to_vec();
8243                                        let _ = self.mtp_step(m, &h, *t, first + j);
8244                                    }
8245                                }
8246                            }
8247                            true
8248                        };
8249                        #[cfg(not(target_os = "macos"))]
8250                        let warmed = false;
8251                        let warm_error = if warmed {
8252                            None
8253                        } else if let Some(m) = mtp.as_mut() {
8254                            self.mtp_warm_prefill_pairs(m, &pairs, first).err()
8255                        } else {
8256                            None
8257                        };
8258                        if let Some(err) = warm_error {
8259                            self.finish_generation(&mut mtp, &mut router, true);
8260                            return Err(err.to_string());
8261                        }
8262                    }
8263                }
8264                if std::env::var("CMF_GRAPH_PROF").is_ok() {
8265                    let ms = t_chunk.elapsed().as_secs_f64() * 1000.0;
8266                    eprintln!(
8267                        "batch-chunk: phase=prompt mode={} k={bk} outcome={outcome:?} {ms:.1} ms ({:.1} tok/s)",
8268                        if o1_batch_ready {
8269                            "o1"
8270                        } else if mtp_batch_prefill {
8271                            "ordinary_mtp"
8272                        } else {
8273                            "ordinary"
8274                        },
8275                        bk as f64 / (ms / 1000.0)
8276                    );
8277                }
8278                {
8279                    use std::sync::atomic::{AtomicBool, Ordering};
8280                    static SAID: AtomicBool = AtomicBool::new(false);
8281                    if !SAID.swap(true, Ordering::Relaxed) {
8282                        if ok_b {
8283                            tracing::info!(
8284                                "batched prefill: ACTIVE mode={} (k={bk})",
8285                                if o1_batch_ready {
8286                                    "o1"
8287                                } else if mtp_batch_prefill {
8288                                    "ordinary_mtp"
8289                                } else {
8290                                    "ordinary"
8291                                }
8292                            );
8293                        } else {
8294                            tracing::warn!("batched prefill {:?} — per-position graph", outcome);
8295                        }
8296                    }
8297                }
8298                if ok_b {
8299                    if mimo_spec {
8300                        self.mimo_note_rows(&hiddens, pos);
8301                    }
8302                    if mtp_batch_prefill {
8303                        let n_pairs = mtp_prefill_pair_count(pos, end, input_ids.len());
8304                        if n_pairs > 0 {
8305                            // `hiddens` is owned by this chunk, so materialize
8306                            // row slices before borrowing the detached MTP
8307                            // module.  The last prompt row has no successor;
8308                            // the helper above is the single source of that
8309                            // boundary rule.
8310                            let rows: Vec<Vec<f32>> = (0..n_pairs)
8311                                .map(|j| hiddens[j * hs..(j + 1) * hs].to_vec())
8312                                .collect();
8313                            let pairs: Vec<(&[f32], u32)> = rows
8314                                .iter()
8315                                .enumerate()
8316                                .map(|(j, row)| (row.as_slice(), input_ids[pos + j + 1]))
8317                                .collect();
8318                            if std::env::var("CMF_GRAPH_PROF").is_ok() {
8319                                eprintln!(
8320                                    "mtp-warm: phase=prompt mode=ordinary_mtp first_pos={} pairs={} last_pos={}",
8321                                    pos,
8322                                    n_pairs,
8323                                    pos + n_pairs - 1,
8324                                );
8325                            }
8326                            let t_warm = std::time::Instant::now();
8327                            let warm_error = if let Some(m) = mtp.as_mut() {
8328                                self.mtp_warm_prefill_pairs(m, &pairs, pos).err()
8329                            } else {
8330                                None
8331                            };
8332                            if std::env::var("CMF_GRAPH_PROF").is_ok() {
8333                                eprintln!("mtp-warm: {n_pairs} pairs in {:.1} ms", t_warm.elapsed().as_secs_f64() * 1e3);
8334                            }
8335                            if let Some(err) = warm_error {
8336                                // The trunk batch was already admitted.  A
8337                                // failed MTP warm-up therefore clears both
8338                                // mirrors and exits; continuing would pair a
8339                                // current trunk state with a stale MTP cache.
8340                                self.finish_generation(&mut mtp, &mut router, true);
8341                                return Err(err.to_string());
8342                            }
8343                        }
8344                    }
8345                    hidden.copy_from_slice(&hiddens[(bk - 1) * hs..]);
8346                    pos = end;
8347                    if snap_at == Some(end) {
8348                        self.gdn_snap = crate::gpu::gdn_snapshot(self.graph_kv_id, end).then(|| input_ids[..end].to_vec());
8349                    }
8350                } else if outcome == crate::gpu::BatchGraphOutcome::Failed {
8351                    // A failed batch may have advanced a device recurrent
8352                    // state (ordinary GDN or sealed O(1)). A CPU fallback
8353                    // would then observe stale accumulators, so clear the
8354                    // request state and make the failure explicit.
8355                    self.finish_generation(&mut mtp, &mut router, true);
8356                    return Err(if o1_batch_ready {
8357                        "sealed O(1) batch graph failed after admission".to_string()
8358                    } else {
8359                        "ordinary recurrent batch graph failed after admission".to_string()
8360                    });
8361                } else {
8362                    break; // unsupported → per-position graph handles the rest
8363                }
8364            }
8365            // a deferred chunk's archive rows the loop left behind (a later chunk declined)
8366            if let (Some(a), Some((p0, b0, n0))) = (o1_arch.as_mut(), arch_lag.take()) {
8367                if let Err(err) = self.o1_archive_chunk(a, p0, b0, Some(n0)) {
8368                    self.finish_generation(&mut mtp, &mut router, true);
8369                    return Err(err);
8370                }
8371            }
8372            if mtp_batch_prefill && mtp.is_some() && pos == input_ids.len() {
8373                self.mtp_warm_base = Some(self.mtp_pos_base);
8374            }
8375            // the CUDA DFlash block is built once the trunk's kernels are, so
8376            // its first round does not pay it
8377            #[cfg(feature = "cuda")]
8378            if crate::gpu::cuda_active() {
8379                if let Some(d) = &self.dflash {
8380                    let _ = d.dev_ready();
8381                }
8382            }
8383            #[cfg(target_os = "macos")]
8384            if std::env::var("CMF_PREFILL_PROF").is_ok() {
8385                crate::gpu_metal::cut_report();
8386            }
8387            // A dense stack the batched graph does not take reads the prompt chunked
8388            // on the host walk (its GEMMs on the card), as before the graph took dense
8389            // prompts, instead of one position at a time.
8390            if pos == pos_start
8391                && graph_prefill
8392                && !o1_batch_ready
8393                && mtp.is_none()
8394                && !mimo_spec
8395                && self.can_prefill_batched()
8396                && !self.per_token_stack()
8397                && self.weights.layers.iter().all(|lw| {
8398                    !matches!(&lw.attn, AttnKind::LinearGdn(_)) && !matches!(&lw.ffn, FfnKind::Moe(_))
8399                })
8400            {
8401                self.dense_batch_declined.store(true, std::sync::atomic::Ordering::Relaxed);
8402                let chunk = self.prefill_chunk();
8403                while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
8404                    let end = (pos + chunk).min(input_ids.len());
8405                    let hb = self.prefill_batch(&input_ids[pos..end], pos);
8406                    hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
8407                    pos = end;
8408                }
8409            }
8410        }
8411        // Resident Embryo graph: the prompt in chunks of one submit each
8412        // instead of one whole-graph submit per position; the last chunk
8413        // carries the logits exactly as the per-position walk would.
8414        if graph_prefill
8415            && task_mask.is_none()
8416            && mtp.is_none()
8417            && !dyn_prefill
8418            && pos == 0
8419            && input_ids.len() > 1
8420            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
8421        {
8422            if let Some(lg) = self.embryo_prefill_chunked(input_ids, 0) {
8423                self.graph_logits = Some(lg);
8424                hidden = vec![0.0; self.hidden_size];
8425                pos = input_ids.len();
8426            }
8427        }
8428        while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
8429            self.graph_want_logits = fuse_lm && pos + 1 == input_ids.len();
8430            hidden = self.forward_layers(&self.embed_single(input_ids[pos]), pos, task_mask);
8431            if mimo_spec {
8432                self.mimo_note_rows(&hidden, pos);
8433            }
8434            if let Some(m) = &mut mtp {
8435                if pos + 1 < input_ids.len() {
8436                    // `CMF_MTP_CHAIN_PROBE=k`: teacher-forced acceptance of a
8437                    // CHAINED draft — iterate the head on its own hidden k
8438                    // deep and score every depth against the prompt's real
8439                    // continuation. The economics of a k-token speculative
8440                    // round stand or fall on this table.
8441                    let probe: usize = std::env::var("CMF_MTP_CHAIN_PROBE")
8442                        .ok()
8443                        .and_then(|v| v.parse().ok())
8444                        .unwrap_or(0);
8445                    if probe >= 1 && pos + 2 < input_ids.len() {
8446                        let (d1, mut hx) = self.mtp_step_h(m, &hidden, input_ids[pos + 1], pos);
8447                        let mut ok = d1 == input_ids[pos + 2];
8448                        Self::chain_probe_note(0, ok);
8449                        let mut d_prev = d1;
8450                        let mut extra = 0usize;
8451                        for j in 1..probe {
8452                            if pos + 2 + j >= input_ids.len() {
8453                                break;
8454                            }
8455                            let (dj, hj) = self.mtp_step_h(m, &hx, d_prev, pos + 1 + j);
8456                            extra += 1;
8457                            ok = ok && dj == input_ids[pos + 2 + j];
8458                            Self::chain_probe_note(j, ok);
8459                            d_prev = dj;
8460                            hx = hj;
8461                        }
8462                        // The chain's rows are speculation, not the prompt —
8463                        // keep only the warmup row the plain path would add.
8464                        m.kv.truncate_last(extra);
8465                    } else {
8466                        let _ = self.mtp_step(m, &hidden, input_ids[pos + 1], pos);
8467                    }
8468                }
8469            }
8470            pos += 1;
8471        }
8472        #[cfg(not(target_os = "macos"))]
8473        crate::gpu::set_batch_kv_hint(0);
8474        if std::env::var("CMF_PREFILL_PROF").is_ok() {
8475            eprintln!(
8476                "prefill: {} tokens in {:.1} ms (batch_k={batch_k})",
8477                input_ids.len(),
8478                _tpf.elapsed().as_secs_f64() * 1000.0
8479            );
8480        }
8481        // The Neural Engine read the prompt; decode runs on the GPU, so its surfaces go back
8482        // to the weight map (`ane::release_idle`).
8483        #[cfg(target_os = "macos")]
8484        crate::gpu_metal::ane::release_idle();
8485        if self
8486            .graph_failed
8487            .swap(false, std::sync::atomic::Ordering::Relaxed)
8488        {
8489            // MTP is detached for speculative generation.  Restore the
8490            // module before returning the terminal graph error; otherwise a
8491            // failed request would silently remove the head from a pooled
8492            // pipeline and the next request would lose its configured route.
8493            self.finish_generation(&mut mtp, &mut router, true);
8494            return Err("GPU token graph failed during prefill".to_string());
8495        }
8496        // Cancelled mid-prefill: the cache holds a partial prompt —
8497        // drop the reuse history and return an empty generation.
8498        if self
8499            .cancel
8500            .swap(false, std::sync::atomic::Ordering::Relaxed)
8501        {
8502            // A cancelled prefill can already have advanced the device
8503            // mirror. Drop the whole partial sequence so a pooled pipeline
8504            // cannot carry that state into its next request.
8505            self.finish_generation(&mut mtp, &mut router, true);
8506            return Ok(GenerateResult {
8507                text: String::new(),
8508                token_ids: Vec::new(),
8509                prompt_tokens: input_ids.len(),
8510                tokens_generated: 0,
8511                finish_reason: "cancelled".to_string(),
8512                mtp_drafted: 0,
8513                mtp_accepted: 0,
8514                token_confidence: Vec::new(),
8515                traces: Vec::new(),
8516            });
8517        }
8518
8519        // Prompt absorbed → freeze the o1 layers' skeletons; from here
8520        // every decode step on those layers is O(W + m·dv + m²).
8521        if !o1_sealed {
8522            match self.o1_seal_checked() {
8523                Ok(_) => {}
8524                Err(err) => {
8525                    self.finish_generation(&mut mtp, &mut router, true);
8526                    return Err(err);
8527                }
8528            }
8529        }
8530
8531        // Bytes of a character the last streamed token left unfinished.
8532        let mut utf8_pending: Vec<u8> = Vec::new();
8533        // Commit one token: push, check EOS, stream. Returns false = stop.
8534        macro_rules! commit {
8535            ($id:expr) => {{
8536                all_ids.push($id);
8537                generated += 1;
8538                self.note_draft_id($id);
8539                if self.tokenizer.is_eos($id) && !self.ignore_eos {
8540                    finish_reason = "stop".to_string();
8541                    false
8542                } else {
8543                    let token_text = self.tokenizer.decode_token_stream($id, &mut utf8_pending);
8544                    let mut go = true;
8545                    if let Some(ref mut cb) = on_token {
8546                        if !cb(&token_text) {
8547                            finish_reason = "cancelled".to_string();
8548                            go = false;
8549                        }
8550                    }
8551                    if go
8552                        && self.sampler_config.loop_stop
8553                        && crate::sampler::tail_repeats(&all_ids[all_ids.len() - generated..])
8554                    {
8555                        finish_reason = "loop".to_string();
8556                        go = false;
8557                    }
8558                    go
8559                }
8560            }};
8561        }
8562
8563        // Speculation is decided by MEASUREMENT, not by an acceptance
8564        // model. A k=4 round costs ~3.8 plain tokens on the 5090 (draft
8565        // 6.6 + verify 66.6 + commit 4.8 ms against a 20.6 ms token), so it
8566        // pays only when the head lands ~2.8 of 4 — predictable text (code,
8567        // structured output) does, free prose often does not, and the
8568        // ratio at which the two cross depends on the card and the context
8569        // depth. So: four speculative rounds timed, then eight plain
8570        // tokens timed, and the faster arm runs until a re-check 256
8571        // tokens later (context growth moves the balance). The trial
8572        // costs at most a few tokens of the slower arm per 256.
8573        let mut spec_trial = SpecTrial::Spec {
8574            t0: std::time::Instant::now(),
8575            gen0: generated,
8576            rounds: 0,
8577        };
8578        // The token-count proxy prices a round at ~1.9 plain tokens. That
8579        // holds for the Metal rounds whose cost was measured — greedy and
8580        // the sparse sampling chain — so an expensive round (the dense
8581        // chain, reachable only by `CMF_GRAPH_SPEC_SAMPLE=1`) still times
8582        // the plain path before it decides.
8583        let mut spec_mon = SpecMon {
8584            metal: graph_spec && crate::gpu::q1_force() && spec_cheap_round,
8585            cuda: graph_spec && crate::gpu::cuda_active() && self.sampler_config.temperature < 1e-6,
8586            ..SpecMon::default()
8587        };
8588        // wgpu: a plain token an earlier request's trial timed stands while
8589        // the context is of the same order (the trunk's weights are most of
8590        // a token's time), and this trial decides after its rounds.
8591        if !spec_mon.metal && self.spec_plain_ms.0 > 0.0 && input_ids.len() <= self.spec_plain_ms.1 * 2 + 1024 {
8592            spec_mon.plain_ms = self.spec_plain_ms.0;
8593        }
8594        let mut spec_watchdog_off = false;
8595        // CMF_GRAPH_SPEC_TIME: the round walls so far (round 1 excluded —
8596        // it pays the scratch), for the outlier test on each new one
8597        let mut spec_walls: Vec<f32> = Vec::new();
8598        // ... and the end of the last round: the host time between rounds
8599        // (token commits, streaming, the loop top) is printed at level 2
8600        let mut spec_round_end: Option<std::time::Instant> = None;
8601        if mimo_spec {
8602            if let Ok(path) = std::env::var("CMF_MIMO_MTP_PROBE") {
8603                if let Some(mut st) = self.mimo_mtp.take() {
8604                    self.mimo_mtp_probe(&mut st, input_ids, &path);
8605                    self.mimo_mtp = Some(st);
8606                }
8607            }
8608        }
8609        // ── Decode ──
8610        let mut next_pos = input_ids.len();
8611        'decode: while generated < max_tokens {
8612            if self
8613                .graph_failed
8614                .swap(false, std::sync::atomic::Ordering::Relaxed)
8615            {
8616                // Keep the detached MTP module attached after a terminal
8617                // graph error so the pipeline can be reused for a fresh
8618                // sequence.  `clear_sequence_state` only clears mirrors and
8619                // host KV; it cannot recover a module dropped here.
8620                self.finish_generation(&mut mtp, &mut router, true);
8621                return Err("GPU token graph failed during decode".to_string());
8622            }
8623            if self
8624                .cancel
8625                .swap(false, std::sync::atomic::Ordering::Relaxed)
8626            {
8627                finish_reason = "cancelled".to_string();
8628                break 'decode;
8629            }
8630            // A rejected speculative draft already drew this position's
8631            // token from the residual distribution (graph_spec_step); it
8632            // is committed as-is — sampling again from the row's logits
8633            // would bias the stream toward the target's mode.
8634            if mimo_spec && next_pos > 0 {
8635                // Every path leaves `hidden` = the backbone output at
8636                // next_pos-1; the draft layers read it (idempotent).
8637                self.mimo_note_rows(&hidden, next_pos - 1);
8638            }
8639            let forced = self.spec_forced.take();
8640            let mut logits = match (forced, self.graph_logits.take()) {
8641                (Some(_), _) => Vec::new(),
8642                (None, Some(lg)) => lg,
8643                (None, None) => {
8644                    let _prof = crate::cpuprof::time(crate::cpuprof::Slot::Head);
8645                    // Pooled-tail mode: the head as one layer-less device
8646                    // pass (final-norm + matvec + readback). Any decline —
8647                    // no pool, unresolvable weight, backend off — keeps the
8648                    // host head exactly as before.
8649                    #[cfg(feature = "gpu")]
8650                    let logits_out = if let Some(lg) = self.m3_device_logits(&hidden) {
8651                        lg
8652                    } else {
8653                        inference::rms_norm_into(
8654                            &hidden,
8655                            &self.weights.final_norm,
8656                            self.rms_eps,
8657                            self.norm_style,
8658                            &mut self.ws.n1,
8659                        );
8660                        self.lm_head_forward(&self.ws.n1)
8661                    };
8662                    #[cfg(not(feature = "gpu"))]
8663                    let logits_out = {
8664                        inference::rms_norm_into(
8665                            &hidden,
8666                            &self.weights.final_norm,
8667                            self.rms_eps,
8668                            self.norm_style,
8669                            &mut self.ws.n1,
8670                        );
8671                        self.lm_head_forward(&self.ws.n1)
8672                    };
8673                    logits_out
8674                }
8675            };
8676            // CMF_LOGIT_DUMP=<path>: the first decode step's hidden + logits
8677            // as raw f32 (hidden first) — cross-backend numerics diffing.
8678            if generated
8679                == std::env::var("CMF_LOGIT_DUMP_STEP")
8680                    .ok()
8681                    .and_then(|v| v.parse().ok())
8682                    .unwrap_or(0)
8683            {
8684                if let Ok(path) = std::env::var("CMF_LOGIT_DUMP") {
8685                    let mut bytes: Vec<u8> = Vec::with_capacity((hidden.len() + logits.len()) * 4);
8686                    for v in hidden.iter().chain(logits.iter()) {
8687                        bytes.extend_from_slice(&v.to_le_bytes());
8688                    }
8689                    if let Err(e) = std::fs::write(&path, &bytes) {
8690                        eprintln!("logit dump: failed to write {path}: {e}");
8691                        self.finish_generation(&mut mtp, &mut router, true);
8692                        return Err(format!("logit dump write failed: {e}"));
8693                    }
8694                }
8695            }
8696            // CMF_LOGIT_DUMP_ALL=<dir>: every decode step's logits as raw
8697            // f32, `<dir>/step{n:05}.f32` — step-by-step backend diffing
8698            // (a greedy run on two backends compares until they diverge).
8699            if let Ok(dir) = std::env::var("CMF_LOGIT_DUMP_ALL") {
8700                if !logits.is_empty() {
8701                    let path = std::path::Path::new(&dir).join(format!("step{generated:05}.f32"));
8702                    let bytes: Vec<u8> = logits.iter().flat_map(|v| v.to_le_bytes()).collect();
8703                    if let Err(e) =
8704                        std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(&path, &bytes))
8705                    {
8706                        eprintln!("logit dump: failed to write {}: {e}", path.display());
8707                    }
8708                }
8709            }
8710            self.clover_causal_logits(&mut logits, generated, &all_ids[penalty_from..]);
8711            if let Some(g) = self.dash.as_mut().and_then(|d| d.guard.as_mut()) {
8712                g.apply(&mut logits, &all_ids[input_ids.len()..]);
8713            }
8714            let t_next = match forced.or_else(|| forced_ids_at(generated)) {
8715                Some(c) => c,
8716                None => {
8717                    let _prof = crate::cpuprof::time(crate::cpuprof::Slot::Sampler);
8718                    sampler::sample_with_scratch_pool(
8719                        &logits,
8720                        &self.sampler_config,
8721                        self.sampler_config.penalty_past(&all_ids[penalty_from..], bounded_native),
8722                        &mut self.rng,
8723                        &mut self.sampler_scratch,
8724                        self.pool.as_deref(),
8725                    )
8726                }
8727            };
8728            if self.confidence_on {
8729                confidence.push(if logits.is_empty() {
8730                    0.0
8731                } else {
8732                    sampler::top1_prob_pool(
8733                        self.pool.as_deref(),
8734                        &mut self.sampler_scratch,
8735                        &logits,
8736                        t_next,
8737                        calib_temp,
8738                    )
8739                });
8740            }
8741            if !logits.is_empty() {
8742                attention::recycle_buf(&mut logits);
8743            }
8744            if trace_on {
8745                // active_skill = the overlay in force while this token was
8746                // generated; recon/switched are filled after the post-emit
8747                // routing eval below (freshest coherence for this token).
8748                let skill = router.as_ref().and_then(|r| r.active_id());
8749                traces.push(TokenTrace {
8750                    t: generated,
8751                    token_id: t_next,
8752                    confidence: confidence.last().copied().unwrap_or(0.0),
8753                    active_skill: skill,
8754                    recon: None,
8755                    switched: false,
8756                });
8757            }
8758            if !commit!(t_next) {
8759                break 'decode;
8760            }
8761            if generated >= max_tokens {
8762                break 'decode;
8763            }
8764
8765            // Catch-all for decode paths that bypass the walks' own trim
8766            // (a graph step, a speculative round).
8767            self.swa_trim_tails();
8768            if self.dsv41.is_none() && self.dory.is_none() && self.kv_cache.needs_eviction() {
8769                // Say it ONCE, loudly: past this point the model keeps
8770                // talking but has lost half its context, and on a GDN
8771                // hybrid the graph's device state goes stale on top. The
8772                // Qwen3.8 bring-up spent a day reading this cliff as
8773                // three different model bugs.
8774                static SAID: std::sync::Once = std::sync::Once::new();
8775                SAID.call_once(|| {
8776                    tracing::warn!(
8777                        "KV cache full at {} positions — evicting half; quality \
8778                         will degrade. Raise CMF_MAX_SEQ.",
8779                        self.kv_cache.max_seq_len,
8780                    );
8781                });
8782                let keep = (self.kv_cache.max_seq_len / 2).max(1);
8783                self.kv_cache.evict(keep);
8784            }
8785
8786            // Advance the speculation trial: plain-phase accounting and
8787            // the periodic re-check happen here, on every token.
8788            if graph_spec {
8789                match spec_trial {
8790                    SpecTrial::Plain { t0, gen0 } if spec_mon.plain_done(t0, gen0, generated) => {
8791                        spec_mon.plain_ms =
8792                            t0.elapsed().as_secs_f64() * 1e3 / (generated - gen0) as f64;
8793                        if !spec_mon.metal {
8794                            self.spec_plain_ms = (spec_mon.plain_ms, next_pos);
8795                        }
8796                        let keep = spec_mon.pays();
8797                        tracing::info!(
8798                            "speculation trial: {:.2} tok/round in {:.1} ms vs plain {:.1} ms/tok — {}",
8799                            spec_mon.tokens,
8800                            spec_mon.round_ms,
8801                            spec_mon.plain_ms,
8802                            if keep { "speculating" } else { "plain" }
8803                        );
8804                        spec_mon.fails = 0;
8805                        spec_trial = SpecTrial::Decided {
8806                            spec: keep,
8807                            recheck_at: if keep { usize::MAX } else { spec_mon.recheck_plain_at(generated) },
8808                        };
8809                    }
8810                    SpecTrial::Decided { recheck_at, .. } if generated >= recheck_at => {
8811                        spec_mon.n = 0;
8812                        spec_mon.zero_accept_rounds = 0;
8813                        spec_trial = SpecTrial::Spec {
8814                            t0: std::time::Instant::now(),
8815                            gen0: generated,
8816                            rounds: 0,
8817                        };
8818                    }
8819                    _ => {}
8820                }
8821                spec_watchdog_off = matches!(
8822                    spec_trial,
8823                    SpecTrial::Plain { .. } | SpecTrial::Decided { spec: false, .. }
8824                );
8825            }
8826            // ── MiMo-V2 draft stack: draft K, verify K+1 rows in one batch ──
8827            if mimo_spec && generated + 1 < max_tokens && next_pos > 0 {
8828                let budget = max_tokens - generated - 1;
8829                if let Some(mut st) = self.mimo_mtp.take() {
8830                    let k = st.depth.min(budget);
8831                    let r = self.mimo_spec_round(&mut st, next_pos, &all_ids, k);
8832                    self.mimo_mtp = Some(st);
8833                    let r = match r {
8834                        Ok(r) => r,
8835                        Err(err) => {
8836                            self.finish_generation(&mut mtp, &mut router, true);
8837                            return Err(err);
8838                        }
8839                    };
8840                    if let Some(r) = r {
8841                        drafted += r.drafted;
8842                        accepted += r.accepted.len();
8843                        let mut stopped = false;
8844                        for &id in &r.accepted {
8845                            if self.confidence_on {
8846                                confidence.push(0.0);
8847                            }
8848                            if !commit!(id) {
8849                                stopped = true;
8850                                break;
8851                            }
8852                        }
8853                        if stopped {
8854                            break 'decode;
8855                        }
8856                        next_pos += r.accepted.len() + 1;
8857                        hidden = r.hidden;
8858                        // The loop top chooses the round's own token from
8859                        // these logits — the same sampler, same history.
8860                        self.graph_logits = Some(r.logits);
8861                        continue 'decode;
8862                    }
8863                }
8864            }
8865            // ── A trunk without a draft block: the sidecar's block drafts, the batch graph verifies ──
8866            #[cfg(feature = "gpu")]
8867            if solo_spec && next_pos > 0 {
8868                let now = std::time::Instant::now();
8869                // the step that just ended, on the account of its kind
8870                if let Some((t, tokens)) = solo.last.take() {
8871                    let ms = (now - t).as_secs_f32() * 1e3;
8872                    if tokens == 0 {
8873                        if solo.plain_n > 0 {
8874                            solo.plain_ms = if solo.plain_ms == 0.0 { ms } else { 0.7 * solo.plain_ms + 0.3 * ms };
8875                        }
8876                        solo.plain_n += 1;
8877                    } else if solo.first {
8878                        solo.first = false;
8879                        if spec_time_level() > 0 {
8880                            eprintln!("solo-round wall {ms:.1} ms → {tokens} tokens (the first round: not a sample)");
8881                        }
8882                    } else {
8883                        let per = ms / tokens as f32;
8884                        // a tenth a round: one round that kept nothing (85 ms for its
8885                        // one token against 20 a token before it) must not send a
8886                        // drafter keeping 80 % to rest — at a fifth it did, 36 against
8887                        // 47 tok/s on code
8888                        solo.round_ms = if solo.rounds == 0 { per } else { 0.9 * solo.round_ms + 0.1 * per };
8889                        solo.rounds += 1;
8890                        if spec_time_level() > 0 {
8891                            eprintln!(
8892                                "solo-round wall {ms:.1} ms → {tokens} tokens ({:.1} ms a token, plain {:.1})",
8893                                solo.round_ms, solo.plain_ms
8894                            );
8895                        }
8896                        // Rounds that land tokens no faster than plain steps sit out, longer
8897                        // each time. Judged on the window's summed wall over its summed
8898                        // tokens from its SOLO_JUDGE-th round on: a short answer was over
8899                        // before six rounds at a third kept had sent the drafter to rest
8900                        // (MNN-Pocket-0.3B chat: 237 against 303 tok/s plain), and one
8901                        // round that kept nothing weighs only its share of the sum.
8902                        solo.win_ms += ms;
8903                        solo.win_tok += tokens as u32;
8904                        if solo_pin.is_none() && solo.plain_ms > 0.0 && solo.rounds >= SOLO_JUDGE {
8905                            if solo.win_ms / solo.win_tok.max(1) as f32 > solo.plain_ms {
8906                                solo.rest = solo.back;
8907                                solo.back = (solo.back * 2).min(SOLO_REST_MOST);
8908                                solo.rounds = 0;
8909                                solo.win_ms = 0.0;
8910                                solo.win_tok = 0;
8911                            } else if solo.rounds >= SOLO_TRIAL {
8912                                // a winning window starts over, so the verdict follows the text
8913                                solo.rounds = 0;
8914                                solo.win_ms = 0.0;
8915                                solo.win_tok = 0;
8916                            }
8917                        }
8918                    }
8919                }
8920                if solo.rest == 0 && generated + 1 < max_tokens {
8921                    let k = solo.k.min(max_tokens - generated);
8922                    match self.solo_spec_round(t_next, next_pos, &all_ids, k) {
8923                        Some(r) => {
8924                            drafted += r.drafted;
8925                            accepted += r.accepted.len();
8926                            if solo_pin.is_none() {
8927                                // two past what held: a round that held all of its drafts goes deeper
8928                                solo.k = (r.accepted.len() + 2).clamp(2, SOLO_K_AUTO);
8929                            }
8930                            solo.last = Some((now, r.accepted.len() + 1));
8931                            let mut stopped = false;
8932                            for &id in &r.accepted {
8933                                if self.confidence_on {
8934                                    confidence.push(0.0);
8935                                }
8936                                if trace_on {
8937                                    traces.push(TokenTrace {
8938                                        t: generated,
8939                                        token_id: id,
8940                                        confidence: confidence.last().copied().unwrap_or(0.0),
8941                                        active_skill: None,
8942                                        recon: None,
8943                                        switched: false,
8944                                    });
8945                                }
8946                                if !commit!(id) {
8947                                    stopped = true;
8948                                    break;
8949                                }
8950                            }
8951                            if stopped {
8952                                break 'decode;
8953                            }
8954                            next_pos += r.accepted.len() + 1;
8955                            hidden = r.hidden;
8956                            self.graph_logits = Some(r.logits);
8957                            continue 'decode;
8958                        }
8959                        None => {
8960                            if self.graph_failed.swap(false, std::sync::atomic::Ordering::Relaxed) {
8961                                self.finish_generation(&mut mtp, &mut router, true);
8962                                return Err("GPU batch graph failed during a speculative round".to_string());
8963                            }
8964                            // no round here (the drafter's context is not at the tip, the batch graph declined)
8965                            solo.rest = 8;
8966                        }
8967                    }
8968                }
8969                solo.rest = solo.rest.saturating_sub(1);
8970                solo.last = Some((now, 0));
8971            }
8972            // ── Qwen3.8-Flash-Next draft head: k greedy drafts from the MTP
8973            //    sidecar, one batched verify window on the device ──
8974            #[cfg(feature = "gpu")]
8975            if self.speculative
8976                && self.qwen4_exp.is_some()
8977                && task_mask.is_none()
8978                && self.sampler_config.temperature < 1e-6
8979                && generated + 1 < max_tokens
8980                && next_pos > 0
8981                && std::env::var("CMF_QWEN_MTP").as_deref() != Ok("0")
8982            {
8983                let r = match &mut self.qwen4_exp {
8984                    Some(b) => {
8985                        // a copy frame drafts no further than the request goes
8986                        b.3.set_draft_budget(max_tokens - generated - 1);
8987                        crate::qwen4_exp::spec_round(
8988                            &b.0,
8989                            &b.1,
8990                            &b.2,
8991                            &mut b.3,
8992                            next_pos,
8993                            &all_ids,
8994                            &self.inv_freq,
8995                            self.pool.as_deref(),
8996                        )
8997                    }
8998                    None => None,
8999                };
9000                if let Some(r) = r {
9001                    drafted += r.drafted;
9002                    accepted += r.accepted.len();
9003                    let mut stopped = false;
9004                    for &id in &r.accepted {
9005                        if self.confidence_on {
9006                            confidence.push(0.0);
9007                        }
9008                        if !commit!(id) {
9009                            stopped = true;
9010                            break;
9011                        }
9012                    }
9013                    if stopped {
9014                        break 'decode;
9015                    }
9016                    next_pos += r.accepted.len() + 1;
9017                    hidden.fill(0.0);
9018                    self.graph_logits = Some(r.logits);
9019                    continue 'decode;
9020                }
9021            }
9022            match &mut mtp {
9023                // ── Graph speculation: chain-draft, batch-verify on device ──
9024                #[cfg(feature = "gpu")]
9025                Some(m)
9026                    if graph_spec
9027                        && !spec_watchdog_off
9028                        && generated + 1 < max_tokens
9029                        && next_pos > 0 =>
9030                {
9031                    let t_round = std::time::Instant::now();
9032                    if spec_time_level() >= 2 {
9033                        if let Some(t) = spec_round_end.take() {
9034                            eprintln!(
9035                                "spec-gap {:.2} ms (host between rounds)",
9036                                t.elapsed().as_secs_f64() * 1e3
9037                            );
9038                        }
9039                    }
9040                    spec_stamps_begin();
9041                    // device buffers allocated during this round: a
9042                    // first-touch Shared allocation is zero-filled inside
9043                    // the command buffer that uses it, which is what the
9044                    // long outlier rounds were
9045                    #[cfg(target_os = "macos")]
9046                    let allocs0 =
9047                        crate::gpu_metal::IO_BUF_ALLOCS.load(std::sync::atomic::Ordering::Relaxed);
9048                    #[cfg(not(target_os = "macos"))]
9049                    let allocs0 = 0u64;
9050                    if let Some((extra, n_pos, new_h)) = self.graph_spec_step(
9051                        m,
9052                        &hidden,
9053                        t_next,
9054                        next_pos,
9055                        &mut drafted,
9056                        &mut accepted,
9057                        &mut all_ids,
9058                        max_tokens - generated,
9059                    ) {
9060                        next_pos = n_pos;
9061                        hidden = new_h;
9062                        let level = spec_time_level();
9063                        if level > 0 {
9064                            let wall = t_round.elapsed().as_secs_f32() * 1e3;
9065                            let stamps = spec_stamps_take();
9066                            // the running median of the rounds before this
9067                            // one (round 1 pays the scratch: not a sample)
9068                            let median = if spec_walls.len() >= 3 {
9069                                let mut s = spec_walls.clone();
9070                                s.sort_by(|a, b| a.partial_cmp(b).unwrap());
9071                                Some(s[s.len() / 2])
9072                            } else {
9073                                None
9074                            };
9075                            let outlier = median.is_some_and(|m| wall > 1.4 * m);
9076                            #[cfg(target_os = "macos")]
9077                            let allocs = crate::gpu_metal::IO_BUF_ALLOCS
9078                                .load(std::sync::atomic::Ordering::Relaxed)
9079                                - allocs0;
9080                            #[cfg(not(target_os = "macos"))]
9081                            let allocs = allocs0;
9082                            eprintln!(
9083                                "spec-round wall {wall:.1} ms → {} tokens{}{}",
9084                                extra.len() + 1,
9085                                if allocs > 0 {
9086                                    format!(" [{allocs} new device buffers]")
9087                                } else {
9088                                    String::new()
9089                                },
9090                                match (outlier, median) {
9091                                    (true, Some(m)) => format!(" OUTLIER (median {m:.1})"),
9092                                    _ => String::new(),
9093                                }
9094                            );
9095                            if level >= 2 || outlier {
9096                                let sum: f32 = stamps.iter().map(|s| s.1).sum();
9097                                eprintln!(
9098                                    "spec-stamps: {}| untracked {:.1}",
9099                                    spec_stamps_format(&stamps),
9100                                    wall - sum
9101                                );
9102                            }
9103                            if spec_mon.n >= 1 {
9104                                spec_walls.push(wall);
9105                            }
9106                        }
9107                        // One speculative round done: the monitor counts it
9108                        // (round 1 untimed — it pays the batch scratch and
9109                        // the draft mirror), and the trial advances.
9110                        spec_mon.round(t_round.elapsed().as_secs_f64() * 1e3, extra.len() + 1);
9111                        // the round's tokens land in `generated` below; the
9112                        // plain phase must start counting AFTER them
9113                        spec_trial = Self::spec_trial_round(
9114                            spec_trial,
9115                            &mut spec_mon,
9116                            generated + extra.len() + 1,
9117                        );
9118                        let mut stopped = false;
9119                        for &id in &extra {
9120                            if self.confidence_on {
9121                                confidence.push(0.0);
9122                            }
9123                            // `graph_spec_step` commits the accepted MTP
9124                            // drafts as a batch.  They do not pass through
9125                            // the ordinary loop-top sampling block below,
9126                            // which is normally where the telemetry row is
9127                            // created.  Keep the public trace contract
9128                            // (one row per emitted token) here as well.
9129                            //
9130                            // The graph-spec path does not surface a
9131                            // per-row probability for accepted extras.  It
9132                            // deliberately matches the zero placed in the
9133                            // confidence channel above instead of inventing
9134                            // one or adding a separate probability pass.
9135                            if trace_on {
9136                                traces.push(TokenTrace {
9137                                    t: generated,
9138                                    token_id: id,
9139                                    confidence: confidence.last().copied().unwrap_or(0.0),
9140                                    active_skill: None,
9141                                    recon: None,
9142                                    switched: false,
9143                                });
9144                            }
9145                            if !commit!(id) {
9146                                stopped = true;
9147                                break;
9148                            }
9149                        }
9150                        if stopped {
9151                            break 'decode;
9152                        }
9153                        if spec_time_level() >= 2 {
9154                            spec_round_end = Some(std::time::Instant::now());
9155                        }
9156                        continue 'decode;
9157                    }
9158                    if self
9159                        .graph_failed
9160                        .swap(false, std::sync::atomic::Ordering::Relaxed)
9161                    {
9162                        // `graph_spec_step` may have detached MTP while a
9163                        // warm-up was in flight.  Do not reinterpret its
9164                        // terminal device failure as a plain decode step;
9165                        // restore the head, clear both mirrors, and surface
9166                        // one explicit error to the caller.
9167                        self.finish_generation(&mut mtp, &mut router, true);
9168                        return Err("GPU MTP graph failed during speculative decode".to_string());
9169                    }
9170                    // Declined (batch graph refused): plain forward below —
9171                    // and a round that produced one token for the trial's
9172                    // ledger, so a graph that keeps refusing is measured out
9173                    // like a head that keeps missing (it was spinning
9174                    // forever on a file whose batch graph declines).
9175                    // A declined round is not a cheap one-token round — it
9176                    // is a verify that does not exist for this file (a
9177                    // healed q8_2f tail measured 760 drafts, 0 accepted, 33
9178                    // against 48.8 tok/s while the monitor called the draft
9179                    // alone "paying"). Count it as the losing streak in one.
9180                    spec_mon.round(t_round.elapsed().as_secs_f64() * 1e3, 1);
9181                    spec_mon.tokens = 0.0;
9182                    spec_mon.fails = 3;
9183                    spec_trial = Self::spec_trial_round(spec_trial, &mut spec_mon, generated + 1);
9184                    hidden = self.forward_layers(&self.embed_single(t_next), next_pos, task_mask);
9185                    next_pos += 1;
9186                    continue 'decode;
9187                }
9188                // ── Speculative: draft t+2, verify in a fused pair ──
9189                Some(m) if !graph_spec && generated + 1 < max_tokens => {
9190                    let draft = self.mtp_step(m, &hidden, t_next, next_pos - 1);
9191                    drafted += 1;
9192                    let emb1 = self.embed_single(t_next);
9193                    let emb2 = self.embed_single(draft);
9194                    let (h1, h2) = self.forward_pair(&emb1, &emb2, next_pos);
9195
9196                    inference::rms_norm_into(
9197                        &h1,
9198                        &self.weights.final_norm,
9199                        self.rms_eps,
9200                        self.norm_style,
9201                        &mut self.ws.n1,
9202                    );
9203                    let mut logits1 = self.lm_head_forward(&self.ws.n1);
9204                    let t_after = sampler::sample_with_scratch_pool(
9205                        &logits1,
9206                        &self.sampler_config,
9207                        self.sampler_config.penalty_past(&all_ids, bounded_native),
9208                        &mut self.rng,
9209                        &mut self.sampler_scratch,
9210                        self.pool.as_deref(),
9211                    );
9212                    if self.confidence_on {
9213                        confidence.push(sampler::top1_prob_pool(
9214                            self.pool.as_deref(),
9215                            &mut self.sampler_scratch,
9216                            &logits1,
9217                            t_after,
9218                            calib_temp,
9219                        ));
9220                    }
9221                    attention::recycle_buf(&mut logits1);
9222                    if trace_on {
9223                        // Speculative decode is mutually exclusive with
9224                        // dynamic routing (router is None here) — no skill.
9225                        traces.push(TokenTrace {
9226                            t: generated,
9227                            token_id: t_after,
9228                            confidence: confidence.last().copied().unwrap_or(0.0),
9229                            active_skill: None,
9230                            recon: None,
9231                            switched: false,
9232                        });
9233                    }
9234                    let stop = !commit!(t_after);
9235
9236                    if t_after == draft {
9237                        accepted += 1;
9238                        self.commit_linear_scratch();
9239                        let _ = self.mtp_step(m, &h1, t_after, next_pos);
9240                        hidden = h2;
9241                        next_pos += 2;
9242                    } else {
9243                        // The draft lane is wrong: roll its KV entry back.
9244                        for layer in &mut self.kv_cache.layers {
9245                            layer.truncate_last(1);
9246                        }
9247                        if !stop {
9248                            let _ = self.mtp_step(m, &h1, t_after, next_pos);
9249                            hidden = self.forward_layers(
9250                                &self.embed_single(t_after),
9251                                next_pos + 1,
9252                                None,
9253                            );
9254                        }
9255                        next_pos += 2;
9256                    }
9257                    if stop {
9258                        break 'decode;
9259                    }
9260                }
9261                // ── Vanilla: forward the sampled token ──
9262                _ => {
9263                    // ── DeepSeek-V4 speculative decode (CMF_DSV4_SPEC=1):
9264                    // draft five on the card, verify batched, commit the
9265                    // accepted prefix. Greedy only; a rejected token's state
9266                    // is restored and replayed, so output equals the walk. ──
9267                    #[cfg(feature = "gpu")]
9268                    if Self::dsv4_spec_on() && self.dsv4.is_some() {
9269                        static SAID: std::sync::Once = std::sync::Once::new();
9270                        SAID.call_once(|| {
9271                            eprintln!(
9272                                "dsv4-spec gate: mtp={} mask={} router={} trace={} temp={} rep={} ",
9273                                !self.dsv4_mtp.is_empty(),
9274                                task_mask.is_none(),
9275                                router.is_none(),
9276                                !trace_on,
9277                                self.sampler_config.temperature < 1e-6,
9278                                self.sampler_config.repetition_penalty == 1.0,
9279                            );
9280                        });
9281                    }
9282                    #[cfg(feature = "gpu")]
9283                    if Self::dsv4_spec_on()
9284                        && self.dsv4.is_some()
9285                        && !self.dsv4_mtp.is_empty()
9286                        && task_mask.is_none()
9287                        && router.is_none()
9288                        && !trace_on
9289                        && self.sampler_config.temperature < 1e-6
9290                        && self.sampler_config.repetition_penalty == 1.0
9291                        && generated + 1 < max_tokens
9292                        && all_ids.len() >= 2
9293                        && generated >= dsv4_spec_retry_at
9294                    {
9295                        let tip_token = all_ids[all_ids.len() - 2];
9296                        let drafted0 = drafted;
9297                        let round = self.dsv4_spec_step(
9298                            tip_token,
9299                            t_next,
9300                            next_pos,
9301                            max_tokens.saturating_sub(generated),
9302                            &mut drafted,
9303                            &mut accepted,
9304                        );
9305                        if drafted > drafted0 {
9306                            let useful = round.as_ref().is_some_and(|(extra, _)| !extra.is_empty());
9307                            if useful {
9308                                dsv4_spec_bad = 0;
9309                            } else {
9310                                dsv4_spec_bad += 1;
9311                                if dsv4_spec_bad >= 2 {
9312                                    dsv4_spec_bad = 0;
9313                                    dsv4_spec_retry_at = generated.saturating_add(32);
9314                                    tracing::info!(
9315                                        "dsv4: the draft did not pay off twice — exact walk for 32 tokens"
9316                                    );
9317                                }
9318                            }
9319                        }
9320                        if let Some((extra, n_pos)) = round {
9321                            next_pos = n_pos;
9322                            let mut stopped = false;
9323                            for &id in &extra {
9324                                if self.confidence_on {
9325                                    confidence.push(0.0);
9326                                }
9327                                if !commit!(id) {
9328                                    stopped = true;
9329                                    break;
9330                                }
9331                            }
9332                            if stopped {
9333                                break 'decode;
9334                            }
9335                            continue 'decode;
9336                        }
9337                    }
9338                    // ── Inkling 2 DSpark (the file's drafter, greedy): the
9339                    // anchor and its drafts through the target in one call,
9340                    // the agreed prefix kept, the rest rolled back; the output
9341                    // is plain decoding's. ──
9342                    if self.inkling.as_ref().is_some_and(|b| b.0.draft.is_some())
9343                        && crate::inkling::spec_k() > 0
9344                        && task_mask.is_none()
9345                        && router.is_none()
9346                        && !trace_on
9347                        && self.sampler_config.temperature < 1e-6
9348                        && self.sampler_config.repetition_penalty == 1.0
9349                        && generated + 2 < max_tokens
9350                    {
9351                        let room = max_tokens.saturating_sub(generated + 1);
9352                        let mut lg = Vec::new();
9353                        let (round, k) = match &mut self.inkling {
9354                            Some(b) => {
9355                                let k = b.3.spec.pick(next_pos, room);
9356                                let r = if k > 0 { crate::inkling::spec_round(&b.0, &b.1, &b.2, &mut b.3, t_next, next_pos, k, &mut lg) } else { None };
9357                                match &r {
9358                                    Some(extra) => b.3.spec.done(next_pos, k, extra.len()),
9359                                    None => b.3.spec.done(next_pos, 0, 0),
9360                                }
9361                                (r, k)
9362                            }
9363                            None => (None, 0),
9364                        };
9365                        if let Some(extra) = round {
9366                            drafted += k;
9367                            accepted += extra.len();
9368                            self.graph_logits = Some(lg);
9369                            next_pos += 1 + extra.len();
9370                            let mut stopped = false;
9371                            for &id in &extra {
9372                                if self.confidence_on {
9373                                    confidence.push(0.0);
9374                                }
9375                                if !commit!(id) {
9376                                    stopped = true;
9377                                    break;
9378                                }
9379                            }
9380                            if stopped {
9381                                break 'decode;
9382                            }
9383                            continue 'decode;
9384                        }
9385                    }
9386                    self.graph_want_logits = fuse_lm;
9387                    // Greedy burst (CMF_MULTISTEP, off unless explicitly set): while
9388                    // nothing observes per-token state — pure argmax sampling,
9389                    // no router/trace/confidence/mask — decode k tokens per
9390                    // submit and commit them wholesale. The trailing normal
9391                    // forward leaves logits for the loop top, as always.
9392                    let mut t_fwd = t_next;
9393                    let pure_greedy = self.sampler_config.temperature < 1e-6
9394                        && self.sampler_config.repetition_penalty == 1.0
9395                        && self.sampler_config.presence_penalty == 0.0
9396                        && self.sampler_config.suppress_tokens.is_empty();
9397                    // Off by default: at every k the burst measured at or
9398                    // below the plain path on this graph shape (k=1 loses
9399                    // the argmax dispatches vs a 1 MB readback, k>=8 loses
9400                    // inter-step drains vs the saved sync). Experimental.
9401                    let burst_k = std::env::var("CMF_MULTISTEP")
9402                        .ok()
9403                        .and_then(|v| v.parse::<usize>().ok())
9404                        .unwrap_or(0);
9405                    if pure_greedy
9406                        && burst_k >= 1
9407                        && fuse_lm
9408                        && task_mask.is_none()
9409                        && router.is_none()
9410                        && !trace_on
9411                        && !self.confidence_on
9412                        // Diagnostics and teacher forcing observe every
9413                        // individual logit row.  A device-only burst returns
9414                        // only ids, so decline it rather than silently
9415                        // skipping requested evidence or forced ids.
9416                        && std::env::var_os("CMF_FORCE_IDS").is_none()
9417                        && std::env::var_os("CMF_LOGIT_DUMP").is_none()
9418                        && std::env::var_os("CMF_LOGIT_DUMP_ALL").is_none()
9419                    {
9420                        let mut stopped = false;
9421                        loop {
9422                            // The outer loop checks cancellation too, but a
9423                            // long run can stay in this burst loop for many
9424                            // submits.  Bound cancellation latency to one
9425                            // exact k-token frame.
9426                            if self
9427                                .cancel
9428                                .swap(false, std::sync::atomic::Ordering::Relaxed)
9429                            {
9430                                finish_reason = "cancelled".to_string();
9431                                stopped = true;
9432                                break;
9433                            }
9434                            let room = max_tokens.saturating_sub(generated);
9435                            if room <= 2 {
9436                                break;
9437                            }
9438                            let k = burst_k.min(room - 1);
9439                            if k < 1 {
9440                                break;
9441                            }
9442                            let Some(ids) = self.try_multi_burst(t_fwd, next_pos, k) else {
9443                                if self
9444                                    .graph_failed
9445                                    .swap(false, std::sync::atomic::Ordering::Relaxed)
9446                                {
9447                                    self.finish_generation(&mut mtp, &mut router, true);
9448                                    return Err(
9449                                        "GPU token graph failed during greedy burst".to_string()
9450                                    );
9451                                }
9452                                break;
9453                            };
9454                            next_pos += k;
9455                            for &id in &ids {
9456                                if !commit!(id) {
9457                                    stopped = true;
9458                                    break;
9459                                }
9460                            }
9461                            if stopped {
9462                                break;
9463                            }
9464                            t_fwd = *ids.last().unwrap();
9465                        }
9466                        if stopped {
9467                            break 'decode;
9468                        }
9469                    }
9470                    // Metal: keep the draft head's cache in step through
9471                    // the trial's plain phase and a paused speculation —
9472                    // the pair (hidden, t_fwd) at next_pos−1, the step the
9473                    // round's draft 0 would take. Without it the head's
9474                    // cache lagged the trunk by every plain token for the
9475                    // rest of the generation: the batched warm-up declined
9476                    // every later round and its rows went one by one (a
9477                    // whole MTP step per accepted token), and the drafts
9478                    // attended a context with those tokens missing.
9479                    #[cfg(target_os = "macos")]
9480                    if graph_spec
9481                        && spec_watchdog_off
9482                        && next_pos > 0
9483                        && self.mtp_graph_mode == Some(true)
9484                        && crate::gpu::q1_force()
9485                    {
9486                        if let Some(m) = mtp.as_mut() {
9487                            let _ = self.mtp_step_metal(m, &hidden, t_fwd, next_pos - 1, false);
9488                        }
9489                    }
9490                    if let Some(d) = self.dash.as_mut() {
9491                        d.at_decode(t_fwd, next_pos);
9492                    }
9493                    hidden = self.forward_layers(&self.embed_single(t_fwd), next_pos, task_mask);
9494                    next_pos += 1;
9495                    // Dynamic routing: the forward updated φ; ask the
9496                    // router whether to switch skills before the next token.
9497                    if let Some(r) = &mut router {
9498                        let phi = self.dyn_phi_ema.clone();
9499                        let decision = r.step(&phi, generated);
9500                        if let Some(new_active) = decision {
9501                            if self.set_active_skill(new_active).is_ok() && next_pos <= all_ids.len() {
9502                                // The switch is a sequence boundary: every state
9503                                // the old weights made is gone. The context so far
9504                                // is read again under the new ones, so the next
9505                                // token conditions on all of it, not on an empty
9506                                // cache.
9507                                match self.reprefill_context(&all_ids[..next_pos], task_mask) {
9508                                    Ok(h) => hidden = h,
9509                                    Err(e) => tracing::warn!("dynamic routing: re-reading the context after a skill switch failed: {e}"),
9510                                }
9511                            }
9512                        }
9513                        // Backfill this token's coherence + switch flag from
9514                        // the just-run eval (freshest measured values).
9515                        if trace_on {
9516                            if let Some(last) = traces.last_mut() {
9517                                let e = r.last_best_e();
9518                                last.recon = e.is_finite().then_some(e);
9519                                last.switched = decision.is_some();
9520                            }
9521                        }
9522                    }
9523                }
9524            }
9525        }
9526
9527        let cancelled = finish_reason == "cancelled";
9528        // A generation during which the router switched weights holds no
9529        // state any single overlay would produce (each switch cleared the
9530        // cache mid-sequence), so it leaves no reuse key behind either.
9531        let dyn_switched = router.as_ref().is_some_and(|r| !r.switches.is_empty());
9532        if mimo_spec {
9533            if let Some(st) = self.mimo_mtp.as_ref() {
9534                let line = st.stats.line();
9535                tracing::info!("{line}");
9536                if std::env::var_os("CMF_MIMO_MTP_STATS").is_some() {
9537                    eprintln!("{line}");
9538                }
9539            }
9540        }
9541        self.finish_generation(&mut mtp, &mut router, cancelled);
9542
9543        if self.dflash_solo && spec_time_level() > 0 {
9544            if let Some(line) = crate::dflash::stage_report() {
9545                eprintln!("solo-draft: {line}");
9546            }
9547        }
9548        // `CMF_GEN_IDS_OUT=FILE`: the sequence as ids, prompt first (what
9549        // `CMF_SPEC_SCRIPT` reads back).
9550        if let Ok(path) = std::env::var("CMF_GEN_IDS_OUT") {
9551            let text = all_ids.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(" ");
9552            if let Err(e) = std::fs::write(&path, text) {
9553                tracing::warn!("CMF_GEN_IDS_OUT: {path}: {e}");
9554            }
9555        }
9556        let output_ids = &all_ids[input_ids.len()..];
9557        // Forwarded = prompt + all generated but the LAST sampled token
9558        // (emitted without being fed back). Exact only without MTP —
9559        // reuse is gated off when MTP is active.
9560        let forwarded = input_ids.len() + output_ids.len().saturating_sub(1);
9561        // A MiMo speculative round that stopped on an accepted draft (EOS,
9562        // cancel) leaves verify rows past the committed stream in the cache:
9563        // never offer that cache for reuse. Neither does a router that
9564        // switched weights mid-sequence (no single overlay produced it).
9565        let consumed = std::mem::take(&mut all_ids);
9566        if dyn_switched {
9567            self.clear_sequence_state();
9568        } else if cancelled || mimo_spec || prompt_rows.is_some() {
9569            self.clear_history();
9570        } else {
9571            self.record_consumed_prefix(&consumed[..forwarded.min(consumed.len())], reuse_from);
9572        }
9573        all_ids = consumed;
9574        let output_ids = &all_ids[input_ids.len()..];
9575        confidence.truncate(output_ids.len()); // guard against any overshoot
9576        traces.truncate(output_ids.len());
9577        // The loop monitor stopped the answer: it says the repeated block once.
9578        let output_ids = match finish_reason.as_str() {
9579            "loop" => {
9580                let excess = crate::sampler::tail_repeat_excess(output_ids).unwrap_or(0);
9581                &output_ids[..output_ids.len() - excess]
9582            }
9583            _ => output_ids,
9584        };
9585        Ok(GenerateResult {
9586            text: self.tokenizer.decode(output_ids),
9587            token_ids: output_ids.to_vec(),
9588            prompt_tokens: input_ids.len(),
9589            tokens_generated: generated,
9590            finish_reason,
9591            mtp_drafted: drafted,
9592            mtp_accepted: accepted,
9593            token_confidence: confidence,
9594            traces,
9595        })
9596    }
9597
9598    /// One MTP step: feed `(hidden_p, token_{p+1})` into the draft head,
9599    /// advance its KV cache at position `p`, return the drafted token
9600    /// for position `p+2`.
9601    fn mtp_step(
9602        &mut self,
9603        m: &mut MtpModule,
9604        hidden: &[f32],
9605        next_token: u32,
9606        position: usize,
9607    ) -> u32 {
9608        self.mtp_step_h(m, hidden, next_token, position).0
9609    }
9610
9611    /// Tally for `CMF_MTP_CHAIN_PROBE`: per depth, how often the CHAIN is
9612    /// still an exact prefix of the real continuation. Printed every 128
9613    /// depth-0 samples so a killed run still shows its table.
9614    fn chain_probe_note(depth: usize, prefix_ok: bool) {
9615        use std::sync::Mutex;
9616        static T: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
9617        let mut t = T.lock().unwrap();
9618        if t.len() <= depth {
9619            t.resize(depth + 1, (0, 0));
9620        }
9621        t[depth].0 += 1;
9622        t[depth].1 += prefix_ok as u64;
9623        if depth == 0 && t[0].0 % 128 == 0 {
9624            let line: Vec<String> = t
9625                .iter()
9626                .enumerate()
9627                .map(|(d, (n, k))| {
9628                    format!(
9629                        "d{}={:.0}%({n})",
9630                        d + 1,
9631                        100.0 * *k as f64 / (*n).max(1) as f64
9632                    )
9633                })
9634                .collect();
9635            eprintln!("mtp-chain: {}", line.join(" "));
9636        }
9637    }
9638
9639    /// `mtp_step` that also hands back the block's own output hidden — the
9640    /// state a CHAINED draft feeds the next step, the way a multi-token
9641    /// speculative round iterates the head on itself.
9642    /// One MTP block step from (trunk hidden, token): the head's LOGITS
9643    /// and the block's own hidden for chaining. The draft is argmax of the
9644    /// logits on the greedy path and a draw from their post-chain
9645    /// distribution on the sampling path.
9646    fn mtp_step_hl(
9647        &mut self,
9648        m: &mut MtpModule,
9649        hidden: &[f32],
9650        next_token: u32,
9651        position: usize,
9652    ) -> (Vec<f32>, Vec<f32>) {
9653        let position = position.saturating_sub(self.mtp_pos_base);
9654        // The graph arm: the MTP block as a one-layer token graph with the
9655        // head fused — device attention over the block's own KV mirror,
9656        // one submit for block + head, hidden and logits back together.
9657        // Decided once per generation (see `mtp_graph_mode`).
9658        #[cfg(target_os = "macos")]
9659        if self.mtp_graph_mode != Some(false) && crate::gpu::q1_force() {
9660            if let Some(r) = self.mtp_step_metal(m, hidden, next_token, position, true) {
9661                self.mtp_graph_mode = Some(true);
9662                return r;
9663            }
9664            if self.mtp_graph_mode == Some(true) {
9665                tracing::error!("mtp Metal graph failed after admission");
9666                self.clear_sequence_state();
9667                self.graph_failed
9668                    .store(true, std::sync::atomic::Ordering::Relaxed);
9669                self.cancel
9670                    .store(true, std::sync::atomic::Ordering::Relaxed);
9671                return (Vec::new(), Vec::new());
9672            }
9673            self.mtp_graph_mode = Some(false);
9674        }
9675        #[cfg(feature = "gpu")]
9676        if self.mtp_graph_mode != Some(false) {
9677            if !self.mtp_graph_ok(m) {
9678                if self.mtp_graph_mode == Some(true) {
9679                    // A mirror was already admitted, so a capability change
9680                    // cannot safely switch this request to the stale CPU
9681                    // cache.  Keep the same terminal contract as a failed
9682                    // token graph.
9683                    tracing::error!("mtp graph became unavailable after admission");
9684                    self.clear_sequence_state();
9685                    self.graph_failed
9686                        .store(true, std::sync::atomic::Ordering::Relaxed);
9687                    self.cancel
9688                        .store(true, std::sync::atomic::Ordering::Relaxed);
9689                    return (Vec::new(), Vec::new());
9690                }
9691                self.mtp_graph_mode = Some(false);
9692            } else {
9693                if let Some(r) = self.mtp_step_graph(m, hidden, next_token, position) {
9694                    self.mtp_graph_mode = Some(true);
9695                    return r;
9696                }
9697                if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
9698                    // A token graph can have admitted a persistent MTP/GDN
9699                    // mirror before its readback failed.  The CPU MTP cache
9700                    // is not a valid continuation in that state; leave the
9701                    // flag set so the generation caller returns through its
9702                    // terminal error path instead of silently switching
9703                    // arithmetic.
9704                    return (Vec::new(), Vec::new());
9705                }
9706                // `mtp_graph_ok` was true, so a None here means a refusal or
9707                // failure after graph admission.  Do not fall through to a
9708                // CPU cache whose rows may lag the device mirror.
9709                tracing::error!("mtp graph failed or declined after admission");
9710                self.clear_sequence_state();
9711                self.graph_failed
9712                    .store(true, std::sync::atomic::Ordering::Relaxed);
9713                self.cancel
9714                    .store(true, std::sync::atomic::Ordering::Relaxed);
9715                return (Vec::new(), Vec::new());
9716            }
9717        }
9718        // fc concat order is [enorm(embed); hnorm(hidden)] — EMBEDDING
9719        // FIRST. Verified by the oracle (converter/mtp_oracle.py):
9720        // [emb;hid] → 45.8% acceptance, [hid;emb] → 0.00%.
9721        let e = self.embed_single(next_token);
9722        let mut cat = vec![0.0f32; 2 * self.hidden_size];
9723        let (cat_e, cat_h) = cat.split_at_mut(self.hidden_size);
9724        inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
9725        inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
9726        let mut x = vec![0.0f32; self.hidden_size];
9727        m.eh_proj.matvec(&cat, &mut x, self.pool.as_deref());
9728
9729        // One standard transformer block over the MTP's own cache.
9730        let lw = &m.layer;
9731        inference::rms_norm_into(
9732            &x,
9733            &lw.input_norm,
9734            self.rms_eps,
9735            self.norm_style,
9736            &mut self.ws.n1,
9737        );
9738        let attn = match &lw.attn {
9739            // MLA models carry no MTP head; this path cannot see them.
9740            AttnKind::Mla(_) => unreachable!("MLA has no MTP/pair path"),
9741            AttnKind::Kda(_) => unreachable!("KDA has no MTP/pair path"),
9742            AttnKind::Full {
9743                wq,
9744                wk,
9745                wv,
9746                wo,
9747                q_norm,
9748                k_norm,
9749                output_gate,
9750                softplus_gate,
9751                bias,
9752            } => {
9753                let mut cfg = self.attn_cfg(position);
9754                cfg.q_norm = q_norm.as_deref();
9755                cfg.k_norm = k_norm.as_deref();
9756                cfg.output_gate = *output_gate;
9757                cfg.softplus_gate = softplus_gate
9758                    .as_ref()
9759                    .map(|(gate, per_head)| (gate, *per_head));
9760                cfg.bias = bias
9761                    .as_ref()
9762                    .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice()));
9763                attention::qwen_attention(&self.ws.n1, wq, wk, wv, wo, &mut m.kv, &cfg)
9764            }
9765            AttnKind::Linear(_)
9766            | AttnKind::LinearGdn(_)
9767            | AttnKind::ShortConv(_)
9768            | AttnKind::Bounded(_) => {
9769                unreachable!("MTP block is full attention")
9770            }
9771        };
9772        for (i, &a) in attn.iter().enumerate() {
9773            x[i] += a;
9774        }
9775        inference::rms_norm_into(
9776            &x,
9777            &lw.post_norm,
9778            self.rms_eps,
9779            self.norm_style,
9780            &mut self.ws.p1,
9781        );
9782        let ffn = ffn_forward(&lw.ffn, &self.ws.p1, self.pool.as_deref(), None);
9783        for (i, &f) in ffn.iter().enumerate() {
9784            x[i] += f;
9785        }
9786
9787        inference::rms_norm_into(
9788            &x,
9789            &m.final_norm,
9790            self.rms_eps,
9791            self.norm_style,
9792            &mut self.ws.n1,
9793        );
9794        let lg = self.lm_head_forward(&self.ws.n1);
9795        (lg, x)
9796    }
9797
9798    /// `mtp_step_hl` reduced to the greedy draft: argmax of the head.
9799    fn mtp_step_h(
9800        &mut self,
9801        m: &mut MtpModule,
9802        hidden: &[f32],
9803        next_token: u32,
9804        position: usize,
9805    ) -> (u32, Vec<f32>) {
9806        let (mut lg, x) = self.mtp_step_hl(m, hidden, next_token, position);
9807        let draft = sampler::argmax(&lg);
9808        attention::recycle_buf(&mut lg);
9809        (draft, x)
9810    }
9811
9812    /// One speculative round for the trial: rounds 1..5 of a `Spec` phase
9813    /// advance it (the monitor already averaged this round); after five,
9814    /// the plain phase runs (once — a known plain rate decides at once);
9815    /// a decided speculation keeps re-checking the rule every round and
9816    /// stops after four losing rounds in a row.
9817    fn spec_trial_round(trial: SpecTrial, mon: &mut SpecMon, generated: usize) -> SpecTrial {
9818        // CMF_GRAPH_SPEC_PIN=1 keeps the rounds on whatever they cost: a
9819        // count of how a draft head holds has to include the stretches a
9820        // trial would decode plain.
9821        static PIN: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
9822        if *PIN.get_or_init(|| std::env::var("CMF_GRAPH_SPEC_PIN").as_deref() == Ok("1")) {
9823            return SpecTrial::Decided {
9824                spec: true,
9825                recheck_at: usize::MAX,
9826            };
9827        }
9828        match trial {
9829            SpecTrial::Spec { t0, gen0, rounds } => {
9830                let rounds = rounds + 1;
9831                // A round that accepts no draft still has to run the MTP
9832                // chain and a K+1 verifier, but emits only its verifier tip.
9833                // After `SPEC_ZERO_ROUNDS` such real rounds the speculative
9834                // arm cannot win on any backend; time plain immediately
9835                // rather than spend the remaining exploratory rounds on the
9836                // same one-token result. A re-check soon after (the evidence
9837                // is a few rounds) gives the text a chance to re-admit it.
9838                if mon.repeated_zero_acceptance() {
9839                    tracing::info!(
9840                        "speculation trial: no accepted drafts in two rounds — timing plain"
9841                    );
9842                    return SpecTrial::Plain {
9843                        t0: std::time::Instant::now(),
9844                        gen0: generated,
9845                    };
9846                }
9847                if rounds >= 5 {
9848                    if mon.plain_ms > 0.0 {
9849                        let keep = mon.pays();
9850                        mon.fails = 0;
9851                        tracing::info!(
9852                            "speculation re-check: {:.2} tok/round in {:.1} ms vs plain {:.1} ms/tok — {}",
9853                            mon.tokens,
9854                            mon.round_ms,
9855                            mon.plain_ms,
9856                            if keep { "speculating" } else { "plain" }
9857                        );
9858                        SpecTrial::Decided {
9859                            spec: keep,
9860                            recheck_at: if keep { usize::MAX } else { mon.recheck_plain_at(generated) },
9861                        }
9862                    } else if mon.pays() {
9863                        // Metal: the rounds land enough tokens each that no
9864                        // plain measurement is needed — keep speculating,
9865                        // and re-check every round (a losing streak sends
9866                        // the loop to the plain phase, below).
9867                        mon.fails = 0;
9868                        tracing::info!(
9869                            "speculation trial: {:.2} tok/round in {:.1} ms — speculating (plain not timed)",
9870                            mon.tokens,
9871                            mon.round_ms,
9872                        );
9873                        SpecTrial::Decided {
9874                            spec: true,
9875                            recheck_at: usize::MAX,
9876                        }
9877                    } else {
9878                        SpecTrial::Plain {
9879                            t0: std::time::Instant::now(),
9880                            gen0: generated,
9881                        }
9882                    }
9883                } else {
9884                    SpecTrial::Spec { t0, gen0, rounds }
9885                }
9886            }
9887            SpecTrial::Decided { spec: true, .. } => {
9888                if mon.pays() {
9889                    mon.fails = 0;
9890                    trial
9891                } else {
9892                    mon.fails += 1;
9893                    if mon.fails >= 4 {
9894                        if mon.plain_ms <= 0.0 {
9895                            // Metal, plain never timed: four doubtful rounds
9896                            // buy the (bounded) plain measurement, and the
9897                            // exact rule decides from it.
9898                            tracing::info!(
9899                                "speculation doubtful: {:.2} tok/round in {:.1} ms — timing plain",
9900                                mon.tokens,
9901                                mon.round_ms,
9902                            );
9903                            return SpecTrial::Plain {
9904                                t0: std::time::Instant::now(),
9905                                gen0: generated,
9906                            };
9907                        }
9908                        tracing::info!(
9909                            "speculation stopped: {:.2} tok/round in {:.1} ms vs plain {:.1} ms/tok",
9910                            mon.tokens,
9911                            mon.round_ms,
9912                            mon.plain_ms
9913                        );
9914                        SpecTrial::Decided {
9915                            spec: false,
9916                            recheck_at: generated + SPEC_RECHECK_PLAIN,
9917                        }
9918                    } else {
9919                        trial
9920                    }
9921                }
9922            }
9923            other => other,
9924        }
9925    }
9926
9927    /// The MTP block's device-mirror id: the trunk's id with a high bit,
9928    /// so the (kv_id, layer) mirror keys never collide.
9929    fn mtp_kv_id(&self) -> u64 {
9930        self.graph_kv_id | (1u64 << 40)
9931    }
9932
9933    /// The MTP block's mirror layer index: 0 — its own kv_id keeps it
9934    /// apart from the trunk, and the BATCH graph (the warm-up path) keys
9935    /// its mirrors at layer 0 with no base of its own, so the draft's
9936    /// token graph must key the same slot.
9937    const MTP_LAYER_BASE: usize = 0;
9938
9939    /// The wgpu MTP draft writes speculative rows straight into its device
9940    /// mirror while the CPU owner retains only the real prompt/decode anchor.
9941    /// After verification, move that mirror cursor back to the anchor before
9942    /// replaying accepted pairs.  The next graph append then sees the same
9943    /// contiguous position as the CPU/Metal path without uploading stale
9944    /// speculative rows.
9945    #[cfg(feature = "gpu")]
9946    fn rewind_mtp_graph_mirror(&self, stored: usize) -> bool {
9947        let stored = stored.saturating_sub(self.mtp_pos_base);
9948        self.mtp_graph_mode != Some(true)
9949            || crate::gpu::graph_kv_set_stored(self.mtp_kv_id(), Self::MTP_LAYER_BASE, stored)
9950    }
9951
9952    /// A speculative verify graph appends the full `k+1` trunk rows before
9953    /// the acceptance count is known.  GDN state already has a snapshot
9954    /// restore; Full-attention mirrors need the matching logical cursor
9955    /// rewind so the next graph call does not reject an ahead-of-position KV
9956    /// cache after a partial acceptance.
9957    #[cfg(feature = "gpu")]
9958    fn rewind_trunk_graph_mirrors(&self, stored: usize) -> bool {
9959        let mut ok = true;
9960        let mut expected = false;
9961        for li in 0..self.num_layers {
9962            if matches!(
9963                self.weights.layers[self.phys_layer(li)].attn,
9964                AttnKind::Full { .. }
9965            ) {
9966                // A sealed layer has no mirror: its state moved by `o1_spec_commit`.
9967                if self.o1_flags.get(li).copied().unwrap_or(false) && self.kv_cache.layers[li].o1_sealed() {
9968                    continue;
9969                }
9970                expected = true;
9971                ok &= crate::gpu::graph_kv_set_stored(self.graph_kv_id, li, stored);
9972            }
9973        }
9974        !expected || ok
9975    }
9976
9977    /// Count the recurrent layers participating in the trunk verify graph.
9978    /// Snapshot restore is all-or-nothing across that set; deriving the count
9979    /// from the model keeps the restore contract valid for looped models too.
9980    fn graph_gdn_layer_count(&self) -> usize {
9981        // stacks that keep their own layers (qwen4, DSV4) leave the generic
9982        // ones empty: no generic GDN layer, nothing to index
9983        (0..self.num_layers)
9984            .filter(|&li| {
9985                self.weights
9986                    .layers
9987                    .get(self.phys_layer(li))
9988                    .is_some_and(|l| matches!(&l.attn, AttnKind::LinearGdn(_)))
9989            })
9990            .count()
9991    }
9992
9993    /// The block's input from (trunk hidden, token): eh_proj · [enorm(e);
9994    /// hnorm(h)] — the same arithmetic the per-op path starts with.
9995    fn mtp_block_input(&mut self, m: &MtpModule, hidden: &[f32], next_token: u32) -> Vec<f32> {
9996        self.mtp_block_inputs(m, &[(hidden, next_token)])
9997    }
9998
9999    /// The block inputs of several (trunk hidden, token) pairs, `[n][hidden]`.
10000    /// On the CUDA hybrid arm eh_proj runs on the card for all of them at
10001    /// once (about 1 ms a pair on the host for Qwen3.8-27B's 27 MB matrix,
10002    /// tens of microseconds there); everywhere else one host matvec a pair.
10003    fn mtp_block_inputs(&mut self, m: &MtpModule, pairs: &[(&[f32], u32)]) -> Vec<f32> {
10004        let hs = self.hidden_size;
10005        let mut cats = vec![0.0f32; pairs.len() * 2 * hs];
10006        for (i, (hidden, tok)) in pairs.iter().enumerate() {
10007            let e = self.embed_single(*tok);
10008            let cat = &mut cats[i * 2 * hs..(i + 1) * 2 * hs];
10009            let (cat_e, cat_h) = cat.split_at_mut(hs);
10010            inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
10011            inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
10012        }
10013        let mut xs = vec![0.0f32; pairs.len() * hs];
10014        #[cfg(feature = "gpu")]
10015        if crate::gpu::cuda_active() {
10016            if let Some((model, idx, kind, rs)) = m.eh_proj.graph_weight() {
10017                let gw = crate::gpu::GraphW {
10018                    idx,
10019                    kind,
10020                    row_scale: rs,
10021                    data: &[],
10022                    prism: crate::gpu::GraphPrismOp::None,
10023                    affine: false,
10024                };
10025                let model = model.clone();
10026                if crate::gpu::rows_matvec(&model, &gw, hs, 2 * hs, &cats, pairs.len(), &mut xs) {
10027                    return xs;
10028                }
10029            }
10030        }
10031        if pairs.len() > 1 && std::env::var("CMF_MTP_EH_BATCH").as_deref() != Ok("0") {
10032            m.eh_proj.matmat(&cats, pairs.len(), &mut xs, self.pool.as_deref());
10033            return xs;
10034        }
10035        for i in 0..pairs.len() {
10036            m.eh_proj.matvec(&cats[i * 2 * hs..(i + 1) * 2 * hs], &mut xs[i * hs..(i + 1) * hs], self.pool.as_deref());
10037        }
10038        xs
10039    }
10040
10041    /// Is the MTP block graphable at all (device up, full attention
10042    /// without softplus, dense FFN)? The plan itself is built per call.
10043    #[cfg(feature = "gpu")]
10044    fn mtp_block_graph_ok(&self, m: &MtpModule) -> bool {
10045        if std::env::var("CMF_MTP_GRAPH").as_deref() == Ok("0") {
10046            return false;
10047        }
10048        if !crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode) || !crate::gpu::enabled_here() {
10049            return false;
10050        }
10051        self.mtp_block_shape_ok(m)
10052    }
10053
10054    /// The shape a device MTP step takes (the wgpu token graph and native
10055    /// Metal's `mtp_step_metal` alike): one dense block of full attention
10056    /// without a softplus gate, V as wide as K, no softcap. A MoE draft block
10057    /// drafts op by op on the host and costs more than it saves.
10058    fn mtp_block_shape_ok(&self, m: &MtpModule) -> bool {
10059        if std::env::var("CMF_MTP_GRAPH").as_deref() == Ok("0")
10060            || self.attn_softcap > 0.0
10061            || self.attention_heads_per_layer.is_some()
10062            // The block graph caches V as wide as K and feeds o_proj
10063            // nh·head_dim; a narrow-V model keeps its MTP block per-op.
10064            || self.v_head_dim.is_some()
10065        {
10066            return false;
10067        }
10068        matches!(
10069            &m.layer.attn,
10070            AttnKind::Full {
10071                softplus_gate: None,
10072                ..
10073            }
10074        ) && matches!(&m.layer.ffn, FfnKind::Dense(_))
10075    }
10076
10077    /// Full MTP token-graph eligibility, including the fused lm-head and all
10078    /// block projection weights.  Keep this distinct from the block-only
10079    /// check: prompt warm-up does not need the head, while a draft step does.
10080    #[cfg(feature = "gpu")]
10081    fn mtp_graph_ok(&self, m: &MtpModule) -> bool {
10082        if !self.mtp_block_graph_ok(m) {
10083            return false;
10084        }
10085        let AttnKind::Full { wq, wk, wv, wo, .. } = &m.layer.attn else {
10086            return false;
10087        };
10088        let FfnKind::Dense(d) = &m.layer.ffn else {
10089            return false;
10090        };
10091        d.segs.is_empty()
10092            && wq.graph_weight().is_some()
10093            && wk.graph_weight().is_some()
10094            && wv.graph_weight().is_some()
10095            && wo.graph_weight().is_some()
10096            && d.gate_proj.graph_weight().is_some()
10097            && d.up_proj.graph_weight().is_some()
10098            && d.down_proj.graph_weight().is_some()
10099            && self.weights.lm_head.graph_weight().is_some()
10100    }
10101
10102    /// One MTP block step on the wgpu token graph: block + fused head in
10103    /// one submit, the block hidden and the logits read back together.
10104    /// None = the graph cannot take this block (softplus gate, non-dense
10105    /// FFN, unquantized head, no device) — the caller keeps the per-op
10106    /// path for the whole generation.
10107    #[cfg(feature = "gpu")]
10108    fn mtp_step_graph(
10109        &mut self,
10110        m: &mut MtpModule,
10111        hidden: &[f32],
10112        next_token: u32,
10113        position: usize,
10114    ) -> Option<(Vec<f32>, Vec<f32>)> {
10115        if !self.mtp_graph_ok(m) {
10116            return None;
10117        }
10118        let lw = &m.layer;
10119        let AttnKind::Full {
10120            wq,
10121            wk,
10122            wv,
10123            wo,
10124            q_norm,
10125            k_norm,
10126            output_gate,
10127            softplus_gate,
10128            bias,
10129        } = &lw.attn
10130        else {
10131            return None;
10132        };
10133        if softplus_gate.is_some() {
10134            return None;
10135        }
10136        let FfnKind::Dense(d) = &lw.ffn else {
10137            return None;
10138        };
10139        if !d.segs.is_empty() {
10140            return None; // tube layers run on the segmented path
10141        }
10142        // The block's input first: it borrows `self` mutably (embed scratch,
10143        // pool), the plan below borrows the weights immutably.
10144        let mut x = self.mtp_block_input(m, hidden, next_token);
10145        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
10146            let (_, i, kind, rs) = t.graph_weight()?;
10147            Some(crate::gpu::GraphW {
10148                idx: i,
10149                kind,
10150                row_scale: rs,
10151                data: &[],
10152                prism: crate::gpu::GraphPrismOp::None,
10153                affine: false,
10154            })
10155        }
10156        let (model, _, _, _) = wq.graph_weight()?;
10157        let model = model.clone();
10158        let (lm_gw, lm_rows) = {
10159            let (_, i, kind, rs) = self.weights.lm_head.graph_weight()?;
10160            // The draft's head over the CMF_DRAFT_VOCAB shortlist (the same
10161            // cut the native Metal draft takes): 662 MB a step on Qwen3.8
10162            // becomes 170 MB at 65536; the verify keeps the full head.
10163            let rows = if kind == 6 {
10164                self.draft_head_rows(self.weights.lm_head.rows())
10165            } else {
10166                self.weights.lm_head.rows()
10167            };
10168            (
10169                crate::gpu::GraphW {
10170                    idx: i,
10171                    kind,
10172                    row_scale: rs,
10173                    data: &[],
10174                    prism: crate::gpu::GraphPrismOp::None,
10175                    affine: false,
10176                },
10177                rows,
10178            )
10179        };
10180        let layer = crate::gpu::GraphLayer {
10181            engram: None,
10182            mhc: None,
10183            input_norm: &lw.input_norm,
10184            attn: crate::gpu::GraphAttn::Full {
10185                wq: gw(wq)?,
10186                wk: gw(wk)?,
10187                wv: gw(wv)?,
10188                wo: gw(wo)?,
10189                q_norm: q_norm.as_deref(),
10190                k_norm: k_norm.as_deref(),
10191                late_qk_norm: self.qk_norm_after_rope,
10192                bias: bias
10193                    .as_ref()
10194                    .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
10195                output_gate: *output_gate,
10196                cpu_k: m.kv.k_heads(),
10197                cpu_v: m.kv.v_heads(),
10198                cpu_base: m.kv.base(),
10199                geom: None,
10200                head_gate: None,
10201            },
10202            post_norm: &lw.post_norm,
10203            attn_out_norm: None,
10204            ffn_out_norm: None,
10205            layer_scale: None,
10206            ffn: crate::gpu::GraphFfn::Dense {
10207                gate: gw(&d.gate_proj)?,
10208                up: gw(&d.up_proj)?,
10209                down: gw(&d.down_proj)?,
10210                act: d.act.graph_act()?,
10211                limit: 0.0,
10212                hot: None,
10213            },
10214        };
10215        let nh = self.num_heads;
10216        let (nkv, hd, rd) = self.layer_geom(0);
10217        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
10218        let mut logits = Vec::new();
10219        let ok = crate::gpu::forward_token_graph(
10220            &model,
10221            self.mtp_kv_id(),
10222            std::slice::from_ref(&layer),
10223            &[None],
10224            self.o1_epoch,
10225            &self.inv_freq,
10226            &mut x,
10227            nh,
10228            nkv,
10229            hd,
10230            self.attn_scale,
10231            rd,
10232            self.hidden_size,
10233            // An MTP draft can have an independently compacted FFN. The
10234            // graph must use the checked local tensor width, not the trunk
10235            // arch-wide intermediate size.
10236            d.gate_proj.rows(),
10237            position,
10238            self.kv_cache.max_seq_len,
10239            gemma,
10240            self.rms_eps as f32,
10241            Some((&lm_gw, lm_rows)),
10242            &m.final_norm,
10243            &mut logits,
10244            &[],
10245            1,
10246            None,
10247            None,
10248            None,
10249            Self::MTP_LAYER_BASE,
10250            true,
10251        );
10252        match ok {
10253            crate::gpu::TokenGraphOutcome::Completed => {}
10254            crate::gpu::TokenGraphOutcome::Declined => return None,
10255            crate::gpu::TokenGraphOutcome::Failed => {
10256                // The backend has already admitted persistent state.  Keep
10257                // this distinct from a capability refusal so the caller
10258                // cannot switch to the stale CPU MTP cache.
10259                self.clear_sequence_state();
10260                self.graph_failed
10261                    .store(true, std::sync::atomic::Ordering::Relaxed);
10262                self.cancel
10263                    .store(true, std::sync::atomic::Ordering::Relaxed);
10264                return None;
10265            }
10266        }
10267        // The graph may deliberately evaluate only a prefix of the draft
10268        // head.  Do not turn every omitted token into a zero-logit candidate:
10269        // that can win an all-negative shortlist and collapses acceptance.
10270        pad_mtp_draft_logits(&mut logits, self.vocab_size);
10271        Some((logits, x))
10272    }
10273
10274    /// The round's `k` greedy drafts on the CUDA hybrid arm as ONE graph
10275    /// (`gpu_cuda::mtp_chain`): the block input, the block and the shortlist
10276    /// head k times, each step's token embedding gathered on the card from
10277    /// the argmax before it. Err(false): declined before any state changed
10278    /// (the per-step loop takes the round); Err(true): failed after the
10279    /// block's mirror moved.
10280    #[cfg(feature = "cuda")]
10281    fn mtp_draft_chain_cuda(&self, m: &MtpModule, hidden: &[f32], t_next: u32, position: usize, k: usize) -> Result<Vec<u32>, bool> {
10282        let position = position.saturating_sub(self.mtp_pos_base);
10283        if !crate::gpu::cuda_active()
10284            || !Self::mtp_chain_on()
10285            || std::env::var("CMF_MTP_GRAPH").as_deref() == Ok("0")
10286            || self.draft_full_streak > 0
10287            || !self.mtp_graph_ok(m)
10288            || hidden.len() != self.hidden_size
10289        {
10290            return Err(false);
10291        }
10292        let lw = &m.layer;
10293        let AttnKind::Full { wq, wk, wv, wo, q_norm, k_norm, output_gate, softplus_gate: None, bias } = &lw.attn else {
10294            return Err(false);
10295        };
10296        let FfnKind::Dense(d) = &lw.ffn else {
10297            return Err(false);
10298        };
10299        if !d.segs.is_empty() {
10300            return Err(false);
10301        }
10302        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
10303            let (_, i, kind, rs) = t.graph_weight()?;
10304            Some(crate::gpu::GraphW { idx: i, kind, row_scale: rs, data: &[], prism: crate::gpu::GraphPrismOp::None, affine: false })
10305        }
10306        let mk = || -> Option<_> {
10307            let (model, _, _, _) = wq.graph_weight()?;
10308            let (_, li, lkind, lrs) = self.weights.lm_head.graph_weight()?;
10309            if lkind != 6 {
10310                return None;
10311            }
10312            let rows = Self::draft_vocab_rows(self.weights.lm_head.rows());
10313            let lm = crate::gpu::GraphW { idx: li, kind: lkind, row_scale: lrs, data: &[], prism: crate::gpu::GraphPrismOp::None, affine: false };
10314            let eh = gw(&m.eh_proj)?;
10315            let layer = crate::gpu::GraphLayer {
10316                engram: None,
10317                mhc: None,
10318                input_norm: &lw.input_norm,
10319                attn: crate::gpu::GraphAttn::Full {
10320                    wq: gw(wq)?,
10321                    wk: gw(wk)?,
10322                    wv: gw(wv)?,
10323                    wo: gw(wo)?,
10324                    q_norm: q_norm.as_deref(),
10325                    k_norm: k_norm.as_deref(),
10326                    late_qk_norm: self.qk_norm_after_rope,
10327                    bias: bias.as_ref().map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
10328                    output_gate: *output_gate,
10329                    cpu_k: m.kv.k_heads(),
10330                    cpu_v: m.kv.v_heads(),
10331                    cpu_base: m.kv.base(),
10332                    geom: None,
10333                    head_gate: None,
10334                },
10335                post_norm: &lw.post_norm,
10336                attn_out_norm: None,
10337                ffn_out_norm: None,
10338                layer_scale: None,
10339                ffn: crate::gpu::GraphFfn::Dense {
10340                    gate: gw(&d.gate_proj)?,
10341                    up: gw(&d.up_proj)?,
10342                    down: gw(&d.down_proj)?,
10343                    act: d.act.graph_act()?,
10344                    limit: 0.0,
10345                    hot: None,
10346                },
10347            };
10348            // the embedding: q4tp in the same file (the chain gathers its rows)
10349            let (emodel, ei, ekind, ers) = self.weights.embed_tokens.graph_weight()?;
10350            if ekind != 6 || !std::sync::Arc::ptr_eq(emodel, model) || crate::prism::is_inverse_embedding(model, &model.tensors[ei].name) {
10351                return None;
10352            }
10353            let emb = crate::gpu::GraphW { idx: ei, kind: ekind, row_scale: ers, data: &[], prism: crate::gpu::GraphPrismOp::None, affine: false };
10354            Some((model.clone(), lm, rows, eh, layer, emb))
10355        };
10356        let Some((model, lm, rows, eh, layer, emb)) = mk() else {
10357            return Err(false);
10358        };
10359        let (nkv, hd, rd) = self.layer_geom(0);
10360        let e0 = self.embed_single(t_next);
10361        crate::gpu_cuda::mtp_chain(
10362            &model,
10363            self.mtp_kv_id(),
10364            &layer,
10365            &self.inv_freq,
10366            hidden,
10367            &e0,
10368            t_next,
10369            k,
10370            self.num_heads,
10371            nkv,
10372            hd,
10373            self.attn_scale,
10374            rd,
10375            self.hidden_size,
10376            position,
10377            self.kv_cache.max_seq_len,
10378            self.norm_style == cortiq_core::NormStyle::Gemma,
10379            self.rms_eps as f32,
10380            (&lm, rows),
10381            &m.final_norm,
10382            &eh,
10383            &m.enorm,
10384            &m.hnorm,
10385            &emb,
10386            Self::MTP_LAYER_BASE,
10387        )
10388    }
10389
10390    /// The warm-ups of one speculative round on the device: every accepted
10391    /// (hidden, token) pair as ONE batched graph run over the MTP block
10392    /// (no head) — its kv_append lands the pairs in the block's mirror.
10393    /// `pairs` are consecutive positions from `first_pos`.  The tri-state
10394    /// result is intentional: a refusal before admission may use the
10395    /// per-row/CPU route, while a failure after admission must terminate the
10396    /// sequence rather than fall through to a stale CPU cache.
10397    #[cfg(feature = "gpu")]
10398    fn mtp_warm_graph(
10399        &mut self,
10400        m: &mut MtpModule,
10401        pairs: &[(&[f32], u32)],
10402        first_pos: usize,
10403    ) -> crate::gpu::BatchGraphOutcome {
10404        let first_pos = first_pos.saturating_sub(self.mtp_pos_base);
10405        if pairs.is_empty() {
10406            return crate::gpu::BatchGraphOutcome::Completed;
10407        }
10408        if !self.mtp_block_graph_ok(m) {
10409            return crate::gpu::BatchGraphOutcome::Declined;
10410        }
10411        let hs = self.hidden_size;
10412        // Block inputs for every pair (eh_proj on the per-op path, one
10413        // matvec each — the plan's own prologue).
10414        let mut hiddens = self.mtp_block_inputs(m, pairs);
10415        debug_assert_eq!(hiddens.len(), pairs.len() * hs);
10416        spec_stamp("w.inp");
10417        let lw = &m.layer;
10418        let AttnKind::Full {
10419            wq,
10420            wk,
10421            wv,
10422            wo,
10423            q_norm,
10424            k_norm,
10425            output_gate,
10426            bias,
10427            ..
10428        } = &lw.attn
10429        else {
10430            return crate::gpu::BatchGraphOutcome::Declined;
10431        };
10432        let FfnKind::Dense(d) = &lw.ffn else {
10433            return crate::gpu::BatchGraphOutcome::Declined;
10434        };
10435        if !d.segs.is_empty() {
10436            return crate::gpu::BatchGraphOutcome::Declined; // tube layers run on the segmented path
10437        }
10438        // The graph has no arm for a projected output gate, and only the
10439        // activations `graph_act` names.
10440        let (
10441            AttnKind::Full {
10442                softplus_gate: None,
10443                ..
10444            },
10445            Some(gact),
10446        ) = (&lw.attn, d.act.graph_act())
10447        else {
10448            return crate::gpu::BatchGraphOutcome::Declined;
10449        };
10450        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
10451            let (_, i, kind, rs) = t.graph_weight()?;
10452            Some(crate::gpu::GraphW {
10453                idx: i,
10454                kind,
10455                row_scale: rs,
10456                data: &[],
10457                prism: crate::gpu::GraphPrismOp::None,
10458                affine: false,
10459            })
10460        }
10461        let Some((model, _, _, _)) = wq.graph_weight() else {
10462            return crate::gpu::BatchGraphOutcome::Declined;
10463        };
10464        let model = model.clone();
10465        let (Some(gwq), Some(gwk), Some(gwv), Some(gwo), Some(gg), Some(gu), Some(gd)) = (
10466            gw(wq),
10467            gw(wk),
10468            gw(wv),
10469            gw(wo),
10470            gw(&d.gate_proj),
10471            gw(&d.up_proj),
10472            gw(&d.down_proj),
10473        ) else {
10474            return crate::gpu::BatchGraphOutcome::Declined;
10475        };
10476        let layer = crate::gpu::GraphLayer {
10477            engram: None,
10478            mhc: None,
10479            input_norm: &lw.input_norm,
10480            attn: crate::gpu::GraphAttn::Full {
10481                wq: gwq,
10482                wk: gwk,
10483                wv: gwv,
10484                wo: gwo,
10485                q_norm: q_norm.as_deref(),
10486                k_norm: k_norm.as_deref(),
10487                late_qk_norm: self.qk_norm_after_rope,
10488                bias: bias
10489                    .as_ref()
10490                    .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
10491                output_gate: *output_gate,
10492                cpu_k: m.kv.k_heads(),
10493                cpu_v: m.kv.v_heads(),
10494                cpu_base: m.kv.base(),
10495                geom: None,
10496                head_gate: None,
10497            },
10498            post_norm: &lw.post_norm,
10499            attn_out_norm: None,
10500            ffn_out_norm: None,
10501            layer_scale: None,
10502            ffn: crate::gpu::GraphFfn::Dense {
10503                gate: gg,
10504                up: gu,
10505                down: gd,
10506                act: gact,
10507                limit: 0.0,
10508                hot: None,
10509            },
10510        };
10511        let positions: Vec<usize> = (first_pos..first_pos + pairs.len()).collect();
10512        let nh = self.num_heads;
10513        let (nkv, hd, rd) = self.layer_geom(0);
10514        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
10515        // nothing reads the block's rows back: the warm-up is its K/V rows
10516        // (no readback, no wait; the next prompt chunk is encoded while the
10517        // card runs it — on wgpu too: SenseNova-Loop-9B over Vulkan waited
10518        // ~0.35 s a 512-row chunk). `CMF_MTP_WARM_DEFER=0` waits.
10519        let defer = (crate::gpu::cuda_active() || crate::gpu::wgpu_active())
10520            && std::env::var("CMF_MTP_WARM_DEFER").as_deref() != Ok("0");
10521        if defer {
10522            crate::gpu::set_batch_defer(true);
10523        }
10524        let out = crate::gpu::forward_batch_graph(
10525            &model,
10526            self.mtp_kv_id(),
10527            std::slice::from_ref(&layer),
10528            &self.inv_freq,
10529            &mut hiddens,
10530            nh,
10531            nkv,
10532            hd,
10533            rd,
10534            hs,
10535            // See `mtp_step_graph`: draft FFN geometry is local to this
10536            // block after independent MTP compaction.
10537            d.gate_proj.rows(),
10538            &positions,
10539            self.kv_cache.max_seq_len,
10540            gemma,
10541            self.rms_eps as f32,
10542            self.attn_scale,
10543            pairs.len(),
10544            &[],
10545            0,
10546            None,
10547            None,
10548        );
10549        if defer {
10550            crate::gpu::set_batch_defer(false);
10551        }
10552        spec_stamp("w.run");
10553        out
10554    }
10555
10556    /// Complete an MTP warm-up after the batched graph has refused.  A
10557    /// graphable block is retried one row at a time; once any device row has
10558    /// been admitted, a CPU fallback would observe a stale mirror, so every
10559    /// token-graph refusal is terminal.  If the block is not graphable and no
10560    /// mirror exists yet, warming on the CPU is safe and records the CPU mode
10561    /// for the rest of the generation.
10562    #[cfg(feature = "gpu")]
10563    fn mtp_warm_graph_fallback(
10564        &mut self,
10565        m: &mut MtpModule,
10566        pairs: &[(&[f32], u32)],
10567        first_pos: usize,
10568    ) -> bool {
10569        let first_pos = first_pos.saturating_sub(self.mtp_pos_base);
10570        if pairs.is_empty() {
10571            return true;
10572        }
10573        let graphable = self.mtp_block_graph_ok(m);
10574        if !graphable {
10575            // A previously admitted mirror cannot be made coherent by
10576            // appending to the host cache.  The caller turns this into a
10577            // terminal generation error and clears both mirrors.
10578            if self.mtp_graph_mode == Some(true) {
10579                return false;
10580            }
10581            self.mtp_graph_mode = Some(false);
10582            for (j, (h, t)) in pairs.iter().enumerate() {
10583                self.mtp_warm(m, h, *t, first_pos + j);
10584            }
10585            return true;
10586        }
10587
10588        // The batch refusal is recoverable only through the same device
10589        // state.  Keep rows owned until each token graph has completed; a
10590        // None is treated as unsafe because the token-graph API deliberately
10591        // collapses its backend refusal/failure into that result.
10592        for (j, (h, t)) in pairs.iter().enumerate() {
10593            if self.mtp_step_graph(m, h, *t, first_pos + j).is_none() {
10594                return false;
10595            }
10596        }
10597        self.mtp_graph_mode = Some(true);
10598        true
10599    }
10600
10601    /// Warm a contiguous set of MTP pairs using the existing graph seam, with
10602    /// an all-or-nothing error contract for callers that already admitted the
10603    /// trunk batch.  The non-GPU build keeps the same pair accounting while
10604    /// using the established CPU warm path.
10605    #[cfg(feature = "gpu")]
10606    fn mtp_warm_prefill_pairs(
10607        &mut self,
10608        m: &mut MtpModule,
10609        pairs: &[(&[f32], u32)],
10610        first_pos: usize,
10611    ) -> Result<(), &'static str> {
10612        // Keep unsupported token-graph heads on the established CPU MTP
10613        // route before admitting any block mirror.  Once a device mirror is
10614        // active, the same condition is terminal because CPU rows cannot
10615        // repair its state.
10616        if self.mtp_graph_mode == Some(false) || !self.mtp_graph_ok(m) {
10617            if self.mtp_graph_mode == Some(true) {
10618                return Err("MTP token graph became unavailable after admission");
10619            }
10620            self.mtp_graph_mode = Some(false);
10621            for (j, (h, t)) in pairs.iter().enumerate() {
10622                self.mtp_warm(m, h, *t, first_pos + j);
10623            }
10624            return Ok(());
10625        }
10626        match self.mtp_warm_graph(m, pairs, first_pos) {
10627            crate::gpu::BatchGraphOutcome::Completed => {
10628                if !pairs.is_empty() {
10629                    self.mtp_graph_mode = Some(true);
10630                }
10631                Ok(())
10632            }
10633            crate::gpu::BatchGraphOutcome::Declined => {
10634                if self.mtp_warm_graph_fallback(m, pairs, first_pos) {
10635                    Ok(())
10636                } else {
10637                    Err("MTP warm-up fallback failed after device admission")
10638                }
10639            }
10640            crate::gpu::BatchGraphOutcome::Failed => {
10641                Err("MTP warm batch graph failed after admission")
10642            }
10643        }
10644    }
10645
10646    #[cfg(not(feature = "gpu"))]
10647    fn mtp_warm_prefill_pairs(
10648        &mut self,
10649        m: &mut MtpModule,
10650        pairs: &[(&[f32], u32)],
10651        first_pos: usize,
10652    ) -> Result<(), &'static str> {
10653        for (j, (h, t)) in pairs.iter().enumerate() {
10654            self.mtp_warm(m, h, *t, first_pos + j);
10655        }
10656        Ok(())
10657    }
10658
10659    /// The MTP block alone — advance its KV with a (hidden, token) pair the
10660    /// verify just proved, without paying the head. What keeps the draft's
10661    /// attention context warm between speculative rounds.
10662    fn mtp_warm(&mut self, m: &mut MtpModule, hidden: &[f32], next_token: u32, position: usize) {
10663        let position = position.saturating_sub(self.mtp_pos_base);
10664        let e = self.embed_single(next_token);
10665        let mut cat = vec![0.0f32; 2 * self.hidden_size];
10666        let (cat_e, cat_h) = cat.split_at_mut(self.hidden_size);
10667        inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
10668        inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
10669        let mut x = vec![0.0f32; self.hidden_size];
10670        m.eh_proj.matvec(&cat, &mut x, self.pool.as_deref());
10671        inference::rms_norm_into(
10672            &x,
10673            &m.layer.input_norm,
10674            self.rms_eps,
10675            self.norm_style,
10676            &mut self.ws.n1,
10677        );
10678        let attn = match &m.layer.attn {
10679            AttnKind::Full {
10680                wq,
10681                wk,
10682                wv,
10683                wo,
10684                q_norm,
10685                k_norm,
10686                output_gate,
10687                softplus_gate,
10688                bias,
10689            } => {
10690                let mut cfg = self.attn_cfg(position);
10691                cfg.q_norm = q_norm.as_deref();
10692                cfg.k_norm = k_norm.as_deref();
10693                cfg.output_gate = *output_gate;
10694                cfg.softplus_gate = softplus_gate.as_ref().map(|(g, p)| (g, *p));
10695                cfg.bias = bias
10696                    .as_ref()
10697                    .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice()));
10698                attention::qwen_attention(&self.ws.n1, wq, wk, wv, wo, &mut m.kv, &cfg)
10699            }
10700            _ => return,
10701        };
10702        let _ = attn;
10703    }
10704
10705    /// Speculative decode ON the wgpu whole-token graph: draft k with the
10706    /// MTP head, verify all of them plus the tip in ONE batched graph
10707    /// submit whose tail folds the head, commit the accepted prefix and
10708    /// roll the GDN state back to the last real position. Greedy only —
10709    /// output equals the plain graph's token for token, the way the DSV4
10710    /// verify equals the walk.
10711    #[cfg(feature = "gpu")]
10712    #[allow(clippy::too_many_arguments)]
10713    fn graph_spec_step(
10714        &mut self,
10715        m: &mut MtpModule,
10716        hidden: &[f32],
10717        t_next: u32,
10718        next_pos: usize,
10719        drafted: &mut usize,
10720        accepted: &mut usize,
10721        // The committed stream (prompt + generated so far, `t_next`
10722        // included): the sampler chain's penalties read it, and the
10723        // sampling arm extends it with the drafts position by position.
10724        all_ids: &mut Vec<u32>,
10725        // Tokens left before `max_tokens`. A round commits up to k
10726        // accepted drafts, and those positions are already in the cache,
10727        // so the depth is capped here — trimming the output afterwards
10728        // would leave cache rows the committed stream does not have.
10729        room: usize,
10730    ) -> Option<(Vec<u32>, usize, Vec<f32>)> {
10731        // 3 is the measured optimum on Qwen3.6-27B / RTX 5090 (medians
10732        // of three, greedy): 51.1 tok/s against a plain 49.4, where k=2
10733        // gives 46.1, k=4 50.0, k=5 47.4, k=6 45.2. Acceptance is 89-91%
10734        // throughout — what turns the curve over is the verify, which
10735        // costs ~7.4 ms per extra position, and the draft ~3 ms a step.
10736        // 4 since the draft moved onto the graph (Qwen3.8-27B / 5090:
10737        // k=3 51.2, k=4 51.8 with the per-op draft; the graph draft
10738        // halves the draft cost, so the extra draft is cheaper still).
10739        // 5 with the int8 verify (the default: measured 76.5 against
10740        // k=4's 72-74 and k=6's 74 on the 5090), 4 with the f32 one.
10741        #[cfg(target_os = "macos")]
10742        let metal_native = crate::gpu::q1_force();
10743        #[cfg(not(target_os = "macos"))]
10744        let metal_native = false;
10745        #[cfg(feature = "gpu")]
10746        let k_default = if metal_native {
10747            // the Metal verify's GEMM tile is 8 rows wide and flat in b:
10748            // seven drafts + the tip fill it for free
10749            7
10750        } else if crate::gpu_wgpu::verify_i8_on() {
10751            5
10752        } else {
10753            4
10754        };
10755        #[cfg(not(feature = "gpu"))]
10756        let k_default = 4;
10757        let k_env: Option<usize> = std::env::var("CMF_GRAPH_SPEC_K")
10758            .ok()
10759            .and_then(|v| v.parse().ok())
10760            .filter(|&v| (1..=8).contains(&v));
10761        // Adaptive depth: start below the card's flat-verify optimum and
10762        // let the accepted fraction move it — predictable text climbs to
10763        // the old default within a few rounds, prose settles at 2-3 where
10764        // the shorter verify pays.
10765        // Native Metal over a q4tp trunk: two rows verify at about a plain
10766        // token's price and three at a quarter more, so the depth follows
10767        // each depth's running acceptance instead of filling the GEMM tile.
10768        let metal_small = metal_native && self.metal_small_batch_verify();
10769        // Greedy without penalties verifies by argmax equality (bit-exact
10770        // against the plain path). Anything else is speculative SAMPLING:
10771        // each draft is a DRAW from the MTP head's post-chain distribution
10772        // q_j, kept for the accept test; the verify's rows give p_j.
10773        let cfg = self.sampler_config.clone();
10774        let penalized = !(cfg.repetition_penalty == 1.0
10775            && cfg.presence_penalty == 0.0
10776            && cfg.suppress_tokens.is_empty());
10777        // Three verify regimes: plain greedy (argmax of the raw rows),
10778        // greedy WITH penalties (argmax of the penalized rows — a single
10779        // pass each, no distributions), and sampling (draw / accept /
10780        // correct on post-chain distributions).
10781        let greedy_pen = cfg.temperature < 1e-6 && penalized;
10782        let sampling = cfg.temperature >= 1e-6;
10783        // A DFlash drafter beside the model drafts a round in one block
10784        // (plain greedy on native Metal, where the verify hands it the
10785        // trunk's rows). Its block costs the same at any depth, so its
10786        // rounds go deep where its drafts hold; the MTP chain's are short
10787        // and nearly free. Each keeps its own account of what it holds, and
10788        // the round goes to the one that lands more tokens in a unit of time
10789        // (the one in turn has to be beaten by more than the noise). The
10790        // block was trained on Latin-script text: while the committed tokens
10791        // come from the high table (`draft_full_streak`) the chain keeps the
10792        // rounds. A turn the chain takes back makes the block sit out, longer
10793        // each time it is a short one.
10794        // The wgpu graphs keep the drafter's rows on their way (`layer_taps`):
10795        // they become context here, and a round is the block's only while that
10796        // context reaches the tip. There the block is for measuring, pinned
10797        // with `CMF_DFLASH_PICK=dflash`, and the chain keeps the rounds
10798        // otherwise: the block is a matrix a submission, and on a 16 GB card
10799        // the Turbo trunk leaves its 1.3 GB no room among the resident weights
10800        // (RTX 2000 Ada: 135 ms a block against 11 ms for the chain's drafts,
10801        // and a verify of eight rows costs two plain tokens).
10802        if !metal_native {
10803            self.dflash_taps_absorb();
10804        }
10805        // The CUDA hybrid arm keeps the drafter's context at the tip every
10806        // call (its graphs copy the tapped rows out) and verifies eight rows
10807        // at about one price: the round goes to the drafter that lands more
10808        // tokens at that card's prices, as on Metal.
10809        let cuda_rate = !metal_native && crate::gpu::cuda_active();
10810        let dflash_ok = !sampling
10811            && !greedy_pen
10812            && match &self.dflash {
10813                Some(d) => metal_native || ((dflash_pick() == Some(true) || cuda_rate) && d.next_position() == next_pos),
10814                None => false,
10815            };
10816        if !metal_native && !cuda_rate && self.dflash.is_some() && dflash_pick() != Some(true) {
10817            static SAID: std::sync::Once = std::sync::Once::new();
10818            SAID.call_once(|| {
10819                tracing::info!(
10820                    "DFlash drafter: on wgpu the MTP chain keeps the rounds (CMF_DFLASH_PICK=dflash pins the block)"
10821                )
10822            });
10823        }
10824        let (k_flash, rate_flash) = if cuda_rate {
10825            spec_plan_at(&CUDA_ROUND_COST, &self.dflash_hold, CUDA_BLOCK_DRAFT, 0.0)
10826        } else {
10827            metal_spec_plan(&self.dflash_hold, DFLASH_ROUND_DRAFT)
10828        };
10829        let (_, rate_mtp) = if cuda_rate {
10830            spec_plan_at(&CUDA_ROUND_COST, &self.spec_hold, 0.0, CUDA_DRAFT_STEP)
10831        } else {
10832            metal_spec_plan(&self.spec_hold, 0.0)
10833        };
10834        // A sidecar that carries a router says which drafter the text at the
10835        // tip is for, from the target's own row there: two subspaces of such
10836        // rows, one of the rounds the block won and one of the chain's, and
10837        // the row goes to the one that holds it better (`dflash::Route`).
10838        // A few rounds are averaged, and the drafter in turn keeps a round
10839        // the average does not clearly give away.
10840        let routed = match (&self.dflash, dflash_ok) {
10841            (Some(d), true) => d.route.as_ref().map(|r| r.margin(hidden)),
10842            _ => None,
10843        };
10844        if let Some(m) = routed {
10845            self.dflash_lean += DFLASH_LEAN_STEP * (m - self.dflash_lean);
10846        }
10847        // CUDA verifies a lookup of sixteen rows at about one price: while the
10848        // lookups land (their running gain past `DFLASH_LOOKUP_KEEPS`), an
10849        // edit or a quote stays the chain's, which the router (fitted where
10850        // the lookup was eight rows) would give the block
10851        let copying = (routed.is_some() || cuda_rate)
10852            && dflash_pick().is_none()
10853            && (tail_repeat(all_ids) >= DFLASH_COPY_MIN || (cuda_rate && self.spec_lookup_gain > DFLASH_LOOKUP_KEEPS));
10854        let dflash_round = dflash_ok
10855            && match (dflash_pick(), routed) {
10856                (Some(pin), _) => pin,
10857                (None, Some(_)) if copying => false,
10858                // the block drafts over the head's shortlist: text from the
10859                // high table is the chain's (CUDA, where the router alone
10860                // sent a Danish article to the block: 55 against 73 tok/s)
10861                (None, Some(_)) if cuda_rate && self.draft_full_streak > 0 => false,
10862                (None, Some(_)) if self.dflash_last => self.dflash_lean > -DFLASH_LEAN_BAND,
10863                (None, Some(_)) => self.dflash_lean > DFLASH_LEAN_BAND,
10864                // the chain's short round with the prompt lookup copies for less
10865                (None, None) if copying => false,
10866                (None, None) if !metal_small && !cuda_rate => true,
10867                (None, None) if self.draft_full_streak > 0 => false,
10868                (None, None) if self.dflash_last => rate_flash * 1.05 >= rate_mtp,
10869                (None, None) if self.dflash_wait > 0 => {
10870                    self.dflash_wait -= 1;
10871                    false
10872                }
10873                (None, None) => rate_flash > rate_mtp * 1.05,
10874            };
10875        if dflash_ok && dflash_round != self.dflash_last {
10876            if dflash_round {
10877                (self.dflash_turn, self.dflash_turn_sum) = (0, (0.0, 0.0));
10878            } else {
10879                // the block's turn is over: it comes back to a fresh account
10880                let (tokens, cost) = self.dflash_turn_sum;
10881                if self.dflash_turn >= DFLASH_TURN && tokens >= rate_mtp * cost {
10882                    self.dflash_wait = DFLASH_WAIT_DIP;
10883                } else {
10884                    self.dflash_back = if self.dflash_turn < DFLASH_TURN {
10885                        (self.dflash_back * 2).min(DFLASH_WAIT_MOST)
10886                    } else {
10887                        DFLASH_WAIT
10888                    };
10889                    self.dflash_wait = self.dflash_back;
10890                }
10891                self.dflash_hold = DFLASH_HOLD_PRIOR;
10892            }
10893            if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
10894                eprintln!(
10895                    "spec-drafter: {} ({rate_flash:.2} against {rate_mtp:.2} tokens in a plain token's time)",
10896                    if dflash_round { "the DFlash block" } else { "the MTP chain" }
10897                );
10898            }
10899        }
10900        self.dflash_turn += u32::from(dflash_round);
10901        self.dflash_last = dflash_round;
10902        // a pinned block never hands a round to the chain: its cache may lapse
10903        let mtp_in_step = dflash_pick() != Some(true) || dflash_rows_log().is_some();
10904        let (k_start, k_max) = if dflash_round && metal_small {
10905            (k_flash, 7)
10906        } else if metal_small {
10907            (metal_spec_depth(&self.spec_hold), 7)
10908        } else if metal_native || dflash_round {
10909            // (a block costs the same at any depth: its rounds start at all seven)
10910            (7, 7)
10911        } else {
10912            (3, k_default.max(5))
10913        };
10914        let k_full: usize = k_env.unwrap_or_else(|| {
10915            if metal_small {
10916                k_start
10917            } else if dflash_round && !metal_native {
10918                self.dflash_k_adapt.unwrap_or(k_start)
10919            } else {
10920                self.spec_k_adapt.unwrap_or(k_start)
10921            }
10922        });
10923        let k_spec = k_full.min(room).max(1);
10924        // a tail round cut short by `room` says nothing about the text:
10925        // it must not move the adaptive depth the next request starts at
10926        let k_capped = k_spec < k_full;
10927        if next_pos == 0 {
10928            return None;
10929        }
10930        let t_round = std::time::Instant::now();
10931        // Submissions per phase — and they say where the round's money is.
10932        // Qwen3.6-27B on an RTX 5090, k=3:
10933        //
10934        //   draft   9.3 ms / 12 submissions   (four per MTP step)
10935        //   verify 52.8 ms /  1               (the batched graph)
10936        //   commit  5.4 ms /  6               (two per warm)
10937        //
10938        // The verify is already one submit. The draft's own work is 834 MB
10939        // a step — 0.8 ms at this card's measured 1056 GB/s — against 3.1
10940        // ms measured, so ~0.58 ms of every step is round trip, not
10941        // arithmetic, and the same holds for the warms. Eighteen round
10942        // trips a round at roughly half a millisecond each is ~11 ms of a
10943        // 68 ms round: fusing the MTP block into ONE submit the way the
10944        // trunk already is projects to ~64 tok/s against today's 50.9.
10945        // That is the largest measured item left on this path.
10946        let subs = || crate::gpu_wgpu::SUBMITS.load(std::sync::atomic::Ordering::Relaxed);
10947        let sub0 = subs();
10948        let k_spec = match &self.dflash {
10949            Some(d) if dflash_round => k_spec.min(d.g.block - 1),
10950            _ => k_spec,
10951        };
10952        // Sampling with a top-k goes through the SPARSE chain: the dense
10953        // one builds nine 248k-float distributions a round (four drafts,
10954        // five verify rows) and measured 19-22 tok/s against a plain 40 —
10955        // the host, not the card. Sparse, the same nine cost tens of
10956        // microseconds each.
10957        let sparse = sampling && sampler::sparse_ok(&cfg);
10958        let base_len = all_ids.len();
10959        if sampling && !sparse && self.spec_q.len() < k_spec {
10960            self.spec_q.resize_with(k_spec, Vec::new);
10961        }
10962        if sparse && self.spec_qs.len() < k_spec {
10963            self.spec_qs.resize_with(k_spec, Vec::new);
10964        }
10965        // Draft the chain: first from the trunk's tip hidden, then the head
10966        // iterating on itself. Rows land in the MTP KV; the chain rows past
10967        // the first are speculation over speculative state and roll back
10968        // below, replaced by verified pairs.
10969        let mut drafts = Vec::with_capacity(k_spec);
10970        let mut hx = hidden.to_vec();
10971        // CMF_SPEC_DBG=1: draft 0 through BOTH MTP arms (graph and per-op)
10972        // from the same inputs — are the arms the difference, or the inputs?
10973        let spec_dbg = std::env::var("CMF_SPEC_DBG").is_ok();
10974        spec_stamp("pro");
10975        if dflash_round {
10976            drafts = self.dflash_draft(t_next, next_pos, k_spec);
10977            spec_stamp("d.flash");
10978        }
10979        // the chain's drafts of a round the block has, for the rows log: its
10980        // cache is then cut and warmed as after a round of its own
10981        let mut beside: Vec<u32> = Vec::new();
10982        #[cfg(target_os = "macos")]
10983        if dflash_round && dflash_rows_log().is_some() && self.mtp_graph_mode != Some(false) {
10984            match self.mtp_draft_chain_metal(m, hidden, t_next, next_pos - 1, 7) {
10985                Ok(ids) => {
10986                    self.mtp_graph_mode = Some(true);
10987                    beside = ids;
10988                }
10989                Err(true) => {
10990                    tracing::error!("mtp Metal draft chain failed after commit");
10991                    self.clear_sequence_state();
10992                    self.graph_failed
10993                        .store(true, std::sync::atomic::Ordering::Relaxed);
10994                    self.cancel
10995                        .store(true, std::sync::atomic::Ordering::Relaxed);
10996                    return None;
10997                }
10998                Err(false) => {}
10999            }
11000        }
11001        // Plain greedy on native Metal: the whole chain as one command
11002        // buffer (device argmax + embedding gather between the steps).
11003        // A decline before commit hands the round to the per-step loop
11004        // below; a failure after commit is terminal, like any graph
11005        // failure after admission.
11006        #[cfg(target_os = "macos")]
11007        if metal_native && !dflash_round && !sampling && !greedy_pen && self.mtp_graph_mode != Some(false) {
11008            match self.mtp_draft_chain_metal(m, hidden, t_next, next_pos - 1, k_spec) {
11009                Ok(ids) => {
11010                    self.mtp_graph_mode = Some(true);
11011                    drafts = ids;
11012                }
11013                Err(true) => {
11014                    tracing::error!("mtp Metal draft chain failed after commit");
11015                    self.clear_sequence_state();
11016                    self.graph_failed
11017                        .store(true, std::sync::atomic::Ordering::Relaxed);
11018                    self.cancel
11019                        .store(true, std::sync::atomic::Ordering::Relaxed);
11020                    return None;
11021                }
11022                Err(false) => {}
11023            }
11024        }
11025        // CUDA hybrid arm, greedy: the whole chain as one graph (device
11026        // argmax and embedding gather between the steps). A suppress list
11027        // whose ids all sit past the draft shortlist cannot change its
11028        // argmax. A decline hands the round to the per-step loop below; a
11029        // failure after admission is terminal, like any graph failure.
11030        #[cfg(feature = "cuda")]
11031        if crate::gpu::cuda_active()
11032            && !dflash_round
11033            && !sampling
11034            && !spec_dbg
11035            && drafts.is_empty()
11036            && self.mtp_graph_mode != Some(false)
11037            && (!greedy_pen
11038                || (cfg.repetition_penalty == 1.0
11039                    && cfg.presence_penalty == 0.0
11040                    && cfg.suppress_tokens.iter().all(|&t| (t as usize) >= Self::draft_vocab_rows(self.weights.lm_head.rows()))))
11041        {
11042            match self.mtp_draft_chain_cuda(m, &hx, t_next, next_pos - 1, k_spec) {
11043                Ok(ids) => {
11044                    self.mtp_graph_mode = Some(true);
11045                    drafts = ids;
11046                    spec_stamp("d.chain");
11047                }
11048                Err(true) => {
11049                    tracing::error!("cuda draft chain failed after admission");
11050                    self.clear_sequence_state();
11051                    self.graph_failed
11052                        .store(true, std::sync::atomic::Ordering::Relaxed);
11053                    self.cancel
11054                        .store(true, std::sync::atomic::Ordering::Relaxed);
11055                    return None;
11056                }
11057                Err(false) => {}
11058            }
11059        }
11060        for j in drafts.len()..k_spec {
11061            let tok_in = if j == 0 { t_next } else { drafts[j - 1] };
11062            let mut dbg_ref: Option<(Vec<f32>, Vec<f32>)> = None;
11063            if spec_dbg {
11064                let saved = self.mtp_graph_mode;
11065                self.mtp_graph_mode = Some(false);
11066                let r = self.mtp_step_hl(m, &hx, tok_in, next_pos - 1 + j);
11067                self.mtp_graph_mode = saved;
11068                if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
11069                    return None;
11070                }
11071                m.kv.truncate_last(1);
11072                dbg_ref = Some(r);
11073            }
11074            let (mut lg, hj) = self.mtp_step_hl(m, &hx, tok_in, next_pos - 1 + j);
11075            if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
11076                return None;
11077            }
11078            if let Some((lg_cpu, h_cpu)) = dbg_ref {
11079                let n = |v: &[f32]| v.iter().map(|x| x * x).sum::<f32>().sqrt();
11080                let dl = lg
11081                    .iter()
11082                    .zip(&lg_cpu)
11083                    .fold(0f32, |m, (a, b)| m.max((a - b).abs()));
11084                let dh = hj
11085                    .iter()
11086                    .zip(&h_cpu)
11087                    .fold(0f32, |m, (a, b)| m.max((a - b).abs()));
11088                eprintln!(
11089                    "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 {}",
11090                    next_pos - 1 + j,
11091                    sampler::argmax(&lg_cpu),
11092                    sampler::argmax(&lg),
11093                    n(&h_cpu),
11094                    n(&hj),
11095                    m.kv.seq_len
11096                );
11097            }
11098            let dj = if sparse {
11099                let mut q = std::mem::take(&mut self.spec_qs[j]);
11100                let ok = sampler::sparse_distribution_into(
11101                    &lg,
11102                    &cfg,
11103                    all_ids,
11104                    &mut self.sampler_scratch,
11105                    self.pool.as_deref(),
11106                    &mut q,
11107                );
11108                let d = if ok {
11109                    sampler::draw_sparse(&q, &mut self.rng)
11110                } else {
11111                    // everything filtered: the dense chain's greedy fallback
11112                    let t = sampler::argmax(&lg);
11113                    q.clear();
11114                    q.push((t, 1.0));
11115                    t
11116                };
11117                self.spec_qs[j] = q;
11118                all_ids.push(d);
11119                d
11120            } else if sampling {
11121                let mut q = std::mem::take(&mut self.spec_q[j]);
11122                sampler::distribution_into(
11123                    &lg,
11124                    &cfg,
11125                    all_ids,
11126                    &mut self.sampler_scratch,
11127                    self.pool.as_deref(),
11128                    &mut q,
11129                );
11130                let d = sampler::draw(&q, &mut self.rng);
11131                self.spec_q[j] = q;
11132                all_ids.push(d); // the next draft's penalties see this one
11133                d
11134            } else if greedy_pen {
11135                let d = sampler::argmax_penalized(
11136                    &lg,
11137                    &cfg,
11138                    all_ids,
11139                    &mut self.sampler_scratch,
11140                    self.pool.as_deref(),
11141                );
11142                all_ids.push(d);
11143                d
11144            } else {
11145                sampler::argmax(&lg)
11146            };
11147            attention::recycle_buf(&mut lg);
11148            drafts.push(dj);
11149            hx = hj;
11150            spec_stamp("d.pick");
11151        }
11152        all_ids.truncate(base_len);
11153        // Prompt lookup, plain greedy on native Metal, where a verify of
11154        // four to eight rows has one price: when the tip and the head's
11155        // drafts repeat an earlier stretch of the sequence, the tokens that
11156        // followed it there go on as drafts. The head's drafts are the
11157        // test: a lookup continues only what they agree with.
11158        let k_mtp = k_spec;
11159        // steps the MTP block took this round: its own round's drafts, the
11160        // chain run beside a DFlash block, or none
11161        let mtp_steps = if dflash_round { beside.len() } else { k_mtp };
11162        // The CUDA hybrid arm verifies up to 16 rows on the tensor cores at
11163        // about one price (8 rows 1.05x a plain token, 16 about 1.6x on a
11164        // 3090): a copy may run 15 drafts deep there.
11165        let cuda_window = crate::gpu::cuda_active();
11166        let k_room = room.min(if cuda_window && self.spec_lookup_wide { 15 } else { 7 });
11167        // A suppress list alone scores a continuation the same at any
11168        // history, so the CUDA window takes lookups under it too.
11169        let history_free = cfg.repetition_penalty == 1.0 && cfg.presence_penalty == 0.0;
11170        if (metal_native || cuda_window)
11171            && !sampling
11172            && (!greedy_pen || (cuda_window && history_free))
11173            && k_mtp < k_room
11174            && drafts.len() == k_mtp
11175            && Self::spec_lookup_on()
11176        {
11177            if self.spec_lookup_rest > 0 {
11178                self.spec_lookup_rest -= 1;
11179            } else {
11180                all_ids.extend_from_slice(&drafts);
11181                let more =
11182                    lookup_continuation(all_ids, k_mtp + LOOKUP_MIN_REAL, k_room - k_mtp).to_vec();
11183                all_ids.truncate(base_len);
11184                drafts.extend(more);
11185            }
11186        }
11187        let k_spec = drafts.len();
11188        spec_stamp("d.look");
11189        *drafted += k_spec;
11190        let t_draft = t_round.elapsed();
11191        let sub_draft = subs();
11192        // Verify batch: [t_next, d1 .. d_{k-1}] at next_pos.. — every row's
11193        // logits come back from the graph's own head.
11194        let b = k_spec + 1;
11195        let mut hiddens = vec![0.0f32; b * self.hidden_size];
11196        for (i, &t) in std::iter::once(&t_next).chain(drafts.iter()).enumerate() {
11197            let e = self.embed_single(t);
11198            hiddens[i * self.hidden_size..(i + 1) * self.hidden_size].copy_from_slice(&e);
11199        }
11200        let positions: Vec<usize> = (next_pos..next_pos + b).collect();
11201        spec_stamp("v.emb");
11202        let (lm_gw, lm_rows) = {
11203            let (_, i, kind, rs) = self.weights.lm_head.graph_weight()?;
11204            (
11205                crate::gpu::GraphW {
11206                    idx: i,
11207                    kind,
11208                    row_scale: rs,
11209                    data: &[],
11210                    prism: crate::gpu::GraphPrismOp::None,
11211                    affine: false,
11212                },
11213                self.weights.lm_head.rows(),
11214            )
11215        };
11216        let mut logits = Vec::new();
11217        let final_norm = self.weights.final_norm.clone();
11218        // Plain greedy on Metal: the b argmaxes come from the device
11219        // (`argmax_rows` after the head) and the 7.9 MB logits plane is
11220        // never read back — the round's decision needs only the ids, and
11221        // the loop top takes the last verified id as `spec_forced`, which
11222        // is exactly what its argmax of the row would give. The full rows
11223        // stay for anything that reads them: sampling, penalties,
11224        // confidence, the verify oracle, the logit dump.
11225        // `CMF_METAL_DEV_ARGMAX=0` keeps the host path.
11226        #[cfg(target_os = "macos")]
11227        let greedy_dev = metal_native
11228            && !sampling
11229            && !greedy_pen
11230            && !self.confidence_on
11231            && self.final_softcap.is_none()
11232            // The host acceptance argmax scans the WHOLE head row
11233            // (`lm_rows`), the sampler's own row only `vocab_size`: they
11234            // coincide exactly when the head has no padding rows, and
11235            // only then is the device argmax (which scores `vocab_size`)
11236            // bit-identical to both.
11237            && self.vocab_size == lm_rows
11238            && std::env::var_os("CMF_METAL_VERIFY_CHECK").is_none()
11239            && std::env::var_os("CMF_LOGIT_DUMP").is_none()
11240            && std::env::var("CMF_METAL_DEV_ARGMAX").as_deref() != Ok("0");
11241        // The CUDA hybrid arm the same way: each verify row's argmax on the
11242        // card (the host's tie rule), 5 MB of logits not read back.
11243        // `CMF_CUDA_DEV_ARGMAX=0` keeps the host path.
11244        #[cfg(all(not(target_os = "macos"), feature = "cuda"))]
11245        let greedy_dev = crate::gpu::cuda_active()
11246            && !sampling
11247            && !greedy_pen
11248            && !self.confidence_on
11249            && self.final_softcap.is_none()
11250            && self.vocab_size == lm_rows
11251            && std::env::var_os("CMF_LOGIT_DUMP").is_none()
11252            && std::env::var("CMF_CUDA_DEV_ARGMAX").as_deref() != Ok("0");
11253        #[cfg(all(not(target_os = "macos"), not(feature = "cuda")))]
11254        let greedy_dev = false;
11255        let mut dev_ids: Vec<u32> = Vec::new();
11256        #[cfg(target_os = "macos")]
11257        let verify_outcome = if metal_native {
11258            let lm = self.weights.lm_head.q1_parts()?;
11259            let n_score = self.vocab_size.min(lm_rows);
11260            self.try_batch_graph_metal(
11261                &mut hiddens,
11262                &positions,
11263                b,
11264                Some((lm, &final_norm, &mut logits)),
11265                if greedy_dev {
11266                    Some((n_score, &mut dev_ids))
11267                } else {
11268                    None
11269                },
11270            )
11271        } else {
11272            self.try_batch_graph_wgpu(
11273                &mut hiddens,
11274                &positions,
11275                b,
11276                Some(crate::gpu::SpecTail {
11277                    lm: lm_gw,
11278                    lm_rows,
11279                    final_norm: &final_norm,
11280                    logits_out: &mut logits,
11281                    pick: None,
11282                }),
11283            )
11284        };
11285        #[cfg(all(not(target_os = "macos"), feature = "cuda"))]
11286        crate::gpu_cuda::verify_argmax_arm(greedy_dev);
11287        #[cfg(not(target_os = "macos"))]
11288        let verify_outcome = self.try_batch_graph_wgpu(
11289            &mut hiddens,
11290            &positions,
11291            b,
11292            Some(crate::gpu::SpecTail {
11293                lm: lm_gw,
11294                lm_rows,
11295                final_norm: &final_norm,
11296                logits_out: &mut logits,
11297                pick: None,
11298            }),
11299        );
11300        #[cfg(all(not(target_os = "macos"), feature = "cuda"))]
11301        if greedy_dev {
11302            if let Some(ids) = crate::gpu_cuda::verify_argmax_take() {
11303                dev_ids = ids;
11304            }
11305        }
11306        match verify_outcome {
11307            crate::gpu::BatchGraphOutcome::Completed => {}
11308            crate::gpu::BatchGraphOutcome::Declined => {
11309                // The verifier refused before admission.  Its draft MTP
11310                // rows are still device-resident, so rewind the separate
11311                // mirror before the caller takes the exact one-token path.
11312                // (A DFlash round put no rows there.)
11313                self.dflash_rows = None;
11314                m.kv.truncate_last(mtp_steps);
11315                if !metal_native && mtp_steps > 0 && !self.rewind_mtp_graph_mirror(next_pos) {
11316                    self.clear_sequence_state();
11317                    self.graph_failed
11318                        .store(true, std::sync::atomic::Ordering::Relaxed);
11319                    self.cancel
11320                        .store(true, std::sync::atomic::Ordering::Relaxed);
11321                    tracing::error!("MTP graph mirror rewind failed after verify decline");
11322                }
11323                return None;
11324            }
11325            crate::gpu::BatchGraphOutcome::Failed => {
11326                // A failed batch may have advanced trunk/GDN state.  Clear
11327                // both mirrors and preserve the terminal outcome rather than
11328                // falling through to stale CPU state.
11329                self.clear_sequence_state();
11330                self.graph_failed
11331                    .store(true, std::sync::atomic::Ordering::Relaxed);
11332                self.cancel
11333                    .store(true, std::sync::atomic::Ordering::Relaxed);
11334                tracing::error!("MTP verify batch graph failed after admission");
11335                self.dflash_rows = None;
11336                return None;
11337            }
11338        }
11339        // `CMF_METAL_VERIFY_CHECK=1`: run the same b tokens through the
11340        // plain per-token path and compare each row's argmax + logits with
11341        // the verify's — the bring-up oracle for the batched graph. The
11342        // plain forwards mutate the CPU state; it is snapshotted and put
11343        // back, and the K/V mirrors re-pointed, before the round goes on.
11344        #[cfg(target_os = "macos")]
11345        if metal_native && std::env::var("CMF_METAL_VERIFY_CHECK").as_deref() == Ok("1") {
11346            let snap: Vec<Vec<f32>> = self
11347                .kv_cache
11348                .layers
11349                .iter()
11350                .map(|l| l.linear_state.clone())
11351                .collect();
11352            let attn_lens: Vec<usize> = self.kv_cache.layers.iter().map(|l| l.seq_len).collect();
11353            let toks: Vec<u32> = std::iter::once(t_next)
11354                .chain(drafts.iter().copied())
11355                .collect();
11356            let want_save = self.graph_want_logits;
11357            self.graph_want_logits = false;
11358            for (i, &t) in toks.iter().enumerate() {
11359                let hi = self.forward_layers(&self.embed_single(t), next_pos + i, None);
11360                let _ = self.graph_logits.take();
11361                // CMF_SPEC_PLAIN_HIDDEN=1: the next round drafts from the
11362                // plain path's hidden instead of the verify's (an experiment
11363                // on the chain's sensitivity to the half-GEMM noise)
11364                if std::env::var("CMF_SPEC_PLAIN_HIDDEN").as_deref() == Ok("1") {
11365                    hiddens[i * self.hidden_size..(i + 1) * self.hidden_size].copy_from_slice(&hi);
11366                }
11367                let ref_lg = self.logits_from_hidden(&hi);
11368                let row = &logits[i * lm_rows..(i + 1) * lm_rows];
11369                let ra = sampler::argmax(&ref_lg);
11370                let va = sampler::argmax(row);
11371                let mut md = 0f32;
11372                let mut rms = 0f64;
11373                for j in 0..lm_rows.min(ref_lg.len()) {
11374                    let d = (ref_lg[j] - row[j]).abs();
11375                    md = md.max(d);
11376                    rms += (d as f64) * (d as f64);
11377                }
11378                let mut hd = 0f32;
11379                for j in 0..self.hidden_size {
11380                    hd = hd.max((hi[j] - hiddens[i * self.hidden_size + j]).abs());
11381                }
11382                eprintln!(
11383                    "verify-check row {i} tok {t} pos {}: ref argmax {ra} verify argmax {va} {} | max|dlogit| {md:.3e} rms {:.3e} | max|dhidden| {hd:.3e}",
11384                    next_pos + i,
11385                    if ra == va { "OK" } else { "MISMATCH" },
11386                    (rms / lm_rows as f64).sqrt()
11387                );
11388            }
11389            self.graph_want_logits = want_save;
11390            // restore IN PLACE: the pending verify graph wraps these very
11391            // allocations (zero-copy) — replacing the Vec would strand it
11392            for (l, st) in self.kv_cache.layers.iter_mut().zip(snap) {
11393                if l.linear_state.len() == st.len() {
11394                    l.linear_state.copy_from_slice(&st);
11395                } else {
11396                    l.linear_state = st;
11397                }
11398            }
11399            for (li, (l, n0)) in self.kv_cache.layers.iter_mut().zip(attn_lens).enumerate() {
11400                let extra = l.seq_len.saturating_sub(n0);
11401                if extra > 0 {
11402                    l.truncate_last(extra);
11403                    crate::gpu_metal::kv_mirror_set_stored(self.graph_kv_id, li, n0);
11404                }
11405            }
11406        }
11407        let t_verify = t_round.elapsed();
11408        let sub_verify = subs();
11409        // Acceptance. Greedy: row i's argmax is the trunk's token after
11410        // input i. Sampling: accept draft i with min(1, p_i/q_i), and on
11411        // the first rejection draw the correction from max(0, p_i − q_i)
11412        // — that token is committed by the loop top as-is (spec_forced).
11413        let mut a = 0usize;
11414        let mut forced: Option<u32> = None;
11415        let ids: Vec<u32> = if sparse {
11416            let mut p = std::mem::take(&mut self.spec_ps);
11417            let mut res = std::mem::take(&mut self.spec_ress);
11418            while a < k_spec {
11419                let ok = sampler::sparse_distribution_into(
11420                    &logits[a * lm_rows..(a + 1) * lm_rows],
11421                    &cfg,
11422                    all_ids,
11423                    &mut self.sampler_scratch,
11424                    self.pool.as_deref(),
11425                    &mut p,
11426                );
11427                if !ok {
11428                    let t = sampler::argmax(&logits[a * lm_rows..(a + 1) * lm_rows]);
11429                    p.clear();
11430                    p.push((t, 1.0));
11431                }
11432                match sampler::spec_accept_or_correct_sparse(
11433                    &p,
11434                    &self.spec_qs[a],
11435                    drafts[a],
11436                    &mut self.rng,
11437                    &mut res,
11438                ) {
11439                    None => {
11440                        all_ids.push(drafts[a]);
11441                        a += 1;
11442                    }
11443                    Some(c) => {
11444                        forced = Some(c);
11445                        break;
11446                    }
11447                }
11448            }
11449            all_ids.truncate(base_len);
11450            self.spec_ps = p;
11451            self.spec_ress = res;
11452            drafts.clone()
11453        } else if sampling {
11454            let mut p = std::mem::take(&mut self.spec_p);
11455            let mut res = std::mem::take(&mut self.spec_res);
11456            while a < k_spec {
11457                sampler::distribution_into(
11458                    &logits[a * lm_rows..(a + 1) * lm_rows],
11459                    &cfg,
11460                    all_ids,
11461                    &mut self.sampler_scratch,
11462                    self.pool.as_deref(),
11463                    &mut p,
11464                );
11465                match sampler::spec_accept_or_correct(
11466                    &p,
11467                    &self.spec_q[a],
11468                    drafts[a],
11469                    &mut self.rng,
11470                    &mut res,
11471                    self.pool.as_deref(),
11472                ) {
11473                    None => {
11474                        all_ids.push(drafts[a]);
11475                        a += 1;
11476                    }
11477                    Some(c) => {
11478                        forced = Some(c);
11479                        break;
11480                    }
11481                }
11482            }
11483            all_ids.truncate(base_len);
11484            self.spec_p = p;
11485            self.spec_res = res;
11486            // the accepted drafts ARE the verified tokens after inputs 0..a
11487            drafts.clone()
11488        } else if greedy_pen {
11489            // Row i's penalized argmax, penalties over the stream that
11490            // includes the accepted drafts before it — the plain loop's
11491            // exact arithmetic, one pass per row, no working copy.
11492            let mut ids: Vec<u32> = Vec::with_capacity(b);
11493            for i in 0..b {
11494                let t = sampler::argmax_penalized(
11495                    &logits[i * lm_rows..(i + 1) * lm_rows],
11496                    &cfg,
11497                    all_ids,
11498                    &mut self.sampler_scratch,
11499                    self.pool.as_deref(),
11500                );
11501                ids.push(t);
11502                if i < k_spec && t == drafts[i] {
11503                    all_ids.push(t);
11504                } else {
11505                    break;
11506                }
11507            }
11508            all_ids.truncate(base_len);
11509            while a < k_spec && a < ids.len() && ids[a] == drafts[a] {
11510                a += 1;
11511            }
11512            // rows past the first mismatch were never scored; the loop
11513            // top re-samples the last verified row itself.
11514            ids
11515        } else if greedy_dev && dev_ids.len() == b {
11516            let ids = std::mem::take(&mut dev_ids);
11517            while a < k_spec && ids[a] == drafts[a] {
11518                a += 1;
11519            }
11520            ids
11521        } else {
11522            if logits.len() < b * lm_rows {
11523                // the device argmax was asked for and came back short:
11524                // no rows to fall back on — terminal like a failed batch
11525                self.clear_sequence_state();
11526                self.graph_failed
11527                    .store(true, std::sync::atomic::Ordering::Relaxed);
11528                self.cancel
11529                    .store(true, std::sync::atomic::Ordering::Relaxed);
11530                tracing::error!("Metal verify returned neither logits nor argmax ids");
11531                return None;
11532            }
11533            let ids: Vec<u32> = (0..b)
11534                .map(|i| sampler::argmax(&logits[i * lm_rows..(i + 1) * lm_rows]))
11535                .collect();
11536            while a < k_spec && ids[a] == drafts[a] {
11537                a += 1;
11538            }
11539            ids
11540        };
11541        spec_stamp("acc");
11542        if dflash_round {
11543            if let Some(log) = dflash_rows_log() {
11544                let mut rec = [u32::MAX; 24];
11545                (rec[0], rec[1], rec[2], rec[3]) = (next_pos as u32, t_next, k_spec as u32, a as u32);
11546                for (o, &d) in rec[4..11].iter_mut().zip(&drafts) {
11547                    *o = d;
11548                }
11549                for (o, &d) in rec[11..18].iter_mut().zip(&beside) {
11550                    *o = d;
11551                }
11552                // what a round of the chain's own would have added from the context
11553                let mut more: Vec<u32> = Vec::new();
11554                if beside.len() >= 2 && Self::spec_lookup_on() {
11555                    all_ids.extend_from_slice(&beside[..2]);
11556                    more = lookup_continuation(all_ids, 2 + LOOKUP_MIN_REAL, 5).to_vec();
11557                    all_ids.truncate(base_len);
11558                }
11559                rec[18] = more.len() as u32;
11560                for (o, &d) in rec[19..24].iter_mut().zip(&more) {
11561                    *o = d;
11562                }
11563                let mut bytes: Vec<u8> = rec.iter().flat_map(|v| v.to_le_bytes()).collect();
11564                bytes.extend(hidden.iter().flat_map(|v| v.to_le_bytes()));
11565                use std::io::Write as _;
11566                // the stream through the first logged round's first token, once:
11567                // a lookup reads the prompt, and the fit has to as well
11568                static IDS: std::sync::Once = std::sync::Once::new();
11569                IDS.call_once(|| {
11570                    if let Ok(path) = std::env::var("CMF_DFLASH_ROWS") {
11571                        let ids: Vec<u8> = all_ids.iter().flat_map(|v| v.to_le_bytes()).collect();
11572                        if let Err(e) = std::fs::write(format!("{path}.ids"), ids) {
11573                            tracing::warn!("CMF_DFLASH_ROWS: {path}.ids: {e}");
11574                        }
11575                    }
11576                });
11577                if let Ok(mut f) = log.lock() {
11578                    let _ = f.write_all(&bytes);
11579                }
11580            }
11581        }
11582        if spec_dbg {
11583            eprintln!(
11584                "spec-dbg round: t_next {t_next} drafts {:?} verified {:?} accepted {a}",
11585                drafts, ids
11586            );
11587        }
11588        // CMF_METAL_VERIFY_CHECK=2: the commit oracle — plain-forward the
11589        // a+1 accepted tokens from a snapshot, then diff the replayed GDN
11590        // states and the appended K/V rows against that.
11591        #[cfg(target_os = "macos")]
11592        let commit_ref: Option<(Vec<Vec<f32>>, Vec<(usize, Vec<f32>, Vec<f32>)>)> = if metal_native
11593            && std::env::var("CMF_METAL_VERIFY_CHECK").as_deref() == Ok("2")
11594        {
11595            let snap: Vec<Vec<f32>> = self
11596                .kv_cache
11597                .layers
11598                .iter()
11599                .map(|l| l.linear_state.clone())
11600                .collect();
11601            let attn_lens: Vec<usize> = self.kv_cache.layers.iter().map(|l| l.seq_len).collect();
11602            let toks: Vec<u32> = std::iter::once(t_next)
11603                .chain(drafts.iter().copied())
11604                .collect();
11605            let want_save = self.graph_want_logits;
11606            self.graph_want_logits = false;
11607            for (i, &t) in toks.iter().take(a + 1).enumerate() {
11608                let _ = self.forward_layers(&self.embed_single(t), next_pos + i, None);
11609                let _ = self.graph_logits.take();
11610            }
11611            self.graph_want_logits = want_save;
11612            let plain_states: Vec<Vec<f32>> = self
11613                .kv_cache
11614                .layers
11615                .iter()
11616                .map(|l| l.linear_state.clone())
11617                .collect();
11618            let (nkv, hd) = (self.num_kv_heads, self.head_dim);
11619            let mut rows = Vec::new();
11620            for (li, (l, n0)) in self
11621                .kv_cache
11622                .layers
11623                .iter_mut()
11624                .zip(attn_lens.iter())
11625                .enumerate()
11626            {
11627                let extra = l.seq_len.saturating_sub(*n0);
11628                if extra > 0 {
11629                    let mut kk = Vec::new();
11630                    let mut vv = Vec::new();
11631                    for g in 0..nkv {
11632                        kk.extend_from_slice(&l.head_keys(g)[n0 * hd..]);
11633                        vv.extend_from_slice(&l.head_values(g)[n0 * hd..]);
11634                    }
11635                    rows.push((li, kk, vv));
11636                    l.truncate_last(extra);
11637                    crate::gpu_metal::kv_mirror_set_stored(self.graph_kv_id, li, *n0);
11638                }
11639            }
11640            for (l, st) in self.kv_cache.layers.iter_mut().zip(snap) {
11641                if l.linear_state.len() == st.len() {
11642                    l.linear_state.copy_from_slice(&st);
11643                } else {
11644                    l.linear_state = st;
11645                }
11646            }
11647            Some((plain_states, rows))
11648        } else {
11649            None
11650        };
11651        let warm_off = std::env::var("CMF_SPEC_WARM").is_ok_and(|v| v == "0");
11652        // Metal: the MTP cache cut and the round's warm-up SUBMIT come
11653        // BEFORE the trunk commit, so the warm-up's command buffer is
11654        // queued ahead of the GDN replay (second queue) and its wait
11655        // below no longer sits behind the replay — measured: the warm-up's
11656        // wait grew with the accepted count exactly like the replay does
11657        // (8 ms at a=1, 17 ms at a=3, 25 ms at a=5 for ~2 ms of its own
11658        // work). The replay now overlaps the warm-up's readback, the
11659        // round's return and the next draft chain.
11660        #[cfg(target_os = "macos")]
11661        let mut warm_pending: Option<MetalWarmPending> = None;
11662        // The pairs the MTP cache has to hold of this round: the accepted
11663        // ones and, before them, the tip's own when the block was DFlash's
11664        // (an MTP chain's first step is that pair). The MTP block stays in
11665        // step through DFlash rounds, so either drafter can take the next.
11666        let hs_w = self.hidden_size;
11667        let warm_first = usize::from(mtp_steps == 0);
11668        let warm_n = if dflash_round && !mtp_in_step { 0 } else { a + warm_first };
11669        let warm_pos = next_pos - warm_first;
11670        let warm_pair = |j: usize| -> (&[f32], u32) {
11671            if j < warm_first {
11672                (hidden, t_next)
11673            } else {
11674                let j = j - warm_first;
11675                (&hiddens[j * hs_w..(j + 1) * hs_w], ids[j])
11676            }
11677        };
11678        #[cfg(target_os = "macos")]
11679        if metal_native {
11680            if mtp_steps > 0 {
11681                m.kv.truncate_last(mtp_steps - 1);
11682            }
11683            if self.mtp_graph_mode == Some(true) {
11684                // the mirror rows below the cut are the CPU rows: re-point,
11685                // no re-upload
11686                crate::gpu_metal::kv_mirror_set_stored(
11687                    self.mtp_kv_id(),
11688                    Self::MTP_LAYER_BASE,
11689                    m.kv.seq_len,
11690                );
11691                if !warm_off && warm_n > 0 {
11692                    let pairs: Vec<(&[f32], u32)> = (0..warm_n).map(&warm_pair).collect();
11693                    warm_pending = self.mtp_warm_batch_submit(m, &pairs, warm_pos);
11694                }
11695            }
11696            spec_stamp("c.wsub");
11697        }
11698        // a fully-accepted round needs no restore: every input was real.
11699        #[cfg(target_os = "macos")]
11700        if metal_native {
11701            // the Metal verify never wrote its states: the commit replays the
11702            // accepted prefix into the CPU owners and appends the K/V rows
11703            if !self.metal_verify_commit(a) {
11704                self.clear_sequence_state();
11705                self.graph_failed
11706                    .store(true, std::sync::atomic::Ordering::Relaxed);
11707                self.cancel
11708                    .store(true, std::sync::atomic::Ordering::Relaxed);
11709                tracing::error!("Metal verify state/KV handoff failed after admission");
11710                return None;
11711            }
11712            // the rows the round keeps are the drafter's next context
11713            if let (Some((pos0, rows)), Some(d)) = (self.dflash_rows.take(), self.dflash.as_mut()) {
11714                let tw = d.g.tap_width();
11715                d.queue_context(pos0, &rows[..(a + 1) * tw], self.pool.as_deref());
11716                spec_stamp("c.flash");
11717            }
11718            if let Some((plain_states, rows)) = commit_ref {
11719                crate::gpu_metal::queue_fence();
11720                // the commit's replay runs on the second queue: collect it
11721                // before the oracle reads the CPU owners it writes into
11722                let _ = crate::gpu_metal::wait_replay();
11723                let (nkv, hd) = (self.num_kv_heads, self.head_dim);
11724                let mut worst_s = 0f32;
11725                let mut worst_li = 0usize;
11726                for (li, (l, ps)) in self.kv_cache.layers.iter().zip(&plain_states).enumerate() {
11727                    if l.linear_state.len() != ps.len() || ps.is_empty() {
11728                        continue;
11729                    }
11730                    let d = l
11731                        .linear_state
11732                        .iter()
11733                        .zip(ps)
11734                        .fold(0f32, |m, (x, y)| m.max((x - y).abs()));
11735                    let n = ps.iter().fold(0f32, |m, y| m.max(y.abs()));
11736                    let rel = d / n.max(1e-6);
11737                    if rel > worst_s {
11738                        worst_s = rel;
11739                        worst_li = li;
11740                    }
11741                }
11742                let mut worst_k = 0f32;
11743                for (li, kk, vv) in &rows {
11744                    let l = &self.kv_cache.layers[*li];
11745                    let n0 = l.seq_len - (kk.len() / (nkv * hd));
11746                    let mut ck = Vec::new();
11747                    let mut cv = Vec::new();
11748                    for g in 0..nkv {
11749                        ck.extend_from_slice(&l.head_keys(g)[n0 * hd..]);
11750                        cv.extend_from_slice(&l.head_values(g)[n0 * hd..]);
11751                    }
11752                    if ck.len() == kk.len() {
11753                        let dk = ck
11754                            .iter()
11755                            .zip(kk)
11756                            .fold(0f32, |m, (x, y)| m.max((x - y).abs()));
11757                        let dv = cv
11758                            .iter()
11759                            .zip(vv)
11760                            .fold(0f32, |m, (x, y)| m.max((x - y).abs()));
11761                        worst_k = worst_k.max(dk).max(dv);
11762                    } else {
11763                        eprintln!(
11764                            "commit-check L{li}: kv row count mismatch {} vs {}",
11765                            ck.len(),
11766                            kk.len()
11767                        );
11768                    }
11769                }
11770                eprintln!(
11771                    "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}"
11772                );
11773            }
11774        }
11775        if !metal_native && a + 1 < b {
11776            let expected_gdn_layers = self.graph_gdn_layer_count();
11777            if expected_gdn_layers > 0
11778                && !crate::gpu::gdn_spec_restore(self.graph_kv_id, a, next_pos, expected_gdn_layers)
11779            {
11780                self.clear_sequence_state();
11781                self.graph_failed
11782                    .store(true, std::sync::atomic::Ordering::Relaxed);
11783                self.cancel
11784                    .store(true, std::sync::atomic::Ordering::Relaxed);
11785                tracing::error!("GDN speculative restore failed after verify");
11786                return None;
11787            }
11788        }
11789        if self.o1_active() && !crate::gpu::o1_spec_commit(self.graph_kv_id, next_pos, a + 1) {
11790            self.clear_sequence_state();
11791            self.graph_failed
11792                .store(true, std::sync::atomic::Ordering::Relaxed);
11793            self.cancel
11794                .store(true, std::sync::atomic::Ordering::Relaxed);
11795            tracing::error!("far field commit failed after verify");
11796            return None;
11797        }
11798        // the rows a wgpu verify kept for the drafter: those the round keeps
11799        // are its next context
11800        if !metal_native {
11801            let kept = self.dflash_taps.lock().unwrap().pop();
11802            if let (Some((pos0, rows)), Some(d)) = (kept, self.dflash.as_mut()) {
11803                let tw = d.g.tap_width();
11804                if pos0 == next_pos && rows.len() >= (a + 1) * tw {
11805                    d.queue_context(pos0, &rows[..(a + 1) * tw], self.pool.as_deref());
11806                }
11807            }
11808        }
11809        if !metal_native && !self.rewind_trunk_graph_mirrors(next_pos + a + 1) {
11810            // The verify graph committed the full batch, but one of its
11811            // persistent Full-attention mirrors could not be re-pointed to
11812            // the accepted prefix.  Treat that as terminal state failure;
11813            // an exact CPU fallback would otherwise consume stale GDN/KV.
11814            self.clear_sequence_state();
11815            self.graph_failed
11816                .store(true, std::sync::atomic::Ordering::Relaxed);
11817            self.cancel
11818                .store(true, std::sync::atomic::Ordering::Relaxed);
11819            tracing::error!("trunk graph KV rewind failed after speculative verify");
11820            return None;
11821        }
11822        *accepted += a;
11823        // MTP cache: keep the first draft row (its inputs were real), drop
11824        // the chain's, then append the verified pairs the round produced.
11825        // Each of those is a whole MTP block on the per-op path and they
11826        // cost 5.8 ms of a 69 ms round at k=3 — a third of what the
11827        // round's own draft costs. PRICED, and they earn it: skipping
11828        // them (`CMF_SPEC_WARM=0`) drops acceptance from 89% to 81% at
11829        // k=3 and 85% to 74% at k=4, and the tok/s goes nowhere at k=3
11830        // (50.3 against 50.5) and backwards at k=4 (48.1 against 50.1).
11831        // The knob stays so the next person can re-price it after the
11832        // warms are batched instead of assuming either way.
11833        if !metal_native && mtp_steps > 0 {
11834            // (Metal cut its MTP cache before the trunk commit, above)
11835            m.kv.truncate_last(mtp_steps - 1);
11836        }
11837        spec_stamp("c.trunc");
11838        // (the block's round put no row there: the mirror already ends where
11839        // the warm-up starts)
11840        if !metal_native
11841            && self.mtp_graph_mode == Some(true)
11842            && (mtp_steps > 0 || warm_n > 0)
11843            && !self.rewind_mtp_graph_mirror(warm_pos)
11844        {
11845            // The graph draft was admitted, so inability to move its cursor
11846            // back to the real anchor is a state failure, not a capability
11847            // refusal.  Do not warm or continue with a stale mirror.
11848            self.clear_sequence_state();
11849            self.graph_failed
11850                .store(true, std::sync::atomic::Ordering::Relaxed);
11851            self.cancel
11852                .store(true, std::sync::atomic::Ordering::Relaxed);
11853            tracing::error!("MTP graph mirror rewind failed after verify commit");
11854            return None;
11855        }
11856        if !warm_off && warm_n > 0 {
11857            // Graph arm: all accepted pairs in ONE batched run over the
11858            // MTP block; the token graph one by one if the batch declines.
11859            let mut warmed = false;
11860            #[cfg(target_os = "macos")]
11861            if metal_native && self.mtp_graph_mode == Some(true) {
11862                // the batched warm-up was submitted before the trunk
11863                // commit: collect it here; one by one on the token graph
11864                // if it declined (or failed)
11865                warmed = match warm_pending.take() {
11866                    Some(p) => self.mtp_warm_batch_finish(m, p),
11867                    None => false,
11868                };
11869                if !warmed {
11870                    warmed = true;
11871                    for j in 0..warm_n {
11872                        let (row, tok) = warm_pair(j);
11873                        let row = row.to_vec();
11874                        if self
11875                            .mtp_step_metal(m, &row, tok, warm_pos + j, false)
11876                            .is_none()
11877                        {
11878                            warmed = false;
11879                            break;
11880                        }
11881                    }
11882                }
11883            }
11884            if !warmed && self.mtp_graph_mode != Some(false) && !metal_native {
11885                let rows: Vec<(Vec<f32>, u32)> = (0..warm_n)
11886                    .map(|j| {
11887                        let (row, tok) = warm_pair(j);
11888                        (row.to_vec(), tok)
11889                    })
11890                    .collect();
11891                let pairs: Vec<(&[f32], u32)> = rows.iter().map(|(r, t)| (r.as_slice(), *t)).collect();
11892                match self.mtp_warm_prefill_pairs(m, &pairs, warm_pos) {
11893                    Ok(()) => warmed = true,
11894                    Err(err) => {
11895                        // A warm-up failure after graph admission cannot
11896                        // fall back to `mtp_warm`: the detached CPU cache is
11897                        // not authoritative for the device mirror.  Mark it
11898                        // terminal so the generation caller clears state and
11899                        // returns instead of drafting from stale attention.
11900                        tracing::error!("{err}");
11901                        self.clear_sequence_state();
11902                        self.graph_failed
11903                            .store(true, std::sync::atomic::Ordering::Relaxed);
11904                        self.cancel
11905                            .store(true, std::sync::atomic::Ordering::Relaxed);
11906                        return None;
11907                    }
11908                }
11909            }
11910            if !warmed {
11911                for j in 0..warm_n {
11912                    let (row, tok) = warm_pair(j);
11913                    let row = row.to_vec();
11914                    self.mtp_warm(m, &row, tok, warm_pos + j);
11915                }
11916            }
11917        }
11918        // The sampler's contract: logits of the LAST verified position —
11919        // unless a rejected draft already drew the correction, in which
11920        // case the loop top commits that token and samples nothing.
11921        spec_stamp("c.warm");
11922        if let Some(c) = forced {
11923            self.spec_forced = Some(c);
11924            self.graph_logits = None;
11925        } else if greedy_dev && logits.is_empty() {
11926            // the row's argmax IS the token the loop top would pick from
11927            // it (plain greedy, no penalties): commit it as forced
11928            self.spec_forced = Some(ids[a]);
11929            self.graph_logits = None;
11930        } else {
11931            let mut row = logits[a * lm_rows..(a + 1) * lm_rows].to_vec();
11932            row.resize(self.vocab_size, 0.0);
11933            if let Some(c) = self.final_softcap {
11934                for l in row.iter_mut() {
11935                    *l = c * (*l / c).tanh();
11936                }
11937            }
11938            self.graph_logits = Some(row);
11939        }
11940        let new_hidden = hiddens[a * self.hidden_size..(a + 1) * self.hidden_size].to_vec();
11941        spec_stamp("c.row");
11942        // Three phases, not two. The round's wall clock was 4 ms longer
11943        // than draft+verify and the difference had nowhere to be seen:
11944        // the accepted prefix re-runs the MTP block once per token to
11945        // keep the draft head's attention cache warm, and the GDN state
11946        // rolls back on any rejection. Both live here, after the verify.
11947        if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
11948            let end = subs();
11949            eprintln!(
11950                "spec-round: draft {:.1} ms/{} sub | verify {:.1} ms/{} sub | \
11951                 commit {:.1} ms/{} sub (accepted {a} of {k_spec}, full-head streak {})",
11952                t_draft.as_secs_f64() * 1e3,
11953                sub_draft - sub0,
11954                (t_verify - t_draft).as_secs_f64() * 1e3,
11955                sub_verify - sub_draft,
11956                (t_round.elapsed() - t_verify).as_secs_f64() * 1e3,
11957                end - sub_verify,
11958                self.draft_full_streak,
11959            );
11960        }
11961        // Native Metal's verify tile is flat in b (eight rows for the price
11962        // of one), so a shorter round only forfeits tokens — measured on
11963        // the M4: an essay round at k=2 still verified in 260 ms. The
11964        // adaptation is for cards whose verify grows with the rows.
11965        if k_spec > k_mtp {
11966            // a lookup's round: what it added over the head's own drafts
11967            let extra = a.saturating_sub(k_mtp) as f32;
11968            self.spec_lookup_gain += 0.2 * (extra - self.spec_lookup_gain);
11969            // a copy that holds whole earns the long window; a miss goes back
11970            self.spec_lookup_wide = a == k_spec;
11971            if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
11972                eprintln!(
11973                    "spec-lookup: {} drafts from the context, {extra} held (average {:.2})",
11974                    k_spec - k_mtp,
11975                    self.spec_lookup_gain
11976                );
11977            }
11978            if self.spec_lookup_gain < LOOKUP_PAYS {
11979                self.spec_lookup_rest = 24;
11980                self.spec_lookup_gain = 1.6;
11981            }
11982        }
11983        if metal_small && !k_capped {
11984            // (the chain's account stands as its last rounds on this text
11985            // left it while the block has the rounds: that is what the block
11986            // has to beat)
11987            if dflash_round {
11988                self.dflash_turn_sum.0 += (a + 1) as f32;
11989                self.dflash_turn_sum.1 += METAL_ROUND_COST[k_spec.clamp(1, 7) - 1] + DFLASH_ROUND_DRAFT;
11990            }
11991            let hold = if dflash_round { &mut self.dflash_hold } else { &mut self.spec_hold };
11992            spec_hold_update(hold, k_mtp, a.min(k_mtp));
11993            if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
11994                let next = metal_spec_plan(hold, if dflash_round { DFLASH_ROUND_DRAFT } else { 0.0 }).0;
11995                if next != k_mtp && k_env.is_none() {
11996                    eprintln!("spec-k: {k_mtp} → {next} (a draft holds after the last {hold:.2?})");
11997                }
11998            }
11999        }
12000
12001        if k_env.is_none() && !metal_native && !k_capped {
12002            // The depth is the drafter's own: a round the context lookup
12003            // lengthened (CUDA) adapts by the chain's drafts and what of them
12004            // held, and its wall (a longer verify) is not a depth's price.
12005            let lookup_round = k_spec > k_mtp;
12006            let (k_spec, a) = (k_mtp, a.min(k_mtp));
12007            // Slow average and a wide band: a fast one oscillated 2↔3 on
12008            // an essay every other round (measured), which forfeits the
12009            // draft it just paid for. Each drafter has its own depth.
12010            if cuda_rate && dflash_round && !k_capped {
12011                self.dflash_turn_sum.0 += (a + 1) as f32;
12012                self.dflash_turn_sum.1 += CUDA_ROUND_COST[k_spec.clamp(1, 7) - 1] + CUDA_BLOCK_DRAFT;
12013                spec_hold_update(&mut self.dflash_hold, k_spec, a.min(k_spec));
12014            }
12015            let (ewma, k_min) = if dflash_round { (&mut self.dflash_acc_ewma, 3) } else { (&mut self.spec_acc_ewma, 2) };
12016            let f = a as f32 / k_spec.max(1) as f32;
12017            *ewma += 0.2 * (f - *ewma);
12018            let mut k_next = k_spec;
12019            if *ewma >= 0.75 && k_spec < k_max {
12020                k_next = k_spec + 1;
12021            } else if *ewma < 0.4 && k_spec > k_min {
12022                k_next = k_spec - 1;
12023            }
12024            // The chain's rounds are timed by depth, and once two depths
12025            // are, the depth is the one that lands the most tokens in a unit
12026            // of time at this device's prices (`wgpu_spec_depth`): the share
12027            // of drafts kept climbs to five on text that holds whatever a
12028            // fifth row costs. A depth's first round pays its scratch and
12029            // is not counted; a change stands for six rounds.
12030            let mut planned = false;
12031            if !dflash_round && !lookup_round {
12032                spec_hold_update(&mut self.spec_hold, k_spec, a);
12033                let d = k_spec.clamp(1, 7) - 1;
12034                let w = t_round.elapsed().as_secs_f32() * 1e3;
12035                match self.spec_wall_n[d] {
12036                    0 => self.spec_wall_n[d] = 1,
12037                    1 => (self.spec_wall[d], self.spec_wall_n[d]) = (w, 2),
12038                    _ => self.spec_wall[d] += 0.2 * (w - self.spec_wall[d]),
12039                }
12040                if let Some(k_plan) = wgpu_spec_depth(&self.spec_hold, &self.spec_wall, k_spec, k_min, k_max) {
12041                    planned = true;
12042                    k_next = if self.spec_k_dwell > 0 {
12043                        self.spec_k_dwell -= 1;
12044                        k_spec
12045                    } else {
12046                        k_plan
12047                    };
12048                    if k_next != k_spec {
12049                        self.spec_k_dwell = 6;
12050                    }
12051                }
12052            }
12053            if k_next != k_spec {
12054                *ewma = 0.6;
12055                if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
12056                    if planned {
12057                        eprintln!(
12058                            "spec-k: {k_spec} → {k_next} (a round costs {:.0?} ms, a draft holds after the last {:.2?})",
12059                            self.spec_wall, self.spec_hold
12060                        );
12061                    } else {
12062                        eprintln!("spec-k: {k_spec} → {k_next}");
12063                    }
12064                }
12065            }
12066            if dflash_round {
12067                self.dflash_k_adapt = Some(k_next);
12068            } else {
12069                self.spec_k_adapt = Some(k_next);
12070            }
12071        }
12072        spec_stamp("end");
12073        Some((drafts[..a].to_vec(), next_pos + a + 1, new_hidden))
12074    }
12075
12076    /// A round's drafts from the DFlash drafter: the block behind the anchor
12077    /// `t_next` at `next_pos`, its first `k` tokens. The block reads the
12078    /// context the trunk's rows before `next_pos` left; the tokens come from
12079    /// the trunk's own head through the drafter's selector.
12080    fn dflash_draft(&mut self, t_next: u32, next_pos: usize, k: usize) -> Vec<u32> {
12081        let Some(mut d) = self.dflash.take() else {
12082            return Vec::new();
12083        };
12084        let (hs, rows) = (self.hidden_size, d.g.block);
12085        let mut h = vec![0f32; rows * hs];
12086        h[..hs].copy_from_slice(&self.embed_single(t_next));
12087        let mask = self.embed_single(d.g.mask_token);
12088        for r in 1..rows {
12089            h[r * hs..(r + 1) * hs].copy_from_slice(&mask);
12090        }
12091        // A trunk that scales its embeddings on the way in (Ripple): the
12092        // block reads the table's rows as they are (`CMF_DFLASH_EMBED=scaled`
12093        // hands it the trunk's input rows).
12094        if self.embed_multiplier != 1.0 && std::env::var("CMF_DFLASH_EMBED").as_deref() != Ok("scaled") {
12095            let inv = 1.0 / self.embed_multiplier;
12096            h.iter_mut().for_each(|v| *v *= inv);
12097        }
12098        let pool = self.pool.as_deref();
12099        let t0 = std::time::Instant::now();
12100        d.settle(pool);
12101        spec_stamp("d.ctx");
12102        let t_ctx = t0.elapsed();
12103        // the block, the head and the selector's projection as one
12104        // submission on wgpu; the host block below where it declines
12105        #[cfg(feature = "gpu")]
12106        if let Some((logits, hp)) = d.block_dev(next_pos, &h, k.min(rows - 1), &self.weights.lm_head) {
12107            spec_stamp("d.block");
12108            let t_block = t0.elapsed();
12109            let n = k.min(rows - 1);
12110            let (mut ids, _) = d.select_with(&hp, &logits, t_next, n);
12111            ids.truncate(k);
12112            // `CMF_DFLASH_DEV_CHECK=1`: the host block on the same rows, and
12113            // how far the device's logits, selector rows and drafts are from it
12114            if std::env::var_os("CMF_DFLASH_DEV_CHECK").is_some() {
12115                let out = d.block(next_pos, h.clone(), pool);
12116                let head = &self.weights.lm_head;
12117                let mut hl = vec![0f32; n * head.rows()];
12118                head.matmat(&out[hs..(n + 1) * hs], n, &mut hl, pool);
12119                // the device may score only the head's first rows (CUDA: the shortlist)
12120                let width = logits.len() / n.max(1);
12121                let hl: Vec<f32> = (0..n).flat_map(|j| hl[j * head.rows()..j * head.rows() + width].to_vec()).collect();
12122                let (hids, _) = d.select(&out[hs..(n + 1) * hs], &hl, t_next);
12123                let (mut dmax, mut ref_max, mut dsum, mut cnt) = (0f32, 0f32, 0f64, 0usize);
12124                for (a, b) in logits.iter().zip(&hl) {
12125                    dmax = dmax.max((a - b).abs());
12126                    ref_max = ref_max.max(b.abs());
12127                    dsum += ((a - b) * (a - b)) as f64;
12128                    cnt += 1;
12129                }
12130                let arg = |v: &[f32]| (0..n).map(|j| sampler::argmax(&v[j * width..(j + 1) * width])).collect::<Vec<u32>>();
12131                eprintln!(
12132                    "dflash-dev-check: logits max|Δ| {dmax:.4} of max {ref_max:.2}, rms Δ {:.5} | argmax device {:?} host {:?} | drafts device {:?} host {:?}",
12133                    (dsum / cnt.max(1) as f64).sqrt(),
12134                    arg(&logits),
12135                    arg(&hl),
12136                    ids,
12137                    &hids[..k.min(hids.len())]
12138                );
12139            }
12140            if self.dflash_solo && spec_time_level() > 0 {
12141                eprintln!(
12142                    "solo-draft: context {:.1} ms | device block + head {:.1} ms | selector {:.1} ms",
12143                    t_ctx.as_secs_f64() * 1e3,
12144                    (t_block - t_ctx).as_secs_f64() * 1e3,
12145                    (t0.elapsed() - t_block).as_secs_f64() * 1e3
12146                );
12147            }
12148            spec_stamp("d.head");
12149            self.dflash = Some(d);
12150            return ids;
12151        }
12152        let out = d.block(next_pos, h, pool);
12153        spec_stamp("d.block");
12154        let t_block = t0.elapsed();
12155        // the head over the round's shortlist of the vocabulary, as the MTP
12156        // draft has it (the full head while `draft_full_streak` runs). The
12157        // shortlist is the low ids of Qwen's vocabulary: a trunk with another
12158        // tokenizer (`dflash_solo`) scores the whole head.
12159        let (n, head) = (rows - 1, &self.weights.lm_head);
12160        let width = if self.dflash_solo { head.rows() } else { self.draft_head_rows(head.rows()) };
12161        let mut logits = vec![0f32; n * width];
12162        // the block's rows on the narrow kernel; any other head as a batch
12163        let narrow = head.mapped_q4tp().is_some_and(|(m, idx)| {
12164            crate::gpu::q4tp_rows8_many(m, &[(idx, head.rows(), head.cols(), width)], &out[hs..], n, &mut [&mut logits[..]])
12165        });
12166        if !narrow {
12167            logits = vec![0f32; n * head.rows()];
12168            if !head.device_matmat(&out[hs..], n, &mut logits) {
12169                head.matmat(&out[hs..], n, &mut logits, pool);
12170            }
12171        }
12172        spec_stamp("d.head");
12173        let t_head = t0.elapsed();
12174        let (mut ids, _) = d.select(&out[hs..], &logits, t_next);
12175        ids.truncate(k);
12176        if self.dflash_solo && spec_time_level() > 0 {
12177            eprintln!(
12178                "solo-draft: context {:.1} ms | block {:.1} ms | head {:.1} ms | selector {:.1} ms",
12179                t_ctx.as_secs_f64() * 1e3,
12180                (t_block - t_ctx).as_secs_f64() * 1e3,
12181                (t_head - t_block).as_secs_f64() * 1e3,
12182                (t0.elapsed() - t_head).as_secs_f64() * 1e3
12183            );
12184        }
12185        if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() && d.next_position() != next_pos {
12186            eprintln!("dflash: the context ends at {} for a block at {next_pos}", d.next_position());
12187        }
12188        self.dflash = Some(d);
12189        ids
12190    }
12191
12192    /// A speculative round of a trunk that has no draft block of its own.
12193    /// The drafts are the DFlash sidecar's block behind the tip `t_next` (or
12194    /// the next ids of `CMF_SPEC_SCRIPT`); the batch graph verifies them with
12195    /// the tip in one submission, and the cache keeps the rows of the drafts
12196    /// that held and of the tip. None: no round was made (plain greedy goes
12197    /// on), or the graph failed after admission (`graph_failed` is set).
12198    #[cfg(feature = "gpu")]
12199    fn solo_spec_round(&mut self, t_next: u32, next_pos: usize, all_ids: &[u32], k: usize) -> Option<SoloRound> {
12200        self.dflash_taps_absorb();
12201        let t0 = std::time::Instant::now();
12202        let drafts: Vec<u32> = match solo_script() {
12203            Some(script) => script.iter().skip(all_ids.len()).take(k).copied().collect(),
12204            None => {
12205                if self.dflash.as_ref().is_none_or(|d| d.next_position() != next_pos) {
12206                    return None;
12207                }
12208                self.dflash_draft(t_next, next_pos, k)
12209            }
12210        };
12211        if drafts.is_empty() {
12212            return None;
12213        }
12214        let t_draft = t0.elapsed();
12215        let (b, hs) = (drafts.len() + 1, self.hidden_size);
12216        let mut hiddens = vec![0f32; b * hs];
12217        for (i, &t) in std::iter::once(&t_next).chain(drafts.iter()).enumerate() {
12218            hiddens[i * hs..(i + 1) * hs].copy_from_slice(&self.embed_single(t));
12219        }
12220        let positions: Vec<usize> = (next_pos..next_pos + b).collect();
12221        let (lm_gw, lm_rows) = {
12222            let (_, i, kind, rs) = self.weights.lm_head.graph_weight()?;
12223            (
12224                crate::gpu::GraphW { idx: i, kind, row_scale: rs, data: &[], prism: crate::gpu::GraphPrismOp::None, affine: false },
12225                self.weights.lm_head.rows(),
12226            )
12227        };
12228        let mut logits = Vec::new();
12229        let final_norm = self.weights.final_norm.clone();
12230        let outcome = self.try_batch_graph_wgpu(
12231            &mut hiddens,
12232            &positions,
12233            b,
12234            Some(crate::gpu::SpecTail { lm: lm_gw, lm_rows, final_norm: &final_norm, logits_out: &mut logits, pick: None }),
12235        );
12236        let fail = |p: &mut Self, what: &str| {
12237            p.clear_sequence_state();
12238            p.graph_failed.store(true, std::sync::atomic::Ordering::Relaxed);
12239            p.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
12240            tracing::error!("{what}");
12241        };
12242        match outcome {
12243            crate::gpu::BatchGraphOutcome::Completed if logits.len() >= b * lm_rows => {}
12244            crate::gpu::BatchGraphOutcome::Declined => return None,
12245            _ => {
12246                fail(self, "the verify of a speculative round failed after admission");
12247                return None;
12248            }
12249        }
12250        let t_verify = t0.elapsed();
12251        // row i's argmax is the trunk's token after input i
12252        let ids: Vec<u32> = (0..b).map(|i| sampler::argmax(&logits[i * lm_rows..(i + 1) * lm_rows])).collect();
12253        let mut a = 0usize;
12254        while a < drafts.len() && ids[a] == drafts[a] {
12255            a += 1;
12256        }
12257        if std::env::var_os("CMF_SPEC_DBG").is_some() {
12258            eprintln!(
12259                "solo-dbg: tip {t_next} at {next_pos} | context {:?} | drafts {drafts:?} | the trunk's {ids:?} | kept {a}",
12260                self.dflash.as_ref().map(|d| d.span())
12261            );
12262        }
12263        if self.o1_active() && !crate::gpu::o1_spec_commit(self.graph_kv_id, next_pos, a + 1) {
12264            fail(self, "far field commit failed after a speculative round");
12265            return None;
12266        }
12267        // a hybrid trunk (Arete-27B, no draft block of its own): its GDN
12268        // states back to the rows the round kept, as after a chain's round
12269        if a + 1 < b {
12270            let gdn = self.graph_gdn_layer_count();
12271            if gdn > 0 && !crate::gpu::gdn_spec_restore(self.graph_kv_id, a, next_pos, gdn) {
12272                fail(self, "GDN restore failed after a speculative round");
12273                return None;
12274            }
12275        }
12276        // the rows the round keeps are the drafter's next context
12277        let kept = self.dflash_taps.lock().unwrap().pop();
12278        if let (Some((pos0, rows)), Some(d)) = (kept, self.dflash.as_mut()) {
12279            let tw = d.g.tap_width();
12280            if pos0 == next_pos && rows.len() >= (a + 1) * tw {
12281                d.queue_context(pos0, &rows[..(a + 1) * tw], self.pool.as_deref());
12282            }
12283        }
12284        if !self.rewind_trunk_graph_mirrors(next_pos + a + 1) {
12285            fail(self, "trunk graph KV rewind failed after a speculative round");
12286            return None;
12287        }
12288        let mut row = logits[a * lm_rows..(a + 1) * lm_rows].to_vec();
12289        row.resize(self.vocab_size, 0.0);
12290        if let Some(c) = self.final_softcap {
12291            for l in row.iter_mut() {
12292                *l = c * (*l / c).tanh();
12293            }
12294        }
12295        if spec_time_level() > 0 {
12296            eprintln!(
12297                "solo-round: draft {:.1} ms | verify {:.1} ms | commit {:.1} ms | kept {a} of {}",
12298                t_draft.as_secs_f64() * 1e3,
12299                (t_verify - t_draft).as_secs_f64() * 1e3,
12300                (t0.elapsed() - t_verify).as_secs_f64() * 1e3,
12301                drafts.len()
12302            );
12303        }
12304        Some(SoloRound { accepted: drafts[..a].to_vec(), drafted: drafts.len(), hidden: hiddens[a * hs..(a + 1) * hs].to_vec(), logits: row })
12305    }
12306
12307    /// Micro-benchmark: two single-position forwards vs one fused pair
12308    /// from the current cache state (KV rewound after each probe).
12309    /// Returns (two_singles_ms, fused_pair_ms) per probe, or the (0, 0)
12310    /// sentinel when this model has no pair path to measure — the same
12311    /// answer the o1 arm gives, and the bench prints it the same way.
12312    /// (An architecture that loads its own layers leaves `weights.layers`
12313    /// empty; walking it here was an index panic, found by `bench` on
12314    /// deepseek_v4.)
12315    pub fn measure_pair_fusion(&mut self, iters: usize) -> (f64, f64) {
12316        if !self.pair_supported() {
12317            return (0.0, 0.0);
12318        }
12319        // A GDN model that needs an automatic device prefix never uses this
12320        // fused-pair path in normal generation: its recurrence is serial and
12321        // the speculative pair is disabled by default.  More importantly,
12322        // this diagnostic suppresses the token graph, so measuring it would
12323        // stream the non-resident tail through per-op Vulkan just to print a
12324        // non-production number.  Leave inference untouched and report the
12325        // established unavailable sentinel instead.
12326        if self.gdn_cfg.is_some()
12327            && self.graph_prefill_preferred()
12328            && self.automatic_gpu_prefix().is_some()
12329        {
12330            tracing::info!(
12331                "pair micro-benchmark skipped: GDN device-prefix path has no production pair route"
12332            );
12333            return (0.0, 0.0);
12334        }
12335        // Routed experts past the card live in the graphs' placement only
12336        // (system-memory banks under card slots): per op they run on the
12337        // host and the matrices' device copies outgrow the card (MiniMax-M3.1
12338        // on a whole A40: out of memory before the timed run).
12339        #[cfg(feature = "gpu")]
12340        let past = crate::gpu_wgpu::experts_past_card();
12341        #[cfg(not(feature = "gpu"))]
12342        let past = false;
12343        #[cfg(feature = "cuda")]
12344        let past = past || crate::gpu_cuda::experts_streamed();
12345        if past {
12346            tracing::info!("pair micro-benchmark skipped: routed experts past the card have no per-op route");
12347            return (0.0, 0.0);
12348        }
12349        // This is a host-side pair micro-benchmark. It truncates the host KV
12350        // after every probe, so letting the whole-token graph participate
12351        // would leave its device GDN/KV mirror ahead of the next probe and
12352        // poison the process-wide graph verdict before the real generation
12353        // benchmark starts. Keep the existing per-op/GPU arithmetic while
12354        // suppressing only the stateful token graph for this measurement.
12355        let graph_env = std::env::var_os("CMF_GPU_WGPU_GRAPH");
12356        unsafe { std::env::set_var("CMF_GPU_WGPU_GRAPH", "0") };
12357        let emb1 = self.embed_single(1);
12358        let emb2 = self.embed_single(2);
12359        let pos = self.kv_cache.seq_len();
12360
12361        let t0 = std::time::Instant::now();
12362        for _ in 0..iters {
12363            let _ = self.forward_layers(&emb1, pos, None);
12364            let _ = self.forward_layers(&emb2, pos + 1, None);
12365            for l in &mut self.kv_cache.layers {
12366                l.truncate_last(2);
12367            }
12368        }
12369        let singles_ms = t0.elapsed().as_secs_f64() * 1000.0 / iters as f64;
12370
12371        let t1 = std::time::Instant::now();
12372        for _ in 0..iters {
12373            let _ = self.forward_pair(&emb1, &emb2, pos);
12374            for l in &mut self.kv_cache.layers {
12375                l.truncate_last(2);
12376            }
12377        }
12378        let pair_ms = t1.elapsed().as_secs_f64() * 1000.0 / iters as f64;
12379        match graph_env {
12380            Some(value) => unsafe { std::env::set_var("CMF_GPU_WGPU_GRAPH", value) },
12381            None => unsafe { std::env::remove_var("CMF_GPU_WGPU_GRAPH") },
12382        }
12383        (singles_ms, pair_ms)
12384    }
12385
12386    /// Fused two-position forward: weight rows are streamed from memory
12387    /// once per layer for both positions. Full layers → fused GQA pair;
12388    /// linear layers → vmf_phase pair (lane 2 state is tentative in the
12389    /// per-layer scratch until the draft is accepted).
12390    /// Whether the fused two-position path covers every layer kind in
12391    /// this model. MLA and KDA run per position (their pair arms are
12392    /// unreachable); the seq prefill falls back to singles for them.
12393    fn pair_supported(&self) -> bool {
12394        // An EMPTY layer stack means the architecture loaded its own and
12395        // this path has nothing to walk. Checking that directly, rather
12396        // than naming each such architecture, is what makes the guard hold
12397        // for the next one: `any()` over no layers is false, so a
12398        // feature-by-feature test says "supported" for a model that has no
12399        // layers here at all.
12400        !self.weights.layers.is_empty()
12401            && !self.per_token_stack()
12402            && !self
12403                .weights
12404                .layers
12405                .iter()
12406                .any(|lw| matches!(&lw.attn, AttnKind::Mla(_) | AttnKind::Kda(_)))
12407    }
12408
12409    fn forward_pair(
12410        &mut self,
12411        emb1: &[f32],
12412        emb2: &[f32],
12413        position: usize,
12414    ) -> (Vec<f32>, Vec<f32>) {
12415        // A two-token prompt starts here, not in the layer walk: decide the
12416        // MiMo placement before the pair's per-op MoE uploads any expert.
12417        self.mimo_moe_prepare();
12418        let mut h1 = emb1.to_vec();
12419        let mut h2 = emb2.to_vec();
12420        if self.value_blend.is_some() {
12421            self.vres_e0.clear();
12422            self.vres_e0.extend_from_slice(emb1);
12423            self.vres_e0.extend_from_slice(emb2);
12424        }
12425        let (_nkv, _hd, hs, _rd, eps) = (
12426            self.num_kv_heads,
12427            self.head_dim,
12428            self.hidden_size,
12429            self.rotary_dim,
12430            self.rms_eps,
12431        );
12432        let pool = self.pool.clone();
12433        // `forward_pair` bypasses `forward_layers_span`, but its per-op
12434        // body must still obey the ordinary layer placement. In particular,
12435        // an over-capacity Vulkan model has a device prefix and a CPU tail;
12436        // letting the pair walk submit the tail's selected MoE experts would
12437        // stream the whole tail through the residency arena and defeat the
12438        // measured VRAM bound.
12439        let automatic_gpu_prefix = self.automatic_gpu_prefix();
12440
12441        for li in 0..self.num_layers {
12442            let _capacity_tail = automatic_gpu_prefix
12443                .filter(|&prefix| li >= prefix && !self.mimo_moe.is_dynamic(li, false))
12444                .map(|_| crate::gpu::enter_cpu_scope());
12445            // Also makes an explicit CMF_GPU_LAYERS split apply to fused
12446            // pairs, just as it does to the ordinary layer walk.
12447            crate::gpu::set_layer(li as i64);
12448            let lw = &self.weights.layers[self.phys_layer(li)];
12449            // Norms into pipeline scratch (4 allocs/layer on the MTP
12450            // decode hot path before this).
12451            inference::rms_norm_into(
12452                &h1,
12453                &lw.input_norm,
12454                self.rms_eps,
12455                self.norm_style,
12456                &mut self.ws.n1,
12457            );
12458            inference::rms_norm_into(
12459                &h2,
12460                &lw.input_norm,
12461                self.rms_eps,
12462                self.norm_style,
12463                &mut self.ws.n2,
12464            );
12465            // The two rows V projects, when the layer blends the embeddings into them.
12466            let vres = match self.layer_value_blend(li) {
12467                Some(blend) => {
12468                    let mut second = Vec::new();
12469                    vres_lerp(&self.vres_e0[..hs], &self.ws.n1, blend, &mut self.vres_in);
12470                    vres_lerp(&self.vres_e0[hs..], &self.ws.n2, blend, &mut second);
12471                    self.vres_in.extend_from_slice(&second);
12472                    true
12473                }
12474                None => false,
12475            };
12476
12477            let (a1, a2) = match &lw.attn {
12478                AttnKind::Mla(_) => unreachable!("MLA has no MTP/pair path"),
12479                AttnKind::Kda(_) => unreachable!("KDA has no MTP/pair path"),
12480                AttnKind::Bounded(w) => {
12481                    // Two sequential positions of the bounded operator
12482                    // (the ring's causal order is the pair's order).
12483                    let rope = self
12484                        .bounded_rope
12485                        .clone()
12486                        .expect("bounded layer without an installed rotation table");
12487                    let cfg = crate::bounded::BoundedAttnCfg {
12488                        num_heads: self.num_heads,
12489                        num_kv_heads: self.num_kv_heads,
12490                        head_dim: self.head_dim,
12491                        hidden_size: hs,
12492                        scale: self.attn_scale,
12493                        rope: &rope,
12494                        pool: pool.as_deref(),
12495                    };
12496                    let a1 = crate::bounded::bounded_attention(
12497                        &self.ws.n1,
12498                        w,
12499                        &mut self.kv_cache.layers[li],
12500                        &cfg,
12501                    );
12502                    let a2 = crate::bounded::bounded_attention(
12503                        &self.ws.n2,
12504                        w,
12505                        &mut self.kv_cache.layers[li],
12506                        &cfg,
12507                    );
12508                    (a1, a2)
12509                }
12510                AttnKind::Linear(w) => {
12511                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
12512                    let layer = &mut self.kv_cache.layers[li];
12513                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
12514                    vmf_phase_pair(
12515                        &self.ws.n1,
12516                        &self.ws.n2,
12517                        w,
12518                        &cfg,
12519                        state,
12520                        scratch,
12521                        self.pool.as_deref(),
12522                    )
12523                }
12524                AttnKind::LinearGdn(w) => {
12525                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
12526                    let layer = &mut self.kv_cache.layers[li];
12527                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
12528                    gdn_pair(
12529                        &self.ws.n1,
12530                        &self.ws.n2,
12531                        w,
12532                        &cfg,
12533                        state,
12534                        scratch,
12535                        self.pool.as_deref(),
12536                    )
12537                }
12538                AttnKind::ShortConv(w) => {
12539                    let cfg = self
12540                        .short_conv_cfg
12541                        .expect("short-conv layer without short_conv_cfg");
12542                    let layer = &mut self.kv_cache.layers[li];
12543                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
12544                    short_conv_pair(
12545                        &self.ws.n1,
12546                        &self.ws.n2,
12547                        w,
12548                        &cfg,
12549                        state,
12550                        scratch,
12551                        self.pool.as_deref(),
12552                    )
12553                }
12554                AttnKind::Full {
12555                    wq,
12556                    wk,
12557                    wv,
12558                    wo,
12559                    q_norm,
12560                    k_norm,
12561                    output_gate,
12562                    softplus_gate,
12563                    bias,
12564                } => {
12565                    let inv_freq_l = self.layer_inv_freq(li);
12566                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
12567                    let cfg = QwenAttnCfg {
12568                        mrope: None,
12569                        num_heads: self.layer_num_heads(li),
12570                        num_kv_heads: nkv_l,
12571                        head_dim: hd_l,
12572                        hidden_size: hs,
12573                        position,
12574                        inv_freq: &inv_freq_l,
12575                        rotary_dim: rd_l,
12576                        scale: self.attn_scale,
12577                        softcap: self.attn_softcap,
12578                        window: self.layer_window(li),
12579                        v_norm: self.attn_v_norm,
12580                        qk_norm_after_rope: self.qk_norm_after_rope,
12581                        gate_sigmoid: self.proj_gate_sigmoid,
12582                        q_norm: q_norm.as_deref(),
12583                        k_norm: k_norm.as_deref(),
12584                        output_gate: *output_gate,
12585                        softplus_gate: softplus_gate
12586                            .as_ref()
12587                            .map(|(gate, per_head)| (gate, *per_head)),
12588                        rope_scale: self.layer_rope_scale(li),
12589                        bias: bias
12590                            .as_ref()
12591                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
12592                        rms_eps: eps,
12593                        norm_style: self.norm_style,
12594                        pool: pool.as_deref(),
12595                        v_head_dim: self.layer_v_dim(li),
12596                        value_in: vres.then(|| self.vres_in.as_slice()),
12597                    };
12598                    attention::qwen_attention_pair(
12599                        &self.ws.n1,
12600                        &self.ws.n2,
12601                        wq,
12602                        wk,
12603                        wv,
12604                        wo,
12605                        &mut self.kv_cache.layers[li],
12606                        &cfg,
12607                    )
12608                }
12609            };
12610            let (a1, a2) = match &self.weights.layers[self.phys_layer(li)].attn_out_norm {
12611                Some(w) => (
12612                    inference::rms_norm(&a1, w, self.rms_eps, self.norm_style),
12613                    inference::rms_norm(&a2, w, self.rms_eps, self.norm_style),
12614                ),
12615                None => (a1, a2),
12616            };
12617            for i in 0..self.hidden_size {
12618                h1[i] += a1[i];
12619                h2[i] += a2[i];
12620            }
12621            let (mut a1, mut a2) = (a1, a2);
12622            attention::recycle_buf(&mut a1);
12623            attention::recycle_buf(&mut a2);
12624
12625            let lw = &self.weights.layers[self.phys_layer(li)];
12626            inference::rms_norm_into(
12627                &h1,
12628                &lw.post_norm,
12629                self.rms_eps,
12630                self.norm_style,
12631                &mut self.ws.p1,
12632            );
12633            inference::rms_norm_into(
12634                &h2,
12635                &lw.post_norm,
12636                self.rms_eps,
12637                self.norm_style,
12638                &mut self.ws.p2,
12639            );
12640            let (f1, f2) = match &lw.ffn {
12641                // Dual-branch layers need the raw residuals — run the
12642                // two positions through the same fn decode uses.
12643                FfnKind::DenseMoe(dm) => (
12644                    dense_moe_ffn(
12645                        dm,
12646                        &self.ws.p1,
12647                        &h1,
12648                        self.rms_eps,
12649                        self.norm_style,
12650                        self.pool.as_deref(),
12651                    ),
12652                    dense_moe_ffn(
12653                        dm,
12654                        &self.ws.p2,
12655                        &h2,
12656                        self.rms_eps,
12657                        self.norm_style,
12658                        self.pool.as_deref(),
12659                    ),
12660                ),
12661                FfnKind::Moe(m) if self.mimo_moe.is_dynamic(li, false) => (
12662                    moe_ffn_banked(&mut self.mimo_moe, li, m, &self.ws.p1, self.pool.as_deref()),
12663                    moe_ffn_banked(&mut self.mimo_moe, li, m, &self.ws.p2, self.pool.as_deref()),
12664                ),
12665                _ => ffn_forward_pair(
12666                    &lw.ffn,
12667                    &self.ws.p1,
12668                    &self.ws.p2,
12669                    self.pool.as_deref(),
12670                    None,
12671                ),
12672            };
12673            let (f1, f2) = match &self.weights.layers[self.phys_layer(li)].ffn_out_norm {
12674                Some(w) => (
12675                    inference::rms_norm(&f1, w, self.rms_eps, self.norm_style),
12676                    inference::rms_norm(&f2, w, self.rms_eps, self.norm_style),
12677                ),
12678                None => (f1, f2),
12679            };
12680            for i in 0..self.hidden_size {
12681                h1[i] += f1[i];
12682                h2[i] += f2[i];
12683            }
12684            let (mut f1, mut f2) = (f1, f2);
12685            attention::recycle_buf(&mut f1);
12686            attention::recycle_buf(&mut f2);
12687            if let Some(sc) = self.weights.layers[self.phys_layer(li)].layer_scale {
12688                for i in 0..self.hidden_size {
12689                    h1[i] *= sc;
12690                    h2[i] *= sc;
12691                }
12692            }
12693            // Looped Transformer: apply final norm at the end of each loop iteration.
12694            if self.is_loop_end(li) && li + 1 < self.num_layers {
12695                h1 = inference::rms_norm(
12696                    &h1,
12697                    &self.weights.final_norm,
12698                    self.rms_eps,
12699                    self.norm_style,
12700                );
12701                h2 = inference::rms_norm(
12702                    &h2,
12703                    &self.weights.final_norm,
12704                    self.rms_eps,
12705                    self.norm_style,
12706                );
12707            }
12708        }
12709        crate::gpu::set_layer(-1); // final/O(1) work is outside layer placement
12710        // Real O(1) prefill pairs may also carry tentative lane-2 recurrent
12711        // state. Commit it before publishing the transition epoch so the
12712        // next serial/device row cannot observe a new attention epoch with an
12713        // old GDN state. Speculative pairs run only when O(1) is inactive and
12714        // retain their existing caller-controlled commit/rollback semantics.
12715        if self.o1_active() {
12716            self.commit_linear_scratch();
12717        }
12718        self.o1_progress();
12719        self.swa_trim_tails();
12720        (h1, h2)
12721    }
12722
12723    /// Commit lane-2 linear states after an accepted draft.
12724    fn commit_linear_scratch(&mut self) {
12725        for layer in &mut self.kv_cache.layers {
12726            if !layer.linear_scratch.is_empty() {
12727                std::mem::swap(&mut layer.linear_state, &mut layer.linear_scratch);
12728                layer.linear_scratch.clear();
12729            }
12730        }
12731    }
12732
12733    /// This is the encoder counterpart to `forward_ids`: it runs a fresh
12734    /// sequence through the existing full/GDN hybrid stack and returns the
12735    /// final RMS-normalized hidden row for *every* token.  It is used by
12736    /// component pipelines whose text tower intentionally has no LM head
12737    /// (such as an image-conditioner Qwen3.5 model).  The sequence state is
12738    /// always released before returning, so a large text tower can be dropped
12739    /// immediately after conditioning a subsequent stage.
12740    pub fn encode_hidden_states(&mut self, ids: &[u32]) -> Result<Vec<f32>, String> {
12741        #[cfg(target_os = "macos")]
12742        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
12743        if ids.is_empty() {
12744            return Err("empty id sequence".to_string());
12745        }
12746
12747        self.nll_begin()?;
12748        let result = (|| {
12749            let hidden = self.prefill_input_rows(PrefillIn::Ids(ids), 0, None)?;
12750            self.nll_check_graph("encoder prefill", 0)?;
12751            let expected = ids.len() * self.hidden_size;
12752            if hidden.len() != expected {
12753                return Err(format!(
12754                    "encoder prefill returned {} values for {} rows of hidden size {}",
12755                    hidden.len(),
12756                    ids.len(),
12757                    self.hidden_size
12758                ));
12759            }
12760
12761            let mut out = vec![0.0f32; expected];
12762            for (src, dst) in hidden
12763                .chunks_exact(self.hidden_size)
12764                .zip(out.chunks_exact_mut(self.hidden_size))
12765            {
12766                inference::rms_norm_into(
12767                    src,
12768                    &self.weights.final_norm,
12769                    self.rms_eps,
12770                    self.norm_style,
12771                    dst,
12772                );
12773            }
12774            Ok(out)
12775        })();
12776        self.nll_end();
12777        result
12778    }
12779
12780    /// The last layer's hidden row (before the final norm) for every token
12781    /// of `ids`, from a fresh sequence, through the whole-stack prefill (the
12782    /// device chunk graph where there is one) — what a distillation cache of
12783    /// teacher outputs needs, at prefill speed.
12784    pub fn final_hidden_rows(&mut self, ids: &[u32]) -> Result<Vec<f32>, String> {
12785        #[cfg(target_os = "macos")]
12786        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
12787        if ids.is_empty() {
12788            return Err("empty id sequence".to_string());
12789        }
12790        self.nll_begin()?;
12791        let result = (|| {
12792            let hidden = self.prefill_input_rows(PrefillIn::Ids(ids), 0, None)?;
12793            self.nll_check_graph("hidden prefill", 0)?;
12794            if hidden.len() != ids.len() * self.hidden_size {
12795                return Err(format!("hidden prefill returned {} values for {} rows", hidden.len(), ids.len()));
12796            }
12797            Ok(hidden)
12798        })();
12799        self.nll_end();
12800        result
12801    }
12802
12803    /// Forward a full id sequence from a fresh cache and return the
12804    /// logits after the last position (golden-parity harness, bench).
12805    pub fn forward_ids(
12806        &mut self,
12807        ids: &[u32],
12808        task_mask: Option<&TaskMask>,
12809    ) -> Result<Vec<f32>, String> {
12810        #[cfg(target_os = "macos")]
12811        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
12812        if ids.is_empty() {
12813            return Err("empty id sequence".to_string());
12814        }
12815        self.clear_sequence_state();
12816        self.check_forward_graph("forward_ids setup", 0)?;
12817        if task_mask.is_none() {
12818            self.o1_begin();
12819        }
12820        let mut hidden = vec![0.0f32; self.hidden_size];
12821        let mut pos = 0usize;
12822        if self.dory.is_some() {
12823            return Ok(self.dory_forward(ids, 0, crate::dory::Want::Last));
12824        }
12825        if let Some(b) = &mut self.dsv41 {
12826            let pool = self.pool.clone();
12827            let mut logits = Vec::new();
12828            crate::dsv41::forward_chunk(
12829                &b.0,
12830                &b.1,
12831                &b.2,
12832                &mut b.3,
12833                ids,
12834                0,
12835                pool.as_deref(),
12836                &mut logits,
12837            );
12838            if let Err(err) = self.o1_seal_checked() {
12839                self.clear_sequence_state();
12840                return Err(err);
12841            }
12842            return Ok(logits);
12843        }
12844        // Inkling-2-Mini: the prompt as generation reads it (the card's
12845        // prompt calls, else host chunks), so bench times that route
12846        if let Some(b) = &mut self.inkling {
12847            let mut logits = Vec::new();
12848            let taken = crate::inkling::forward_prompt(&b.0, &b.1, &b.2, &mut b.3, ids, 0, self.pool.as_deref(), &mut logits);
12849            for (i, &t) in ids.iter().enumerate().skip(taken) {
12850                crate::inkling::forward_token(&b.0, &b.1, &b.2, &mut b.3, t, i, self.pool.as_deref(), &mut logits, i + 1 == ids.len());
12851            }
12852            self.graph_logits = Some(logits.clone());
12853            return Ok(logits);
12854        }
12855        // Same routing predicate generation uses. Two reasons it must be
12856        // the same one: (1) a GDN hybrid's recurrent state is GPU-
12857        // resident, and a batched CPU prefill would build it on the host
12858        // only — decode then reads buffers the prefill never wrote;
12859        // (2) bench times THIS function and calls the result "prefill",
12860        // so a different path here reports a number production never
12861        // sees (W2 on 2×5090: 8.7 tok/s reported against 125 real).
12862        // Gemma-4: generation's batched-graph ingest (`g4_batch_ingest`),
12863        // so bench and the parity tools time and score the route run/serve
12864        // take; a refusal leaves the rest to the chunked host prefill.
12865        #[cfg(not(target_os = "macos"))]
12866        if task_mask.is_none() && ids.len() > 2 && self.g4_batch_prefill() {
12867            let (n, last) = match self.g4_batch_ingest(ids, 0, false) {
12868                Ok(r) => r,
12869                Err(e) => {
12870                    self.clear_sequence_state();
12871                    return Err(e);
12872                }
12873            };
12874            if n > 0 {
12875                hidden.copy_from_slice(&last);
12876                pos = n;
12877            }
12878        }
12879        if self.can_prefill_batched() && !self.graph_prefill_preferred() && ids.len() > 2 {
12880            // prefill-GEMM in chunks; only the last position's hidden is
12881            // needed. (o1-compatible: the batch path attends per position
12882            // through qwen_attention, which carries the collection hook.)
12883            let chunk = self.prefill_chunk();
12884            let hs = self.hidden_size;
12885            while pos < ids.len() {
12886                let end = (pos + chunk).min(ids.len());
12887                let hb = self.prefill_rows(&ids[pos..end], pos, task_mask)?;
12888                self.check_forward_graph("forward_ids batched prefill", end - 1)?;
12889                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
12890                pos = end;
12891            }
12892        }
12893        // Same guards as generation's prefill — INCLUDING the graph one.
12894        // The CPU pair walk was intercepting positions that the resident
12895        // token graph would have run itself: on a GDN hybrid over wgpu
12896        // that is 89 ms of host forward against 7 ms of device submit,
12897        // and it made prefill look 12× slower than it is (W2 on an RTX
12898        // 5090, ctx 512: 11.2 tok/s with the walk, 136.6 without).
12899        // CMF_PAIR=0 opts out; a model whose layers live outside
12900        // `weights.layers` has no pair walk to take.
12901        if task_mask.is_none()
12902            && !self.graph_prefill_preferred()
12903            && !std::env::var("CMF_PAIR").is_ok_and(|v| v == "0")
12904            && self.pair_supported()
12905        {
12906            while pos + 1 < ids.len() {
12907                let e1 = self.embed_single(ids[pos]);
12908                let e2 = self.embed_single(ids[pos + 1]);
12909                let (_, h2) = self.forward_pair(&e1, &e2, pos);
12910                self.check_forward_graph("forward_ids pair", pos + 1)?;
12911                self.commit_linear_scratch();
12912                hidden = h2;
12913                pos += 2;
12914            }
12915        }
12916        // Resident Embryo graph: the prompt in chunks of one submit each
12917        // (the same device state and logits as the per-position walk).
12918        if task_mask.is_none() && pos == 0 && ids.len() > 1 {
12919            if let Some(lg) = self.embryo_prefill_chunked(ids, 0) {
12920                self.graph_logits = Some(lg);
12921                hidden = vec![0.0; self.hidden_size];
12922                pos = ids.len();
12923            }
12924        }
12925        // Flash-Next class: the prompt in the frames generation reads it in
12926        // (`qwen4_exp::forward_tokens`, a chunk a call) — the per-position
12927        // walk below read a 4096-token prompt on Vulkan at 46 tok/s where
12928        // generation's own prefill took 6.4 s.
12929        if task_mask.is_none() && pos == 0 && self.qwen4_exp.is_some() {
12930            while pos < ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
12931                let end = (pos + crate::qwen4_exp::prefill_chunk()).min(ids.len());
12932                let want = end == ids.len();
12933                let mut lg = Vec::new();
12934                if let Some(b) = &mut self.qwen4_exp {
12935                    crate::qwen4_exp::forward_tokens(&b.0, &b.1, &b.2, &mut b.3, &ids[pos..end], pos, &self.inv_freq, self.pool.as_deref(), &mut lg, want);
12936                }
12937                if want {
12938                    self.graph_logits = Some(lg);
12939                }
12940                pos = end;
12941            }
12942            hidden = vec![0.0; self.hidden_size];
12943        }
12944        while pos < ids.len() {
12945            hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, task_mask);
12946            self.check_forward_graph("forward_ids", pos)?;
12947            pos += 1;
12948        }
12949        if let Some(logits) = self.graph_logits.take() {
12950            // Resident stacks already applied final norm and their head in
12951            // the same submit; do not run a second norm/head over the zero
12952            // hidden sentinel returned by forward_layers_span.
12953            if let Err(err) = self.o1_seal_checked() {
12954                self.clear_sequence_state();
12955                return Err(err);
12956            }
12957            return Ok(logits);
12958        }
12959        // Harness contract: after forward_ids the cache is decode-ready —
12960        // under o1 that means sealed (bench measures the seal as part of
12961        // prefill, honestly).
12962        if let Err(err) = self.o1_seal_checked() {
12963            self.clear_sequence_state();
12964            return Err(err);
12965        }
12966        let normed = inference::rms_norm(
12967            &hidden,
12968            &self.weights.final_norm,
12969            self.rms_eps,
12970            self.norm_style,
12971        );
12972        Ok(self.lm_head_forward(&normed))
12973    }
12974
12975    /// Run the V4.1 stack one token at a time and retain logits for every
12976    /// position. This is a diagnostic surface for comparing a converted
12977    /// checkpoint with a tokenwise reference implementation.
12978    #[doc(hidden)]
12979    pub fn dsv41_serial_logits(&mut self, ids: &[u32]) -> Result<Vec<Vec<f32>>, String> {
12980        #[cfg(target_os = "macos")]
12981        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
12982        if ids.is_empty() {
12983            return Err("empty id sequence".to_string());
12984        }
12985        self.clear_sequence_state();
12986        self.dsv41
12987            .as_ref()
12988            .ok_or_else(|| "dsv41 serial logits require a DeepSeek-V4.1 model".to_string())?;
12989        self.o1_begin();
12990        let rows = {
12991            let pool = self.pool.clone();
12992            let b = self
12993                .dsv41
12994                .as_mut()
12995                .expect("dsv41 checked above; state cannot change during forward");
12996            let mut rows = Vec::with_capacity(ids.len());
12997            for (position, &id) in ids.iter().enumerate() {
12998                let mut logits = Vec::new();
12999                crate::dsv41::forward_token(
13000                    &b.0,
13001                    &b.1,
13002                    &b.2,
13003                    &mut b.3,
13004                    id,
13005                    position,
13006                    pool.as_deref(),
13007                    &mut logits,
13008                );
13009                rows.push(logits);
13010            }
13011            rows
13012        };
13013        self.o1_seal();
13014        Ok(rows)
13015    }
13016
13017    /// GPTQ calibration of DeepSeek-V4.1 (`cortiq quantize-moe`): the MoE
13018    /// input rows and routed expert ids of layers `lo..hi` for `ids` (a fresh
13019    /// sequence), see [`crate::dsv41::Dsv41MoeCapture`].
13020    pub fn dsv41_moe_capture(
13021        &mut self,
13022        ids: &[u32],
13023        lo: usize,
13024        hi: usize,
13025    ) -> Result<crate::dsv41::Dsv41MoeCapture, String> {
13026        #[cfg(target_os = "macos")]
13027        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
13028        if ids.is_empty() {
13029            return Err("empty id sequence".to_string());
13030        }
13031        self.dsv41
13032            .as_ref()
13033            .ok_or_else(|| "not a DeepSeek-V4.1 model".to_string())?;
13034        self.clear_sequence_state();
13035        let res = {
13036            let pool = self.pool.clone();
13037            let b = self.dsv41.as_mut().expect("dsv41 checked above");
13038            crate::dsv41::capture_window(&b.0, &b.1, &b.2, &mut b.3, ids, lo, hi, pool.as_deref())
13039        };
13040        self.clear_sequence_state();
13041        res
13042    }
13043
13044    /// GPTQ calibration of Maxwell's routed experts (`cortiq quantize-moe`):
13045    /// the routed FFNs' input rows and expert ids of layers `lo..hi` for
13046    /// `ids` (a fresh sequence), see [`crate::maxwell::MoeCapture`].
13047    pub fn maxwell_moe_capture(&mut self, ids: &[u32], lo: usize, hi: usize) -> Result<crate::maxwell::MoeCapture, String> {
13048        if ids.is_empty() {
13049            return Err("empty id sequence".to_string());
13050        }
13051        self.maxwell.as_ref().ok_or_else(|| "not a Maxwell model".to_string())?;
13052        self.clear_sequence_state();
13053        let res = {
13054            let pool = self.pool.clone();
13055            let b = self.maxwell.as_mut().expect("maxwell checked above");
13056            crate::maxwell::capture_window(&b.0, &b.1, &b.2, &mut b.3, ids, lo, hi, pool.as_deref())
13057        };
13058        self.clear_sequence_state();
13059        res
13060    }
13061
13062    /// Teacher-forced perplexity over a token sequence (phase-C gate:
13063    /// honest quant comparisons instead of prompt vibes).
13064    ///
13065    /// Attention is EXACT even on a model whose layers are flagged for
13066    /// the O(1) kernel — scoring the backbone is the default on purpose
13067    /// (it is the yardstick). `nll_ids_o1` scores the CONVERTED model.
13068    pub fn ppl_ids(&mut self, ids: &[u32]) -> Result<f64, String> {
13069        let (nll, cnt) = self.nll_ids_from(ids, 0)?;
13070        Ok((nll / cnt.max(1) as f64).exp())
13071    }
13072
13073    /// GPTQ calibration forward: `ids` through layers `0..upto` only, in
13074    /// layer-major chunks of `chunk` positions, with no vocabulary head and
13075    /// no scoring. The Hessian hook (`gptq_capture`) folds every
13076    /// projection's input on the way; the layers above the captured span
13077    /// and the head would only cost time. Falls back to a scored forward
13078    /// where the batched prefill does not apply.
13079    pub fn calib_forward(&mut self, ids: &[u32], upto: usize, chunk: usize) -> Result<(), String> {
13080        if !self.can_prefill_batched() {
13081            return self.nll_ids_from(ids, 0).map(|_| ());
13082        }
13083        self.nll_begin()?;
13084        let result: Result<(), String> = (|| {
13085            let chunk = chunk.max(1);
13086            let mut pos = 0usize;
13087            while pos < ids.len() {
13088                let end = (pos + chunk).min(ids.len());
13089                let _ = self.prefill_batch_span(PrefillIn::Ids(&ids[pos..end]), pos, None, 0, upto);
13090                self.nll_check_graph("calibration prefill", pos)?;
13091                pos = end;
13092            }
13093            Ok(())
13094        })();
13095        self.nll_end();
13096        result
13097    }
13098
13099    /// Layer-streamed calibration of one fresh window: layers `from..mid` run
13100    /// on `input` (the hidden state entering layer `from`; `None` = the
13101    /// token embeddings of `ids`) and their output is returned, then layers
13102    /// `mid..upto` run on that output for the capture hooks (their output is
13103    /// dropped). A caller that keeps the returned state per window runs each
13104    /// layer once over the whole conversion instead of re-running the stack
13105    /// below every layer. With `mid == from` the input is returned as is
13106    /// (`None` input: an empty vector).
13107    pub fn calib_window_span(
13108        &mut self,
13109        ids: &[u32],
13110        input: Option<&[f32]>,
13111        from: usize,
13112        mid: usize,
13113        upto: usize,
13114    ) -> Result<Vec<f32>, String> {
13115        if !self.can_prefill_batched() {
13116            return Err("calib_window_span: this architecture has no batched prefill".into());
13117        }
13118        self.nll_begin()?;
13119        let result: Result<Vec<f32>, String> = (|| {
13120            let h = if mid > from {
13121                let inp = match input {
13122                    Some(h) => PrefillIn::Hidden(h),
13123                    None => PrefillIn::Ids(ids),
13124                };
13125                let h = self.prefill_batch_span(inp, 0, None, from, mid);
13126                self.nll_check_graph("calibration span", 0)?;
13127                h
13128            } else {
13129                input.map(<[f32]>::to_vec).unwrap_or_default()
13130            };
13131            if upto > mid {
13132                let inp = if mid > from || input.is_some() {
13133                    PrefillIn::Hidden(&h)
13134                } else {
13135                    PrefillIn::Ids(ids)
13136                };
13137                let _ = self.prefill_batch_span(inp, 0, None, mid, upto);
13138                self.nll_check_graph("calibration span", 0)?;
13139            }
13140            Ok(h)
13141        })();
13142        self.nll_end();
13143        result
13144    }
13145
13146    /// GPTQ calibration of a Flash-Next-class MoE (`qwen4_exp`): MoE input
13147    /// rows and router logits of layers `lo..hi` for `ids` (a fresh
13148    /// sequence), per layer `[ids.len()][hidden + n_experts]`.
13149    #[cfg(feature = "gpu")]
13150    pub fn qwen4_capture(
13151        &mut self,
13152        ids: &[u32],
13153        lo: usize,
13154        hi: usize,
13155    ) -> Result<Vec<Vec<f32>>, String> {
13156        let b = self.qwen4_exp.as_mut().ok_or("not a qwen4_exp model")?;
13157        crate::qwen4_exp::capture_window(
13158            &b.0,
13159            &b.1,
13160            &b.2,
13161            &mut b.3,
13162            ids,
13163            lo,
13164            hi,
13165            &self.inv_freq,
13166            self.pool.as_deref(),
13167        )
13168    }
13169
13170    /// GPTQ calibration capture of an ordinary MoE stack (Qwen3.5/3.6
13171    /// MoE, Clover): `ids` from position 0 through the batched device graph
13172    /// in prefill-sized chunks, the MoE input rows and router logits of
13173    /// layers `lo..hi` copied out after routing. Returns per layer
13174    /// `[ids.len()][hidden + n_experts]`; the sequence state is left fresh.
13175    #[cfg(feature = "gpu")]
13176    pub fn moe_capture(&mut self, ids: &[u32], lo: usize, hi: usize) -> Result<Vec<Vec<f32>>, String> {
13177        use crate::gpu_wgpu::clover as cap;
13178        let (hs, hi) = (self.hidden_size, hi.min(self.num_layers));
13179        let ne = (lo..hi)
13180            .find_map(|li| match &self.weights.layers[self.phys_layer(li)].ffn {
13181                FfnKind::Moe(m) => Some(m.experts.len()),
13182                _ => None,
13183            })
13184            .ok_or("no MoE layer in the capture range")?;
13185        let chunk = self.prefill_chunk().max(1);
13186        self.clear_sequence_state();
13187        if !cap::moe_capture_begin(lo, hi, chunk, hs, ne) {
13188            return Err("capture unavailable (no wgpu device)".into());
13189        }
13190        let mut out: Vec<Vec<f32>> = (lo..hi).map(|_| Vec::with_capacity(ids.len() * (hs + ne))).collect();
13191        let res = (|| {
13192            for (ci, part) in ids.chunks(chunk).enumerate() {
13193                let mut hiddens = Vec::with_capacity(part.len() * hs);
13194                for &id in part {
13195                    hiddens.extend_from_slice(&self.embed_single(id));
13196                }
13197                let positions: Vec<usize> = (ci * chunk..ci * chunk + part.len()).collect();
13198                match self.try_batch_graph_wgpu(&mut hiddens, &positions, part.len(), None) {
13199                    crate::gpu::BatchGraphOutcome::Completed => {}
13200                    _ => return Err("the batched graph declined the calibration forward (VRAM budget?)".to_string()),
13201                }
13202                let (rows, written) = cap::moe_capture_read(part.len()).ok_or("capture readback")?;
13203                if written < hi - lo {
13204                    return Err(format!("{written} of {} captured layers ran through the device MoE arm", hi - lo));
13205                }
13206                for (o, r) in out.iter_mut().zip(rows) {
13207                    o.extend_from_slice(&r);
13208                }
13209            }
13210            Ok(())
13211        })();
13212        cap::moe_capture_end();
13213        self.clear_sequence_state();
13214        res.map(|_| out)
13215    }
13216
13217    /// Expert directory triples (gate, up, down) of an ordinary MoE layer,
13218    /// routed and shared.
13219    pub fn moe_expert_dirs(
13220        &self,
13221        li: usize,
13222    ) -> Option<(Vec<(usize, usize, usize)>, Option<(usize, usize, usize)>)> {
13223        let FfnKind::Moe(m) = &self.weights.layers.get(self.phys_layer(li))?.ffn else {
13224            return None;
13225        };
13226        let dirs = |d: &DenseFfn| Some((d.gate_proj.model_idx()?, d.up_proj.model_idx()?, d.down_proj.model_idx()?));
13227        let routed = m.experts.iter().map(dirs).collect::<Option<Vec<_>>>()?;
13228        let shared = match &m.shared {
13229            Some((se, _)) => Some(dirs(se)?),
13230            None => None,
13231        };
13232        Some((routed, shared))
13233    }
13234
13235    /// Expert directory triples of a `qwen4_exp` layer (routed, shared).
13236    pub fn qwen4_expert_dirs(
13237        &self,
13238        li: usize,
13239    ) -> Option<(Vec<(usize, usize, usize)>, Option<(usize, usize, usize)>)> {
13240        let b = self.qwen4_exp.as_ref()?;
13241        crate::qwen4_exp::expert_dirs(&b.1, li)
13242    }
13243
13244    /// Teacher-force the installed MTP draft stack and collect each draft
13245    /// FFN's own pre-down activation statistics.
13246    ///
13247    /// This is deliberately separate from [`Self::probe_ffn_mass`]: canonical
13248    /// MTP and MiMo sidecars can have independently compacted FFNs, and MiMo
13249    /// draft layers can differ in width from one another and from the trunk.
13250    /// The returned vector follows the actual draft stack (one entry for a
13251    /// canonical MTP head; one per MiMo draft layer). MiMo layer `k` replays
13252    /// the teacher-forced pairs `(hidden[j], ids[j + k + 1])`.
13253    ///
13254    /// Calibration starts from a fresh sequence and leaves the trunk, draft
13255    /// KVs, history, and device mirrors fresh on both success and error. It
13256    /// is therefore unsuitable for the middle of a conversation whose KV
13257    /// cache must be retained.
13258    pub fn probe_mtp_ffn(&mut self, ids: &[u32]) -> Result<Vec<MtpFfnProbe>, String> {
13259        self.reset_mtp_probe_state();
13260        // The trunk runs as one prefill (the device graph where there is
13261        // one); the draft replays on the host under a CPU scope, where its
13262        // FFN input can be measured. This guard also suppresses gate/oracle
13263        // sparsity experiments for the duration so the statistics and
13264        // admission replay always execute the full dense FFN.
13265        let _exact_calibration = ExactMtpCalibrationGuard::enter();
13266        let result = if ids.len() < 2 {
13267            Err("MTP FFN probe needs at least two token ids".into())
13268        } else if ids
13269            .iter()
13270            .any(|&id| id as usize >= self.weights.embed_tokens.rows())
13271        {
13272            Err("MTP FFN probe received a token id outside the embedding table".into())
13273        } else if self.mtp.is_some() && self.mimo_mtp.is_some() {
13274            // A synthetic pipeline can carry both mechanisms, but merging
13275            // unlike draft semantics into one compaction plan is unsafe.
13276            Err("MTP FFN probe found both canonical and MiMo draft stacks".into())
13277        } else if self.mimo_mtp.is_some() {
13278            let mut st = self
13279                .mimo_mtp
13280                .take()
13281                .expect("checked MiMo MTP before detaching it");
13282            let result = match self.probe_trunk_rows(ids) {
13283                Ok(trunk) => crate::gpu::cpu_scope(|| {
13284                    self.mimo_mtp_ffn_probe_teacher_forced(&mut st, ids, &trunk)
13285                }),
13286                Err(e) => Err(e),
13287            };
13288            // The owner is detached during the replay, so the common trunk
13289            // reset cannot clear its KVs. Restore it even on an error.
13290            st.reset();
13291            self.mimo_mtp = Some(st);
13292            result
13293        } else if self.mtp.is_some() {
13294            let mut mtp = self
13295                .mtp
13296                .take()
13297                .expect("checked canonical MTP before detaching it");
13298            let result = match self.probe_trunk_rows(ids) {
13299                Ok(trunk) => crate::gpu::cpu_scope(|| {
13300                    self.mtp_ffn_probe_teacher_forced(&mut mtp, ids, &trunk)
13301                }),
13302                Err(e) => Err(e),
13303            };
13304            mtp.kv.clear();
13305            self.mtp = Some(mtp);
13306            result
13307        } else {
13308            Err("MTP FFN probe: this pipeline has no draft stack".into())
13309        };
13310        // Cover every early/error arm above: no failed calibration can leak
13311        // a partially populated trunk or draft cache into the next request.
13312        self.reset_mtp_probe_state();
13313        result
13314    }
13315
13316    /// Reset every state owner touched by [`Self::probe_mtp_ffn`].
13317    fn reset_mtp_probe_state(&mut self) {
13318        self.clear_sequence_state();
13319        if let Some(mtp) = self.mtp.as_mut() {
13320            mtp.kv.clear();
13321        }
13322        if let Some(mimo) = self.mimo_mtp.as_mut() {
13323            mimo.reset();
13324        }
13325        self.mtp_graph_mode = None;
13326    }
13327
13328    /// The trunk's last hidden row (before the final norm) at every
13329    /// position a teacher-forced draft probe reads (`ids[..len-1]`), from
13330    /// the whole-stack prefill — the device graph where there is one. One
13331    /// position at a time through `forward_layers` on the host this was the
13332    /// probe's whole cost: a 14B's 96k calibration tokens ran for hours.
13333    pub(crate) fn probe_trunk_rows(&mut self, ids: &[u32]) -> Result<Vec<f32>, String> {
13334        if ids.len() < 2 {
13335            return Err("MTP FFN probe needs at least two token ids".into());
13336        }
13337        let rows = self.final_hidden_rows(&ids[..ids.len() - 1])?;
13338        self.clear_sequence_state();
13339        Ok(rows)
13340    }
13341
13342    /// Canonical one-layer MTP teacher-forced replay over the trunk rows
13343    /// of [`Self::probe_trunk_rows`]. Its cache advances for every row so
13344    /// later attention inputs match a real draft warm-up rather than a
13345    /// collection of independent one-token measurements. The FFN inputs are
13346    /// measured in batches: nothing after the FFN feeds a later row.
13347    fn mtp_ffn_probe_teacher_forced(
13348        &mut self,
13349        mtp: &mut MtpModule,
13350        ids: &[u32],
13351        trunk: &[f32],
13352    ) -> Result<Vec<MtpFfnProbe>, String> {
13353        let FfnKind::Dense(dense) = &mtp.layer.ffn else {
13354            return Err("MTP FFN probe: canonical draft FFN is not dense".into());
13355        };
13356        let inter = dense.gate_proj.rows();
13357        let (hs, n) = (self.hidden_size, ids.len() - 1);
13358        if trunk.len() != n * hs {
13359            return Err(format!(
13360                "MTP FFN probe: {} trunk values for {n} rows of width {hs}",
13361                trunk.len()
13362            ));
13363        }
13364        let mut mass = vec![0.0f64; inter];
13365        let mut squared_mass = vec![0.0f64; inter];
13366        let mut inputs = Vec::with_capacity(MTP_PROBE_FFN_ROWS.min(n) * hs);
13367        for position in 0..n {
13368            self.mtp_probe_ffn_input(
13369                mtp,
13370                &trunk[position * hs..(position + 1) * hs],
13371                ids[position + 1],
13372                position,
13373            )?;
13374            inputs.extend_from_slice(&self.ws.p1[..hs]);
13375            if inputs.len() == MTP_PROBE_FFN_ROWS * hs || position + 1 == n {
13376                let FfnKind::Dense(dense) = &mtp.layer.ffn else {
13377                    unreachable!("checked dense above");
13378                };
13379                accumulate_dense_ffn_activation_mass(
13380                    dense,
13381                    &inputs,
13382                    inputs.len() / hs,
13383                    self.pool.as_deref(),
13384                    &mut mass,
13385                    &mut squared_mass,
13386                )?;
13387                inputs.clear();
13388            }
13389        }
13390        Ok(vec![MtpFfnProbe {
13391            mass,
13392            squared_mass,
13393            observed_positions: n,
13394        }])
13395    }
13396
13397    /// CPU-only MTP block replay up to the FFN's input (the post-attention
13398    /// norm, left in `ws.p1`), where the probe measures. The ordinary
13399    /// `mtp_step_hl` device path keeps these values resident and therefore
13400    /// cannot truthfully provide a per-neuron calibration statistic. The
13401    /// FFN arm itself is not run: its output feeds only this row's logits.
13402    fn mtp_probe_ffn_input(
13403        &mut self,
13404        mtp: &mut MtpModule,
13405        hidden: &[f32],
13406        next_token: u32,
13407        position: usize,
13408    ) -> Result<(), String> {
13409        let e = self.embed_single(next_token);
13410        let mut cat = vec![0.0f32; 2 * self.hidden_size];
13411        let (cat_e, cat_h) = cat.split_at_mut(self.hidden_size);
13412        inference::rms_norm_into(&e, &mtp.enorm, self.rms_eps, self.norm_style, cat_e);
13413        inference::rms_norm_into(
13414            hidden,
13415            &mtp.hnorm,
13416            self.rms_eps,
13417            self.norm_style,
13418            cat_h,
13419        );
13420        let mut x = vec![0.0f32; self.hidden_size];
13421        mtp.eh_proj.matvec(&cat, &mut x, self.pool.as_deref());
13422
13423        let lw = &mtp.layer;
13424        inference::rms_norm_into(
13425            &x,
13426            &lw.input_norm,
13427            self.rms_eps,
13428            self.norm_style,
13429            &mut self.ws.n1,
13430        );
13431        let attn = match &lw.attn {
13432            AttnKind::Full {
13433                wq,
13434                wk,
13435                wv,
13436                wo,
13437                q_norm,
13438                k_norm,
13439                output_gate,
13440                softplus_gate,
13441                bias,
13442            } => {
13443                let mut cfg = self.attn_cfg(position);
13444                cfg.q_norm = q_norm.as_deref();
13445                cfg.k_norm = k_norm.as_deref();
13446                cfg.output_gate = *output_gate;
13447                cfg.softplus_gate = softplus_gate
13448                    .as_ref()
13449                    .map(|(gate, per_head)| (gate, *per_head));
13450                cfg.bias = bias
13451                    .as_ref()
13452                    .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice()));
13453                attention::qwen_attention(&self.ws.n1, wq, wk, wv, wo, &mut mtp.kv, &cfg)
13454            }
13455            _ => return Err("MTP FFN probe: draft attention is not full attention".into()),
13456        };
13457        for (dst, src) in x.iter_mut().zip(attn) {
13458            *dst += src;
13459        }
13460        inference::rms_norm_into(
13461            &x,
13462            &lw.post_norm,
13463            self.rms_eps,
13464            self.norm_style,
13465            &mut self.ws.p1,
13466        );
13467        Ok(())
13468    }
13469
13470    /// DTG-MA calibration pass (Patent 2): run `ids` through the model
13471    /// (CPU path, per position) and return each layer's per-neuron
13472    /// activation mass Σ|silu(gate)·up| — the statistic the task-guided
13473    /// FFN mask is derived from.
13474    pub fn probe_ffn_mass(&mut self, ids: &[u32]) -> Vec<Vec<f64>> {
13475        self.clear_sequence_state();
13476        FFN_PROBE.with(|p| {
13477            *p.borrow_mut() = Some(vec![vec![0f64; self.intermediate_size]; self.num_layers]);
13478        });
13479        crate::gpu::cpu_scope(|| {
13480            for (pos, &id) in ids.iter().enumerate() {
13481                let emb = self.embed_single(id);
13482                let _ = self.forward_layers(&emb, pos, None);
13483            }
13484        });
13485        self.clear_sequence_state();
13486        FFN_PROBE
13487            .with(|p| p.borrow_mut().take())
13488            .unwrap_or_default()
13489    }
13490
13491    /// `probe_ffn_mass` over the BATCHED prefill: same accumulator, one
13492    /// sweep instead of one forward per token. What makes the statistic
13493    /// affordable on a 27B.
13494    pub fn probe_ffn_mass_batch(&mut self, ids: &[u32]) -> Result<Vec<Vec<f64>>, String> {
13495        if let Err(err) = self.nll_begin() {
13496            // A recorder can be left by a caller that was interrupted before
13497            // this request entered its scoring block.  Consume it even when
13498            // the preflight failure prevents initialization of a new one.
13499            let _ = FFN_PROBE.with(|p| p.borrow_mut().take());
13500            self.nll_end();
13501            return Err(err);
13502        }
13503        FFN_PROBE.with(|p| {
13504            *p.borrow_mut() = Some(vec![vec![0f64; self.intermediate_size]; self.num_layers]);
13505        });
13506        let result: Result<(), String> = (|| {
13507            for chunk in ids.chunks(256) {
13508                if chunk.len() < 2 {
13509                    continue;
13510                }
13511                self.nll_ids_masked(chunk, 0, None)?;
13512            }
13513            Ok(())
13514        })();
13515        self.nll_end();
13516        let probe = FFN_PROBE
13517            .with(|p| p.borrow_mut().take())
13518            .unwrap_or_default();
13519        match result {
13520            Ok(()) => Ok(probe),
13521            Err(err) => {
13522                drop(probe);
13523                Err(err)
13524            }
13525        }
13526    }
13527
13528    /// The FFN probe over one window of the layer-major batched walk
13529    /// (`calib_forward`): the statistic of `probe_ffn_mass`, the window's rows
13530    /// in one context, every projection a GEMM on the device where one is up.
13531    pub fn probe_ffn_mass_span(&mut self, ids: &[u32], chunk: usize) -> Result<Vec<Vec<f64>>, String> {
13532        FFN_PROBE.with(|p| {
13533            *p.borrow_mut() = Some(vec![vec![0f64; self.intermediate_size]; self.num_layers]);
13534        });
13535        let result = self.calib_forward(ids, self.num_layers, chunk);
13536        let probe = FFN_PROBE.with(|p| p.borrow_mut().take()).unwrap_or_default();
13537        result.map(|()| probe)
13538    }
13539
13540    /// The hot-neuron statistic of a MoE model's routed experts over `ids`:
13541    /// per layer `[expert · inter + neuron]` of Σ (w·act)², `w` the expert's
13542    /// final routing weight (a layer without experts gives an empty row).
13543    /// Qwen-3.5/3.8 MoE models only, on the host path: the caller runs with
13544    /// `CMF_GPU=0`, since the device frames and the fused expert kernels do
13545    /// not report activations.
13546    pub fn probe_moe_mass(&mut self, ids: &[u32]) -> Result<Vec<Vec<f64>>, String> {
13547        let Some(b) = self.qwen4_exp.as_mut() else {
13548            return Err("hot-probe --experts: not a Qwen MoE model (the probe reads the qwen4 host path)".into());
13549        };
13550        let geom: Vec<(usize, usize)> = b.1.iter().map(crate::qwen4_exp::Layer::expert_geometry).collect();
13551        let inter = geom.iter().map(|g| g.1).max().unwrap_or(0);
13552        if inter == 0 || ids.is_empty() {
13553            return Err("hot-probe --experts: the model has no routed experts".into());
13554        }
13555        MOE_PROBE.with(|p| {
13556            *p.borrow_mut() = Some(MoeProbe {
13557                acc: geom.iter().map(|&(ne, _)| vec![0f64; ne * inter]).collect(),
13558                inter,
13559                cur: None,
13560            });
13561        });
13562        b.3.reset();
13563        let mut pos = 0usize;
13564        while pos < ids.len() {
13565            let end = (pos + crate::qwen4_exp::prefill_chunk()).min(ids.len());
13566            let mut lg = Vec::new();
13567            crate::qwen4_exp::forward_tokens(&b.0, &b.1, &b.2, &mut b.3, &ids[pos..end], pos, &self.inv_freq, self.pool.as_deref(), &mut lg, false);
13568            pos = end;
13569        }
13570        b.3.reset();
13571        let probe = MOE_PROBE.with(|p| p.borrow_mut().take()).map_or_else(Vec::new, |p| p.acc);
13572        if !probe.iter().any(|r| r.iter().any(|&v| v > 0.0)) {
13573            return Err("hot-probe --experts: the statistic is all zero (a device path hid the experts from the probe; run with CMF_GPU=0)".into());
13574        }
13575        Ok(probe)
13576    }
13577
13578    /// Teacher-forced PPL with a task mask active (sparse execution) —
13579    /// the quality gate for a DTG-MA-masked skill. Sequential per
13580    /// position: the batched prefill path is dense-only.
13581    pub fn ppl_ids_masked(&mut self, ids: &[u32], mask: &TaskMask) -> Result<f64, String> {
13582        self.nll_begin()?;
13583        let result: Result<f64, String> = (|| {
13584            let mut nll = 0f64;
13585            let mut cnt = 0usize;
13586            let mut hidden = vec![0f32; self.hidden_size];
13587            for (pos, &id) in ids.iter().enumerate() {
13588                if pos > 0 {
13589                    inference::rms_norm_into(
13590                        &hidden,
13591                        &self.weights.final_norm,
13592                        self.rms_eps,
13593                        self.norm_style,
13594                        &mut self.ws.n1,
13595                    );
13596                    let mut logits = self.lm_head_forward(&self.ws.n1);
13597                    let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
13598                    let sum: f64 = logits.iter().map(|&v| ((v - max) as f64).exp()).sum();
13599                    let p = ((logits[id as usize] - max) as f64).exp() / sum.max(1e-300);
13600                    nll -= p.max(1e-300).ln();
13601                    cnt += 1;
13602                    attention::recycle_buf(&mut logits);
13603                }
13604                let emb = self.embed_single(id);
13605                hidden = self.forward_layers(&emb, pos, Some(mask));
13606                self.nll_check_graph("masked serial forward", pos)?;
13607                // Consume a possible graph logits side channel before the
13608                // next row.  Masked scoring normally disables that route,
13609                // but stale channel state must never survive a request.
13610                let _ = self.graph_logits.take();
13611            }
13612            Ok((nll / cnt.max(1) as f64).exp())
13613        })();
13614        self.nll_end();
13615        result
13616    }
13617
13618    /// Teacher-forced NLL sum + scored-token count over positions
13619    /// `start..len-1`, attention EXACT. Positions below `start` still
13620    /// run — they are the context — they are just not scored, so this
13621    /// pairs with `nll_ids_o1(ids, start)` over the very same tokens.
13622    ///
13623    /// Returning (nll, cnt) rather than a ppl is what lets a windowed
13624    /// caller combine windows before the exp, so every scored token
13625    /// weighs the same regardless of how the windows are cut.
13626    /// `nll_ids_from` with a task mask held active at every position.
13627    ///
13628    /// The batched prefill path does not thread masks, so this walks the
13629    /// per-position forward — slower, but it scores the file exactly the
13630    /// way `run --task` will serve it, which is the point of the gate
13631    /// that calls it. With `None` it defers to the fast path.
13632    /// Masked scoring rides the SAME batched sweep as unmasked scoring —
13633    /// the masked-inference fast path: `prefill_batch_masked` lands the
13634    /// per-visit FFN rows on the activations inside the fused arms. The
13635    /// per-position loop below remains only as the no-batch fallback.
13636    pub fn nll_ids_masked(
13637        &mut self,
13638        ids: &[u32],
13639        start: usize,
13640        task_mask: Option<&TaskMask>,
13641    ) -> Result<(f64, usize), String> {
13642        let task_mask = self.drop_open_mask(task_mask);
13643        self.nll_ids_inner(ids, start, task_mask)
13644    }
13645
13646    pub fn nll_ids_from(&mut self, ids: &[u32], start: usize) -> Result<(f64, usize), String> {
13647        self.nll_ids_inner(ids, start, None)
13648    }
13649
13650    /// Diagnostic (`CMF_PREFILL_PARITY=split[,k]` on `cortiq ppl`): the same
13651    /// tokens through three ingests, each from a clean sequence — H the host
13652    /// chunked prefill, G the wgpu batch graph in k-row chunks, M the host
13653    /// prefill up to `split` and the batch graph after it, seeded from the
13654    /// host state — and where they part: NLL and top-1 per 256-position bin
13655    /// from each arm's post-stack rows, every GDN layer's recurrent state
13656    /// (the host `linear_state` against the graph's) at `split` and at the
13657    /// end, and every exact-attention layer's K/V rows.
13658    pub fn prefill_parity_probe(
13659        &mut self,
13660        ids: &[u32],
13661        split: usize,
13662        bk: usize,
13663    ) -> Result<String, String> {
13664        use std::fmt::Write as _;
13665        let (n, hs) = (ids.len(), self.hidden_size);
13666        if split == 0 || split >= n || bk == 0 || !self.can_prefill_batched() {
13667            return Err(format!(
13668                "prefill parity: needs 0 < split < {n} tokens, k > 0 and a batched host prefill"
13669            ));
13670        }
13671        // 1 = GDN, 2 = exact attention, 0 = anything else (not compared).
13672        let kinds: Vec<u8> = (0..self.num_layers)
13673            .map(|li| match &self.weights.layers[self.phys_layer(li)].attn {
13674                AttnKind::LinearGdn(_) => 1,
13675                AttnKind::Full { .. } => 2,
13676                _ => 0,
13677            })
13678            .collect();
13679        let kv_id = self.graph_kv_id;
13680        let host_chunk = self.prefill_chunk().max(1);
13681        let host_states = |p: &Self| -> Vec<Vec<f32>> {
13682            (0..p.num_layers)
13683                .map(|li| {
13684                    if kinds[li] == 1 {
13685                        p.kv_cache.layers[li].linear_state.clone()
13686                    } else {
13687                        Vec::new()
13688                    }
13689                })
13690                .collect()
13691        };
13692        let graph_states = |_p: &Self| -> Vec<Vec<f32>> {
13693            (0..kinds.len())
13694                .map(|li| {
13695                    if kinds[li] == 1 {
13696                        crate::gpu::graph_gdn_state_read(kv_id, li).unwrap_or_default()
13697                    } else {
13698                        Vec::new()
13699                    }
13700                })
13701                .collect()
13702        };
13703        // Position-major K/V rows [0, n) of every exact-attention layer.
13704        let host_kv = |p: &Self| -> Vec<(Vec<f32>, Vec<f32>)> {
13705            (0..p.num_layers)
13706                .map(|li| {
13707                    let c = &p.kv_cache.layers[li];
13708                    if kinds[li] != 2
13709                        || c.mode != crate::kv_cache::KvMode::F32
13710                        || c.base() != 0
13711                        || c.seq_len != n
13712                    {
13713                        return (Vec::new(), Vec::new());
13714                    }
13715                    let (nkv, hd) = (c.num_kv_heads, c.head_dim);
13716                    let (mut k, mut v) = (vec![0f32; n * nkv * hd], vec![0f32; n * nkv * hd]);
13717                    for (h, (kh, vh)) in c.k_heads().iter().zip(c.v_heads()).enumerate() {
13718                        for pos in 0..n {
13719                            let d = (pos * nkv + h) * hd;
13720                            k[d..d + hd].copy_from_slice(&kh[pos * hd..(pos + 1) * hd]);
13721                            v[d..d + hd].copy_from_slice(&vh[pos * hd..(pos + 1) * hd]);
13722                        }
13723                    }
13724                    (k, v)
13725                })
13726                .collect()
13727        };
13728        let graph_kv = |p: &Self| -> Vec<(Vec<f32>, Vec<f32>)> {
13729            (0..p.num_layers)
13730                .map(|li| {
13731                    let c = &p.kv_cache.layers[li];
13732                    if kinds[li] != 2 {
13733                        return (Vec::new(), Vec::new());
13734                    }
13735                    crate::gpu::graph_kv_read_rows(kv_id, &[(li, 0, n)], c.num_kv_heads, c.head_dim)
13736                        .and_then(|mut v| v.pop())
13737                        .unwrap_or_default()
13738                })
13739                .collect()
13740        };
13741        let host_walk = |p: &mut Self,
13742                         from: usize,
13743                         to: usize,
13744                         rows: &mut [f32],
13745                         at_split: &mut Option<Vec<Vec<f32>>>| {
13746            let mut pos = from;
13747            while pos < to {
13748                let mut end = (pos + host_chunk).min(to);
13749                if pos < split && end > split {
13750                    end = split;
13751                }
13752                let hb = p.prefill_batch(&ids[pos..end], pos);
13753                rows[pos * hs..end * hs].copy_from_slice(&hb[..(end - pos) * hs]);
13754                pos = end;
13755                if pos == split {
13756                    *at_split = Some(host_states(p));
13757                }
13758            }
13759        };
13760        let graph_walk = |p: &mut Self,
13761                          from: usize,
13762                          to: usize,
13763                          rows: &mut [f32],
13764                          at_split: &mut Option<Vec<Vec<f32>>>|
13765         -> Result<(), String> {
13766            let mut pos = from;
13767            while pos < to {
13768                let mut end = (pos + bk).min(to);
13769                if pos < split && end > split {
13770                    end = split;
13771                }
13772                let k = end - pos;
13773                let mut hid = vec![0f32; k * hs];
13774                for (j, &id) in ids[pos..end].iter().enumerate() {
13775                    hid[j * hs..(j + 1) * hs].copy_from_slice(&p.embed_single(id));
13776                }
13777                let positions: Vec<usize> = (pos..end).collect();
13778                let outcome = p.try_batch_graph_wgpu(&mut hid, &positions, k, None);
13779                if outcome != crate::gpu::BatchGraphOutcome::Completed {
13780                    return Err(format!(
13781                        "prefill parity: batch graph {outcome:?} at position {pos}"
13782                    ));
13783                }
13784                rows[pos * hs..end * hs].copy_from_slice(&hid);
13785                pos = end;
13786                if pos == split {
13787                    *at_split = Some(graph_states(p));
13788                }
13789            }
13790            Ok(())
13791        };
13792        let score = |p: &Self, rows: &[f32], from: usize| p.parity_score(ids, rows, from);
13793
13794        let t = std::time::Instant::now();
13795        self.clear_sequence_state();
13796        let (mut hh, mut h_split) = (vec![0f32; n * hs], None);
13797        host_walk(self, 0, n, &mut hh, &mut h_split);
13798        let (h_end, h_kv) = (host_states(self), host_kv(self));
13799        let t_h = t.elapsed().as_secs_f64();
13800
13801        let t = std::time::Instant::now();
13802        self.clear_sequence_state();
13803        let (mut hg, mut g_split) = (vec![0f32; n * hs], None);
13804        let g_run = graph_walk(self, 0, n, &mut hg, &mut g_split);
13805        let (g_end, g_kv) = (graph_states(self), graph_kv(self));
13806        let t_g = t.elapsed().as_secs_f64();
13807
13808        let t = std::time::Instant::now();
13809        self.clear_sequence_state();
13810        let (mut hm, mut m_split) = (vec![0f32; n * hs], None);
13811        host_walk(self, 0, split, &mut hm, &mut m_split);
13812        let m_run = graph_walk(self, split, n, &mut hm, &mut None);
13813        let (m_end, m_kv) = (graph_states(self), graph_kv(self));
13814        let t_m = t.elapsed().as_secs_f64();
13815        self.clear_sequence_state();
13816        g_run?;
13817        m_run?;
13818
13819        let (sh, sg, sm) = (
13820            score(self, &hh, 0),
13821            score(self, &hg, 0),
13822            score(self, &hm, split),
13823        );
13824        let mut r = String::new();
13825        let _ = writeln!(
13826            r,
13827            "prefill parity: {n} tokens, split {split}, host chunk {host_chunk}, graph k {bk} \
13828             (host {t_h:.1} s, graph {t_g:.1} s, host+graph {t_m:.1} s)"
13829        );
13830        let _ = writeln!(
13831            r,
13832            "  bin          | NLL host  graph  h+g   | top1 host=graph h+g=graph | hidden rel host:graph h+g:graph"
13833        );
13834        let bin = 256usize;
13835        let mut b0 = 0;
13836        while b0 + 1 < n {
13837            let b1 = (b0 + bin).min(n - 1);
13838            let mean = |s: &[(f64, usize)], off: usize| -> Option<f64> {
13839                let v: Vec<f64> = (b0.max(off)..b1).map(|p| s[p - off].0).collect();
13840                (!v.is_empty()).then(|| v.iter().sum::<f64>() / v.len() as f64)
13841            };
13842            let agree = |a: &[(f64, usize)], ao: usize, b: &[(f64, usize)], bo: usize| {
13843                let ps: Vec<usize> = (b0.max(ao).max(bo)..b1).collect();
13844                if ps.is_empty() {
13845                    return None;
13846                }
13847                let same = ps.iter().filter(|&&p| a[p - ao].1 == b[p - bo].1).count();
13848                Some(100.0 * same as f64 / ps.len() as f64)
13849            };
13850            let hid_rel = |a: &[f32], from: usize| -> Option<f64> {
13851                (b0.max(from)..b1)
13852                    .map(|p| rel_l2(&a[p * hs..(p + 1) * hs], &hg[p * hs..(p + 1) * hs]))
13853                    .reduce(f64::max)
13854            };
13855            let f =
13856                |v: Option<f64>, prec: usize| v.map_or("-".to_string(), |x| format!("{x:.prec$}"));
13857            let e = |v: Option<f64>| v.map_or("-".to_string(), |x| format!("{x:.1e}"));
13858            let _ = writeln!(
13859                r,
13860                "  {b0:5}..{b1:<5} | {:>8} {:>6} {:>6} | {:>14} {:>9} | {:>16} {:>9}",
13861                f(mean(&sh, 0), 3),
13862                f(mean(&sg, 0), 3),
13863                f(mean(&sm, split), 3),
13864                f(agree(&sh, 0, &sg, 0), 1),
13865                f(agree(&sm, split, &sg, 0), 1),
13866                e(hid_rel(&hh, 0)),
13867                e(hid_rel(&hm, split)),
13868            );
13869            b0 = b1;
13870        }
13871        // Recurrent state, layer by layer: [conv ring | S] split at the ring.
13872        let ring_len = self
13873            .gdn_cfg
13874            .map(|c| c.conv_dim() * c.conv_kernel.saturating_sub(1))
13875            .unwrap_or(0);
13876        let state_line = |r: &mut String, label: &str, a: &[Vec<f32>], b: &[Vec<f32>]| {
13877            let _ = write!(r, "  GDN {label} (ring/S rel):");
13878            let mut first = None;
13879            for li in (0..kinds.len()).filter(|&li| kinds[li] == 1) {
13880                let (x, y) = (&a[li], &b[li]);
13881                if x.len() != y.len() || x.len() <= ring_len {
13882                    let _ = write!(r, " L{li} len {}/{}", x.len(), y.len());
13883                    continue;
13884                }
13885                let (rr, rs) = (
13886                    rel_l2(&x[..ring_len], &y[..ring_len]),
13887                    rel_l2(&x[ring_len..], &y[ring_len..]),
13888                );
13889                if first.is_none() && rr.max(rs) > 1e-2 {
13890                    first = Some(li);
13891                }
13892                let _ = write!(r, " L{li} {rr:.0e}/{rs:.0e}");
13893            }
13894            let _ = writeln!(
13895                r,
13896                "\n    first GDN layer past 1e-2: {}",
13897                first.map_or("none".to_string(), |l| l.to_string())
13898            );
13899        };
13900        match (&h_split, &g_split) {
13901            (Some(a), Some(b)) => state_line(&mut r, "host vs graph at split", a, b),
13902            _ => {
13903                let _ = writeln!(r, "  GDN at split: not captured");
13904            }
13905        }
13906        if let (Some(a), Some(b)) = (&m_split, &h_split) {
13907            state_line(&mut r, "h+g host part vs host at split", a, b);
13908        }
13909        state_line(&mut r, "host vs graph at end", &h_end, &g_end);
13910        state_line(&mut r, "h+g vs graph at end", &m_end, &g_end);
13911        // Exact-attention K/V: the worst 256-row bin per layer and the first
13912        // bin past 1e-2.
13913        let kv_line = |r: &mut String, label: &str, a: &[(Vec<f32>, Vec<f32>)], from: usize| {
13914            let _ = writeln!(r, "  K/V {label} (worst bin K/V rel, first bin past 1e-2):");
13915            for li in (0..kinds.len()).filter(|&li| kinds[li] == 2) {
13916                let ((ak, av), (gk, gv)) = (&a[li], &g_kv[li]);
13917                if ak.len() != gk.len() || ak.is_empty() {
13918                    let _ = writeln!(r, "    L{li}: rows {}/{}", ak.len(), gk.len());
13919                    continue;
13920                }
13921                let row = ak.len() / n;
13922                let (mut wk, mut wv, mut first) = (0f64, 0f64, None);
13923                let mut b0 = from;
13924                while b0 < n {
13925                    let b1 = (b0 + bin).min(n);
13926                    let (s0, s1) = (b0 * row, b1 * row);
13927                    let (rk, rv) = (
13928                        rel_l2(&ak[s0..s1], &gk[s0..s1]),
13929                        rel_l2(&av[s0..s1], &gv[s0..s1]),
13930                    );
13931                    (wk, wv) = (wk.max(rk), wv.max(rv));
13932                    if first.is_none() && rk.max(rv) > 1e-2 {
13933                        first = Some(b0);
13934                    }
13935                    b0 = b1;
13936                }
13937                let _ = writeln!(
13938                    r,
13939                    "    L{li}: {wk:.1e}/{wv:.1e} first {}",
13940                    first.map_or("none".to_string(), |p| p.to_string())
13941                );
13942            }
13943        };
13944        kv_line(&mut r, "host vs graph", &h_kv, 0);
13945        kv_line(&mut r, "h+g vs graph", &m_kv, 0);
13946        Ok(r)
13947    }
13948
13949    /// (nll, top-1 id) of every position in [from, len − 1) from post-stack
13950    /// rows (`rows` indexed by absolute position), through the scorer's
13951    /// final norm and head.
13952    fn parity_score(&self, ids: &[u32], rows: &[f32], from: usize) -> Vec<(f64, usize)> {
13953        let (n, hs) = (ids.len(), self.hidden_size);
13954        let vrows = self.weights.lm_head.rows();
13955        let vs = self.vocab_size.min(vrows);
13956        let mut out = Vec::with_capacity(n.saturating_sub(from + 1));
13957        let mut pos = from;
13958        while pos + 1 < n {
13959            let end = (pos + 32).min(n - 1);
13960            let sb = end - pos;
13961            let mut normed = vec![0f32; sb * hs];
13962            for j in 0..sb {
13963                let r = inference::rms_norm(
13964                    &rows[(pos + j) * hs..(pos + j + 1) * hs],
13965                    &self.weights.final_norm,
13966                    self.rms_eps,
13967                    self.norm_style,
13968                );
13969                normed[j * hs..(j + 1) * hs].copy_from_slice(&r);
13970            }
13971            let mut logits = vec![0f32; sb * vrows];
13972            self.weights
13973                .lm_head
13974                .matmat(&normed, sb, &mut logits, self.pool.as_deref());
13975            for j in 0..sb {
13976                let lg = &mut logits[j * vrows..j * vrows + vs];
13977                if let Some(mu) = self.logit_multiplier {
13978                    lg.iter_mut().for_each(|v| *v *= mu);
13979                }
13980                if let Some(c) = self.final_softcap {
13981                    softcap_in_place(lg, c, self.pool.as_deref());
13982                }
13983                let (mut max, mut top) = (f32::NEG_INFINITY, 0usize);
13984                for (i, &v) in lg.iter().enumerate() {
13985                    if v > max {
13986                        (max, top) = (v, i);
13987                    }
13988                }
13989                let lse = lg
13990                    .iter()
13991                    .map(|&v| ((v - max) as f64).exp())
13992                    .sum::<f64>()
13993                    .ln()
13994                    + max as f64;
13995                out.push((lse - lg[ids[pos + j + 1] as usize] as f64, top));
13996            }
13997            pos = end;
13998        }
13999        out
14000    }
14001
14002    /// Diagnostic (`CMF_PREFILL_PARITY_O1=k` on `cortiq ppl --o1 …
14003    /// --o1-prefill P`): how much the O(1) seal depends on where its exact
14004    /// prefix ran. Every arm continues on the batch graph from the boundary
14005    /// in k-row chunks:
14006    /// - OH: prefix on the host chunked prefill; seal from the host's
14007    ///   queries and K/V; recurrent state seeded from the host.
14008    /// - OG: prefix on the batch graph (recurrent state stays on the
14009    ///   device); seal from OH's host queries and host K/V.
14010    /// - OD: prefix on the batch graph; seal from OH's queries and the
14011    ///   graph's own K/V rows (read back).
14012    ///
14013    /// OH vs OG isolates the recurrent-state hand-off, OG vs OD the seal's
14014    /// response to the host/graph K/V difference. X is the exact graph.
14015    pub fn o1_seal_parity_probe(
14016        &mut self,
14017        ids: &[u32],
14018        cfg: crate::nystrom::O1Cfg,
14019        requested: usize,
14020        bk: usize,
14021    ) -> Result<String, String> {
14022        use std::fmt::Write as _;
14023        let (n, hs) = (ids.len(), self.hidden_size);
14024        self.set_o1(Some(cfg));
14025        let split = self
14026            .o1_effective_boundary(requested)
14027            .ok_or("o1 parity: no O(1) configuration")?;
14028        if split + 1 >= n || bk == 0 || !self.can_prefill_batched() {
14029            return Err(format!(
14030                "o1 parity: needs the boundary {split} inside {n} tokens, k > 0 and a batched host prefill"
14031            ));
14032        }
14033        let o1_layers: Vec<usize> = (0..self.num_layers)
14034            .filter(|&li| self.o1_flags.get(li).copied().unwrap_or(false))
14035            .collect();
14036        let graph_rows = |p: &mut Self, from: usize, to: usize, rows: &mut [f32]| {
14037            let mut pos = from;
14038            while pos < to {
14039                let end = (pos + bk).min(to);
14040                let k = end - pos;
14041                let mut hid = vec![0f32; k * hs];
14042                for (j, &id) in ids[pos..end].iter().enumerate() {
14043                    hid[j * hs..(j + 1) * hs].copy_from_slice(&p.embed_single(id));
14044                }
14045                let positions: Vec<usize> = (pos..end).collect();
14046                let outcome = p.try_batch_graph_wgpu(&mut hid, &positions, k, None);
14047                if outcome != crate::gpu::BatchGraphOutcome::Completed {
14048                    return Err(format!(
14049                        "o1 parity: batch graph {outcome:?} at position {pos}"
14050                    ));
14051                }
14052                rows[pos * hs..end * hs].copy_from_slice(&hid);
14053                pos = end;
14054            }
14055            Ok(())
14056        };
14057        // Seal every O(1) layer from the given rows; `trace` = (q, k, v) per
14058        // O(1) layer, position-major.
14059        let seal_from = |p: &mut Self, trace: &[(Vec<f32>, Vec<f32>, Vec<f32>)]| {
14060            for (&li, (q, k, v)) in o1_layers.iter().zip(trace) {
14061                let c = &mut p.kv_cache.layers[li];
14062                let (row, qrow) = (k.len() / split, q.len() / split);
14063                for pos in 0..split {
14064                    c.append(
14065                        &k[pos * row..(pos + 1) * row],
14066                        &v[pos * row..(pos + 1) * row],
14067                        &[],
14068                    );
14069                    c.o1_push_q(&q[pos * qrow..(pos + 1) * qrow]);
14070                }
14071            }
14072            p.o1_seal_checked()
14073        };
14074        // Greedy continuation (`CMF_PARITY_GREEDY` tokens, default 40) from
14075        // the last prompt row, one batch-graph row per step.
14076        let steps: usize = std::env::var("CMF_PARITY_GREEDY")
14077            .ok()
14078            .and_then(|v| v.parse().ok())
14079            .unwrap_or(40);
14080        // `CMF_PARITY_DECODE=token`: the steps through `decode_step_logits`
14081        // (the token graph generation decodes on) instead of the batch graph.
14082        let token_decode = std::env::var("CMF_PARITY_DECODE").as_deref() == Ok("token");
14083        let greedy = |p: &mut Self, rows: &[f32]| -> Result<Vec<u32>, String> {
14084            let argmax = |lg: &[f32], vs: usize| {
14085                (0..vs.min(lg.len())).fold(0, |b, i| if lg[i] > lg[b] { i } else { b }) as u32
14086            };
14087            let normed = inference::rms_norm(
14088                &rows[(n - 1) * hs..n * hs],
14089                &p.weights.final_norm,
14090                p.rms_eps,
14091                p.norm_style,
14092            );
14093            let mut out = vec![argmax(&p.lm_head_forward(&normed), p.vocab_size)];
14094            for s in 1..steps {
14095                let (tok, at) = (out[s - 1], n + s - 1);
14096                let lg = if token_decode {
14097                    p.decode_step_logits(tok, at)
14098                } else {
14099                    let mut hid = p.embed_single(tok);
14100                    let outcome = p.try_batch_graph_wgpu(&mut hid, &[at], 1, None);
14101                    if outcome != crate::gpu::BatchGraphOutcome::Completed {
14102                        return Err(format!("o1 parity: greedy step {s} {outcome:?}"));
14103                    }
14104                    let normed =
14105                        inference::rms_norm(&hid, &p.weights.final_norm, p.rms_eps, p.norm_style);
14106                    p.lm_head_forward(&normed)
14107                };
14108                out.push(argmax(&lg, p.vocab_size));
14109            }
14110            Ok(out)
14111        };
14112
14113        // OW first, in a fresh process as `run` starts: the host prefix
14114        // exactly as generation runs it — boundary at `split`, the
14115        // pipeline's prefill chunk, the layers sealing after the chunk that
14116        // reaches the boundary (`CMF_O1_WALK_BOUNDARY=1`: that chunk walks
14117        // its rows one at a time, each layer sealing after the boundary row).
14118        self.clear_sequence_state();
14119        self.o1_begin_with_prefix(Some(requested));
14120        let walk_chunk = self.prefill_chunk().max(1);
14121        let walk_from = (split - 1) / walk_chunk * walk_chunk;
14122        let mut ow = vec![0f32; n * hs];
14123        let mut pos = 0;
14124        while pos < split {
14125            let end = (pos + walk_chunk).min(split);
14126            let hb = self.prefill_batch(&ids[pos..end], pos);
14127            ow[pos * hs..end * hs].copy_from_slice(&hb[..(end - pos) * hs]);
14128            pos = end;
14129        }
14130        self.o1_seal_checked()?;
14131        let ow_run = graph_rows(self, split, n, &mut ow);
14132        let ow_text = ow_run.clone().and_then(|_| greedy(self, &ow));
14133
14134        // OH. Collect one row past the boundary's natural barrier so the
14135        // host walk does not seal inside the last chunk, copy the trace,
14136        // then seal at `split` exactly.
14137        let t = std::time::Instant::now();
14138        self.clear_sequence_state();
14139        self.o1_begin_with_prefix(Some(split + 1));
14140        let mut oh = vec![0f32; n * hs];
14141        let mut pos = 0;
14142        while pos < split {
14143            let end = (pos + 128).min(split);
14144            let hb = self.prefill_batch(&ids[pos..end], pos);
14145            oh[pos * hs..end * hs].copy_from_slice(&hb[..(end - pos) * hs]);
14146            pos = end;
14147        }
14148        let mut host = Vec::with_capacity(o1_layers.len());
14149        for &li in &o1_layers {
14150            let c = &self.kv_cache.layers[li];
14151            let q = c
14152                .o1_q_trace()
14153                .ok_or("o1 parity: host walk sealed early")?
14154                .to_vec();
14155            let (nkv, hd) = (c.num_kv_heads, c.head_dim);
14156            let (mut k, mut v) = (vec![0f32; split * nkv * hd], vec![0f32; split * nkv * hd]);
14157            for (h, (kh, vh)) in c.k_heads().iter().zip(c.v_heads()).enumerate() {
14158                for p in 0..split {
14159                    let d = (p * nkv + h) * hd;
14160                    k[d..d + hd].copy_from_slice(&kh[p * hd..(p + 1) * hd]);
14161                    v[d..d + hd].copy_from_slice(&vh[p * hd..(p + 1) * hd]);
14162                }
14163            }
14164            host.push((q, k, v));
14165        }
14166        for &li in &o1_layers {
14167            self.kv_cache.layers[li].o1_set_boundary(split);
14168        }
14169        self.o1_seal_checked()?;
14170        let oh_run = graph_rows(self, split, n, &mut oh);
14171        let t_oh = t.elapsed().as_secs_f64();
14172        let oh_text = oh_run.clone().and_then(|_| greedy(self, &oh));
14173
14174        // OG: graph prefix, host seal inputs. `CMF_PARITY_PERTURB=eps`
14175        // scales every host K/V value by (1 ± eps), signs from a fixed
14176        // xorshift stream: the seal's sensitivity to rounding-size noise.
14177        self.clear_sequence_state();
14178        self.o1_begin_with_prefix(Some(requested));
14179        let mut og = vec![0f32; n * hs];
14180        graph_rows(self, 0, split, &mut og)?;
14181        let perturb: f32 = std::env::var("CMF_PARITY_PERTURB")
14182            .ok()
14183            .and_then(|v| v.parse().ok())
14184            .unwrap_or(0.0);
14185        if perturb > 0.0 {
14186            let mut seed = 0x9e37_79b9_7f4a_7c15u64;
14187            let noisy: Vec<_> = host
14188                .iter()
14189                .map(|(q, k, v)| {
14190                    let mut jitter = |x: &f32| {
14191                        seed ^= seed << 13;
14192                        seed ^= seed >> 7;
14193                        seed ^= seed << 17;
14194                        x * if seed & 1 == 0 {
14195                            1.0 + perturb
14196                        } else {
14197                            1.0 - perturb
14198                        }
14199                    };
14200                    let k: Vec<f32> = k.iter().map(&mut jitter).collect();
14201                    let v: Vec<f32> = v.iter().map(&mut jitter).collect();
14202                    (q.clone(), k, v)
14203                })
14204                .collect();
14205            seal_from(self, &noisy)?;
14206        } else {
14207            seal_from(self, &host)?;
14208        }
14209        let og_run = graph_rows(self, split, n, &mut og);
14210        let og_text = og_run.clone().and_then(|_| greedy(self, &og));
14211
14212        // OD: graph prefix, the graph's own K/V with the host queries.
14213        self.clear_sequence_state();
14214        self.o1_begin_with_prefix(Some(requested));
14215        let mut od = vec![0f32; n * hs];
14216        graph_rows(self, 0, split, &mut od)?;
14217        let mut dev = Vec::with_capacity(o1_layers.len());
14218        let mut kv_rel = Vec::with_capacity(o1_layers.len());
14219        for (&li, (q, hk, hv)) in o1_layers.iter().zip(&host) {
14220            let c = &self.kv_cache.layers[li];
14221            let (k, v) = crate::gpu::graph_kv_read_rows(
14222                self.graph_kv_id,
14223                &[(li, 0, split)],
14224                c.num_kv_heads,
14225                c.head_dim,
14226            )
14227            .and_then(|mut rows| rows.pop())
14228            .ok_or_else(|| format!("o1 parity: no graph K/V rows for layer {li}"))?;
14229            kv_rel.push((li, rel_l2(hk, &k), rel_l2(hv, &v)));
14230            dev.push((q.clone(), k, v));
14231        }
14232        seal_from(self, &dev)?;
14233        let od_run = graph_rows(self, split, n, &mut od);
14234        let od_text = od_run.clone().and_then(|_| greedy(self, &od));
14235
14236        // X: exact batch graph.
14237        self.clear_sequence_state();
14238        self.set_o1(None);
14239        let mut xx = vec![0f32; n * hs];
14240        let x_run = graph_rows(self, 0, n, &mut xx);
14241        let x_text = x_run.clone().and_then(|_| greedy(self, &xx));
14242        self.clear_sequence_state();
14243        oh_run?;
14244        ow_run?;
14245        og_run?;
14246        od_run?;
14247        x_run?;
14248
14249        let sx = self.parity_score(ids, &xx, split);
14250        let arms = [
14251            ("OH", self.parity_score(ids, &oh, split)),
14252            ("OG", self.parity_score(ids, &og, split)),
14253            ("OD", self.parity_score(ids, &od, split)),
14254            ("OW", self.parity_score(ids, &ow, split)),
14255        ];
14256        let mut r = String::new();
14257        let _ = writeln!(
14258            r,
14259            "o1 seal parity: {n} tokens, boundary {split}, graph k {bk} (OH {t_oh:.1} s), \
14260             OW chunk {walk_chunk}, boundary chunk {walk_from}..{split}"
14261        );
14262        let _ = write!(r, "  seal K/V rel host vs graph:");
14263        for (li, rk, rv) in &kv_rel {
14264            let _ = write!(r, " L{li} {rk:.0e}/{rv:.0e}");
14265        }
14266        // Post-stack prefix rows against the exact graph: the batched rows,
14267        // then the rows OW walks one at a time.
14268        let worst = |a: &[f32], p0: usize, p1: usize| {
14269            (p0..p1)
14270                .map(|p| rel_l2(&a[p * hs..(p + 1) * hs], &xx[p * hs..(p + 1) * hs]))
14271                .fold(0f64, f64::max)
14272        };
14273        let _ = writeln!(
14274            r,
14275            "\n  prefix rows rel vs exact graph, [0,{walk_from}) / [{walk_from},{split}): \
14276             OH {:.1e} / {:.1e}, OW {:.1e} / {:.1e}",
14277            worst(&oh, 0, walk_from),
14278            worst(&oh, walk_from, split),
14279            worst(&ow, 0, walk_from),
14280            worst(&ow, walk_from, split),
14281        );
14282        let _ = writeln!(
14283            r,
14284            "  bin          | NLL exact    OH     OG     OD     OW | top1=exact  OH    OG    OD    OW"
14285        );
14286        let mean = |s: &[(f64, usize)], b0: usize, b1: usize| {
14287            (b0..b1).map(|p| s[p - split].0).sum::<f64>() / (b1 - b0).max(1) as f64
14288        };
14289        let agree = |s: &[(f64, usize)], b0: usize, b1: usize| {
14290            let same = (b0..b1)
14291                .filter(|&p| s[p - split].1 == sx[p - split].1)
14292                .count();
14293            100.0 * same as f64 / (b1 - b0).max(1) as f64
14294        };
14295        let mut b0 = split;
14296        let mut total = [0f64; 5];
14297        while b0 + 1 < n {
14298            let b1 = ((b0 / 256 + 1) * 256).min(n - 1);
14299            let _ = writeln!(
14300                r,
14301                "  {b0:5}..{b1:<5} | {:>9.3} {:>6.3} {:>6.3} {:>6.3} {:>6.3} | {:>12.1} {:>5.1} {:>5.1} {:>5.1}",
14302                mean(&sx, b0, b1),
14303                mean(&arms[0].1, b0, b1),
14304                mean(&arms[1].1, b0, b1),
14305                mean(&arms[2].1, b0, b1),
14306                mean(&arms[3].1, b0, b1),
14307                agree(&arms[0].1, b0, b1),
14308                agree(&arms[1].1, b0, b1),
14309                agree(&arms[2].1, b0, b1),
14310                agree(&arms[3].1, b0, b1),
14311            );
14312            b0 = b1;
14313        }
14314        for (i, s) in std::iter::once(&sx)
14315            .chain(arms.iter().map(|a| &a.1))
14316            .enumerate()
14317        {
14318            total[i] = s.iter().map(|x| x.0).sum::<f64>() / s.len().max(1) as f64;
14319        }
14320        let _ = writeln!(
14321            r,
14322            "  all          | {:>9.3} {:>6.3} {:>6.3} {:>6.3} {:>6.3} | ppl ratio vs exact OH ×{:.3} OG ×{:.3} OD ×{:.3} OW ×{:.3}",
14323            total[0],
14324            total[1],
14325            total[2],
14326            total[3],
14327            total[4],
14328            (total[1] - total[0]).exp(),
14329            (total[2] - total[0]).exp(),
14330            (total[3] - total[0]).exp(),
14331            (total[4] - total[0]).exp(),
14332        );
14333        for (name, text) in [
14334            ("X ", x_text),
14335            ("OH", oh_text),
14336            ("OG", og_text),
14337            ("OD", od_text),
14338            ("OW", ow_text),
14339        ] {
14340            let s = text.map_or_else(|e| e, |t| self.tokenizer.decode(&t));
14341            let _ = writeln!(r, "  greedy {name}: {:?}", s);
14342        }
14343        Ok(r)
14344    }
14345
14346    /// The positions of `input_ids` a Dory sequence already holds: the common
14347    /// prefix, unless going back to it passes what a sliding ring still keeps.
14348    fn dory_cached_prefix(&self, input_ids: &[u32]) -> usize {
14349        if std::env::var("CMF_KV_REUSE").is_ok_and(|v| v == "0") {
14350            return 0;
14351        }
14352        let h = &self.kv_history;
14353        let lcp = h.iter().zip(input_ids).take_while(|(a, b)| a == b).count();
14354        let n = lcp.min(input_ids.len().saturating_sub(1));
14355        if n == 0 || h.len() - n > crate::dory::REWIND {
14356            return 0;
14357        }
14358        // Rows past the prefix have gone through the far field: a sealed sequence can
14359        // only be extended, and a turn that goes back starts over.
14360        let sealed = crate::gpu::dory_sealed(self.graph_kv_id)
14361            || self.dory.as_ref().is_some_and(|b| b.1.slots.iter().flatten().any(|s| !s.far.is_empty()));
14362        if n < h.len() && sealed {
14363            return 0;
14364        }
14365        n
14366    }
14367
14368    /// Dory's score: chunks through its own stack, logits of every row.
14369    fn dory_nll(&mut self, ids: &[u32], start: usize) -> Result<(f64, usize), String> {
14370        self.clear_sequence_state();
14371        let chunk: usize = std::env::var("CMF_NLL_CHUNK")
14372            .ok()
14373            .and_then(|v| v.parse().ok())
14374            .filter(|&c: &usize| c > 0)
14375            .unwrap_or(128);
14376        let vocab = self.vocab_size;
14377        let n = ids.len().saturating_sub(1);
14378        // `CMF_NLL_SKIP`: a prompt of so many rows goes in as a prompt does.
14379        let skip: usize = std::env::var("CMF_NLL_SKIP").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
14380        let start = start.max(skip.min(n));
14381        let (mut nll, mut cnt, mut pos) = (0f64, 0usize, 0usize);
14382        while pos < n {
14383            if pos < skip {
14384                let end = (pos + 64).min(skip).min(n);
14385                self.dory_forward(&ids[pos..end], pos, crate::dory::Want::None);
14386                pos = end;
14387                continue;
14388            }
14389            let end = (pos + chunk).min(n);
14390            let lg = self.dory_forward(&ids[pos..end], pos, crate::dory::Want::All);
14391            for (r, row) in lg.chunks_exact(vocab).enumerate() {
14392                if pos + r < start {
14393                    continue;
14394                }
14395                let target = ids[pos + r + 1] as usize;
14396                let best = row.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b)) as f64;
14397                let den: f64 = row.iter().map(|&x| ((x as f64) - best).exp()).sum();
14398                nll += den.ln() - (row[target] as f64 - best);
14399                cnt += 1;
14400            }
14401            pos = end;
14402        }
14403        Ok((nll, cnt))
14404    }
14405
14406    /// Dory's forward over a chunk: the device path when it takes the file.
14407    fn dory_forward(&mut self, ids: &[u32], pos: usize, want: crate::dory::Want) -> Vec<f32> {
14408        let pool = self.pool.clone();
14409        let id = self.graph_kv_id;
14410        let b = self.dory.as_mut().expect("a Dory file");
14411        let (m, st) = (&b.0, &mut b.1);
14412        let mut logits = Vec::new();
14413        let loops = m.cfg.loops;
14414        // GPTQ's Hessian hook sees a matrix's input only on the host stack.
14415        let host = crate::gptq_capture::capturing();
14416        let file = m.file.clone();
14417        if host || !crate::gpu::dory_forward(id, file.as_ref(), m, ids, pos, loops, want, &mut logits) {
14418            logits.clear();
14419            crate::dory::forward_host(m, st, ids, pos, loops, want, pool.as_deref(), None, &mut logits);
14420        }
14421        if m.o1.is_some() && std::env::var_os("CMF_DORY_KV_REPORT").is_some() {
14422            let (e, f) = crate::dory::host_kv_bytes(st);
14423            eprintln!("dory kv at {}: exact {:.1} MB, far {:.1} MB", pos + ids.len(), e as f64 / 1e6, f as f64 / 1e6);
14424        }
14425        if let Ok(dir) = std::env::var("CMF_DORY_DUMP") {
14426            let bytes: Vec<u8> = logits.iter().flat_map(|v| v.to_le_bytes()).collect();
14427            let _ = std::fs::write(format!("{dir}/{pos}.bin"), bytes);
14428        }
14429        logits
14430    }
14431
14432    fn nll_ids_inner(
14433        &mut self,
14434        ids: &[u32],
14435        start: usize,
14436        task_mask: Option<&TaskMask>,
14437    ) -> Result<(f64, usize), String> {
14438        if self.dory.is_some() && task_mask.is_none() {
14439            return self.dory_nll(ids, start);
14440        }
14441        // Hy4-flash: the window on the card's prompt graph, the head on the host
14442        if task_mask.is_none()
14443            && let Some(b) = &mut self.hy4
14444            && let Some(r) = crate::hy4::nll(&b.0, &b.1, &b.2, &mut b.3, ids, start, self.pool.as_deref())
14445        {
14446            return Ok(r);
14447        }
14448        // Maxwell-V1-Flash: the same, through its own stack
14449        if task_mask.is_none()
14450            && let Some(b) = &mut self.maxwell
14451            && let Some(r) = crate::maxwell::nll(&b.0, &b.1, &b.2, &mut b.3, ids, start, self.pool.as_deref())
14452        {
14453            return Ok(r);
14454        }
14455        // Inkling-2-Mini: the same, through its own stack
14456        if task_mask.is_none()
14457            && let Some(b) = &mut self.inkling
14458            && let Some(r) = crate::inkling::nll(&b.0, &b.1, &b.2, &mut b.3, ids, start, self.pool.as_deref())
14459        {
14460            return Ok(r);
14461        }
14462        self.nll_begin()?;
14463        // Block diffusion on Apple silicon: the Metal executor's causal path.
14464        #[cfg(target_os = "macos")]
14465        if task_mask.is_none() && self.is_block_diffusion() {
14466            if let Some(r) = self.clover_metal_nll(ids, start) {
14467                self.nll_end();
14468                return r;
14469            }
14470        }
14471        let result: Result<(f64, usize), String> = (|| {
14472            let mut nll = 0f64;
14473            let mut cnt = 0usize;
14474            // An unmasked quality run with the resident wgpu graph must score
14475            // the same stateful path used by generation.  The layer-major
14476            // GEMM prefill below is a valid CPU/GEMM oracle, but it seeds
14477            // neither the graph's device GDN state nor its device KV mirrors;
14478            // using it here would silently score a different execution.  Keep
14479            // masked scoring on the exact per-position path as before, and
14480            // let the serial arm below drive the graph-aware scorer.
14481            // Only native Metal has a fused graph lm_head contract.  Vulkan
14482            // and other graph backends may expose hidden state without the
14483            // optional logits side channel; preserve their established CPU
14484            // norm/head fallback instead of turning that valid route into a
14485            // hard missing-logits error.
14486            let (graph_quality, fused_head_quality) = nll_graph_policy(
14487                task_mask.is_none(),
14488                self.graph_prefill_preferred(),
14489                crate::gpu::q1_force(),
14490            );
14491            self.graph_head_required = fused_head_quality;
14492            self.graph_want_logits = fused_head_quality;
14493            #[cfg(target_os = "macos")]
14494            if graph_quality && std::env::var("CMF_METAL_BATCH_NLL").as_deref() != Ok("0") {
14495                match self.nll_batch_metal(ids, start) {
14496                    MetalBatchNllOutcome::Completed(nll, count) => {
14497                        return Ok((nll, count));
14498                    }
14499                    MetalBatchNllOutcome::Declined => {}
14500                    MetalBatchNllOutcome::Failed(err) => return Err(err),
14501                }
14502            }
14503            // CMF_NLL_SERIAL=1 scores position by position through the
14504            // decode path (the wgpu token graph where it admits the model)
14505            // — the perplexity gate of a decode kernel, which the batched
14506            // prefill arm below never runs.
14507            let force_serial = std::env::var("CMF_NLL_SERIAL").as_deref() == Ok("1");
14508            if self.can_prefill_batched() && !graph_quality && !force_serial {
14509                // prefill-GEMM: layer-major position chunks, lm_head batched
14510                // (254MB lm_head read once per chunk, not per position).
14511                // The layer chunk is large (grouping positions by MoE experts
14512                // wins with size), lm_head in sub-blocks (logit buffer
14513                // 32×vocab ≈ 32MB instead of 128×).
14514                // CMF_NLL_CHUNK: positions per prefill step (default 128).
14515                // A device scorer pays one round trip per projection per
14516                // step, so a 512-position step quarters them.
14517                let chunk_len: usize = std::env::var("CMF_NLL_CHUNK")
14518                    .ok()
14519                    .and_then(|v| v.parse().ok())
14520                    .filter(|&c: &usize| c > 0)
14521                    .unwrap_or(128);
14522                const LM_SUB: usize = 32;
14523                let n = ids.len().saturating_sub(1);
14524                let hs = self.hidden_size;
14525                let rows = self.weights.lm_head.rows();
14526                let mut pos = 0usize;
14527                let state_trace = std::env::var("CMF_STATE_TRACE").is_ok();
14528                while pos < n {
14529                    let end = (pos + chunk_len).min(n);
14530                    let bsz = end - pos;
14531                    let hb = self.prefill_rows(&ids[pos..end], pos, task_mask)?;
14532                    self.nll_check_graph("batched prefill", pos)?;
14533                    if state_trace && end % 256 == 0 {
14534                        self.trace_recurrent_state(end);
14535                    }
14536                    let mut k0 = 0usize;
14537                    while k0 < bsz {
14538                        let k1 = (k0 + LM_SUB).min(bsz);
14539                        let sb = k1 - k0;
14540                        // Sub-block entirely below the scored range: the KV
14541                        // it just built is all this pass needed from it.
14542                        if pos + k1 <= start {
14543                            k0 = k1;
14544                            continue;
14545                        }
14546                        let mut normed = vec![0.0f32; sb * hs];
14547                        for k in 0..sb {
14548                            let r = inference::rms_norm(
14549                                &hb[(k0 + k) * hs..(k0 + k + 1) * hs],
14550                                &self.weights.final_norm,
14551                                self.rms_eps,
14552                                self.norm_style,
14553                            );
14554                            normed[k * hs..(k + 1) * hs].copy_from_slice(&r);
14555                        }
14556                        let mut logits = vec![0.0f32; sb * rows];
14557                        self.weights
14558                            .lm_head
14559                            .matmat(&normed, sb, &mut logits, self.pool.as_deref());
14560                        for k in 0..sb {
14561                            if pos + k0 + k < start {
14562                                continue;
14563                            }
14564                            self.nll_check_graph("batched score row", pos + k0 + k)?;
14565                            let lg = &mut logits[k * rows..k * rows + self.vocab_size.min(rows)];
14566                            if let Some(mu) = self.logit_multiplier {
14567                                for v in lg.iter_mut() {
14568                                    *v *= mu;
14569                                }
14570                            }
14571                            // Gemma-class final-logit soft-capping: the
14572                            // decode paths apply it; scoring must too, or
14573                            // the uncapped softmax misprices every token.
14574                            if let Some(c) = self.final_softcap {
14575                                softcap_in_place(lg, c, self.pool.as_deref());
14576                            }
14577                            // Cortiq Embryo hierarchical head: same correction
14578                            // the decode path applies (lm_head_forward).
14579                            if let Some(cm) = self.head_clusters.clone() {
14580                                self.hierarchical_head_logprobs(
14581                                    &normed[k * hs..(k + 1) * hs],
14582                                    &cm,
14583                                    lg,
14584                                );
14585                            }
14586                            let lg = &logits[k * rows..k * rows + self.vocab_size.min(rows)];
14587                            let target = ids[pos + k0 + k + 1] as usize;
14588                            let max = lg.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
14589                            let lse: f64 = lg
14590                                .iter()
14591                                .map(|&v| ((v - max) as f64).exp())
14592                                .sum::<f64>()
14593                                .ln()
14594                                + max as f64;
14595                            nll += lse - lg[target] as f64;
14596                            cnt += 1;
14597                            if std::env::var("CMF_PPL_TRACE").is_ok() {
14598                                let top = lg
14599                                    .iter()
14600                                    .enumerate()
14601                                    .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
14602                                    .map(|(i, _)| i)
14603                                    .unwrap_or(0);
14604                                eprintln!(
14605                                    "BTRACE pos {} target {} nll {:.4} top {} lg_t {:.3} lg_top {:.3}",
14606                                    pos + k0 + k,
14607                                    target,
14608                                    lse - lg[target] as f64,
14609                                    top,
14610                                    lg[target],
14611                                    lg[top]
14612                                );
14613                            }
14614                        }
14615                        k0 = k1;
14616                    }
14617                    pos = end;
14618                }
14619                return Ok((nll, cnt));
14620            }
14621            for pos in 0..ids.len().saturating_sub(1) {
14622                let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, task_mask);
14623                self.nll_check_graph("serial forward", pos)?;
14624                // Architectures whose head lives inside their own stack return
14625                // the logits out of band and a zero hidden — DeepSeek-V4 folds
14626                // its hyper-connection copies between the last layer and the
14627                // norm, so it cannot hand back a vector this loop could use.
14628                // Scoring the zeros gave a perplexity of exactly the vocabulary
14629                // size, which is a uniform distribution reported as a
14630                // measurement. `generate` already reads this channel.
14631                let out_of_band = self.graph_logits.take();
14632                if self.graph_head_required && out_of_band.is_none() {
14633                    METAL_GRAPH_HEAD_MISS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14634                    return Err(format!(
14635                        "fused Metal graph head did not complete at NLL position {pos}"
14636                    ));
14637                }
14638                if pos < start {
14639                    continue;
14640                }
14641                let logits = match out_of_band {
14642                    Some(lg) => lg,
14643                    None => {
14644                        let normed = inference::rms_norm(
14645                            &hidden,
14646                            &self.weights.final_norm,
14647                            self.rms_eps,
14648                            self.norm_style,
14649                        );
14650                        // lm_head_forward applies the final-logit softcap itself
14651                        // — capping again here double-squashed gemma-class
14652                        // logits (tanh∘tanh) and reported a flattered ppl.
14653                        self.lm_head_forward(&normed)
14654                    }
14655                };
14656                let target = ids[pos + 1] as usize;
14657                let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
14658                let lse: f64 = logits
14659                    .iter()
14660                    .map(|&v| ((v - max) as f64).exp())
14661                    .sum::<f64>()
14662                    .ln()
14663                    + max as f64;
14664                let tok_nll = lse - logits[target] as f64;
14665                if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 10_000 {
14666                    let top = logits
14667                        .iter()
14668                        .enumerate()
14669                        .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
14670                        .map(|(i, _)| i)
14671                        .unwrap_or(0);
14672                    eprintln!(
14673                        "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
14674                        logits[target], logits[top]
14675                    );
14676                }
14677                nll += tok_nll;
14678                cnt += 1;
14679            }
14680            Ok((nll, cnt))
14681        })();
14682        self.nll_end();
14683        result
14684    }
14685
14686    /// Score one post-layer hidden with the same final norm/head path used by
14687    /// decode. Keeping this in one helper is important for the production
14688    /// batch scorer: its rows stop before the final norm, just like the
14689    /// per-position O(1) path below.
14690    fn nll_from_hidden(&mut self, hidden: &[f32], target: u32, pos: usize) -> f64 {
14691        let normed = inference::rms_norm(
14692            hidden,
14693            &self.weights.final_norm,
14694            self.rms_eps,
14695            self.norm_style,
14696        );
14697        // lm_head_forward applies the final-logit softcap itself — capping
14698        // again here double-squashed gemma-class logits in earlier scorers.
14699        let mut logits = self.lm_head_forward(&normed);
14700        let target = target as usize;
14701        let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
14702        let lse: f64 = logits
14703            .iter()
14704            .map(|&v| ((v - max) as f64).exp())
14705            .sum::<f64>()
14706            .ln()
14707            + max as f64;
14708        let tok_nll = lse - logits[target] as f64;
14709        if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 10_000 {
14710            let top = logits
14711                .iter()
14712                .enumerate()
14713                .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
14714                .map(|(i, _)| i)
14715                .unwrap_or(0);
14716            eprintln!(
14717                "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
14718                logits[target], logits[top]
14719            );
14720        }
14721        attention::recycle_buf(&mut logits);
14722        tok_nll
14723    }
14724
14725    /// `CMF_STATE_TRACE`: per-layer magnitude of the recurrent record at
14726    /// position `pos` — the whole `linear_state` (vmf: S then the conv
14727    /// ring; GDN: conv ring then S), its recurrent S part alone, the
14728    /// bounded ring, and the last per-position KV row count.  The tool
14729    /// that separated the ~4k perplexity cliff of the 500-step exports
14730    /// (a state that keeps climbing past the trained window) from a
14731    /// runtime boundary; one line per layer, `STATE pos=… layer=…`.
14732    fn trace_recurrent_state(&self, pos: usize) {
14733        let stats = |v: &[f32]| -> (f64, f64) {
14734            if v.is_empty() {
14735                return (0.0, 0.0);
14736            }
14737            let (mut ss, mut mx) = (0f64, 0f64);
14738            for &x in v {
14739                ss += (x as f64) * (x as f64);
14740                mx = mx.max((x as f64).abs());
14741            }
14742            ((ss / v.len() as f64).sqrt(), mx)
14743        };
14744        for (li, l) in self.kv_cache.layers.iter().enumerate() {
14745            let lw = &self.weights.layers[self.phys_layer(li)];
14746            let (kind, s_len) = match &lw.attn {
14747                AttnKind::Linear(_) => ("vmf", self.vmf_cfg.map(|c| c.state_len()).unwrap_or(0)),
14748                AttnKind::LinearGdn(_) => ("gdn", self.gdn_cfg.map(|c| c.state_len()).unwrap_or(0)),
14749                AttnKind::Bounded(_) => ("bounded", 0),
14750                AttnKind::Full { .. } => ("full", 0),
14751                _ => ("other", 0),
14752            };
14753            let (rms, max) = stats(&l.linear_state);
14754            let s_part = if kind == "vmf" {
14755                &l.linear_state[..s_len.min(l.linear_state.len())]
14756            } else if kind == "gdn" {
14757                let ring = l
14758                    .linear_state
14759                    .len()
14760                    .saturating_sub(s_len)
14761                    .min(l.linear_state.len());
14762                &l.linear_state[ring..]
14763            } else {
14764                &l.linear_state[..0]
14765            };
14766            let (s_rms, s_max) = stats(s_part);
14767            let (ring_rms, ring_len) = match &l.bounded {
14768                Some(b) => (stats(&b.ring_k).0, b.ring_k.len()),
14769                None => (0.0, 0),
14770            };
14771            eprintln!(
14772                "STATE pos={pos} layer={li} kind={kind} state_len={} rms={rms:.5} max={max:.4} \
14773                 S_rms={s_rms:.5} S_max={s_max:.4} ring_k_rms={ring_rms:.5} ring_len={ring_len} kv_rows={}",
14774                l.linear_state.len(),
14775                l.seq_len
14776            );
14777        }
14778    }
14779
14780    /// Teacher-forced NLL of the CONVERTED model: the O(1) Nyström path
14781    /// is ACTIVE over the scored positions. Returns `Ok((nll sum, scored
14782    /// count))` over `prefill..len-1` and surfaces a post-mutation batch
14783    /// failure instead of returning a partial score.
14784    ///
14785    /// Runtime discipline, deliberately NOT the matrix probe's: the
14786    /// requested prefix plus any required deferred lead-in run the exact
14787    /// prompt pass — that pass is what freezes the landmarks and M — and
14788    /// every post-seal scored position goes through `NystromState::step()`,
14789    /// the same code decode runs.
14790    /// So the landmarks are PREFILL-frozen (what ships), not
14791    /// full-sequence oracles (what the published probe measured). When the
14792    /// requested prefix is shorter than the bounded transition, rows in the
14793    /// exact lead-in are still scored so the shifted target range is stable.
14794    ///
14795    /// Pair with `nll_ids_from(ids, prefill)` for the exact baseline
14796    /// over the identical token set — that ratio is the honest one.
14797    pub fn nll_ids_o1(&mut self, ids: &[u32], prefill: usize) -> Result<(f64, usize), String> {
14798        // This scorer consumes host hiddens, so never request the optional
14799        // token-graph lm_head side channel. `nll_begin` also consumes a
14800        // prior graph failure and clears only the cancel bit that failure
14801        // raised, leaving a caller-owned cancellation observable.
14802        self.nll_begin()?;
14803        let requested_prefix = (prefill > 0).then_some(prefill);
14804        self.o1_begin_with_prefix(requested_prefix);
14805        let n = ids.len().saturating_sub(1);
14806        let requested_start = prefill.min(n);
14807        // The exact prefix must reach the deferred boundary before a
14808        // collecting layer can convert. Rows between the requested start and
14809        // that boundary remain part of the public NLL range and are scored
14810        // from the same hidden pass below.
14811        let exact_end = if self.o1_active() {
14812            match requested_prefix {
14813                Some(requested) => self.o1_effective_boundary(requested),
14814                None => self
14815                    .o1_cfg
14816                    .as_ref()
14817                    .and_then(|c| crate::nystrom::o1_deferred_boundary(c.w, c.sink)),
14818            }
14819            .unwrap_or(requested_start)
14820            .min(n)
14821        } else {
14822            requested_start
14823        };
14824        let mut nll = 0f64;
14825        let mut cnt = 0usize;
14826
14827        // Exact prompt pass over ids[..exact_end]: the seal consumes its
14828        // q/k/v. Rows at or after requested_start are scored here when the
14829        // bounded lead-in is longer than the caller's requested prefix.
14830        let mut pos = 0usize;
14831        if self.can_prefill_batched() {
14832            const CHUNK: usize = 128;
14833            while pos < exact_end {
14834                let end = (pos + CHUNK).min(exact_end);
14835                let hiddens = self.prefill_batch(&ids[pos..end], pos);
14836                if self
14837                    .graph_failed
14838                    .swap(false, std::sync::atomic::Ordering::Relaxed)
14839                {
14840                    self.cancel
14841                        .store(false, std::sync::atomic::Ordering::Relaxed);
14842                    self.nll_end();
14843                    return Err("GPU graph failed during O(1) NLL prefix".into());
14844                }
14845                for row in 0..end - pos {
14846                    let score_pos = pos + row;
14847                    if score_pos >= requested_start && score_pos < n {
14848                        nll += self.nll_from_hidden(
14849                            &hiddens[row * self.hidden_size..(row + 1) * self.hidden_size],
14850                            ids[score_pos + 1],
14851                            score_pos,
14852                        );
14853                        cnt += 1;
14854                    }
14855                }
14856                pos = end;
14857            }
14858        } else {
14859            while pos < exact_end {
14860                let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
14861                if self
14862                    .graph_failed
14863                    .swap(false, std::sync::atomic::Ordering::Relaxed)
14864                {
14865                    self.cancel
14866                        .store(false, std::sync::atomic::Ordering::Relaxed);
14867                    self.nll_end();
14868                    return Err("GPU graph failed during O(1) NLL prefix".into());
14869                }
14870                if pos >= requested_start && pos < n {
14871                    nll += self.nll_from_hidden(&hidden, ids[pos + 1], pos);
14872                    cnt += 1;
14873                }
14874                pos += 1;
14875            }
14876        }
14877        self.o1_seal_checked().map_err(|err| {
14878            self.nll_end();
14879            err
14880        })?;
14881
14882        // Reuse the production whole-token batch graph for the post-seal
14883        // suffix when the caller explicitly enabled both routes. This is a
14884        // teacher-forced scorer, so every row is ids[pos] and its target is
14885        // ids[pos + 1]; no speculative tail or rollback state is involved.
14886        // A first Declined is safe to handle with the established serial O(1)
14887        // path. Once a chunk completes, however, the device recurrent state
14888        // owns the sequence and a later decline must be terminal rather than
14889        // falling back to stale CPU state.
14890        let batch_k = std::env::var("CMF_BATCH_K")
14891            .ok()
14892            .and_then(|v| v.parse::<usize>().ok())
14893            .unwrap_or(0);
14894        let batch_admitted = batch_k > 0
14895            && self.can_prefill_batched()
14896            && self.o1_active()
14897            && self.o1_on_graph()
14898            && (0..self.num_layers).all(|li| {
14899                let cache = &self.kv_cache.layers[self.phys_layer(li)];
14900                cache.o1.is_none() || cache.o1_views().is_some()
14901            });
14902        if std::env::var("CMF_GRAPH_PROF").is_ok() {
14903            eprintln!(
14904                "nll-batch: phase=post-seal admission={} requested_k={} scored_rows={}",
14905                batch_admitted,
14906                batch_k,
14907                n.saturating_sub(exact_end),
14908            );
14909        }
14910        let mut batch_completed = false;
14911        if batch_admitted && exact_end < n {
14912            let hs = self.hidden_size;
14913            let mut batch_pos = exact_end;
14914            while batch_pos < n {
14915                let end = (batch_pos + batch_k).min(n);
14916                let bk = end - batch_pos;
14917                let mut hiddens = vec![0.0f32; bk * hs];
14918                for (row, &id) in ids[batch_pos..end].iter().enumerate() {
14919                    hiddens[row * hs..(row + 1) * hs].copy_from_slice(&self.embed_single(id));
14920                }
14921                let positions: Vec<usize> = (batch_pos..end).collect();
14922                let t_batch = std::time::Instant::now();
14923                let outcome = self.try_batch_graph_wgpu(&mut hiddens, &positions, bk, None);
14924                if std::env::var("CMF_GRAPH_PROF").is_ok() {
14925                    let ms = t_batch.elapsed().as_secs_f64() * 1000.0;
14926                    eprintln!(
14927                        "nll-batch: phase=post-seal mode=o1 k={bk} pos={}..{} outcome={outcome:?} {ms:.1} ms ({:.1} tok/s)",
14928                        batch_pos,
14929                        end.saturating_sub(1),
14930                        bk as f64 / (ms / 1000.0),
14931                    );
14932                }
14933                if let Err(err) = self.nll_check_graph("batch graph", batch_pos) {
14934                    self.nll_end();
14935                    return Err(err);
14936                }
14937                match outcome {
14938                    crate::gpu::BatchGraphOutcome::Completed => {
14939                        batch_completed = true;
14940                        for row in 0..bk {
14941                            nll += self.nll_from_hidden(
14942                                &hiddens[row * hs..(row + 1) * hs],
14943                                ids[batch_pos + row + 1],
14944                                batch_pos + row,
14945                            );
14946                            cnt += 1;
14947                        }
14948                        batch_pos = end;
14949                    }
14950                    crate::gpu::BatchGraphOutcome::Declined => {
14951                        if batch_completed {
14952                            self.nll_end();
14953                            return Err(format!(
14954                                "O(1) NLL batch declined after completed chunk at position {batch_pos}"
14955                            ));
14956                        }
14957                        break;
14958                    }
14959                    crate::gpu::BatchGraphOutcome::Failed => {
14960                        self.nll_end();
14961                        return Err(format!(
14962                            "O(1) NLL batch graph failed after admission at position {batch_pos}"
14963                        ));
14964                    }
14965                }
14966            }
14967            if batch_completed && cnt == n.saturating_sub(requested_start) {
14968                self.nll_end();
14969                return Ok((nll, cnt));
14970            }
14971        }
14972
14973        // Serial O(1) fallback/reference. It is intentionally retained when
14974        // batch admission declines before mutation; callers must label this
14975        // CMF_BATCH_K=0/per-position path separately from the production
14976        // whole-token batch route.
14977        for pos in exact_end..n {
14978            let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
14979            if self
14980                .graph_failed
14981                .swap(false, std::sync::atomic::Ordering::Relaxed)
14982            {
14983                self.cancel
14984                    .store(false, std::sync::atomic::Ordering::Relaxed);
14985                self.nll_end();
14986                return Err(format!(
14987                    "GPU graph failed during O(1) NLL serial scoring at position {pos}"
14988                ));
14989            }
14990            nll += self.nll_from_hidden(&hidden, ids[pos + 1], pos);
14991            cnt += 1;
14992        }
14993        self.nll_end();
14994        Ok((nll, cnt))
14995    }
14996
14997    /// Teacher-forced calibration data (B1): for each position, whether the
14998    /// argmax equals the actual next token, and the top-1 softmax prob
14999    /// (top-1 probability) under EACH temperature in `temps` — all from ONE forward
15000    /// pass (argmax/correctness are temperature-invariant; only p_max
15001    /// reshapes). Feeds `cortiq calibrate` (reliability/ECE + temperature
15002    /// fit): is the model's confidence a true property, or does it need a
15003    /// measured scaling?
15004    pub fn calib_ids(&mut self, ids: &[u32], temps: &[f32]) -> (Vec<bool>, Vec<Vec<f32>>) {
15005        self.clear_sequence_state();
15006        let n = ids.len().saturating_sub(1);
15007        let mut correct = Vec::with_capacity(n);
15008        let mut pmax = Vec::with_capacity(n);
15009        for pos in 0..n {
15010            let emb = self.embed_single(ids[pos]);
15011            let hidden = self.forward_layers(&emb, pos, None);
15012            let logits = if let Some(logits) = self.graph_logits.take() {
15013                logits
15014            } else {
15015                let normed = inference::rms_norm(
15016                    &hidden,
15017                    &self.weights.final_norm,
15018                    self.rms_eps,
15019                    self.norm_style,
15020                );
15021                // lm_head_forward applies the final-logit softcap itself —
15022                // capping again here double-squashed gemma-class logits
15023                // (tanh∘tanh) and reported a flattered ppl.
15024                self.lm_head_forward(&normed)
15025            };
15026            let target = ids[pos + 1] as usize;
15027            let (mut amax, mut mval) = (0usize, f32::NEG_INFINITY);
15028            for (i, &v) in logits.iter().enumerate() {
15029                if v > mval {
15030                    mval = v;
15031                    amax = i;
15032                }
15033            }
15034            correct.push(amax == target);
15035            let row: Vec<f32> = temps
15036                .iter()
15037                .map(|&t| {
15038                    let tt = t.max(1e-3);
15039                    let s: f32 = logits.iter().map(|&v| ((v - mval) / tt).exp()).sum();
15040                    1.0 / s.max(1e-12) // numerator at the max is exp(0)=1
15041                })
15042                .collect();
15043            pmax.push(row);
15044        }
15045        self.clear_sequence_state();
15046        (correct, pmax)
15047    }
15048
15049    /// Teacher-forced PPL with the dynamic router driving per-window
15050    /// skill switches (VMF experiment №2 measurement). Sequential (φ
15051    /// must update per token), returns (ppl, switch_count). The router
15052    /// must be enabled (`enable_dynamic_routing`); else this equals
15053    /// plain `ppl_ids`. The active skill when scoring token t shapes the
15054    /// logits for t+1 — on-policy over the held-out text itself.
15055    pub fn ppl_ids_dynamic(&mut self, ids: &[u32]) -> Result<(f64, usize), String> {
15056        if self.dyn_router.is_none() {
15057            return Ok((self.ppl_ids(ids)?, 0));
15058        }
15059        self.nll_begin()?;
15060        let saved_active = self.dyn_active;
15061        let mut router = self
15062            .dyn_router
15063            .take()
15064            .ok_or_else(|| "dynamic router disappeared before PPL scoring".to_string())?;
15065        router.reset();
15066        self.dyn_phi_seen = 0;
15067        let _ = self.set_active_skill(None);
15068
15069        let result: Result<(f64, usize), String> = (|| {
15070            let mut nll = 0f64;
15071            let mut cnt = 0usize;
15072            for pos in 0..ids.len().saturating_sub(1) {
15073                let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
15074                self.nll_check_graph("dynamic serial forward", pos)?;
15075                let out_of_band = self.graph_logits.take();
15076                let mut logits = match out_of_band {
15077                    Some(lg) => lg,
15078                    None => {
15079                        let normed = inference::rms_norm(
15080                            &hidden,
15081                            &self.weights.final_norm,
15082                            self.rms_eps,
15083                            self.norm_style,
15084                        );
15085                        // lm_head_forward applies the final-logit softcap itself —
15086                        // capping again here double-squashed gemma-class logits
15087                        // and reported a flattered ppl.
15088                        self.lm_head_forward(&normed)
15089                    }
15090                };
15091                let target = ids[pos + 1] as usize;
15092                let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
15093                let lse: f64 = logits
15094                    .iter()
15095                    .map(|&v| ((v - max) as f64).exp())
15096                    .sum::<f64>()
15097                    .ln()
15098                    + max as f64;
15099                let tok_nll = lse - logits[target] as f64;
15100                if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 10_000 {
15101                    let top = logits
15102                        .iter()
15103                        .enumerate()
15104                        .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
15105                        .map(|(i, _)| i)
15106                        .unwrap_or(0);
15107                    eprintln!(
15108                        "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
15109                        logits[target], logits[top]
15110                    );
15111                }
15112                nll += tok_nll;
15113                cnt += 1;
15114                attention::recycle_buf(&mut logits);
15115                // Route on the evolving phi (drives the NEXT token's skill).
15116                let phi = self.dyn_phi_ema.clone();
15117                if let Some(new_active) = router.step(&phi, pos) {
15118                    // a switch clears the state: positions 0..=pos are read
15119                    // again under the new weights before pos+1 is scored
15120                    if self.set_active_skill(new_active).is_ok() {
15121                        self.reprefill_context(&ids[..=pos], None)?;
15122                        self.graph_logits = None;
15123                    }
15124                }
15125            }
15126            Ok(((nll / cnt.max(1) as f64).exp(), router.switches.len()))
15127        })();
15128
15129        // Restore the detached router and the active overlay on both success
15130        // and failure. The scoring state is cleared independently below.
15131        let _ = self.set_active_skill(saved_active);
15132        self.dyn_router = Some(router);
15133        self.nll_end();
15134        result
15135    }
15136
15137    /// Routing probe φ (spec §9): mean-pooled hidden after `layer`.
15138    pub fn probe_phi(&mut self, ids: &[u32], layer: usize) -> Vec<f32> {
15139        self.clear_sequence_state();
15140        let mut acc = vec![0f32; self.hidden_size];
15141        for (pos, &id) in ids.iter().enumerate() {
15142            let h = self.forward_layers_upto(&self.embed_single(id), pos, None, Some(layer));
15143            for (a, v) in acc.iter_mut().zip(&h) {
15144                *a += v;
15145            }
15146        }
15147        let n = ids.len().max(1) as f32;
15148        for a in acc.iter_mut() {
15149            *a /= n;
15150        }
15151        self.clear_sequence_state();
15152        acc
15153    }
15154
15155    /// Every position's hidden AFTER `layer` (n × hidden, not normalized): the
15156    /// walk of [`Self::probe_phi_span`] without the pooling, for `phi-dump`.
15157    pub fn probe_hidden_rows(&mut self, ids: &[u32], layer: usize) -> Vec<f32> {
15158        #[cfg(target_os = "macos")]
15159        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
15160        self.clear_sequence_state();
15161        let mut rows = Vec::with_capacity(ids.len() * self.hidden_size);
15162        for (pos, &id) in ids.iter().enumerate() {
15163            let h = self.forward_layers_upto(&self.embed_single(id), pos, None, Some(layer));
15164            rows.extend_from_slice(&h);
15165        }
15166        self.clear_sequence_state();
15167        rows
15168    }
15169
15170    /// Router-v2 φ probe (spec §9.4, `phi.pool = "span_mean"`): the hidden
15171    /// AFTER `layer` — the same per-position walk and the same quantity as
15172    /// [`Self::probe_phi`] — averaged over the positions in `span` only
15173    /// (the user text between the template's prefix and suffix ids), NOT
15174    /// unit-normalized (the decision normalizes). The walk stops at
15175    /// `span.end`: causality makes the later positions irrelevant, so the
15176    /// result is bit-identical to probing `ids[..span.end]`. An empty span
15177    /// gives the zero vector, which the decision treats as degenerate.
15178    ///
15179    /// Every sequence state is reset before and after — the host KV/ring/
15180    /// recurrent state, the reuse keys (`kv_history`, `kv_prefix`) and the
15181    /// device graph's sequence — so run it on a pipeline that does not
15182    /// also serve a conversation (its prefix reuse would be lost).
15183    pub fn probe_phi_span(
15184        &mut self,
15185        ids: &[u32],
15186        layer: usize,
15187        span: std::ops::Range<usize>,
15188    ) -> Vec<f32> {
15189        #[cfg(target_os = "macos")]
15190        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
15191        let end = span.end.min(ids.len());
15192        let start = span.start.min(end);
15193        let reset = |p: &mut Self| p.clear_sequence_state();
15194        reset(self);
15195        let mut acc = vec![0f32; self.hidden_size];
15196        for (pos, &id) in ids[..end].iter().enumerate() {
15197            let h = self.forward_layers_upto(&self.embed_single(id), pos, None, Some(layer));
15198            if pos >= start {
15199                for (a, v) in acc.iter_mut().zip(&h) {
15200                    *a += v;
15201                }
15202            }
15203        }
15204        let n = end - start;
15205        if n > 0 {
15206            let n = n as f32;
15207            for a in acc.iter_mut() {
15208                *a /= n;
15209            }
15210        }
15211        reset(self);
15212        acc
15213    }
15214
15215    /// One decode step of the current sequence: forward `token` at
15216    /// `position` (the cache holds positions `[0, position)`, e.g. after
15217    /// [`Self::forward_ids`]) and return the next-token logits — the same
15218    /// forward and head the generation loop runs (resident-graph logits
15219    /// when the graph ran, final norm + lm_head otherwise). The logit-dump
15220    /// tools drive greedy decoding with it so every position is observable.
15221    pub fn decode_step_logits(&mut self, token: u32, position: usize) -> Vec<f32> {
15222        #[cfg(target_os = "macos")]
15223        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
15224        self.graph_logits = None;
15225        let hidden = self.forward_layers(&self.embed_single(token), position, None);
15226        if let Some(logits) = self.graph_logits.take() {
15227            return logits;
15228        }
15229        inference::rms_norm_into(
15230            &hidden,
15231            &self.weights.final_norm,
15232            self.rms_eps,
15233            self.norm_style,
15234            &mut self.ws.n1,
15235        );
15236        self.lm_head_forward(&self.ws.n1)
15237    }
15238
15239    /// Layer-major batched prefill (prefill-GEMM): full-attention —
15240    /// per-position with the existing operators (KV grows naturally,
15241    /// causality preserved), GDN projections / FFN / MoE — batched
15242    /// (a weight row is read from DRAM once per chunk, not per
15243    /// position). Returns the hidden of all positions [b × hidden].
15244    fn prefill_batch(&mut self, ids: &[u32], start_pos: usize) -> Vec<f32> {
15245        self.prefill_batch_masked(ids, start_pos, None)
15246    }
15247
15248    /// `prefill_batch` with a task mask honored on the dense-FFN panels
15249    /// (the masked-inference fast path: full fused compute, mask lands on
15250    /// the activations). The whole-chunk GPU graph is skipped for masked
15251    /// layers by the callers' arms; the per-GEMM device paths stay in
15252    /// play because the zeroing happens on the host between them.
15253    fn prefill_batch_masked(
15254        &mut self,
15255        ids: &[u32],
15256        start_pos: usize,
15257        task_mask: Option<&TaskMask>,
15258    ) -> Vec<f32> {
15259        self.prefill_batch_span(PrefillIn::Ids(ids), start_pos, task_mask, 0, usize::MAX)
15260    }
15261
15262    /// One prompt chunk through the whole stack, post-stack rows out (no
15263    /// final norm) — the ingest generation uses, shared by scoring and
15264    /// `forward_ids` so they measure the same execution: the batched wgpu
15265    /// graph's device prefix plus the host's batched walk for the rest when
15266    /// `batch_prefix_prefill` holds and the graph admits the chunk, else
15267    /// the host's chunked prefill. Err only when a graph that had mutated
15268    /// device state failed.
15269    fn prefill_rows(
15270        &mut self,
15271        ids: &[u32],
15272        pos: usize,
15273        task_mask: Option<&TaskMask>,
15274    ) -> Result<Vec<f32>, String> {
15275        self.prefill_input_rows(PrefillIn::Ids(ids), pos, task_mask)
15276    }
15277
15278    fn prefill_input_rows(
15279        &mut self,
15280        input: PrefillIn<'_>,
15281        pos: usize,
15282        task_mask: Option<&TaskMask>,
15283    ) -> Result<Vec<f32>, String> {
15284        if self.dash.is_some() {
15285            let PrefillIn::Hidden(rows) = input else {
15286                return Err("Unlimited-OCR prompts carry image rows".into());
15287            };
15288            return Ok(self.dash_prefill_rows(rows, pos));
15289        }
15290        self.mimo_moe_prepare();
15291        let hs = self.hidden_size;
15292        let bk = match input {
15293            PrefillIn::Ids(ids) => ids.len(),
15294            PrefillIn::Hidden(rows) => rows.len() / hs,
15295        };
15296        // MiniCPM-OCR's vision rows on native Metal: the rows graph, as an id
15297        // prompt's chunks take it in the generation loop.
15298        #[cfg(target_os = "macos")]
15299        if let PrefillIn::Hidden(rows) = input
15300            && task_mask.is_none()
15301            && self.onevision2_prefill()
15302            && (crate::gpu::q1_force() || crate::gpu::q2tp_gpu_opt_in())
15303            && crate::gpu::enabled_here()
15304            && self.gdn_cfg.is_some()
15305            && !self.per_token_stack()
15306            && bk > 8
15307            && bk <= 512
15308            && std::env::var("CMF_METAL_PREFILL").as_deref() != Ok("0")
15309        {
15310            match self.prefill_hiddens_metal(rows.to_vec(), pos, None) {
15311                MetalPrefillOutcome::Completed(h) => return Ok(h),
15312                MetalPrefillOutcome::Failed => {
15313                    return Err("Metal prefill of the prompt rows failed after admission".into());
15314                }
15315                MetalPrefillOutcome::Declined => {}
15316            }
15317        }
15318        #[cfg(not(target_os = "macos"))]
15319        if task_mask.is_none()
15320            && !self.o1_active()
15321            && bk > 1
15322            && (self.batch_prefix_prefill()
15323                // Ripple: scoring reads its chunks through the batch graph
15324                // too (the host walk attends 80 heads a row on the CPU).
15325                || (self.value_blend.is_some() && self.g4_batch_prefill())
15326                // An embedded prompt (vision rows) on the graph route takes
15327                // the batched graph like an id prompt does.
15328                || (matches!(input, PrefillIn::Hidden(_)) && self.generation_batch_k() > 0)
15329                || (self.verify_exact_moe
15330                    && crate::gpu::enabled_here()
15331                    && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)))
15332        {
15333            let mut hiddens = match input {
15334                PrefillIn::Hidden(rows) => rows.to_vec(),
15335                PrefillIn::Ids(ids) => ids.iter().flat_map(|&id| self.embed_single(id)).collect(),
15336            };
15337            let positions: Vec<usize> = (pos..pos + bk).collect();
15338            let mut run = 0usize;
15339            match self.try_batch_graph_wgpu_prefix(
15340                &mut hiddens,
15341                &positions,
15342                bk,
15343                None,
15344                Some(&mut run),
15345            ) {
15346                crate::gpu::BatchGraphOutcome::Completed => {
15347                    let out = if run < self.num_layers {
15348                        self.prefill_batch_span(
15349                            PrefillIn::Hidden(&hiddens),
15350                            pos,
15351                            None,
15352                            run,
15353                            self.num_layers,
15354                        )
15355                    } else {
15356                        hiddens
15357                    };
15358                    return if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
15359                        Err("MiMo attention graph failed after admission".into())
15360                    } else {
15361                        Ok(out)
15362                    };
15363                }
15364                crate::gpu::BatchGraphOutcome::Failed => {
15365                    return Err("batched prefix prefill failed after admission".into());
15366                }
15367                crate::gpu::BatchGraphOutcome::Declined => {
15368                    // Rows an earlier chunk left on the device only.
15369                    #[cfg(feature = "gpu")]
15370                    self.pull_lagging_host_kv(0, self.num_layers, pos);
15371                }
15372            }
15373        }
15374        let out = self.prefill_batch_span(input, pos, task_mask, 0, usize::MAX);
15375        if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
15376            Err("batch tail graph failed after admission".into())
15377        } else {
15378            Ok(out)
15379        }
15380    }
15381
15382    /// Unlimited-OCR's prompt rows, one position at a time: each query has its
15383    /// own coordinates and page candidates.
15384    fn dash_prefill_rows(&mut self, rows: &[f32], pos: usize) -> Vec<f32> {
15385        let hs = self.hidden_size;
15386        let n = rows.len() / hs;
15387        let mut last = vec![0f32; hs];
15388        let mut i = 0usize;
15389        while i < n && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
15390            #[cfg(not(target_os = "macos"))]
15391            if self.dash_batch_on {
15392                let k = (n - i).min(crate::gpu::DASH_CHUNK_MAX);
15393                if let Some(d) = self.dash.as_mut() {
15394                    d.at_prompt_chunk(pos + i, k);
15395                }
15396                let mut h = rows[i * hs..(i + k) * hs].to_vec();
15397                let positions: Vec<usize> = (pos + i..pos + i + k).collect();
15398                match self.try_batch_graph_wgpu_prefix(&mut h, &positions, k, None, None) {
15399                    crate::gpu::BatchGraphOutcome::Completed => {
15400                        last.copy_from_slice(&h[(k - 1) * hs..]);
15401                        i += k;
15402                        continue;
15403                    }
15404                    crate::gpu::BatchGraphOutcome::Failed => {
15405                        self.graph_failed.store(true, std::sync::atomic::Ordering::Relaxed);
15406                        return last;
15407                    }
15408                    crate::gpu::BatchGraphOutcome::Declined => self.dash_batch_on = false,
15409                }
15410            }
15411            #[cfg(target_os = "macos")]
15412            if self.dash_batch_on && n - i >= 8 && crate::gpu::backend_name() == "metal" {
15413                let k = (n - i).min(crate::gpu::DASH_CHUNK_MAX);
15414                if let Some(d) = self.dash.as_mut() {
15415                    d.at_prompt_chunk(pos + i, k);
15416                }
15417                let mut h = rows[i * hs..(i + k) * hs].to_vec();
15418                if self.chunk_run_gpu(0, &mut h, k, pos + i, None, self.num_layers) == self.num_layers {
15419                    last.copy_from_slice(&h[(k - 1) * hs..]);
15420                    i += k;
15421                    continue;
15422                }
15423                self.dash_batch_on = false;
15424            }
15425            if let Some(d) = self.dash.as_mut() {
15426                d.at_prompt(pos + i);
15427            }
15428            last = self.forward_layers(&rows[i * hs..(i + 1) * hs], pos + i, None);
15429            i += 1;
15430        }
15431        last
15432    }
15433
15434    /// The layer-major batched walk over a layer span [from..upto_excl):
15435    /// the whole prefill machinery (chunk graph, batched attends, GEMM
15436    /// panels) for a PARTIAL stack — the network split's prefill rides
15437    /// the same canon as the local one. Input is token ids (embeds
15438    /// itself, coordinator side) or ready boundary hiddens (worker side).
15439    fn prefill_batch_span(
15440        &mut self,
15441        input: PrefillIn<'_>,
15442        start_pos: usize,
15443        task_mask: Option<&TaskMask>,
15444        from: usize,
15445        upto_excl: usize,
15446    ) -> Vec<f32> {
15447        let hs = self.hidden_size;
15448        let b = match input {
15449            PrefillIn::Ids(ids) => ids.len(),
15450            PrefillIn::Hidden(hb) => hb.len() / hs,
15451        };
15452        let upto_excl = upto_excl.min(self.num_layers);
15453        // The CPU embed is deferred: when the chunk graph takes the run
15454        // from layer 0 it gathers the embeddings on the device instead.
15455        // A hidden input is ready by definition.
15456        let mut h: Vec<f32>;
15457        let mut h_ready;
15458        match input {
15459            PrefillIn::Ids(_) => {
15460                h = vec![0.0; b * hs];
15461                h_ready = false;
15462            }
15463            PrefillIn::Hidden(hb) => {
15464                h = hb.to_vec();
15465                h_ready = true;
15466            }
15467        }
15468        // Ripple's value residual reads the chunk's embedding rows in every layer.
15469        if self.value_blend.is_some() {
15470            self.vres_e0.clear();
15471            match input {
15472                PrefillIn::Ids(ids) => {
15473                    for &id in ids {
15474                        let e = self.embed_single(id);
15475                        self.vres_e0.extend_from_slice(&e);
15476                    }
15477                }
15478                PrefillIn::Hidden(hb) => {
15479                    assert!(from == 0, "value residual: a layer span past the first layer has no embedding rows");
15480                    self.vres_e0.extend_from_slice(hb);
15481                }
15482            }
15483        }
15484        let fill_h = |h: &mut Vec<f32>, me: &Self| {
15485            if let PrefillIn::Ids(ids) = input {
15486                for (bi, &id) in ids.iter().enumerate() {
15487                    let e = me.embed_single(id);
15488                    h[bi * hs..(bi + 1) * hs].copy_from_slice(&e);
15489                }
15490                if let Ok(tp) = std::env::var("CMF_TRACE_POS") {
15491                    if let Ok(t) = tp.parse::<usize>() {
15492                        if t >= start_pos && t < start_pos + ids.len() {
15493                            let bi = t - start_pos;
15494                            let row = &h[bi * hs..(bi + 1) * hs];
15495                            let n: f32 = row.iter().map(|x| x * x).sum::<f32>().sqrt();
15496                            eprintln!(
15497                                "BATCH pos {t} embed: id {} |h| = {n:.6} h0 {:.6} h1 {:.6} | b={} start={start_pos} ids[..8]={:?}",
15498                                ids[bi],
15499                                row[0],
15500                                row[1],
15501                                ids.len(),
15502                                &ids[..ids.len().min(8)]
15503                            );
15504                        }
15505                    }
15506                }
15507            }
15508        };
15509        let (_nkv, _hd, _rd, eps) = (
15510            self.num_kv_heads,
15511            self.head_dim,
15512            self.rotary_dim,
15513            self.rms_eps,
15514        );
15515        let pool = self.pool.clone();
15516        let norm_style = self.norm_style;
15517        self.mimo_moe_prepare();
15518        let automatic_gpu_prefix = self.automatic_gpu_prefix();
15519
15520        #[cfg(target_os = "macos")]
15521        let mut chunk_skip_until = 0usize;
15522        // SenseNova-Loop: the chunk rows' mHC streams.
15523        let mut mhc_rs: Vec<f32> = Vec::new();
15524        for li in from..upto_excl {
15525            let _capacity_tail = automatic_gpu_prefix
15526                .filter(|&prefix| {
15527                    li >= prefix && !(self.verify_exact_moe && self.mimo_moe.is_dynamic(li, false))
15528                })
15529                .map(|_| crate::gpu::enter_cpu_scope());
15530            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU
15531            // Spark-X2.5: the layer's int8 matrix-unit GEMMs take the
15532            // `zi_mm` tile, bit-identical to the 64x64 kernel and about
15533            // three times its rate (`gpu_wgpu::zi_gemm_route`).
15534            #[cfg(feature = "gpu")]
15535            let _fast_gemm = self
15536                .proj_gate_sigmoid
15537                .then(crate::gpu::enter_prefill_fast_gemm);
15538            // GPU chunk graph (default-on under CMF_GPU=1): a run of
15539            // consecutive eligible layers for the whole chunk in ONE
15540            // Metal submission — norm, QKV, RoPE with fused mirror
15541            // append, causal attend, O, FFN, hidden device-resident
15542            // across the run. Any refusal falls through to the CPU path.
15543            #[cfg(target_os = "macos")]
15544            if task_mask.is_none() {
15545                if li < chunk_skip_until {
15546                    continue;
15547                }
15548                // Device-side embedding needs a q8_row embedding matrix;
15549                // with any other layout the CPU fills `h` first and the
15550                // graph starts from a ready hidden (refusing the whole
15551                // run over the embedding alone kept q4t models — the
15552                // whole Nanbeige/Bonsai class — on the CPU prefill).
15553                if !h_ready && li == 0 && self.weights.embed_tokens.q8_row_parts().is_none() {
15554                    fill_h(&mut h, self);
15555                    h_ready = true;
15556                }
15557                let ids_for_embed = match input {
15558                    PrefillIn::Ids(ids) => (!h_ready && li == 0).then_some(ids),
15559                    PrefillIn::Hidden(_) => None,
15560                };
15561                let end = self.chunk_run_gpu(li, &mut h, b, start_pos, ids_for_embed, upto_excl);
15562                if end > li {
15563                    h_ready = true;
15564                    chunk_skip_until = end;
15565                    // Looped Transformer: the graph stopped at a loop
15566                    // boundary — apply final norm before the next iteration.
15567                    if self.is_loop_end(end - 1) && end < self.num_layers {
15568                        for bi in 0..b {
15569                            let normed = inference::rms_norm(
15570                                &h[bi * hs..(bi + 1) * hs],
15571                                &self.weights.final_norm,
15572                                eps,
15573                                norm_style,
15574                            );
15575                            h[bi * hs..(bi + 1) * hs].copy_from_slice(&normed);
15576                        }
15577                    }
15578                    continue;
15579                }
15580            }
15581            if !h_ready {
15582                fill_h(&mut h, self);
15583                h_ready = true;
15584            }
15585            if task_mask.is_none() && self.verify_exact_moe {
15586                let positions: Vec<_> = (start_pos..start_pos + b).collect();
15587                match self.mimo_graph_layer_rows(li, &mut h, &positions) {
15588                    crate::gpu::BatchGraphOutcome::Completed => continue,
15589                    crate::gpu::BatchGraphOutcome::Failed => return h,
15590                    crate::gpu::BatchGraphOutcome::Declined => {}
15591                }
15592            }
15593            #[cfg(feature = "gpu")]
15594            self.pull_lagging_host_kv(li, li + 1, start_pos);
15595            // SenseNova-Loop mHC: every row's streams route into `h`; the
15596            // attention below adds onto that branch, so its output is the
15597            // difference from the copy kept here.
15598            let mhc_attn = self.mhc_layer(li).then(|| {
15599                let m = self.mhc.as_deref().expect("mhc layer");
15600                let p = self.phys_layer(li);
15601                let n = m.s.streams * hs;
15602                mhc_rs.resize(b * n, 0.0);
15603                let coefs: Vec<_> = (0..b)
15604                    .map(|bi| {
15605                        let r = &mut mhc_rs[bi * n..(bi + 1) * n];
15606                        if m.enters(p) {
15607                            m.enter(r, &h[bi * hs..(bi + 1) * hs]);
15608                        }
15609                        m.route(p, false, r, &mut h[bi * hs..(bi + 1) * hs])
15610                    })
15611                    .collect();
15612                (h.clone(), coefs)
15613            });
15614            let lw = &self.weights.layers[self.phys_layer(li)];
15615            let t_attn = std::time::Instant::now();
15616            // ── attention ──
15617            match &lw.attn {
15618                AttnKind::Kda(w) => {
15619                    // Projections batched, recurrence sequential.
15620                    let cfg = self.kda_cfg.expect("kda layer without kda_cfg");
15621                    let mut normed = vec![0.0f32; b * hs];
15622                    for bi in 0..b {
15623                        inference::rms_norm_into(
15624                            &h[bi * hs..(bi + 1) * hs],
15625                            &lw.input_norm,
15626                            eps,
15627                            norm_style,
15628                            &mut normed[bi * hs..(bi + 1) * hs],
15629                        );
15630                    }
15631                    let attn = crate::linear_core::kda_forward_batch(
15632                        &normed,
15633                        b,
15634                        w,
15635                        &cfg,
15636                        &mut self.kv_cache.layers[li].linear_state,
15637                        pool.as_deref(),
15638                    );
15639                    for (dst, &a) in h.iter_mut().zip(&attn) {
15640                        *dst += a;
15641                    }
15642                }
15643                AttnKind::LinearGdn(w) => {
15644                    // Projections batched, recurrence sequential.
15645                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
15646                    let mut normed = vec![0.0f32; b * hs];
15647                    for bi in 0..b {
15648                        let r = inference::rms_norm(
15649                            &h[bi * hs..(bi + 1) * hs],
15650                            &lw.input_norm,
15651                            eps,
15652                            norm_style,
15653                        );
15654                        normed[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
15655                    }
15656                    let attn = crate::linear_core::gdn_forward_batch(
15657                        &normed,
15658                        b,
15659                        w,
15660                        &cfg,
15661                        &mut self.kv_cache.layers[li].linear_state,
15662                        pool.as_deref(),
15663                    );
15664                    for (dst, &a) in h.iter_mut().zip(&attn) {
15665                        *dst += a;
15666                    }
15667                }
15668                AttnKind::ShortConv(w) => {
15669                    // Projections batched over the chunk; the conv walks the
15670                    // contiguous positions in order (same ring as decode).
15671                    let cfg = self
15672                        .short_conv_cfg
15673                        .expect("short-conv layer without short_conv_cfg");
15674                    let mut normed = vec![0.0f32; b * hs];
15675                    for bi in 0..b {
15676                        inference::rms_norm_into(
15677                            &h[bi * hs..(bi + 1) * hs],
15678                            &lw.input_norm,
15679                            eps,
15680                            norm_style,
15681                            &mut normed[bi * hs..(bi + 1) * hs],
15682                        );
15683                    }
15684                    let mut attn = short_conv_forward_batch(
15685                        &normed,
15686                        b,
15687                        w,
15688                        &cfg,
15689                        &mut self.kv_cache.layers[li].linear_state,
15690                        pool.as_deref(),
15691                    );
15692                    // LFM3 sandwich: the mixer output is normalized before
15693                    // the residual, as on the decode path.
15694                    if let Some(wn) = &lw.attn_out_norm {
15695                        for bi in 0..b {
15696                            inference::rms_norm_into(
15697                                &attn[bi * hs..(bi + 1) * hs],
15698                                wn,
15699                                eps,
15700                                norm_style,
15701                                &mut normed[bi * hs..(bi + 1) * hs],
15702                            );
15703                        }
15704                        attn.copy_from_slice(&normed);
15705                    }
15706                    for (dst, &a) in h.iter_mut().zip(&attn) {
15707                        *dst += a;
15708                    }
15709                }
15710                AttnKind::Mla(w) => {
15711                    // Per-position prefill (correctness first; latent
15712                    // batching is a later optimization).
15713                    let inv_freq_l = self.layer_inv_freq(li);
15714                    let rs = self.layer_rope_scale(li);
15715                    let mut normed = vec![0.0f32; hs];
15716                    for bi in 0..b {
15717                        inference::rms_norm_into(
15718                            &h[bi * hs..(bi + 1) * hs],
15719                            &lw.input_norm,
15720                            eps,
15721                            norm_style,
15722                            &mut normed,
15723                        );
15724                        let ao = mla_attention(
15725                            w,
15726                            &normed,
15727                            &mut self.kv_cache.layers[li],
15728                            start_pos + bi,
15729                            &inv_freq_l,
15730                            rs,
15731                            eps,
15732                            pool.as_deref(),
15733                        );
15734                        for (dst, &a) in h[bi * hs..(bi + 1) * hs].iter_mut().zip(&ao) {
15735                            *dst += a;
15736                        }
15737                    }
15738                }
15739                AttnKind::Full {
15740                    wq,
15741                    wk,
15742                    wv,
15743                    wo,
15744                    q_norm,
15745                    k_norm,
15746                    output_gate,
15747                    softplus_gate,
15748                    bias,
15749                } => {
15750                    // Chunk-GEMM QKV/O; per-position causal attention
15751                    // inside (roadmap §3 P0 — full-attention prefill no
15752                    // longer re-reads the projection weights b times).
15753                    let mut normed = vec![0.0f32; b * hs];
15754                    for bi in 0..b {
15755                        inference::rms_norm_into(
15756                            &h[bi * hs..(bi + 1) * hs],
15757                            &lw.input_norm,
15758                            eps,
15759                            norm_style,
15760                            &mut normed[bi * hs..(bi + 1) * hs],
15761                        );
15762                    }
15763                    // The rows V projects, when the layer blends the embeddings into them.
15764                    let vres = match self.layer_value_blend(li) {
15765                        Some(blend) => {
15766                            vres_lerp(&self.vres_e0, &normed, blend, &mut self.vres_in);
15767                            true
15768                        }
15769                        None => false,
15770                    };
15771                    let inv_freq_l = self.layer_inv_freq(li);
15772                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
15773                    let cfg = QwenAttnCfg {
15774                        mrope: self.prompt_mrope.as_deref().zip(self.mrope_sections).map(|(pos, sections)| attention::MropeView { base: 0, pos, sections }),
15775                        num_heads: self.layer_num_heads(li),
15776                        num_kv_heads: nkv_l,
15777                        head_dim: hd_l,
15778                        hidden_size: hs,
15779                        position: start_pos,
15780                        inv_freq: &inv_freq_l,
15781                        rotary_dim: rd_l,
15782                        scale: self.attn_scale,
15783                        softcap: self.attn_softcap,
15784                        window: self.layer_window(li),
15785                        v_norm: self.attn_v_norm,
15786                        qk_norm_after_rope: self.qk_norm_after_rope,
15787                        gate_sigmoid: self.proj_gate_sigmoid,
15788                        q_norm: q_norm.as_deref(),
15789                        k_norm: k_norm.as_deref(),
15790                        output_gate: *output_gate,
15791                        softplus_gate: softplus_gate
15792                            .as_ref()
15793                            .map(|(gate, per_head)| (gate, *per_head)),
15794                        rope_scale: self.layer_rope_scale(li),
15795                        bias: bias
15796                            .as_ref()
15797                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
15798                        rms_eps: eps,
15799                        norm_style,
15800                        pool: pool.as_deref(),
15801                        v_head_dim: self.layer_v_dim(li),
15802                        value_in: vres.then(|| self.vres_in.as_slice()),
15803                    };
15804                    #[cfg(feature = "gpu")]
15805                    let _mirror = self
15806                        .prefill_mirror_target(li)
15807                        .map(crate::gpu::enter_prefill_mirror);
15808                    let mut attn = attention::qwen_attention_batch(
15809                        &normed,
15810                        b,
15811                        wq,
15812                        wk,
15813                        wv,
15814                        wo,
15815                        &mut self.kv_cache.layers[li],
15816                        &cfg,
15817                    );
15818                    if let Some(w) = &lw.attn_out_norm {
15819                        for bi in 0..b {
15820                            inference::rms_norm_into(
15821                                &attn[bi * hs..(bi + 1) * hs],
15822                                w,
15823                                eps,
15824                                norm_style,
15825                                &mut normed[bi * hs..(bi + 1) * hs],
15826                            );
15827                        }
15828                        attn.copy_from_slice(&normed);
15829                    }
15830                    for (dst, &a) in h.iter_mut().zip(&attn) {
15831                        *dst += a;
15832                    }
15833                }
15834                AttnKind::Bounded(w) => {
15835                    // Chunk-GEMM projections, the bounded operator per
15836                    // position over ring + chunk — never a growing KV.
15837                    let mut normed = vec![0.0f32; b * hs];
15838                    for bi in 0..b {
15839                        inference::rms_norm_into(
15840                            &h[bi * hs..(bi + 1) * hs],
15841                            &lw.input_norm,
15842                            eps,
15843                            norm_style,
15844                            &mut normed[bi * hs..(bi + 1) * hs],
15845                        );
15846                    }
15847                    let rope = self
15848                        .bounded_rope
15849                        .clone()
15850                        .expect("bounded layer without an installed rotation table");
15851                    let cfg = crate::bounded::BoundedAttnCfg {
15852                        num_heads: self.num_heads,
15853                        num_kv_heads: self.num_kv_heads,
15854                        head_dim: self.head_dim,
15855                        hidden_size: hs,
15856                        scale: self.attn_scale,
15857                        rope: &rope,
15858                        pool: pool.as_deref(),
15859                    };
15860                    let mut attn = crate::bounded::bounded_attention_batch(
15861                        &normed,
15862                        b,
15863                        w,
15864                        &mut self.kv_cache.layers[li],
15865                        &cfg,
15866                    );
15867                    if let Some(wn) = &lw.attn_out_norm {
15868                        for bi in 0..b {
15869                            inference::rms_norm_into(
15870                                &attn[bi * hs..(bi + 1) * hs],
15871                                wn,
15872                                eps,
15873                                norm_style,
15874                                &mut normed[bi * hs..(bi + 1) * hs],
15875                            );
15876                        }
15877                        attn.copy_from_slice(&normed);
15878                    }
15879                    for (dst, &a) in h.iter_mut().zip(&attn) {
15880                        *dst += a;
15881                    }
15882                    attention::recycle_buf(&mut attn);
15883                }
15884                AttnKind::Linear(w) => {
15885                    for bi in 0..b {
15886                        let normed = inference::rms_norm(
15887                            &h[bi * hs..(bi + 1) * hs],
15888                            &lw.input_norm,
15889                            eps,
15890                            norm_style,
15891                        );
15892                        vmf_phase_forward(
15893                            &normed,
15894                            w,
15895                            &self.vmf_cfg.expect("linear layer without vmf_cfg"),
15896                            &mut self.kv_cache.layers[li].linear_state,
15897                            pool.as_deref(),
15898                        )
15899                        .iter()
15900                        .enumerate()
15901                        .for_each(|(i, &a)| h[bi * hs + i] += a);
15902                    }
15903                }
15904            }
15905
15906            // mHC: fold the attention output into the streams, route the
15907            // FFN's branch.
15908            let mhc_ffn = mhc_attn.map(|(branch, coefs)| {
15909                let m = self.mhc.as_deref().expect("mhc layer");
15910                let p = self.phys_layer(li);
15911                let n = m.s.streams * hs;
15912                let mut y = vec![0f32; hs];
15913                (0..b)
15914                    .map(|bi| {
15915                        for (e, v) in y.iter_mut().enumerate() {
15916                            *v = h[bi * hs + e] - branch[bi * hs + e];
15917                        }
15918                        let r = &mut mhc_rs[bi * n..(bi + 1) * n];
15919                        m.merge(r, &y, &coefs[bi]);
15920                        m.route(p, true, r, &mut h[bi * hs..(bi + 1) * hs])
15921                    })
15922                    .collect::<Vec<_>>()
15923            });
15924            // ── FFN batched ──
15925            let lw = &self.weights.layers[self.phys_layer(li)];
15926            let mut post = vec![0.0f32; b * hs];
15927            for bi in 0..b {
15928                let r =
15929                    inference::rms_norm(&h[bi * hs..(bi + 1) * hs], &lw.post_norm, eps, norm_style);
15930                post[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
15931            }
15932            // A restrictive per-visit FFN row lands on the activations
15933            // inside the dense arm; an all-open row costs nothing.
15934            let mask_row = task_mask
15935                .filter(|m| m.ffn_active_count(li) < self.intermediate_size)
15936                .and_then(|m| m.ffn_masks.get(li))
15937                .map(|v| v.as_slice());
15938            let attn_ns = t_attn.elapsed().as_nanos() as u64;
15939            let t_ffn = std::time::Instant::now();
15940            let mut ffn = match &lw.ffn {
15941                FfnKind::Dense(d) if !d.segs.is_empty() => {
15942                    tube_ffn(d, &post, b, pool.as_deref(), mask_row)
15943                }
15944                FfnKind::Dense(d) => dense_ffn_batch(d, &post, b, pool.as_deref(), mask_row),
15945                FfnKind::Moe(m) if self.verify_exact_moe && self.mimo_moe.is_dynamic(li, false) => {
15946                    moe_ffn_banked_rows(&mut self.mimo_moe, li, m, &post, b, hs, pool.as_deref())
15947                }
15948                FfnKind::Moe(m) if self.verify_exact_moe => {
15949                    moe_ffn_rows_exact(m, &post, b, hs, pool.as_deref())
15950                }
15951                // Keep prompt expert panels off the projection arena and
15952                // use their routes to prime the model-wide bank.
15953                FfnKind::Moe(m) if self.mimo_moe.is_dynamic(li, false) => {
15954                    let before = m.stats.borrow().clone();
15955                    let out = crate::gpu::cpu_scope(|| {
15956                        moe_ffn_batch(m, &post, b, hs, pool.as_deref(), None)
15957                    });
15958                    self.mimo_moe.prime(li, m, &before);
15959                    out
15960                }
15961                FfnKind::Moe(m) => moe_ffn_batch(m, &post, b, hs, pool.as_deref(), None),
15962                // Dual-branch layers run per position (the expert branch
15963                // reads the raw residual — nothing to batch yet).
15964                FfnKind::DenseMoe(dm) => {
15965                    let mut out = vec![0.0f32; b * hs];
15966                    for bi in 0..b {
15967                        let r = dense_moe_ffn(
15968                            dm,
15969                            &post[bi * hs..(bi + 1) * hs],
15970                            &h[bi * hs..(bi + 1) * hs],
15971                            eps,
15972                            norm_style,
15973                            pool.as_deref(),
15974                        );
15975                        out[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
15976                    }
15977                    out
15978                }
15979            };
15980            if prefill_prof_on() {
15981                PREFILL_SPLIT[0].fetch_add(attn_ns, std::sync::atomic::Ordering::Relaxed);
15982                PREFILL_SPLIT[1].fetch_add(
15983                    t_ffn.elapsed().as_nanos() as u64,
15984                    std::sync::atomic::Ordering::Relaxed,
15985                );
15986            }
15987            if let Some(w) = &lw.ffn_out_norm {
15988                for bi in 0..b {
15989                    inference::rms_norm_into(
15990                        &ffn[bi * hs..(bi + 1) * hs],
15991                        w,
15992                        eps,
15993                        norm_style,
15994                        &mut post[bi * hs..(bi + 1) * hs],
15995                    );
15996                }
15997                ffn.copy_from_slice(&post);
15998            }
15999            if let Some(coefs) = mhc_ffn {
16000                // mHC: fold the FFN output in; the range's last layer hands
16001                // the streams' mean on as the hidden.
16002                let m = self.mhc.as_deref().expect("mhc layer");
16003                let p = self.phys_layer(li);
16004                let n = m.s.streams * hs;
16005                for bi in 0..b {
16006                    let r = &mut mhc_rs[bi * n..(bi + 1) * n];
16007                    m.merge(r, &ffn[bi * hs..(bi + 1) * hs], &coefs[bi]);
16008                    if m.leaves(p) {
16009                        m.leave(r, &mut h[bi * hs..(bi + 1) * hs]);
16010                    }
16011                }
16012            } else {
16013                for (dst, &f) in h.iter_mut().zip(&ffn) {
16014                    *dst += f;
16015                }
16016            }
16017            if let Some(sc) = lw.layer_scale {
16018                for v in h.iter_mut() {
16019                    *v *= sc;
16020                }
16021            }
16022            // CMF_LAYER_DUMP: every position's hidden after layer li.
16023            if self.layer_dump.is_some() {
16024                for bi in 0..b {
16025                    self.dump_layer_row(start_pos + bi, li, &h[bi * hs..(bi + 1) * hs]);
16026                }
16027            }
16028            if let Ok(tp) = std::env::var("CMF_TRACE_POS") {
16029                if let Ok(t) = tp.parse::<usize>() {
16030                    if t >= start_pos && t < start_pos + b {
16031                        let bi = t - start_pos;
16032                        let row = &h[bi * hs..(bi + 1) * hs];
16033                        let n: f32 = row.iter().map(|x| x * x).sum::<f32>().sqrt();
16034                        eprintln!(
16035                            "BATCH pos {t} after layer {li}: |h| = {n:.6} h0 {:.6} h1 {:.6}",
16036                            row[0], row[1]
16037                        );
16038                    }
16039                }
16040            }
16041            // CMF_DEBUG_LAYERS=1: per-layer hidden-state health of the
16042            // LAST prompt position — the knife for "which layer type
16043            // breaks first" on a new architecture.
16044            if std::env::var("CMF_DEBUG_LAYERS").is_ok() {
16045                let row = &h[(b - 1) * hs..b * hs];
16046                let rms =
16047                    (row.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / hs as f64).sqrt();
16048                let mx = row.iter().fold(0f32, |m, &v| m.max(v.abs()));
16049                eprintln!(
16050                    "layer {li:>3} {:>10} ffn={:<5} rms={rms:>12.4} max={mx:>12.4}",
16051                    match &self.weights.layers[self.phys_layer(li)].attn {
16052                        AttnKind::LinearGdn(_) => "gdn",
16053                        AttnKind::Linear(_) => "vmf",
16054                        AttnKind::ShortConv(_) => "conv",
16055                        _ => "attn",
16056                    },
16057                    match &lw.ffn {
16058                        FfnKind::Moe(_) => "moe",
16059                        FfnKind::Dense(_) => "dense",
16060                        FfnKind::DenseMoe(_) => "dense+moe",
16061                    },
16062                );
16063            }
16064            // Looped Transformer: apply final norm at the end of each loop iteration.
16065            if self.is_loop_end(li) && li + 1 < self.num_layers {
16066                for bi in 0..b {
16067                    let normed = inference::rms_norm(
16068                        &h[bi * hs..(bi + 1) * hs],
16069                        &self.weights.final_norm,
16070                        eps,
16071                        norm_style,
16072                    );
16073                    h[bi * hs..(bi + 1) * hs].copy_from_slice(&normed);
16074                }
16075            }
16076            if std::env::var("CMF_TRACE_H").is_ok() {
16077                let n = h[..hs].iter().map(|v| v.abs()).sum::<f32>() / hs as f32;
16078                let mx = h[..hs].iter().fold(0.0f32, |a, &v| a.max(v.abs()));
16079                eprintln!(
16080                    "layer {li}: mean|h|={n:.4} max|h|={mx:.2} scale={:?}",
16081                    lw.layer_scale
16082                );
16083            }
16084        }
16085        crate::gpu::set_layer(-1); // lm_head/final ops outside layer-split
16086        if prefill_prof_on() {
16087            let ms = |a: &std::sync::atomic::AtomicU64| {
16088                a.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6
16089            };
16090            let sp = &attention::ATTN_SPLIT;
16091            let (qkv_enq, qkv_wait, ca_wait, zi) = wgpu_prefill_counters();
16092            eprintln!(
16093                "prefill-split: attention {:.1} ms (proj {:.1} [qkv enqueue {:.1} wait {:.1}, \
16094                 host gate {:.1}], host loop {:.1}, attend {:.1} \
16095                 [q pack {:.1}, device {:.1} of which readback {:.1}], o-proj {:.1}), \
16096                 ffn {:.1} ms (cumulative; zi_mm GEMMs {zi})",
16097                ms(&PREFILL_SPLIT[0]),
16098                ms(&sp[0]),
16099                qkv_enq,
16100                qkv_wait,
16101                ms(&sp[6]),
16102                ms(&sp[1]),
16103                ms(&sp[2]),
16104                ms(&sp[4]),
16105                ms(&sp[5]),
16106                ca_wait,
16107                ms(&sp[3]),
16108                ms(&PREFILL_SPLIT[1]),
16109            );
16110            let [calls, attended, wo, ring, reseed, f16] = wgpu_mirror_counters();
16111            eprintln!(
16112                "prefill-mirror: {calls} calls, {attended} attended ({wo} with O on the card), \
16113                 {ring} ring refusals, {reseed} reseeds, {f16} f16 fallbacks, {} upload \
16114                 fallbacks (cumulative)",
16115                attention::MIRROR_UPLOADS.load(std::sync::atomic::Ordering::Relaxed),
16116            );
16117        }
16118        // A batched span owns a complete set of positions. Publish any
16119        // collecting→sealed transition only after every layer has finished;
16120        // callers that cross into serial/device work must see the new epoch
16121        // before this function returns.
16122        self.o1_progress();
16123        // Every layer of the chunk has appended and attended its rows.
16124        self.swa_trim_tails();
16125        h
16126    }
16127
16128    /// Embed a single token.
16129    fn embed_single(&self, id: u32) -> Vec<f32> {
16130        let mut out = vec![0.0f32; self.hidden_size];
16131        if (id as usize) < self.weights.embed_tokens.rows() {
16132            self.weights.embed_tokens.row_f32(id as usize, &mut out);
16133        }
16134        if self.embed_multiplier != 1.0 {
16135            for v in out.iter_mut() {
16136                *v *= self.embed_multiplier;
16137            }
16138        }
16139        // DeepSeek-V4's hash layers route by TOKEN ID, so the id has to
16140        // reach the forward. It rides in slot 0 (the forward re-reads the
16141        // real embedding itself from the table).
16142        if self.dsv4.is_some() || self.dsv41.is_some() || self.dory.is_some() || self.qwen4_exp.is_some() || self.glm5_next.is_some() || self.hy4.is_some() || self.maxwell.is_some() || self.inkling.is_some() {
16143            let mut v = vec![0.0f32; self.hidden_size.max(1)];
16144            v[0] = id as f32;
16145            return v;
16146        }
16147        // Gemma-3n: the per-layer-embedding half needs the token ID, so
16148        // it rides appended to the embedding; the g3n forward splits it.
16149        // Gemma-4 E-series PLE: same contract, its own table.
16150        if let Some(b) = &self.g4e {
16151            return b.0.extend_embedding(id, &out, self.pool.as_deref());
16152        }
16153        if let Some(b) = &self.g3n {
16154            return b.0.extend_embedding(id, &out, self.pool.as_deref());
16155        }
16156        out
16157    }
16158
16159    /// A run of consecutive prefill layers on the GPU for the whole
16160    /// chunk (default-on under CMF_GPU=1; CMF_GPU_CHUNK=0 disables).
16161    /// Eligibility per layer: q8_row weights, plain full attention
16162    /// (no output gate), F32 KV, no o1/masks/gemma extras. Returns the
16163    /// first layer index NOT processed (== `li0` when the run is empty).
16164    #[cfg(target_os = "macos")]
16165    fn chunk_run_gpu(
16166        &mut self,
16167        li0: usize,
16168        h: &mut [f32],
16169        b: usize,
16170        pos0: usize,
16171        embed_ids: Option<&[u32]>,
16172        cap: usize,
16173    ) -> usize {
16174        // (The old streaming attend needed a depth bound at ~1k; the
16175        // GEMM attention scales like the CPU path and lifted it.)
16176        // CMF_GPU_CHUNK=0 disables the graph.
16177        // Gemma-4 (`metal_gemma4`) brings its own kernels for the global
16178        // layers, V norm, attention scale and sandwich (`ChunkGemma4`).
16179        // `CMF_METAL_GEMMA4_CHUNK=0` keeps its prompt on the host walk.
16180        let gemma4 =
16181            self.metal_gemma4() && std::env::var("CMF_METAL_GEMMA4_CHUNK").as_deref() != Ok("0");
16182        if !crate::gpu::enabled_here()
16183            || std::env::var("CMF_GPU_CHUNK")
16184                .map(|v| v == "0")
16185                .unwrap_or(false)
16186            || (b < self.chunk_min_rows && self.dash.is_none() && !self.o1_chunk_prefix)
16187            // MRoPE rows rotate on the host (`attention::MropeView`).
16188            || self.prompt_mrope.is_some()
16189            // V with rows of its own (Ripple's value residual) stays on the host walk.
16190            || self.value_blend.is_some()
16191            // Sliding windows with per-layer RoPE ride the chunk graph
16192            // (`metal_graph_swa`: causal_softmax_win, per-layer tables).
16193            || (self.swa.is_some() && !self.metal_graph_swa() && !gemma4)
16194            || (self.global_attn.is_some() && !gemma4)
16195            // Chunk attention has no value-less learned-sink column. q1
16196            // decode can carry it through ordinary `gqa_attend`, but prompt
16197            // chunks must stay on the exact host attention path.
16198            || self.kv_cache.layers.iter().any(|l| l.sinks.is_some())
16199            // Per-layer KV heads and narrow V remain outside this chunk
16200            // graph (the q1 sliding-native door checks the same geometry).
16201            || (self.graph_attn_decline_reason().is_some() && !self.metal_graph_swa() && !gemma4)
16202            // Collection owns the exact Q trace and boundary conversion;
16203            // this chunk graph appends dense KV without feeding that trace,
16204            // but for a far field's exact prefix, where it keeps the queries.
16205            || (self.o1_active() && !self.o1_chunk_prefix)
16206            || (self.attn_v_norm && !gemma4)
16207            || !self.metal_rope_scale_ok()
16208            || ((self.attn_scale - 1.0 / (self.head_dim as f32).sqrt()).abs() > 1e-9 && !gemma4)
16209        {
16210            return li0;
16211        }
16212        let Some(model) = self.model.clone() else {
16213            return li0;
16214        };
16215        let (nh, nkv, hd, hs) = (
16216            self.num_heads,
16217            self.num_kv_heads,
16218            self.head_dim,
16219            self.hidden_size,
16220        );
16221        // Collect the longest run of consecutive eligible layers.
16222        // Looped Transformer: stop at the loop boundary so the CPU can
16223        // apply loop_final_norm between iterations.
16224        let loop_end = if self.loop_final_norm {
16225            ((li0 / self.physical_layers) + 1) * self.physical_layers
16226        } else {
16227            self.num_layers
16228        };
16229        let run_end = self.num_layers.min(loop_end).min(cap);
16230        // Each layer's own RoPE table (Spark-X2.5: sliding and full layers
16231        // differ); the global one for every model without sliding layers.
16232        // Declared before `layers`, which borrows it (and drops a routing
16233        // closure on MoE layers).
16234        let tables: Vec<std::sync::Arc<Vec<f32>>> =
16235            (li0..run_end).map(|li| self.layer_inv_freq(li)).collect();
16236        let mut layers: Vec<crate::gpu_metal::ChunkLayer> = Vec::new();
16237        let mut stored_at: Vec<usize> = Vec::new();
16238        for li in li0..run_end {
16239            if self.mhc_layer(li) {
16240                break;
16241            }
16242            let lw = &self.weights.layers[self.phys_layer(li)];
16243            if (lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some())
16244                && !gemma4
16245            {
16246                break;
16247            }
16248            let AttnKind::Full {
16249                wq,
16250                wk,
16251                wv,
16252                wo,
16253                q_norm,
16254                k_norm,
16255                output_gate: false,
16256                softplus_gate,
16257                bias,
16258            } = &lw.attn
16259            else {
16260                break;
16261            };
16262            // Spark-X2.5's per-head sigmoid g_proj gate, from f32 rows.
16263            let head_gate = match softplus_gate {
16264                None => None,
16265                Some((g, true)) if self.proj_gate_sigmoid => match g.f32_parts() {
16266                    Some((d, r, c)) if r == nh && c == hs => Some(d),
16267                    _ => break,
16268                },
16269                Some(_) => break,
16270            };
16271            // The FFN: a dense SiLU/GELU trio, or routed q4tp experts
16272            // (Mellum2.1: softmax router, no shared expert) whose first
16273            // trio stands in for the shape checks.
16274            let (gate_t, up_t, down_t, ffn_act, moe) = match &lw.ffn {
16275                FfnKind::Dense(d)
16276                    if (matches!(d.act, Act::Silu | Act::Gelu)
16277                        || (gemma4 && d.act == Act::GeluTanh))
16278                        && d.segs.is_empty() =>
16279                {
16280                    (&d.gate_proj, &d.up_proj, &d.down_proj, d.act, None)
16281                }
16282                FfnKind::Moe(m) => match chunk_moe_parts(m, hs) {
16283                    Some((router, experts, q8)) => {
16284                        let e0 = &m.experts[0];
16285                        let route = Box::new(move |lg: &[f32]| {
16286                            // `moe_ffn_batch`'s routing and weights, row by row.
16287                            let (idx, p, wsum) = moe_route(lg, m, None);
16288                            let mut st = m.stats.borrow_mut();
16289                            if st.len() < m.experts.len() {
16290                                st.resize(m.experts.len(), 0);
16291                            }
16292                            for &e in &idx {
16293                                st[e] += 1;
16294                            }
16295                            let w = idx.iter().map(|&e| p[e] / wsum).collect();
16296                            (idx, w)
16297                        });
16298                        let detached = m.shared.as_ref().map(|(s, _)| {
16299                            let t = |x: &QTensor| {
16300                                x.q8_2f_parts().map(|p| p.0).or_else(|| x.q4tp_parts().map(|p| p.0)).unwrap_or(usize::MAX)
16301                            };
16302                            ([t(&s.gate_proj), t(&s.up_proj), t(&s.down_proj)], s.gate_proj.rows())
16303                        });
16304                        (
16305                            &e0.gate_proj,
16306                            &e0.up_proj,
16307                            &e0.down_proj,
16308                            Act::Silu,
16309                            Some(crate::gpu_metal::ChunkMoe {
16310                                router,
16311                                experts,
16312                                q8,
16313                                route,
16314                                detached,
16315                            }),
16316                        )
16317                    }
16318                    None => break,
16319                },
16320                _ => break,
16321            };
16322            // q8_row (row_scale populated), q8_2f (plus its input field),
16323            // or q4_tiled / q4tp (row_scale empty — their scales are in the
16324            // payload). Mixing across the seven projections of one layer is
16325            // fine; the encoder branches per weight on the tensor's dtype.
16326            // Anything else refuses.
16327            fn cw(t: &QTensor) -> Option<(usize, usize, usize, &[f32])> {
16328                t.q8_row_parts()
16329                    .or_else(|| t.q8_2f_parts().map(|(i, r, c, rs, _)| (i, r, c, rs)))
16330                    .or_else(|| t.q4t_parts().map(|(i, r, c)| (i, r, c, &[][..])))
16331                    .or_else(|| t.q4tp_parts().map(|(i, r, c)| (i, r, c, &[][..])))
16332            }
16333            fn cf(t: &QTensor) -> &[f32] {
16334                t.q8_2f_parts().map_or(&[][..], |(_, _, _, _, cf)| cf)
16335            }
16336            let col = [cf(wq), cf(wk), cf(wv), cf(wo)];
16337            let ffn_col = [cf(gate_t), cf(up_t), cf(down_t)];
16338            // q8_2f projections ride the chunk graph on the MoE layers it
16339            // was measured on (Mellum2.1) and on the dense exact-GELU FFN
16340            // (Spark-X2.6-4B q8_2f on the M4: the gate/up inputs staged as
16341            // x·col, the down field applied after the activation —
16342            // `ChunkLayer::ffn_col`). A dense SiLU q8_2f stack keeps the host
16343            // walk: its down GEMM fuses the activation into the X-tile load
16344            // and has no input field (0.8.14 refused every q8_2f weight here).
16345            // Gemma-4 reads every q8_2f weight through the blob GEMM with its
16346            // own field (`ChunkGemma4`), so its dense q8_2f stack rides.
16347            if moe.is_none()
16348                && !gemma4
16349                && self.dash.is_none()
16350                && ffn_act != Act::Gelu
16351                && (col.iter().any(|c| !c.is_empty()) || ffn_col.iter().any(|c| !c.is_empty()))
16352            {
16353                break;
16354            }
16355            let parts = (
16356                cw(wq),
16357                cw(wk),
16358                cw(wv),
16359                cw(wo),
16360                cw(gate_t),
16361                cw(up_t),
16362                cw(down_t),
16363            );
16364            let (Some(pq), Some(pk), Some(pv), Some(po), Some(pg), Some(pu), Some(pd)) = parts
16365            else {
16366                break;
16367            };
16368            let layer = &self.kv_cache.layers[li];
16369            if layer.mode != crate::kv_cache::KvMode::F32
16370                || (layer.o1.is_some() && !(self.o1_chunk_prefix && layer.o1_is_collecting()))
16371            {
16372                break;
16373            }
16374            // A trimmed tail holds every row the chunk's first query reads.
16375            debug_assert!(
16376                layer.base() == 0
16377                    || self
16378                        .layer_window(li)
16379                        .is_some_and(|w| layer.head_len(0) + 1 >= w)
16380            );
16381            stored_at.push(layer.head_len(0));
16382            // Per-layer geometry for Gemma-4 (512-wide global layers over
16383            // one KV head); every other model keeps the pipeline-wide one.
16384            let (nkv, hd) = if gemma4 {
16385                let (a, bb, _) = self.layer_geom(li);
16386                (a, bb)
16387            } else {
16388                (nkv, hd)
16389            };
16390            layers.push(crate::gpu_metal::ChunkLayer {
16391                model: &model,
16392                kv_id: self.graph_kv_id,
16393                layer: li,
16394                wq: pq,
16395                wk: pk,
16396                wv: pv,
16397                wo: po,
16398                gate: pg,
16399                up: pu,
16400                down: pd,
16401                input_norm: &lw.input_norm,
16402                post_norm: &lw.post_norm,
16403                bias: bias
16404                    .as_ref()
16405                    .map(|(a, bb, cc)| (a.as_slice(), bb.as_slice(), cc.as_slice())),
16406                q_norm: q_norm.as_deref(),
16407                k_norm: k_norm.as_deref(),
16408                inv_freq: &tables[li - li0],
16409                rope_scale: self.layer_rope_scale(li),
16410                rd: self.layer_geom(li).2,
16411                nh,
16412                nkv,
16413                hd,
16414                hs,
16415                inter: gate_t.rows(),
16416                gemma: matches!(self.norm_style, cortiq_core::NormStyle::Gemma),
16417                late_qk_norm: self.qk_norm_after_rope,
16418                eps: self.rms_eps as f32,
16419                window: self.layer_window(li),
16420                head_gate,
16421                act: ffn_act.graph_act().map_or(0, |a| a.code() as u8),
16422                g4: gemma4.then(|| crate::gpu_metal::ChunkGemma4 {
16423                    v_norm: self.attn_v_norm,
16424                    scale: self.attn_scale,
16425                    attn_out_norm: lw.attn_out_norm.as_deref(),
16426                    ffn_out_norm: lw.ffn_out_norm.as_deref(),
16427                    layer_scale: lw.layer_scale,
16428                }),
16429                col,
16430                // The plain dense branch alone reads it: routed experts and
16431                // Gemma-4 carry their own fields.
16432                ffn_col: if moe.is_none() && !gemma4 {
16433                    ffn_col
16434                } else {
16435                    [&[][..]; 3]
16436                },
16437                moe,
16438                dash: self.graph_dash(li),
16439            });
16440        }
16441        if layers.is_empty() {
16442            return li0;
16443        }
16444        // Unlimited-OCR: all of it or none of it (the router state).
16445        if self.dash.is_some() && (li0 != 0 || layers.len() != self.num_layers) {
16446            return li0;
16447        }
16448        // KV row width per layer (uniform but for Gemma-4).
16449        let rows_kv: Vec<(usize, usize)> = layers.iter().map(|l| (l.nkv, l.nkv * l.hd)).collect();
16450        let mut store: Vec<(Vec<f32>, Vec<f32>, Vec<f32>)> = stored_at
16451            .iter()
16452            .zip(&rows_kv)
16453            .map(|(&st, &(_, row))| (vec![0f32; b * row], vec![0f32; b * row], vec![0f32; st + b]))
16454            .collect();
16455        let mut io: Vec<crate::gpu_metal::ChunkIo> = Vec::with_capacity(layers.len());
16456        for (i, (ok, ov, oi)) in store.iter_mut().enumerate() {
16457            let li = layers[i].layer;
16458            let layer = &self.kv_cache.layers[li];
16459            let nkv = rows_kv[i].0;
16460            io.push(crate::gpu_metal::ChunkIo {
16461                cpu_stored: stored_at[i],
16462                cpu_gen: layer.generation(),
16463                cpu_k: (0..nkv).map(|g| layer.head_keys(g)).collect(),
16464                cpu_v: (0..nkv).map(|g| layer.head_values(g)).collect(),
16465                out_k: ok,
16466                out_v: ov,
16467                imp: oi,
16468            });
16469        }
16470        let n_run = layers.len();
16471        let last = layers.last().map(|l| l.layer + 1).unwrap_or(li0);
16472        // Device-side embedding when the run starts the model and the
16473        // embedding matrix is q8_row-mapped.
16474        let ep = embed_ids.and_then(|ids| {
16475            self.weights
16476                .embed_tokens
16477                .q8_row_parts()
16478                .map(|(idx, rows, _c, rs)| crate::gpu_metal::ChunkEmbed {
16479                    idx,
16480                    rows,
16481                    row_scale: rs,
16482                    ids,
16483                    mult: self.embed_multiplier,
16484                })
16485        });
16486        if embed_ids.is_some() && ep.is_none() {
16487            return li0;
16488        }
16489        if !crate::gpu_metal::chunk_run_gpu(&layers, &mut io, h, b, pos0, ep.as_ref()) {
16490            return li0;
16491        }
16492        drop(io);
16493        drop(layers);
16494        // CPU caches stay the owners of record: append the chunk rows
16495        // and bank the importance masses per layer.
16496        for (i, (ok, ov, oi)) in store.iter().enumerate().take(n_run) {
16497            let li = li0 + i;
16498            let row = rows_kv[i].1;
16499            let layer = &mut self.kv_cache.layers[li];
16500            for bi in 0..b {
16501                layer.append(
16502                    &ok[bi * row..(bi + 1) * row],
16503                    &ov[bi * row..(bi + 1) * row],
16504                    &[],
16505                );
16506            }
16507            layer.accumulate_imp(oi);
16508        }
16509        last
16510    }
16511
16512    /// Is layer `li` a sliding-window (local-RoPE) layer? Gemma-3:
16513    /// every `pattern`-th layer is global, the rest are local.
16514    fn layer_is_local(&self, li: usize) -> bool {
16515        if let Some(layers) = &self.sliding_layers {
16516            return layers.get(li).copied().unwrap_or(false);
16517        }
16518        match self.swa {
16519            Some((_, pattern)) => (li + 1) % pattern.max(1) != 0,
16520            None => false,
16521        }
16522    }
16523
16524    /// The RoPE table for layer `li` (local layers may have their own;
16525    /// Gemma-4 global layers use the proportional padded table).
16526    fn layer_inv_freq(&self, li: usize) -> std::sync::Arc<Vec<f32>> {
16527        if self.layer_is_local(li) {
16528            if let Some(f) = &self.inv_freq_local {
16529                return f.clone();
16530            }
16531        } else if let Some(f) = &self.inv_freq_global {
16532            return f.clone();
16533        }
16534        self.inv_freq.clone()
16535    }
16536
16537    /// Layer `li`'s value-residual blend (None = V reads the normed input).
16538    fn layer_value_blend(&self, li: usize) -> Option<f32> {
16539        self.value_blend
16540            .as_ref()
16541            .and_then(|v| v.get(self.phys_layer(li)).copied())
16542    }
16543
16544    /// The attend window for layer `li` (None = full context).
16545    fn layer_window(&self, li: usize) -> Option<usize> {
16546        self.swa
16547            .and_then(|(w, _)| self.layer_is_local(li).then_some(w))
16548    }
16549
16550    /// Drop every sliding layer's rows its window can no longer read
16551    /// (`LayerKvCache::trim_window`). Call only at a safe point — after a
16552    /// complete position / pair / chunk walk, never between a layer's
16553    /// appends and its attend. One comparison per layer below the trigger.
16554    ///
16555    /// Off with an MTP head: its verify oracles and rollbacks snapshot and
16556    /// compare per-layer row counts as positions (`CMF_METAL_VERIFY_CHECK`,
16557    /// the MTP caches), which a trimmed tail would break.
16558    fn swa_trim_tails(&mut self) {
16559        let Some((slack, align)) = self.swa_trim else {
16560            return;
16561        };
16562        if self.mtp.is_some() || self.mimo_mtp.is_some() || !self.dsv4_mtp.is_empty() {
16563            return;
16564        }
16565        for li in 0..self.num_layers.min(self.kv_cache.layers.len()) {
16566            if let Some(w) = self.layer_window(li) {
16567                self.kv_cache.layers[li].trim_window_anchored(w, slack, align, self.swa_trim_anchor);
16568            }
16569        }
16570    }
16571
16572    fn layer_num_heads(&self, li: usize) -> usize {
16573        self.attention_heads_per_layer
16574            .as_ref()
16575            .and_then(|v| v.get(li).copied())
16576            .unwrap_or(self.num_heads)
16577    }
16578
16579    fn layer_rope_scale(&self, li: usize) -> f32 {
16580        if self.layer_is_local(li) {
16581            self.rope_scale_local
16582        } else {
16583            self.rope_scale
16584        }
16585    }
16586
16587    /// Attention geometry of layer `li`: (num_kv_heads, head_dim,
16588    /// rotary_dim). Gemma-4 global layers override all three.
16589    fn layer_geom(&self, li: usize) -> (usize, usize, usize) {
16590        if !self.layer_is_local(li) {
16591            if let Some((ghd, gkv)) = self.global_attn {
16592                return (gkv, ghd, ghd);
16593            }
16594        }
16595        let rd = if self.layer_is_local(li) {
16596            self.rotary_dim_local.unwrap_or(self.rotary_dim)
16597        } else {
16598            self.rotary_dim
16599        };
16600        // A layer without positional encoding rotates nothing.
16601        let rd = if self
16602            .no_rope_layers
16603            .as_ref()
16604            .and_then(|v| v.get(li))
16605            .copied()
16606            == Some(true)
16607        {
16608            0
16609        } else {
16610            rd
16611        };
16612        (self.layer_num_kv_heads(li), self.head_dim, rd)
16613    }
16614
16615    /// KV heads of layer `li` (virtual index): the per-layer count when the
16616    /// model has one (MiMo-V2), else the uniform `num_kv_heads`.
16617    fn layer_num_kv_heads(&self, li: usize) -> usize {
16618        self.kv_heads_per_layer
16619            .as_ref()
16620            .and_then(|v| v.get(self.phys_layer(li)).copied())
16621            .unwrap_or(self.num_kv_heads)
16622    }
16623
16624    /// V head width of layer `li` (≤ its head_dim).
16625    fn layer_v_dim(&self, li: usize) -> usize {
16626        let (_, hd, _) = self.layer_geom(li);
16627        self.v_head_dim.unwrap_or(hd).min(hd)
16628    }
16629
16630    /// Install a per-layer KV geometry: KV heads per PHYSICAL layer and/or
16631    /// a V head width narrower than `head_dim` (MiMo-V2). Validates it and
16632    /// reshapes the caches of every layer whose KV head count differs from
16633    /// `num_kv_heads`. The loader and the tests share this one path, so a
16634    /// hand-built pipeline cannot hold a geometry the loader would refuse.
16635    /// Call before the first forward (it drops cached rows of reshaped
16636    /// layers). Refuses combinations whose paths would read it wrong:
16637    /// Gemma-4 global layers and MLA carry their own geometry.
16638    pub fn set_attn_geometry(
16639        &mut self,
16640        kv_heads_per_layer: Option<Vec<usize>>,
16641        v_head_dim: Option<usize>,
16642    ) -> Result<(), String> {
16643        if kv_heads_per_layer.is_some() || v_head_dim.is_some() {
16644            if self.global_attn.is_some() {
16645                return Err(
16646                    "per-layer KV heads / v_head_dim cannot combine with Gemma-4 global \
16647                     attention geometry"
16648                        .into(),
16649                );
16650            }
16651            if self
16652                .weights
16653                .layers
16654                .iter()
16655                .any(|lw| matches!(lw.attn, AttnKind::Mla(_)))
16656            {
16657                return Err("per-layer KV heads / v_head_dim cannot combine with MLA".into());
16658            }
16659        }
16660        if let Some(vd) = v_head_dim {
16661            if vd == 0 || vd > self.head_dim {
16662                return Err(format!(
16663                    "v_head_dim {vd} must be in 1..={} (head_dim)",
16664                    self.head_dim
16665                ));
16666            }
16667        }
16668        if let Some(v) = &kv_heads_per_layer {
16669            if v.len() != self.physical_layers {
16670                return Err(format!(
16671                    "kv_heads_per_layer has {} entries, expected {} layers",
16672                    v.len(),
16673                    self.physical_layers
16674                ));
16675            }
16676            for (li, &nkv) in v.iter().enumerate() {
16677                let is_attn = matches!(
16678                    self.weights.layers.get(li).map(|lw| &lw.attn),
16679                    Some(AttnKind::Full { .. }) | None
16680                );
16681                if !is_attn {
16682                    continue;
16683                }
16684                let nh = self
16685                    .attention_heads_per_layer
16686                    .as_ref()
16687                    .and_then(|h| h.get(li).copied())
16688                    .unwrap_or(self.num_heads);
16689                if nkv == 0 || nh % nkv != 0 {
16690                    return Err(format!(
16691                        "layer {li}: {nkv} KV heads must be nonzero and divide {nh} Q heads"
16692                    ));
16693                }
16694            }
16695        }
16696        self.kv_heads_per_layer = kv_heads_per_layer;
16697        self.v_head_dim = v_head_dim.filter(|&vd| vd != self.head_dim);
16698        if self.kv_heads_per_layer.is_some() {
16699            for li in 0..self.kv_cache.layers.len() {
16700                let full = matches!(
16701                    self.weights
16702                        .layers
16703                        .get(self.phys_layer(li))
16704                        .map(|lw| &lw.attn),
16705                    Some(AttnKind::Full { .. })
16706                );
16707                let nkv = self.layer_num_kv_heads(li);
16708                let cache = &self.kv_cache.layers[li];
16709                if full && (cache.num_kv_heads != nkv || cache.head_dim != self.head_dim) {
16710                    let sinks = cache.sinks.clone();
16711                    self.kv_cache.layers[li] =
16712                        crate::kv_cache::LayerKvCache::new(nkv, self.head_dim);
16713                    self.kv_cache.layers[li].sinks = sinks;
16714                }
16715            }
16716        }
16717        Ok(())
16718    }
16719
16720    /// Attach learned attention-sink logits (one per Q head) to PHYSICAL
16721    /// layer `phys` — every virtual layer that runs it. The loader calls
16722    /// this for each `model.layers.N.self_attn.sinks` tensor.
16723    pub fn set_layer_sinks(&mut self, phys: usize, sinks: Vec<f32>) -> Result<(), String> {
16724        let Some(lw) = self.weights.layers.get(phys) else {
16725            return Err(format!("sinks for layer {phys}: no such layer"));
16726        };
16727        if !matches!(lw.attn, AttnKind::Full { .. }) {
16728            return Err(format!(
16729                "sinks for layer {phys}: only softmax (Full) attention layers take sinks"
16730            ));
16731        }
16732        let nh = self
16733            .attention_heads_per_layer
16734            .as_ref()
16735            .and_then(|h| h.get(phys).copied())
16736            .unwrap_or(self.num_heads);
16737        if sinks.len() != nh {
16738            return Err(format!(
16739                "sinks for layer {phys}: {} values, expected one per Q head ({nh})",
16740                sinks.len()
16741            ));
16742        }
16743        if let Some(bad) = sinks.iter().find(|v| !v.is_finite()) {
16744            return Err(format!("sinks for layer {phys}: non-finite value {bad}"));
16745        }
16746        for li in 0..self.kv_cache.layers.len() {
16747            if self.phys_layer(li) == phys {
16748                self.kv_cache.layers[li].sinks = Some(sinks.clone());
16749            }
16750        }
16751        Ok(())
16752    }
16753
16754    /// Why the GPU attention graphs cannot serve this model, if they
16755    /// cannot: the wgpu whole-token and batched graphs, the greedy
16756    /// multi-burst, the q1 attention dropin and the Metal block/chunk/rows
16757    /// graphs all assume ONE (num_kv_heads, head_dim) geometry, V heads as
16758    /// wide as K, a single RoPE table, full-context attention and a plain
16759    /// softmax. A model outside that contract runs on the CPU layer walk
16760    /// (and the per-op GPU matvecs) until a graph learns it — never on a
16761    /// graph that would read it wrong. None = no attention-level reason
16762    /// (the graph builders still check weights and layer kinds).
16763    pub fn graph_attn_decline_reason(&self) -> Option<&'static str> {
16764        if self.kv_heads_per_layer.is_some() {
16765            return Some("per-layer KV head counts");
16766        }
16767        if self.v_head_dim.is_some_and(|vd| vd != self.head_dim) {
16768            return Some("V heads narrower than Q/K heads");
16769        }
16770        if self.kv_cache.layers.iter().any(|l| l.sinks.is_some()) {
16771            return Some("learned attention sinks");
16772        }
16773        if self.swa.is_some() || self.sliding_layers.is_some() {
16774            return Some("sliding-window layers");
16775        }
16776        None
16777    }
16778
16779    /// Can the Metal kernels apply this model's RoPE amplitude? Every
16780    /// rotation kernel (`attn_rope_qkn[_b]`, `chunk_rope_kv`) multiplies the
16781    /// rotated pair by the layer's `rope_scale` (YaRN `attention_factor`,
16782    /// Mellum2.1's global layers) exactly where the CPU's
16783    /// `rope_rotate_scaled` does. With the Q/K norm AFTER RoPE the kernels'
16784    /// shared sum of squares would be the unscaled one, so that pairing
16785    /// (no known model) declines.
16786    #[cfg(target_os = "macos")]
16787    fn metal_rope_scale_ok(&self) -> bool {
16788        !(self.qk_norm_after_rope
16789            && (0..self.num_layers).any(|li| self.layer_rope_scale(li) != 1.0))
16790    }
16791
16792    /// Can the Metal block graph carry this model's sliding-window layers?
16793    /// Both of its attention forms take a layer's own window, RoPE table
16794    /// and rotary width: the device attend (`AttnDeviceParams::window`, the
16795    /// layer's `inv_freq`/`rd`) and the sandwich's host attend (exactly the
16796    /// CPU path's attention). True when the sliding window is the model's
16797    /// only attention-level decline (Spark-X2.5). Learned, value-less
16798    /// sinks may accompany that geometry: q1's ordinary device GQA
16799    /// includes the sink in its softmax denominator and disables split-K.
16800    /// Per-layer KV heads, narrow V and Gemma-4 global geometry still
16801    /// decline; a YaRN amplitude per layer rides along
16802    /// (`metal_rope_scale_ok`).
16803    ///
16804    /// Per-layer Q heads (Laguna) and capped scores (Gemma-2) decline here
16805    /// too, with V norm (Gemma-4): the chunk prefill's own gate checks
16806    /// neither of the first two, and before this door opened its `swa`
16807    /// refusal kept every sliding model with them off the chunk graph.
16808    #[cfg(target_os = "macos")]
16809    fn metal_graph_swa(&self) -> bool {
16810        (self.swa.is_some() || self.sliding_layers.is_some())
16811            && self.attention_heads_per_layer.is_none()
16812            && !self.attn_v_norm
16813            && self.attn_softcap == 0.0
16814            && self.kv_heads_per_layer.is_none()
16815            && self.v_head_dim.map_or(true, |vd| vd == self.head_dim)
16816            && self.global_attn.is_none()
16817            && self.inv_freq_global.is_none()
16818            && self.metal_rope_scale_ok()
16819            && !(0..self.num_layers).any(|li| {
16820                self.layer_is_local(li)
16821                    && self.inv_freq_local.is_none()
16822                    && self.rotary_dim_local.is_some_and(|r| r != self.rotary_dim)
16823            })
16824    }
16825
16826    /// Can the Metal graphs carry this Gemma-4 model (`gpu_metal::gemma4`)?
16827    /// Its sliding layers (window, local RoPE table, 256-wide heads)
16828    /// device-attend like Spark-X2.5's; the 512-wide global layers (one KV
16829    /// head, proportional RoPE in the zero-padded table) take the 16-slot
16830    /// kernels; the V norm, sandwich norms, layer scalar and tanh-GELU come
16831    /// from the Gemma-4 library. Dense FFNs only (no Gemma-4 MoE measured).
16832    /// `CMF_METAL_GEMMA4=0` declines it as before (CPU attention).
16833    #[cfg(target_os = "macos")]
16834    fn metal_gemma4(&self) -> bool {
16835        crate::gpu_metal::gemma4::enabled()
16836            && (self.global_attn.is_some() || self.attn_v_norm)
16837            && self.attention_heads_per_layer.is_none()
16838            && self.kv_heads_per_layer.is_none()
16839            && self.v_head_dim.is_none()
16840            && !self.kv_cache.layers.iter().any(|l| l.sinks.is_some())
16841            && self.attn_softcap == 0.0
16842            && !self.qk_norm_after_rope
16843            && self.metal_rope_scale_ok()
16844            && self
16845                .weights
16846                .layers
16847                .iter()
16848                .all(|lw| matches!(&lw.ffn, FfnKind::Dense(d) if d.segs.is_empty()))
16849            && !(0..self.num_layers).any(|li| {
16850                self.layer_is_local(li)
16851                    && self.inv_freq_local.is_none()
16852                    && self.rotary_dim_local.is_some_and(|r| r != self.rotary_dim)
16853            })
16854    }
16855
16856    /// Why the WGPU graphs (whole-token, batched prefill, greedy burst)
16857    /// cannot run this model's attention, if they cannot. Per-layer KV
16858    /// heads, V narrower than K, learned sinks and sliding windows ride
16859    /// their per-layer geometry (`GraphAttnGeom`, the ATTEND_X kernels);
16860    /// what that geometry does not express keeps the decline, by name.
16861    /// None for every model with one attention geometry.
16862    pub fn wgpu_graph_attn_decline(&self) -> Option<&'static str> {
16863        if self.value_blend.is_some() && !crate::gpu::vres_graph_on() {
16864            return Some("value residual");
16865        }
16866        // Keep the ordinary (uniform) fast arms off YaRN until they carry a
16867        // scale field too. A non-uniform geometry gets a `GraphAttnGeom` and
16868        // is handled below by the generic graph kernels.
16869        let geometry_reason = self.graph_attn_decline_reason();
16870        let has_scaled_rope = (0..self.num_layers).any(|li| self.layer_rope_scale(li) != 1.0);
16871        if has_scaled_rope && geometry_reason.is_none() {
16872            return Some("scaled RoPE without per-layer geometry");
16873        }
16874        // For Q/K norm after partial RoPE, the scale changes only the rotary
16875        // slice's RMS denominator. The generic graph deliberately declines
16876        // that uncommon combination until it carries a separate rotary sum;
16877        // Mellum has q/k norm before RoPE, so it remains on this path.
16878        if has_scaled_rope && self.qk_norm_after_rope {
16879            return Some("scaled RoPE with post-RoPE Q/K norm");
16880        }
16881        geometry_reason?;
16882        // Gemma-4: global layers 512 wide over 256-wide sliding ones
16883        // (`GraphAttnGeom::hd`), the scale-less V norm (`v_norm`), and the
16884        // sandwich norms + layer scalar (`GraphLayer`) ride the TOKEN graph.
16885        // The batch graph has none of the three and refuses them itself
16886        // (`batch_graph_gemma_decline`).
16887        if self.attention_heads_per_layer.is_some() {
16888            return Some("per-layer Q head counts with per-layer geometry");
16889        }
16890        // Sandwich norms are measured on Gemma-4 (the humanizer port) and
16891        // LFM3, both with plain x̂·w weights, against HF transformers;
16892        // Gemma-2/3's (1+w) norms keep the per-op path until they are
16893        // measured the same way, and a layer scale stays Gemma-4's.
16894        let gemma4 = self.global_attn.is_some() || self.attn_v_norm;
16895        let plain_norms = self.norm_style == cortiq_core::NormStyle::Qwen;
16896        if !gemma4
16897            && self.weights.layers.iter().any(|lw| {
16898                lw.layer_scale.is_some()
16899                    || (!plain_norms && (lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some()))
16900            })
16901        {
16902            return Some("sandwich norms / layer scale with per-layer geometry");
16903        }
16904        // `GraphAttnGeom::rope_scale` carries YaRN's post-rotation
16905        // attention-amplitude factor to the WGPU RoPE kernel. It is not an
16906        // angular position scale, so it must not be folded into `invf`.
16907        if self.weights.layers.iter().any(|lw| {
16908            matches!(
16909                &lw.attn,
16910                AttnKind::Full {
16911                    output_gate: true,
16912                    ..
16913                }
16914            )
16915        }) && self.v_head_dim.is_some()
16916        {
16917            return Some("gated attention with V narrower than K");
16918        }
16919        if (0..self.num_layers).any(|li| {
16920            self.layer_is_local(li)
16921                && self.inv_freq_local.is_none()
16922                && self.rotary_dim_local.is_some_and(|r| r != self.rotary_dim)
16923        }) {
16924            return Some("local rotary width without a local RoPE table");
16925        }
16926        None
16927    }
16928
16929    /// What the wgpu BATCH graph (and the attention-only singleton graphs)
16930    /// cannot run of Gemma-4, which the token graph does run: per-layer
16931    /// head widths, the V norm, sandwich norms and the layer scalar.
16932    fn batch_graph_gemma_decline(&self) -> Option<&'static str> {
16933        // Gemma-4 rides `gemma_batch` (per-layer head width, V norm,
16934        // sandwich norms, layer scalar) unless CMF_G4_BATCH=0.
16935        if (self.global_attn.is_some() || self.attn_v_norm) && crate::gpu::g4_batch_on() {
16936            return None;
16937        }
16938        if self.global_attn.is_some() {
16939            return Some("per-layer head width (Gemma-4 global layers)");
16940        }
16941        if self.attn_v_norm {
16942            return Some("V norm");
16943        }
16944        // Sandwich norms alone ride the batch graph's plain tails (Ripple).
16945        if self.weights.layers.iter().any(|lw| lw.layer_scale.is_some()) {
16946            return Some("layer scale");
16947        }
16948        // CUDA's hybrid prompt path takes plain sandwich norms itself (LFM3's,
16949        // beside its short convolutions and head gate): its batch arm decides.
16950        // So does wgpu's batch graph for the LFM stacks (short convolutions):
16951        // their sandwich norms ride its plain tails, as Ripple's do.
16952        let lfm = self.short_conv_cfg.is_some() && self.weights.layers.iter().any(|lw| matches!(lw.attn, AttnKind::ShortConv(_)));
16953        if self.value_blend.is_none()
16954            && !lfm
16955            && !crate::gpu::cuda_active()
16956            && self
16957                .weights
16958                .layers
16959                .iter()
16960                .any(|lw| lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some())
16961        {
16962            return Some("sandwich norms");
16963        }
16964        None
16965    }
16966
16967    /// The wgpu graphs' attention geometry for layer `li` (virtual index):
16968    /// Some only for a model whose layers do not share one (MiMo-V2) — KV
16969    /// heads, V width, rotary width and RoPE table, window and sinks of
16970    /// THIS layer, exactly what the CPU attention reads for it.
16971    /// Unlimited-OCR: layer `li`'s router for the device graphs.
16972    /// Kimi-Linear's mixers for the graphs (`GraphAttn::Kda` / `Mla`), with
16973    /// the model the weights live in; `gw` the caller's weight resolver.
16974    fn graph_attn_kimi<'s>(
16975        &'s self,
16976        li: usize,
16977        attn: &'s AttnKind,
16978        gw: &dyn Fn(&'s QTensor) -> Option<crate::gpu::GraphW<'s>>,
16979    ) -> Option<(crate::gpu::GraphAttn<'s>, std::sync::Arc<cortiq_core::CmfModel>)> {
16980        match attn {
16981            AttnKind::Kda(w) => {
16982                let cfg = self.kda_cfg?;
16983                let (m, _, _, _) = w.q_proj.graph_weight_or_blr()?;
16984                let (g_a, g_b) = match &w.gate {
16985                    crate::linear_core::KdaOutGate::Full(g) => (gw(g)?, None),
16986                    crate::linear_core::KdaOutGate::LowRank(a, b) => (gw(a)?, Some(gw(b)?)),
16987                };
16988                Some((
16989                    crate::gpu::GraphAttn::Kda {
16990                        q: gw(&w.q_proj)?,
16991                        k: gw(&w.k_proj)?,
16992                        v: gw(&w.v_proj)?,
16993                        conv_q: &w.conv_q,
16994                        conv_k: &w.conv_k,
16995                        conv_v: &w.conv_v,
16996                        f_a: gw(&w.f_a)?,
16997                        f_b: gw(&w.f_b)?,
16998                        dt_bias: &w.dt_bias,
16999                        a_log: &w.a_log,
17000                        b: gw(&w.b_proj)?,
17001                        g_a,
17002                        g_b,
17003                        o_norm: &w.o_norm,
17004                        out: gw(&w.o_proj)?,
17005                        nh: cfg.num_heads,
17006                        dk: cfg.head_k_dim,
17007                        dv: cfg.head_v_dim,
17008                        kk: cfg.conv_kernel,
17009                        lower_bound: w.gate_lower_bound,
17010                        cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
17011                    },
17012                    m.clone(),
17013                ))
17014            }
17015            AttnKind::Mla(w) => {
17016                let (m, _, _, _) = w.kv_a.graph_weight_or_blr()?;
17017                let q_a = match &w.q_a {
17018                    Some(t) => Some(gw(t)?),
17019                    None => None,
17020                };
17021                Some((
17022                    crate::gpu::GraphAttn::Mla {
17023                        hy: None,
17024                        q_a,
17025                        q_a_norm: w.q_a_norm.as_deref(),
17026                        q: gw(&w.q_proj)?,
17027                        kv_a: gw(&w.kv_a)?,
17028                        kv_a_norm: &w.kv_a_norm,
17029                        kv_b: gw(&w.kv_b)?,
17030                        o: gw(&w.o_proj)?,
17031                        nh: w.nh,
17032                        rope: w.qk_rope,
17033                        nope: w.qk_nope,
17034                        v_dim: w.v_dim,
17035                        lora: w.lora,
17036                        scale: w.scale,
17037                        no_rope: w.nope,
17038                        cpu_k: self.kv_cache.layers[li].k_heads(),
17039                        cpu_v: self.kv_cache.layers[li].v_heads(),
17040                        cpu_base: self.kv_cache.layers[li].base(),
17041                        dsa: None,
17042                    },
17043                    m.clone(),
17044                ))
17045            }
17046            _ => None,
17047        }
17048    }
17049
17050    fn graph_dash(&self, li: usize) -> Option<crate::gpu::GraphDash<'_>> {
17051        self.dash.as_deref().map(|d| {
17052            let l = &d.layers[li];
17053            crate::gpu::GraphDash {
17054                qk_proj: &l.qk_proj,
17055                q_norm: &l.q_norm,
17056                k_norm: &l.k_norm,
17057                head_cls: &l.head_cls,
17058                idx_scale: l.route.idx_scale,
17059                floor: l.route.floor,
17060                sigma: l.route.sigma,
17061                k: l.route.k,
17062                block: d.block,
17063                local_blocks: d.local_blocks,
17064                nblk: d.allow.len(),
17065                cands: &d.cands,
17066                coff: &d.coff,
17067                angles: &d.angles,
17068            }
17069        })
17070    }
17071
17072    fn graph_attn_geom(&self, li: usize) -> Option<crate::gpu::GraphAttnGeom<'_>> {
17073        if self.dash.is_none() {
17074            self.graph_attn_decline_reason()?;
17075        }
17076        let (nkv, hd, rd) = self.layer_geom(li);
17077        let dash = self.graph_dash(li);
17078        let invf: &[f32] = if let Some(d) = self.dash.as_deref() {
17079            &d.angles
17080        } else if self.layer_is_local(li) {
17081            match &self.inv_freq_local {
17082                Some(f) => f.as_slice(),
17083                None => self.inv_freq.as_slice(),
17084            }
17085        } else {
17086            match &self.inv_freq_global {
17087                Some(f) => f.as_slice(),
17088                None => self.inv_freq.as_slice(),
17089            }
17090        };
17091        Some(crate::gpu::GraphAttnGeom {
17092            nkv,
17093            hd,
17094            dv: self.layer_v_dim(li),
17095            rd,
17096            invf,
17097            rope_scale: self.layer_rope_scale(li),
17098            window: self.layer_window(li),
17099            sink: self.kv_cache.layers[li].sinks.as_deref(),
17100            v_norm: self.attn_v_norm,
17101            dash,
17102            vres: None,
17103            route: None,
17104        })
17105    }
17106
17107    /// The decode graph's geometry of layer `li`: `graph_attn_geom`, except
17108    /// that a full-attention layer of the call's own geometry takes the
17109    /// uniform arms (None) on the wgpu token graph of a stack that asked for
17110    /// it (`uniform_full_layers`). Its mirror is the one the prompt's
17111    /// per-layer-geometry arm filled — one f32 row a position either way —
17112    /// and the decode reads it through the flash-decoding attend instead of
17113    /// one workgroup a head over every row (Aion-2.3B q4tp on an L4 at 16k /
17114    /// 30k tokens: 54 / 41 → see CHANGELOG). The prompt keeps the geometry
17115    /// arm: its matrix-unit tile takes 128-wide heads, the uniform one 256.
17116    fn graph_attn_geom_decode<'a>(&'a self, li: usize, e0: &'a [f32]) -> Option<crate::gpu::GraphAttnGeom<'a>> {
17117        let (nkv, hd, rd) = self.layer_geom(li);
17118        if self.uniform_full_layers
17119            && crate::gpu::wgpu_active()
17120            && self.dash.is_none()
17121            && !self.layer_is_local(li)
17122            && self.kv_cache.layers[li].sinks.is_none()
17123            && (nkv, hd, rd) == (self.num_kv_heads, self.head_dim, self.rotary_dim)
17124            && self.layer_v_dim(li) == hd
17125            && self.inv_freq_global.is_none()
17126            && self.layer_rope_scale(li) == 1.0
17127            && !self.attn_v_norm
17128            && self.value_blend.is_none()
17129        {
17130            return None;
17131        }
17132        self.graph_attn_geom_vres(li, e0)
17133    }
17134
17135    /// `graph_attn_geom` with Ripple's value residual: the layer's blend and
17136    /// `e0`, the embedding rows of the graph call.
17137    fn graph_attn_geom_vres<'a>(&'a self, li: usize, e0: &'a [f32]) -> Option<crate::gpu::GraphAttnGeom<'a>> {
17138        let mut g = self.graph_attn_geom(li)?;
17139        g.vres = self.layer_value_blend(li).map(|b| (b, e0));
17140        Some(g)
17141    }
17142
17143    /// The decode graph's device K/V mirror that layer `li`'s batched
17144    /// prefill appends its chunk to and attends against (wgpu), instead
17145    /// of uploading the layer's whole K/V prefix every chunk and the whole
17146    /// cache again at the first decode token. Only where the token graph
17147    /// will read that very mirror: the decode graph on, not refused, and
17148    /// this layer's geometry what it requests (`graph_attn_geom`: KV heads,
17149    /// V as wide as K, the window as a ring, no sink).
17150    ///
17151    /// Spark-X2.5 only (`proj_gate_sigmoid`), the one architecture whose
17152    /// output was measured identical on it. `CMF_PREFILL_MIRROR=0` keeps
17153    /// the host upload (A/B).
17154    #[cfg(feature = "gpu")]
17155    fn prefill_mirror_target(&self, li: usize) -> Option<crate::gpu::PrefillMirror> {
17156        if !self.proj_gate_sigmoid
17157            || std::env::var("CMF_PREFILL_MIRROR").as_deref() == Ok("0")
17158            || !crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)
17159            || self.graph_refused()
17160            || self.o1_active()
17161            || self.attn_softcap > 0.0
17162            || self.wgpu_graph_attn_decline().is_some()
17163        {
17164            return None;
17165        }
17166        let g = self.graph_attn_geom(li)?;
17167        let (nkv, hd, _) = self.layer_geom(li);
17168        // The token graph passes the call-wide head width (layer 0's).
17169        if g.nkv != nkv || g.dv != hd || g.sink.is_some() || hd != self.layer_geom(0).1 {
17170            return None;
17171        }
17172        Some(crate::gpu::PrefillMirror {
17173            kv_id: self.graph_kv_id,
17174            layer: li,
17175            limit: self.kv_cache.max_seq_len,
17176        })
17177    }
17178
17179    /// Bring the host KV cache of every Full-attention layer in
17180    /// `[from, upto)` up to `position` rows from the wgpu mirrors, where a
17181    /// device graph advanced a layer that the host is about to run: a
17182    /// device prefix that shrank since the prompt (or a batched prefill
17183    /// prefix longer than the decode one). A layer whose mirror does not
17184    /// hold the missing rows is left alone. Rows a sliding layer's ring
17185    /// no longer holds come back as zeros — outside every window that
17186    /// will read them.
17187    #[cfg(feature = "gpu")]
17188    fn pull_lagging_host_kv(&mut self, from: usize, upto: usize, position: usize) {
17189        let kv_id = self.graph_kv_id;
17190        for li in from..upto.min(self.num_layers) {
17191            if !matches!(
17192                self.weights.layers[self.phys_layer(li)].attn,
17193                AttnKind::Full { .. }
17194            ) {
17195                continue;
17196            }
17197            // Absolute: a trimmed sliding tail holds positions base.. only.
17198            let host = self.kv_cache.layers[li].pos_len();
17199            if host >= position {
17200                continue;
17201            }
17202            let Some(dev) = crate::gpu::graph_kv_stored(kv_id, li) else {
17203                continue;
17204            };
17205            let to = dev.min(position);
17206            if to <= host {
17207                continue;
17208            }
17209            let (nkv, hd) = {
17210                let c = &self.kv_cache.layers[li];
17211                (c.num_kv_heads, c.head_dim)
17212            };
17213            let Some((k, v, first_valid)) =
17214                crate::gpu::graph_kv_pull_host(kv_id, li, host, to, nkv, hd)
17215            else {
17216                continue;
17217            };
17218            // A sliding layer only ever reads its last `window` rows; a
17219            // full-context layer needs every row it did not have.
17220            let need_from = match self.layer_window(li) {
17221                Some(w) => host.max((position + 1).saturating_sub(w)),
17222                None => host,
17223            };
17224            if first_valid > need_from {
17225                tracing::warn!(
17226                    "layer {li}: device KV rows {host}..{to} no longer resident \
17227                     (from {first_valid}); host attention will miss them"
17228                );
17229            }
17230            let row = nkv * hd;
17231            let cache = &mut self.kv_cache.layers[li];
17232            for p in 0..to - host {
17233                cache.append(&k[p * row..(p + 1) * row], &v[p * row..(p + 1) * row], &[]);
17234            }
17235        }
17236    }
17237
17238    /// Log (once per graph site and pipeline) that `site` declined for
17239    /// `reason`. The lines are kept so a caller or a test can read them.
17240    fn note_graph_decline(&self, site: &'static str, reason: &'static str) {
17241        let mut seen = self.graph_declines.borrow_mut();
17242        if !seen.iter().any(|&(s, r)| s == site && r == reason) {
17243            tracing::warn!("{site} declined: {reason} (CPU attention path)");
17244            seen.push((site, reason));
17245        }
17246    }
17247
17248    /// The GPU-graph declines this pipeline has logged so far, as the
17249    /// logged lines.
17250    pub fn graph_declines(&self) -> Vec<String> {
17251        self.graph_declines
17252            .borrow()
17253            .iter()
17254            .map(|(site, reason)| format!("{site} declined: {reason} (CPU attention path)"))
17255            .collect()
17256    }
17257
17258    /// Does layer `li` have the plain attention geometry the historical
17259    /// head-masked f32 path (`multi_head_attention`) assumes — pipeline-wide
17260    /// KV heads / head_dim / RoPE table, full context, no sink, V as wide
17261    /// as K? Anything else runs the dense `qwen_attention` instead.
17262    /// `CMF_LAYER_DUMP` writer (see `Pipeline::layer_dump`): one position's
17263    /// hidden after layer `li` as raw little-endian f32 into
17264    /// `<dir>/p{pos:06}_l{li:02}.f32`. A failed write is reported once and
17265    /// never stops the forward — the dump is a diagnostic.
17266    fn dump_layer_row(&self, pos: usize, li: usize, row: &[f32]) {
17267        let Some(dir) = &self.layer_dump else {
17268            return;
17269        };
17270        let mut bytes = Vec::with_capacity(row.len() * 4);
17271        for v in row {
17272            bytes.extend_from_slice(&v.to_le_bytes());
17273        }
17274        let path = dir.join(format!("p{pos:06}_l{li:02}.f32"));
17275        if let Err(e) = std::fs::create_dir_all(dir).and_then(|_| std::fs::write(&path, &bytes)) {
17276            use std::sync::atomic::{AtomicBool, Ordering};
17277            static SAID: AtomicBool = AtomicBool::new(false);
17278            if !SAID.swap(true, Ordering::Relaxed) {
17279                tracing::error!("CMF_LAYER_DUMP: cannot write {}: {e}", path.display());
17280            }
17281        }
17282    }
17283
17284    /// Decide the MiMo-V2 expert placement once (`crate::mimo_moe`). Any
17285    /// other model turns the slot off on the first call.
17286    fn mimo_moe_prepare(&mut self) {
17287        if !self.mimo_moe.is_undecided() {
17288            return;
17289        }
17290        let slot = {
17291            let layers: Vec<(usize, &MoeFfn)> = (0..self.num_layers)
17292                .filter_map(
17293                    |li| match &self.weights.layers.get(self.phys_layer(li))?.ffn {
17294                        FfnKind::Moe(m) => Some((li, m)),
17295                        _ => None,
17296                    },
17297                )
17298                .collect();
17299            // One bank lives on one device: an in-process multi-GPU split
17300            // keeps the whole-layer path.
17301            if layers.is_empty()
17302                || self.physical_layers != self.num_layers
17303                || self.gpu_plan.is_some()
17304            {
17305                crate::mimo_moe::Slot::Off
17306            } else {
17307                // Whether a whole-token graph could run this model's layers
17308                // (then a whole-layer prefix is one submit, not per-layer
17309                // fences).
17310                let graph_prefix =
17311                    self.wgpu_graph_attn_decline().is_none() && crate::gpu::wgpu_graph_default();
17312                crate::mimo_moe::Slot::decide(&layers, self.num_layers, graph_prefix)
17313            }
17314        };
17315        self.mimo_moe = slot;
17316    }
17317
17318    #[cfg(test)]
17319    pub(crate) fn test_graph_kv_id(&self) -> u64 {
17320        self.graph_kv_id
17321    }
17322
17323    /// Dynamic MiMo layer: one device attention graph, followed by a bank
17324    /// frame. Both decode and short verification use this same attention
17325    /// path and absolute layer key; the host KV may intentionally lag.
17326    pub(crate) fn mimo_graph_layer_rows(
17327        &mut self,
17328        li: usize,
17329        h: &mut [f32],
17330        positions: &[usize],
17331    ) -> crate::gpu::BatchGraphOutcome {
17332        use crate::gpu::BatchGraphOutcome as Out;
17333        let b = positions.len();
17334        if !(1..=4).contains(&b)
17335            || h.len() != b * self.hidden_size
17336            || !self.mimo_moe.is_dynamic(li, true)
17337            || !crate::gpu::enabled_here()
17338            || !crate::gpu::wgpu_active()
17339            || self.o1_active()
17340            || self.physical_layers != self.num_layers
17341            // The pair-fusion diagnostic (and an explicit graph-off run)
17342            // rewinds only host KV. A hidden singleton attention graph here
17343            // would leave device mirrors ahead of the next host position.
17344            || std::env::var("CMF_GPU_WGPU_GRAPH").as_deref() == Ok("0")
17345            || std::env::var("CMF_MIMO_ATTN_GRAPH").as_deref() == Ok("0")
17346            || self.wgpu_graph_attn_decline().is_some()
17347        {
17348            return Out::Declined;
17349        }
17350        let attn_started = std::time::Instant::now();
17351        let outcome = {
17352            let lw = &self.weights.layers[li];
17353            if lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some() {
17354                return Out::Declined;
17355            }
17356            let FfnKind::Moe(m) = &lw.ffn else {
17357                return Out::Declined;
17358            };
17359            let AttnKind::Full {
17360                wq,
17361                wk,
17362                wv,
17363                wo,
17364                q_norm,
17365                k_norm,
17366                output_gate,
17367                softplus_gate,
17368                bias,
17369            } = &lw.attn
17370            else {
17371                return Out::Declined;
17372            };
17373            if *output_gate || softplus_gate.is_some() {
17374                return Out::Declined;
17375            }
17376            let Some(model) = wq.graph_weight().map(|(m, ..)| m.clone()).or_else(|| {
17377                m.experts
17378                    .first()?
17379                    .gate_proj
17380                    .mapped_q4tp()
17381                    .map(|(m, _)| m.clone())
17382            }) else {
17383                return Out::Declined;
17384            };
17385            fn gw<'a>(
17386                t: &'a QTensor,
17387                owner: &std::sync::Arc<cortiq_core::CmfModel>,
17388            ) -> Option<crate::gpu::GraphW<'a>> {
17389                if let Some((m, idx, kind, rs)) = t.graph_weight() {
17390                    if m.uid() != owner.uid() || t.has_prism_contract() {
17391                        return None;
17392                    }
17393                    return Some(crate::gpu::GraphW {
17394                        idx,
17395                        kind,
17396                        row_scale: rs,
17397                        data: &[],
17398                        prism: crate::gpu::GraphPrismOp::None,
17399                        affine: false,
17400                    });
17401                }
17402                t.as_f32().map(|data| crate::gpu::GraphW {
17403                    idx: 0,
17404                    kind: 4,
17405                    row_scale: &[],
17406                    data,
17407                    prism: crate::gpu::GraphPrismOp::None,
17408                    affine: false,
17409                })
17410            }
17411            let (Some(q), Some(k), Some(v), Some(o)) = (
17412                gw(wq, &model),
17413                gw(wk, &model),
17414                gw(wv, &model),
17415                gw(wo, &model),
17416            ) else {
17417                return Out::Declined;
17418            };
17419            let layer = crate::gpu::GraphLayer {
17420                engram: None,
17421                mhc: None,
17422                input_norm: &lw.input_norm,
17423                post_norm: &lw.post_norm,
17424                attn_out_norm: None,
17425                ffn_out_norm: None,
17426                layer_scale: None,
17427                ffn: crate::gpu::GraphFfn::AttentionOnly,
17428                attn: crate::gpu::GraphAttn::Full {
17429                    wq: q,
17430                    wk: k,
17431                    wv: v,
17432                    wo: o,
17433                    q_norm: q_norm.as_deref(),
17434                    k_norm: k_norm.as_deref(),
17435                    late_qk_norm: self.qk_norm_after_rope,
17436                    bias: bias
17437                        .as_ref()
17438                        .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice())),
17439                    output_gate: false,
17440                    cpu_k: self.kv_cache.layers[li].k_heads(),
17441                    cpu_v: self.kv_cache.layers[li].v_heads(),
17442                    cpu_base: self.kv_cache.layers[li].base(),
17443                    geom: self.graph_attn_geom(li),
17444                    head_gate: None,
17445                },
17446            };
17447            let (nkv, hd, rd) = self.layer_geom(li);
17448            crate::gpu::forward_batch_graph_at(
17449                &model,
17450                self.graph_kv_id,
17451                li,
17452                &[layer],
17453                &self.inv_freq,
17454                h,
17455                self.layer_num_heads(li),
17456                nkv,
17457                hd,
17458                rd,
17459                self.hidden_size,
17460                1,
17461                positions,
17462                self.kv_cache.max_seq_len,
17463                self.norm_style == cortiq_core::NormStyle::Gemma,
17464                self.rms_eps as f32,
17465                self.attn_scale,
17466                b,
17467                &[],
17468                self.o1_epoch,
17469                None,
17470                None,
17471            )
17472        };
17473        match outcome {
17474            Out::Completed => {}
17475            Out::Declined => return Out::Declined,
17476            Out::Failed => {
17477                self.graph_failed
17478                    .store(true, std::sync::atomic::Ordering::Relaxed);
17479                return Out::Failed;
17480            }
17481        }
17482        let attn_ns = attn_started.elapsed().as_nanos() as u64;
17483        let hs = self.hidden_size;
17484        let lw = &self.weights.layers[li];
17485        let FfnKind::Moe(m) = &lw.ffn else {
17486            unreachable!()
17487        };
17488        let mut post = vec![0.0; h.len()];
17489        for (x, y) in h.chunks_exact(hs).zip(post.chunks_exact_mut(hs)) {
17490            inference::rms_norm_into(x, &lw.post_norm, self.rms_eps, self.norm_style, y);
17491        }
17492        let mut ffn = if b == 1 {
17493            moe_ffn_banked(&mut self.mimo_moe, li, m, &post, self.pool.as_deref())
17494        } else {
17495            moe_ffn_banked_rows(
17496                &mut self.mimo_moe,
17497                li,
17498                m,
17499                &post,
17500                b,
17501                hs,
17502                self.pool.as_deref(),
17503            )
17504        };
17505        for (x, &f) in h.iter_mut().zip(&ffn) {
17506            *x += f;
17507        }
17508        attention::recycle_buf(&mut ffn);
17509        if self.layer_dump.is_some() {
17510            for (&pos, row) in positions.iter().zip(h.chunks_exact(hs)) {
17511                self.dump_layer_row(pos, li, row);
17512            }
17513        }
17514        crate::mimo_moe::note_attention_graph(b, attn_ns);
17515        Out::Completed
17516    }
17517
17518    fn layer_attn_plain(&self, li: usize) -> bool {
17519        self.kv_heads_per_layer.is_none()
17520            && self.v_head_dim.is_none()
17521            && self.global_attn.is_none()
17522            && self.layer_window(li).is_none()
17523            && self.kv_cache.layers[li].sinks.is_none()
17524    }
17525
17526    /// Forward one position through all layers (hybrid dispatch).
17527    fn forward_layers(
17528        &mut self,
17529        hidden: &[f32],
17530        position: usize,
17531        task_mask: Option<&TaskMask>,
17532    ) -> Vec<f32> {
17533        let out = self.forward_layers_upto(hidden, position, task_mask, None);
17534        self.o1_progress();
17535        self.swa_trim_tails();
17536        out
17537    }
17538
17539    // ── Network pipeline-split building blocks (coordinator/worker) ──
17540    // A remote worker owns layers [from ..= upto] and their KV; the
17541    // coordinator owns the rest plus embed / final norm / head. Attention
17542    // causality is per-layer, so a whole prompt's boundary hiddens ship
17543    // as one batch and decode ships one vector per token.
17544
17545    /// Embed one token id (embed multiplier applied).
17546    pub fn embed_id(&self, id: u32) -> Vec<f32> {
17547        self.embed_single(id)
17548    }
17549
17550    /// Refuse the archs/modes whose forward cannot be cut at a layer
17551    /// boundary. Loud by design: a split that silently changed the math
17552    /// would be a chimera.
17553    pub fn split_supported(&self) -> Result<(), String> {
17554        if self.dsv4.is_some() {
17555            return Err(
17556                "network split: DeepSeek-V4 runs its own fused stack (not splittable yet)".into(),
17557            );
17558        }
17559        if self.dory.is_some() {
17560            return Err("network split: Dory's looped stack is not splittable".into());
17561        }
17562        if self.dsv41.is_some() {
17563            return Err(
17564                "network split: DeepSeek-V4.1 owns the shared CED/CSA2 state (not splittable)"
17565                    .into(),
17566            );
17567        }
17568        if self.qwen4_exp.is_some() {
17569            return Err(
17570                "network split: Qwen3.8-Flash-Next hyper/QSA stack is not splittable yet".into(),
17571            );
17572        }
17573        if self.glm5_next.is_some() {
17574            return Err("network split: GLM-5.3-Flash mHC/KDA/DSA stack is not splittable yet".into());
17575        }
17576        if self.hy4.is_some() {
17577            return Err("network split: the Hy4-flash iHC/Engram stack is not splittable yet".into());
17578        }
17579        if self.maxwell.is_some() {
17580            return Err("network split: the Maxwell mHC stack is not splittable yet".into());
17581        }
17582        if self.inkling.is_some() {
17583            return Err("network split: the Inkling looped stack is not splittable yet".into());
17584        }
17585        if self.per_token_stack() {
17586            return Err(
17587                "network split: the per-token stack (gemma-3n AltUp / gemma-4 E-series) is not splittable yet".into(),
17588            );
17589        }
17590        if self.value_blend.is_some() {
17591            return Err(
17592                "network split: a value-residual stack (Ripple) reads the embedding row in every layer".into(),
17593            );
17594        }
17595        Ok(())
17596    }
17597
17598    /// Forward `hidden` through layers [from ..= upto] at `position`,
17599    /// appending those layers' KV/state. Both split sides call this
17600    /// over their own range; a task mask applies to the span's own
17601    /// layers (each side masks what it runs).
17602    pub fn forward_span(
17603        &mut self,
17604        hidden: &[f32],
17605        position: usize,
17606        from: usize,
17607        upto: usize,
17608        task_mask: Option<&TaskMask>,
17609    ) -> Result<Vec<f32>, String> {
17610        self.split_supported()?;
17611        if from > upto || upto >= self.num_layers {
17612            return Err(format!(
17613                "forward_span: layer range {from}..={upto} outside 0..{}",
17614                self.num_layers
17615            ));
17616        }
17617        if hidden.len() != self.hidden_size {
17618            return Err(format!(
17619                "forward_span: hidden len {} ≠ hidden_size {}",
17620                hidden.len(),
17621                self.hidden_size
17622            ));
17623        }
17624        let out = self.forward_layers_span(hidden, position, task_mask, from, Some(upto));
17625        self.o1_progress();
17626        self.swa_trim_tails();
17627        if self
17628            .graph_failed
17629            .swap(false, std::sync::atomic::Ordering::Relaxed)
17630        {
17631            self.cancel
17632                .store(false, std::sync::atomic::Ordering::Relaxed);
17633            self.clear_sequence_state();
17634            return Err("forward_span: deferred O(1) transition failed".into());
17635        }
17636        Ok(out)
17637    }
17638
17639    /// Final norm + lm_head over a boundary hidden (the final-logit
17640    /// softcap is applied by lm_head_forward itself).
17641    pub fn logits_from_hidden(&mut self, hidden: &[f32]) -> Vec<f32> {
17642        let normed = inference::rms_norm(
17643            hidden,
17644            &self.weights.final_norm,
17645            self.rms_eps,
17646            self.norm_style,
17647        );
17648        self.lm_head_forward(&normed)
17649    }
17650
17651    /// Sample the next token with this pipeline's sampler state.
17652    pub fn sample_next(&mut self, logits: &[f32], past_tokens: &[u32]) -> u32 {
17653        sampler::sample_with_scratch(
17654            logits,
17655            &self.sampler_config,
17656            past_tokens,
17657            &mut self.rng,
17658            &mut self.sampler_scratch,
17659        )
17660    }
17661
17662    /// Fresh sequence: clear KV, reuse history and device mirrors.
17663    pub fn reset_session(&mut self) {
17664        self.clear_sequence_state();
17665    }
17666
17667    /// Batched span prefill from token ids (coordinator side): embed +
17668    /// layers [0 ..= upto]; returns the boundary hiddens of ALL positions
17669    /// (ids.len() × hidden). Rides the same layer-major machinery as the
17670    /// local prefill; falls back to the per-position walk under
17671    /// CMF_PREFILL=seq.
17672    pub fn prefill_span_ids(
17673        &mut self,
17674        ids: &[u32],
17675        start_pos: usize,
17676        upto: usize,
17677        task_mask: Option<&TaskMask>,
17678    ) -> Result<Vec<f32>, String> {
17679        self.split_supported()?;
17680        if upto >= self.num_layers {
17681            return Err(format!(
17682                "prefill_span_ids: upto {upto} outside 0..{}",
17683                self.num_layers
17684            ));
17685        }
17686        // Same predicate as the whole-stack prefill: a span whose GDN
17687        // state lives on the device must walk positions through the
17688        // graph, not through the batched CPU span.
17689        if self.can_prefill_batched() && !self.graph_prefill_preferred() {
17690            let out =
17691                self.prefill_batch_span(PrefillIn::Ids(ids), start_pos, task_mask, 0, upto + 1);
17692            self.check_o1_progress_failure("prefill_span_ids")?;
17693            Ok(out)
17694        } else {
17695            let hs = self.hidden_size;
17696            let mut out = Vec::with_capacity(ids.len() * hs);
17697            for (i, &id) in ids.iter().enumerate() {
17698                let emb = self.embed_id(id);
17699                out.extend_from_slice(&self.forward_span(
17700                    &emb,
17701                    start_pos + i,
17702                    0,
17703                    upto,
17704                    task_mask,
17705                )?);
17706            }
17707            Ok(out)
17708        }
17709    }
17710
17711    /// Batched span prefill from boundary hiddens (worker side): layers
17712    /// [from ..= upto] for every position in the batch; returns the batch.
17713    pub fn prefill_span_hidden(
17714        &mut self,
17715        hidden: &[f32],
17716        start_pos: usize,
17717        from: usize,
17718        upto: usize,
17719        task_mask: Option<&TaskMask>,
17720    ) -> Result<Vec<f32>, String> {
17721        self.split_supported()?;
17722        let hs = self.hidden_size;
17723        if hidden.is_empty() || hidden.len() % hs != 0 {
17724            return Err(format!(
17725                "prefill_span_hidden: {} floats is not a multiple of hidden {hs}",
17726                hidden.len()
17727            ));
17728        }
17729        if from > upto || upto >= self.num_layers {
17730            return Err(format!(
17731                "prefill_span_hidden: layer range {from}..={upto} outside 0..{}",
17732                self.num_layers
17733            ));
17734        }
17735        if self.can_prefill_batched() && !self.graph_prefill_preferred() {
17736            let out = self.prefill_batch_span(
17737                PrefillIn::Hidden(hidden),
17738                start_pos,
17739                task_mask,
17740                from,
17741                upto + 1,
17742            );
17743            self.check_o1_progress_failure("prefill_span_hidden")?;
17744            Ok(out)
17745        } else {
17746            let b = hidden.len() / hs;
17747            let mut out = Vec::with_capacity(hidden.len());
17748            for i in 0..b {
17749                let h = self.forward_span(
17750                    &hidden[i * hs..(i + 1) * hs],
17751                    start_pos + i,
17752                    from,
17753                    upto,
17754                    task_mask,
17755                )?;
17756                out.extend_from_slice(&h);
17757            }
17758            Ok(out)
17759        }
17760    }
17761
17762    /// Build the whole-token wgpu graph for a pure-attention q1 model (every
17763    /// layer Full q1 + dense q1 FFN, no gate/bias). Returns the post-stack
17764    /// hidden (caller does final norm + lm_head), or None to fall back.
17765    fn try_token_graph_wgpu(
17766        &self,
17767        hidden: &[f32],
17768        position: usize,
17769        logits_out: &mut Vec<f32>,
17770        layers_run: &mut usize,
17771    ) -> Option<Result<Vec<f32>, ()>> {
17772        self.try_token_graph_wgpu_steps(
17773            hidden,
17774            position,
17775            logits_out,
17776            1,
17777            None,
17778            Some(layers_run),
17779            0,
17780            self.num_layers,
17781        )
17782    }
17783
17784    /// The span twin (network split): the graph covers [from..upto_excl)
17785    /// — one submit per SEGMENT per token. lm_head folds in only when
17786    /// the span reaches the last layer.
17787    fn try_token_graph_wgpu_span(
17788        &self,
17789        hidden: &[f32],
17790        position: usize,
17791        logits_out: &mut Vec<f32>,
17792        from: usize,
17793        upto_excl: usize,
17794        layers_run: &mut usize,
17795    ) -> Option<Result<Vec<f32>, ()>> {
17796        self.try_token_graph_wgpu_steps(
17797            hidden,
17798            position,
17799            logits_out,
17800            1,
17801            None,
17802            Some(layers_run),
17803            from,
17804            upto_excl,
17805        )
17806    }
17807
17808    /// A device token graph (wgpu or CUDA) decodes this pipeline: the head
17809    /// of a row the graph did not run — the first token after a prompt —
17810    /// takes the graph's head pass as well (`CMF_HEAD_GRAPH=0`: the host
17811    /// head, as before).
17812    ///
17813    /// The host head of a q8 file on a GPU run is a hybrid: half of the
17814    /// vocabulary's rows on the card in f32, the other half on the CPU with
17815    /// integer activations (`gpu_split_frac`). Every later token's logits
17816    /// come from the graph's fused head, so that one row alone carried the
17817    /// integer half. Spark-X2.6-4B q8_2f on an A40 over Vulkan, against the
17818    /// host with float activations: first-token logits 0.29 off (and a
17819    /// near-tie token flipped on one prompt in four), every other token
17820    /// 0.015; through the graph's head the first token is 0.014 off too.
17821    /// On wgpu only those two codecs take it (`m3_device_logits`): a q4tp
17822    /// head measured the same either way.
17823    #[cfg(feature = "gpu")]
17824    fn graph_head_after_prompt(&self) -> bool {
17825        (crate::gpu::wgpu_active() || crate::gpu::cuda_active())
17826            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)
17827            && !self.graph_refused()
17828            && std::env::var("CMF_HEAD_GRAPH").as_deref() != Ok("0")
17829    }
17830
17831    /// The pooled tail's device lm_head: final-norm + head as one
17832    /// layer-less graph pass, so decode stops paying the double-digit
17833    /// millisecond host matvec every token. `None` keeps the host head.
17834    /// Also the head of the first token after a prompt wherever a device
17835    /// graph decodes (`graph_head_after_prompt`).
17836    #[cfg(feature = "gpu")]
17837    fn m3_device_logits(&self, hidden: &[f32]) -> Option<Vec<f32>> {
17838        let pooled = crate::minicpm_tail::minimax_pool_on();
17839        if !(pooled || self.graph_head_after_prompt())
17840            || !crate::gpu::enabled_here()
17841            || self.head_clusters.is_some()
17842            || self.graph_failed.load(std::sync::atomic::Ordering::Relaxed)
17843            || std::env::var("CMF_GPU_LMHEAD").map(|v| v != "0") == Ok(false)
17844        {
17845            return None;
17846        }
17847        let (model, i, kind, rs) = self
17848            .weights
17849            .lm_head
17850            .graph_weight()
17851            .or_else(|| self.weights.lm_head.graph_weight_descriptor())?;
17852        // After a prompt on wgpu: the codecs whose host head is the hybrid
17853        // (q8 by rows, q8_2f). CUDA has no host GPU head at all.
17854        if !pooled && !crate::gpu::cuda_active() && !matches!(kind, 0 | 7) {
17855            return None;
17856        }
17857        let name = &model.tensors[i].name;
17858        let prism = if crate::prism::is_inverse_embedding(&model, name) {
17859            crate::gpu::GraphPrismOp::InverseEmbedding
17860        } else if crate::prism::is_forward_weight(&model, name) {
17861            crate::gpu::GraphPrismOp::Forward
17862        } else {
17863            crate::gpu::GraphPrismOp::None
17864        };
17865        let gw = crate::gpu::GraphW {
17866            idx: i,
17867            kind,
17868            row_scale: rs,
17869            data: &[],
17870            prism,
17871            affine: crate::prism::is_affine_target(&model, name),
17872        };
17873        let rows = self.weights.lm_head.rows();
17874        let mut h = hidden.to_vec();
17875        let mut lg = Vec::new();
17876        let mut layers_run = 0usize;
17877        let outcome = crate::gpu::forward_token_graph(
17878            &model,
17879            self.graph_kv_id,
17880            &[],
17881            &[],
17882            self.o1_epoch,
17883            &self.inv_freq,
17884            &mut h,
17885            self.num_heads,
17886            self.num_kv_heads,
17887            self.head_dim,
17888            self.attn_scale,
17889            self.head_dim,
17890            self.hidden_size,
17891            self.intermediate_size,
17892            0,
17893            self.kv_cache.max_seq_len,
17894            self.norm_style == cortiq_core::NormStyle::Gemma,
17895            self.rms_eps as f32,
17896            Some((&gw, rows)),
17897            &self.weights.final_norm,
17898            &mut lg,
17899            &[],
17900            1,
17901            None,
17902            None,
17903            Some(&mut layers_run),
17904            0,
17905            false,
17906        );
17907        if outcome != crate::gpu::TokenGraphOutcome::Completed || lg.is_empty() {
17908            return None;
17909        }
17910        // The same post-steps the host head applies — keep sampling
17911        // identical whichever arm produced the logits.
17912        lg.resize(self.vocab_size, 0.0);
17913        if let Some(m) = self.logit_multiplier {
17914            for l in lg.iter_mut() {
17915                *l *= m;
17916            }
17917        }
17918        if let Some(c) = self.final_softcap {
17919            softcap_in_place(&mut lg, c, self.pool.as_deref());
17920        }
17921        Some(lg)
17922    }
17923
17924    /// Record one token-layer's winners into the route-frequency profile and
17925    /// write it out every 16 tokens when `CMF_M3_PROFILE_SAVE=<path>` is set.
17926    fn m3_note_route(&mut self, li: usize, winners: &[u32]) {
17927        if winners.is_empty() {
17928            return;
17929        }
17930        if self.m3_n_exp == 0 {
17931            self.m3_n_exp = crate::minicpm_tail::minimax_n_experts(&self.weights.layers, self.phys_layer(0)).max(1);
17932            self.m3_counts = vec![0; self.num_layers * self.m3_n_exp];
17933        }
17934        for &e in winners {
17935            let e = e as usize;
17936            if e < self.m3_n_exp && li < self.num_layers {
17937                self.m3_counts[li * self.m3_n_exp + e] = self.m3_counts[li * self.m3_n_exp + e].saturating_add(1);
17938            }
17939        }
17940        if li + 1 == self.num_layers {
17941            self.m3_tokens += 1;
17942            if self.m3_tokens % 16 == 0 {
17943                if let Ok(path) = std::env::var("CMF_M3_PROFILE_SAVE") {
17944                    let bytes: Vec<u8> = self.m3_counts.iter().flat_map(|c| c.to_le_bytes()).collect();
17945                    let _ = std::fs::write(&path, bytes);
17946                }
17947            }
17948        }
17949    }
17950
17951    /// Admit the most frequent (layer, expert) pairs of a saved profile into
17952    /// the bank before the first token: `CMF_M3_PROFILE=<path>` names the
17953    /// file, `CMF_M3_PREWARM_N` (default 300) bounds how many experts go in.
17954    /// The bank's own eviction stays in charge; prewarm only chooses order.
17955    fn m3_prewarm(&mut self) {
17956        let Ok(path) = std::env::var("CMF_M3_PROFILE") else {
17957            return;
17958        };
17959        let Ok(bytes) = std::fs::read(&path) else {
17960            tracing::warn!("m3 prewarm: cannot read profile {path}");
17961            return;
17962        };
17963        let counts: Vec<u32> = bytes
17964            .chunks_exact(4)
17965            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
17966            .collect();
17967        let n_exp = crate::minicpm_tail::minimax_n_experts(&self.weights.layers, self.phys_layer(0)).max(1);
17968        if counts.len() != self.num_layers * n_exp {
17969            tracing::warn!("m3 prewarm: profile size {} does not match {}x{}", counts.len(), self.num_layers, n_exp);
17970            return;
17971        }
17972        let limit: usize = std::env::var("CMF_M3_PREWARM_N")
17973            .ok()
17974            .and_then(|v| v.parse().ok())
17975            .unwrap_or(300);
17976        let mut ranked: Vec<(u32, usize, usize)> = counts
17977            .iter()
17978            .enumerate()
17979            .filter(|(_, c)| **c > 0)
17980            .map(|(i, &c)| (c, i / n_exp, i % n_exp))
17981            .collect();
17982        ranked.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)).then(a.2.cmp(&b.2)));
17983        ranked.truncate(limit);
17984        let mut per_layer: Vec<Vec<usize>> = vec![Vec::new(); self.num_layers];
17985        for (_, li, e) in ranked {
17986            per_layer[li].push(e);
17987        }
17988        let mut admitted = 0usize;
17989        for (li, ids) in per_layer.iter().enumerate() {
17990            if ids.is_empty() {
17991                continue;
17992            }
17993            let lw = &self.weights.layers[self.phys_layer(li)];
17994            let FfnKind::Moe(m) = &lw.ffn else {
17995                continue;
17996            };
17997            // Arming installs the layer's layout; nothing predicted yet.
17998            let _ = crate::minicpm_tail::minimax_pool_arm(m, li, self.num_layers, &[]);
17999            if crate::minicpm_tail::minimax_pool_ensure(m, li, self.num_layers, ids) {
18000                admitted += ids.len();
18001            }
18002        }
18003        tracing::info!("m3 prewarm: admitted {admitted} experts from {path}");
18004    }
18005
18006    /// One MiniMax tail layer through the pooled token-graph arm: attention,
18007    /// the pre-FFN norm, device routing and the descriptor-indexed expert
18008    /// bank in ONE submit (one sync instead of host attention + a MoE
18009    /// frame), with cold experts finished on the host against the read-back
18010    /// FFN input and admitted for the next token.
18011    ///
18012    /// `Ok(true)` — the layer is done (hidden replaced). `Ok(false)` —
18013    /// decline before any device mutation; the ordinary host path owns this
18014    /// position. `Err(())` — the device failed after admission; the caller
18015    /// must stop the sequence exactly like a failed span run.
18016    #[cfg(feature = "gpu")]
18017    fn m3_pooled_layer(&mut self, li: usize, position: usize, h: &mut Vec<f32>) -> Result<bool, ()> {
18018        if self.o1_active() || self.attn_softcap > 0.0 {
18019            return Ok(false);
18020        }
18021        if !self.m3_prewarmed {
18022            self.m3_prewarmed = true;
18023            self.m3_prewarm();
18024        }
18025        let frame = {
18026            let lw = &self.weights.layers[self.phys_layer(li)];
18027            let FfnKind::Moe(m) = &lw.ffn else {
18028                return Ok(false);
18029            };
18030            if !crate::minicpm_tail::MiniCpmTail::is_requested_target(m) {
18031                return Ok(false);
18032            }
18033            let t_arm = std::time::Instant::now();
18034            if self.m3_winners.len() != self.num_layers {
18035                self.m3_winners = vec![Vec::new(); self.num_layers];
18036            }
18037            let pred = std::mem::take(&mut self.m3_winners[li]);
18038            let armed = crate::minicpm_tail::minimax_pool_arm(m, li, self.num_layers, &pred);
18039            if armed.is_none() {
18040                self.m3_winners[li] = pred; // declined before anything ran
18041            }
18042            M3_ARM_NS.fetch_add(t_arm.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
18043            match armed {
18044                Some(frame) => frame,
18045                // First-call refusal (geometry/bank): the host layer still
18046                // runs; nothing was mutated.
18047                None => return Ok(false),
18048            }
18049        };
18050        crate::gpu_wgpu::pooled_frame_enter(frame);
18051        // The pooled call must not fold lm_head: its cold experts have to
18052        // land before any final norm. The decode loop re-arms this flag for
18053        // the next position anyway.
18054        let want_logits = self.graph_want_logits;
18055        self.graph_want_logits = false;
18056        let mut lg = Vec::new();
18057        let mut gl = 0usize;
18058        let t_span = std::time::Instant::now();
18059        let span = crate::gpu::gpu_scope(|| {
18060            self.try_token_graph_wgpu_span(h, position, &mut lg, li, li + 1, &mut gl)
18061        });
18062        self.graph_want_logits = want_logits;
18063        M3_SPAN_NS.fetch_add(t_span.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
18064        let hh = match span {
18065            Some(Ok(hh)) => hh,
18066            Some(Err(())) => return Err(()),
18067            None => {
18068                // Declined before submission (seed/resolve/refusal): the
18069                // device mirror has not moved, so the host path is exact.
18070                return Ok(false);
18071            }
18072        };
18073        if gl != 1 {
18074            // A single-layer run that reports no layer mutated nothing we
18075            // may build on; anything else is a contract break.
18076            return if gl == 0 { Ok(false) } else { Err(()) };
18077        }
18078        *h = hh;
18079        let winners = crate::gpu_wgpu::pooled_frame_take_winners();
18080        self.m3_note_route(li, &winners);
18081        if self.m3_winners.len() != self.num_layers {
18082            self.m3_winners = vec![Vec::new(); self.num_layers];
18083        }
18084        self.m3_winners[li] = winners;
18085        let mut cold = crate::gpu_wgpu::pooled_frame_take_cold();
18086        // A non-finite parsed weight would poison the residual for the rest
18087        // of the sequence — drop such entries loudly instead.
18088        cold.retain(|&(_, w)| {
18089            if w.is_finite() {
18090                true
18091            } else {
18092                tracing::error!("pooled tail: non-finite cold weight from expert route");
18093                false
18094            }
18095        });
18096        if cold.is_empty() {
18097            return Ok(true);
18098        }
18099        let x = crate::gpu_wgpu::pooled_frame_take_input();
18100        if x.len() != self.hidden_size {
18101            return Err(());
18102        }
18103        // Cold experts: on the device first (admit, then one prepared frame
18104        // over exactly those slots — one submit for the layer). The host
18105        // computes them only when the device declines, and then they are
18106        // admitted for the next token. `CMF_M3_COLD_CPU=1` forces the host
18107        // arm for an A/B measurement.
18108        let lw = &self.weights.layers[self.phys_layer(li)];
18109        let FfnKind::Moe(m) = &lw.ffn else {
18110            return Err(());
18111        };
18112        let t_cold = std::time::Instant::now();
18113        let force_host = std::env::var("CMF_M3_COLD_CPU").as_deref() == Ok("1");
18114        let mut out = crate::attention::take_buf(self.hidden_size);
18115        let on_device = !force_host
18116            && crate::minicpm_tail::minimax_cold_device(m, li, self.num_layers, &cold, &x, &mut out);
18117        if !on_device {
18118            crate::attention::recycle_buf(&mut out);
18119            let jobs: Vec<(&crate::pipeline::DenseFfn, f32)> = cold
18120                .iter()
18121                .map(|&(e, w)| m.experts.get(e).map(|ex| (ex, w)).ok_or(()))
18122                .collect::<Result<_, ()>>()?;
18123            out = crate::gpu::cpu_scope(|| {
18124                crate::pipeline::moe_cold_experts_cpu(&jobs, &x, self.pool.as_deref())
18125            });
18126            let ids: Vec<usize> = cold.iter().map(|&(e, _)| e).collect();
18127            let _ = crate::minicpm_tail::minimax_pool_ensure(m, li, self.num_layers, &ids);
18128        }
18129        M3_COLD_NS.fetch_add(t_cold.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
18130        M3_COLD_N.fetch_add(cold.len() as u64, std::sync::atomic::Ordering::Relaxed);
18131        if out.len() != h.len() {
18132            crate::attention::recycle_buf(&mut out);
18133            return Err(());
18134        }
18135        for (dst, src) in h.iter_mut().zip(out.iter()) {
18136            *dst += src;
18137        }
18138        crate::attention::recycle_buf(&mut out);
18139        if on_device {
18140            M3_COLD_DEV_N.fetch_add(cold.len() as u64, std::sync::atomic::Ordering::Relaxed);
18141        }
18142        Ok(true)
18143    }
18144
18145    #[cfg(not(feature = "gpu"))]
18146    fn m3_pooled_layer(
18147        &mut self,
18148        _li: usize,
18149        _position: usize,
18150        _h: &mut Vec<f32>,
18151    ) -> Result<bool, ()> {
18152        Ok(false)
18153    }
18154
18155    /// Greedy burst: forward `t_next` and let the device pick + re-embed
18156    /// the next k−1 tokens — k frames, ONE submit, k ids back. The ZML
18157    /// trade, on wgpu. None ⇒ caller keeps the per-token path.
18158    fn try_multi_burst(&self, t_next: u32, position: usize, k: usize) -> Option<Vec<u32>> {
18159        if self.o1_active() || self.attn_softcap > 0.0 {
18160            return None;
18161        }
18162        // The burst builds the whole-token graph; attention the graph's
18163        // per-layer geometry cannot express keeps the per-token path.
18164        if let Some(reason) = self.wgpu_graph_attn_decline() {
18165            self.note_graph_decline("wgpu multi-burst", reason);
18166            return None;
18167        }
18168        let graph_on = crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode);
18169        if !graph_on || self.graph_refused() {
18170            // Same memo as the decode site: this path builds the very
18171            // same graph, so a model it cannot build for must not be
18172            // walked again here either. Missing this guard was worth
18173            // 2.5x on an Adreno — 0.361 tok/s against 0.905 — because
18174            // the burst retried per token what decode had already given
18175            // up on.
18176            return None;
18177        }
18178        let emb = self.embed_single(t_next);
18179        let mut lg = Vec::new();
18180        let mut ids = Vec::new();
18181        match self.try_token_graph_wgpu_steps(
18182            &emb,
18183            position,
18184            &mut lg,
18185            k,
18186            Some(&mut ids),
18187            None,
18188            0,
18189            self.num_layers,
18190        ) {
18191            Some(Ok(_)) => {}
18192            Some(Err(())) => {
18193                // Preserve the backend's post-admission failure through the
18194                // Option-based burst API.  The decode caller consumes this
18195                // flag and clears the sequence instead of falling through
18196                // to a stale CPU recurrent state.
18197                self.graph_failed
18198                    .store(true, std::sync::atomic::Ordering::Relaxed);
18199                return None;
18200            }
18201            None => return None,
18202        }
18203        (ids.len() == k).then_some(ids)
18204    }
18205
18206    /// The sequence may keep f16 K/V mirrors on the wgpu graphs (`kv16`):
18207    /// nothing it runs reads f32 mirror rows — no MTP head, no drafter, no
18208    /// O(1) seal, no block preview.
18209    fn kv16_allowed(&self) -> bool {
18210        self.mtp.is_none()
18211            && self.dflash.is_none()
18212            && !self.o1_active()
18213            && !self.is_block_diffusion()
18214            && self.clover.is_none()
18215    }
18216
18217    /// Multi-step greedy: k whole frames in ONE submit, argmax and re-embed
18218    /// on the device. `ids_out` receives the k winner ids; the hidden/logits
18219    /// outputs are NOT produced in that mode.
18220    fn try_token_graph_wgpu_steps(
18221        &self,
18222        hidden: &[f32],
18223        position: usize,
18224        logits_out: &mut Vec<f32>,
18225        steps: usize,
18226        ids_out: Option<&mut Vec<u32>>,
18227        layers_run: Option<&mut usize>,
18228        from: usize,
18229        upto_excl: usize,
18230    ) -> Option<Result<Vec<f32>, ()>> {
18231        crate::gpu::graph_kv16_note(self.graph_kv_id, self.kv16_allowed());
18232        // SenseNova-Loop: MRoPE prompt rows rotate on the host; the graph's
18233        // mHC kernels take two streams only, and a graph must not enter an
18234        // mHC range midway (its streams would be the host's).
18235        if self.prompt_mrope.is_some()
18236            || self.mhc.as_deref().is_some_and(|m| {
18237                from < self.num_layers && m.on(self.phys_layer(from)) && !m.enters(self.phys_layer(from))
18238            })
18239            || self.mhc.as_ref().is_some_and(|m| m.s.streams != 2 || m.s.fixed_identity)
18240            || std::env::var("CMF_MHC_GRAPH").as_deref() == Ok("0")
18241                && (from..upto_excl.min(self.num_layers)).any(|li| self.mhc_layer(li))
18242        {
18243            return None;
18244        }
18245        // The bank has already reserved its VRAM. Never build a second
18246        // all-expert arena across bank-owned layers (including bursts).
18247        let upto_excl = match self.mimo_moe.graph_prefix_end() {
18248            Some(end) if end < upto_excl => {
18249                if steps != 1 || layers_run.is_none() || from >= end {
18250                    return None;
18251                }
18252                end
18253            }
18254            _ => upto_excl,
18255        };
18256        // O(1) Nyström decode runs off the sealed state, not the KV cache the
18257        // graph mirrors — never take the graph while o1 is active.
18258        let o1_gpu = self.o1_on_graph();
18259        if (self.o1_active() && !o1_gpu) || self.attn_softcap > 0.0 {
18260            // Softcapped scores have no graph kernel yet — CPU owns them.
18261            // o1 rides the graph only behind CMF_O1_GPU=1 while the port
18262            // proves itself; without it the CPU path owns o1 as before.
18263            return None;
18264        }
18265        // Per-layer KV heads, narrow V, sinks and sliding windows ride
18266        // `GraphAttn::Full::geom` (the ATTEND_X kernels). Anything that
18267        // geometry cannot express declines here, by name — before the
18268        // per-layer gate existed a sliding/sink model ran the graph as
18269        // full-context attention, fluent and wrong. The caller memoizes
18270        // the refusal.
18271        if let Some(reason) = self.wgpu_graph_attn_decline() {
18272            self.note_graph_decline("wgpu token graph", reason);
18273            return None;
18274        }
18275        // Per-layer sealed o1 state for the graph. During prefill the
18276        // state is still Collecting -> views are None -> the graph
18277        // refuses below and the CPU prefill records the q trace and
18278        // seals, exactly as the o1 design requires.
18279        let o1_views: Vec<Option<Vec<crate::nystrom::O1DeviceView<'_>>>> = (from..upto_excl)
18280            .map(|li| {
18281                if !o1_gpu {
18282                    return None;
18283                }
18284                self.kv_cache.layers[self.phys_layer(li)].o1_views()
18285            })
18286            .collect();
18287        if self.o1_active() && o1_gpu {
18288            // Any o1 layer not sealed (or degenerate exact-only) keeps the
18289            // whole token on the CPU: half-graph forwards would desync.
18290            let want: usize = (from..upto_excl)
18291                .filter(|li| self.kv_cache.layers[self.phys_layer(*li)].o1.is_some())
18292                .count();
18293            let have = o1_views.iter().filter(|v| v.is_some()).count();
18294            if want == 0 || have != want {
18295                // The silent twin of the gpu-side o1 gates, found the
18296                // same way: a 15x decode drop with an empty log. Views
18297                // stay None until the layer's state SEALS, so `have`
18298                // lagging `want` early in a run is the o1 design working
18299                // — but it must say so, or the next reader spends a
18300                // night proving the kernels innocent.
18301                // On CHANGE, not once: the first decline is the legal
18302                // unsealed prefill, and a once-print buries the state
18303                // that matters — what the count reads AFTER the seal.
18304                use std::sync::atomic::{AtomicUsize, Ordering};
18305                static LAST: AtomicUsize = AtomicUsize::new(usize::MAX);
18306                let code = have * 1000 + want;
18307                if LAST.swap(code, Ordering::Relaxed) != code {
18308                    tracing::warn!(
18309                        "o1 graph: {have} of {want} layers sealed — per-op until all seal"
18310                    );
18311                }
18312                return None;
18313            }
18314        }
18315        let nh = self.num_heads;
18316        let (nkv, hd, rd) = self.layer_geom(0);
18317        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
18318        // Ripple's value residual: the embedding row of this position. A
18319        // span past the first layer reads the one `forward_layers_span` kept.
18320        let vres_e0: &[f32] = if from == 0 { hidden } else { &self.vres_e0 };
18321        let mut layers = Vec::with_capacity(upto_excl - from);
18322        let mut model = None;
18323        let dbg = std::env::var("CMF_GRAPH_DEBUG").is_ok();
18324        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
18325            // `blr` rides as GRAPH_KIND_BLR (two stage dispatches).
18326            if let Some((m, i, kind, rs)) = t.graph_weight_or_blr() {
18327                let name = &m.tensors[i].name;
18328                let prism = if crate::prism::is_inverse_embedding(m, name) {
18329                    crate::gpu::GraphPrismOp::InverseEmbedding
18330                } else if crate::prism::is_forward_weight(m, name) {
18331                    crate::gpu::GraphPrismOp::Forward
18332                } else {
18333                    crate::gpu::GraphPrismOp::None
18334                };
18335                return Some(crate::gpu::GraphW {
18336                    idx: i,
18337                    kind,
18338                    row_scale: rs,
18339                    data: &[],
18340                    prism,
18341                    affine: crate::prism::is_affine_target(m, name),
18342                });
18343            }
18344            // Small unquantized projections (GDN in_proj_a/b) stay f32.
18345            match t.as_f32() {
18346                Some(d) => Some(crate::gpu::GraphW {
18347                    idx: 0,
18348                    kind: 4,
18349                    row_scale: &[],
18350                    data: d,
18351                    prism: crate::gpu::GraphPrismOp::None,
18352                    affine: false,
18353                }),
18354                None => {
18355                    if std::env::var_os("CMF_BATCH_DEBUG").is_some() {
18356                        eprintln!("batch graph: weight has no graph/f32 representation");
18357                    }
18358                    None
18359                }
18360            }
18361        }
18362        for li in from..upto_excl {
18363            let lw = &self.weights.layers[self.phys_layer(li)];
18364            if dbg {
18365                let ak = match &lw.attn {
18366                    AttnKind::Mla(_) => "Mla".into(),
18367                    AttnKind::Full {
18368                        output_gate, bias, ..
18369                    } => format!("Full gate={output_gate} bias={}", bias.is_some()),
18370                    AttnKind::LinearGdn(_) => "LinearGdn".into(),
18371                    AttnKind::Kda(_) => "Kda".into(),
18372                    AttnKind::Linear(_) => "Linear".into(),
18373                    AttnKind::ShortConv(_) => "ShortConv".into(),
18374                    AttnKind::Bounded(_) => "Bounded".into(),
18375                };
18376                let fk = match &lw.ffn {
18377                    FfnKind::Dense(_) => "Dense",
18378                    FfnKind::Moe(_) => "Moe",
18379                    FfnKind::DenseMoe(_) => "DenseMoe",
18380                };
18381                eprintln!("graph L{li}: attn={ak} ffn={fk}");
18382            }
18383            let gffn = match &lw.ffn {
18384                FfnKind::DenseMoe(_) => return None, // dual branch: CPU path
18385                // A tube layer is several matrices, not one. The graph has
18386                // a shape for the core with one more triple that is always
18387                // on (a hot-neuron file); task tubes keep the segmented path.
18388                FfnKind::Dense(d) if d.segs.len() > 1 => return None,
18389                FfnKind::Dense(d) => {
18390                    // An activation the graph has no kernel arm for keeps
18391                    // the CPU/per-op owner, by name — the dense graph FFN
18392                    // used to compute SiLU for whatever the model asked.
18393                    let Some((act, limit)) = d.act.dense_graph_contract() else {
18394                        self.note_graph_decline(
18395                            "wgpu token graph",
18396                            "dense FFN activation without a graph kernel",
18397                        );
18398                        return None;
18399                    };
18400                    crate::gpu::GraphFfn::Dense {
18401                        gate: gw(&d.gate_proj)?,
18402                        up: gw(&d.up_proj)?,
18403                        down: gw(&d.down_proj)?,
18404                        act,
18405                        limit,
18406                        hot: match d.segs.first() {
18407                            Some(seg) => Some(crate::gpu::GraphMoeDetachedShared {
18408                                gate: gw(&seg.gate)?,
18409                                up: gw(&seg.up)?,
18410                                down: gw(&seg.down)?,
18411                                width: seg.width,
18412                            }),
18413                            None => None,
18414                        },
18415                    }
18416                }
18417                FfnKind::Moe(m) => {
18418                    // Adaptive τ and expert masks keep the CPU path, where
18419                    // they are implemented. Sigmoid routing with a selection
18420                    // bias (LFM2-MoE / DeepSeek noaux_tc), a routed scale ≠ 1
18421                    // and an UNGATED shared expert (HunYuan hy_v3: ×2.826 on
18422                    // the routed mix, the shared expert at weight 1) are all
18423                    // graphed — before, every such token fell to the per-op
18424                    // path whole (145 submits/token on Hy-MT2-30B-A3B).
18425                    if m.route_tau.is_some() || m.mask.is_some() {
18426                        return None;
18427                    }
18428                    let shared = m.shared.as_ref();
18429                    // The resident MoE kernels do not yet carry the
18430                    // descriptor-aware transform through router/shared-gate
18431                    // selection.  Refuse the complete layer instead of
18432                    // scoring with an untransformed Prism plane (the dense
18433                    // path has an explicit FWHT boundary below).
18434                    let inter = m.experts.first()?.gate_proj.rows();
18435                    // Flint's shared expert is a 1024-wide SwiGLU while its
18436                    // routed bank is 512-wide.  The resident MoE shader
18437                    // indexes a uniform-width packed bank, so keep that
18438                    // expert out of the routed slots and add it through the
18439                    // dense q4tp path after routed accumulation.  This is
18440                    // also the safe route for a mixed q2-routed/q4-shared
18441                    // artifact: neither layout nor row stride is faked.
18442                    let detached_shared = match shared {
18443                        Some((se, None))
18444                            if se.gate_proj.rows() != inter || se.up_proj.rows() != inter =>
18445                        {
18446                            let q4 = se.gate_proj.mapped_q4tp().is_some()
18447                                && se.up_proj.mapped_q4tp().is_some()
18448                                && se.down_proj.mapped_q4tp().is_some();
18449                            let q8 = se.gate_proj.mapped_q8_2f().is_some()
18450                                && se.up_proj.mapped_q8_2f().is_some()
18451                                && se.down_proj.mapped_q8_2f().is_some();
18452                            if !matches!(se.act, Act::Silu) || !(q4 || q8) {
18453                                return None;
18454                            }
18455                            Some(crate::gpu::GraphMoeDetachedShared {
18456                                gate: gw(&se.gate_proj)?,
18457                                up: gw(&se.up_proj)?,
18458                                down: gw(&se.down_proj)?,
18459                                width: se.gate_proj.rows(),
18460                            })
18461                        }
18462                        // A separately shaped gated shared expert needs a
18463                        // second sigmoid gate path.  Do not turn it into an
18464                        // ungated one merely to make the graph run.
18465                        Some((se, Some(_)))
18466                            if se.gate_proj.rows() != inter || se.up_proj.rows() != inter =>
18467                        {
18468                            return None;
18469                        }
18470                        _ => None,
18471                    };
18472                    let has_shared = shared.is_some() && detached_shared.is_none();
18473                    let shared_gated = has_shared && matches!(shared, Some((_, Some(_))));
18474                    let sgate = match shared {
18475                        Some((_, Some(sg))) if has_shared => gw(sg)?,
18476                        // No gate, no shared expert, or a detached shared
18477                        // expert: the router only keeps the binding total;
18478                        // the selection shader does not read it.
18479                        _ => gw(&m.router)?,
18480                    };
18481                    let router = gw(&m.router)?;
18482                    // The resident MoE kernels do not yet carry the
18483                    // descriptor-aware transform through router/shared-gate
18484                    // selection.  Refuse the complete layer instead of
18485                    // scoring with an untransformed Prism plane (the dense
18486                    // path has an explicit FWHT boundary below).
18487                    if router.prism != crate::gpu::GraphPrismOp::None
18488                        || sgate.prism != crate::gpu::GraphPrismOp::None
18489                        || router.affine
18490                        || sgate.affine
18491                    {
18492                        tracing::warn!(
18493                            "resident MoE declined: Prism/affine router or shared gate transform is not implemented"
18494                        );
18495                        return None;
18496                    }
18497                    let in_bank_shared = shared.filter(|_| has_shared).map(|(se, _)| se);
18498                    let edge = |t: &QTensor| {
18499                        t.graph_weight()
18500                            .or_else(|| t.graph_weight_descriptor())
18501                            .map(|(mm, i, _, _)| (std::sync::Arc::as_ptr(mm) as usize, i))
18502                    };
18503                    let bank_key: Option<GraphMoeKey> = match (
18504                        m.experts.first().and_then(|e| edge(&e.gate_proj)),
18505                        m.experts.last().and_then(|e| edge(&e.down_proj)),
18506                    ) {
18507                        (Some((fm, fi)), Some((_, di))) if graph_moe_bank_on() => Some((
18508                            self.phys_layer(li),
18509                            m.experts.as_ptr() as usize,
18510                            m.experts.len(),
18511                            in_bank_shared.map_or(0, |se| std::ptr::from_ref(se) as usize),
18512                            fm,
18513                            fi,
18514                            di,
18515                        )),
18516                        _ => None,
18517                    };
18518                    let cached =
18519                        bank_key.and_then(|k| self.graph_moe_banks.lock().unwrap().get(&k).cloned());
18520                    let bank = if let Some(b) = cached {
18521                        b
18522                    } else {
18523                    let mut experts = Vec::with_capacity(m.experts.len() + 1);
18524                    let mut bank_model: Option<std::sync::Arc<cortiq_core::CmfModel>> = None;
18525                    // q4t or q4tp, but not both in one layer — the kernels
18526                    // are picked per layer, not per expert.
18527                    let mut q4tp: Option<bool> = None;
18528                    // The mixed 2-bit profile: q2tp gate/up over a q4tp
18529                    // down. Uniform across the layer, like `q4tp` itself.
18530                    let mut gu_q2: Option<bool> = None;
18531                    // q8_2f experts (gate, up and down): their own kernels.
18532                    let mut q82: Option<bool> = None;
18533                    // One MoE gate/up kernel serves the complete packed bank.
18534                    // Bind an activation only when every routed (and in-bank
18535                    // shared) expert owns the same exact WGPU contract.
18536                    let mut moe_act = None;
18537                    for e in m.experts.iter().chain(in_bank_shared.into_iter()) {
18538                        let Some(e_act) = e.act.wgpu_graph_act() else {
18539                            return None;
18540                        };
18541                        match moe_act {
18542                            Some(existing) if existing != e_act => return None,
18543                            None => moe_act = Some(e_act),
18544                            _ => {}
18545                        }
18546                        if e.gate_proj.rows() != inter || e.up_proj.rows() != inter {
18547                            return None;
18548                        }
18549                        // Expert tensors are packed into one resident buffer
18550                        // and the MoE kernels have no transform slot per
18551                        // expert.  Keep the CPU/per-op owner for Prism or
18552                        // affine experts rather than silently using raw bytes.
18553                        for expert_weight in [&e.gate_proj, &e.up_proj, &e.down_proj] {
18554                            let Some((em, ei, _, _)) = expert_weight
18555                                .graph_weight()
18556                                .or_else(|| expert_weight.graph_weight_descriptor())
18557                            else {
18558                                return None;
18559                            };
18560                            let name = &em.tensors[ei].name;
18561                            if crate::prism::is_forward_weight(em, name)
18562                                || crate::prism::is_inverse_embedding(em, name)
18563                                || crate::prism::is_affine_target(em, name)
18564                            {
18565                                tracing::warn!(
18566                                    "resident MoE declined: expert Prism/affine transform is not implemented"
18567                                );
18568                                return None;
18569                            }
18570                        }
18571                        let (mm, gi, ui, di, is_p, is_q2, is_8) = match e.gate_proj.mapped_q4t() {
18572                            Some((mm, gi)) => (
18573                                mm,
18574                                gi,
18575                                e.up_proj.mapped_q4t()?.1,
18576                                e.down_proj.mapped_q4t()?.1,
18577                                false,
18578                                false,
18579                                false,
18580                            ),
18581                            None => match e.gate_proj.mapped_q2tp() {
18582                                Some((mm, gi)) => (
18583                                    mm,
18584                                    gi,
18585                                    e.up_proj.mapped_q2tp()?.1,
18586                                    e.down_proj.mapped_q4tp()?.1,
18587                                    true,
18588                                    true,
18589                                    false,
18590                                ),
18591                                None => match e.gate_proj.mapped_q4tp() {
18592                                    Some((mm, gi)) => (
18593                                        mm,
18594                                        gi,
18595                                        e.up_proj.mapped_q4tp()?.1,
18596                                        e.down_proj.mapped_q4tp()?.1,
18597                                        true,
18598                                        false,
18599                                        false,
18600                                    ),
18601                                    // q8_2f experts: all three projections,
18602                                    // each with its own column field.
18603                                    None => {
18604                                        if !crate::gpu::moe_q82_graph_on() {
18605                                            return None;
18606                                        }
18607                                        let (mm, gi) = e.gate_proj.mapped_q8_2f()?;
18608                                        (
18609                                            mm,
18610                                            gi,
18611                                            e.up_proj.mapped_q8_2f()?.1,
18612                                            e.down_proj.mapped_q8_2f()?.1,
18613                                            false,
18614                                            false,
18615                                            true,
18616                                        )
18617                                    }
18618                                },
18619                            },
18620                        };
18621                        if *q4tp.get_or_insert(is_p) != is_p
18622                            || *gu_q2.get_or_insert(is_q2) != is_q2
18623                            || *q82.get_or_insert(is_8) != is_8
18624                        {
18625                            // The shared expert rides in the same packed
18626                            // buffer as the routed ones, so a layer that
18627                            // mixes layouts cannot be indexed by one stride.
18628                            // Say so: the symptom is a whole model quietly
18629                            // running its MoE on the CPU.
18630                            tracing::warn!(
18631                                "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."
18632                            );
18633                            return None;
18634                        }
18635                        bank_model.get_or_insert_with(|| mm.clone());
18636                        experts.push((gi, ui, di));
18637                    }
18638                    let b = GraphMoeBank {
18639                        experts,
18640                        q4tp,
18641                        gu_q2,
18642                        q82,
18643                        act: moe_act,
18644                        model: bank_model,
18645                    };
18646                    if let Some(k) = bank_key {
18647                        self.graph_moe_banks.lock().unwrap().insert(k, b.clone());
18648                    }
18649                    b
18650                    };
18651                    if let Some(mm) = &bank.model {
18652                        model.get_or_insert_with(|| mm.clone());
18653                    }
18654                    crate::gpu::GraphFfn::Moe {
18655                        latent: None,
18656                        shared_limit: None,
18657                        router,
18658                        shared_gate: sgate,
18659                        experts: bank.experts,
18660                        n_exp: m.experts.len(),
18661                        // CMF_TOPK_PROBE: timing probe only — output is WRONG.
18662                        // Fewer experts shrink the MoE arithmetic while the
18663                        // dispatch count stays identical, which is the only
18664                        // clean way to tell a launch-bound decode from a
18665                        // compute-bound one.
18666                        top_k: std::env::var("CMF_TOPK_PROBE")
18667                            .ok()
18668                            .and_then(|v| v.parse::<usize>().ok())
18669                            .filter(|k| *k > 0 && *k <= m.top_k)
18670                            .unwrap_or(m.top_k),
18671                        inter,
18672                        act: bank.act?,
18673                        norm_topk: m.norm_topk_prob,
18674                        q4tp: bank.q4tp?,
18675                        gu_q2: bank.gu_q2.unwrap_or(false),
18676                        q82: bank.q82.unwrap_or(false),
18677                        sigmoid: m.router_sigmoid,
18678                        sigmoid_denom_eps: m.sigmoid_denom_eps,
18679                        bias: m.expert_bias.as_deref(),
18680                        has_shared,
18681                        detached_shared,
18682                        shared_gated,
18683                        route_scale: m.routed_scaling,
18684                        limit: 0.0,
18685                    }
18686                }
18687            };
18688            let attn = match &lw.attn {
18689                AttnKind::Full {
18690                    wq,
18691                    wk,
18692                    wv,
18693                    wo,
18694                    q_norm,
18695                    k_norm,
18696                    output_gate,
18697                    softplus_gate,
18698                    bias,
18699                } => {
18700                    if self.attention_heads_per_layer.is_some() {
18701                        return None;
18702                    }
18703                    // A projected output gate rides the graph in one form:
18704                    // Spark-X2.5's head-wise sigmoid (one g_proj row per Q
18705                    // head). Laguna's softplus gate keeps the CPU path.
18706                    let head_gate = match softplus_gate {
18707                        None => None,
18708                        Some((g, true)) if self.proj_gate_sigmoid && !*output_gate => Some(gw(g)?),
18709                        Some(_) => {
18710                            self.note_graph_decline(
18711                                "wgpu token graph",
18712                                "projected softplus / per-element output gate",
18713                            );
18714                            return None;
18715                        }
18716                    };
18717                    model = Some(self.graph_model_of(&[wq, wk, wv, wo])?);
18718                    crate::gpu::GraphAttn::Full {
18719                        wq: gw(wq)?,
18720                        wk: gw(wk)?,
18721                        wv: gw(wv)?,
18722                        wo: gw(wo)?,
18723                        q_norm: q_norm.as_deref(),
18724                        k_norm: k_norm.as_deref(),
18725                        late_qk_norm: self.qk_norm_after_rope,
18726                        bias: bias
18727                            .as_ref()
18728                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
18729                        output_gate: *output_gate,
18730                        cpu_k: self.kv_cache.layers[li].k_heads(),
18731                        cpu_v: self.kv_cache.layers[li].v_heads(),
18732                        cpu_base: self.kv_cache.layers[li].base(),
18733                        geom: self.graph_attn_geom_decode(li, vres_e0),
18734                        head_gate,
18735                    }
18736                }
18737                AttnKind::LinearGdn(w) => {
18738                    let cfg = self.gdn_cfg?;
18739                    model = Some(self.graph_model_of(&[&w.in_proj_qkv, &w.in_proj_z, &w.out_proj])?);
18740                    crate::gpu::GraphAttn::Gdn {
18741                        qkv: gw(&w.in_proj_qkv)?,
18742                        z: gw(&w.in_proj_z)?,
18743                        a: gw(&w.in_proj_a)?,
18744                        b: gw(&w.in_proj_b)?,
18745                        out: gw(&w.out_proj)?,
18746                        conv1d: &w.conv1d,
18747                        a_log: &w.a_log,
18748                        dt_bias: &w.dt_bias,
18749                        norm: &w.norm,
18750                        nv: cfg.num_v_heads,
18751                        nk: cfg.num_k_heads,
18752                        dk: cfg.key_head_dim,
18753                        dv: cfg.value_head_dim,
18754                        kk: cfg.conv_kernel,
18755                        cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
18756                        preview: None,
18757                    }
18758                }
18759                AttnKind::ShortConv(w) => {
18760                    let cfg = self.short_conv_cfg?;
18761                    let (m, _, _, _) = w
18762                        .in_proj
18763                        .graph_weight()
18764                        .or_else(|| w.in_proj.graph_weight_descriptor())?;
18765                    model = Some(m.clone());
18766                    crate::gpu::GraphAttn::ShortConv {
18767                        inp: gw(&w.in_proj)?,
18768                        out: gw(&w.out_proj)?,
18769                        taps: &w.conv,
18770                        kernel: cfg.kernel,
18771                        cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
18772                    }
18773                }
18774                // Kimi-Linear's mixers: the CUDA hybrid arm runs them, the
18775                // wgpu graphs decline them at their entry
18776                AttnKind::Kda(_) | AttnKind::Mla(_) => {
18777                    let (attn, m) = self.graph_attn_kimi(li, &lw.attn, &gw)?;
18778                    model = Some(m);
18779                    attn
18780                }
18781                _ => return None,
18782            };
18783            layers.push(crate::gpu::GraphLayer {
18784                engram: None,
18785                mhc: crate::sensenova::graph_mhc(self.mhc.as_deref(), self.phys_layer(li)),
18786                input_norm: &lw.input_norm,
18787                attn,
18788                post_norm: &lw.post_norm,
18789                attn_out_norm: lw.attn_out_norm.as_deref(),
18790                ffn_out_norm: lw.ffn_out_norm.as_deref(),
18791                layer_scale: lw.layer_scale,
18792                ffn: gffn,
18793            });
18794        }
18795        let model = model?;
18796        // Fold final-norm + lm_head into the graph when this call wants logits
18797        // and the lm_head is a graphable (quantized) weight — the graph then
18798        // reads back logits (into logits_out) instead of the hidden, dropping
18799        // the separate CPU/GPU lm_head op + its sync. Never the f32 fallback:
18800        // an unquantized lm_head is vocab·hidden and must not be uploaded.
18801        let lm_gw = if upto_excl == self.num_layers
18802            && self.graph_want_logits
18803            && std::env::var("CMF_GPU_LMHEAD")
18804                .map(|v| v != "0")
18805                .unwrap_or(true)
18806        {
18807            self.weights
18808                .lm_head
18809                .graph_weight()
18810                .or_else(|| self.weights.lm_head.graph_weight_descriptor())
18811                .map(|(m, i, kind, rs)| {
18812                    let name = &m.tensors[i].name;
18813                    let prism = if crate::prism::is_inverse_embedding(m, name) {
18814                        crate::gpu::GraphPrismOp::InverseEmbedding
18815                    } else if crate::prism::is_forward_weight(m, name) {
18816                        crate::gpu::GraphPrismOp::Forward
18817                    } else {
18818                        crate::gpu::GraphPrismOp::None
18819                    };
18820                    (
18821                        crate::gpu::GraphW {
18822                            idx: i,
18823                            kind,
18824                            row_scale: rs,
18825                            data: &[],
18826                            prism,
18827                            affine: crate::prism::is_affine_target(m, name),
18828                        },
18829                        self.weights.lm_head.rows(),
18830                    )
18831                })
18832        } else {
18833            None
18834        };
18835        let lm = lm_gw.as_ref().map(|(gw, rows)| (gw, *rows));
18836        // Multi-step re-embeds the winner on the device.
18837        let emb_gw = if steps > 1 {
18838            self.weights
18839                .embed_tokens
18840                .graph_weight()
18841                .or_else(|| self.weights.embed_tokens.graph_weight_descriptor())
18842                .map(|(m, i, kind, rs)| {
18843                    let name = &m.tensors[i].name;
18844                    let prism = if crate::prism::is_inverse_embedding(m, name) {
18845                        crate::gpu::GraphPrismOp::InverseEmbedding
18846                    } else if crate::prism::is_forward_weight(m, name) {
18847                        crate::gpu::GraphPrismOp::Forward
18848                    } else {
18849                        crate::gpu::GraphPrismOp::None
18850                    };
18851                    (
18852                        crate::gpu::GraphW {
18853                            idx: i,
18854                            kind,
18855                            row_scale: rs,
18856                            data: &[],
18857                            prism,
18858                            affine: crate::prism::is_affine_target(m, name),
18859                        },
18860                        self.weights.embed_tokens.rows(),
18861                        self.embed_multiplier,
18862                    )
18863                })
18864        } else {
18865            None
18866        };
18867
18868        // Loop boundaries: virtual layer indices after which final_norm is
18869        // applied (mid-stack only; the GLOBAL last layer's norm folds into
18870        // lm_head). Span-relative — the executor compares its enumerate
18871        // index. A span ending mid-stack keeps its boundary norm even when
18872        // it is the span's own last layer.
18873        let loop_norm_at: Vec<usize> = if self.loop_final_norm {
18874            (from..upto_excl.min(self.num_layers - 1))
18875                .filter(|&li| (li + 1) % self.physical_layers == 0)
18876                .map(|li| li - from)
18877                .collect()
18878        } else {
18879            Vec::new()
18880        };
18881        let mut h = hidden.to_vec();
18882        // The normal decode path only needs the fused lm-head logits.  A
18883        // CMF_LOGIT_DUMP diagnostic, however, promises a prompt-boundary
18884        // post-stack hidden alongside those logits; request the existing
18885        // second readback only for that explicit probe instead of dumping
18886        // the input copy left in `h` by a folded-head graph.
18887        let dump_hidden = std::env::var_os("CMF_LOGIT_DUMP").is_some();
18888        let mut taps = if steps == 1 { self.dflash_taps_wanted(from, upto_excl) } else { Vec::new() };
18889        let n_dflash = taps.len();
18890        // Dynamic skill routing reads φ, the residual after the router's
18891        // layer, every token: the graph keeps that row the way it keeps a
18892        // drafter's, and `forward_layers_upto` folds it into the EMA.
18893        let phi_slot = match self.dyn_phi_layer {
18894            Some(l) if steps == 1 && (from..upto_excl).contains(&l) => {
18895                Some(taps.iter().position(|&t| t == l).unwrap_or_else(|| {
18896                    taps.push(l);
18897                    taps.len() - 1
18898                }))
18899            }
18900            _ => None,
18901        };
18902        *self.dyn_phi_tap.lock().unwrap() = None;
18903        crate::gpu::layer_taps_arm(&taps);
18904        let outcome = crate::gpu::forward_token_graph(
18905            &model,
18906            self.graph_kv_id,
18907            &layers,
18908            &o1_views,
18909            self.o1_epoch,
18910            &self.inv_freq,
18911            &mut h,
18912            nh,
18913            nkv,
18914            hd,
18915            self.attn_scale,
18916            rd,
18917            self.hidden_size,
18918            self.intermediate_size,
18919            position,
18920            self.kv_cache.max_seq_len,
18921            gemma,
18922            self.rms_eps as f32,
18923            lm,
18924            &self.weights.final_norm,
18925            logits_out,
18926            &loop_norm_at,
18927            steps,
18928            emb_gw.as_ref().map(|(gw, rows, m)| (gw, *rows, *m)),
18929            ids_out,
18930            layers_run,
18931            from,
18932            dump_hidden,
18933        );
18934        self.graph_taps_keep(&taps, n_dflash, phi_slot, position, 1, outcome == crate::gpu::TokenGraphOutcome::Completed);
18935        match outcome {
18936            crate::gpu::TokenGraphOutcome::Completed => Some(Ok(h)),
18937            crate::gpu::TokenGraphOutcome::Failed => Some(Err(())),
18938            crate::gpu::TokenGraphOutcome::Declined => None,
18939        }
18940    }
18941
18942    /// Batched prefill: k contiguous prompt positions through the whole wgpu
18943    /// graph in ONE submit (projections/FFN as GEMMs). `hiddens` is [k·hidden]
18944    /// in/out (embeddings in, layer output out); KV mirror / GDN state advance.
18945    /// false ⇒ unsupported → caller keeps the per-position graph.
18946    /// The b-row Metal graph plan for the whole model: every layer as a
18947    /// GDN run or a full-attention item, all-or-nothing (a layer outside the
18948    /// graph's contract → None, the caller runs plain). Shared by the
18949    /// speculative verify and the batched prefill.
18950    #[cfg(target_os = "macos")]
18951    #[allow(clippy::type_complexity)]
18952    fn metal_rows_plan(
18953        &self,
18954    ) -> Option<(
18955        Vec<MetalRowsItem<'_>>,
18956        std::sync::Arc<cortiq_core::CmfModel>,
18957        Option<crate::gpu_metal::GdnGpuCfg>,
18958    )> {
18959        use crate::gpu_metal::{AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, MetalFfn};
18960        let graph_force = crate::gpu::q1_force() || crate::gpu::q2tp_gpu_opt_in();
18961        if !graph_force
18962            || !crate::gpu::enabled_here()
18963            || std::env::var("CMF_GPU_BLOCK")
18964                .map(|v| v == "0")
18965                .unwrap_or(false)
18966            || self.attn_softcap > 0.0
18967            || (self.o1_active() && !self.o1_on_graph())
18968            // Sliding windows with per-layer RoPE (Spark-X2.6) ride the rows graph
18969            // as they ride the chunk graph (`metal_graph_swa`).
18970            || (self.swa.is_some() && !self.metal_graph_swa())
18971            || self.global_attn.is_some()
18972            || self.attention_heads_per_layer.is_some()
18973            // per-layer KV heads, narrow V, learned sinks (MiMo-V2)
18974            || (self.graph_attn_decline_reason().is_some() && !self.metal_graph_swa())
18975            || self.attn_v_norm
18976            || self.loop_final_norm
18977            || !self.metal_rope_scale_ok()
18978        {
18979            return None;
18980        }
18981        let attend_contract = self.head_dim % 4 == 0
18982            && self.head_dim <= 256
18983            && self.rotary_dim >= 2
18984            && self.rotary_dim <= self.head_dim
18985            && (self.rotary_dim / 2) % 32 == 0
18986            && self.num_kv_heads > 0
18987            && self.num_heads % self.num_kv_heads == 0;
18988        if !attend_contract {
18989            return None;
18990        }
18991        let mut plan: Vec<MetalRowsItem> = Vec::new();
18992        let mut model_ref: Option<std::sync::Arc<cortiq_core::CmfModel>> = None;
18993        // SenseNova-Loop's mHC streams ride the rows graph as they ride the token graph:
18994        // two streams, the Sinkhorn mix, kernels that compiled. `CMF_METAL_ROWS_MHC=0`
18995        // keeps such a prompt on the token graph, a row at a time.
18996        if self.mhc.as_ref().is_some_and(|m| m.s.streams != 2 || m.s.fixed_identity)
18997            || (self.mhc.is_some()
18998                && (!crate::gpu_metal::mhc::available()
18999                    || std::env::var("CMF_MHC_GRAPH").as_deref() == Ok("0")
19000                    || std::env::var("CMF_METAL_ROWS_MHC").as_deref() == Ok("0")))
19001        {
19002            return None;
19003        }
19004        for li in 0..self.num_layers {
19005            let lw = &self.weights.layers[self.phys_layer(li)];
19006            if lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some() {
19007                return None;
19008            }
19009            let mhc = if self.mhc_layer(li) {
19010                Some(crate::sensenova::graph_mhc(self.mhc.as_deref(), self.phys_layer(li))?)
19011            } else {
19012                None
19013            };
19014            let ffn = match &lw.ffn {
19015                FfnKind::Dense(d) if matches!(d.act, Act::Silu | Act::Gelu) && d.segs.is_empty() => {
19016                    let (Some(g), Some(u), Some(dn)) = (
19017                        d.gate_proj.metal_graph_parts(),
19018                        d.up_proj.metal_graph_parts(),
19019                        d.down_proj.metal_graph_parts(),
19020                    ) else {
19021                        return None;
19022                    };
19023                    MetalFfn::Dense {
19024                        gate: g,
19025                        up: u,
19026                        down: dn,
19027                        // SiLU, or the exact GELU of Spark-X2.6 (`gelu_rows`).
19028                        act: if d.act == Act::Gelu { 1 } else { 0 },
19029                    }
19030                }
19031                _ => return None,
19032            };
19033            match &lw.attn {
19034                AttnKind::LinearGdn(w) if self.gdn_cfg.is_some() => {
19035                    let (Some(qkv), Some(z), Some(a), Some(bb), Some(out)) = (
19036                        w.in_proj_qkv.metal_graph_parts(),
19037                        w.in_proj_z.metal_graph_parts(),
19038                        w.in_proj_a.f32_parts(),
19039                        w.in_proj_b.f32_parts(),
19040                        w.out_proj.metal_graph_parts(),
19041                    ) else {
19042                        return None;
19043                    };
19044                    if let QTensor::Mapped { model, .. } = &w.in_proj_qkv {
19045                        model_ref.get_or_insert_with(|| model.clone());
19046                    }
19047                    let gl = GdnGpuLayer {
19048                        mhc,
19049                        attn_norm: &lw.input_norm,
19050                        post_norm: &lw.post_norm,
19051                        qkv,
19052                        z,
19053                        a,
19054                        b: bb,
19055                        out,
19056                        ffn,
19057                        conv1d: &w.conv1d,
19058                        a_log: &w.a_log,
19059                        dt_bias: &w.dt_bias,
19060                        gnorm: &w.norm,
19061                    };
19062                    match plan.last_mut() {
19063                        Some(MetalRowsItem::Gdn { run, .. }) => run.push(gl),
19064                        _ => plan.push(MetalRowsItem::Gdn {
19065                            run: vec![gl],
19066                            first: li,
19067                        }),
19068                    }
19069                }
19070                AttnKind::Full {
19071                    wq,
19072                    wk,
19073                    wv,
19074                    wo,
19075                    q_norm,
19076                    k_norm,
19077                    output_gate,
19078                    softplus_gate,
19079                    bias: None,
19080                } => {
19081                    // Spark-X2.6's per-head sigmoid g_proj gate, from f32 rows.
19082                    let head_gate = match softplus_gate {
19083                        None => None,
19084                        Some((g, true)) if self.proj_gate_sigmoid && !*output_gate => match g.f32_parts() {
19085                            Some((d, r, c)) if r == self.num_heads && c == self.hidden_size => Some(d),
19086                            _ => return None,
19087                        },
19088                        Some(_) => return None,
19089                    };
19090                    let (Some(pq), Some(pk), Some(pv), Some(po)) = (
19091                        wq.metal_graph_parts(),
19092                        wk.metal_graph_parts(),
19093                        wv.metal_graph_parts(),
19094                        wo.metal_graph_parts(),
19095                    ) else {
19096                        return None;
19097                    };
19098                    if let QTensor::Mapped { model, .. } = wq {
19099                        model_ref.get_or_insert_with(|| model.clone());
19100                    }
19101                    let cache = &self.kv_cache.layers[li];
19102                    if cache.mode != crate::kv_cache::KvMode::F32 || (cache.o1.is_some() && !self.o1_on_graph()) {
19103                        return None;
19104                    }
19105                    plan.push(MetalRowsItem::Attn {
19106                        l: AttnGpuLayer {
19107                            mhc,
19108                            attn_norm: &lw.input_norm,
19109                            post_norm: &lw.post_norm,
19110                            wq: pq,
19111                            wk: pk,
19112                            wv: pv,
19113                            wo: po,
19114                            ffn,
19115                            attn_out_norm: None,
19116                            ffn_out_norm: None,
19117                            layer_scale: None,
19118                        },
19119                        li,
19120                        q_norm: q_norm.as_deref(),
19121                        k_norm: k_norm.as_deref(),
19122                        output_gate: *output_gate,
19123                        head_gate,
19124                    });
19125                }
19126                _ => return None,
19127            }
19128        }
19129        let model = model_ref?;
19130        let gcfg = self.gdn_cfg.map(|cfg| GdnGpuCfg {
19131            nv: cfg.num_v_heads,
19132            nk: cfg.num_k_heads,
19133            dk: cfg.key_head_dim,
19134            dv: cfg.value_head_dim,
19135            kk: cfg.conv_kernel,
19136            hidden: self.hidden_size,
19137            inter: self.intermediate_size,
19138            c_dim: cfg.conv_dim(),
19139            eps: cfg.rms_eps as f32,
19140            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
19141        });
19142        Some((plan, model, gcfg))
19143    }
19144
19145    /// `AttnDeviceParams` for a plan item over the CPU cache as it stands.
19146    #[cfg(target_os = "macos")]
19147    #[allow(clippy::too_many_arguments)]
19148    fn metal_attn_params<'a>(
19149        li: usize,
19150        cache: &'a crate::kv_cache::LayerKvCache,
19151        q_norm: Option<&'a [f32]>,
19152        k_norm: Option<&'a [f32]>,
19153        output_gate: bool,
19154        inv_freq: &'a [f32],
19155        rope_scale: f32,
19156        geom: (usize, usize, usize, usize),
19157        pos0: usize,
19158        kv_id: u64,
19159        scale: f32,
19160        eps: f32,
19161        gemma: bool,
19162        late_qk_norm: bool,
19163        o1_epoch: u64,
19164        head_gate: Option<&'a [f32]>,
19165        window: Option<usize>,
19166    ) -> (crate::gpu_metal::AttnDeviceParams<'a>, usize) {
19167        let (nh, nkv, hd, rd) = geom;
19168        let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
19169        let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
19170        let cpu_stored = cpu_k[0].len() / hd;
19171        (
19172            crate::gpu_metal::AttnDeviceParams {
19173                kv_id,
19174                layer: li,
19175                nh,
19176                nkv,
19177                hd,
19178                rd,
19179                position: pos0,
19180                scale,
19181                eps,
19182                gemma,
19183                late_qk_norm,
19184                output_gate,
19185                q_norm,
19186                k_norm,
19187                inv_freq,
19188                rope_scale,
19189                cpu_k,
19190                cpu_v,
19191                cpu_stored,
19192                cpu_gen: cache.generation(),
19193                // A layer still collecting has no views, and its rows go through the mirror.
19194                o1: cache.o1_views().map(|views| crate::gpu_metal::O1AttnParams { views, epoch: o1_epoch }),
19195                window,
19196                softmax_sink: cache.sinks.as_deref(),
19197                head_gate,
19198                v_norm: false,
19199                dash: None,
19200            },
19201            cpu_stored,
19202        )
19203    }
19204
19205    /// Run the rows plan over `hiddens` (b rows at `pos0..`): validate,
19206    /// encode every item, optionally the head, sync. Returns the graph
19207    /// (for the commit / state finish) plus the GDN layer indices and the
19208    /// attention layers with the row count they were encoded against.
19209    #[cfg(target_os = "macos")]
19210    #[allow(clippy::type_complexity)]
19211    fn metal_rows_run(
19212        &mut self,
19213        hiddens: &mut [f32],
19214        pos0: usize,
19215        b: usize,
19216        prefill: bool,
19217        spec: Option<((usize, usize, usize), &[f32], &mut Vec<f32>)>,
19218        // Greedy verify: (row length scored, the b argmax ids out) — the
19219        // head's argmax runs on the device and the logits plane is NOT
19220        // read back (`spec.2` stays empty).
19221        mut argmax_out: Option<(usize, &mut Vec<u32>)>,
19222    ) -> MetalRowsRun {
19223        use crate::gpu_metal::{GraphDims, VerifyGraph};
19224        // The previous round's commit may still be replaying into the
19225        // trunk GDN owners on the second queue: this graph reads them
19226        // (zero-copy wraps) and may reallocate them below — collect the
19227        // replay first. Normally already complete (the draft chain ran
19228        // in between); a failed replay is terminal like a failed commit.
19229        if !crate::gpu_metal::wait_replay() {
19230            tracing::error!("Metal rows graph: the pending async replay failed");
19231            return MetalRowsRun::Failed;
19232        }
19233        spec_stamp("v.wait");
19234        // Seed the GDN recurrent records the rows graph reads — GDN layers
19235        // ONLY (the record the CPU path would allocate anyway).  Sizing
19236        // every layer here planted a zero GDN-sized record on a bounded
19237        // anchor of a natively bounded file this path then refused, and
19238        // that record counted as recurrent state on macOS.
19239        let want = self.gdn_cfg.map(|c| c.state_len()).unwrap_or(0);
19240        if want > 0 {
19241            // a looped stack's visit runs its physical layer (`phys_layer`), not `li % phys`
19242            let gdn: Vec<bool> = (0..self.kv_cache.layers.len())
19243                .map(|li| {
19244                    self.weights
19245                        .layers
19246                        .get(self.phys_layer(li))
19247                        .is_some_and(|lw| matches!(lw.attn, AttnKind::LinearGdn(_)))
19248                })
19249                .collect();
19250            for (l, is_gdn) in self.kv_cache.layers.iter_mut().zip(gdn) {
19251                if is_gdn && l.linear_state.len() != want {
19252                    l.linear_state = vec![0f32; want];
19253                }
19254            }
19255        }
19256        let Some((plan, model, gcfg)) = self.metal_rows_plan() else {
19257            return MetalRowsRun::Declined;
19258        };
19259        spec_stamp("v.plan");
19260        let dims = GraphDims {
19261            hidden: self.hidden_size,
19262            eps: self.rms_eps as f32,
19263            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
19264        };
19265        // A prompt chunk for the Neural Engine goes as two halves, a thread each: one is on the
19266        // ANE while the GPU has the other.
19267        let hs = self.hidden_size;
19268        let relay = prefill
19269            && spec.is_none()
19270            && b >= 128
19271            && crate::gpu_metal::ane::wanted()
19272            && std::env::var("CMF_ANE_RELAY").as_deref() != Ok("0");
19273        let cuts: Vec<(usize, usize)> = if relay { vec![(0, b / 2), (b / 2, b - b / 2)] } else { vec![(0, b)] };
19274        let gate = crate::gpu_metal::LaneGate::new();
19275        let mut lanes: Vec<VerifyGraph> = Vec::with_capacity(cuts.len());
19276        for (ln, &(r0, n)) in cuts.iter().enumerate() {
19277            let h = &hiddens[r0 * hs..(r0 + n) * hs];
19278            let g = if relay {
19279                VerifyGraph::new_prefill_lane(&model, dims, h, n, ln, b - r0 - n, &gate)
19280            } else if prefill {
19281                VerifyGraph::new_prefill(&model, dims, h, n)
19282            } else {
19283                VerifyGraph::new(&model, dims, h, n)
19284            };
19285            let Some(g) = g else {
19286                return MetalRowsRun::Declined;
19287            };
19288            lanes.push(g);
19289        }
19290        if prefill {
19291            use crate::gpu_metal::{AneWants, MetalFfn};
19292            // SiLU or the exact GELU (Spark-X2.6), one activation for the file's FFNs.
19293            let mut ane_act = None;
19294            let ffn = |f: &MetalFfn<'_>, ane_act: &mut Option<u8>| match f {
19295                MetalFfn::Dense { gate, up, down, act } if *act <= 1 && ane_act.is_none_or(|a| a == *act) => {
19296                    *ane_act = Some(*act);
19297                    Some([*gate, *up, *down])
19298                }
19299                _ => None,
19300            };
19301            let mut wants = Vec::new();
19302            for item in &plan {
19303                match item {
19304                    MetalRowsItem::Gdn { run, .. } => {
19305                        wants.extend(run.iter().map(|l| AneWants {
19306                            ffn: ffn(&l.ffn, &mut ane_act),
19307                            mix: if crate::gpu_metal::ane_takes_qkv() { vec![l.qkv, l.z] } else { vec![l.z] },
19308                        }))
19309                    }
19310                    MetalRowsItem::Attn { l, .. } => wants.push(AneWants {
19311                        ffn: ffn(&l.ffn, &mut ane_act),
19312                        mix: if crate::gpu_metal::ane_takes_qkv() {
19313                            vec![l.wk, l.wv, l.wq]
19314                        } else if crate::gpu_metal::ane_takes_q() {
19315                            vec![l.wq]
19316                        } else {
19317                            Vec::new()
19318                        },
19319                    }),
19320                }
19321            }
19322            crate::gpu_metal::ane::set_act(ane_act.unwrap_or(0));
19323            for g in lanes.iter_mut() {
19324                g.ane_attach(&wants);
19325            }
19326            lanes[0].ane_begin(lanes.len());
19327        }
19328        // With the Neural Engine a layer's command is committed as it ends, so a refusal past
19329        // the first one leaves states half written.
19330        let hard = relay || lanes[0].has_ane();
19331        let geom = (
19332            self.num_heads,
19333            self.num_kv_heads,
19334            self.head_dim,
19335            self.rotary_dim,
19336        );
19337        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
19338        let eps = self.rms_eps as f32;
19339        let kv_id = self.graph_kv_id;
19340        // Each layer's own RoPE table and width (Spark-X2.6: sliding and full layers differ).
19341        let tables: Vec<std::sync::Arc<Vec<f32>>> = (0..self.num_layers).map(|li| self.layer_inv_freq(li)).collect();
19342        let lgeom = |li: usize| (geom.0, geom.1, geom.2, self.layer_geom(li).2);
19343        for item in &plan {
19344            let ok = match item {
19345                MetalRowsItem::Gdn { run, .. } => gcfg
19346                    .as_ref()
19347                    .map(|gc| lanes.iter().all(|g| run.iter().all(|l| g.gdn_ok(l, gc))))
19348                    .unwrap_or(false),
19349                MetalRowsItem::Attn {
19350                    l,
19351                    li,
19352                    q_norm,
19353                    k_norm,
19354                    output_gate,
19355                    head_gate,
19356                } => {
19357                    let (p, _) = Self::metal_attn_params(
19358                        *li,
19359                        &self.kv_cache.layers[*li],
19360                        *q_norm,
19361                        *k_norm,
19362                        *output_gate,
19363                        &tables[*li],
19364                        self.layer_rope_scale(*li),
19365                        lgeom(*li),
19366                        pos0,
19367                        kv_id,
19368                        self.attn_scale,
19369                        eps,
19370                        gemma,
19371                        self.qk_norm_after_rope,
19372                        self.o1_epoch,
19373                        *head_gate,
19374                        self.layer_window(*li),
19375                    );
19376                    lanes.iter().all(|g| g.attn_ok(l, &p))
19377                }
19378            };
19379            if !ok {
19380                use std::sync::atomic::{AtomicBool, Ordering};
19381                static SAID: AtomicBool = AtomicBool::new(false);
19382                if !SAID.swap(true, Ordering::Relaxed) {
19383                    tracing::warn!("metal rows graph: a layer failed preflight — declining");
19384                }
19385                return MetalRowsRun::Declined;
19386            }
19387        }
19388        let lm = match &spec {
19389            Some((lm, _, _)) => {
19390                if !lanes[0].lm_head_ok(*lm) {
19391                    return MetalRowsRun::Declined;
19392                }
19393                Some(*lm)
19394            }
19395            None => None,
19396        };
19397        // What each half encodes, layer by layer: nothing here changes while they run.
19398        enum Step<'a> {
19399            Gdn(&'a crate::gpu_metal::GdnGpuLayer<'a>, &'a [f32]),
19400            Attn(&'a crate::gpu_metal::AttnGpuLayer<'a>, crate::gpu_metal::AttnDeviceParams<'a>),
19401        }
19402        let mut gdn_layers = Vec::new();
19403        let mut attn_layers = Vec::new();
19404        let mut steps: Vec<Vec<Step<'_>>> = cuts.iter().map(|_| Vec::new()).collect();
19405        // the layer each step is, for the rows a DFlash drafter reads
19406        let mut step_layer: Vec<usize> = Vec::new();
19407        for item in &plan {
19408            match item {
19409                MetalRowsItem::Gdn { run, first } => {
19410                    for (l, kv) in run.iter().zip(&self.kv_cache.layers[*first..*first + run.len()]) {
19411                        for st in steps.iter_mut() {
19412                            st.push(Step::Gdn(l, kv.linear_state.as_slice()));
19413                        }
19414                    }
19415                    gdn_layers.extend(*first..*first + run.len());
19416                    step_layer.extend(*first..*first + run.len());
19417                }
19418                MetalRowsItem::Attn {
19419                    l,
19420                    li,
19421                    q_norm,
19422                    k_norm,
19423                    output_gate,
19424                    head_gate,
19425                } => {
19426                    for (ln, st) in steps.iter_mut().enumerate() {
19427                        let (mut p, cpu_stored) = Self::metal_attn_params(
19428                            *li,
19429                            &self.kv_cache.layers[*li],
19430                            *q_norm,
19431                            *k_norm,
19432                            *output_gate,
19433                            &tables[*li],
19434                            self.layer_rope_scale(*li),
19435                            lgeom(*li),
19436                            pos0 + cuts[ln].0,
19437                            kv_id,
19438                            self.attn_scale,
19439                            eps,
19440                            gemma,
19441                            self.qk_norm_after_rope,
19442                            self.o1_epoch,
19443                            *head_gate,
19444                            self.layer_window(*li),
19445                        );
19446                        // The half before leaves its rows in the mirror, not yet in the host's.
19447                        p.cpu_stored += cuts[ln].0;
19448                        // A sealed layer leaves no mirror row to pull.
19449                        if ln == 0 && p.o1.is_none() {
19450                            attn_layers.push((*li, cpu_stored));
19451                        }
19452                        st.push(Step::Attn(l, p));
19453                    }
19454                    step_layer.push(*li);
19455                }
19456            }
19457        }
19458        // The outputs of the layers a DFlash drafter reads are kept on the way
19459        // (one graph only: a chunk in halves through the Neural Engine keeps none).
19460        let taps: Vec<usize> = match &self.dflash {
19461            Some(d) if !relay => d.g.taps.clone(),
19462            _ => Vec::new(),
19463        };
19464        let tap_slot: Vec<Option<usize>> = step_layer.iter().map(|l| taps.iter().position(|t| t == l)).collect();
19465        let tapped = std::sync::atomic::AtomicUsize::new(0);
19466        // One half's layers in order; `Err` tells whether a command was already committed.
19467        let gc = gcfg.as_ref();
19468        let walk = |g: &mut VerifyGraph, steps: &[Step<'_>]| -> Result<(), bool> {
19469            for (i, step) in steps.iter().enumerate() {
19470                let ok = match step {
19471                    Step::Gdn(l, state) => match gc {
19472                        Some(gc) => g.encode_gdn_run_b(std::slice::from_ref(*l), &[*state], gc),
19473                        None => false,
19474                    },
19475                    Step::Attn(l, p) => g.encode_attn_b(l, p),
19476                };
19477                if !ok {
19478                    return Err(i > 0);
19479                }
19480                if let Some(slot) = tap_slot.get(i).copied().flatten() {
19481                    if g.tap(slot, taps.len()) {
19482                        tapped.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
19483                    }
19484                }
19485            }
19486            Ok(())
19487        };
19488        let refused = |started: bool| if hard && started { MetalRowsRun::Failed } else { MetalRowsRun::Declined };
19489        if relay {
19490            let (first, second) = lanes.split_at_mut(1);
19491            let (sa, sb) = (&steps[0], &steps[1]);
19492            let (ra, rb) = std::thread::scope(|sc| {
19493                let other = sc.spawn(|| {
19494                    let r = walk(&mut second[0], sb);
19495                    if r.is_err() {
19496                        // The first half must not wait for this one's turn on the ANE.
19497                        crate::gpu_metal::ane::retire("a half of the chunk stopped");
19498                    }
19499                    r
19500                });
19501                let r = walk(&mut first[0], sa);
19502                if r.is_err() {
19503                    gate.fail();
19504                }
19505                (r, other.join().unwrap_or(Err(true)))
19506            });
19507            if ra.is_err() || rb.is_err() {
19508                return MetalRowsRun::Failed;
19509            }
19510        } else if let Err(started) = walk(&mut lanes[0], &steps[0]) {
19511            return refused(started);
19512        }
19513        drop(steps);
19514        if let (Some(lm), Some((_, final_norm, _))) = (lm, spec.as_ref()) {
19515            if !lanes[0].encode_lm_head_b(final_norm, lm) {
19516                return refused(true);
19517            }
19518            // The device argmax is an OPTIMISATION, never a reason to
19519            // decline the round: if it will not encode, drop it and read
19520            // the logits plane back the old way (the head is encoded
19521            // either way, so the rows are there).
19522            if let Some((n, _)) = argmax_out.as_ref() {
19523                if !lanes[0].encode_argmax_b(*n) {
19524                    argmax_out = None;
19525                }
19526            }
19527        }
19528        spec_stamp("v.enc");
19529        for g in lanes.iter_mut() {
19530            if !g.sync() {
19531                return MetalRowsRun::Failed;
19532            }
19533        }
19534        spec_stamp("v.gpu");
19535        match (spec, argmax_out) {
19536            (Some(_), Some((_, ids))) => {
19537                ids.resize(b, 0);
19538                if !lanes[0].read_argmax(ids) {
19539                    return MetalRowsRun::Failed;
19540                }
19541                spec_stamp("v.am");
19542            }
19543            (Some((lm, _, logits)), None) => {
19544                logits.resize(b * lm.1, 0.0);
19545                if !lanes[0].read_logits(logits) {
19546                    return MetalRowsRun::Failed;
19547                }
19548                spec_stamp("v.lg");
19549            }
19550            (None, _) => {}
19551        }
19552        for (g, &(r0, n)) in lanes.iter().zip(&cuts) {
19553            if !g.read_hidden(&mut hiddens[r0 * hs..(r0 + n) * hs]) {
19554                return MetalRowsRun::Failed;
19555            }
19556        }
19557        spec_stamp("v.hid");
19558        // The tapped rows, a row's layers joined: a prompt's rows are context at
19559        // once, a verify's wait for the round to say which of them it keeps.
19560        self.dflash_rows = None;
19561        if !taps.is_empty() && tapped.load(std::sync::atomic::Ordering::Relaxed) == taps.len() && lanes.len() == 1 {
19562            let nt = taps.len();
19563            let mut raw = vec![0f32; nt * b * hs];
19564            if lanes[0].read_taps(&mut raw) {
19565                let mut joined = vec![0f32; b * nt * hs];
19566                for s in 0..nt {
19567                    for r in 0..b {
19568                        joined[(r * nt + s) * hs..][..hs].copy_from_slice(&raw[(s * b + r) * hs..][..hs]);
19569                    }
19570                }
19571                if prefill {
19572                    if let Some(d) = self.dflash.as_mut() {
19573                        d.queue_context(pos0, &joined, self.pool.as_deref());
19574                    }
19575                } else {
19576                    self.dflash_rows = Some((pos0, joined));
19577                }
19578                spec_stamp("v.taps");
19579            }
19580        }
19581        // The last half's graph: the layers' states are the chunk's.
19582        let graph = lanes.pop().unwrap();
19583        MetalRowsRun::Completed(MetalVerifyPending {
19584            graph,
19585            gdn_layers,
19586            attn_layers,
19587        })
19588    }
19589
19590    /// Native-Metal twin of `try_batch_graph_wgpu`: the b rows through the
19591    /// whole model on the `VerifyGraph` (one submit), the head folded in
19592    /// when `spec` asks; `hiddens` come back as the last layer's output
19593    /// rows, `spec.2` as `[b][lm_rows]` logits. The graph is parked in
19594    /// `metal_verify` for `metal_verify_commit`.
19595    #[cfg(target_os = "macos")]
19596    fn try_batch_graph_metal(
19597        &mut self,
19598        hiddens: &mut [f32],
19599        positions: &[usize],
19600        b: usize,
19601        spec: Option<((usize, usize, usize), &[f32], &mut Vec<f32>)>,
19602        argmax_out: Option<(usize, &mut Vec<u32>)>,
19603    ) -> crate::gpu::BatchGraphOutcome {
19604        let _t0 = std::time::Instant::now();
19605        if positions.len() != b
19606            || self.prompt_mrope.is_some()
19607            || self.value_blend.is_some()
19608            || positions.windows(2).any(|w| w[1] != w[0] + 1)
19609            || hiddens.len() != b * self.hidden_size
19610        {
19611            return crate::gpu::BatchGraphOutcome::Declined;
19612        }
19613        let pending = match self.metal_rows_run(hiddens, positions[0], b, false, spec, argmax_out) {
19614            MetalRowsRun::Declined => return crate::gpu::BatchGraphOutcome::Declined,
19615            MetalRowsRun::Failed => return crate::gpu::BatchGraphOutcome::Failed,
19616            MetalRowsRun::Completed(pending) => pending,
19617        };
19618        if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
19619            eprintln!(
19620                "metal-verify: {:.1} ms | b={b}",
19621                _t0.elapsed().as_secs_f64() * 1e3
19622            );
19623        }
19624        self.metal_verify = Some(pending);
19625        crate::gpu::BatchGraphOutcome::Completed
19626    }
19627
19628    /// Batched prefill on the Metal rows graph: `ids` (≤ 512) at
19629    /// `start_pos..`, states written in place, K/V rows appended to the
19630    /// CPU caches; optional final norm/head logits are returned in `spec`.
19631    /// Declined means no command buffer was admitted; Failed is terminal.
19632    #[cfg(target_os = "macos")]
19633    fn prefill_rows_metal(
19634        &mut self,
19635        ids: &[u32],
19636        start_pos: usize,
19637        spec: Option<((usize, usize, usize), &[f32], &mut Vec<f32>)>,
19638    ) -> MetalPrefillOutcome {
19639        let b = ids.len();
19640        if b == 0 || b > 512 {
19641            return MetalPrefillOutcome::Declined;
19642        }
19643        let hs = self.hidden_size;
19644        let mut hiddens = vec![0f32; b * hs];
19645        for (j, &id) in ids.iter().enumerate() {
19646            let e = self.embed_single(id);
19647            hiddens[j * hs..(j + 1) * hs].copy_from_slice(&e);
19648        }
19649        self.prefill_hiddens_metal(hiddens, start_pos, spec)
19650    }
19651
19652    /// Ready prompt rows (`b <= 512`) through the rows graph.
19653    #[cfg(target_os = "macos")]
19654    fn prefill_hiddens_metal(
19655        &mut self,
19656        mut hiddens: Vec<f32>,
19657        start_pos: usize,
19658        spec: Option<((usize, usize, usize), &[f32], &mut Vec<f32>)>,
19659    ) -> MetalPrefillOutcome {
19660        let b = hiddens.len() / self.hidden_size;
19661        METAL_PREFILL_CHUNKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
19662        let with_head = spec.is_some();
19663        let mut pending = match self.metal_rows_run(&mut hiddens, start_pos, b, true, spec, None) {
19664            MetalRowsRun::Declined => return MetalPrefillOutcome::Declined,
19665            MetalRowsRun::Failed => {
19666                METAL_PREFILL_ERRORS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
19667                return MetalPrefillOutcome::Failed;
19668            }
19669            MetalRowsRun::Completed(pending) => pending,
19670        };
19671        // states are final: copy them to the owners
19672        let idxs = pending.gdn_layers.clone();
19673        let mut outs: Vec<&mut [f32]> = self
19674            .kv_cache
19675            .layers
19676            .iter_mut()
19677            .enumerate()
19678            .filter(|(i, _)| idxs.binary_search(i).is_ok())
19679            .map(|(_, l)| l.linear_state.as_mut_slice())
19680            .collect();
19681        if !pending.graph.finish_states(&mut outs) {
19682            METAL_PREFILL_ERRORS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
19683            return MetalPrefillOutcome::Failed;
19684        }
19685        let (nkv, hd) = (self.num_kv_heads, self.head_dim);
19686        // Read every layer before mutating any CPU cache.  A missing mirror
19687        // row is a terminal graph failure, not a reason to append a partial
19688        // prefix and replay the remainder serially.
19689        let mut rows = Vec::with_capacity(pending.attn_layers.len());
19690        for (li, cpu_stored) in &pending.attn_layers {
19691            let mut kbuf = vec![0f32; b * nkv * hd];
19692            let mut vbuf = vec![0f32; b * nkv * hd];
19693            if !crate::gpu_metal::kv_mirror_read_rows(
19694                self.graph_kv_id,
19695                *li,
19696                nkv,
19697                hd,
19698                *cpu_stored,
19699                b,
19700                &mut kbuf,
19701                &mut vbuf,
19702            ) {
19703                METAL_PREFILL_ERRORS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
19704                return MetalPrefillOutcome::Failed;
19705            }
19706            rows.push((*li, *cpu_stored, kbuf, vbuf));
19707        }
19708        for (li, cpu_stored, kbuf, vbuf) in rows {
19709            let cache = &mut self.kv_cache.layers[li];
19710            for r in 0..b {
19711                cache.append(
19712                    &kbuf[r * nkv * hd..(r + 1) * nkv * hd],
19713                    &vbuf[r * nkv * hd..(r + 1) * nkv * hd],
19714                    &[],
19715                );
19716            }
19717            crate::gpu_metal::kv_mirror_set_stored(self.graph_kv_id, li, cpu_stored + b);
19718        }
19719        METAL_PREFILL_ROWS.fetch_add(b as u64, std::sync::atomic::Ordering::Relaxed);
19720        if with_head {
19721            METAL_PREFILL_HEAD_ROWS.fetch_add(b as u64, std::sync::atomic::Ordering::Relaxed);
19722        }
19723        // Every layer appended the chunk: sliding layers keep their tails only.
19724        self.swa_trim_tails();
19725        MetalPrefillOutcome::Completed(hiddens)
19726    }
19727
19728    #[cfg(target_os = "macos")]
19729    fn prefill_batch_metal(&mut self, ids: &[u32], start_pos: usize) -> MetalPrefillOutcome {
19730        self.prefill_rows_metal(ids, start_pos, None)
19731    }
19732
19733    /// Exact teacher-forced NLL through the ordinary Metal rows graph.  This
19734    /// is intentionally separate from the serial TokenGraph scorer: every
19735    /// chunk owns a real b-row graph/head completion and the recurrent/KV
19736    /// handoff is committed before the next chunk begins.
19737    #[cfg(target_os = "macos")]
19738    fn nll_batch_metal(&mut self, ids: &[u32], start: usize) -> MetalBatchNllOutcome {
19739        if ids.len() < 2 || self.o1_active() || self.head_clusters.is_some() {
19740            return MetalBatchNllOutcome::Declined;
19741        }
19742        let Some(lm) = self.weights.lm_head.metal_graph_parts() else {
19743            return MetalBatchNllOutcome::Declined;
19744        };
19745        let chunk = std::env::var("CMF_METAL_PREFILL_CHUNK")
19746            .ok()
19747            .and_then(|v| v.parse::<usize>().ok())
19748            .filter(|&v| (1..=512).contains(&v))
19749            .unwrap_or(32);
19750        let final_norm = self.weights.final_norm.clone();
19751        let mut nll = 0.0f64;
19752        let mut count = 0usize;
19753        let mut pos = 0usize;
19754        let mut completed = 0usize;
19755        while pos < ids.len() {
19756            let end = (pos + chunk).min(ids.len());
19757            let mut logits = Vec::new();
19758            let outcome =
19759                self.prefill_rows_metal(&ids[pos..end], pos, Some((lm, &final_norm, &mut logits)));
19760            match outcome {
19761                MetalPrefillOutcome::Declined => {
19762                    return if completed == 0 {
19763                        MetalBatchNllOutcome::Declined
19764                    } else {
19765                        MetalBatchNllOutcome::Failed(format!(
19766                            "ordinary Metal NLL batch declined after {completed} chunks"
19767                        ))
19768                    };
19769                }
19770                MetalPrefillOutcome::Failed => {
19771                    return MetalBatchNllOutcome::Failed(
19772                        "ordinary Metal NLL batch failed after admission".to_string(),
19773                    );
19774                }
19775                MetalPrefillOutcome::Completed(_) => {}
19776            }
19777            completed += 1;
19778            let vocab = self.vocab_size.min(lm.1);
19779            if logits.len() != (end - pos) * lm.1 || vocab == 0 {
19780                return MetalBatchNllOutcome::Failed(
19781                    "ordinary Metal NLL head returned an invalid shape".to_string(),
19782                );
19783            }
19784            for row in 0..(end - pos) {
19785                let absolute = pos + row;
19786                if absolute < start || absolute + 1 >= ids.len() {
19787                    continue;
19788                }
19789                let lg = &mut logits[row * lm.1..row * lm.1 + vocab];
19790                if let Some(mu) = self.logit_multiplier {
19791                    for v in lg.iter_mut() {
19792                        *v *= mu;
19793                    }
19794                }
19795                if let Some(c) = self.final_softcap {
19796                    softcap_in_place(lg, c, self.pool.as_deref());
19797                }
19798                let target = ids[absolute + 1] as usize;
19799                if target >= vocab {
19800                    return MetalBatchNllOutcome::Failed(format!(
19801                        "target token {target} exceeds Metal head rows {vocab}"
19802                    ));
19803                }
19804                let max = lg.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
19805                let lse: f64 = lg
19806                    .iter()
19807                    .map(|&v| ((v - max) as f64).exp())
19808                    .sum::<f64>()
19809                    .ln()
19810                    + max as f64;
19811                nll += lse - lg[target] as f64;
19812                count += 1;
19813            }
19814            pos = end;
19815        }
19816        MetalBatchNllOutcome::Completed(nll, count)
19817    }
19818
19819    /// Commit a Metal verify round: replay the GDN recurrences over the
19820    /// `a + 1` accepted positions into the CPU states, append the accepted
19821    /// K/V rows from the mirrors to the CPU caches, re-point the mirrors.
19822    #[cfg(target_os = "macos")]
19823    fn metal_verify_commit(&mut self, a: usize) -> bool {
19824        let Some(mut pending) = self.metal_verify.take() else {
19825            return false;
19826        };
19827        let n = a + 1;
19828        // encode order == ascending layer order (the plan walks 0..layers)
19829        let idxs = pending.gdn_layers.clone();
19830        let mut outs: Vec<&mut [f32]> = self
19831            .kv_cache
19832            .layers
19833            .iter_mut()
19834            .enumerate()
19835            .filter(|(i, _)| idxs.binary_search(i).is_ok())
19836            .map(|(_, l)| l.linear_state.as_mut_slice())
19837            .collect();
19838        if !pending.graph.commit(n, &mut outs) {
19839            return false;
19840        }
19841        spec_stamp("c.replay");
19842        let (nkv, hd) = (self.num_kv_heads, self.head_dim);
19843        // Read every layer before mutating any CPU cache.  Missing rows are
19844        // terminal after the replay has executed; never append a partial KV
19845        // prefix and continue on a serial path.
19846        let mut rows = Vec::with_capacity(pending.attn_layers.len());
19847        for (li, cpu_stored) in &pending.attn_layers {
19848            let mut kbuf = vec![0f32; n * nkv * hd];
19849            let mut vbuf = vec![0f32; n * nkv * hd];
19850            if !crate::gpu_metal::kv_mirror_read_rows(
19851                self.graph_kv_id,
19852                *li,
19853                nkv,
19854                hd,
19855                *cpu_stored,
19856                n,
19857                &mut kbuf,
19858                &mut vbuf,
19859            ) {
19860                return false;
19861            }
19862            rows.push((*li, *cpu_stored, kbuf, vbuf));
19863        }
19864        for (li, cpu_stored, kbuf, vbuf) in rows {
19865            let cache = &mut self.kv_cache.layers[li];
19866            for r in 0..n {
19867                cache.append(
19868                    &kbuf[r * nkv * hd..(r + 1) * nkv * hd],
19869                    &vbuf[r * nkv * hd..(r + 1) * nkv * hd],
19870                    &[],
19871                );
19872            }
19873            crate::gpu_metal::kv_mirror_set_stored(self.graph_kv_id, li, cpu_stored + n);
19874        }
19875        spec_stamp("c.kv");
19876        true
19877    }
19878
19879    /// The round's warm-ups as ONE b-row graph run over the MTP block on
19880    /// Metal: `pairs` = (trunk hidden, next token) at consecutive positions
19881    /// from `first_pos`; the block's input projection is folded in. This
19882    /// half encodes and SUBMITS (no wait); `mtp_warm_batch_finish` waits
19883    /// and pulls the appended K/V rows into the CPU MTP cache. None = the
19884    /// graph declined (nothing submitted, nothing appended).
19885    #[cfg(target_os = "macos")]
19886    fn mtp_warm_batch_submit(
19887        &mut self,
19888        m: &mut MtpModule,
19889        pairs: &[(&[f32], u32)],
19890        first_pos: usize,
19891    ) -> Option<MetalWarmPending> {
19892        use crate::gpu_metal::{AttnDeviceParams, AttnGpuLayer, GraphDims, MetalFfn, VerifyGraph};
19893        let first_pos = first_pos.saturating_sub(self.mtp_pos_base);
19894        let b = pairs.len();
19895        if b == 0 || b > 512 || m.kv.mode != crate::kv_cache::KvMode::F32 || m.kv.o1.is_some() {
19896            return None;
19897        }
19898        let AttnKind::Full {
19899            wq,
19900            wk,
19901            wv,
19902            wo,
19903            q_norm,
19904            k_norm,
19905            output_gate,
19906            softplus_gate: None,
19907            bias: None,
19908        } = &m.layer.attn
19909        else {
19910            return None;
19911        };
19912        let FfnKind::Dense(d) = &m.layer.ffn else {
19913            return None;
19914        };
19915        if !d.segs.is_empty() {
19916            return None;
19917        }
19918        let (Some(pq), Some(pk), Some(pv), Some(po)) =
19919            (wq.q1_parts(), wk.q1_parts(), wv.q1_parts(), wo.q1_parts())
19920        else {
19921            return None;
19922        };
19923        let (Some(g), Some(u), Some(dn)) = (
19924            d.gate_proj.q1_parts(),
19925            d.up_proj.q1_parts(),
19926            d.down_proj.q1_parts(),
19927        ) else {
19928            return None;
19929        };
19930        let Some(eh) = m.eh_proj.q1_parts() else {
19931            return None;
19932        };
19933        let QTensor::Mapped { model, .. } = wq else {
19934            return None;
19935        };
19936        let model = model.clone();
19937        let hs = self.hidden_size;
19938        // [enorm(embed(tok)); hnorm(hidden)] rows
19939        let mut cat = vec![0f32; b * 2 * hs];
19940        for (j, (h, tok)) in pairs.iter().enumerate() {
19941            let e = self.embed_single(*tok);
19942            let (ce, ch) = cat[j * 2 * hs..(j + 1) * 2 * hs].split_at_mut(hs);
19943            inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, ce);
19944            inference::rms_norm_into(h, &m.hnorm, self.rms_eps, self.norm_style, ch);
19945        }
19946        let dims = GraphDims {
19947            hidden: hs,
19948            eps: self.rms_eps as f32,
19949            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
19950        };
19951        spec_stamp("w.cat");
19952        let Some(mut graph) = VerifyGraph::new_via_proj(&model, dims, eh, &cat, b) else {
19953            return None;
19954        };
19955        spec_stamp("w.new");
19956        let l = AttnGpuLayer {
19957            mhc: None,
19958            attn_norm: &m.layer.input_norm,
19959            post_norm: &m.layer.post_norm,
19960            wq: pq,
19961            wk: pk,
19962            wv: pv,
19963            wo: po,
19964            ffn: MetalFfn::Dense {
19965                gate: g,
19966                up: u,
19967                down: dn,
19968                act: (d.act == Act::Gelu) as u8,
19969            },
19970            attn_out_norm: None,
19971            ffn_out_norm: None,
19972            layer_scale: None,
19973        };
19974        let (nh, nkv, hd, rd) = (
19975            self.num_heads,
19976            self.num_kv_heads,
19977            self.head_dim,
19978            self.rotary_dim,
19979        );
19980        let inv_freq = self.inv_freq.clone();
19981        let cpu_stored;
19982        {
19983            let cache = &m.kv;
19984            let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
19985            let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
19986            cpu_stored = cpu_k[0].len() / hd;
19987            // The cache may LAG the position (rows nobody warmed): the
19988            // pairs land at cpu_stored.. with their true RoPE positions
19989            // first_pos.., exactly what the one-by-one warm does. A cache
19990            // AHEAD of the position is a real inconsistency.
19991            if cpu_stored > first_pos {
19992                spec_stamp("w.decl");
19993                return None;
19994            }
19995            let p = AttnDeviceParams {
19996                kv_id: self.mtp_kv_id(),
19997                layer: Self::MTP_LAYER_BASE,
19998                nh,
19999                nkv,
20000                hd,
20001                rd,
20002                position: first_pos,
20003                scale: self.attn_scale,
20004                eps: self.rms_eps as f32,
20005                gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
20006                late_qk_norm: self.qk_norm_after_rope,
20007                output_gate: *output_gate,
20008                q_norm: q_norm.as_deref(),
20009                k_norm: k_norm.as_deref(),
20010                inv_freq: &inv_freq,
20011                rope_scale: self.rope_scale,
20012                cpu_k,
20013                cpu_v,
20014                cpu_stored,
20015                cpu_gen: cache.generation(),
20016                o1: None,
20017                window: None,
20018                softmax_sink: None,
20019                head_gate: None,
20020                v_norm: false,
20021                dash: None,
20022            };
20023            if !graph.attn_ok(&l, &p) || !graph.encode_attn_b(&l, &p) {
20024                return None;
20025            }
20026        }
20027        spec_stamp("w.enc");
20028        if !graph.submit() {
20029            return None;
20030        }
20031        spec_stamp("w.sub");
20032        Some(MetalWarmPending {
20033            graph,
20034            cpu_stored,
20035            b,
20036        })
20037    }
20038
20039    /// Submit and finish in one call (the prefill's MTP warm-up, where
20040    /// nothing runs in between).
20041    #[cfg(target_os = "macos")]
20042    fn mtp_warm_batch_metal(
20043        &mut self,
20044        m: &mut MtpModule,
20045        pairs: &[(&[f32], u32)],
20046        first_pos: usize,
20047    ) -> bool {
20048        match self.mtp_warm_batch_submit(m, pairs, first_pos) {
20049            Some(p) => self.mtp_warm_batch_finish(m, p),
20050            None => false,
20051        }
20052    }
20053
20054    /// Second half of the batched warm-up: wait for the submitted graph,
20055    /// pull its b appended K/V rows into the CPU MTP cache, re-point the
20056    /// mirror. False = the command buffer failed or the rows are missing
20057    /// (nothing appended; the caller falls back to the one-by-one warm).
20058    #[cfg(target_os = "macos")]
20059    fn mtp_warm_batch_finish(&mut self, m: &mut MtpModule, pending: MetalWarmPending) -> bool {
20060        let MetalWarmPending {
20061            mut graph,
20062            cpu_stored,
20063            b,
20064        } = pending;
20065        let (nkv, hd) = (self.num_kv_heads, self.head_dim);
20066        if !graph.sync() {
20067            return false;
20068        }
20069        spec_stamp("w.gpu");
20070        let mut kbuf = vec![0f32; b * nkv * hd];
20071        let mut vbuf = vec![0f32; b * nkv * hd];
20072        if !crate::gpu_metal::kv_mirror_read_rows(
20073            self.mtp_kv_id(),
20074            Self::MTP_LAYER_BASE,
20075            nkv,
20076            hd,
20077            cpu_stored,
20078            b,
20079            &mut kbuf,
20080            &mut vbuf,
20081        ) {
20082            return false;
20083        }
20084        for r in 0..b {
20085            m.kv.append(
20086                &kbuf[r * nkv * hd..(r + 1) * nkv * hd],
20087                &vbuf[r * nkv * hd..(r + 1) * nkv * hd],
20088                &[],
20089            );
20090        }
20091        crate::gpu_metal::kv_mirror_set_stored(
20092            self.mtp_kv_id(),
20093            Self::MTP_LAYER_BASE,
20094            cpu_stored + b,
20095        );
20096        spec_stamp("w.kv");
20097        true
20098    }
20099
20100    /// A committed token id from the high table (Cyrillic, CJK and the
20101    /// like sit above 131072 in Qwen's vocabulary; Latin subwords past
20102    /// the 65536 cut are rare enough to lose as rejected drafts) switches
20103    /// the draft to the full head for the next 16 tokens; other ids count
20104    /// down. On an M4 the full 660 MB head costs 5.5 ms a draft step
20105    /// against 1.4 for the shortlist, so the streak is kept short.
20106    pub(crate) fn note_draft_id(&mut self, id: u32) {
20107        let cut = Self::draft_vocab_rows(usize::MAX).max(131_072);
20108        if (id as usize) >= cut {
20109            self.draft_full_streak = 16;
20110        } else {
20111            self.draft_full_streak = self.draft_full_streak.saturating_sub(1);
20112        }
20113    }
20114
20115    /// The draft head's rows for the next step: the shortlist, or the full
20116    /// head while `draft_full_streak` runs.
20117    fn draft_head_rows(&self, head_rows: usize) -> usize {
20118        if self.draft_full_streak > 0 {
20119            head_rows
20120        } else {
20121            Self::draft_vocab_rows(head_rows)
20122        }
20123    }
20124
20125    /// Draft-head shortlist size: `CMF_DRAFT_VOCAB` rows (default 65536,
20126    /// capped at the head; 0 = full head).
20127    fn draft_vocab_rows(head_rows: usize) -> usize {
20128        static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
20129        let n = *N.get_or_init(|| {
20130            std::env::var("CMF_DRAFT_VOCAB")
20131                .ok()
20132                .and_then(|v| v.parse().ok())
20133                .unwrap_or(65536)
20134        });
20135        if n == 0 { head_rows } else { n.min(head_rows) }
20136    }
20137
20138    /// One MTP block step on the native Metal token graph: block input on
20139    /// the host, the attention layer + FFN device-resident over the MTP
20140    /// mirror, the head folded in when `want_logits`. The appended K/V row
20141    /// is pulled into the CPU MTP cache (owner of record) after the sync.
20142    #[cfg(target_os = "macos")]
20143    fn mtp_step_metal(
20144        &mut self,
20145        m: &mut MtpModule,
20146        hidden: &[f32],
20147        next_token: u32,
20148        position: usize,
20149        want_logits: bool,
20150    ) -> Option<(Vec<f32>, Vec<f32>)> {
20151        use crate::gpu_metal::{AttnDeviceParams, AttnGpuLayer, GraphDims, MetalFfn, TokenGraph};
20152        let position = position.saturating_sub(self.mtp_pos_base);
20153        if std::env::var("CMF_MTP_GRAPH").as_deref() == Ok("0")
20154            || !crate::gpu::q1_force()
20155            || !crate::gpu::enabled_here()
20156            || self.attn_softcap > 0.0
20157            || self.attention_heads_per_layer.is_some()
20158            || m.kv.mode != crate::kv_cache::KvMode::F32
20159            || m.kv.o1.is_some()
20160        {
20161            return None;
20162        }
20163        let AttnKind::Full {
20164            wq,
20165            wk,
20166            wv,
20167            wo,
20168            q_norm,
20169            k_norm,
20170            output_gate,
20171            softplus_gate: None,
20172            bias: None,
20173        } = &m.layer.attn
20174        else {
20175            return None;
20176        };
20177        let FfnKind::Dense(d) = &m.layer.ffn else {
20178            return None;
20179        };
20180        if d.act != Act::Silu || !d.segs.is_empty() {
20181            return None;
20182        }
20183        let (pq, pk, pv, po) = (
20184            wq.q1_parts()?,
20185            wk.q1_parts()?,
20186            wv.q1_parts()?,
20187            wo.q1_parts()?,
20188        );
20189        let (g, u, dn) = (
20190            d.gate_proj.q1_parts()?,
20191            d.up_proj.q1_parts()?,
20192            d.down_proj.q1_parts()?,
20193        );
20194        let QTensor::Mapped { model, .. } = wq else {
20195            return None;
20196        };
20197        let model = model.clone();
20198        let lm = if want_logits {
20199            Some(self.weights.lm_head.q1_parts()?)
20200        } else {
20201            None
20202        };
20203        let dims = GraphDims {
20204            hidden: self.hidden_size,
20205            eps: self.rms_eps as f32,
20206            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
20207        };
20208        // The block input `eh_proj · [enorm(e); hnorm(h)]` rides in the
20209        // graph (one submit a step); the host per-op matvec if it cannot.
20210        let hs = self.hidden_size;
20211        let mut x = vec![0f32; hs];
20212        // Let an eligible q4tp MTP draft use the measured masked-nibble
20213        // matvec.  Unlike fused epilogues, this reduces the draft's
20214        // projection work without changing its residual-update schedule;
20215        // the target verifier remains the authority over emitted tokens.
20216        // The guard keeps `CMF_METAL_MVFAST=0` as an immediate rollback
20217        // switch and restores the caller's setting on every early return.
20218        let _mtp_fast = crate::gpu_metal::MvFastGuard::set_bits(
20219            crate::gpu_metal::DENSE_MV,
20220        );
20221        let mut graph = TokenGraph::new(&model, dims, &x)?;
20222        let mut folded = false;
20223        if let Some(eh) = m.eh_proj.q1_parts() {
20224            let e = self.embed_single(next_token);
20225            let mut cat = vec![0.0f32; 2 * hs];
20226            let (cat_e, cat_h) = cat.split_at_mut(hs);
20227            inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
20228            inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
20229            folded = graph.encode_input_proj(eh, &cat);
20230        }
20231        if !folded {
20232            x = self.mtp_block_input(m, hidden, next_token);
20233            graph = TokenGraph::new(&model, dims, &x)?;
20234        }
20235        spec_stamp("d.in");
20236        let l = AttnGpuLayer {
20237            mhc: None,
20238            attn_norm: &m.layer.input_norm,
20239            post_norm: &m.layer.post_norm,
20240            wq: pq,
20241            wk: pk,
20242            wv: pv,
20243            wo: po,
20244            ffn: MetalFfn::Dense {
20245                gate: g,
20246                up: u,
20247                down: dn,
20248                act: (d.act == Act::Gelu) as u8,
20249            },
20250            attn_out_norm: None,
20251            ffn_out_norm: None,
20252            layer_scale: None,
20253        };
20254        let (nh, nkv, hd, rd) = (
20255            self.num_heads,
20256            self.num_kv_heads,
20257            self.head_dim,
20258            self.rotary_dim,
20259        );
20260        let inv_freq = self.inv_freq.clone();
20261        {
20262            let cache = &m.kv;
20263            let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
20264            let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
20265            let cpu_stored = cpu_k[0].len() / hd;
20266            let p = AttnDeviceParams {
20267                kv_id: self.mtp_kv_id(),
20268                layer: Self::MTP_LAYER_BASE,
20269                nh,
20270                nkv,
20271                hd,
20272                rd,
20273                position,
20274                scale: self.attn_scale,
20275                eps: self.rms_eps as f32,
20276                gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
20277                late_qk_norm: self.qk_norm_after_rope,
20278                output_gate: *output_gate,
20279                q_norm: q_norm.as_deref(),
20280                k_norm: k_norm.as_deref(),
20281                inv_freq: &inv_freq,
20282                rope_scale: self.rope_scale,
20283                cpu_k,
20284                cpu_v,
20285                cpu_stored,
20286                cpu_gen: cache.generation(),
20287                o1: None,
20288                window: None,
20289                softmax_sink: None,
20290                head_gate: None,
20291                v_norm: false,
20292                dash: None,
20293            };
20294            if !graph.attn_device_ok(&l, &p) || !graph.encode_attn_device(&l, &p) {
20295                return None;
20296            }
20297        }
20298        // The draft's head over a vocabulary SHORTLIST (the first
20299        // CMF_DRAFT_VOCAB rows — BPE ids run roughly by merge rank, so the
20300        // low ids carry the mass): the verify keeps the full head, so a true
20301        // token past the cut is only a rejected draft, never a wrong token.
20302        // 662 MB a step on Qwen3.8 becomes 170 MB at 65536.
20303        let draft_rows = if let Some(lm) = lm {
20304            self.draft_head_rows(lm.1)
20305        } else {
20306            0
20307        };
20308        if let Some(lm) = lm {
20309            if !graph.lm_head_ok(lm) {
20310                return None;
20311            }
20312            if draft_rows < lm.1 {
20313                if !graph.encode_lm_head_part(&m.final_norm, lm, draft_rows) {
20314                    return None;
20315                }
20316            } else {
20317                graph.encode_lm_head(&m.final_norm, lm);
20318            }
20319        }
20320        spec_stamp("d.enc");
20321        if graph.sync_checked().is_err() {
20322            return None;
20323        }
20324        spec_stamp("d.gpu");
20325        let mut logits = Vec::new();
20326        if let Some(lm) = lm {
20327            let n_read = draft_rows.min(lm.1).min(self.vocab_size);
20328            logits = attention::take_buf(n_read);
20329            graph.read_logits(&mut logits);
20330            // ids past the shortlist: never drafted (−∞ in every chain)
20331            pad_mtp_draft_logits(&mut logits, self.vocab_size);
20332        }
20333        graph.finish(&mut x);
20334        let mut krow = attention::take_buf(nkv * hd);
20335        let mut vrow = attention::take_buf(nkv * hd);
20336        if crate::gpu_metal::kv_mirror_read_last(
20337            self.mtp_kv_id(),
20338            Self::MTP_LAYER_BASE,
20339            nkv,
20340            hd,
20341            &mut krow,
20342            &mut vrow,
20343        ) {
20344            m.kv.append(&krow, &vrow, &[]);
20345        }
20346        attention::recycle_buf(&mut krow);
20347        attention::recycle_buf(&mut vrow);
20348        spec_stamp("d.rd");
20349        Some((logits, x))
20350    }
20351
20352    /// `CMF_MTP_CHAIN=0` keeps the per-step draft (one submit and one
20353    /// host round trip per MTP step); the default drafts the whole chain
20354    /// in one command buffer when the round is plain greedy.
20355    ///
20356    /// Measured on an M4 (24 GB), Qwen3.8-27B q4tp, P3 at 160 tokens,
20357    /// k=7, six runs per arm alternating inside one lock window — the
20358    /// round's draft phase (median over the 34 rounds of a run) is
20359    /// 34.5 ms per round old against 30.1 new, i.e. 4.93 → 4.31 ms per
20360    /// draft step. That is the whole prize: the 7 submits cost ~0.6 ms
20361    /// each in host and submit latency and nothing else changes —
20362    /// acceptance (3.41 of 7) and tokens per round (4.41) are identical,
20363    /// and the round is 289 → 285 ms, decode 13.8 → 14.0 tok/s.
20364    fn mtp_chain_on() -> bool {
20365        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
20366        *ON.get_or_init(|| std::env::var("CMF_MTP_CHAIN").as_deref() != Ok("0"))
20367    }
20368
20369    /// The round's k greedy drafts as ONE command buffer on Metal: the MTP
20370    /// block k times back to back, each step's token embedding gathered
20371    /// on the device from the argmax the step before it wrote, the head
20372    /// over the round's shortlist (or the full head during a full-head
20373    /// streak — decided once, before the chain, exactly as the per-step
20374    /// path decides it per step, since `draft_full_streak` only moves on
20375    /// a commit). One wait, then the k ids and the k appended K/V rows
20376    /// come back; the CPU MTP cache ends where k `mtp_step_metal` calls
20377    /// would have left it. `Err(false)` = declined before anything was
20378    /// committed (the per-step path takes the round); `Err(true)` = the
20379    /// command buffer failed after commit.
20380    #[cfg(target_os = "macos")]
20381    fn mtp_draft_chain_metal(
20382        &mut self,
20383        m: &mut MtpModule,
20384        hidden: &[f32],
20385        t_next: u32,
20386        position: usize,
20387        k: usize,
20388    ) -> Result<Vec<u32>, bool> {
20389        use crate::gpu_metal::{AttnDeviceParams, AttnGpuLayer, GraphDims, MetalFfn, TokenGraph};
20390        let position = position.saturating_sub(self.mtp_pos_base);
20391        if k == 0
20392            || k > 64
20393            || !Self::mtp_chain_on()
20394            || std::env::var("CMF_MTP_GRAPH").as_deref() == Ok("0")
20395            || !crate::gpu::q1_force()
20396            || !crate::gpu::enabled_here()
20397            || self.attn_softcap > 0.0
20398            || self.attention_heads_per_layer.is_some()
20399            || m.kv.mode != crate::kv_cache::KvMode::F32
20400            || m.kv.o1.is_some()
20401            // the chain gathers embeddings itself: only the plain table
20402            || self.dsv4.is_some()
20403            || self.dsv41.is_some()
20404            || self.dory.is_some()
20405            || self.qwen4_exp.is_some()
20406            || self.glm5_next.is_some()
20407            || self.hy4.is_some()
20408            || self.maxwell.is_some()
20409            || self.inkling.is_some()
20410            || self.per_token_stack()
20411        {
20412            return Err(false);
20413        }
20414        let AttnKind::Full {
20415            wq,
20416            wk,
20417            wv,
20418            wo,
20419            q_norm,
20420            k_norm,
20421            output_gate,
20422            softplus_gate: None,
20423            bias: None,
20424        } = &m.layer.attn
20425        else {
20426            return Err(false);
20427        };
20428        let FfnKind::Dense(d) = &m.layer.ffn else {
20429            return Err(false);
20430        };
20431        if d.act != Act::Silu || !d.segs.is_empty() {
20432            return Err(false);
20433        }
20434        let (Some(pq), Some(pk), Some(pv), Some(po)) =
20435            (wq.q1_parts(), wk.q1_parts(), wv.q1_parts(), wo.q1_parts())
20436        else {
20437            return Err(false);
20438        };
20439        let (Some(g), Some(u), Some(dn)) = (
20440            d.gate_proj.q1_parts(),
20441            d.up_proj.q1_parts(),
20442            d.down_proj.q1_parts(),
20443        ) else {
20444            return Err(false);
20445        };
20446        let (Some(eh), Some(lm)) = (m.eh_proj.q1_parts(), self.weights.lm_head.q1_parts()) else {
20447            return Err(false);
20448        };
20449        let QTensor::Mapped { model, .. } = wq else {
20450            return Err(false);
20451        };
20452        let model = model.clone();
20453        // the embedding table: a q4tp tensor of the SAME blob, no Prism
20454        // inverse-embedding post-pass
20455        let QTensor::Mapped {
20456            model: em,
20457            idx: eidx,
20458            dtype: cortiq_core::TensorDtype::Q4TiledP,
20459            ..
20460        } = &self.weights.embed_tokens
20461        else {
20462            return Err(false);
20463        };
20464        if !std::sync::Arc::ptr_eq(em, &model)
20465            || crate::prism::is_inverse_embedding(&model, &model.tensors[*eidx].name)
20466        {
20467            return Err(false);
20468        }
20469        let embed = (
20470            *eidx,
20471            self.weights.embed_tokens.rows(),
20472            self.weights.embed_tokens.cols(),
20473        );
20474        if embed.2 != self.hidden_size || hidden.len() != self.hidden_size {
20475            return Err(false);
20476        }
20477        let dims = GraphDims {
20478            hidden: self.hidden_size,
20479            eps: self.rms_eps as f32,
20480            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
20481        };
20482        // Keep the chained MTP draft on the masked-nibble Metal matvec
20483        // path.  This scope covers every encode in the chain; the guard
20484        // restores its predecessor when this round returns or declines.
20485        let _mtp_fast = crate::gpu_metal::MvFastGuard::set_bits(
20486            crate::gpu_metal::DENSE_MV,
20487        );
20488        let Some(mut graph) = TokenGraph::new(&model, dims, hidden) else {
20489            return Err(false);
20490        };
20491        if !graph.chain_embed_ok(embed) || !graph.lm_head_ok(lm) {
20492            return Err(false);
20493        }
20494        let l = AttnGpuLayer {
20495            mhc: None,
20496            attn_norm: &m.layer.input_norm,
20497            post_norm: &m.layer.post_norm,
20498            wq: pq,
20499            wk: pk,
20500            wv: pv,
20501            wo: po,
20502            ffn: MetalFfn::Dense {
20503                gate: g,
20504                up: u,
20505                down: dn,
20506                act: (d.act == Act::Gelu) as u8,
20507            },
20508            attn_out_norm: None,
20509            ffn_out_norm: None,
20510            layer_scale: None,
20511        };
20512        let (nh, nkv, hd, rd) = (
20513            self.num_heads,
20514            self.num_kv_heads,
20515            self.head_dim,
20516            self.rotary_dim,
20517        );
20518        let inv_freq = self.inv_freq.clone();
20519        let draft_rows = self.draft_head_rows(lm.1);
20520        let n_arg = draft_rows.min(lm.1).min(self.vocab_size);
20521        if n_arg == 0 {
20522            return Err(false);
20523        }
20524        // `CMF_MTP_CHAIN_SPLIT=1` commits each step as it is encoded, so
20525        // the GPU starts on step 0 while the host is still encoding step
20526        // 1 — a probe for whether the host encode is on the critical
20527        // path. It is not: three runs each, draft 30.0 ms per round split
20528        // against 30.1 whole, and the whole chain's host encode measures
20529        // 0.3 ms against a 29.7 ms wait. Kept as a probe, off by default.
20530        let split = std::env::var("CMF_MTP_CHAIN_SPLIT").as_deref() == Ok("1");
20531        // The input stage, the embedding and the block's input projection, goes as a command
20532        // of its own. The weights are one buffer of 13.6 GB on a Mac, the embedding table lies
20533        // 1.5 GB into it and the draft block 13.1 GB: in one command with the block the driver
20534        // held the command 150 to 170 ms before the GPU ran its 9 ms, in every round until the
20535        // first one without a warm-up. MacBook Air M4, Qwen3.8-27B, a round of two drafts:
20536        // 362 → 204 ms. `CMF_MTP_CHAIN_JOIN=1` keeps one command.
20537        let join = std::env::var("CMF_MTP_CHAIN_JOIN").as_deref() == Ok("1");
20538        let t_chain = std::time::Instant::now();
20539        graph.chain_ids_init(t_next, k);
20540        let cpu_stored;
20541        {
20542            let cache = &m.kv;
20543            let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
20544            let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
20545            cpu_stored = cpu_k[0].len() / hd;
20546            for j in 0..k {
20547                if !graph.encode_chain_input(
20548                    embed,
20549                    j as u32,
20550                    &m.enorm,
20551                    &m.hnorm,
20552                    self.embed_multiplier,
20553                    eh,
20554                ) {
20555                    return Err(false);
20556                }
20557                // step j's mirror row: the mirror is re-pointed at the CPU
20558                // rows before step 0 and advances by one per step; its
20559                // resync (never taken past step 0) reads the CPU rows
20560                let p = AttnDeviceParams {
20561                    kv_id: self.mtp_kv_id(),
20562                    layer: Self::MTP_LAYER_BASE,
20563                    nh,
20564                    nkv,
20565                    hd,
20566                    rd,
20567                    position: position + j,
20568                    scale: self.attn_scale,
20569                    eps: self.rms_eps as f32,
20570                    gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
20571                    late_qk_norm: self.qk_norm_after_rope,
20572                    output_gate: *output_gate,
20573                    q_norm: q_norm.as_deref(),
20574                    k_norm: k_norm.as_deref(),
20575                    inv_freq: &inv_freq,
20576                    rope_scale: self.rope_scale,
20577                    cpu_k: cpu_k.clone(),
20578                    cpu_v: cpu_v.clone(),
20579                    cpu_stored: cpu_stored + j,
20580                    cpu_gen: cache.generation(),
20581                    o1: None,
20582                    window: None,
20583                    softmax_sink: None,
20584                    head_gate: None,
20585                    v_norm: false,
20586                    dash: None,
20587                };
20588                if !join {
20589                    graph.commit();
20590                }
20591                if !graph.attn_device_ok(&l, &p) || !graph.encode_attn_device(&l, &p) {
20592                    return Err(false);
20593                }
20594                if draft_rows < lm.1 {
20595                    if !graph.encode_lm_head_part(&m.final_norm, lm, draft_rows) {
20596                        return Err(false);
20597                    }
20598                } else {
20599                    graph.encode_lm_head(&m.final_norm, lm);
20600                }
20601                if !graph.encode_argmax(n_arg, j as u32 + 1) {
20602                    return Err(false);
20603                }
20604                if split {
20605                    // CMF_MTP_CHAIN_SPLIT=1: commit every step so the GPU
20606                    // starts on step 0 while the host encodes the rest
20607                    graph.commit();
20608                }
20609            }
20610        }
20611        let t_enc = t_chain.elapsed();
20612        if graph.sync_checked().is_err() {
20613            return Err(true);
20614        }
20615        if std::env::var_os("CMF_GRAPH_SPEC_TIME").is_some() {
20616            eprintln!(
20617                "mtp-chain: encode {:.1} ms | wait {:.1} ms (k={k}, head rows {draft_rows}{})",
20618                t_enc.as_secs_f64() * 1e3,
20619                (t_chain.elapsed() - t_enc).as_secs_f64() * 1e3,
20620                if split { ", split" } else { "" }
20621            );
20622            if std::env::var("CMF_METAL_CMD_TIMES").as_deref() == Ok("1") {
20623                eprintln!("metal-set: {}", crate::gpu_metal::working_set_report());
20624            }
20625        }
20626        let mut ids = vec![0u32; k];
20627        if !graph.chain_ids_read(&mut ids) {
20628            return Err(true);
20629        }
20630        let mut kbuf = vec![0f32; k * nkv * hd];
20631        let mut vbuf = vec![0f32; k * nkv * hd];
20632        if !crate::gpu_metal::kv_mirror_read_rows(
20633            self.mtp_kv_id(),
20634            Self::MTP_LAYER_BASE,
20635            nkv,
20636            hd,
20637            cpu_stored,
20638            k,
20639            &mut kbuf,
20640            &mut vbuf,
20641        ) {
20642            return Err(true);
20643        }
20644        for r in 0..k {
20645            m.kv.append(
20646                &kbuf[r * nkv * hd..(r + 1) * nkv * hd],
20647                &vbuf[r * nkv * hd..(r + 1) * nkv * hd],
20648                &[],
20649            );
20650        }
20651        Ok(ids)
20652    }
20653
20654    fn try_batch_graph_wgpu(
20655        &self,
20656        hiddens: &mut [f32],
20657        positions: &[usize],
20658        k: usize,
20659        spec: Option<crate::gpu::SpecTail<'_>>,
20660    ) -> crate::gpu::BatchGraphOutcome {
20661        self.try_batch_graph_wgpu_prefix(hiddens, positions, k, spec, None)
20662    }
20663
20664    /// `try_batch_graph_wgpu` with the device-prefix mode: `layers_run`
20665    /// Some lets a stack that does not fit run its leading layers (the
20666    /// token graph's prefix rule) and reports how many; `hiddens` then
20667    /// holds the boundary rows and the caller runs the rest on the host.
20668    fn try_batch_graph_wgpu_prefix(
20669        &self,
20670        hiddens: &mut [f32],
20671        positions: &[usize],
20672        k: usize,
20673        spec: Option<crate::gpu::SpecTail<'_>>,
20674        layers_run: Option<&mut usize>,
20675    ) -> crate::gpu::BatchGraphOutcome {
20676        crate::gpu::graph_kv16_note(self.graph_kv_id, self.kv16_allowed());
20677        // SenseNova-Loop: the mHC kernels take two streams (the
20678        // CMF_MHC_GRAPH=0 knob keeps the host); MRoPE prompt rows ride the
20679        // per-row attention loop with their own angle tables.
20680        if self.mhc.as_ref().is_some_and(|m| {
20681                m.s.streams != 2 || m.s.fixed_identity || std::env::var("CMF_MHC_GRAPH").as_deref() == Ok("0")
20682            })
20683        {
20684            return crate::gpu::BatchGraphOutcome::Declined;
20685        }
20686        let graph_end = match self.mimo_moe.graph_prefix_end() {
20687            Some(end) if end < self.num_layers => {
20688                if layers_run.is_none() || spec.is_some() || end == 0 {
20689                    return crate::gpu::BatchGraphOutcome::Declined;
20690                }
20691                end
20692            }
20693            _ => self.num_layers,
20694        };
20695        let _tb = std::time::Instant::now();
20696        let batch_debug = std::env::var_os("CMF_BATCH_DEBUG").is_some();
20697        if self.attn_softcap > 0.0 {
20698            return crate::gpu::BatchGraphOutcome::Declined; // capped scores: no graph kernel — CPU path
20699        }
20700        // Same attention contract as the token graph: per-layer geometry
20701        // rides `geom`, anything it cannot express declines by name.
20702        if let Some(reason) = self
20703            .wgpu_graph_attn_decline()
20704            .or_else(|| self.batch_graph_gemma_decline())
20705        {
20706            self.note_graph_decline("wgpu batch graph", reason);
20707            return crate::gpu::BatchGraphOutcome::Declined;
20708        }
20709        let nh = self.num_heads;
20710        let (nkv, hd, rd) = self.layer_geom(0);
20711        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
20712        // `blr` rides as GRAPH_KIND_BLR on CUDA, whose hybrid arm runs it
20713        // the small path's rows at a time (the wgpu batch graph declines it)
20714        fn bw(t: &QTensor) -> Option<(&std::sync::Arc<cortiq_core::CmfModel>, usize, u8, &[f32])> {
20715            if crate::gpu::cuda_active() {
20716                t.graph_weight_or_blr()
20717            } else {
20718                t.graph_weight().or_else(|| t.graph_weight_descriptor())
20719            }
20720        }
20721        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
20722            if let Some((m, i, kind, rs)) = bw(t)
20723            {
20724                let name = &m.tensors[i].name;
20725                let prism = if crate::prism::is_inverse_embedding(m, name) {
20726                    crate::gpu::GraphPrismOp::InverseEmbedding
20727                } else if crate::prism::is_forward_weight(m, name) {
20728                    crate::gpu::GraphPrismOp::Forward
20729                } else {
20730                    crate::gpu::GraphPrismOp::None
20731                };
20732                return Some(crate::gpu::GraphW {
20733                    idx: i,
20734                    kind,
20735                    row_scale: rs,
20736                    data: &[],
20737                    prism,
20738                    affine: crate::prism::is_affine_target(m, name),
20739                });
20740            }
20741            if std::env::var_os("CMF_BATCH_DEBUG").is_some() {
20742                eprintln!(
20743                    "batch graph: tensor has no graph descriptor/f32 fallback rows={} cols={}",
20744                    t.rows(),
20745                    t.cols()
20746                );
20747            }
20748            t.as_f32().map(|d| crate::gpu::GraphW {
20749                idx: 0,
20750                kind: 4,
20751                row_scale: &[],
20752                data: d,
20753                prism: crate::gpu::GraphPrismOp::None,
20754                affine: false,
20755            })
20756        }
20757        // Ripple's value residual: the chunk's embedding rows, as they enter
20758        // the first layer (the graph overwrites `hiddens`).
20759        let vres_e0: Vec<f32> = if self.value_blend.is_some() {
20760            hiddens[..k * self.hidden_size].to_vec()
20761        } else {
20762            Vec::new()
20763        };
20764        let built: Option<(
20765            Vec<crate::gpu::GraphLayer<'_>>,
20766            std::sync::Arc<cortiq_core::CmfModel>,
20767        )> = (|| {
20768            let mut layers = Vec::with_capacity(graph_end);
20769            let mut model = None;
20770            for li in 0..graph_end {
20771                let lw = &self.weights.layers[self.phys_layer(li)];
20772                // MoE routes per token, so its experts are encoded token by
20773                // token inside the batched submit while attention and the
20774                // projections stay GEMMs. Refusing MoE here is what left
20775                // prefill running one position at a time: 33 tok/s against
20776                // 54 on decode, i.e. reading the prompt was slower than
20777                // writing the answer.
20778                let gffn = match &lw.ffn {
20779                    FfnKind::Dense(d) if d.segs.len() > 1 => {
20780                        if batch_debug {
20781                            eprintln!("batch graph: dense segmented FFN at layer {li}");
20782                        }
20783                        return None;
20784                    }
20785                    FfnKind::Dense(d) => {
20786                        let Some((act, limit)) = d.act.dense_graph_contract() else {
20787                            if batch_debug {
20788                                eprintln!(
20789                                    "batch graph: dense FFN activation {:?} without a graph kernel at layer {li}",
20790                                    d.act
20791                                );
20792                            }
20793                            return None;
20794                        };
20795                        crate::gpu::GraphFfn::Dense {
20796                            gate: gw(&d.gate_proj)?,
20797                            up: gw(&d.up_proj)?,
20798                            down: gw(&d.down_proj)?,
20799                            act,
20800                            limit,
20801                            // The layer's one tube (hot neurons), always on.
20802                            hot: match d.segs.first() {
20803                                Some(seg) => Some(crate::gpu::GraphMoeDetachedShared {
20804                                    gate: gw(&seg.gate)?,
20805                                    up: gw(&seg.up)?,
20806                                    down: gw(&seg.down)?,
20807                                    width: seg.width,
20808                                }),
20809                                None => None,
20810                            },
20811                        }
20812                    }
20813                    FfnKind::Moe(m) => {
20814                        // Adaptive τ and expert masks stay on the CPU path.
20815                        // Sigmoid scores, the selection bias, a routed scale
20816                        // ≠ 1 and an ungated shared expert (hy_v3) ride the
20817                        // same flags word as the token graph — before, this
20818                        // refusal sent every Hy-MT2-30B prompt to the chunked
20819                        // fallback (8 tok/s of ingest against 53 of decode).
20820                        if m.route_tau.is_some() || m.mask.is_some() {
20821                            return None;
20822                        }
20823                        // A shared expert rides as slot top_k (gated or
20824                        // not is a flag on the select kernel); without one
20825                        // (MiMo-V2, LFM2-MoE) the kernels run top_k slots.
20826                        let inter0 = m.experts.first()?.gate_proj.rows();
20827                        // A wider shared expert (Unlimited-OCR) stays out of
20828                        // the packed bank, as on the token graph.
20829                        let detached_shared = match m.shared.as_ref() {
20830                            Some((se, None)) if se.gate_proj.rows() != inter0 || se.up_proj.rows() != inter0 => {
20831                                if !matches!(se.act, Act::Silu) {
20832                                    return None;
20833                                }
20834                                Some(crate::gpu::GraphMoeDetachedShared {
20835                                    gate: gw(&se.gate_proj)?,
20836                                    up: gw(&se.up_proj)?,
20837                                    down: gw(&se.down_proj)?,
20838                                    width: se.gate_proj.rows(),
20839                                })
20840                            }
20841                            _ => None,
20842                        };
20843                        let shared = m.shared.as_ref().filter(|_| detached_shared.is_none());
20844                        let has_shared = shared.is_some();
20845                        let shared_gated = matches!(shared, Some((_, Some(_))));
20846                        let sgate = match shared {
20847                            Some((_, Some(sg))) => gw(sg)?,
20848                            // Ungated or absent: the router plane stands in
20849                            // so the plumbing stays total; the kernel pins
20850                            // weight 1 or never reads it.
20851                            _ => gw(&m.router)?,
20852                        };
20853                        let router = gw(&m.router)?;
20854                        // The batch MoE kernels still consume raw per-token
20855                        // rows and do not carry the descriptor-aware Prism
20856                        // transform/affine bit for router or shared-gate
20857                        // planes.  Refuse rather than route an untransformed
20858                        // source activation.
20859                        if router.prism != crate::gpu::GraphPrismOp::None
20860                            || router.affine
20861                            || sgate.prism != crate::gpu::GraphPrismOp::None
20862                            || sgate.affine
20863                        {
20864                            return None;
20865                        }
20866                        let inter = m.experts.first()?.gate_proj.rows();
20867                        let mut experts = Vec::with_capacity(m.experts.len() + 1);
20868                        let mut q4tp: Option<bool> = None;
20869                        let mut gu_q2: Option<bool> = None;
20870                        let mut q82: Option<bool> = None;
20871                        // The packed MoE graph has one gate/up program per
20872                        // layer, so accept only one exact activation contract
20873                        // across routed and in-bank shared experts.
20874                        let mut moe_act = None;
20875                        for e in m.experts.iter().chain(shared.map(|(se, _)| se)) {
20876                            let Some(e_act) = e.act.wgpu_graph_act() else {
20877                                return None;
20878                            };
20879                            match moe_act {
20880                                Some(existing) if existing != e_act => return None,
20881                                None => moe_act = Some(e_act),
20882                                _ => {}
20883                            }
20884                            if e.gate_proj.rows() != inter || e.up_proj.rows() != inter {
20885                                return None;
20886                            }
20887                            // Same ladder as the token graph: q4t → q2tp
20888                            // (mixed profile: 2-bit gate/up over a q4tp
20889                            // down) → q4tp → q8_2f. Uniform across the layer.
20890                            let (mm, gi, ui, di, is_p, is_q2, is_8) = match e.gate_proj.mapped_q4t()
20891                            {
20892                                Some((mm, gi)) => (
20893                                    mm,
20894                                    gi,
20895                                    e.up_proj.mapped_q4t()?.1,
20896                                    e.down_proj.mapped_q4t()?.1,
20897                                    false,
20898                                    false,
20899                                    false,
20900                                ),
20901                                None => match e.gate_proj.mapped_q2tp() {
20902                                    Some((mm, gi)) => (
20903                                        mm,
20904                                        gi,
20905                                        e.up_proj.mapped_q2tp()?.1,
20906                                        e.down_proj.mapped_q4tp()?.1,
20907                                        true,
20908                                        true,
20909                                        false,
20910                                    ),
20911                                    None => match e.gate_proj.mapped_q4tp() {
20912                                        Some((mm, gi)) => (
20913                                            mm,
20914                                            gi,
20915                                            e.up_proj.mapped_q4tp()?.1,
20916                                            e.down_proj.mapped_q4tp()?.1,
20917                                            true,
20918                                            false,
20919                                            false,
20920                                        ),
20921                                        None => {
20922                                            if !crate::gpu::moe_q82_graph_on() {
20923                                                return None;
20924                                            }
20925                                            let (mm, gi) = e.gate_proj.mapped_q8_2f()?;
20926                                            (
20927                                                mm,
20928                                                gi,
20929                                                e.up_proj.mapped_q8_2f()?.1,
20930                                                e.down_proj.mapped_q8_2f()?.1,
20931                                                false,
20932                                                false,
20933                                                true,
20934                                            )
20935                                        }
20936                                    },
20937                                },
20938                            };
20939                            if *q4tp.get_or_insert(is_p) != is_p
20940                                || *gu_q2.get_or_insert(is_q2) != is_q2
20941                                || *q82.get_or_insert(is_8) != is_8
20942                            {
20943                                return None;
20944                            }
20945                            if [gi, ui, di].into_iter().any(|idx| {
20946                                mm.tensors.get(idx).is_some_and(|t| {
20947                                    crate::prism::is_forward_weight(mm, &t.name)
20948                                        || crate::prism::is_affine_target(mm, &t.name)
20949                                })
20950                            }) {
20951                                return None;
20952                            }
20953                            model.get_or_insert_with(|| mm.clone());
20954                            experts.push((gi, ui, di));
20955                        }
20956                        crate::gpu::GraphFfn::Moe {
20957                            latent: None,
20958                            shared_limit: None,
20959                            router,
20960                            shared_gate: sgate,
20961                            experts,
20962                            n_exp: m.experts.len(),
20963                            top_k: m.top_k,
20964                            inter,
20965                            act: moe_act?,
20966                            norm_topk: m.norm_topk_prob,
20967                            q4tp: q4tp?,
20968                            gu_q2: gu_q2.unwrap_or(false),
20969                            q82: q82.unwrap_or(false),
20970                            sigmoid: m.router_sigmoid,
20971                            sigmoid_denom_eps: m.sigmoid_denom_eps,
20972                            bias: m.expert_bias.as_deref(),
20973                            has_shared,
20974                            detached_shared,
20975                            shared_gated,
20976                            route_scale: m.routed_scaling,
20977                            limit: 0.0,
20978                        }
20979                    }
20980                    _ => return None,
20981                };
20982                let attn = match &lw.attn {
20983                    AttnKind::Full {
20984                        wq,
20985                        wk,
20986                        wv,
20987                        wo,
20988                        q_norm,
20989                        k_norm,
20990                        output_gate,
20991                        softplus_gate,
20992                        bias,
20993                    } => {
20994                        // Spark-X2.6's head-wise sigmoid gate rides the batch graph
20995                        // (one g_proj row per Q head); Laguna's softplus gate does not.
20996                        let head_gate = match softplus_gate {
20997                            Some((g, true)) if self.proj_gate_sigmoid && !*output_gate => Some(gw(g)?),
20998                            None => None,
20999                            Some(_) => {
21000                                if batch_debug {
21001                                    eprintln!("batch graph: unsupported Full attention gate at layer {li}");
21002                                }
21003                                return None;
21004                            }
21005                        };
21006                        if self.attention_heads_per_layer.is_some() {
21007                            if batch_debug {
21008                                eprintln!("batch graph: per-layer Q heads at layer {li}");
21009                            }
21010                            return None;
21011                        }
21012                        model = Some(self.graph_model_of(&[wq, wk, wv, wo])?);
21013                        crate::gpu::GraphAttn::Full {
21014                            wq: gw(wq)?,
21015                            wk: gw(wk)?,
21016                            wv: gw(wv)?,
21017                            wo: gw(wo)?,
21018                            q_norm: q_norm.as_deref(),
21019                            k_norm: k_norm.as_deref(),
21020                            late_qk_norm: self.qk_norm_after_rope,
21021                            bias: bias
21022                                .as_ref()
21023                                .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
21024                            output_gate: *output_gate,
21025                            cpu_k: self.kv_cache.layers[li].k_heads(),
21026                            cpu_v: self.kv_cache.layers[li].v_heads(),
21027                            cpu_base: self.kv_cache.layers[li].base(),
21028                            geom: self.graph_attn_geom_vres(li, &vres_e0),
21029                            head_gate,
21030                        }
21031                    }
21032                    AttnKind::LinearGdn(w) => {
21033                        let Some(cfg) = self.gdn_cfg else {
21034                            if batch_debug {
21035                                eprintln!("batch graph: no GDN config at layer {li}");
21036                            }
21037                            return None;
21038                        };
21039                        model = Some(self.graph_model_of(&[&w.in_proj_qkv, &w.in_proj_z, &w.out_proj])?);
21040                        crate::gpu::GraphAttn::Gdn {
21041                            qkv: gw(&w.in_proj_qkv)?,
21042                            z: gw(&w.in_proj_z)?,
21043                            a: gw(&w.in_proj_a)?,
21044                            b: gw(&w.in_proj_b)?,
21045                            out: gw(&w.out_proj)?,
21046                            conv1d: &w.conv1d,
21047                            a_log: &w.a_log,
21048                            dt_bias: &w.dt_bias,
21049                            norm: &w.norm,
21050                            nv: cfg.num_v_heads,
21051                            nk: cfg.num_k_heads,
21052                            dk: cfg.key_head_dim,
21053                            dv: cfg.value_head_dim,
21054                            kk: cfg.conv_kernel,
21055                            cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
21056                            preview: self.clover.as_ref().and_then(|c| c.graph_preview(li)),
21057                        }
21058                    }
21059                    AttnKind::Kda(_) | AttnKind::Mla(_) => {
21060                        let (attn, m) = self.graph_attn_kimi(li, &lw.attn, &gw)?;
21061                        model = Some(m);
21062                        attn
21063                    }
21064                    // LFM2/3's short convolution: the CUDA hybrid arm's prompt
21065                    // path and the wgpu batch graph (`sconv_batch`) run it
21066                    AttnKind::ShortConv(w) => {
21067                        let cfg = self.short_conv_cfg?;
21068                        let (m, _, _, _) = bw(&w.in_proj)?;
21069                        model = Some(m.clone());
21070                        crate::gpu::GraphAttn::ShortConv {
21071                            inp: gw(&w.in_proj)?,
21072                            out: gw(&w.out_proj)?,
21073                            taps: &w.conv,
21074                            kernel: cfg.kernel,
21075                            cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
21076                        }
21077                    }
21078                    _ => return None,
21079                };
21080                // Gemma-4's sandwich norms and layer scalar (`gemma_batch`),
21081                // Ripple's and the LFM stacks' sandwich norms (wgpu's plain
21082                // tails), and on CUDA any plain sandwich norms (the hybrid
21083                // prompt path's `sandwich_rows`); every other model hands the
21084                // graph none.
21085                let g4 = self.global_attn.is_some() || self.attn_v_norm;
21086                let lfm = self.short_conv_cfg.is_some();
21087                let sandwich = g4 || self.value_blend.is_some() || lfm || crate::gpu::cuda_active();
21088                layers.push(crate::gpu::GraphLayer {
21089                    engram: None,
21090                    mhc: crate::sensenova::graph_mhc(self.mhc.as_deref(), self.phys_layer(li)),
21091                    input_norm: &lw.input_norm,
21092                    attn,
21093                    post_norm: &lw.post_norm,
21094                    attn_out_norm: if sandwich {
21095                        lw.attn_out_norm.as_deref()
21096                    } else {
21097                        None
21098                    },
21099                    ffn_out_norm: if sandwich { lw.ffn_out_norm.as_deref() } else { None },
21100                    layer_scale: if g4 { lw.layer_scale } else { None },
21101                    ffn: gffn,
21102                });
21103            }
21104            Some((layers, model?))
21105        })();
21106        let Some((layers, model)) = built else {
21107            {
21108                use std::sync::atomic::{AtomicBool, Ordering};
21109                static SAID: AtomicBool = AtomicBool::new(false);
21110                if !SAID.swap(true, Ordering::Relaxed) {
21111                    tracing::warn!("batch graph: BUILDER refused (layer weights/kinds)");
21112                }
21113            }
21114            return crate::gpu::BatchGraphOutcome::Declined;
21115        };
21116        if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
21117            eprintln!("batch-build: {:.1} ms", _tb.elapsed().as_secs_f64() * 1e3);
21118        }
21119        // SenseNova-Loop and Mage-VL: their q8_2f prompt chunks take the
21120        // batched int8 GEMM.
21121        #[cfg(feature = "gpu")]
21122        crate::gpu_wgpu::set_batch_q82_mm(self.mhc.is_some() || self.onevision2_prefill());
21123        // SenseNova-Loop image prompt: each row's absolute MRoPE angles.
21124        #[cfg(feature = "gpu")]
21125        let _mrope = self.prompt_mrope.as_deref().zip(self.mrope_sections).map(|(pos, sections)| {
21126            let half = rd / 2;
21127            let mut tab = vec![0f32; k * 64];
21128            for (i, &p) in positions.iter().enumerate() {
21129                for j in 0..half.min(64) {
21130                    let a = pos.get(p).map_or(p as f32, |q| q[crate::sensenova::mrope_axis(j, sections)] as f32);
21131                    tab[i * 64 + j] = a * self.inv_freq[j];
21132                }
21133            }
21134            crate::gpu_wgpu::set_batch_mrope(Some(tab));
21135            struct Clear;
21136            impl Drop for Clear {
21137                fn drop(&mut self) {
21138                    crate::gpu_wgpu::set_batch_mrope(None);
21139                }
21140            }
21141            Clear
21142        });
21143        // A Looped Transformer: the final norm on the stream after each
21144        // loop's last layer, as the token graph's `loop_norm_at` (the
21145        // stack's own last layer aside: the head norms it). Without them
21146        // the batch graph ran the loops back to back: Nanbeige's long
21147        // prompts read as noise on both GPU backends.
21148        let _loop = self.loop_final_norm.then(|| {
21149            let at: Vec<usize> = (0..graph_end.min(self.num_layers - 1)).filter(|&li| self.is_loop_end(li)).collect();
21150            crate::gpu::set_batch_loop_norm(Some((at, self.weights.final_norm.to_vec())));
21151            struct Clear;
21152            impl Drop for Clear {
21153                fn drop(&mut self) {
21154                    crate::gpu::set_batch_loop_norm(None);
21155                }
21156            }
21157            Clear
21158        });
21159        // a prompt chunk wholly before what the drafter's windows reach keeps none
21160        let mut taps = if positions.last().is_some_and(|&p| p < self.dflash_tap_from) { Vec::new() } else { self.dflash_taps_wanted(0, graph_end) };
21161        let n_dflash = taps.len();
21162        // a routed prompt's rows at the router's layer, φ in row order
21163        let phi_slot = match self.dyn_phi_layer {
21164            Some(l) if l < graph_end => Some(taps.iter().position(|&t| t == l).unwrap_or_else(|| {
21165                taps.push(l);
21166                taps.len() - 1
21167            })),
21168            _ => None,
21169        };
21170        *self.dyn_phi_tap.lock().unwrap() = None;
21171        crate::gpu::layer_taps_arm(&taps);
21172        let outcome = crate::gpu::forward_batch_graph(
21173            &model,
21174            self.graph_kv_id,
21175            &layers,
21176            &self.inv_freq,
21177            hiddens,
21178            nh,
21179            nkv,
21180            hd,
21181            rd,
21182            self.hidden_size,
21183            self.intermediate_size,
21184            positions,
21185            self.kv_cache.max_seq_len,
21186            gemma,
21187            self.rms_eps as f32,
21188            self.attn_scale,
21189            k,
21190            &(0..graph_end)
21191                .map(|li| self.kv_cache.layers[self.phys_layer(li)].o1_views())
21192                .collect::<Vec<_>>(),
21193            self.o1_epoch,
21194            spec,
21195            layers_run,
21196        );
21197        self.graph_taps_keep(&taps, n_dflash, phi_slot, positions[0], k, outcome == crate::gpu::BatchGraphOutcome::Completed);
21198        outcome
21199    }
21200
21201    /// The layers a DFlash drafter reads, when a wgpu graph over layers
21202    /// `from..upto_excl` is the whole stack (nothing otherwise).
21203    fn dflash_taps_wanted(&self, from: usize, upto_excl: usize) -> Vec<usize> {
21204        match &self.dflash {
21205            Some(d) if (self.dflash_solo || dflash_pick() == Some(true) || crate::gpu::cuda_active()) && from == 0 && upto_excl >= self.num_layers => d.g.taps.clone(),
21206            _ => Vec::new(),
21207        }
21208    }
21209
21210    /// Collect what the armed graph kept for `rows` rows from `pos0`
21211    /// (`ok`: it completed) into `dflash_taps`, a row's layers joined.
21212    fn dflash_taps_keep(&self, taps: &[usize], pos0: usize, rows: usize, ok: bool) {
21213        self.graph_taps_keep(taps, taps.len(), None, pos0, rows, ok);
21214    }
21215
21216    /// What the armed graph kept, `[slot][row][hidden]`: the first
21217    /// `n_dflash` slots are the drafter's (`dflash_taps`), `phi_slot` the
21218    /// router's φ rows (`dyn_phi_tap`).
21219    fn graph_taps_keep(&self, taps: &[usize], n_dflash: usize, phi_slot: Option<usize>, pos0: usize, rows: usize, ok: bool) {
21220        if taps.is_empty() {
21221            return;
21222        }
21223        let (nt, hs) = (taps.len(), self.hidden_size);
21224        let mut raw = Vec::new();
21225        if !crate::gpu::layer_taps_take(&mut raw) || !ok || raw.len() != nt * rows * hs {
21226            return;
21227        }
21228        if let Some(s) = phi_slot {
21229            *self.dyn_phi_tap.lock().unwrap() = Some(raw[s * rows * hs..(s + 1) * rows * hs].to_vec());
21230        }
21231        if n_dflash > 0 {
21232            raw.truncate(n_dflash * rows * hs);
21233            self.dflash_taps_join(&taps[..n_dflash], raw, pos0, rows);
21234        }
21235    }
21236
21237    /// The drafter's slots of a graph's taps into `dflash_taps`.
21238    fn dflash_taps_join(&self, taps: &[usize], raw: Vec<f32>, pos0: usize, rows: usize) {
21239        let (nt, hs) = (taps.len(), self.hidden_size);
21240        let mut joined = vec![0f32; rows * nt * hs];
21241        for s in 0..nt {
21242            for r in 0..rows {
21243                joined[(r * nt + s) * hs..][..hs].copy_from_slice(&raw[(s * rows + r) * hs..][..hs]);
21244            }
21245        }
21246        if std::env::var_os("CMF_SPEC_DBG").is_some() {
21247            let rms = (joined.iter().map(|v| (*v as f64) * (*v as f64)).sum::<f64>() / joined.len().max(1) as f64).sqrt();
21248            eprintln!("solo-dbg: {rows} rows of {nt} layers kept from position {pos0} (rms {rms:.3})");
21249        }
21250        if let Some(dir) = std::env::var_os("CMF_DFLASH_DUMP") {
21251            self.dflash_dump(std::path::Path::new(&dir), pos0, rows, &joined);
21252        }
21253        let mut kept = self.dflash_taps.lock().unwrap();
21254        kept.push((pos0, joined));
21255        // a long prompt's rows wait here until the first round: past
21256        // `DFLASH_TAPS_ROWS` the oldest chunks go, and the drafter's context
21257        // starts at what is left
21258        let mut rows: usize = kept.iter().map(|(_, r)| r.len()).sum::<usize>() / (nt * hs);
21259        let cap = match &self.dflash {
21260            Some(d) if (0..d.g.layers).all(|l| d.g.window_of(l) > 0) => {
21261                DFLASH_TAPS_ROWS.min((0..d.g.layers).map(|l| d.g.window_of(l)).max().unwrap_or(0) + crate::dflash::BLOCK_SLACK)
21262            }
21263            _ => DFLASH_TAPS_ROWS,
21264        };
21265        while rows > cap && kept.len() > 1 {
21266            rows -= kept.remove(0).1.len() / (nt * hs);
21267        }
21268    }
21269
21270    /// `CMF_DFLASH_DUMP=DIR`: what a reference run of the published drafter
21271    /// reads (`scripts/ripple/ripple_dflash_ref.py`). `taps.bin` grows by a
21272    /// record a kept chunk (position and row count as u64, then the rows'
21273    /// f32, a row's layers joined); the embedding table and the head are
21274    /// written once as f32, the table without the trunk's input scale.
21275    fn dflash_dump(&self, dir: &std::path::Path, pos0: usize, rows: usize, joined: &[f32]) {
21276        use std::io::Write;
21277        let _ = std::fs::create_dir_all(dir);
21278        let table = |name: &str, t: &QTensor| {
21279            let p = dir.join(name);
21280            if p.exists() {
21281                return;
21282            }
21283            let Ok(f) = std::fs::File::create(&p) else { return };
21284            let mut w = std::io::BufWriter::new(f);
21285            let mut row = vec![0f32; t.cols()];
21286            for r in 0..t.rows() {
21287                t.row_f32(r, &mut row);
21288                let _ = w.write_all(&f32_bytes(&row));
21289            }
21290        };
21291        table("embed.f32", &self.weights.embed_tokens);
21292        table("head.f32", &self.weights.lm_head);
21293        let meta = dir.join("meta.json");
21294        if !meta.exists() {
21295            let _ = std::fs::write(
21296                &meta,
21297                format!(
21298                    "{{\"hidden\": {}, \"vocab\": {}, \"embed_multiplier\": {}}}\n",
21299                    self.hidden_size,
21300                    self.weights.lm_head.rows(),
21301                    self.embed_multiplier
21302                ),
21303            );
21304        }
21305        if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("taps.bin")) {
21306            let _ = f.write_all(&(pos0 as u64).to_le_bytes());
21307            let _ = f.write_all(&(rows as u64).to_le_bytes());
21308            let _ = f.write_all(&f32_bytes(joined));
21309        }
21310    }
21311
21312    /// Rows the wgpu graphs kept become the drafter's context, oldest first.
21313    fn dflash_taps_absorb(&mut self) {
21314        let kept = std::mem::take(&mut *self.dflash_taps.lock().unwrap());
21315        if let Some(d) = self.dflash.as_mut() {
21316            for (pos0, rows) in kept {
21317                d.queue_context(pos0, &rows, self.pool.as_deref());
21318            }
21319        }
21320    }
21321
21322    /// Same, stopping after layer `upto` inclusive (routing probe φ).
21323    /// `CMF_DSV4_DRAFT_PROBE=1` — grade the draft against what the trunk goes on
21324    /// to produce. Off by default; it runs a whole draft per decoded token.
21325    fn draft_probe() -> bool {
21326        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
21327        *ON.get_or_init(|| std::env::var("CMF_DSV4_DRAFT_PROBE").is_ok_and(|v| v != "0"))
21328    }
21329
21330    /// `CMF_DSV4_DRAFT_PROBE=1`: measure how much of the draft the trunk
21331    /// would have agreed with, WITHOUT verifying or rolling anything back.
21332    ///
21333    /// The number this produces decides the whole speculation design — at
21334    /// acceptance a, a block of B positions yields 1 + a + a² + ... tokens
21335    /// per trunk pass — so it is worth measuring before any of the machinery
21336    /// that would exploit it exists. Each draft is parked with the position
21337    /// it was made at, and graded as the real tokens arrive.
21338    /// `CMF_DSV4_SPEC=1` — the DeepSeek-V4 speculative decode: draft five
21339    /// on the card, verify them in one batched trunk pass, commit the
21340    /// accepted prefix, roll the rest back.
21341    #[cfg(feature = "gpu")]
21342    fn dsv4_spec_on() -> bool {
21343        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
21344        *ON.get_or_init(|| {
21345            // Test-only runtime gate: model loading still performs the same
21346            // reservation and trunk packing, which gives rollback parity a
21347            // topology-identical non-speculative control arm.
21348            if let Ok(v) = std::env::var("CMF_DSV4_SPEC_RUN") {
21349                return v != "0";
21350            }
21351            // An explicit value is a diagnostic force/escape hatch.  With no
21352            // knob, speculation is eligible only when model loading reserved
21353            // its bounded pack.  On small q4tp cards the geometric reserve
21354            // gate deliberately leaves this at zero: trying to build DSpark
21355            // after the exact trunk filled VRAM is both slower and a device
21356            // OOM (measured on A40).
21357            std::env::var("CMF_DSV4_SPEC")
21358                .map(|v| v != "0")
21359                .unwrap_or_else(|_| {
21360                    crate::gpu_wgpu::DRAFT_RESERVE.load(std::sync::atomic::Ordering::Relaxed) > 0
21361                })
21362        })
21363    }
21364
21365    /// One speculative round at the decode tip. `t_next` is the token the
21366    /// sampler just committed for `next_pos`. Returns the EXTRA accepted
21367    /// tokens (possibly none) and the new position, with `graph_logits`
21368    /// left holding the last accepted position's logits — exactly what the
21369    /// loop top expects. `None` means "speculate not this round": nothing
21370    /// was committed, the caller forwards normally.
21371    #[cfg(feature = "gpu")]
21372    fn dsv4_spec_step(
21373        &mut self,
21374        tip_token: u32,
21375        t_next: u32,
21376        next_pos: usize,
21377        max_extra: usize,
21378        drafted: &mut usize,
21379        accepted_ctr: &mut usize,
21380    ) -> Option<(Vec<u32>, usize)> {
21381        let t_all = std::time::Instant::now();
21382        if std::env::var("CMF_DSV4_SPEC_TIME").is_ok() {
21383            thread_local! {
21384                static LAST: std::cell::Cell<Option<std::time::Instant>> =
21385                    const { std::cell::Cell::new(None) };
21386            }
21387            LAST.with(|l| {
21388                if let Some(prev) = l.get() {
21389                    eprintln!(
21390                        "between rounds {:.1} ms",
21391                        prev.elapsed().as_secs_f64() * 1e3
21392                    );
21393                }
21394                l.set(Some(std::time::Instant::now()));
21395            });
21396        }
21397        if std::env::var("CMF_DSV4_SPEC_DEBUG").is_ok() {
21398            eprintln!("spec_step: enter pos={next_pos}");
21399        }
21400        let n_layers = self.dsv4.as_ref().map(|b| b.1.len())?;
21401        let cfg = self.dsv4.as_ref().map(|b| b.2)?;
21402        // The draft state and its capture, armed exactly as the probe does.
21403        if self.dspark.is_none() {
21404            let t = crate::dsv4::dspark_targets(&self.dsv4_mtp, &cfg, n_layers);
21405            if t.is_empty() {
21406                return None;
21407            }
21408            crate::dsv4::dspark_arm(&t, cfg.dim);
21409            self.dspark = Some(crate::dsv4::DsparkState::new(
21410                self.dsv4_mtp.len(),
21411                &cfg,
21412                t.len(),
21413            ));
21414        }
21415        let targets = crate::dsv4::dspark_targets(&self.dsv4_mtp, &cfg, n_layers);
21416        let pack = crate::dsv4::dspark_pack_get(&self.dsv4_mtp, &cfg);
21417        if pack.is_none() && std::env::var("CMF_DSV4_SPEC_DEBUG").is_ok() {
21418            eprintln!("spec_step: the pack was not built (targets {targets:?})");
21419        }
21420        let pack = pack?;
21421        let block = crate::dsv4::dspark_block();
21422        let b_box = self.dsv4.as_mut()?;
21423        let (g, layers, st) = (&b_box.0, &b_box.1, &mut b_box.3);
21424        let ds = self.dspark.as_mut()?;
21425        // The tip's captures: either this token ran on a normal path that
21426        // filled the thread-local, or the previous spec round left them.
21427        let dbg = std::env::var("CMF_DSV4_SPEC_DEBUG").is_ok();
21428        if !crate::dsv4::dspark_take(&mut ds.main_hidden) && !ds.have_hidden {
21429            if dbg {
21430                eprintln!("spec_step: no capture");
21431            }
21432            return None;
21433        }
21434        ds.have_hidden = true;
21435        let tip_pos = next_pos.checked_sub(1)?;
21436        let draft_started = std::time::Instant::now();
21437        let mut conf = Vec::new();
21438        let props = crate::dsv4::dspark_draft_gpu(
21439            g,
21440            &self.dsv4_mtp,
21441            &cfg,
21442            ds,
21443            pack,
21444            st.kv_id,
21445            tip_token,
21446            tip_pos,
21447            self.pool.as_deref(),
21448            &mut conf,
21449        );
21450        self.dspark_draft_ns += draft_started.elapsed().as_nanos();
21451        *drafted += block;
21452        if props.is_empty() || props[0] != t_next {
21453            if dbg {
21454                eprintln!(
21455                    "spec_step: draft {} (props0={:?} t_next={t_next})",
21456                    if props.is_empty() {
21457                        "empty"
21458                    } else {
21459                        "miss"
21460                    },
21461                    props.first()
21462                );
21463            }
21464            return None;
21465        }
21466        // `fed[0]` is `t_next`, which the outer loop has already committed;
21467        // only `fed[1..]` become additional output tokens. Cap the verify
21468        // transaction itself to the caller's remaining output budget instead
21469        // of merely truncating the returned vector: otherwise the KV/state
21470        // would advance past `max_tokens` and a 64-token request could return
21471        // 66 tokens (and poison a reused session with two invisible steps).
21472        let mut k_verify = crate::dsv4::dspark_verify_k()
21473            .min(props.len())
21474            .min(max_extra.saturating_add(1));
21475        // Adaptive depth: positions the draft itself doubts are paid for on
21476        // every verify and delivered almost never (natural-text survival
21477        // [.67 .50 .29 .08 .04]). `CMF_DSPARK_CONF_MIN=p` trims the fed
21478        // prefix at the first proposal whose confidence drops below p; on
21479        // predictable text the confidences stay high and nothing changes.
21480        let conf_min = {
21481            static M: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
21482            *M.get_or_init(|| {
21483                std::env::var("CMF_DSPARK_CONF_MIN")
21484                    .ok()
21485                    .and_then(|v| v.parse().ok())
21486                    .unwrap_or(0.0)
21487            })
21488        };
21489        if conf_min > 0.0 && conf.len() >= props.len() {
21490            let mut keep = 1usize;
21491            while keep < k_verify && conf.get(keep).copied().unwrap_or(0.0) >= conf_min {
21492                keep += 1;
21493            }
21494            k_verify = k_verify.min(keep.max(2));
21495        }
21496        if k_verify < 2 {
21497            return None;
21498        }
21499        let mut fed = Vec::with_capacity(k_verify);
21500        fed.push(t_next);
21501        fed.extend_from_slice(&props[1..k_verify]);
21502        let mut argmax = Vec::new();
21503        let mut logits_all = Vec::new();
21504        let mut walked = Vec::new();
21505        let txn = crate::dsv4::dsv4_verify_chunk(
21506            g,
21507            layers,
21508            &cfg,
21509            st,
21510            &fed,
21511            next_pos,
21512            &self.inv_freq,
21513            self.pool.as_deref(),
21514            &targets,
21515            &mut argmax,
21516            &mut logits_all,
21517            &mut walked,
21518        );
21519        if txn.is_none() && dbg {
21520            eprintln!("spec_step: verify declined");
21521        }
21522        let txn = txn?;
21523        let spec_gpu_end = txn.gpu_end;
21524        let b = fed.len();
21525        let mut accepted = 1usize;
21526        while accepted < b && fed[accepted] == argmax[accepted - 1] {
21527            accepted += 1;
21528        }
21529        // `CMF_DSV4_SPEC_FORCE_REJECT=1` — accept nothing beyond the known
21530        // token, every round: the pure rollback exerciser. The output must
21531        // stay byte-identical to the plain walk; anything else is a
21532        // transaction bug, isolated from the acceptance logic.
21533        if std::env::var("CMF_DSV4_SPEC_FORCE_REJECT").is_ok_and(|v| v != "0") {
21534            accepted = 1;
21535        }
21536        if std::env::var("CMF_DSV4_SPEC_TRACE").is_ok() {
21537            eprintln!("spec@{next_pos}: fed={fed:?} argmax={argmax:?} accepted={accepted}");
21538        }
21539        let t_fin = std::time::Instant::now();
21540        if !crate::dsv4::dsv4_spec_finish(
21541            g,
21542            layers,
21543            &cfg,
21544            st,
21545            txn,
21546            accepted,
21547            &fed,
21548            &self.inv_freq,
21549            self.pool.as_deref(),
21550        ) {
21551            tracing::warn!("dsv4: the speculative rollback failed — the state is suspect");
21552            return None;
21553        }
21554        if std::env::var("CMF_DSV4_SPEC_TIME").is_ok() {
21555            eprintln!(
21556                "finish(k={accepted}): {:.1} ms",
21557                t_fin.elapsed().as_secs_f64() * 1e3
21558            );
21559        }
21560        *accepted_ctr += accepted - 1;
21561        // Captures per accepted token: device targets photographed by the
21562        // batch, host targets from the verify's own walk. The last one
21563        // becomes the new tip's draft input; every one owes the ring an
21564        // entry for its position.
21565        let (hc, dim) = (cfg.hc_mult, cfg.dim);
21566        // Complete-chain layers are photographed by the fused submission;
21567        // partial device layers overwrite that slot after exact host cold-
21568        // expert correction.  Thus every target in the contiguous device
21569        // prefix has a valid per-token capture.
21570        let dev_caps: Vec<usize> = targets
21571            .iter()
21572            .copied()
21573            .filter(|&t| t < spec_gpu_end)
21574            .collect();
21575        let mut caps_all = vec![0.0f32; dev_caps.len() * b * hc * dim];
21576        if !crate::gpu_wgpu::dsv4_spec_cap_read_all(b, dev_caps.len(), hc * dim, &mut caps_all) {
21577            return None;
21578        }
21579        for t in 0..accepted {
21580            let tip = t + 1 == accepted;
21581            for (slot, &tl) in targets.iter().enumerate() {
21582                if let Some(di) = dev_caps.iter().position(|&d| d == tl) {
21583                    let lo = (di * b + t) * hc * dim;
21584                    crate::dsv4::dspark_capture(
21585                        &caps_all[lo..lo + hc * dim],
21586                        &cfg,
21587                        slot,
21588                        &mut ds.main_hidden,
21589                    );
21590                } else if tip
21591                    && crate::dsv4::dspark_peek_slot(slot, dim, {
21592                        let lo = slot * dim;
21593                        &mut ds.main_hidden[lo..lo + dim]
21594                    })
21595                {
21596                    // The tip's host-layer captures are the walk's own
21597                    // per-layer notes — exact. (The walk that ran last ended
21598                    // on exactly this token, on both the accept-all and the
21599                    // rollback path.)
21600                } else {
21601                    // Intermediate tokens: the post-tail state stands in for
21602                    // the per-layer capture on host targets below the last
21603                    // layer. Ring-entry quality only; the tip is exact.
21604                    crate::dsv4::dspark_capture(
21605                        &walked[t * hc * dim..(t + 1) * hc * dim],
21606                        &cfg,
21607                        slot,
21608                        &mut ds.main_hidden,
21609                    );
21610                }
21611            }
21612            crate::dsv4::dspark_ring_append(
21613                g,
21614                &self.dsv4_mtp,
21615                &cfg,
21616                ds,
21617                next_pos + t,
21618                self.pool.as_deref(),
21619            );
21620        }
21621        let row = logits_all[(accepted - 1) * cfg.vocab..accepted * cfg.vocab].to_vec();
21622        self.graph_logits = Some(row);
21623        // The speculative loop never runs the probe, so the trunk tally has
21624        // no other place to cycle. Armed only when someone asked for the
21625        // dump; the host tail is the only tallying path here, which is
21626        // precisely the population a partial pack would serve.
21627        if std::env::var("CMF_DSV4_TRUNK_PICK_DUMP").is_ok() {
21628            crate::dsv4::trunk_freq_note(&crate::dsv4::pick_tally_take());
21629            crate::dsv4::pick_tally_arm();
21630        }
21631        if std::env::var("CMF_DSV4_SPEC_TIME").is_ok() {
21632            eprintln!(
21633                "spec_step total {:.1} ms (k={accepted})",
21634                t_all.elapsed().as_secs_f64() * 1e3
21635            );
21636        }
21637        Some((fed[1..accepted].to_vec(), next_pos + accepted))
21638    }
21639
21640    fn dspark_probe(&mut self, position: usize, token_id: u32) {
21641        if self.dsv4_mtp.is_empty() || !Self::draft_probe() {
21642            return;
21643        }
21644        // What the trunk just routed to, for this token.
21645        let trunk_now = crate::dsv4::pick_tally_take();
21646        crate::dsv4::trunk_freq_note(&trunk_now);
21647        if !trunk_now.is_empty() {
21648            self.dspark_trunk_picks.push(trunk_now);
21649            let keep = crate::dsv4::dspark_block();
21650            if self.dspark_trunk_picks.len() > keep {
21651                self.dspark_trunk_picks.remove(0);
21652            }
21653        }
21654        // Grade whatever is waiting: the token just decoded sits at
21655        // `position`, so it answers the draft made at `position - 1 - i`.
21656        for p in std::mem::take(&mut self.dspark_pending) {
21657            let Some(i) = position.checked_sub(p.0 + 1) else {
21658                continue;
21659            };
21660            let mut p = p;
21661            if i < p.1.len() {
21662                if p.2 && p.1[i] == token_id {
21663                    p.3 = i + 1;
21664                } else {
21665                    p.2 = false;
21666                }
21667                if i + 1 < p.1.len() {
21668                    self.dspark_pending.push(p);
21669                    continue;
21670                }
21671            }
21672            self.dspark_hist.push(p.3);
21673            self.dspark_real.push(token_id);
21674        }
21675        let Some(b) = &mut self.dsv4 else { return };
21676        let (g, layers, cfg) = (&b.0, &b.1, b.2);
21677        let n_layers = layers.len();
21678        if self.dspark.is_none() {
21679            let t = crate::dsv4::dspark_targets(&self.dsv4_mtp, &cfg, n_layers);
21680            if t.is_empty() {
21681                return;
21682            }
21683            eprintln!(
21684                "DSpark: capture from layers {t:?}, block {}",
21685                crate::dsv4::dspark_block()
21686            );
21687            crate::dsv4::dspark_arm(&t, cfg.dim);
21688            self.dspark = Some(crate::dsv4::DsparkState::new(
21689                self.dsv4_mtp.len(),
21690                &cfg,
21691                t.len(),
21692            ));
21693        }
21694        let ds = self.dspark.as_mut().unwrap();
21695        if !crate::dsv4::dspark_take(&mut ds.main_hidden) {
21696            return; // this token ran on a path that captures nothing
21697        }
21698        let mut conf = Vec::new();
21699        crate::dsv4::pick_tally_arm();
21700        // The trunk has already consumed the adaptive VRAM budget. Until the
21701        // draft owns an explicit bounded device pack, its tensors are an
21702        // out-of-core CPU/disk tier by contract: never let per-op probes try
21703        // to squeeze another multi-gigabyte MTP expert cache onto the card.
21704        let draft_started = std::time::Instant::now();
21705        #[cfg(feature = "gpu")]
21706        let gpu_draft = crate::dsv4::dspark_gpu_on();
21707        #[cfg(not(feature = "gpu"))]
21708        let gpu_draft = false;
21709        let props = if gpu_draft {
21710            #[cfg(feature = "gpu")]
21711            {
21712                let kv_id = b.3.kv_id;
21713                match crate::dsv4::dspark_pack_get(&self.dsv4_mtp, &cfg) {
21714                    Some(pk) => crate::dsv4::dspark_draft_gpu(
21715                        g,
21716                        &self.dsv4_mtp,
21717                        &cfg,
21718                        ds,
21719                        pk,
21720                        kv_id,
21721                        token_id,
21722                        position,
21723                        self.pool.as_deref(),
21724                        &mut conf,
21725                    ),
21726                    None => Vec::new(),
21727                }
21728            }
21729            #[cfg(not(feature = "gpu"))]
21730            Vec::new()
21731        } else {
21732            crate::gpu::cpu_scope(|| {
21733                crate::dsv4::dspark_draft(
21734                    g,
21735                    &self.dsv4_mtp,
21736                    &cfg,
21737                    ds,
21738                    token_id,
21739                    position,
21740                    self.pool.as_deref(),
21741                    &mut conf,
21742                )
21743            })
21744        };
21745        self.dspark_draft_ns += draft_started.elapsed().as_nanos();
21746        let draft_picks = crate::dsv4::pick_tally_take();
21747        crate::dsv4::dspark_freq_note(&draft_picks);
21748        // Re-arm for the NEXT trunk token; the probe runs after the forward,
21749        // so this is the only place that can.
21750        crate::dsv4::pick_tally_arm();
21751        if !props.is_empty() {
21752            // Two ratios, side by side: what a batched verify over the trunk
21753            // would read against what it asks for, and the same for the
21754            // draft's three stages. Near 1.0 means a batch amortises nothing.
21755            let (tu, tt) = {
21756                let flat: Vec<(usize, Vec<usize>)> = self
21757                    .dspark_trunk_picks
21758                    .iter()
21759                    .flat_map(|v| v.iter().cloned())
21760                    .collect();
21761                // Per layer, across the window of tokens.
21762                let mut per: std::collections::HashMap<usize, Vec<usize>> =
21763                    std::collections::HashMap::new();
21764                for (li, picks) in flat {
21765                    per.entry(li).or_default().extend(picks);
21766                }
21767                let n = per.len().max(1);
21768                let mut u = 0usize;
21769                let mut t = 0usize;
21770                for (_, v) in per {
21771                    t += v.len();
21772                    u += v.iter().collect::<std::collections::HashSet<_>>().len();
21773                }
21774                (u / n, t / n)
21775            };
21776            let (du, dt) = crate::dsv4::tally_unique(&draft_picks);
21777            self.dspark_exp.push((tu, tt, du, dt));
21778            self.dspark_pending.push((position, props, true, 0));
21779        }
21780        if self.dspark_hist.len() >= 8 && self.dspark_hist.len() % 8 == 0 {
21781            let n = self.dspark_hist.len() as f32;
21782            let mean: f32 = self.dspark_hist.iter().sum::<usize>() as f32 / n;
21783            let block = crate::dsv4::dspark_block();
21784            let mut at = vec![0usize; block + 1];
21785            for &k in &self.dspark_hist {
21786                at[k] += 1;
21787            }
21788            // Prefix survival: S_i = P(the first i positions all held).
21789            let mut surv = Vec::with_capacity(block);
21790            for i in 1..=block {
21791                let k = at[i..].iter().sum::<usize>() as f32 / n;
21792                surv.push(format!("{k:.2}"));
21793            }
21794            let distinct = self
21795                .dspark_real
21796                .iter()
21797                .collect::<std::collections::HashSet<_>>()
21798                .len();
21799            let (tu, tt, du, dt) = self.dspark_exp.iter().fold((0, 0, 0, 0), |a, b| {
21800                (a.0 + b.0, a.1 + b.1, a.2 + b.2, a.3 + b.3)
21801            });
21802            let m = self.dspark_exp.len().max(1);
21803            eprintln!(
21804                "DSpark: {} drafts, {mean:.2} of {block} accepted on average \
21805                 (tokens per pass {:.2}), distribution {at:?}, survival [{}]",
21806                self.dspark_hist.len(),
21807                mean + 1.0,
21808                surv.join(" ")
21809            );
21810            eprintln!(
21811                "DSpark: {distinct} distinct tokens of {} (degeneracy), \
21812                 trunk experts {}/{} per layer over {block} tokens, \
21813                 draft {}/{} per block, draft {:.2} ms/block",
21814                self.dspark_real.len(),
21815                tu / m,
21816                tt / m,
21817                du / m,
21818                dt / m,
21819                self.dspark_draft_ns as f64 / self.dspark_exp.len().max(1) as f64 / 1e6
21820            );
21821        }
21822    }
21823
21824    fn forward_layers_upto(
21825        &mut self,
21826        hidden: &[f32],
21827        position: usize,
21828        task_mask: Option<&TaskMask>,
21829        upto: Option<usize>,
21830    ) -> Vec<f32> {
21831        // In-process multi-GPU: each segment runs pinned to its card,
21832        // and the only thing crossing the boundary is one hidden vector
21833        // that never leaves this address space. Same layer split the
21834        // network mode does, minus the second process, the socket, the
21835        // serialization and the dir_hash handshake.
21836        if let Some(plan) = self.gpu_plan.clone() {
21837            if upto.is_none() && plan.len() > 1 {
21838                let mut h = hidden.to_vec();
21839                for &(dev, from, upto_incl) in plan.iter() {
21840                    h = crate::gpu::with_device(dev, || {
21841                        self.forward_layers_span(&h, position, task_mask, from, Some(upto_incl))
21842                    });
21843                }
21844                return h;
21845            }
21846        }
21847        self.forward_layers_span(hidden, position, task_mask, 0, upto)
21848    }
21849
21850    /// Split this pipeline's layer stack across local GPUs: segment i
21851    /// runs on `devices[i]`. Contiguous and even by layer count — the
21852    /// VRAM-weighted planner is the next step, and an uneven card pair
21853    /// is why it will be needed. `None` clears the plan.
21854    pub fn set_gpu_plan(&mut self, devices: Option<&[usize]>) -> Result<(), String> {
21855        self.set_gpu_plan_at(devices, None)
21856    }
21857
21858    /// The same, with an explicit first boundary (`--peer-split`): card
21859    /// 0 takes layers `[0..at)`, the rest split what remains. Uneven
21860    /// cards, or an attention-heavy head, are why this knob exists.
21861    pub fn set_gpu_plan_at(
21862        &mut self,
21863        devices: Option<&[usize]>,
21864        at: Option<usize>,
21865    ) -> Result<(), String> {
21866        let Some(devs) = devices.filter(|d| d.len() > 1) else {
21867            self.gpu_plan = None;
21868            return Ok(());
21869        };
21870        self.split_supported()?;
21871        let n = self.num_layers;
21872        if devs.len() > n {
21873            return Err(format!("{} devices for {n} layers", devs.len()));
21874        }
21875        if let Some(k) = at {
21876            if k == 0 || k >= n {
21877                return Err(format!("split at {k}: the model has {n} layers"));
21878            }
21879            if devs.len() == 2 {
21880                self.gpu_plan = Some(std::sync::Arc::new(vec![
21881                    (devs[0], 0, k - 1),
21882                    (devs[1], k, n - 1),
21883                ]));
21884                return Ok(());
21885            }
21886            return Err(format!(
21887                "an explicit split point takes exactly 2 devices, got {}",
21888                devs.len()
21889            ));
21890        }
21891        let per = n.div_ceil(devs.len());
21892        let mut plan = Vec::with_capacity(devs.len());
21893        let mut from = 0usize;
21894        for &d in devs {
21895            if from >= n {
21896                break;
21897            }
21898            let upto = (from + per - 1).min(n - 1);
21899            plan.push((d, from, upto));
21900            from = upto + 1;
21901        }
21902        self.gpu_plan = Some(std::sync::Arc::new(plan));
21903        Ok(())
21904    }
21905
21906    /// The active in-process split, if any: (device, first layer, last).
21907    pub fn gpu_plan(&self) -> Option<Vec<(usize, usize, usize)>> {
21908        self.gpu_plan.as_ref().map(|p| p.as_ref().clone())
21909    }
21910
21911    /// Layer span [from ..= upto] (upto None = last layer): the building
21912    /// block the network pipeline-split rides on. `from > 0` skips the
21913    /// arch escape hatches (the pub `forward_span` refuses those archs
21914    /// first) and the whole-token graph — the plain per-layer loop is
21915    /// the canonical executor for a partial stack.
21916    fn embryo_qtensor_f32(t: &QTensor) -> Vec<f32> {
21917        if let Some(x) = t.as_f32() {
21918            return x.to_vec();
21919        }
21920        let mut out = vec![0.0; t.rows() * t.cols()];
21921        for r in 0..t.rows() {
21922            t.row_f32(r, &mut out[r * t.cols()..(r + 1) * t.cols()]);
21923        }
21924        out
21925    }
21926
21927    fn embryo_resident_eligible(&self) -> bool {
21928        fn served(t: &QTensor) -> bool {
21929            t.as_f32().is_some() || t.q8_2f_codes().is_some()
21930        }
21931        // One mixer family per file: vmf_phase (kind 0/1) or
21932        // gated_delta_net (kind 4); the anchors are full (2) or bounded (3).
21933        if (self.vmf_cfg.is_none() && self.gdn_cfg.is_none())
21934            || self.num_layers != self.physical_layers
21935            || self.loop_final_norm
21936            || self.weights.layers.len() != self.num_layers
21937            || self.head_clusters.is_none()
21938            || self.final_softcap.is_some()
21939            || self.logit_multiplier.is_some()
21940            || self.attn_softcap != 0.0
21941            || self.mtp.is_some()
21942            || self.per_token_stack()
21943            || self.dsv4.is_some()
21944            || self.dsv41.is_some()
21945            || self.dory.is_some()
21946            || self.qwen4_exp.is_some()
21947            || self.glm5_next.is_some()
21948            || self.hy4.is_some()
21949            || self.maxwell.is_some()
21950            || self.inkling.is_some()
21951            // Dynamic routing swaps FFN weights mid-sequence under the
21952            // packed graph; a blend has no single overlay. A STATIC skill
21953            // (`from_model_with_skill`) is fine: the pack reads the live
21954            // `weights.layers[*].ffn`, i.e. the skill's tensors, and a
21955            // later `set_active_skill` change drops the pack
21956            // (`invalidate_for_weight_change`).
21957            || self.dyn_router.is_some()
21958            || self.dyn_phi_layer.is_some()
21959            || self.dyn_blend_loaded
21960            || self.o1_cfg.is_some()
21961            || self.swa.is_some()
21962            || self.sliding_layers.is_some()
21963            || self.global_attn.is_some()
21964            || self.attention_heads_per_layer.is_some()
21965            || self.attn_v_norm
21966            || self
21967                .kv_cache
21968                .layers
21969                .iter()
21970                .any(|l| l.mode != crate::kv_cache::KvMode::F32)
21971            || self.rope_scale != 1.0
21972            || self.rope_scale_local != 1.0
21973            || self.attn_scale != 1.0 / (self.head_dim as f32).sqrt()
21974            || self.hidden_size == 0
21975            || self.hidden_size > 1024
21976            || self.intermediate_size > 1024
21977            || self.num_heads == 0
21978            || self.num_kv_heads == 0
21979            || self.num_heads % self.num_kv_heads != 0
21980            || self.num_heads.saturating_mul(self.head_dim) > 1024
21981            || self.num_kv_heads.saturating_mul(self.head_dim) > 1024
21982            || self.vocab_size == 0
21983            || self.kv_cache.max_seq_len == 0
21984            || self.rotary_dim == 0
21985            || self.rotary_dim > self.head_dim
21986            || self.rotary_dim % 2 != 0
21987            || self.inv_freq.len() < self.rotary_dim / 2
21988        {
21989            return false;
21990        }
21991        // The resident shaders read f32 or f16 values, or q8_2f codes through
21992        // the same formula as the CPU path. Other quantized files keep the
21993        // ordinary executor: dequantizing a Q4 tensor into the packed buffer
21994        // would silently change the operator relative to the CPU quantized
21995        // path. Measured consequence (RTX PRO 4000, S4 bounded export requantized
21996        // with `cortiq requant --quant q4tp-quantize`): `eligible=false`,
21997        // the generic wgpu whole-token graph refuses too, and the per-op
21998        // path decodes at ~73 tok/s against ~200 tok/s on the CPU q4tp path.
21999        if self.weights.lm_head.q8_2f_codes().is_some() && !self.embryo_wide_candidate(true) {
22000            return false;
22001        }
22002        if !served(&self.weights.lm_head)
22003            || !served(&self.weights.embed_tokens)
22004            || self.weights.lm_head.rows() < self.vocab_size
22005            || self.weights.lm_head.cols() != self.hidden_size
22006            || self.weights.embed_tokens.rows() < self.vocab_size
22007            || self.weights.embed_tokens.cols() != self.hidden_size
22008            || self.weights.final_norm.len() != self.hidden_size
22009        {
22010            return false;
22011        }
22012        if let Some(cfg) = self.vmf_cfg {
22013            if cfg.num_heads.saturating_mul(cfg.nphase) > 1024
22014                || cfg.num_heads.saturating_mul(cfg.nphase.saturating_add(1)) > 1024
22015                || cfg.num_heads.saturating_mul(cfg.value_head_dim) > 1024
22016                || cfg.state_len() == 0
22017            {
22018                return false;
22019            }
22020        }
22021        if let Some(g) = self.gdn_cfg {
22022            // The resident GDN kernels (gpu_wgpu.rs `embryo_core_gdn_*`):
22023            // fused projection ≤ 2048 rows, nv·dv ≤ 1024, dk ≤ 128 lanes,
22024            // dv ≤ 256 lanes in vec4 rows, SiLU output gate (the Embryo
22025            // export), same rms eps as the stack.
22026            if g.num_v_heads == 0
22027                || g.num_k_heads == 0
22028                || g.num_v_heads % g.num_k_heads != 0
22029                || g.key_head_dim == 0
22030                || g.key_head_dim > 128
22031                || g.value_head_dim == 0
22032                || g.value_head_dim > 256
22033                || g.value_head_dim % 4 != 0
22034                || g.conv_kernel == 0
22035                || g.num_v_heads > 512
22036                || g.num_v_heads.saturating_mul(g.value_head_dim) > 1024
22037                || g.conv_dim() > 2048
22038                || g.conv_dim() % 4 != 0
22039                || g.hidden_size != self.hidden_size
22040                || g.output_gate_sigmoid
22041                || g.rms_eps != self.rms_eps
22042                || g.state_len() == 0
22043            {
22044                return false;
22045            }
22046        }
22047        let mut full_seen = false;
22048        for lw in &self.weights.layers {
22049            if lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some() {
22050                return false;
22051            }
22052            match &lw.attn {
22053                AttnKind::LinearGdn(w) => {
22054                    let Some(g) = self.gdn_cfg else {
22055                        return false;
22056                    };
22057                    let (nv, dv, kk) = (g.num_v_heads, g.value_head_dim, g.conv_kernel);
22058                    if w.in_proj_qkv.rows() != g.conv_dim()
22059                        || w.in_proj_qkv.cols() != self.hidden_size
22060                        || !served(&w.in_proj_qkv)
22061                        || w.in_proj_z.rows() != nv * dv
22062                        || w.in_proj_z.cols() != self.hidden_size
22063                        || !served(&w.in_proj_z)
22064                        || w.in_proj_a.rows() != nv
22065                        || w.in_proj_a.cols() != self.hidden_size
22066                        || !served(&w.in_proj_a)
22067                        || w.in_proj_b.rows() != nv
22068                        || w.in_proj_b.cols() != self.hidden_size
22069                        || !served(&w.in_proj_b)
22070                        || w.conv1d.len() != g.conv_dim() * kk
22071                        || w.a_log.len() != nv
22072                        || w.dt_bias.len() != nv
22073                        || w.norm.len() != dv
22074                        || w.out_proj.rows() != self.hidden_size
22075                        || w.out_proj.cols() != nv * dv
22076                        || !served(&w.out_proj)
22077                    {
22078                        return false;
22079                    }
22080                }
22081                AttnKind::Linear(w) => {
22082                    let Some(cfg) = self.vmf_cfg else {
22083                        return false;
22084                    };
22085                    if w.thq.rows() != cfg.num_heads * cfg.nphase
22086                        || w.thq.cols() != self.hidden_size
22087                        || !served(&w.thq)
22088                        || w.thk.rows() != cfg.num_heads * cfg.nphase
22089                        || w.thk.cols() != self.hidden_size
22090                        || !served(&w.thk)
22091                        || w.v_proj.rows() != cfg.num_heads * cfg.value_head_dim
22092                        || w.v_proj.cols() != self.hidden_size
22093                        || !served(&w.v_proj)
22094                        || w.out_proj.rows() != self.hidden_size
22095                        || w.out_proj.cols() != cfg.num_heads * cfg.value_head_dim
22096                        || !served(&w.out_proj)
22097                        || w.decay.len() != cfg.num_heads * 2 * cfg.nphase
22098                    {
22099                        return false;
22100                    }
22101                    if let Some((kg, kb)) = &w.k_gate {
22102                        if kg.rows() != cfg.num_heads
22103                            || kg.cols() != self.hidden_size
22104                            || !served(&kg)
22105                            || kb.len() != cfg.num_heads
22106                        {
22107                            return false;
22108                        }
22109                    }
22110                    if let Some(conv) = &w.conv {
22111                        if conv.len() % self.hidden_size != 0 || conv.len() / self.hidden_size < 2 {
22112                            return false;
22113                        }
22114                    }
22115                }
22116                AttnKind::Full {
22117                    wq,
22118                    wk,
22119                    wv,
22120                    wo,
22121                    q_norm,
22122                    k_norm,
22123                    output_gate,
22124                    softplus_gate,
22125                    bias,
22126                } => {
22127                    if full_seen
22128                        || q_norm.is_some()
22129                        || k_norm.is_some()
22130                        || *output_gate
22131                        || softplus_gate.is_some()
22132                        || bias.is_some()
22133                        || !served(&wq)
22134                        || !served(&wk)
22135                        || !served(&wv)
22136                        || !served(&wo)
22137                        || wq.rows() != self.num_heads * self.head_dim
22138                        || wk.rows() != self.num_kv_heads * self.head_dim
22139                        || wv.rows() != self.num_kv_heads * self.head_dim
22140                        || wq.cols() != self.hidden_size
22141                        || wk.cols() != self.hidden_size
22142                        || wv.cols() != self.hidden_size
22143                        || wo.rows() != self.hidden_size
22144                        || wo.cols() != self.num_heads * self.head_dim
22145                    {
22146                        return false;
22147                    }
22148                    full_seen = true;
22149                }
22150                AttnKind::Bounded(w) => {
22151                    // The resident bounded attend walks S + W keys in
22152                    // 256-lane tiles (online softmax), any window the format
22153                    // allows; per-group windows come from header word 22.
22154                    let Some(ac) = self.anchor_core.as_ref() else {
22155                        return false;
22156                    };
22157                    if self.bounded_rope.is_none()
22158                        || w.window != ac.window
22159                        || w.sink != ac.sink
22160                        || w.group_windows != ac.group_windows
22161                        || w.window == 0
22162                        || w.sink_k.len() != self.num_kv_heads * w.sink * self.head_dim
22163                        || w.sink_v.len() != self.num_kv_heads * w.sink * self.head_dim
22164                        || !served(&w.wq)
22165                        || !served(&w.wk)
22166                        || !served(&w.wv)
22167                        || !served(&w.wo)
22168                        || w.wq.rows() != self.num_heads * self.head_dim
22169                        || w.wk.rows() != self.num_kv_heads * self.head_dim
22170                        || w.wv.rows() != self.num_kv_heads * self.head_dim
22171                        || w.wq.cols() != self.hidden_size
22172                        || w.wk.cols() != self.hidden_size
22173                        || w.wv.cols() != self.hidden_size
22174                        || w.wo.rows() != self.hidden_size
22175                        || w.wo.cols() != self.num_heads * self.head_dim
22176                    {
22177                        return false;
22178                    }
22179                }
22180                _ => return false,
22181            }
22182            match &lw.ffn {
22183                FfnKind::Dense(d) => {
22184                    if d.act != Act::Silu
22185                        || !d.segs.is_empty()
22186                        || !served(&d.gate_proj)
22187                        || !served(&d.up_proj)
22188                        || !served(&d.down_proj)
22189                        || d.gate_proj.rows() != self.intermediate_size
22190                        || d.gate_proj.cols() != self.hidden_size
22191                        || d.up_proj.rows() != self.intermediate_size
22192                        || d.up_proj.cols() != self.hidden_size
22193                        || d.down_proj.rows() != self.hidden_size
22194                        || d.down_proj.cols() != self.intermediate_size
22195                    {
22196                        return false;
22197                    }
22198                }
22199                FfnKind::Moe(m) => {
22200                    if m.resonance.is_none()
22201                        || m.top_k != 1
22202                        || m.router_sigmoid
22203                        || !m.norm_topk_prob
22204                        || m.expert_bias.is_some()
22205                        || m.routed_scaling != 1.0
22206                        || m.route_tau.is_some()
22207                        || m.shared.is_none()
22208                        || m.mask.is_some()
22209                        || m.per_expert_scale.is_some()
22210                        || m.router_input_norm
22211                        || m.experts.is_empty()
22212                        || m.experts.len() > 8
22213                    {
22214                        return false;
22215                    }
22216                    let r = m.resonance.as_ref().unwrap();
22217                    if r.mu.len() != m.experts.len() * self.hidden_size
22218                        || r.bias.len() != m.experts.len()
22219                        || r.u.len() != m.experts.len() * r.k * self.hidden_size
22220                        || r.k > 128
22221                    {
22222                        return false;
22223                    }
22224                    let Some((shared, gate)) = &m.shared else {
22225                        return false;
22226                    };
22227                    if gate.is_some() || shared.act != Act::Silu || !shared.segs.is_empty() {
22228                        return false;
22229                    }
22230                    if !served(&shared.gate_proj)
22231                        || !served(&shared.up_proj)
22232                        || !served(&shared.down_proj)
22233                        || shared.gate_proj.rows() != self.intermediate_size
22234                        || shared.gate_proj.cols() != self.hidden_size
22235                        || shared.up_proj.rows() != self.intermediate_size
22236                        || shared.up_proj.cols() != self.hidden_size
22237                        || shared.down_proj.rows() != self.hidden_size
22238                        || shared.down_proj.cols() != self.intermediate_size
22239                    {
22240                        return false;
22241                    }
22242                    for e in &m.experts {
22243                        if e.act != Act::Silu
22244                            || !e.segs.is_empty()
22245                            || !served(&e.gate_proj)
22246                            || !served(&e.up_proj)
22247                            || !served(&e.down_proj)
22248                            || e.gate_proj.rows() != self.intermediate_size
22249                            || e.gate_proj.cols() != self.hidden_size
22250                            || e.up_proj.rows() != self.intermediate_size
22251                            || e.up_proj.cols() != self.hidden_size
22252                            || e.down_proj.rows() != self.hidden_size
22253                            || e.down_proj.cols() != self.intermediate_size
22254                        {
22255                            return false;
22256                        }
22257                    }
22258                }
22259                FfnKind::DenseMoe(_) => return false,
22260            }
22261            if lw.input_norm.len() != self.hidden_size || lw.post_norm.len() != self.hidden_size {
22262                return false;
22263            }
22264        }
22265        if full_seen && self.anchor_core.is_some() {
22266            return false;
22267        }
22268        full_seen || self.num_layers > 0
22269    }
22270
22271    /// The resident Embryo graph is the owner of this pipeline's forward:
22272    /// the same gate `forward_layers_span` applies before handing a token
22273    /// to `forward_embryo_graph` (both graph phases on, the explicit
22274    /// opt-in, a wgpu device, no earlier refusal, an eligible stack).
22275    fn embryo_resident_wanted(&self) -> bool {
22276        crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)
22277            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill)
22278            && matches!(
22279                std::env::var("CMF_EMBRYO_RESIDENT").as_deref(),
22280                Ok("1") | Ok("parallel")
22281            )
22282            && crate::gpu::enabled_here()
22283            && !self.graph_refused()
22284            && self.embryo_resident_eligible()
22285    }
22286
22287    /// Chunked prefill on the resident graph: `ids` from `start` in
22288    /// chunks of `EMBRYO_CHUNK_MAX`, one submit each, projections/FFN as
22289    /// chunk GEMMs and the recurrent layers walked in time on the device.
22290    /// Returns the last position's logits when the whole span ran there.
22291    /// `None` = refused before any device work (the per-position path
22292    /// takes the span).  `CMF_EMBRYO_CHUNK=0` keeps the per-position
22293    /// prefill (A/B and the parity reference).
22294    fn embryo_prefill_chunked(&mut self, ids: &[u32], start: usize) -> Option<Vec<f32>> {
22295        if ids.len() < 2
22296            || std::env::var("CMF_EMBRYO_CHUNK").as_deref() == Ok("0")
22297            || !self.embryo_resident_wanted()
22298        {
22299            return None;
22300        }
22301        let model = self.ensure_embryo_graph()?;
22302        let cmax = std::env::var("CMF_EMBRYO_CHUNK")
22303            .ok()
22304            .and_then(|v| v.parse::<usize>().ok())
22305            .filter(|&v| v >= 1)
22306            .unwrap_or(crate::gpu::EMBRYO_CHUNK_MAX)
22307            .min(crate::gpu::EMBRYO_CHUNK_MAX);
22308        let hs = self.hidden_size;
22309        let n = ids.len();
22310        let mut pos = start;
22311        let mut last = None;
22312        let mut rows = Vec::with_capacity(cmax * hs);
22313        while pos < n {
22314            let end = (pos + cmax).min(n);
22315            rows.clear();
22316            for &id in &ids[pos..end] {
22317                rows.extend_from_slice(&self.embed_single(id));
22318            }
22319            let mut lg = Vec::new();
22320            if !crate::gpu::forward_embryo_graph_chunk(
22321                &model,
22322                self.graph_kv_id,
22323                &rows,
22324                pos,
22325                end - pos,
22326                &mut lg,
22327            ) {
22328                if pos == start {
22329                    if std::env::var("CMF_EMBRYO_DBG").as_deref() == Ok("1") {
22330                        eprintln!("embryo-dbg: chunk prefill refused at position {pos}");
22331                    }
22332                    return None;
22333                }
22334                // The device sequence advanced through the earlier chunks;
22335                // a host continuation would mix two owners of the state.
22336                // Fail this sequence alone, leaving no stale state or key.
22337                self.kv_cache.clear();
22338                self.clear_history();
22339                crate::gpu::graph_kv_reset(self.graph_kv_id);
22340                panic!(
22341                    "resident Embryo chunk prefill refused at position {pos}; refusing an in-flight host fallback"
22342                );
22343            }
22344            last = Some(lg);
22345            pos = end;
22346        }
22347        if std::env::var("CMF_EMBRYO_DBG").as_deref() == Ok("1") {
22348            eprintln!(
22349                "embryo-dbg: chunk prefill {} ids from {start} in {} submits (chunk {cmax})",
22350                n - start,
22351                (n - start).div_ceil(cmax)
22352            );
22353        }
22354        last
22355    }
22356
22357    /// Can this file run the wide token path? GDN mixers, bounded anchors, and
22358    /// rows and columns that fit the kernels' four-row, eight-column grid.
22359    fn embryo_wide_candidate(&self, q8: bool) -> bool {
22360        if self.embryo_wide_refused
22361            || std::env::var("CMF_EMBRYO_WIDE").as_deref() == Ok("0")
22362            || !crate::gpu::embryo_wide_ready(q8)
22363        {
22364            return false;
22365        }
22366        let Some(g) = self.gdn_cfg else {
22367            return false;
22368        };
22369        let (hidden, inter, hd) = (self.hidden_size, self.intermediate_size, self.head_dim);
22370        let (nv, nk, dk, dv) = (g.num_v_heads, g.num_k_heads, g.key_head_dim, g.value_head_dim);
22371        let (q, kv) = (self.num_heads, self.num_kv_heads);
22372        // A q8_2f row is read 16 codes at a time, an f16 row 8 values at a time.
22373        let step = if q8 { 16 } else { 8 };
22374        let geometry = hidden % step == 0
22375            && hidden <= 1024
22376            && inter % step == 0
22377            && inter <= 1024
22378            && self.vocab_size % 4 == 0
22379            && self.head_clusters.as_ref().is_some_and(|c| {
22380                let nc = c.len() / hidden.max(1);
22381                // A workgroup holds a cluster's rows.
22382                nc > 0 && nc <= 256 && self.vocab_size % nc == 0 && self.vocab_size / nc <= 256
22383            })
22384            && dk % 4 == 0
22385            && dv % 4 == 0
22386            && (nv * dv) % step == 0
22387            && nv * dv <= 1024
22388            && nv <= 508
22389            && nk > 0
22390            && nv % nk == 0
22391            && g.conv_dim() % 4 == 0
22392            && g.conv_dim() <= 2048
22393            && hd % 4 == 0
22394            && (q * hd) % step == 0
22395            && q * hd <= 1024
22396            && kv > 0
22397            && q % kv == 0
22398            && (kv * hd) % 4 == 0
22399            && (self.rotary_dim / 2) % 4 == 0;
22400        if !geometry {
22401            return false;
22402        }
22403        self.weights.layers.iter().all(|lw| {
22404            matches!(lw.attn, AttnKind::Bounded(_) | AttnKind::LinearGdn(_))
22405                && match &lw.ffn {
22406                    FfnKind::Moe(m) => m.resonance.as_ref().is_some_and(|r| m.experts.len() * (r.k + 1) <= 256) && m.shared.is_some(),
22407                    FfnKind::Dense(_) => true,
22408                    FfnKind::DenseMoe(_) => false,
22409                }
22410        })
22411    }
22412
22413    fn ensure_embryo_graph(&mut self) -> Option<std::sync::Arc<crate::gpu::EmbryoGraphModel>> {
22414        if self.embryo_graph.is_none() && self.embryo_resident_eligible() {
22415            const UMAX: u32 = u32::MAX;
22416            const HEADER: usize = crate::gpu::EMBRYO_META_HEADER;
22417            const REC: usize = 64;
22418            struct Pack {
22419                data: Vec<f32>,
22420                /// The wide token path: matrices in their packed form in `mats`.
22421                wide: bool,
22422                q8: bool,
22423                mats: Vec<u8>,
22424                /// q8_2f: (codes, row scales, column field) of each matrix; its
22425                /// word in the layer record is its index in the meta after the layers.
22426                table: Vec<u32>,
22427                table_base: u32,
22428                refused: bool,
22429            }
22430            impl Pack {
22431                fn put(&mut self, x: &[f32]) -> u32 {
22432                    if x.is_empty() {
22433                        return u32::MAX;
22434                    }
22435                    // The wide kernels read the small tensors as vec4
22436                    if self.wide {
22437                        self.data.resize(self.data.len().next_multiple_of(4), 0.0);
22438                    }
22439                    let off = self.data.len();
22440                    self.data.extend_from_slice(x);
22441                    off as u32
22442                }
22443                /// A matrix a token reads in full.
22444                fn mat(&mut self, t: &QTensor) -> u32 {
22445                    if !self.wide {
22446                        return self.put(&Pipeline::embryo_qtensor_f32(t));
22447                    }
22448                    if self.q8 {
22449                        let Some((q, rows, cols)) = t.q8_2f_codes() else {
22450                            self.refused = true;
22451                            return 0;
22452                        };
22453                        self.mats.resize(self.mats.len().next_multiple_of(16), 0);
22454                        let off = self.mats.len() as u32;
22455                        self.mats.extend_from_slice(&q[..t.rows() * t.cols()]);
22456                        let (rs, cs) = (self.put(rows), self.put(cols));
22457                        let e = self.table_base + self.table.len() as u32;
22458                        self.table.extend_from_slice(&[off, rs, cs]);
22459                        return e;
22460                    }
22461                    self.mats.resize(self.mats.len().next_multiple_of(16), 0);
22462                    let off = self.mats.len() / 2;
22463                    for v in Pipeline::embryo_qtensor_f32(t) {
22464                        let h = cortiq_core::quant::f32_to_f16(v);
22465                        self.refused |= cortiq_core::quant::f16_to_f32(h).to_bits() != v.to_bits();
22466                        self.mats.extend_from_slice(&h.to_le_bytes());
22467                    }
22468                    off as u32
22469                }
22470            }
22471            // The mixer family of the file: vmf_phase geometry fills the
22472            // phase header words, gated_delta_net fills words 24..29.  A
22473            // file has exactly one linear core, so at most one is live.
22474            let vmf = self.vmf_cfg;
22475            let gdn = self.gdn_cfg;
22476            // A file of q8_2f matrices or of matrices exact in f16 runs the wide path.
22477            let q8 = self.weights.lm_head.q8_2f_codes().is_some();
22478            let wide = self.embryo_wide_candidate(q8);
22479            let mut pack = Pack {
22480                data: Vec::new(),
22481                wide,
22482                q8,
22483                mats: Vec::new(),
22484                table: Vec::new(),
22485                table_base: (HEADER + self.num_layers * REC) as u32,
22486                refused: false,
22487            };
22488            let mut meta = vec![0u32; HEADER];
22489            meta[0] = self.hidden_size as u32;
22490            meta[1] = self.intermediate_size as u32;
22491            meta[2] = self.vocab_size as u32;
22492            meta[3] = self.num_layers as u32;
22493            meta[4] = vmf.map(|c| c.num_heads).unwrap_or(0) as u32;
22494            meta[5] = vmf.map(|c| c.nphase).unwrap_or(0) as u32;
22495            meta[6] = vmf.map(|c| c.value_head_dim).unwrap_or(0) as u32;
22496            if let Some(g) = gdn {
22497                meta[24] = g.num_v_heads as u32;
22498                meta[25] = g.num_k_heads as u32;
22499                meta[26] = g.key_head_dim as u32;
22500                meta[27] = g.value_head_dim as u32;
22501                meta[28] = g.conv_kernel as u32;
22502                meta[29] = g.conv_dim() as u32;
22503            }
22504            meta[7] = self.num_heads as u32;
22505            meta[8] = self.num_kv_heads as u32;
22506            meta[9] = self.head_dim as u32;
22507            meta[10] = self.kv_cache.max_seq_len as u32;
22508            let clusters = self.head_clusters.as_ref().unwrap();
22509            let cluster_count = clusters.len() / self.hidden_size;
22510            if clusters.len() % self.hidden_size != 0
22511                || cluster_count == 0
22512                || cluster_count > 1024
22513                || self.vocab_size % cluster_count != 0
22514                || self.weights.lm_head.rows() < self.vocab_size
22515                || self.weights.final_norm.len() != self.hidden_size
22516            {
22517                return None;
22518            }
22519            meta[11] = cluster_count as u32;
22520            meta[12] = (self.vocab_size / cluster_count) as u32;
22521            meta[13] = vmf.map(|c| c.state_len()).unwrap_or(0) as u32;
22522            meta[16] = self.rotary_dim as u32;
22523            meta[17] = matches!(self.norm_style, NormStyle::Gemma) as u32;
22524            meta[19] = (self.rms_eps as f32).to_bits();
22525            let max_conv = self
22526                .weights
22527                .layers
22528                .iter()
22529                .filter_map(|lw| match &lw.attn {
22530                    AttnKind::Linear(w) => w.conv.as_ref().map(|v| v.len() / self.hidden_size),
22531                    _ => None,
22532                })
22533                .max()
22534                .unwrap_or(1);
22535            // One state slot per recurrent layer: the phase state plus its
22536            // hidden-wide conv ring, or the GDN record `[conv ring | S]`
22537            // (`GdnCfg::state_len`).  A file carries one mixer family, so
22538            // the stride is exactly that family's record and the device
22539            // state buffer equals the header's recurrent bytes.
22540            let phase_stride = vmf
22541                .map(|c| c.state_len() + max_conv.saturating_sub(1) * self.hidden_size)
22542                .unwrap_or(0);
22543            let gdn_stride = gdn.map(|g| g.state_len()).unwrap_or(0);
22544            let state_stride = phase_stride.max(gdn_stride);
22545            // Bounded genome: the KV plane of an anchor is its ring
22546            // `[kvh][W][hd]` K + V, and only anchors own one.  Legacy full
22547            // anchors keep the `max_seq` planes indexed by layer.
22548            let bounded = self.anchor_core.clone();
22549            let (anchor_window, anchor_sink) = bounded
22550                .as_ref()
22551                .map(|ac| (ac.window, ac.sink))
22552                .unwrap_or((0, 0));
22553            let kv_stride = if bounded.is_some() {
22554                2usize
22555                    .saturating_mul(self.num_kv_heads)
22556                    .saturating_mul(anchor_window)
22557                    .saturating_mul(self.head_dim)
22558            } else {
22559                2usize
22560                    .saturating_mul(self.num_kv_heads)
22561                    .saturating_mul(self.kv_cache.max_seq_len)
22562                    .saturating_mul(self.head_dim)
22563            };
22564            meta[14] = state_stride as u32;
22565            meta[15] = kv_stride as u32;
22566            meta[18] = anchor_window as u32;
22567            meta[20] = anchor_sink as u32;
22568            // Scores, weights and the key list of each head fit the wide scratch plane.
22569            pack.refused |= pack.wide
22570                && 3 * self.num_heads * (anchor_window + anchor_sink + 3) + 256 > 65_536;
22571            meta[21] = match &self.bounded_rope {
22572                // The wide path rotates by the absolute position: no table.
22573                _ if pack.wide => UMAX,
22574                Some(rope) => {
22575                    // [W][half] cos then [W][half] sin, one contiguous table.
22576                    let off = pack.put(&rope.cos);
22577                    let _ = pack.put(&rope.sin);
22578                    off
22579                }
22580                None => UMAX,
22581            };
22582            // swa_sink_v2: one window per KV group (f32 in the pack; exact
22583            // for any window the format allows); UMAX = every group `W`.
22584            meta[22] = match bounded.as_ref().filter(|ac| !ac.group_windows.is_empty()) {
22585                Some(ac) => {
22586                    let gw: Vec<f32> = ac.group_windows.iter().map(|&w| w as f32).collect();
22587                    pack.put(&gw)
22588                }
22589                None => UMAX,
22590            };
22591            let mut full_seen = false;
22592            let mut bounded_seen = 0usize;
22593            // Recurrent state slots belong to mixer layers only (phase or
22594            // GDN): an anchor owns a ring, not a state stride, so the
22595            // device state buffer is exactly the header's recurrent bytes.
22596            let mut phase_seen = 0usize;
22597            let mut gdn_seen = 0usize;
22598            for (li, lw) in self.weights.layers.iter().enumerate() {
22599                let base = meta.len();
22600                meta.resize(base + REC, UMAX);
22601                meta[base] = match &lw.attn {
22602                    AttnKind::Linear(w) if w.phase_delta => 1,
22603                    AttnKind::Linear(_) => 0,
22604                    AttnKind::Full { .. } => 2,
22605                    AttnKind::Bounded(_) => 3,
22606                    AttnKind::LinearGdn(_) => 4,
22607                    _ => UMAX,
22608                };
22609                meta[base + 1] = pack.put(&lw.input_norm);
22610                meta[base + 2] = pack.put(&lw.post_norm);
22611                meta[base + 25] = match &lw.attn {
22612                    AttnKind::Linear(_) => {
22613                        let off = ((phase_seen + gdn_seen) * state_stride) as u32;
22614                        phase_seen += 1;
22615                        off
22616                    }
22617                    AttnKind::LinearGdn(_) => {
22618                        let off = ((phase_seen + gdn_seen) * state_stride) as u32;
22619                        gdn_seen += 1;
22620                        off
22621                    }
22622                    _ => UMAX,
22623                };
22624                match &lw.attn {
22625                    AttnKind::LinearGdn(w) => {
22626                        // Layer record words 56..63 + 29, as the resident
22627                        // kernels read them (gpu_wgpu.rs `embryo_core_gdn_*`).
22628                        meta[base + 56] = pack.mat(&w.in_proj_qkv);
22629                        meta[base + 57] = pack.mat(&w.in_proj_z);
22630                        meta[base + 58] = pack.mat(&w.in_proj_a);
22631                        meta[base + 59] = pack.mat(&w.in_proj_b);
22632                        meta[base + 60] = pack.put(&w.conv1d);
22633                        meta[base + 61] = pack.put(&w.a_log);
22634                        meta[base + 62] = pack.put(&w.dt_bias);
22635                        meta[base + 63] = pack.put(&w.norm);
22636                        meta[base + 29] = pack.mat(&w.out_proj);
22637                        meta[base + 24] = 0;
22638                    }
22639                    AttnKind::Linear(w) => {
22640                        meta[base + 3] = pack.mat(&w.thq);
22641                        meta[base + 4] = pack.mat(&w.thk);
22642                        meta[base + 5] = pack.mat(&w.v_proj);
22643                        meta[base + 6] = pack.mat(&w.out_proj);
22644                        let decay: Vec<f32> = w.decay.iter().map(|&x| x as f32).collect();
22645                        meta[base + 7] = pack.put(&decay);
22646                        if let Some((kg, kb)) = &w.k_gate {
22647                            meta[base + 8] = pack.mat(&kg);
22648                            meta[base + 9] = pack.put(kb);
22649                        }
22650                        if let Some(conv) = &w.conv {
22651                            meta[base + 10] = pack.put(conv);
22652                            meta[base + 24] = (conv.len() / self.hidden_size) as u32;
22653                        } else {
22654                            meta[base + 24] = 0;
22655                        }
22656                    }
22657                    AttnKind::Full { wq, wk, wv, wo, .. } => {
22658                        full_seen = true;
22659                        meta[base + 11] = pack.mat(&wq);
22660                        meta[base + 12] = pack.mat(&wk);
22661                        meta[base + 13] = pack.mat(&wv);
22662                        meta[base + 14] = pack.mat(&wo);
22663                        meta[base + 26] = (li * kv_stride) as u32;
22664                    }
22665                    AttnKind::Bounded(w) => {
22666                        meta[base + 11] = pack.mat(&w.wq);
22667                        meta[base + 12] = pack.mat(&w.wk);
22668                        meta[base + 13] = pack.mat(&w.wv);
22669                        meta[base + 14] = pack.mat(&w.wo);
22670                        // Ring slot of this anchor (anchors only, packed).
22671                        meta[base + 26] = (bounded_seen * kv_stride) as u32;
22672                        meta[base + 27] = pack.put(&w.sink_k);
22673                        meta[base + 28] = pack.put(&w.sink_v);
22674                        bounded_seen += 1;
22675                    }
22676                    _ => return None,
22677                }
22678                match &lw.ffn {
22679                    FfnKind::Dense(d) => {
22680                        meta[base + 15] = 0;
22681                        meta[base + 16] = 0;
22682                        meta[base + 21] = pack.mat(&d.gate_proj);
22683                        meta[base + 22] = pack.mat(&d.up_proj);
22684                        meta[base + 23] = pack.mat(&d.down_proj);
22685                    }
22686                    FfnKind::Moe(m) => {
22687                        let r = m.resonance.as_ref().unwrap();
22688                        let (shared, _) = m.shared.as_ref().unwrap();
22689                        meta[base + 15] = 1;
22690                        meta[base + 16] = m.experts.len() as u32;
22691                        meta[base + 17] = pack.put(&r.mu);
22692                        meta[base + 18] = pack.put(&r.u);
22693                        meta[base + 19] = pack.put(&r.bias);
22694                        meta[base + 20] = r.k as u32;
22695                        // Word 30: the growth shell as the runtime applies
22696                        // it now (`+inf` on trunk rows, the stored finite
22697                        // shell on grown rows, all `+inf` under
22698                        // `CMF_GROWTH_SHELL=off`), followed by one `−∞`
22699                        // sentinel at index E the kernel writes as the
22700                        // score of an expert outside its shell — WGSL has
22701                        // no infinity literal, so the value travels as
22702                        // data (`embryo_core_route_finalize`).
22703                        let mut shell = r.effective_shell(m.experts.len());
22704                        shell.push(f32::NEG_INFINITY);
22705                        meta[base + 30] = pack.put(&shell);
22706                        meta[base + 21] = pack.mat(&shared.gate_proj);
22707                        meta[base + 22] = pack.mat(&shared.up_proj);
22708                        meta[base + 23] = pack.mat(&shared.down_proj);
22709                        for (e, ex) in m.experts.iter().enumerate() {
22710                            meta[base + 32 + e * 3] =
22711                                pack.mat(&ex.gate_proj);
22712                            meta[base + 33 + e * 3] =
22713                                pack.mat(&ex.up_proj);
22714                            meta[base + 34 + e * 3] =
22715                                pack.mat(&ex.down_proj);
22716                        }
22717                    }
22718                    FfnKind::DenseMoe(_) => return None,
22719                }
22720            }
22721            if !full_seen && self.num_layers == 0 {
22722                return None;
22723            }
22724            let mut lm_head = Vec::new();
22725            let mut lm_head_packed = Vec::new();
22726            if wide && q8 {
22727                let parts = self.weights.lm_head.q8_2f_codes();
22728                if let Some((q, rows, cols)) = parts {
22729                    lm_head_packed = q[..self.weights.lm_head.rows() * self.weights.lm_head.cols()].to_vec();
22730                    let (rs, cs) = (pack.put(rows), pack.put(cols));
22731                    meta[30] = pack.table_base + pack.table.len() as u32;
22732                    pack.table.extend_from_slice(&[0, rs, cs]);
22733                }
22734                meta.extend_from_slice(&pack.table);
22735            } else if wide {
22736                for v in Self::embryo_qtensor_f32(&self.weights.lm_head) {
22737                    let h = cortiq_core::quant::f32_to_f16(v);
22738                    pack.refused |= cortiq_core::quant::f16_to_f32(h).to_bits() != v.to_bits();
22739                    lm_head_packed.extend_from_slice(&h.to_le_bytes());
22740                }
22741            } else {
22742                lm_head = Self::embryo_qtensor_f32(&self.weights.lm_head);
22743            }
22744            if pack.refused {
22745                self.embryo_wide_refused = true;
22746                return self.ensure_embryo_graph();
22747            }
22748            let id = {
22749                static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
22750                NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
22751            };
22752            let model = crate::gpu::EmbryoGraphModel {
22753                id,
22754                hidden: self.hidden_size,
22755                intermediate: self.intermediate_size,
22756                vocab: self.vocab_size,
22757                layers: self.num_layers,
22758                phase_heads: vmf.map(|c| c.num_heads).unwrap_or(0),
22759                nphase: vmf.map(|c| c.nphase).unwrap_or(0),
22760                phase_dv: vmf.map(|c| c.value_head_dim).unwrap_or(0),
22761                anchor_q_heads: self.num_heads,
22762                anchor_kv_heads: self.num_kv_heads,
22763                anchor_head_dim: self.head_dim,
22764                rotary_dim: self.rotary_dim,
22765                rope_freq: if wide { self.inv_freq[..self.rotary_dim / 2].to_vec() } else { Vec::new() },
22766                max_seq: self.kv_cache.max_seq_len,
22767                cluster_count,
22768                cluster_size: self.vocab_size / cluster_count,
22769                phase_state_len: vmf.map(|c| c.state_len()).unwrap_or(0),
22770                state_stride,
22771                kv_stride,
22772                norm_gemma: matches!(self.norm_style, NormStyle::Gemma),
22773                phase_mass: vmf.map(|c| c.phase_mass).unwrap_or(0.0),
22774                weights: pack.data,
22775                meta,
22776                lm_head,
22777                wide,
22778                wide_q8: wide && q8,
22779                mats: pack.mats,
22780                lm_head_packed,
22781                clusters: clusters.as_ref().clone(),
22782                final_norm: self.weights.final_norm.clone(),
22783                inv_freq: self.inv_freq.as_ref().clone(),
22784                bounded: bounded.is_some(),
22785                kv_layers: if bounded.is_some() {
22786                    bounded_seen
22787                } else {
22788                    self.num_layers
22789                },
22790                state_layers: phase_seen + gdn_seen,
22791                anchor_window,
22792                anchor_sink,
22793                phase_layers: phase_seen,
22794                gdn_layers: gdn_seen,
22795                gdn_heads: gdn.map(|g| g.num_v_heads).unwrap_or(0),
22796                gdn_k_heads: gdn.map(|g| g.num_k_heads).unwrap_or(0),
22797                gdn_dk: gdn.map(|g| g.key_head_dim).unwrap_or(0),
22798                gdn_dv: gdn.map(|g| g.value_head_dim).unwrap_or(0),
22799                gdn_kk: gdn.map(|g| g.conv_kernel).unwrap_or(0),
22800            };
22801            self.embryo_graph = Some(std::sync::Arc::new(model));
22802        }
22803        self.embryo_graph.clone()
22804    }
22805
22806    fn forward_layers_span(
22807        &mut self,
22808        hidden: &[f32],
22809        position: usize,
22810        task_mask: Option<&TaskMask>,
22811        from: usize,
22812        upto: Option<usize>,
22813    ) -> Vec<f32> {
22814        #[cfg(target_os = "macos")]
22815        let _metal_pager_token_prof = crate::gpu_metal::MoePagerTokenScope::new(
22816            position,
22817            from,
22818            upto.map_or(self.num_layers, |u| u.saturating_add(1)),
22819        );
22820        debug_assert!(
22821            from == 0
22822                || (self.dsv4.is_none()
22823                    && self.dsv41.is_none()
22824                    && self.qwen4_exp.is_none()
22825                    && self.glm5_next.is_none()
22826                    && self.hy4.is_none()
22827                    && self.maxwell.is_none()
22828                    && self.inkling.is_none()
22829                    && !self.per_token_stack())
22830        );
22831        // Every plain forward — the whole-token Metal graph (`q1_graph_gpu`
22832        // wraps the GDN owners zero-copy and reallocates them on a size
22833        // change) and the CPU layer loop (reads/swaps `linear_state`) —
22834        // must see the previous speculative commit's asynchronous replay
22835        // complete. One mutex probe when nothing is pending.
22836        #[cfg(target_os = "macos")]
22837        if !crate::gpu_metal::wait_replay() {
22838            self.fail_metal_graph("the pending async replay failed before a plain forward");
22839            return vec![0.0; self.hidden_size];
22840        }
22841        if let Some(b) = &mut self.glm5_next {
22842            let _ = (task_mask, upto);
22843            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
22844            let mut logits = Vec::new();
22845            crate::glm5_next::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, position, self.pool.as_deref(), &mut logits, true);
22846            self.graph_logits = Some(logits);
22847            return vec![0.0; self.hidden_size];
22848        }
22849        if let Some(b) = &mut self.hy4 {
22850            let _ = (task_mask, upto);
22851            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
22852            let mut logits = Vec::new();
22853            crate::hy4::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, position, self.pool.as_deref(), &mut logits, true);
22854            self.graph_logits = Some(logits);
22855            return vec![0.0; self.hidden_size];
22856        }
22857        if let Some(b) = &mut self.maxwell {
22858            let _ = (task_mask, upto);
22859            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
22860            let mut logits = Vec::new();
22861            crate::maxwell::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, position, self.pool.as_deref(), &mut logits, true);
22862            self.graph_logits = Some(logits);
22863            return vec![0.0; self.hidden_size];
22864        }
22865        if let Some(b) = &mut self.inkling {
22866            let _ = (task_mask, upto);
22867            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
22868            let mut logits = Vec::new();
22869            crate::inkling::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, position, self.pool.as_deref(), &mut logits, true);
22870            self.graph_logits = Some(logits);
22871            return vec![0.0; self.hidden_size];
22872        }
22873        if let Some(b) = &mut self.qwen4_exp {
22874            let _ = (task_mask, upto);
22875            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
22876            let mut logits = Vec::new();
22877            crate::qwen4_exp::forward_token(
22878                &b.0,
22879                &b.1,
22880                &b.2,
22881                &mut b.3,
22882                token_id,
22883                position,
22884                &self.inv_freq,
22885                self.pool.as_deref(),
22886                &mut logits,
22887                true,
22888            );
22889            self.graph_logits = Some(logits);
22890            return vec![0.0; self.hidden_size];
22891        }
22892        // DeepSeek-V4 runs its own stack: the state is hc_mult copies, and
22893        // the forward returns LOGITS, not a hidden — the head is inside it
22894        // (the final fold sits between the last layer and the norm). The
22895        // token id rides in `hidden[0]`, written by embed_single, because
22896        // the hash layers route by id rather than by content.
22897        if let Some(b) = &mut self.dsv4 {
22898            let _ = (task_mask, upto);
22899            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
22900            let (g, layers, cfg, st) = (&b.0, &b.1, b.2, &mut b.3);
22901            st.pos = position;
22902            let mut logits = Vec::new();
22903            crate::dsv4::forward_token(
22904                g,
22905                layers,
22906                &cfg,
22907                st,
22908                token_id,
22909                &self.inv_freq,
22910                self.pool.as_deref(),
22911                &mut logits,
22912            );
22913            self.graph_logits = Some(logits);
22914            self.dspark_probe(position, token_id);
22915            // The caller expects a hidden; the logits went out of band, as
22916            // with the fused lm_head path.
22917            return vec![0.0; self.hidden_size];
22918        }
22919        // Dory owns its complete stack and emits logits out of band.
22920        if self.dory.is_some() {
22921            let _ = (task_mask, upto);
22922            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
22923            let lg = self.dory_forward(&[token_id], position, crate::dory::Want::Last);
22924            self.graph_logits = Some(lg);
22925            return vec![0.0; self.hidden_size];
22926        }
22927        // DeepSeek-V4.1 owns its complete stack and emits logits out of band.
22928        if let Some(b) = &mut self.dsv41 {
22929            let _ = (task_mask, upto);
22930            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
22931            let mut logits = Vec::new();
22932            crate::dsv41::forward_token(
22933                &b.0,
22934                &b.1,
22935                &b.2,
22936                &mut b.3,
22937                token_id,
22938                position,
22939                self.pool.as_deref(),
22940                &mut logits,
22941            );
22942            self.graph_logits = Some(logits);
22943            return vec![0.0; self.hidden_size];
22944        }
22945        // Gemma-3n runs its own stack (4 AltUp replicas don't fit this
22946        // loop); `hidden` is the extended embedding from embed_single.
22947        // Gemma-4 E-series: same hand-off — its dual-geometry attention
22948        // with shared-KV tail layers and the PLE injection live in
22949        // `g4e_forward`.
22950        if let Some(b) = &self.g4e {
22951            let _ = (task_mask, upto);
22952            return crate::g4e::g4e_forward(
22953                &b.0,
22954                &b.1,
22955                hidden,
22956                position,
22957                &mut self.kv_cache.layers,
22958                self.num_heads,
22959                self.num_kv_heads,
22960                self.pool.as_deref(),
22961            );
22962        }
22963        if let Some(b) = &self.g3n {
22964            let _ = (task_mask, upto);
22965            return crate::g3n::g3n_forward(
22966                &b.0,
22967                &b.1,
22968                hidden,
22969                position,
22970                &mut self.kv_cache.layers,
22971                self.num_heads,
22972                self.num_kv_heads,
22973                self.head_dim,
22974                self.pool.as_deref(),
22975            );
22976        }
22977        // Cortiq Embryo owns a separate resident graph: phase recurrent
22978        // state, resonance routing, the GQA anchor KV and hierarchical head
22979        // all execute in one Vulkan submit. It is limited to a complete
22980        // unmasked stack; spans and task masks retain the exact host path.
22981        // `CMF_EMBRYO_DBG=1` names the gate that keeps a token off the
22982        // resident graph — every refusal below is otherwise silent.
22983        if from == 0
22984            && upto.is_none()
22985            && task_mask.is_none()
22986            && self.anchor_core.is_some()
22987            && std::env::var("CMF_EMBRYO_DBG").as_deref() == Ok("1")
22988        {
22989            static ONCE: std::sync::Once = std::sync::Once::new();
22990            ONCE.call_once(|| {
22991                eprintln!(
22992                    "embryo-dbg: graph_on decode={} prefill={} resident_env={:?} enabled_here={} \
22993                     unsupported={} eligible={}",
22994                    crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode),
22995                    crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill),
22996                    std::env::var("CMF_EMBRYO_RESIDENT").ok(),
22997                    crate::gpu::enabled_here(),
22998                    self.graph_refused(),
22999                    self.embryo_resident_eligible(),
23000                );
23001            });
23002        }
23003        if from == 0
23004            && upto.is_none()
23005            && task_mask.is_none()
23006            // Embryo's recurrent/KV state has no host import path.  Do not
23007            // seed it for a prefill-only graph and then silently decode from
23008            // an empty CPU cache; both phases must select the resident owner.
23009            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)
23010            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill)
23011            // This whole-token Embryo path remains explicitly opt-in.
23012            // `CMF_GPU_WGPU_GRAPH=1` still enables the mature generic graph,
23013            // but must not silently select this model-specific resident path.
23014            && matches!(
23015                std::env::var("CMF_EMBRYO_RESIDENT").as_deref(),
23016                Ok("1") | Ok("parallel")
23017            )
23018            && crate::gpu::enabled_here()
23019            && !self.graph_refused()
23020            // Sequence owner: past position zero the device continues only
23021            // a sequence it holds. A host-owned sequence (the graph refused
23022            // at its start, or its prefix was prefilled on the host) keeps
23023            // the host path to its end — never a device attempt at p > 0
23024            // over an empty device image.
23025            && (position == 0 || self.device_sequence_position().is_some())
23026            && self.embryo_resident_eligible()
23027            && let Some(model) = self.ensure_embryo_graph()
23028        {
23029            let mut lg = Vec::new();
23030            if crate::gpu::forward_embryo_graph(&model, self.graph_kv_id, hidden, position, &mut lg)
23031            {
23032                self.graph_logits = Some(lg);
23033                return vec![0.0; self.hidden_size];
23034            }
23035            if std::env::var("CMF_EMBRYO_DBG").as_deref() == Ok("1") {
23036                eprintln!("embryo-dbg: forward_embryo_graph refused at position {position}");
23037            }
23038            // The refusal is THIS pipeline's: falling through once is safe
23039            // at position zero (the host owns the sequence from here),
23040            // while a refusal at a later position of a device-owned
23041            // sequence would mix a host KV/state path with a partial
23042            // device sequence.
23043            self.mark_graph_refused();
23044            if position != 0 {
23045                // Fail this sequence alone and leave nothing stale behind:
23046                // no reuse key, no host or device state for the next
23047                // request on this slot to "extend".
23048                self.kv_cache.clear();
23049                self.clear_history();
23050                crate::gpu::graph_kv_reset(self.graph_kv_id);
23051                panic!(
23052                    "resident Embryo graph refused at position {position}; refusing an in-flight host fallback"
23053                );
23054            }
23055        }
23056        let mut h = hidden.to_vec();
23057        // Ripple's value residual reads this position's embedding row in every layer.
23058        // A later span of the same position (a stack split across cards)
23059        // keeps the row its first span stored.
23060        if self.value_blend.is_some() {
23061            if from == 0 {
23062                self.vres_e0.clear();
23063                self.vres_e0.extend_from_slice(hidden);
23064            }
23065            assert!(
23066                self.vres_e0.len() == hidden.len(),
23067                "value residual: a layer span past the first layer has no embedding row"
23068            );
23069        }
23070        // MiMo-V2 expert placement: decided before the graph or the per-op
23071        // arena can claim the budget the expert bank needs.
23072        self.mimo_moe_prepare();
23073        let _mimo_q8 = self
23074            .mimo_moe
23075            .is_on()
23076            .then(crate::qtensor::enter_full_gpu_q8_scope);
23077        // Split borrows: copy scalars / clone handles so the per-layer
23078        // cfg does not hold `&self` while the KV cache is `&mut`.
23079        let (nh, _nkv, _hd, hs, _rd, eps) = (
23080            self.num_heads,
23081            self.num_kv_heads,
23082            self.head_dim,
23083            self.hidden_size,
23084            self.rotary_dim,
23085            self.rms_eps,
23086        );
23087        let pool = self.pool.clone();
23088        // Opt-in wgpu token-graph attention (discrete Vulkan/DX12): the whole
23089        // attention sub-block runs resident in one submit. Off by default.
23090        // Whole-token wgpu graph: eligibility + arbitration.
23091        //  - explicit CMF_GPU_WGPU_GRAPH forces it on/off;
23092        //  - discrete adapters (4090: decode 76 -> 137 tok/s) and GDN
23093        //    hybrids (recurrent state device-resident, no CPU twin to
23094        //    race) TRUST it;
23095        //  - integrated/mobile adapters RACE it against the normal path
23096        //    at generation granularity (gpu::graph_race_*) — tiled
23097        //    mobile GPUs can turn the ~300-dispatch graph into seconds
23098        //    per token, while a fast phone GPU keeps its win.
23099        let graph_env = std::env::var("CMF_GPU_WGPU_GRAPH").ok();
23100        let graph_on = match graph_env.as_deref() {
23101            Some("0") => false,
23102            Some("prefill") => false, // decode keeps the per-op path
23103            Some(_) => true,
23104            // Unset: same discrete-only default as every other graph
23105            // site. "Is the GPU on" used to stand in here — which made
23106            // the 0.2 tok/s whole-token graph race-eligible on mobile
23107            // adapters and cost 12-14× on first tokens (cmfmobile
23108            // TUNING.md); integrated GPUs keep the per-op probe path.
23109            None => crate::gpu::wgpu_graph_default(),
23110        };
23111        let graph_trusted =
23112            graph_env.is_some() || crate::gpu::wgpu_graph_default() || self.gdn_cfg.is_some();
23113        let race_eligible =
23114            graph_on && upto.is_none() && task_mask.is_none() && from == 0 && !self.graph_refused();
23115        let mut tail_start = 0usize;
23116        if race_eligible && crate::gpu::graph_race_use_graph(graph_trusted) {
23117            let t_graph = std::time::Instant::now();
23118            let mut lg = Vec::new();
23119            let mut gl = 0usize;
23120            let built = self.try_token_graph_wgpu(hidden, position, &mut lg, &mut gl);
23121            let declined = built.is_none();
23122            let built = match built {
23123                Some(Ok(hh)) => Some(hh),
23124                Some(Err(())) => {
23125                    // O(1) state was admitted before the device failure; the
23126                    // CPU mirrors are stale by construction.  Clear the whole
23127                    // sequence and stop rather than walking that stale state.
23128                    self.clear_sequence_state();
23129                    self.graph_failed
23130                        .store(true, std::sync::atomic::Ordering::Relaxed);
23131                    self.cancel
23132                        .store(true, std::sync::atomic::Ordering::Relaxed);
23133                    tracing::error!("token graph failed after admission; sequence state cleared");
23134                    return vec![0.0; self.hidden_size];
23135                }
23136                None => None,
23137            };
23138            // Past the transient guards (o1 still collecting, a softcap)
23139            // a refusal is about the weights and will never change —
23140            // remember it instead of walking every layer again next
23141            // token.
23142            if declined && !self.o1_active() && self.attn_softcap == 0.0 {
23143                self.mark_graph_refused();
23144            }
23145            graph_note(built.is_some(), gl, self.num_layers);
23146            if let Some(hh) = built {
23147                let dur = t_graph.elapsed();
23148                if std::env::var("CMF_GRAPH_PROF").is_ok() {
23149                    eprintln!("graph-call: {:.2} ms total", dur.as_secs_f64() * 1000.0);
23150                }
23151                if gl > 0 && gl < self.num_layers {
23152                    // Device prefix: the graph ran layers 0..gl and handed
23153                    // back the boundary hidden — the loop below owns the
23154                    // tail. The prefix layers' KV/state advanced on the
23155                    // device; the tail's advances on the host below. One
23156                    // boundary crossing per token.
23157                    h = hh;
23158                    tail_start = gl;
23159                    self.absorb_phi_tap(0..gl);
23160                } else if graph_trusted || !crate::gpu::graph_race_first_token_hopeless(dur) {
23161                    if !graph_trusted {
23162                        crate::gpu::graph_race_record(true, dur);
23163                    }
23164                    self.absorb_phi_tap(0..self.num_layers);
23165                    if !lg.is_empty() {
23166                        // Graph produced logits (final-norm + lm_head folded in) —
23167                        // pad/cap to vocab and hand them to the sampler directly.
23168                        lg.resize(self.vocab_size, 0.0);
23169                        if let Some(c) = self.final_softcap {
23170                            softcap_in_place(&mut lg, c, self.pool.as_deref());
23171                        }
23172                        self.graph_logits = Some(lg);
23173                    }
23174                    return hh;
23175                }
23176                // Hopeless first graph token: discard it and fall through
23177                // to the normal path. Safe exactly here — the prompt KV is
23178                // still CPU-owned (chunked prefill), so recomputing this
23179                // position is exact; the mirror's extra row is never read
23180                // (the race just settled on the normal path).
23181            }
23182        }
23183        // KIMI-LINEAR HAS NO SPLIT BUG. The 2.6× reported from the
23184        // model rotation (12.2 tok/s on one card against 4.6 on two)
23185        // was a single measurement of a model whose arm arbitration is
23186        // borderline, and it did not survive repetition. Three runs an
23187        // arm, same binary, back to back:
23188        //   probe on : 1 GPU 9.5 / 5.7 / 5.9   2 GPU 7.8 / 13.0 / 13.3
23189        //   pinned   : 1 GPU 5.6 / 5.3 / 5.2   2 GPU 3.5 / 4.2 / 3.4
23190        // With the arms pinned the split costs about 1.45×, which is
23191        // what a layer split costs. With the probe free, TWO CARDS RUN
23192        // FASTER — because for this model the CPU arm wins some op
23193        // classes and the probe finds that.
23194        //
23195        // Two things do stand, and both are measured. The token graph
23196        // builds NOTHING here (`covered 0 of 14 layers [0..14)`), so
23197        // every layer walks per-op on either arm — that is where the
23198        // headroom is, not in the split. And this model's benchmark is
23199        // unusable without `CMF_GPU_PROBE=0`: the arbitration alone
23200        // moves it by more than 2×.
23201        //
23202        // Span runs (network split): the graph covers exactly [from..=upto]
23203        // — one submit per SEGMENT per token. No race: its state is global
23204        // and calibrated on full stacks, so spans take the graph only where
23205        // it is trusted by default (discrete adapters / CMF_GPU_WGPU_GRAPH).
23206        let span = from > 0 || upto.is_some();
23207        if span && graph_on && task_mask.is_none() && graph_trusted {
23208            let upto_excl = upto.map_or(self.num_layers, |u| u + 1);
23209            let mut lg = Vec::new();
23210            let mut gl = 0usize;
23211            let span_res =
23212                self.try_token_graph_wgpu_span(hidden, position, &mut lg, from, upto_excl, &mut gl);
23213            let span_res = match span_res {
23214                Some(Ok(hh)) => Some(hh),
23215                Some(Err(())) => {
23216                    self.clear_sequence_state();
23217                    self.graph_failed
23218                        .store(true, std::sync::atomic::Ordering::Relaxed);
23219                    self.cancel
23220                        .store(true, std::sync::atomic::Ordering::Relaxed);
23221                    tracing::error!(
23222                        "span token graph failed after admission; sequence state cleared"
23223                    );
23224                    return vec![0.0; self.hidden_size];
23225                }
23226                None => None,
23227            };
23228            graph_note(span_res.is_some(), gl, upto_excl - from);
23229            if std::env::var("CMF_GPU_DEBUG").is_ok() {
23230                // How much of the span the graph actually covered. A
23231                // prefix of nothing means every layer walks per-op and
23232                // the split's extra cost is elsewhere.
23233                static SEEN: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
23234                if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 {
23235                    eprintln!(
23236                        "span graph: covered {gl} of {} layers [{from}..{upto_excl}) res={}",
23237                        upto_excl - from,
23238                        span_res.is_some()
23239                    );
23240                }
23241            }
23242            if let Some(hh) = span_res {
23243                self.absorb_phi_tap(from..from + gl);
23244                if gl == upto_excl - from {
23245                    if !lg.is_empty() {
23246                        lg.resize(self.vocab_size, 0.0);
23247                        if let Some(c) = self.final_softcap {
23248                            softcap_in_place(&mut lg, c, self.pool.as_deref());
23249                        }
23250                        self.graph_logits = Some(lg);
23251                    }
23252                    crate::gpu::set_layer(-1);
23253                    return hh;
23254                }
23255                // Partial device prefix of the span: CPU owns the tail.
23256                h = hh;
23257                tail_start = from + gl;
23258            }
23259        }
23260        // Layers the host is about to run whose device mirror moved ahead
23261        // of the host cache (a device prefix that shrank since the prompt,
23262        // a batched-prefill prefix longer than this token's): bring their
23263        // rows over first. One comparison per layer when nothing lags.
23264        let t_race_cpu = (race_eligible && !graph_trusted).then(std::time::Instant::now);
23265
23266        // A partial graph is an explicit GPU-prefix / CPU-tail split. Keep
23267        // the tail PURE host-side: letting its QTensor hooks re-enter the
23268        // residency arena streams every omitted layer through Vulkan and the
23269        // driver's freed-allocation cache can grow to the full model size
23270        // (25.4 GiB observed with a 14 GiB budget on Granite 30B Q8_2F).
23271        // With a MiMo expert bank the tail is not a whole-layer host
23272        // stream: its experts run from the bank (never the arena) and its
23273        // projections stay per-op on the device, which the bank's placement
23274        // left room for.
23275        let host_tail = tail_start > from;
23276        let _host_tail = (host_tail && !self.mimo_moe.is_on()).then(crate::gpu::enter_cpu_scope);
23277        let automatic_gpu_prefix = self.automatic_gpu_prefix();
23278
23279        let _prof_layers = crate::cpuprof::time(crate::cpuprof::Slot::Layers);
23280        #[cfg(target_os = "macos")]
23281        let mut gpu_skip_until = 0usize;
23282        for li in tail_start.max(from)..self.num_layers {
23283            let _capacity_tail = automatic_gpu_prefix
23284                .filter(|&prefix| li >= prefix && !self.mimo_moe.is_dynamic(li, host_tail))
23285                .map(|_| crate::gpu::enter_cpu_scope());
23286            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU (CMF_GPU_LAYERS)
23287            if let Some(u) = upto {
23288                if li > u {
23289                    break;
23290                }
23291            }
23292            if let Some(mask) = task_mask {
23293                if !mask.layer_alive(li) {
23294                    continue; // dead layer: residual pass-through
23295                }
23296            }
23297            // MiniMax's dynamic tail: attention + pooled MoE of this layer as
23298            // ONE device frame (single-layer graph call), cold experts on
23299            // the host. Any decline falls through to the ordinary host
23300            // layer; a post-admission device failure stops the sequence.
23301            if host_tail && task_mask.is_none() {
23302                match self.m3_pooled_layer(li, position, &mut h) {
23303                    Ok(true) => {
23304                        crate::gpu::set_layer(-1);
23305                        continue;
23306                    }
23307                    Ok(false) => {}
23308                    Err(()) => {
23309                        self.clear_sequence_state();
23310                        self.graph_failed
23311                            .store(true, std::sync::atomic::Ordering::Relaxed);
23312                        self.cancel
23313                            .store(true, std::sync::atomic::Ordering::Relaxed);
23314                        tracing::error!(
23315                            "pooled tail token graph failed after admission; sequence state cleared"
23316                        );
23317                        return vec![0.0; self.hidden_size];
23318                    }
23319                }
23320            }
23321            // Whole-block q1 token graph: a run of consecutive q1
23322            // layers — GDN and full attention — executes with one sync
23323            // per CPU attend instead of per op (macOS/Metal).
23324            #[cfg(target_os = "macos")]
23325            {
23326                if li < gpu_skip_until {
23327                    continue;
23328                }
23329                if task_mask.is_none() {
23330                    let end = self.q1_graph_gpu(li, upto, position, &mut h);
23331                    if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
23332                        // The graph may have mutated device state before a
23333                        // command-buffer error. Never continue with a CPU
23334                        // tail or read a stale host mirror after admission.
23335                        return vec![0.0; self.hidden_size];
23336                    }
23337                    if end > li {
23338                        gpu_skip_until = end;
23339                        // Looped Transformer: the graph stopped at a loop
23340                        // boundary — apply final norm before the next iteration.
23341                        if self.is_loop_end(end - 1) && end < self.num_layers {
23342                            h = inference::rms_norm(
23343                                &h,
23344                                &self.weights.final_norm,
23345                                self.rms_eps,
23346                                self.norm_style,
23347                            );
23348                        }
23349                        continue;
23350                    }
23351                }
23352            }
23353
23354            if task_mask.is_none() {
23355                match self.mimo_graph_layer_rows(li, &mut h, &[position]) {
23356                    crate::gpu::BatchGraphOutcome::Completed => continue,
23357                    crate::gpu::BatchGraphOutcome::Failed => return vec![0.0; self.hidden_size],
23358                    crate::gpu::BatchGraphOutcome::Declined => {}
23359                }
23360            }
23361            #[cfg(feature = "gpu")]
23362            self.pull_lagging_host_kv(li, li + 1, position);
23363            // SenseNova-Loop mHC: the attention reads the routed branch of
23364            // the streams.
23365            let mhc_attn = self.mhc_layer(li).then(|| self.mhc_pre(li, false, &mut h));
23366            let lw = &self.weights.layers[self.phys_layer(li)];
23367            if let Ok(tp) = std::env::var("CMF_TRACE_POS") {
23368                if tp.parse::<usize>().ok() == Some(position) {
23369                    let n: f32 = h.iter().map(|x| x * x).sum::<f32>().sqrt();
23370                    eprintln!(
23371                        "TRACE pos {position} layer {li}: |h| = {n:.6} h0 {:.6} h1 {:.6}",
23372                        h[0], h[1]
23373                    );
23374                }
23375            }
23376            // Norm into the pipeline scratch — the returning rms_norm
23377            // allocated twice per layer per token (roadmap §3 P0).
23378            let prof = crate::cpuprof::time(crate::cpuprof::Slot::Norms);
23379            inference::rms_norm_into(
23380                &h,
23381                &lw.input_norm,
23382                self.rms_eps,
23383                self.norm_style,
23384                &mut self.ws.n1,
23385            );
23386            drop(prof);
23387            // The row V projects, when the layer blends the embedding into it.
23388            let vres = match self.layer_value_blend(li) {
23389                Some(blend) => {
23390                    vres_lerp(&self.vres_e0, &self.ws.n1, blend, &mut self.vres_in);
23391                    true
23392                }
23393                None => false,
23394            };
23395
23396            let attn_out = match &lw.attn {
23397                AttnKind::Mla(w) => {
23398                    let inv_freq_l = self.layer_inv_freq(li);
23399                    let rs = self.layer_rope_scale(li);
23400                    let eps = self.rms_eps;
23401                    let pool = self.pool.clone();
23402                    mla_attention(
23403                        w,
23404                        &self.ws.n1,
23405                        &mut self.kv_cache.layers[li],
23406                        position,
23407                        &inv_freq_l,
23408                        rs,
23409                        eps,
23410                        pool.as_deref(),
23411                    )
23412                }
23413                AttnKind::Linear(w) => {
23414                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
23415                    vmf_phase_forward(
23416                        &self.ws.n1,
23417                        w,
23418                        &cfg,
23419                        &mut self.kv_cache.layers[li].linear_state,
23420                        self.pool.as_deref(),
23421                    )
23422                }
23423                AttnKind::Kda(w) => {
23424                    let cfg = self.kda_cfg.expect("kda layer without kda_cfg");
23425                    crate::linear_core::kda_forward(
23426                        &self.ws.n1,
23427                        w,
23428                        &cfg,
23429                        &mut self.kv_cache.layers[li].linear_state,
23430                        self.pool.as_deref(),
23431                    )
23432                }
23433                AttnKind::LinearGdn(w) => {
23434                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
23435                    gdn_forward(
23436                        &self.ws.n1,
23437                        w,
23438                        &cfg,
23439                        &mut self.kv_cache.layers[li].linear_state,
23440                        self.pool.as_deref(),
23441                    )
23442                }
23443                AttnKind::ShortConv(w) => {
23444                    let cfg = self
23445                        .short_conv_cfg
23446                        .expect("short-conv layer without short_conv_cfg");
23447                    short_conv_forward(
23448                        &self.ws.n1,
23449                        w,
23450                        &cfg,
23451                        &mut self.kv_cache.layers[li].linear_state,
23452                        self.pool.as_deref(),
23453                    )
23454                }
23455                AttnKind::Bounded(w) => {
23456                    // Natively bounded anchor: insert into the ring, attend
23457                    // over sinks ∪ window. No position, nothing appended.
23458                    let rope = self
23459                        .bounded_rope
23460                        .clone()
23461                        .expect("bounded layer without an installed rotation table");
23462                    let cfg = crate::bounded::BoundedAttnCfg {
23463                        num_heads: self.num_heads,
23464                        num_kv_heads: self.num_kv_heads,
23465                        head_dim: self.head_dim,
23466                        hidden_size: hs,
23467                        scale: self.attn_scale,
23468                        rope: &rope,
23469                        pool: pool.as_deref(),
23470                    };
23471                    crate::bounded::bounded_attention(
23472                        &self.ws.n1,
23473                        w,
23474                        &mut self.kv_cache.layers[li],
23475                        &cfg,
23476                    )
23477                }
23478                AttnKind::Full { wq, wk, wv, wo, .. } if self.dash.is_some() => {
23479                    let (nh_l, hd_l) = (self.num_heads, self.head_dim);
23480                    let mut ao = vec![0f32; nh_l * hd_l];
23481                    let dash = self.dash.as_mut().expect("guarded");
23482                    crate::uocr::attention_host(
23483                        dash,
23484                        li,
23485                        &self.ws.n1,
23486                        wq,
23487                        wk,
23488                        wv,
23489                        &mut self.kv_cache.layers[li],
23490                        position,
23491                        nh_l,
23492                        hd_l,
23493                        self.rms_eps as f32,
23494                        pool.as_deref(),
23495                        &mut ao,
23496                    );
23497                    let mut out = vec![0f32; hs];
23498                    wo.matvec(&ao, &mut out, pool.as_deref());
23499                    out
23500                }
23501                AttnKind::Full {
23502                    wq,
23503                    wk,
23504                    wv,
23505                    wo,
23506                    q_norm,
23507                    k_norm,
23508                    output_gate,
23509                    softplus_gate,
23510                    bias,
23511                } if self.kv_cache.layers[li].o1_sealed() => {
23512                    // O(1) override: decode on the sealed Nyström state
23513                    // instead of the growing KV cache.
23514                    let inv_freq_l = self.layer_inv_freq(li);
23515                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
23516                    let cfg = QwenAttnCfg {
23517                        mrope: None,
23518                        num_heads: self.layer_num_heads(li),
23519                        num_kv_heads: nkv_l,
23520                        head_dim: hd_l,
23521                        hidden_size: hs,
23522                        position,
23523                        inv_freq: &inv_freq_l,
23524                        rotary_dim: rd_l,
23525                        scale: self.attn_scale,
23526                        softcap: self.attn_softcap,
23527                        window: None,
23528                        v_norm: self.attn_v_norm,
23529                        qk_norm_after_rope: self.qk_norm_after_rope,
23530                        gate_sigmoid: self.proj_gate_sigmoid,
23531                        q_norm: q_norm.as_deref(),
23532                        k_norm: k_norm.as_deref(),
23533                        output_gate: *output_gate,
23534                        softplus_gate: softplus_gate
23535                            .as_ref()
23536                            .map(|(gate, per_head)| (gate, *per_head)),
23537                        rope_scale: self.layer_rope_scale(li),
23538                        bias: bias
23539                            .as_ref()
23540                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
23541                        rms_eps: eps,
23542                        norm_style: self.norm_style,
23543                        pool: pool.as_deref(),
23544                        v_head_dim: self.layer_v_dim(li),
23545                        value_in: vres.then(|| self.vres_in.as_slice()),
23546                    };
23547                    attention::qwen_attention_nystrom(
23548                        &self.ws.n1,
23549                        wq,
23550                        wk,
23551                        wv,
23552                        wo,
23553                        &mut self.kv_cache.layers[li],
23554                        &cfg,
23555                    )
23556                }
23557                AttnKind::Full {
23558                    wq,
23559                    wk,
23560                    wv,
23561                    wo,
23562                    q_norm,
23563                    k_norm,
23564                    output_gate,
23565                    softplus_gate,
23566                    bias,
23567                } => 'attn: {
23568                    // wgpu token-graph attention (opt-in): whole sub-block in
23569                    // one submit, device K/V mirror. q1 only, no gate/bias/mask.
23570                    // Its kernel has no window, sink or narrow-V slot and
23571                    // one mirror geometry: such models stay on the CPU attend.
23572                    let dropin_reason =
23573                        graph_on.then(|| self.graph_attn_decline_reason()).flatten();
23574                    if let Some(reason) = dropin_reason {
23575                        self.note_graph_decline("wgpu attn dropin", reason);
23576                    }
23577                    if graph_on
23578                        && dropin_reason.is_none()
23579                        && !*output_gate
23580                        && softplus_gate.is_none()
23581                        && self.attention_heads_per_layer.is_none()
23582                        && bias.is_none()
23583                        && task_mask.is_none()
23584                    {
23585                        let inv_freq_l = self.layer_inv_freq(li);
23586                        let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
23587                        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
23588                        if let (Some((gm, qi)), Some((_, ki)), Some((_, vi)), Some((_, oi))) = (
23589                            wq.mapped_q1(),
23590                            wk.mapped_q1(),
23591                            wv.mapped_q1(),
23592                            wo.mapped_q1(),
23593                        ) {
23594                            let gm = gm.clone();
23595                            let mut out = vec![0f32; hs];
23596                            let cache = &self.kv_cache.layers[li];
23597                            if crate::gpu::attn_dropin(
23598                                &gm,
23599                                self.graph_kv_id,
23600                                li,
23601                                &self.ws.n1,
23602                                qi,
23603                                ki,
23604                                vi,
23605                                oi,
23606                                q_norm.as_deref(),
23607                                k_norm.as_deref(),
23608                                self.qk_norm_after_rope,
23609                                &inv_freq_l,
23610                                nh,
23611                                nkv_l,
23612                                hd_l,
23613                                rd_l,
23614                                hs,
23615                                position,
23616                                self.kv_cache.max_seq_len,
23617                                gemma,
23618                                eps as f32,
23619                                cache.k_heads(),
23620                                cache.v_heads(),
23621                                &mut out,
23622                            ) {
23623                                break 'attn out;
23624                            }
23625                        }
23626                    }
23627                    let masked = task_mask
23628                        .map(|m| m.head_flags(li, self.num_heads).iter().any(|&a| !a))
23629                        .unwrap_or(false);
23630                    let f32_view = (wq.as_f32(), wk.as_f32(), wv.as_f32(), wo.as_f32());
23631                    // The masked kernel knows one pipeline-wide geometry and
23632                    // RoPE table, no window and no sink.
23633                    let plain = self.layer_attn_plain(li);
23634                    match (masked, f32_view) {
23635                        // Historical masked path (f32 slices; the loader
23636                        // keeps masked models in f32).
23637                        (true, (Some(q), Some(k), Some(v), Some(o))) if plain => {
23638                            let active_heads = task_mask.unwrap().head_flags(li, self.num_heads);
23639                            attention::multi_head_attention(
23640                                &self.ws.n1,
23641                                q,
23642                                k,
23643                                v,
23644                                o,
23645                                &mut self.kv_cache.layers[li],
23646                                self.num_heads,
23647                                self.num_kv_heads,
23648                                self.head_dim,
23649                                self.hidden_size,
23650                                position,
23651                                &active_heads,
23652                                &self.inv_freq,
23653                            )
23654                        }
23655                        (masked, _) => {
23656                            if masked {
23657                                tracing::warn!(
23658                                    "layer {li}: head mask on quantized weights or on a \
23659                                     window/sink/per-layer-geometry layer not supported \
23660                                     yet — executing dense"
23661                                );
23662                            }
23663                            let inv_freq_l = self.layer_inv_freq(li);
23664                            let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
23665                            let cfg = QwenAttnCfg {
23666                                mrope: self.prompt_mrope.as_deref().zip(self.mrope_sections).map(|(pos, sections)| attention::MropeView { base: 0, pos, sections }),
23667                                num_heads: self.layer_num_heads(li),
23668                                num_kv_heads: nkv_l,
23669                                head_dim: hd_l,
23670                                hidden_size: hs,
23671                                position,
23672                                inv_freq: &inv_freq_l,
23673                                rotary_dim: rd_l,
23674                                scale: self.attn_scale,
23675                                softcap: self.attn_softcap,
23676                                window: self.layer_window(li),
23677                                v_norm: self.attn_v_norm,
23678                                qk_norm_after_rope: self.qk_norm_after_rope,
23679                                gate_sigmoid: self.proj_gate_sigmoid,
23680                                q_norm: q_norm.as_deref(),
23681                                k_norm: k_norm.as_deref(),
23682                                output_gate: *output_gate,
23683                                softplus_gate: softplus_gate
23684                                    .as_ref()
23685                                    .map(|(gate, per_head)| (gate, *per_head)),
23686                                rope_scale: self.layer_rope_scale(li),
23687                                bias: bias
23688                                    .as_ref()
23689                                    .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
23690                                rms_eps: eps,
23691                                norm_style: self.norm_style,
23692                                pool: pool.as_deref(),
23693                                v_head_dim: self.layer_v_dim(li),
23694                                value_in: vres.then(|| self.vres_in.as_slice()),
23695                            };
23696                            attention::qwen_attention(
23697                                &self.ws.n1,
23698                                wq,
23699                                wk,
23700                                wv,
23701                                wo,
23702                                &mut self.kv_cache.layers[li],
23703                                &cfg,
23704                            )
23705                        }
23706                    }
23707                }
23708            };
23709            // Gemma sandwich norm: normalize the attention branch before
23710            // it joins the residual stream.
23711            let attn_out = match &self.weights.layers[self.phys_layer(li)].attn_out_norm {
23712                Some(w) => inference::rms_norm(&attn_out, w, self.rms_eps, self.norm_style),
23713                None => attn_out,
23714            };
23715            let mhc_ffn = match mhc_attn {
23716                Some(c) => {
23717                    // mHC: fold the attention output in, route the FFN's
23718                    // branch, and norm that.
23719                    self.mhc_post(li, false, &attn_out, &c, &mut h);
23720                    let cf = self.mhc_pre(li, true, &mut h);
23721                    let lw = &self.weights.layers[self.phys_layer(li)];
23722                    inference::rms_norm_into(&h, &lw.post_norm, self.rms_eps, self.norm_style, &mut self.ws.p1);
23723                    Some(cf)
23724                }
23725                None => {
23726                    let lw = &self.weights.layers[self.phys_layer(li)];
23727                    let prof = crate::cpuprof::time(crate::cpuprof::Slot::Norms);
23728                    inference::add_rmsnorm_fused_into(
23729                        &mut h,
23730                        &attn_out,
23731                        &lw.post_norm,
23732                        self.rms_eps,
23733                        self.norm_style,
23734                        &mut self.ws.p1,
23735                    );
23736                    drop(prof);
23737                    None
23738                }
23739            };
23740            let lw = &self.weights.layers[self.phys_layer(li)];
23741            let mut attn_out = attn_out;
23742            attention::recycle_buf(&mut attn_out);
23743            let post_normed = &self.ws.p1;
23744
23745            let ffn_masked = task_mask
23746                .map(|m| m.ffn_active_count(li) < self.intermediate_size)
23747                .unwrap_or(false);
23748            // One masked dense CONTRACT, dispatched by cost. The
23749            // activation-zeroing arm (the batched sweep's, validated
23750            // against the replica to 0.8%) computes the FULL fused FFN
23751            // and zeroes the dead — right whenever most neurons live.
23752            // The sparse arm reads ONLY active rows and down columns —
23753            // per-row dots are slower per element than the fused kernel,
23754            // so it pays only once the mask is deep enough. The 0.5
23755            // crossover is first-principles (fused kernels run ~2x the
23756            // per-row dot throughput); a shallow specialist (95% alive)
23757            // stays fused, a --target-sparsity bake flips arms on its
23758            // own weight.
23759            let ffn_out = match (ffn_masked, &lw.ffn) {
23760                // A defragged tube layer answers its own mask: the core
23761                // always runs, each tube runs when its bit is on, and
23762                // the tubes that are off are never read from the mmap.
23763                (_, FfnKind::Dense(d)) if !d.segs.is_empty() => {
23764                    let row = task_mask
23765                        .and_then(|tm| tm.ffn_masks.get(li))
23766                        .map(|v| v.as_slice());
23767                    tube_ffn(d, post_normed, 1, self.pool.as_deref(), row)
23768                }
23769                (true, FfnKind::Dense(d)) => {
23770                    let tm = task_mask.unwrap();
23771                    let alive = tm.ffn_active_count(li);
23772                    let deep = alive * 2 <= self.intermediate_size;
23773                    if deep && d.down_proj.sparse_col_ok() && !d.gate_proj.has_prism_contract() {
23774                        let active = tm.ffn_active_indices(li);
23775                        sparse_ffn_quant(
23776                            d,
23777                            post_normed,
23778                            &active,
23779                            self.hidden_size,
23780                            self.pool.as_deref(),
23781                        )
23782                    } else if deep
23783                        && let (Some(g), Some(u), Some(dn)) = (
23784                            d.gate_proj.as_f32(),
23785                            d.up_proj.as_f32(),
23786                            d.down_proj.as_f32(),
23787                        )
23788                    {
23789                        let active = tm.ffn_active_indices(li);
23790                        inference::sparse_ffn_forward(
23791                            post_normed,
23792                            g,
23793                            u,
23794                            dn,
23795                            self.hidden_size,
23796                            self.intermediate_size,
23797                            &active,
23798                            self.pool.as_deref(),
23799                        )
23800                    } else {
23801                        let row = tm.ffn_masks.get(li).map(|v| v.as_slice());
23802                        dense_ffn_batch(d, post_normed, 1, self.pool.as_deref(), row)
23803                    }
23804                }
23805                (true, FfnKind::Moe(m)) => {
23806                    // MoE is sparse by expert selection; a task mask
23807                    // narrows the ROUTABLE set via its expert fields
23808                    // (spec §5) when it carries them.
23809                    let allowed = task_mask.and_then(|tm| tm.expert_flags(li, m.experts.len()));
23810                    ffn_forward(
23811                        &lw.ffn,
23812                        post_normed,
23813                        self.pool.as_deref(),
23814                        allowed.as_deref(),
23815                    )
23816                }
23817                (true, FfnKind::DenseMoe(dm)) => dense_moe_ffn(
23818                    dm,
23819                    post_normed,
23820                    &h,
23821                    self.rms_eps,
23822                    self.norm_style,
23823                    self.pool.as_deref(),
23824                ),
23825                (false, _) => match &lw.ffn {
23826                    FfnKind::DenseMoe(dm) => dense_moe_ffn(
23827                        dm,
23828                        post_normed,
23829                        &h,
23830                        self.rms_eps,
23831                        self.norm_style,
23832                        self.pool.as_deref(),
23833                    ),
23834                    FfnKind::Moe(m)
23835                        if task_mask.is_none()
23836                            && host_tail
23837                            && li >= tail_start
23838                            && crate::minicpm_tail::MiniCpmTail::is_requested_target(m) =>
23839                    {
23840                        moe_ffn_minicpm_tail(
23841                            &mut self.minicpm_tail,
23842                            li,
23843                            self.num_layers,
23844                            m,
23845                            post_normed,
23846                            self.pool.as_deref(),
23847                        )
23848                    }
23849                    FfnKind::Moe(m)
23850                        if task_mask.is_none() && self.mimo_moe.is_dynamic(li, host_tail) =>
23851                    {
23852                        moe_ffn_banked(&mut self.mimo_moe, li, m, post_normed, self.pool.as_deref())
23853                    }
23854                    _ => {
23855                        let allowed = match (&lw.ffn, task_mask) {
23856                            (FfnKind::Moe(m), Some(tm)) => tm.expert_flags(li, m.experts.len()),
23857                            _ => None,
23858                        };
23859                        ffn_forward(
23860                            &lw.ffn,
23861                            post_normed,
23862                            self.pool.as_deref(),
23863                            allowed.as_deref(),
23864                        )
23865                    }
23866                },
23867            };
23868            let ffn_out = match &self.weights.layers[self.phys_layer(li)].ffn_out_norm {
23869                Some(w) => inference::rms_norm(&ffn_out, w, self.rms_eps, self.norm_style),
23870                None => ffn_out,
23871            };
23872            match mhc_ffn {
23873                Some(c) => self.mhc_post(li, true, &ffn_out, &c, &mut h),
23874                None => {
23875                    for (i, &f) in ffn_out.iter().enumerate() {
23876                        h[i] += f;
23877                    }
23878                }
23879            }
23880            let mut ffn_out = ffn_out;
23881            attention::recycle_buf(&mut ffn_out);
23882
23883            // Gemma-4: the layer output is scaled by a learned scalar.
23884            if let Some(sc) = self.weights.layers[self.phys_layer(li)].layer_scale {
23885                for v in h.iter_mut() {
23886                    *v *= sc;
23887                }
23888            }
23889            // CMF_LAYER_DUMP: this position's hidden after layer li.
23890            if self.layer_dump.is_some() {
23891                self.dump_layer_row(position, li, &h);
23892            }
23893
23894            // Looped Transformer: apply final norm at the end of each loop iteration.
23895            // Nanbeige 4.2: after layer 21 (virtual), apply norm before looping back to layer 0.
23896            if self.is_loop_end(li) && li + 1 < self.num_layers {
23897                h = inference::rms_norm(
23898                    &h,
23899                    &self.weights.final_norm,
23900                    self.rms_eps,
23901                    self.norm_style,
23902                );
23903            }
23904
23905            // Dynamic routing φ capture (on-policy): the
23906            // EMA of the post-residual hidden at the router's phi_layer,
23907            // updated as the context evolves during decode.
23908            if self.dyn_phi_layer == Some(li) {
23909                self.update_dyn_phi(&h);
23910            }
23911        }
23912        crate::gpu::set_layer(-1); // layers done — lm_head outside layer-split
23913        if let Some(t) = t_race_cpu {
23914            crate::gpu::graph_race_record(false, t.elapsed());
23915        }
23916
23917        h
23918    }
23919
23920    /// Read `ids` (positions `0..len`) into a sequence the weights just
23921    /// changed under (`set_active_skill` cleared it): all but the last
23922    /// position through the prompt ingest (`prefill_rows`: the batch graph
23923    /// where it admits them, else the host's chunked prefill), the last as
23924    /// a decode step. Returns that step's post-stack hidden; logits the
23925    /// graph folded in are its own, never the old weights'. The router's φ
23926    /// does not take these rows — they are context it has already seen.
23927    fn reprefill_context(&mut self, ids: &[u32], task_mask: Option<&TaskMask>) -> Result<Vec<f32>, String> {
23928        let n = ids.len();
23929        if n == 0 {
23930            return Err("nothing to read".into());
23931        }
23932        let phi = self.dyn_phi_layer.take();
23933        self.graph_logits = None;
23934        let r = (|| {
23935            let chunk = self.prefill_chunk().max(1);
23936            // the device's own prompt path where generation takes it (the
23937            // batch graph, chunks of `generation_batch_k`), else the host's
23938            let batch_k = self.generation_batch_k();
23939            let mut graphed = batch_k > 1 && task_mask.is_none() && !self.o1_active() && self.graph_prefill_preferred();
23940            let mut pos = 0usize;
23941            while pos + 1 < n {
23942                if graphed {
23943                    let end = (pos + batch_k).min(n - 1);
23944                    let hs = self.hidden_size;
23945                    let mut hiddens = vec![0f32; (end - pos) * hs];
23946                    for (j, &id) in ids[pos..end].iter().enumerate() {
23947                        hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
23948                    }
23949                    let positions: Vec<usize> = (pos..end).collect();
23950                    match self.try_batch_graph_wgpu(&mut hiddens, &positions, end - pos, None) {
23951                        crate::gpu::BatchGraphOutcome::Completed => {
23952                            pos = end;
23953                            continue;
23954                        }
23955                        crate::gpu::BatchGraphOutcome::Failed => {
23956                            return Err(format!("the batch graph failed at position {pos}"));
23957                        }
23958                        crate::gpu::BatchGraphOutcome::Declined => graphed = false,
23959                    }
23960                }
23961                let end = (pos + chunk).min(n - 1);
23962                let _ = self.prefill_rows(&ids[pos..end], pos, task_mask)?;
23963                // a failed graph stays flagged for the caller's own check
23964                if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
23965                    return Err(format!("the device graph failed at position {pos}"));
23966                }
23967                pos = end;
23968            }
23969            Ok(self.forward_layers(&self.embed_single(ids[n - 1]), n - 1, task_mask))
23970        })();
23971        self.dyn_phi_layer = phi;
23972        r
23973    }
23974
23975    /// The file a graph layer's weights come from: the first of `ws` that is
23976    /// a mapped graph weight. A soft skill blend holds its working tensors
23977    /// in f32 (no file entry); on CUDA, whose hybrid arm keeps such a
23978    /// matrix on the card as int8 tiles, the pipeline's own file stands in.
23979    fn graph_model_of(&self, ws: &[&QTensor]) -> Option<std::sync::Arc<cortiq_core::CmfModel>> {
23980        if let Some(m) = ws.iter().find_map(|t| t.graph_weight_or_blr().map(|r| r.0.clone())) {
23981            return Some(m);
23982        }
23983        if self.dyn_blend_loaded && crate::gpu::cuda_active() {
23984            return self.model.clone();
23985        }
23986        None
23987    }
23988
23989    /// Fold the φ rows a device graph kept (`dyn_phi_tap`) into the EMA,
23990    /// in row order. `ran`: the layers the graph ran; a router layer outside
23991    /// them runs on the host, whose own hook takes it. A router layer the
23992    /// graph ran without keeping its row is a φ the router never sees —
23993    /// said once, never silent.
23994    fn absorb_phi_tap(&mut self, ran: std::ops::Range<usize>) {
23995        let Some(l) = self.dyn_phi_layer else {
23996            return;
23997        };
23998        let rows = self.dyn_phi_tap.get_mut().unwrap().take();
23999        match rows {
24000            Some(rows) => {
24001                let hs = self.hidden_size;
24002                for r in rows.chunks_exact(hs) {
24003                    self.update_dyn_phi(r);
24004                }
24005            }
24006            None if ran.contains(&l) => {
24007                static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
24008                if !SAID.swap(true, std::sync::atomic::Ordering::Relaxed) {
24009                    tracing::warn!(
24010                        "dynamic routing: the device graph ran the router's layer {l} without keeping its row — φ is not updated on this backend"
24011                    );
24012                }
24013            }
24014            None => {}
24015        }
24016    }
24017
24018    /// EMA of φ at the router layer (rolling, weight 0.2 = ~5-token
24019    /// horizon). First observation seeds it exactly.
24020    fn update_dyn_phi(&mut self, h: &[f32]) {
24021        const A: f32 = 0.2;
24022        if self.dyn_phi_ema.len() != h.len() {
24023            self.dyn_phi_ema = vec![0.0; h.len()];
24024            self.dyn_phi_seen = 0;
24025        }
24026        if self.dyn_phi_seen == 0 {
24027            self.dyn_phi_ema.copy_from_slice(h);
24028        } else {
24029            for (e, &v) in self.dyn_phi_ema.iter_mut().zip(h) {
24030                *e = (1.0 - A) * *e + A * v;
24031            }
24032        }
24033        self.dyn_phi_seen += 1;
24034    }
24035
24036    /// Current router φ (EMA at phi_layer); empty until first capture.
24037    pub fn dyn_phi(&self) -> &[f32] {
24038        &self.dyn_phi_ema
24039    }
24040
24041    /// Enable/disable φ capture at the router layer, reset the EMA.
24042    pub fn set_dyn_phi_layer(&mut self, layer: Option<usize>) {
24043        self.dyn_phi_layer = layer;
24044        self.dyn_phi_ema.clear();
24045        self.dyn_phi_seen = 0;
24046    }
24047
24048    /// Skills eligible for dynamic switching: (index, id, phi_layer).
24049    pub fn dynamic_skills(&self) -> Vec<(usize, String, usize)> {
24050        let Some(model) = &self.model else {
24051            return Vec::new();
24052        };
24053        model
24054            .header
24055            .skills
24056            .iter()
24057            .enumerate()
24058            .filter_map(|(i, sk)| {
24059                // A v2 record routes only through the request-level
24060                // backbone-gated decision (its status and gate are
24061                // checked there), never per token.
24062                if sk.is_v2() {
24063                    return None;
24064                }
24065                let ok = matches!(self.dyn_skill_layers.get(i), Some(Some(_)));
24066                let sel = sk.selection.as_ref()?;
24067                (ok).then(|| (i, sk.id.clone(), sel.phi_layer))
24068            })
24069            .collect()
24070    }
24071
24072    /// Index of the currently overlaid skill (None = backbone).
24073    pub fn active_skill(&self) -> Option<usize> {
24074        self.dyn_active
24075    }
24076
24077    /// Enable dynamic per-token skill routing: build the hysteresis
24078    /// router from the container's routable skills, start φ capture at
24079    /// their (shared) phi_layer. Returns the number of routable skills
24080    /// (0 = nothing to route; router stays off). Idempotent.
24081    pub fn enable_dynamic_routing(&mut self) -> usize {
24082        use crate::swarm::{DynRouter, RoutableSkill};
24083        let Some(model) = self.model.clone() else {
24084            return 0;
24085        };
24086        // Router policy v2 (spec §9.4) routes per REQUEST: the backbone is
24087        // the default and only the backbone-gated decision may pick a
24088        // skill. A per-token switch would bypass that gate (and change
24089        // the O(1) state mid-sequence), so the hysteresis router never
24090        // runs on such a file; the caller keeps the request-level
24091        // decision.
24092        if let Some(r) = &model.header.router {
24093            tracing::warn!(
24094                "dynamic routing disabled: this file declares router policy '{}' with \
24095                 granularity \"{}\" — the request-level decision applies instead",
24096                r.policy,
24097                r.granularity
24098            );
24099            return 0;
24100        }
24101        // Format-v2 skill records (bit SKILLS_V2) without a router policy:
24102        // their status/gate contract ("auto-routing requires active +
24103        // measured") lives in the backbone-gated decision only — the
24104        // hysteresis router would switch into a quarantined record
24105        // (fail-open). Refuse the whole file, not just its v2 records.
24106        if model.required_features & cortiq_core::format::features::SKILLS_V2 != 0
24107            || model.header.skills.iter().any(|s| s.is_v2())
24108        {
24109            tracing::warn!(
24110                "dynamic routing disabled: this file carries format-v2 skill records \
24111                 (SKILLS_V2) — they route per request through a router policy only"
24112            );
24113            return 0;
24114        }
24115        // A blend materialized f32 working tensors into the layers; there
24116        // is no single skill index to revert from → refuse (honest).
24117        if self.dyn_blend_loaded {
24118            tracing::warn!("dynamic routing unavailable on a blend-loaded pipeline");
24119            return 0;
24120        }
24121        // A statically-overlaid skill that is NOT FFN-eligible can't be
24122        // cheaply reverted at generation start → refuse rather than
24123        // silently keep it overlaid.
24124        if let Some(a) = self.dyn_active {
24125            if !matches!(self.dyn_skill_layers.get(a), Some(Some(_))) {
24126                tracing::warn!("loaded skill is not FFN-eligible — dynamic routing unavailable");
24127                return 0;
24128            }
24129        }
24130        let hidden = self.hidden_size;
24131        let mut skills = Vec::new();
24132        for (idx, id, _phi) in self.dynamic_skills() {
24133            if let Some(sel) = model.header.skills[idx].selection.as_ref() {
24134                if let Some(rs) = RoutableSkill::from_descriptor(idx, id, sel, hidden) {
24135                    skills.push(rs);
24136                }
24137            }
24138        }
24139        if skills.is_empty() {
24140            return 0;
24141        }
24142        // Skills should share a phi_layer; warn (not fail) if they don't.
24143        let phi = skills[0].phi_layer;
24144        if skills.iter().any(|s| s.phi_layer != phi) {
24145            tracing::warn!("routable skills disagree on phi_layer; using {phi}");
24146        }
24147        let n = skills.len();
24148        self.set_dyn_phi_layer(Some(phi));
24149        self.dyn_router = Some(DynRouter::new(skills));
24150        n
24151    }
24152
24153    /// Human-readable switch log from the last dynamic-routed generation.
24154    pub fn route_switches(&self) -> Vec<(usize, Option<String>, Option<String>)> {
24155        self.dyn_router
24156            .as_ref()
24157            .map(|r| r.switches.clone())
24158            .unwrap_or_default()
24159    }
24160
24161    /// LM head: hidden → logits [vocab_size]. The dominant matvec of
24162    /// every decode step — row-parallel on the worker pool.
24163    fn lm_head_forward(&self, hidden: &[f32]) -> Vec<f32> {
24164        let _mimo_q8 = self
24165            .mimo_moe
24166            .is_on()
24167            .then(crate::qtensor::enter_full_gpu_q8_scope);
24168        let rows = self.weights.lm_head.rows();
24169        let mut logits = attention::take_buf(rows.min(self.vocab_size));
24170        // Banked MiMo uses the same exact projection family for the
24171        // plain/draft head and the batched verification head. Read both
24172        // scale planes in-place instead of preparing per-op scale buffers.
24173        let served = self.mimo_moe.is_on()
24174            && crate::gpu::mimo_q8_short_enabled()
24175            && rows == self.vocab_size
24176            && !self.weights.lm_head.has_prism_contract()
24177            && self
24178                .weights
24179                .lm_head
24180                .graph_weight()
24181                .is_some_and(|(model, idx, kind, _)| {
24182                    kind == 7
24183                        && crate::gpu::q82_short_rows(
24184                            model,
24185                            idx,
24186                            hidden,
24187                            1,
24188                            rows,
24189                            self.hidden_size,
24190                            &mut logits,
24191                        )
24192                });
24193        if !served {
24194            self.weights
24195                .lm_head
24196                .matvec(hidden, &mut logits, self.pool.as_deref());
24197        }
24198        logits.resize(self.vocab_size, 0.0);
24199        if let Some(m) = self.logit_multiplier {
24200            for l in logits.iter_mut() {
24201                *l *= m;
24202            }
24203        }
24204        if let Some(c) = self.final_softcap {
24205            softcap_in_place(&mut logits, c, self.pool.as_deref());
24206        }
24207        if let Some(cm) = self.head_clusters.as_ref() {
24208            self.hierarchical_head_logprobs(hidden, cm, &mut logits);
24209        }
24210        logits
24211    }
24212
24213    /// Two-level head (Cortiq Embryo): in place, logits[v] ← log p(v) =
24214    /// (lc[c] − lse(lc)) + (logit[v] − lse over v's cluster block), c = v / S.
24215    fn hierarchical_head_logprobs(&self, hidden: &[f32], cm: &[f32], logits: &mut [f32]) {
24216        let h = hidden.len();
24217        let ncl = cm.len() / h.max(1);
24218        if ncl == 0 || logits.len() % ncl != 0 {
24219            return;
24220        }
24221        let cs = logits.len() / ncl;
24222        // cluster logits + log-softmax
24223        let mut lc = vec![0.0f32; ncl];
24224        for c in 0..ncl {
24225            let row = &cm[c * h..(c + 1) * h];
24226            let mut s = 0.0f32;
24227            for j in 0..h {
24228                s += row[j] * hidden[j];
24229            }
24230            lc[c] = s;
24231        }
24232        let mx = lc.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
24233        let lse: f32 = mx + lc.iter().map(|v| (v - mx).exp()).sum::<f32>().ln();
24234        for c in 0..ncl {
24235            let blk = &mut logits[c * cs..(c + 1) * cs];
24236            let bm = blk.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
24237            let bl: f32 = bm + blk.iter().map(|v| (v - bm).exp()).sum::<f32>().ln();
24238            let add = lc[c] - lse - bl;
24239            for v in blk.iter_mut() {
24240                *v += add;
24241            }
24242        }
24243    }
24244
24245    /// Prefill `ids` and return the next-token logits — what the model
24246    /// would predict next, WITHOUT committing to generation (introspection
24247    /// for `cortiq explain`). Clears and repopulates the KV cache; leaves
24248    /// the active overlay untouched.
24249    pub fn prefill_next_logits(&mut self, ids: &[u32], task_mask: Option<&TaskMask>) -> Vec<f32> {
24250        #[cfg(target_os = "macos")]
24251        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
24252        self.clear_sequence_state();
24253        // This helper is used by the pooled classification endpoint, where
24254        // every request is a fresh sequence. The shared reset also clears the
24255        // wgpu token graph's device-side recurrent state.
24256        crate::gpu::graph_race_begin_generation();
24257        if task_mask.is_none() {
24258            self.o1_begin();
24259        }
24260        let mut hidden = vec![0.0f32; self.hidden_size];
24261        for (pos, &id) in ids.iter().enumerate() {
24262            let emb = self.embed_single(id);
24263            hidden = self.forward_layers(&emb, pos, task_mask);
24264        }
24265        if let Err(err) = self.o1_seal_checked() {
24266            self.o1_fail(err);
24267        }
24268        // Stacks that own their head (V4, V4.1, Qwen3.8-Flash-Next, GLM-5)
24269        // return a zero hidden and hand the logits out of band.
24270        if let Some(logits) = self.graph_logits.take() {
24271            return logits;
24272        }
24273        inference::rms_norm_into(
24274            &hidden,
24275            &self.weights.final_norm,
24276            self.rms_eps,
24277            self.norm_style,
24278            &mut self.ws.n1,
24279        );
24280        self.lm_head_forward(&self.ws.n1)
24281    }
24282}
24283
24284/// Convenience: deterministic tiny pipeline for tests.
24285pub fn create_test_pipeline(
24286    hidden_size: usize,
24287    intermediate_size: usize,
24288    num_heads: usize,
24289    num_kv_heads: usize,
24290    head_dim: usize,
24291    num_layers: usize,
24292    vocab_size: usize,
24293) -> Pipeline {
24294    // Small pseudo-random weights: constant weights make attention
24295    // degenerate and hide indexing bugs.
24296    let synth = |n: usize, salt: usize| -> Vec<f32> {
24297        (0..n)
24298            .map(|i| (((i * 31 + salt * 17 + 7) % 97) as f32 / 97.0 - 0.5) * 0.2)
24299            .collect()
24300    };
24301    let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
24302        QTensor::from_f32(synth(rows * cols, salt), rows, cols)
24303    };
24304    let layer_weights: Vec<LayerWeights> = (0..num_layers)
24305        .map(|li| LayerWeights {
24306            input_norm: vec![1.0; hidden_size],
24307            post_norm: vec![1.0; hidden_size],
24308            attn_out_norm: None,
24309            ffn_out_norm: None,
24310            layer_scale: None,
24311            ffn: FfnKind::Dense(DenseFfn {
24312                gate_proj: qt(intermediate_size, hidden_size, li * 10 + 5),
24313                up_proj: qt(intermediate_size, hidden_size, li * 10 + 6),
24314                down_proj: qt(hidden_size, intermediate_size, li * 10 + 7),
24315                act: Act::Silu,
24316                down_t: None,
24317                segs: Vec::new(),
24318            }),
24319            attn: AttnKind::Full {
24320                bias: None,
24321                wq: qt(num_heads * head_dim, hidden_size, li * 10 + 1),
24322                wk: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 2),
24323                wv: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 3),
24324                wo: qt(hidden_size, num_heads * head_dim, li * 10 + 4),
24325                q_norm: None,
24326                k_norm: None,
24327                output_gate: false,
24328                softplus_gate: None,
24329            },
24330        })
24331        .collect();
24332
24333    Pipeline::new(
24334        Tokenizer::byte_level(),
24335        PipelineWeights {
24336            embed_tokens: qt(vocab_size, hidden_size, 100),
24337            layers: layer_weights,
24338            lm_head: qt(vocab_size, hidden_size, 200),
24339            final_norm: vec![1.0; hidden_size],
24340        },
24341        hidden_size,
24342        intermediate_size,
24343        num_heads,
24344        num_kv_heads,
24345        head_dim,
24346        num_layers,
24347        num_layers, // physical_layers = num_layers (non-looped)
24348        false,      // loop_final_norm
24349        vocab_size,
24350        1e-6,
24351        10_000.0,
24352        NormStyle::Qwen,
24353        4096,
24354        SamplerConfig {
24355            seed: Some(42),
24356            ..Default::default()
24357        },
24358    )
24359}
24360
24361/// Batched dense-FFN: gate/up/down via matmat (element-wise the same
24362/// math as b × dense_ffn — the same dot kernels).
24363/// One mask bit, LSB-first per byte — `TaskMask::ffn_active_indices`'s
24364/// convention.
24365#[inline]
24366fn mask_bit(row: &[u8], j: usize) -> bool {
24367    (row.get(j >> 3).copied().unwrap_or(0) >> (j & 7)) & 1 != 0
24368}
24369
24370/// Zero the CLOSED neurons' activations in a [rows × inter] panel — the
24371/// masked-inference fast path's whole trick: full fused quant compute,
24372/// then the mask lands on the ACTIVATIONS, which is arithmetically the
24373/// pruned network without touching a quantized weight byte. Whole open
24374/// bytes (0xFF = 8 open neurons) skip in one test.
24375/// `CMF_FFN_MASK_GAIN` — Patent 12 FIG. 4, variance-preserving
24376/// rescaling: truncation removes a share of the layer's output energy,
24377/// so the survivors are scaled up to put the variance back where the
24378/// downstream norm expects it. A scalar here; per layer it is
24379/// `sqrt(total energy / kept energy)`.
24380fn mask_gain() -> f32 {
24381    static G: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
24382    *G.get_or_init(|| {
24383        std::env::var("CMF_FFN_MASK_GAIN")
24384            .ok()
24385            .and_then(|v| v.parse().ok())
24386            .unwrap_or(1.0)
24387    })
24388}
24389
24390fn zero_masked_cols(g: &mut [f32], rows: usize, inter: usize, row: &[u8]) {
24391    // With CMF_FFN_MEANFILL a closed neuron contributes its average
24392    // instead of nothing — same bytes read, one constant restored.
24393    let fill = meanfill().and_then(|(i, v)| {
24394        let li = crate::gpu::cur_layer();
24395        (*i == inter && li >= 0).then(|| &v[li as usize * inter..(li as usize + 1) * inter])
24396    });
24397    for r in 0..rows {
24398        let base = r * inter;
24399        for (bi, &byte) in row.iter().enumerate() {
24400            if byte == 0xFF {
24401                continue;
24402            }
24403            let j0 = bi * 8;
24404            for bit in 0..8 {
24405                let j = j0 + bit;
24406                if j < inter && byte & (1 << bit) == 0 {
24407                    g[base + j] = fill.map_or(0.0, |f| f[j]);
24408                }
24409            }
24410        }
24411    }
24412    let gain = mask_gain();
24413    if gain != 1.0 {
24414        for v in g[..rows * inter].iter_mut() {
24415            *v *= gain;
24416        }
24417    }
24418}
24419
24420/// True when neuron `i`'s bit is set (no mask = everything runs).
24421#[inline]
24422fn tube_bit(row: Option<&[u8]>, i: usize) -> bool {
24423    row.is_none_or(|r| mask_bit(r, i))
24424}
24425
24426/// Every bit below `n` set — the common case for a tube file's CORE,
24427/// where only the tube bits vary per task.
24428fn all_bits_on(row: &[u8], n: usize) -> bool {
24429    (0..n).all(|i| mask_bit(row, i))
24430}
24431
24432/// `CMF_TUBE_TOPK` — how many tubes a TOKEN may open (0 = the task mask
24433/// decides alone). This is the dense FFN read as a mixture: the tubes
24434/// are the experts a k-means over `gate_proj` rows found, and the token
24435/// picks among them. `CMF_TUBE_SCORE=gate` scores a tube by its own
24436/// gate (realizable: only `up`/`down` of the losers go unread),
24437/// `=oracle` scores by the true `silu(gate)·up` mass (the ceiling —
24438/// only `down` is saved, and the selection has read what it predicts).
24439fn tube_topk() -> usize {
24440    static K: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
24441    *K.get_or_init(|| {
24442        std::env::var("CMF_TUBE_TOPK")
24443            .ok()
24444            .and_then(|v| v.parse().ok())
24445            .unwrap_or(0)
24446    })
24447}
24448
24449fn tube_score_oracle() -> bool {
24450    static O: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
24451    *O.get_or_init(|| std::env::var("CMF_TUBE_SCORE").is_ok_and(|v| v == "oracle"))
24452}
24453
24454/// The routed arm of `tube_ffn`: a token opens only its best `k` tubes.
24455/// At `b == 1` (decode) the losers are genuinely never read — that is
24456/// the speed. At `b > 1` (the scoring sweep) every tube is computed and
24457/// the losers' activations are zeroed instead: same arithmetic, so the
24458/// perplexity is the routed model's, measured without a per-token
24459/// gather in the middle of a GEMM.
24460fn tube_ffn_routed(
24461    d: &DenseFfn,
24462    xs: &[f32],
24463    b: usize,
24464    pool: Option<&Pool>,
24465    mask_row: Option<&[u8]>,
24466    k: usize,
24467) -> Vec<f32> {
24468    let hidden = d.down_proj.rows();
24469    let core = d.gate_proj.rows();
24470    let core_full = mask_row.is_none_or(|r| all_bits_on(r, core));
24471    let mut out = match (b, core_full, mask_row) {
24472        (1, true, _) => dense_ffn(d, xs, pool),
24473        (1, false, Some(row)) => dense_ffn_masked(d, xs, pool, row),
24474        (_, true, _) => dense_ffn_batch(d, xs, b, pool, None),
24475        (_, false, row) => dense_ffn_batch(d, xs, b, pool, row),
24476    };
24477    let cand: Vec<usize> = (0..d.segs.len())
24478        .filter(|&i| tube_bit(mask_row, d.segs[i].start))
24479        .collect();
24480    if cand.is_empty() {
24481        return out;
24482    }
24483    // gate (and, where the score or the batch needs it, up) per tube.
24484    // The SCORE is taken at the point the serving path could take it:
24485    // off the gate alone, or off the finished activation for the oracle.
24486    let oracle = tube_score_oracle();
24487    let mut acts: Vec<Vec<f32>> = Vec::with_capacity(cand.len());
24488    let mut scores = vec![0f32; b * cand.len()];
24489    for (ci, &i) in cand.iter().enumerate() {
24490        let seg = &d.segs[i];
24491        let w = seg.width;
24492        let mut g = vec![0.0f32; b * w];
24493        if b == 1 {
24494            seg.gate.matvec(xs, &mut g, pool);
24495        } else {
24496            seg.gate.matmat(xs, b, &mut g, pool);
24497        }
24498        for v in g.iter_mut() {
24499            *v = Act::Silu.combine(*v, 1.0);
24500        }
24501        if !oracle {
24502            for t in 0..b {
24503                scores[t * cand.len() + ci] =
24504                    g[t * w..(t + 1) * w].iter().map(|v| v * v).sum::<f32>();
24505            }
24506        }
24507        if oracle || b > 1 {
24508            let mut u = vec![0.0f32; b * w];
24509            if b == 1 {
24510                seg.up.matvec(xs, &mut u, pool);
24511            } else {
24512                seg.up.matmat(xs, b, &mut u, pool);
24513            }
24514            for (a, &v) in g.iter_mut().zip(u.iter()) {
24515                *a *= v;
24516            }
24517            if oracle {
24518                for t in 0..b {
24519                    scores[t * cand.len() + ci] =
24520                        g[t * w..(t + 1) * w].iter().map(|v| v * v).sum::<f32>();
24521                }
24522            }
24523        }
24524        acts.push(g);
24525    }
24526    // per-token scores and the winners
24527    let keep = k.min(cand.len());
24528    let mut scratch: Vec<f32> = Vec::new();
24529    for t in 0..b {
24530        let mut sc: Vec<(f32, usize)> = (0..cand.len())
24531            .map(|ci| (scores[t * cand.len() + ci], ci))
24532            .collect();
24533        sc.sort_unstable_by(|x, y| y.0.total_cmp(&x.0));
24534        let mut alive = vec![false; cand.len()];
24535        for &(_, ci) in sc.iter().take(keep) {
24536            alive[ci] = true;
24537        }
24538        if b > 1 {
24539            for (ci, a) in acts.iter_mut().enumerate() {
24540                if !alive[ci] {
24541                    let w = d.segs[cand[ci]].width;
24542                    a[t * w..(t + 1) * w].fill(0.0);
24543                }
24544            }
24545        } else {
24546            // decode: finish only the winners — the losers' up/down
24547            // (and, with the gate score, everything but their gate)
24548            // are never touched.
24549            for (ci, &i) in cand.iter().enumerate() {
24550                if !alive[ci] {
24551                    continue;
24552                }
24553                let seg = &d.segs[i];
24554                let w = seg.width;
24555                let g = &mut acts[ci];
24556                if !tube_score_oracle() {
24557                    scratch.clear();
24558                    scratch.resize(w, 0.0);
24559                    seg.up.matvec(xs, &mut scratch, pool);
24560                    for (a, &v) in g.iter_mut().zip(scratch.iter()) {
24561                        *a *= v;
24562                    }
24563                }
24564                let mut acc = vec![0.0f32; hidden];
24565                seg.down.matvec(g, &mut acc, pool);
24566                for (o, a) in out.iter_mut().zip(&acc) {
24567                    *o += *a;
24568                }
24569            }
24570        }
24571    }
24572    if b > 1 {
24573        for (ci, &i) in cand.iter().enumerate() {
24574            let seg = &d.segs[i];
24575            let mut acc = vec![0.0f32; b * hidden];
24576            seg.down.matmat(&acts[ci], b, &mut acc, pool);
24577            for (o, a) in out.iter_mut().zip(&acc) {
24578                *o += *a;
24579            }
24580        }
24581    }
24582    out
24583}
24584
24585/// FFN of a defragged tube layer: the always-on core plus the tubes the
24586/// task mask switches on. Each tube is a normal tensor triple, so the
24587/// same kernels run it and an inactive tube's bytes are never read —
24588/// that is the whole point of the defrag (a scattered mask cannot skip
24589/// bytes; a contiguous one is just a smaller matrix).
24590fn tube_ffn(
24591    d: &DenseFfn,
24592    xs: &[f32],
24593    b: usize,
24594    pool: Option<&Pool>,
24595    mask_row: Option<&[u8]>,
24596) -> Vec<f32> {
24597    if tube_topk() > 0 {
24598        return tube_ffn_routed(d, xs, b, pool, mask_row, tube_topk());
24599    }
24600    let hidden = d.down_proj.rows();
24601    let core = d.gate_proj.rows();
24602    let core_full = mask_row.is_none_or(|r| all_bits_on(r, core));
24603    let mut out = match (b, core_full, mask_row) {
24604        (1, true, _) => dense_ffn(d, xs, pool),
24605        (1, false, Some(row)) => dense_ffn_masked(d, xs, pool, row),
24606        (_, true, _) => dense_ffn_batch(d, xs, b, pool, None),
24607        (_, false, row) => dense_ffn_batch(d, xs, b, pool, row),
24608    };
24609    TUBE_SCRATCH.with(|sc| {
24610        let mut sc = sc.borrow_mut();
24611        let [g, u, acc] = &mut *sc;
24612        for seg in &d.segs {
24613            if !tube_bit(mask_row, seg.start) {
24614                continue;
24615            }
24616            let w = seg.width;
24617            g.resize(b * w, 0.0);
24618            if b == 1
24619                && d.act == Act::Silu
24620                && QTensor::matvec_silu_mul(&seg.gate, &seg.up, xs, g, pool)
24621            {
24622                // g holds silu(gate)·up.
24623            } else {
24624                u.resize(b * w, 0.0);
24625                if b == 1 {
24626                    QTensor::matvec_many([&seg.gate, &seg.up], xs, [g, u], pool);
24627                } else {
24628                    seg.gate.matmat(xs, b, g, pool);
24629                    seg.up.matmat(xs, b, u, pool);
24630                }
24631                for i in 0..b * w {
24632                    g[i] = d.act.combine(g[i], u[i]);
24633                }
24634            }
24635            acc.resize(b * hidden, 0.0);
24636            acc.fill(0.0);
24637            if b == 1 {
24638                seg.down.matvec(g, acc, pool);
24639            } else {
24640                seg.down.matmat(g, b, acc, pool);
24641            }
24642            for (o, a) in out.iter_mut().zip(acc.iter()) {
24643                *o += *a;
24644            }
24645        }
24646        out
24647    })
24648}
24649
24650thread_local! {
24651    /// gate / up / down-accumulator scratch for the tube loop — a tube
24652    /// runs once per layer per token, and a fresh Vec each time is a
24653    /// malloc per tube per layer per token.
24654    static TUBE_SCRATCH: std::cell::RefCell<[Vec<f32>; 3]> =
24655        const { std::cell::RefCell::new([Vec::new(), Vec::new(), Vec::new()]) };
24656}
24657
24658/// An expert's tubes (`mlp.experts.{e}.*_proj.tube1.weight`: its hot neurons at eight
24659/// bits, their rows zero in the expert's own triple) added to `out` with the expert's
24660/// routing weight. The MoE paths compute the triple themselves; this is the rest.
24661pub(crate) fn expert_tubes_add(d: &DenseFfn, x: &[f32], weight: f32, out: &mut [f32], pool: Option<&Pool>) {
24662    if d.segs.is_empty() {
24663        return;
24664    }
24665    TUBE_SCRATCH.with(|sc| {
24666        let mut sc = sc.borrow_mut();
24667        let [g, u, acc] = &mut *sc;
24668        for seg in &d.segs {
24669            let w = seg.width;
24670            g.resize(w, 0.0);
24671            if !(d.act == Act::Silu && QTensor::matvec_silu_mul(&seg.gate, &seg.up, x, g, pool)) {
24672                u.resize(w, 0.0);
24673                QTensor::matvec_many([&seg.gate, &seg.up], x, [g, u], pool);
24674                for i in 0..w {
24675                    g[i] = d.act.combine(g[i], u[i]);
24676                }
24677            }
24678            acc.resize(out.len(), 0.0);
24679            acc.fill(0.0);
24680            seg.down.matvec(g, acc, pool);
24681            for (o, a) in out.iter_mut().zip(acc.iter()) {
24682                *o += weight * *a;
24683            }
24684        }
24685    });
24686}
24687
24688/// The shared expert's weight on one token: σ of its gate, or 1 without one.
24689pub(crate) fn shared_expert_weight(gate: Option<&QTensor>, x: &[f32], pool: Option<&Pool>) -> f32 {
24690    gate.map_or(1.0, |gate| {
24691        let mut gl = [0.0f32; 1];
24692        gate.matvec(x, &mut gl, pool);
24693        1.0 / (1.0 + (-gl[0]).exp())
24694    })
24695}
24696
24697/// The shared expert's tubes (`mlp.shared_expert.*_proj.tube1.weight`, `hot-bake
24698/// --shared-q8`: the whole expert at eight bits) added to `out` with its weight.
24699pub(crate) fn shared_tubes_add(m: &MoeFfn, x: &[f32], out: &mut [f32], pool: Option<&Pool>) {
24700    if let Some((se, gate)) = &m.shared
24701        && !se.segs.is_empty()
24702    {
24703        let g = shared_expert_weight(gate.as_ref(), x, pool);
24704        expert_tubes_add(se, x, g, out, pool);
24705    }
24706}
24707
24708/// CMF_PREFILL_PROF: cumulative ns of the batched walk's attention and
24709/// FFN halves (all layers, all chunks).
24710static PREFILL_SPLIT: [std::sync::atomic::AtomicU64; 2] = [
24711    std::sync::atomic::AtomicU64::new(0),
24712    std::sync::atomic::AtomicU64::new(0),
24713];
24714
24715/// The wgpu side of `CMF_PREFILL_PROF`: q|k|v GEMMs' enqueue and readback
24716/// wait, the chunk attend's readback wait (ms, cumulative) and the int8
24717/// GEMMs the `zi_mm` route took.
24718fn wgpu_prefill_counters() -> (f64, f64, f64, u64) {
24719    #[cfg(feature = "gpu")]
24720    {
24721        use std::sync::atomic::Ordering::Relaxed;
24722        let ms = |a: &std::sync::atomic::AtomicU64| a.load(Relaxed) as f64 / 1e6;
24723        (
24724            ms(&crate::gpu_wgpu::GEMM_MANY_NS[0]),
24725            ms(&crate::gpu_wgpu::GEMM_MANY_NS[1]),
24726            ms(&crate::gpu_wgpu::CHUNK_ATTEND_WAIT_NS),
24727            crate::gpu_wgpu::ZI_GEMM_CALLS.load(Relaxed),
24728        )
24729    }
24730    #[cfg(not(feature = "gpu"))]
24731    (0.0, 0.0, 0.0, 0)
24732}
24733
24734/// The wgpu prefill mirror attend's outcome counters
24735/// (`gpu_wgpu::MIRROR_EVENTS`).
24736fn wgpu_mirror_counters() -> [u64; 6] {
24737    #[cfg(feature = "gpu")]
24738    {
24739        crate::gpu_wgpu::MIRROR_EVENTS
24740            .each_ref()
24741            .map(|a| a.load(std::sync::atomic::Ordering::Relaxed))
24742    }
24743    #[cfg(not(feature = "gpu"))]
24744    [0; 6]
24745}
24746
24747fn prefill_prof_on() -> bool {
24748    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
24749    *ON.get_or_init(|| std::env::var_os("CMF_PREFILL_PROF").is_some())
24750}
24751
24752/// Accumulate the dense FFN activations which feed the down projection.
24753///
24754/// MTP calibration intentionally calls this independently of the trunk's
24755/// `FFN_PROBE` TLS recorder: an MTP sidecar can use a different FFN width,
24756/// and borrowing the trunk's layer-numbered accumulator would silently turn
24757/// draft statistics into trunk proxies.  The caller owns the execution scope
24758/// (the public MTP probe uses `gpu::cpu_scope`) and supplies one accumulator
24759/// per actual MTP FFN channel.
24760pub(crate) fn accumulate_dense_ffn_activation_mass(
24761    d: &DenseFfn,
24762    xs: &[f32],
24763    b: usize,
24764    pool: Option<&Pool>,
24765    mass: &mut [f64],
24766    squared_mass: &mut [f64],
24767) -> Result<(), String> {
24768    let inter = d.gate_proj.rows();
24769    let hidden = d.gate_proj.cols();
24770    if mass.len() != inter || squared_mass.len() != inter {
24771        return Err(format!(
24772            "MTP FFN probe: accumulator widths ({}, {}) != gate width {inter}",
24773            mass.len(),
24774            squared_mass.len()
24775        ));
24776    }
24777    if d.up_proj.rows() != inter
24778        || d.up_proj.cols() != hidden
24779        || d.down_proj.cols() != inter
24780        || d.down_proj.rows() != hidden
24781    {
24782        return Err("MTP FFN probe: inconsistent dense FFN shapes".into());
24783    }
24784    if !d.segs.is_empty() {
24785        return Err("MTP FFN probe: tube-segmented draft FFNs are not supported".into());
24786    }
24787    if xs.len() != b.saturating_mul(hidden) {
24788        return Err(format!(
24789            "MTP FFN probe: {} input values for {b} × {hidden} rows",
24790            xs.len()
24791        ));
24792    }
24793    if b == 0 {
24794        return Ok(());
24795    }
24796    let mut gate = vec![0.0f32; b * inter];
24797    let mut up = vec![0.0f32; b * inter];
24798    d.gate_proj.matmat(xs, b, &mut gate, pool);
24799    d.up_proj.matmat(xs, b, &mut up, pool);
24800    for row in 0..b {
24801        for i in 0..inter {
24802            let a = d.act.combine(gate[row * inter + i], up[row * inter + i]);
24803            let a = a as f64;
24804            mass[i] += a.abs();
24805            squared_mass[i] += a * a;
24806        }
24807    }
24808    Ok(())
24809}
24810
24811fn dense_ffn_batch(
24812    d: &DenseFfn,
24813    xs: &[f32],
24814    b: usize,
24815    pool: Option<&Pool>,
24816    mask_row: Option<&[u8]>,
24817) -> Vec<f32> {
24818    let inter = d.gate_proj.rows();
24819    let hidden = d.down_proj.rows();
24820    // Fused on-device SwiGLU when the device is in play: three separate
24821    // `matmat` calls are three round trips per layer, and the gate/up
24822    // panels (b × inter — 22 MB each at a 512-token chunk) cross the bus
24823    // twice for nothing. The kernel already existed for the image DiT;
24824    // the LLM prefill was simply never wired to it. A task mask needs the
24825    // activations on the host between the halves, so it keeps the CPU
24826    // arm below.
24827    // SiLU/GELU have device arms everywhere they are admitted.  MiniMax
24828    // M3's frozen OAI contract has an additional WGPU-only arm; callers on
24829    // native Metal still get an honest decline from `q4_ffn_act` rather than
24830    // an accidental SiLU evaluation.
24831    let fused_act = d.act.wgpu_graph_act();
24832    if mask_row.is_none()
24833        && fused_act.is_some()
24834        && b >= 32
24835        && crate::gpu::enabled_here()
24836        && !crate::gpu::mm_killed()
24837        // The refit pass needs this layer's activations on the host; the
24838        // fused chain keeps them on the device. Refusing it here costs
24839        // one round trip and keeps every GEMM on the card — the
24840        // alternative was running the whole calibration on the CPU.
24841        && refit_dir().is_none()
24842        // Same for the mass/hit probes. The accumulator at the bottom of
24843        // this function only sees `g` when `g` came back to the host, so
24844        // a fused batch would leave it summing nothing — a probe that
24845        // reports zeros rather than failing, which is worse.
24846        && !ffn_probe_active()
24847        // GPTQ calibration folds every projection's input on the host
24848        // (`QTensor::matmat`); the fused chain would hand gate/up/down
24849        // their inputs on the card and leave the FFN uncalibrated.
24850        && !crate::gptq_capture::capturing()
24851    {
24852        if let (Some((model, w1)), Some((_, w3)), Some((_, w2))) = (
24853            d.gate_proj.mapped_q4t(),
24854            d.up_proj.mapped_q4t(),
24855            d.down_proj.mapped_q4t(),
24856        ) {
24857            let mut out = vec![0.0f32; b * hidden];
24858            let act = fused_act.expect("checked above");
24859            if crate::gpu::q4_ffn_act(
24860                model, w1, w3, w2, xs, b, hidden, inter, false, act, &mut out,
24861            ) {
24862                return out;
24863            }
24864        }
24865        // The q4tp twin (same kernel family, scale from the row ladder) —
24866        // the DiT has run it in production since the pipeline containers;
24867        // the LLM prefill was simply never wired to it, so a q4tp model's
24868        // prefill panels stayed on the CPU.
24869        if let (Some((model, w1)), Some((_, w3)), Some((_, w2))) = (
24870            d.gate_proj.mapped_q4tp(),
24871            d.up_proj.mapped_q4tp(),
24872            d.down_proj.mapped_q4tp(),
24873        ) {
24874            let mut out = vec![0.0f32; b * hidden];
24875            let act = fused_act.expect("checked above");
24876            if crate::gpu::q4_ffn_act(model, w1, w3, w2, xs, b, hidden, inter, true, act, &mut out)
24877            {
24878                return out;
24879            }
24880        }
24881        // Every other device codec — int8, or gate/up and down in different
24882        // codecs: the three GEMMs with the panels kept on the card. Without
24883        // it a q8_2f prefill read both b·inter panels home, folded them on
24884        // one host thread, and sent the result back for down.
24885        // CMF_FFN_KEEP=0 keeps the per-GEMM path (A/B).
24886        if let (true, Some((model, w1)), Some((_, w3)), Some((_, w2))) = (
24887            std::env::var("CMF_FFN_KEEP").as_deref() != Ok("0"),
24888            d.gate_proj.mapped_device_gemm(),
24889            d.up_proj.mapped_device_gemm(),
24890            d.down_proj.mapped_device_gemm(),
24891        ) {
24892            let mut out = vec![0.0f32; b * hidden];
24893            let act = fused_act.expect("checked above");
24894            if crate::gpu::ffn_act_keep(model, w1, w3, w2, xs, b, hidden, inter, act, &mut out) {
24895                return out;
24896            }
24897        }
24898    }
24899    let mut g = vec![0.0f32; b * inter];
24900    d.gate_proj.matmat(xs, b, &mut g, pool);
24901    let mut u = vec![0.0f32; b * inter];
24902    d.up_proj.matmat(xs, b, &mut u, pool);
24903    if gate_topk() > 0 && d.act == Act::Silu {
24904        for t in 0..b {
24905            let row = &mut g[t * inter..(t + 1) * inter];
24906            for v in row.iter_mut() {
24907                *v = Act::Silu.combine(*v, 1.0);
24908            }
24909            keep_top_k(row, gate_topk());
24910        }
24911        for i in 0..b * inter {
24912            g[i] *= u[i];
24913        }
24914    } else {
24915        combine_pooled(d.act, &mut g[..b * inter], &u[..b * inter], pool);
24916    }
24917    if let Some(row) = mask_row {
24918        zero_masked_cols(&mut g, b, inter, row);
24919    }
24920    if oracle_topk() > 0 {
24921        for t in 0..b {
24922            keep_top_k(&mut g[t * inter..(t + 1) * inter], oracle_topk());
24923        }
24924    }
24925    let mut out = vec![0.0f32; b * hidden];
24926    d.down_proj.matmat(&g, b, &mut out, pool);
24927    if refit_dir().is_some() {
24928        let li = crate::gpu::cur_layer();
24929        if li >= 0 {
24930            refit_accumulate(li as usize, &g, b, inter, &out, hidden, pool);
24931        }
24932    }
24933    // The DTG-MA probe, on the batched path: one prefill sweep gives the
24934    // same per-neuron statistic the per-position probe does, and on a 27B
24935    // that is minutes instead of hours.
24936    FFN_PROBE.with(|pr| {
24937        if let Some(acc) = pr.borrow_mut().as_mut() {
24938            let li = crate::gpu::cur_layer();
24939            if li < 0 {
24940                return;
24941            }
24942            let Some(row) = acc.get_mut(li as usize) else {
24943                return;
24944            };
24945            let (sq, topk) = (probe_sq(), probe_topk().min(inter));
24946            let mut mag: Vec<f32> = Vec::new();
24947            for t in 0..b {
24948                let gr = &g[t * inter..(t + 1) * inter];
24949                if topk > 0 {
24950                    // The hit count of the per-position probe: a position's
24951                    // `topk` loudest neurons each get one.
24952                    mag.clear();
24953                    mag.extend(gr.iter().map(|v| v.abs()));
24954                    let (_, kth, _) = mag.select_nth_unstable_by(topk - 1, |a, b| {
24955                        b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
24956                    });
24957                    let thr = *kth;
24958                    for (a, &v) in row.iter_mut().zip(gr) {
24959                        if v.abs() >= thr {
24960                            *a += 1.0;
24961                        }
24962                    }
24963                    continue;
24964                }
24965                for (a, &v) in row.iter_mut().zip(gr) {
24966                    *a += if sq {
24967                        (v as f64) * (v as f64)
24968                    } else {
24969                        (v as f64).abs()
24970                    };
24971                }
24972            }
24973        }
24974    });
24975    out
24976}
24977
24978/// Batched MoE-FFN: router batched, positions are GROUPED by expert —
24979/// an expert's weights are read once for all its positions in the chunk
24980/// (the main prefill-GEMM win on MoE: 960MB/token of 35B experts).
24981/// Accumulate per-channel activation energy for `CMF_RMS_TRACE`.
24982fn accumulate_act(m: &MoeFfn, xs: &[f32], b: usize) {
24983    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
24984    static DUMP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
24985    let on = *ON.get_or_init(|| std::env::var("CMF_RMS_TRACE").is_ok());
24986    let dump = *DUMP.get_or_init(|| std::env::var("CMF_ACT_DUMP").is_ok());
24987    if (!on && !dump) || b == 0 {
24988        return;
24989    }
24990    let hidden = xs.len() / b;
24991    if on {
24992        let mut acc = m.act_sq.borrow_mut();
24993        if acc.len() < hidden {
24994            acc.resize(hidden, 0.0);
24995        }
24996        for t in 0..b {
24997            let row = &xs[t * hidden..(t + 1) * hidden];
24998            for (a, &v) in acc.iter_mut().zip(row) {
24999                *a += (v as f64) * (v as f64);
25000            }
25001        }
25002    }
25003    if dump {
25004        // Cap the capture: the covariance needs a few thousand rows, and a
25005        // whole prefill of every layer would be gigabytes for no extra rank.
25006        let cap: usize = std::env::var("CMF_ACT_DUMP_ROWS")
25007            .ok()
25008            .and_then(|v| v.parse().ok())
25009            .unwrap_or(4096);
25010        let mut rows = m.act_rows.borrow_mut();
25011        if rows.len() < cap * hidden {
25012            let take = b.min((cap * hidden - rows.len()) / hidden.max(1));
25013            rows.extend_from_slice(&xs[..take * hidden]);
25014        }
25015    }
25016}
25017
25018/// Send-able cursor over a Vec-of-Vecs: each pool worker writes only its
25019/// own slots (disjoint by construction in the caller).
25020#[derive(Clone, Copy)]
25021struct SendVecs(*mut Vec<f32>);
25022unsafe impl Send for SendVecs {}
25023unsafe impl Sync for SendVecs {}
25024impl SendVecs {
25025    #[inline]
25026    fn at(self, i: usize) -> *mut Vec<f32> {
25027        unsafe { self.0.add(i) }
25028    }
25029}
25030
25031fn moe_ffn_batch(
25032    m: &MoeFfn,
25033    xs: &[f32],
25034    b: usize,
25035    hidden: usize,
25036    pool: Option<&Pool>,
25037    allowed: Option<&[bool]>,
25038) -> Vec<f32> {
25039    accumulate_act(m, xs, b);
25040    let ne = m.experts.len();
25041    let mut logits = vec![0.0f32; b * ne];
25042    match &m.resonance {
25043        Some(r) => {
25044            let hdim = xs.len() / b.max(1);
25045            for bi in 0..b {
25046                r.scores(
25047                    &xs[bi * hdim..(bi + 1) * hdim],
25048                    &mut logits[bi * ne..(bi + 1) * ne],
25049                );
25050            }
25051        }
25052        None => m.router.matmat(xs, b, &mut logits, pool),
25053    }
25054
25055    // Assignments: expert → [(position, weight)] — same routing as
25056    // moe_ffn, per position (see `moe_route`).
25057    let mut assign: Vec<Vec<(usize, f32)>> = vec![Vec::new(); ne];
25058    {
25059        let mut st = m.stats.borrow_mut();
25060        if st.len() < ne {
25061            st.resize(ne, 0);
25062        }
25063        for bi in 0..b {
25064            let (idx, p, wsum) = moe_route(&logits[bi * ne..(bi + 1) * ne], m, allowed);
25065            for &e in &idx {
25066                st[e] += 1;
25067                assign[e].push((bi, p[e] / wsum));
25068            }
25069        }
25070    }
25071
25072    let mut out = vec![0.0f32; b * hidden];
25073    let cols = m.experts[0].gate_proj.cols();
25074    let run_expert = |d: &DenseFfn, list: &[(usize, f32)], out: &mut [f32]| {
25075        let sb = list.len();
25076        let mut sub = vec![0.0f32; sb * cols];
25077        for (k, &(bi, _)) in list.iter().enumerate() {
25078            sub[k * cols..(k + 1) * cols].copy_from_slice(&xs[bi * cols..(bi + 1) * cols]);
25079        }
25080        let eo = dense_ffn_batch(d, &sub, sb, pool, None);
25081        for (k, &(bi, w)) in list.iter().enumerate() {
25082            for i in 0..hidden {
25083                out[bi * hidden + i] += w * eo[k * hidden + i];
25084            }
25085        }
25086    };
25087    // Routed experts: the panels are TINY (b·top_k spread over every
25088    // expert — a few positions each), so a pool dispatch per expert is
25089    // pure barrier cost. Invert the parallelism: workers take WHOLE
25090    // experts (serial math inside), then one deterministic scatter in
25091    // expert order — the exact accumulation order the serial loop had.
25092    let active: Vec<usize> = (0..ne).filter(|&e| !assign[e].is_empty()).collect();
25093    if pool.is_some() && active.len() >= 8 {
25094        let mut panels: Vec<Vec<f32>> = vec![Vec::new(); active.len()];
25095        {
25096            let panel_ptr = SendVecs(panels.as_mut_ptr());
25097            // Capture only the expert table: `m` itself carries RefCell
25098            // stats and must not cross the pool boundary.
25099            let experts = &m.experts;
25100            let (active_r, assign_r) = (&active, &assign);
25101            let inherit_cpu = crate::gpu::inherit_cpu_scope();
25102            let run = |start: usize, end: usize| {
25103                let _cpu_scope = inherit_cpu();
25104                // Native Metal: the per-op device helpers (`q4tp_ffn`,
25105                // `q8_matmat`, …) stage through size-keyed shared io
25106                // buffers and are not re-entrant — two workers whose experts
25107                // drew the same row count wrote one buffer at once, so a
25108                // Mellum2.1 prompt came out different on every run. The
25109                // workers keep whole experts on the CPU there; the device
25110                // prefill is the MoE chunk graph.
25111                #[cfg(target_os = "macos")]
25112                let _metal_cpu = crate::gpu::enter_cpu_scope();
25113                for ai in start..end {
25114                    let e = active_r[ai];
25115                    let list = &assign_r[e];
25116                    let sb = list.len();
25117                    let mut sub = vec![0.0f32; sb * cols];
25118                    for (k, &(bi, _)) in list.iter().enumerate() {
25119                        sub[k * cols..(k + 1) * cols]
25120                            .copy_from_slice(&xs[bi * cols..(bi + 1) * cols]);
25121                    }
25122                    // SAFETY: each worker owns a disjoint panels[ai].
25123                    unsafe {
25124                        *panel_ptr.at(ai) = dense_ffn_batch(&experts[e], &sub, sb, None, None);
25125                    }
25126                }
25127            };
25128            match pool {
25129                Some(p) => p.run_rows(active.len(), &run),
25130                None => run(0, active.len()),
25131            }
25132        }
25133        for (ai, &e) in active.iter().enumerate() {
25134            for (k, &(bi, w)) in assign[e].iter().enumerate() {
25135                let eo = &panels[ai][k * hidden..(k + 1) * hidden];
25136                for i in 0..hidden {
25137                    out[bi * hidden + i] += w * eo[i];
25138                }
25139            }
25140        }
25141    } else {
25142        for &e in &active {
25143            run_expert(&m.experts[e], &assign[e], &mut out);
25144        }
25145    }
25146    if let Some((se, gate)) = &m.shared {
25147        let all: Vec<(usize, f32)> = if let Some(gate) = gate {
25148            let mut gl = vec![0.0f32; b];
25149            gate.matmat(xs, b, &mut gl, pool);
25150            (0..b)
25151                .map(|bi| (bi, 1.0 / (1.0 + (-gl[bi]).exp())))
25152                .collect()
25153        } else {
25154            (0..b).map(|bi| (bi, 1.0)).collect()
25155        };
25156        run_expert(se, &all, &mut out);
25157    }
25158    out
25159}
25160
25161/// Decode-exact multi-token MoE — the MiMo speculative verify's FFN. Row
25162/// `r` of the result is bit-identical to `moe_ffn(m, x_r)` on the CPU
25163/// (`moe_ffn_cpu` → `moe_ffn_cpu_batched`): router matvec per row, the same
25164/// routing, the same int8 gate/up/SiLU and down terms
25165/// (`QTensor::moe_gate_up_rows` / `moe_down_rows`), and the row's experts
25166/// summed in ITS route order from 0. What the rows share is the weight
25167/// traffic: each routed expert is read once for every row that picked it.
25168/// (`moe_ffn_batch`, the prompt path, groups the same way but sums in
25169/// expert-index order and runs blocked kernels on wide groups — close, not
25170/// bit-equal to decode.) Any layer the kernels do not cover, or a device
25171/// that could answer `moe_ffn` itself, walks `moe_ffn` row by row.
25172fn moe_ffn_rows_exact(
25173    m: &MoeFfn,
25174    xs: &[f32],
25175    b: usize,
25176    hidden: usize,
25177    pool: Option<&Pool>,
25178) -> Vec<f32> {
25179    let mut out = vec![0.0f32; b * hidden];
25180    let per_row = |out: &mut [f32]| {
25181        for r in 0..b {
25182            let o = moe_ffn(m, &xs[r * hidden..(r + 1) * hidden], pool, None);
25183            out[r * hidden..(r + 1) * hidden].copy_from_slice(&o);
25184        }
25185    };
25186    let covered = !crate::gpu::enabled_here()
25187        && moe_batch_enabled()
25188        && m.shared.is_none()
25189        && m.resonance.is_none()
25190        && FFN_PROBE.with(|pr| pr.borrow().is_none())
25191        && m.experts.iter().all(|d| d.act == Act::Silu);
25192    if !covered {
25193        per_row(&mut out);
25194        return out;
25195    }
25196    let ne = m.experts.len();
25197    // Routing, row by row, exactly as `moe_ffn`.
25198    let mut routes: Vec<(Vec<usize>, Vec<f32>)> = Vec::with_capacity(b);
25199    for r in 0..b {
25200        let x = &xs[r * hidden..(r + 1) * hidden];
25201        accumulate_act(m, x, 1);
25202        let mut logits = vec![0.0f32; ne];
25203        m.router.matvec(x, &mut logits, pool);
25204        let (idx, p, wsum) = moe_route(&logits, m, None);
25205        {
25206            let mut st = m.stats.borrow_mut();
25207            if st.len() < ne {
25208                st.resize(ne, 0);
25209            }
25210            for &e in &idx {
25211                st[e] += 1;
25212            }
25213        }
25214        let w: Vec<f32> = idx
25215            .iter()
25216            .map(|&e| p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]))
25217            .collect();
25218        routes.push((idx, w));
25219    }
25220    if routes.iter().any(|(idx, _)| idx.is_empty()) {
25221        per_row(&mut out);
25222        return out;
25223    }
25224    // Group the (row, expert) picks by expert, in first-seen order.
25225    let mut experts: Vec<usize> = Vec::new();
25226    let mut groups: Vec<Vec<usize>> = Vec::new();
25227    for (r, (idx, _)) in routes.iter().enumerate() {
25228        for &e in idx {
25229            match experts.iter().position(|&x| x == e) {
25230                Some(g) => groups[g].push(r),
25231                None => {
25232                    experts.push(e);
25233                    groups.push(vec![r]);
25234                }
25235            }
25236        }
25237    }
25238    let n_pairs: usize = groups.iter().map(|g| g.len()).sum();
25239    let inter = m.experts[experts[0]].gate_proj.rows();
25240    let pairs: Vec<(&QTensor, &QTensor)> = experts
25241        .iter()
25242        .map(|&e| (&m.experts[e].gate_proj, &m.experts[e].up_proj))
25243        .collect();
25244    let mut gs: Vec<Vec<f32>> = (0..n_pairs).map(|_| vec![0f32; inter]).collect();
25245    if !QTensor::moe_gate_up_rows(&pairs, &groups, xs, &mut gs, pool) {
25246        per_row(&mut out);
25247        return out;
25248    }
25249    let downs: Vec<&QTensor> = experts.iter().map(|&e| &m.experts[e].down_proj).collect();
25250    let lens: Vec<usize> = groups.iter().map(|g| g.len()).collect();
25251    let mut ds: Vec<Vec<f32>> = (0..n_pairs).map(|_| vec![0f32; hidden]).collect();
25252    if !QTensor::moe_down_rows(&downs, &lens, &gs, &mut ds, pool) {
25253        per_row(&mut out);
25254        return out;
25255    }
25256    // Where each (row, expert) term landed in the flat pair list.
25257    let mut slot = std::collections::HashMap::with_capacity(n_pairs);
25258    let mut p = 0usize;
25259    for (g, &e) in experts.iter().enumerate() {
25260        for &r in &groups[g] {
25261            slot.insert((r, e), p);
25262            p += 1;
25263        }
25264    }
25265    for (r, (idx, w)) in routes.iter().enumerate() {
25266        let terms: Vec<(&[f32], f32)> = idx
25267            .iter()
25268            .zip(w)
25269            .map(|(&e, &we)| (ds[slot[&(r, e)]].as_slice(), we))
25270            .collect();
25271        let row = &mut out[r * hidden..(r + 1) * hidden];
25272        for (i, dst) in row.iter_mut().enumerate() {
25273            // `moe_down_many`'s per-row sum: from 0, in route order.
25274            let mut acc = 0f32;
25275            for (d, we) in &terms {
25276                acc += we * d[i];
25277            }
25278            *dst = acc;
25279        }
25280    }
25281    out
25282}
25283
25284/// Gemma's final-logit soft-capping, `c·tanh(x/c)`, over a whole vocab row —
25285/// element for element the serial expression, split across the pool: at a
25286/// 262k vocab the serial `tanh` pass was ~5 ms of a 36 ms decode token.
25287/// Ripple's value residual: the rows V projects, `torch.lerp(e0, normed, blend)` term for term
25288/// (the two forms torch picks between at a weight of one half).
25289pub(crate) fn vres_lerp(e0: &[f32], normed: &[f32], blend: f32, out: &mut Vec<f32>) {
25290    debug_assert_eq!(e0.len(), normed.len());
25291    out.clear();
25292    if blend < 0.5 {
25293        out.extend(e0.iter().zip(normed).map(|(&e, &n)| e + blend * (n - e)));
25294    } else {
25295        out.extend(e0.iter().zip(normed).map(|(&e, &n)| n - (n - e) * (1.0 - blend)));
25296    }
25297}
25298
25299pub(crate) fn softcap_in_place(v: &mut [f32], c: f32, pool: Option<&Pool>) {
25300    match pool {
25301        Some(p) if v.len() >= 1 << 15 => {
25302            let base = v.as_mut_ptr() as usize;
25303            p.run_rows(v.len(), &|s, e| {
25304                // SAFETY: run_rows hands out disjoint [s, e) ranges of `v`,
25305                // which outlives the (blocking) dispatch.
25306                let sl =
25307                    unsafe { std::slice::from_raw_parts_mut((base as *mut f32).add(s), e - s) };
25308                for x in sl {
25309                    *x = c * (*x / c).tanh();
25310                }
25311            });
25312        }
25313        _ => {
25314            for x in v.iter_mut() {
25315                *x = c * (*x / c).tanh();
25316            }
25317        }
25318    }
25319}
25320
25321thread_local! {
25322    /// gate/up activation scratch for the dense FFN paths (single uses
25323    /// two slots, the fused pair all four) — these were fresh
25324    /// intermediate-size Vecs on every layer of every token.
25325    static FFN_SCRATCH: std::cell::RefCell<[Vec<f32>; 4]> =
25326        const { std::cell::RefCell::new([Vec::new(), Vec::new(), Vec::new(), Vec::new()]) };
25327}
25328
25329/// Dense SwiGLU FFN through QTensor matvecs (any storage).
25330pub(crate) fn dense_ffn(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
25331    // Per-token sparsity, when the file was built for it: gate first,
25332    // then only the chosen neurons' up/down rows leave the mmap.
25333    if gate_topk() > 0
25334        && let Some(out) = dense_ffn_dynamic(d, x, pool, gate_topk())
25335    {
25336        return out;
25337    }
25338    // Whole-FFN GPU submit (этап 4.2 increment): gate → silu·up → down
25339    // chained in ONE command buffer with the intermediate activations
25340    // resident on the device — 3 per-op polls become 1 per layer. The
25341    // moe_block backend already implements exactly this chain; a dense
25342    // FFN is one expert with weight 1. Runtime probe: the chain still
25343    // pays one submit+poll per layer — alternate it against the pure-CPU
25344    // FFN and keep whichever is faster on this machine.
25345    // q1 FFNs offload at any practical size: the q1 CPU kernel is
25346    // compute-bound, so the UMA threshold logic does not apply — the
25347    // probe measures and decides either way.
25348    // The fused GPU block has no descriptor-aware Prism path: it would either
25349    // consume an unrotated activation or decline after inspecting the mixed
25350    // q2tp/q4tp tensors.  Do not let that structural refusal enter the FFN
25351    // probe's CPU_ONLY scope; the ordinary body below dispatches each matrix
25352    // through QTensor::matvec, which owns the signed FWHT + affine q2tp route.
25353    let prism_body = d.gate_proj.has_prism_contract()
25354        || d.up_proj.has_prism_contract()
25355        || d.down_proj.has_prism_contract();
25356    if !prism_body
25357        && crate::gpu::enabled_here()
25358        && (d.gate_proj.rows() >= crate::gpu::min_rows() || d.gate_proj.is_q1())
25359    {
25360        let arm = if d.gate_proj.is_q1() && crate::gpu::q1_force() {
25361            crate::gpu::ProbeArm::Gpu
25362        } else {
25363            crate::gpu::probe_arm(crate::gpu::OpClass::Ffn)
25364        };
25365        match arm {
25366            crate::gpu::ProbeArm::Gpu => {
25367                let t0 = std::time::Instant::now();
25368                if let Some(out) = dense_ffn_gpu(d, x, pool) {
25369                    crate::gpu::probe_record(crate::gpu::OpClass::Ffn, true, t0.elapsed());
25370                    return out;
25371                }
25372                // Declined: no timing exists, so say so. Silence here is
25373                // what left `ffn` undecided for 9000 calls and cost a
25374                // failed device attempt on half of them.
25375                crate::gpu::probe_note_decline(crate::gpu::OpClass::Ffn);
25376            }
25377            crate::gpu::ProbeArm::CpuTimed => {
25378                let t0 = std::time::Instant::now();
25379                let out = crate::gpu::cpu_scope(|| dense_ffn_cpu(d, x, pool));
25380                crate::gpu::probe_record(crate::gpu::OpClass::Ffn, false, t0.elapsed());
25381                return out;
25382            }
25383            crate::gpu::ProbeArm::Cpu => {
25384                return crate::gpu::cpu_scope(|| dense_ffn_cpu(d, x, pool));
25385            }
25386        }
25387    }
25388    dense_ffn_cpu(d, x, pool)
25389}
25390
25391/// `g[i] = act.combine(g[i], u[i])`, spread over the pool from 8192
25392/// elements: elementwise, so the same bits as the serial loop. An exact
25393/// GELU is one `erf` an element — 1.3 M a layer for a 128-row chunk of
25394/// Spark-X2.6, 10 240 a decode step — and the main thread paid them alone
25395/// while the workers waited for the down projection.
25396fn combine_pooled(act: Act, g: &mut [f32], u: &[f32], pool: Option<&Pool>) {
25397    debug_assert_eq!(g.len(), u.len());
25398    match pool {
25399        Some(p) if g.len() >= 8192 => {
25400            let gp = crate::pool::SendMut::new(g.as_mut_ptr());
25401            p.run_rows(g.len(), &|start, end| {
25402                for i in start..end {
25403                    // SAFETY: each worker owns elements [start, end).
25404                    unsafe {
25405                        let v = gp.at(i);
25406                        *v = act.combine(*v, u[i]);
25407                    }
25408                }
25409            });
25410        }
25411        _ => {
25412            for (gv, &uv) in g.iter_mut().zip(u) {
25413                *gv = act.combine(*gv, uv);
25414            }
25415        }
25416    }
25417}
25418
25419/// The pure-CPU dense-FFN body (also the fallback of every GPU refusal).
25420fn dense_ffn_cpu(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
25421    let inter = d.gate_proj.rows();
25422    FFN_SCRATCH.with(|s| {
25423        let mut s = s.borrow_mut();
25424        let [g, u, ..] = &mut *s;
25425        g.resize(inter, 0.0);
25426        // Fused gate+up+silu: one dispatch, no separate silu pass.
25427        // Falls back to matvec_many + silu loop for unsupported dtypes.
25428        if gate_topk() > 0 {
25429            // Gate first, select, and only then pay for `up`: the
25430            // measurement arm computes both and zeroes the losers, which
25431            // is the same arithmetic.
25432            u.resize(inter, 0.0);
25433            QTensor::matvec_many([&d.gate_proj, &d.up_proj], x, [g, u], pool);
25434            for i in 0..inter {
25435                g[i] = Act::Silu.combine(g[i], 1.0);
25436            }
25437            keep_top_k(g, gate_topk());
25438            for i in 0..inter {
25439                g[i] *= u[i];
25440            }
25441        } else if d.act == Act::Silu && {
25442            let _prof = crate::cpuprof::time(crate::cpuprof::Slot::FfnGateUp);
25443            QTensor::matvec_silu_mul(&d.gate_proj, &d.up_proj, x, g, pool)
25444        } {
25445            // g now holds silu(gate)·up directly.
25446        } else if d.act.clamp_limit() > 0.0 && {
25447            let _prof = crate::cpuprof::time(crate::cpuprof::Slot::FfnGateUp);
25448            QTensor::matvec_silu_mul_limited(&d.gate_proj, &d.up_proj, x, g, d.act.clamp_limit(), pool)
25449        } {
25450            // g holds silu(min(gate, limit))·clamp(up).
25451        } else {
25452            u.resize(inter, 0.0);
25453            // Multi-matrix job: gate+up under one pool dispatch.
25454            let _prof = crate::cpuprof::time(crate::cpuprof::Slot::FfnGateUp);
25455            QTensor::matvec_many([&d.gate_proj, &d.up_proj], x, [g, u], pool);
25456            let _c = crate::cpuprof::time(crate::cpuprof::Slot::FfnCombine);
25457            combine_pooled(d.act, &mut g[..inter], &u[..inter], pool);
25458        }
25459        // DTG-MA bake probe (Patent 2): accumulate this layer's
25460        // per-neuron activation mass while a probe pass is active.
25461        // `CMF_FFN_PROBE_TOPK=k` switches the statistic from mass to a
25462        // HIT COUNT — how many tokens rank the neuron in their own top
25463        // k. Mass asks "how loud is this neuron overall", the count
25464        // asks "how often does this task actually need it", and the two
25465        // rank neurons differently whenever a few tokens are loud.
25466        FFN_PROBE.with(|pr| {
25467            if let Some(acc) = pr.borrow_mut().as_mut() {
25468                let li = crate::gpu::cur_layer();
25469                if li >= 0 {
25470                    if let Some(row) = acc.get_mut(li as usize) {
25471                        match probe_topk() {
25472                            0 if probe_sq() => {
25473                                for (a, &v) in row.iter_mut().zip(g.iter()) {
25474                                    *a += (v as f64) * (v as f64);
25475                                }
25476                            }
25477                            0 if probe_signed() => {
25478                                for (a, &v) in row.iter_mut().zip(g.iter()) {
25479                                    *a += v as f64;
25480                                }
25481                            }
25482                            0 => {
25483                                for (a, &v) in row.iter_mut().zip(g.iter()) {
25484                                    *a += (v as f64).abs();
25485                                }
25486                            }
25487                            k => {
25488                                let n = g.len();
25489                                let k = k.min(n);
25490                                let mut mag: Vec<f32> = g.iter().map(|v| v.abs()).collect();
25491                                let (_, kth, _) = mag.select_nth_unstable_by(k - 1, |a, b| {
25492                                    b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
25493                                });
25494                                let thr = *kth;
25495                                for (a, &v) in row.iter_mut().zip(g.iter()) {
25496                                    if v.abs() >= thr {
25497                                        *a += 1.0;
25498                                    }
25499                                }
25500                            }
25501                        }
25502                    }
25503                }
25504            }
25505        });
25506        MOE_PROBE.with(|pr| {
25507            if let Some(pr) = pr.borrow_mut().as_mut()
25508                && let Some((e, w)) = pr.cur
25509            {
25510                let li = crate::gpu::cur_layer();
25511                if li >= 0
25512                    && let Some(row) = pr.acc.get_mut(li as usize)
25513                    && let Some(cell) = row.get_mut(e * pr.inter..(e + 1) * pr.inter)
25514                {
25515                    for (a, &v) in cell.iter_mut().zip(g.iter()) {
25516                        let s = (w * v) as f64;
25517                        *a += s * s;
25518                    }
25519                }
25520            }
25521        });
25522        if oracle_topk() > 0 {
25523            keep_top_k(g, oracle_topk());
25524        }
25525        {
25526            let li = crate::gpu::cur_layer();
25527            if li >= 0 {
25528                adump_row(li as usize, g);
25529            }
25530        }
25531        let mut out = attention::take_buf(d.down_proj.rows());
25532        let _prof = crate::cpuprof::time(crate::cpuprof::Slot::FfnDown);
25533        d.down_proj.matvec(g, &mut out, pool);
25534        out
25535    })
25536}
25537
25538/// Online accumulators for the AWNP refit of a narrowed FFN.
25539///
25540/// The refit needs `Gss = A_SᵀA_S` and `YA = YᵀA_S` per layer, where `A_S`
25541/// are the calibration activations of the KEPT neurons and `Y` the full
25542/// FFN output. Both are small enough to hold; the thing that is not is
25543/// the activations they are built from — a 27B layer would dump a
25544/// gigabyte per thousand tokens. So they are accumulated as the
25545/// calibration runs and written once at the end.
25546///
25547/// `CMF_FFN_REFIT=<dir>` holds `support.<L>.u32` (a u32 count then the
25548/// kept indices) for every layer to accumulate; `CMF_FFN_REFIT_FROM/TO`
25549/// bound the layer span so the accumulators fit in RAM.
25550pub struct RefitAcc {
25551    pub support: Vec<u32>,
25552    pub gss: Vec<f32>,
25553    pub ya: Vec<f32>,
25554    pub hidden: usize,
25555    pub tokens: u64,
25556    /// Activations staged transposed ([ns, t] and [hidden, t]) until the
25557    /// batch is worth a GEMM. The product costs `ns²` to move and add
25558    /// REGARDLESS of how many tokens went into it, so folding 16 chunks
25559    /// into one call cuts that cost 16× — it was 15 TB of traffic per
25560    /// calibration pass at one call per 256 tokens.
25561    pub buf_g: Vec<f32>,
25562    pub buf_o: Vec<f32>,
25563    pub buf_t: usize,
25564}
25565
25566/// The product buffer is SHARED across layers — one 473 MB allocation,
25567/// not one per layer (that was 30 GB of nothing on a 64-layer model).
25568/// It lives under the same lock as the accumulators.
25569type RefitState = (std::collections::HashMap<usize, RefitAcc>, Vec<f32>);
25570
25571static REFIT: std::sync::OnceLock<Option<(String, std::sync::Mutex<RefitState>)>> =
25572    std::sync::OnceLock::new();
25573
25574/// Is an FFN probe accumulator installed on this thread? The fused GPU
25575/// FFN must decline while one is, or the probe silently measures zero.
25576fn ffn_probe_active() -> bool {
25577    FFN_PROBE.with(|p| p.borrow().is_some())
25578}
25579
25580fn refit_dir() -> Option<&'static (String, std::sync::Mutex<RefitState>)> {
25581    REFIT
25582        .get_or_init(|| {
25583            std::env::var("CMF_FFN_REFIT").ok().map(|d| {
25584                (
25585                    d,
25586                    std::sync::Mutex::new((std::collections::HashMap::new(), Vec::new())),
25587                )
25588            })
25589        })
25590        .as_ref()
25591}
25592
25593/// Accumulate one prefill panel into the layer's refit statistics.
25594fn refit_accumulate(
25595    li: usize,
25596    g: &[f32],
25597    b: usize,
25598    inter: usize,
25599    out: &[f32],
25600    hidden: usize,
25601    pool: Option<&Pool>,
25602) {
25603    let Some((dir, map)) = refit_dir() else {
25604        return;
25605    };
25606    static SPAN: std::sync::OnceLock<(usize, usize)> = std::sync::OnceLock::new();
25607    let (from, to) = *SPAN.get_or_init(|| {
25608        let g = |k: &str, d: usize| {
25609            std::env::var(k)
25610                .ok()
25611                .and_then(|v| v.parse().ok())
25612                .unwrap_or(d)
25613        };
25614        (
25615            g("CMF_FFN_REFIT_FROM", 0),
25616            g("CMF_FFN_REFIT_TO", usize::MAX),
25617        )
25618    });
25619    if li < from || li > to {
25620        return;
25621    }
25622    let mut guard = map.lock().unwrap();
25623    let (map, shared) = &mut *guard;
25624    let acc = match map.entry(li) {
25625        std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
25626        std::collections::hash_map::Entry::Vacant(e) => {
25627            let path = format!("{dir}/support.{li}.u32");
25628            let Ok(bytes) = std::fs::read(&path) else {
25629                eprintln!("refit: no {path} — layer {li} skipped");
25630                return;
25631            };
25632            let n = u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize;
25633            let support: Vec<u32> = bytes[4..4 + n * 4]
25634                .chunks_exact(4)
25635                .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
25636                .collect();
25637            eprintln!(
25638                "refit: layer {li} support {n} ({:.0} MB of accumulator)",
25639                (n * n + hidden * n) as f64 * 4.0 / 1e6
25640            );
25641            e.insert(RefitAcc {
25642                gss: vec![0.0; n * n],
25643                ya: vec![0.0; hidden * n],
25644                buf_g: Vec::new(),
25645                buf_o: Vec::new(),
25646                buf_t: 0,
25647                support,
25648                hidden,
25649                tokens: 0,
25650            })
25651        }
25652    };
25653    let ns = acc.support.len();
25654    // Stage this chunk transposed; the GEMM fires once the batch is full.
25655    let cap = refit_batch();
25656    if acc.buf_g.is_empty() {
25657        acc.buf_g = vec![0.0; ns * cap];
25658        acc.buf_o = vec![0.0; hidden * cap];
25659    }
25660    let take = b.min(cap - acc.buf_t);
25661    for t in 0..take {
25662        let col = acc.buf_t + t;
25663        for (j, &n) in acc.support.iter().enumerate() {
25664            acc.buf_g[j * cap + col] = g[t * inter + n as usize];
25665        }
25666        for h in 0..hidden {
25667            acc.buf_o[h * cap + col] = out[t * hidden + h];
25668        }
25669    }
25670    acc.buf_t += take;
25671    acc.tokens += take as u64;
25672    if acc.buf_t < cap {
25673        return;
25674    }
25675    let bt = acc.buf_t;
25676    acc.buf_t = 0;
25677    // The GEMM WRITES its C (it zeroes the accumulators it uses), so the
25678    // chunk product lands in scratch and is added on — the one thing that
25679    // silently turns a Gram over 13 000 tokens into a Gram over 256.
25680    // Both products are `C[n, m] += X[n, b] · Yᵀ[b, m]` with X and Y
25681    // stored row-major [·, b] — exactly `gemm_nt_f32`'s shape, so the
25682    // card does them when it is up (this is the whole calibration's
25683    // cost: O(|S|²) per token, 2.9 PFLOP for a 27B pass). The tiled CPU
25684    // loop stays as the fallback. Neither accumulates, so the product
25685    // lands in scratch and is added on.
25686    let RefitAcc {
25687        gss,
25688        ya,
25689        buf_g,
25690        buf_o,
25691        ..
25692    } = acc;
25693    let need = (ns * ns).max(hidden * ns);
25694    if shared.len() < need {
25695        shared.resize(need, 0.0);
25696    }
25697    let scratch = &mut shared[..];
25698    let _ = bt;
25699    if crate::gpu::gemm_nt_f32_transient(buf_g, buf_g, &mut scratch[..ns * ns], ns, cap, ns) {
25700        add_into(gss, &scratch[..ns * ns], pool);
25701        if crate::gpu::gemm_nt_f32_transient(
25702            buf_o,
25703            buf_g,
25704            &mut scratch[..hidden * ns],
25705            hidden,
25706            cap,
25707            ns,
25708        ) {
25709            add_into(ya, &scratch[..hidden * ns], pool);
25710        } else {
25711            accum_outer_t(ya, hidden, ns, cap, buf_o, buf_g, pool);
25712        }
25713    } else {
25714        accum_outer_t(gss, ns, ns, cap, buf_g, buf_g, pool);
25715        accum_outer_t(ya, hidden, ns, cap, buf_o, buf_g, pool);
25716    }
25717    // No zeroing: the batch is always filled exactly (cap is a multiple
25718    // of the prefill chunk), and a memset of 178 MB a layer would cost
25719    // more than the GEMM.
25720}
25721
25722/// `CMF_FFN_REFIT_BATCH` — tokens staged before each GEMM (default 4096).
25723fn refit_batch() -> usize {
25724    static B: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
25725    *B.get_or_init(|| {
25726        std::env::var("CMF_FFN_REFIT_BATCH")
25727            .ok()
25728            .and_then(|v| v.parse().ok())
25729            .unwrap_or(4096)
25730    })
25731}
25732
25733/// `c[m, n] += Σ_t left[m, t]·right[n, t]` — both operands transposed,
25734/// the CPU fallback for the staged batch.
25735fn accum_outer_t(
25736    c: &mut [f32],
25737    m: usize,
25738    n: usize,
25739    b: usize,
25740    left: &[f32],
25741    right: &[f32],
25742    pool: Option<&Pool>,
25743) {
25744    let ptr = SendMut(c.as_mut_ptr());
25745    let body = |i: usize| {
25746        let ptr = &ptr;
25747        let row = unsafe { std::slice::from_raw_parts_mut(ptr.0.add(i * n), n) };
25748        for t in 0..b {
25749            let a = left[i * b + t];
25750            if a == 0.0 {
25751                continue;
25752            }
25753            for (j, o) in row.iter_mut().enumerate() {
25754                *o += a * right[j * b + t];
25755            }
25756        }
25757    };
25758    match pool {
25759        Some(p) if m > 1 => p.run_rows(m, &|s, e| {
25760            for i in s..e {
25761                body(i);
25762            }
25763        }),
25764        _ => {
25765            for i in 0..m {
25766                body(i);
25767            }
25768        }
25769    }
25770}
25771
25772/// `dst += src`, spread over the pool — at 118 M floats a layer this is
25773/// not a loop to leave on one core.
25774fn add_into(dst: &mut [f32], src: &[f32], pool: Option<&Pool>) {
25775    let n = dst.len().min(src.len());
25776    match pool {
25777        Some(p) if n >= 1 << 16 => {
25778            let ptr = SendMut(dst.as_mut_ptr());
25779            let f = |s: usize, e: usize| {
25780                let ptr = &ptr;
25781                for blk in s..e {
25782                    let (a, b) = (blk * 4096, ((blk + 1) * 4096).min(n));
25783                    for i in a..b {
25784                        unsafe { *ptr.0.add(i) += src[i] };
25785                    }
25786                }
25787            };
25788            p.run_rows(n.div_ceil(4096), &f);
25789        }
25790        _ => {
25791            for (d, v) in dst.iter_mut().zip(&src[..n]) {
25792                *d += *v;
25793            }
25794        }
25795    }
25796}
25797
25798/// `c[m, n] += Σ_t left[t, m]·right[t, n]`, with `left` stored [m, t] and
25799/// `right` [t, n]. Tiled over the rows of `c` so a tile stays in cache
25800/// while each token's `right` row streams past it once, and parallel
25801/// over tiles.
25802fn accum_outer(
25803    c: &mut [f32],
25804    m: usize,
25805    n: usize,
25806    b: usize,
25807    left: &[f32],
25808    right: &[f32],
25809    pool: Option<&Pool>,
25810) {
25811    const TILE: usize = 32;
25812    let tiles = m.div_ceil(TILE);
25813    let cp = SendMut(c.as_mut_ptr());
25814    let body = |ti: usize| {
25815        let cp = &cp;
25816        let i0 = ti * TILE;
25817        let i1 = (i0 + TILE).min(m);
25818        for t in 0..b {
25819            let r = &right[t * n..t * n + n];
25820            for i in i0..i1 {
25821                let a = left[i * b + t];
25822                if a == 0.0 {
25823                    continue;
25824                }
25825                // SAFETY: tiles partition c's rows; workers never overlap.
25826                let row = unsafe { std::slice::from_raw_parts_mut(cp.0.add(i * n), n) };
25827                for (o, v) in row.iter_mut().zip(r) {
25828                    *o += a * *v;
25829                }
25830            }
25831        }
25832    };
25833    match pool {
25834        Some(p) if tiles > 1 => p.run_rows(tiles, &|s, e| {
25835            for ti in s..e {
25836                body(ti);
25837            }
25838        }),
25839        _ => {
25840            for ti in 0..tiles {
25841                body(ti);
25842            }
25843        }
25844    }
25845}
25846
25847/// Write what the calibration accumulated: `gss.<L>.f32` and `ya.<L>.f32`.
25848pub fn refit_flush() -> usize {
25849    let Some((dir, map)) = refit_dir() else {
25850        return 0;
25851    };
25852    let guard = map.lock().unwrap();
25853    let mut n = 0;
25854    for (li, acc) in guard.0.iter() {
25855        // A silently truncated write here is a Gram that reshapes to
25856        // nothing an hour later — say it out loud instead.
25857        let w = |name: &str, v: &[f32]| {
25858            let path = format!("{dir}/{name}.{li}.f32");
25859            let bytes: Vec<u8> = v.iter().flat_map(|x| x.to_le_bytes()).collect();
25860            match std::fs::write(&path, &bytes) {
25861                Ok(()) => {}
25862                Err(e) => eprintln!(
25863                    "refit: FAILED to write {path} ({} MB): {e}",
25864                    bytes.len() / 1_000_000
25865                ),
25866            }
25867        };
25868        w("gss", &acc.gss);
25869        w("ya", &acc.ya);
25870        println!(
25871            "refit L{li}: {} support, {} tokens, hidden {}",
25872            acc.support.len(),
25873            acc.tokens,
25874            acc.hidden
25875        );
25876        n += 1;
25877    }
25878    n
25879}
25880
25881/// `CMF_FFN_ADUMP=<prefix>` — append every probed token's FFN activation
25882/// row to `<prefix>.<layer>.f16`. The co-activation record: which
25883/// neurons fire together, which is what a tube has to group if a token
25884/// is ever going to open one tube instead of sixteen.
25885fn adump_row(li: usize, g: &[f32]) {
25886    use std::io::Write as _;
25887    static FILES: std::sync::OnceLock<
25888        Option<(
25889            String,
25890            std::sync::Mutex<std::collections::HashMap<usize, std::fs::File>>,
25891        )>,
25892    > = std::sync::OnceLock::new();
25893    let Some((prefix, map)) = FILES
25894        .get_or_init(|| {
25895            std::env::var("CMF_FFN_ADUMP")
25896                .ok()
25897                .map(|p| (p, std::sync::Mutex::new(std::collections::HashMap::new())))
25898        })
25899        .as_ref()
25900    else {
25901        return;
25902    };
25903    // `CMF_FFN_ADUMP_FROM/_TO` narrow the dump to a layer span, so a big
25904    // calibration run fits on disk in a few passes instead of one.
25905    static SPAN: std::sync::OnceLock<(usize, usize)> = std::sync::OnceLock::new();
25906    let (from, to) = *SPAN.get_or_init(|| {
25907        let g = |k: &str, d: usize| {
25908            std::env::var(k)
25909                .ok()
25910                .and_then(|v| v.parse().ok())
25911                .unwrap_or(d)
25912        };
25913        (
25914            g("CMF_FFN_ADUMP_FROM", 0),
25915            g("CMF_FFN_ADUMP_TO", usize::MAX),
25916        )
25917    });
25918    if li < from || li > to {
25919        return;
25920    }
25921    let mut map = map.lock().unwrap();
25922    let f = map.entry(li).or_insert_with(|| {
25923        std::fs::File::create(format!("{prefix}.{li}.f16")).expect("adump file")
25924    });
25925    let mut bytes = Vec::with_capacity(g.len() * 2);
25926    for v in g {
25927        bytes.extend_from_slice(&cortiq_core::quant::f32_to_f16(*v).to_le_bytes());
25928    }
25929    let _ = f.write_all(&bytes);
25930}
25931
25932/// `CMF_FFN_ORACLE_TOPK` — keep only the k largest |silu(g)·u| of each
25933/// token and zero the rest. Not a serving mode: it is the CEILING of
25934/// contextual sparsity — what a per-token router would be chasing —
25935/// measured by cheating, since the selection reads the very activations
25936/// it would have to predict.
25937fn oracle_topk() -> usize {
25938    if exact_mtp_calibration_active() {
25939        return 0;
25940    }
25941    static K: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
25942    *K.get_or_init(|| {
25943        std::env::var("CMF_FFN_ORACLE_TOPK")
25944            .ok()
25945            .and_then(|v| v.parse().ok())
25946            .unwrap_or(0)
25947    })
25948}
25949
25950/// `CMF_FFN_GATE_TOPK` — the REALIZABLE cousin of the oracle: rank the
25951/// neurons by their gate alone (which the kernel has computed anyway
25952/// before it reads `up`), keep the k best, and drop the rest. Every
25953/// dropped neuron's `up` row and `down` column stay unread, so this is
25954/// the sparsity a serving path can actually take without a router.
25955fn gate_topk() -> usize {
25956    if exact_mtp_calibration_active() {
25957        return 0;
25958    }
25959    static K: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
25960    *K.get_or_init(|| {
25961        std::env::var("CMF_FFN_GATE_TOPK")
25962            .ok()
25963            .and_then(|v| v.parse().ok())
25964            .unwrap_or(0)
25965    })
25966}
25967
25968/// `CMF_FFN_GATE_BLOCK` — select in blocks of B neurons instead of one
25969/// by one. A scattered per-neuron choice cannot be read efficiently (a
25970/// row at a time, no prefetch runway); a block of 32 is a contiguous
25971/// 32-row slab of `up` and of the transposed `down`, which the ordinary
25972/// kernels stream. The question the measurement answers is what the
25973/// block costs in quality.
25974fn gate_block() -> usize {
25975    static B: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
25976    *B.get_or_init(|| {
25977        std::env::var("CMF_FFN_GATE_BLOCK")
25978            .ok()
25979            .and_then(|v| v.parse().ok())
25980            .unwrap_or(1)
25981    })
25982}
25983
25984/// Zero all but the `k` largest BLOCKS (by summed square) of a row.
25985fn keep_top_blocks(g: &mut [f32], keep_n: usize, block: usize) {
25986    let n = g.len();
25987    let nb = n.div_ceil(block);
25988    let kb = (keep_n.div_ceil(block)).clamp(1, nb);
25989    if kb >= nb {
25990        return;
25991    }
25992    let mut score: Vec<f32> = (0..nb)
25993        .map(|b| {
25994            g[b * block..((b + 1) * block).min(n)]
25995                .iter()
25996                .map(|v| v * v)
25997                .sum::<f32>()
25998        })
25999        .collect();
26000    let mut ord = score.clone();
26001    let (_, kth, _) = ord.select_nth_unstable_by(kb - 1, |a, b| {
26002        b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
26003    });
26004    let thr = *kth;
26005    for b in 0..nb {
26006        if score[b] < thr {
26007            g[b * block..((b + 1) * block).min(n)].fill(0.0);
26008        }
26009    }
26010    score.clear();
26011}
26012
26013/// Zero all but the `k` largest magnitudes of one token's activation row.
26014fn keep_top_k(g: &mut [f32], k: usize) {
26015    if gate_block() > 1 {
26016        return keep_top_blocks(g, k, gate_block());
26017    }
26018    let n = g.len();
26019    if k == 0 || k >= n {
26020        return;
26021    }
26022    let mut mag: Vec<f32> = g.iter().map(|v| v.abs()).collect();
26023    let (_, kth, _) = mag.select_nth_unstable_by(k - 1, |a, b| {
26024        b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
26025    });
26026    let thr = *kth;
26027    for v in g.iter_mut() {
26028        if v.abs() < thr {
26029            *v = 0.0;
26030        }
26031    }
26032}
26033
26034/// `CMF_FFN_PROBE_SQ` — accumulate Σa², so the dump divided by the token
26035/// count and square-rooted is the RMS activation trace Patent 12 weights
26036/// its matrices by.
26037fn probe_sq() -> bool {
26038    static S: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
26039    *S.get_or_init(|| std::env::var("CMF_FFN_PROBE_SQ").is_ok())
26040}
26041
26042/// `CMF_FFN_PROBE_SIGNED` — accumulate the SIGNED activation sum
26043/// instead of its magnitude: what a dropped neuron contributes ON
26044/// AVERAGE, which is the bias a narrowed FFN can add back for free.
26045fn probe_signed() -> bool {
26046    static S: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
26047    *S.get_or_init(|| std::env::var("CMF_FFN_PROBE_SIGNED").is_ok())
26048}
26049
26050/// `CMF_FFN_MEANFILL=<file>` — a masked-out neuron contributes its MEAN
26051/// activation instead of zero (`u32 layers, u32 inter, f32[…]`, the mass
26052/// dump layout, holding per-neuron means). Dropping a neuron outright
26053/// also drops its average contribution, which shifts the layer output by
26054/// a constant; filling the mean back is one add per layer and costs no
26055/// bytes off the bus. This is the measurement arm — in a tube file the
26056/// same correction ships as a per-task bias vector.
26057fn meanfill() -> Option<&'static (usize, Vec<f32>)> {
26058    static M: std::sync::OnceLock<Option<(usize, Vec<f32>)>> = std::sync::OnceLock::new();
26059    M.get_or_init(|| {
26060        let p = std::env::var("CMF_FFN_MEANFILL").ok()?;
26061        let b = std::fs::read(&p).ok()?;
26062        let inter = u32::from_le_bytes(b[4..8].try_into().ok()?) as usize;
26063        let vals: Vec<f32> = b[8..]
26064            .chunks_exact(4)
26065            .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
26066            .collect();
26067        eprintln!("meanfill: {} value(s), inter {inter}", vals.len());
26068        Some((inter, vals))
26069    })
26070    .as_ref()
26071}
26072
26073/// `CMF_FFN_PROBE_TOPK` — 0 (default) = accumulate mass, k>0 = count
26074/// how often a neuron lands in a token's top k.
26075fn probe_topk() -> usize {
26076    static K: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
26077    *K.get_or_init(|| {
26078        std::env::var("CMF_FFN_PROBE_TOPK")
26079            .ok()
26080            .and_then(|v| v.parse().ok())
26081            .unwrap_or(0)
26082    })
26083}
26084
26085thread_local! {
26086    /// DTG-MA activation probe: per-layer per-neuron Σ|silu(g)·u|
26087    /// accumulator, alive only during `Pipeline::probe_ffn_mass`.
26088    static FFN_PROBE: std::cell::RefCell<Option<Vec<Vec<f64>>>> =
26089        const { std::cell::RefCell::new(None) };
26090}
26091
26092/// Hot-neuron probe of a MoE layer's routed experts (`cortiq hot-probe --experts`):
26093/// per layer, per expert and neuron, Σ (w·act)² over the tokens the router sent
26094/// there, `w` the expert's final weight — what the neuron's down column sees.
26095pub(crate) struct MoeProbe {
26096    /// `[layer][expert · inter + neuron]`; a layer without experts keeps an empty row.
26097    acc: Vec<Vec<f64>>,
26098    inter: usize,
26099    /// The routed expert `dense_ffn` is running for, and its weight; `None`
26100    /// outside the routed loop (the shared expert is not probed).
26101    cur: Option<(usize, f32)>,
26102}
26103
26104thread_local! {
26105    /// Alive only during `Pipeline::probe_moe_mass`.
26106    static MOE_PROBE: std::cell::RefCell<Option<MoeProbe>> = const { std::cell::RefCell::new(None) };
26107}
26108
26109fn moe_probe_active() -> bool {
26110    MOE_PROBE.with(|p| p.borrow().is_some())
26111}
26112
26113/// Per-token structured sparsity, paid for in bytes.
26114///
26115/// The gate is the cheapest third of an FFN and it already says which
26116/// neurons matter: `silu(gate)` near zero means the neuron contributes
26117/// nothing whatever `up` says. So compute every gate, keep the `k`
26118/// loudest, and read ONLY those neurons' `up` rows and `down` rows —
26119/// the latter needs `down_proj` stored transposed, otherwise a neuron's
26120/// down weights are a strided column and "reading only those" costs a
26121/// full cache line each.
26122///
26123/// Returns `None` when the file has no transposed `down` (the caller
26124/// then runs the ordinary dense path).
26125fn dense_ffn_dynamic(d: &DenseFfn, x: &[f32], pool: Option<&Pool>, k: usize) -> Option<Vec<f32>> {
26126    // The scatter path reads individual rows/columns and cannot express the
26127    // per-matrix signed FWHT boundary.  Let the descriptor-aware dense path
26128    // handle Prism files rather than silently running an unrotated sparse
26129    // approximation.
26130    if d.gate_proj.has_prism_contract()
26131        || d.up_proj.has_prism_contract()
26132        || d.down_proj.has_prism_contract()
26133    {
26134        return None;
26135    }
26136    let dt = d.down_t.as_ref()?;
26137    let inter = d.gate_proj.rows();
26138    let hidden = dt.cols();
26139    if k == 0 || k >= inter || d.act != Act::Silu {
26140        return None;
26141    }
26142    DYN_SCRATCH.with(|sc| {
26143        let mut sc = sc.borrow_mut();
26144        let DynScratch {
26145            g,
26146            mag,
26147            live,
26148            parts,
26149        } = &mut *sc;
26150        g.resize(inter, 0.0);
26151        d.gate_proj.matvec(x, g, pool);
26152        for v in g.iter_mut() {
26153            *v = inference::silu(*v);
26154        }
26155        // The k-th largest |silu(gate)| is the threshold; ties keep more,
26156        // which is the safe side.
26157        mag.clear();
26158        mag.extend(g.iter().map(|v| v.abs()));
26159        let (_, kth, _) = mag.select_nth_unstable_by(k - 1, |a, b| {
26160            b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
26161        });
26162        let thr = *kth;
26163        live.clear();
26164        live.extend((0..inter as u32).filter(|&n| g[n as usize].abs() >= thr));
26165        let mut out = vec![0.0f32; hidden];
26166        match pool {
26167            Some(p) if live.len() >= 64 => {
26168                let nw = p.n_workers() + 1;
26169                parts.clear();
26170                parts.resize(nw * hidden, 0.0);
26171                let ptr = SendMut(parts.as_mut_ptr());
26172                let n = live.len();
26173                let live_ref: &[u32] = live;
26174                let g_ref: &[f32] = g;
26175                p.run(&|w, workers| {
26176                    let chunk = n.div_ceil(workers);
26177                    let (s, e) = (w * chunk, ((w + 1) * chunk).min(n));
26178                    if s >= e {
26179                        return;
26180                    }
26181                    WORKER_SCRATCH.with(|ws| {
26182                        let mut ws = ws.borrow_mut();
26183                        let [scratch, acc] = &mut *ws;
26184                        scratch.resize(hidden.max(x.len()), 0.0);
26185                        acc.clear();
26186                        acc.resize(hidden, 0.0);
26187                        for (o, &nrm) in live_ref[s..e].iter().enumerate() {
26188                            // One neuron of runway: the next row's lines
26189                            // start moving while this one is multiplied.
26190                            if let Some(&nx) = live_ref[s..e].get(o + 1) {
26191                                d.up_proj.prefetch_row(nx as usize);
26192                                dt.prefetch_row(nx as usize);
26193                            }
26194                            let idx = nrm as usize;
26195                            let up = d.up_proj.row_dot(idx, x, scratch);
26196                            let a = g_ref[idx] * up;
26197                            if a != 0.0 {
26198                                dt.add_row_scaled(idx, a, acc, scratch);
26199                            }
26200                        }
26201                        for (j, v) in acc.iter().enumerate() {
26202                            unsafe { *ptr.at(w * hidden + j) = *v };
26203                        }
26204                    });
26205                });
26206                for w in 0..nw {
26207                    for (j, o) in out.iter_mut().enumerate() {
26208                        *o += parts[w * hidden + j];
26209                    }
26210                }
26211            }
26212            _ => {
26213                WORKER_SCRATCH.with(|ws| {
26214                    let mut ws = ws.borrow_mut();
26215                    let [scratch, _acc] = &mut *ws;
26216                    scratch.resize(hidden.max(x.len()), 0.0);
26217                    for &nrm in live.iter() {
26218                        let idx = nrm as usize;
26219                        let up = d.up_proj.row_dot(idx, x, scratch);
26220                        let a = g[idx] * up;
26221                        if a != 0.0 {
26222                            dt.add_row_scaled(idx, a, &mut out, scratch);
26223                        }
26224                    }
26225                });
26226            }
26227        }
26228        Some(out)
26229    })
26230}
26231
26232/// Caller-side scratch of the dynamic path — one allocation per thread,
26233/// not one per layer per token (that alone cost a third of the decode).
26234struct DynScratch {
26235    g: Vec<f32>,
26236    mag: Vec<f32>,
26237    live: Vec<u32>,
26238    parts: Vec<f32>,
26239}
26240
26241thread_local! {
26242    static DYN_SCRATCH: std::cell::RefCell<DynScratch> = const {
26243        std::cell::RefCell::new(DynScratch {
26244            g: Vec::new(),
26245            mag: Vec::new(),
26246            live: Vec::new(),
26247            parts: Vec::new(),
26248        })
26249    };
26250    /// Pool-worker scratch: the row buffer and this worker's partial sum.
26251    static WORKER_SCRATCH: std::cell::RefCell<[Vec<f32>; 2]> =
26252        const { std::cell::RefCell::new([Vec::new(), Vec::new()]) };
26253}
26254
26255/// `dense_ffn_cpu` with a per-visit mask landing on the activations —
26256/// the masked-inference fast path's decode arm. Full fused quant
26257/// compute, closed neurons zeroed before down: arithmetically the
26258/// pruned network, no dequant, no weight bytes touched.
26259fn dense_ffn_masked(d: &DenseFfn, x: &[f32], pool: Option<&Pool>, mask_row: &[u8]) -> Vec<f32> {
26260    let inter = d.gate_proj.rows();
26261    FFN_SCRATCH.with(|s| {
26262        let mut s = s.borrow_mut();
26263        let [g, u, ..] = &mut *s;
26264        g.resize(inter, 0.0);
26265        if d.act == Act::Silu && QTensor::matvec_silu_mul(&d.gate_proj, &d.up_proj, x, g, pool) {
26266            // g holds silu(gate)·up.
26267        } else {
26268            u.resize(inter, 0.0);
26269            QTensor::matvec_many([&d.gate_proj, &d.up_proj], x, [g, u], pool);
26270            for i in 0..inter {
26271                g[i] = d.act.combine(g[i], u[i]);
26272            }
26273        }
26274        zero_masked_cols(g, 1, inter, mask_row);
26275        let mut out = attention::take_buf(d.down_proj.rows());
26276        d.down_proj.matvec(g, &mut out, pool);
26277        out
26278    })
26279}
26280
26281/// Dense FFN as one GPU submission via the MoE block path (single
26282/// expert, weight 1.0): gate → silu·up → down chained in one command
26283/// buffer, intermediate activations device-resident. None → weights
26284/// not q8-mapped in the primary shard / over the VRAM budget / backend
26285/// refusal → honest CPU path.
26286fn dense_ffn_gpu(d: &DenseFfn, x: &[f32], _pool: Option<&Pool>) -> Option<Vec<f32>> {
26287    if d.gate_proj.has_prism_contract()
26288        || d.up_proj.has_prism_contract()
26289        || d.down_proj.has_prism_contract()
26290    {
26291        return None;
26292    }
26293    // The GPU block applies the standard graph activations plus the exact
26294    // MiniMax-M3 OAI contract; any other activation stays on the CPU.
26295    d.act.moe_job_graph_contract()?;
26296    // Threshold: tiny FFNs are not worth a submission (q1 excepted —
26297    // see the caller's gate).
26298    if d.gate_proj.rows() < crate::gpu::min_rows() && !d.gate_proj.is_q1() {
26299        return None;
26300    }
26301    let mut jobs: Vec<crate::gpu::MoeJob> = Vec::with_capacity(1);
26302    let mut model_ref = None;
26303    moe_push_job(d, x, 1.0, &mut jobs, &mut model_ref)?;
26304    let model = model_ref?;
26305    let hidden = jobs[0].down.1;
26306    let mut out = attention::take_buf(hidden);
26307    if crate::gpu::moe_block(&model, &jobs, &mut out) {
26308        Some(out)
26309    } else {
26310        let mut out = out;
26311        attention::recycle_buf(&mut out);
26312        None
26313    }
26314}
26315
26316/// q8-mapped primary-shard tensor parts for a GPU job: q8_2f carries
26317/// its column field, q8_row runs with empty col slices (the backend
26318/// skips the multiply). Shared by the MoE block and the dense-FFN
26319/// single-job path.
26320#[allow(clippy::type_complexity)]
26321#[allow(clippy::type_complexity)]
26322pub(crate) fn moe_parts(
26323    t: &QTensor,
26324) -> Option<(
26325    &std::sync::Arc<cortiq_core::CmfModel>,
26326    usize,
26327    usize,
26328    usize,
26329    &[f32],
26330    &[f32],
26331    bool,
26332    bool,
26333    bool,
26334)> {
26335    match t {
26336        QTensor::Mapped {
26337            model,
26338            idx,
26339            dtype: dt @ (cortiq_core::TensorDtype::Q8_2f | cortiq_core::TensorDtype::Q8Row),
26340            rows,
26341            cols,
26342            row_scale,
26343            col_field,
26344            ..
26345        } if (*dt == cortiq_core::TensorDtype::Q8Row) || !col_field.is_empty() => Some((
26346            model, *idx, *rows, *cols, row_scale, col_field, false, false, false,
26347        )),
26348        // q1: tile-embedded scales — empty rs/col slices, raw xs.
26349        QTensor::Mapped {
26350            model,
26351            idx,
26352            dtype: cortiq_core::TensorDtype::Q1,
26353            rows,
26354            cols,
26355            ..
26356        } => Some((
26357            model,
26358            *idx,
26359            *rows,
26360            *cols,
26361            &[][..],
26362            &[][..],
26363            true,
26364            false,
26365            false,
26366        )),
26367        // q4_tiled: 18-byte tiles with embedded f16 scales — raw xs.
26368        QTensor::Mapped {
26369            model,
26370            idx,
26371            dtype: cortiq_core::TensorDtype::Q4Tiled,
26372            rows,
26373            cols,
26374            ..
26375        } => Some((
26376            model,
26377            *idx,
26378            *rows,
26379            *cols,
26380            &[][..],
26381            &[][..],
26382            false,
26383            true,
26384            false,
26385        )),
26386        // q4tp: same raw-xs contract, different stride and scale plane.
26387        QTensor::Mapped {
26388            model,
26389            idx,
26390            dtype: cortiq_core::TensorDtype::Q4TiledP,
26391            rows,
26392            cols,
26393            ..
26394        } => Some((
26395            model,
26396            *idx,
26397            *rows,
26398            *cols,
26399            &[][..],
26400            &[][..],
26401            false,
26402            true,
26403            false,
26404        )),
26405        // q2tp: the 2-bit expert plane of the mixed profile — q4 family
26406        // for stride bookkeeping, flagged q2 so the trio validation can
26407        // demand a q4tp down.
26408        QTensor::Mapped {
26409            model,
26410            idx,
26411            dtype: cortiq_core::TensorDtype::Q2TiledP,
26412            rows,
26413            cols,
26414            ..
26415        } => Some((
26416            model,
26417            *idx,
26418            *rows,
26419            *cols,
26420            &[][..],
26421            &[][..],
26422            false,
26423            true,
26424            true,
26425        )),
26426        _ => None,
26427    }
26428}
26429
26430/// The routed experts of a MoE layer as the Metal chunk prefill takes
26431/// them: f32 router rows and every expert's q4tp (gate, up, down) tensor
26432/// indices, uniform SiLU shapes. Only the plain routed form — no shared
26433/// expert, no per-expert scale, no resonance or τ router, no router input
26434/// norm; the batched host walk keeps the rest. The routing itself stays the
26435/// host's (`moe_route`), so mask and selection bias need nothing here.
26436#[cfg(target_os = "macos")]
26437#[allow(clippy::type_complexity)]
26438fn chunk_moe_parts(
26439    m: &MoeFfn,
26440    hidden: usize,
26441) -> Option<(&[f32], Vec<(usize, usize, usize)>, bool)> {
26442    // Only a shared expert of its own width, without a gate: it adds to the
26443    // routed mix (`ChunkMoe::detached`).
26444    if m.shared.as_ref().is_some_and(|(s, g)| {
26445        g.is_some()
26446            || m.experts.is_empty()
26447            || s.gate_proj.rows() == m.experts[0].gate_proj.rows()
26448            || !(s.gate_proj.q8_2f_parts().is_some() || s.gate_proj.q4tp_parts().is_some())
26449            || !(s.up_proj.q8_2f_parts().is_some() || s.up_proj.q4tp_parts().is_some())
26450            || !(s.down_proj.q8_2f_parts().is_some() || s.down_proj.q4tp_parts().is_some())
26451    }) || m.per_expert_scale.is_some()
26452        || m.resonance.is_some()
26453        || m.route_tau.is_some()
26454        || m.router_input_norm
26455        || m.experts.is_empty()
26456        || m.top_k == 0
26457        || std::env::var("CMF_RMS_TRACE").is_ok()
26458        || std::env::var("CMF_ACT_DUMP").is_ok()
26459        || std::env::var("CMF_METAL_MOE_PREFILL").as_deref() == Ok("0")
26460    {
26461        return None;
26462    }
26463    let (rf, rr, rc) = m.router.f32_parts()?;
26464    if rr != m.experts.len() || rc != hidden {
26465        return None;
26466    }
26467    let inter = m.experts[0].gate_proj.rows();
26468    // All-q8_2f experts (Mellum2.1 q8_2f) ride the `moe_q8` GEMMs;
26469    // `CMF_METAL_MOE_Q8=0` keeps them on the host walk.
26470    let q8 = crate::gpu_metal::moe_q8::enabled() && m.experts[0].gate_proj.q8_2f_parts().is_some();
26471    let experts = m
26472        .experts
26473        .iter()
26474        .map(|e| {
26475            if e.act != Act::Silu
26476                || !e.segs.is_empty()
26477                || e.gate_proj.rows() != inter
26478                || e.up_proj.rows() != inter
26479                || e.down_proj.cols() != inter
26480                || e.gate_proj.cols() != hidden
26481                || e.down_proj.rows() != hidden
26482            {
26483                return None;
26484            }
26485            if q8 {
26486                let q8i = |t: &QTensor| t.q8_2f_parts().map(|p| p.0);
26487                return Some((q8i(&e.gate_proj)?, q8i(&e.up_proj)?, q8i(&e.down_proj)?));
26488            }
26489            Some((
26490                e.gate_proj.mapped_q4tp()?.1,
26491                e.up_proj.mapped_q4tp()?.1,
26492                e.down_proj.mapped_q4tp()?.1,
26493            ))
26494        })
26495        .collect::<Option<Vec<_>>>()?;
26496    Some((rf, experts, q8))
26497}
26498
26499/// Map a MoE onto the Metal token graph's contract: f32 router, a
26500/// shared expert (gated — Qwen — or ungated at weight 1 — DeepSeek-V3 /
26501/// HunYuan hy_v3), softmax or sigmoid scores with an optional selection
26502/// bias and routed scale, experts uniformly q4tp (or the mixed profile:
26503/// q2tp gate/up over a q4tp down). τ routers, masks, per-expert scales
26504/// and Gemma's router-input norm refuse here — those semantics stay on
26505/// the CPU path.
26506/// Map Flint's released ragged MoE into the native page graph.  This stays
26507/// separate from `metal_moe_graph_parts`: its six routed slots are Q2TP and
26508/// 512-wide, while its ungated shared SwiGLU is Q4TP and 1024-wide.  Feeding
26509/// the shared tuple into the uniform jobs descriptor would make the shader
26510/// use the routed stride on a different payload.
26511#[cfg(target_os = "macos")]
26512fn metal_flint_moe_graph_parts(
26513    m: &MoeFfn,
26514    hidden: usize,
26515    scratch_key: usize,
26516) -> Option<crate::gpu::GpuFlintMoe<'_>> {
26517    use std::sync::Arc;
26518
26519    const HIDDEN: usize = 2_048;
26520    const ROUTED_INTER: usize = 512;
26521    const SHARED_INTER: usize = 1_024;
26522    const EXPERTS: usize = 256;
26523    const TOP_K: usize = 6;
26524
26525    if hidden != HIDDEN || !strict_flint_metal_pager_candidate(m) {
26526        return None;
26527    }
26528    let routed0 = m.experts.first()?;
26529    let (model, _) = routed0.gate_proj.mapped_q2tp()?;
26530    let (router, router_rows, router_cols) = m.router.f32_parts()?;
26531    if router_rows != EXPERTS || router_cols != HIDDEN {
26532        return None;
26533    }
26534    if m.expert_bias.as_ref().is_some_and(|b| b.len() != EXPERTS) {
26535        return None;
26536    }
26537    let same_q2 = |t: &QTensor| -> Option<usize> {
26538        let (owner, idx) = t.mapped_q2tp()?;
26539        Arc::ptr_eq(&owner, &model).then_some(idx)
26540    };
26541    let same_q4 = |t: &QTensor| -> Option<usize> {
26542        let (owner, idx) = t.mapped_q4tp()?;
26543        Arc::ptr_eq(&owner, &model).then_some(idx)
26544    };
26545    let routed = |e: &DenseFfn| -> Option<(usize, usize, usize)> {
26546        if e.act != Act::Silu
26547            || !e.segs.is_empty()
26548            || e.gate_proj.rows() != ROUTED_INTER
26549            || e.gate_proj.cols() != HIDDEN
26550            || e.up_proj.rows() != ROUTED_INTER
26551            || e.up_proj.cols() != HIDDEN
26552            || e.down_proj.rows() != HIDDEN
26553            || e.down_proj.cols() != ROUTED_INTER
26554        {
26555            return None;
26556        }
26557        Some((
26558            same_q2(&e.gate_proj)?,
26559            same_q2(&e.up_proj)?,
26560            same_q4(&e.down_proj)?,
26561        ))
26562    };
26563    let shared = |e: &DenseFfn| -> Option<(usize, usize, usize)> {
26564        if e.act != Act::Silu
26565            || !e.segs.is_empty()
26566            || e.gate_proj.rows() != SHARED_INTER
26567            || e.gate_proj.cols() != HIDDEN
26568            || e.up_proj.rows() != SHARED_INTER
26569            || e.up_proj.cols() != HIDDEN
26570            || e.down_proj.rows() != HIDDEN
26571            || e.down_proj.cols() != SHARED_INTER
26572        {
26573            return None;
26574        }
26575        Some((
26576            same_q4(&e.gate_proj)?,
26577            same_q4(&e.up_proj)?,
26578            same_q4(&e.down_proj)?,
26579        ))
26580    };
26581    let experts = m.experts.iter().map(routed).collect::<Option<Vec<_>>>()?;
26582    if experts.len() != EXPERTS {
26583        return None;
26584    }
26585    let (shared_ffn, shared_gate) = m.shared.as_ref()?;
26586    if shared_gate.is_some() {
26587        return None;
26588    }
26589    Some(crate::gpu::GpuFlintMoe {
26590        router,
26591        bias: m.expert_bias.as_deref(),
26592        experts,
26593        scratch_key,
26594        shared: shared(shared_ffn)?,
26595        top_k: m.top_k,
26596        norm_topk: m.norm_topk_prob,
26597        route_scale: m.routed_scaling,
26598        sigmoid: m.router_sigmoid,
26599        sigmoid_denom_eps: m.sigmoid_denom_eps,
26600    })
26601}
26602
26603#[cfg(target_os = "macos")]
26604fn metal_moe_graph_parts(m: &MoeFfn, hidden: usize) -> Option<crate::gpu::GpuMoe<'_>> {
26605    if m.router_input_norm
26606        || m.route_tau.is_some()
26607        || m.mask.is_some()
26608        || m.per_expert_scale.is_some()
26609        || m.experts.is_empty()
26610        || m.top_k == 0
26611        || m.resonance.is_some()
26612    {
26613        return None;
26614    }
26615    // An ungated shared expert of its own width stays out of the jobs ladder:
26616    // it runs after the routed mix (`GpuMoe::detached`).
26617    let detached = m.shared.as_ref().filter(|(s, g)| {
26618        g.is_none() && !m.router_sigmoid && s.gate_proj.rows() != m.experts[0].gate_proj.rows()
26619    });
26620    // Without a shared expert the select kernel fills the k routed jobs
26621    // only (flag 32). Measured on Mellum2.1's softmax router; the sigmoid /
26622    // biased routers without one (LFM2-MoE) keep the CPU path until they
26623    // are measured too.
26624    let (sh, sg) = match &m.shared {
26625        Some((sh, sg)) if detached.is_none() => (Some(sh), sg.as_ref()),
26626        _ if !m.router_sigmoid && m.expert_bias.is_none() => (None, None),
26627        _ => return None,
26628    };
26629    let (rf, rr, rc) = m.router.f32_parts()?;
26630    if rr != m.experts.len() || rc != hidden {
26631        return None;
26632    }
26633    let shared_gated = sg.is_some();
26634    let sf = match sg {
26635        Some(sg) => {
26636            let (sf, sr, sc) = sg.f32_parts()?;
26637            if sr * sc != hidden {
26638                return None;
26639            }
26640            sf
26641        }
26642        // Ungated: the router's first row stands in for the gate matvec
26643        // (its logit is never read — the kernel pins weight 1).
26644        None => &rf[..hidden],
26645    };
26646    if let Some(b) = &m.expert_bias {
26647        if b.len() != m.experts.len() {
26648            return None;
26649        }
26650    }
26651    let inter = m.experts[0].gate_proj.rows();
26652    // The first expert's gate decides the profile; every trio (shared
26653    // included) must agree — the jobs ladder flips ONE kernel for all.
26654    let gu_q2 = m.experts[0].gate_proj.mapped_q2tp().is_some();
26655    // All-q8_2f routed experts (Mellum2.1 q8_2f: no shared expert, the
26656    // contract they were measured on) take the `moe_q8` kernels;
26657    // `CMF_METAL_MOE_Q8=0` keeps them off the graph (per-op path).
26658    let q8 = crate::gpu_metal::moe_q8::enabled()
26659        && (m.shared.is_none() || detached.is_some())
26660        && m.experts[0].gate_proj.q8_2f_parts().is_some();
26661    let trio = |e: &DenseFfn| -> Option<(usize, usize, usize)> {
26662        if e.act != Act::Silu
26663            || e.gate_proj.rows() != inter
26664            || e.gate_proj.cols() != hidden
26665            || e.up_proj.rows() != inter
26666            || e.up_proj.cols() != hidden
26667            || e.down_proj.rows() != hidden
26668            || e.down_proj.cols() != inter
26669        {
26670            return None;
26671        }
26672        if q8 {
26673            let q8i = |t: &QTensor| t.q8_2f_parts().map(|p| p.0);
26674            return Some((q8i(&e.gate_proj)?, q8i(&e.up_proj)?, q8i(&e.down_proj)?));
26675        }
26676        let pick = |t: &QTensor| -> Option<usize> {
26677            if gu_q2 {
26678                t.mapped_q2tp().map(|(_, i)| i)
26679            } else {
26680                t.mapped_q4tp().map(|(_, i)| i)
26681            }
26682        };
26683        Some((
26684            pick(&e.gate_proj)?,
26685            pick(&e.up_proj)?,
26686            e.down_proj.mapped_q4tp().map(|(_, i)| i)?,
26687        ))
26688    };
26689    let experts = m.experts.iter().map(trio).collect::<Option<Vec<_>>>()?;
26690    let shared = match sh {
26691        Some(sh) => Some(trio(sh)?),
26692        None => None,
26693    };
26694    let detached = match detached {
26695        Some((s, _)) => Some([
26696            s.gate_proj.metal_graph_parts()?,
26697            s.up_proj.metal_graph_parts()?,
26698            s.down_proj.metal_graph_parts()?,
26699        ]),
26700        None => None,
26701    };
26702    Some(crate::gpu::GpuMoe {
26703        router: rf,
26704        sgate: sf,
26705        experts,
26706        shared,
26707        n_exp: m.experts.len(),
26708        top_k: m.top_k,
26709        inter,
26710        norm_topk: m.norm_topk_prob,
26711        route_scale: m.routed_scaling,
26712        gu_q2,
26713        q8,
26714        sigmoid: m.router_sigmoid,
26715        sigmoid_denom_eps: m.sigmoid_denom_eps,
26716        bias: m.expert_bias.as_deref(),
26717        shared_gated,
26718        detached,
26719    })
26720}
26721
26722/// `CMF_FORCE_IDS=<file>` (diagnostics): decode step n commits the n-th
26723/// whitespace-separated token id of the file instead of sampling, while the
26724/// logits are still computed (and dumped by `CMF_LOGIT_DUMP_ALL`) — one
26725/// backend teacher-forced along another's greedy sequence, so top-1
26726/// agreement can be counted past a near-tie divergence.
26727fn forced_ids_at(step: usize) -> Option<u32> {
26728    static IDS: std::sync::OnceLock<Vec<u32>> = std::sync::OnceLock::new();
26729    IDS.get_or_init(|| {
26730        std::env::var("CMF_FORCE_IDS")
26731            .ok()
26732            .and_then(|p| std::fs::read_to_string(p).ok())
26733            .map(|s| {
26734                s.split_whitespace()
26735                    .filter_map(|t| t.parse().ok())
26736                    .collect()
26737            })
26738            .unwrap_or_default()
26739    })
26740    .get(step)
26741    .copied()
26742}
26743
26744/// Build one gate/up/down GPU job from three tensors. `moe_push_job` is the
26745/// DenseFfn-shaped caller; architectures that keep their experts in their own
26746/// structs (DeepSeek-V4) come here directly.
26747pub(crate) fn moe_push_job_parts<'a>(
26748    gate: &'a QTensor,
26749    up: &'a QTensor,
26750    down: &'a QTensor,
26751    x: &[f32],
26752    w: f32,
26753    swiglu_limit: f32,
26754    jobs: &mut Vec<crate::gpu::MoeJob<'a>>,
26755    model_ref: &mut Option<std::sync::Arc<cortiq_core::CmfModel>>,
26756) -> Option<()> {
26757    use crate::qtensor::prescale;
26758    let (gm, gi, gr, gc, grs, gcf, gq1, gq4, gq2) = moe_parts(gate)?;
26759    let (_, ui, ur, uc, urs, ucf, uq1, uq4, uq2) = moe_parts(up)?;
26760    let (_, di, dr, dc, drs, dcf, dq1, dq4, dq2) = moe_parts(down)?;
26761    if gq1 != uq1 || uq1 != dq1 || gq4 != uq4 || uq4 != dq4 || gq2 != uq2 {
26762        return None; // mixed-dtype trio — honest CPU path
26763    }
26764    // The 2-bit profile is gate/up q2tp over a PLAIN q4tp down; any other
26765    // 2-bit arrangement stays on the CPU.
26766    if gq2 && (dq2 || !dq4 || down.mapped_q4tp().is_none()) {
26767        return None;
26768    }
26769    if !gq2 && dq2 {
26770        return None;
26771    }
26772    model_ref.get_or_insert_with(|| gm.clone());
26773    let dt = |cf: &[f32]| {
26774        if cf.is_empty() {
26775            cortiq_core::TensorDtype::Q8Row
26776        } else {
26777            cortiq_core::TensorDtype::Q8_2f
26778        }
26779    };
26780    jobs.push(crate::gpu::MoeJob {
26781        gate: (gi, gr, gc, grs),
26782        up: (ui, ur, uc, urs),
26783        down: (di, dr, dc, drs),
26784        xs_gate: prescale(x, gcf, dt(gcf)).into_owned(),
26785        xs_up: prescale(x, ucf, dt(ucf)).into_owned(),
26786        down_col: dcf,
26787        w,
26788        q1: gq1,
26789        q4t: gq4 && !gq2 && gate.mapped_q4tp().is_none(),
26790        q4tp: gq4 && (gq2 || gate.mapped_q4tp().is_some()),
26791        gu_q2: gq2,
26792        swiglu_limit,
26793        act: 0,
26794    });
26795    Some(())
26796}
26797
26798/// Build one gate/up/down GPU job (see `moe_parts`).
26799fn moe_push_job<'a>(
26800    d: &'a DenseFfn,
26801    x: &[f32],
26802    w: f32,
26803    jobs: &mut Vec<crate::gpu::MoeJob<'a>>,
26804    model_ref: &mut Option<std::sync::Arc<cortiq_core::CmfModel>>,
26805) -> Option<()> {
26806    use crate::qtensor::prescale;
26807    // The block's act(gate)·up pass takes an exact device contract.  For
26808    // ordinary SiLU/GELU this is a zero clamp; MiniMax M3 contributes its
26809    // dedicated OAI marker and frozen 7.0 source limit.  Anything without a
26810    // device contract stays on the CPU.
26811    let (graph_act, swiglu_limit) = d.act.moe_job_graph_contract()?;
26812    let act = graph_act.code();
26813    let (gm, gi, gr, gc, grs, gcf, gq1, gq4, gq2) = moe_parts(&d.gate_proj)?;
26814    let (_, ui, ur, uc, urs, ucf, uq1, uq4, uq2) = moe_parts(&d.up_proj)?;
26815    let (_, di, dr, dc, drs, dcf, dq1, dq4, dq2) = moe_parts(&d.down_proj)?;
26816    if gq1 != uq1 || uq1 != dq1 || gq4 != uq4 || uq4 != dq4 || gq2 != uq2 {
26817        return None; // mixed-dtype trio — honest CPU path
26818    }
26819    if gq2 && (dq2 || !dq4 || d.down_proj.mapped_q4tp().is_none()) {
26820        return None;
26821    }
26822    if !gq2 && dq2 {
26823        return None;
26824    }
26825    model_ref.get_or_insert_with(|| gm.clone());
26826    let gdt = if gcf.is_empty() {
26827        cortiq_core::TensorDtype::Q8Row
26828    } else {
26829        cortiq_core::TensorDtype::Q8_2f
26830    };
26831    let udt = if ucf.is_empty() {
26832        cortiq_core::TensorDtype::Q8Row
26833    } else {
26834        cortiq_core::TensorDtype::Q8_2f
26835    };
26836    jobs.push(crate::gpu::MoeJob {
26837        gate: (gi, gr, gc, grs),
26838        up: (ui, ur, uc, urs),
26839        down: (di, dr, dc, drs),
26840        xs_gate: prescale(x, gcf, gdt).into_owned(),
26841        xs_up: prescale(x, ucf, udt).into_owned(),
26842        down_col: dcf,
26843        w,
26844        q1: gq1,
26845        q4t: gq4 && !gq2 && d.gate_proj.mapped_q4tp().is_none(),
26846        q4tp: gq4 && (gq2 || d.gate_proj.mapped_q4tp().is_some()),
26847        gu_q2: gq2,
26848        swiglu_limit,
26849        act,
26850    });
26851    Some(())
26852}
26853
26854/// Sparse dense-FFN directly on QUANTIZED weights (mask × mmap): reads
26855/// ONLY the active neurons' gate/up rows and down columns from the mmap
26856/// — no full-matrix dequant, no f32 model copy. This is what lets a
26857/// masked big model run at quantized RSS (the historical mask path
26858/// forced the whole model to f32). Semantics identical to the f32
26859/// sparse path within quant tolerance.
26860fn sparse_ffn_quant(
26861    d: &DenseFfn,
26862    x: &[f32],
26863    active: &[u16],
26864    hidden: usize,
26865    pool: Option<&Pool>,
26866) -> Vec<f32> {
26867    let n = active.len();
26868    let inter = d.gate_proj.rows();
26869    let mut act = vec![0.0f32; n];
26870    // Scratch is needed if EITHER projection is group-packed (q4/vbit);
26871    // gate/up normally share a dtype but sizing on both is robust.
26872    let need_scratch = !(d.gate_proj.sparse_col_ok() && d.up_proj.sparse_col_ok());
26873    let compute = |ai: usize| -> f32 {
26874        let idx = active[ai] as usize;
26875        if idx >= inter {
26876            return 0.0; // defensive parity with the f32 sparse path
26877        }
26878        let mut s = if need_scratch {
26879            vec![0.0f32; hidden]
26880        } else {
26881            Vec::new()
26882        };
26883        let gate = d.gate_proj.row_dot(idx, x, &mut s);
26884        let up = d.up_proj.row_dot(idx, x, &mut s);
26885        d.act.combine(gate, up)
26886    };
26887    match pool {
26888        Some(p) if n >= 256 => {
26889            let ptr = SendMut(act.as_mut_ptr());
26890            p.run(&|widx, nw| {
26891                let chunk = n.div_ceil(nw);
26892                let (s, e) = (widx * chunk, ((widx + 1) * chunk).min(n));
26893                for ai in s..e {
26894                    unsafe { *ptr.at(ai) = compute(ai) };
26895                }
26896            });
26897        }
26898        _ => {
26899            for (ai, a) in act.iter_mut().enumerate() {
26900                *a = compute(ai);
26901            }
26902        }
26903    }
26904    // Scatter through active down columns (reads only those columns).
26905    let mut out = vec![0.0f32; hidden];
26906    for (ai, &idx) in active.iter().enumerate() {
26907        let w = act[ai];
26908        if w.abs() >= 1e-12 && (idx as usize) < inter {
26909            d.down_proj.add_col_scaled(idx as usize, w, &mut out);
26910        }
26911    }
26912    out
26913}
26914
26915/// Test-only re-export of the private sparse-quant FFN (mask × mmap gate).
26916#[doc(hidden)]
26917pub fn sparse_ffn_quant_for_test(
26918    d: &DenseFfn,
26919    x: &[f32],
26920    active: &[u16],
26921    hidden: usize,
26922) -> Vec<f32> {
26923    sparse_ffn_quant(d, x, active, hidden, None)
26924}
26925
26926/// Dequantize a DenseFfn's three matrices to f32 (transient; only the
26927/// q4/vbit-masked fallback uses it — the memory-lean path is
26928/// sparse_ffn_quant). Reuses row_f32 row-by-row.
26929fn dequant_dense_f32(d: &DenseFfn) -> (Vec<f32>, Vec<f32>, Vec<f32>) {
26930    let deq = |t: &QTensor| -> Vec<f32> {
26931        let (rows, cols) = (t.rows(), t.cols());
26932        let mut out = vec![0.0f32; rows * cols];
26933        for r in 0..rows {
26934            t.row_f32(r, &mut out[r * cols..(r + 1) * cols]);
26935        }
26936        out
26937    };
26938    (deq(&d.gate_proj), deq(&d.up_proj), deq(&d.down_proj))
26939}
26940
26941/// Pointer wrapper for the worker-pool scatter (same pattern as qtensor).
26942struct SendMut(*mut f32);
26943unsafe impl Send for SendMut {}
26944unsafe impl Sync for SendMut {}
26945impl SendMut {
26946    #[inline]
26947    // Deliberate unsynchronized scatter: pool workers write disjoint indices
26948    // in parallel, so returning `&mut` from `&self` is intentional here.
26949    #[allow(clippy::mut_from_ref)]
26950    unsafe fn at(&self, i: usize) -> &mut f32 {
26951        unsafe { &mut *self.0.add(i) }
26952    }
26953}
26954
26955/// Router → (selected experts in torch.topk order, per-expert score
26956/// vector, normalizer). The final weight of expert `e` is `p[e] / wsum`.
26957///
26958/// Two regimes share this. Qwen: softmax over ALL experts, top-k of the
26959/// probabilities, optional renorm — `router_sigmoid=false`, no bias,
26960/// scale 1 → bit-identical to the historical path. LFM2-MoE /
26961/// DeepSeek-V3 `noaux_tc`: per-expert sigmoid scores, an optional
26962/// selection bias (top-k CHOICE only; weights stay unbiased), an
26963/// architecture-specified renorm floor and a routed scale.  The ordinary
26964/// loader contract is `1e-6`; Flint and MiniMax M3.1 preserve their
26965/// reference runtime's selected-score `sum + 1e-20`.
26966pub(crate) fn moe_route(
26967    logits: &[f32],
26968    m: &MoeFfn,
26969    allowed: Option<&[bool]>,
26970) -> (Vec<usize>, Vec<f32>, f32) {
26971    moe_route_with_eps(logits, m, allowed, m.sigmoid_denom_eps)
26972}
26973
26974/// Router implementation with an explicit sigmoid renormalization floor.
26975///
26976/// Flint and MiniMax M3.1 reference runtimes compute
26977/// `sum(selected_scores) + 1e-20` in FP32. Using the generic 1e-6 floor is
26978/// not a harmless tolerance difference when all logits are very negative: it
26979/// collapses the routed branch toward zero instead of normalizing the selected
26980/// experts. Keeping the epsilon parameter here avoids changing the established
26981/// Qwen/LFM2 contract while allowing each architecture to preserve its own
26982/// numerical semantics.
26983pub(crate) fn moe_route_with_eps(
26984    logits: &[f32],
26985    m: &MoeFfn,
26986    allowed: Option<&[bool]>,
26987    sigmoid_denom_eps: f32,
26988) -> (Vec<usize>, Vec<f32>, f32) {
26989    let ne = logits.len();
26990    // Expert restriction: the static env mask (CMF_MOE_MASK) AND the
26991    // active task mask's expert fields (spec §5) both narrow the
26992    // candidate set; selection happens over the admitted experts only.
26993    // With norm_topk the kept weights renormalize below; without it
26994    // the excluded mass is honestly dropped.
26995    let admit = |e: usize| {
26996        m.mask.as_ref().is_none_or(|mk| mk[e])
26997            && allowed.is_none_or(|a| a.get(e).copied().unwrap_or(false))
26998    };
26999    // The resonance router (spec §9.5.1) selects by the RAW score: the
27000    // trainer (`resonance_winner`) and the resident graph
27001    // (`embryo_core_route_pick`) take the first maximum of the scores
27002    // and run the winner with weight 1.0. Selecting through the softmax
27003    // instead is not the same decision: `exp(l − max)` rounds two scores
27004    // closer than 2^-25 (possible below |score| 0.25) to the same 1.0, and
27005    // the lower index would take a token whose score is strictly smaller
27006    // — the trainer's trace and the graph would disagree with this path.
27007    // `−∞` (outside the shell) never wins; with no finite admitted expert
27008    // the generic path below degrades to uniform. The winner's
27009    // probability is 1.0 by construction (a one-hot `p`), so its
27010    // renormalized weight is `routed_scaling` on both norm_topk settings.
27011    if m.resonance.is_some() && m.top_k == 1 {
27012        let mut best: Option<usize> = None;
27013        for e in (0..ne).filter(|&e| admit(e)) {
27014            let l = logits[e];
27015            if l == f32::NEG_INFINITY || l.is_nan() {
27016                continue;
27017            }
27018            if best.is_none_or(|b| l > logits[b]) {
27019                best = Some(e);
27020            }
27021        }
27022        if let Some(b) = best {
27023            let mut p = vec![0.0f32; ne];
27024            p[b] = 1.0;
27025            return (vec![b], p, 1.0 / m.routed_scaling);
27026        }
27027    }
27028    // A `−∞` logit (a grown expert outside its shell, `Resonance::scores`)
27029    // takes probability 0 on both paths: sigmoid(−∞) = 0, exp(−∞ − max) = 0
27030    // — top-1 is the best FINITE expert, its renormalized weight exactly
27031    // 1.0. Every expert at −∞ cannot happen (trunk experts have no shell);
27032    // should it, the softmax would be NaN, so it degrades to uniform.
27033    let p: Vec<f32> = if m.router_sigmoid {
27034        logits.iter().map(|&l| 1.0 / (1.0 + (-l).exp())).collect()
27035    } else {
27036        let mx = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
27037        if mx == f32::NEG_INFINITY {
27038            vec![1.0 / ne.max(1) as f32; ne]
27039        } else {
27040            let mut e: Vec<f32> = logits.iter().map(|&l| (l - mx).exp()).collect();
27041            let s: f32 = e.iter().sum();
27042            for v in &mut e {
27043                *v /= s;
27044            }
27045            e
27046        }
27047    };
27048    let mut idx: Vec<usize> = (0..ne).filter(|&e| admit(e)).collect();
27049    // Descending by selection score, lower index wins ties (torch.topk).
27050    match &m.expert_bias {
27051        Some(b) => idx.sort_unstable_by(|&x, &y| {
27052            (p[y] + b[y])
27053                .partial_cmp(&(p[x] + b[x]))
27054                .unwrap()
27055                .then(x.cmp(&y))
27056        }),
27057        None => idx.sort_unstable_by(|&x, &y| p[y].partial_cmp(&p[x]).unwrap().then(x.cmp(&y))),
27058    }
27059    idx.truncate(m.top_k);
27060    // Adaptive τ-routing: trim the tail experts once the kept mass is
27061    // enough. wsum below renormalizes over the KEPT set, so the output
27062    // stays a proper weighted average.
27063    if let Some(tau) = m.route_tau {
27064        let total: f32 = idx.iter().map(|&e| p[e]).sum();
27065        if total > 0.0 {
27066            let mut acc = 0.0f32;
27067            let mut keep = idx.len();
27068            for (i, &e) in idx.iter().enumerate() {
27069                acc += p[e];
27070                if acc >= tau * total {
27071                    keep = i + 1;
27072                    break;
27073                }
27074            }
27075            idx.truncate(keep);
27076        }
27077    }
27078    let wsum: f32 = if m.norm_topk_prob {
27079        let s: f32 = idx.iter().map(|&e| p[e]).sum();
27080        // Sigmoid routers use their architecture's reference floor; the
27081        // softmax path's probs already sum near 1, so it stays exactly as
27082        // before.
27083        (if m.router_sigmoid {
27084            s + sigmoid_denom_eps
27085        } else {
27086            s
27087        }) / m.routed_scaling
27088    } else {
27089        1.0 / m.routed_scaling
27090    };
27091    (idx, p, wsum)
27092}
27093
27094/// See the call site: one `layer:e1,e2,…` line per routed token.
27095fn moe_trace(idx: &[usize]) {
27096    moe_trace_at(crate::gpu::cur_layer() as i32, idx)
27097}
27098
27099/// The same, for callers that know their layer (DSV4 owns its layers and
27100/// never sets the pipeline's current-layer marker).
27101pub(crate) fn moe_trace_at(li: i32, idx: &[usize]) {
27102    use std::io::Write;
27103    static F: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
27104        std::sync::OnceLock::new();
27105    let Some(f) = F.get_or_init(|| {
27106        let p = std::env::var("CMF_MOE_TRACE").ok()?;
27107        Some(std::sync::Mutex::new(
27108            std::fs::OpenOptions::new()
27109                .create(true)
27110                .append(true)
27111                .open(p)
27112                .ok()?,
27113        ))
27114    }) else {
27115        return;
27116    };
27117    let ids: Vec<String> = idx.iter().map(|e| e.to_string()).collect();
27118    let _ = writeln!(f.lock().unwrap(), "{li}:{}", ids.join(","));
27119}
27120
27121/// MoE FFN: router → top-k experts (see `moe_route`). Only selected
27122/// experts' pages are touched in mmap.
27123pub(crate) fn moe_ffn(
27124    m: &MoeFfn,
27125    x: &[f32],
27126    pool: Option<&Pool>,
27127    allowed: Option<&[bool]>,
27128) -> Vec<f32> {
27129    let r = moe_ffn_route(m, x, pool, allowed);
27130    moe_ffn_experts(m, x, &r, pool)
27131}
27132
27133/// One token's host route through a MoE layer: the chosen experts in
27134/// selection order, the per-expert scores and the normalizer (see
27135/// `moe_route`), plus the raw router logits.
27136pub(crate) struct MoeRoute {
27137    pub idx: Vec<usize>,
27138    pub p: Vec<f32>,
27139    pub wsum: f32,
27140    pub logits: Vec<f32>,
27141}
27142
27143/// The routing half of `moe_ffn`, shared by every executor of the chosen
27144/// experts (the host/per-op path below and the MiMo dynamic device cache,
27145/// `crate::mimo_moe`): activation accounting, router logits, `moe_route`,
27146/// the selection statistics and the `CMF_MOE_TRACE` line — so switching
27147/// executors can never change which experts a token gets.
27148pub(crate) fn moe_ffn_route(
27149    m: &MoeFfn,
27150    x: &[f32],
27151    pool: Option<&Pool>,
27152    allowed: Option<&[bool]>,
27153) -> MoeRoute {
27154    accumulate_act(m, x, 1);
27155    let ne = m.experts.len();
27156    let mut logits = vec![0.0f32; ne];
27157    match &m.resonance {
27158        Some(r) => r.scores(x, &mut logits),
27159        None => m.router.matvec(x, &mut logits, pool),
27160    }
27161    let (idx, p, wsum) = moe_route(&logits, m, allowed);
27162    {
27163        let mut st = m.stats.borrow_mut();
27164        if st.len() < ne {
27165            st.resize(ne, 0);
27166        }
27167        for &e in &idx {
27168            st[e] += 1;
27169        }
27170    }
27171    // `CMF_MOE_TRACE=<file>`: append one line per (layer, token) with the
27172    // selected expert ids. The cumulative `stats` above answer "which
27173    // experts are popular"; a residency design needs the question they
27174    // cannot answer — whether CONSECUTIVE tokens reuse experts (the
27175    // temporal locality an LRU cache lives on, FreeToken §4).
27176    moe_trace(&idx);
27177    MoeRoute {
27178        idx,
27179        p,
27180        wsum,
27181        logits,
27182    }
27183}
27184
27185/// Flint's released mixed MoE profile has a native-Metal selected-expert
27186/// pager with a different numerical contract from the generic CPU probe:
27187/// the pager keeps activations in f32, whereas the fast host arm normally
27188/// uses its A8W8 activation path.  Timing those two approximations against
27189/// one another can make the probe reject the exact pager even when it is the
27190/// faster exact-f32 implementation.  Keep this gate deliberately narrower
27191/// than the pager itself; the pager revalidates every selected tuple before
27192/// it binds a no-copy view and an honest refusal still takes the CPU path.
27193#[cfg(target_os = "macos")]
27194fn strict_flint_metal_pager_candidate(m: &MoeFfn) -> bool {
27195    const HIDDEN: usize = 2_048;
27196    const ROUTED_INTER: usize = 512;
27197    const SHARED_INTER: usize = 1_024;
27198    const EXPERTS: usize = 256;
27199    const TOP_K: usize = 6;
27200
27201    let Some(routed) = m.experts.first() else {
27202        return false;
27203    };
27204    let Some((model, _)) = routed.gate_proj.mapped_q2tp() else {
27205        return false;
27206    };
27207    let Some((shared, shared_gate)) = &m.shared else {
27208        return false;
27209    };
27210    if shared_gate.is_some()
27211        || model.header.arch.arch_name != "flint"
27212        || model.header.arch.prism_hadamard.is_some()
27213        || model.header.arch.hidden_size != HIDDEN
27214        || m.experts.len() != EXPERTS
27215        || m.top_k != TOP_K
27216        || !m.router_sigmoid
27217        || !m.norm_topk_prob
27218        || m.sigmoid_denom_eps.to_bits() != (1e-20f32).to_bits()
27219        || m.routed_scaling.to_bits() != 1.0f32.to_bits()
27220        || m.route_tau.is_some()
27221        || m.mask.is_some()
27222        || m.per_expert_scale.is_some()
27223        || m.router_input_norm
27224        || m.resonance.is_some()
27225        || !m.grown.is_empty()
27226    {
27227        return false;
27228    }
27229
27230    let routed_q2 = routed.act == Act::Silu
27231        && routed.segs.is_empty()
27232        && routed.gate_proj.rows() == ROUTED_INTER
27233        && routed.gate_proj.cols() == HIDDEN
27234        && routed.up_proj.rows() == ROUTED_INTER
27235        && routed.up_proj.cols() == HIDDEN
27236        && routed.down_proj.rows() == HIDDEN
27237        && routed.down_proj.cols() == ROUTED_INTER
27238        && routed.up_proj.mapped_q2tp().is_some()
27239        && routed.down_proj.mapped_q4tp().is_some();
27240    let shared_q4 = shared.act == Act::Silu
27241        && shared.segs.is_empty()
27242        && shared.gate_proj.rows() == SHARED_INTER
27243        && shared.gate_proj.cols() == HIDDEN
27244        && shared.up_proj.rows() == SHARED_INTER
27245        && shared.up_proj.cols() == HIDDEN
27246        && shared.down_proj.rows() == HIDDEN
27247        && shared.down_proj.cols() == SHARED_INTER
27248        && shared.gate_proj.mapped_q4tp().is_some()
27249        && shared.up_proj.mapped_q4tp().is_some()
27250        && shared.down_proj.mapped_q4tp().is_some();
27251    routed_q2 && shared_q4
27252}
27253
27254/// The expert half of `moe_ffn`: run a route's experts on the per-op GPU
27255/// block or the host.
27256pub(crate) fn moe_ffn_experts(
27257    m: &MoeFfn,
27258    x: &[f32],
27259    r: &MoeRoute,
27260    pool: Option<&Pool>,
27261) -> Vec<f32> {
27262    let (idx, p, wsum) = (&r.idx, &r.p, r.wsum);
27263    // D5: the whole layer MoE block in one GPU command buffer (experts — the
27264    // same mmap via a no-copy buffer; intermediate activations on the GPU).
27265    // MoE owns a separate probe class from dense FFN: its selected-span pager
27266    // has materially different residency and latency costs.
27267    if crate::gpu::enabled_here() {
27268        #[cfg(target_os = "macos")]
27269        if crate::gpu_metal::enabled() && strict_flint_metal_pager_candidate(m) {
27270            // Do not compare the pager's exact-f32 result with the CPU's
27271            // optional A8W8 activation approximation.  The strict pager is
27272            // the validated Flint path; if a directory/view/device check
27273            // declines, preserve the existing CPU fallback rather than
27274            // leaving the probe in a half-sampled state.
27275            return moe_ffn_gpu(m, x, &idx, &p, wsum, pool).unwrap_or_else(|| {
27276                crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool))
27277            });
27278        }
27279        match crate::gpu::probe_arm(crate::gpu::OpClass::Moe) {
27280            crate::gpu::ProbeArm::Gpu => {
27281                let t0 = std::time::Instant::now();
27282                if let Some(out) = moe_ffn_gpu(m, x, &idx, &p, wsum, pool) {
27283                    crate::gpu::probe_record(crate::gpu::OpClass::Moe, true, t0.elapsed());
27284                    return out;
27285                }
27286                crate::gpu::probe_note_decline(crate::gpu::OpClass::Moe);
27287            }
27288            crate::gpu::ProbeArm::CpuTimed => {
27289                let t0 = std::time::Instant::now();
27290                let out = crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool));
27291                crate::gpu::probe_record(crate::gpu::OpClass::Moe, false, t0.elapsed());
27292                return out;
27293            }
27294            crate::gpu::ProbeArm::Cpu => {
27295                return crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool));
27296            }
27297        }
27298    }
27299    moe_ffn_cpu(m, x, &idx, &p, wsum, pool)
27300}
27301
27302/// One MiniCPM CPU-tail MoE through its opt-in dynamic bank, or through the
27303/// same-route host fallback.  The route is formed exactly once so statistics,
27304/// tracing, and model semantics remain owned by `moe_ffn_route`.
27305fn moe_ffn_minicpm_tail(
27306    slot: &mut crate::minicpm_tail::MiniCpmTail,
27307    li: usize,
27308    total_layers: usize,
27309    m: &MoeFfn,
27310    x: &[f32],
27311    pool: Option<&Pool>,
27312) -> Vec<f32> {
27313    let route = moe_ffn_route(m, x, pool, None);
27314    match slot.forward(li, m, x, &route, pool, total_layers) {
27315        Some(out) => out,
27316        // A cache refusal must be observationally identical to the generic
27317        // CPU-tail path. The surrounding host-tail scope already disables the
27318        // per-op arena, so do not introduce a float-activation policy change
27319        // merely because this explicit opt-in cache declined a model/layout.
27320        None => moe_ffn_experts(m, x, &route, pool),
27321    }
27322}
27323
27324/// One MoE token through the MiMo expert bank (`crate::mimo_moe`), or —
27325/// when the bank does not serve it — through the host path with the SAME
27326/// route, so the routing statistics and `CMF_MOE_TRACE` see it once.
27327fn moe_ffn_banked(
27328    slot: &mut crate::mimo_moe::Slot,
27329    li: usize,
27330    m: &MoeFfn,
27331    x: &[f32],
27332    pool: Option<&Pool>,
27333) -> Vec<f32> {
27334    let t0 = std::time::Instant::now();
27335    let r = moe_ffn_route(m, x, pool, None);
27336    slot.note_route(t0.elapsed().as_nanos() as u64);
27337    match slot.forward(li, m, x, &r, pool) {
27338        Some(out) => out,
27339        None => crate::qtensor::float_activations_scope(|| {
27340            crate::gpu::cpu_scope(|| moe_ffn_experts(m, x, &r, pool))
27341        }),
27342    }
27343}
27344
27345/// Verify rows share a bank frame; routing and fallback are decode's.
27346fn moe_ffn_banked_rows(
27347    slot: &mut crate::mimo_moe::Slot,
27348    li: usize,
27349    m: &MoeFfn,
27350    xs: &[f32],
27351    b: usize,
27352    hidden: usize,
27353    pool: Option<&Pool>,
27354) -> Vec<f32> {
27355    let t0 = std::time::Instant::now();
27356    let routes: Vec<_> = xs
27357        .chunks_exact(hidden)
27358        .map(|x| moe_ffn_route(m, x, pool, None))
27359        .collect();
27360    slot.note_route(t0.elapsed().as_nanos() as u64);
27361    if let Some(out) = slot.forward_rows(li, m, xs, &routes, pool) {
27362        return out;
27363    }
27364    let mut out = Vec::with_capacity(b * hidden);
27365    for (x, r) in xs.chunks_exact(hidden).zip(&routes) {
27366        let row = slot.forward(li, m, x, r, pool).unwrap_or_else(|| {
27367            // A failed bank must not stream missing experts into the arena.
27368            crate::qtensor::float_activations_scope(|| {
27369                crate::gpu::cpu_scope(|| moe_ffn_experts(m, x, r, pool))
27370            })
27371        });
27372        out.extend(row);
27373    }
27374    out
27375}
27376
27377/// One-shot report of whether the whole-token wgpu graph actually formed.
27378/// A refusal silently reverts to the per-op path, which is how a model can
27379/// look "GPU-accelerated" while every layer walks the host.  A device prefix
27380/// is tracked separately because it still pays a host boundary for the tail.
27381fn graph_note(built: bool, layers_run: usize, total_layers: usize) {
27382    use std::sync::atomic::{AtomicBool, Ordering};
27383    if built {
27384        GRAPH_TOK_OK.fetch_add(1, Ordering::Relaxed);
27385        if total_layers > 0 && layers_run < total_layers {
27386            GRAPH_TOK_PREFIX.fetch_add(1, Ordering::Relaxed);
27387        } else {
27388            GRAPH_TOK_FULL.fetch_add(1, Ordering::Relaxed);
27389        }
27390    } else {
27391        GRAPH_TOK_MISS.fetch_add(1, Ordering::Relaxed);
27392    }
27393    static SAID: AtomicBool = AtomicBool::new(false);
27394    if !SAID.swap(true, Ordering::Relaxed) {
27395        if built {
27396            tracing::info!("wgpu whole-token graph: ACTIVE");
27397        } else {
27398            tracing::warn!("wgpu whole-token graph refused — per-op path");
27399        }
27400    }
27401}
27402
27403/// Whole-token graph outcomes, process-wide: a benchmark that claims a
27404/// GPU number while MISS climbs is measuring the CPU — the honest-bench
27405/// contract makes that an error, not a footnote.
27406pub static GRAPH_TOK_OK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27407pub static GRAPH_TOK_MISS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27408/// Graph calls that returned a hidden after running only a leading device
27409/// prefix.  These are valid hybrid executions but must not be reported as a
27410/// full GPU graph in benchmark evidence.
27411pub static GRAPH_TOK_PREFIX: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27412/// Graph calls that covered the complete requested layer span.
27413pub static GRAPH_TOK_FULL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27414
27415/// Native Metal TokenGraph completion counters. These are incremented only
27416/// after checked command-buffer completion and successful readback, so a
27417/// fused-head NLL report can prove the route rather than infer it from env.
27418pub static METAL_GRAPH_TOK_OK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27419pub static METAL_GRAPH_HEAD_OK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27420pub static METAL_GRAPH_HEAD_MISS: std::sync::atomic::AtomicU64 =
27421    std::sync::atomic::AtomicU64::new(0);
27422pub static METAL_GRAPH_LAYERS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27423pub static METAL_GRAPH_ERRORS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27424/// Ordinary native-Metal rows-prefill admissions and completed rows.  These
27425/// counters are separate from TokenGraph token/head counts so a batch NLL
27426/// receipt cannot accidentally claim serial execution as batched.
27427pub static METAL_PREFILL_CHUNKS: std::sync::atomic::AtomicU64 =
27428    std::sync::atomic::AtomicU64::new(0);
27429pub static METAL_PREFILL_ROWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27430pub static METAL_PREFILL_HEAD_ROWS: std::sync::atomic::AtomicU64 =
27431    std::sync::atomic::AtomicU64::new(0);
27432pub static METAL_PREFILL_ERRORS: std::sync::atomic::AtomicU64 =
27433    std::sync::atomic::AtomicU64::new(0);
27434
27435/// `CMF_MOE_BATCH=0` restores the per-expert serial loop — the A/B lever
27436/// for the batched kernel, and how its bit-identity is checked.
27437fn moe_batch_enabled() -> bool {
27438    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
27439    *ON.get_or_init(|| std::env::var("CMF_MOE_BATCH").as_deref() != Ok("0"))
27440}
27441
27442/// Two-dispatch CPU MoE: every routed expert (and the shared one) fused
27443/// into one gate/up/SiLU dispatch and one down dispatch, instead of two
27444/// pool barriers per expert. Bit-identical to the serial loop below —
27445/// see `moe_gate_up_many` / `moe_down_many`. `None` = the batched kernel
27446/// does not cover this layer, walk the serial path.
27447fn moe_ffn_cpu_batched(
27448    m: &MoeFfn,
27449    x: &[f32],
27450    idx: &[usize],
27451    p: &[f32],
27452    wsum: f32,
27453    pool: Option<&Pool>,
27454) -> Option<Vec<f32>> {
27455    if idx.is_empty() || !moe_batch_enabled() {
27456        return None;
27457    }
27458    // The bake probe reads per-neuron activation mass out of the
27459    // single-expert path; batching would skip it. Rare and offline —
27460    // hand those runs to the serial loop.
27461    if FFN_PROBE.with(|pr| pr.borrow().is_some()) || moe_probe_active() {
27462        return None;
27463    }
27464    let n = idx.len() + usize::from(m.shared.is_some());
27465    let mut pairs = Vec::with_capacity(n);
27466    let mut downs = Vec::with_capacity(n);
27467    let mut ws = Vec::with_capacity(n);
27468    for &e in idx {
27469        let d = &m.experts[e];
27470        if d.act != Act::Silu {
27471            return None;
27472        }
27473        pairs.push((&d.gate_proj, &d.up_proj));
27474        downs.push(&d.down_proj);
27475        ws.push(p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]));
27476    }
27477    // The shared expert goes last, matching the serial loop's order —
27478    // the f32 accumulation order is part of the bit-identity claim.
27479    if let Some((se, gate)) = &m.shared {
27480        if se.act != Act::Silu {
27481            return None;
27482        }
27483        let g = gate.as_ref().map_or(1.0, |gate| {
27484            let mut gl = [0.0f32; 1];
27485            gate.matvec(x, &mut gl, pool);
27486            1.0 / (1.0 + (-gl[0]).exp())
27487        });
27488        pairs.push((&se.gate_proj, &se.up_proj));
27489        downs.push(&se.down_proj);
27490        ws.push(g);
27491    }
27492    let inter = pairs[0].0.rows();
27493    let mut gs: Vec<Vec<f32>> = (0..pairs.len()).map(|_| vec![0f32; inter]).collect();
27494    if !QTensor::moe_gate_up_many(&pairs, x, &mut gs, pool) {
27495        return None;
27496    }
27497    let mut out = attention::take_buf(x.len());
27498    if !QTensor::moe_down_many(&downs, &gs, &ws, &mut out, pool) {
27499        attention::recycle_buf(&mut out);
27500        return None;
27501    }
27502    Some(out)
27503}
27504
27505/// Exact CPU completion for the routed experts a dynamic device cache did
27506/// not contain. The weights are already the router's final normalized mix.
27507/// Keeping this independent of `MoeFfn` makes the job `Sync`: its routing
27508/// statistics live in a `RefCell`, while the immutable expert tensors can be
27509/// evaluated safely in parallel with the GPU's resident subset.
27510/// Pooled-tail stage timers, reported per token by the bench JSON
27511/// (`m3_span_ms_per_tok`, `m3_cold_ms_per_tok`, `m3_arm_ms_per_tok`).
27512pub static M3_SPAN_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27513pub static M3_COLD_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27514pub static M3_ARM_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27515pub static M3_COLD_N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27516pub static M3_COLD_DEV_N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27517
27518pub(crate) fn moe_cold_experts_cpu(
27519    experts: &[(&DenseFfn, f32)],
27520    x: &[f32],
27521    pool: Option<&Pool>,
27522) -> Vec<f32> {
27523    moe_cold_experts_cpu_with(experts, x, pool, true)
27524}
27525
27526/// [`moe_cold_experts_cpu`] with the experts' tubes (`expert_tubes_add`) optional: the
27527/// Flash-Next device path computes every winner's tube on the card.
27528pub(crate) fn moe_cold_experts_cpu_with(
27529    experts: &[(&DenseFfn, f32)],
27530    x: &[f32],
27531    pool: Option<&Pool>,
27532    tubes: bool,
27533) -> Vec<f32> {
27534    let mut out = attention::take_buf(x.len());
27535    if experts.is_empty() {
27536        return out;
27537    }
27538    let pairs: Vec<_> = experts
27539        .iter()
27540        .map(|(e, _)| (&e.gate_proj, &e.up_proj))
27541        .collect();
27542    let downs: Vec<_> = experts.iter().map(|(e, _)| &e.down_proj).collect();
27543    let weights: Vec<_> = experts.iter().map(|(_, w)| *w).collect();
27544    let inter = experts[0].0.gate_proj.rows();
27545    let mut activations: Vec<Vec<f32>> = (0..experts.len()).map(|_| vec![0.0; inter]).collect();
27546    // The batched gate/up kernels implement PLAIN SiLU only (their legacy
27547    // helper passes limit 0 and no activation code). MiniMax's SwiGLU-OAI
27548    // (alpha 1.702, shifted up) must take the per-expert path that reads
27549    // each tensor's own activation — otherwise every cold expert computes
27550    // silu and the residual walks away from the reference (measured: the
27551    // pooled tail shipped cos 0.047 hidden while the resident path was
27552    // bit-close).
27553    let silu_only = experts
27554        .iter()
27555        .all(|(e, _)| matches!(e.act, crate::pipeline::Act::Silu));
27556    if silu_only
27557        && QTensor::moe_gate_up_many(&pairs, x, &mut activations, pool)
27558        && QTensor::moe_down_many(&downs, &activations, &weights, &mut out, pool)
27559    {
27560        if tubes {
27561            for &(expert, weight) in experts {
27562                expert_tubes_add(expert, x, weight, &mut out, pool);
27563            }
27564        }
27565        return out;
27566    }
27567    out.fill(0.0);
27568    for &(expert, weight) in experts {
27569        if tubes {
27570            expert_tubes_add(expert, x, weight, &mut out, pool);
27571        }
27572        let mut one = dense_ffn(expert, x, pool);
27573        for (o, v) in out.iter_mut().zip(&one) {
27574            *o += weight * v;
27575        }
27576        attention::recycle_buf(&mut one);
27577    }
27578    out
27579}
27580
27581/// Cold part of a short bank batch. Share each expert's weight stream
27582/// across its tokens, but reduce contributions in each token's route order.
27583/// On an unsupported CPU/layout, retain the single-token cold kernels.
27584pub(crate) fn moe_cold_experts_rows_cpu(
27585    jobs: &[Vec<(&DenseFfn, f32)>],
27586    xs: &[f32],
27587    hidden: usize,
27588    pool: Option<&Pool>,
27589) -> Vec<f32> {
27590    let mut out = vec![0.0; xs.len()];
27591    let mut experts: Vec<&DenseFfn> = Vec::new();
27592    let mut groups: Vec<Vec<usize>> = Vec::new();
27593    let mut terms = vec![Vec::new(); jobs.len()];
27594    for (r, row) in jobs.iter().enumerate() {
27595        for &(e, w) in row {
27596            let g = match experts.iter().position(|&d| std::ptr::eq(d, e)) {
27597                Some(g) => g,
27598                None => {
27599                    experts.push(e);
27600                    groups.push(Vec::new());
27601                    groups.len() - 1
27602                }
27603            };
27604            terms[r].push((g, groups[g].len(), w));
27605            groups[g].push(r);
27606        }
27607    }
27608    if experts.is_empty() {
27609        return out;
27610    }
27611    let pairs: Vec<_> = experts.iter().map(|e| (&e.gate_proj, &e.up_proj)).collect();
27612    let downs: Vec<_> = experts.iter().map(|e| &e.down_proj).collect();
27613    let lens: Vec<_> = groups.iter().map(Vec::len).collect();
27614    let count: usize = lens.iter().sum();
27615    let mut acts = vec![vec![0.0; experts[0].gate_proj.rows()]; count];
27616    let mut ds = vec![vec![0.0; hidden]; count];
27617    if QTensor::moe_gate_up_rows(&pairs, &groups, xs, &mut acts, pool)
27618        && QTensor::moe_down_rows(&downs, &lens, &acts, &mut ds, pool)
27619    {
27620        let mut offset = 0;
27621        let offsets: Vec<_> = lens
27622            .iter()
27623            .map(|&n| {
27624                let start = offset;
27625                offset += n;
27626                start
27627            })
27628            .collect();
27629        for (r, terms) in terms.iter().enumerate() {
27630            for &(g, slot, w) in terms {
27631                for (o, &v) in out[r * hidden..(r + 1) * hidden]
27632                    .iter_mut()
27633                    .zip(&ds[offsets[g] + slot])
27634                {
27635                    *o += w * v;
27636                }
27637            }
27638        }
27639    } else {
27640        for (r, jobs) in jobs.iter().enumerate() {
27641            if !jobs.is_empty() {
27642                let mut row = moe_cold_experts_cpu(jobs, &xs[r * hidden..(r + 1) * hidden], pool);
27643                out[r * hidden..(r + 1) * hidden].copy_from_slice(&row);
27644                attention::recycle_buf(&mut row);
27645            }
27646        }
27647    }
27648    out
27649}
27650
27651/// The pure-CPU MoE expert loop (also the fallback of every GPU refusal).
27652fn moe_ffn_cpu(
27653    m: &MoeFfn,
27654    x: &[f32],
27655    idx: &[usize],
27656    p: &[f32],
27657    wsum: f32,
27658    pool: Option<&Pool>,
27659) -> Vec<f32> {
27660    if let Some(mut out) = moe_ffn_cpu_batched(m, x, idx, p, wsum, pool) {
27661        for &e in idx {
27662            let w = p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]);
27663            expert_tubes_add(&m.experts[e], x, w, &mut out, pool);
27664        }
27665        shared_tubes_add(m, x, &mut out, pool);
27666        return out;
27667    }
27668    let mut out = attention::take_buf(x.len());
27669    for &e in idx {
27670        let w = p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]);
27671        MOE_PROBE.with(|pr| {
27672            if let Some(pr) = pr.borrow_mut().as_mut() {
27673                pr.cur = Some((e, w));
27674            }
27675        });
27676        let mut eo = dense_ffn(&m.experts[e], x, pool);
27677        MOE_PROBE.with(|pr| {
27678            if let Some(pr) = pr.borrow_mut().as_mut() {
27679                pr.cur = None;
27680            }
27681        });
27682        for i in 0..out.len() {
27683            out[i] += w * eo[i];
27684        }
27685        attention::recycle_buf(&mut eo);
27686        expert_tubes_add(&m.experts[e], x, w, &mut out, pool);
27687    }
27688    if let Some((se, gate)) = &m.shared {
27689        let mut so = dense_ffn(se, x, pool);
27690        let g = gate.as_ref().map_or(1.0, |gate| {
27691            let mut gl = [0.0f32; 1];
27692            gate.matvec(x, &mut gl, pool);
27693            1.0 / (1.0 + (-gl[0]).exp())
27694        });
27695        for i in 0..out.len() {
27696            out[i] += g * so[i];
27697        }
27698        attention::recycle_buf(&mut so);
27699        expert_tubes_add(se, x, g, &mut out, pool);
27700    }
27701    out
27702}
27703
27704/// DeepSeek-V2 MLA forward, expand-to-MHA form (see `AttnKind::Mla`):
27705/// per token the latent expands to every head's K/V and the ordinary
27706/// cache + grouped attend do the rest. K head layout is [rope | nope]
27707/// (rotary_dim = qk_rope rotates the shared rope key and each q head's
27708/// prefix); V rows are zero-padded to the K head_dim inside the cache
27709/// and the pad is sliced off before O. Attention importance is not
27710/// accumulated for MLA yet (no eviction interplay).
27711#[allow(clippy::too_many_arguments)]
27712pub(crate) fn mla_attention(
27713    w: &MlaWeights,
27714    normed: &[f32],
27715    cache: &mut crate::kv_cache::LayerKvCache,
27716    position: usize,
27717    inv_freq: &[f32],
27718    rope_scale: f32,
27719    eps: f64,
27720    pool: Option<&Pool>,
27721) -> Vec<f32> {
27722    let (nh, dr, dn, dv, lora) = (w.nh, w.qk_rope, w.qk_nope, w.v_dim, w.lora);
27723    let hd = dr + dn;
27724    let mut q = vec![0.0f32; nh * hd];
27725    match (&w.q_a, &w.q_a_norm) {
27726        (Some(qa), Some(qn)) => {
27727            let mut t = vec![0.0f32; qa.rows()];
27728            qa.matvec(normed, &mut t, pool);
27729            let tn = inference::rms_norm(&t, qn, eps, NormStyle::Qwen);
27730            w.q_proj.matvec(&tn, &mut q, pool);
27731        }
27732        _ => w.q_proj.matvec(normed, &mut q, pool),
27733    }
27734    let mut ca = vec![0.0f32; lora + dr];
27735    w.kv_a.matvec(normed, &mut ca, pool);
27736    let (c_lat, k_rope) = ca.split_at_mut(lora);
27737    let latn = inference::rms_norm(c_lat, &w.kv_a_norm, eps, NormStyle::Qwen);
27738    let mut kvb = vec![0.0f32; nh * (dn + dv)];
27739    w.kv_b.matvec(&latn, &mut kvb, pool);
27740    if !w.nope {
27741        attention::rope_rotate_scaled(k_rope, position, inv_freq, rope_scale);
27742    }
27743    for h in 0..nh {
27744        if !w.nope {
27745            attention::rope_rotate_scaled(
27746                &mut q[h * hd..h * hd + dr],
27747                position,
27748                inv_freq,
27749                rope_scale,
27750            );
27751        }
27752    }
27753    let mut k = vec![0.0f32; nh * hd];
27754    let mut v = vec![0.0f32; nh * hd];
27755    for h in 0..nh {
27756        k[h * hd..h * hd + dr].copy_from_slice(k_rope);
27757        k[h * hd + dr..(h + 1) * hd].copy_from_slice(&kvb[h * (dn + dv)..h * (dn + dv) + dn]);
27758        v[h * hd..h * hd + dv].copy_from_slice(&kvb[h * (dn + dv) + dn..(h + 1) * (dn + dv)]);
27759    }
27760    cache.append(&k, &v, &vec![true; nh]);
27761    let (ao, mut imp) = attention::attend_all_heads(&q, cache, nh, 1, hd, w.scale, None, 0.0);
27762    attention::recycle_buf(&mut imp);
27763    let mut ov = vec![0.0f32; nh * dv];
27764    for h in 0..nh {
27765        ov[h * dv..(h + 1) * dv].copy_from_slice(&ao[h * hd..h * hd + dv]);
27766    }
27767    let mut out = vec![0.0f32; w.o_proj.rows()];
27768    w.o_proj.matvec(&ov, &mut out, pool);
27769    out
27770}
27771
27772/// Gemma-4 dual-branch FFN (spec: see `FfnKind::DenseMoe`). The dense
27773/// branch reads the pre-FFN-normed activation; the router and the
27774/// expert branch read the RAW residual — the router through a
27775/// scale-less rms norm (its constant gain is folded into the weights),
27776/// the experts through `pre_norm_2`. CPU path; GPU graphs refuse the
27777/// layer kind honestly.
27778fn dense_moe_ffn(
27779    dm: &DenseMoeFfn,
27780    x_normed: &[f32],
27781    h_raw: &[f32],
27782    eps: f64,
27783    norm_style: NormStyle,
27784    pool: Option<&Pool>,
27785) -> Vec<f32> {
27786    let mut d = dense_ffn(&dm.dense, x_normed, pool);
27787    d = inference::rms_norm(&d, &dm.post_norm_1, eps, norm_style);
27788    let m = &dm.moe;
27789    let ne = m.experts.len();
27790    let mut logits = vec![0.0f32; ne];
27791    if m.router_input_norm {
27792        let ss: f32 = h_raw.iter().map(|v| v * v).sum::<f32>() / h_raw.len() as f32;
27793        let inv = 1.0 / (ss + eps as f32).sqrt();
27794        let xr: Vec<f32> = h_raw.iter().map(|v| v * inv).collect();
27795        m.router.matvec(&xr, &mut logits, pool);
27796    } else {
27797        m.router.matvec(h_raw, &mut logits, pool);
27798    }
27799    let (idx, p, wsum) = moe_route(&logits, m, None);
27800    {
27801        let mut st = m.stats.borrow_mut();
27802        if st.len() < ne {
27803            st.resize(ne, 0);
27804        }
27805        for &e in &idx {
27806            st[e] += 1;
27807        }
27808    }
27809    let x2 = inference::rms_norm(h_raw, &dm.pre_norm_2, eps, norm_style);
27810    let mo = moe_ffn_cpu(m, &x2, &idx, &p, wsum, pool);
27811    let mo = inference::rms_norm(&mo, &dm.post_norm_2, eps, norm_style);
27812    for (di, mi) in d.iter_mut().zip(&mo) {
27813        *di += mi;
27814    }
27815    d
27816}
27817
27818/// Building the MoE-layer GPU jobs: all selected experts (+shared) must
27819/// be q8_2f-Mapped from the primary mapping; otherwise None → CPU path.
27820/// One-shot report of why the MoE GPU block refused. A silent `?` here
27821/// sends every expert to the CPU with nothing in the logs to say so —
27822/// which is exactly how a q4tp MoE model looked "GPU-accelerated" while
27823/// running entirely on the host.
27824fn moe_gpu_refused(why: &'static str) {
27825    use std::sync::atomic::{AtomicBool, Ordering};
27826    static SAID: AtomicBool = AtomicBool::new(false);
27827    if !SAID.swap(true, Ordering::Relaxed) {
27828        tracing::warn!("MoE GPU block refused ({why}) — experts run on the CPU");
27829    }
27830}
27831
27832fn moe_ffn_gpu(
27833    m: &MoeFfn,
27834    x: &[f32],
27835    idx: &[usize],
27836    p: &[f32],
27837    wsum: f32,
27838    pool: Option<&Pool>,
27839) -> Option<Vec<f32>> {
27840    use crate::gpu::MoeJob;
27841
27842    let mut jobs: Vec<MoeJob> = Vec::with_capacity(idx.len() + 1);
27843    let mut model_ref = None;
27844    for &e in idx {
27845        if moe_push_job(&m.experts[e], x, p[e] / wsum, &mut jobs, &mut model_ref).is_none() {
27846            moe_gpu_refused("push_job(expert)");
27847            return None;
27848        }
27849    }
27850    if let Some((se, gate)) = &m.shared {
27851        let g = gate.as_ref().map_or(1.0, |gate| {
27852            let mut gl = [0.0f32; 1];
27853            gate.matvec(x, &mut gl, pool);
27854            1.0 / (1.0 + (-gl[0]).exp())
27855        });
27856        if moe_push_job(se, x, g, &mut jobs, &mut model_ref).is_none() {
27857            moe_gpu_refused("push_job(shared)");
27858            return None;
27859        }
27860    }
27861    let Some(model) = model_ref else {
27862        moe_gpu_refused("no model_ref");
27863        return None;
27864    };
27865    let hidden = jobs[0].down.1;
27866    let mut out = vec![0.0f32; hidden];
27867    if crate::gpu::moe_block(&model, &jobs, &mut out) {
27868        // The block knows no tubes (`hot-bake --experts`): the winners' and the
27869        // shared expert's come here, as the CPU paths add them.
27870        for &e in idx {
27871            expert_tubes_add(&m.experts[e], x, p[e] / wsum, &mut out, pool);
27872        }
27873        shared_tubes_add(m, x, &mut out, pool);
27874        Some(out)
27875    } else {
27876        moe_gpu_refused("gpu::moe_block");
27877        None
27878    }
27879}
27880
27881/// Single-position FFN dispatch.
27882fn ffn_forward(
27883    ffn: &FfnKind,
27884    x: &[f32],
27885    pool: Option<&Pool>,
27886    experts_allowed: Option<&[bool]>,
27887) -> Vec<f32> {
27888    match ffn {
27889        FfnKind::Dense(d) if !d.segs.is_empty() => tube_ffn(d, x, 1, pool, None),
27890        FfnKind::Dense(d) => dense_ffn(d, x, pool),
27891        FfnKind::Moe(m) => moe_ffn(m, x, pool, experts_allowed),
27892        // Dual-branch layers need the raw residual — their callers
27893        // dispatch dense_moe_ffn directly; the auxiliary paths that land
27894        // here (MTP draft, o1 replay) do not co-occur with gemma-4 MoE.
27895        FfnKind::DenseMoe(_) => unreachable!("DenseMoe dispatches via dense_moe_ffn"),
27896    }
27897}
27898
27899/// Fused two-position FFN: gate/up/down streamed once (dense). MoE
27900/// falls back to two singles — expert sets differ per position, there
27901/// is nothing to fuse.
27902fn ffn_forward_pair(
27903    ffn: &FfnKind,
27904    x1: &[f32],
27905    x2: &[f32],
27906    pool: Option<&Pool>,
27907    experts_allowed: Option<&[bool]>,
27908) -> (Vec<f32>, Vec<f32>) {
27909    let d = match ffn {
27910        // A tube layer has nothing to fuse across the pair — the tubes
27911        // are separate matrices; two singles are the honest path.
27912        FfnKind::Dense(d) if !d.segs.is_empty() => {
27913            return (
27914                tube_ffn(d, x1, 1, pool, None),
27915                tube_ffn(d, x2, 1, pool, None),
27916            );
27917        }
27918        FfnKind::Dense(d) => d,
27919        FfnKind::Moe(m) => {
27920            return (
27921                moe_ffn(m, x1, pool, experts_allowed),
27922                moe_ffn(m, x2, pool, experts_allowed),
27923            );
27924        }
27925        FfnKind::DenseMoe(_) => unreachable!("DenseMoe dispatches via dense_moe_ffn"),
27926    };
27927    let inter = d.gate_proj.rows();
27928    FFN_SCRATCH.with(|s| {
27929        let mut s = s.borrow_mut();
27930        let [g1, g2, u1, u2] = &mut *s;
27931        g1.resize(inter, 0.0);
27932        g2.resize(inter, 0.0);
27933        u1.resize(inter, 0.0);
27934        u2.resize(inter, 0.0);
27935        // Multi-matrix pair job: gate+up under one pool dispatch
27936        // (o1s = lane-1 outputs across tensors, o2s = lane-2).
27937        QTensor::matvec2_many(
27938            [&d.gate_proj, &d.up_proj],
27939            x1,
27940            x2,
27941            [g1.as_mut_slice(), u1.as_mut_slice()],
27942            [g2.as_mut_slice(), u2.as_mut_slice()],
27943            pool,
27944        );
27945        for i in 0..inter {
27946            g1[i] = d.act.combine(g1[i], u1[i]);
27947            g2[i] = d.act.combine(g2[i], u2[i]);
27948        }
27949        let mut o1 = attention::take_buf(d.down_proj.rows());
27950        let mut o2 = attention::take_buf(d.down_proj.rows());
27951        d.down_proj.matvec2(g1, g2, &mut o1, &mut o2, pool);
27952        (o1, o2)
27953    })
27954}
27955
27956/// Rows a far-field prompt chunk keeps at least when it is the last before
27957/// `stop`: a chunk of a few rows can go a backend's decode-sized path (the
27958/// CUDA hybrid arm's 16-row small path), which captures neither the seal's
27959/// queries nor the archive's K/V rows. Aion-2.3B, 26 626 rows: the whole-prompt
27960/// prefix in 1024-row chunks ended in 2 rows ("0 query values"), the sealed
27961/// 512-row chunks before the tail in 2 rows (an archive two rows short, exact
27962/// rows read from the wrong place, a garbled answer).
27963const O1_MIN_LAST_CHUNK: usize = 32;
27964
27965/// The end of a far-field prompt chunk from `pos`, at most `chunk` rows and not
27966/// past `stop`, that leaves the chunk after it at least [`O1_MIN_LAST_CHUNK`] rows.
27967fn o1_chunk_end(pos: usize, chunk: usize, stop: usize) -> usize {
27968    let end = (pos + chunk).min(stop);
27969    let rest = stop - end;
27970    if rest > 0 && rest < O1_MIN_LAST_CHUNK && stop - O1_MIN_LAST_CHUNK > pos + O1_MIN_LAST_CHUNK {
27971        stop - O1_MIN_LAST_CHUNK
27972    } else {
27973        end
27974    }
27975}
27976
27977#[cfg(test)]
27978mod tests {
27979
27980    #[test]
27981    fn o1_chunks_never_end_in_a_sliver() {
27982        // 26 626 rows in 1024-row chunks: the last but one stops 32 short
27983        let mut ends = Vec::new();
27984        let mut pos = 0;
27985        while pos < 26_626 {
27986            let e = super::o1_chunk_end(pos, 1024, 26_626);
27987            ends.push(e - pos);
27988            pos = e;
27989        }
27990        assert_eq!(pos, 26_626);
27991        assert!(ends.iter().all(|&b| b >= 32 && b <= 1024), "{ends:?}");
27992        assert_eq!(*ends.last().unwrap(), 32);
27993        // an exact multiple and a short span are left alone
27994        assert_eq!(super::o1_chunk_end(0, 512, 1024), 512);
27995        assert_eq!(super::o1_chunk_end(1000, 512, 1010), 1010);
27996        assert_eq!(super::o1_chunk_end(0, 512, 530), 498);
27997    }
27998    use std::ffi::OsString;
27999    use std::sync::Mutex;
28000
28001    // Environment switches are process-global. Keep the speculative-path
28002    // tests serialized and restore every prior value even during unwinding.
28003    static MTP_ENV_LOCK: Mutex<()> = Mutex::new(());
28004
28005    struct ScopedTestEnv {
28006        previous: Vec<(&'static str, Option<OsString>)>,
28007    }
28008
28009    impl ScopedTestEnv {
28010        fn set(vars: &[(&'static str, Option<&'static str>)]) -> Self {
28011            let previous = vars
28012                .iter()
28013                .map(|(name, _)| (*name, std::env::var_os(name)))
28014                .collect();
28015            for &(name, value) in vars {
28016                unsafe {
28017                    match value {
28018                        Some(value) => std::env::set_var(name, value),
28019                        None => std::env::remove_var(name),
28020                    }
28021                }
28022            }
28023            Self { previous }
28024        }
28025    }
28026
28027    impl Drop for ScopedTestEnv {
28028        fn drop(&mut self) {
28029            for (name, value) in self.previous.drain(..).rev() {
28030                unsafe {
28031                    match value {
28032                        Some(value) => std::env::set_var(name, value),
28033                        None => std::env::remove_var(name),
28034                    }
28035                }
28036            }
28037        }
28038    }
28039
28040    #[test]
28041    fn tail_repeat_counts_the_copied_stretch() {
28042        assert_eq!(tail_repeat(&[]), 0);
28043        assert_eq!(tail_repeat(&[5]), 0);
28044        assert_eq!(tail_repeat(&[1, 2, 3, 4]), 0);
28045        // the last three repeat the first three
28046        assert_eq!(tail_repeat(&[1, 2, 3, 9, 1, 2, 3]), 3);
28047        // the longest repeat wins over a later, shorter one
28048        assert_eq!(tail_repeat(&[1, 2, 3, 4, 8, 3, 4, 7, 1, 2, 3, 4]), 4);
28049        // a repeat reaching the start of the sequence
28050        assert_eq!(tail_repeat(&[1, 2, 1, 2]), 2);
28051        let long: Vec<u32> = (0..40).chain(0..40).collect();
28052        assert_eq!(tail_repeat(&long), 32);
28053    }
28054
28055    /// The chain's depth on wgpu follows the device's own round prices: a
28056    /// card whose verify climbs with its rows comes back from five drafts
28057    /// to three on the same acceptance that keeps a flat card at five.
28058    #[test]
28059    fn wgpu_spec_depth_follows_the_round_prices() {
28060        // RTX 2000 Ada, Qwen3.8-27B Turbo: rounds of 2..5 drafts, ms
28061        let steep = [0.0, 100.5, 111.3, 126.3, 144.6, 0.0, 0.0];
28062        let hold = [0.90, 0.85, 0.80, 0.60, 0.60, 0.60, 0.60];
28063        assert_eq!(wgpu_spec_depth(&hold, &steep, 5, 2, 5), Some(3));
28064        // the depth in turn stays while no other is 4 % better
28065        assert_eq!(wgpu_spec_depth(&hold, &steep, 4, 2, 5), Some(4));
28066        let flat = [0.0, 0.0, 60.0, 62.0, 64.0, 0.0, 0.0];
28067        assert_eq!(wgpu_spec_depth(&[0.9; 7], &flat, 3, 2, 5), Some(5));
28068        // an untimed depth is priced on the line through the two nearest
28069        let two = [0.0, 0.0, 111.3, 126.3, 0.0, 0.0, 0.0];
28070        assert_eq!(wgpu_spec_depth(&[0.5; 7], &two, 4, 2, 5), Some(2));
28071        // one timed depth says nothing of the slope
28072        assert_eq!(wgpu_spec_depth(&hold, &[0.0, 0.0, 111.3, 0.0, 0.0, 0.0, 0.0], 3, 2, 5), None);
28073    }
28074
28075    #[test]
28076    fn dflash_round_values_price_a_round_of_each_drafter() {
28077        // the block holds all seven of its drafts, the chain its first only
28078        let after: Vec<u32> = (10..30).collect();
28079        let seq: Vec<u32> = (100..140).collect();
28080        let block: Vec<u32> = (10..17).collect();
28081        let chain: Vec<u32> = vec![10, 99, 99, 99, 99, 99, 99];
28082        let starts: Vec<DflashStart<'_>> =
28083            (0..40).map(|_| DflashStart { seq: &seq, after: &after, block: &block, chain: &chain }).collect();
28084        let v = dflash_round_values(&starts);
28085        let (b, c) = v[39];
28086        // a block seven deep: eight tokens for a round of seven drafts and the block's own price
28087        assert_eq!(b, (8.0, METAL_ROUND_COST[6] + DFLASH_ROUND_DRAFT));
28088        // the chain has settled at one draft, which holds
28089        assert_eq!(c, (2.0, METAL_ROUND_COST[0]));
28090        assert!(b.0 / b.1 > c.0 / c.1);
28091    }
28092
28093    #[test]
28094    fn lookup_continues_a_repeated_stretch() {
28095        // 1 2 3 4 5 6 7 | 9 9 | 2 3 4 → the stretch 2 3 4 was followed by 5 6 7
28096        let seq = [1, 2, 3, 4, 5, 6, 7, 9, 9, 2, 3, 4];
28097        assert_eq!(lookup_continuation(&seq, 3, 3), &[5, 6, 7]);
28098        assert_eq!(lookup_continuation(&seq, 3, 2), &[5, 6]);
28099        // a repeat shorter than asked gives nothing
28100        assert!(lookup_continuation(&seq, 4, 3).is_empty());
28101        // the longest repeat wins over a later, shorter one
28102        let seq = [5, 2, 3, 4, 8, 0, 3, 4, 7, 0, 5, 2, 3, 4];
28103        assert_eq!(lookup_continuation(&seq, 2, 1), &[8]);
28104        // of equal ones the latest
28105        let seq = [2, 3, 4, 8, 0, 2, 3, 4, 7, 0, 2, 3, 4];
28106        assert_eq!(lookup_continuation(&seq, 2, 1), &[7]);
28107        // a period continues through the tail itself
28108        let seq = [1, 2, 1, 2, 1, 2];
28109        assert_eq!(lookup_continuation(&seq, 3, 4), &[1, 2]);
28110        assert!(lookup_continuation(&[1, 2, 3], 3, 2).is_empty());
28111        assert!(lookup_continuation(&[], 1, 2).is_empty());
28112    }
28113
28114    #[test]
28115    fn metal_spec_depth_follows_what_the_chain_holds() {
28116        // before any round: two drafts
28117        assert_eq!(metal_spec_depth(&SPEC_HOLD_PRIOR), 2);
28118        // a second draft that seldom holds is not worth its verify
28119        assert_eq!(metal_spec_depth(&[0.6, 0.15, 0.5, 0.5, 0.5, 0.5, 0.5]), 1);
28120        // predictable text fills the GEMM tile
28121        assert_eq!(metal_spec_depth(&[0.97; 7]), 7);
28122        // rounds of two drafts that both hold reach for a longer chain
28123        let mut h = SPEC_HOLD_PRIOR;
28124        let mut k = metal_spec_depth(&h);
28125        let mut rounds = 0;
28126        while k == 2 && rounds < 200 {
28127            spec_hold_update(&mut h, k, 2);
28128            k = metal_spec_depth(&h);
28129            rounds += 1;
28130        }
28131        assert!(k > 2 && rounds < 60, "depth {k} after {rounds} rounds");
28132        // ... and come back once the longer chain shows that a third never holds
28133        let mut back = 0;
28134        while k > 2 && back < 200 {
28135            spec_hold_update(&mut h, k, 2);
28136            k = metal_spec_depth(&h);
28137            back += 1;
28138        }
28139        assert!(k == 2 && back < 10, "depth {k} after {back} rounds");
28140        // most rounds of such text stay at two drafts
28141        let mut deep = 0;
28142        for _ in 0..400 {
28143            let k = metal_spec_depth(&h);
28144            deep += (k > 2) as usize;
28145            spec_hold_update(&mut h, k, 2);
28146        }
28147        assert!(deep < 40, "{deep} of 400 rounds went deeper");
28148        // a chain that holds one draft in two rounds of three, two in one of three: never deeper
28149        let mut h = SPEC_HOLD_PRIOR;
28150        for i in 0..300 {
28151            let k = metal_spec_depth(&h);
28152            assert!(k <= 2, "depth {k} at round {i}");
28153            spec_hold_update(&mut h, k, (i % 3).min(k));
28154        }
28155    }
28156
28157    #[test]
28158    fn mtp_draft_shortlist_masks_unevaluated_vocab_rows() {
28159        use super::pad_mtp_draft_logits;
28160
28161        let mut logits = vec![-3.0, -1.0, -2.0];
28162        pad_mtp_draft_logits(&mut logits, 6);
28163        assert_eq!(&logits[..3], &[-3.0, -1.0, -2.0]);
28164        assert!(logits[3..].iter().all(|&x| x == f32::NEG_INFINITY));
28165        assert_eq!(
28166            logits
28167                .iter()
28168                .enumerate()
28169                .max_by(|(_, a), (_, b)| a.total_cmp(b))
28170                .map(|(i, _)| i),
28171            Some(1),
28172            "an unevaluated row cannot win an all-negative shortlist"
28173        );
28174    }
28175
28176    #[test]
28177    fn speculative_trial_fast_exits_after_three_zero_acceptance_rounds() {
28178        use super::{Pipeline, SpecMon, SpecTrial};
28179
28180        let mut mon = SpecMon::default();
28181        let start = std::time::Instant::now();
28182        mon.round(1.0, 1);
28183        let first = Pipeline::spec_trial_round(
28184            SpecTrial::Spec {
28185                t0: start,
28186                gen0: 0,
28187                rounds: 0,
28188            },
28189            &mut mon,
28190            1,
28191        );
28192        assert!(matches!(first, SpecTrial::Spec { rounds: 1, .. }));
28193
28194        // Two empty rounds in a row happen to a good head: the trial goes on.
28195        mon.round(1.0, 1);
28196        let second = Pipeline::spec_trial_round(first, &mut mon, 2);
28197        assert!(
28198            matches!(second, SpecTrial::Spec { rounds: 2, .. }),
28199            "two empty rounds are not evidence enough to leave the drafts"
28200        );
28201        mon.round(1.0, 1);
28202        let third = Pipeline::spec_trial_round(second, &mut mon, 3);
28203        assert!(
28204            matches!(third, SpecTrial::Plain { gen0: 3, .. }),
28205            "three verifier-tip-only rounds must stop the losing MTP trial"
28206        );
28207        // A plain decision on three rounds is tried again soon.
28208        assert_eq!(mon.recheck_plain_at(3), 3 + super::SPEC_RECHECK_THIN);
28209
28210        // One successful draft resets the streak, so a viable head retains
28211        // the normal five-round measurement budget.
28212        let mut viable = SpecMon::default();
28213        viable.round(1.0, 1);
28214        viable.round(1.0, 2);
28215        let continued = Pipeline::spec_trial_round(
28216            SpecTrial::Spec {
28217                t0: start,
28218                gen0: 0,
28219                rounds: 1,
28220            },
28221            &mut viable,
28222            3,
28223        );
28224        assert!(matches!(continued, SpecTrial::Spec { rounds: 2, .. }));
28225    }
28226
28227    #[test]
28228    fn fresh_mtp_request_does_not_inherit_full_head_streak() {
28229        let mut p = spark_test_pipeline(None);
28230        let head_rows = 248_070;
28231        p.draft_full_streak = 7;
28232        assert_eq!(p.draft_head_rows(head_rows), head_rows);
28233
28234        p.reset_fresh_mtp_draft_state();
28235        assert_eq!(
28236            p.draft_head_rows(head_rows),
28237            super::Pipeline::draft_vocab_rows(head_rows),
28238            "a fresh request returns to its configured shortlist"
28239        );
28240
28241        // A high-id first token of the NEW request still restores the
28242        // full-head protection immediately.
28243        p.note_draft_id(u32::MAX);
28244        assert_eq!(p.draft_head_rows(head_rows), head_rows);
28245    }
28246
28247    #[test]
28248    fn native_metal_batch_spec_defaults_on_over_a_q4tp_trunk() {
28249        use super::graph_spec_wanted_by_policy;
28250
28251        // A default-eligible (q4tp trunk) native Metal model drafts unless
28252        // told not to; any value other than 0/1 means the default there.
28253        assert!(graph_spec_wanted_by_policy(None, true, false, false, true));
28254        assert!(graph_spec_wanted_by_policy(
28255            Some("anything-but-1"),
28256            true,
28257            false,
28258            false,
28259            true,
28260        ));
28261        // A trunk outside the default (not q4tp) stays plain until asked.
28262        assert!(!graph_spec_wanted_by_policy(None, false, false, false, true));
28263        assert!(!graph_spec_wanted_by_policy(
28264            Some("anything-but-1"),
28265            false,
28266            false,
28267            false,
28268            true,
28269        ));
28270        assert!(graph_spec_wanted_by_policy(
28271            Some("1"),
28272            false,
28273            true,
28274            false,
28275            true,
28276        ));
28277        assert!(!graph_spec_wanted_by_policy(
28278            Some("0"),
28279            true,
28280            false,
28281            false,
28282            true,
28283        ));
28284
28285        // Do not regress the established discrete/wgpu policy while closing
28286        // the native-Metal quality gate.
28287        assert!(graph_spec_wanted_by_policy(None, true, false, false, false));
28288        assert!(graph_spec_wanted_by_policy(
28289            Some("legacy-force"),
28290            false,
28291            true,
28292            true,
28293            false,
28294        ));
28295    }
28296
28297    #[test]
28298    fn encoder_hidden_states_are_normalized_and_reusable() {
28299        let mut p = super::create_test_pipeline(8, 12, 2, 1, 4, 2, 32);
28300        let ids = [1, 7, 11, 19];
28301
28302        let first = p.encode_hidden_states(&ids).expect("encoder forward");
28303        let second = p
28304            .encode_hidden_states(&ids)
28305            .expect("reusable encoder forward");
28306        assert_eq!(first.len(), ids.len() * 8);
28307        assert!(first.iter().all(|v| v.is_finite()));
28308        assert_eq!(
28309            first, second,
28310            "encoder forward must start from a fresh state"
28311        );
28312
28313        // An encoder call must not leave stale KV/GDN state behind for the
28314        // regular generative API sharing the same Pipeline implementation.
28315        assert!(p.forward_ids(&ids, None).is_ok());
28316    }
28317
28318    /// The 0.7.6 prefill-chunk rule: a plain dense stack wholly on a
28319    /// discrete card reads the prompt in wide chunks on x86; every other
28320    /// case keeps the width it had (the GDN-hybrid, MoE and DeepSeek paths
28321    /// were tuned on hardware not measured for this change).
28322    #[test]
28323    fn prefill_chunk_rule_widens_only_dense_on_discrete() {
28324        use super::{ChunkHost, ChunkStackFacts, DISCRETE_DENSE_PREFILL_CHUNK, prefill_chunk_rule};
28325        let dense_card = ChunkStackFacts {
28326            plain_dense: true,
28327            discrete: true,
28328            gpu_on: true,
28329            ..Default::default()
28330        };
28331        assert!(dense_card.dense_on_discrete());
28332        // The bug: a dense Llama on a Vulkan RTX 3090 got 48.
28333        assert_eq!(
28334            prefill_chunk_rule(None, ChunkHost::Other, dense_card.dense_on_discrete()),
28335            DISCRETE_DENSE_PREFILL_CHUNK
28336        );
28337        assert!(DISCRETE_DENSE_PREFILL_CHUNK > 48);
28338        for (label, facts) in [
28339            (
28340                "GDN hybrid / MoE / DeepSeek stack",
28341                ChunkStackFacts {
28342                    plain_dense: false,
28343                    ..dense_card
28344                },
28345            ),
28346            (
28347                "integrated GPU",
28348                ChunkStackFacts {
28349                    discrete: false,
28350                    ..dense_card
28351                },
28352            ),
28353            (
28354                "CPU only",
28355                ChunkStackFacts {
28356                    gpu_on: false,
28357                    discrete: false,
28358                    ..dense_card
28359                },
28360            ),
28361            (
28362                "capacity split",
28363                ChunkStackFacts {
28364                    capacity_split: true,
28365                    ..dense_card
28366                },
28367            ),
28368            (
28369                "multi-GPU plan",
28370                ChunkStackFacts {
28371                    multi_gpu: true,
28372                    ..dense_card
28373                },
28374            ),
28375            (
28376                "O(1) layers",
28377                ChunkStackFacts {
28378                    o1: true,
28379                    ..dense_card
28380                },
28381            ),
28382        ] {
28383            assert!(!facts.dense_on_discrete(), "{label}");
28384            assert_eq!(
28385                prefill_chunk_rule(None, ChunkHost::Other, facts.dense_on_discrete()),
28386                48,
28387                "{label} keeps the historical x86 chunk"
28388            );
28389        }
28390        // Other hosts are untouched whatever the model.
28391        for dense in [false, true] {
28392            assert_eq!(prefill_chunk_rule(None, ChunkHost::Macos, dense), 512);
28393            assert_eq!(prefill_chunk_rule(None, ChunkHost::Aarch64, dense), 256);
28394        }
28395        // CMF_PREFILL_CHUNK still wins everywhere (and is clamped to ≥ 1).
28396        for host in [ChunkHost::Macos, ChunkHost::Aarch64, ChunkHost::Other] {
28397            for dense in [false, true] {
28398                assert_eq!(prefill_chunk_rule(Some(48), host, dense), 48);
28399                assert_eq!(prefill_chunk_rule(Some(0), host, dense), 1);
28400            }
28401        }
28402    }
28403
28404    #[test]
28405    fn kv_reuse_plan_pulls_rows_decode_wrote_only_on_the_device() {
28406        use super::{ReuseLayer, ReusePlan, kv_reuse_plan};
28407        let full = |host_rows, device_rows| ReuseLayer {
28408            full: true,
28409            host_rows,
28410            device_rows,
28411            device_state: false,
28412        };
28413        // Turn 1: 300-token prompt prefilled on the host, 40 tokens decoded
28414        // by the wgpu graph into the device mirror only. Turn 2 reuses 339.
28415        assert_eq!(
28416            kv_reuse_plan(339, &[full(300, Some(339)), full(300, Some(339))]),
28417            ReusePlan::Pull(vec![(0, 300, 339), (1, 300, 339)])
28418        );
28419        // CPU / Metal: the host owner already holds every forwarded row.
28420        assert_eq!(kv_reuse_plan(339, &[full(339, None)]), ReusePlan::Ready);
28421        // A mirror past the prefix is fine for the host (it gets rewound).
28422        assert_eq!(
28423            kv_reuse_plan(339, &[full(339, Some(345))]),
28424            ReusePlan::Ready
28425        );
28426        // GPU prefix / CPU tail: only the device layers lag.
28427        assert_eq!(
28428            kv_reuse_plan(339, &[full(300, Some(339)), full(339, None)]),
28429            ReusePlan::Pull(vec![(0, 300, 339)])
28430        );
28431        // The device cannot supply the missing rows: never continue.
28432        assert_eq!(
28433            kv_reuse_plan(339, &[full(300, Some(320))]),
28434            ReusePlan::Fresh
28435        );
28436        assert_eq!(kv_reuse_plan(339, &[full(300, None)]), ReusePlan::Fresh);
28437        assert_eq!(kv_reuse_plan(339, &[full(350, None)]), ReusePlan::Fresh);
28438        // A recurrent state advanced on the device cannot be handed to a
28439        // host prefill (it is not rewindable and the host copy is stale).
28440        let conv = |device_state| ReuseLayer {
28441            full: false,
28442            host_rows: 0,
28443            device_rows: None,
28444            device_state,
28445        };
28446        assert_eq!(
28447            kv_reuse_plan(339, &[conv(true), full(300, Some(339))]),
28448            ReusePlan::Fresh
28449        );
28450        assert_eq!(
28451            kv_reuse_plan(339, &[conv(false), full(339, None)]),
28452            ReusePlan::Ready
28453        );
28454    }
28455
28456    #[test]
28457    fn nll_graph_policy_scopes_only_the_fused_head() {
28458        for (label, unmasked, prefer_graph, native_metal, want_graph, want_head) in [
28459            // A Vulkan/Wgpu hidden-only graph remains the quality route.
28460            ("vulkan graph", true, true, false, true, false),
28461            // Native Metal adds the strict fused graph-head contract.
28462            ("native Metal graph", true, true, true, true, true),
28463            // Masked NLL and the explicit non-graph fallback remain unchanged.
28464            ("masked", false, true, false, false, false),
28465            ("graph disabled", true, false, true, false, false),
28466        ] {
28467            let (graph_quality, graph_head_required) =
28468                super::nll_graph_policy(unmasked, prefer_graph, native_metal);
28469            assert_eq!(graph_quality, want_graph, "{label}: graph quality");
28470            assert_eq!(graph_head_required, want_head, "{label}: fused head");
28471        }
28472    }
28473
28474    #[test]
28475    fn mtp_prefill_pair_boundaries_skip_only_final_prompt_row() {
28476        assert_eq!(mtp_prefill_pair_count(0, 128, 256), 128);
28477        assert_eq!(mtp_prefill_pair_count(128, 256, 256), 127);
28478        assert_eq!(mtp_prefill_pair_count(0, 256, 256), 255);
28479        assert_eq!(mtp_prefill_pair_count(256, 256, 256), 0);
28480        assert_eq!(mtp_prefill_pair_count(300, 320, 256), 0);
28481    }
28482
28483    #[test]
28484    fn cancel_flag_stops_generation() {
28485        let mut p = create_test_pipeline(16, 32, 2, 2, 8, 2, 32);
28486        // Set before the call: the prefill loops honour it, the run
28487        // returns immediately with the cancelled reason and no tokens.
28488        p.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
28489        let r = p.generate_from_ids(&[1, 2, 3], 8, None, None).unwrap();
28490        assert_eq!(r.finish_reason, "cancelled");
28491        assert!(
28492            r.token_ids.is_empty(),
28493            "no tokens after cancel: {:?}",
28494            r.token_ids
28495        );
28496        assert_eq!(p.kv_cache.seq_len(), 0);
28497        assert!(p.kv_history.is_empty());
28498        assert!(!p.graph_want_logits);
28499        assert!(p.graph_logits.is_none());
28500        // Flag auto-cleared: the next call generates normally.
28501        let r2 = p.generate_from_ids(&[1, 2, 3], 4, None, None).unwrap();
28502        assert_ne!(r2.finish_reason, "cancelled");
28503    }
28504    use super::*;
28505
28506    #[test]
28507    fn minimax_m3_arch_selects_checked_oai_activation_only() {
28508        // Keep this fixture minimal: `Act::from_arch_full` needs only the
28509        // architecture id and activation name, while serde supplies stable
28510        // defaults for unrelated CMF fields.
28511        let arch = |arch_name: &str, hidden_act: &str| {
28512            serde_json::from_value::<cortiq_core::ModelArch>(serde_json::json!({
28513                "arch_name": arch_name,
28514                "hidden_size": 8,
28515                "intermediate_size": 16,
28516                "num_layers": 1,
28517                "num_attention_heads": 1,
28518                "num_kv_heads": 1,
28519                "head_dim": 8,
28520                "vocab_size": 16,
28521                "layer_types": ["FullAttention"],
28522                "rms_norm_eps": 1e-6,
28523                "max_position_embeddings": 16,
28524                "hidden_act": hidden_act
28525            }))
28526            .expect("minimal architecture")
28527        };
28528        let minimax = arch("minimax_m3_vl", "swigluoai");
28529        assert_eq!(
28530            Act::from_arch_full(&minimax),
28531            Act::SwiGluOai {
28532                alpha: 1.702,
28533                limit: 7.0,
28534            }
28535        );
28536
28537        // The same spelling must not turn into MiniMax math on a generic
28538        // model.  Only the source-validated M3 architecture owns it.
28539        let unrelated = arch("qwen2", "swigluoai");
28540        assert_eq!(Act::from_arch_full(&unrelated), Act::Silu);
28541
28542        // Conversely, an M3-tagged header with a normal activation keeps the
28543        // normal path; this prevents the architecture id from overriding the
28544        // explicit serialized contract.
28545        let non_oai = arch("minimax_m3_vl", "gelu");
28546        assert_eq!(Act::from_arch_full(&non_oai), Act::Gelu);
28547    }
28548
28549    #[test]
28550    fn minimax_swiglu_oai_act_matches_scalar_contract() {
28551        let act = Act::swiglu_oai(1.702, 7.0);
28552        let got = act.combine(10.0, -10.0);
28553        let expected = crate::inference::swiglu_oai(10.0, -10.0, 1.702, 1.0, Some(7.0));
28554        assert!((got - expected).abs() < 1e-6);
28555        assert_eq!(act.graph_act(), None, "no inexact generic graph fallback");
28556        assert_eq!(
28557            act.wgpu_graph_act(),
28558            Some(crate::gpu::GraphAct::SwiGluOaiM3),
28559            "the WGPU-only arm accepts only the frozen M3 constants"
28560        );
28561        assert_eq!(
28562            Act::swiglu_oai(1.701, 7.0).wgpu_graph_act(),
28563            None,
28564            "nearby OAI constants must not borrow MiniMax's kernel"
28565        );
28566        assert_eq!(
28567            act.moe_job_graph_contract(),
28568            Some((crate::gpu::GraphAct::SwiGluOaiM3, 7.0)),
28569            "the direct MoE path carries the frozen clamp with the marker"
28570        );
28571        assert_eq!(
28572            Act::swiglu_oai(1.702, 6.999).moe_job_graph_contract(),
28573            None,
28574            "a nearby clamp must not borrow MiniMax's device contract"
28575        );
28576
28577        // `apply` is the gate half only; `combine` owns the up clamp and
28578        // +1 offset. The two must not accidentally collapse to ordinary SiLU.
28579        let gate_only = act.apply(-10.0);
28580        let expected_gate = -10.0 / (1.0 + (17.02f32).exp());
28581        assert!((gate_only - expected_gate).abs() < 1e-10);
28582    }
28583
28584    #[test]
28585    fn explicit_sliding_schedule_selects_local_rope_profile() {
28586        // Mellum alternates three local 1,024-token layers with one global
28587        // YaRN layer.  An explicit schedule deliberately overrides the
28588        // cadence sentinel in `swa`, so test both RoPE table and scale
28589        // dispatch rather than merely checking that the metadata loaded.
28590        let mut p = create_test_pipeline(32, 64, 4, 1, 8, 4, 32);
28591        p.swa = Some((1024, usize::MAX));
28592        p.sliding_layers = Some(vec![true, true, true, false]);
28593        p.inv_freq = std::sync::Arc::new(vec![0.125; 4]);
28594        p.inv_freq_local = Some(std::sync::Arc::new(vec![0.25; 4]));
28595        p.rope_scale = 1.277_258_9;
28596        p.rope_scale_local = 1.0;
28597
28598        for li in 0..3 {
28599            assert_eq!(p.layer_window(li), Some(1024), "local layer {li}");
28600            assert_eq!(p.layer_inv_freq(li).as_slice(), &[0.25; 4]);
28601            assert_eq!(p.layer_rope_scale(li), 1.0, "local layer {li}");
28602        }
28603        assert_eq!(p.layer_window(3), None);
28604        assert_eq!(p.layer_inv_freq(3).as_slice(), &[0.125; 4]);
28605        assert_eq!(p.layer_rope_scale(3), 1.277_258_9);
28606    }
28607
28608    /// sparse_ffn_quant must equal a dense FFN where inactive neurons are
28609    /// zeroed (mask × mmap correctness). On F32 tensors this is EXACT —
28610    /// it validates the row_dot / add_col_scaled / scatter indexing, the
28611    /// bug-prone part. The q8 branches reuse the golden-tested linear
28612    /// The per-token sparse path reads a transposed `down`; it must
28613    /// agree with the arm that computes everything and zeroes the
28614    /// losers, or the speed measurement is measuring a different model.
28615    #[test]
28616    fn dynamic_ffn_equals_the_zeroing_arm() {
28617        let (hidden, inter) = (8usize, 32usize);
28618        let synth = |n: usize, salt: usize| -> Vec<f32> {
28619            (0..n)
28620                .map(|i| (((i * 29 + salt * 13 + 7) % 89) as f32 / 89.0 - 0.5) * 0.6)
28621                .collect()
28622        };
28623        let down = synth(hidden * inter, 3);
28624        let mut down_t = vec![0.0f32; inter * hidden];
28625        for r in 0..hidden {
28626            for c in 0..inter {
28627                down_t[c * hidden + r] = down[r * inter + c];
28628            }
28629        }
28630        let d = DenseFfn {
28631            gate_proj: QTensor::from_f32(synth(inter * hidden, 1), inter, hidden),
28632            up_proj: QTensor::from_f32(synth(inter * hidden, 2), inter, hidden),
28633            down_proj: QTensor::from_f32(down.clone(), hidden, inter),
28634            act: Act::Silu,
28635            down_t: Some(QTensor::from_f32(down_t, inter, hidden)),
28636            segs: Vec::new(),
28637        };
28638        let x = synth(hidden, 11);
28639        let k = 12usize;
28640        let got = dense_ffn_dynamic(&d, &x, None, k).expect("down_t present");
28641        // Reference: full compute, keep the k loudest |silu(gate)|.
28642        let mut g = vec![0.0f32; inter];
28643        d.gate_proj.matvec(&x, &mut g, None);
28644        let mut u = vec![0.0f32; inter];
28645        d.up_proj.matvec(&x, &mut u, None);
28646        for v in g.iter_mut() {
28647            *v = inference::silu(*v);
28648        }
28649        keep_top_k(&mut g, k);
28650        for i in 0..inter {
28651            g[i] *= u[i];
28652        }
28653        let mut want = vec![0.0f32; hidden];
28654        d.down_proj.matvec(&g, &mut want, None);
28655        for (a, b) in want.iter().zip(&got) {
28656            assert!((a - b).abs() < 1e-5, "dynamic {b} vs reference {a}");
28657        }
28658    }
28659
28660    /// A tube layer is the same layer, re-cut. With every tube open the
28661    /// answer must equal the dense FFN over the concatenated neurons
28662    /// (the permutation is an identity on the layer's function); with a
28663    /// tube closed it must equal the dense FFN with those neurons
28664    /// zeroed — the mask semantics, now paid for in bytes not read.
28665    #[test]
28666    fn tube_ffn_open_equals_dense_and_closed_equals_masked() {
28667        let (hidden, core, tube) = (8usize, 12usize, 8usize);
28668        let inter = core + tube;
28669        let synth = |n: usize, salt: usize| -> Vec<f32> {
28670            (0..n)
28671                .map(|i| (((i * 41 + salt * 17 + 5) % 97) as f32 / 97.0 - 0.5) * 0.5)
28672                .collect()
28673        };
28674        let (g_all, u_all) = (synth(inter * hidden, 1), synth(inter * hidden, 2));
28675        let d_all = synth(hidden * inter, 3);
28676        // The dense layer, and the same weights cut into core + tube.
28677        let dense = DenseFfn {
28678            gate_proj: QTensor::from_f32(g_all.clone(), inter, hidden),
28679            up_proj: QTensor::from_f32(u_all.clone(), inter, hidden),
28680            down_proj: QTensor::from_f32(d_all.clone(), hidden, inter),
28681            act: Act::Silu,
28682            down_t: None,
28683            segs: Vec::new(),
28684        };
28685        let rows =
28686            |v: &[f32], a: usize, b: usize| -> Vec<f32> { v[a * hidden..b * hidden].to_vec() };
28687        let cols = |v: &[f32], a: usize, b: usize| -> Vec<f32> {
28688            let mut o = Vec::with_capacity(hidden * (b - a));
28689            for r in 0..hidden {
28690                o.extend_from_slice(&v[r * inter + a..r * inter + b]);
28691            }
28692            o
28693        };
28694        let tubed = DenseFfn {
28695            down_t: None,
28696            gate_proj: QTensor::from_f32(rows(&g_all, 0, core), core, hidden),
28697            up_proj: QTensor::from_f32(rows(&u_all, 0, core), core, hidden),
28698            down_proj: QTensor::from_f32(cols(&d_all, 0, core), hidden, core),
28699            act: Act::Silu,
28700            segs: vec![FfnSeg {
28701                gate: QTensor::from_f32(rows(&g_all, core, inter), tube, hidden),
28702                up: QTensor::from_f32(rows(&u_all, core, inter), tube, hidden),
28703                down: QTensor::from_f32(cols(&d_all, core, inter), hidden, tube),
28704                start: core,
28705                width: tube,
28706            }],
28707        };
28708        let x = synth(hidden, 7);
28709        let want = dense_ffn(&dense, &x, None);
28710        let got = tube_ffn(&tubed, &x, 1, None, None);
28711        for (a, b) in want.iter().zip(&got) {
28712            assert!((a - b).abs() < 1e-5, "open tube: {a} vs {b}");
28713        }
28714        // Closed tube: bits on for the core, off for the tube.
28715        let mut bits = vec![0u8; inter.div_ceil(8)];
28716        for n in 0..core {
28717            bits[n / 8] |= 1 << (n % 8);
28718        }
28719        let closed = tube_ffn(&tubed, &x, 1, None, Some(&bits));
28720        let masked = dense_ffn_masked(&dense, &x, None, &bits);
28721        for (a, b) in masked.iter().zip(&closed) {
28722            assert!((a - b).abs() < 1e-5, "closed tube: {a} vs {b}");
28723        }
28724        // The batched arm must agree with the single-position one.
28725        let batch = tube_ffn(&tubed, &x, 1, None, Some(&bits));
28726        for (a, b) in closed.iter().zip(&batch) {
28727            assert_eq!(a, b, "batch arm disagrees with decode arm");
28728        }
28729    }
28730
28731    /// scale, structurally identical to the matvec kernels.
28732    #[test]
28733    fn sparse_ffn_quant_equals_dense_with_inactive_zeroed() {
28734        let (hidden, inter) = (16usize, 40usize);
28735        let synth = |n: usize, salt: usize| -> Vec<f32> {
28736            (0..n)
28737                .map(|i| (((i * 37 + salt * 11 + 3) % 101) as f32 / 101.0 - 0.5) * 0.4)
28738                .collect()
28739        };
28740        let d = DenseFfn {
28741            gate_proj: QTensor::from_f32(synth(inter * hidden, 1), inter, hidden),
28742            up_proj: QTensor::from_f32(synth(inter * hidden, 2), inter, hidden),
28743            down_proj: QTensor::from_f32(synth(hidden * inter, 3), hidden, inter),
28744            act: Act::Silu,
28745            down_t: None,
28746            segs: Vec::new(),
28747        };
28748        let x = synth(hidden, 9);
28749        // Active = every 3rd neuron.
28750        let active: Vec<u16> = (0..inter as u16).filter(|i| i % 3 == 0).collect();
28751
28752        let sparse = sparse_ffn_quant(&d, &x, &active, hidden, None);
28753
28754        // Reference: full dense FFN but g[i]=0 for inactive neurons.
28755        let mut g = vec![0.0f32; inter];
28756        d.gate_proj.matvec(&x, &mut g, None);
28757        let mut u = vec![0.0f32; inter];
28758        d.up_proj.matvec(&x, &mut u, None);
28759        let act_set: std::collections::HashSet<u16> = active.iter().copied().collect();
28760        for i in 0..inter {
28761            g[i] = if act_set.contains(&(i as u16)) {
28762                inference::silu(g[i]) * u[i]
28763            } else {
28764                0.0
28765            };
28766        }
28767        let mut reference = vec![0.0f32; hidden];
28768        d.down_proj.matvec(&g, &mut reference, None);
28769
28770        let max_d = sparse
28771            .iter()
28772            .zip(&reference)
28773            .map(|(a, b)| (a - b).abs())
28774            .fold(0.0f32, f32::max);
28775        assert!(max_d < 1e-5, "sparse != dense-zeroed: max|Δ| = {max_d}");
28776    }
28777
28778    /// Attach a synthetic MTP head. `inter` deliberately stays independent
28779    /// from the trunk width so calibration tests can catch a trunk-proxy bug.
28780    fn attach_test_mtp_width(p: &mut Pipeline, inter: usize) {
28781        let (h, inter, heads, kv, hd) = (
28782            p.hidden_size,
28783            inter,
28784            p.num_heads,
28785            p.num_kv_heads,
28786            p.head_dim,
28787        );
28788        let synth = |n: usize, salt: usize| -> Vec<f32> {
28789            (0..n)
28790                .map(|i| (((i * 29 + salt * 23 + 5) % 101) as f32 / 101.0 - 0.5) * 0.2)
28791                .collect()
28792        };
28793        let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
28794            QTensor::from_f32(synth(rows * cols, salt), rows, cols)
28795        };
28796        p.mtp = Some(MtpModule {
28797            enorm: vec![1.0; h],
28798            hnorm: vec![1.0; h],
28799            eh_proj: qt(h, 2 * h, 301),
28800            layer: LayerWeights {
28801                input_norm: vec![1.0; h],
28802                post_norm: vec![1.0; h],
28803                attn_out_norm: None,
28804                ffn_out_norm: None,
28805                layer_scale: None,
28806                ffn: FfnKind::Dense(DenseFfn {
28807                    gate_proj: qt(inter, h, 315),
28808                    up_proj: qt(inter, h, 316),
28809                    down_proj: qt(h, inter, 317),
28810                    act: Act::Silu,
28811                    down_t: None,
28812                    segs: Vec::new(),
28813                }),
28814                attn: AttnKind::Full {
28815                    bias: None,
28816                    wq: qt(heads * hd, h, 311),
28817                    wk: qt(kv * hd, h, 312),
28818                    wv: qt(kv * hd, h, 313),
28819                    wo: qt(h, heads * hd, 314),
28820                    q_norm: None,
28821                    k_norm: None,
28822                    output_gate: false,
28823                    softplus_gate: None,
28824                },
28825            },
28826            final_norm: vec![1.0; h],
28827            kv: crate::kv_cache::LayerKvCache::new(kv, hd),
28828        });
28829    }
28830
28831    /// Attach a synthetic MTP head with the trunk's conventional width.
28832    fn attach_test_mtp(p: &mut Pipeline) {
28833        attach_test_mtp_width(p, p.intermediate_size);
28834    }
28835
28836    #[test]
28837    fn canonical_mtp_ffn_probe_uses_draft_width_and_cleans_state() {
28838        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 64);
28839        // This differs from the trunk FFN width (16). A result shaped like
28840        // the trunk probe would be a silent, dangerous compaction bug.
28841        attach_test_mtp_width(&mut p, 11);
28842        let ids = [3, 9, 4, 12, 7, 2];
28843        let trunk = p.probe_ffn_mass(&ids);
28844        assert_eq!(trunk[0].len(), p.intermediate_size);
28845
28846        let got = p.probe_mtp_ffn(&ids).expect("canonical MTP probe");
28847        assert_eq!(got.len(), 1);
28848        assert_eq!(got[0].mass.len(), 11);
28849        assert_eq!(got[0].squared_mass.len(), 11);
28850        assert_eq!(got[0].observed_positions, ids.len() - 1);
28851        assert!(got[0].mass.iter().any(|&v| v > 0.0));
28852        assert!(got[0]
28853            .mass
28854            .iter()
28855            .zip(&got[0].squared_mass)
28856            .all(|(&m, &s)| m.is_finite() && s.is_finite() && m >= 0.0 && s >= 0.0));
28857        assert_eq!(p.kv_cache.seq_len(), 0, "probe must leave a fresh trunk");
28858        assert_eq!(p.mtp.as_ref().unwrap().kv.seq_len, 0, "and fresh MTP KV");
28859
28860        // Force an error *after* the MTP attention has appended a draft KV
28861        // row. This proves the error path clears detached draft state, not
28862        // merely the easy invalid-token preflight branch.
28863        let h = p.hidden_size;
28864        let FfnKind::Dense(dense) = &mut p.mtp.as_mut().unwrap().layer.ffn else {
28865            panic!("synthetic MTP must be dense")
28866        };
28867        dense.segs.push(FfnSeg {
28868            gate: QTensor::from_f32(vec![0.0; h], 1, h),
28869            up: QTensor::from_f32(vec![0.0; h], 1, h),
28870            down: QTensor::from_f32(vec![0.0; h], h, 1),
28871            start: dense.gate_proj.rows(),
28872            width: 1,
28873        });
28874        let err = p.probe_mtp_ffn(&ids);
28875        assert!(err
28876            .unwrap_err()
28877            .contains("tube-segmented draft FFNs are not supported"));
28878        assert_eq!(p.kv_cache.seq_len(), 0);
28879        assert_eq!(p.mtp.as_ref().unwrap().kv.seq_len, 0);
28880    }
28881
28882    #[test]
28883    fn speculative_equals_vanilla_greedy() {
28884        let _env_lock = MTP_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
28885        // Exercise the experimental host pair deterministically; the native
28886        // and wgpu batch graphs have independent coverage.
28887        let _env = ScopedTestEnv::set(&[
28888            ("CMF_GPU", Some("0")),
28889            ("CMF_GPU_WGPU_GRAPH", Some("0")),
28890            ("CMF_MTP_PAIR", Some("1")),
28891        ]);
28892        let run = |spec: bool| {
28893            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
28894            p.sampler_config.temperature = 0.0;
28895            attach_test_mtp(&mut p);
28896            p.speculative = spec;
28897            let r = p.generate("abcdef", 12, None, None).unwrap();
28898            (r.token_ids, r.mtp_drafted, r.mtp_accepted)
28899        };
28900        let (vanilla, d0, _) = run(false);
28901        let (spec, d1, a1) = run(true);
28902        assert_eq!(d0, 0, "vanilla path must not draft");
28903        assert!(d1 > 0, "speculative path must draft");
28904        assert!(a1 <= d1, "accepted drafts cannot exceed proposals");
28905        assert_eq!(
28906            vanilla, spec,
28907            "speculative must reproduce the exact greedy sequence (accepted {a1}/{d1})"
28908        );
28909    }
28910
28911    #[test]
28912    fn speculative_accepts_constant_oracle() {
28913        let _env_lock = MTP_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
28914        let _env = ScopedTestEnv::set(&[
28915            ("CMF_GPU", Some("0")),
28916            ("CMF_GPU_WGPU_GRAPH", Some("0")),
28917            ("CMF_MTP_PAIR", Some("1")),
28918        ]);
28919        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
28920        p.sampler_config.temperature = 0.0;
28921        p.sampler_config.repetition_penalty = 1.0;
28922        // Constant lm_head → every logit equal → both the main model and
28923        // the draft head argmax to token 0: acceptance must be 100%.
28924        p.weights.lm_head = QTensor::from_f32(vec![0.01; 64 * 8], 64, 8);
28925        attach_test_mtp(&mut p);
28926        p.speculative = true;
28927        let r = p.generate("abcd", 10, None, None).unwrap();
28928        assert!(r.mtp_drafted > 0);
28929        assert_eq!(
28930            r.mtp_accepted, r.mtp_drafted,
28931            "constant logits → every draft accepted"
28932        );
28933        // Ties resolve to the same token in both the main and draft
28934        // heads — the sequence is one repeated token.
28935        assert!(r.token_ids.windows(2).all(|w| w[0] == w[1]));
28936    }
28937
28938    #[test]
28939    fn host_fused_mtp_pair_is_opt_in() {
28940        let _env_lock = MTP_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
28941        let _env = ScopedTestEnv::set(&[
28942            ("CMF_GPU", Some("0")),
28943            ("CMF_GPU_WGPU_GRAPH", Some("0")),
28944            ("CMF_MTP_PAIR", None),
28945        ]);
28946        let run = |spec: bool| {
28947            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
28948            p.sampler_config.temperature = 0.0;
28949            attach_test_mtp(&mut p);
28950            p.speculative = spec;
28951            let r = p.generate("abcdef", 12, None, None).unwrap();
28952            (r.token_ids, r.mtp_drafted, r.mtp_accepted)
28953        };
28954        let (plain, d0, _) = run(false);
28955        let (guarded, d1, a1) = run(true);
28956        assert_eq!(d0, 0);
28957        assert_eq!(d1, 0, "host MTP pair must remain opt-in");
28958        assert_eq!(a1, 0);
28959        assert_eq!(guarded, plain, "the safe default is ordinary greedy decode");
28960    }
28961
28962    #[test]
28963    fn empty_prompt_is_an_error_not_a_panic() {
28964        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
28965        let r = p.generate("", 4, None, None);
28966        assert!(r.is_err(), "empty prompt must be a clean error");
28967    }
28968
28969    #[test]
28970    fn every_token_enters_kv_exactly_once() {
28971        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
28972        // Greedy so no RNG variance; byte tokenizer → 3 prompt tokens.
28973        p.sampler_config.temperature = 0.0;
28974        let r = p.generate("abc", 2, None, None).unwrap();
28975        assert_eq!(r.prompt_tokens, 3);
28976        // prompt(3) + first sampled token forwarded before second logits:
28977        // step0 samples from prefill hidden (no extra forward), then
28978        // forwards t1 → cache 4; step1 samples, loop ends (max_tokens).
28979        assert_eq!(
28980            p.kv_cache.seq_len(),
28981            3 + r.tokens_generated - 1,
28982            "each token must be cached exactly once (v1 cached the last prompt token twice)"
28983        );
28984    }
28985
28986    #[test]
28987    fn generation_is_reproducible_with_seed() {
28988        let run = || {
28989            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
28990            p.generate("hello", 8, None, None).unwrap().token_ids
28991        };
28992        assert_eq!(run(), run());
28993    }
28994
28995    #[test]
28996    fn resetting_sampler_restarts_the_seeded_stream() {
28997        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
28998        let config = SamplerConfig {
28999            seed: Some(1234),
29000            ..SamplerConfig::default()
29001        };
29002        p.set_sampler_config(config.clone());
29003        let first = p.generate("hello", 8, None, None).unwrap().token_ids;
29004        p.set_sampler_config(config);
29005        let second = p.generate("hello", 8, None, None).unwrap().token_ids;
29006        assert_eq!(first, second);
29007    }
29008
29009    #[test]
29010    fn eviction_bounds_the_cache() {
29011        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
29012        p.kv_cache.max_seq_len = 6;
29013        p.sampler_config.temperature = 0.0;
29014        let _ = p.generate("abcd", 12, None, None).unwrap();
29015        assert!(
29016            p.kv_cache.seq_len() <= 6 + 1,
29017            "cache must stay bounded by max_seq_len (got {})",
29018            p.kv_cache.seq_len()
29019        );
29020    }
29021
29022    #[test]
29023    fn confidence_matches_tokens_and_is_a_probability() {
29024        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
29025        p.sampler_config.temperature = 0.0;
29026        p.sampler_config.repetition_penalty = 1.0;
29027        let r = p.generate("abcd", 10, None, None).unwrap();
29028        assert_eq!(
29029            r.token_confidence.len(),
29030            r.token_ids.len(),
29031            "one confidence per emitted token"
29032        );
29033        for &c in &r.token_confidence {
29034            assert!((0.0..=1.0).contains(&c), "confidence out of [0,1]: {c}");
29035        }
29036        // top1_prob is a valid softmax probability.
29037        let logits = [1.0f32, 3.0, 0.5, 3.0];
29038        let p0 = top1_prob_t(&logits, 1, 1.0);
29039        let p1 = top1_prob_t(&logits, 3, 1.0);
29040        assert!((p0 - p1).abs() < 1e-6, "equal logits → equal prob");
29041        assert!(p0 > 0.0 && p0 < 1.0);
29042        // Calibration temperature > 1 softens an over-confident peak.
29043        let sharp = top1_prob_t(&logits, 1, 1.0);
29044        let soft = top1_prob_t(&logits, 1, 2.0);
29045        assert!(soft < sharp, "higher temperature lowers peak confidence");
29046    }
29047
29048    #[test]
29049    fn trace_is_opt_in_and_parallels_the_output() {
29050        // Off by default: the runtime is silent unless observation asked.
29051        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
29052        p.sampler_config.temperature = 0.0;
29053        p.sampler_config.repetition_penalty = 1.0;
29054        let r = p.generate("abcd", 10, None, None).unwrap();
29055        assert!(r.traces.is_empty(), "trace must be empty unless enabled");
29056
29057        // On: exactly one row per emitted token, aligned with the output.
29058        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
29059        p.sampler_config.temperature = 0.0;
29060        p.sampler_config.repetition_penalty = 1.0;
29061        p.set_trace(true);
29062        let r = p.generate("abcd", 10, None, None).unwrap();
29063        assert_eq!(r.traces.len(), r.token_ids.len(), "one trace row per token");
29064        for (i, tr) in r.traces.iter().enumerate() {
29065            assert_eq!(tr.t, i, "trace index is sequential");
29066            assert_eq!(tr.token_id, r.token_ids[i], "trace token_id matches output");
29067            assert_eq!(
29068                tr.confidence, r.token_confidence[i],
29069                "trace confidence matches the confidence channel"
29070            );
29071            // No dynamic router in this pipeline → no skill, no coherence.
29072            assert!(tr.active_skill.is_none() && tr.recon.is_none() && !tr.switched);
29073        }
29074    }
29075
29076    #[test]
29077    fn explain_prefill_logits_match_greedy_first_token() {
29078        // `cortiq explain` shows the next-token distribution from
29079        // prefill_next_logits; its argmax must equal what greedy generate
29080        // actually emits first — otherwise explain would lie.
29081        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
29082        p.sampler_config.temperature = 0.0;
29083        p.sampler_config.repetition_penalty = 1.0;
29084        let ids = p.tokenizer.encode("abcd");
29085        let logits = p.prefill_next_logits(&ids, None);
29086        let argmax = logits
29087            .iter()
29088            .enumerate()
29089            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
29090            .unwrap()
29091            .0 as u32;
29092        let r = p.generate("abcd", 1, None, None).unwrap();
29093        assert_eq!(
29094            argmax, r.token_ids[0],
29095            "explain preview must match greedy emit"
29096        );
29097    }
29098
29099    #[test]
29100    fn laguna_shared_expert_is_unconditionally_added() {
29101        let matrix = |values: Vec<f32>| QTensor::from_f32(values, 2, 2);
29102        let identity = || matrix(vec![1.0, 0.0, 0.0, 1.0]);
29103        let zero_dense = || DenseFfn {
29104            gate_proj: matrix(vec![0.0; 4]),
29105            up_proj: matrix(vec![0.0; 4]),
29106            down_proj: matrix(vec![0.0; 4]),
29107            act: Act::Silu,
29108            down_t: None,
29109            segs: Vec::new(),
29110        };
29111        let shared = DenseFfn {
29112            gate_proj: identity(),
29113            up_proj: identity(),
29114            down_proj: identity(),
29115            act: Act::Silu,
29116            down_t: None,
29117            segs: Vec::new(),
29118        };
29119        let x = [1.0, 2.0];
29120        let expected = dense_ffn(&shared, &x, None);
29121        let moe = MoeFfn {
29122            router: QTensor::from_f32(vec![0.0, 0.0], 1, 2),
29123            experts: vec![zero_dense()],
29124            top_k: 1,
29125            norm_topk_prob: true,
29126            router_sigmoid: true,
29127            sigmoid_denom_eps: 1e-6,
29128            expert_bias: None,
29129            routed_scaling: 1.0,
29130            route_tau: None,
29131            shared: Some((shared, None)),
29132            stats: std::cell::RefCell::new(Vec::new()),
29133            act_sq: std::cell::RefCell::new(Vec::new()),
29134            act_rows: std::cell::RefCell::new(Vec::new()),
29135            mask: None,
29136            per_expert_scale: None,
29137            router_input_norm: false,
29138            resonance: None,
29139            grown: Vec::new(),
29140        };
29141        let actual = moe_ffn_cpu(&moe, &x, &[0], &[0.0], 1.0, None);
29142        for (actual, expected) in actual.iter().zip(expected) {
29143            assert!((actual - expected).abs() < 1e-6);
29144        }
29145    }
29146
29147    /// A tiny MiMo-V2-shaped stack (the M3 fixture): layers [full, sliding,
29148    /// sliding, full]; 4 Q heads over 1 (full) / 2 (sliding) KV heads;
29149    /// head_dim 8 with 4-wide V heads; partial rotary 4 at θ 1e7 (full) /
29150    /// 1e4 (sliding); window 3; learned sinks on the sliding layers; layer
29151    /// 0 a dense FFN, layers 1..3 sigmoid-routed MoE with a selection bias
29152    /// (4 experts, top-2, renormalized, no shared expert). Geometry and
29153    /// sinks go through the same `set_attn_geometry` / `set_layer_sinks`
29154    /// the loader calls.
29155    fn mimo_test_pipeline() -> Pipeline {
29156        let (hs, inter, nh, hd, vd, vocab) = (16usize, 24usize, 4usize, 8usize, 4usize, 64usize);
29157        let kvh = [1usize, 2, 2, 1];
29158        let synth = |n: usize, salt: usize| -> Vec<f32> {
29159            (0..n)
29160                .map(|i| (((i * 31 + salt * 17 + 7) % 97) as f32 / 97.0 - 0.5) * 0.4)
29161                .collect()
29162        };
29163        let qt = |rows: usize, cols: usize, salt: usize| {
29164            QTensor::from_f32(synth(rows * cols, salt), rows, cols)
29165        };
29166        let dense = |inter: usize, salt: usize| DenseFfn {
29167            gate_proj: qt(inter, hs, salt),
29168            up_proj: qt(inter, hs, salt + 1),
29169            down_proj: qt(hs, inter, salt + 2),
29170            act: Act::Silu,
29171            down_t: None,
29172            segs: Vec::new(),
29173        };
29174        let layers: Vec<LayerWeights> = (0..4)
29175            .map(|li| LayerWeights {
29176                input_norm: vec![1.0; hs],
29177                post_norm: vec![1.0; hs],
29178                attn_out_norm: None,
29179                ffn_out_norm: None,
29180                layer_scale: None,
29181                ffn: if li == 0 {
29182                    FfnKind::Dense(dense(inter, 50))
29183                } else {
29184                    FfnKind::Moe(MoeFfn {
29185                        router: qt(4, hs, 60 + li),
29186                        experts: (0..4).map(|e| dense(8, 70 + li * 10 + e * 3)).collect(),
29187                        top_k: 2,
29188                        norm_topk_prob: true,
29189                        router_sigmoid: true,
29190                        sigmoid_denom_eps: 1e-6,
29191                        expert_bias: Some(vec![0.02, -0.03, 0.01, 0.0]),
29192                        routed_scaling: 1.0,
29193                        route_tau: None,
29194                        shared: None,
29195                        stats: std::cell::RefCell::new(Vec::new()),
29196                        act_sq: std::cell::RefCell::new(Vec::new()),
29197                        act_rows: std::cell::RefCell::new(Vec::new()),
29198                        mask: None,
29199                        per_expert_scale: None,
29200                        router_input_norm: false,
29201                        resonance: None,
29202                        grown: Vec::new(),
29203                    })
29204                },
29205                attn: AttnKind::Full {
29206                    wq: qt(nh * hd, hs, li * 10 + 1),
29207                    wk: qt(kvh[li] * hd, hs, li * 10 + 2),
29208                    wv: qt(kvh[li] * vd, hs, li * 10 + 3),
29209                    wo: qt(hs, nh * vd, li * 10 + 4),
29210                    q_norm: None,
29211                    k_norm: None,
29212                    output_gate: false,
29213                    softplus_gate: None,
29214                    bias: None,
29215                },
29216            })
29217            .collect();
29218        let mut p = Pipeline::new(
29219            Tokenizer::byte_level(),
29220            PipelineWeights {
29221                embed_tokens: qt(vocab, hs, 100),
29222                layers,
29223                lm_head: qt(vocab, hs, 200),
29224                final_norm: vec![1.0; hs],
29225            },
29226            hs,
29227            inter,
29228            nh,
29229            1, // header num_kv_heads (the full layers')
29230            hd,
29231            4,
29232            4,
29233            false,
29234            vocab,
29235            1e-6,
29236            1e7,
29237            NormStyle::Qwen,
29238            4096,
29239            SamplerConfig {
29240                seed: Some(7),
29241                ..Default::default()
29242            },
29243        );
29244        // Diagnostics stay off whatever the test environment exports.
29245        p.layer_dump = None;
29246        p.set_rotary(4, 1e7);
29247        p.sliding_layers = Some(vec![false, true, true, false]);
29248        p.swa = Some((3, usize::MAX));
29249        p.rotary_dim_local = Some(4);
29250        p.inv_freq_local = Some(std::sync::Arc::new(attention::rope_inv_freq(4, 1e4)));
29251        p.set_attn_geometry(Some(kvh.to_vec()), Some(vd)).unwrap();
29252        p.set_layer_sinks(1, vec![0.5, -1.0, 1.5, 0.0]).unwrap();
29253        p.set_layer_sinks(2, vec![-0.25, 2.0, 0.75, -1.5]).unwrap();
29254        p
29255    }
29256
29257    #[test]
29258    fn mimo_embedded_prompt_uses_rows_and_never_reuses_token_only_kv() {
29259        let mut p = mimo_test_pipeline();
29260        p.speculative = false;
29261        p.ignore_eos = true;
29262        p.sampler_config.temperature = 0.0;
29263        p.sampler_config.repetition_penalty = 1.0;
29264        let a = vec![3, 5, 7, 9, 11, 13];
29265        let b = vec![4, 8, 12, 16, 20, 24];
29266        let rows: Vec<_> = b.iter().flat_map(|&id| p.embed_id(id)).collect();
29267        let expected = p.generate_from_ids(&b, 8, None, None).unwrap().token_ids;
29268        // Same placeholder IDs as an earlier request are not a cache key
29269        // for different media. The actual rows, not a re-embedding of a,
29270        // must determine the continuation.
29271        let actual = p
29272            .generate_from_embeds(&a, &rows, 8, None, None)
29273            .unwrap()
29274            .token_ids;
29275        assert_eq!(actual, expected);
29276        assert!(p.kv_history.is_empty());
29277        let mut extended = a.clone();
29278        extended.push(17);
29279        let after_media = p
29280            .generate_from_ids(&extended, 8, None, None)
29281            .unwrap()
29282            .token_ids;
29283        p.reset_session();
29284        let fresh = p
29285            .generate_from_ids(&extended, 8, None, None)
29286            .unwrap()
29287            .token_ids;
29288        assert_eq!(after_media, fresh);
29289        assert!(
29290            p.generate_from_embeds(&a, &rows[..rows.len() - 1], 1, None, None)
29291                .is_err()
29292        );
29293        // Force a real token-prefix reuse opportunity into the media call.
29294        // Those labels are unchanged, but their embeddings now describe a
29295        // different source sequence and every KV row must be rebuilt.
29296        p.reset_session();
29297        p.generate_from_ids(&a, 1, None, None).unwrap();
29298        let mut media_ids = p.kv_history.clone();
29299        assert!(!media_ids.is_empty());
29300        media_ids.extend_from_slice(&[19, 21, 23]);
29301        let source_ids: Vec<_> = (0..media_ids.len()).map(|i| b[i % b.len()]).collect();
29302        let source_rows: Vec<_> = source_ids.iter().flat_map(|&id| p.embed_id(id)).collect();
29303        let mut oracle = mimo_test_pipeline();
29304        oracle.speculative = false;
29305        oracle.ignore_eos = true;
29306        oracle.sampler_config.temperature = 0.0;
29307        oracle.sampler_config.repetition_penalty = 1.0;
29308        let expected = oracle
29309            .generate_from_ids(&source_ids, 8, None, None)
29310            .unwrap()
29311            .token_ids;
29312        assert_eq!(
29313            p.generate_from_embeds(&media_ids, &source_rows, 8, None, None)
29314                .unwrap()
29315                .token_ids,
29316            expected
29317        );
29318        assert!(p.kv_history.is_empty());
29319        let mut bad = rows;
29320        bad[0] = f32::NAN;
29321        assert!(p.generate_from_embeds(&a, &bad, 1, None, None).is_err());
29322    }
29323
29324    fn f32_bits(v: &[f32]) -> Vec<u32> {
29325        v.iter().map(|x| x.to_bits()).collect()
29326    }
29327
29328    /// M3 acceptance: on the MiMo-shaped stack the decode walk (one
29329    /// position at a time through `forward_layers`) and the batched
29330    /// prefill (`prefill_batch_span`, whole prompt and split in two
29331    /// chunks) give bit-identical logits at all 12 positions — per-layer
29332    /// KV heads, narrow V, sinks, the window and the biased sigmoid MoE all
29333    /// agree across the two walks.
29334    #[test]
29335    fn mimo_shaped_decode_matches_prefill_batch_bitwise() {
29336        let mut p = mimo_test_pipeline();
29337        let kv: Vec<usize> = p.kv_cache.layers.iter().map(|l| l.num_kv_heads).collect();
29338        assert_eq!(kv, vec![1, 2, 2, 1]);
29339        assert!(p.kv_cache.layers[0].sinks.is_none() && p.kv_cache.layers[3].sinks.is_none());
29340        assert!(p.kv_cache.layers[1].sinks.is_some() && p.kv_cache.layers[2].sinks.is_some());
29341        let ids: Vec<u32> = (0..12u32).map(|i| (i * 7 + 3) % 64).collect();
29342        let hs = p.hidden_size;
29343        let mut decode = Vec::new();
29344        for (pos, &id) in ids.iter().enumerate() {
29345            let e = p.embed_single(id);
29346            let h = p.forward_layers(&e, pos, None);
29347            decode.push(p.logits_from_hidden(&h));
29348        }
29349        for l in &p.kv_cache.layers {
29350            assert_eq!(l.seq_len, 12);
29351            // V rows are padded to head_dim inside the cache.
29352            assert_eq!(l.head_values(0).len(), 12 * 8);
29353        }
29354        assert!(decode.iter().flatten().all(|v| v.is_finite()));
29355
29356        p.clear_sequence_state();
29357        let hb = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
29358        for pos in 0..ids.len() {
29359            let lg = p.logits_from_hidden(&hb[pos * hs..(pos + 1) * hs]);
29360            assert_eq!(
29361                f32_bits(&decode[pos]),
29362                f32_bits(&lg),
29363                "whole prompt, pos {pos}"
29364            );
29365        }
29366
29367        p.clear_sequence_state();
29368        let a = p.prefill_batch_span(PrefillIn::Ids(&ids[..5]), 0, None, 0, p.num_layers);
29369        let b = p.prefill_batch_span(PrefillIn::Ids(&ids[5..]), 5, None, 0, p.num_layers);
29370        for pos in 0..ids.len() {
29371            let row = if pos < 5 {
29372                &a[pos * hs..(pos + 1) * hs]
29373            } else {
29374                &b[(pos - 5) * hs..(pos - 4) * hs]
29375            };
29376            let lg = p.logits_from_hidden(row);
29377            assert_eq!(
29378                f32_bits(&decode[pos]),
29379                f32_bits(&lg),
29380                "two chunks, pos {pos}"
29381            );
29382        }
29383
29384        // The fixture is not degenerate: the sinks and the window each
29385        // change the answer.
29386        let last = |p: &mut Pipeline| {
29387            p.clear_sequence_state();
29388            let hb = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
29389            p.logits_from_hidden(&hb[11 * hs..12 * hs])
29390        };
29391        let base = last(&mut p);
29392        let mut no_sinks = mimo_test_pipeline();
29393        for l in &mut no_sinks.kv_cache.layers {
29394            l.sinks = None;
29395        }
29396        assert_ne!(
29397            f32_bits(&last(&mut no_sinks)),
29398            f32_bits(&base),
29399            "sinks are live"
29400        );
29401        let mut wide = mimo_test_pipeline();
29402        wide.swa = Some((64, usize::MAX));
29403        assert_ne!(
29404            f32_bits(&last(&mut wide)),
29405            f32_bits(&base),
29406            "window is live"
29407        );
29408
29409        // Generation runs end to end on the same stack.
29410        p.clear_sequence_state();
29411        p.ignore_eos = true;
29412        let r = p.generate_from_ids(&ids, 4, None, None).unwrap();
29413        assert_eq!(r.token_ids.len(), 4);
29414    }
29415
29416    /// A Spark-X2.5-shaped stack: layers 0..3 slide (window 6), layer 3
29417    /// is global, every attention carries the head-wise sigmoid g_proj gate.
29418    fn spark_test_pipeline(trim: Option<(usize, usize)>) -> Pipeline {
29419        let (hs, nh) = (16usize, 4usize);
29420        let mut p = create_test_pipeline(hs, 24, nh, 2, 8, 4, 64);
29421        p.layer_dump = None;
29422        p.swa = Some((6, 4));
29423        p.proj_gate_sigmoid = true;
29424        for (li, lw) in p.weights.layers.iter_mut().enumerate() {
29425            if let AttnKind::Full { softplus_gate, .. } = &mut lw.attn {
29426                let g: Vec<f32> = (0..nh * hs)
29427                    .map(|i| (((i * 29 + li * 7) % 83) as f32 / 83.0 - 0.5) * 0.8)
29428                    .collect();
29429                *softplus_gate = Some((QTensor::from_f32(g, nh, hs), true));
29430            }
29431        }
29432        p.swa_trim = trim;
29433        p
29434    }
29435
29436    /// Trimming the sliding tails changes nothing but memory: the same
29437    /// prompt in uneven chunks, a decode walk, and fused pairs with a
29438    /// 2-row rollback give bit-identical hiddens with and without it,
29439    /// while the trimmed sliding layers stay bounded and the global layer
29440    /// keeps every row.
29441    #[test]
29442    fn swa_trim_pipeline_matches_untrimmed_bitwise() {
29443        let mut a = spark_test_pipeline(None);
29444        let mut b = spark_test_pipeline(Some((2, 4)));
29445        assert_eq!(
29446            (0..4).map(|li| b.layer_window(li)).collect::<Vec<_>>(),
29447            vec![Some(6), Some(6), Some(6), None]
29448        );
29449        let ids: Vec<u32> = (0..41u32).map(|i| (i * 11 + 5) % 64).collect();
29450        let mut pos = 0usize;
29451        for &n in [5usize, 13, 7, 16].iter().cycle() {
29452            if pos >= ids.len() {
29453                break;
29454            }
29455            let end = (pos + n).min(ids.len());
29456            let ha = a.prefill_batch_span(PrefillIn::Ids(&ids[pos..end]), pos, None, 0, 4);
29457            let hb = b.prefill_batch_span(PrefillIn::Ids(&ids[pos..end]), pos, None, 0, 4);
29458            assert_eq!(f32_bits(&ha), f32_bits(&hb), "prefill chunk at {pos}");
29459            pos = end;
29460        }
29461        for _ in 0..23 {
29462            let e = a.embed_single(((pos * 7) % 64) as u32);
29463            let ha = a.forward_layers(&e, pos, None);
29464            let hb = b.forward_layers(&e, pos, None);
29465            assert_eq!(f32_bits(&ha), f32_bits(&hb), "decode at {pos}");
29466            for li in 0..3 {
29467                assert!(b.kv_cache.layers[li].seq_len <= 12, "layer {li} bounded");
29468            }
29469            pos += 1;
29470        }
29471        for round in 0..9 {
29472            let (e1, e2) = (a.embed_single(round * 3 + 1), a.embed_single(round * 5 + 2));
29473            let (a1, a2) = a.forward_pair(&e1, &e2, pos);
29474            let (b1, b2) = b.forward_pair(&e1, &e2, pos);
29475            assert_eq!(f32_bits(&a1), f32_bits(&b1), "pair lane 1 round {round}");
29476            assert_eq!(f32_bits(&a2), f32_bits(&b2), "pair lane 2 round {round}");
29477            if round % 2 == 1 {
29478                // A rejected draft: both lanes roll back.
29479                for p in [&mut a, &mut b] {
29480                    for l in &mut p.kv_cache.layers {
29481                        l.truncate_last(2);
29482                    }
29483                }
29484            } else {
29485                pos += 2;
29486            }
29487        }
29488        let e = a.embed_single(9);
29489        let (ha, hb) = (
29490            a.forward_layers(&e, pos, None),
29491            b.forward_layers(&e, pos, None),
29492        );
29493        assert_eq!(f32_bits(&ha), f32_bits(&hb), "after the pairs");
29494        for li in 0..3 {
29495            let (la, lb) = (&a.kv_cache.layers[li], &b.kv_cache.layers[li]);
29496            assert!(lb.base() > 0, "layer {li} trimmed");
29497            assert_eq!(la.base(), 0);
29498            assert_eq!(lb.pos_len(), la.seq_len);
29499            assert_eq!(lb.head_keys(0), &la.head_keys(0)[lb.base() * 8..]);
29500        }
29501        let (ga, gb) = (&a.kv_cache.layers[3], &b.kv_cache.layers[3]);
29502        assert_eq!(
29503            (gb.base(), gb.seq_len),
29504            (0, ga.seq_len),
29505            "the global layer keeps all"
29506        );
29507        assert_eq!(b.kv_cache.seq_len(), a.kv_cache.seq_len());
29508        assert!(b.kv_cache.total_memory_bytes() < a.kv_cache.total_memory_bytes());
29509    }
29510
29511    /// The network split's KvFetch hand-off on a trimmed stack: every
29512    /// layer shipped over the wire mid-sequence (the sliding ones as
29513    /// `FullTail`) into a fresh pipeline that never ran a position, which
29514    /// then decodes on — bit for bit what the untrimmed pipeline decodes.
29515    #[test]
29516    fn swa_trim_wire_handoff_continues_bitwise() {
29517        let mut a = spark_test_pipeline(None);
29518        let mut b = spark_test_pipeline(Some((2, 4)));
29519        let ids: Vec<u32> = (0..29u32).map(|i| (i * 13 + 7) % 64).collect();
29520        let ha = a.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, 4);
29521        let hb = b.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, 4);
29522        assert_eq!(f32_bits(&ha), f32_bits(&hb));
29523        let mut pos = ids.len();
29524        for _ in 0..5 {
29525            let e = a.embed_single(((pos * 5) % 64) as u32);
29526            assert_eq!(
29527                f32_bits(&a.forward_layers(&e, pos, None)),
29528                f32_bits(&b.forward_layers(&e, pos, None))
29529            );
29530            pos += 1;
29531        }
29532        let mut c = spark_test_pipeline(Some((2, 4)));
29533        for li in 0..4 {
29534            let bytes = b.kv_cache.layers[li].export_wire(false).unwrap();
29535            c.kv_cache.layers[li].import_wire(&bytes).unwrap();
29536        }
29537        assert!(c.kv_cache.layers[0].base() > 0, "a tail travelled");
29538        assert_eq!(c.kv_cache.seq_len(), pos);
29539        for step in 0..17 {
29540            let e = a.embed_single(((pos * 3 + 1) % 64) as u32);
29541            let ha = a.forward_layers(&e, pos, None);
29542            let hc = c.forward_layers(&e, pos, None);
29543            assert_eq!(
29544                f32_bits(&ha),
29545                f32_bits(&hc),
29546                "after the hand-off, step {step}"
29547            );
29548            pos += 1;
29549        }
29550        assert!(c.kv_cache.layers[0].seq_len <= 12, "the receiver trims on");
29551    }
29552
29553    /// A synthetic MiMo draft stack for `mimo_test_pipeline` (the SWA
29554    /// geometry of its sliding layers: 2 KV heads, head 8 / V 4).  Widths
29555    /// are per-draft-layer so the MTP collector cannot accidentally borrow
29556    /// the trunk's `intermediate_size`.
29557    fn mimo_test_mtp_widths(widths: &[usize], gain: f32) -> mimo_mtp::MimoMtp {
29558        let (hs, nh, hd, vd, nkv) = (16usize, 4usize, 8usize, 4usize, 2usize);
29559        let synth = |len: usize, salt: usize| -> Vec<f32> {
29560            (0..len)
29561                .map(|i| (((i * 37 + salt * 13 + 3) % 89) as f32 / 89.0 - 0.5) * 0.6 * gain)
29562                .collect()
29563        };
29564        let qt = |rows: usize, cols: usize, salt: usize| {
29565            QTensor::from_f32(synth(rows * cols, salt), rows, cols)
29566        };
29567        let layers = widths
29568            .iter()
29569            .copied()
29570            .enumerate()
29571            .map(|(k, inter)| {
29572                let s = 500 + k * 40;
29573                let mut kv = crate::kv_cache::LayerKvCache::new(nkv, hd);
29574                kv.sinks = Some(vec![0.3, -0.7, 1.1, 0.0]);
29575                MtpModule {
29576                    enorm: vec![1.0; hs],
29577                    hnorm: vec![1.0; hs],
29578                    eh_proj: qt(hs, 2 * hs, s),
29579                    layer: LayerWeights {
29580                        input_norm: vec![1.0; hs],
29581                        post_norm: vec![1.0; hs],
29582                        attn_out_norm: None,
29583                        ffn_out_norm: None,
29584                        layer_scale: None,
29585                        attn: AttnKind::Full {
29586                            wq: qt(nh * hd, hs, s + 1),
29587                            wk: qt(nkv * hd, hs, s + 2),
29588                            wv: qt(nkv * vd, hs, s + 3),
29589                            wo: qt(hs, nh * vd, s + 4),
29590                            q_norm: None,
29591                            k_norm: None,
29592                            output_gate: false,
29593                            softplus_gate: None,
29594                            bias: None,
29595                        },
29596                        ffn: FfnKind::Dense(DenseFfn {
29597                            gate_proj: qt(inter, hs, s + 5),
29598                            up_proj: qt(inter, hs, s + 6),
29599                            down_proj: qt(hs, inter, s + 7),
29600                            act: Act::Silu,
29601                            down_t: None,
29602                            segs: Vec::new(),
29603                        }),
29604                    },
29605                    final_norm: vec![1.0; hs],
29606                    kv,
29607                }
29608            })
29609            .collect();
29610        mimo_mtp::MimoMtp::from_layers(layers)
29611    }
29612
29613    fn mimo_test_mtp(n: usize, gain: f32) -> mimo_mtp::MimoMtp {
29614        mimo_test_mtp_widths(&vec![24; n], gain)
29615    }
29616
29617    fn mimo_greedy(p: &mut Pipeline, ids: &[u32], n: usize, spec: bool) -> GenerateResult {
29618        p.clear_sequence_state();
29619        p.speculative = spec;
29620        p.ignore_eos = true;
29621        p.sampler_config.temperature = 0.0;
29622        p.generate_from_ids(ids, n, None, None).unwrap()
29623    }
29624
29625    #[test]
29626    fn mimo_mtp_ffn_probe_tracks_each_independent_draft_width() {
29627        let mut p = mimo_test_pipeline();
29628        let widths = [7usize, 13, 29];
29629        assert_ne!(widths[0], p.intermediate_size);
29630        assert_ne!(widths[1], p.intermediate_size);
29631        assert_ne!(widths[2], p.intermediate_size);
29632        p.mimo_mtp = Some(mimo_test_mtp_widths(&widths, 1.0));
29633        let ids: Vec<u32> = (0..11).map(|i| (i * 9 + 5) % 64).collect();
29634
29635        let trunk = p.probe_ffn_mass(&ids);
29636        assert!(trunk.iter().all(|v| v.len() == p.intermediate_size));
29637        let got = p.probe_mtp_ffn(&ids).expect("MiMo MTP probe");
29638        assert_eq!(got.len(), widths.len());
29639        for (k, (stat, &width)) in got.iter().zip(&widths).enumerate() {
29640            assert_eq!(stat.mass.len(), width, "draft layer {k}");
29641            assert_eq!(stat.squared_mass.len(), width, "draft layer {k}");
29642            assert_eq!(stat.observed_positions, ids.len() - k - 1);
29643            assert!(stat.mass.iter().any(|&v| v > 0.0), "draft layer {k}");
29644            assert!(stat
29645                .mass
29646                .iter()
29647                .zip(&stat.squared_mass)
29648                .all(|(&m, &s)| m.is_finite() && s.is_finite() && m >= 0.0 && s >= 0.0));
29649        }
29650        assert_eq!(p.kv_cache.seq_len(), 0, "probe leaves a fresh trunk");
29651        let st = p.mimo_mtp.as_ref().unwrap();
29652        assert!(st.layers.iter().all(|m| m.kv.seq_len == 0));
29653
29654        // As above, reject only after a MiMo draft KV has been appended.
29655        // The detached multi-layer owner must still be reset on that error.
29656        let h = p.hidden_size;
29657        let FfnKind::Dense(dense) = &mut p.mimo_mtp.as_mut().unwrap().layers[0].layer.ffn else {
29658            panic!("synthetic MiMo MTP must be dense")
29659        };
29660        dense.segs.push(FfnSeg {
29661            gate: QTensor::from_f32(vec![0.0; h], 1, h),
29662            up: QTensor::from_f32(vec![0.0; h], 1, h),
29663            down: QTensor::from_f32(vec![0.0; h], h, 1),
29664            start: dense.gate_proj.rows(),
29665            width: 1,
29666        });
29667        assert!(p
29668            .probe_mtp_ffn(&ids)
29669            .unwrap_err()
29670            .contains("tube-segmented draft FFNs are not supported"));
29671        assert_eq!(p.kv_cache.seq_len(), 0);
29672        assert!(p
29673            .mimo_mtp
29674            .as_ref()
29675            .unwrap()
29676            .layers
29677            .iter()
29678            .all(|m| m.kv.seq_len == 0));
29679    }
29680
29681    #[test]
29682    fn mimo_mtp_ffn_probe_chunking_preserves_teacher_forced_statistics() {
29683        fn collect(p: &mut Pipeline, ids: &[u32], rows: usize) -> Vec<MtpFfnProbe> {
29684            p.clear_sequence_state();
29685            let mut st = p.mimo_mtp.take().expect("synthetic MiMo draft");
29686            let _exact = ExactMtpCalibrationGuard::enter();
29687            let got = crate::gpu::cpu_scope(|| {
29688                let trunk = p.probe_trunk_rows(ids)?;
29689                p.mimo_mtp_ffn_probe_teacher_forced_with_chunk_rows(&mut st, ids, &trunk, rows)
29690            })
29691            .expect("teacher-forced MiMo probe");
29692            st.reset();
29693            p.mimo_mtp = Some(st);
29694            p.reset_mtp_probe_state();
29695            got
29696        }
29697
29698        for post_norm_hidden in [false, true] {
29699            let ids: Vec<u32> = (0..263u32).map(|i| (i * 17 + 5) % 64).collect();
29700            let make = || {
29701                let mut p = mimo_test_pipeline();
29702                let mut st = mimo_test_mtp_widths(&[7, 13, 29], 1.0);
29703                st.post_norm_hidden = post_norm_hidden;
29704                p.mimo_mtp = Some(st);
29705                p
29706            };
29707            let mut full = make();
29708            let expected = collect(&mut full, &ids, usize::MAX);
29709            for rows in [1usize, 7, 128] {
29710                let mut chunked = make();
29711                let got = collect(&mut chunked, &ids, rows);
29712                assert_eq!(got.len(), expected.len(), "post={post_norm_hidden}, rows={rows}");
29713                for (layer, (got, expected)) in got.iter().zip(&expected).enumerate() {
29714                    assert_eq!(
29715                        got.observed_positions, expected.observed_positions,
29716                        "post={post_norm_hidden}, rows={rows}, layer={layer}"
29717                    );
29718                    assert_eq!(
29719                        got.mass.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
29720                        expected.mass.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
29721                        "post={post_norm_hidden}, rows={rows}, layer={layer} mass"
29722                    );
29723                    assert_eq!(
29724                        got.squared_mass
29725                            .iter()
29726                            .map(|v| v.to_bits())
29727                            .collect::<Vec<_>>(),
29728                        expected
29729                            .squared_mass
29730                            .iter()
29731                            .map(|v| v.to_bits())
29732                            .collect::<Vec<_>>(),
29733                        "post={post_norm_hidden}, rows={rows}, layer={layer} squared mass"
29734                    );
29735                }
29736            }
29737        }
29738    }
29739
29740    /// The draft stack's incremental rounds (a few rows per layer, last
29741    /// round's provisional rows dropped) give exactly the teacher-forced
29742    /// table of one causal pass per layer over the whole sequence — the
29743    /// table `tools/mimo_ref.py mtp` computes for variant A: layer k, row
29744    /// j reads (x[j+k+1], norm(h_j)) at RoPE position j.
29745    #[test]
29746    fn mimo_mtp_incremental_rounds_equal_the_teacher_forced_table() {
29747        // Both readings of the backbone hidden: pre-final-norm (default)
29748        // and post-final-norm (`CMF_MIMO_MTP_HIDDEN=post`).
29749        for post in [false, true] {
29750            let mut p = mimo_test_pipeline();
29751            // A non-trivial final norm, so the two readings differ.
29752            p.weights.final_norm = (0..p.hidden_size).map(|i| 0.5 + 0.1 * i as f32).collect();
29753            let mut st0 = mimo_test_mtp(3, 1.0);
29754            st0.post_norm_hidden = post;
29755            p.mimo_mtp = Some(st0);
29756            let ids: Vec<u32> = (0..14u32).map(|i| (i * 11 + 5) % 64).collect();
29757            let hs = p.hidden_size;
29758            let hb = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
29759            p.mimo_note_rows(&hb, 0);
29760            let mut st = p.mimo_mtp.take().unwrap();
29761            // Incremental: one round per t through the decode path (later
29762            // tokens from `ids`, the probe's teacher forcing).
29763            let k = 3;
29764            let mut inc = Vec::new();
29765            for t in 0..ids.len() - k - 1 {
29766                inc.push(p.mimo_mtp_draft(&mut st, t, &ids, k));
29767            }
29768            // Reference: per layer, ONE batched causal pass over all rows
29769            // with fresh caches.
29770            let s = ids.len();
29771            let mut reference = vec![vec![0u32; k]; s - k - 1];
29772            let mut fresh = mimo_test_mtp(3, 1.0);
29773            for (layer, m) in fresh.layers.iter_mut().enumerate() {
29774                let n = s - layer - 1;
29775                let mut cats = vec![0.0f32; n * 2 * hs];
29776                for j in 0..n {
29777                    let e = p.embed_single(ids[j + layer + 1]);
29778                    let raw = &hb[j * hs..(j + 1) * hs];
29779                    let g = if post {
29780                        inference::rms_norm(raw, &p.weights.final_norm, p.rms_eps, p.norm_style)
29781                    } else {
29782                        raw.to_vec()
29783                    };
29784                    let (ce, ch) = cats[j * 2 * hs..(j + 1) * 2 * hs].split_at_mut(hs);
29785                    inference::rms_norm_into(&e, &m.enorm, p.rms_eps, p.norm_style, ce);
29786                    inference::rms_norm_into(&g, &m.hnorm, p.rms_eps, p.norm_style, ch);
29787                }
29788                let mut x = vec![0.0f32; n * hs];
29789                m.eh_proj.matmat(&cats, n, &mut x, None);
29790                p.mimo_mtp_block(m, &mut x, n, 0);
29791                for (t, row) in reference.iter_mut().enumerate() {
29792                    let y = inference::rms_norm(
29793                        &x[t * hs..(t + 1) * hs],
29794                        &m.final_norm,
29795                        p.rms_eps,
29796                        p.norm_style,
29797                    );
29798                    row[layer] = sampler::argmax(&p.lm_head_forward(&y));
29799                }
29800            }
29801            assert_eq!(inc, reference, "post_norm_hidden = {post}");
29802            // Not a degenerate table: the drafts vary.
29803            let distinct: std::collections::HashSet<u32> = inc.iter().flatten().copied().collect();
29804            assert!(distinct.len() > 3, "{inc:?}");
29805            // Each layer's cache ends holding rows up to the last round start.
29806            let last_t = ids.len() - k - 2;
29807            for m in &st.layers {
29808                assert_eq!(m.kv.seq_len, last_t + 1);
29809            }
29810        }
29811    }
29812
29813    /// Greedy with the MiMo draft stack is the plain greedy stream, token
29814    /// for token — with the real draft layers (low acceptance) and with a
29815    /// drafter that is right most of the time (exercises accepted prefixes
29816    /// of every length, the KV truncation of the rejected rows and the
29817    /// logits hand-off to the loop top), under the default repetition
29818    /// penalty.
29819    #[test]
29820    fn mimo_speculative_greedy_equals_plain_greedy() {
29821        let _env_lock = MTP_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
29822        let _env = ScopedTestEnv::set(&[
29823            ("CMF_GPU", Some("0")),
29824            ("CMF_GPU_WGPU_GRAPH", Some("0")),
29825        ]);
29826        let ids: Vec<u32> = (0..9u32).map(|i| (i * 7 + 3) % 64).collect();
29827        let n = 24;
29828        let mut p = mimo_test_pipeline();
29829        let plain = mimo_greedy(&mut p, &ids, n, false);
29830        assert_eq!(plain.mtp_drafted, 0);
29831        assert_eq!(plain.token_ids.len(), n);
29832        let plain_kv = p.kv_cache.layers[0].seq_len;
29833
29834        // Real draft layers.
29835        p.mimo_mtp = Some(mimo_test_mtp(3, 1.0));
29836        let spec = mimo_greedy(&mut p, &ids, n, true);
29837        assert!(spec.mtp_drafted > 0, "the round must draft");
29838        assert_eq!(spec.token_ids, plain.token_ids);
29839        assert_eq!(p.kv_cache.layers[0].seq_len, plain_kv);
29840
29841        // A drafter reading the true continuation with every fifth token
29842        // wrong: accepted prefixes of 0..=3 all occur.
29843        let mut truth: Vec<u32> = ids.clone();
29844        truth.extend(&plain.token_ids);
29845        let mut noisy = truth.clone();
29846        for (i, t) in noisy.iter_mut().enumerate() {
29847            if i % 5 == 0 {
29848                *t = (*t + 1) % 64;
29849            }
29850        }
29851        let mut st = mimo_test_mtp(3, 1.0);
29852        st.draft_override = Some(noisy);
29853        p.mimo_mtp = Some(st);
29854        let spec = mimo_greedy(&mut p, &ids, n, true);
29855        assert_eq!(spec.token_ids, plain.token_ids);
29856        assert_eq!(p.kv_cache.layers[0].seq_len, plain_kv);
29857        let stats = p.mimo_mtp.as_ref().unwrap().stats.clone();
29858        assert_eq!(stats.accepted as usize, spec.mtp_accepted);
29859        assert!(spec.mtp_accepted > 0 && spec.mtp_accepted < spec.mtp_drafted);
29860        assert!(
29861            stats.accept_hist.iter().filter(|&&c| c > 0).count() >= 3,
29862            "{:?}",
29863            stats.accept_hist
29864        );
29865        assert!(stats.tokens_per_round() > 1.5, "{}", stats.line());
29866
29867        // A perfect drafter: every draft accepted, rounds of K+1 tokens,
29868        // and the budget is never overrun.
29869        let mut st = mimo_test_mtp(3, 1.0);
29870        st.draft_override = Some(truth);
29871        p.mimo_mtp = Some(st);
29872        let spec = mimo_greedy(&mut p, &ids, n, true);
29873        assert_eq!(spec.token_ids, plain.token_ids);
29874        assert_eq!(spec.mtp_accepted, spec.mtp_drafted);
29875        assert_eq!(p.kv_cache.layers[0].seq_len, plain_kv);
29876
29877        // CMF_MTP=0 path: the stack is attached but idle.
29878        let off = mimo_greedy(&mut p, &ids, n, false);
29879        assert_eq!(off.token_ids, plain.token_ids);
29880        assert_eq!(off.mtp_drafted, 0);
29881    }
29882
29883    /// The wgpu graphs carry MiMo-V2's attention per layer (KV heads,
29884    /// narrow V, sinks, windows, two RoPE tables): no attention-level
29885    /// decline for it any more, and the geometry each layer hands the
29886    /// graph is exactly what the CPU attention reads for that layer. The
29887    /// descriptive reasons stay (the Metal graphs and the q1 dropin still
29888    /// decline on them), and what the per-layer geometry cannot express
29889    /// keeps a named wgpu decline.
29890
29891    #[test]
29892    fn mimo_shaped_model_rides_the_wgpu_graph_geometry() {
29893        let p = mimo_test_pipeline();
29894        assert_eq!(
29895            p.graph_attn_decline_reason(),
29896            Some("per-layer KV head counts")
29897        );
29898        assert_eq!(p.wgpu_graph_attn_decline(), None);
29899        let g0 = p.graph_attn_geom(0).expect("full layer geometry");
29900        assert_eq!(
29901            (g0.nkv, g0.dv, g0.rd, g0.window, g0.sink.is_some()),
29902            (1, 4, 4, None, false)
29903        );
29904        assert_eq!(g0.invf, p.inv_freq.as_slice());
29905        let g1 = p.graph_attn_geom(1).expect("sliding layer geometry");
29906        assert_eq!((g1.nkv, g1.dv, g1.rd, g1.window), (2, 4, 4, Some(3)));
29907        assert_eq!(g1.sink, Some(&[0.5f32, -1.0, 1.5, 0.0][..]));
29908        assert_eq!(g1.invf, p.inv_freq_local.as_ref().unwrap().as_slice());
29909        assert_ne!(g0.invf, g1.invf, "two RoPE tables");
29910        let g3 = p.graph_attn_geom(3).expect("full layer geometry");
29911        assert_eq!((g3.nkv, g3.window, g3.sink.is_some()), (1, None, false));
29912
29913        // No wgpu device in this process: the builders run and decline on
29914        // the (f32, unmapped) experts — never with an attention line.
29915        let emb = p.embed_single(3);
29916        let mut lg = Vec::new();
29917        assert!(
29918            p.try_token_graph_wgpu_steps(&emb, 0, &mut lg, 1, None, None, 0, p.num_layers)
29919                .is_none()
29920        );
29921        let mut hid = emb.clone();
29922        assert_eq!(
29923            p.try_batch_graph_wgpu(&mut hid, &[0], 1, None),
29924            crate::gpu::BatchGraphOutcome::Declined
29925        );
29926        assert_eq!(hid, emb, "a declined batch graph leaves the rows untouched");
29927        assert!(p.try_multi_burst(3, 0, 4).is_none());
29928        assert!(
29929            p.graph_declines().is_empty(),
29930            "no attention decline logged: {:?}",
29931            p.graph_declines()
29932        );
29933        // (No assertion on graph_prefill_preferred: with no attention
29934        // decline it follows the device — a test process that brought a
29935        // wgpu adapter up routes this resident MoE through the graph.)
29936
29937        let plain = || create_test_pipeline(8, 16, 2, 1, 4, 2, 32);
29938        assert_eq!(plain().graph_attn_decline_reason(), None);
29939        assert_eq!(plain().wgpu_graph_attn_decline(), None);
29940        assert!(
29941            plain().graph_attn_geom(0).is_none(),
29942            "uniform models keep the historical arms"
29943        );
29944        let mut q = plain();
29945        q.set_layer_sinks(1, vec![0.25, -0.25]).unwrap();
29946        assert_eq!(
29947            q.graph_attn_decline_reason(),
29948            Some("learned attention sinks")
29949        );
29950        assert_eq!(
29951            q.graph_attn_geom(1).unwrap().sink,
29952            Some(&[0.25f32, -0.25][..])
29953        );
29954        let mut q = plain();
29955        q.set_attn_geometry(None, Some(2)).unwrap();
29956        assert_eq!(
29957            q.graph_attn_decline_reason(),
29958            Some("V heads narrower than Q/K heads")
29959        );
29960        assert_eq!(q.graph_attn_geom(0).unwrap().dv, 2);
29961        let mut q = plain();
29962        q.sliding_layers = Some(vec![true, false]);
29963        q.swa = Some((4, usize::MAX));
29964        assert_eq!(q.graph_attn_decline_reason(), Some("sliding-window layers"));
29965        assert_eq!(q.graph_attn_geom(0).unwrap().window, Some(4));
29966        assert_eq!(q.graph_attn_geom(1).unwrap().window, None);
29967
29968        // YaRN's post-rotation amplitude factor rides the per-layer graph
29969        // geometry. It is intentionally not an angular scale folded into
29970        // `invf`: the WGPU RoPE kernel receives it separately.
29971        let mut q = mimo_test_pipeline();
29972        q.rope_scale = 2.0;
29973        q.rope_scale_local = 1.25;
29974        assert_eq!(q.wgpu_graph_attn_decline(), None);
29975        assert_eq!(q.graph_attn_geom(0).unwrap().rope_scale, 2.0);
29976        assert_eq!(q.graph_attn_geom(1).unwrap().rope_scale, 1.25);
29977
29978        // A uniform YaRN model cannot yet pass the factor through the fused
29979        // RKV arm; decline safely instead of producing scale-1 output.
29980        let mut q = plain();
29981        q.rope_scale = 2.0;
29982        assert_eq!(
29983            q.wgpu_graph_attn_decline(),
29984            Some("scaled RoPE without per-layer geometry")
29985        );
29986    }
29987
29988    /// The native q1 attention path has a narrower contract than the WGPU
29989    /// per-layer geometry graph, but it must not discard the exact Flint
29990    /// combination of uniform GQA + sliding windows + learned sinks.  The
29991    /// actual Metal kernel is covered independently with a direct sink
29992    /// softmax test; this is the pure admission test, with no model run.
29993    #[cfg(target_os = "macos")]
29994    #[test]
29995    fn metal_swa_admits_uniform_learned_sinks_for_q1_decode() {
29996        // rd=64 is in the native rope kernel's lane-pair contract; the
29997        // synthetic stack otherwise has the same uniform K/V geometry that
29998        // Flint needs for q1 (unlike the deliberately ragged MiMo fixture).
29999        let mut p = create_test_pipeline(256, 512, 4, 1, 64, 2, 64);
30000        p.swa = Some((16, usize::MAX));
30001        p.sliding_layers = Some(vec![true, true]);
30002        p.set_layer_sinks(0, vec![0.25, -0.5, 1.0, -1.25]).unwrap();
30003        p.set_layer_sinks(1, vec![-0.75, 0.5, 0.0, 1.5]).unwrap();
30004
30005        assert_eq!(
30006            p.graph_attn_decline_reason(),
30007            Some("learned attention sinks")
30008        );
30009        let swa_graph = p.metal_graph_swa();
30010        assert!(swa_graph, "uniform sliding sink geometry must reach q1");
30011        let native_sink_attend = p.graph_attn_decline_reason() == Some("learned attention sinks")
30012            && (swa_graph || (p.swa.is_none() && p.sliding_layers.is_none()));
30013        assert!(
30014            native_sink_attend,
30015            "the q1 sink admission must follow the SWA door"
30016        );
30017        // The batched chunk softmax has no value-less sink column, so its
30018        // separate admission gate must keep this prompt on the host path.
30019        assert!(p.kv_cache.layers.iter().any(|l| l.sinks.is_some()));
30020    }
30021
30022    #[test]
30023    fn mimo_verify_rewind_preserves_lagging_host_caches() {
30024        let mut p = mimo_test_pipeline();
30025        for (li, layer) in p.kv_cache.layers.iter_mut().enumerate() {
30026            let row = vec![0.0; layer.num_kv_heads * layer.head_dim];
30027            for _ in 0..if li == 0 { 2 } else { 12 } {
30028                layer.append(&row, &row, &[]);
30029            }
30030        }
30031        p.mimo_verify_rewind(9).unwrap();
30032        assert_eq!(p.kv_cache.layers[0].seq_len, 2);
30033        for layer in &p.kv_cache.layers[1..] {
30034            assert_eq!(layer.seq_len, 9);
30035        }
30036    }
30037
30038    /// CMF_LAYER_DUMP: the decode walk and the batched prefill both write
30039    /// every (position, layer) hidden, the two sets agree byte for byte,
30040    /// and the last layer's file is the stack output.
30041    #[test]
30042    fn layer_dump_covers_every_position_and_layer_on_both_walks() {
30043        let dir = std::env::temp_dir().join(format!("cmf-layer-dump-{}", std::process::id()));
30044        let _ = std::fs::remove_dir_all(&dir);
30045        let mut p = mimo_test_pipeline();
30046        let hs = p.hidden_size;
30047        let ids = [5u32, 9, 11, 2, 40];
30048        p.layer_dump = Some(dir.join("decode"));
30049        for (pos, &id) in ids.iter().enumerate() {
30050            let e = p.embed_single(id);
30051            let _ = p.forward_layers(&e, pos, None);
30052        }
30053        p.clear_sequence_state();
30054        p.layer_dump = Some(dir.join("prefill"));
30055        let hb = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
30056        for pos in 0..ids.len() {
30057            for li in 0..p.num_layers {
30058                let name = format!("p{pos:06}_l{li:02}.f32");
30059                let a = std::fs::read(dir.join("decode").join(&name)).unwrap();
30060                let b = std::fs::read(dir.join("prefill").join(&name)).unwrap();
30061                assert_eq!(a.len(), hs * 4, "{name}");
30062                assert_eq!(a, b, "{name}");
30063            }
30064        }
30065        let last = std::fs::read(dir.join("prefill").join("p000004_l03.f32")).unwrap();
30066        let vals: Vec<f32> = last
30067            .chunks(4)
30068            .map(|c| f32::from_le_bytes(c.try_into().unwrap()))
30069            .collect();
30070        assert_eq!(f32_bits(&vals), f32_bits(&hb[4 * hs..5 * hs]));
30071        let _ = std::fs::remove_dir_all(&dir);
30072    }
30073
30074    #[test]
30075    fn attn_geometry_and_sinks_are_validated() {
30076        let mut p = create_test_pipeline(8, 16, 4, 2, 4, 2, 32);
30077        assert!(
30078            p.set_attn_geometry(Some(vec![2]), None).is_err(),
30079            "one entry per layer"
30080        );
30081        assert!(
30082            p.set_attn_geometry(Some(vec![2, 3]), None).is_err(),
30083            "3 does not divide 4"
30084        );
30085        assert!(p.set_attn_geometry(Some(vec![2, 0]), None).is_err());
30086        assert!(p.set_attn_geometry(None, Some(0)).is_err());
30087        assert!(
30088            p.set_attn_geometry(None, Some(5)).is_err(),
30089            "V wider than the head"
30090        );
30091        p.set_attn_geometry(None, Some(4)).unwrap();
30092        assert_eq!(
30093            p.v_head_dim, None,
30094            "v_head_dim == head_dim is the uniform case"
30095        );
30096        p.set_layer_sinks(1, vec![0.1; 4]).unwrap();
30097        p.set_attn_geometry(Some(vec![1, 4]), None).unwrap();
30098        assert_eq!(p.kv_cache.layers[0].num_kv_heads, 1);
30099        assert_eq!(p.kv_cache.layers[1].num_kv_heads, 4);
30100        assert!(
30101            p.kv_cache.layers[1].sinks.is_some(),
30102            "a reshape keeps the layer's sinks"
30103        );
30104        assert_eq!(p.layer_geom(1).0, 4);
30105        assert!(
30106            p.set_layer_sinks(0, vec![0.0; 3]).is_err(),
30107            "one sink per Q head"
30108        );
30109        assert!(p.set_layer_sinks(7, vec![0.0; 4]).is_err());
30110        assert!(p.set_layer_sinks(0, vec![f32::NAN, 0.0, 0.0, 0.0]).is_err());
30111    }
30112
30113    /// The O(1) Nyström state replaces a plain full-context softmax; it
30114    /// must never be armed on a sliding, sink or narrow-V layer.
30115    #[test]
30116    fn o1_is_never_armed_on_sink_window_or_narrow_v_layers() {
30117        let cfg = || {
30118            Some(crate::nystrom::O1Cfg {
30119                layers: crate::nystrom::O1Layers::All,
30120                m: 4,
30121                w: 8,
30122                sink: 2,
30123                rect: crate::nystrom::O1Rect::Aggregate,
30124            })
30125        };
30126        let mut p = mimo_test_pipeline();
30127        p.set_o1(cfg());
30128        assert!(!p.o1_active(), "every MiMo-shaped layer is ineligible");
30129        let mut q = create_test_pipeline(8, 16, 2, 1, 4, 3, 64);
30130        q.set_layer_sinks(1, vec![0.0, 0.0]).unwrap();
30131        q.sliding_layers = Some(vec![false, false, true]);
30132        q.swa = Some((4, usize::MAX));
30133        q.set_o1(cfg());
30134        assert_eq!(q.o1_flags, vec![true, false, false]);
30135    }
30136
30137    #[test]
30138    fn o1_batch_transition_publishes_one_epoch_before_serial_handoff() {
30139        const B: usize = 19;
30140        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
30141        p.set_o1(Some(crate::nystrom::O1Cfg {
30142            layers: crate::nystrom::O1Layers::All,
30143            m: 4,
30144            w: 8,
30145            sink: 2,
30146            rect: crate::nystrom::O1Rect::Aggregate,
30147        }));
30148        p.o1_begin_with_prefix(Some(B));
30149        let ids: Vec<u32> = (0..B as u32).collect();
30150        let _ = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
30151
30152        assert_eq!(p.o1_epoch, 1, "all layers publish one completed transition");
30153        assert!(p.kv_cache.layers.iter().all(|l| l.o1_sealed()));
30154        let next = p.embed_single(B as u32);
30155        let _ = p.forward_layers(&next, B, None);
30156        assert_eq!(p.o1_epoch, 1, "sealed handoff must not republish the epoch");
30157    }
30158
30159    /// A turbo file's exact rows are chosen across every far-field layer at the
30160    /// boundary. A batched chunk ending on it used to seal each layer as it
30161    /// finished, before the pipeline could choose, so no row stayed exact on the
30162    /// host path (LFM2 on Metal).
30163    #[test]
30164    fn o1_exact_rows_are_chosen_before_a_batched_boundary_seals() {
30165        const B: usize = 19;
30166        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
30167        let cfg = crate::nystrom::O1Cfg {
30168            layers: crate::nystrom::O1Layers::All,
30169            m: 4,
30170            w: 8,
30171            sink: 2,
30172            rect: crate::nystrom::O1Rect::Aggregate,
30173        };
30174        p.set_o1(Some(cfg.clone()));
30175        p.o1_turbo = Some(O1Turbo {
30176            cfg,
30177            seal: B,
30178            exact: crate::dory::ExactRows { weights: std::sync::Arc::new(vec![1.0; 2 * 2]), budget: 3 },
30179        });
30180        p.o1_begin_with_prefix(Some(B));
30181        let ids: Vec<u32> = (0..B as u32).collect();
30182        let _ = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
30183        // The span's own completion chooses the rows and seals every layer.
30184        assert!(p.kv_cache.layers.iter().all(|l| l.o1_sealed()));
30185        let keep = p.kv_cache.layers[0].o1_keep.clone();
30186        assert_eq!(keep.len(), 3, "the budget of exact rows is spent");
30187        assert_eq!(keep, p.kv_cache.layers[1].o1_keep, "the same rows in every layer");
30188        assert!(keep.iter().all(|&r| (2..B - 8).contains(&r)), "never a sink or a window row");
30189    }
30190
30191    #[test]
30192    fn o1_pair_transition_commits_scratch_before_epoch_publication() {
30193        const B: usize = 19;
30194        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
30195        // Keep a real recurrent layer ahead of the Full O(1) layer so the
30196        // pair test observes the GDN lane-2 scratch swap at the same
30197        // boundary, rather than only exercising an artificial scratch vec.
30198        let gdn_cfg = crate::linear_core::GdnCfg {
30199            num_v_heads: 2,
30200            num_k_heads: 1,
30201            key_head_dim: 2,
30202            value_head_dim: 4,
30203            conv_kernel: 3,
30204            hidden_size: 8,
30205            rms_eps: 1e-6,
30206            output_gate_sigmoid: false,
30207        };
30208        let synth = |n: usize, salt: usize| -> Vec<f32> {
30209            (0..n)
30210                .map(|i| (((i * 13 + salt * 7) % 97) as f32 / 97.0 - 0.5) * 0.4)
30211                .collect()
30212        };
30213        let qt = |rows: usize, cols: usize, salt: usize| {
30214            crate::qtensor::QTensor::from_f32(synth(rows * cols, salt), rows, cols)
30215        };
30216        let c_dim = gdn_cfg.conv_dim();
30217        let vd = gdn_cfg.num_v_heads * gdn_cfg.value_head_dim;
30218        p.weights.layers[0].attn = AttnKind::LinearGdn(crate::linear_core::GdnWeights {
30219            in_proj_qkv: qt(c_dim, 8, 1),
30220            in_proj_z: qt(vd, 8, 2),
30221            in_proj_a: qt(gdn_cfg.num_v_heads, 8, 3),
30222            in_proj_b: qt(gdn_cfg.num_v_heads, 8, 4),
30223            conv1d: synth(c_dim * gdn_cfg.conv_kernel, 5),
30224            a_log: vec![0.2, 0.5],
30225            dt_bias: synth(gdn_cfg.num_v_heads, 6),
30226            norm: vec![1.0; gdn_cfg.value_head_dim],
30227            out_proj: qt(8, vd, 7),
30228        });
30229        p.gdn_cfg = Some(gdn_cfg);
30230        p.set_o1(Some(crate::nystrom::O1Cfg {
30231            layers: crate::nystrom::O1Layers::All,
30232            m: 4,
30233            w: 8,
30234            sink: 2,
30235            rect: crate::nystrom::O1Rect::Aggregate,
30236        }));
30237        p.o1_begin_with_prefix(Some(B));
30238        for pos in 0..B - 2 {
30239            let emb = p.embed_single(pos as u32);
30240            let _ = p.forward_layers(&emb, pos, None);
30241        }
30242        let lane1_state = p.kv_cache.layers[0].linear_state.clone();
30243
30244        let e1 = p.embed_single((B - 2) as u32);
30245        let e2 = p.embed_single((B - 1) as u32);
30246        let _ = p.forward_pair(&e1, &e2, B - 2);
30247
30248        assert_eq!(p.o1_epoch, 1, "pair crossing B publishes one epoch");
30249        assert!(
30250            p.kv_cache
30251                .layers
30252                .iter()
30253                .enumerate()
30254                .all(|(li, l)| !p.o1_flags[li] || l.o1_sealed())
30255        );
30256        assert!(!p.kv_cache.layers[0].linear_state.is_empty());
30257        assert_ne!(
30258            p.kv_cache.layers[0].linear_state, lane1_state,
30259            "real pair must commit GDN lane 2 before returning"
30260        );
30261        assert!(p.kv_cache.layers[0].linear_scratch.is_empty());
30262        let next = p.embed_single(B as u32);
30263        let _ = p.forward_layers(&next, B, None);
30264        assert_eq!(p.o1_epoch, 1, "serial continuation must reuse the epoch");
30265    }
30266
30267    #[test]
30268    fn o1_error_observation_stays_terminal_until_reset() {
30269        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30270        p.set_o1(Some(crate::nystrom::O1Cfg {
30271            layers: crate::nystrom::O1Layers::All,
30272            m: 4,
30273            w: 8,
30274            sink: 2,
30275            rect: crate::nystrom::O1Rect::Aggregate,
30276        }));
30277        p.o1_begin();
30278        p.kv_cache.layers[0].o1_abort("synthetic transition failure".into());
30279
30280        assert!(p.o1_seal_checked().is_err());
30281        assert!(
30282            p.o1_seal_checked().is_err(),
30283            "retry must see the sticky error"
30284        );
30285        let k = vec![0.2f32; 4];
30286        let v = vec![0.3f32; 4];
30287        p.kv_cache.layers[0].append(&k, &v, &[]);
30288        assert_eq!(p.kv_cache.layers[0].seq_len, 0);
30289
30290        p.reset_session();
30291        p.o1_begin();
30292        p.kv_cache.layers[0].append(&k, &v, &[]);
30293        assert_eq!(p.kv_cache.layers[0].seq_len, 1);
30294    }
30295
30296    #[test]
30297    fn nll_graph_failure_is_terminal_and_request_is_reusable() {
30298        let ids = vec![1u32, 2, 3, 4, 5, 6];
30299        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30300        p.graph_logits = Some(vec![123.0]);
30301        p.graph_want_logits = true;
30302        p.graph_failed
30303            .store(true, std::sync::atomic::Ordering::Relaxed);
30304        p.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
30305        let err = p.nll_ids_from(&ids, 0).expect_err("prior graph failure");
30306        assert!(err.contains("before NLL"));
30307        assert!(p.graph_logits.is_none());
30308        assert!(!p.graph_want_logits);
30309        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
30310        assert!(!p.cancel.load(std::sync::atomic::Ordering::Relaxed));
30311
30312        let mut fresh = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30313        let expected = fresh.nll_ids_from(&ids, 0).expect("fresh NLL");
30314        let actual = p.nll_ids_from(&ids, 0).expect("reused NLL");
30315        assert_eq!(actual.1, expected.1);
30316        assert!((actual.0 - expected.0).abs() < 1e-9);
30317    }
30318
30319    #[test]
30320    fn nll_forward_failure_discards_partial_score_and_clears_sidechannels() {
30321        let ids = vec![1u32, 2, 3, 4, 5, 6];
30322        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30323        p.nll_test_fail_at = Some(1);
30324        let err = p
30325            .nll_ids_from(&ids, 0)
30326            .expect_err("one-shot forward failure");
30327        assert!(err.contains("forward") || err.contains("score row"));
30328        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
30329        assert!(!p.graph_want_logits);
30330        assert!(p.graph_logits.is_none());
30331        assert!(p.kv_history.is_empty());
30332
30333        let mut fresh = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30334        let expected = fresh.nll_ids_from(&ids, 0).expect("fresh NLL");
30335        let actual = p.nll_ids_from(&ids, 0).expect("reused NLL");
30336        assert_eq!(actual.1, expected.1);
30337        assert!((actual.0 - expected.0).abs() < 1e-9);
30338    }
30339
30340    #[test]
30341    fn nll_serial_failure_before_first_row_is_reported() {
30342        let ids = vec![1u32, 2, 3, 4];
30343        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30344        p.nll_test_force_serial = true;
30345        p.nll_test_fail_at = Some(0);
30346        let err = p.nll_ids_from(&ids, 0).expect_err("serial forward failure");
30347        assert!(err.contains("serial forward"));
30348        assert!(p.kv_history.is_empty());
30349        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
30350        assert!(!p.cancel.load(std::sync::atomic::Ordering::Relaxed));
30351    }
30352
30353    #[test]
30354    fn ffn_probe_failure_discards_recorder_and_state() {
30355        let ids = vec![1u32, 2, 3, 4];
30356        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30357        p.nll_test_fail_at = Some(0);
30358        let err = p
30359            .probe_ffn_mass_batch(&ids)
30360            .expect_err("probe forward failure");
30361        assert!(err.contains("NLL"));
30362        assert!(FFN_PROBE.with(|probe| probe.borrow().is_none()));
30363        assert!(p.kv_history.is_empty());
30364        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
30365    }
30366
30367    #[test]
30368    fn nll_test_controls_are_pipeline_scoped() {
30369        let ids = vec![1u32, 2, 3, 4];
30370        let mut failing = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30371        let mut unaffected = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30372        failing.nll_test_force_serial = true;
30373        failing.nll_test_fail_at = Some(0);
30374
30375        assert!(!failing.can_prefill_batched());
30376        assert!(unaffected.can_prefill_batched());
30377        let expected = unaffected
30378            .nll_ids_from(&ids, 0)
30379            .expect("unaffected pipeline remains usable");
30380        let err = failing
30381            .nll_ids_from(&ids, 0)
30382            .expect_err("failure injection belongs to failing pipeline");
30383        assert!(err.contains("serial forward"));
30384        assert!(failing.nll_test_fail_at.is_none());
30385        assert!(unaffected.can_prefill_batched());
30386        let actual = unaffected
30387            .nll_ids_from(&ids, 0)
30388            .expect("unaffected pipeline remains reusable");
30389        assert_eq!(actual.1, expected.1);
30390        assert!((actual.0 - expected.0).abs() < 1e-9);
30391    }
30392
30393    #[test]
30394    fn forward_ids_failure_channel_is_terminal_and_reusable() {
30395        let ids = vec![1u32, 2, 3, 4, 5, 6];
30396        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30397        p.graph_logits = Some(vec![123.0]);
30398        p.graph_want_logits = true;
30399        p.graph_failed
30400            .store(true, std::sync::atomic::Ordering::Relaxed);
30401        p.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
30402
30403        let err = p
30404            .forward_ids(&ids, None)
30405            .expect_err("a failed forward must not become a valid head result");
30406        assert!(err.contains("forward_ids setup"));
30407        assert!(p.graph_logits.is_none());
30408        assert!(!p.graph_want_logits);
30409        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
30410        assert!(!p.cancel.load(std::sync::atomic::Ordering::Relaxed));
30411        assert_eq!(p.kv_cache.seq_len(), 0);
30412
30413        let expected = create_test_pipeline(8, 16, 2, 1, 4, 1, 64)
30414            .forward_ids(&ids, None)
30415            .expect("fresh forward_ids");
30416        let actual = p
30417            .forward_ids(&ids, None)
30418            .expect("pipeline remains reusable after a failed forward");
30419        assert_eq!(actual.len(), expected.len());
30420        assert!(
30421            actual
30422                .iter()
30423                .zip(expected)
30424                .all(|(a, b)| (a - b).abs() < 1e-9)
30425        );
30426        assert_eq!(p.kv_cache.seq_len(), ids.len());
30427    }
30428
30429    #[test]
30430    fn sigmoid_router_floor_is_explicit_per_architecture() {
30431        // Flint and MiniMax M3.1 reference runtimes use +1e-20, while the
30432        // generic LFM2-compatible path uses +1e-6. At low (but representable)
30433        // sigmoid scores, silently sharing the latter changes expert weights by
30434        // orders of magnitude and can make a routed layer look coherent while
30435        // discarding its expert contribution.
30436        let zero = || DenseFfn {
30437            gate_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30438            up_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30439            down_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30440            act: Act::Silu,
30441            down_t: None,
30442            segs: Vec::new(),
30443        };
30444        let m = MoeFfn {
30445            router: QTensor::from_f32(vec![0.0; 4], 2, 2),
30446            experts: vec![zero(), zero()],
30447            top_k: 1,
30448            norm_topk_prob: true,
30449            router_sigmoid: true,
30450            sigmoid_denom_eps: 1e-20,
30451            expert_bias: None,
30452            routed_scaling: 2.5,
30453            route_tau: None,
30454            shared: None,
30455            stats: std::cell::RefCell::new(Vec::new()),
30456            act_sq: std::cell::RefCell::new(Vec::new()),
30457            act_rows: std::cell::RefCell::new(Vec::new()),
30458            mask: None,
30459            per_expert_scale: None,
30460            router_input_norm: false,
30461            resonance: None,
30462            grown: Vec::new(),
30463        };
30464        let logits = [-20.0f32, -20.0];
30465        let (_, p, flint_wsum) = moe_route(&logits, &m, None);
30466        let (_, _, minimax_wsum) = moe_route_with_eps(&logits, &m, None, 1e-20);
30467        let (_, _, legacy_wsum) = moe_route_with_eps(&logits, &m, None, 1e-6);
30468        let reference_expected = (p[0] + 1e-20) / m.routed_scaling;
30469        assert!((flint_wsum - reference_expected).abs() < 1e-15);
30470        assert_eq!(minimax_wsum.to_bits(), reference_expected.to_bits());
30471        assert!(legacy_wsum > minimax_wsum * 100.0);
30472    }
30473
30474    #[test]
30475    fn resonance_scores_match_formula_and_stable_tie() {
30476        let r = Resonance {
30477            // Three descriptors, hidden=2, one projection row each.
30478            mu: vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0],
30479            u: vec![1.0, 0.0, 0.0, 1.0, 1.0, 1.0],
30480            k: 1,
30481            bias: vec![1.5, 0.5, 0.0],
30482            shell: Vec::new(),
30483        };
30484        let x = [1.0f32, 1.0];
30485        let mut got = vec![0.0; 3];
30486        r.scores(&x, &mut got);
30487        // Expert 0 and 1 are an exact score tie; the CPU top-1 contract uses
30488        // the lower index.  The values also check d² - (U·d)², not just tie
30489        // ordering.
30490        assert!((got[0] - 0.5).abs() < 1e-6);
30491        assert!((got[1] - 0.5).abs() < 1e-6);
30492        assert!(got[2].abs() < 1e-6);
30493        let best = got
30494            .iter()
30495            .enumerate()
30496            .max_by(|(ia, a), (ib, b)| a.partial_cmp(b).unwrap().then(ib.cmp(ia)))
30497            .map(|(i, _)| i);
30498        assert_eq!(best, Some(0));
30499        assert!(got.iter().all(|v| v.is_finite()));
30500    }
30501
30502    /// The growth shell (spec §2): a grown expert whose reconstruction
30503    /// error lies outside its shell scores −∞, one inside keeps the exact
30504    /// resonance score, trunk rows (`+inf` shell) are bit-identical to the
30505    /// shell-less computation; the process-wide switch disables it.
30506    #[test]
30507    fn resonance_shell_masks_outside_keeps_inside_and_trunk_bits() {
30508        // hidden = 2, rank 1. Experts 0/1 = trunk (shell +inf); 2 and 3 =
30509        // grown, the same descriptor (μ = (0, 1), u = (1, 1)) with shells
30510        // 6.0 and 0.25. At x' = (3, 0): d = (3, −1), d² = 10, proj =
30511        // (3 − 1)² = 4, err = 6 exactly — on the boundary of expert 2's
30512        // shell (kept: the rule is strict `>`), outside expert 3's.
30513        let plain = Resonance {
30514            mu: vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0],
30515            u: vec![1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0],
30516            k: 1,
30517            bias: vec![1.5, 0.5, 0.0, 0.0],
30518            shell: Vec::new(),
30519        };
30520        let shelled = Resonance {
30521            mu: plain.mu.clone(),
30522            u: plain.u.clone(),
30523            k: 1,
30524            bias: plain.bias.clone(),
30525            shell: vec![f32::INFINITY, f32::INFINITY, 6.0, 0.25],
30526        };
30527        assert!(!plain.has_shell());
30528        assert!(shelled.has_shell());
30529        let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
30530        let (mut a, mut b) = (vec![0.0; 4], vec![0.0; 4]);
30531        set_growth_shell(Some(true));
30532        assert!(growth_shell_enabled());
30533        // x = (1, 1): the grown experts reconstruct it exactly (err 0):
30534        // inside both shells, every row the shell-less bits.
30535        let x = [1.0f32, 1.0];
30536        plain.scores(&x, &mut a);
30537        shelled.scores(&x, &mut b);
30538        assert_eq!(bits(&a), bits(&b), "inside every shell: unchanged");
30539        assert!(a[2] == 0.0 && a[3] == 0.0);
30540        // x' = (3, 0): expert 3 → −∞, expert 2 (err == shell) and the
30541        // trunk rows keep their exact bits.
30542        let xo = [3.0f32, 0.0];
30543        plain.scores(&xo, &mut a);
30544        shelled.scores(&xo, &mut b);
30545        assert_eq!(a[2], -6.0);
30546        assert_eq!(a[3], -6.0);
30547        assert_eq!(
30548            bits(&a[..3]),
30549            bits(&b[..3]),
30550            "trunk rows + the boundary row"
30551        );
30552        assert_eq!(b[3], f32::NEG_INFINITY, "outside the shell: −∞");
30553        assert_eq!(shelled.effective_shell(4), shelled.shell);
30554        // The switch (`CMF_GROWTH_SHELL=off` / `growth-eval --shell off`):
30555        // all +inf, the shell-less bits everywhere.
30556        set_growth_shell(Some(false));
30557        assert!(!growth_shell_enabled());
30558        assert_eq!(shelled.effective_shell(4), vec![f32::INFINITY; 4]);
30559        shelled.scores(&xo, &mut b);
30560        assert_eq!(bits(&a), bits(&b));
30561        set_growth_shell(None);
30562        // A shell vector shorter than the expert count masks nothing
30563        // beyond it (a legacy layer whose tail has no shell).
30564        let short = Resonance {
30565            shell: vec![f32::INFINITY, f32::INFINITY],
30566            ..shelled
30567        };
30568        set_growth_shell(Some(true));
30569        short.scores(&xo, &mut b);
30570        assert_eq!(bits(&a), bits(&b));
30571        set_growth_shell(None);
30572    }
30573
30574    /// `moe_route` with −∞ logits (a grown expert outside its shell):
30575    /// top-1 is the best finite expert with weight exactly 1.0 on both
30576    /// the softmax and the sigmoid path; all −∞ degrades to uniform.
30577    #[test]
30578    fn moe_route_neg_inf_logits_pick_the_best_finite_expert_with_weight_one() {
30579        let zero = || DenseFfn {
30580            gate_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30581            up_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30582            down_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30583            act: Act::Silu,
30584            down_t: None,
30585            segs: Vec::new(),
30586        };
30587        let moe = |sigmoid: bool| MoeFfn {
30588            router: QTensor::from_f32(vec![0.0; 8], 4, 2),
30589            experts: vec![zero(), zero(), zero(), zero()],
30590            top_k: 1,
30591            norm_topk_prob: true,
30592            router_sigmoid: sigmoid,
30593            sigmoid_denom_eps: 1e-6,
30594            expert_bias: None,
30595            routed_scaling: 1.0,
30596            route_tau: None,
30597            shared: None,
30598            stats: std::cell::RefCell::new(Vec::new()),
30599            act_sq: std::cell::RefCell::new(Vec::new()),
30600            act_rows: std::cell::RefCell::new(Vec::new()),
30601            mask: None,
30602            per_expert_scale: None,
30603            router_input_norm: false,
30604            resonance: None,
30605            grown: Vec::new(),
30606        };
30607        let logits = [-1.0f32, f32::NEG_INFINITY, -0.5, f32::NEG_INFINITY];
30608        for sigmoid in [false, true] {
30609            let m = moe(sigmoid);
30610            let (idx, p, wsum) = moe_route(&logits, &m, None);
30611            assert_eq!(idx, vec![2], "sigmoid {sigmoid}");
30612            assert_eq!(p[1], 0.0);
30613            assert_eq!(p[3], 0.0);
30614            assert!(p[2] > p[0] && p[0] > 0.0);
30615            assert!(p.iter().all(|v| v.is_finite()));
30616            let w = p[2] / wsum;
30617            if sigmoid {
30618                // The sigmoid renorm keeps its reference floor (+1e-6).
30619                assert!((w - 1.0).abs() < 1e-5, "sigmoid: weight {w}");
30620            } else {
30621                assert_eq!(
30622                    w, 1.0,
30623                    "softmax: the renormalized top-1 weight is exactly 1"
30624                );
30625            }
30626            // Masked experts stay masked even when they are the only ones
30627            // "admitted" by an allow-list that covers everything.
30628            let (idx, _, _) = moe_route(&logits, &m, Some(&[true, true, true, true]));
30629            assert_eq!(idx, vec![2]);
30630        }
30631        // A finite expert always beats −∞ whatever the bias / order.
30632        let m = moe(false);
30633        let (idx, _, _) = moe_route(
30634            &[
30635                f32::NEG_INFINITY,
30636                f32::NEG_INFINITY,
30637                f32::NEG_INFINITY,
30638                -9.0,
30639            ],
30640            &m,
30641            None,
30642        );
30643        assert_eq!(idx, vec![3]);
30644        // Every expert at −∞ (cannot happen on a grown file — trunk rows
30645        // have no shell): uniform, finite, lowest index.
30646        let (idx, p, wsum) = moe_route(&[f32::NEG_INFINITY; 4], &m, None);
30647        assert_eq!(idx, vec![0]);
30648        assert!(p.iter().all(|&v| v == 0.25));
30649        assert!(wsum.is_finite() && wsum > 0.0);
30650    }
30651
30652    /// MiniMax-M3.1's DEVICE route (the pooled token-graph arm's exact
30653    /// flags: sigmoid scoring via n's high bit, +1e-20 floor,
30654    /// routed_scaling 2.0, selection bias on the CHOICE only) must match
30655    /// the host reference in experts, ORDER and weights — the check that
30656    /// caught the flags/slot collision.
30657    #[cfg(feature = "gpu")]
30658    #[test]
30659    fn minimax_device_route_matches_host_sigmoid_contract() {
30660        match crate::gpu_wgpu::selected_and_up() {
30661            None => {
30662                crate::gpu_wgpu::skip_or_fail(module_path!());
30663                return;
30664            }
30665            // Sibling unit tests in THIS process select wgpu by writing
30666            // `CMF_GPU` (the gpu_wgpu test module does it ~70 times), so on a
30667            // headless runner the variable is already set by the time this
30668            // test reads it — "requested" here is test pollution, not an
30669            // operator's ask, and the adapter genuinely does not exist in
30670            // this process. Same treatment as the gpu_wgpu tests themselves:
30671            // a visible skip, never a silent pass.
30672            Some(false) => {
30673                eprintln!(
30674                    "SKIPPED ({}): CMF_GPU names wgpu but no adapter came up in this process",
30675                    module_path!()
30676                );
30677                return;
30678            }
30679            Some(true) => {}
30680        }
30681        let n = 128usize;
30682        let top_k = 4usize;
30683        let logits: Vec<f32> = (0..n)
30684            .map(|i| ((i as f32 * 0.61).sin() * 3.4) + ((i % 23) as f32 * 0.13))
30685            .collect();
30686        let bias: Vec<f32> = (0..n).map(|i| ((i as f32 * 2.3).cos()) * 0.5).collect();
30687        let m = MoeFfn {
30688            router: QTensor::from_f32(vec![0.0; 4], 2, 2),
30689            experts: Vec::new(),
30690            top_k,
30691            norm_topk_prob: true,
30692            router_sigmoid: true,
30693            sigmoid_denom_eps: 1e-20,
30694            expert_bias: Some(bias.clone()),
30695            routed_scaling: 2.0,
30696            route_tau: None,
30697            shared: None,
30698            stats: std::cell::RefCell::new(Vec::new()),
30699            act_sq: std::cell::RefCell::new(Vec::new()),
30700            act_rows: std::cell::RefCell::new(Vec::new()),
30701            mask: None,
30702            per_expert_scale: None,
30703            router_input_norm: false,
30704            resonance: None,
30705            grown: Vec::new(),
30706        };
30707        let (ci, p, wsum) = moe_route_with_eps(&logits, &m, None, 1e-20);
30708        let cw: Vec<f32> = ci.iter().map(|&e| p[e] / wsum).collect();
30709
30710        for shared in [Some(n as u32), None] {
30711            let mut gi = Vec::new();
30712            let mut gw = Vec::new();
30713            assert!(
30714                crate::gpu_wgpu::minimax_moe_route_for_test(
30715                    &logits,
30716                    Some(&bias),
30717                    top_k,
30718                    2.0,
30719                    shared,
30720                    &mut gi,
30721                    &mut gw,
30722                ),
30723                "the device did not come up — the test checked nothing"
30724            );
30725            let routed = if shared.is_some() { top_k } else { gi.len() };
30726            assert_eq!(
30727                &gi[..routed],
30728                &ci[..],
30729                "different experts or order (shared={shared:?})"
30730            );
30731            let d = cw
30732                .iter()
30733                .zip(&gw[..routed])
30734                .map(|(a, b)| (a - b).abs())
30735                .fold(0.0f32, f32::max);
30736            println!("minimax route shared={shared:?}: {ci:?} max|Δw|={d:.3e}");
30737            assert!(d < 1e-6, "the weights diverged by {d:.3e}");
30738            if let Some(s) = shared {
30739                assert_eq!(gi[top_k], s as usize, "shared pin slot");
30740                assert_eq!(gw[top_k], 1.0, "shared weight");
30741            }
30742        }
30743    }
30744
30745    /// The pooled arm's COLD hand-back: `(expert, weight)` pairs for the
30746    /// picks the bank could not serve must carry the host's EXACT final
30747    /// weights — the device ships its resident sum, the host adds this on
30748    /// top of the same residual, so a weight drift compounds per layer.
30749    #[cfg(feature = "gpu")]
30750    #[test]
30751    fn minimax_device_cold_weights_match_host_contract() {
30752        match crate::gpu_wgpu::selected_and_up() {
30753            None => {
30754                crate::gpu_wgpu::skip_or_fail(module_path!());
30755                return;
30756            }
30757            // Sibling unit tests in THIS process select wgpu by writing
30758            // `CMF_GPU` (the gpu_wgpu test module does it ~70 times), so on a
30759            // headless runner the variable is already set by the time this
30760            // test reads it — "requested" here is test pollution, not an
30761            // operator's ask, and the adapter genuinely does not exist in
30762            // this process. Same treatment as the gpu_wgpu tests themselves:
30763            // a visible skip, never a silent pass.
30764            Some(false) => {
30765                eprintln!(
30766                    "SKIPPED ({}): CMF_GPU names wgpu but no adapter came up in this process",
30767                    module_path!()
30768                );
30769                return;
30770            }
30771            Some(true) => {}
30772        }
30773        let n = 128usize;
30774        let top_k = 4usize;
30775        let logits: Vec<f32> = (0..n)
30776            .map(|i| ((i as f32 * 0.61).sin() * 3.4) + ((i % 23) as f32 * 0.13))
30777            .collect();
30778        let bias: Vec<f32> = (0..n).map(|i| ((i as f32 * 2.3).cos()) * 0.5).collect();
30779        let m = MoeFfn {
30780            router: QTensor::from_f32(vec![0.0; 4], 2, 2),
30781            experts: Vec::new(),
30782            top_k,
30783            norm_topk_prob: true,
30784            router_sigmoid: true,
30785            sigmoid_denom_eps: 1e-20,
30786            expert_bias: Some(bias.clone()),
30787            routed_scaling: 2.0,
30788            route_tau: None,
30789            shared: None,
30790            stats: std::cell::RefCell::new(Vec::new()),
30791            act_sq: std::cell::RefCell::new(Vec::new()),
30792            act_rows: std::cell::RefCell::new(Vec::new()),
30793            mask: None,
30794            per_expert_scale: None,
30795            router_input_norm: false,
30796            resonance: None,
30797            grown: Vec::new(),
30798        };
30799        let (ci, p, wsum) = moe_route_with_eps(&logits, &m, None, 1e-20);
30800        assert_eq!(ci.len(), top_k);
30801
30802        // Every pick resident → no cold pairs at all.
30803        let resident: Vec<u32> = (0..n).map(|e| e as u32).collect();
30804        let mut cold = Vec::new();
30805        let mut idx = Vec::new();
30806        let mut dw = Vec::new();
30807        assert!(crate::gpu_wgpu::minimax_moe_route_cold_for_test(
30808            &logits,
30809            Some(&bias),
30810            top_k,
30811            2.0,
30812            &resident,
30813            n as u32,
30814            &mut cold,
30815            &mut idx,
30816            &mut dw,
30817        ));
30818        assert!(cold.is_empty(), "fully resident bank: {cold:?}");
30819        // With subset+pin together: routed slots carry the FLAT remap value
30820        // (here identity = the expert id), weights the host contract, and
30821        // the pinned shared keeps weight 1 — this exact combination is what
30822        // the pooled arm runs with.
30823        for (r, &e) in ci.iter().enumerate() {
30824            assert_eq!(idx[r] as usize, e, "resident slot mapping r={r}");
30825            let host = p[e] / wsum;
30826            let d = (dw[r] - host).abs();
30827            assert!(
30828                d <= 1e-6 * host.abs().max(1.0),
30829                "resident weight r={r} expert {e}: device={:.9e} host={host:.9e}",
30830                dw[r]
30831            );
30832        }
30833        assert_eq!(idx[top_k] as usize, n, "shared pin slot");
30834        assert_eq!(dw[top_k], 1.0, "shared weight");
30835
30836        // Make exactly two of the CHOSEN picks cold.
30837        let mut remap = resident.clone();
30838        remap[ci[0]] = u32::MAX;
30839        remap[ci[2]] = u32::MAX;
30840        let mut cold = Vec::new();
30841        let mut idx2 = Vec::new();
30842        let mut dw2 = Vec::new();
30843        assert!(crate::gpu_wgpu::minimax_moe_route_cold_for_test(
30844            &logits,
30845            Some(&bias),
30846            top_k,
30847            2.0,
30848            &remap,
30849            n as u32,
30850            &mut cold,
30851            &mut idx2,
30852            &mut dw2,
30853        ));
30854        // The resident picks of the partial bank still carry exact weights.
30855        // A COLD rank is a placeholder the device writes as slot 0 / weight
30856        // 0.0 — its real (id, weight) pair rides in `cold` — so weight zero
30857        // is what marks it, not the slot value: reading the placeholder as
30858        // a resident expert compared 0.0 against p[0]/wsum and failed with
30859        // Δ=2.552e-1. The test logits keep every sigmoid score strictly
30860        // positive, so a resident pick can never weigh exactly zero.
30861        let mut resident_weight_checked = 0usize;
30862        for (r, &slot) in idx2.iter().enumerate().take(top_k) {
30863            if dw2[r] == 0.0 {
30864                continue; // cold rank: placeholder, not an expert id
30865            }
30866            let e = slot as usize;
30867            assert!(e < n && remap[e] != u32::MAX, "resident slot {e} escaped the remap");
30868            let host = p[e] / wsum;
30869            let d = (dw2[r] - host).abs();
30870            assert!(
30871                d <= 1e-6 * host.abs().max(1.0),
30872                "partial-bank resident weight expert {e}: Δ={d:.3e}"
30873            );
30874            resident_weight_checked += 1;
30875        }
30876        assert_eq!(resident_weight_checked, 2, "exactly two resident peaks out of four");
30877        println!("partial bank: checked {resident_weight_checked} resident weights");
30878        assert_eq!(dw2.get(top_k).copied(), Some(1.0), "shared weight under subset");
30879        let mut ids: Vec<usize> = cold.iter().map(|&(e, _)| e).collect();
30880        ids.sort_unstable();
30881        let mut want = vec![ci[0], ci[2]];
30882        want.sort_unstable();
30883        assert_eq!(ids, want, "the cold experts diverged: {cold:?} versus {want:?}");
30884        for &(e, w) in &cold {
30885            let host = p[e] / wsum;
30886            let d = (w - host).abs();
30887            println!("cold expert {e}: device={w:.9e} host={host:.9e} Δ={d:.3e}");
30888            assert!(d <= 1e-6 * host.abs().max(1.0), "cold weight of expert {e}: Δ={d:.3e}");
30889        }
30890    }
30891
30892    /// The resonance router (top-1) selects by the raw score as the
30893    /// trainer and the graph do — not by softmax probabilities, where two
30894    /// scores closer than 2^-25 collapse to the same `exp(l − max) = 1.0`
30895    /// and the LOWER index wins a token whose score is strictly smaller.
30896    #[test]
30897    fn resonance_route_picks_the_raw_argmax_not_the_softmax_tie() {
30898        let zero = || DenseFfn {
30899            gate_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30900            up_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30901            down_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30902            act: Act::Silu,
30903            down_t: None,
30904            segs: Vec::new(),
30905        };
30906        let moe = |resonant: bool, norm_topk: bool| MoeFfn {
30907            router: QTensor::from_f32(vec![0.0; 6], 3, 2),
30908            experts: vec![zero(), zero(), zero()],
30909            top_k: 1,
30910            norm_topk_prob: norm_topk,
30911            router_sigmoid: false,
30912            sigmoid_denom_eps: 1e-6,
30913            expert_bias: None,
30914            routed_scaling: 1.0,
30915            route_tau: None,
30916            shared: None,
30917            stats: std::cell::RefCell::new(Vec::new()),
30918            act_sq: std::cell::RefCell::new(Vec::new()),
30919            act_rows: std::cell::RefCell::new(Vec::new()),
30920            mask: None,
30921            per_expert_scale: None,
30922            router_input_norm: false,
30923            resonance: resonant.then(|| Resonance {
30924                mu: vec![0.0; 6],
30925                u: Vec::new(),
30926                k: 0,
30927                bias: vec![0.0; 3],
30928                shell: Vec::new(),
30929            }),
30930            grown: Vec::new(),
30931        };
30932        // lo = −0.1, hi = the next f32 towards zero: hi − lo = 2^-27 <
30933        // 2^-25, so exp(lo − hi) rounds to exactly 1.0 — a softmax tie.
30934        let lo = -0.1f32;
30935        let hi = f32::from_bits(lo.to_bits() - 1);
30936        assert!(hi > lo && hi - lo < 2f32.powi(-25));
30937        assert_eq!((lo - hi).exp(), 1.0, "the tie this test is about");
30938        // The gated MoE (softmax) path: the tie hands the token to index 0.
30939        let (idx, _, _) = moe_route(&[lo, hi], &moe(false, true), None);
30940        assert_eq!(
30941            idx,
30942            vec![0],
30943            "softmax tie → lower index (the gated contract)"
30944        );
30945        // The resonance path: the strictly larger raw score wins, weight
30946        // exactly 1.0 with and without norm_topk.
30947        for norm in [true, false] {
30948            let m = moe(true, norm);
30949            let (idx, p, wsum) = moe_route(&[lo, hi, f32::NEG_INFINITY], &m, None);
30950            assert_eq!(idx, vec![1], "norm_topk {norm}");
30951            assert_eq!(p, vec![0.0, 1.0, 0.0]);
30952            assert_eq!(p[1] / wsum, 1.0);
30953            // An exact tie: the first maximum (as `resonance_winner` and
30954            // `embryo_core_route_pick`).
30955            let (idx, _, _) = moe_route(&[hi, hi, lo], &m, None);
30956            assert_eq!(idx, vec![0]);
30957            // `−∞` never wins; the admitted set is honoured.
30958            let (idx, _, _) = moe_route(&[f32::NEG_INFINITY, lo, hi], &m, None);
30959            assert_eq!(idx, vec![2]);
30960            let (idx, p, wsum) = moe_route(&[lo, hi, hi], &m, Some(&[true, false, false]));
30961            assert_eq!(idx, vec![0]);
30962            assert_eq!(p[0] / wsum, 1.0);
30963            // Every admitted expert at −∞: the generic path's uniform
30964            // fallback (lowest index, finite weights).
30965            let (idx, p, wsum) = moe_route(&[f32::NEG_INFINITY; 3], &m, None);
30966            assert_eq!(idx, vec![0]);
30967            assert!(p.iter().all(|v| v.is_finite()) && wsum.is_finite() && wsum > 0.0);
30968        }
30969    }
30970}