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    /// A prompt chunk's rows' mHC streams a device prefix left on the card
156    /// (`[rows][streams · hidden]`), for the host's batched walk that continues
157    /// inside the range (`mhc_from_device`); taken by that walk.
158    mhc_rows_in: Vec<f32>,
159    /// Interleaved-MRoPE sections and the prompt rows' (t, h, w) positions
160    /// for the prefill of an image prompt (SenseNova-Loop); cleared when
161    /// the prefill ends.
162    pub mrope_sections: Option<[usize; 3]>,
163    pub prompt_mrope: Option<Vec<[i64; 3]>>,
164    pub vocab_size: usize,
165    pub rms_eps: f64,
166    pub rope_base: f32,
167    pub norm_style: NormStyle,
168    /// RoPE dims actually rotated (≤ head_dim; Qwen3.5 uses head_dim/4).
169    pub rotary_dim: usize,
170    /// Optional Q-head count override for each attention layer (Laguna).
171    pub attention_heads_per_layer: Option<Vec<usize>>,
172    /// Optional KV-head count of each PHYSICAL attention layer (MiMo-V2:
173    /// 4 on full-attention layers, 8 on sliding ones). Set only through
174    /// [`Pipeline::set_attn_geometry`], which also reshapes the layer
175    /// caches. None = every layer has `num_kv_heads`.
176    pub kv_heads_per_layer: Option<Vec<usize>>,
177    /// Width of each V head when it is narrower than `head_dim` (MiMo-V2:
178    /// 128 against 192). V is zero-padded to `head_dim` inside the cache
179    /// and the attention output is compacted back to nh·v_head_dim before
180    /// o_proj (see `QwenAttnCfg::v_head_dim`). None = `head_dim`.
181    pub v_head_dim: Option<usize>,
182    /// `CMF_LAYER_DUMP=<dir>` (read once at construction; tests set it
183    /// directly): the hidden state after every layer, for every position,
184    /// as raw little-endian f32 files `p{pos:06}_l{li:02}.f32` of
185    /// `hidden_size` floats each. Written by the CPU layer walks — the
186    /// batched prefill (`prefill_batch_span`) and the single-token forward
187    /// (`forward_layers_span`) — so both prompt ingest and decode can be
188    /// diffed layer by layer against an external oracle (tools/mimo_ref).
189    /// Layers a device graph runs (wgpu token/batch graph, Metal chunk or
190    /// block graphs) and the own-stack families (DeepSeek-V4/V4.1,
191    /// Qwen3.8-Flash-Next, Gemma-3n) are not dumped: run with CMF_GPU=0
192    /// for a complete set. `li` is the virtual layer index. Final logits:
193    /// `CMF_LOGIT_DUMP=<file>` (hidden + logits of the first decode step).
194    pub layer_dump: Option<std::path::PathBuf>,
195    /// GPU-graph declines already logged for this pipeline, as (graph
196    /// site, reason) — one line each, see `graph_attn_decline_reason`.
197    graph_declines: std::cell::RefCell<Vec<(&'static str, &'static str)>>,
198    /// MiMo-V2 expert placement (prefix / dynamic bank / hybrid), decided
199    /// on the first forward — see `crate::mimo_moe`.
200    pub(crate) mimo_moe: crate::mimo_moe::Slot,
201    /// Opt-in MiniCPM q4tp expert cache for a graph-produced CPU tail.
202    /// It is deliberately separate from MiMo's placement policy because it
203    /// serves only the stock MiniCPM top-8 geometry and otherwise falls back
204    /// to the ordinary exact host MoE path.
205    pub(crate) minicpm_tail: crate::minicpm_tail::MiniCpmTail,
206    /// Linear-core geometry (present when the model has linear layers).
207    pub vmf_cfg: Option<VmfPhaseCfg>,
208    /// GatedDeltaNet geometry (faithful vendor operator).
209    pub gdn_cfg: Option<GdnCfg>,
210    /// MiniCPM-class logit scale (tied lm_head → cannot fold into weights).
211    pub logit_multiplier: Option<f32>,
212    /// Cooperative cancel: set from any thread (FFI `cortiq_cancel`,
213    /// a dropped server connection); the generate loop checks it at
214    /// every prefill chunk and decode step and finishes with
215    /// `finish_reason: "cancelled"`. Auto-cleared when honoured.
216    pub cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
217    /// A GPU graph failure is distinct from a user/request cancellation.
218    /// Graph code sets this before raising the cooperative cancel flag so the
219    /// generation API can return an error instead of reporting a successful
220    /// `finish_reason: cancelled` result.
221    graph_failed: std::sync::atomic::AtomicBool,
222    /// Resident-graph MoE expert banks, built once per layer
223    /// (`GraphMoeBank`). `CMF_GRAPH_MOE_BANK=0` rebuilds them every token.
224    graph_moe_banks: std::sync::Mutex<std::collections::HashMap<GraphMoeKey, GraphMoeBank>>,
225    /// Token ids currently materialized in the KV cache (the forwarded
226    /// prompt + all generated tokens except the last, which is sampled
227    /// but not yet forwarded). Lets the next generate call prefill only
228    /// the suffix when a chat app resends the whole history.
229    pub kv_history: Vec<u32>,
230    /// Owner tag of `kv_history`: the resident device graph held that
231    /// sequence (true) or the host did. Reuse continues only on the owner.
232    pub kv_history_device: bool,
233    /// KDA geometry (Kimi Linear / Kimi-K3) — shared by every Kda layer.
234    pub kda_cfg: Option<crate::linear_core::KdaCfg>,
235    /// Gemma-3n stack (AltUp/LAuReL/PLE/KV-sharing): its own forward —
236    /// weights.layers stays empty, the KV caches are the shared ones.
237    pub g3n: Option<Box<(crate::g3n::G3nGlobals, Vec<crate::g3n::G3nLayer>)>>,
238    /// Gemma-4 E-series stack (dual-geometry gemma4 + PLE + shared KV):
239    /// its own per-token forward, same contract as `g3n`.
240    pub g4e: Option<Box<(crate::g4e::G4eGlobals, Vec<crate::g4e::G4eLayer>)>>,
241    /// DeepSeek-V4 runs its own stack too: its hidden state is `hc_mult`
242    /// copies of a vector, so no loop written for a single residual
243    /// stream can carry it.
244    pub dsv4: Option<
245        Box<(
246            crate::dsv4::Dsv4Globals,
247            Vec<crate::dsv4::Dsv4Layer>,
248            crate::dsv4::Dsv4Cfg,
249            crate::dsv4::Dsv4State,
250        )>,
251    >,
252    /// DeepSeek-V4.1 owns the shared CED/CSA2 attention state, raw Engram
253    /// lookup and four-stream mHC handoff. It cannot use the V4 cache
254    /// layout, so it has a dedicated executor and state tuple.
255    /// Dory: a looped normalized GPT, its weights and KV state (`dory`).
256    pub dory: Option<Box<(crate::dory::Dory, crate::dory::DoryState)>>,
257    pub dsv41: Option<
258        Box<(
259            crate::dsv41::Dsv41Globals,
260            Vec<crate::dsv41::Dsv41Layer>,
261            crate::dsv41::Dsv41Cfg,
262            crate::dsv41::Dsv41State,
263        )>,
264    >,
265    /// Optional V4.1 vision tower. Text-only files leave this unset.
266    pub dsv41_vision: Option<crate::dsv41_vision::VisionModel>,
267    /// Prepared image rows consumed by the next V4.1 prefill.
268    dsv41_prefill: Option<(Vec<Option<Vec<f32>>>, Vec<bool>)>,
269    /// Qwen3.8-Flash-Next owns four residual streams plus QSA/PLE state;
270    /// the generic single-residual layer loop cannot represent it.
271    /// Block-diffusion generation (Clover): preview weights and the
272    /// decoding controls; `None` on every causal model.
273    pub(crate) clover: Option<std::sync::Arc<clover::Clover>>,
274    clover_stats: clover::CloverStats,
275    /// The causal decode's response penalties (`clover_causal_logits`).
276    clover_pen: clover::Penalties,
277    pub qwen4_exp: Option<
278        Box<(
279            crate::qwen4_exp::Globals,
280            Vec<crate::qwen4_exp::Layer>,
281            crate::qwen4_exp::Cfg,
282            crate::qwen4_exp::State,
283        )>,
284    >,
285    /// Hy4-flash owns four iHC streams, gated MLA/indexer state and Engram.
286    pub hy4: Option<
287        Box<(
288            crate::hy4::Globals,
289            Vec<crate::hy4::Layer>,
290            crate::hy4::Cfg,
291            crate::hy4::State,
292        )>,
293    >,
294    /// Maxwell-V1-Flash owns four mHC streams, its block router and a
295    /// sigmoid-routed MoE.
296    pub maxwell: Option<
297        Box<(
298            crate::maxwell::Globals,
299            Vec<crate::maxwell::Layer>,
300            crate::maxwell::Cfg,
301            crate::maxwell::State,
302        )>,
303    >,
304    /// Inkling-2-Mini owns its looped stack: block attention residuals,
305    /// short convolutions, per-pass caches.
306    pub inkling: Option<
307        Box<(
308            crate::inkling::Globals,
309            Vec<crate::inkling::Layer>,
310            crate::inkling::Cfg,
311            crate::inkling::State,
312        )>,
313    >,
314    /// GLM-5.3-Flash owns four mHC streams plus KDA/DSA state.
315    pub glm5_next: Option<
316        Box<(
317            crate::glm5_next::Globals,
318            Vec<crate::glm5_next::Layer>,
319            crate::glm5_next::Cfg,
320            crate::glm5_next::State,
321        )>,
322    >,
323    /// DeepSeek-V4's own speculation stack: three draft modules, each a full
324    /// layer, plus a confidence head on the last. Empty when the file has
325    /// none, which is the only signal the decode path needs.
326    pub dsv4_mtp: Vec<crate::dsv4::Dsv4Mtp>,
327    /// The draft's per-sequence state (KV rings, captured trunk hidden).
328    pub dspark: Option<crate::dsv4::DsparkState>,
329    /// Drafts awaiting their verdict: (position, proposals, still matching,
330    /// accepted so far).
331    pub dspark_pending: Vec<(usize, Vec<u32>, bool, usize)>,
332    /// Accepted prefix length of every graded draft.
333    pub dspark_hist: Vec<usize>,
334    /// The real tokens the drafts were graded against — a degenerate,
335    /// repeating output would make any acceptance number meaningless, and
336    /// the cheapest guard against believing one is to count them.
337    pub dspark_real: Vec<u32>,
338    /// The trunk's expert picks for the last few tokens, per layer. The
339    /// union over a window of them is what a batched verify would have to
340    /// read, and the ratio to the pick count is all it could save.
341    pub dspark_trunk_picks: Vec<Vec<(usize, Vec<usize>)>>,
342    /// (unique, total) expert picks per draft, trunk side and draft side.
343    pub dspark_exp: Vec<(usize, usize, usize, usize)>,
344    /// Wall time spent in the deliberately out-of-core draft. Kept separate
345    /// from trunk decode so block batching can be judged without conflating
346    /// it with GPU chain variance.
347    pub dspark_draft_ns: u128,
348    /// Per-layer winners of the last pooled route — the admission predictor.
349    m3_winners: Vec<Vec<u32>>,
350    /// Route frequency per (layer, expert) — the bank's prewarm profile.
351    m3_counts: Vec<u32>,
352    m3_n_exp: usize,
353    m3_tokens: u64,
354    m3_prewarmed: bool,
355    /// LFM2 short-convolution geometry (present when the model has
356    /// `ShortConv` mixer layers).
357    pub short_conv_cfg: Option<ShortConvCfg>,
358    /// Multi-token-prediction head (None = absent).
359    pub mtp: Option<MtpModule>,
360    /// MiMo-V2's draft stack (three chained MTP layers from the
361    /// `<stem>.mtp.cmf` sidecar); None = absent. Speculative greedy decode
362    /// uses it unless `CMF_MTP=0` / `CMF_MIMO_MTP=0`.
363    pub mimo_mtp: Option<mimo_mtp::MimoMtp>,
364    /// Set while the MiMo speculative verify runs `prefill_batch`: its MoE
365    /// layers take `moe_ffn_rows_exact` (each row bit-identical to decode).
366    verify_exact_moe: bool,
367    /// Speculative decode via MTP (greedy only; `CMF_MTP=0` disables).
368    pub speculative: bool,
369    /// Keep generating past end-of-sequence ids (the llama-bench contract
370    /// for a timed run). A loop flag, deliberately NOT a sampler
371    /// suppression: suppressed ids count as a penalty and switch the
372    /// speculative round and the greedy burst off, so a benchmark that
373    /// suppressed EOS never measured either.
374    pub ignore_eos: bool,
375    /// Draft-head shortlist guard: tokens left during which the draft
376    /// uses the FULL head because a recently committed id lay past the
377    /// `CMF_DRAFT_VOCAB` cut (Cyrillic and CJK ids sit above 131072 in
378    /// Qwen's table, so a prefix shortlist would draft nothing usable
379    /// there — measured on Russian prose: 2.9 → 1.6 accepted a round).
380    pub draft_full_streak: u32,
381    /// Adaptive draft depth for the speculative round (None until the
382    /// first round): grows while nearly every draft is accepted, shrinks
383    /// when fewer than half are. The verify's cost climbs with the rows on
384    /// a discrete card (RTX PRO 4000: 52 ms at 2 rows, 74 at 5, 80 at 6),
385    /// so prose wants k≈3 and code or the repetitive bench k≈5 — measured
386    /// 33.6 vs 27.6 tok/s on an essay at k=3 vs 5, 45.6 vs 38 on code.
387    /// `CMF_GRAPH_SPEC_K` pins it.
388    pub spec_k_adapt: Option<usize>,
389    /// EWMA of the accepted fraction that drives `spec_k_adapt`.
390    pub spec_acc_ewma: f32,
391    /// Native Metal over a q4tp trunk: how often draft `j` holds once the
392    /// one before it held, a running average (see `metal_spec_depth`).
393    pub spec_hold: [f32; 7],
394    /// wgpu: what a round of k drafts costs on this device, a running
395    /// average of its wall in ms (0 until a depth has run twice), the rounds
396    /// each depth has run, and the rounds the depth still stays where the
397    /// last change put it (`wgpu_spec_depth`).
398    spec_wall: [f32; 7],
399    spec_wall_n: [u8; 7],
400    spec_k_dwell: u8,
401    /// wgpu: a plain token's time as a speculation trial last measured it,
402    /// and the position it was measured at. A later request's trial decides
403    /// from it instead of decoding eight plain tokens again.
404    spec_plain_ms: (f64, usize),
405    /// wgpu: the batch graph refused a verify because the whole stack does not fit
406    /// the weight budget (a device prefix runs the rest on the host): the drafts
407    /// stay off for this model, their rounds could never be checked.
408    spec_over_budget: bool,
409    /// The same for the DFlash drafter's rounds, and whether the last round
410    /// was one of them.
411    pub dflash_hold: [f32; 7],
412    dflash_last: bool,
413    /// Rounds the DFlash block still sits out, the wait its next lost turn
414    /// costs, and the rounds of its turn so far.
415    dflash_wait: u32,
416    dflash_back: u32,
417    dflash_turn: u32,
418    /// The tokens the turn's rounds landed and what they cost, in plain tokens.
419    dflash_turn_sum: (f32, f32),
420    /// The sidecar's router: how far the target's last rows lean to the
421    /// block's rounds (a running average of `Route::margin`).
422    dflash_lean: f32,
423    /// The depth of the block's rounds on a card whose verify grows with its
424    /// rows, and the running share of drafts they keep (`spec_k_adapt`'s twin).
425    dflash_k_adapt: Option<usize>,
426    dflash_acc_ewma: f32,
427    /// Prompt lookup on native Metal: the drafts it added to a round that
428    /// held, a running average, and the rounds it sits out after that fell
429    /// under `LOOKUP_PAYS`.
430    pub spec_lookup_gain: f32,
431    /// CUDA: the context lookup may fill a 16-row verify window (after a
432    /// lookup round whose drafts all held), else 8 rows (one price there).
433    pub spec_lookup_wide: bool,
434    pub spec_lookup_rest: u32,
435    rng: SplitMix64,
436    sampler_scratch: SamplerScratch,
437    /// Speculative SAMPLING state (graph_spec_step, temperature > 0): the
438    /// correction token a rejected draft produced — committed by the loop
439    /// top in place of a fresh draw — and the per-round draft
440    /// distributions / target scratch, reused so a round allocates
441    /// nothing at the vocab size.
442    spec_forced: Option<u32>,
443    spec_q: Vec<Vec<f32>>,
444    spec_p: Vec<f32>,
445    spec_res: Vec<f32>,
446    /// The same three for the sparse chain (top-k configs).
447    spec_qs: Vec<sampler::Sparse>,
448    spec_ps: sampler::Sparse,
449    spec_ress: sampler::Sparse,
450    /// Which arm the MTP draft block runs on this generation: Some(true)
451    /// = the whole-token graph (device attention, one submit a step),
452    /// Some(false) = the per-op path; None = not decided yet. Decided
453    /// on the first draft and held, because the two arms keep the MTP
454    /// KV in different places (device mirror vs the CPU cache) and a
455    /// mid-run switch would read the wrong one.
456    mtp_graph_mode: Option<bool>,
457    /// The DFlash block drafter of the model's sidecar (`CMF_DFLASH=1`): it
458    /// drafts a round in one block from the trunk's tapped layer outputs.
459    pub dflash: Option<Box<crate::dflash::Drafter>>,
460    /// The tapped rows of the verify in flight, joined a row at a time, and
461    /// their first position: the accepted ones become the drafter's context.
462    dflash_rows: Option<(usize, Vec<f32>)>,
463    /// Rows the wgpu graphs kept for the drafter, `(first position, rows as
464    /// [row][layer][hidden])` in the order the graphs ran: a prompt's and a
465    /// plain token's become context at the next round, a verify's are taken
466    /// by the round that ran it.
467    dflash_taps: std::sync::Mutex<Vec<(usize, Vec<f32>)>>,
468    /// The sidecar's block is the trunk's only drafter (the model has no MTP
469    /// block): the wgpu graphs keep its rows without being asked to.
470    pub(crate) dflash_solo: bool,
471    /// The first position whose tapped rows a DFlash drafter can still
472    /// read once the prompt is in (its layers' widest window back from the
473    /// prompt's end): the prompt's chunks before it keep none.
474    dflash_tap_from: usize,
475    /// The Metal verify graph of the round in flight, between its sync
476    /// (logits read) and the commit that replays the accepted prefix.
477    #[cfg(target_os = "macos")]
478    metal_verify: Option<MetalVerifyPending>,
479    /// Precomputed RoPE inverse frequencies [head_dim/2]. Arc: the
480    /// forward path clones a handle to escape the &mut self borrow —
481    /// cloning the table itself was a per-forward allocation.
482    pub(crate) inv_freq: std::sync::Arc<Vec<f32>>,
483    /// Reusable norm buffers for the decode hot path (roadmap §3 P0:
484    /// steady-state forward should not heap-allocate). Disjoint field
485    /// from `weights`/`kv_cache`, so split borrows keep working.
486    ws: ForwardScratch,
487    /// Persistent worker pool (None = serial; see CMF_THREADS).
488    pool: Option<std::sync::Arc<Pool>>,
489    // ── Dynamic per-token skill routing (spec §9, claim 14/16) ──
490    /// Source model, retained so a skill switch can re-resolve the
491    /// touched layers' FFN tensors (Mapped = mmap pointers, cheap).
492    pub(crate) model: Option<std::sync::Arc<cortiq_core::CmfModel>>,
493    /// Masks present → weights are dequantized f32 (rebuild path).
494    pub(crate) dyn_force_f32: bool,
495    /// Per-skill FFN layers actually replaced (derived from tensors, not
496    /// the meta `layers` field — ru2 replaces down_proj in 0..23 while
497    /// its meta says [20..23]). None = skill touches non-FFN tensors →
498    /// ineligible for cheap dynamic switching (honest refusal).
499    pub(crate) dyn_skill_layers: Vec<Option<Vec<usize>>>,
500    /// Currently overlaid skill (index into model.header.skills); None =
501    /// backbone. Set at load time to the statically-overlaid skill so
502    /// `set_active_skill(None)` correctly reverts it (else a static
503    /// skill would silently persist — the union-diff assumes dyn_active
504    /// always mirrors the live overlay). Switched by `set_active_skill`.
505    pub(crate) dyn_active: Option<usize>,
506    /// Pipeline was loaded with a soft blend (materialized working
507    /// tensors, not a single skill index) → dynamic routing refuses:
508    /// there is no single index to revert the blend from.
509    pub(crate) dyn_blend_loaded: bool,
510    /// Layer whose post-residual hidden feeds the router φ (shared by
511    /// swarm skills). None = φ capture off.
512    pub(crate) dyn_phi_layer: Option<usize>,
513    /// EMA of φ at `dyn_phi_layer` over the decode window (on-policy).
514    dyn_phi_ema: Vec<f32>,
515    dyn_phi_seen: usize,
516    /// φ rows a device token graph kept at `dyn_phi_layer` (its layer taps):
517    /// the graph runs the router's layer on the card, so the host loop's φ
518    /// hook never sees it; `forward_layers_upto` folds these into the EMA.
519    dyn_phi_tap: std::sync::Mutex<Option<Vec<f32>>>,
520    /// Hysteresis router driving per-token skill switches during decode
521    /// (None = static/no dynamic routing). Taken out during generation.
522    pub dyn_router: Option<crate::swarm::DynRouter>,
523    /// O(1) Nyström attention setting (CLI/env/header-hint resolved by
524    /// the caller; None = plain cache attention everywhere).
525    o1_cfg: Option<crate::nystrom::O1Cfg>,
526    /// A turbo file: the far field on long prompts only (`cortiq far-turbo`).
527    pub(crate) o1_turbo: Option<O1Turbo>,
528    /// Over a far field the draft head starts at this prompt row, and counts from it.
529    mtp_pos_base: usize,
530    /// A whole prompt's tail rows read by the far field's prefix (the draft
531    /// head is warmed over them).
532    o1_prefix_tail: Vec<f32>,
533    /// The CUDA hybrid arm's chat snapshot: the prompt ids before the last
534    /// turn's assistant header, whose GDN states the card keeps a copy of
535    /// (`gpu::gdn_snapshot`). The next turn that starts with them goes back
536    /// there and reads only what follows.
537    gdn_snap: Option<Vec<u32>>,
538    /// The draft head's base position when the last turn warmed it over
539    /// its whole prompt on the batched path (None otherwise): its rows from
540    /// there to that prompt's end are prompt rows a chat snapshot keeps.
541    mtp_warm_base: Option<usize>,
542    /// Bumped once per collecting→sealed transition — the GPU state mirror
543    /// re-uploads when it sees a new epoch (each fresh sealed state).
544    o1_epoch: u64,
545    /// Per-layer o1 flags derived from `o1_cfg` (Full layers only).
546    o1_flags: Vec<bool>,
547    /// Emit a structured per-token trace (B4 telemetry channel). Off by
548    /// default — the runtime is silent unless observation is requested.
549    trace: bool,
550    /// Confidence-calibration temperature (B1): reported probability is
551    /// softmax(logits / calib_temp). 1.0 = raw. Set from header.calibration.
552    calib_temp: f32,
553    /// Process-unique id keying this pipeline's device KV mirrors.
554    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
555    graph_kv_id: u64,
556    /// Decode asks the token graph to also run final-norm + lm_head on
557    /// the device (drops the separate per-op lm_head round trip).
558    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
559    graph_want_logits: bool,
560    /// NLL quality gates require the graph's fused head rather than silently
561    /// accepting a CPU head fallback. Generation keeps the historical
562    /// best-effort `graph_want_logits` behavior.
563    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
564    graph_head_required: bool,
565    /// Logits the graph produced for the token just forwarded (taken by
566    /// the decode loop; None = compute on the CPU path).
567    graph_logits: Option<Vec<f32>>,
568    /// Packed Embryo graph model, built lazily on the first eligible
569    /// resident call so other architectures pay no packing cost.
570    embryo_graph: Option<std::sync::Arc<crate::gpu::EmbryoGraphModel>>,
571    /// The wide token path refused this file: a matrix is not exactly f16.
572    embryo_wide_refused: bool,
573    /// This pipeline's token graph refused for a STRUCTURAL reason (its
574    /// own weights / layer kinds): not retried. Per pipeline, never
575    /// process-wide: a skill lane whose pack does not build must not flip
576    /// the backbone slot mid-sequence onto the host path (and a new lane
577    /// must not clear the backbone's verdict) — R4/NF-2.
578    graph_refused: std::sync::atomic::AtomicBool,
579    /// Token embeddings are multiplied by this at input (Gemma: √hidden).
580    pub embed_multiplier: f32,
581    /// Attention score scale (1/√head_dim unless the arch overrides —
582    /// Gemma's query_pre_attn_scalar).
583    pub attn_scale: f32,
584    /// Sliding-window attention: (window, every-Nth-layer-is-global
585    /// pattern) — Gemma-3.
586    pub swa: Option<(usize, usize)>,
587    /// Sliding-window tail trimming, `(slack, align)` for
588    /// `LayerKvCache::trim_window`: every layer with a window keeps only
589    /// the rows its window can still read (Spark-X2.5: 576..639 rows per
590    /// 512-window layer instead of the whole context — 27 of the 4B's 36
591    /// layers). Set at load for Spark-X2.5 only (`CMF_SWA_TRIM=0` turns
592    /// it off); None keeps every row, as every other model always has.
593    pub swa_trim: Option<(usize, usize)>,
594    /// On the wgpu graphs a full-attention layer of the call's own geometry
595    /// takes the uniform arms (f16 mirror rows, the flash-decoding attend)
596    /// beside sliding layers on their rings, instead of every layer going
597    /// the per-layer-geometry kernels because one of them slides. Set at
598    /// load for Aion (`CMF_MIXED_GEOM=0` turns it off).
599    pub uniform_full_layers: bool,
600    /// Prompt end of the current turn: the tail trim keeps every row a
601    /// rollback to it still reads (`LayerKvCache::trim_window_anchored`),
602    /// so the next chat turn can drop this turn's answer.
603    swa_trim_anchor: usize,
604    /// Fewest prompt rows the Metal chunk prefill graph takes; a shorter
605    /// chunk walks the layers on the host. 32 since the graph landed
606    /// (measured on Qwen2.5-0.5B); Spark-X2.5/X2.6 take 8 (`loader`).
607    pub chunk_min_rows: usize,
608    /// A far field's exact prefix rides the Metal chunk graph, which then also
609    /// keeps the collecting layers' queries (`o1_prefix_on_metal`).
610    o1_chunk_prefix: bool,
611    /// The batched wgpu graph declined this dense stack's prompt: later
612    /// prompts read chunked on the host walk (`graph_prefill_preferred`).
613    dense_batch_declined: std::sync::atomic::AtomicBool,
614    /// Explicit local/global schedule for architectures that cannot be
615    /// represented by Gemma's every-Nth-global convention.
616    pub sliding_layers: Option<Vec<bool>>,
617    /// Per-layer flag: this layer runs WITHOUT RoPE. Recursive Flint applies
618    /// position encoding only on its sliding-window layers; its 14
619    /// full-attention layers have none. The rotary dim of such a layer is 0,
620    /// which is what the attention kernel reads.
621    pub no_rope_layers: Option<Vec<bool>>,
622    /// Ripple's value residual: per layer, the blend `sigmoid(value_res_lambda)` of the lerp
623    /// that feeds V, `lerp(embedding, normed, blend)`. None = V reads the normed input.
624    pub value_blend: Option<Vec<f32>>,
625    /// The scaled embedding rows of the positions in flight (one, a pair's two, a chunk's).
626    vres_e0: Vec<f32>,
627    /// The rows V projects in the layer being run.
628    vres_in: Vec<f32>,
629    /// Natively bounded anchor record (`arch.anchor_core`): the file's
630    /// operator, installed once at load. `Some` = the model is
631    /// bounded-native — `--o1`/`CMF_O1*` are refused, prefix reuse and
632    /// the penalty window are bounded, and no anchor layer stores
633    /// anything per position.
634    pub anchor_core: Option<cortiq_core::AnchorCoreConfig>,
635    /// The `[W][rd/2]` relative-rotation table every bounded layer shares
636    /// (built from `inv_freq` once the RoPE setup is final).
637    bounded_rope: Option<std::sync::Arc<crate::bounded::BoundedRope>>,
638    /// Bounded prefix-reuse key (length + rolling hash + tail) of a
639    /// bounded-native model; `kv_history` stays empty there so nothing
640    /// in the pipeline grows with the dialogue.
641    pub kv_prefix: KvPrefix,
642    /// Prompt positions the last `generate*` call actually forwarded
643    /// (prefix reuse subtracts what the cache already held).
644    pub last_prefill_tokens: usize,
645    /// RoPE table of the sliding (local) layers, when they use their
646    /// own base frequency (Gemma-3: 10k local vs 1M global).
647    pub inv_freq_local: Option<std::sync::Arc<Vec<f32>>>,
648    pub rotary_dim_local: Option<usize>,
649    pub rope_scale: f32,
650    pub rope_scale_local: f32,
651    /// Gemma-4: global layers run their own geometry — (head_dim,
652    /// num_kv_heads); sliding layers keep the base fields.
653    pub global_attn: Option<(usize, usize)>,
654    /// Gemma-4: the global layers' proportional RoPE table (len
655    /// global_head_dim/2, zero-padded tail = identity rotation).
656    pub inv_freq_global: Option<std::sync::Arc<Vec<f32>>>,
657    /// Scale-less RMS normalization of V heads before caching (Gemma-4).
658    pub attn_v_norm: bool,
659    /// HunYuan dense: per-head q/k norm runs after RoPE (see the arch flag).
660    pub qk_norm_after_rope: bool,
661    /// The per-head `self_attn.g_proj` output gate uses sigmoid
662    /// (Spark-X2.5) instead of softplus (Laguna).
663    pub proj_gate_sigmoid: bool,
664    /// Final-logit soft-capping C: logits = C·tanh(logits/C) (Gemma-4).
665    pub final_softcap: Option<f32>,
666    /// Cortiq Embryo hierarchical head: cluster matrix [C, hidden]. The
667    /// flat logits h·Eᵀ are turned into the two-level log-probabilities
668    /// log softmax_c(h·Cᵀ)[c(v)] + log softmax_{s∈c(v)}(h·E_c(v)ᵀ)[v].
669    pub head_clusters: Option<std::sync::Arc<Vec<f32>>>,
670    /// Gemma-2 attention-logit soft-capping (0.0 = off).
671    pub attn_softcap: f32,
672    /// Compute per-token confidence (a full-vocab softmax each
673    /// token). On by default; `bench --core` turns it off to match
674    /// llama-bench's core timing.
675    confidence_on: bool,
676    /// `prompt_next_logits`: keep the first decode step's logits (the
677    /// next-token logits after the prompt) in `first_logits`.
678    want_first_logits: bool,
679    first_logits: Option<Vec<f32>>,
680    /// Test-only one-shot forward failure, scoped to this pipeline so
681    /// parallel scoring tests cannot consume one another's injection.
682    #[cfg(test)]
683    nll_test_fail_at: Option<usize>,
684    /// Test-only route override; avoids mutating the process-wide
685    /// `CMF_PREFILL` environment variable while forcing the serial path.
686    #[cfg(test)]
687    nll_test_force_serial: bool,
688}
689
690#[cfg(target_os = "macos")]
691impl Drop for Pipeline {
692    fn drop(&mut self) {
693        // the async replay writes into `kv_cache` Vecs about to be freed
694        let _ = crate::gpu_metal::wait_replay();
695        crate::gpu::kv_mirror_drop(self.graph_kv_id);
696    }
697}
698
699#[cfg(not(target_os = "macos"))]
700impl Drop for Pipeline {
701    fn drop(&mut self) {
702        // The wgpu resident Embryo graph owns recurrent/KV buffers keyed by
703        // this pipeline's sequence id.  Release that sequence image when a
704        // pooled pipeline is dropped; model weights stay cached for reuse.
705        crate::gpu::graph_kv_reset(self.graph_kv_id);
706    }
707}
708
709/// Model weights. Matrices are `QTensor` (owned f32 for small models
710/// and tests — bit-identical to the historical paths — or quantized
711/// bytes zero-copy from the CMF mmap for big models). 1-D norms are
712/// always small and stay f32.
713pub struct PipelineWeights {
714    /// Embedding table: [vocab_size, hidden_size]
715    pub embed_tokens: QTensor,
716    /// Per-layer weights
717    pub layers: Vec<LayerWeights>,
718    /// LM head: [vocab_size, hidden_size]
719    pub lm_head: QTensor,
720    /// Final norm: [hidden_size]
721    pub final_norm: Vec<f32>,
722}
723
724/// One transformer layer: shared norms + MLP, attention by kind.
725pub struct LayerWeights {
726    pub input_norm: Vec<f32>,
727    /// The pre-FFN norm (`post_attention_layernorm` classically;
728    /// `pre_feedforward_layernorm` on Gemma-2/3 sandwich layers).
729    pub post_norm: Vec<f32>,
730    /// Gemma-2/3 sandwich: norm applied to the ATTENTION OUTPUT before
731    /// its residual add (`post_attention_layernorm` there).
732    pub attn_out_norm: Option<Vec<f32>>,
733    /// Gemma-4: the whole layer output is multiplied by this scalar.
734    pub layer_scale: Option<f32>,
735    /// Gemma-2/3 sandwich: norm applied to the FFN OUTPUT before its
736    /// residual add (`post_feedforward_layernorm`).
737    pub ffn_out_norm: Option<Vec<f32>>,
738    pub ffn: FfnKind,
739    pub attn: AttnKind,
740}
741
742/// FFN gate activation: SiLU (SwiGLU family), tanh-GELU (Gemma's GeGLU),
743/// or a source-specific gated contract. A property of the model, carried on
744/// every FFN triple.
745#[derive(Clone, Copy, PartialEq, Debug, Default)]
746pub enum Act {
747    #[default]
748    Silu,
749    GeluTanh,
750    /// Exact erf GELU (HF `hidden_act = "gelu"`: Spark-X2.5).
751    Gelu,
752    /// Kimi-K3 SituAndMul: BOTH halves transform —
753    /// a = β·tanh(g/β)·σ(g), up' = linβ·tanh(u/linβ) (linβ>0), out = a·up'.
754    Situ {
755        beta: f32,
756        linear_beta: f32,
757    },
758    /// MiniMax M3's SwiGLU-OAI: upper-clamped gate, symmetrically clamped
759    /// up branch, `sigmoid(alpha * gate)`, and a `+1` up-branch offset.
760    /// It deliberately has no generic GPU graph arm until a matching kernel
761    /// exists; CPU uses the exact scalar reference in `inference`.
762    SwiGluOai {
763        alpha: f32,
764        limit: f32,
765    },
766    /// Ripple's clamped SwiGLU (`ModelArch::ffn_clamp`): the gate is cut from above and the up
767    /// branch on both sides at `limit`, then `silu(gate)·up`. The contract of the
768    /// `swiglu_limit` kernels.
769    SiluClamp {
770        limit: f32,
771    },
772}
773
774impl Act {
775    pub fn from_arch(name: &str) -> Self {
776        if name == "gelu_tanh" {
777            Self::GeluTanh
778        } else if name == "gelu" {
779            Self::Gelu
780        } else {
781            Self::Silu
782        }
783    }
784
785    /// Arch-driven constructor (activation name + situ betas).
786    pub fn from_arch_full(arch: &cortiq_core::ModelArch) -> Self {
787        match arch.hidden_act.as_str() {
788            "situ" => Self::Situ {
789                beta: arch.activation_situ_beta.unwrap_or(1.0) as f32,
790                linear_beta: arch.activation_situ_linear_beta.unwrap_or(0.0) as f32,
791            },
792            // `swigluoai` alone is deliberately not a generic activation
793            // alias.  Its alpha/limit are part of MiniMax M3's checked
794            // source contract, and accepting that string on an unrelated
795            // architecture would silently impose M3 math on its FFN.
796            "swigluoai" if arch.arch_name == "minimax_m3_vl" => Self::SwiGluOai {
797                alpha: 1.702,
798                limit: 7.0,
799            },
800            "silu" if arch.ffn_clamp.is_some_and(|l| l > 0.0) => Self::SiluClamp {
801                limit: arch.ffn_clamp.unwrap_or(0.0),
802            },
803            other => Self::from_arch(other),
804        }
805    }
806
807    /// The clamp of a dense FFN's pre-activations (0 = none).
808    #[inline]
809    pub fn clamp_limit(self) -> f32 {
810        match self {
811            Self::SiluClamp { limit } => limit,
812            _ => 0.0,
813        }
814    }
815
816    /// The wgpu graphs' dense FFN: an arm and the clamp its kernels take beside it. Only the
817    /// builders that hand the clamp on may ask; every other door reads `graph_act`, which has
818    /// no arm for a clamped SiLU.
819    pub(crate) fn dense_graph_contract(self) -> Option<(crate::gpu::GraphAct, f32)> {
820        match self {
821            Self::SiluClamp { limit } => Some((crate::gpu::GraphAct::Silu, limit)),
822            // The M3 arm carries its frozen clamp inside its code.
823            _ => self.wgpu_graph_act().map(|a| (a, 0.0)),
824        }
825    }
826
827    /// Construct the MiniMax M3 SwiGLU-OAI activation from a checked model
828    /// contract. This is intentionally explicit rather than recognizing an
829    /// arbitrary `hidden_act` string: callers must validate `alpha` and
830    /// `limit` against their source architecture before enabling it.
831    #[inline]
832    pub fn swiglu_oai(alpha: f32, limit: f32) -> Self {
833        Self::SwiGluOai { alpha, limit }
834    }
835
836    #[inline]
837    pub fn apply(self, x: f32) -> f32 {
838        match self {
839            Self::Silu => inference::silu(x),
840            Self::GeluTanh => inference::gelu_tanh(x),
841            Self::Gelu => inference::gelu_erf(x),
842            Self::Situ { beta, .. } => beta * (x / beta).tanh() * (1.0 / (1.0 + (-x).exp())),
843            Self::SwiGluOai { alpha, limit } => {
844                let gate = x.min(limit);
845                gate * (1.0 / (1.0 + (-alpha * gate).exp()))
846            }
847            Self::SiluClamp { limit } => inference::silu(x.min(limit)),
848        }
849    }
850
851    /// Gated combine — the FFN contract. Situ transforms the UP half
852    /// too, so callers must use this instead of apply(g)·u.
853    #[inline]
854    pub fn combine(self, g: f32, u: f32) -> f32 {
855        match self {
856            Self::Situ { linear_beta, .. } if linear_beta > 0.0 => {
857                self.apply(g) * (linear_beta * (u / linear_beta).tanh())
858            }
859            Self::SwiGluOai { alpha, limit } => {
860                inference::swiglu_oai(g, u, alpha, 1.0, Some(limit))
861            }
862            Self::SiluClamp { limit } => self.apply(g) * u.clamp(-limit, limit),
863            _ => self.apply(g) * u,
864        }
865    }
866
867    /// The wgpu graphs' arm for this activation; None = no device kernel
868    /// computes it, and the graph builder must refuse the layer (the dense
869    /// graph FFN once computed SiLU for whatever the model asked for).
870    pub fn graph_act(self) -> Option<crate::gpu::GraphAct> {
871        match self {
872            Self::Silu => Some(crate::gpu::GraphAct::Silu),
873            Self::Gelu => Some(crate::gpu::GraphAct::GeluErf),
874            Self::GeluTanh => Some(crate::gpu::GraphAct::GeluTanh),
875            Self::Situ { .. } | Self::SwiGluOai { .. } | Self::SiluClamp { .. } => None,
876        }
877    }
878
879    /// The WGPU graph arm.  Keep this deliberately separate from
880    /// `graph_act`: OAI needs its dedicated code rather than a generic SiLU
881    /// fallback.  Only the frozen MiniMax-M3 source constants get a device
882    /// code; a future OAI-like architecture with different constants must add
883    /// and test its own kernel contract.
884    pub(crate) fn wgpu_graph_act(self) -> Option<crate::gpu::GraphAct> {
885        // A clamped SiLU is an arm AND a limit: a door that reads the arm alone would run it
886        // unclamped, so it gets none here (`dense_graph_contract` hands both on).
887        if matches!(self, Self::SiluClamp { .. }) {
888            return None;
889        }
890        self.moe_job_graph_contract().map(|(act, _)| act)
891    }
892
893    /// The exact device contract for a gate/up/down MoE job.  OAI is not a
894    /// generic "clamped SiLU": code 3 commits a backend to MiniMax M3's
895    /// alpha, asymmetric up transform, and frozen clamp.  Keep the clamp
896    /// alongside the marker so a backend cannot accidentally run code 3 with
897    /// a nearby model's limit.
898    pub(crate) fn moe_job_graph_contract(self) -> Option<(crate::gpu::GraphAct, f32)> {
899        match self {
900            Self::SwiGluOai { alpha, limit }
901                if alpha.to_bits() == 1.702f32.to_bits()
902                    && limit.to_bits() == 7.0f32.to_bits() =>
903            {
904                Some((crate::gpu::GraphAct::SwiGluOaiM3, 7.0))
905            }
906            // The `swiglu_limit` kernels' own contract: gate from above, up on both sides.
907            Self::SiluClamp { limit } => Some((crate::gpu::GraphAct::Silu, limit)),
908            _ => self.graph_act().map(|act| (act, 0.0)),
909        }
910    }
911}
912
913/// Dense gated triple — the FFN of a dense layer or of one expert.
914pub struct DenseFfn {
915    pub gate_proj: QTensor,
916    pub up_proj: QTensor,
917    pub down_proj: QTensor,
918    /// Gate activation (SiLU default; Gemma: tanh-GELU).
919    pub act: Act,
920    /// `down_proj` stored transposed (`[inter, hidden]`), when the file
921    /// carries it. Only the per-token sparse path reads it: a neuron's
922    /// down weights are a contiguous ROW there, so the token's chosen
923    /// neurons are the only bytes touched. `None` = the ordinary layout,
924    /// and the sparse path stays off.
925    pub down_t: Option<QTensor>,
926    /// Task tubes (spec: defragged task-conditional width). The three
927    /// matrices above are the CORE — the neurons every task computes;
928    /// each tube is an independently quantized slice of the SAME layer
929    /// holding the neurons only some tasks need. A tube is a normal
930    /// tensor triple, so every kernel runs it unchanged, and the bytes
931    /// of an inactive tube are never read. Empty = ordinary dense FFN.
932    pub segs: Vec<FfnSeg>,
933}
934
935/// One task tube: a contiguous slice of a layer's FFN neurons, stored
936/// as its own `[w, hidden]` / `[hidden, w]` triple. `start` is the
937/// neuron's index in the layer's FULL space (core first, then tubes in
938/// order) — the bit a task mask sets to switch this tube on.
939pub struct FfnSeg {
940    pub gate: QTensor,
941    pub up: QTensor,
942    pub down: QTensor,
943    pub start: usize,
944    pub width: usize,
945}
946
947/// FFN operator of a layer, decided by tensor presence at load time
948/// (router `mlp.gate.weight` in the directory = MoE layer).
949pub enum FfnKind {
950    Dense(DenseFfn),
951    /// Mixture-of-Experts (Qwen2-MoE / Qwen3-MoE): softmax over ALL
952    /// expert logits → top-k, optional renorm; experts stay quantized
953    /// in mmap — only the selected ones are touched per token.
954    Moe(MoeFfn),
955    /// Gemma-4 MoE: a dense MLP branch AND a routed-expert branch in
956    /// the SAME layer, each with its own norm sandwich. The dense
957    /// branch reads the pre-FFN-normed input; the expert branch (and
958    /// the router) read the RAW residual through `pre_norm_2`:
959    ///   d = post_norm_1(dense(x̂));  m = post_norm_2(Σwₑ·FFNₑ(pre_norm_2(h)))
960    ///   ffn_out = d + m   (the caller's ffn_out_norm + residual follow)
961    DenseMoe(Box<DenseMoeFfn>),
962}
963
964/// Gemma-4 dual-branch FFN (see `FfnKind::DenseMoe`).
965pub struct DenseMoeFfn {
966    pub dense: DenseFfn,
967    pub moe: MoeFfn,
968    /// post_feedforward_layernorm_1 — dense-branch output norm.
969    pub post_norm_1: Vec<f32>,
970    /// pre_feedforward_layernorm_2 — expert-branch input norm (applied
971    /// to the RAW residual, not the pre-FFN-normed activation).
972    pub pre_norm_2: Vec<f32>,
973    /// post_feedforward_layernorm_2 — expert-branch output norm.
974    pub post_norm_2: Vec<f32>,
975}
976
977pub struct MoeFfn {
978    /// Router `mlp.gate.weight` [num_experts, hidden].
979    pub router: QTensor,
980    pub experts: Vec<DenseFfn>,
981    pub top_k: usize,
982    pub norm_topk_prob: bool,
983    /// Router scores per-expert with a sigmoid (LFM2-MoE / DeepSeek-V3
984    /// `noaux_tc`) instead of a softmax over all experts (Qwen).
985    pub router_sigmoid: bool,
986    /// Addend in the selected-score denominator of a sigmoid router.
987    /// Most supported checkpoints use the historical `1e-6` floor; Flint's
988    /// reference routing uses `1e-20`; MiniMax M3.1 preserves the same FP32
989    /// `sum + 1e-20` law. This is per-MoE rather than a global family switch
990    /// because the same sigmoid routing law has several contracts.
991    pub sigmoid_denom_eps: f32,
992    /// Per-expert selection bias `mlp.expert_bias` [num_experts]
993    /// (LFM2-MoE): added to the sigmoid scores for the top-k CHOICE only;
994    /// the gathered weights use the unbiased scores. None = no bias.
995    pub expert_bias: Option<Vec<f32>>,
996    /// Top-k weights are multiplied by this after the optional renorm
997    /// (LFM2-MoE `routed_scaling_factor`; 1.0 = off).
998    pub routed_scaling: f32,
999    /// Adaptive routing (CMF_MOE_TAU, opt-in): keep the smallest
1000    /// prefix of the top-k whose renormalized mass reaches τ —
1001    /// confident tokens touch 1–2 experts, flat ones keep all k.
1002    /// MoE decode is memory-bound, so skipped experts are skipped
1003    /// weight traffic. None = classic fixed top-k (bit-identical).
1004    pub route_tau: Option<f32>,
1005    /// Always-on shared expert. Qwen2-MoE carries an additional sigmoid
1006    /// gate; Laguna adds the shared expert unconditionally (`None`).
1007    pub shared: Option<(DenseFfn, Option<QTensor>)>,
1008    /// Expert-selection counters (truncated Fisher B-field of claim 12:
1009    /// routing frequency during calibration). Filled by every forward,
1010    /// read by the CLI via CMF_MOE_STATS. RefCell: decode is single-threaded.
1011    pub stats: std::cell::RefCell<Vec<u64>>,
1012    /// Per-CHANNEL sum of squares of this FFN's input, accumulated over a
1013    /// calibration run (`CMF_RMS_TRACE`). These are the RMS activation
1014    /// traces AWNP needs: raw weight magnitude says every channel matters
1015    /// equally, and the question AWNP asks is whether the ACTIVATIONS
1016    /// disagree. Off unless the env var is set — an f64 add per channel
1017    /// per token is cheap, but not free.
1018    pub act_sq: std::cell::RefCell<Vec<f64>>,
1019    /// Raw FFN-input rows captured for the layers named by `CMF_ACT_DUMP`
1020    /// (`"9,19"`). AWNP is nullspace PROJECTION: after dropping channels the
1021    /// survivors are refitted to absorb what was removed, and how much they
1022    /// can absorb depends on the activation COVARIANCE, not on per-channel
1023    /// RMS. Per-channel numbers can only bound the cost from above.
1024    pub act_rows: std::cell::RefCell<Vec<f32>>,
1025    /// Task mask over routed experts (DTG-MA over MoE, claim-12 B-field
1026    /// applied): `false` experts are excluded from selection, the
1027    /// softmax renormalizes over the allowed set. Built by the loader
1028    /// from CMF_MOE_MASK=<stats.json> + CMF_MOE_MASK_COVER. None = all.
1029    pub mask: Option<Vec<bool>>,
1030    /// Gemma-4: per-expert weight scale applied AFTER the top-k renorm
1031    /// (`router.per_expert_scale`). None = 1.0 everywhere.
1032    pub per_expert_scale: Option<Vec<f32>>,
1033    /// Gemma-4: the router reads a SCALE-LESS rms-norm of its input
1034    /// (the constant gain router.scale·√hidden is folded into the
1035    /// router weights at convert time).
1036    pub router_input_norm: bool,
1037    /// Cortiq Embryo: resonance routing (P1) — the "logits" are
1038    /// bias_e − ‖(x−μ_e) − U_eᵀU_e(x−μ_e)‖², argmax = the expert whose
1039    /// descriptor reconstructs the input best. `router` is a placeholder.
1040    pub resonance: Option<Resonance>,
1041    /// Growth records (`kind = "expert_append"`, spec §9.5.1) mounted
1042    /// behind the trunk experts, one entry per grown expert IN THE ORDER
1043    /// they sit in `experts` (the tail `experts[experts.len() - grown.len()..]`).
1044    /// The trunk keeps `experts.len() - grown.len()` experts. Empty on a
1045    /// gated MoE, on a file without records and under `CMF_GROWTH=off`.
1046    pub grown: Vec<GrownExpert>,
1047}
1048
1049/// One grown expert of an `expert_append` record as the loader mounted it.
1050#[derive(Debug, Clone, PartialEq, Eq)]
1051pub struct GrownExpert {
1052    /// The record's skill id.
1053    pub record: String,
1054    /// Position of the record in `header.skills`.
1055    pub record_index: usize,
1056    pub layer: usize,
1057    /// The index the tensor name declares (`experts.{e}` — the chain rule
1058    /// of the format); the executed position may be smaller when an
1059    /// earlier record of the layer is not mounted.
1060    pub expert: usize,
1061}
1062
1063/// Per-expert resonance descriptors of one MoE layer (`mlp.desc.*`).
1064pub struct Resonance {
1065    /// [E, hidden]
1066    pub mu: Vec<f32>,
1067    /// [E, k, hidden] orthonormal directions (k may be 0)
1068    pub u: Vec<f32>,
1069    pub k: usize,
1070    /// [E] selection bias (loss-free balancing, trained online)
1071    pub bias: Vec<f32>,
1072    /// [E] reconstruction-error shell: an expert whose error
1073    /// `‖(x−μ)⊥U‖² = d² − proj` exceeds its shell scores `−∞` (it never
1074    /// wins). `+inf` = no shell — every trunk expert; a grown expert
1075    /// (`expert_append`) carries the finite `desc.shell` its record stores.
1076    /// Empty = no shell anywhere (legacy constructors).
1077    pub shell: Vec<f32>,
1078}
1079
1080/// `CMF_GROWTH_SHELL` state: 0 = not yet read from the environment, 1 = on,
1081/// 2 = off. Process-wide, like the environment it mirrors.
1082static GROWTH_SHELL: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1083
1084/// Is the growth shell applied (`Resonance::scores` −∞ rule, the resident
1085/// graph's packed shell)? `CMF_GROWTH_SHELL=off` disables it for
1086/// measurement; [`set_growth_shell`] overrides the environment in-process
1087/// (`growth-eval --shell`). Default: on.
1088pub fn growth_shell_enabled() -> bool {
1089    use std::sync::atomic::Ordering;
1090    match GROWTH_SHELL.load(Ordering::Relaxed) {
1091        1 => true,
1092        2 => false,
1093        _ => {
1094            let off = std::env::var("CMF_GROWTH_SHELL")
1095                .map(|v| v.eq_ignore_ascii_case("off") || v == "0")
1096                .unwrap_or(false);
1097            GROWTH_SHELL.store(if off { 2 } else { 1 }, Ordering::Relaxed);
1098            !off
1099        }
1100    }
1101}
1102
1103/// Switch the growth shell on/off for this process (`None` = re-read
1104/// `CMF_GROWTH_SHELL` on the next query). A pipeline packed into the
1105/// resident graph BEFORE the switch keeps the shell it was packed with —
1106/// build a new pipeline after switching.
1107pub fn set_growth_shell(on: Option<bool>) {
1108    GROWTH_SHELL.store(
1109        match on {
1110            Some(true) => 1,
1111            Some(false) => 2,
1112            None => 0,
1113        },
1114        std::sync::atomic::Ordering::Relaxed,
1115    );
1116}
1117
1118impl Resonance {
1119    /// Does any expert carry a finite shell (a mounted growth record)?
1120    pub fn has_shell(&self) -> bool {
1121        self.shell.iter().any(|s| s.is_finite())
1122    }
1123
1124    /// The shell the runtime applies right now: the stored one, or all
1125    /// `+inf` when the shell is switched off (`CMF_GROWTH_SHELL=off`).
1126    pub fn effective_shell(&self, ne: usize) -> Vec<f32> {
1127        let mut out = vec![f32::INFINITY; ne];
1128        if growth_shell_enabled() {
1129            for (o, s) in out.iter_mut().zip(&self.shell) {
1130                *o = *s;
1131            }
1132        }
1133        out
1134    }
1135
1136    /// Routing scores for one input row (higher = better). A grown
1137    /// expert whose reconstruction error lies outside its shell gets
1138    /// `−∞` (unless the shell is switched off); trunk rows are the exact
1139    /// bit pattern they were before growth.
1140    pub fn scores(&self, x: &[f32], out: &mut [f32]) {
1141        let h = x.len();
1142        let ne = out.len();
1143        let shell_on = growth_shell_enabled() && !self.shell.is_empty();
1144        for e in 0..ne {
1145            let mu = &self.mu[e * h..(e + 1) * h];
1146            let mut d2 = 0.0f32;
1147            for j in 0..h {
1148                let d = x[j] - mu[j];
1149                d2 += d * d;
1150            }
1151            let mut proj = 0.0f32;
1152            for i in 0..self.k {
1153                let u = &self.u[(e * self.k + i) * h..(e * self.k + i + 1) * h];
1154                let mut p = 0.0f32;
1155                for j in 0..h {
1156                    p += (x[j] - mu[j]) * u[j];
1157                }
1158                proj += p * p;
1159            }
1160            let err = d2 - proj;
1161            out[e] = self.bias.get(e).copied().unwrap_or(0.0) - err;
1162            if shell_on && err > self.shell.get(e).copied().unwrap_or(f32::INFINITY) {
1163                out[e] = f32::NEG_INFINITY;
1164            }
1165        }
1166    }
1167}
1168
1169/// Attention operator of a layer. Extension point: new operators are
1170/// new variants here + a forward in their own module.
1171pub enum AttnKind {
1172    /// GQA softmax attention (+ optional Qwen3.5 qk-norm / output gate).
1173    Full {
1174        wq: QTensor,
1175        wk: QTensor,
1176        wv: QTensor,
1177        wo: QTensor,
1178        q_norm: Option<Vec<f32>>,
1179        k_norm: Option<Vec<f32>>,
1180        output_gate: bool,
1181        /// Laguna: a separate softplus projection applied to the attention
1182        /// output before O. The bool means one scalar per head (broadcast
1183        /// across head_dim); false means one scalar per element.
1184        softplus_gate: Option<(QTensor, bool)>,
1185        /// Qwen2-family projection biases (q, k, v).
1186        bias: Option<(Vec<f32>, Vec<f32>, Vec<f32>)>,
1187    },
1188    /// Canonical linear core (VMF phase attention).
1189    Linear(VmfPhaseWeights),
1190    /// Faithful vendor linear operator (Qwen3.5 GatedDeltaNet).
1191    LinearGdn(GdnWeights),
1192    /// LFM2 gated short-convolution mixer (no KV cache; conv ring state
1193    /// lives in the layer's `linear_state`).
1194    ShortConv(ShortConvWeights),
1195    /// DeepSeek-V2 Multi-head Latent Attention. v1 executes it as
1196    /// expand-to-MHA: the latent is projected per token, K/V expand to
1197    /// every head and live in the ordinary cache (K head layout
1198    /// [rope | nope] so the standard partial rotary covers the shared
1199    /// rope key; V rows are zero-padded to the K head_dim and the pad
1200    /// is sliced off before O). Latent-resident cache is a later
1201    /// optimization, not a semantic change.
1202    Mla(Box<MlaWeights>),
1203    /// Kimi Delta Attention (Kimi Linear / Kimi-K3): per-channel decayed
1204    /// delta rule, separate q/k/v short convs, sigmoid-gated output norm.
1205    /// State lives in the layer's `linear_state` (no KV cache).
1206    Kda(Box<crate::linear_core::KdaWeights>),
1207    /// Natively bounded softmax anchor `swa_sink_v1` (Embryo-O1): ring of
1208    /// the last W raw keys with relative RoPE + trained NoPE sinks, one
1209    /// softmax. State is the fixed-size ring in `LayerKvCache::bounded`;
1210    /// nothing is stored per position (see `crate::bounded`).
1211    Bounded(Box<crate::bounded::BoundedWeights>),
1212}
1213
1214/// DeepSeek-V2 MLA projections (see `AttnKind::Mla`).
1215pub struct MlaWeights {
1216    /// `[nh·(rope+nope), hidden]` (or `[…, q_lora]` when compressed) —
1217    /// the converter permutes each head rope-first so rotary_dim =
1218    /// qk_rope works unchanged.
1219    pub q_proj: QTensor,
1220    /// Compressed q (K3/V3 class): x → q_a `[q_lora, hidden]` →
1221    /// rms(q_a_norm) → q_proj (= q_b). None = direct q (V2-Lite).
1222    pub q_a: Option<QTensor>,
1223    pub q_a_norm: Option<Vec<f32>>,
1224    /// `kv_a_proj_with_mqa` `[lora + rope, hidden]` (latent first).
1225    pub kv_a: QTensor,
1226    /// RMS-norm weights over the latent (`kv_a_layernorm`, [lora]).
1227    pub kv_a_norm: Vec<f32>,
1228    /// `[nh·(nope+v), lora]` — per head [k_nope | v].
1229    pub kv_b: QTensor,
1230    /// `[hidden, nh·v]`.
1231    pub o_proj: QTensor,
1232    pub nh: usize,
1233    pub qk_rope: usize,
1234    pub qk_nope: usize,
1235    pub v_dim: usize,
1236    pub lora: usize,
1237    /// Softmax scale (1/√(rope+nope), YaRN-mscale-corrected at load).
1238    pub scale: f32,
1239    /// Kimi Linear NoPE: skip the rotary entirely (layout unchanged).
1240    pub nope: bool,
1241}
1242
1243/// Multi-token-prediction head (DeepSeek/Qwen style, spec §2.1):
1244/// `x = eh_proj·[enorm(embed(next)); hnorm(hidden)]` → one transformer
1245/// block over its own KV → shared lm_head. Drafts the token after next;
1246/// the main model verifies, so output is exact — MTP only buys speed.
1247pub struct MtpModule {
1248    pub enorm: Vec<f32>,
1249    pub hnorm: Vec<f32>,
1250    /// [hidden, 2·hidden]
1251    pub eh_proj: QTensor,
1252    pub layer: LayerWeights,
1253    pub final_norm: Vec<f32>,
1254    pub kv: crate::kv_cache::LayerKvCache,
1255}
1256
1257/// Teacher-forced activation statistics for one MTP draft FFN.
1258///
1259/// `mass[i]` is `Σ_rows |activation_i|`; `squared_mass[i]` is
1260/// `Σ_rows activation_i²`, where `activation = act(gate) · up` immediately
1261/// before the draft layer's down projection. `observed_positions` is the
1262/// number of teacher-forced rows that contributed to both arrays.
1263///
1264/// Rows of FFN input the canonical draft probe measures in one batch.
1265const MTP_PROBE_FFN_ROWS: usize = 128;
1266
1267/// [`Pipeline::probe_mtp_ffn`] returns one of these for each actual draft
1268/// layer.  It intentionally has a separate type/API from
1269/// [`Pipeline::probe_ffn_mass`] so a compactor cannot accidentally substitute
1270/// trunk statistics for an MTP sidecar whose FFN has a different width.
1271#[derive(Clone, Debug, PartialEq)]
1272pub struct MtpFfnProbe {
1273    pub mass: Vec<f64>,
1274    pub squared_mass: Vec<f64>,
1275    pub observed_positions: usize,
1276}
1277
1278/// A Metal verify graph after its sync: what the commit needs — the
1279/// graph (per-layer replay scratch), the GDN layers in encode order (their
1280/// CPU states receive the replay), and the attention layers with the CPU
1281/// row count they were encoded against (the accepted rows are pulled from
1282/// the mirror from there).
1283/// One item of the Metal rows-graph plan.
1284#[cfg(target_os = "macos")]
1285enum MetalRowsItem<'a> {
1286    Gdn {
1287        run: Vec<crate::gpu_metal::GdnGpuLayer<'a>>,
1288        first: usize,
1289    },
1290    Attn {
1291        l: crate::gpu_metal::AttnGpuLayer<'a>,
1292        li: usize,
1293        q_norm: Option<&'a [f32]>,
1294        k_norm: Option<&'a [f32]>,
1295        output_gate: bool,
1296        /// Spark-X2.6's per-head gate `[nh × hidden]`.
1297        head_gate: Option<&'a [f32]>,
1298    },
1299}
1300
1301#[cfg(target_os = "macos")]
1302struct MetalVerifyPending {
1303    graph: crate::gpu_metal::VerifyGraph,
1304    gdn_layers: Vec<usize>,
1305    attn_layers: Vec<(usize, usize)>,
1306}
1307
1308/// A round's batched MTP warm-up, submitted but not yet waited
1309/// (`mtp_warm_batch_submit` → `mtp_warm_batch_finish`): the trunk commit's
1310/// GDN replay is queued between the two.
1311#[cfg(target_os = "macos")]
1312struct MetalWarmPending {
1313    graph: crate::gpu_metal::VerifyGraph,
1314    cpu_stored: usize,
1315    b: usize,
1316}
1317
1318#[cfg(target_os = "macos")]
1319enum MetalRowsRun {
1320    /// Capability/preflight refusal before a command buffer was committed.
1321    Declined,
1322    /// A graph was admitted and then failed; callers must clear the sequence
1323    /// rather than replaying it through CPU/serial state.
1324    Failed,
1325    Completed(MetalVerifyPending),
1326}
1327
1328#[cfg(target_os = "macos")]
1329enum MetalPrefillOutcome {
1330    Declined,
1331    Failed,
1332    Completed(Vec<f32>),
1333}
1334
1335/// One teacher-forced position of [`Pipeline::score_ids_device`]: the
1336/// target's natural-log probability and whether it is the argmax (the
1337/// first maximum on ties, as torch's `argmax`).
1338#[derive(Debug, Clone, Copy, PartialEq)]
1339pub struct TokenScore {
1340    pub logprob: f64,
1341    pub greedy: bool,
1342}
1343
1344/// Rows a verify window of the device scorer carries: the CUDA hybrid
1345/// arm's small path (`NMAX`), the widest window it runs with a head.
1346pub const DEVICE_SCORE_ROWS: usize = 16;
1347
1348#[cfg(target_os = "macos")]
1349enum MetalBatchNllOutcome {
1350    Declined,
1351    Failed(String),
1352    Completed(f64, usize),
1353}
1354
1355/// The speculation trial's phases (see the decode loop): up to five timed
1356/// speculative rounds, eight timed plain tokens, then the faster arm until a
1357/// re-check. Two consecutive rounds with no accepted draft skip directly to
1358/// the plain measurement: another speculative round cannot pay when it emits
1359/// exactly the one token the plain loop would have produced.
1360#[derive(Clone, Copy)]
1361enum SpecTrial {
1362    Spec {
1363        t0: std::time::Instant,
1364        gen0: usize,
1365        rounds: usize,
1366    },
1367    Plain {
1368        t0: std::time::Instant,
1369        gen0: usize,
1370    },
1371    Decided {
1372        spec: bool,
1373        recheck_at: usize,
1374    },
1375}
1376
1377/// `CMF_GRAPH_SPEC_TIME`: 0 = off, 1 = one line per speculative round
1378/// plus the host stamps of any OUTLIER round (wall > 1.4× the running
1379/// median), 2 = the host stamps of every round.
1380pub(crate) fn spec_time_level() -> u8 {
1381    static L: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
1382    *L.get_or_init(|| match std::env::var("CMF_GRAPH_SPEC_TIME") {
1383        Ok(v) => v.trim().parse::<u8>().map(|n| n.max(1)).unwrap_or(1),
1384        Err(_) => 0,
1385    })
1386}
1387
1388/// `GraphMoeBank` reuse across tokens (`CMF_GRAPH_MOE_BANK=0` rebuilds
1389/// every layer's bank on every token, the route before the cache).
1390fn graph_moe_bank_on() -> bool {
1391    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1392    *ON.get_or_init(|| std::env::var("CMF_GRAPH_MOE_BANK").as_deref() != Ok("0"))
1393}
1394
1395/// Decide whether the batched speculative verifier is admitted by the
1396/// user/backend policy, before capability checks.  Native Metal's row-batch
1397/// verifier is deliberately fail-closed by default: it has produced a
1398/// different *emitted* greedy token than the serial path on a real model.
1399/// It remains available only through the documented explicit experiment
1400/// spelling, `CMF_GRAPH_SPEC=1`; other backends retain their historical
1401/// nonzero override behaviour.
1402fn graph_spec_wanted_by_policy(
1403    spec_env: Option<&str>,
1404    spec_default_ok: bool,
1405    penalized: bool,
1406    metal_wgpu: bool,
1407    native_metal: bool,
1408) -> bool {
1409    match spec_env {
1410        Some("0") => false,
1411        Some("1") => true,
1412        // Off native Metal any other value still forces the drafts on, as it
1413        // always did; on native Metal it means the default below.
1414        Some(_) if !native_metal => true,
1415        // Native Metal shares the default since the batched verify passed the
1416        // exact-ID gate over q4tp trunks (`spec_default_ok`): MacBook Air M4,
1417        // Qwen3.8-27B Turbo and OrcaCyber-Nano-1.0, five prompts each, the
1418        // same token ids with drafts and without, 1.45-2.3x the plain decode.
1419        _ => spec_default_ok && !penalized && !metal_wgpu,
1420    }
1421}
1422
1423/// The round's host stamps: `spec_stamp(name)` records the time since
1424/// the previous stamp (the section that just ended) — from anywhere on
1425/// the round's call chain (the Metal verify, the draft step, the commit),
1426/// no plumbing. Off (a single atomic load) unless `CMF_GRAPH_SPEC_TIME`
1427/// is set; one decode thread at a time is assumed (diagnostics).
1428struct SpecStampLog {
1429    t_last: std::time::Instant,
1430    items: Vec<(&'static str, f32)>,
1431}
1432
1433static SPEC_STAMPS: std::sync::Mutex<Option<SpecStampLog>> = std::sync::Mutex::new(None);
1434
1435pub(crate) fn spec_stamp(name: &'static str) {
1436    if spec_time_level() == 0 {
1437        return;
1438    }
1439    if let Ok(mut g) = SPEC_STAMPS.lock() {
1440        if let Some(log) = g.as_mut() {
1441            let now = std::time::Instant::now();
1442            log.items
1443                .push((name, (now - log.t_last).as_secs_f32() * 1e3));
1444            log.t_last = now;
1445        }
1446    }
1447}
1448
1449fn spec_stamps_begin() {
1450    if spec_time_level() == 0 {
1451        return;
1452    }
1453    if let Ok(mut g) = SPEC_STAMPS.lock() {
1454        *g = Some(SpecStampLog {
1455            t_last: std::time::Instant::now(),
1456            items: Vec::with_capacity(64),
1457        });
1458    }
1459}
1460
1461fn spec_stamps_take() -> Vec<(&'static str, f32)> {
1462    SPEC_STAMPS
1463        .lock()
1464        .ok()
1465        .and_then(|mut g| g.take())
1466        .map(|l| l.items)
1467        .unwrap_or_default()
1468}
1469
1470/// One line: every stamp name in first-seen order with its total over the
1471/// round and, when it fired more than once (the draft steps), the count.
1472fn spec_stamps_format(items: &[(&'static str, f32)]) -> String {
1473    let mut agg: Vec<(&'static str, f32, u32)> = Vec::with_capacity(items.len());
1474    for &(n, ms) in items {
1475        match agg.iter_mut().find(|e| e.0 == n) {
1476            Some(e) => {
1477                e.1 += ms;
1478                e.2 += 1;
1479            }
1480            None => agg.push((n, ms, 1)),
1481        }
1482    }
1483    let mut s = String::with_capacity(agg.len() * 16);
1484    for (n, ms, k) in agg {
1485        if k > 1 {
1486            s.push_str(&format!("{n} {ms:.1}/{k} "));
1487        } else {
1488            s.push_str(&format!("{n} {ms:.1} "));
1489        }
1490    }
1491    s
1492}
1493
1494/// The speculation monitor: exponential averages of a round's wall time
1495/// and of the tokens it produced, and the plain token's wall time — the
1496/// three numbers the keep/stop rule needs. A round pays when
1497/// `tokens_per_round · plain_ms > round_ms · 1.03`. The one-shot trial
1498/// (four rounds against eight tokens) mis-called prose: the first rounds
1499/// after a prompt are formulaic and accept well, the body does not (an
1500/// essay measured 39 against a plain 44.8 with the trial saying
1501/// "speculate"), so the rule now runs on EVERY round and stops after four
1502/// consecutive losing rounds; a stopped speculation is retried 128 tokens
1503/// later.
1504///
1505/// Native Metal (`metal: true`) does not pay the eight plain tokens up
1506/// front: on the 27B a plain token is ~150 ms, so the trial alone cost
1507/// ~1.2 s of every answer. There the plain phase is (a) skipped while the
1508/// rounds land at least `SPEC_PROXY_TOKENS` tokens each — a k=7 round on
1509/// Metal costs ~1.9 plain tokens (286 against 148 ms measured on the M4),
1510/// so 3.5 tokens/round cannot lose on any Metal round/plain ratio seen —
1511/// and (b) otherwise bounded to the fewest tokens that time it: two, or
1512/// as many as fit in `SPEC_PLAIN_MIN_MS` (a 150-ms token measures itself;
1513/// a 10-ms one needs the eight). The keep/stop rule itself is unchanged:
1514/// the moment a plain rate exists, it decides.
1515#[derive(Default, Clone, Copy)]
1516struct SpecMon {
1517    round_ms: f64,
1518    tokens: f64,
1519    plain_ms: f64,
1520    n: u32,
1521    fails: u32,
1522    /// Consecutive rounds that produced only their verifier-tip token (zero
1523    /// accepted MTP drafts). This is deliberately counted before the warm-up
1524    /// round is excluded from timing: `SPEC_ZERO_ROUNDS` real zero-acceptance
1525    /// rounds stop charging an obviously losing speculative arm.
1526    zero_accept_rounds: u8,
1527    metal: bool,
1528    /// The CUDA hybrid arm: a round costs about 1.25 plain tokens (a verify
1529    /// of five rows 1.1x a token, the drafts a tenth more), so rounds that
1530    /// land `SPEC_PROXY_TOKENS_CUDA` pay without timing plain tokens.
1531    cuda: bool,
1532}
1533
1534/// What a speculative round of k drafts costs on native Metal over a q4tp
1535/// trunk, in plain tokens. One and two drafts verify on the small-batch
1536/// matvec (`q4tp_matvec_b2` / `_b3`), three and more on the narrow GEMM at
1537/// one flat price. MacBook Air M4, Qwen3.8-27B: a plain token 160 ms, a
1538/// round of one draft 176, of two 204, of three 246, of seven 281.
1539const METAL_ROUND_COST: [f32; 7] = [1.10, 1.275, 1.54, 1.59, 1.65, 1.70, 1.76];
1540/// The same on the CUDA hybrid arm, verify and commit of a round of k
1541/// drafts: RTX 3090, Qwen3.8-27B q4tp, a plain token 20.4 ms, a round of
1542/// four chain drafts 24.3 ms past its drafts, of seven block drafts 25.1.
1543const CUDA_ROUND_COST: [f32; 7] = [1.12, 1.15, 1.17, 1.19, 1.21, 1.22, 1.24];
1544/// A DFlash block on the CUDA arm with its context rows and head (3.9 ms),
1545/// and a step of the MTP chain (0.62 ms), in plain tokens.
1546const CUDA_BLOCK_DRAFT: f32 = 0.19;
1547const CUDA_DRAFT_STEP: f32 = 0.03;
1548/// How often a draft holds once the one before it held, before any round has
1549/// shown it: the 27B's chain on code and on prose holds its first draft in
1550/// four rounds of five, the second in three of four after that, the third in
1551/// one of two.
1552const SPEC_HOLD_PRIOR: [f32; 7] = [0.80, 0.75, 0.50, 0.67, 0.65, 0.69, 0.67];
1553
1554/// The draft depth that lands the most tokens in a unit of time: a round of
1555/// k drafts gives its tip and every draft the chain held, for the cost of
1556/// that depth's verify.
1557fn metal_spec_depth(hold: &[f32; 7]) -> usize {
1558    metal_spec_plan(hold, 0.0).0
1559}
1560
1561/// `metal_spec_depth` for a drafter whose drafts cost `draft` plain tokens a
1562/// round whatever the depth (a DFlash block; an MTP chain's steps are small
1563/// change beside the verify and count as nothing): the depth, and the tokens
1564/// it lands in the time of a plain one.
1565fn metal_spec_plan(hold: &[f32; 7], draft: f32) -> (usize, f32) {
1566    spec_plan_at(&METAL_ROUND_COST, hold, draft, 0.0)
1567}
1568
1569/// `metal_spec_plan` over any device's price list: `cost[k - 1]` plain tokens
1570/// for a round of k drafts, `draft` a round and `step` a draft on top.
1571fn spec_plan_at(cost: &[f32; 7], hold: &[f32; 7], draft: f32, step: f32) -> (usize, f32) {
1572    let mut best = (1usize, 0f32);
1573    let (mut tokens, mut reach) = (1.0f32, 1.0f32);
1574    for k in 1..=7 {
1575        reach *= hold[k - 1];
1576        tokens += reach;
1577        let rate = tokens / (cost[k - 1] + draft + step * k as f32);
1578        // a longer chain has to win by more than the averages' noise
1579        if rate > best.1 * 1.04 {
1580            best = (k, rate);
1581        }
1582    }
1583    best
1584}
1585
1586/// The depth of the MTP chain's rounds on wgpu, from what a round costs on
1587/// this device: `wall[k - 1]` is the measured wall of a round of k drafts in
1588/// ms (0: not timed yet), and a depth between or past the timed ones is
1589/// priced on the line through the two nearest. A verify's price climbs with
1590/// its rows by a card's own slope (Qwen3.8-27B Turbo, a round of 3 / 4 / 5
1591/// drafts: RTX 2000 Ada 111 / 126 / 145 ms against a plain token's 75), so
1592/// the acceptance alone does not say where a deeper round stops paying.
1593/// `None` until two depths are timed: the acceptance rule moves the depth
1594/// until then. The depth in turn stays unless another lands 4 % more tokens
1595/// in a unit of time.
1596fn wgpu_spec_depth(hold: &[f32; 7], wall: &[f32; 7], k_now: usize, k_min: usize, k_max: usize) -> Option<usize> {
1597    let mut timed = (1..=7usize).filter(|&k| wall[k - 1] > 0.0);
1598    let (first, second) = (timed.next()?, timed.next()?);
1599    let price = |k: usize| -> f32 {
1600        if wall[k - 1] > 0.0 {
1601            return wall[k - 1];
1602        }
1603        // the two timed depths nearest to k
1604        let (mut a, mut b) = (first, second);
1605        for j in (1..=7usize).filter(|&j| wall[j - 1] > 0.0 && j != first && j != second) {
1606            let far = if a.abs_diff(k) >= b.abs_diff(k) { &mut a } else { &mut b };
1607            if j.abs_diff(k) < far.abs_diff(k) {
1608                *far = j;
1609            }
1610        }
1611        let (a, b) = (a.min(b), a.max(b));
1612        let slope = ((wall[b - 1] - wall[a - 1]) / (b - a) as f32).max(0.0);
1613        (wall[a - 1] + slope * (k as f32 - a as f32)).max(wall[a - 1] * 0.5)
1614    };
1615    let (k_min, k_max) = (k_min.clamp(1, 7), k_max.clamp(1, 7));
1616    let (mut tokens, mut reach) = (1.0f32, 1.0f32);
1617    let mut rate = [0f32; 7];
1618    for k in 1..=7 {
1619        reach *= hold[k - 1];
1620        tokens += reach;
1621        rate[k - 1] = tokens / price(k);
1622    }
1623    let k_now = k_now.clamp(k_min, k_max);
1624    let best = (k_min..=k_max).max_by(|&a, &b| rate[a - 1].total_cmp(&rate[b - 1]))?;
1625    Some(if rate[best - 1] > rate[k_now - 1] * 1.04 { best } else { k_now })
1626}
1627
1628/// A DFlash block with its head and selector on native Metal, in plain
1629/// tokens: one price a round, every draft of the block at once. MacBook Air
1630/// M4, the DFlash 2 drafter of Qwen3.8-27B as q4tp: 70 ms against a plain
1631/// token's 160.
1632const DFLASH_ROUND_DRAFT: f32 = 0.44;
1633/// How often a DFlash draft holds once the one before it held, before any
1634/// round has shown it: the 27B's drafter keeps 3.4 drafts of seven from every
1635/// start of mixed text.
1636const DFLASH_HOLD_PRIOR: [f32; 7] = [0.85, 0.82, 0.80, 0.80, 0.80, 0.80, 0.80];
1637/// Rounds the DFlash block sits out after a turn that the MTP chain took
1638/// back, and the most it ever sits out: a turn of fewer than `DFLASH_TURN`
1639/// rounds doubles the wait, a longer one starts it over. A turn that landed
1640/// more tokens over all its rounds than the chain was landing lost them to a
1641/// hard stretch (the block holds a whole round or none of it, so a few empty
1642/// rounds in a row say little): it sits out `DFLASH_WAIT_DIP` rounds only.
1643const DFLASH_WAIT: u32 = 48;
1644const DFLASH_WAIT_MOST: u32 = 768;
1645/// The router's margin of a round enters the running average with this
1646/// weight, and the drafter in turn keeps the rounds while the average is
1647/// inside this band (the margin is a difference of squared errors of unit
1648/// rows).
1649pub const DFLASH_LEAN_STEP: f32 = 0.5;
1650pub const DFLASH_LEAN_BAND: f32 = 0.0;
1651/// A stretch being copied from the context is the chain's whatever the router
1652/// says: this many of the last tokens repeating an earlier stretch (see
1653/// `tail_repeat`). Its short round and the lookup after it draft such text
1654/// for less than a block (edits and quotes: 8 keeps the code's rounds, where
1655/// three or four tokens repeat all the time).
1656pub const DFLASH_COPY_MIN: usize = 8;
1657/// The running gain of the chain's lookups (`spec_lookup_gain`) past which a
1658/// CUDA round stays the chain's: an edit of 512 tokens lost 15 % to the
1659/// block's rounds between its copies.
1660const DFLASH_LOOKUP_KEEPS: f32 = 5.0;
1661const DFLASH_WAIT_DIP: u32 = 8;
1662const DFLASH_TURN: u32 = 16;
1663
1664/// One logged start of a sequence, for `dflash_round_values`.
1665pub struct DflashStart<'a> {
1666    /// The committed stream through the round's first token.
1667    pub seq: &'a [u32],
1668    /// What the trunk went on to say after it (seven tokens or more).
1669    pub after: &'a [u32],
1670    /// The block's seven drafts there.
1671    pub block: &'a [u32],
1672    /// The chain's seven.
1673    pub chain: &'a [u32],
1674}
1675
1676/// For `cortiq dflash-route-fit`: what a round at each of a sequence's logged
1677/// starts lands and what it costs in plain tokens, `(tokens, cost)` under the
1678/// block and under the chain, each at the depth its own rule picks from the
1679/// starts before it, a prompt lookup going on after the drafts as it does in
1680/// a round (`METAL_ROUND_COST`, `DFLASH_ROUND_DRAFT`: the price of a round on
1681/// a MacBook Air M4).
1682pub fn dflash_round_values(starts: &[DflashStart<'_>]) -> Vec<((f32, f32), (f32, f32))> {
1683    dflash_round_values_at(starts, &METAL_ROUND_COST, DFLASH_ROUND_DRAFT, 0.0)
1684}
1685
1686/// `dflash_round_values` at another device's prices: `cost[k - 1]` plain
1687/// tokens for the verify and commit of a round of k drafts, `block_draft`
1688/// for a block, `chain_step` for each draft of the chain.
1689pub fn dflash_round_values_at(
1690    starts: &[DflashStart<'_>],
1691    cost: &[f32; 7],
1692    block_draft: f32,
1693    chain_step: f32,
1694) -> Vec<((f32, f32), (f32, f32))> {
1695    // a drafter's account of what holds, and what its lookups have paid
1696    struct Side {
1697        hold: [f32; 7],
1698        gain: f32,
1699        rest: u32,
1700        draft: f32,
1701        step: f32,
1702    }
1703    let mut seq: Vec<u32> = Vec::new();
1704    let mut round = |side: &mut Side, s: &DflashStart<'_>, own: &[u32]| -> (f32, f32) {
1705        let k = spec_plan_at(cost, &side.hold, side.draft, side.step).0.min(own.len()).max(1);
1706        let mut drafts = own[..k.min(own.len())].to_vec();
1707        if k < 7 && drafts.len() == k {
1708            if side.rest > 0 {
1709                side.rest -= 1;
1710            } else {
1711                seq.clear();
1712                seq.extend_from_slice(s.seq);
1713                seq.extend_from_slice(&drafts);
1714                let more = lookup_continuation(&seq, k + LOOKUP_MIN_REAL, 7 - k).to_vec();
1715                drafts.extend(more);
1716            }
1717        }
1718        let kept = drafts.iter().zip(s.after).take_while(|(d, t)| d == t).count();
1719        if drafts.len() > k {
1720            side.gain += 0.2 * (kept.saturating_sub(k) as f32 - side.gain);
1721            if side.gain < LOOKUP_PAYS {
1722                (side.rest, side.gain) = (24, 1.6);
1723            }
1724        }
1725        spec_hold_update(&mut side.hold, k, kept.min(k));
1726        ((1 + kept) as f32, cost[drafts.len().clamp(1, 7) - 1] + side.draft + side.step * k as f32)
1727    };
1728    let mut block = Side { hold: DFLASH_HOLD_PRIOR, gain: 2.0, rest: 0, draft: block_draft, step: 0.0 };
1729    let mut chain = Side { hold: SPEC_HOLD_PRIOR, gain: 2.0, rest: 0, draft: 0.0, step: chain_step };
1730    starts.iter().map(|s| (round(&mut block, s, s.block), round(&mut chain, s, s.chain))).collect()
1731}
1732
1733/// `CMF_DFLASH_ROWS=FILE`: every round of the DFlash block is written there
1734/// for `cortiq dflash-route-fit`, and the MTP chain drafts the same round
1735/// beside it, unverified. A record is 24 u32 and the target's row at the
1736/// tip (hidden f32), little-endian: the position of the round's first
1737/// token, that token, drafts verified, drafts accepted, the block's seven
1738/// drafts, the chain's seven, the lookup's count and its five after the
1739/// chain's first two (`u32::MAX` where there is none). `FILE.ids` holds the
1740/// stream through the first logged round's first token (u32).
1741fn dflash_rows_log() -> Option<&'static std::sync::Mutex<std::fs::File>> {
1742    static LOG: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> = std::sync::OnceLock::new();
1743    LOG.get_or_init(|| {
1744        let path = std::env::var("CMF_DFLASH_ROWS").ok()?;
1745        match std::fs::OpenOptions::new().create(true).append(true).open(&path) {
1746            Ok(f) => Some(std::sync::Mutex::new(f)),
1747            Err(e) => {
1748                tracing::warn!("CMF_DFLASH_ROWS: {path}: {e}");
1749                None
1750            }
1751        }
1752    })
1753    .as_ref()
1754}
1755
1756/// Rows of the trunk's tapped layers that may wait for the drafter
1757/// (`dflash_taps`): 100 KB a row on five layers of 5120.
1758const DFLASH_TAPS_ROWS: usize = 16384;
1759
1760/// `CMF_SPEC_SCRIPT=FILE`: token ids (the whole sequence, prompt first) that a
1761/// round of a trunk without a draft block takes its drafts from, in place of
1762/// a drafter. For tests of the verify and the rewind: with the plain greedy
1763/// sequence in the file every draft holds, and an id changed there is a
1764/// draft that does not.
1765#[cfg(feature = "gpu")]
1766fn solo_script() -> Option<&'static [u32]> {
1767    static IDS: std::sync::OnceLock<Option<Vec<u32>>> = std::sync::OnceLock::new();
1768    IDS.get_or_init(|| {
1769        let path = std::env::var("CMF_SPEC_SCRIPT").ok()?;
1770        match std::fs::read_to_string(&path) {
1771            Ok(s) => Some(s.split_whitespace().filter_map(|t| t.parse().ok()).collect()),
1772            Err(e) => {
1773                tracing::warn!("CMF_SPEC_SCRIPT: {path}: {e}");
1774                None
1775            }
1776        }
1777    })
1778    .as_deref()
1779}
1780
1781/// Little-endian bytes of f32 values (`Pipeline::dflash_dump`).
1782fn f32_bytes(v: &[f32]) -> Vec<u8> {
1783    v.iter().flat_map(|x| x.to_le_bytes()).collect()
1784}
1785
1786/// What a round of a trunk without a draft block leaves the decode loop
1787/// (`Pipeline::solo_spec_round`): the drafts that held, the trunk's row and
1788/// logits after the last of them.
1789#[cfg(feature = "gpu")]
1790struct SoloRound {
1791    accepted: Vec<u32>,
1792    drafted: usize,
1793    hidden: Vec<f32>,
1794    logits: Vec<f32>,
1795}
1796
1797/// The decode loop's account of those rounds: how deep the next one drafts,
1798/// and whether rounds land tokens faster than plain steps do.
1799#[cfg(feature = "gpu")]
1800struct SoloSpec {
1801    k: usize,
1802    /// Plain tokens to go before the next round, and the wait a losing
1803    /// stretch of rounds gets next time.
1804    rest: u32,
1805    back: u32,
1806    /// A plain token's time and a round's time per token it lands, ms
1807    /// (the first plain token of a sequence pays the warm-up: not a sample).
1808    plain_ms: f32,
1809    plain_n: u32,
1810    round_ms: f32,
1811    rounds: u32,
1812    /// The judging window: the rounds' summed wall and summed tokens (a
1813    /// ratio of sums — a mean of per-round ratios misrates a drafter).
1814    win_ms: f32,
1815    win_tok: u32,
1816    /// The step in flight: its start, and the tokens it lands (0: a plain one).
1817    last: Option<(std::time::Instant, usize)>,
1818    /// The sequence's first round is still to come: it pays the drafter's
1819    /// read of the prompt (and, on a device block, the kernels' warm-up),
1820    /// so like the first plain token it is not a sample. Before this the
1821    /// 700 ms of that round sat in the EWMA for a dozen rounds and sent a
1822    /// drafter that was winning 40 against 30 tok/s on code to rest.
1823    first: bool,
1824}
1825
1826/// The deepest round of a trunk without a draft block (the tip and seven
1827/// drafts: the batch graph's narrow kernels take eight rows, and a ninth
1828/// row costs a plane-wide GEMM a layer — 660 ms a verify against 120 on
1829/// the A40), the rounds a stretch is judged over, and the waits of a
1830/// stretch that lost.
1831#[cfg(feature = "gpu")]
1832const SOLO_K_MOST: usize = 7;
1833/// The deepest round the pay-off monitor picks on its own. The verify's
1834/// int8 batch kernels grow with the rows (eight rows 108 ms, five 70 on
1835/// Ripple-65B / RTX PRO 6000), so seven drafts at 80 % kept gave 36 tok/s
1836/// where four gave 47; `CMF_GRAPH_SPEC_K` still pins any depth to 7.
1837#[cfg(feature = "gpu")]
1838const SOLO_K_AUTO: usize = 5;
1839#[cfg(feature = "gpu")]
1840const SOLO_TRIAL: u32 = 6;
1841/// The rounds a judging window holds before its first verdict.
1842#[cfg(feature = "gpu")]
1843const SOLO_JUDGE: u32 = 3;
1844#[cfg(feature = "gpu")]
1845const SOLO_REST: u32 = 32;
1846#[cfg(feature = "gpu")]
1847const SOLO_REST_MOST: u32 = 512;
1848
1849/// Which drafter takes rounds when a DFlash sidecar sits beside the model's
1850/// own MTP block: `CMF_DFLASH_PICK=dflash` / `mtp` pins one, anything else
1851/// leaves it to what each of them holds.
1852fn dflash_pick() -> Option<bool> {
1853    static PICK: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
1854    *PICK.get_or_init(|| match std::env::var("CMF_DFLASH_PICK").as_deref() {
1855        Ok("dflash") => Some(true),
1856        Ok("mtp") => Some(false),
1857        _ => None,
1858    })
1859}
1860
1861/// A round of `k` drafts held its first `accepted`: move every depth the
1862/// round put to the test. Depths past `k` keep their last value, except
1863/// while the deepest one shown holds in nine rounds of ten: text that
1864/// predictable is worth a longer chain now and then, so they drift towards
1865/// it until a deeper round measures them.
1866fn spec_hold_update(hold: &mut [f32; 7], k: usize, accepted: usize) {
1867    let k = k.clamp(1, 7);
1868    for j in 1..=k {
1869        if accepted + 1 >= j {
1870            let hit = if accepted >= j { 1.0 } else { 0.0 };
1871            hold[j - 1] += 0.1 * (hit - hold[j - 1]);
1872        }
1873    }
1874    if k < 7 && hold[k - 1] >= 0.9 {
1875        for j in k + 1..=7 {
1876            hold[j - 1] += 0.005 * (hold[k - 1] - hold[j - 1]);
1877        }
1878    }
1879}
1880
1881/// Real tokens before the head's drafts that have to repeat with them for a
1882/// lookup to continue the chain.
1883const LOOKUP_MIN_REAL: usize = 3;
1884/// Drafts a lookup has to add to a round on average to pay for the wider
1885/// verify (a round of two drafts against one of seven on the M4: 204 and
1886/// 281 ms).
1887const LOOKUP_PAYS: f32 = 1.0;
1888
1889/// Prompt lookup: where the tail of `seq`, its last `min_len` tokens or
1890/// more, repeats an earlier stretch, the tokens that followed that stretch
1891/// there, at most `want` of them. The longest repeat wins, the latest of
1892/// equal ones.
1893fn lookup_continuation(seq: &[u32], min_len: usize, want: usize) -> &[u32] {
1894    const CAP: usize = 32;
1895    let n = seq.len();
1896    if want == 0 || min_len == 0 || n <= min_len {
1897        return &[];
1898    }
1899    let last = seq[n - 1];
1900    let mut best = (0usize, 0usize);
1901    for p in (0..n - 1).rev() {
1902        if seq[p] != last {
1903            continue;
1904        }
1905        let mut l = 1;
1906        while l < CAP && l <= p && seq[p - l] == seq[n - 1 - l] {
1907            l += 1;
1908        }
1909        if l > best.0 {
1910            best = (l, p);
1911            if l == CAP {
1912                break;
1913            }
1914        }
1915    }
1916    if best.0 < min_len {
1917        return &[];
1918    }
1919    let from = best.1 + 1;
1920    &seq[from..(from + want).min(n)]
1921}
1922
1923/// How many of the last tokens of `seq` repeat an earlier stretch of it (the
1924/// longest such repeat, 32 at most): text that is being copied from the
1925/// context. A lookup drafts such a stretch for nothing after the chain's
1926/// short round, so a round there is not worth a DFlash block.
1927pub fn tail_repeat(seq: &[u32]) -> usize {
1928    const CAP: usize = 32;
1929    let n = seq.len();
1930    if n < 2 {
1931        return 0;
1932    }
1933    let last = seq[n - 1];
1934    let mut best = 0usize;
1935    for p in (0..n - 1).rev() {
1936        if seq[p] != last {
1937            continue;
1938        }
1939        let mut l = 1;
1940        while l < CAP && l <= p && seq[p - l] == seq[n - 1 - l] {
1941            l += 1;
1942        }
1943        if l > best {
1944            best = l;
1945            if l == CAP {
1946                break;
1947            }
1948        }
1949    }
1950    best
1951}
1952
1953/// Zero-acceptance rounds in a row that end a speculation trial early. Two
1954/// was too few: a good head meets two empty rounds in a row now and then
1955/// (OrcaCyber-Nano-1.0 on an RTX 2000 Ada, 95 pinned rounds of code and a
1956/// review: four such pairs, no triple), and at the start of a chat turn a
1957/// pair sent the whole 200-token turn to plain decode, 13.4 tok/s against
1958/// 25.9 with the drafts. A head that never holds costs one more round.
1959const SPEC_ZERO_ROUNDS: u8 = 3;
1960/// Tokens a plain decision taken on thin evidence (fewer than five timed
1961/// rounds) stands before the rounds are tried again; one taken on a full
1962/// trial stands for `SPEC_RECHECK_PLAIN`.
1963const SPEC_RECHECK_THIN: usize = 32;
1964const SPEC_RECHECK_PLAIN: usize = 128;
1965
1966/// Tokens per round at or above which a Metal round pays without a plain
1967/// measurement (see `SpecMon`).
1968const SPEC_PROXY_TOKENS: f64 = 3.5;
1969/// The CUDA hybrid arm's proxy (see `SpecMon::cuda`): RTX 3090, Qwen3.8-27B,
1970/// a round 24.5-26.8 ms against a plain token's 20.4.
1971const SPEC_PROXY_TOKENS_CUDA: f64 = 2.0;
1972/// The Metal plain phase: at least two tokens, and more until this much
1973/// wall time has been timed (up to the eight the other backends time).
1974const SPEC_PLAIN_MIN_MS: f64 = 200.0;
1975
1976impl SpecMon {
1977    fn round(&mut self, dt_ms: f64, produced: usize) {
1978        if produced <= 1 {
1979            self.zero_accept_rounds = self.zero_accept_rounds.saturating_add(1);
1980        } else {
1981            self.zero_accept_rounds = 0;
1982        }
1983        self.n += 1;
1984        if self.n == 1 {
1985            return; // round 1 pays the batch scratch and the draft mirror
1986        }
1987        let a = if self.n == 2 { 1.0 } else { 0.3 };
1988        self.round_ms += a * (dt_ms - self.round_ms);
1989        self.tokens += a * (produced as f64 - self.tokens);
1990    }
1991    fn pays(&self) -> bool {
1992        if self.plain_ms > 0.0 {
1993            self.tokens * self.plain_ms > self.round_ms * 1.03
1994        } else {
1995            (self.metal && self.tokens >= SPEC_PROXY_TOKENS) || (self.cuda && self.tokens >= SPEC_PROXY_TOKENS_CUDA)
1996        }
1997    }
1998    fn repeated_zero_acceptance(&self) -> bool {
1999        self.zero_accept_rounds >= SPEC_ZERO_ROUNDS
2000    }
2001    /// When a plain decision is tried again: soon if the rounds behind it
2002    /// were few (round 1 is not timed, so `n` counts one more).
2003    fn recheck_plain_at(&self, generated: usize) -> usize {
2004        generated + if self.n < 6 { SPEC_RECHECK_THIN } else { SPEC_RECHECK_PLAIN }
2005    }
2006    /// Has the plain phase timed enough tokens to decide?
2007    fn plain_done(&self, t0: std::time::Instant, gen0: usize, generated: usize) -> bool {
2008        let n = generated.saturating_sub(gen0);
2009        if n >= 8 {
2010            return true;
2011        }
2012        self.metal && n >= 2 && t0.elapsed().as_secs_f64() * 1e3 >= SPEC_PLAIN_MIN_MS
2013    }
2014}
2015
2016/// Ids of the consumed prefix the bounded reuse key remembers literally
2017/// (the rest is covered by the rolling hash).
2018pub const KV_PREFIX_TAIL: usize = 128;
2019
2020/// Bounded prefix-reuse key: how many ids the cache holds, a rolling
2021/// hash of ALL of them and the last [`KV_PREFIX_TAIL`] ids literally.
2022/// Answers "does this prompt strictly extend what is cached" exactly
2023/// (hash over the whole consumed prefix + literal tail) without keeping
2024/// the dialogue — the record is a fixed size whatever the session length.
2025#[derive(Debug, Clone, Default)]
2026pub struct KvPrefix {
2027    len: usize,
2028    hash: u64,
2029    tail: Vec<u32>,
2030    /// Owner of the state this key describes: the resident device graph
2031    /// (true) or the host. A turn continues the prefix only on its owner
2032    /// (R4: a host continuation of a device sequence reads an empty host
2033    /// state; a device continuation of a host sequence has no image).
2034    device: bool,
2035}
2036
2037impl KvPrefix {
2038    #[inline]
2039    fn fold(mut h: u64, ids: &[u32]) -> u64 {
2040        for &id in ids {
2041            h ^= id as u64;
2042            h = h.wrapping_mul(0x100000001b3);
2043            h ^= h >> 29;
2044        }
2045        h
2046    }
2047
2048    pub fn clear(&mut self) {
2049        self.len = 0;
2050        self.hash = 0xcbf29ce484222325;
2051        self.tail.clear();
2052        self.device = false;
2053    }
2054
2055    /// Was the prefix built on the resident device graph?
2056    pub fn on_device(&self) -> bool {
2057        self.device
2058    }
2059
2060    /// Tag the owner of the recorded prefix.
2061    pub fn set_on_device(&mut self, device: bool) {
2062        self.device = device;
2063    }
2064
2065    /// Ids the cache holds (the forwarded prefix).
2066    pub fn len(&self) -> usize {
2067        self.len
2068    }
2069
2070    pub fn is_empty(&self) -> bool {
2071        self.len == 0
2072    }
2073
2074    /// Literal tail currently kept (≤ `KV_PREFIX_TAIL`).
2075    pub fn tail_len(&self) -> usize {
2076        self.tail.len()
2077    }
2078
2079    /// Replace the key with `ids` (a fresh sequence).
2080    pub fn set(&mut self, ids: &[u32]) {
2081        self.clear();
2082        self.extend(ids);
2083    }
2084
2085    /// Append `more` to the consumed prefix (an extension-only turn).
2086    pub fn extend(&mut self, more: &[u32]) {
2087        if self.len == 0 && self.hash == 0 {
2088            self.hash = 0xcbf29ce484222325;
2089        }
2090        self.hash = Self::fold(self.hash, more);
2091        self.len += more.len();
2092        if more.len() >= KV_PREFIX_TAIL {
2093            self.tail.clear();
2094            self.tail
2095                .extend_from_slice(&more[more.len() - KV_PREFIX_TAIL..]);
2096        } else {
2097            let drop = (self.tail.len() + more.len()).saturating_sub(KV_PREFIX_TAIL);
2098            self.tail.drain(..drop);
2099            self.tail.extend_from_slice(more);
2100        }
2101    }
2102
2103    /// Cached positions when `ids` strictly extends the consumed prefix,
2104    /// 0 otherwise. The tail is compared literally first (cheap), then
2105    /// the hash over the whole prefix must agree.
2106    pub fn extension(&self, ids: &[u32]) -> usize {
2107        if self.len == 0 || ids.len() <= self.len {
2108            return 0;
2109        }
2110        let t = self.tail.len();
2111        if ids[self.len - t..self.len] != self.tail[..] {
2112            return 0;
2113        }
2114        if Self::fold(0xcbf29ce484222325, &ids[..self.len]) != self.hash {
2115            return 0;
2116        }
2117        self.len
2118    }
2119}
2120
2121/// Result of a generation call.
2122pub struct GenerateResult {
2123    pub text: String,
2124    pub token_ids: Vec<u32>,
2125    pub prompt_tokens: usize,
2126    pub tokens_generated: usize,
2127    pub finish_reason: String,
2128    /// Speculative-decode stats (0/0 when MTP is absent or inactive).
2129    pub mtp_drafted: usize,
2130    pub mtp_accepted: usize,
2131    /// Per-generated-token confidence = softmax probability of the token
2132    /// that was actually emitted (softmax probability on the chosen state). High =
2133    /// the model was sure; low = it was guessing. Same length as the
2134    /// generated slice of `token_ids`.
2135    pub token_confidence: Vec<f32>,
2136    /// Structured per-token telemetry (B4 channel). Empty unless
2137    /// `set_trace(true)`; otherwise same length as the generated slice.
2138    pub traces: Vec<TokenTrace>,
2139}
2140
2141/// One row of the structured telemetry trace (B4): the model's internal
2142/// routing state at the moment a token was emitted. Every field is a
2143/// quantity the runtime already computes — nothing is inferred or
2144/// estimated (anti-principle: only measured bytes).
2145#[derive(Clone, Debug)]
2146pub struct TokenTrace {
2147    /// 0-based index within the generated slice.
2148    pub t: usize,
2149    /// The emitted token id.
2150    pub token_id: u32,
2151    /// Softmax probability on the emitted token — how sure the model was.
2152    pub confidence: f32,
2153    /// Skill in force while this token was generated (None = backbone).
2154    pub active_skill: Option<String>,
2155    /// Recon error E = ‖r−BBᵀr‖²/‖φ‖² at the last routing eval — coherence
2156    /// with the active skill's subspace (low = coherent). None = no router
2157    /// or not yet evaluated.
2158    pub recon: Option<f32>,
2159    /// The router changed the active skill right after this token (a
2160    /// domain boundary crossed under the hysteresis barrier).
2161    pub switched: bool,
2162}
2163
2164/// Calibrated softmax probability of `id` under `logits` (the confidence on
2165/// the emitted token) — the confidence signal, cheap from logits already
2166/// computed for sampling. `temp` is the calibration temperature (B1):
2167/// softmax(logits / temp); 1.0 = raw.
2168#[cfg_attr(not(test), allow(dead_code))]
2169fn top1_prob_t(logits: &[f32], id: u32, temp: f32) -> f32 {
2170    let t = if temp > 1e-3 { temp } else { 1.0 };
2171    let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
2172    let sum: f32 = logits.iter().map(|&v| ((v - max) / t).exp()).sum();
2173    if sum > 0.0 {
2174        (((logits[id as usize] - max) / t).exp()) / sum
2175    } else {
2176        0.0
2177    }
2178}
2179
2180/// prefill-GEMM enabled? (CMF_PREFILL=seq — emergency fallback to the
2181/// sequential path.)
2182fn prefill_batched() -> bool {
2183    std::env::var("CMF_PREFILL")
2184        .map(|v| v != "seq")
2185        .unwrap_or(true)
2186}
2187
2188/// Decide the graph NLL route without conflating graph quality with the
2189/// optional native-Metal fused head. A hidden-state graph remains a valid
2190/// quality route on Vulkan/Wgpu; only native Metal requires graph logits.
2191#[inline]
2192/// ‖a − b‖ / ‖b‖ (infinite when the lengths differ).
2193fn rel_l2(a: &[f32], b: &[f32]) -> f64 {
2194    if a.len() != b.len() {
2195        return f64::INFINITY;
2196    }
2197    let (mut d, mut r) = (0f64, 0f64);
2198    for (&x, &y) in a.iter().zip(b) {
2199        let e = (x - y) as f64;
2200        d += e * e;
2201        r += y as f64 * y as f64;
2202    }
2203    (d / r.max(1e-30)).sqrt()
2204}
2205
2206fn nll_graph_policy(unmasked: bool, prefer_graph: bool, native_metal: bool) -> (bool, bool) {
2207    let graph_quality = unmasked && prefer_graph;
2208    let fused_head_quality = graph_quality && native_metal;
2209    (graph_quality, fused_head_quality)
2210}
2211
2212/// Input to the layer-major batched span walk: token ids (embeds itself,
2213/// full-stack and coordinator prefill) or ready boundary hiddens (the
2214/// network worker's side of a split).
2215#[derive(Clone, Copy)]
2216enum PrefillIn<'a> {
2217    Ids(&'a [u32]),
2218    Hidden(&'a [f32]),
2219}
2220
2221/// The batched prefill walks `weights.layers`. Architectures that load
2222/// their own stack (gemma-3n's AltUp replicas, DeepSeek-V4's hyper-
2223/// connections) leave that empty and must go position by position — asking
2224/// otherwise indexes an empty vector, which is a panic rather than a
2225/// fallback. Every call site goes through here so the next such
2226/// architecture is one line, not four.
2227/// What a turbo file's header asks for.
2228#[derive(Clone)]
2229pub(crate) struct O1Turbo {
2230    pub(crate) cfg: crate::nystrom::O1Cfg,
2231    /// A prompt this long goes over to the far field; a shorter one stays exact.
2232    pub(crate) seal: usize,
2233    pub(crate) exact: crate::dory::ExactRows,
2234}
2235
2236/// Rows of a prompt read exactly on the card before the first seal, at most. Past them
2237/// the rows leave the card as they are read.
2238const O1_PREFIX_MAX: usize = 8192;
2239
2240/// Where a turbo file seals on this card. Exact rows take about 190 KB each on Qwen3.8-27B,
2241/// and the state, the scratch and the draft head about 1.8 GB beside the weights: a 16 GB card
2242/// has no room for 8192 rows, and gives up a little prompt speed to keep the ceiling.
2243/// `CMF_O1_PREFIX_MAX` chooses by hand.
2244pub(crate) fn o1_seal_for_card(seal: usize, weight_bytes: u64) -> usize {
2245    o1_seal_for_card_rows(seal, weight_bytes, 190 << 10)
2246}
2247
2248/// `o1_seal_for_card` for rows of `row_bytes` on the card (Dory's full layers: 54 KB).
2249pub(crate) fn o1_seal_for_card_rows(seal: usize, weight_bytes: u64, row_bytes: u64) -> usize {
2250    if let Some(s) = std::env::var("CMF_O1_PREFIX_MAX").ok().and_then(|v| v.parse().ok()) {
2251        return s;
2252    }
2253    let mut budget = crate::gpu::vram_budget();
2254    // Unified memory: what the system lets the GPU keep, and a row there lives twice, in the
2255    // host's cache and in the mirror.
2256    let mut row = row_bytes.max(1);
2257    #[cfg(target_os = "macos")]
2258    if budget == u64::MAX {
2259        budget = crate::gpu_metal::working_set_bytes();
2260        row *= 2;
2261    }
2262    if budget == 0 || budget == u64::MAX {
2263        return seal;
2264    }
2265    let room = budget.saturating_sub(weight_bytes + (1800 << 20));
2266    seal.min(((room / row) as usize).max(O1_PREFIX_MAX / 2))
2267}
2268
2269/// Rows of an archive as they come in: in RAM, or in a file (`CMF_O1_SPILL=DIR`) when
2270/// RAM is short and a disk is not.
2271pub(crate) enum ArchStore {
2272    Ram(Vec<f32>),
2273    Disk { path: std::path::PathBuf, file: std::io::BufWriter<std::fs::File> },
2274}
2275
2276impl ArchStore {
2277    pub(crate) fn new(dir: Option<&std::path::Path>, name: String) -> Result<Self, String> {
2278        let Some(dir) = dir else { return Ok(Self::Ram(Vec::new())) };
2279        std::fs::create_dir_all(dir).map_err(|e| format!("O(1) spill {}: {e}", dir.display()))?;
2280        let path = dir.join(format!("cortiq-o1-{}-{name}.rows", std::process::id()));
2281        let file = std::fs::File::create(&path).map_err(|e| format!("O(1) spill {}: {e}", path.display()))?;
2282        Ok(Self::Disk { path, file: std::io::BufWriter::with_capacity(1 << 22, file) })
2283    }
2284
2285    pub(crate) fn push(&mut self, rows: &[f32]) -> Result<(), String> {
2286        match self {
2287            Self::Ram(v) => {
2288                v.extend_from_slice(rows);
2289                Ok(())
2290            }
2291            Self::Disk { path, file } => {
2292                use std::io::Write;
2293                // SAFETY: an `f32` slice is valid as bytes of four times its length.
2294                let bytes = unsafe { std::slice::from_raw_parts(rows.as_ptr().cast::<u8>(), rows.len() * 4) };
2295                file.write_all(bytes).map_err(|e| format!("O(1) spill {}: {e}", path.display()))
2296            }
2297        }
2298    }
2299
2300    pub(crate) fn freeze(mut self) -> Result<ArchRows, String> {
2301        match self {
2302            Self::Ram(ref mut v) => Ok(ArchRows::Ram(std::mem::take(v))),
2303            Self::Disk { ref mut path, ref mut file } => {
2304                use std::io::Write;
2305                file.flush().map_err(|e| format!("O(1) spill {}: {e}", path.display()))?;
2306                let f = std::fs::File::open(&*path).map_err(|e| format!("O(1) spill {}: {e}", path.display()))?;
2307                // SAFETY: the file is this process's own and no one writes it any more.
2308                let map = unsafe { memmap2::Mmap::map(&f) }.map_err(|e| format!("O(1) spill {}: {e}", path.display()))?;
2309                Ok(ArchRows::Disk { map: Some(map), path: std::mem::take(path) })
2310            }
2311        }
2312    }
2313}
2314
2315impl Drop for ArchStore {
2316    fn drop(&mut self) {
2317        if let Self::Disk { path, .. } = self {
2318            // A store that was frozen hands its file over; the file is gone only here if not.
2319            if !path.as_os_str().is_empty() {
2320                let _ = std::fs::remove_file(&*path);
2321            }
2322        }
2323    }
2324}
2325
2326pub(crate) enum ArchRows {
2327    Ram(Vec<f32>),
2328    Disk { map: Option<memmap2::Mmap>, path: std::path::PathBuf },
2329}
2330
2331impl ArchRows {
2332    pub(crate) fn as_slice(&self) -> &[f32] {
2333        match self {
2334            Self::Ram(v) => v,
2335            Self::Disk { map, .. } => {
2336                let b = map.as_ref().map_or(&[][..], |m| &m[..]);
2337                // SAFETY: a page-aligned map of what `push` wrote, whole `f32`s.
2338                unsafe { std::slice::from_raw_parts(b.as_ptr().cast::<f32>(), b.len() / 4) }
2339            }
2340        }
2341    }
2342}
2343
2344impl Drop for ArchRows {
2345    fn drop(&mut self) {
2346        if let Self::Disk { map, path } = self {
2347            *map = None;
2348            let _ = std::fs::remove_file(&*path);
2349        }
2350    }
2351}
2352
2353/// The rows of a prompt past its first seal, off the card until the far field is built
2354/// anew over all of them.
2355struct O1Archive {
2356    dir: Option<std::path::PathBuf>,
2357    layers: Vec<O1ArchLayer>,
2358    rows: usize,
2359    stride: usize,
2360    nh: usize,
2361    nk: usize,
2362    hd: usize,
2363}
2364
2365impl O1Archive {
2366    fn new() -> Self {
2367        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 }
2368    }
2369}
2370
2371struct O1ArchLayer {
2372    li: usize,
2373    k: ArchStore,
2374    v: ArchStore,
2375    q: ArchStore,
2376}
2377
2378impl Pipeline {
2379    pub(crate) fn can_prefill_batched(&self) -> bool {
2380        #[cfg(test)]
2381        let force_serial = self.nll_test_force_serial;
2382        #[cfg(not(test))]
2383        let force_serial = false;
2384        prefill_batched() && !force_serial && !self.weights.layers.is_empty()
2385    }
2386
2387    /// The backend's automatic capacity split for a mapped transformer.
2388    /// Kept as a method so prefill and decode use the exact same boundary.
2389    fn automatic_gpu_prefix(&self) -> Option<usize> {
2390        let (model, _, _, _) = self.weights.embed_tokens.graph_weight()?;
2391        crate::gpu::automatic_layer_prefix(&model, self.num_layers, self.physical_layers)
2392    }
2393
2394    /// Positions per batched pass of the layer-stack prefill for THIS
2395    /// model on THIS backend (see [`prefill_chunk_rule`]). Pub: the network
2396    /// split must chunk exactly like the local path to reproduce it.
2397    pub fn prefill_chunk(&self) -> usize {
2398        let env = env_prefill_chunk();
2399        if env.is_some() || ChunkHost::here() != ChunkHost::Other {
2400            return prefill_chunk_rule(env, ChunkHost::here(), false);
2401        }
2402        let facts = self.chunk_stack_facts();
2403        if facts.dense_on_cpu() {
2404            return CPU_DENSE_PREFILL_CHUNK;
2405        }
2406        prefill_chunk_rule(None, ChunkHost::Other, facts.dense_on_discrete())
2407    }
2408
2409    /// Prompt lookup in a speculative round (`CMF_SPEC_LOOKUP=0` leaves the
2410    /// chain to the draft head alone).
2411    fn spec_lookup_on() -> bool {
2412        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2413        *ON.get_or_init(|| std::env::var("CMF_SPEC_LOOKUP").as_deref() != Ok("0"))
2414    }
2415
2416    /// Whether a verify of two or three rows runs on the small-batch matvec:
2417    /// native Metal, a dense q4tp FFN in the trunk, the kernel not switched
2418    /// off (`CMF_METAL_MVS=0`).
2419    fn metal_small_batch_verify(&self) -> bool {
2420        #[cfg(target_os = "macos")]
2421        {
2422            crate::gpu::q1_force()
2423                && crate::gpu_metal::small_batch_mv()
2424                && self.weights.layers.first().is_some_and(|l| match &l.ffn {
2425                    FfnKind::Dense(d) => d.gate_proj.mapped_q4tp().is_some(),
2426                    _ => false,
2427                })
2428        }
2429        #[cfg(not(target_os = "macos"))]
2430        {
2431            false
2432        }
2433    }
2434
2435    /// Architectures that run a dedicated per-token stack (gemma-3n's
2436    /// AltUp flow, the gemma-4 E-series PLE/shared-KV body): batched
2437    /// prefill and the graphs stay off for them.
2438    fn per_token_stack(&self) -> bool {
2439        self.g3n.is_some() || self.g4e.is_some()
2440    }
2441
2442    fn chunk_stack_facts(&self) -> ChunkStackFacts {
2443        let plain_dense = !self.weights.layers.is_empty()
2444            && !self.per_token_stack()
2445            && self.dsv4.is_none()
2446            && self.dsv41.is_none()
2447            && self.dory.is_none()
2448            && self.qwen4_exp.is_none()
2449            && self.glm5_next.is_none()
2450            && self.hy4.is_none()
2451            && self.maxwell.is_none()
2452            && self.inkling.is_none()
2453            && self.weights.layers.iter().all(|lw| {
2454                // LFM2/LFM3's short-conv mixer is two projection GEMMs and
2455                // an elementwise conv: the host-driven chunk walk starves
2456                // the card the same way (LFM3-1.7B q8_2f on an A40, 2048
2457                // positions: 137 tok/s at 48, 460-640 at 512).
2458                matches!(lw.attn, AttnKind::Full { .. } | AttnKind::ShortConv(_))
2459                    && matches!(lw.ffn, FfnKind::Dense(_))
2460            });
2461        let gpu_on = crate::gpu::enabled();
2462        ChunkStackFacts {
2463            plain_dense,
2464            discrete: gpu_on && crate::gpu::discrete(),
2465            gpu_on,
2466            // Only asked when the rest already qualifies: it opens the
2467            // backend's capacity plan.
2468            capacity_split: std::env::var_os("CMF_GPU_LAYERS").is_some()
2469                || (plain_dense && gpu_on && self.automatic_gpu_prefix().is_some()),
2470            multi_gpu: self.gpu_plan.is_some(),
2471            o1: self.o1_active(),
2472        }
2473    }
2474}
2475
2476/// Prefill chunk (positions per batched pass), model-agnostic form. On
2477/// macOS the AMX GEMM path wants tall panels — M=48 starves the matrix
2478/// units (ggml uses ubatch 512); elsewhere the historical 48 stays.
2479/// CMF_PREFILL_CHUNK overrides. The architectures with their own stacks
2480/// (DeepSeek-V4/V4.1) chunk with this; the layer-stack prefill asks
2481/// [`Pipeline::prefill_chunk`], which also knows the model and the card.
2482/// A different chunk is a different (equally valid) generation: panel
2483/// width reorders float accumulation.
2484pub fn prefill_chunk() -> usize {
2485    prefill_chunk_rule(env_prefill_chunk(), ChunkHost::here(), false)
2486}
2487
2488fn env_prefill_chunk() -> Option<usize> {
2489    std::env::var("CMF_PREFILL_CHUNK")
2490        .ok()
2491        .and_then(|v| v.parse::<usize>().ok())
2492}
2493
2494/// The host classes the chunk width distinguishes.
2495#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2496enum ChunkHost {
2497    Macos,
2498    /// Linux/Android aarch64 (phones, SBCs).
2499    Aarch64,
2500    /// Everything else: x86-64 Linux/Windows, CPU or Vulkan/DX12.
2501    Other,
2502}
2503
2504impl ChunkHost {
2505    fn here() -> Self {
2506        if cfg!(target_os = "macos") {
2507            ChunkHost::Macos
2508        } else if cfg!(target_arch = "aarch64") {
2509            ChunkHost::Aarch64
2510        } else {
2511            ChunkHost::Other
2512        }
2513    }
2514}
2515
2516/// Chunk for a plain dense stack whose every layer lives on a discrete
2517/// card. On x86 the layer-stack prefill is host-driven: each GEMM and the
2518/// chunk attention (which re-uploads the whole KV prefix per layer) is a
2519/// separate submit + readback, so 48 positions a pass left the card idle
2520/// between them. Measured in-process on an RTX 3090 (Vulkan), 2048-token
2521/// prompt — see CHANGELOG 0.7.6 for the table.
2522const DISCRETE_DENSE_PREFILL_CHUNK: usize = 512;
2523
2524/// Chunk for a plain dense stack with no GPU at all on x86-64: the AVX2
2525/// q4tp batch kernel and the micro-GEMM chunk attend feed on wider
2526/// panels. Spark-X2.6-4B q4tp, 1000-token prompt on 8 Zen 2 cores: 20.7
2527/// tok/s at 48, 24.7 at 128, 25.0 at 256.
2528const CPU_DENSE_PREFILL_CHUNK: usize = 128;
2529
2530/// The chunk-width rule. `dense_on_discrete` is true only for a plain
2531/// dense transformer (full attention, dense FFN, no special stack) that
2532/// is entirely resident on one discrete card — the one case measured
2533/// here. GDN hybrids, MoE, DeepSeek stacks, capacity-split and CPU-only
2534/// runs keep the width they were tuned with.
2535fn prefill_chunk_rule(env: Option<usize>, host: ChunkHost, dense_on_discrete: bool) -> usize {
2536    if let Some(n) = env {
2537        return n.max(1);
2538    }
2539    match host {
2540        ChunkHost::Macos => 512,
2541        // Mobile: big enough to feed the batched attend (gate b ≥ 32)
2542        // and the blocked SDOT GEMM without the memory of 512.
2543        ChunkHost::Aarch64 => 256,
2544        ChunkHost::Other if dense_on_discrete => DISCRETE_DENSE_PREFILL_CHUNK,
2545        ChunkHost::Other => 48,
2546    }
2547}
2548
2549/// What the chunk rule needs to know about a loaded stack.
2550#[derive(Clone, Copy, Debug, Default)]
2551struct ChunkStackFacts {
2552    /// Every layer is `AttnKind::Full` or `AttnKind::ShortConv` +
2553    /// `FfnKind::Dense`, and no architecture-owned stack (g3n,
2554    /// DeepSeek-V4/V4.1, qwen4-exp) is set.
2555    plain_dense: bool,
2556    /// The active GPU backend is a discrete card.
2557    discrete: bool,
2558    /// The backend is up and not paused.
2559    gpu_on: bool,
2560    /// A capacity-derived device prefix: some layers run on the host.
2561    capacity_split: bool,
2562    /// An in-process multi-GPU plan is set.
2563    multi_gpu: bool,
2564    /// O(1) layers (their Q trace is recorded by the prefill).
2565    o1: bool,
2566}
2567
2568impl ChunkStackFacts {
2569    /// A plain dense stack on an x86-64 host with no GPU backend up
2570    /// (O(1) stacks keep the width their trace was measured with).
2571    fn dense_on_cpu(self) -> bool {
2572        cfg!(target_arch = "x86_64")
2573            && self.plain_dense
2574            && !self.gpu_on
2575            && !self.multi_gpu
2576            && !self.o1
2577    }
2578
2579    fn dense_on_discrete(self) -> bool {
2580        self.plain_dense
2581            && self.discrete
2582            && self.gpu_on
2583            && !self.capacity_split
2584            && !self.multi_gpu
2585            && !self.o1
2586    }
2587}
2588
2589/// Number of prompt rows that have a real teacher-forced next-token pair in a
2590/// prefill span.  The final prompt row has no successor token, so it must not
2591/// be handed to the MTP warm-up.  Keeping this arithmetic in one helper makes
2592/// the full-chunk and tail-chunk boundaries explicit for both the graph and
2593/// CPU implementations.
2594#[inline]
2595fn mtp_prefill_pair_count(start: usize, end: usize, input_len: usize) -> usize {
2596    if end <= start || start >= input_len {
2597        return 0;
2598    }
2599    let rows = (end.min(input_len) - start).min(input_len - start);
2600    if end < input_len {
2601        rows
2602    } else {
2603        rows.saturating_sub(1)
2604    }
2605}
2606
2607/// Callback for streaming tokens. Return `false` to cancel.
2608pub type TokenCallback = Box<dyn FnMut(&str) -> bool + Send>;
2609
2610/// One layer's cache ownership at a cross-turn KV reuse boundary.
2611#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2612pub(crate) struct ReuseLayer {
2613    /// Exact-attention layer (rows in `LayerKvCache`); otherwise a
2614    /// recurrent / latent mixer whose state cannot be rewound.
2615    pub full: bool,
2616    /// Positions the host owner cache reaches (`pos_len`: a trimmed
2617    /// sliding tail stores only the newest of them).
2618    pub host_rows: usize,
2619    /// Rows the wgpu token graph's device mirror holds (None: no mirror).
2620    pub device_rows: Option<usize>,
2621    /// A recurrent state lives on the device (advanced past the host copy).
2622    pub device_state: bool,
2623}
2624
2625/// What a reused turn must do before its tail prefill runs on the HOST.
2626#[derive(Debug, Clone, PartialEq, Eq)]
2627pub(crate) enum ReusePlan {
2628    /// Host caches already hold exactly the reused prefix.
2629    Ready,
2630    /// Copy device mirror rows `[from..to)` into the host cache of each
2631    /// listed layer (the rows decode wrote on the device only).
2632    Pull(Vec<(usize, usize, usize)>),
2633    /// The prefix cannot be continued on the host exactly: start fresh.
2634    Fresh,
2635}
2636
2637/// The wgpu whole-token graph decodes into a DEVICE K/V mirror and never
2638/// writes those rows back to the host cache, while the chunked prefill of a
2639/// pure-attention model reads (and appends to) the host cache. A reused turn
2640/// therefore found its host cache ending at the previous PROMPT, not at the
2641/// previous answer: the tail prefill attended without the model's own
2642/// answer and appended its rows at the wrong index (MiniCPM5 on Vulkan
2643/// repeated its tool call instead of reading the tool result). Every layer
2644/// must hold exactly `reuse_from` host rows before the host continues; rows
2645/// that exist only on the device are pulled back, anything else is fresh.
2646pub(crate) fn kv_reuse_plan(reuse_from: usize, layers: &[ReuseLayer]) -> ReusePlan {
2647    let mut pulls = Vec::new();
2648    for (li, l) in layers.iter().enumerate() {
2649        if !l.full {
2650            if l.device_state {
2651                return ReusePlan::Fresh;
2652            }
2653            continue;
2654        }
2655        if l.host_rows == reuse_from {
2656            continue;
2657        }
2658        if l.host_rows < reuse_from && l.device_rows.is_some_and(|d| d >= reuse_from) {
2659            pulls.push((li, l.host_rows, reuse_from));
2660            continue;
2661        }
2662        return ReusePlan::Fresh;
2663    }
2664    if pulls.is_empty() {
2665        ReusePlan::Ready
2666    } else {
2667        ReusePlan::Pull(pulls)
2668    }
2669}
2670
2671impl Pipeline {
2672    /// Reset state whose meaning is local to a single MTP draft sequence.
2673    /// Unlike ordinary KV reuse, MTP is always rebuilt from the prompt.
2674    fn reset_fresh_mtp_draft_state(&mut self) {
2675        self.draft_full_streak = 0;
2676    }
2677
2678    /// Clear all per-sequence state, including backend device mirrors.
2679    ///
2680    /// The host KV/history buffers are only half of the request lifecycle on
2681    /// wgpu: GDN/O(1) state and cached graph bind groups are keyed by the
2682    /// pipeline id and otherwise survive a pooled request.  Keep every fresh
2683    /// sequence entry point on this one reset path so a new request cannot
2684    /// inherit the prior request's device state.
2685    fn clear_sequence_state(&mut self) {
2686        // a replay still writing the GDN owners must land before they are
2687        // cleared or reallocated (the device holds raw pointers to them)
2688        #[cfg(target_os = "macos")]
2689        let _ = crate::gpu_metal::wait_replay();
2690        self.kv_cache.clear();
2691        // Both reuse keys (the legacy `kv_history` and the bounded
2692        // `kv_prefix`) describe the state being dropped here.
2693        self.clear_history();
2694        self.graph_logits = None;
2695        if let Some(d) = &mut self.dflash {
2696            d.reset();
2697        }
2698        self.dflash_rows = None;
2699        self.dflash_taps.lock().unwrap().clear();
2700        // a new sequence owes the DFlash block nothing of the last one's turns
2701        self.dflash_hold = DFLASH_HOLD_PRIOR;
2702        (self.dflash_last, self.dflash_wait, self.dflash_back, self.dflash_turn) = (false, 0, DFLASH_WAIT, 0);
2703        self.dflash_turn_sum = (0.0, 0.0);
2704        self.dflash_lean = 0.0;
2705        if let Some(b) = &mut self.dsv41 {
2706            b.3.clear();
2707        }
2708        if let Some(b) = &mut self.dory {
2709            b.1.clear();
2710            crate::gpu::dory_reset(self.graph_kv_id);
2711        }
2712        crate::gpu::graph_kv_reset(self.graph_kv_id);
2713        // the card's GDN snapshot went with the sequence's states
2714        self.gdn_snap = None;
2715        self.mtp_warm_base = None;
2716        // MTP is detached from `self` for the duration of generation, so its
2717        // device mirror is not covered by the trunk reset above.  Reset the
2718        // derived id as well: a failed/aborted warm-up must never leave a
2719        // mirror that a later request can mistake for a current MTP cache.
2720        crate::gpu::graph_kv_reset(self.mtp_kv_id());
2721    }
2722
2723    /// Make the host caches own exactly the reused prefix `[0..reuse_from)`
2724    /// before a reused turn's tail prefill runs on the host (see
2725    /// [`kv_reuse_plan`]). Returns false when the prefix cannot be continued
2726    /// exactly — the caller then starts a fresh sequence. A model whose
2727    /// prefill runs through the token graph keeps its device state as the
2728    /// authority and is left untouched.
2729    fn prepare_kv_reuse(&mut self, reuse_from: usize) -> bool {
2730        if self.dory.is_some() || self.graph_prefill_preferred() {
2731            return true;
2732        }
2733        let kv_id = self.graph_kv_id;
2734        let layers: Vec<ReuseLayer> = (0..self.num_layers)
2735            .map(|li| {
2736                let full = matches!(
2737                    self.weights.layers[self.phys_layer(li)].attn,
2738                    AttnKind::Full { .. }
2739                );
2740                ReuseLayer {
2741                    full,
2742                    // Absolute depth: a trimmed sliding tail stores fewer
2743                    // rows than the positions it has seen.
2744                    host_rows: self.kv_cache.layers[li].pos_len(),
2745                    device_rows: crate::gpu::graph_kv_stored(kv_id, li),
2746                    device_state: crate::gpu::graph_state_resident(kv_id, li),
2747                }
2748            })
2749            .collect();
2750        // No wgpu device state at all (CPU, Metal — whose graph appends every
2751        // decoded row to the owner cache itself): the host is the owner and
2752        // the extension check already proved the prefix.
2753        if layers
2754            .iter()
2755            .all(|l| l.device_rows.is_none() && !l.device_state)
2756        {
2757            return true;
2758        }
2759        let plan = kv_reuse_plan(reuse_from, &layers);
2760        let (what, rows, n) = match &plan {
2761            ReusePlan::Ready => ("host ready", 0, 0),
2762            ReusePlan::Fresh => ("fresh", 0, 0),
2763            ReusePlan::Pull(p) => (
2764                "pull",
2765                p.iter().map(|&(_, a, b)| b - a).max().unwrap_or(0),
2766                p.len(),
2767            ),
2768        };
2769        let t0 = std::time::Instant::now();
2770        let ok = self.apply_kv_reuse_plan(reuse_from, plan, &layers);
2771        if std::env::var("CMF_PREFILL_PROF").is_ok() {
2772            eprintln!(
2773                "kv-reuse: {what}{}: {rows} device row(s) × {n} layer(s) to the host in {:.2} ms",
2774                if ok { "" } else { " (failed → fresh)" },
2775                t0.elapsed().as_secs_f64() * 1e3
2776            );
2777        }
2778        ok
2779    }
2780
2781    fn apply_kv_reuse_plan(
2782        &mut self,
2783        reuse_from: usize,
2784        plan: ReusePlan,
2785        layers: &[ReuseLayer],
2786    ) -> bool {
2787        let kv_id = self.graph_kv_id;
2788        match plan {
2789            ReusePlan::Fresh => return false,
2790            ReusePlan::Ready => {}
2791            ReusePlan::Pull(pulls) => {
2792                // Mirrors of one uniform geometry: one batched read serves
2793                // every layer. Per-layer geometry (MiMo-V2: 4/8 KV heads,
2794                // narrow V, sliding rings) is read layer by layer in the
2795                // host layout instead.
2796                let (nkv, hd) = {
2797                    let c = &self.kv_cache.layers[pulls[0].0];
2798                    (c.num_kv_heads, c.head_dim)
2799                };
2800                let uniform = pulls.iter().all(|&(li, _, _)| {
2801                    let c = &self.kv_cache.layers[li];
2802                    (c.num_kv_heads, c.head_dim) == (nkv, hd)
2803                });
2804                let batched = if uniform {
2805                    crate::gpu::graph_kv_read_rows(kv_id, &pulls, nkv, hd)
2806                } else {
2807                    None
2808                };
2809                let rows: Vec<(Vec<f32>, Vec<f32>)> = match batched {
2810                    Some(rows) => rows,
2811                    None => {
2812                        let mut rows = Vec::with_capacity(pulls.len());
2813                        for &(li, from, to) in &pulls {
2814                            let (lnkv, lhd) = {
2815                                let c = &self.kv_cache.layers[li];
2816                                (c.num_kv_heads, c.head_dim)
2817                            };
2818                            let Some((k, v, first_valid)) =
2819                                crate::gpu::graph_kv_pull_host(kv_id, li, from, to, lnkv, lhd)
2820                            else {
2821                                return false;
2822                            };
2823                            // The host continues at `to`: a sliding layer
2824                            // reads back only its last window, a full one
2825                            // every row it lacks.
2826                            let need_from = match self.layer_window(li) {
2827                                Some(w) => from.max((to + 1).saturating_sub(w)),
2828                                None => from,
2829                            };
2830                            if first_valid > need_from {
2831                                return false;
2832                            }
2833                            rows.push((k, v));
2834                        }
2835                        rows
2836                    }
2837                };
2838                for ((li, from, to), (k, v)) in pulls.into_iter().zip(rows) {
2839                    let cache = &mut self.kv_cache.layers[li];
2840                    let row = cache.num_kv_heads * cache.head_dim;
2841                    for p in 0..to - from {
2842                        cache.append(&k[p * row..(p + 1) * row], &v[p * row..(p + 1) * row], &[]);
2843                    }
2844                    if cache.pos_len() != to {
2845                        return false;
2846                    }
2847                }
2848            }
2849        }
2850        // A mirror past the prefix (a greedy burst that ran beyond the stop)
2851        // holds rows of the OLD continuation: rewind it so the next graph
2852        // token re-syncs those positions from the host.
2853        for (li, l) in layers.iter().enumerate() {
2854            if l.full
2855                && l.device_rows.is_some_and(|d| d > reuse_from)
2856                && !crate::gpu::graph_kv_set_stored(kv_id, li, reuse_from)
2857            {
2858                return false;
2859            }
2860        }
2861        true
2862    }
2863
2864    /// Finish a generation lifecycle after the MTP/router owners were
2865    /// detached.  Every terminal path must put those owners back before the
2866    /// pooled pipeline can serve another request.  Graph side channels and
2867    /// device mirrors are cleared on errors and cancellations; a successful
2868    /// generation keeps its decode-ready host cache for KV reuse.
2869    fn finish_generation(
2870        &mut self,
2871        mtp: &mut Option<MtpModule>,
2872        router: &mut Option<crate::swarm::DynRouter>,
2873        clear_sequence: bool,
2874    ) {
2875        // A dynamic route may have switched the overlay before the terminal
2876        // path. Restore the backbone while the detached router is still
2877        // available, because set_active_skill also owns the overlay reset.
2878        if router.is_some() {
2879            let _ = self.set_active_skill(None);
2880        }
2881        // The last speculative round's replay may still be in flight on
2882        // the second queue: whoever reads the host cache after generate()
2883        // returns (session export, the network split's KV wire, a KV
2884        // reuse) must see the final states.
2885        // A replay that failed leaves the GDN owners half-written: fail
2886        // closed and drop the sequence instead of handing the cache on.
2887        #[cfg(target_os = "macos")]
2888        let clear_sequence = clear_sequence || !crate::gpu_metal::wait_replay();
2889        if clear_sequence {
2890            self.clear_sequence_state();
2891            if let Some(m) = mtp.as_mut() {
2892                // The MTP owner is detached while generation runs, so the
2893                // trunk reset above cannot clear its host cache.  Drop its
2894                // partial rows before reattaching it to the pooled pipeline;
2895                // the next request must start from the same empty anchor on
2896                // CPU and on the device mirror.
2897                m.kv.clear();
2898            }
2899            if let Some(m) = self.mtp.as_mut() {
2900                // A non-speculative request leaves the configured MTP owner
2901                // attached.  Clear that dormant cache too when a shared
2902                // generation failure/cancellation resets the sequence.
2903                m.kv.clear();
2904            }
2905        }
2906        self.graph_want_logits = false;
2907        self.graph_head_required = false;
2908        self.graph_logits = None;
2909        self.graph_failed
2910            .store(false, std::sync::atomic::Ordering::Relaxed);
2911        self.cancel
2912            .store(false, std::sync::atomic::Ordering::Relaxed);
2913        self.dyn_router = router.take().or(self.dyn_router.take());
2914        self.mtp = mtp.take().or(self.mtp.take());
2915        self.mtp_graph_mode = None;
2916        self.spec_forced = None;
2917    }
2918
2919    /// Consume a graph failure reported by a forward that returns only a
2920    /// hidden vector.  `forward_ids` is a public Result API, so it must not
2921    /// turn the graph's zero hidden sentinel into a valid lm_head result.
2922    fn check_forward_graph(&mut self, phase: &str, pos: usize) -> Result<(), String> {
2923        if self
2924            .graph_failed
2925            .swap(false, std::sync::atomic::Ordering::Relaxed)
2926        {
2927            self.cancel
2928                .store(false, std::sync::atomic::Ordering::Relaxed);
2929            self.clear_sequence_state();
2930            self.graph_logits = None;
2931            self.graph_want_logits = false;
2932            self.graph_head_required = false;
2933            return Err(format!("GPU graph failed during {phase} at position {pos}"));
2934        }
2935        Ok(())
2936    }
2937
2938    #[cfg(target_os = "macos")]
2939    fn fail_metal_graph(&mut self, reason: &str) {
2940        crate::pipeline::METAL_GRAPH_ERRORS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2941        self.clear_sequence_state();
2942        self.graph_logits = None;
2943        self.graph_failed
2944            .store(true, std::sync::atomic::Ordering::Relaxed);
2945        self.cancel
2946            .store(true, std::sync::atomic::Ordering::Relaxed);
2947        tracing::error!("native Metal TokenGraph failed closed: {reason}");
2948    }
2949
2950    /// Start an NLL/PPL request with all graph side channels in a known
2951    /// state.  A graph failure also raises the cooperative cancel bit; it is
2952    /// consumed here and that graph-induced bit is cleared so an independent
2953    /// request can be reused.  A caller-owned cancellation remains intact.
2954    fn nll_begin(&mut self) -> Result<(), String> {
2955        if self
2956            .graph_failed
2957            .swap(false, std::sync::atomic::Ordering::Relaxed)
2958        {
2959            self.cancel
2960                .store(false, std::sync::atomic::Ordering::Relaxed);
2961            self.clear_sequence_state();
2962            self.graph_logits = None;
2963            self.graph_want_logits = false;
2964            self.graph_head_required = false;
2965            return Err("GPU graph failed before NLL scoring".to_string());
2966        }
2967        self.clear_sequence_state();
2968        self.graph_logits = None;
2969        self.graph_want_logits = false;
2970        self.graph_head_required = false;
2971        Ok(())
2972    }
2973
2974    /// End an NLL/PPL request, including the side channels that are not part
2975    /// of the host KV cache.  This is intentionally explicit instead of
2976    /// relying on a tuple/sentinel return: callers must see every failure.
2977    fn nll_end(&mut self) {
2978        self.clear_sequence_state();
2979        self.graph_logits = None;
2980        self.graph_want_logits = false;
2981        self.graph_head_required = false;
2982        self.graph_failed
2983            .store(false, std::sync::atomic::Ordering::Relaxed);
2984    }
2985
2986    /// Check the graph failure channel at a scoring boundary and leave the
2987    /// pipeline reusable when the device path failed.
2988    fn nll_check_graph(&mut self, phase: &str, pos: usize) -> Result<(), String> {
2989        #[cfg(test)]
2990        if self.nll_test_fail_at == Some(pos) {
2991            self.nll_test_fail_at = None;
2992            self.graph_failed
2993                .store(true, std::sync::atomic::Ordering::Relaxed);
2994            self.cancel
2995                .store(true, std::sync::atomic::Ordering::Relaxed);
2996        }
2997        if self
2998            .graph_failed
2999            .swap(false, std::sync::atomic::Ordering::Relaxed)
3000        {
3001            self.cancel
3002                .store(false, std::sync::atomic::Ordering::Relaxed);
3003            self.clear_sequence_state();
3004            self.graph_logits = None;
3005            self.graph_want_logits = false;
3006            return Err(format!(
3007                "GPU graph failed during NLL {phase} at position {pos}"
3008            ));
3009        }
3010        Ok(())
3011    }
3012
3013    /// Map a virtual layer index to its physical weight index.
3014    /// Looped Transformer (Nanbeige 4.2): 22 physical layers × 2 loops = 44 virtual;
3015    /// virtual layer 23 maps back to physical layer 1 (23 % 22 = 1).
3016    #[inline]
3017    pub fn phys_layer(&self, virtual_idx: usize) -> usize {
3018        match &self.layer_map {
3019            Some(m) => m[virtual_idx],
3020            None => virtual_idx % self.physical_layers,
3021        }
3022    }
3023
3024    /// Mage-VL (`llava_onevision2`) and MiniCPM-OCR prompt ingest through the batched wgpu
3025    /// graph (`CMF_GRAPH_PREFILL=0` keeps the chunked host prefill).
3026    fn onevision2_prefill(&self) -> bool {
3027        self.model.as_ref().is_some_and(|m| matches!(m.header.arch.arch_name.as_str(), "llava_onevision2" | "minicpm_ocr"))
3028            && std::env::var("CMF_GRAPH_PREFILL").as_deref() != Ok("0")
3029    }
3030
3031    /// SenseNova-Loop: whether virtual layer `li` runs inside the mHC
3032    /// streams (the device graphs decline such layers).
3033    #[inline]
3034    pub fn mhc_layer(&self, li: usize) -> bool {
3035        self.mhc.as_ref().is_some_and(|m| m.on(self.phys_layer(li)))
3036    }
3037
3038    /// A device prefix stopped at layer `at`, inside an mHC range (not its first
3039    /// layer): the host's layers continue from the streams the card holds — the
3040    /// decode token's (`mhc_r`) or, `chunk` rows given, a prompt chunk's for
3041    /// `prefill_batch_span`. False when `at` is not inside a range.
3042    fn mhc_from_device(&mut self, at: usize, chunk: Option<usize>) -> bool {
3043        let inside = at < self.num_layers
3044            && self.mhc_layer(at)
3045            && !self.mhc.as_deref().is_some_and(|m| m.enters(self.phys_layer(at)));
3046        if !inside {
3047            return false;
3048        }
3049        match (crate::gpu::mhc_streams_read(self.hidden_size, chunk.unwrap_or(1)), chunk) {
3050            (Some(r), None) => self.mhc_r = r,
3051            (Some(r), Some(_)) => self.mhc_rows_in = r,
3052            (None, _) => tracing::error!("mHC: the device prefix's streams could not be read back at layer {at}"),
3053        }
3054        true
3055    }
3056
3057    /// mHC before a sub-layer of the decode token: route its streams into
3058    /// `h` (entering the range copies `h` into every stream first).
3059    fn mhc_pre(&mut self, li: usize, ffn: bool, h: &mut [f32]) -> crate::sensenova::MhcCoef {
3060        let p = self.phys_layer(li);
3061        let m = self.mhc.as_deref().expect("mhc layer");
3062        let n = m.s.streams * m.dim;
3063        if self.mhc_r.len() != n {
3064            self.mhc_r.resize(n, 0.0);
3065        }
3066        if !ffn && m.enters(p) {
3067            m.enter(&mut self.mhc_r, h);
3068        }
3069        m.route(p, ffn, &self.mhc_r, h)
3070    }
3071
3072    /// mHC after a sub-layer: fold its output `y` into the streams; after
3073    /// the range's last FFN, `h` becomes the streams' mean.
3074    fn mhc_post(&mut self, li: usize, ffn: bool, y: &[f32], c: &crate::sensenova::MhcCoef, h: &mut [f32]) {
3075        let p = self.phys_layer(li);
3076        let m = self.mhc.as_deref().expect("mhc layer");
3077        m.merge(&mut self.mhc_r, y, c);
3078        if ffn && m.leaves(p) {
3079            m.leave(&self.mhc_r, h);
3080        }
3081    }
3082
3083    /// True when `virtual_idx` is the last layer of a loop iteration
3084    /// (used for loop_final_norm insertion).
3085    #[inline]
3086    pub fn is_loop_end(&self, virtual_idx: usize) -> bool {
3087        self.loop_final_norm && (virtual_idx + 1) % self.physical_layers == 0
3088    }
3089
3090    /// Build a pipeline from parts (used by the loader and tests).
3091    #[allow(clippy::too_many_arguments)]
3092
3093    /// Whole-block q1 token graph on the GPU (macOS/Metal): the run of
3094    /// consecutive q1 layers — GDN *and* full attention — starting at
3095    /// `start` executes as few command buffers as the CPU truly needs.
3096    /// Hidden stays device-resident across every layer; the only syncs
3097    /// are before each CPU attend (it needs q/k/v and owns the KV
3098    /// cache) and the final hidden readback. Recurrent states
3099    /// round-trip through shared memory (the CPU stays their owner, so
3100    /// every other path remains coherent). Returns the first layer
3101    /// index NOT covered (== `start` → refused, caller falls through
3102    /// to the per-layer CPU path).
3103    /// Should prefill run position-by-position through the GPU token
3104    /// graph instead of the batched CPU chunk-GEMM? True for q1 GDN
3105    /// hybrids on native Metal: their chunk prefill is walled by the
3106    /// sequential scalar recurrence, so the graph's decode rate wins.
3107    /// NOT for Looped Transformers, despite the per-chunk loop_final_norm
3108    /// sync: the chunk-GEMM amortizes each weight over the whole chunk,
3109    /// which the per-position graph cannot (Nanbeige 4.2 on M4, 512-token
3110    /// prompt: 85 tok/s chunked vs 14 through the graph).
3111    #[cfg(target_os = "macos")]
3112    fn graph_prefill_preferred(&self) -> bool {
3113        // The resident Embryo graph owns the phase state and the anchor KV on
3114        // the device: the prompt must seed them there (wgpu over Metal).
3115        if crate::gpu::enabled_here()
3116            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)
3117            && matches!(std::env::var("CMF_EMBRYO_RESIDENT").as_deref(), Ok("1") | Ok("parallel"))
3118            && self.embryo_resident_eligible()
3119        {
3120            return true;
3121        }
3122        let graph_force = crate::gpu::q1_force() || crate::gpu::q2tp_gpu_opt_in();
3123        if !crate::gpu::enabled_here()
3124            || !graph_force
3125            || std::env::var("CMF_GPU_BLOCK")
3126                .map(|v| v == "0")
3127                .unwrap_or(false)
3128            // CMF_PREFILL_GRAPH=0: the chunked prefill (GEMM projections,
3129            // CPU recurrence) instead of the per-position token graph.
3130            || std::env::var("CMF_PREFILL_GRAPH").as_deref() == Ok("0")
3131        {
3132            return false;
3133        }
3134        self.weights
3135            .layers
3136            .iter()
3137            .any(|lw| {
3138                matches!(&lw.attn, AttnKind::LinearGdn(w) if w.in_proj_qkv.metal_graph_parts().is_some())
3139            })
3140    }
3141
3142    /// Prompt ingest through the batched wgpu graph in device-prefix mode:
3143    /// a MoE stack that does not fit the card runs each chunk's leading
3144    /// layers on the device (experts resident) and the rest on the host's
3145    /// batched walk. On by default for models with per-layer attention
3146    /// geometry (MiMo-V2 — its measured default); `CMF_BATCH_PREFIX=1`
3147    /// opts any other MoE model in, `=0` keeps the chunked host prefill.
3148    #[cfg(not(target_os = "macos"))]
3149    fn batch_prefix_prefill(&self) -> bool {
3150        let forced = match std::env::var("CMF_BATCH_PREFIX").as_deref() {
3151            Ok("0") => return false,
3152            Ok("1") => true,
3153            _ => false,
3154        };
3155        crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill)
3156            && crate::gpu::enabled_here()
3157            && !self.graph_refused()
3158            && (forced || self.graph_attn_decline_reason().is_some())
3159            && self.wgpu_graph_attn_decline().is_none()
3160            && self.attn_softcap == 0.0
3161            && self
3162                .weights
3163                .layers
3164                .iter()
3165                .any(|lw| matches!(&lw.ffn, FfnKind::Moe(_)))
3166            && self.automatic_gpu_prefix().is_some()
3167    }
3168
3169    /// Gemma-4's prompt through the batched wgpu graph (`gemma_batch`): a
3170    /// dense stack wholly on a discrete card, whose token graph already
3171    /// decodes it. Not `graph_prefill_preferred` — the host stays the KV
3172    /// owner for reuse and scoring; only generation's ingest changes.
3173    /// `CMF_G4_BATCH=0` keeps the chunked host prefill.
3174    fn g4_batch_prefill(&self) -> bool {
3175        #[cfg(target_os = "macos")]
3176        {
3177            false
3178        }
3179        #[cfg(not(target_os = "macos"))]
3180        {
3181            // An EMPTY layer stack (`all()` is vacuously true) plus a
3182            // gemma4 geometry flag is exactly the gemma-4 E-series
3183            // per-token stack — it has no batch graph rows to ingest.
3184            !self.weights.layers.is_empty()
3185                && !self.per_token_stack()
3186                // Gemma-4, and Ripple: a dense stack with per-layer geometry
3187                // whose host walk attends 80 heads a row on the CPU.
3188                && (self.global_attn.is_some() || self.attn_v_norm || self.value_blend.is_some())
3189                && crate::gpu::g4_batch_on()
3190                && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill)
3191                && crate::gpu::enabled_here()
3192                && crate::gpu::discrete()
3193                && !self.graph_refused()
3194                && !self.o1_active()
3195                && self.attn_softcap == 0.0
3196                && self.wgpu_graph_attn_decline().is_none()
3197                && self.weights.layers.iter().all(|lw| {
3198                    matches!(lw.attn, AttnKind::Full { .. }) && matches!(lw.ffn, FfnKind::Dense(_))
3199                })
3200                && self.automatic_gpu_prefix().is_none()
3201        }
3202    }
3203
3204    /// Gemma-4's batched prefill of `ids` at positions `pos0..`
3205    /// (`g4_batch_prefill`): chunks of `generation_batch_k` rows through the
3206    /// batch graph. Ok((n, rows)): `n` positions ingested; `rows` = the last
3207    /// one's hidden, or every row's (`keep_all`). A refusal stops early
3208    /// (n < ids.len()) after pulling the device rows the host walk needs.
3209    /// Err: a failure after admission — the device state is undefined.
3210    #[cfg(not(target_os = "macos"))]
3211    fn g4_batch_ingest(
3212        &mut self,
3213        ids: &[u32],
3214        pos0: usize,
3215        keep_all: bool,
3216    ) -> Result<(usize, Vec<f32>), String> {
3217        let hs = self.hidden_size;
3218        let chunk = self.generation_batch_k().max(1);
3219        let end_all = pos0 + ids.len();
3220        let mut pos = pos0;
3221        let mut out = Vec::new();
3222        while pos < end_all && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
3223            let end = (pos + chunk).min(end_all);
3224            let bk = end - pos;
3225            let mut hiddens = vec![0f32; bk * hs];
3226            for (j, &id) in ids[pos - pos0..end - pos0].iter().enumerate() {
3227                hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
3228            }
3229            let positions: Vec<usize> = (pos..end).collect();
3230            let t_chunk = std::time::Instant::now();
3231            let outcome = self.try_batch_graph_wgpu(&mut hiddens, &positions, bk, None);
3232            if std::env::var("CMF_GRAPH_PROF").is_ok() {
3233                let ms = t_chunk.elapsed().as_secs_f64() * 1000.0;
3234                eprintln!(
3235                    "batch-chunk: phase=prompt mode=gemma4 k={bk} outcome={outcome:?} {ms:.1} ms ({:.1} tok/s)",
3236                    bk as f64 / (ms / 1000.0)
3237                );
3238            }
3239            match outcome {
3240                crate::gpu::BatchGraphOutcome::Completed => {
3241                    if keep_all {
3242                        out.extend_from_slice(&hiddens);
3243                    } else {
3244                        out = hiddens[(bk - 1) * hs..].to_vec();
3245                    }
3246                    pos = end;
3247                }
3248                crate::gpu::BatchGraphOutcome::Failed => {
3249                    return Err("Gemma-4 batched prefill failed after admission".into());
3250                }
3251                crate::gpu::BatchGraphOutcome::Declined => {
3252                    #[cfg(feature = "gpu")]
3253                    if pos > pos0 {
3254                        self.pull_lagging_host_kv(0, self.num_layers, pos);
3255                    }
3256                    break;
3257                }
3258            }
3259        }
3260        Ok((pos - pos0, out))
3261    }
3262
3263    /// Hidden rows of every position of `ids` through Gemma-4's batched
3264    /// prefill from a fresh sequence (the prefill's teacher-forced logits
3265    /// for parity gates: `logits_from_hidden` per row). None when the model
3266    /// or the card does not take that route, or it refused part way.
3267    pub fn g4_prefill_hidden_rows(&mut self, ids: &[u32]) -> Option<Vec<f32>> {
3268        #[cfg(not(target_os = "macos"))]
3269        {
3270            if ids.is_empty() || !self.g4_batch_prefill() {
3271                return None;
3272            }
3273            self.clear_sequence_state();
3274            match self.g4_batch_ingest(ids, 0, true) {
3275                Ok((n, rows)) if n == ids.len() => Some(rows),
3276                _ => {
3277                    self.clear_sequence_state();
3278                    None
3279                }
3280            }
3281        }
3282        #[cfg(target_os = "macos")]
3283        {
3284            let _ = ids;
3285            None
3286        }
3287    }
3288
3289    #[cfg(not(target_os = "macos"))]
3290    fn graph_prefill_preferred(&self) -> bool {
3291        // Discrete-GPU wgpu whole-token graph: GDN layers carry recurrent state
3292        // (conv ring + delta-rule S) resident on the GPU. A batched CPU prefill
3293        // builds that state on the CPU only, leaving the GPU buffers zeroed at
3294        // decode → garbage. Route GDN-hybrid prefill through the graph one
3295        // position at a time so the resident state is seeded exactly as decode
3296        // will read it. Fully resident pure-attention models take the batched
3297        // graph as well (see the end of this function).
3298        let graph_on = crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill);
3299        if !graph_on || !crate::gpu::enabled_here() {
3300            return false;
3301        }
3302        // Embryo's phase state is device-owned by the resident graph during
3303        // prefill; the batched CPU path would leave decode seeing a zeroed
3304        // device recurrence.  Route the prompt position-by-position too.
3305        if self.embryo_resident_eligible() {
3306            // The resident graph owns the phase state and anchor KV on the
3307            // device.  A prefill-only graph would leave decode on the host
3308            // with no way to import that state, so keep the whole sequence
3309            // on one owner (or use the ordinary CPU prefill/decode pair).
3310            return crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode);
3311        }
3312        // The descriptor-aware Prism graph now carries both the FWHT/affine
3313        // transforms and resident GDN state, so it is also the exact prefill
3314        // path for this model.  Keeping it here (rather than falling through
3315        // to the CPU chunk walk) is required for a long prompt to seed the
3316        // same device state that decode consumes.
3317        // O(1) needs the CPU prefill: the q-trace that seals the Nyström
3318        // skeleton is recorded there and nowhere else. The GDN half of
3319        // the hybrid loses nothing — the graph's first decode creates
3320        // its (ring, S) entries seeded from `cpu_state`, the same
3321        // handoff every graph run relies on when the entry is fresh.
3322        // Without this line the two designs collide on hybrids and o1
3323        // never becomes graph-portable: prefill through the graph
3324        // records no trace, so views stay None forever.
3325        if self.o1_active() {
3326            return false;
3327        }
3328        // A model the wgpu graphs decline outright would walk its prompt
3329        // one position at a time through a graph that never runs: the
3330        // batched CPU chunk prefill is the right ingest for it.
3331        if self.wgpu_graph_attn_decline().is_some() {
3332            return false;
3333        }
3334        if self
3335            .weights
3336            .layers
3337            .iter()
3338            .any(|lw| matches!(&lw.attn, AttnKind::LinearGdn(_)))
3339            // Mage-VL: its screenshot prompts (~2k rows) go through the
3340            // batched graph, 4× the chunked host ingest on an A40 (2048
3341            // tokens: 806 tok/s at 128 rows, 893 at 256, against 196).
3342            || self.onevision2_prefill()
3343        {
3344            return true;
3345        }
3346        // MoE models too: the chunked CPU prefill runs every expert on the
3347        // host (Hy-MT2-30B-A3B on a Xeon: 8 tok/s of ingest against 53 of
3348        // graph decode), while the token graph — and the batched graph under
3349        // CMF_BATCH_K — keep the experts resident. Full attention in the
3350        // graph writes the KV mirror that decode reads, exactly as it does
3351        // for the hybrids' attention layers. Only when the whole stack is
3352        // resident: with a device prefix the per-position walk finishes
3353        // every token on the host, and the chunked prefill (GEMMs on the
3354        // card, the expert loop batched on the host) is the faster ingest
3355        // (the 8 GB ladder point: 7 tok/s chunked against ~1 walked).
3356        // Dense stacks too: the chunked walk paid a submit, a wait and a
3357        // readback per projection and per attend, so a resident 2B read its
3358        // prompt at the host's pace (CherryPit-1.2-2B on an RTX 5090, 2048
3359        // tokens: 10.6 s chunked, 1.2 s through the batched graph, the same
3360        // greedy text). `CMF_DENSE_GRAPH_PREFILL=0` keeps the chunked walk.
3361        // A dense stack the batched graph declined once (Spark-X2.6) keeps the
3362        // chunked walk: the per-position graph read its prompt at decode pace,
3363        // 65 tok/s against 350 on an RTX 2000 Ada.
3364        (self
3365            .weights
3366            .layers
3367            .iter()
3368            .any(|lw| matches!(&lw.ffn, FfnKind::Moe(_)))
3369            || (std::env::var("CMF_DENSE_GRAPH_PREFILL").as_deref() != Ok("0")
3370                && !self.dense_batch_declined.load(std::sync::atomic::Ordering::Relaxed)
3371                // Sliding-window stacks take the graph where its whole-run
3372                // attend is tiled: Spark-X2.6 q4tp on an RTX 2000 Ada,
3373                // 16 000 tokens, 182 tok/s chunked, 135 through the per-token
3374                // batched arm, 390+ tiled. `CMF_DENSE_GRAPH_PREFILL=1` sends
3375                // them through the graph regardless.
3376                && ((self.sliding_layers.is_none() && self.swa.is_none())
3377                    || crate::gpu::batched_attend_tiled()
3378                    || std::env::var("CMF_DENSE_GRAPH_PREFILL").as_deref() == Ok("1"))))
3379            && self.automatic_gpu_prefix().is_none()
3380    }
3381
3382    #[cfg(target_os = "macos")]
3383    fn q1_graph_gpu(
3384        &mut self,
3385        start: usize,
3386        upto: Option<usize>,
3387        position: usize,
3388        h: &mut [f32],
3389    ) -> usize {
3390        let _mt0 = std::time::Instant::now(); // CMF_METAL_HOSTPROF
3391        use crate::gpu::{
3392            AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, GraphDims, MetalFfn, SconvGpuLayer, TokenGraph,
3393        };
3394        const MOE_WORKING_SET_REASON: &str =
3395            "model weights exceed Metal working set for native MoE graph";
3396        // A prior admission check rejected this pipeline. Avoid rebuilding the
3397        // entire 40-layer graph plan at every individual host layer after the
3398        // fallback begins; the per-operation path below stays eligible.
3399        if self
3400            .graph_declines
3401            .borrow()
3402            .iter()
3403            .any(|&(site, reason)| site == "metal block graph" && reason == MOE_WORKING_SET_REASON)
3404        {
3405            return start;
3406        }
3407        let graph_force = crate::gpu::q1_force() || crate::gpu::q2tp_gpu_opt_in();
3408        if self.attn_softcap > 0.0 // capped scores: no graph kernel — CPU path
3409            // V with rows of its own (Ripple's value residual): no Metal kernel blends them.
3410            || self.value_blend.is_some()
3411            || !self.metal_rope_scale_ok()
3412            || !crate::gpu::enabled_here()
3413            || !graph_force
3414            || std::env::var("CMF_GPU_BLOCK")
3415                .map(|v| v == "0")
3416                .unwrap_or(false)
3417        {
3418            if std::env::var("CMF_GRAPH_DBG").is_ok() {
3419                eprintln!(
3420                    "block-graph: front gate (softcap={} enabled_here={} graph_force={})",
3421                    self.attn_softcap > 0.0,
3422                    crate::gpu::enabled_here(),
3423                    graph_force,
3424                );
3425            }
3426            if self.graph_head_required {
3427                self.fail_metal_graph("native graph front gate refused");
3428            }
3429            return start;
3430        }
3431        // The graph encodes SiLU or exact-GELU FFNs and attention with an
3432        // explicit model scale. Sliding-window layers with their own RoPE
3433        // table / rotary width ride it too (`metal_graph_swa`): both the
3434        // device attend and the sandwich's CPU attend read each layer's
3435        // window and table. Sandwich norms and other activations fall back
3436        // to the CPU path.
3437        // Gemma-4 (`metal_gemma4`): its sliding layers ride the same door,
3438        // its global layers, V norm, sandwich norms, layer scalar and
3439        // tanh-GELU the `gpu_metal::gemma4` kernels.
3440        let gemma4 = self.metal_gemma4();
3441        let swa_graph = self.metal_graph_swa() || gemma4;
3442        // The normal native GQA kernel carries a learned, value-less
3443        // softmax column.  It also takes the exact per-layer sliding
3444        // window, but its split-K twin has no sink column.  Thus a
3445        // sink-bearing model may use this door only when the ordinary
3446        // sliding geometry has passed `metal_graph_swa` (or when it has no
3447        // sliding layers at all).
3448        let graph_attn_reason = self.graph_attn_decline_reason();
3449        let native_sink_attend = graph_attn_reason == Some("learned attention sinks")
3450            && (swa_graph || (self.swa.is_none() && self.sliding_layers.is_none()));
3451        // Plain-weight (x̂·w) sandwich norms (LFM3) take the generic norm
3452        // kernels, as on the wgpu graph; Gemma-2/3's (1+w) norms and the
3453        // layer scalar stay Gemma-4's.
3454        let plain_norms = self.norm_style == cortiq_core::NormStyle::Qwen;
3455        if (self.swa.is_some() && !swa_graph)
3456            || (self.global_attn.is_some() && !gemma4)
3457            || self.attention_heads_per_layer.is_some()
3458            || (self.attn_v_norm && !gemma4)
3459            // Per-layer KV heads / narrow V stay outside this graph.  A
3460            // learned sink is admitted only through native_sink_attend.
3461            || (graph_attn_reason.is_some() && !swa_graph && !native_sink_attend)
3462            || self.weights.layers.iter().any(|lw| {
3463                ((lw.layer_scale.is_some()
3464                    || (!plain_norms && (lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some())))
3465                    && !gemma4)
3466                    || matches!(&lw.ffn, FfnKind::Dense(d)
3467                        if !(matches!(d.act, Act::Silu | Act::Gelu)
3468                            || (gemma4 && d.act == Act::GeluTanh)))
3469            })
3470        {
3471            // The Metal graphs' device attend has no per-layer attention
3472            // geometry (the wgpu graphs do): say so once, by name.
3473            if let Some(reason) = graph_attn_reason.filter(|_| !swa_graph && !native_sink_attend) {
3474                self.note_graph_decline("metal block graph", reason);
3475            }
3476            if std::env::var("CMF_GRAPH_DBG").is_ok() {
3477                eprintln!(
3478                    "block-graph: arch ineligible (swa={} gattn={} hpl={} vnorm={} scale_delta={:.2e})",
3479                    self.swa.is_some(),
3480                    self.global_attn.is_some(),
3481                    self.attention_heads_per_layer.is_some(),
3482                    self.attn_v_norm,
3483                    (self.attn_scale - 1.0 / (self.head_dim as f32).sqrt()).abs(),
3484                );
3485            }
3486            if self.graph_head_required {
3487                self.fail_metal_graph("native graph architecture gate refused");
3488            }
3489            return start;
3490        }
3491        // Looped Transformer: the graph covers ALL loop iterations;
3492        // encode_loop_norm is inserted on-device at each boundary.
3493        let limit = upto
3494            .map(|u| u + 1)
3495            .unwrap_or(self.num_layers)
3496            .min(self.num_layers);
3497
3498        enum Item<'a> {
3499            Gdn {
3500                run: Vec<GdnGpuLayer<'a>>,
3501                first: usize,
3502            },
3503            /// A run of LFM2/LFM3 short-conv layers (conv ring on device).
3504            Sconv {
3505                run: Vec<SconvGpuLayer<'a>>,
3506                first: usize,
3507            },
3508            Attn {
3509                l: AttnGpuLayer<'a>,
3510                li: usize,
3511                q_norm: Option<&'a [f32]>,
3512                k_norm: Option<&'a [f32]>,
3513                output_gate: bool,
3514                /// `self_attn.g_proj` output gate (per-head flag): the
3515                /// sandwich projects the device-normed input on the host
3516                /// and gates the attend's output before O.
3517                proj_gate: Option<(&'a QTensor, bool)>,
3518                /// The same gate's f32 rows `[nh × hidden]` when the device
3519                /// attend can apply it (per-head sigmoid, f32 in RAM).
3520                head_gate_w: Option<&'a [f32]>,
3521                bias: Option<(&'a [f32], &'a [f32], &'a [f32])>,
3522                /// Attend on the device too (no sync): F32 KV, no
3523                /// o1/bias, dims inside the kernels' contract.
3524                full_gpu: bool,
3525            },
3526        }
3527
3528        // Device-attend KERNEL contract, shared by every Full layer. The
3529        // hd>128 default-off POLICY is applied after the scan: it was
3530        // measured on dense models, and a MoE plan inverts it — with the
3531        // experts on device each CPU-attend sandwich costs a
3532        // commit+wait, ~30 submits/token (W2 on M4: 14.7 tok/s
3533        // sandwiched vs 27.1 device-attend vs 18.8 pure CPU).
3534        let attend_mode = std::env::var("CMF_GPU_ATTEND").unwrap_or_else(|_| "auto".into());
3535        let attend_contract = attend_mode != "0"
3536            && attend_mode != "off"
3537            && self.head_dim % 4 == 0
3538            && self.head_dim <= 256
3539            // Flint has explicit no-RoPE layers.  The device RoPE kernel
3540            // accepts rd=0 (zero rotation lanes) and binds a sentinel table;
3541            // retain the historical lane-pair requirement for nonzero rd.
3542            && (self.rotary_dim == 0
3543                || (self.rotary_dim >= 2
3544                    && self.rotary_dim <= self.head_dim
3545                    && (self.rotary_dim / 2) % 32 == 0))
3546            && self.num_kv_heads > 0
3547            && self.num_heads % self.num_kv_heads == 0;
3548
3549        let mut plan: Vec<Item> = Vec::new();
3550        let mut model_ref: Option<std::sync::Arc<cortiq_core::CmfModel>> = None;
3551        // Break-reason diagnostics ride the same env as the plan summary.
3552        let block_diag = std::env::var("CMF_GRAPH_DBG").is_ok();
3553        let mut scan = start;
3554        while scan < limit {
3555            // SenseNova-Loop: MRoPE prompt rows rotate on the host; an mHC
3556            // layer rides the graph when its kernels compiled (two streams,
3557            // dense FFN, device attend — checked below).
3558            if self.prompt_mrope.is_some()
3559                || (self.mhc_layer(scan)
3560                    && (!crate::gpu_metal::mhc::available()
3561                        || std::env::var("CMF_MHC_GRAPH").as_deref() == Ok("0")
3562                        || self.mhc.as_ref().is_some_and(|m| m.s.streams != 2 || m.s.fixed_identity)
3563                        || !matches!(self.weights.layers[self.phys_layer(scan)].ffn, FfnKind::Dense(_))))
3564            {
3565                break;
3566            }
3567            let lw = &self.weights.layers[self.phys_layer(scan)];
3568            let ffn = match &lw.ffn {
3569                FfnKind::Dense(d) if d.segs.is_empty() => {
3570                    let (Some(g), Some(u), Some(dn)) = (
3571                        d.gate_proj.metal_graph_parts(),
3572                        d.up_proj.metal_graph_parts(),
3573                        d.down_proj.metal_graph_parts(),
3574                    ) else {
3575                        if block_diag {
3576                            eprintln!(
3577                                "block-graph: L{scan} FFN trio not graph-mappable — run ends"
3578                            );
3579                        }
3580                        break;
3581                    };
3582                    MetalFfn::Dense {
3583                        gate: g,
3584                        up: u,
3585                        down: dn,
3586                        // The front gate admitted SiLU, exact GELU and
3587                        // (Gemma-4) tanh-GELU only.
3588                        act: d.act.graph_act().map_or(0, |a| a.code() as u8),
3589                    }
3590                }
3591                FfnKind::Moe(m) => {
3592                    // Flint's detached Q4 shared expert is intentionally
3593                    // tried before the generic uniform-bank graph builder.
3594                    // The latter correctly refuses its ragged Q2/Q4 widths;
3595                    // this narrow descriptor keeps the router and selected
3596                    // routed experts device-resident inside a bounded page.
3597                    let ffn = if let Some(flint) = metal_flint_moe_graph_parts(m, self.hidden_size, scan)
3598                    {
3599                        MetalFfn::FlintMoe(flint)
3600                    } else if let Some(moe) = metal_moe_graph_parts(m, self.hidden_size) {
3601                        MetalFfn::Moe(moe)
3602                    } else {
3603                        if block_diag {
3604                            eprintln!(
3605                                "block-graph: L{scan} MoE outside the graph contract — run ends"
3606                            );
3607                        }
3608                        break;
3609                    };
3610                    if let QTensor::Mapped { model, .. } = &m.experts[0].gate_proj {
3611                        model_ref.get_or_insert_with(|| model.clone());
3612                    }
3613                    ffn
3614                }
3615                _ => {
3616                    if block_diag {
3617                        eprintln!("block-graph: L{scan} non-graph FFN — run ends");
3618                    }
3619                    break;
3620                }
3621            };
3622            match &lw.attn {
3623                AttnKind::LinearGdn(w) if self.gdn_cfg.is_some() => {
3624                    let parts = (
3625                        w.in_proj_qkv.metal_graph_parts(),
3626                        w.in_proj_z.metal_graph_parts(),
3627                        w.in_proj_a.f32_parts(),
3628                        w.in_proj_b.f32_parts(),
3629                        w.out_proj.metal_graph_parts(),
3630                    );
3631                    let (Some(qkv), Some(z), Some(a), Some(b), Some(out)) = parts else {
3632                        if block_diag {
3633                            eprintln!(
3634                                "block-graph: L{scan} GDN parts refused (qkv={} z={} a_f32={} b_f32={} out={})",
3635                                w.in_proj_qkv.metal_graph_parts().is_some(),
3636                                w.in_proj_z.metal_graph_parts().is_some(),
3637                                w.in_proj_a.f32_parts().is_some(),
3638                                w.in_proj_b.f32_parts().is_some(),
3639                                w.out_proj.metal_graph_parts().is_some(),
3640                            );
3641                        }
3642                        break;
3643                    };
3644                    if let QTensor::Mapped { model, .. } = &w.in_proj_qkv {
3645                        model_ref.get_or_insert_with(|| model.clone());
3646                    }
3647                    let gl = GdnGpuLayer {
3648                        mhc: crate::sensenova::graph_mhc(self.mhc.as_deref(), self.phys_layer(scan)),
3649                        attn_norm: &lw.input_norm,
3650                        post_norm: &lw.post_norm,
3651                        qkv,
3652                        z,
3653                        a,
3654                        b,
3655                        out,
3656                        ffn,
3657                        conv1d: &w.conv1d,
3658                        a_log: &w.a_log,
3659                        dt_bias: &w.dt_bias,
3660                        gnorm: &w.norm,
3661                    };
3662                    // a run ends at a layer a DFlash drafter reads: its output is kept there
3663                    let cut = scan > 0 && self.dflash.as_ref().is_some_and(|d| d.g.taps.contains(&(scan - 1)));
3664                    match plan.last_mut() {
3665                        Some(Item::Gdn { run, .. }) if !cut => run.push(gl),
3666                        _ => plan.push(Item::Gdn {
3667                            run: vec![gl],
3668                            first: scan,
3669                        }),
3670                    }
3671                }
3672                AttnKind::ShortConv(w) if self.short_conv_cfg.is_some() => {
3673                    let (Some(inp), Some(out)) =
3674                        (w.in_proj.metal_graph_parts(), w.out_proj.metal_graph_parts())
3675                    else {
3676                        if block_diag {
3677                            eprintln!("block-graph: L{scan} short-conv parts refused");
3678                        }
3679                        break;
3680                    };
3681                    if let QTensor::Mapped { model, .. } = &w.in_proj {
3682                        model_ref.get_or_insert_with(|| model.clone());
3683                    }
3684                    let sl = SconvGpuLayer {
3685                        attn_norm: &lw.input_norm,
3686                        post_norm: &lw.post_norm,
3687                        in_proj: inp,
3688                        taps: &w.conv,
3689                        out,
3690                        attn_out_norm: lw.attn_out_norm.as_deref(),
3691                        ffn_out_norm: lw.ffn_out_norm.as_deref(),
3692                        ffn,
3693                    };
3694                    match plan.last_mut() {
3695                        Some(Item::Sconv { run, .. }) => run.push(sl),
3696                        _ => plan.push(Item::Sconv {
3697                            run: vec![sl],
3698                            first: scan,
3699                        }),
3700                    }
3701                }
3702                AttnKind::Full {
3703                    wq,
3704                    wk,
3705                    wv,
3706                    wo,
3707                    q_norm,
3708                    k_norm,
3709                    output_gate,
3710                    softplus_gate,
3711                    bias,
3712                } if (!self.kv_cache.layers[scan].o1_sealed()
3713                    // Sealed o1 stays plannable when the Metal o1 port
3714                    // is on: full_gpu attends through the device state,
3715                    // and any refusal falls to the sandwich, whose CPU
3716                    // core routes sealed layers through the nystrom step.
3717                    || std::env::var("CMF_O1_METAL").as_deref() == Ok("1")
3718                    || self.o1_on_graph())
3719                    // A projected output gate: Spark-X2.5's per-head
3720                    // sigmoid form only (Laguna's softplus gate is
3721                    // unmeasured on these paths and keeps the CPU walk).
3722                    && softplus_gate
3723                        .as_ref()
3724                        .is_none_or(|(_, per_head)| *per_head && self.proj_gate_sigmoid) =>
3725                {
3726                    let parts = (
3727                        wq.metal_graph_parts(),
3728                        wk.metal_graph_parts(),
3729                        wv.metal_graph_parts(),
3730                        wo.metal_graph_parts(),
3731                    );
3732                    let (Some(pq), Some(pk), Some(pv), Some(po)) = parts else {
3733                        break;
3734                    };
3735                    if let QTensor::Mapped { model, .. } = wq {
3736                        model_ref.get_or_insert_with(|| model.clone());
3737                    }
3738                    let cache = &self.kv_cache.layers[scan];
3739                    // O(1) layer on Metal: the device attends through the
3740                    // sealed Nystrom state (opt-in while the port proves
3741                    // itself). Unsealed -> sandwich path = the CPU o1 step.
3742                    let o1_metal = cache.o1.is_some()
3743                        && (std::env::var("CMF_O1_METAL").as_deref() == Ok("1") || self.o1_on_graph())
3744                        && cache.o1_views().is_some();
3745                    // The device attend takes the layer's window and RoPE
3746                    // table, and the per-head gate from f32 rows; a gate
3747                    // held otherwise sandwiches.
3748                    let head_gate_w = softplus_gate
3749                        .as_ref()
3750                        .and_then(|(g, _)| g.f32_parts())
3751                        .filter(|&(_, r, c)| r == self.num_heads && c == self.hidden_size)
3752                        .map(|(d, _, _)| d);
3753                    // Gemma-4's global layers are 512 wide over one KV head
3754                    // (the `gemma4` 16-slot kernels, `CMF_METAL_GEMMA4_W16`).
3755                    let (nkv_g, hd_g) = if gemma4 {
3756                        let (a, b, _) = self.layer_geom(scan);
3757                        (a, b)
3758                    } else {
3759                        (self.num_kv_heads, self.head_dim)
3760                    };
3761                    let full_gpu = attend_contract
3762                        && softplus_gate.is_none() == head_gate_w.is_none()
3763                        && cache.mode == crate::kv_cache::KvMode::F32
3764                        && (cache.o1.is_none() || o1_metal)
3765                        && bias.is_none()
3766                        && (hd_g <= 256 || crate::gpu_metal::gemma4::w16_on())
3767                        && pq.1 == self.num_heads * hd_g * (1 + *output_gate as usize)
3768                        && pk.1 == nkv_g * hd_g
3769                        && pv.1 == nkv_g * hd_g
3770                        && po.2 == self.num_heads * hd_g;
3771                    // An mHC layer needs the device attend (the CPU-attend
3772                    // sandwich has no stream hand-off), and so does a DASH
3773                    // layer: its router state lives on the device.
3774                    if !full_gpu && (self.mhc_layer(scan) || self.dash.is_some()) {
3775                        break;
3776                    }
3777                    plan.push(Item::Attn {
3778                        l: AttnGpuLayer {
3779                            mhc: crate::sensenova::graph_mhc(self.mhc.as_deref(), self.phys_layer(scan)),
3780                            attn_norm: &lw.input_norm,
3781                            post_norm: &lw.post_norm,
3782                            wq: pq,
3783                            wk: pk,
3784                            wv: pv,
3785                            wo: po,
3786                            ffn,
3787                            attn_out_norm: lw.attn_out_norm.as_deref(),
3788                            ffn_out_norm: lw.ffn_out_norm.as_deref(),
3789                            layer_scale: lw.layer_scale,
3790                        },
3791                        li: scan,
3792                        q_norm: q_norm.as_deref(),
3793                        k_norm: k_norm.as_deref(),
3794                        output_gate: *output_gate,
3795                        proj_gate: softplus_gate.as_ref().map(|(g, per_head)| (g, *per_head)),
3796                        head_gate_w,
3797                        bias: bias
3798                            .as_ref()
3799                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
3800                        full_gpu,
3801                    });
3802                }
3803                _ => break,
3804            }
3805            scan += 1;
3806        }
3807        // SenseNova-Loop: the mHC streams live on the device only inside one
3808        // graph, so a graph may neither enter a range midway nor stop
3809        // inside one (the host walks such a stretch with its own streams).
3810        if let Some(m) = self.mhc.as_deref() {
3811            let inside = |li: usize| m.on(self.phys_layer(li));
3812            let starts_mid = inside(start) && !m.enters(self.phys_layer(start));
3813            let stops_mid = scan > start && inside(scan - 1) && !m.leaves(self.phys_layer(scan - 1));
3814            if starts_mid || stops_mid {
3815                if std::env::var("CMF_GRAPH_DBG").is_ok() {
3816                    eprintln!("q1-graph: [{start}, {scan}) would split an mHC range — host path");
3817                }
3818                return start;
3819            }
3820        }
3821        // Unlimited-OCR: all of it or none of it, the host's router state and
3822        // the device's are not interchangeable (`CMF_GPU=wgpu` keeps the host's).
3823        if self.dash.is_some()
3824            && (start != 0 || scan != self.num_layers || crate::gpu::backend_name() != "metal")
3825        {
3826            return start;
3827        }
3828        let Some(model) = model_ref else {
3829            if std::env::var("CMF_GRAPH_DBG").is_ok() {
3830                eprintln!("q1-graph: no model ref (start {start}, scanned to {scan})");
3831            }
3832            if self.graph_head_required {
3833                self.fail_metal_graph("native graph has no mapped model reference");
3834            }
3835            return start;
3836        };
3837        if plan.is_empty() {
3838            if std::env::var("CMF_GRAPH_DBG").is_ok() {
3839                eprintln!("q1-graph: empty plan at layer {start}");
3840            }
3841            if self.graph_head_required {
3842                self.fail_metal_graph("native graph plan is empty");
3843            }
3844            return start;
3845        }
3846        let has_moe = plan.iter().any(|it| match it {
3847            Item::Gdn { run, .. } => run
3848                .iter()
3849                .any(|l| matches!(l.ffn, MetalFfn::Moe(_) | MetalFfn::FlintMoe(_))),
3850            Item::Sconv { run, .. } => run
3851                .iter()
3852                .any(|l| matches!(l.ffn, MetalFfn::Moe(_) | MetalFfn::FlintMoe(_))),
3853            Item::Attn { l, .. } => matches!(l.ffn, MetalFfn::Moe(_) | MetalFfn::FlintMoe(_)),
3854        });
3855        let has_flint_moe = plan.iter().any(|it| match it {
3856            Item::Gdn { run, .. } => run.iter().any(|l| matches!(l.ffn, MetalFfn::FlintMoe(_))),
3857            Item::Sconv { run, .. } => run.iter().any(|l| matches!(l.ffn, MetalFfn::FlintMoe(_))),
3858            Item::Attn { l, .. } => matches!(l.ffn, MetalFfn::FlintMoe(_)),
3859        });
3860        let metal_working_set = crate::gpu_metal::working_set_bytes();
3861        let metal_max_buffer = crate::gpu_metal::max_buffer_bytes();
3862        let model_bytes = model.primary_bytes().len() as u64;
3863        // Flint q2 can sit below recommendedMaxWorkingSetSize on a 24 GB
3864        // M4 yet still exceed maxBufferLength. In that case a normal graph
3865        // would manufacture overlapping whole-file WeightArena windows;
3866        // treat it as the same bounded-page requirement rather than letting
3867        // the generic graph reintroduce broad residency.
3868        let needs_bounded_pager = (metal_working_set != 0 && model_bytes > metal_working_set)
3869            || (metal_max_buffer != 0 && model_bytes > metal_max_buffer);
3870        // An oversized MoE mmap normally has to decline: the jobs kernels
3871        // bind all WeightArena windows.  The opt-in pager takes a different,
3872        // bounded route: a *complete sequence of logical layers* is put in
3873        // one transient no-copy page, graph-finished, dropped, then the outer
3874        // layer loop calls us again for the next page.  That preserves exact
3875        // hidden/GDN/KV handoff while replacing ~40 host-routed expert waits
3876        // with a few page-boundary syncs.  Never use it for a fused-head NLL
3877        // request: that contract explicitly requires a single whole graph.
3878        let pager_cap = if !has_moe {
3879            None
3880        } else if has_flint_moe {
3881            // Do not let generic `CMF_METAL_MOE_PAGER` turn the experimental
3882            // full-bank Flint graph on. Its direct selected-view pager stays
3883            // independently automatic; this path needs its own opt-in.
3884            crate::gpu_metal::flint_moe_pager_cap_bytes(&model)
3885        } else {
3886            crate::gpu_metal::moe_pager_cap_bytes()
3887        };
3888        let pager_eligible =
3889            pager_cap.is_some() && !self.graph_head_required && needs_bounded_pager;
3890        let mut pager_span: Option<(usize, usize)> = None;
3891        if pager_eligible {
3892            let cap = pager_cap.expect("checked above");
3893            // When this page reaches the true model end, include the fused
3894            // lm_head too.  Otherwise `lm_head_ok` would correctly refuse a
3895            // binding outside the page after the layers had already run.
3896            let tail_span = (self.graph_want_logits
3897                && upto.is_none()
3898                && scan == self.num_layers
3899                && std::env::var("CMF_GPU_LMHEAD")
3900                    .map(|v| v != "0")
3901                    .unwrap_or(true))
3902            .then(|| self.weights.lm_head.metal_graph_parts())
3903            .flatten()
3904            .and_then(|lm| crate::gpu_metal::model_tensor_span(&model, lm.0));
3905            let add_layer_span = |span: Option<(usize, usize)>, li: usize| {
3906                let (lo, hi) = crate::gpu_metal::model_layer_span(&model, self.phys_layer(li))?;
3907                Some(match span {
3908                    Some((cur_lo, cur_hi)) => (cur_lo.min(lo), cur_hi.max(hi)),
3909                    None => (lo, hi),
3910                })
3911            };
3912            let page_span = |span: (usize, usize), include_tail: bool| {
3913                let (mut lo, mut hi) = span;
3914                if include_tail {
3915                    if let Some((tail_lo, tail_hi)) = tail_span {
3916                        lo = lo.min(tail_lo);
3917                        hi = hi.max(tail_hi);
3918                    }
3919                }
3920                crate::gpu_metal::page_round_span(lo, hi)
3921            };
3922            let mut selected = 0usize;
3923            let mut selected_span: Option<(usize, usize)> = None;
3924            // `Item::Gdn` is built as a maximal run so the normal resident
3925            // graph can batch its recurrent state work.  A physical CMF can
3926            // nevertheless place that whole run across a page cap while each
3927            // logical layer fits.  Split *only the final admitted run* at a
3928            // layer boundary: the next outer-loop call rebuilds the remaining
3929            // suffix, preserving hidden/state handoff and keeping the normal
3930            // long-run batching within every page.
3931            let mut gdn_prefix: Option<(usize, usize)> = None;
3932            'items: for (i, item) in plan.iter().enumerate() {
3933                match item {
3934                    // Short-conv runs are not paged (no oversized
3935                    // short-conv MoE has been measured): the page ends.
3936                    Item::Sconv { .. } => break,
3937                    Item::Attn { li, .. } => {
3938                        let Some(span) = add_layer_span(selected_span, *li) else {
3939                            break;
3940                        };
3941                        let Some((page_lo, page_hi)) = page_span(span, i + 1 == plan.len()) else {
3942                            break;
3943                        };
3944                        if page_hi - page_lo > cap {
3945                            break;
3946                        }
3947                        selected = i + 1;
3948                        selected_span = Some((page_lo, page_hi));
3949                    }
3950                    Item::Gdn { first, run } => {
3951                        // Preserve a complete recurrent run whenever it can
3952                        // occupy a page on its own.  If the preceding items
3953                        // merely used the remaining cap, close that page and
3954                        // let the next q1 invocation retain the full run.
3955                        // Prefix-splitting is only for a run that genuinely
3956                        // cannot fit an empty page.
3957                        let mut whole = None;
3958                        for take in 1..=run.len() {
3959                            whole = add_layer_span(whole, *first + take - 1);
3960                            if whole.is_none() {
3961                                break;
3962                            }
3963                        }
3964                        let whole_fits_empty_page = whole
3965                            .and_then(|span| page_span(span, false))
3966                            .is_some_and(|(lo, hi)| hi - lo <= cap);
3967                        if whole_fits_empty_page {
3968                            let mut span = selected_span;
3969                            for take in 1..=run.len() {
3970                                let Some(next) = add_layer_span(span, *first + take - 1) else {
3971                                    break 'items;
3972                                };
3973                                span = Some(next);
3974                            }
3975                            let Some(span) = span else {
3976                                break;
3977                            };
3978                            let Some((page_lo, page_hi)) = page_span(span, i + 1 == plan.len())
3979                            else {
3980                                break;
3981                            };
3982                            if page_hi - page_lo > cap {
3983                                break;
3984                            }
3985                            selected = i + 1;
3986                            selected_span = Some((page_lo, page_hi));
3987                            continue;
3988                        }
3989                        if selected != 0 {
3990                            break;
3991                        }
3992                        let mut span = None;
3993                        let mut best: Option<(usize, (usize, usize))> = None;
3994                        for take in 1..=run.len() {
3995                            let Some(next) = add_layer_span(span, *first + take - 1) else {
3996                                break;
3997                            };
3998                            // A partial final run cannot encode the lm_head;
3999                            // only its complete form above may include it.
4000                            let Some((page_lo, page_hi)) = page_span(next, false) else {
4001                                break;
4002                            };
4003                            if page_hi - page_lo > cap {
4004                                break;
4005                            }
4006                            span = Some((page_lo, page_hi));
4007                            best = Some((take, (page_lo, page_hi)));
4008                        }
4009                        let Some((take, page)) = best else {
4010                            break;
4011                        };
4012                        selected = i + 1;
4013                        selected_span = Some(page);
4014                        if take != run.len() {
4015                            gdn_prefix = Some((i, take));
4016                            break 'items;
4017                        }
4018                    }
4019                }
4020            }
4021            if selected != 0 {
4022                if let Some((item, take)) = gdn_prefix {
4023                    match &mut plan[item] {
4024                        Item::Gdn { run, .. } => run.truncate(take),
4025                        Item::Sconv { .. } | Item::Attn { .. } => {
4026                            unreachable!("only a GDN run is splittable")
4027                        }
4028                    }
4029                }
4030                let (page_lo, page_hi) = selected_span.expect("selected page span");
4031                tracing::info!(
4032                    page_start = page_lo,
4033                    page_end = page_hi,
4034                    page_mb = (page_hi - page_lo) / (1024 * 1024),
4035                    cap_mb = cap / (1024 * 1024),
4036                    graph_items = selected,
4037                    "native Metal MoE graph uses transient bounded weight page"
4038                );
4039                plan.truncate(selected);
4040                pager_span = Some((page_lo, page_hi));
4041            } else {
4042                tracing::warn!(
4043                    cap_mb = cap / (1024 * 1024),
4044                    "native Metal MoE pager declined: one graph item does not fit its safe page cap"
4045                );
4046            }
4047        }
4048        // A native MoE graph binds every WeightArena window to its jobs
4049        // kernels. On UMA, an mmap that already exceeds the driver's
4050        // recommended working set will therefore fail after admission, when
4051        // some recurrent/KV scratch has already been touched. Decline before
4052        // allocating/encoding the graph instead; the ordinary per-operation
4053        // route remains available and only materializes the needed window.
4054        // Do not apply this to dense graphs: they bind one projection at a
4055        // time and do not have the MoE jobs' all-window lifetime.
4056        if has_moe && needs_bounded_pager && pager_span.is_none() {
4057            tracing::info!(
4058                model_bytes,
4059                metal_working_set,
4060                "native Metal MoE graph declined before allocation"
4061            );
4062            self.note_graph_decline("metal block graph", MOE_WORKING_SET_REASON);
4063            if self.graph_head_required {
4064                self.fail_metal_graph(MOE_WORKING_SET_REASON);
4065            }
4066            return start;
4067        }
4068        let has_gdn = plan.iter().any(|it| matches!(it, Item::Gdn { .. }));
4069        let dev_attend = attend_contract
4070            && (self.head_dim <= 128
4071                || has_moe
4072                // A GDN hybrid attends on a quarter of its layers: the
4073                // hd>128 caution was measured on pure-dense models where
4074                // gqa_attend dominates, and on Qwen3.8-27B (hd 256, 48
4075                // GDN + 16 attn) the sandwich costs 2x the whole decode
4076                // (1.2 vs 2.21 tok/s measured before the arena fix).
4077                || (self.head_dim <= 256 && has_gdn)
4078                // Sliding-window layers bound most attends by the window:
4079                // Spark-X2.5-1.7B q4tp on the M4 decodes 67 tok/s
4080                // device-attended against 23 sandwiched (28 syncs/token).
4081                || (self.head_dim <= 256 && swa_graph)
4082                || attend_mode == "force"
4083                || attend_mode == "256");
4084        if !dev_attend {
4085            for it in &mut plan {
4086                if let Item::Attn { li, full_gpu, .. } = it {
4087                    // The hd>128 policy is about gqa_attend; an o1 layer
4088                    // attends through its own kernel set.
4089                    let keep_o1 = self.kv_cache.layers[*li].o1.is_some()
4090                        && std::env::var("CMF_O1_METAL").as_deref() == Ok("1");
4091                    if !keep_o1 {
4092                        *full_gpu = false;
4093                    }
4094                }
4095            }
4096        }
4097        if std::env::var("CMF_GRAPH_DBG").is_ok() {
4098            use std::sync::atomic::{AtomicBool, Ordering};
4099            static SAID: AtomicBool = AtomicBool::new(false);
4100            if !SAID.swap(true, Ordering::Relaxed) {
4101                let fg = plan
4102                    .iter()
4103                    .filter(|it| matches!(it, Item::Attn { full_gpu: true, .. }))
4104                    .count();
4105                let att = plan
4106                    .iter()
4107                    .filter(|it| matches!(it, Item::Attn { .. }))
4108                    .count();
4109                eprintln!(
4110                    "q1-graph: plan of {} items from layer {start} to {scan} | dev_attend={dev_attend} full_gpu {fg}/{att} | hd={} rd={} nkv={} nh={}",
4111                    plan.len(),
4112                    self.head_dim,
4113                    self.rotary_dim,
4114                    self.num_kv_heads,
4115                    self.num_heads,
4116                );
4117            }
4118        }
4119        let dims = GraphDims {
4120            hidden: self.hidden_size,
4121            eps: self.rms_eps as f32,
4122            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
4123        };
4124        // The outer `forward_layers_span` scope is one logical token.  This
4125        // guard starts at q1_graph_gpu entry and ends after all page readback,
4126        // so a multi-page token cannot be reported as several whole tokens.
4127        let mut pager_profile_page = pager_span.map(|(page_lo, page_hi)| {
4128            crate::gpu_metal::MoePagerPageScope::new(
4129                _mt0,
4130                position,
4131                start,
4132                page_lo,
4133                page_hi,
4134                // `pager_span` is selected only after a cap was admitted;
4135                // keep the profiler observational if that invariant is ever
4136                // loosened rather than introducing a new inference panic.
4137                pager_cap.unwrap_or(0),
4138            )
4139        });
4140        let graph_new = match pager_span {
4141            Some((page_lo, page_hi)) => TokenGraph::new_paged(&model, dims, h, page_lo, page_hi),
4142            None => TokenGraph::new(&model, dims, h),
4143        };
4144        let Some(mut graph) = graph_new else {
4145            if self.graph_head_required {
4146                self.fail_metal_graph("native TokenGraph allocation refused");
4147            }
4148            return start;
4149        };
4150        if swa_graph && self.head_dim > 128 {
4151            // Spark-X2.5 (hd 256, 4 Q heads per KV head): the GQA-shared
4152            // split-K attend reads each K/V row once for the group instead
4153            // of once per head plus the importance re-read — at depth 1000
4154            // on the M4, 59.5 tok/s against 50.0 with the per-head kernel
4155            // up to the default 512 (every sliding layer sits at <= 512).
4156            // From the second position on and in 32-position blocks (more
4157            // threadgroups in flight for a latency-bound walk): Spark-X2.6
4158            // q4tp decode 0.86x the GPU time short and 0.88x at depth 1000,
4159            // q8_2f 0.91x / 0.92x (in-process A/B, M4).
4160            graph.set_attend_blk(1, 32);
4161        }
4162        let gcfg = self.gdn_cfg.map(|cfg| GdnGpuCfg {
4163            nv: cfg.num_v_heads,
4164            nk: cfg.num_k_heads,
4165            dk: cfg.key_head_dim,
4166            dv: cfg.value_head_dim,
4167            kk: cfg.conv_kernel,
4168            hidden: self.hidden_size,
4169            inter: self.intermediate_size,
4170            c_dim: cfg.conv_dim(),
4171            eps: cfg.rms_eps as f32,
4172            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
4173        });
4174        // Validate the whole plan BEFORE encoding anything: after the
4175        // first sync a refused layer would leave the token
4176        // half-executed, so truncate to the provably encodable prefix.
4177        let mut valid = 0usize;
4178        let mut end = start;
4179        crate::gpu::stageprof(1, _mt0.elapsed()); // конец планирования
4180        if std::env::var("CMF_PLAN_DUMP").is_ok() {
4181            static ONCE: std::sync::Once = std::sync::Once::new();
4182            ONCE.call_once(|| {
4183                for it in &plan {
4184                    match it {
4185                        Item::Gdn { first, run } => {
4186                            eprintln!("plan: Gdn first={first} len={}", run.len())
4187                        }
4188                        Item::Sconv { first, run } => {
4189                            eprintln!("plan: Sconv first={first} len={}", run.len())
4190                        }
4191                        Item::Attn { li, full_gpu, .. } => {
4192                            eprintln!("plan: Attn li={li} full_gpu={full_gpu}")
4193                        }
4194                    }
4195                }
4196            });
4197        }
4198        for item in &plan {
4199            let ok = match item {
4200                Item::Gdn { run, .. } => gcfg
4201                    .as_ref()
4202                    .map(|gc| run.iter().all(|l| graph.gdn_ok(l, gc)))
4203                    .unwrap_or(false),
4204                Item::Sconv { run, .. } => self
4205                    .short_conv_cfg
4206                    .is_some_and(|sc| run.iter().all(|l| graph.sconv_ok(l, sc.kernel))),
4207                Item::Attn { l, .. } => graph.attn_ok(l),
4208            };
4209            if !ok {
4210                if block_diag {
4211                    eprintln!(
4212                        "block-graph: plan item {} ({}) failed graph preflight",
4213                        valid,
4214                        match item {
4215                            Item::Gdn { run, first } => format!("GDN run L{first}+{}", run.len()),
4216                            Item::Sconv { run, first } => {
4217                                format!("short-conv run L{first}+{}", run.len())
4218                            }
4219                            Item::Attn { li, .. } => format!("Attn L{li}"),
4220                        }
4221                    );
4222                }
4223                break;
4224            }
4225            valid += 1;
4226            end += match item {
4227                Item::Gdn { run, .. } => run.len(),
4228                Item::Sconv { run, .. } => run.len(),
4229                Item::Attn { .. } => 1,
4230            };
4231        }
4232        plan.truncate(valid);
4233        if plan.is_empty() {
4234            if self.graph_head_required {
4235                self.fail_metal_graph("native graph preflight produced no valid items");
4236            }
4237            return start;
4238        }
4239
4240        if self.graph_head_required && (upto.is_some() || end != self.num_layers) {
4241            self.fail_metal_graph("fused-head NLL requires a complete 64-layer graph");
4242            return start;
4243        }
4244
4245        // Plain dense decode (every item a device-attended full-attention
4246        // layer with a dense FFN, no O(1) state): the only plan shape the
4247        // masked-nibble q4tp matvec and the concurrent layer encoder were
4248        // measured on (MiniCPM5-2B, Qwen3-0.6B on the M4). Hybrids, MoE and
4249        // o1 layers keep the historical serial path bit for bit.
4250        // Every projection must be ONE dispatch (q1t adds an overlay pass,
4251        // Prism q2tp a transform pass — dependent pairs a concurrent
4252        // encoder would race).
4253        let one_pass = |t: (usize, usize, usize)| {
4254            use cortiq_core::TensorDtype as D;
4255            matches!(
4256                model.tensors[t.0].dtype,
4257                D::Q4TiledP | D::Q4Tiled | D::Q4Block | D::Q8Row | D::Q8_2f | D::Q1 | D::Q1G
4258            )
4259        };
4260        let dense_fast = plan.iter().all(|it| match it {
4261            Item::Attn {
4262                l, li, full_gpu, ..
4263            } => {
4264                *full_gpu
4265                    && self.kv_cache.layers[*li].o1.is_none()
4266                    && [l.wq, l.wk, l.wv, l.wo].into_iter().all(one_pass)
4267                    && match l.ffn {
4268                        MetalFfn::Dense { gate, up, down, .. } => {
4269                            one_pass(gate) && one_pass(up) && one_pass(down)
4270                        }
4271                        _ => false,
4272                    }
4273            }
4274            // A short-conv run encodes serially in its own encoder: its
4275            // one-pass projections take the same matvec levers.
4276            Item::Sconv { run, .. } => run.iter().all(|l| {
4277                one_pass(l.in_proj)
4278                    && one_pass(l.out)
4279                    && match l.ffn {
4280                        MetalFfn::Dense { gate, up, down, .. } => {
4281                            one_pass(gate) && one_pass(up) && one_pass(down)
4282                        }
4283                        _ => false,
4284                    }
4285            }),
4286            Item::Gdn { .. } => false,
4287        });
4288        // MoE decode with every layer device-attended (Mellum2.1): the
4289        // routed experts' jobs ladder and the q8_2f attention projections
4290        // take their measured levers (`MOE_*`, `DENSE_Q8R4`).
4291        let moe_plan = !dense_fast
4292            && plan.iter().all(|it| match it {
4293                Item::Attn {
4294                    l, li, full_gpu, ..
4295                } => {
4296                    *full_gpu
4297                        && self.kv_cache.layers[*li].o1.is_none()
4298                        && (matches!(l.ffn, MetalFfn::Moe(_) | MetalFfn::FlintMoe(_))
4299                            || self.dash.is_some())
4300                }
4301                Item::Gdn { .. } | Item::Sconv { .. } => false,
4302            });
4303        let ab = crate::gpu_metal::dense_ab_arm().filter(|_| dense_fast || moe_plan);
4304        if block_diag {
4305            use std::sync::atomic::{AtomicBool, Ordering};
4306            static SAID_AB: AtomicBool = AtomicBool::new(false);
4307            if !SAID_AB.swap(true, Ordering::Relaxed) {
4308                eprintln!("q1-graph: dense_fast={dense_fast} moe_plan={moe_plan} ab={ab:?}");
4309            }
4310        }
4311        let _mv_fast = match ab {
4312            Some((bits, _)) => {
4313                graph.set_dense_concurrent_raw(bits & crate::gpu_metal::DENSE_CONC != 0);
4314                crate::gpu_metal::MvFastGuard::set_raw(bits)
4315            }
4316            None if moe_plan => {
4317                graph.set_dense_concurrent(
4318                    crate::gpu_metal::MOE_PLAN_BITS & crate::gpu_metal::DENSE_CONC != 0,
4319                );
4320                crate::gpu_metal::MvFastGuard::set_bits(crate::gpu_metal::MOE_PLAN_BITS)
4321            }
4322            None => {
4323                graph.set_dense_concurrent(dense_fast);
4324                // The four-row q8_2f matvec (same per-row sum order, text
4325                // unchanged): in-process A/B on the M4, token time 0.81x on
4326                // MiniCPM5-2B, 0.78x on Minico-M1, 0.85x on MNN-Pocket-0.3B;
4327                // Spark-X2.5 1.7B 40.5 against 27.7 tok/s. `CMF_Q8_R4=0` closes it.
4328                let _ = swa_graph;
4329                crate::gpu_metal::MvFastGuard::set_bits(if dense_fast {
4330                    crate::gpu_metal::DENSE_MV | crate::gpu_metal::DENSE_FUSE | crate::gpu_metal::DENSE_Q8R4
4331                } else {
4332                    0
4333                })
4334            }
4335        };
4336
4337        // RoPE table and rotary width are per layer (`layer_inv_freq`,
4338        // `layer_geom`) inside the loop below.
4339        let pool = self.pool.clone();
4340        let (nh, nkv, hd, hs, eps) = (
4341            self.num_heads,
4342            self.num_kv_heads,
4343            self.head_dim,
4344            self.hidden_size,
4345            self.rms_eps,
4346        );
4347        let norm_style = self.norm_style;
4348        let gemma = norm_style == cortiq_core::NormStyle::Gemma;
4349        let want = self.gdn_cfg.map(|c| c.state_len()).unwrap_or(0);
4350        let kv_id = self.graph_kv_id;
4351        // GDN runs whose states await readback after the next sync
4352        // (device-attended layers add no sync, so several may stack).
4353        let mut pending: Vec<(usize, usize)> = Vec::new();
4354        // Device-attended layers: their K/V/imp are pulled from the
4355        // mirror after the final sync.
4356        let mut dev_attn: Vec<(usize, usize, usize)> = Vec::new();
4357        // The layers a DFlash drafter reads, kept as the token passes them
4358        // (a whole token in one graph only).
4359        let taps: Vec<usize> = match &self.dflash {
4360            Some(d) if start == 0 && end == self.num_layers => d.g.taps.clone(),
4361            _ => Vec::new(),
4362        };
4363        let mut tapped = 0usize;
4364        for item in &plan {
4365            let _xt0 = std::time::Instant::now();
4366            let _xkind: u32 = match item {
4367                Item::Gdn { .. } | Item::Sconv { .. } => 2,
4368                Item::Attn { .. } => 3,
4369            };
4370            // Looped Transformer: insert on-device norm at loop boundaries.
4371            if self.loop_final_norm {
4372                let item_start = match item {
4373                    Item::Gdn { first, .. } | Item::Sconv { first, .. } => *first,
4374                    Item::Attn { li, .. } => *li,
4375                };
4376                if item_start > start && self.is_loop_end(item_start - 1) {
4377                    graph.encode_loop_norm(&self.weights.final_norm);
4378                }
4379            }
4380            match item {
4381                Item::Gdn { run, first } => {
4382                    for l in &mut self.kv_cache.layers[*first..*first + run.len()] {
4383                        if l.linear_state.len() != want {
4384                            l.linear_state = vec![0f32; want];
4385                        }
4386                    }
4387                    let ro: Vec<&[f32]> = self.kv_cache.layers[*first..*first + run.len()]
4388                        .iter()
4389                        .map(|l| l.linear_state.as_slice())
4390                        .collect();
4391                    let _ig = std::time::Instant::now();
4392                    if !graph.encode_gdn_run(run, &ro, gcfg.as_ref().unwrap()) {
4393                        // Unreachable: the plan was validated above.
4394                        tracing::error!("q1 graph: GDN run refused after validation");
4395                        return start;
4396                    }
4397                    if let Some(slot) = taps.iter().position(|t| *t + 1 == *first + run.len()) {
4398                        tapped += graph.tap(slot, taps.len()) as usize;
4399                    }
4400                    // Early commit: the GPU starts the run while the
4401                    // CPU encodes the next layer (nothing to wait on).
4402                    graph.commit_kind = 2;
4403                    graph.commit();
4404                    crate::gpu::stageprof(0, _ig.elapsed());
4405                    pending.push((*first, run.len()));
4406                }
4407                Item::Sconv { run, first } => {
4408                    let sc = self.short_conv_cfg.expect("validated short-conv run");
4409                    for l in &mut self.kv_cache.layers[*first..*first + run.len()] {
4410                        if l.linear_state.len() != sc.state_len() {
4411                            l.linear_state = vec![0f32; sc.state_len()];
4412                        }
4413                    }
4414                    let ro: Vec<&[f32]> = self.kv_cache.layers[*first..*first + run.len()]
4415                        .iter()
4416                        .map(|l| l.linear_state.as_slice())
4417                        .collect();
4418                    if !graph.encode_sconv_run(run, &ro, sc.kernel) {
4419                        tracing::error!("q1 graph: short-conv run refused after validation");
4420                        return start;
4421                    }
4422                    graph.commit_kind = 2;
4423                    graph.commit();
4424                    pending.push((*first, run.len()));
4425                }
4426                Item::Attn {
4427                    l,
4428                    li,
4429                    q_norm,
4430                    k_norm,
4431                    output_gate,
4432                    proj_gate,
4433                    head_gate_w,
4434                    bias,
4435                    full_gpu,
4436                } => {
4437                    let _ia = std::time::Instant::now();
4438                    // This layer's attention geometry: its window, RoPE
4439                    // table and rotary width (Spark-X2.5 interleaves
4440                    // 512-window layers rotating all dims at θ 1e4 with
4441                    // full layers rotating a quarter at θ 5e6). Every model
4442                    // without sliding layers reads the global ones here.
4443                    let inv_freq_l = self.layer_inv_freq(*li);
4444                    let rd_l = self.layer_geom(*li).2;
4445                    let window_l = self.layer_window(*li);
4446                    let head_gate_w = *head_gate_w;
4447                    // This layer's KV heads and head width: Gemma-4's global
4448                    // layers (one 512-wide KV head) differ from the base.
4449                    let (nkv, hd) = if gemma4 {
4450                        let (a, b, _) = self.layer_geom(*li);
4451                        (a, b)
4452                    } else {
4453                        (nkv, hd)
4454                    };
4455                    // ── Fully device-resident attention: no sync at all.
4456                    if *full_gpu {
4457                        let cache = &self.kv_cache.layers[*li];
4458                        let o1p = if cache.o1.is_some() {
4459                            match cache.o1_views() {
4460                                Some(views) => Some(crate::gpu::O1AttnParams {
4461                                    views,
4462                                    epoch: self.o1_epoch,
4463                                }),
4464                                // Sealed state gone mid-run: sandwich.
4465                                None => None,
4466                            }
4467                        } else {
4468                            None
4469                        };
4470                        let o1_layer = cache.o1.is_some();
4471                        if o1_layer && o1p.is_none() {
4472                            // fall to the sandwich (CPU o1 step)
4473                        }
4474                        let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
4475                        let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
4476                        let cpu_stored = if o1_layer { 0 } else { cpu_k[0].len() / hd };
4477                        // A trimmed tail always holds the window the
4478                        // device attend reads (`first = rows + 1 − w`).
4479                        debug_assert!(
4480                            cache.base() == 0 || window_l.is_some_and(|w| cpu_stored + 1 >= w)
4481                        );
4482                        let dash_l = self.graph_dash(*li);
4483                        // A DASH row carries its own angles: position 1 over
4484                        // them is the rotation (`uocr::rope_angles`).
4485                        let (rope_at, rope_invf, rope_sc): (usize, &[f32], f32) = match self.dash.as_deref() {
4486                            Some(d) => (1, &d.angles, 1.0),
4487                            None => (position, &inv_freq_l, self.layer_rope_scale(*li)),
4488                        };
4489                        let p = crate::gpu::AttnDeviceParams {
4490                            kv_id,
4491                            layer: *li,
4492                            nh,
4493                            nkv,
4494                            hd,
4495                            rd: rd_l,
4496                            position: rope_at,
4497                            scale: self.attn_scale,
4498                            eps: eps as f32,
4499                            gemma,
4500                            late_qk_norm: self.qk_norm_after_rope,
4501                            output_gate: *output_gate,
4502                            q_norm: *q_norm,
4503                            k_norm: *k_norm,
4504                            inv_freq: rope_invf,
4505                            rope_scale: rope_sc,
4506                            cpu_k,
4507                            cpu_v,
4508                            cpu_stored,
4509                            cpu_gen: cache.generation(),
4510                            o1: o1p,
4511                            window: window_l,
4512                            softmax_sink: cache.sinks.as_deref(),
4513                            head_gate: head_gate_w,
4514                            v_norm: self.attn_v_norm,
4515                            dash: dash_l.as_ref(),
4516                        };
4517                        let o1_bad = o1_layer && p.o1.is_none();
4518                        if !o1_bad && graph.attn_device_ok(l, &p) && graph.encode_attn_device(l, &p)
4519                        {
4520                            // o1 layers leave no mirror row to pull.
4521                            if p.o1.is_none() {
4522                                dev_attn.push((*li, nkv, hd));
4523                            }
4524                            if let Some(slot) = taps.iter().position(|t| t == li) {
4525                                tapped += graph.tap(slot, taps.len()) as usize;
4526                            }
4527                            graph.commit_kind = 3;
4528                            graph.commit();
4529                            // The footer below is skipped by `continue`:
4530                            // account the device-attn item here or its
4531                            // cost hides from the stage profile entirely.
4532                            crate::gpu::stageprof(_xkind, _xt0.elapsed());
4533                            continue;
4534                        }
4535                        // Mirror refused (nothing encoded) → sandwich.
4536                    }
4537                    graph.encode_attn_prefix(l);
4538                    if let Err(err) = graph.sync_checked() {
4539                        self.fail_metal_graph(&err);
4540                        return start;
4541                    }
4542                    if !pending.is_empty() {
4543                        let idxs: Vec<usize> =
4544                            pending.drain(..).flat_map(|(f, n)| f..f + n).collect();
4545                        let mut outs: Vec<&mut [f32]> = self
4546                            .kv_cache
4547                            .layers
4548                            .iter_mut()
4549                            .enumerate()
4550                            .filter(|(i, _)| idxs.binary_search(i).is_ok())
4551                            .map(|(_, s)| s.linear_state.as_mut_slice())
4552                            .collect();
4553                        graph.read_states(&mut outs);
4554                    }
4555                    let mut q_raw = attention::take_buf(l.wq.1);
4556                    let mut k = attention::take_buf(l.wk.1);
4557                    let mut v = attention::take_buf(l.wv.1);
4558                    graph.read_qkv(&mut q_raw, &mut k, &mut v);
4559                    // Projected output gate: g = G·norm(h) on the host, off
4560                    // the normed input the prefix left on the device.
4561                    let mut gate_raw = proj_gate.map(|(gp, _)| {
4562                        let mut normed = attention::take_buf(hs);
4563                        graph.read_normed(&mut normed);
4564                        let mut raw = attention::take_buf(gp.rows());
4565                        gp.matvec(&normed, &mut raw, pool.as_deref());
4566                        attention::recycle_buf(&mut normed);
4567                        raw
4568                    });
4569                    let cfg = QwenAttnCfg {
4570                        mrope: None,
4571                        num_heads: nh,
4572                        num_kv_heads: nkv,
4573                        head_dim: hd,
4574                        hidden_size: hs,
4575                        position,
4576                        inv_freq: &inv_freq_l,
4577                        rotary_dim: rd_l,
4578                        scale: self.attn_scale,
4579                        softcap: self.attn_softcap,
4580                        window: window_l,
4581                        // Gemma-4 only (the front gate refuses V norm
4582                        // otherwise).
4583                        v_norm: self.attn_v_norm,
4584                        qk_norm_after_rope: self.qk_norm_after_rope,
4585                        gate_sigmoid: self.proj_gate_sigmoid,
4586                        q_norm: *q_norm,
4587                        k_norm: *k_norm,
4588                        output_gate: *output_gate,
4589                        softplus_gate: None,
4590                        rope_scale: self.layer_rope_scale(*li),
4591                        bias: *bias,
4592                        rms_eps: eps,
4593                        norm_style,
4594                        pool: pool.as_deref(),
4595                        v_head_dim: hd,
4596                        value_in: None,
4597                    };
4598                    // CMF_ATTN_ORACLE=1: diff the device attend against
4599                    // this CPU attend on identical inputs (bring-up).
4600                    let oracle = std::env::var("CMF_ATTN_ORACLE").as_deref() == Ok("1")
4601                        || std::env::var("CMF_ATTN_DUMP").is_ok();
4602                    let _ = full_gpu;
4603                    let oracle_in = oracle.then(|| (q_raw.clone(), k.clone(), v.clone()));
4604                    let mut ao = attention::qwen_attention_core(
4605                        q_raw,
4606                        k,
4607                        v,
4608                        &mut self.kv_cache.layers[*li],
4609                        &cfg,
4610                    );
4611                    // CMF_ATTN_DUMP=<dir>: this token's rope'd Q and the layer's whole
4612                    // K/V cache as raw f32 (offline attention-statistics probes:
4613                    // block bounds, mass concentration). Needs CMF_GPU_ATTEND=0.
4614                    if let Ok(dir) = std::env::var("CMF_ATTN_DUMP") {
4615                        if let Some((qr0, k0, v0)) = oracle_in.clone() {
4616                            let (cq, _cg, _ck, _cv) =
4617                                attention::finish_projection_debug(qr0, k0, v0, &cfg, position);
4618                            let cache = &self.kv_cache.layers[*li];
4619                            let n = cache.head_keys(0).len() / hd;
4620                            let mut bytes: Vec<u8> = Vec::new();
4621                            for v in [nh as u32, nkv as u32, hd as u32, n as u32, position as u32] {
4622                                bytes.extend_from_slice(&v.to_le_bytes());
4623                            }
4624                            for v in &cq {
4625                                bytes.extend_from_slice(&v.to_le_bytes());
4626                            }
4627                            for g in 0..nkv {
4628                                for v in cache.head_keys(g) {
4629                                    bytes.extend_from_slice(&v.to_le_bytes());
4630                                }
4631                            }
4632                            for g in 0..nkv {
4633                                for v in cache.head_values(g) {
4634                                    bytes.extend_from_slice(&v.to_le_bytes());
4635                                }
4636                            }
4637                            let _ =
4638                                std::fs::write(format!("{dir}/L{li}_pos{position}.bin"), &bytes);
4639                        }
4640                    }
4641                    if let Some((qr0, k0, v0)) =
4642                        oracle_in.filter(|_| std::env::var("CMF_ATTN_ORACLE").as_deref() == Ok("1"))
4643                    {
4644                        let (cq, _cg, ck, cv) =
4645                            attention::finish_projection_debug(qr0, k0, v0, &cfg, position);
4646                        let mut h_now = vec![0f32; hs];
4647                        graph.read_h(&mut h_now);
4648                        let cache = &self.kv_cache.layers[*li];
4649                        let n_after = cache.head_keys(0).len() / hd;
4650                        // A sealed O(1) cache may have no dense current-row
4651                        // entry. The oracle is a debug probe, so let it see
4652                        // zero stored exact rows instead of underflowing.
4653                        let stored = n_after.saturating_sub(1);
4654                        let cpu_k: Vec<&[f32]> = (0..nkv)
4655                            .map(|g| &cache.head_keys(g)[..stored * hd])
4656                            .collect();
4657                        let cpu_v: Vec<&[f32]> = (0..nkv)
4658                            .map(|g| &cache.head_values(g)[..stored * hd])
4659                            .collect();
4660                        let p = crate::gpu::AttnDeviceParams {
4661                            kv_id,
4662                            layer: *li,
4663                            nh,
4664                            nkv,
4665                            hd,
4666                            // The layer's own geometry, as the CPU attend
4667                            // above used it (the projected gate is applied
4668                            // after this probe on both sides).
4669                            rd: rd_l,
4670                            position,
4671                            scale: self.attn_scale,
4672                            eps: eps as f32,
4673                            gemma,
4674                            late_qk_norm: self.qk_norm_after_rope,
4675                            output_gate: *output_gate,
4676                            q_norm: *q_norm,
4677                            k_norm: *k_norm,
4678                            inv_freq: &inv_freq_l,
4679                            rope_scale: self.layer_rope_scale(*li),
4680                            cpu_k,
4681                            cpu_v,
4682                            cpu_stored: stored,
4683                            cpu_gen: cache.generation(),
4684                            o1: None,
4685                            window: window_l,
4686                            softmax_sink: cache.sinks.as_deref(),
4687                            head_gate: None,
4688                            v_norm: self.attn_v_norm,
4689                            dash: None,
4690                        };
4691                        if let Some((dq, dk, dv, dao)) = graph.debug_attn_device(l, &p, &h_now) {
4692                            let md = |a: &[f32], b: &[f32]| {
4693                                a.iter().zip(b).fold(0f32, |m, (x, y)| m.max((x - y).abs()))
4694                            };
4695                            let nn = |a: &[f32]| a.iter().map(|x| x * x).sum::<f32>().sqrt();
4696                            eprintln!(
4697                                "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}",
4698                                nn(&cq),
4699                                md(&cq, &dq),
4700                                nn(&ck),
4701                                md(&ck, &dk),
4702                                nn(&cv),
4703                                md(&cv, &dv),
4704                                nn(&ao),
4705                                md(&ao, &dao)
4706                            );
4707                        } else {
4708                            eprintln!("attn-oracle L{li}: device probe declined");
4709                        }
4710                    }
4711                    if let (Some(raw), Some((_, per_head))) = (gate_raw.as_deref(), *proj_gate) {
4712                        // V is as wide as the head (the front gate), so ao
4713                        // is nh·hd here, as in `qwen_attention`.
4714                        attention::apply_projected_gate(
4715                            &mut ao,
4716                            raw,
4717                            per_head,
4718                            hd,
4719                            self.proj_gate_sigmoid,
4720                        );
4721                    }
4722                    if let Some(mut raw) = gate_raw.take() {
4723                        attention::recycle_buf(&mut raw);
4724                    }
4725                    graph.encode_attn_suffix(l, &ao);
4726                    if let Some(slot) = taps.iter().position(|t| t == li) {
4727                        tapped += graph.tap(slot, taps.len()) as usize;
4728                    }
4729                    // Early commit: the GPU starts O+FFN while the CPU
4730                    // encodes the following GDN run / attention prefix.
4731                    graph.commit();
4732                    attention::recycle_buf(&mut ao);
4733                }
4734            }
4735
4736            crate::gpu::stageprof(_xkind, _xt0.elapsed());
4737        }
4738        // Ride the final norm + lm_head in the same command buffer when
4739        // this run reaches the model's end and the caller wants logits:
4740        // the separate per-op lm_head submit (a full round trip) folds
4741        // into the sync that already happens here.
4742        let mut lm_rows = None;
4743        if self.graph_want_logits
4744            && upto.is_none()
4745            && end == self.num_layers
4746            && std::env::var("CMF_GPU_LMHEAD")
4747                .map(|v| v != "0")
4748                .unwrap_or(true)
4749        {
4750            if let Some(lm) = self.weights.lm_head.metal_graph_parts() {
4751                if graph.lm_head_ok(lm) {
4752                    graph.encode_lm_head(&self.weights.final_norm, lm);
4753                    lm_rows = Some(lm.1);
4754                }
4755            }
4756        }
4757        if self.graph_head_required && lm_rows.is_none() {
4758            METAL_GRAPH_HEAD_MISS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4759            self.fail_metal_graph("fused graph head was requested but not encodable");
4760            return start;
4761        }
4762        let _sy0 = std::time::Instant::now();
4763        if let Err(err) = graph.sync_checked() {
4764            if let Some(profile) = pager_profile_page.as_mut() {
4765                profile.finish(start, graph.pager_page_stats(), "sync-error");
4766            }
4767            self.fail_metal_graph(&err);
4768            return start;
4769        }
4770        let _rs0 = std::time::Instant::now();
4771        if !pending.is_empty() {
4772            let idxs: Vec<usize> = pending.drain(..).flat_map(|(f, n)| f..f + n).collect();
4773            let mut outs: Vec<&mut [f32]> = self
4774                .kv_cache
4775                .layers
4776                .iter_mut()
4777                .enumerate()
4778                .filter(|(i, _)| idxs.binary_search(i).is_ok())
4779                .map(|(_, s)| s.linear_state.as_mut_slice())
4780                .collect();
4781            graph.read_states(&mut outs);
4782        }
4783        if std::env::var("CMF_GRAPH_HOSTPROF").as_deref() == Ok("1") {
4784            use std::sync::atomic::{AtomicU64, Ordering};
4785            static SY: AtomicU64 = AtomicU64::new(0);
4786            static RS: AtomicU64 = AtomicU64::new(0);
4787            static N: AtomicU64 = AtomicU64::new(0);
4788            SY.fetch_add((_rs0 - _sy0).as_nanos() as u64, Ordering::Relaxed);
4789            RS.fetch_add(_rs0.elapsed().as_nanos() as u64, Ordering::Relaxed);
4790            let n = N.fetch_add(1, Ordering::Relaxed) + 1;
4791            if n % 100 == 0 {
4792                eprintln!(
4793                    "postprof: sync-wait {:.1} ms/tok | read_states {:.1} ms/tok ({n})",
4794                    SY.load(Ordering::Relaxed) as f64 / n as f64 / 1e6,
4795                    RS.load(Ordering::Relaxed) as f64 / n as f64 / 1e6
4796                );
4797            }
4798        }
4799        if let Some(rows) = lm_rows {
4800            crate::gpu::hostprof_encode_done(_mt0);
4801            let mut lg = attention::take_buf(rows.min(self.vocab_size));
4802            graph.read_logits(&mut lg);
4803            crate::gpu::hostprof_total(_mt0);
4804            lg.resize(self.vocab_size, 0.0);
4805            if let Some(c) = self.final_softcap {
4806                softcap_in_place(&mut lg, c, self.pool.as_deref());
4807            }
4808            self.graph_logits = Some(lg);
4809        }
4810        graph.read_h(h);
4811        // the token's row of the drafter's context
4812        if !taps.is_empty() && tapped == taps.len() {
4813            let mut row = vec![0f32; taps.len() * self.hidden_size];
4814            if graph.read_taps(&mut row) {
4815                if let Some(d) = self.dflash.as_mut() {
4816                    d.queue_context(position, &row, self.pool.as_deref());
4817                }
4818            }
4819        }
4820        if self.graph_head_required && self.graph_logits.is_none() {
4821            METAL_GRAPH_HEAD_MISS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4822            self.fail_metal_graph("fused graph head completed without logits readback");
4823            return start;
4824        }
4825        METAL_GRAPH_TOK_OK.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4826        METAL_GRAPH_LAYERS.fetch_add(
4827            end.saturating_sub(start) as u64,
4828            std::sync::atomic::Ordering::Relaxed,
4829        );
4830        if self.graph_head_required {
4831            METAL_GRAPH_HEAD_OK.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4832        }
4833        // Device-attended layers: replay the CPU bookkeeping — append
4834        // the mirror's new K/V row (rope'd on the GPU) into the owner
4835        // cache, then bank this token's attention-importance mass.
4836        for (li, nkv, hd) in dev_attn {
4837            let mut krow = attention::take_buf(nkv * hd);
4838            let mut vrow = attention::take_buf(nkv * hd);
4839            if crate::gpu::kv_mirror_read_last(kv_id, li, nkv, hd, &mut krow, &mut vrow) {
4840                let cache = &mut self.kv_cache.layers[li];
4841                cache.append(&krow, &vrow, &[]);
4842                let n = cache.seq_len;
4843                let mut imp = attention::take_buf(n);
4844                crate::gpu::kv_mirror_take_imp(kv_id, li, &mut imp);
4845                cache.accumulate_imp(&imp);
4846                attention::recycle_buf(&mut imp);
4847            }
4848            attention::recycle_buf(&mut krow);
4849            attention::recycle_buf(&mut vrow);
4850        }
4851        if let Some(profile) = pager_profile_page.as_mut() {
4852            profile.finish(end, graph.pager_page_stats(), "page-complete");
4853        }
4854        if let Some((_, arm)) = ab {
4855            crate::gpu_metal::dense_ab_record(arm, _mt0.elapsed());
4856        }
4857        end
4858    }
4859
4860    pub fn new(
4861        tokenizer: Tokenizer,
4862        weights: PipelineWeights,
4863        hidden_size: usize,
4864        intermediate_size: usize,
4865        num_heads: usize,
4866        num_kv_heads: usize,
4867        head_dim: usize,
4868        num_layers: usize,
4869        physical_layers: usize,
4870        loop_final_norm: bool,
4871        vocab_size: usize,
4872        rms_eps: f64,
4873        rope_base: f32,
4874        norm_style: NormStyle,
4875        max_seq_len: usize,
4876        sampler_config: SamplerConfig,
4877    ) -> Self {
4878        let rng = match sampler_config.seed {
4879            Some(s) => SplitMix64::new(s),
4880            None => SplitMix64::from_entropy(),
4881        };
4882        let inv_freq = std::sync::Arc::new(attention::rope_inv_freq(head_dim, rope_base));
4883        let pool = Pool::from_env();
4884        if let Some(p) = &pool {
4885            tracing::info!("worker pool: {} threads", p.n_workers());
4886            // Keep the workers on the socket that holds the weights.
4887            if let Some(model) = weights
4888                .lm_head
4889                .model_arc()
4890                .or_else(|| weights.embed_tokens.model_arc())
4891            {
4892                let regions: Vec<&[u8]> =
4893                    model.tensors.iter().map(|t| model.entry_bytes(t)).collect();
4894                p.bind_numa(&regions);
4895            }
4896        }
4897        Self {
4898            gpu_plan: None,
4899            tokenizer: std::sync::Arc::new(tokenizer),
4900            kv_cache: KvCache::new(num_layers, num_kv_heads, head_dim, max_seq_len),
4901            sampler_config,
4902            weights,
4903            hidden_size,
4904            intermediate_size,
4905            num_heads,
4906            num_kv_heads,
4907            head_dim,
4908            num_layers,
4909            physical_layers,
4910            loop_final_norm,
4911            layer_map: None,
4912            dash: None,
4913            dash_batch_on: true,
4914            mhc: None,
4915            mhc_r: Vec::new(),
4916            mhc_rows_in: Vec::new(),
4917            mrope_sections: None,
4918            prompt_mrope: None,
4919            vocab_size,
4920            rms_eps,
4921            rope_base,
4922            norm_style,
4923            rotary_dim: head_dim,
4924            attention_heads_per_layer: None,
4925            kv_heads_per_layer: None,
4926            v_head_dim: None,
4927            layer_dump: std::env::var_os("CMF_LAYER_DUMP")
4928                .filter(|v| !v.is_empty())
4929                .map(std::path::PathBuf::from),
4930            graph_declines: std::cell::RefCell::new(Vec::new()),
4931            mimo_moe: Default::default(),
4932            minicpm_tail: Default::default(),
4933            vmf_cfg: None,
4934            gdn_cfg: None,
4935            kda_cfg: None,
4936            g3n: None,
4937            g4e: None,
4938            dsv4: None,
4939            dory: None,
4940            dsv41: None,
4941            dsv41_vision: None,
4942            dsv41_prefill: None,
4943            qwen4_exp: None,
4944            glm5_next: None,
4945            hy4: None,
4946            maxwell: None,
4947            inkling: None,
4948            clover: None,
4949            clover_stats: clover::CloverStats::default(),
4950            clover_pen: Default::default(),
4951            dsv4_mtp: Vec::new(),
4952            dspark: None,
4953            dspark_pending: Vec::new(),
4954            dspark_hist: Vec::new(),
4955            dspark_real: Vec::new(),
4956            dspark_trunk_picks: Vec::new(),
4957            dspark_exp: Vec::new(),
4958            dspark_draft_ns: 0,
4959            m3_winners: Vec::new(),
4960            m3_counts: Vec::new(),
4961            m3_n_exp: 0,
4962            m3_tokens: 0,
4963            m3_prewarmed: false,
4964            logit_multiplier: None,
4965            cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
4966            graph_failed: std::sync::atomic::AtomicBool::new(false),
4967            graph_moe_banks: std::sync::Mutex::new(std::collections::HashMap::new()),
4968            kv_history: Vec::new(),
4969            kv_history_device: false,
4970            short_conv_cfg: None,
4971            mtp: None,
4972            mimo_mtp: None,
4973            verify_exact_moe: false,
4974            speculative: std::env::var("CMF_MTP").map(|v| v != "0").unwrap_or(true),
4975            ignore_eos: false,
4976            draft_full_streak: 0,
4977            spec_k_adapt: None,
4978            spec_acc_ewma: 0.7,
4979            spec_hold: SPEC_HOLD_PRIOR,
4980            spec_wall: [0.0; 7],
4981            spec_wall_n: [0; 7],
4982            spec_k_dwell: 0,
4983            spec_plain_ms: (0.0, 0),
4984            spec_over_budget: false,
4985            dflash_hold: DFLASH_HOLD_PRIOR,
4986            dflash_last: false,
4987            dflash_wait: 0,
4988            dflash_back: DFLASH_WAIT,
4989            dflash_turn: 0,
4990            dflash_turn_sum: (0.0, 0.0),
4991            dflash_lean: 0.0,
4992            dflash_k_adapt: None,
4993            dflash_acc_ewma: 0.6,
4994            spec_lookup_gain: 2.0,
4995            spec_lookup_wide: false,
4996            spec_lookup_rest: 0,
4997            rng,
4998            sampler_scratch: SamplerScratch::default(),
4999            spec_forced: None,
5000            spec_q: Vec::new(),
5001            spec_p: Vec::new(),
5002            spec_res: Vec::new(),
5003            spec_qs: Vec::new(),
5004            spec_ps: Vec::new(),
5005            spec_ress: Vec::new(),
5006            mtp_graph_mode: None,
5007            dflash: None,
5008            dflash_rows: None,
5009            dflash_taps: std::sync::Mutex::new(Vec::new()),
5010            dflash_solo: false,
5011            dflash_tap_from: 0,
5012            #[cfg(target_os = "macos")]
5013            metal_verify: None,
5014            inv_freq,
5015            ws: ForwardScratch::new(hidden_size),
5016            pool,
5017            model: None,
5018            dyn_force_f32: false,
5019            dyn_skill_layers: Vec::new(),
5020            dyn_active: None,
5021            dyn_blend_loaded: false,
5022            dyn_phi_layer: None,
5023            dyn_phi_ema: Vec::new(),
5024            dyn_phi_seen: 0,
5025            dyn_phi_tap: std::sync::Mutex::new(None),
5026            dyn_router: None,
5027            o1_cfg: None,
5028            o1_turbo: None,
5029            mtp_pos_base: 0,
5030            o1_prefix_tail: Vec::new(),
5031            gdn_snap: None,
5032            mtp_warm_base: None,
5033            o1_epoch: 0,
5034            o1_flags: Vec::new(),
5035            trace: false,
5036            calib_temp: 1.0,
5037            confidence_on: true,
5038            want_first_logits: false,
5039            first_logits: None,
5040            embed_multiplier: 1.0,
5041            attn_scale: 1.0 / (head_dim as f32).sqrt(),
5042            swa: None,
5043            swa_trim: None,
5044            uniform_full_layers: false,
5045            swa_trim_anchor: usize::MAX,
5046            chunk_min_rows: 32,
5047            o1_chunk_prefix: false,
5048            dense_batch_declined: std::sync::atomic::AtomicBool::new(false),
5049            sliding_layers: None,
5050            no_rope_layers: None,
5051            value_blend: None,
5052            vres_e0: Vec::new(),
5053            vres_in: Vec::new(),
5054            anchor_core: None,
5055            bounded_rope: None,
5056            kv_prefix: KvPrefix::default(),
5057            last_prefill_tokens: 0,
5058            inv_freq_local: None,
5059            rotary_dim_local: None,
5060            rope_scale: 1.0,
5061            rope_scale_local: 1.0,
5062            global_attn: None,
5063            inv_freq_global: None,
5064            attn_v_norm: false,
5065            qk_norm_after_rope: false,
5066            proj_gate_sigmoid: false,
5067            final_softcap: None,
5068            head_clusters: None,
5069            attn_softcap: 0.0,
5070            graph_want_logits: false,
5071            graph_head_required: false,
5072            graph_logits: None,
5073            embryo_graph: None,
5074            embryo_wide_refused: false,
5075            graph_refused: std::sync::atomic::AtomicBool::new(false),
5076            graph_kv_id: {
5077                static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
5078                NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
5079            },
5080            #[cfg(test)]
5081            nll_test_fail_at: None,
5082            #[cfg(test)]
5083            nll_test_force_serial: false,
5084        }
5085    }
5086
5087    /// Enable/disable per-layer O(1) Nyström attention. Only Full
5088    /// layers are eligible (a linear layer keeps its own operator).
5089    /// Applies to generation (`generate*`/`forward_ids`): the prompt
5090    /// pass stays exact, then the state seals after prefill or at the
5091    /// deferred skeleton-safe boundary for short prompts; decode runs on
5092    /// the O(1) state. Teacher-forced scoring (`ppl_ids`) intentionally
5093    /// stays exact.
5094    pub fn set_o1(&mut self, cfg: Option<crate::nystrom::O1Cfg>) {
5095        if let Err(e) = self.try_set_o1(cfg) {
5096            tracing::error!("{e}");
5097        }
5098    }
5099
5100    /// True when the file carries a native bounded anchor
5101    /// (`arch.anchor_core`): its state is a fixed record the header
5102    /// fixes, and the post-hoc O(1) override is meaningless on it.
5103    pub fn bounded_native(&self) -> bool {
5104        self.anchor_core.is_some()
5105    }
5106
5107    /// Bytes the resident device graph holds for this pipeline's sequence:
5108    /// `(recurrent state, anchor KV/ring)`; None on the host path.
5109    pub fn device_state_bytes(&self) -> Option<(u64, u64)> {
5110        if self.dory.is_some() {
5111            return crate::gpu::dory_kv_bytes(self.graph_kv_id).map(|b| (0, b));
5112        }
5113        crate::gpu::embryo_device_state_bytes(self.graph_kv_id)
5114    }
5115
5116    /// Why an O(1) override is refused on this pipeline, if it is.
5117    pub fn o1_refusal(&self) -> Option<String> {
5118        self.anchor_core.as_ref().map(|ac| {
5119            format!(
5120                "--o1 / CMF_O1 refused: the anchor is native bounded \
5121                 (anchor_core kind={} window={} sink={}); the file's operator \
5122                 is executed as-is and no post-hoc Nyström overlay applies",
5123                ac.kind, ac.window, ac.sink
5124            )
5125        })
5126    }
5127
5128    /// `set_o1` that reports the refusal instead of logging it.
5129    pub fn try_set_o1(&mut self, cfg: Option<crate::nystrom::O1Cfg>) -> Result<(), String> {
5130        // Dory runs its own stack: the far field goes on its full layers.
5131        if let Some(b) = &mut self.dory {
5132            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) });
5133            return Ok(());
5134        }
5135        if let Some(c) = &cfg {
5136            if let Some(why) = self.o1_refusal() {
5137                self.o1_flags = Vec::new();
5138                self.o1_cfg = None;
5139                return Err(why);
5140            }
5141            if crate::nystrom::o1_deferred_boundary(c.w, c.sink).is_none() {
5142                self.o1_flags.clear();
5143                self.o1_cfg = None;
5144                return Err(format!(
5145                    "o1 disabled: w + sink + slack + 1 overflows usize (w={}, sink={})",
5146                    c.w, c.sink
5147                ));
5148            }
5149        }
5150        self.o1_flags = match &cfg {
5151            Some(c) => {
5152                let mut flags = c.layer_flags(self.num_layers);
5153                for (li, f) in flags.iter_mut().enumerate() {
5154                    // The Nyström state replaces a full-context plain
5155                    // softmax: a sliding window or a learned sink is not
5156                    // something it can represent, and a V narrower than
5157                    // the head is not what its streaming state stores.
5158                    // Those layers keep exact cache attention.
5159                    if *f
5160                        && (!matches!(
5161                            self.weights.layers[self.phys_layer(li)].attn,
5162                            AttnKind::Full { .. }
5163                        ) || self.layer_window(li).is_some()
5164                            || self.kv_cache.layers[li].sinks.is_some()
5165                            || self.layer_v_dim(li) != self.layer_geom(li).1)
5166                    {
5167                        *f = false;
5168                    }
5169                }
5170                flags
5171            }
5172            None => Vec::new(),
5173        };
5174        if let Some(c) = &cfg {
5175            let n = self.o1_flags.iter().filter(|&&f| f).count();
5176            tracing::info!(
5177                "o1 nystrom attention: {n}/{} layer(s), m={} w={} sink={} rect={:?}",
5178                self.num_layers,
5179                c.m,
5180                c.w,
5181                c.sink,
5182                c.rect
5183            );
5184        }
5185        self.o1_cfg = cfg;
5186        Ok(())
5187    }
5188
5189    /// Install the file's bounded anchor: one fixed-size ring per
5190    /// `AttnKind::Bounded` layer (from the header, not per prompt) and
5191    /// the shared relative-rotation table. Must run after the RoPE setup
5192    /// (`set_rotary`, YaRN) so the table is built from the final
5193    /// `inv_freq`.
5194    pub fn install_bounded(&mut self, cfg: &cortiq_core::AnchorCoreConfig) -> Result<(), String> {
5195        if !cortiq_core::AnchorCoreConfig::KINDS.contains(&cfg.kind.as_str()) {
5196            return Err(format!(
5197                "anchor_core kind '{}' is not executable by this runtime",
5198                cfg.kind
5199            ));
5200        }
5201        if cfg.window == 0 {
5202            return Err("anchor_core.window must be >= 1".into());
5203        }
5204        let mut n = 0usize;
5205        for li in 0..self.num_layers {
5206            let pl = self.phys_layer(li);
5207            if let AttnKind::Bounded(w) = &self.weights.layers[pl].attn {
5208                if w.window != cfg.window
5209                    || w.sink != cfg.sink
5210                    || w.group_windows != cfg.group_windows
5211                {
5212                    return Err(format!(
5213                        "layer {li}: bounded weights (window {} sink {} groups {:?}) disagree \
5214                         with anchor_core (window {} sink {} groups {:?})",
5215                        w.window, w.sink, w.group_windows, cfg.window, cfg.sink, cfg.group_windows
5216                    ));
5217                }
5218                self.kv_cache.layers[li].install_bounded(cfg.window);
5219                n += 1;
5220            }
5221        }
5222        if n == 0 {
5223            return Err("anchor_core is present but no layer executes it".into());
5224        }
5225        let rope = crate::bounded::BoundedRope::new(cfg.window, &self.inv_freq, self.rope_scale);
5226        self.bounded_rope = Some(std::sync::Arc::new(rope));
5227        self.anchor_core = Some(cfg.clone());
5228        self.embryo_graph = None;
5229        tracing::info!(
5230            "bounded anchor {}: {n} layer(s), window {} sink {} — {} B of ring per layer",
5231            cfg.kind,
5232            cfg.window,
5233            cfg.sink,
5234            self.kv_cache
5235                .layers
5236                .iter()
5237                .map(|l| l.bounded_state_bytes())
5238                .max()
5239                .unwrap_or(0)
5240        );
5241        Ok(())
5242    }
5243
5244    /// Tag every layer's cache with its wire record kind and the model's
5245    /// operator identity (hash64 of `linear_core_identity` JSON) so the
5246    /// versioned state wire refuses a peer holding another operator.
5247    pub fn install_wire_identity(&mut self, identity: u64) {
5248        for li in 0..self.kv_cache.layers.len() {
5249            let pl = self.phys_layer(li);
5250            let kind = match self.weights.layers.get(pl).map(|l| &l.attn) {
5251                Some(AttnKind::Bounded(_)) => crate::kv_cache::WireKind::Bounded,
5252                Some(AttnKind::Linear(_))
5253                | Some(AttnKind::LinearGdn(_))
5254                | Some(AttnKind::ShortConv(_))
5255                | Some(AttnKind::Kda(_)) => crate::kv_cache::WireKind::Linear,
5256                _ => crate::kv_cache::WireKind::Full,
5257            };
5258            let l = &mut self.kv_cache.layers[li];
5259            l.wire_kind = kind;
5260            l.wire_identity = identity;
5261            // A per-layer geometry (`set_attn_geometry`, Gemma's global
5262            // heads) rebuilds a layer cache with index 0: re-tag it.
5263            l.wire_layer = li as u32;
5264        }
5265    }
5266
5267    /// Forget the reuse keys (legacy `kv_history` and the bounded prefix).
5268    pub fn clear_history(&mut self) {
5269        self.kv_history.clear();
5270        self.kv_history_device = false;
5271        self.kv_prefix.clear();
5272    }
5273
5274    /// Did THIS pipeline's token graph refuse for a structural reason?
5275    /// (Per pipeline: another lane's refusal, or a new pipeline of the
5276    /// same model, never changes it.)
5277    pub fn graph_refused(&self) -> bool {
5278        self.graph_refused
5279            .load(std::sync::atomic::Ordering::Relaxed)
5280    }
5281
5282    /// Remember a structural refusal of this pipeline's token graph.
5283    pub fn mark_graph_refused(&self) {
5284        if !self
5285            .graph_refused
5286            .swap(true, std::sync::atomic::Ordering::Relaxed)
5287        {
5288            tracing::info!(
5289                "token graph: unsupported for this pipeline (seq {}) — not retrying",
5290                self.graph_kv_id
5291            );
5292        }
5293    }
5294
5295    /// Position the resident Embryo graph holds for this pipeline's
5296    /// sequence (`Some(next position)`), `None` when the device holds no
5297    /// image of it (host-owned sequence, or none started).
5298    pub fn device_sequence_position(&self) -> Option<usize> {
5299        crate::gpu::embryo_device_next_position(self.graph_kv_id)
5300    }
5301
5302    /// Is the sequence this pipeline's reuse key describes owned by the
5303    /// device path it would take now? A prefix recorded on the resident
5304    /// graph continues only there (at exactly `n`), a host prefix only on
5305    /// the host; any mismatch means the next turn re-prefills from zero.
5306    fn prefix_owner_matches(&self, n: usize, recorded_on_device: bool) -> bool {
5307        let dev = self.device_sequence_position();
5308        if recorded_on_device {
5309            dev == Some(n) && self.embryo_resident_wanted()
5310        } else {
5311            dev.is_none()
5312        }
5313    }
5314
5315    /// The weights under the sequence changed (a real skill switch): every
5316    /// cached state was computed by other weights. Clear the host KV /
5317    /// ring / recurrent state AND the reuse keys — a surviving `kv_prefix`
5318    /// would let the next turn "extend" a prefix the new weights never
5319    /// saw — drop the packed resident graph (it holds the old FFN
5320    /// tensors; the next build packs the live ones under a fresh id) and
5321    /// reset its device sequence.
5322    pub(crate) fn invalidate_for_weight_change(&mut self) {
5323        self.clear_sequence_state();
5324        self.embryo_graph = None;
5325    }
5326
5327    /// The CUDA hybrid arm keeps a chat snapshot (GDN states copied on the
5328    /// card): a GDN stack with exact attention, no far field, reuse on.
5329    fn gdn_snap_ok(&self) -> bool {
5330        crate::gpu::cuda_active()
5331            && self.gdn_cfg.is_some()
5332            && self.o1_cfg.is_none()
5333            && self.dory.is_none()
5334            && self.dsv41.is_none()
5335            && self.qwen4_exp.is_none()
5336            && self.glm5_next.is_none()
5337            && self.hy4.is_none()
5338            && self.maxwell.is_none()
5339            && self.inkling.is_none()
5340            && std::env::var("CMF_KV_REUSE").as_deref() != Ok("0")
5341    }
5342
5343    /// Where this prompt's snapshot goes: its last `<|im_start|>`, the
5344    /// assistant header the next turn renders differently (a previous
5345    /// answer loses its think block there), past `from` and before the
5346    /// prompt's last row.
5347    fn gdn_snap_target(&self, input_ids: &[u32], from: usize) -> Option<usize> {
5348        if !self.gdn_snap_ok() {
5349            return None;
5350        }
5351        let id = self.tokenizer.token_to_id("<|im_start|>")?;
5352        let s = input_ids.iter().rposition(|&t| t == id)?;
5353        (s > from && s + 1 < input_ids.len()).then_some(s)
5354    }
5355
5356    /// Positions a turn takes back from the chat snapshot (0: none). The
5357    /// card's states go back to it here, all layers or none.
5358    fn gdn_snap_reuse(&mut self, input_ids: &[u32]) -> usize {
5359        let n = match &self.gdn_snap {
5360            Some(s) if !s.is_empty() && s.len() < input_ids.len() && input_ids[..s.len()] == s[..] => s.len(),
5361            _ => return 0,
5362        };
5363        if !self.gdn_snap_ok() || !crate::gpu::gdn_snapshot_restore(self.graph_kv_id, n) {
5364            self.gdn_snap = None;
5365            return 0;
5366        }
5367        n
5368    }
5369
5370    /// Prompt positions the cache already holds when `input_ids`
5371    /// strictly EXTENDS the consumed prefix (0 otherwise). Bounded-native
5372    /// models answer from the fixed-size `kv_prefix` record; everything
5373    /// else from the legacy `kv_history` vector (which the network split
5374    /// also reads and writes).
5375    fn cached_prefix_len(&self, input_ids: &[u32]) -> usize {
5376        let (n, on_device) = if self.bounded_native() {
5377            (
5378                self.kv_prefix.extension(input_ids),
5379                self.kv_prefix.on_device(),
5380            )
5381        } else {
5382            let h = &self.kv_history;
5383            if !h.is_empty() && h.len() < input_ids.len() && input_ids[..h.len()] == h[..] {
5384                (h.len(), self.kv_history_device)
5385            } else if !h.is_empty() && !self.kv_history_device {
5386                (self.rollback_prefix_len(input_ids), false)
5387            } else {
5388                (0, false)
5389            }
5390        };
5391        // The owner tag: the state the key describes must live where this
5392        // turn will continue it (R4) — else a fresh sequence.
5393        if n > 0 && !self.prefix_owner_matches(n, on_device) {
5394            tracing::warn!(
5395                "kv-reuse refused: the cached prefix ({n} positions) was built on the {} path, \
5396                 the device now holds {:?} — re-prefilling from zero",
5397                if on_device { "resident device" } else { "host" },
5398                self.device_sequence_position()
5399            );
5400            return 0;
5401        }
5402        n
5403    }
5404
5405    /// Positions a turn whose ids DIVERGE from the consumed prefix keeps:
5406    /// their longest common prefix, when every layer can drop its rows past
5407    /// it exactly — full attention whose f32 rows the host owns (no wgpu
5408    /// mirror ahead of the host, no recurrent, O(1) or bounded state) and
5409    /// every trimmed sliding tail still holding the window the query at the
5410    /// cut reads. A chat app re-renders the previous answer through the
5411    /// template (a thinking model's history drops its `<think>` block), so a
5412    /// conversation almost never extends token for token: extension-only
5413    /// reuse re-prefilled the whole history every turn. One id at least is
5414    /// left to prefill. `CMF_KV_ROLLBACK=0` keeps extension-only reuse.
5415    fn rollback_prefix_len(&self, input_ids: &[u32]) -> usize {
5416        if std::env::var("CMF_KV_ROLLBACK").as_deref() == Ok("0")
5417            || self.device_sequence_position().is_some()
5418        {
5419            return 0;
5420        }
5421        let h = &self.kv_history;
5422        let lcp = h.iter().zip(input_ids).take_while(|(a, b)| a == b).count();
5423        let n = lcp.min(input_ids.len().saturating_sub(1));
5424        // Stacks that keep their own layers (qwen4, DSV4) leave the generic
5425        // ones empty: nothing here can roll back, the prompt is read again.
5426        if n == 0
5427            || self.kv_cache.layers.len() < self.num_layers
5428            || self.weights.layers.len() < self.num_layers
5429        {
5430            return 0;
5431        }
5432        let kv_id = self.graph_kv_id;
5433        for li in 0..self.num_layers {
5434            let l = &self.kv_cache.layers[li];
5435            let tail_ok = l.base() == 0
5436                || self
5437                    .layer_window(li)
5438                    .is_some_and(|w| l.base() + w <= n + 1);
5439            if !matches!(self.weights.layers[self.phys_layer(li)].attn, AttnKind::Full { .. })
5440                || l.o1.is_some()
5441                || l.bounded.is_some()
5442                || !l.linear_state.is_empty()
5443                || l.mode != crate::kv_cache::KvMode::F32
5444                || l.pos_len() != h.len()
5445                || !tail_ok
5446                || crate::gpu::graph_kv_stored(kv_id, li).is_some()
5447                || crate::gpu::graph_state_resident(kv_id, li)
5448            {
5449                return 0;
5450            }
5451        }
5452        n
5453    }
5454
5455    /// Public view of the prefix-reuse decision for `input_ids` (positions
5456    /// the next `generate*` would take from the cache; 0 = fresh sequence).
5457    pub fn reusable_prefix_len(&self, input_ids: &[u32]) -> usize {
5458        self.cached_prefix_len(input_ids)
5459    }
5460
5461    /// Record the forwarded prefix as the next turn's reuse key. A
5462    /// bounded-native model extends the rolling record (`reused` = the
5463    /// positions this turn found cached); others keep the literal vector.
5464    /// Either way the key carries its OWNER: the resident device graph
5465    /// (it holds an image of this sequence) or the host.
5466    fn record_consumed_prefix(&mut self, consumed: &[u32], reused: usize) {
5467        let on_device = self.device_sequence_position().is_some();
5468        if self.bounded_native() {
5469            let keep = reused > 0 && reused == self.kv_prefix.len() && reused <= consumed.len();
5470            let prev_device = self.kv_prefix.on_device();
5471            self.kv_history.clear();
5472            self.kv_history_device = false;
5473            if keep && prev_device == on_device {
5474                self.kv_prefix.extend(&consumed[reused..]);
5475            } else {
5476                self.kv_prefix.set(consumed);
5477            }
5478            self.kv_prefix.set_on_device(on_device);
5479        } else {
5480            self.kv_history = consumed.to_vec();
5481            self.kv_history_device = on_device;
5482        }
5483    }
5484
5485    /// True when at least one layer runs the O(1) kernel.
5486    pub fn o1_active(&self) -> bool {
5487        self.o1_cfg.is_some() && self.o1_flags.iter().any(|&f| f)
5488    }
5489
5490    /// Whether generation's prompt ingest is routed through the whole-token
5491    /// graph.  The bench uses this to label the measured generation prefill
5492    /// honestly; keep the predicate in Pipeline so CLI labels cannot drift
5493    /// from the production route.
5494    /// Positions per batched-graph submit for the prompt: `CMF_BATCH_K`
5495    /// when set (0 = one position at a time through the token graph),
5496    /// otherwise 128 (32 for a MoE stack) on a discrete card whose prompt
5497    /// takes the graph route.
5498    /// The batched graph read a 2048-token prompt at 53 tok/s against 28.5
5499    /// one position at a time on an RTX PRO 4000 (Qwen3.8-27B q4tp: TTFT
5500    /// 39 s against 72), and its states are the speculative verify's,
5501    /// measured identical to the plain path. macOS keeps its own arm.
5502    /// 128, not 32: the q4tp prefill GEMM tiles 64 batch rows, so a
5503    /// 32-row chunk left half of every tile idle. Qwen3.8-27B q4tp on an
5504    /// RTX 3090, 1000-token prompt: 51 tok/s at 32, 82 at 64, 95 at 128,
5505    /// 97 at 256; greedy output byte-identical to the 32-row chunks
5506    /// (every GEMM row and the k-looped recurrences are per position).
5507    /// A dense sliding-window stack whose batched prefill attends with the
5508    /// query-tiled kernels (the Spark-X2.6 class on a discrete wgpu card).
5509    #[cfg(not(target_os = "macos"))]
5510    fn tiled_sliding_batch(&self) -> bool {
5511        (self.sliding_layers.is_some() || self.swa.is_some())
5512            && !self.weights.layers.iter().any(|lw| matches!(&lw.ffn, FfnKind::Moe(_)))
5513            && crate::gpu::batched_attend_tiled()
5514    }
5515
5516    pub fn generation_batch_k(&self) -> usize {
5517        if let Some(k) = std::env::var("CMF_BATCH_K")
5518            .ok()
5519            .and_then(|v| v.parse::<usize>().ok())
5520        {
5521            return k;
5522        }
5523        // Gemma-4 (`g4_batch_prefill`): 128-row chunks, the GEMM tile's
5524        // two 64-row halves full. The CUDA batch graph expands each weight
5525        // once a chunk: its own chunk (`CMF_CUDA_BATCH`, 1024) — Ripple-65B
5526        // q4tp on an A40, a 4096-token prompt, 141 tok/s at 128 rows, 422 at
5527        // 1024.
5528        if self.g4_batch_prefill() {
5529            #[cfg(not(target_os = "macos"))]
5530            if let Some(k) = crate::gpu::cuda_batch_rows() {
5531                return k;
5532            }
5533            return 128;
5534        }
5535        #[cfg(target_os = "macos")]
5536        if self.o1_active() && self.o1_on_graph() && crate::gpu::q1_force() && crate::gpu::enabled_here() {
5537            return if crate::gpu_metal::ane::wanted() { 512 } else { 128 };
5538        }
5539        // The sealed O(1) suffix of a bounded prompt (`CMF_O1_PREFILL`) on
5540        // the device route rides the batch graph, whose O(1) kernels take
5541        // the chunk in 64-row sub-chunks (`o1_batch`); 128 as the exact
5542        // prompt below. Without it the suffix went one position at a time.
5543        #[cfg(not(target_os = "macos"))]
5544        if self.o1_active()
5545            && self.o1_on_graph()
5546            && crate::gpu::enabled_here()
5547            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill)
5548        {
5549            if let Some(k) = crate::gpu::cuda_batch_rows() {
5550                return k;
5551            }
5552            return if self.tiled_sliding_batch() { 512 } else { 128 };
5553        }
5554        #[cfg(not(target_os = "macos"))]
5555        if self.graph_prefill_preferred() && !self.o1_active() {
5556            // The CUDA batch graph expands each weight once a chunk and
5557            // multiplies with cuBLAS: its own, larger chunk (`CMF_CUDA_BATCH`).
5558            if let Some(k) = crate::gpu::cuda_batch_rows() {
5559                return k;
5560            }
5561            // A dense sliding-window stack on the tiled whole-run attend:
5562            // 512 rows a submit (Spark-X2.6 q4tp on an RTX 2000 Ada, 4096
5563            // tokens: 288 tok/s at 128, 317 at 512, the same greedy text;
5564            // the tile holds 16 tokens, and a chunk is read against its K/V
5565            // once per sub-run of whole tiles).
5566            if self.tiled_sliding_batch() {
5567                return 512;
5568            }
5569            // 128 is measured on the dense hybrids; MoE stacks other than
5570            // the two expert codecs below keep the 32 their expert-grouped
5571            // prefill was measured at.
5572            let moe = self
5573                .weights
5574                .layers
5575                .iter()
5576                .any(|lw| matches!(&lw.ffn, FfnKind::Moe(_)));
5577            // The dense GDN hybrids (Qwen3.5 / 3.6 / 3.8) on the tiled
5578            // attend: 512 rows a submit, each weight unpacked to its f16
5579            // plane once a chunk. Qwen3.5-4B q4tp on an RTX A5000, prompt
5580            // tok/s at 4 000 / 16 000 / 32 000 tokens: 1223 / 1122 / 977
5581            // at 128 rows, 1669 / 1550 / - at 256, 1833 / 1897 / 1539 at 512.
5582            if !moe && self.graph_gdn_layer_count() > 0 && crate::gpu::batched_attend_tiled() {
5583                return 512;
5584            }
5585            // q8_2f experts (moe_q82's grouped prefill) read each expert
5586            // once per group of up to 16 of its entries, so the chunk that
5587            // fills those groups is the faster ingest: Mellum2.1 q8_2f on an
5588            // RTX 3090, 4000-token prompt, 503 tok/s at 64 rows, 542 at 128
5589            // (and 542 at 256).
5590            let q82 = crate::gpu::moe_q82_graph_on()
5591                && self.weights.layers.iter().any(|lw| {
5592                    matches!(&lw.ffn, FfnKind::Moe(m)
5593                        if m.experts.first().is_some_and(|e| e.gate_proj.mapped_q8_2f().is_some()))
5594                });
5595            // q4tp experts: the grouped GEMM reads every routed expert once
5596            // per chunk, and 32 rows (256 entries over 256 experts, about
5597            // one row each) re-read nearly the whole expert set every 32
5598            // tokens. Apex-35B q4tp on an A40, 4096-token prompt, MTP off:
5599            // 295 tok/s at 32 rows, 357 at 64, 385 at 128, 401 at 256,
5600            // 396 at 512.
5601            let q4tp_moe = self.weights.layers.iter().any(|lw| {
5602                matches!(&lw.ffn, FfnKind::Moe(m)
5603                    if m.experts.first().is_some_and(|e| e.gate_proj.mapped_q4tp().is_some()))
5604            });
5605            // q4_tiled experts on wgpu take the split layout (`moe_q4ts`),
5606            // whose grouped prefill reads each expert once a chunk as q4tp's
5607            // does: Kimi-Linear-48B on an RTX A5000, 4096-token prompt, 302
5608            // tok/s at 32 rows, 464-503 at 256.
5609            let q4ts_moe = crate::gpu::wgpu_active()
5610                && std::env::var("CMF_MOE_Q4TS").as_deref() != Ok("0")
5611                && self.weights.layers.iter().any(|lw| {
5612                    matches!(&lw.ffn, FfnKind::Moe(m)
5613                        if m.experts.first().is_some_and(|e| e.gate_proj.mapped_q4t().is_some()))
5614                });
5615            // A file past a discrete card on wgpu keeps banks in system
5616            // memory, and a chunk copies each of them to the card once
5617            // (`moe_cache::staging`): at 32 rows Ornith-122B q2tp-v2 within
5618            // 32 GB copied 43 banks every 32 tokens (512 in 30 s). q8_2f
5619            // banks have no system-memory arm.
5620            let banked = crate::gpu::wgpu_active()
5621                && crate::gpu::discrete()
5622                && self.model.as_ref().is_some_and(|m| m.primary_bytes().len() as u64 > crate::gpu::vram_budget());
5623            // banks streamed or staged from system memory: a chunk reads every
5624            // bank of the stack once, so the widest chunk the scratch takes
5625            // (GLM-5.3 on Vulkan streamed 108 GB of experts every 256 rows)
5626            if moe && banked && !q82 {
5627                return 512;
5628            }
5629            return if q82 {
5630                128
5631            } else if q4tp_moe || q4ts_moe || self.onevision2_prefill() {
5632                256
5633            } else if moe {
5634                32
5635            } else {
5636                128
5637            };
5638        }
5639        0
5640    }
5641
5642    pub fn generation_graph_prefill(&self) -> bool {
5643        let graph = self.graph_prefill_preferred();
5644        // On wgpu, an active MTP head now consumes the trunk's graph batches
5645        // and warms its own block from those returned rows.  The selected
5646        // generation measurement is therefore the batched path, even though
5647        // the underlying GDN model still satisfies the graph-prefill
5648        // predicate.  Keep the CLI label tied to the actual route.  Native
5649        // Metal has a separate prefill-batch arm and retains its historical
5650        // label here.
5651        // A batched prompt (`generation_batch_k` > 0) is the batched graph
5652        // for every model on the graph route, not only those with an MTP
5653        // head — the label follows the route.
5654        #[cfg(not(target_os = "macos"))]
5655        if graph && self.generation_batch_k() > 0 && std::env::var("CMF_MTP_CHAIN_PROBE").is_err() {
5656            return false;
5657        }
5658        graph
5659    }
5660
5661    /// Device-side O(1) mirrors currently uploaded for this pipeline's
5662    /// sequence.  The count/bytes are zero before seal or after a fresh
5663    /// reset; callers use this to distinguish logical host state from the
5664    /// GPU allocation that actually serves decode.
5665    pub fn o1_device_stats(&self) -> (usize, u64) {
5666        crate::gpu::o1_device_stats(self.graph_kv_id)
5667    }
5668
5669    /// Arm query collection on the o1 layers (fresh prompt pass).
5670    /// Reset the o1 layers to Collecting for a fresh sequence. Pub for the
5671    /// network split: each side runs the o1 lifecycle over ITS OWN layers
5672    /// (begin before prefill, seal at the prefill barrier).
5673    pub fn o1_begin(&mut self) {
5674        self.o1_begin_with_prefix(None);
5675    }
5676
5677    /// Arm collection and optionally request a positive calibration prefix.
5678    /// The effective barrier is always at least the skeleton-safe floor, so
5679    /// a short requested prefix cannot create an exact-only runtime state.
5680    pub fn o1_begin_with_prefix(&mut self, requested_prefix: Option<usize>) {
5681        if let Some(c) = &self.o1_cfg {
5682            let (m, w, sink, rect) = (c.m, c.w, c.sink, c.rect);
5683            let boundary = requested_prefix.map(|p| {
5684                p.max(
5685                    crate::nystrom::o1_deferred_boundary(w, sink)
5686                        .expect("o1 config boundary validated in set_o1"),
5687                )
5688            });
5689            // Exact rows are chosen across every far-field layer at the boundary:
5690            // a layer that reached it first must not seal without them.
5691            let await_keep = boundary.is_some() && self.o1_exact_cfg().is_some();
5692            for (li, &f) in self.o1_flags.iter().enumerate() {
5693                if f {
5694                    let cache = &mut self.kv_cache.layers[li];
5695                    cache.o1_begin_with_boundary(m, w, sink, rect, boundary);
5696                    cache.o1_await_keep = await_keep;
5697                }
5698            }
5699        }
5700    }
5701
5702    /// Effective deferred boundary for a positive prefix request.
5703    fn o1_effective_boundary(&self, requested_prefix: usize) -> Option<usize> {
5704        self.o1_cfg.as_ref().and_then(|c| {
5705            crate::nystrom::o1_deferred_boundary(c.w, c.sink)
5706                .map(|floor| requested_prefix.max(floor))
5707        })
5708    }
5709
5710    fn o1_note_transition(&mut self) {
5711        // Drain every layer's one-shot bit before publishing one pipeline
5712        // epoch. `any()` would short-circuit on the first layer and leak the
5713        // remaining bits into later forwards, causing one epoch per layer.
5714        let mut transitioned = false;
5715        for (li, &flagged) in self.o1_flags.iter().enumerate() {
5716            if flagged {
5717                transitioned |= self.kv_cache.layers[li].take_o1_transition();
5718            }
5719        }
5720        if transitioned {
5721            self.o1_epoch = self.o1_epoch.wrapping_add(1);
5722        }
5723    }
5724
5725    fn o1_pending(&self) -> bool {
5726        self.o1_flags.iter().enumerate().any(|(li, &f)| {
5727            f && self.kv_cache.layers[li].seq_len > 0
5728                && self.kv_cache.layers[li].o1_pending_boundary().is_some()
5729        })
5730    }
5731
5732    fn o1_fail(&mut self, err: String) {
5733        tracing::error!("o1 deferred seal failed; terminating sequence: {err}");
5734        self.clear_sequence_state();
5735        self.graph_failed
5736            .store(true, std::sync::atomic::Ordering::Relaxed);
5737        self.cancel
5738            .store(true, std::sync::atomic::Ordering::Relaxed);
5739    }
5740
5741    /// Seal participating layers while retaining the exact state when the
5742    /// prompt is below the deferred boundary. A split worker may have
5743    /// collecting layers outside its owned span; zero-depth layers remain
5744    /// armed and are intentionally skipped until their peer runs them.
5745    pub fn o1_seal_checked(&mut self) -> Result<bool, String> {
5746        if self.o1_cfg.is_none() {
5747            return Ok(false);
5748        }
5749        self.o1_choose_exact_rows();
5750        let (t_seal, mut sealed_now, epoch) = (std::time::Instant::now(), 0usize, self.o1_epoch);
5751        let mut todo: Vec<(usize, usize)> = Vec::new();
5752        for li in 0..self.num_layers {
5753            if !self.o1_flags.get(li).copied().unwrap_or(false) {
5754                continue;
5755            }
5756            if let Some(err) = self.kv_cache.layers[li].take_o1_error() {
5757                return Err(err);
5758            }
5759            if self.kv_cache.layers[li].seq_len == 0 {
5760                continue;
5761            }
5762            todo.push((li, self.layer_num_heads(li)));
5763        }
5764        let participating = !todo.is_empty();
5765        // A layer's seal depends on that layer's rows alone, and its groups
5766        // already seal on their own threads: a few layers go at a time, as
5767        // many as the cores carry (`CMF_O1_SEAL_PAR=N` sets the number). Each
5768        // holds its queries per group while it seals, so not all at once —
5769        // and one after another on a Mac, where that memory is the model's
5770        // too.
5771        let par = std::env::var("CMF_O1_SEAL_PAR")
5772            .ok()
5773            .and_then(|v| v.parse::<usize>().ok())
5774            .unwrap_or_else(|| {
5775                if cfg!(target_os = "macos") {
5776                    return 1;
5777                }
5778                let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
5779                let groups = todo.first().map_or(1, |&(li, _)| self.kv_cache.layers[li].num_kv_heads.max(1));
5780                cores.div_ceil(groups).clamp(1, 3)
5781            })
5782            .max(1);
5783        let mut slots: Vec<Option<&mut crate::kv_cache::LayerKvCache>> = self.kv_cache.layers.iter_mut().map(Some).collect();
5784        let mut jobs: Vec<(&mut crate::kv_cache::LayerKvCache, usize)> =
5785            todo.iter().filter_map(|&(li, nh)| slots[li].take().map(|c| (c, nh))).collect();
5786        for run in jobs.chunks_mut(par) {
5787            let done: Vec<Result<bool, String>> = if run.len() == 1 {
5788                let (c, nh) = &mut run[0];
5789                let was = c.o1_sealed();
5790                vec![c.o1_seal_checked(*nh).map(|ok| ok && !was)]
5791            } else {
5792                std::thread::scope(|s| {
5793                    let hs: Vec<_> = run
5794                        .iter_mut()
5795                        .map(|(c, nh)| {
5796                            let nh = *nh;
5797                            s.spawn(move || {
5798                                let was = c.o1_sealed();
5799                                c.o1_seal_checked(nh).map(|ok| ok && !was)
5800                            })
5801                        })
5802                        .collect();
5803                    hs.into_iter()
5804                        .map(|h| h.join().unwrap_or_else(|_| Err("o1 seal: a layer's thread panicked".into())))
5805                        .collect()
5806                })
5807            };
5808            for r in done {
5809                sealed_now += r? as usize;
5810            }
5811        }
5812        drop(jobs);
5813        drop(slots);
5814        self.o1_note_transition();
5815        if self.o1_epoch != epoch && sealed_now > 0 {
5816            tracing::info!("o1: {sealed_now} layer(s) sealed in {:.2} s", t_seal.elapsed().as_secs_f64());
5817        }
5818        for li in 0..self.num_layers {
5819            if self.o1_flags.get(li).copied().unwrap_or(false) {
5820                if let Some(err) = self.kv_cache.layers[li].take_o1_error() {
5821                    return Err(err);
5822                }
5823            }
5824        }
5825        Ok(participating
5826            && (0..self.num_layers).all(|li| {
5827                !self.o1_flags.get(li).copied().unwrap_or(false)
5828                    || self.kv_cache.layers[li].seq_len == 0
5829                    || self.kv_cache.layers[li].o1_sealed()
5830            }))
5831    }
5832
5833    /// A sealed chunk's rows join the archive.
5834    fn o1_archive_chunk(&self, a: &mut O1Archive, pos: usize, bk: usize, entries: Option<usize>) -> Result<(), String> {
5835        let got = match entries {
5836            Some(n) => crate::gpu::o1_acap_take_first(n),
5837            None => crate::gpu::o1_acap_take(),
5838        }
5839        .ok_or("O(1) archive: readback failed")?;
5840        let qrow = a.nh * a.hd;
5841        let stride = a.stride;
5842        // a backend may hand back the kept query rows alone (CUDA)
5843        let kept = (pos..pos + bk).filter(|p| p % stride == 0).count();
5844        for (gl, q, k, v) in got {
5845            let Some(l) = a.layers.iter_mut().find(|l| l.li == gl) else { continue };
5846            l.k.push(&k)?;
5847            l.v.push(&v)?;
5848            if q.len() == kept * qrow && kept != bk {
5849                l.q.push(&q)?;
5850                continue;
5851            }
5852            if q.len() != bk * qrow {
5853                return Err(format!("O(1) archive: layer {gl} handed back {} query values", q.len()));
5854            }
5855            for p in pos..pos + bk {
5856                if p % stride == 0 {
5857                    l.q.push(&q[(p - pos) * qrow..(p - pos + 1) * qrow])?;
5858                }
5859            }
5860        }
5861        a.rows = pos + bk;
5862        Ok(())
5863    }
5864
5865    /// The far field built anew over all the rows read so far, the chosen ones out of it.
5866    /// One layer at a time, so RAM holds one layer's rows.
5867    fn o1_seal_archive(&mut self, a: O1Archive) -> Result<bool, String> {
5868        let t0 = std::time::Instant::now();
5869        let (rows, stride, nk, hd) = (a.rows, a.stride, a.nk, a.hd);
5870        let mut layers = Vec::with_capacity(a.layers.len());
5871        for l in a.layers {
5872            layers.push((l.li, l.k.freeze()?, l.v.freeze()?, l.q.freeze()?));
5873        }
5874        let keep = match (self.o1_exact_cfg().cloned(), self.o1_cfg.clone()) {
5875            (Some(x), Some(c)) => {
5876                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();
5877                let refs: Vec<&dyn crate::dory::LayerRows> = views.iter().map(|v| v as &dyn crate::dory::LayerRows).collect();
5878                crate::dory::pick_exact_rows(&x, &refs, rows, nk, hd, c.m, c.sink, rows.saturating_sub(c.w))
5879            }
5880            _ => Vec::new(),
5881        };
5882        let t_pick = t0.elapsed().as_secs_f64();
5883        let mut all = !layers.is_empty();
5884        let prof = std::env::var("CMF_PREFILL_PROF").is_ok();
5885        let t_layers = std::time::Instant::now();
5886        // a few layers at a time (`CMF_O1_SEAL_PAR`), each on its own thread: a
5887        // layer's rows into its cache, then its seal (its groups on threads of
5888        // their own); RAM holds those layers' rows twice meanwhile
5889        let par = std::env::var("CMF_O1_SEAL_PAR")
5890            .ok()
5891            .and_then(|v| v.parse::<usize>().ok())
5892            .unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |p| p.get()).div_ceil(8).clamp(1, 4));
5893        let heads: Vec<usize> = (0..self.kv_cache.layers.len()).map(|li| self.layer_num_heads(li)).collect();
5894        let mut by_li: Vec<Option<_>> = (0..self.kv_cache.layers.len()).map(|_| None).collect();
5895        for (li, k, v, q) in layers {
5896            if li < by_li.len() {
5897                by_li[li] = Some((k, v, q));
5898            }
5899        }
5900        let mut jobs: Vec<(usize, &mut crate::kv_cache::LayerKvCache, _)> = Vec::new();
5901        for (li, cache) in self.kv_cache.layers.iter_mut().enumerate() {
5902            if let Some(d) = by_li[li].take() {
5903                jobs.push((li, cache, d));
5904            }
5905        }
5906        let keep_ref = &keep;
5907        let heads = &heads;
5908        let results: Vec<Result<bool, String>> = std::thread::scope(|sc| {
5909            let mut out = Vec::new();
5910            let mut jobs = jobs.into_iter();
5911            loop {
5912                let wave: Vec<_> = jobs.by_ref().take(par.max(1)).collect();
5913                if wave.is_empty() {
5914                    break;
5915                }
5916                let hs: Vec<_> = wave
5917                    .into_iter()
5918                    .map(|(li, cache, (k, v, q))| {
5919                        sc.spawn(move || -> Result<bool, String> {
5920                            if !cache.o1_recollect(k.as_slice(), v.as_slice(), q.as_slice().to_vec(), stride, rows) {
5921                                return Err(format!("O(1) archive: layer {li} is not sealed"));
5922                            }
5923                            drop((k, v, q));
5924                            cache.o1_keep = keep_ref.clone();
5925                            cache.o1_seal_checked(heads[li])
5926                        })
5927                    })
5928                    .collect();
5929                for h in hs {
5930                    out.push(h.join().unwrap_or_else(|_| Err("O(1) archive: a layer's seal panicked".into())));
5931                }
5932            }
5933            out
5934        });
5935        for r in results {
5936            all &= r?;
5937        }
5938        if prof {
5939            eprintln!("o1 archive seal: {} layers {par} at a time in {:.2} s", by_li.len(), t_layers.elapsed().as_secs_f64());
5940        }
5941        self.o1_note_transition();
5942        tracing::info!(
5943            "o1: far field rebuilt over {rows} rows, {} kept exact, chosen in {t_pick:.2} s, {:.2} s in all",
5944            keep.len(),
5945            t0.elapsed().as_secs_f64()
5946        );
5947        Ok(all)
5948    }
5949
5950    /// A sealed prompt chunk on the device: wgpu's batch graph, or Metal's rows graph.
5951    fn o1_prompt_chunk(&mut self, hiddens: &mut Vec<f32>, positions: &[usize], bk: usize) -> crate::gpu::BatchGraphOutcome {
5952        #[cfg(target_os = "macos")]
5953        if crate::gpu::q1_force() && self.o1_active() {
5954            return match self.prefill_hiddens_metal(hiddens.clone(), positions[0], None) {
5955                MetalPrefillOutcome::Completed(h) => {
5956                    *hiddens = h;
5957                    crate::gpu::BatchGraphOutcome::Completed
5958                }
5959                MetalPrefillOutcome::Declined => crate::gpu::BatchGraphOutcome::Declined,
5960                MetalPrefillOutcome::Failed => crate::gpu::BatchGraphOutcome::Failed,
5961            };
5962        }
5963        self.try_batch_graph_wgpu(hiddens, positions, bk, None)
5964    }
5965
5966    /// `o1_prefix_on_graph` on Metal: the prompt's exact part on the rows graph, which leaves its
5967    /// rows in the host cache and the mirror. Queries come from the graph, one row in `QT_STRIDE`.
5968    #[cfg(target_os = "macos")]
5969    fn o1_prefix_on_metal(
5970        &mut self,
5971        ids: &[u32],
5972        chunk: usize,
5973        mut arch: Option<&mut O1Archive>,
5974    ) -> Result<Option<Vec<f32>>, String> {
5975        const QT_STRIDE: usize = 8;
5976        let o1_layers: Vec<usize> = (0..self.num_layers)
5977            .filter(|&li| self.o1_flags.get(li).copied().unwrap_or(false))
5978            .collect();
5979        let Some(&first) = o1_layers.first() else {
5980            return Ok(None);
5981        };
5982        let (nkv, hd) = {
5983            let c = &self.kv_cache.layers[first];
5984            (c.num_kv_heads, c.head_dim)
5985        };
5986        let nh = self.num_heads;
5987        if chunk == 0
5988            || o1_layers.iter().any(|&li| {
5989                let c = &self.kv_cache.layers[li];
5990                self.layer_num_heads(li) != nh
5991                    || (c.num_kv_heads, c.head_dim) != (nkv, hd)
5992                    || c.seq_len != 0
5993                    || c.o1_pending_boundary().is_none()
5994            })
5995        {
5996            return Ok(None);
5997        }
5998        let hs = self.hidden_size;
5999        let n = ids.len();
6000        let mut last = vec![0f32; hs];
6001        let qrow = nh * hd;
6002        let mut qs: Vec<Vec<f32>> = vec![Vec::new(); o1_layers.len()];
6003        crate::gpu_metal::o1c::qcap_begin(&o1_layers);
6004        for &li in &o1_layers {
6005            self.kv_cache.layers[li].o1_set_q_stride(QT_STRIDE);
6006        }
6007        let mut pos = 0;
6008        // Layers the rows graph does not hold (Spark-X2.6: GELU, per-head
6009        // gates, sliding windows) read the prefix on the chunk graph, which
6010        // keeps the collecting layers' queries too. Without it the prefix
6011        // went to the host walk: 14 000 tokens in 155 s against 53 s exact.
6012        let mut on_chunks = false;
6013        let mut step = chunk;
6014        while pos < n {
6015            let end = (pos + step).min(n);
6016            let bk = end - pos;
6017            let mut hiddens = vec![0f32; bk * hs];
6018            for (j, &id) in ids[pos..end].iter().enumerate() {
6019                hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
6020            }
6021            let rows = if on_chunks {
6022                MetalPrefillOutcome::Declined
6023            } else {
6024                self.prefill_hiddens_metal(hiddens.clone(), pos, None)
6025            };
6026            match rows {
6027                MetalPrefillOutcome::Completed(h) => last.copy_from_slice(&h[(bk - 1) * hs..]),
6028                MetalPrefillOutcome::Declined if pos == 0 || on_chunks => {
6029                    if !on_chunks {
6030                        on_chunks = true;
6031                        // The chunk graph's own prompt chunk.
6032                        let want = self.prefill_chunk().max(chunk);
6033                        if want != step {
6034                            step = want;
6035                            continue;
6036                        }
6037                    }
6038                    self.o1_chunk_prefix = true;
6039                    let got = self.chunk_run_gpu(0, &mut hiddens, bk, pos, None, self.num_layers);
6040                    self.o1_chunk_prefix = false;
6041                    if got != self.num_layers {
6042                        crate::gpu_metal::o1c::cap_end();
6043                        if pos == 0 && got == 0 {
6044                            for &li in &o1_layers {
6045                                self.kv_cache.layers[li].o1_set_q_stride(1);
6046                            }
6047                            return Ok(None);
6048                        }
6049                        return Err("O(1) prefix: the Metal chunk graph stopped after admission".into());
6050                    }
6051                    // Every layer appended the chunk: sliding layers keep their tails only.
6052                    self.swa_trim_tails();
6053                    last.copy_from_slice(&hiddens[(bk - 1) * hs..]);
6054                }
6055                _ => {
6056                    crate::gpu_metal::o1c::cap_end();
6057                    return Err("O(1) prefix: the Metal rows graph stopped after admission".into());
6058                }
6059            }
6060            for (li, q, _, _) in crate::gpu_metal::o1c::cap_take() {
6061                let Some(i) = o1_layers.iter().position(|&l| l == li) else { continue };
6062                if q.len() != bk * qrow {
6063                    crate::gpu_metal::o1c::cap_end();
6064                    return Err(format!("O(1) prefix: {} query values, expected {}", q.len(), bk * qrow));
6065                }
6066                for p in pos..end {
6067                    if p % QT_STRIDE == 0 {
6068                        qs[i].extend_from_slice(&q[(p - pos) * qrow..(p - pos + 1) * qrow]);
6069                    }
6070                }
6071            }
6072            pos = end;
6073        }
6074        crate::gpu_metal::o1c::cap_end();
6075        let row = nkv * hd;
6076        for (&li, q) in o1_layers.iter().zip(qs) {
6077            if q.len() != n.div_ceil(QT_STRIDE) * qrow {
6078                return Err(format!("O(1) prefix: layer {li} kept {} query values", q.len()));
6079            }
6080            if let Some(a) = arch.as_deref_mut() {
6081                let (mut k, mut v) = (vec![0f32; n * row], vec![0f32; n * row]);
6082                if !crate::gpu_metal::kv_mirror_read_rows(self.graph_kv_id, li, nkv, hd, 0, n, &mut k, &mut v) {
6083                    return Err("O(1) prefix: K/V readback failed".into());
6084                }
6085                let dir = a.dir.clone();
6086                let mut layer = O1ArchLayer {
6087                    li,
6088                    k: ArchStore::new(dir.as_deref(), format!("{li}-k"))?,
6089                    v: ArchStore::new(dir.as_deref(), format!("{li}-v"))?,
6090                    q: ArchStore::new(dir.as_deref(), format!("{li}-q"))?,
6091                };
6092                layer.k.push(&k)?;
6093                layer.v.push(&v)?;
6094                layer.q.push(&q)?;
6095                a.layers.push(layer);
6096                a.rows = n;
6097                a.stride = QT_STRIDE;
6098                a.nh = nh;
6099                a.nk = nkv;
6100                a.hd = hd;
6101            }
6102            self.kv_cache.layers[li].o1_set_q_trace(q);
6103        }
6104        Ok(Some(last))
6105    }
6106
6107    fn o1_exact_cfg(&self) -> Option<&crate::dory::ExactRows> {
6108        static EXACT: std::sync::OnceLock<Option<crate::dory::ExactRows>> = std::sync::OnceLock::new();
6109        EXACT
6110            .get_or_init(|| crate::dory::exact_from_var("CMF_O1_EXACT"))
6111            .as_ref()
6112            .or(self.o1_turbo.as_ref().map(|t| &t.exact))
6113    }
6114
6115    pub fn is_far_turbo(&self) -> bool {
6116        self.o1_turbo.is_some() && self.o1_graph_backend()
6117    }
6118
6119    /// A backend with the far field's prompt path and stages.
6120    fn o1_graph_backend(&self) -> bool {
6121        crate::gpu::wgpu_active() || crate::gpu::cuda_active() || crate::gpu::backend_name() == "metal"
6122    }
6123
6124    /// The whole prompt is read exact on the card, and one seal after it
6125    /// chooses among all of its rows, with the question's queries in the
6126    /// trace. The CUDA graph's way where it has no sealed-chunk kernels (the
6127    /// dense arm); its hybrid arm reads a prompt past the first seal in chunks
6128    /// as the wgpu graph does, so memory stays at the seal's
6129    /// (`CMF_O1_CHUNKS=0` reads it whole there too). `CMF_O1_WHOLE=1` takes
6130    /// either graph the whole way, so the two can be compared row for row.
6131    #[cfg(not(target_os = "macos"))]
6132    fn o1_whole_prompt(&self) -> bool {
6133        match std::env::var("CMF_O1_WHOLE").as_deref() {
6134            Ok("1") => return true,
6135            Ok("0") => return false,
6136            _ => {}
6137        }
6138        crate::gpu::cuda_active() && (self.graph_gdn_layer_count() == 0 || std::env::var("CMF_O1_CHUNKS").as_deref() == Ok("0"))
6139    }
6140
6141    pub fn far_turbo_seal(&self) -> usize {
6142        self.o1_turbo.as_ref().map_or(usize::MAX, |t| t.seal)
6143    }
6144
6145    /// The draft head on top of a far field: a verify's rows attend, and the state moves
6146    /// over the accepted ones only. On the wgpu graph; `CMF_O1_SPEC=0` turns it off.
6147    fn o1_spec(&self) -> bool {
6148        self.o1_active()
6149            && self.o1_on_graph()
6150            && self.o1_graph_backend()
6151            && (self.o1_turbo.is_some() || std::env::var("CMF_O1_SPEC").as_deref() == Ok("1"))
6152            && std::env::var("CMF_O1_SPEC").as_deref() != Ok("0")
6153    }
6154
6155    /// The far field rides the device graph: asked for, or a turbo file's way.
6156    fn o1_on_graph(&self) -> bool {
6157        self.o1_turbo.is_some() || std::env::var("CMF_O1_GPU").as_deref() == Ok("1")
6158    }
6159
6160    /// A turbo file takes the far field for a long prompt and leaves it for a short one,
6161    /// where exact attention and speculation are the faster way.
6162    fn o1_turbo_gate(&mut self, prompt_rows: usize) {
6163        // Off the wgpu and Metal graphs the far field would run on the host, so a turbo file
6164        // runs as the plain file it holds.
6165        if !self.is_far_turbo() {
6166            return;
6167        }
6168        let Some(t) = self.o1_turbo.clone() else { return };
6169        let want = prompt_rows >= t.seal;
6170        if want != self.o1_active() {
6171            self.clear_sequence_state();
6172            if let Err(e) = self.try_set_o1(want.then(|| t.cfg.clone())) {
6173                tracing::warn!("turbo file: the far field is off: {e}");
6174                self.o1_turbo = None;
6175            }
6176        }
6177    }
6178
6179    /// The rows this seal keeps exact (`CMF_O1_EXACT=FILE:rows`), the same in every layer.
6180    fn o1_choose_exact_rows(&mut self) {
6181        let Some(x) = self.o1_exact_cfg().cloned() else { return };
6182        let Some(c) = self.o1_cfg.clone() else { return };
6183        let layers: Vec<usize> = (0..self.num_layers)
6184            .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())
6185            .collect();
6186        let Some(&first) = layers.first() else { return };
6187        let rows = self.kv_cache.layers[first].seq_len;
6188        let floor = crate::nystrom::o1_deferred_boundary(c.w, c.sink).unwrap_or(usize::MAX);
6189        let target = self.kv_cache.layers[first].o1_pending_boundary().unwrap_or(floor).max(floor);
6190        if rows < target || layers.iter().any(|&li| self.kv_cache.layers[li].seq_len != rows) {
6191            return;
6192        }
6193        let t0 = std::time::Instant::now();
6194        let (nk, hd) = (self.kv_cache.layers[first].num_kv_heads, self.kv_cache.layers[first].head_dim);
6195        let keep = {
6196            let views: Vec<_> = layers.iter().map(|&li| self.kv_cache.layers[li].group_rows()).collect();
6197            let refs: Vec<&dyn crate::dory::LayerRows> = views.iter().map(|v| v as &dyn crate::dory::LayerRows).collect();
6198            crate::dory::pick_exact_rows(&x, &refs, rows, nk, hd, c.m, c.sink, rows.saturating_sub(c.w))
6199        };
6200        tracing::info!("o1: {} exact rows of {rows} chosen in {:.2} s", keep.len(), t0.elapsed().as_secs_f64());
6201        for &li in &layers {
6202            self.kv_cache.layers[li].o1_keep = keep.clone();
6203        }
6204    }
6205
6206    /// Complete a deferred boundary after a full position/span forward.
6207    /// This is the pipeline owner for epoch publication and failure cleanup.
6208    fn o1_progress(&mut self) {
6209        if !self.o1_active() {
6210            return;
6211        }
6212        for li in 0..self.num_layers {
6213            if self.o1_flags.get(li).copied().unwrap_or(false) {
6214                if let Some(err) = self.kv_cache.layers[li].take_o1_error() {
6215                    self.o1_fail(err);
6216                    return;
6217                }
6218            }
6219        }
6220        // A qwen_attention row can seal in the middle of a complete layer
6221        // walk. Consume its transition even though the pending boundary has
6222        // already disappeared from the cache.
6223        self.o1_note_transition();
6224        if !self.o1_pending() {
6225            return;
6226        }
6227        if let Err(err) = self.o1_seal_checked() {
6228            self.o1_fail(err);
6229        }
6230    }
6231
6232    /// Turn a deferred O(1) failure raised by a hidden-only forward into the
6233    /// Result error its public batch/span caller must return. The failure
6234    /// path already cleared host/device sequence state; consume only the
6235    /// side-channel marker here and leave the pipeline reusable.
6236    fn check_o1_progress_failure(&mut self, phase: &str) -> Result<(), String> {
6237        if self
6238            .graph_failed
6239            .swap(false, std::sync::atomic::Ordering::Relaxed)
6240        {
6241            self.cancel
6242                .store(false, std::sync::atomic::Ordering::Relaxed);
6243            self.clear_sequence_state();
6244            return Err(format!("{phase}: deferred O(1) transition failed"));
6245        }
6246        Ok(())
6247    }
6248
6249    /// Freeze landmarks + skeleton state after the prompt pass and drop
6250    /// the o1 layers' full KV; decode then runs `step()` per token.
6251    /// Pub for the network split (see `o1_begin`).
6252    pub fn o1_seal(&mut self) {
6253        if let Err(err) = self.o1_seal_checked() {
6254            self.o1_fail(err);
6255        }
6256    }
6257
6258    /// Run a bounded O(1) prefix (`ids`, positions 0..) through the batch
6259    /// graph instead of the host prefill: the same exact attention, with the
6260    /// O(1) layers' rotated queries captured on the device and their K/V rows
6261    /// read back from the mirror, so each layer's collector holds what the
6262    /// host walk would have given its seal. The recurrent and exact layers'
6263    /// state stays on the device for the sealed suffix batches.
6264    /// `Ok(None)`: declined before any device state moved — the caller runs
6265    /// the host prefill. `Ok(Some(h))`: the last prefix row's hidden.
6266    fn o1_prefix_on_graph(
6267        &mut self,
6268        ids: &[u32],
6269        chunk: usize,
6270        mut arch: Option<&mut O1Archive>,
6271    ) -> Result<Option<Vec<f32>>, String> {
6272        let o1_layers: Vec<usize> = (0..self.num_layers)
6273            .filter(|&li| self.o1_flags.get(li).copied().unwrap_or(false))
6274            .collect();
6275        let Some(&first) = o1_layers.first() else {
6276            return Ok(None);
6277        };
6278        let (nkv, hd) = {
6279            let c = &self.kv_cache.layers[first];
6280            (c.num_kv_heads, c.head_dim)
6281        };
6282        let nh = self.num_heads;
6283        if chunk == 0
6284            || o1_layers.iter().any(|&li| {
6285                let c = &self.kv_cache.layers[li];
6286                self.layer_num_heads(li) != nh
6287                    || (c.num_kv_heads, c.head_dim) != (nkv, hd)
6288                    || c.seq_len != 0
6289                    || c.o1_pending_boundary().is_none()
6290            })
6291            || !crate::gpu::o1_qcap_begin(&o1_layers)
6292        {
6293            return Ok(None);
6294        }
6295        let hs = self.hidden_size;
6296        let n = ids.len();
6297        let mut last = vec![0f32; hs];
6298        let mut pos = 0;
6299        self.o1_prefix_tail.clear();
6300        // `CMF_PREFILL_PROF`: where the prefix's time goes (the chunks, the
6301        // queries off the card, the K/V rows off the card, their way into the cache).
6302        let prof = std::env::var("CMF_PREFILL_PROF").is_ok();
6303        let (mut t_chunks, mut t_q) = (0f64, 0f64);
6304        // The seal's queries leave the card chunk by chunk, one row in `QT_STRIDE`: its
6305        // landmarks are means over long segments.
6306        const QT_STRIDE: usize = 8;
6307        let qrow = nh * hd;
6308        // A backend may hand back the kept rows alone (CUDA gathers them on the card).
6309        let strided = crate::gpu::o1_qcap_stride(QT_STRIDE);
6310        let mut qs: Vec<Vec<f32>> = vec![Vec::new(); o1_layers.len()];
6311        // the prompt's tail for the draft head over the far field
6312        let tail_from = n.saturating_sub(crate::dory::EXACT_TAIL);
6313        // A chunk whose rows nobody reads (before the last and the tail) is submitted
6314        // while the next one is encoded, and the queries leave the card every
6315        // `CMF_O1_QCAP_DRAIN` chunks (8; 1 = every chunk, waiting for each): a drain
6316        // waits for the card. SenseNova-Loop-9B over Vulkan, 8192 rows in 128-row
6317        // chunks: one wait a chunk spent half the prefix with the card idle.
6318        let drain_every = std::env::var("CMF_O1_QCAP_DRAIN").ok().and_then(|v| v.parse().ok()).unwrap_or(8usize).max(1);
6319        let (mut drain_from, mut undrained) = (0usize, 0usize);
6320        while pos < n {
6321            let end = o1_chunk_end(pos, chunk, n);
6322            let bk = end - pos;
6323            let mut hiddens = vec![0f32; bk * hs];
6324            for (j, &id) in ids[pos..end].iter().enumerate() {
6325                hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
6326            }
6327            let positions: Vec<usize> = (pos..end).collect();
6328            let t_c = std::time::Instant::now();
6329            let defer = drain_every > 1 && end < n && end <= tail_from;
6330            #[cfg(not(target_os = "macos"))]
6331            crate::gpu::set_batch_defer(defer);
6332            let outcome = self.try_batch_graph_wgpu(&mut hiddens, &positions, bk, None);
6333            #[cfg(not(target_os = "macos"))]
6334            crate::gpu::set_batch_defer(false);
6335            t_chunks += t_c.elapsed().as_secs_f64();
6336            let t_d = std::time::Instant::now();
6337            match outcome {
6338                crate::gpu::BatchGraphOutcome::Completed => {
6339                    if !defer {
6340                        last.copy_from_slice(&hiddens[(bk - 1) * hs..]);
6341                    }
6342                    if end > tail_from {
6343                        let from = pos.max(tail_from);
6344                        self.o1_prefix_tail.extend_from_slice(&hiddens[(from - pos) * hs..]);
6345                    }
6346                }
6347                crate::gpu::BatchGraphOutcome::Declined if pos == 0 => {
6348                    let _ = crate::gpu::o1_qcap_take();
6349                    return Ok(None);
6350                }
6351                _ => {
6352                    let _ = crate::gpu::o1_qcap_take();
6353                    return Err("O(1) prefix batch graph stopped after admission".into());
6354                }
6355            }
6356            undrained += 1;
6357            pos = end;
6358            if defer && undrained < drain_every {
6359                continue;
6360            }
6361            let Some(drained) = crate::gpu::o1_qcap_drain() else {
6362                let _ = crate::gpu::o1_qcap_take();
6363                return Err("O(1) prefix: query readback failed".into());
6364            };
6365            // the rows since the last drain
6366            let rows_n = end - drain_from;
6367            for (i, (_, rows)) in drained.iter().enumerate() {
6368                if strided {
6369                    let kept = (drain_from..end).filter(|p| p % QT_STRIDE == 0).count();
6370                    if rows.len() != kept * qrow {
6371                        let _ = crate::gpu::o1_qcap_take();
6372                        return Err(format!("O(1) prefix: {} query values, expected {}", rows.len(), kept * qrow));
6373                    }
6374                    qs[i].extend_from_slice(rows);
6375                    continue;
6376                }
6377                if rows.len() != rows_n * qrow {
6378                    let _ = crate::gpu::o1_qcap_take();
6379                    return Err(format!("O(1) prefix: {} query values, expected {}", rows.len(), rows_n * qrow));
6380                }
6381                for p in drain_from..end {
6382                    if p % QT_STRIDE == 0 {
6383                        qs[i].extend_from_slice(&rows[(p - drain_from) * qrow..(p - drain_from + 1) * qrow]);
6384                    }
6385                }
6386            }
6387            drain_from = end;
6388            undrained = 0;
6389            t_q += t_d.elapsed().as_secs_f64();
6390        }
6391        let _ = crate::gpu::o1_qcap_take();
6392        let t_kv = std::time::Instant::now();
6393        let pulls: Vec<(usize, usize, usize)> = o1_layers.iter().map(|&li| (li, 0, n)).collect();
6394        let kv = crate::gpu::graph_kv_read_rows(self.graph_kv_id, &pulls, nkv, hd)
6395            .ok_or("O(1) prefix: K/V readback failed")?;
6396        let (t_kv, t_app) = (t_kv.elapsed().as_secs_f64(), std::time::Instant::now());
6397        let row = nkv * hd;
6398        if arch.is_none() {
6399            // without an archive each layer's rows go into its own cache: the
6400            // layers side by side
6401            for ((&li, q), (k, v)) in o1_layers.iter().zip(&qs).zip(&kv) {
6402                if k.len() != n * row || v.len() != n * row || q.len() != n.div_ceil(QT_STRIDE) * qrow {
6403                    return Err(format!(
6404                        "O(1) prefix: layer {li} read back {}/{}/{} values, expected {}/{}/{}",
6405                        k.len(),
6406                        v.len(),
6407                        q.len(),
6408                        n * row,
6409                        n * row,
6410                        n.div_ceil(QT_STRIDE) * qrow
6411                    ));
6412                }
6413            }
6414            let mut work: Vec<(&mut crate::kv_cache::LayerKvCache, Vec<f32>, (Vec<f32>, Vec<f32>))> = Vec::new();
6415            let mut by_layer: Vec<Option<(Vec<f32>, (Vec<f32>, Vec<f32>))>> = (0..self.kv_cache.layers.len()).map(|_| None).collect();
6416            for ((&li, q), kvp) in o1_layers.iter().zip(qs).zip(kv) {
6417                by_layer[li] = Some((q, kvp));
6418            }
6419            for (cache, slot) in self.kv_cache.layers.iter_mut().zip(by_layer) {
6420                if let Some((q, kvp)) = slot {
6421                    work.push((cache, q, kvp));
6422                }
6423            }
6424            let par = std::thread::available_parallelism().map_or(1, |p| p.get()).clamp(1, 8);
6425            let per = work.len().div_ceil(par).max(1);
6426            std::thread::scope(|sc| {
6427                for part in work.chunks_mut(per) {
6428                    sc.spawn(move || {
6429                        for (cache, q, (k, v)) in part.iter_mut() {
6430                            cache.o1_set_q_stride(QT_STRIDE);
6431                            cache.reserve_rows(n);
6432                            for p in 0..n {
6433                                cache.append(&k[p * row..(p + 1) * row], &v[p * row..(p + 1) * row], &[]);
6434                            }
6435                            cache.o1_set_q_trace(std::mem::take(q));
6436                        }
6437                    });
6438                }
6439            });
6440            if prof {
6441                eprintln!(
6442                    "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",
6443                    t_app.elapsed().as_secs_f64()
6444                );
6445            }
6446            return Ok(Some(last));
6447        }
6448        for ((&li, q), (k, v)) in o1_layers.iter().zip(qs).zip(kv) {
6449            if k.len() != n * row || v.len() != n * row || q.len() != n.div_ceil(QT_STRIDE) * qrow {
6450                return Err(format!(
6451                    "O(1) prefix: layer {li} read back {}/{}/{} values, expected {}/{}/{}",
6452                    k.len(),
6453                    v.len(),
6454                    q.len(),
6455                    n * row,
6456                    n * row,
6457                    n.div_ceil(QT_STRIDE) * qrow
6458                ));
6459            }
6460            let cache = &mut self.kv_cache.layers[li];
6461            cache.o1_set_q_stride(QT_STRIDE);
6462            cache.reserve_rows(n);
6463            for p in 0..n {
6464                cache.append(&k[p * row..(p + 1) * row], &v[p * row..(p + 1) * row], &[]);
6465            }
6466            if let Some(a) = arch.as_deref_mut() {
6467                let dir = a.dir.clone();
6468                let mut layer = O1ArchLayer {
6469                    li,
6470                    k: ArchStore::new(dir.as_deref(), format!("{li}-k"))?,
6471                    v: ArchStore::new(dir.as_deref(), format!("{li}-v"))?,
6472                    q: ArchStore::new(dir.as_deref(), format!("{li}-q"))?,
6473                };
6474                layer.k.push(&k)?;
6475                layer.v.push(&v)?;
6476                layer.q.push(&q)?;
6477                a.layers.push(layer);
6478                a.rows = n;
6479                a.stride = QT_STRIDE;
6480                a.nh = nh;
6481                a.nk = nkv;
6482                a.hd = hd;
6483            }
6484            cache.o1_set_q_trace(q);
6485        }
6486        if prof {
6487            eprintln!(
6488                "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",
6489                t_app.elapsed().as_secs_f64()
6490            );
6491        }
6492        Ok(Some(last))
6493    }
6494
6495    /// Enable/disable the structured per-token telemetry trace (B4).
6496    pub fn set_trace(&mut self, on: bool) {
6497        self.trace = on;
6498    }
6499
6500    /// Replace all request-scoped sampler options and reset the random stream.
6501    /// This is required for deterministic `seed` semantics in pooled servers.
6502    pub fn set_sampler_config(&mut self, config: SamplerConfig) {
6503        self.rng = match config.seed {
6504            Some(seed) => SplitMix64::new(seed),
6505            None => SplitMix64::from_entropy(),
6506        };
6507        self.sampler_config = config;
6508    }
6509
6510    /// Toggle the per-token confidence reduction (a full-vocab
6511    /// softmax each token). `bench --core` turns it off so the timed
6512    /// loop matches llama-bench's core contract; the result's
6513    /// `confidence` vec is empty while off.
6514    pub fn set_confidence(&mut self, on: bool) {
6515        self.confidence_on = on;
6516    }
6517
6518    /// Set the confidence-calibration temperature (B1). Values ≤0 are
6519    /// clamped to raw (1.0).
6520    pub fn set_calib_temp(&mut self, t: f32) {
6521        self.calib_temp = if t > 1e-3 { t } else { 1.0 };
6522    }
6523
6524    /// The active calibration temperature (1.0 = raw probability).
6525    pub fn calib_temp(&self) -> f32 {
6526        self.calib_temp
6527    }
6528
6529    /// The primary (full-attention) RoPE inverse-frequency table selected
6530    /// from the CMF architecture.  This is read-only diagnostic state for
6531    /// parity checks; local sliding layers may use `inv_freq_local` instead.
6532    pub fn rope_inv_freq(&self) -> &[f32] {
6533        self.inv_freq.as_slice()
6534    }
6535
6536    /// Partial rotary (Qwen3.5): rotate only the first `rotary_dim` dims;
6537    /// the frequency table is rebuilt over the rotary dims.
6538    pub fn set_rotary(&mut self, rotary_dim: usize, base: f32) {
6539        self.rotary_dim = rotary_dim.min(self.head_dim);
6540        self.inv_freq = std::sync::Arc::new(attention::rope_inv_freq(self.rotary_dim, base));
6541        // The packed resident graph owns its own inverse-frequency plane;
6542        // changing RoPE after it was built must not leave a stale device
6543        // model behind the exact host configuration.
6544        self.embryo_graph = None;
6545    }
6546
6547    fn attn_cfg(&self, position: usize) -> QwenAttnCfg<'_> {
6548        QwenAttnCfg {
6549            mrope: None,
6550            num_heads: self.num_heads,
6551            num_kv_heads: self.num_kv_heads,
6552            head_dim: self.head_dim,
6553            hidden_size: self.hidden_size,
6554            position,
6555            inv_freq: &self.inv_freq,
6556            rotary_dim: self.rotary_dim,
6557            scale: self.attn_scale,
6558            softcap: self.attn_softcap,
6559            window: None,
6560            v_norm: false,
6561            qk_norm_after_rope: self.qk_norm_after_rope,
6562            gate_sigmoid: self.proj_gate_sigmoid,
6563            q_norm: None,
6564            k_norm: None,
6565            output_gate: false,
6566            softplus_gate: None,
6567            rope_scale: self.rope_scale,
6568            bias: None,
6569            rms_eps: self.rms_eps,
6570            norm_style: self.norm_style,
6571            pool: self.pool.as_deref(),
6572            v_head_dim: self.v_head_dim.unwrap_or(self.head_dim),
6573            value_in: None,
6574        }
6575    }
6576
6577    /// Generate text from a plain-text prompt. Streams tokens via `on_token`.
6578    pub fn generate(
6579        &mut self,
6580        prompt: &str,
6581        max_tokens: usize,
6582        task_mask: Option<&TaskMask>,
6583        on_token: Option<TokenCallback>,
6584    ) -> Result<GenerateResult, String> {
6585        let input_ids = self.tokenizer.with_bos(self.tokenizer.encode(prompt));
6586        self.generate_from_ids(&input_ids, max_tokens, task_mask, on_token)
6587    }
6588
6589    /// Generate from a V4.1 multimodal prompt prepared by the vision module.
6590    /// Vision rows are encoded once and fed through the same bounded token walk as text.
6591    pub fn generate_from_vl(
6592        &mut self,
6593        input: &crate::dsv41_vision::PreparedVlInputs,
6594        max_tokens: usize,
6595        task_mask: Option<&TaskMask>,
6596        on_token: Option<TokenCallback>,
6597    ) -> Result<GenerateResult, String> {
6598        let Some(dsv41) = &self.dsv41 else {
6599            return Err("V4.1 multimodal input requires a DeepSeek-V4.1 pipeline".into());
6600        };
6601        if input.token_ids.is_empty() {
6602            return Err("empty V4.1 multimodal prompt".into());
6603        }
6604        if input.token_types.len() != input.token_ids.len() {
6605            return Err(format!(
6606                "V4.1 token type count {} != token count {}",
6607                input.token_types.len(),
6608                input.token_ids.len()
6609            ));
6610        }
6611        let dim = dsv41.2.dim;
6612        let mut embeddings = vec![None; input.token_ids.len()];
6613        let mut participates = vec![true; input.token_ids.len()];
6614        if !input.images.is_empty() {
6615            let vision = self
6616                .dsv41_vision
6617                .as_ref()
6618                .ok_or_else(|| "V4.1 image prompt has no loaded vision tower".to_string())?;
6619            for image in &input.images {
6620                let end = image.start.saturating_add(image.types.len());
6621                if end > input.token_ids.len() {
6622                    return Err(format!(
6623                        "V4.1 image span {}..{} exceeds prompt length {}",
6624                        image.start,
6625                        end,
6626                        input.token_ids.len()
6627                    ));
6628                }
6629                let mut span = vec![0.0f32; image.types.len() * dim];
6630                vision.fill_image_span(image, &mut span, self.pool.as_deref())?;
6631                for (offset, &kind) in image.types.iter().enumerate() {
6632                    let pos = image.start + offset;
6633                    if input.token_types[pos] != kind {
6634                        return Err(format!(
6635                            "V4.1 image type mismatch at position {pos}: {} != {kind}",
6636                            input.token_types[pos]
6637                        ));
6638                    }
6639                    embeddings[pos] = Some(span[offset * dim..(offset + 1) * dim].to_vec());
6640                    participates[pos] = false;
6641                }
6642            }
6643        }
6644        for (pos, &kind) in input.token_types.iter().enumerate() {
6645            if kind == crate::dsv41_vision::TEXT && embeddings[pos].is_some() {
6646                return Err(format!("V4.1 text position {pos} has an image embedding"));
6647            }
6648            if kind != crate::dsv41_vision::TEXT && embeddings[pos].is_none() {
6649                return Err(format!("V4.1 image position {pos} has no image embedding"));
6650            }
6651        }
6652        self.dsv41_prefill = Some((embeddings, participates));
6653        let result = self.generate_from_ids(&input.token_ids, max_tokens, task_mask, on_token);
6654        self.dsv41_prefill = None;
6655        result
6656    }
6657
6658    /// `None` when the mask forbids nothing (see `TaskMask::fully_open`).
6659    fn drop_open_mask<'m>(&self, m: Option<&'m TaskMask>) -> Option<&'m TaskMask> {
6660        m.filter(|m| !m.fully_open(self.intermediate_size, self.num_heads))
6661    }
6662
6663    /// Generate from prepared token ids (e.g. a chat template).
6664    ///
6665    /// With an MTP head, greedy generation without a task mask takes the
6666    /// speculative path: the MTP module drafts the token after next and
6667    /// the main model verifies both in one fused two-position forward
6668    /// (weights streamed once). The output is EXACTLY the vanilla greedy
6669    /// sequence — a rejected draft is rolled back — MTP only buys speed.
6670    pub fn generate_from_ids(
6671        &mut self,
6672        input_ids: &[u32],
6673        max_tokens: usize,
6674        task_mask: Option<&TaskMask>,
6675        on_token: Option<TokenCallback>,
6676    ) -> Result<GenerateResult, String> {
6677        let out = self.generate_with_prompt_rows(input_ids, None, max_tokens, task_mask, on_token);
6678        crate::gpu::generation_end();
6679        out
6680    }
6681
6682    /// Generate from complete prompt embeddings [token_count, hidden_size].
6683    /// Text rows can be obtained with `embed_id`; media rows replace only
6684    /// their expanded placeholder positions. Rows are already scaled and
6685    /// enter `PrefillIn::Hidden`, so a device graph must not re-embed them.
6686    /// Token-only KV reuse is disabled both into and out of this request.
6687    pub fn generate_from_embeds(
6688        &mut self,
6689        input_ids: &[u32],
6690        prompt_rows: &[f32],
6691        max_tokens: usize,
6692        task_mask: Option<&TaskMask>,
6693        on_token: Option<TokenCallback>,
6694    ) -> Result<GenerateResult, String> {
6695        if input_ids.is_empty()
6696            || input_ids.len().checked_mul(self.hidden_size) != Some(prompt_rows.len())
6697        {
6698            return Err("embedded prompt dimensions must be [tokens, hidden_size]".into());
6699        }
6700        if prompt_rows.iter().any(|x| !x.is_finite()) {
6701            return Err("embedded prompt contains non-finite values".into());
6702        }
6703        // A turbo file picks its far field by the prompt's length: an image prompt
6704        // under the seal reads exact, whatever the previous request held.
6705        self.o1_turbo_gate(input_ids.len());
6706        if !self.can_prefill_batched()
6707            || self.dyn_router.is_some()
6708            || self.o1_active()
6709            || self.gpu_plan.is_some()
6710        {
6711            return Err("embedded prompts require the ordinary transformer path without O(1), dynamic routing or GPU splitting".into());
6712        }
6713        // The MTP head drafts over token rows: an embedded prompt decodes
6714        // without it (the greedy text is the same; MTP state is rebuilt from
6715        // the next prompt, and token reuse out of this request is off).
6716        // SenseNova-Loop-9B's release ships the head, and its image prompts
6717        // were refused before.
6718        let mtp = self.mtp.take();
6719        let out = self.generate_with_prompt_rows(
6720            input_ids,
6721            Some(prompt_rows),
6722            max_tokens,
6723            task_mask,
6724            on_token,
6725        );
6726        self.mtp = mtp;
6727        out
6728    }
6729
6730    fn generate_with_prompt_rows(
6731        &mut self,
6732        input_ids: &[u32],
6733        prompt_rows: Option<&[f32]>,
6734        max_tokens: usize,
6735        task_mask: Option<&TaskMask>,
6736        mut on_token: Option<TokenCallback>,
6737    ) -> Result<GenerateResult, String> {
6738        #[cfg(target_os = "macos")]
6739        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
6740        if std::env::var("CMF_TRACE_H").is_ok() {
6741            eprintln!("input_ids: {input_ids:?}");
6742        }
6743        if input_ids.is_empty() {
6744            return Err("empty prompt: nothing to generate from".to_string());
6745        }
6746        // A prior graph failure is terminal for that sequence but must not
6747        // poison the next independent request.  Keep this flag separate from
6748        // the externally-owned cooperative cancel bit.
6749        self.graph_failed
6750            .store(false, std::sync::atomic::Ordering::Relaxed);
6751        // A mask that forbids nothing still costs every fused path and
6752        // whole-token graph, all of which are gated on `is_none()`. A
6753        // narrowed file whose one segment is always on carries exactly
6754        // such a mask — drop it here rather than pay 5x for a no-op.
6755        self.o1_turbo_gate(input_ids.len());
6756        self.mtp_pos_base = 0;
6757        let prev_mtp_warm = self.mtp_warm_base.take();
6758        // the draft head's rows a chat snapshot keeps (counted from its base)
6759        let mut mtp_keep: Option<usize> = None;
6760        let task_mask = self.drop_open_mask(task_mask);
6761        // Unlimited-OCR: the page coordinates of this prompt.
6762        if self.dash.is_some() {
6763            if prompt_rows.is_none() {
6764                return Err("Unlimited-OCR reads images: pass at least one".into());
6765            }
6766            let eos = self.tokenizer.eos_token_id.unwrap_or(1);
6767            if let Some(d) = self.dash.as_mut() {
6768                d.begin(input_ids, eos)?;
6769            }
6770        }
6771        // A block-diffusion model generates whole blocks by denoising
6772        // previews, unless the request asks for the causal decode.
6773        if self.clover.is_some() && !self.clover_causal_request() {
6774            if prompt_rows.is_some() || task_mask.is_some() {
6775                return Err("block-diffusion generation takes token prompts without task masks".into());
6776            }
6777            return self.clover_generate(input_ids, max_tokens, on_token);
6778        }
6779
6780        // Cross-turn KV reuse: a chat app resends the whole history
6781        // every turn; when the new ids strictly EXTEND what the cache
6782        // already holds, prefill only the tail — turn latency stays
6783        // proportional to the new text instead of the whole session.
6784        // Extension-only (no rollback), so it is exact for every layer
6785        // kind including recurrent state; MTP/o1/task-mask runs keep
6786        // the fresh-sequence path. CMF_KV_REUSE=0 disables.
6787        let mut reuse_from = if self.dory.is_some() {
6788            self.dory_cached_prefix(input_ids)
6789        } else {
6790            let on = !std::env::var("CMF_KV_REUSE").is_ok_and(|v| v == "0");
6791            if on
6792                && prompt_rows.is_none()
6793                && task_mask.is_none()
6794                && self.mtp.is_none()
6795                && !(self.mimo_mtp.is_some() && self.speculative)
6796                && self.o1_cfg.is_none()
6797                && self.dsv41.is_none()
6798            {
6799                self.cached_prefix_len(input_ids)
6800            } else {
6801                0
6802            }
6803        };
6804        // The device may own rows the host tail prefill needs (wgpu decode
6805        // writes only its mirror): hand them to the host, or start fresh.
6806        if reuse_from > 0 && !self.prepare_kv_reuse(reuse_from) {
6807            reuse_from = 0;
6808        }
6809        // The CUDA hybrid arm: a chat turn that starts with the ids before
6810        // the last turn's assistant header goes back to the GDN snapshot the
6811        // card took there; the attention mirrors rewind with it. The rows
6812        // before it are prompt rows no decode wrote, so this is exact after
6813        // any speculative round, and the draft head reads from there on.
6814        if reuse_from == 0 && prompt_rows.is_none() && task_mask.is_none() {
6815            let n = self.gdn_snap_reuse(input_ids);
6816            if n > 0 {
6817                reuse_from = n;
6818                self.kv_history.truncate(n);
6819                for l in &mut self.kv_cache.layers {
6820                    let d = l.pos_len().saturating_sub(n);
6821                    if d > 0 {
6822                        l.truncate_last(d);
6823                    }
6824                }
6825                self.graph_logits = None;
6826                // The draft head's rows before `n` are the last prompt's
6827                // rows when it was warmed over that whole prompt: they stay,
6828                // and it reads the conversation, not just the new turn.
6829                if self.mtp.is_some() {
6830                    match prev_mtp_warm {
6831                        Some(b) if b <= n => {
6832                            self.mtp_pos_base = b;
6833                            mtp_keep = Some(n - b);
6834                        }
6835                        _ => self.mtp_pos_base = n,
6836                    }
6837                }
6838                if std::env::var("CMF_PREFILL_PROF").is_ok() {
6839                    eprintln!("kv-reuse: GDN snapshot at {n} of {} prompt positions", input_ids.len());
6840                }
6841            }
6842        }
6843        // A diverging turn (`rollback_prefix_len`): drop every row past the
6844        // common prefix, so the tail prefill appends at `reuse_from`.
6845        if reuse_from > 0 && self.dory.is_some() && reuse_from < self.kv_history.len() {
6846            // The device's rings are addressed by position, so going back there
6847            // is only this: the next rows overwrite the rolled-back ones.
6848            if let Some(b) = &mut self.dory {
6849                let kv_row = b.0.cfg.nk * b.0.cfg.hd;
6850                b.1.rollback(reuse_from, kv_row);
6851            }
6852            self.kv_history.truncate(reuse_from);
6853            self.graph_logits = None;
6854        }
6855        if reuse_from > 0 && self.dory.is_none() && !self.bounded_native() && reuse_from < self.kv_history.len() {
6856            for l in &mut self.kv_cache.layers {
6857                let d = l.pos_len() - reuse_from;
6858                l.truncate_last(d);
6859            }
6860            if std::env::var("CMF_PREFILL_PROF").is_ok() {
6861                eprintln!(
6862                    "kv-reuse: rolled back {} answer position(s) to the common prefix",
6863                    self.kv_history.len() - reuse_from
6864                );
6865            }
6866            self.kv_history.truncate(reuse_from);
6867            self.graph_logits = None;
6868        }
6869        self.swa_trim_anchor = input_ids.len();
6870        self.dflash_tap_from = match &self.dflash {
6871            Some(d) if (0..d.g.layers).all(|l| d.g.window_of(l) > 0) => {
6872                let w = (0..d.g.layers).map(|l| d.g.window_of(l)).max().unwrap_or(0);
6873                input_ids.len().saturating_sub(w + crate::dflash::BLOCK_SLACK)
6874            }
6875            _ => 0,
6876        };
6877        self.last_prefill_tokens = input_ids.len() - reuse_from;
6878        let bounded_native = self.bounded_native();
6879        if reuse_from == 0 {
6880            // Fresh sequence — the cache holds absolute positions.
6881            // MTP never participates in cross-turn KV reuse, so a
6882            // high-vocabulary token from the previous request must not keep
6883            // this request on its expensive full draft head.
6884            self.reset_fresh_mtp_draft_state();
6885            self.clear_sequence_state();
6886        } else if std::env::var("CMF_PREFILL_PROF").is_ok() {
6887            eprintln!(
6888                "kv-reuse: {} of {} prompt positions already cached",
6889                reuse_from,
6890                input_ids.len()
6891            );
6892        }
6893        crate::gpu::graph_race_begin_generation();
6894        // Optional bounded calibration prefix. Keep the requested value
6895        // even when it is longer than the prompt; the collecting layer will
6896        // defer at the effective boundary and remain exact for short input.
6897        let o1_prefill = if self.o1_active() && task_mask.is_none() {
6898            std::env::var("CMF_O1_PREFILL")
6899                .ok()
6900                .and_then(|v| v.parse::<usize>().ok())
6901                .filter(|&p| p > 0)
6902                // Exact rows are chosen before the prompt's last rows, which then read them.
6903                .or_else(|| {
6904                    self.o1_exact_cfg()
6905                        .map(|_| {
6906                            let max = std::env::var("CMF_O1_PREFIX_MAX")
6907                                .ok()
6908                                .and_then(|v| v.parse().ok())
6909                                .or(self.o1_turbo.as_ref().map(|t| t.seal))
6910                                .unwrap_or(O1_PREFIX_MAX);
6911                            input_ids.len().saturating_sub(crate::dory::EXACT_TAIL).min(max)
6912                        })
6913                        .filter(|&p| p > 0)
6914                })
6915        } else {
6916            None
6917        };
6918        if task_mask.is_none() {
6919            self.o1_begin_with_prefix(o1_prefill);
6920        }
6921        if let Ok(f) = std::env::var("CMF_O1_TOKENS_DUMP") {
6922            let b: Vec<u8> = input_ids.iter().flat_map(|v| v.to_le_bytes()).collect();
6923            let _ = std::fs::write(f, b);
6924        }
6925
6926        // Speculative decode is off under o1: a rejected draft can't be
6927        // rolled back out of the far accumulators / ring window (the
6928        // Nyström insertion is irreversible by design).
6929        // The wgpu token graph owns a device K/V mirror that speculative
6930        // rollback would desync — the two are mutually exclusive.
6931        let graph_on = crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode);
6932        // Graph speculative decode (`CMF_GRAPH_SPEC=1`): the MTP head
6933        // drafts, ONE batched graph submit verifies the whole chain.
6934        //
6935        // It now PAYS on Qwen3.6-27B / RTX 5090 — 51.1 tok/s against a
6936        // plain 49.4 at k=3, medians of three, 89% of drafts accepted,
6937        // and the greedy continuation is byte-identical to the plain
6938        // path. That took the batch matvec sharing its nibble unpack
6939        // across the batch (`CMF_MV_BK=2`); before it, the same round
6940        // measured 43.6, an 11% LOSS, which is what the earlier note
6941        // here described.
6942        //
6943        // Still opt-in. One model's win is not a default: the verify
6944        // rides `gdn_spec_restore` and a batched frame whose numerics
6945        // are the batch kernels', and that has to be shown on more than
6946        // one architecture before every greedy decode takes it.
6947        // Greedy (with or without penalties) verifies by argmax equality.
6948        // Sampling (temperature > 0) can go through speculative SAMPLING —
6949        // draft from the MTP head's own post-chain distribution, accept
6950        // with min(1, p/q), correct from max(0, p − q); the emitted stream
6951        // is distributed exactly as the plain sampler's — but it is
6952        // OPT-IN (`CMF_GRAPH_SPEC_SAMPLE=1`): measured on Qwen3.8-27B /
6953        // RTX 5090 at the instruct row (0.7 / 0.80 / 20 / presence 1.5)
6954        // it decoded 19-22 tok/s against a plain 40 — nine post-chain
6955        // distributions a round plus a lower acceptance than greedy's,
6956        // against a verify that costs 2.7 single tokens. The greedy arms
6957        // pay +10%; the sampling arm needs a cheaper verify first.
6958        // Native Metal has a fast row-batch verify, but it is NOT admitted
6959        // by default: a real-model exactness check found an emitted greedy
6960        // divergence from the serial path.  Every native-Metal speculative
6961        // arm therefore requires the explicit `CMF_GRAPH_SPEC=1` experiment
6962        // gate until the batch kernels are numerically qualified.  If it is
6963        // explicitly enabled, its sampling arm is useful only for a config
6964        // the SPARSE chain serves (a top-k within `sparse_ok`): without it a
6965        // round builds nine 248k-float distributions on the host, which is
6966        // the 5090's measured loss and not a cost the round-token proxy
6967        // below can see. A top-k-less sampling config keeps the plain path
6968        // unless asked for by name.
6969        #[cfg(target_os = "macos")]
6970        let metal_graph = crate::gpu::q1_force()
6971            && crate::gpu::enabled_here()
6972            && std::env::var("CMF_GPU_BLOCK")
6973                .map(|v| v != "0")
6974                .unwrap_or(true);
6975        // `CMF_GPU_BLOCK=0` declines the ordinary native block route but
6976        // does not change the backend identity: a separately requested wgpu
6977        // graph can still reach `graph_spec_step`, whose native branch uses
6978        // VerifyGraph. Keep the quality policy tied to that identity, not to
6979        // the particular block-route admission above.
6980        #[cfg(target_os = "macos")]
6981        let native_metal_backend = crate::gpu::q1_force();
6982        #[cfg(not(target_os = "macos"))]
6983        let metal_graph = false;
6984        #[cfg(not(target_os = "macos"))]
6985        let native_metal_backend = false;
6986        let spec_sample_env = std::env::var("CMF_GRAPH_SPEC_SAMPLE").ok();
6987        // A round whose cost is the MEASURED one: greedy (argmax rows), or
6988        // sampling through the sparse chain. Anything else pays the dense
6989        // chain's host time, which no proxy can price.
6990        let spec_cheap_round =
6991            self.sampler_config.temperature < 1e-6 || sampler::sparse_ok(&self.sampler_config);
6992        let spec_sampling_ok = self.sampler_config.temperature < 1e-6
6993            || match spec_sample_env.as_deref() {
6994                Some("1") => true,
6995                Some(_) => false,
6996                None => metal_graph && spec_cheap_round,
6997            };
6998        // ON by default for greedy on the wgpu graph: with the draft on
6999        // the graph and the verify bit-exact, it measured 58.7 tok/s
7000        // against a plain 48.1 on Qwen3.8-27B q4tp / RTX 5090 (k=4) and
7001        // 51.1 against 49.4 on Qwen3.6-27B, and a round that stops
7002        // paying turns itself off below (acceptance watchdog).
7003        // `CMF_GRAPH_SPEC=0` disables; `=1` is the explicit opt-in spelling.
7004        // …but only where the batched verify has its register-blocked
7005        // kernel: q4tp dense FFNs (graph kind 6). q4t and q8_2f verify
7006        // through tile GEMMs today and measured a LOSS (q8_2f 22 against
7007        // 29 tok/s), the 2-bit plane the same; those stay opt-in
7008        // (`CMF_GRAPH_SPEC=1`).
7009        // …at least in nine dense FFNs of ten: a healed file carries its
7010        // last two layers at q8_2f, and two tile-GEMM verifies among 64 do
7011        // not change the arithmetic (measured: the healed q4tp file
7012        // decodes at the plain file's rate and would otherwise sit out).
7013        let (mut dense_n, mut dense_q4tp) = (0usize, 0usize);
7014        for lw in &self.weights.layers {
7015            if let FfnKind::Dense(d) = &lw.ffn {
7016                dense_n += 1;
7017                if matches!(d.gate_proj.graph_weight(), Some((_, _, 6, _)))
7018                    && matches!(d.up_proj.graph_weight(), Some((_, _, 6, _)))
7019                    && matches!(d.down_proj.graph_weight(), Some((_, _, 6, _)))
7020                {
7021                    dense_q4tp += 1;
7022                }
7023            }
7024        }
7025        // …and only where the MTP block itself runs on the graph. A MoE
7026        // draft block (Qwen3.6-35B-A3B, Apex-35B: 256 experts in the MTP
7027        // layer) fails `mtp_graph_ok`, so it drafts — and warms its cache
7028        // over the whole prompt — op by op on the host. Apex-35B q4tp on an
7029        // A40 + Xeon Gold 6342: greedy 51.8 against 65.6 tok/s plain (300
7030        // tokens, 57 % accepted), and 2.5 ms per prompt position (a
7031        // 4096-token ingest 171 against 295 tok/s); the published
7032        // Qwen3.6-35B-A3B 79.7 against 86.6. `CMF_GRAPH_SPEC=1` opts in.
7033        // Native Metal has no wgpu graph: its draft step is `mtp_step_metal`,
7034        // which takes the same block shape.
7035        #[cfg(feature = "gpu")]
7036        let mtp_on_graph = self.mtp.as_ref().is_none_or(|m| {
7037            if native_metal_backend {
7038                self.mtp_block_shape_ok(m)
7039            } else {
7040                self.mtp_graph_ok(m)
7041            }
7042        });
7043        #[cfg(not(feature = "gpu"))]
7044        let mtp_on_graph = self.mtp.as_ref().is_none_or(|m| !native_metal_backend || self.mtp_block_shape_ok(m));
7045        let spec_default_ok = (dense_n == 0 || dense_q4tp * 10 >= dense_n * 9) && mtp_on_graph;
7046        // Penalties break the draft head's agreement with the trunk (a
7047        // 1.1 repetition penalty measured 2 of 16 accepted): not by
7048        // default there either — off Metal that rule is untouched, and
7049        // suppressed ids keep counting as a penalty there, because no
7050        // measurement on a discrete card says otherwise.
7051        //
7052        // On native Metal the penalized arms DO pay: the draft applies
7053        // the same penalty and the verify scores the penalized rows
7054        // exactly (`greedy_pen`, the plain loop's arithmetic), so the
7055        // text is the plain path's and only the round's shape changes.
7056        // Measured on this M4 — see the report for the interleaved run.
7057        //
7058        // On the CUDA hybrid arm a suppress list alone (a no-think chat
7059        // masks `<think>`) does not count: it reads no history, the draft
7060        // and the verify rows mask the same ids, and the verify rows are
7061        // the plain rows bit for bit, so the round (`greedy_pen`) keeps the
7062        // plain text. Qwen3.8-27B q4tp, RTX 3090, a no-think chat over
7063        // `cortiq serve`: 44.8 tok/s plain before this.
7064        let suppress_only_ok = crate::gpu::cuda_active()
7065            && self.sampler_config.repetition_penalty == 1.0
7066            && self.sampler_config.presence_penalty == 0.0;
7067        let penalized = !metal_graph
7068            && (self.sampler_config.repetition_penalty != 1.0
7069                || self.sampler_config.presence_penalty != 0.0
7070                || (!self.sampler_config.suppress_tokens.is_empty() && !suppress_only_ok));
7071        // …and not on wgpu-over-Metal: the batched verify graph there
7072        // returned 0 accepted drafts and garbage text on a GDN hybrid
7073        // (16.08, Qwen3.5-0.8B) while Vulkan is bit-exact; the Mac's
7074        // default backend is native Metal without a batch graph anyway.
7075        #[cfg(feature = "gpu")]
7076        let metal_wgpu = graph_on && crate::gpu_wgpu::wgpu_backend_is_metal();
7077        #[cfg(not(feature = "gpu"))]
7078        let metal_wgpu = false;
7079        let spec_env = std::env::var("CMF_GRAPH_SPEC").ok();
7080        let spec_wanted = graph_spec_wanted_by_policy(
7081            spec_env.as_deref(),
7082            spec_default_ok,
7083            penalized,
7084            metal_wgpu,
7085            native_metal_backend,
7086        );
7087        if spec_wanted && metal_wgpu {
7088            tracing::warn!(
7089                "CMF_GRAPH_SPEC forced on wgpu/Metal: the batched verify graph is not \
7090                 verified on this backend (garbage measured on Qwen3.5-0.8B)"
7091            );
7092        }
7093        // Native Metal: the b-row verify graph (`try_batch_graph_metal`)
7094        // stands where the wgpu batch graph stands on discrete cards
7095        // (`metal_graph`, above).
7096        // A dynamic router reads φ and may switch skills after every token;
7097        // a speculative round commits several tokens per φ, so the router
7098        // wins (on the host the drafts are off for it already: no graph).
7099        let graph_spec = self.speculative
7100            && (graph_on || metal_graph)
7101            && self.mtp.is_some()
7102            && task_mask.is_none()
7103            && self.dyn_router.is_none()
7104            && (!self.o1_active() || self.o1_spec())
7105            && spec_sampling_ok
7106            && spec_wanted;
7107        // A trunk without a draft block of its own (Ripple): a DFlash sidecar
7108        // drafts a round in one block and the batch graph verifies it, the
7109        // rows of drafts that did not hold let go. Plain greedy only, so the
7110        // text is the plain path's. `CMF_GRAPH_SPEC=0` keeps plain tokens.
7111        #[cfg(feature = "gpu")]
7112        let solo_spec = self.speculative
7113            && graph_on
7114            && !metal_wgpu
7115            && self.mtp.is_none()
7116            && task_mask.is_none()
7117            && self.dyn_router.is_none()
7118            && (!self.o1_active() || self.o1_spec())
7119            && self.sampler_config.temperature < 1e-6
7120            && !penalized
7121            && spec_env.as_deref() != Some("0")
7122            && (self.dflash.is_some() || solo_script().is_some());
7123        #[cfg(feature = "gpu")]
7124        let solo_pin: Option<usize> =
7125            std::env::var("CMF_GRAPH_SPEC_K").ok().and_then(|v| v.parse().ok()).filter(|k| (1..=SOLO_K_MOST).contains(k));
7126        #[cfg(feature = "gpu")]
7127        let mut solo =
7128            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 };
7129        // The host fused pair is an optimization, not a verifier. On real
7130        // q4tp Qwen3.5 a near-tied row produced a different greedy argmax
7131        // from two serial target forwards. That makes a seemingly accepted
7132        // draft change text, which is worse than losing speculative speed.
7133        // Keep it explicitly experimental until a model/backend has passed
7134        // a long exact-ID gate; the native Metal batch verifier has its own
7135        // separate graph admission and is not controlled by this switch.
7136        //
7137        // GDN hybrids are also excluded by default: their recurrence is
7138        // sequential, so the pair lane cannot parallelize and measured 2x
7139        // slower on the 35B. `CMF_MTP_PAIR=1` is deliberately the only
7140        // opt-in for the host fused-pair experiment (not `CMF_MTP=1`).
7141        let host_pair_opt_in = std::env::var("CMF_MTP_PAIR").as_deref() == Ok("1");
7142        let pair_pays = host_pair_opt_in
7143            && (self.gdn_cfg.is_none() || std::env::var("CMF_MTP").as_deref() == Ok("1"));
7144        // Native Metal: say the route ONCE (RUST_LOG=info), including why
7145        // the drafts are off when they are (`graph_spec_wanted_by_policy`).
7146        #[cfg(target_os = "macos")]
7147        if metal_graph {
7148            static SAID: std::sync::Once = std::sync::Once::new();
7149            SAID.call_once(|| {
7150                let spec = if graph_spec {
7151                    let k = std::env::var("CMF_GRAPH_SPEC_K")
7152                        .ok()
7153                        .and_then(|v| v.parse::<usize>().ok())
7154                        .filter(|&v| (1..=8).contains(&v))
7155                        .map(|v| v.to_string())
7156                        .unwrap_or_else(|| {
7157                            if self.metal_small_batch_verify() {
7158                                "auto".to_string()
7159                            } else {
7160                                "7".to_string()
7161                            }
7162                        });
7163                    let arm = if self.sampler_config.temperature < 1e-6 {
7164                        "greedy"
7165                    } else {
7166                        "sampling"
7167                    };
7168                    format!(
7169                        "spec k={k} {arm} (batched verify, draft shortlist {}, trial: proxy)",
7170                        Self::draft_vocab_rows(usize::MAX)
7171                    )
7172                } else if !self.speculative {
7173                    "spec off (CMF_MTP=0)".to_string()
7174                } else if self.mtp.is_none() {
7175                    "spec off (no MTP head)".to_string()
7176                } else if !spec_sampling_ok {
7177                    if spec_cheap_round {
7178                        "spec off (CMF_GRAPH_SPEC_SAMPLE=0)".to_string()
7179                    } else {
7180                        "spec off (sampling without a top-k: the dense chain \
7181                         costs more than it saves)"
7182                            .to_string()
7183                    }
7184                } else if !spec_wanted {
7185                    if spec_env.as_deref() == Some("0") {
7186                        "spec off (CMF_GRAPH_SPEC=0)".to_string()
7187                    } else {
7188                        "spec off (drafts by default only over a q4tp trunk; CMF_GRAPH_SPEC=1 asks for them)".to_string()
7189                    }
7190                } else if task_mask.is_some() {
7191                    "spec off (task mask)".to_string()
7192                } else if !graph_spec && !pair_pays {
7193                    "spec off (host fused pair requires CMF_MTP_PAIR=1 after exact-ID validation)"
7194                        .to_string()
7195                } else {
7196                    "spec off (O(1) attention)".to_string()
7197                };
7198                let on = |var: &str| {
7199                    if std::env::var(var).as_deref() == Ok("0") {
7200                        "off"
7201                    } else {
7202                        "on"
7203                    }
7204                };
7205                tracing::info!(
7206                    "metal native: {spec}, state4 {}, async replay {}, prefill graph {}, \
7207                     MTP graph {}, attend {}, probe {}",
7208                    if crate::gpu_metal::state4_on() {
7209                        "on"
7210                    } else {
7211                        "off"
7212                    },
7213                    if crate::gpu_metal::async_replay_on() {
7214                        "on"
7215                    } else {
7216                        "off"
7217                    },
7218                    on("CMF_METAL_PREFILL"),
7219                    on("CMF_MTP_GRAPH"),
7220                    std::env::var("CMF_GPU_ATTEND").unwrap_or_else(|_| "auto".into()),
7221                    if crate::gpu::probe_enabled() {
7222                        "bypassed (q1 force)"
7223                    } else {
7224                        "off"
7225                    },
7226                );
7227            });
7228        }
7229        let spec_active = self.speculative
7230            && self.mtp.is_some()
7231            && task_mask.is_none()
7232            && self.dyn_router.is_none()
7233            && (!self.o1_active() || self.o1_spec())
7234            // a card the verify does not fit: the head is not even warmed over the prompt
7235            && !(graph_spec && self.spec_over_budget)
7236            && ((!graph_on && pair_pays && self.sampler_config.temperature < 1e-6) || graph_spec);
7237        // The MTP module is detached during generation so its mutable
7238        // state does not fight the borrow on `self`.
7239        let mut mtp = if spec_active { self.mtp.take() } else { None };
7240        if std::env::var("CMF_MTP_CHAIN_PROBE").is_ok() {
7241            eprintln!(
7242                "mtp-probe gate: spec_active={spec_active} mtp={} speculative={} graph_on={graph_on} temp_ok={}",
7243                mtp.is_some(),
7244                self.speculative,
7245                self.sampler_config.temperature < 1e-6,
7246            );
7247        }
7248        if let Some(m) = &mut mtp {
7249            let kept = mtp_keep.is_some_and(|rows| {
7250                crate::gpu::graph_kv_set_stored(self.mtp_kv_id(), Self::MTP_LAYER_BASE, rows)
7251            });
7252            if kept {
7253                let rows = mtp_keep.unwrap_or(0);
7254                let d = m.kv.pos_len().saturating_sub(rows);
7255                if d > 0 {
7256                    m.kv.truncate_last(d);
7257                }
7258            } else {
7259                m.kv.clear();
7260                // The MTP block's own device mirror starts over with its cache.
7261                crate::gpu::graph_kv_reset(self.mtp_kv_id());
7262                if mtp_keep.is_some() {
7263                    // nothing kept: the head reads from the snapshot on
7264                    self.mtp_pos_base = reuse_from;
7265                }
7266            }
7267            self.mtp_graph_mode = None;
7268        }
7269        // MiMo-V2's draft stack: greedy rounds (draft K with the chained
7270        // MTP layers, verify K+1 rows in one batched forward). Sampling
7271        // decodes plain; `CMF_MTP=0` / `CMF_MIMO_MTP=0` turn it off.
7272        let mimo_spec = self.speculative
7273            && self.mimo_mtp.is_some()
7274            && task_mask.is_none()
7275            && !self.o1_active()
7276            && self.dyn_router.is_none()
7277            && self.sampler_config.temperature < 1e-6
7278            && std::env::var("CMF_MIMO_MTP").as_deref() != Ok("0");
7279        if let Some(st) = self.mimo_mtp.as_mut() {
7280            st.reset();
7281            if mimo_spec && std::env::var_os("CMF_MIMO_MTP_PROBE").is_some() {
7282                Self::mimo_mtp_hist_cap(st, input_ids.len());
7283            }
7284        }
7285        // Dynamic router detached during decode (same borrow trick as MTP).
7286        // Speculative decode and dynamic routing are mutually exclusive
7287        // for now — the fused-pair path doesn't carry per-token φ.
7288        let mut router = if mtp.is_none() {
7289            self.dyn_router.take()
7290        } else {
7291            None
7292        };
7293        let mut reuse_from = reuse_from;
7294        if let Some(r) = &mut router {
7295            r.reset(); // active=backbone, matching a fresh overlay
7296            self.dyn_phi_seen = 0; // fresh φ EMA per generation
7297            if self.dyn_active.is_some() {
7298                // A real switch back to the backbone invalidates the
7299                // cache the reuse key was computed against.
7300                let _ = self.set_active_skill(None);
7301                reuse_from = 0;
7302                self.last_prefill_tokens = input_ids.len();
7303            }
7304        }
7305
7306        let mut all_ids = input_ids.to_vec();
7307        // A block-diffusion model's response penalties count the response
7308        // only (`CloverPenaltyState`), never the prompt.
7309        let penalty_from = if self.clover.is_some() { input_ids.len() } else { 0 };
7310        let mut generated = 0usize;
7311        let mut finish_reason = "max_tokens".to_string();
7312        let mut drafted = 0usize;
7313        let mut accepted = 0usize;
7314        // DeepSeek-V4's draft quality is strongly content-dependent.  Two
7315        // consecutive paid rounds with no extra token put it on a bounded
7316        // cooldown; predictable text keeps batching, ordinary prose falls
7317        // back to the exact walk instead of paying a slow draft forever.
7318        // Local to one generation so one difficult request cannot poison the
7319        // next one, and deliberately automatic — this is not a user knob.
7320        let mut dsv4_spec_bad = 0usize;
7321        let mut dsv4_spec_retry_at = 0usize;
7322        let mut confidence: Vec<f32> = Vec::new();
7323        let trace_on = self.trace;
7324        let calib_temp = self.calib_temp;
7325        let mut traces: Vec<TokenTrace> = Vec::new();
7326
7327        // ── Prefill: forward each prompt token once, KEEP the last hidden.
7328        //    Dense prefill runs in fused pairs (weights streamed once per
7329        //    two positions — bit-identical to sequential, proven by the
7330        //    pair tests). With MTP: warm the draft head on
7331        //    (hidden_p, token_{p+1}) pairs.
7332        let mut hidden = vec![0.0f32; self.hidden_size];
7333        let mut pos = reuse_from;
7334        // lm_head-in-graph is only sound when the very next logits
7335        // consumer is this loop's own (MTP and skill routing interleave
7336        // other forwards / can swap lm_head between forward and sample).
7337        // CMF_GPU_LMHEAD=0 keeps lm_head off the graph: the token reads back
7338        // the 8 KB hidden instead of ~1 MB of logits, and the head runs on
7339        // the host. A probe for how much of the graph's fixed per-token cost
7340        // is the logits readback (the layer sweep puts that fixed part at
7341        // 3.88 ms of an 18.5 ms frame).
7342        let fuse_lm = mtp.is_none()
7343            && router.is_none()
7344            && std::env::var("CMF_GPU_LMHEAD").as_deref() != Ok("0");
7345        self.graph_logits = None;
7346        self.graph_want_logits = false;
7347        let _tpf = std::time::Instant::now();
7348        let batch_k = self.generation_batch_k();
7349        if let Some(rows) = prompt_rows {
7350            let hs = self.hidden_size;
7351            // The batched graph's row count when the prompt rides it.
7352            let chunk = if batch_k > 0 { batch_k } else { self.prefill_chunk().max(1) };
7353            while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
7354                let end = (pos + chunk).min(input_ids.len());
7355                let hb = match self.prefill_input_rows(
7356                    PrefillIn::Hidden(&rows[pos * hs..end * hs]),
7357                    pos,
7358                    task_mask,
7359                ) {
7360                    Ok(hb) => hb,
7361                    Err(err) => {
7362                        self.prompt_mrope = None;
7363                        self.finish_generation(&mut mtp, &mut router, true);
7364                        return Err(err);
7365                    }
7366                };
7367                if mimo_spec {
7368                    self.mimo_note_rows(&hb, pos);
7369                }
7370                hidden.copy_from_slice(&hb[hb.len() - hs..]);
7371                pos = end;
7372            }
7373        }
7374        // The prompt's MRoPE rows are in the cache; decode positions are
7375        // plain (`sensenova::mrope_positions` shifted them so).
7376        self.prompt_mrope = None;
7377        // DeepSeek-V4 owns a separate hyper-connection stack. Route it
7378        // before the generic prefill choices: those correctly reject an
7379        // empty `weights.layers`, but their final per-position fallback used
7380        // to consume the whole prompt before `dsv4::forward_chunk` could see
7381        // it. The batch implementation therefore existed without a live
7382        // production entry point.
7383        //
7384        // Bounded chunks preserve cancellation responsiveness. Only the
7385        // prompt's final chunk asks for logits; every earlier head projection
7386        // would produce 129 280 values that no caller reads.
7387        // GLM-5.3-Flash runs its own mHC / KDA / DSA stack: the prompt on the
7388        // card's batch graph when it takes it, else a token at a time.
7389        if mtp.is_none() && pos + 1 < input_ids.len() {
7390            let mut lg = Vec::new();
7391            let taken = match &mut self.glm5_next {
7392                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),
7393                None => 0,
7394            };
7395            if taken > 0 {
7396                pos += taken;
7397                if pos == input_ids.len() {
7398                    self.graph_logits = Some(lg);
7399                }
7400                hidden.fill(0.0);
7401            }
7402        }
7403        while self.glm5_next.is_some()
7404            && mtp.is_none()
7405            && pos < input_ids.len()
7406            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
7407        {
7408            let token_id = input_ids[pos];
7409            let want_logits = pos + 1 == input_ids.len();
7410            let mut lg = Vec::new();
7411            if let Some(b) = &mut self.glm5_next {
7412                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);
7413            }
7414            if want_logits {
7415                self.graph_logits = Some(lg);
7416            }
7417            pos += 1;
7418            hidden.fill(0.0);
7419        }
7420        // Hy4-flash: its own iHC / MLA / Engram stack; the prompt on the
7421        // card's batch graph when it takes it, else a token at a time.
7422        if mtp.is_none() && pos + 1 < input_ids.len() {
7423            let mut lg = Vec::new();
7424            let taken = match &mut self.hy4 {
7425                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),
7426                None => 0,
7427            };
7428            if taken > 0 {
7429                pos += taken;
7430                if pos == input_ids.len() {
7431                    self.graph_logits = Some(lg);
7432                }
7433                hidden.fill(0.0);
7434            }
7435        }
7436        while self.hy4.is_some()
7437            && mtp.is_none()
7438            && pos < input_ids.len()
7439            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
7440        {
7441            let token_id = input_ids[pos];
7442            let want_logits = pos + 1 == input_ids.len();
7443            let mut lg = Vec::new();
7444            if let Some(b) = &mut self.hy4 {
7445                crate::hy4::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, pos, self.pool.as_deref(), &mut lg, want_logits);
7446            }
7447            if want_logits {
7448                self.graph_logits = Some(lg);
7449            }
7450            pos += 1;
7451            hidden.fill(0.0);
7452        }
7453        // Maxwell-V1-Flash: its own mHC stack; the prompt on the card's
7454        // batch graph when it takes it, else a token at a time.
7455        if mtp.is_none() && pos + 1 < input_ids.len() {
7456            let mut lg = Vec::new();
7457            let taken = match &mut self.maxwell {
7458                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),
7459                None => 0,
7460            };
7461            if taken > 0 {
7462                pos += taken;
7463                if pos == input_ids.len() {
7464                    self.graph_logits = Some(lg);
7465                }
7466                hidden.fill(0.0);
7467            }
7468        }
7469        while self.maxwell.is_some()
7470            && mtp.is_none()
7471            && pos < input_ids.len()
7472            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
7473        {
7474            let token_id = input_ids[pos];
7475            let want_logits = pos + 1 == input_ids.len();
7476            let mut lg = Vec::new();
7477            if let Some(b) = &mut self.maxwell {
7478                crate::maxwell::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, pos, self.pool.as_deref(), &mut lg, want_logits);
7479            }
7480            if want_logits {
7481                self.graph_logits = Some(lg);
7482            }
7483            pos += 1;
7484            hidden.fill(0.0);
7485        }
7486        // Inkling-2-Mini: its own looped stack; the prompt on the
7487        // card's batch graph when it takes it, else a token at a time.
7488        if mtp.is_none() && pos + 1 < input_ids.len() {
7489            let mut lg = Vec::new();
7490            let taken = match &mut self.inkling {
7491                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),
7492                None => 0,
7493            };
7494            if taken > 0 {
7495                pos += taken;
7496                if pos == input_ids.len() {
7497                    self.graph_logits = Some(lg);
7498                }
7499                hidden.fill(0.0);
7500            }
7501        }
7502        while self.inkling.is_some()
7503            && mtp.is_none()
7504            && pos < input_ids.len()
7505            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
7506        {
7507            let token_id = input_ids[pos];
7508            let want_logits = pos + 1 == input_ids.len();
7509            let mut lg = Vec::new();
7510            if let Some(b) = &mut self.inkling {
7511                crate::inkling::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, pos, self.pool.as_deref(), &mut lg, want_logits);
7512            }
7513            if want_logits {
7514                self.graph_logits = Some(lg);
7515            }
7516            pos += 1;
7517            hidden.fill(0.0);
7518        }
7519        while self.qwen4_exp.is_some()
7520            && mtp.is_none()
7521            && pos < input_ids.len()
7522            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
7523        {
7524            // The device path takes several prompt tokens per layer frame;
7525            // the host path runs them one by one inside the same call.
7526            let end = (pos + crate::qwen4_exp::prefill_chunk()).min(input_ids.len());
7527            let want_logits = end == input_ids.len();
7528            let mut lg = Vec::new();
7529            if let Some(b) = &mut self.qwen4_exp {
7530                crate::qwen4_exp::forward_tokens(
7531                    &b.0,
7532                    &b.1,
7533                    &b.2,
7534                    &mut b.3,
7535                    &input_ids[pos..end],
7536                    pos,
7537                    &self.inv_freq,
7538                    self.pool.as_deref(),
7539                    &mut lg,
7540                    want_logits,
7541                );
7542            }
7543            if want_logits {
7544                self.graph_logits = Some(lg);
7545            }
7546            pos = end;
7547            hidden.fill(0.0);
7548        }
7549        while self.dsv4.is_some()
7550            && mtp.is_none()
7551            && pos < input_ids.len()
7552            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
7553        {
7554            let end = (pos + prefill_chunk()).min(input_ids.len());
7555            let ids: Vec<u32> = input_ids[pos..end].to_vec();
7556            let mut lg = Vec::new();
7557            if let Some(b) = &mut self.dsv4 {
7558                let (g, layers, cfg, st) = (&b.0, &b.1, b.2, &mut b.3);
7559                crate::dsv4::forward_chunk(
7560                    g,
7561                    layers,
7562                    &cfg,
7563                    st,
7564                    &ids,
7565                    pos,
7566                    &self.inv_freq,
7567                    self.pool.as_deref(),
7568                    &mut lg,
7569                    end == input_ids.len(),
7570                );
7571            }
7572            if end == input_ids.len() {
7573                self.graph_logits = Some(lg);
7574            }
7575            pos = end;
7576            hidden = vec![0.0; self.hidden_size];
7577        }
7578        if self.dory.is_some() && mtp.is_none() && pos < input_ids.len() {
7579            let lg = self.dory_forward(&input_ids[pos..], pos, crate::dory::Want::Last);
7580            self.graph_logits = Some(lg);
7581            pos = input_ids.len();
7582            hidden = vec![0.0; self.hidden_size];
7583        }
7584        let dsv41_prefill = self.dsv41_prefill.take();
7585        while self.dsv41.is_some()
7586            && mtp.is_none()
7587            && pos < input_ids.len()
7588            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
7589        {
7590            let end = (pos + prefill_chunk()).min(input_ids.len());
7591            let ids: Vec<u32> = input_ids[pos..end].to_vec();
7592            let mut lg = Vec::new();
7593            if let Some(b) = &mut self.dsv41 {
7594                let (g, layers, cfg, st) = (&b.0, &b.1, &b.2, &mut b.3);
7595                if let Some((embeddings, participates)) = dsv41_prefill.as_ref() {
7596                    crate::dsv41::forward_chunk_masked_with_embeddings(
7597                        g,
7598                        layers,
7599                        cfg,
7600                        st,
7601                        &ids,
7602                        pos,
7603                        &embeddings[pos..end],
7604                        &participates[pos..end],
7605                        self.pool.as_deref(),
7606                        &mut lg,
7607                    );
7608                } else {
7609                    crate::dsv41::forward_chunk(
7610                        g,
7611                        layers,
7612                        cfg,
7613                        st,
7614                        &ids,
7615                        pos,
7616                        self.pool.as_deref(),
7617                        &mut lg,
7618                    );
7619                }
7620            }
7621            if end == input_ids.len() {
7622                self.graph_logits = Some(lg);
7623            }
7624            pos = end;
7625            hidden = vec![0.0; self.hidden_size];
7626        }
7627        // With dynamic routing, prefill sequentially so the φ hook fires
7628        // over the PROMPT — the router enters decode with a warm φ (the
7629        // fused-pair path skips the per-layer φ capture). o1 layers
7630        // collect their query trace in both the single and pair paths.
7631        let dyn_prefill = router.is_some();
7632        // On CUDA the batch graph keeps the router layer's rows of every
7633        // prompt chunk (`dyn_phi_tap`): the prompt reads batched and φ still
7634        // takes every position in order.
7635        let dyn_batch = dyn_prefill && crate::gpu::cuda_active();
7636        // Optional bounded calibration prefix for generation.  The normal
7637        // O(1) path seals after the full prompt; this explicit knob instead
7638        // runs only the requested prefix through exact attention, seals the
7639        // Nyström state, and streams the rest of the prompt through the same
7640        // O(1) step used by decode.  It keeps the O(1) layers' Q trace and
7641        // temporary full KV bounded by the prefix while leaving the default
7642        // full-prompt quality profile untouched.
7643        let o1_prefill_limit = o1_prefill
7644            .and_then(|requested| self.o1_effective_boundary(requested))
7645            .map(|boundary| boundary.min(input_ids.len()));
7646        let mut o1_sealed = false;
7647        let mut o1_arch: Option<O1Archive> = None;
7648        if let Some(limit) = o1_prefill_limit {
7649            // On the device route the prefix takes the batch graph and its
7650            // sealed suffix the O(1) batches after it (`o1_prefix_on_graph`):
7651            // the host walk read it at 16 tok/s on Qwen3.8-27B / A40, 33 s
7652            // of a 72 s TTFT at 4k. Only when a suffix follows — a prompt
7653            // inside the boundary stays exact on the host as before.
7654            // `CMF_O1_PREFIX_GPU=0` keeps the host prefill.
7655            if pos == 0
7656                && limit < input_ids.len()
7657                && batch_k > 0
7658                && task_mask.is_none()
7659                && (mtp.is_none() || self.o1_spec())
7660                && !dyn_prefill
7661                && self.o1_on_graph()
7662                && std::env::var("CMF_O1_PREFIX_GPU").as_deref() != Ok("0")
7663                // One cache per executed layer: a looped stack whose visits keep
7664                // their own rows (SenseNova-Loop) indexes caches, mirrors and the
7665                // query capture by the visit, as a plain stack does by the layer.
7666                && self.kv_cache.layers.len() == self.num_layers
7667            {
7668                let t_px = std::time::Instant::now();
7669                // More of the prompt than the first seal covers: its rows stay in host
7670                // memory, and the far field is built anew before the prompt's last rows.
7671                let tail_from = input_ids.len().saturating_sub(crate::dory::EXACT_TAIL);
7672                if limit < tail_from && self.o1_exact_cfg().is_some() {
7673                    o1_arch = Some(O1Archive::new());
7674                }
7675                // Without a Metal rows graph (Spark-X2.6: GELU, per-head gates, sliding
7676                // windows) the sealed rows would go one position at a time: 14 000 tokens
7677                // on the M4 took 219 s. The chunk graph reads the whole prompt exact
7678                // instead, and the seal after it chooses among all of its rows, with the
7679                // question's queries in the trace.
7680                #[cfg(target_os = "macos")]
7681                let px_len = if crate::gpu::q1_force() && o1_arch.is_some() && self.metal_rows_plan().is_none() {
7682                    o1_arch = None;
7683                    let n = input_ids.len();
7684                    for li in 0..self.num_layers {
7685                        if self.o1_flags.get(li).copied().unwrap_or(false) {
7686                            self.kv_cache.layers[li].o1_set_boundary(n);
7687                        }
7688                    }
7689                    n
7690                } else {
7691                    limit
7692                };
7693                #[cfg(not(target_os = "macos"))]
7694                let px_len = if self.o1_whole_prompt() {
7695                    o1_arch = None;
7696                    let n = input_ids.len();
7697                    for li in 0..self.num_layers {
7698                        if self.o1_flags.get(li).copied().unwrap_or(false) {
7699                            self.kv_cache.layers[li].o1_set_boundary(n);
7700                        }
7701                    }
7702                    n
7703                } else {
7704                    limit
7705                };
7706                #[cfg(target_os = "macos")]
7707                let prefix = if crate::gpu::q1_force() {
7708                    self.o1_prefix_on_metal(&input_ids[..px_len], batch_k, o1_arch.as_mut())
7709                } else {
7710                    self.o1_prefix_on_graph(&input_ids[..px_len], batch_k, o1_arch.as_mut())
7711                };
7712                #[cfg(not(target_os = "macos"))]
7713                let prefix = {
7714                    // the CUDA mirrors take the whole prompt at the first chunk
7715                    let hint = crate::gpu::cuda_active();
7716                    if hint {
7717                        crate::gpu::set_batch_kv_hint(px_len + 1);
7718                    }
7719                    let r = self.o1_prefix_on_graph(&input_ids[..px_len], batch_k, o1_arch.as_mut());
7720                    if hint {
7721                        crate::gpu::set_batch_kv_hint(0);
7722                    }
7723                    r
7724                };
7725                match prefix {
7726                    Ok(Some(last)) => {
7727                        hidden.copy_from_slice(&last);
7728                        pos = px_len;
7729                        // the whole prompt went by the prefix (CUDA): the draft head
7730                        // reads its tail, as over the wgpu path's far field
7731                        let tail = std::mem::take(&mut self.o1_prefix_tail);
7732                        if px_len == input_ids.len() && mtp.is_some() && !tail.is_empty() {
7733                            let hs = self.hidden_size;
7734                            let from = px_len - tail.len() / hs;
7735                            self.mtp_pos_base = from;
7736                            let n_pairs = mtp_prefill_pair_count(from, px_len, input_ids.len());
7737                            let pairs: Vec<(&[f32], u32)> = (0..n_pairs).map(|j| (&tail[j * hs..(j + 1) * hs], input_ids[from + j + 1])).collect();
7738                            let warm_error = if let Some(m) = mtp.as_mut() { self.mtp_warm_prefill_pairs(m, &pairs, from).err() } else { None };
7739                            if let Some(err) = warm_error {
7740                                self.finish_generation(&mut mtp, &mut router, true);
7741                                return Err(err.to_string());
7742                            }
7743                            self.mtp_warm_base = Some(from);
7744                        }
7745                        if std::env::var("CMF_PREFILL_PROF").is_ok() {
7746                            eprintln!(
7747                                "o1 prefix on the batch graph: {px_len} rows in {:.1} ms",
7748                                t_px.elapsed().as_secs_f64() * 1e3
7749                            );
7750                        }
7751                    }
7752                    Ok(None) => {}
7753                    Err(err) => {
7754                        self.finish_generation(&mut mtp, &mut router, true);
7755                        return Err(err);
7756                    }
7757                }
7758            }
7759            // Without the device route (LFM2's short convolutions on Metal) the rows
7760            // past the first seal would stream into the far field unchosen. With exact
7761            // rows wanted, the host keeps the prompt exact up to its last rows and
7762            // chooses among all of them there, as the archive does on the device.
7763            let tail_from = input_ids.len().saturating_sub(crate::dory::EXACT_TAIL);
7764            let limit = if pos == 0 && limit < tail_from && self.o1_exact_cfg().is_some() {
7765                o1_arch = None;
7766                for li in 0..self.num_layers {
7767                    if self.o1_flags.get(li).copied().unwrap_or(false) {
7768                        self.kv_cache.layers[li].o1_set_boundary(tail_from);
7769                    }
7770                }
7771                tracing::info!("o1: no device prefix; exact on the host up to row {tail_from}, then the seal");
7772                tail_from
7773            } else {
7774                limit
7775            };
7776            // Reuse the exact batched prefix machinery when available; it
7777            // records the same per-position Q trace as the full prefill.
7778            if pos < limit && self.can_prefill_batched() && limit > 2 {
7779                let chunk = self.prefill_chunk();
7780                let hs = self.hidden_size;
7781                while pos < limit && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
7782                    let end = (pos + chunk).min(limit);
7783                    let hb = self.prefill_batch(&input_ids[pos..end], pos);
7784                    hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
7785                    pos = end;
7786                }
7787            } else {
7788                while pos < limit && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
7789                    hidden = self.forward_layers(&self.embed_single(input_ids[pos]), pos, None);
7790                    pos += 1;
7791                }
7792            }
7793            if pos >= limit {
7794                o1_sealed = match self.o1_seal_checked() {
7795                    Ok(sealed) => sealed,
7796                    Err(err) => {
7797                        self.finish_generation(&mut mtp, &mut router, true);
7798                        return Err(err);
7799                    }
7800                };
7801                // Sealed layers read no mirror again: their rows leave the memory they share
7802                // with everything else on a Mac.
7803                #[cfg(target_os = "macos")]
7804                if o1_sealed && crate::gpu::q1_force() {
7805                    crate::gpu_metal::kv_mirror_drop(self.graph_kv_id);
7806                }
7807                tracing::info!(
7808                    "o1 bounded prompt prefix: requested={} effective={} processed={} of {} token(s)",
7809                    o1_prefill.unwrap_or(0),
7810                    self.o1_effective_boundary(o1_prefill.unwrap_or(0))
7811                        .unwrap_or(limit),
7812                    limit,
7813                    input_ids.len()
7814                );
7815            }
7816        }
7817        // q1 hybrids on Metal: the per-position GPU token graph beats
7818        // the CPU chunk-GEMM (whose wall is the sequential scalar GDN
7819        // recurrence), so prefill goes position-by-position through the
7820        // same graph as decode. Pure-attention models keep the batched
7821        // path — there the chunk-GEMM amortization wins.
7822        let graph_prefill = self.graph_prefill_preferred();
7823        // Native Metal, q4tp GDN hybrids: the prompt through the b-row
7824        // rows graph — projections as GEMMs over up to 512 positions, the
7825        // GDN recurrence in registers on the device, K/V rows appended by
7826        // the chunk — instead of one token-graph submit per position (the
7827        // 27B: 8 tok/s → GEMM-bound). The MTP warm-up rows come out of one
7828        // batched run of the block per chunk. Any refusal leaves the rest
7829        // of the prompt to the sequential paths below. Pure-attention
7830        // models take it too (the plan admits their layers): CherryPit-1.2-2B
7831        // read an 8 192-token prompt on the M4 in 31 s instead of the host
7832        // walk's 58 s (q4tp; q8_2f 34 s against 55), at the same WikiText-2
7833        // ppl. `CMF_METAL_PREFILL=0` keeps the host walk.
7834        #[cfg(target_os = "macos")]
7835        if task_mask.is_none()
7836            && !dyn_prefill
7837            && !o1_sealed
7838            && (crate::gpu::q1_force() || crate::gpu::q2tp_gpu_opt_in())
7839            && crate::gpu::enabled_here()
7840            && !self.per_token_stack()
7841            && input_ids.len() > 8
7842            && std::env::var("CMF_MTP_CHAIN_PROBE").is_err()
7843            && std::env::var("CMF_METAL_PREFILL").as_deref() != Ok("0")
7844        {
7845            let chunk: usize = std::env::var("CMF_METAL_PREFILL_CHUNK")
7846                .ok()
7847                .and_then(|v| v.parse().ok())
7848                .filter(|&v| (16..=512).contains(&v))
7849                // The ANE's weights go once a chunk: a larger one pays them over more rows.
7850                .unwrap_or(if crate::gpu_metal::ane::wanted() { 512 } else { 256 });
7851            let hs = self.hidden_size;
7852            let _tp = std::time::Instant::now();
7853            while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
7854                let end = (pos + chunk).min(input_ids.len());
7855                let hb = match self.prefill_batch_metal(&input_ids[pos..end], pos) {
7856                    MetalPrefillOutcome::Completed(hb) => hb,
7857                    MetalPrefillOutcome::Declined => break,
7858                    MetalPrefillOutcome::Failed => {
7859                        self.finish_generation(&mut mtp, &mut router, true);
7860                        return Err("ordinary Metal prefill failed after admission".into());
7861                    }
7862                };
7863                if let Some(m) = &mut mtp {
7864                    let n_pairs = if end < input_ids.len() {
7865                        end - pos
7866                    } else {
7867                        end - pos - 1
7868                    };
7869                    if n_pairs > 0 {
7870                        let pairs: Vec<(&[f32], u32)> = (0..n_pairs)
7871                            .map(|j| (&hb[j * hs..(j + 1) * hs], input_ids[pos + j + 1]))
7872                            .collect();
7873                        if !self.mtp_warm_batch_metal(m, &pairs, pos) {
7874                            for (j, (h, t)) in pairs.iter().enumerate() {
7875                                let h = h.to_vec();
7876                                let _ = self.mtp_step(m, &h, *t, pos + j);
7877                            }
7878                        }
7879                    }
7880                }
7881                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
7882                pos = end;
7883            }
7884            if std::env::var("CMF_PREFILL_PROF").is_ok() {
7885                eprintln!(
7886                    "metal-prefill: {} of {} tokens in {:.1} ms",
7887                    pos,
7888                    input_ids.len(),
7889                    _tp.elapsed().as_secs_f64() * 1e3
7890                );
7891                // Per-stage GPU time of the rows graph (`CMF_VERIFY_CUT=1`).
7892                crate::gpu_metal::cut_report();
7893            }
7894        }
7895        // Gemma-4 on a discrete card: the prompt through the batched wgpu
7896        // graph (`g4_batch_ingest`); its K/V land in the device mirrors
7897        // decode reads. A refusal leaves the rest of the prompt to the
7898        // chunked host prefill below.
7899        #[cfg(not(target_os = "macos"))]
7900        if task_mask.is_none()
7901            && !dyn_prefill
7902            && mtp.is_none()
7903            && o1_prefill.is_none()
7904            && batch_k > 0
7905            && pos + 1 < input_ids.len()
7906            && self.g4_batch_prefill()
7907        {
7908            let t_g4 = std::time::Instant::now();
7909            match self.g4_batch_ingest(&input_ids[pos..], pos, false) {
7910                Ok((n, last)) => {
7911                    if n > 0 {
7912                        hidden.copy_from_slice(&last);
7913                    }
7914                    if std::env::var("CMF_PREFILL_PROF").is_ok() {
7915                        eprintln!(
7916                            "gemma4 batch prefill: {n} of {} tokens in {:.1} ms",
7917                            input_ids.len() - pos,
7918                            t_g4.elapsed().as_secs_f64() * 1e3
7919                        );
7920                    }
7921                    pos += n;
7922                }
7923                Err(e) => {
7924                    self.finish_generation(&mut mtp, &mut router, true);
7925                    return Err(e);
7926                }
7927            }
7928        }
7929        self.mimo_moe_prepare();
7930        // A MoE stack larger than the card (MiMo-V2 q4tp on 96 GB): the
7931        // batched wgpu graph runs the device prefix of every chunk — its
7932        // experts resident — and the host's batched layer walk finishes
7933        // the chunk. Any refusal leaves the rest of the prompt to the
7934        // chunked prefill below.
7935        #[cfg(not(target_os = "macos"))]
7936        if task_mask.is_none()
7937            && !dyn_prefill
7938            && !graph_prefill
7939            && mtp.is_none()
7940            && o1_prefill.is_none()
7941            && !self.o1_active()
7942            && input_ids.len() > 2
7943            && self.batch_prefix_prefill()
7944        {
7945            let chunk = self.prefill_chunk().max(1);
7946            let hs = self.hidden_size;
7947            let t_bp = std::time::Instant::now();
7948            let pos0 = pos;
7949            while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
7950                let end = (pos + chunk).min(input_ids.len());
7951                let bk = end - pos;
7952                let mut hiddens = vec![0f32; bk * hs];
7953                for (j, &id) in input_ids[pos..end].iter().enumerate() {
7954                    hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
7955                }
7956                let positions: Vec<usize> = (pos..end).collect();
7957                let mut run = 0usize;
7958                let outcome = self.try_batch_graph_wgpu_prefix(
7959                    &mut hiddens,
7960                    &positions,
7961                    bk,
7962                    None,
7963                    Some(&mut run),
7964                );
7965                match outcome {
7966                    crate::gpu::BatchGraphOutcome::Completed => {
7967                        let hb = if run < self.num_layers {
7968                            self.mhc_from_device(run, Some(bk));
7969                            self.prefill_batch_span(
7970                                PrefillIn::Hidden(&hiddens),
7971                                pos,
7972                                None,
7973                                run,
7974                                self.num_layers,
7975                            )
7976                        } else {
7977                            hiddens
7978                        };
7979                        if mimo_spec {
7980                            self.mimo_note_rows(&hb, pos);
7981                        }
7982                        hidden.copy_from_slice(&hb[(bk - 1) * hs..]);
7983                        pos = end;
7984                    }
7985                    crate::gpu::BatchGraphOutcome::Failed => {
7986                        self.finish_generation(&mut mtp, &mut router, true);
7987                        return Err("batched prefix prefill failed after admission".into());
7988                    }
7989                    crate::gpu::BatchGraphOutcome::Declined => {
7990                        // Earlier chunks left their prefix rows on the
7991                        // device only: the host walk below needs them.
7992                        #[cfg(feature = "gpu")]
7993                        if pos > pos0 {
7994                            self.pull_lagging_host_kv(0, self.num_layers, pos);
7995                        }
7996                        break;
7997                    }
7998                }
7999            }
8000            if std::env::var("CMF_PREFILL_PROF").is_ok() {
8001                eprintln!(
8002                    "batch-prefix prefill: {} of {} tokens in {:.1} ms",
8003                    pos - pos0,
8004                    input_ids.len(),
8005                    t_bp.elapsed().as_secs_f64() * 1e3
8006                );
8007            }
8008        }
8009        if task_mask.is_none()
8010            && !dyn_prefill
8011            && !graph_prefill
8012            && self.can_prefill_batched()
8013            && !self.per_token_stack()
8014            && o1_prefill.is_none()
8015            && input_ids.len() > 2
8016        {
8017            // Production prefill = the same chunked prefill-GEMM that
8018            // bench/PPL measure (roadmap §3 P0: generation used to warm
8019            // the prompt with the slower pair path — the published
8020            // prefill number didn't match real TTFT). MTP warm-up reads
8021            // each position's hidden straight from the chunk result.
8022            let chunk = self.prefill_chunk();
8023            let hs = self.hidden_size;
8024            while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
8025                let end = (pos + chunk).min(input_ids.len());
8026                let hb = self.prefill_batch(&input_ids[pos..end], pos);
8027                if mimo_spec {
8028                    self.mimo_note_rows(&hb, pos);
8029                }
8030                if let Some(m) = &mut mtp {
8031                    let probe: usize = std::env::var("CMF_MTP_CHAIN_PROBE")
8032                        .ok()
8033                        .and_then(|v| v.parse().ok())
8034                        .unwrap_or(0);
8035                    for p in pos..end {
8036                        if p + 1 < input_ids.len() {
8037                            if probe >= 1 && p + 2 < input_ids.len() {
8038                                // Teacher-forced chain acceptance (see the
8039                                // tail loop's twin): the warm-up row stays,
8040                                // the chain's rows roll back.
8041                                let (d1, mut hx) = self.mtp_step_h(
8042                                    m,
8043                                    &hb[(p - pos) * hs..(p - pos + 1) * hs],
8044                                    input_ids[p + 1],
8045                                    p,
8046                                );
8047                                let mut ok = d1 == input_ids[p + 2];
8048                                Self::chain_probe_note(0, ok);
8049                                let mut d_prev = d1;
8050                                let mut extra = 0usize;
8051                                for j in 1..probe {
8052                                    if p + 2 + j >= input_ids.len() {
8053                                        break;
8054                                    }
8055                                    let (dj, hj) = self.mtp_step_h(m, &hx, d_prev, p + 1 + j);
8056                                    extra += 1;
8057                                    ok = ok && dj == input_ids[p + 2 + j];
8058                                    Self::chain_probe_note(j, ok);
8059                                    d_prev = dj;
8060                                    hx = hj;
8061                                }
8062                                m.kv.truncate_last(extra);
8063                            } else {
8064                                let _ = self.mtp_step(
8065                                    m,
8066                                    &hb[(p - pos) * hs..(p - pos + 1) * hs],
8067                                    input_ids[p + 1],
8068                                    p,
8069                                );
8070                            }
8071                        }
8072                    }
8073                }
8074                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
8075                pos = end;
8076            }
8077        }
8078        let pair_off = std::env::var("CMF_PAIR").is_ok_and(|v| v == "0");
8079        if task_mask.is_none()
8080            && !dyn_prefill
8081            && !graph_prefill
8082            && !pair_off
8083            && self.pair_supported()
8084            && o1_prefill.is_none()
8085        {
8086            while pos + 1 < input_ids.len()
8087                && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
8088            {
8089                let e1 = self.embed_single(input_ids[pos]);
8090                let e2 = self.embed_single(input_ids[pos + 1]);
8091                let (h1, h2) = self.forward_pair(&e1, &e2, pos);
8092                if mimo_spec {
8093                    self.mimo_note_rows(&h1, pos);
8094                    self.mimo_note_rows(&h2, pos + 1);
8095                }
8096                // Both prefill tokens are real → commit lane-2 states.
8097                self.commit_linear_scratch();
8098                if let Some(m) = &mut mtp {
8099                    let _ = self.mtp_step(m, &h1, input_ids[pos + 1], pos);
8100                    if pos + 2 < input_ids.len() {
8101                        let probe: usize = std::env::var("CMF_MTP_CHAIN_PROBE")
8102                            .ok()
8103                            .and_then(|v| v.parse().ok())
8104                            .unwrap_or(0);
8105                        if probe >= 1 && pos + 3 < input_ids.len() {
8106                            // Same teacher-forced chain table as the tail
8107                            // loop below, fed from the pair path that owns
8108                            // most prefill positions.
8109                            let (d1, mut hx) = self.mtp_step_h(m, &h2, input_ids[pos + 2], pos + 1);
8110                            let mut ok = d1 == input_ids[pos + 3];
8111                            Self::chain_probe_note(0, ok);
8112                            let mut d_prev = d1;
8113                            let mut extra = 0usize;
8114                            for j in 1..probe {
8115                                if pos + 3 + j >= input_ids.len() {
8116                                    break;
8117                                }
8118                                let (dj, hj) = self.mtp_step_h(m, &hx, d_prev, pos + 2 + j);
8119                                extra += 1;
8120                                ok = ok && dj == input_ids[pos + 3 + j];
8121                                Self::chain_probe_note(j, ok);
8122                                d_prev = dj;
8123                                hx = hj;
8124                            }
8125                            m.kv.truncate_last(extra);
8126                        } else {
8127                            let _ = self.mtp_step(m, &h2, input_ids[pos + 2], pos + 1);
8128                        }
8129                    }
8130                }
8131                hidden = h2;
8132                pos += 2;
8133            }
8134        }
8135        // Batched GPU prefill for the wgpu decode graph (GDN hybrids): K prompt
8136        // positions per submit — projections/FFN as GEMMs (weight once per K),
8137        // attention/GDN looped inside — instead of one whole-graph submit per
8138        // position. Falls through to the per-position graph on any refusal.
8139        // Batched prefill is opt-in (CMF_BATCH_K>0). Default 0 = per-position
8140        // graph prefill. (Steady-state decode is provably identical either way —
8141        // token-graph submit and lm_head both unchanged — so this only trades
8142        // prefill wall.)
8143        // A bounded O(1) prefix is the one post-seal prompt interval: only
8144        // admit its batch when the device O(1) route is explicitly enabled and
8145        // every sealed layer exposes a portable view. The same batch size and
8146        // refusal behavior remain the ordinary controls/comparator.
8147        let o1_batch_ready = o1_sealed
8148            && o1_prefill.is_some()
8149            && (mtp.is_none() || self.o1_spec())
8150            && self.o1_on_graph()
8151            && (0..self.num_layers).all(|li| {
8152                let cache = &self.kv_cache.layers[self.phys_layer(li)];
8153                cache.o1.is_none() || cache.o1_views().is_some()
8154            });
8155        // The ordinary graph-prefill route can share each completed trunk
8156        // chunk with an attached MTP head.  Keep chain probing on its
8157        // established per-position path: the probe deliberately needs every
8158        // teacher-forced draft row and its rollback table.
8159        let mtp_batch_prefill = mtp.is_some()
8160            && graph_prefill
8161            && task_mask.is_none()
8162            && !dyn_prefill
8163            && !self.o1_active()
8164            && std::env::var("CMF_MTP_CHAIN_PROBE").is_err();
8165        // A hint a failed earlier prompt left behind must not size this one.
8166        #[cfg(not(target_os = "macos"))]
8167        crate::gpu::set_batch_kv_hint(0);
8168        if batch_k > 0
8169            && (graph_prefill || o1_batch_ready)
8170            && task_mask.is_none()
8171            && (!self.o1_active() || o1_batch_ready)
8172            && (mtp.is_none() || mtp_batch_prefill || o1_batch_ready)
8173            && (!dyn_prefill || dyn_batch)
8174            && pos + 1 < input_ids.len()
8175        {
8176            let hs = self.hidden_size;
8177            let chunk = batch_k;
8178            let pos_start = pos;
8179            let tail_from = input_ids.len().saturating_sub(crate::dory::EXACT_TAIL);
8180            // The K/V mirrors take the whole prompt (and its first token) at
8181            // the first chunk instead of growing on the way; cleared below.
8182            // Not under O(1): its exact mirror must stay the tail it keeps.
8183            #[cfg(not(target_os = "macos"))]
8184            if !self.o1_active() && o1_arch.is_none() && !o1_batch_ready {
8185                crate::gpu::set_batch_kv_hint(input_ids.len() + 1);
8186            }
8187            if let Some(a) = o1_arch.as_ref() {
8188                crate::gpu::o1_acap_begin(a.stride);
8189            }
8190            let o1_arch_lag = o1_arch.is_some()
8191                && o1_batch_ready
8192                && crate::gpu::wgpu_active()
8193                && std::env::var("CMF_O1_ARCH_LAG").as_deref() != Ok("0");
8194            let mut arch_lag: Option<(usize, usize, usize)> = None;
8195            if o1_batch_ready && mtp.is_some() {
8196                self.mtp_pos_base = tail_from.max(pos);
8197            }
8198            // a chunk ends at the chat snapshot's row, the card copies the
8199            // GDN states there before the next chunk runs
8200            let snap_at = if o1_arch.is_none() && !o1_batch_ready { self.gdn_snap_target(input_ids, pos) } else { None };
8201            while pos < input_ids.len() {
8202                // The prompt's last rows read the rows chosen just before them.
8203                if pos >= tail_from {
8204                    if let Some(mut a) = o1_arch.take() {
8205                        // the deferred chunk before the tail joins the archive first
8206                        if let Some((p0, b0, n0)) = arch_lag.take() {
8207                            if let Err(err) = self.o1_archive_chunk(&mut a, p0, b0, Some(n0)) {
8208                                self.finish_generation(&mut mtp, &mut router, true);
8209                                return Err(err);
8210                            }
8211                        }
8212                        crate::gpu::o1_acap_end();
8213                        if let Err(err) = self.o1_seal_archive(a) {
8214                            self.finish_generation(&mut mtp, &mut router, true);
8215                            return Err(err);
8216                        }
8217                    }
8218                }
8219                let stop = if o1_arch.is_some() { tail_from } else { input_ids.len() };
8220                let end = match snap_at {
8221                    Some(s) if pos < s => (pos + chunk).min(stop).min(s),
8222                    _ if o1_arch.is_some() => o1_chunk_end(pos, chunk, stop),
8223                    _ => (pos + chunk).min(stop),
8224                };
8225                let bk = end - pos;
8226                let mut hiddens = vec![0f32; bk * hs];
8227                for (j, &id) in input_ids[pos..end].iter().enumerate() {
8228                    hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
8229                }
8230                let positions: Vec<usize> = (pos..end).collect();
8231                let t_chunk = std::time::Instant::now();
8232                // A chunk before the last whose rows nothing reads: the
8233                // graph submits it and returns, and this loop encodes the
8234                // next chunk while the card runs it.
8235                // A sealed chunk before the last whose rows nothing reads (wgpu) is
8236                // deferred too: its rows for the archive are read once the next chunk
8237                // is on the card (`arch_lag`). `CMF_O1_ARCH_LAG=0`: each chunk waits.
8238                let sealed_defer = o1_arch_lag
8239                    && end < input_ids.len()
8240                    && !mimo_spec
8241                    && !dyn_prefill
8242                    && !(mtp.is_some() && end > self.mtp_pos_base);
8243                #[cfg(not(target_os = "macos"))]
8244                crate::gpu::set_batch_defer(
8245                    sealed_defer
8246                        || (end < input_ids.len()
8247                            && o1_arch.is_none()
8248                            && !o1_batch_ready
8249                            && !mimo_spec
8250                            && !mtp_batch_prefill
8251                            && !dyn_prefill),
8252                );
8253                let acap_before = crate::gpu::o1_acap_pending();
8254                let outcome = self.o1_prompt_chunk(&mut hiddens, &positions, bk);
8255                #[cfg(not(target_os = "macos"))]
8256                crate::gpu::set_batch_defer(false);
8257                // this chunk's entries, counted before the chunk before it leaves the queue
8258                let acap_new = crate::gpu::o1_acap_pending().saturating_sub(acap_before);
8259                if let (Some(a), crate::gpu::BatchGraphOutcome::Completed) = (o1_arch.as_mut(), outcome) {
8260                    // the chunk before this one first: its command is done
8261                    let mut res = match arch_lag.take() {
8262                        Some((p0, b0, n0)) => self.o1_archive_chunk(a, p0, b0, Some(n0)),
8263                        None => Ok(()),
8264                    };
8265                    if res.is_ok() {
8266                        if sealed_defer {
8267                            arch_lag = Some((pos, bk, acap_new));
8268                        } else {
8269                            res = self.o1_archive_chunk(a, pos, bk, None);
8270                        }
8271                    }
8272                    if let Err(err) = res {
8273                        self.finish_generation(&mut mtp, &mut router, true);
8274                        return Err(err);
8275                    }
8276                }
8277                let ok_b = outcome == crate::gpu::BatchGraphOutcome::Completed;
8278                if ok_b && dyn_prefill {
8279                    self.absorb_phi_tap(0..self.num_layers);
8280                }
8281                // The draft head over a far field reads the prompt's tail only.
8282                if ok_b && o1_batch_ready && end > self.mtp_pos_base && mtp.is_some() {
8283                    let first = pos.max(self.mtp_pos_base);
8284                    let n_pairs = mtp_prefill_pair_count(first, end, input_ids.len());
8285                    if n_pairs > 0 {
8286                        let rows: Vec<Vec<f32>> = (0..n_pairs).map(|j| hiddens[(first - pos + j) * hs..(first - pos + j + 1) * hs].to_vec()).collect();
8287                        let pairs: Vec<(&[f32], u32)> = rows.iter().enumerate().map(|(j, row)| (row.as_slice(), input_ids[first + j + 1])).collect();
8288                        #[cfg(target_os = "macos")]
8289                        let warmed = crate::gpu::q1_force() && {
8290                            if let Some(m) = mtp.as_mut() {
8291                                if !self.mtp_warm_batch_metal(m, &pairs, first) {
8292                                    for (j, (h, t)) in pairs.iter().enumerate() {
8293                                        let h = h.to_vec();
8294                                        let _ = self.mtp_step(m, &h, *t, first + j);
8295                                    }
8296                                }
8297                            }
8298                            true
8299                        };
8300                        #[cfg(not(target_os = "macos"))]
8301                        let warmed = false;
8302                        let warm_error = if warmed {
8303                            None
8304                        } else if let Some(m) = mtp.as_mut() {
8305                            self.mtp_warm_prefill_pairs(m, &pairs, first).err()
8306                        } else {
8307                            None
8308                        };
8309                        if let Some(err) = warm_error {
8310                            self.finish_generation(&mut mtp, &mut router, true);
8311                            return Err(err.to_string());
8312                        }
8313                    }
8314                }
8315                if std::env::var("CMF_GRAPH_PROF").is_ok() {
8316                    let ms = t_chunk.elapsed().as_secs_f64() * 1000.0;
8317                    eprintln!(
8318                        "batch-chunk: phase=prompt mode={} k={bk} outcome={outcome:?} {ms:.1} ms ({:.1} tok/s)",
8319                        if o1_batch_ready {
8320                            "o1"
8321                        } else if mtp_batch_prefill {
8322                            "ordinary_mtp"
8323                        } else {
8324                            "ordinary"
8325                        },
8326                        bk as f64 / (ms / 1000.0)
8327                    );
8328                }
8329                {
8330                    use std::sync::atomic::{AtomicBool, Ordering};
8331                    static SAID: AtomicBool = AtomicBool::new(false);
8332                    if !SAID.swap(true, Ordering::Relaxed) {
8333                        if ok_b {
8334                            tracing::info!(
8335                                "batched prefill: ACTIVE mode={} (k={bk})",
8336                                if o1_batch_ready {
8337                                    "o1"
8338                                } else if mtp_batch_prefill {
8339                                    "ordinary_mtp"
8340                                } else {
8341                                    "ordinary"
8342                                }
8343                            );
8344                        } else {
8345                            tracing::warn!("batched prefill {:?} — per-position graph", outcome);
8346                        }
8347                    }
8348                }
8349                if ok_b {
8350                    if mimo_spec {
8351                        self.mimo_note_rows(&hiddens, pos);
8352                    }
8353                    if mtp_batch_prefill {
8354                        let n_pairs = mtp_prefill_pair_count(pos, end, input_ids.len());
8355                        if n_pairs > 0 {
8356                            // `hiddens` is owned by this chunk, so materialize
8357                            // row slices before borrowing the detached MTP
8358                            // module.  The last prompt row has no successor;
8359                            // the helper above is the single source of that
8360                            // boundary rule.
8361                            let rows: Vec<Vec<f32>> = (0..n_pairs)
8362                                .map(|j| hiddens[j * hs..(j + 1) * hs].to_vec())
8363                                .collect();
8364                            let pairs: Vec<(&[f32], u32)> = rows
8365                                .iter()
8366                                .enumerate()
8367                                .map(|(j, row)| (row.as_slice(), input_ids[pos + j + 1]))
8368                                .collect();
8369                            if std::env::var("CMF_GRAPH_PROF").is_ok() {
8370                                eprintln!(
8371                                    "mtp-warm: phase=prompt mode=ordinary_mtp first_pos={} pairs={} last_pos={}",
8372                                    pos,
8373                                    n_pairs,
8374                                    pos + n_pairs - 1,
8375                                );
8376                            }
8377                            let t_warm = std::time::Instant::now();
8378                            let warm_error = if let Some(m) = mtp.as_mut() {
8379                                self.mtp_warm_prefill_pairs(m, &pairs, pos).err()
8380                            } else {
8381                                None
8382                            };
8383                            if std::env::var("CMF_GRAPH_PROF").is_ok() {
8384                                eprintln!("mtp-warm: {n_pairs} pairs in {:.1} ms", t_warm.elapsed().as_secs_f64() * 1e3);
8385                            }
8386                            if let Some(err) = warm_error {
8387                                // The trunk batch was already admitted.  A
8388                                // failed MTP warm-up therefore clears both
8389                                // mirrors and exits; continuing would pair a
8390                                // current trunk state with a stale MTP cache.
8391                                self.finish_generation(&mut mtp, &mut router, true);
8392                                return Err(err.to_string());
8393                            }
8394                        }
8395                    }
8396                    hidden.copy_from_slice(&hiddens[(bk - 1) * hs..]);
8397                    pos = end;
8398                    if snap_at == Some(end) {
8399                        self.gdn_snap = crate::gpu::gdn_snapshot(self.graph_kv_id, end).then(|| input_ids[..end].to_vec());
8400                    }
8401                } else if outcome == crate::gpu::BatchGraphOutcome::Failed {
8402                    // A failed batch may have advanced a device recurrent
8403                    // state (ordinary GDN or sealed O(1)). A CPU fallback
8404                    // would then observe stale accumulators, so clear the
8405                    // request state and make the failure explicit.
8406                    self.finish_generation(&mut mtp, &mut router, true);
8407                    return Err(if o1_batch_ready {
8408                        "sealed O(1) batch graph failed after admission".to_string()
8409                    } else {
8410                        "ordinary recurrent batch graph failed after admission".to_string()
8411                    });
8412                } else {
8413                    break; // unsupported → per-position graph handles the rest
8414                }
8415            }
8416            // a deferred chunk's archive rows the loop left behind (a later chunk declined)
8417            if let (Some(a), Some((p0, b0, n0))) = (o1_arch.as_mut(), arch_lag.take()) {
8418                if let Err(err) = self.o1_archive_chunk(a, p0, b0, Some(n0)) {
8419                    self.finish_generation(&mut mtp, &mut router, true);
8420                    return Err(err);
8421                }
8422            }
8423            if mtp_batch_prefill && mtp.is_some() && pos == input_ids.len() {
8424                self.mtp_warm_base = Some(self.mtp_pos_base);
8425            }
8426            // the CUDA DFlash block is built once the trunk's kernels are, so
8427            // its first round does not pay it
8428            #[cfg(feature = "cuda")]
8429            if crate::gpu::cuda_active() {
8430                if let Some(d) = &self.dflash {
8431                    let _ = d.dev_ready();
8432                }
8433            }
8434            #[cfg(target_os = "macos")]
8435            if std::env::var("CMF_PREFILL_PROF").is_ok() {
8436                crate::gpu_metal::cut_report();
8437            }
8438            // A dense stack the batched graph does not take reads the prompt chunked
8439            // on the host walk (its GEMMs on the card), as before the graph took dense
8440            // prompts, instead of one position at a time.
8441            if pos == pos_start
8442                && graph_prefill
8443                && !o1_batch_ready
8444                && mtp.is_none()
8445                && !mimo_spec
8446                && self.can_prefill_batched()
8447                && !self.per_token_stack()
8448                && self.weights.layers.iter().all(|lw| {
8449                    !matches!(&lw.attn, AttnKind::LinearGdn(_)) && !matches!(&lw.ffn, FfnKind::Moe(_))
8450                })
8451            {
8452                self.dense_batch_declined.store(true, std::sync::atomic::Ordering::Relaxed);
8453                let chunk = self.prefill_chunk();
8454                while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
8455                    let end = (pos + chunk).min(input_ids.len());
8456                    let hb = self.prefill_batch(&input_ids[pos..end], pos);
8457                    hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
8458                    pos = end;
8459                }
8460            }
8461        }
8462        // Resident Embryo graph: the prompt in chunks of one submit each
8463        // instead of one whole-graph submit per position; the last chunk
8464        // carries the logits exactly as the per-position walk would.
8465        if graph_prefill
8466            && task_mask.is_none()
8467            && mtp.is_none()
8468            && !dyn_prefill
8469            && pos == 0
8470            && input_ids.len() > 1
8471            && !self.cancel.load(std::sync::atomic::Ordering::Relaxed)
8472        {
8473            if let Some(lg) = self.embryo_prefill_chunked(input_ids, 0) {
8474                self.graph_logits = Some(lg);
8475                hidden = vec![0.0; self.hidden_size];
8476                pos = input_ids.len();
8477            }
8478        }
8479        while pos < input_ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
8480            self.graph_want_logits = fuse_lm && pos + 1 == input_ids.len();
8481            hidden = self.forward_layers(&self.embed_single(input_ids[pos]), pos, task_mask);
8482            if mimo_spec {
8483                self.mimo_note_rows(&hidden, pos);
8484            }
8485            if let Some(m) = &mut mtp {
8486                if pos + 1 < input_ids.len() {
8487                    // `CMF_MTP_CHAIN_PROBE=k`: teacher-forced acceptance of a
8488                    // CHAINED draft — iterate the head on its own hidden k
8489                    // deep and score every depth against the prompt's real
8490                    // continuation. The economics of a k-token speculative
8491                    // round stand or fall on this table.
8492                    let probe: usize = std::env::var("CMF_MTP_CHAIN_PROBE")
8493                        .ok()
8494                        .and_then(|v| v.parse().ok())
8495                        .unwrap_or(0);
8496                    if probe >= 1 && pos + 2 < input_ids.len() {
8497                        let (d1, mut hx) = self.mtp_step_h(m, &hidden, input_ids[pos + 1], pos);
8498                        let mut ok = d1 == input_ids[pos + 2];
8499                        Self::chain_probe_note(0, ok);
8500                        let mut d_prev = d1;
8501                        let mut extra = 0usize;
8502                        for j in 1..probe {
8503                            if pos + 2 + j >= input_ids.len() {
8504                                break;
8505                            }
8506                            let (dj, hj) = self.mtp_step_h(m, &hx, d_prev, pos + 1 + j);
8507                            extra += 1;
8508                            ok = ok && dj == input_ids[pos + 2 + j];
8509                            Self::chain_probe_note(j, ok);
8510                            d_prev = dj;
8511                            hx = hj;
8512                        }
8513                        // The chain's rows are speculation, not the prompt —
8514                        // keep only the warmup row the plain path would add.
8515                        m.kv.truncate_last(extra);
8516                    } else {
8517                        let _ = self.mtp_step(m, &hidden, input_ids[pos + 1], pos);
8518                    }
8519                }
8520            }
8521            pos += 1;
8522        }
8523        #[cfg(not(target_os = "macos"))]
8524        crate::gpu::set_batch_kv_hint(0);
8525        if std::env::var("CMF_PREFILL_PROF").is_ok() {
8526            eprintln!(
8527                "prefill: {} tokens in {:.1} ms (batch_k={batch_k})",
8528                input_ids.len(),
8529                _tpf.elapsed().as_secs_f64() * 1000.0
8530            );
8531        }
8532        // The Neural Engine read the prompt; decode runs on the GPU, so its surfaces go back
8533        // to the weight map (`ane::release_idle`).
8534        #[cfg(target_os = "macos")]
8535        crate::gpu_metal::ane::release_idle();
8536        if self
8537            .graph_failed
8538            .swap(false, std::sync::atomic::Ordering::Relaxed)
8539        {
8540            // MTP is detached for speculative generation.  Restore the
8541            // module before returning the terminal graph error; otherwise a
8542            // failed request would silently remove the head from a pooled
8543            // pipeline and the next request would lose its configured route.
8544            self.finish_generation(&mut mtp, &mut router, true);
8545            return Err("GPU token graph failed during prefill".to_string());
8546        }
8547        // Cancelled mid-prefill: the cache holds a partial prompt —
8548        // drop the reuse history and return an empty generation.
8549        if self
8550            .cancel
8551            .swap(false, std::sync::atomic::Ordering::Relaxed)
8552        {
8553            // A cancelled prefill can already have advanced the device
8554            // mirror. Drop the whole partial sequence so a pooled pipeline
8555            // cannot carry that state into its next request.
8556            self.finish_generation(&mut mtp, &mut router, true);
8557            return Ok(GenerateResult {
8558                text: String::new(),
8559                token_ids: Vec::new(),
8560                prompt_tokens: input_ids.len(),
8561                tokens_generated: 0,
8562                finish_reason: "cancelled".to_string(),
8563                mtp_drafted: 0,
8564                mtp_accepted: 0,
8565                token_confidence: Vec::new(),
8566                traces: Vec::new(),
8567            });
8568        }
8569
8570        // Prompt absorbed → freeze the o1 layers' skeletons; from here
8571        // every decode step on those layers is O(W + m·dv + m²).
8572        if !o1_sealed {
8573            match self.o1_seal_checked() {
8574                Ok(_) => {}
8575                Err(err) => {
8576                    self.finish_generation(&mut mtp, &mut router, true);
8577                    return Err(err);
8578                }
8579            }
8580        }
8581
8582        // Bytes of a character the last streamed token left unfinished.
8583        let mut utf8_pending: Vec<u8> = Vec::new();
8584        // Commit one token: push, check EOS, stream. Returns false = stop.
8585        macro_rules! commit {
8586            ($id:expr) => {{
8587                all_ids.push($id);
8588                generated += 1;
8589                self.note_draft_id($id);
8590                if self.tokenizer.is_eos($id) && !self.ignore_eos {
8591                    finish_reason = "stop".to_string();
8592                    false
8593                } else {
8594                    let token_text = self.tokenizer.decode_token_stream($id, &mut utf8_pending);
8595                    let mut go = true;
8596                    if let Some(ref mut cb) = on_token {
8597                        if !cb(&token_text) {
8598                            finish_reason = "cancelled".to_string();
8599                            go = false;
8600                        }
8601                    }
8602                    if go
8603                        && self.sampler_config.loop_stop
8604                        && crate::sampler::tail_repeats(&all_ids[all_ids.len() - generated..])
8605                    {
8606                        finish_reason = "loop".to_string();
8607                        go = false;
8608                    }
8609                    go
8610                }
8611            }};
8612        }
8613
8614        // Speculation is decided by MEASUREMENT, not by an acceptance
8615        // model. A k=4 round costs ~3.8 plain tokens on the 5090 (draft
8616        // 6.6 + verify 66.6 + commit 4.8 ms against a 20.6 ms token), so it
8617        // pays only when the head lands ~2.8 of 4 — predictable text (code,
8618        // structured output) does, free prose often does not, and the
8619        // ratio at which the two cross depends on the card and the context
8620        // depth. So: four speculative rounds timed, then eight plain
8621        // tokens timed, and the faster arm runs until a re-check 256
8622        // tokens later (context growth moves the balance). The trial
8623        // costs at most a few tokens of the slower arm per 256.
8624        let mut spec_trial = SpecTrial::Spec {
8625            t0: std::time::Instant::now(),
8626            gen0: generated,
8627            rounds: 0,
8628        };
8629        // The token-count proxy prices a round at ~1.9 plain tokens. That
8630        // holds for the Metal rounds whose cost was measured — greedy and
8631        // the sparse sampling chain — so an expensive round (the dense
8632        // chain, reachable only by `CMF_GRAPH_SPEC_SAMPLE=1`) still times
8633        // the plain path before it decides.
8634        let mut spec_mon = SpecMon {
8635            metal: graph_spec && crate::gpu::q1_force() && spec_cheap_round,
8636            cuda: graph_spec && crate::gpu::cuda_active() && self.sampler_config.temperature < 1e-6,
8637            ..SpecMon::default()
8638        };
8639        // wgpu: a plain token an earlier request's trial timed stands while
8640        // the context is of the same order (the trunk's weights are most of
8641        // a token's time), and this trial decides after its rounds.
8642        if !spec_mon.metal && self.spec_plain_ms.0 > 0.0 && input_ids.len() <= self.spec_plain_ms.1 * 2 + 1024 {
8643            spec_mon.plain_ms = self.spec_plain_ms.0;
8644        }
8645        let mut spec_watchdog_off = false;
8646        // CMF_GRAPH_SPEC_TIME: the round walls so far (round 1 excluded —
8647        // it pays the scratch), for the outlier test on each new one
8648        let mut spec_walls: Vec<f32> = Vec::new();
8649        // ... and the end of the last round: the host time between rounds
8650        // (token commits, streaming, the loop top) is printed at level 2
8651        let mut spec_round_end: Option<std::time::Instant> = None;
8652        if mimo_spec {
8653            if let Ok(path) = std::env::var("CMF_MIMO_MTP_PROBE") {
8654                if let Some(mut st) = self.mimo_mtp.take() {
8655                    self.mimo_mtp_probe(&mut st, input_ids, &path);
8656                    self.mimo_mtp = Some(st);
8657                }
8658            }
8659        }
8660        // ── Decode ──
8661        let mut next_pos = input_ids.len();
8662        'decode: while generated < max_tokens {
8663            if self
8664                .graph_failed
8665                .swap(false, std::sync::atomic::Ordering::Relaxed)
8666            {
8667                // Keep the detached MTP module attached after a terminal
8668                // graph error so the pipeline can be reused for a fresh
8669                // sequence.  `clear_sequence_state` only clears mirrors and
8670                // host KV; it cannot recover a module dropped here.
8671                self.finish_generation(&mut mtp, &mut router, true);
8672                return Err("GPU token graph failed during decode".to_string());
8673            }
8674            if self
8675                .cancel
8676                .swap(false, std::sync::atomic::Ordering::Relaxed)
8677            {
8678                finish_reason = "cancelled".to_string();
8679                break 'decode;
8680            }
8681            // A rejected speculative draft already drew this position's
8682            // token from the residual distribution (graph_spec_step); it
8683            // is committed as-is — sampling again from the row's logits
8684            // would bias the stream toward the target's mode.
8685            if mimo_spec && next_pos > 0 {
8686                // Every path leaves `hidden` = the backbone output at
8687                // next_pos-1; the draft layers read it (idempotent).
8688                self.mimo_note_rows(&hidden, next_pos - 1);
8689            }
8690            let forced = self.spec_forced.take();
8691            let mut logits = match (forced, self.graph_logits.take()) {
8692                (Some(_), _) => Vec::new(),
8693                (None, Some(lg)) => lg,
8694                (None, None) => {
8695                    let _prof = crate::cpuprof::time(crate::cpuprof::Slot::Head);
8696                    // Pooled-tail mode: the head as one layer-less device
8697                    // pass (final-norm + matvec + readback). Any decline —
8698                    // no pool, unresolvable weight, backend off — keeps the
8699                    // host head exactly as before.
8700                    #[cfg(feature = "gpu")]
8701                    let logits_out = if let Some(lg) = self.m3_device_logits(&hidden) {
8702                        lg
8703                    } else {
8704                        inference::rms_norm_into(
8705                            &hidden,
8706                            &self.weights.final_norm,
8707                            self.rms_eps,
8708                            self.norm_style,
8709                            &mut self.ws.n1,
8710                        );
8711                        self.lm_head_forward(&self.ws.n1)
8712                    };
8713                    #[cfg(not(feature = "gpu"))]
8714                    let logits_out = {
8715                        inference::rms_norm_into(
8716                            &hidden,
8717                            &self.weights.final_norm,
8718                            self.rms_eps,
8719                            self.norm_style,
8720                            &mut self.ws.n1,
8721                        );
8722                        self.lm_head_forward(&self.ws.n1)
8723                    };
8724                    logits_out
8725                }
8726            };
8727            // CMF_LOGIT_DUMP=<path>: the first decode step's hidden + logits
8728            // as raw f32 (hidden first) — cross-backend numerics diffing.
8729            if generated
8730                == std::env::var("CMF_LOGIT_DUMP_STEP")
8731                    .ok()
8732                    .and_then(|v| v.parse().ok())
8733                    .unwrap_or(0)
8734            {
8735                if let Ok(path) = std::env::var("CMF_LOGIT_DUMP") {
8736                    let mut bytes: Vec<u8> = Vec::with_capacity((hidden.len() + logits.len()) * 4);
8737                    for v in hidden.iter().chain(logits.iter()) {
8738                        bytes.extend_from_slice(&v.to_le_bytes());
8739                    }
8740                    if let Err(e) = std::fs::write(&path, &bytes) {
8741                        eprintln!("logit dump: failed to write {path}: {e}");
8742                        self.finish_generation(&mut mtp, &mut router, true);
8743                        return Err(format!("logit dump write failed: {e}"));
8744                    }
8745                }
8746            }
8747            if generated == 0 && self.want_first_logits {
8748                self.first_logits = Some(logits.clone());
8749            }
8750            // CMF_LOGIT_DUMP_ALL=<dir>: every decode step's logits as raw
8751            // f32, `<dir>/step{n:05}.f32` — step-by-step backend diffing
8752            // (a greedy run on two backends compares until they diverge).
8753            if let Ok(dir) = std::env::var("CMF_LOGIT_DUMP_ALL") {
8754                if !logits.is_empty() {
8755                    let path = std::path::Path::new(&dir).join(format!("step{generated:05}.f32"));
8756                    let bytes: Vec<u8> = logits.iter().flat_map(|v| v.to_le_bytes()).collect();
8757                    if let Err(e) =
8758                        std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(&path, &bytes))
8759                    {
8760                        eprintln!("logit dump: failed to write {}: {e}", path.display());
8761                    }
8762                }
8763            }
8764            self.clover_causal_logits(&mut logits, generated, &all_ids[penalty_from..]);
8765            if let Some(g) = self.dash.as_mut().and_then(|d| d.guard.as_mut()) {
8766                g.apply(&mut logits, &all_ids[input_ids.len()..]);
8767            }
8768            let t_next = match forced.or_else(|| forced_ids_at(generated)) {
8769                Some(c) => c,
8770                None => {
8771                    let _prof = crate::cpuprof::time(crate::cpuprof::Slot::Sampler);
8772                    sampler::sample_with_scratch_pool(
8773                        &logits,
8774                        &self.sampler_config,
8775                        self.sampler_config.penalty_past(&all_ids[penalty_from..], bounded_native),
8776                        &mut self.rng,
8777                        &mut self.sampler_scratch,
8778                        self.pool.as_deref(),
8779                    )
8780                }
8781            };
8782            if self.confidence_on {
8783                confidence.push(if logits.is_empty() {
8784                    0.0
8785                } else {
8786                    sampler::top1_prob_pool(
8787                        self.pool.as_deref(),
8788                        &mut self.sampler_scratch,
8789                        &logits,
8790                        t_next,
8791                        calib_temp,
8792                    )
8793                });
8794            }
8795            if !logits.is_empty() {
8796                attention::recycle_buf(&mut logits);
8797            }
8798            if trace_on {
8799                // active_skill = the overlay in force while this token was
8800                // generated; recon/switched are filled after the post-emit
8801                // routing eval below (freshest coherence for this token).
8802                let skill = router.as_ref().and_then(|r| r.active_id());
8803                traces.push(TokenTrace {
8804                    t: generated,
8805                    token_id: t_next,
8806                    confidence: confidence.last().copied().unwrap_or(0.0),
8807                    active_skill: skill,
8808                    recon: None,
8809                    switched: false,
8810                });
8811            }
8812            if !commit!(t_next) {
8813                break 'decode;
8814            }
8815            if generated >= max_tokens {
8816                break 'decode;
8817            }
8818
8819            // Catch-all for decode paths that bypass the walks' own trim
8820            // (a graph step, a speculative round).
8821            self.swa_trim_tails();
8822            if self.dsv41.is_none() && self.dory.is_none() && self.kv_cache.needs_eviction() {
8823                // Say it ONCE, loudly: past this point the model keeps
8824                // talking but has lost half its context, and on a GDN
8825                // hybrid the graph's device state goes stale on top. The
8826                // Qwen3.8 bring-up spent a day reading this cliff as
8827                // three different model bugs.
8828                static SAID: std::sync::Once = std::sync::Once::new();
8829                SAID.call_once(|| {
8830                    tracing::warn!(
8831                        "KV cache full at {} positions — evicting half; quality \
8832                         will degrade. Raise CMF_MAX_SEQ.",
8833                        self.kv_cache.max_seq_len,
8834                    );
8835                });
8836                let keep = (self.kv_cache.max_seq_len / 2).max(1);
8837                self.kv_cache.evict(keep);
8838            }
8839
8840            // Advance the speculation trial: plain-phase accounting and
8841            // the periodic re-check happen here, on every token.
8842            if graph_spec {
8843                match spec_trial {
8844                    SpecTrial::Plain { t0, gen0 } if spec_mon.plain_done(t0, gen0, generated) => {
8845                        spec_mon.plain_ms =
8846                            t0.elapsed().as_secs_f64() * 1e3 / (generated - gen0) as f64;
8847                        if !spec_mon.metal {
8848                            self.spec_plain_ms = (spec_mon.plain_ms, next_pos);
8849                        }
8850                        let keep = spec_mon.pays();
8851                        tracing::info!(
8852                            "speculation trial: {:.2} tok/round in {:.1} ms vs plain {:.1} ms/tok — {}",
8853                            spec_mon.tokens,
8854                            spec_mon.round_ms,
8855                            spec_mon.plain_ms,
8856                            if keep { "speculating" } else { "plain" }
8857                        );
8858                        spec_mon.fails = 0;
8859                        spec_trial = SpecTrial::Decided {
8860                            spec: keep,
8861                            recheck_at: if keep { usize::MAX } else { spec_mon.recheck_plain_at(generated) },
8862                        };
8863                    }
8864                    SpecTrial::Decided { recheck_at, .. } if generated >= recheck_at => {
8865                        spec_mon.n = 0;
8866                        spec_mon.zero_accept_rounds = 0;
8867                        spec_trial = SpecTrial::Spec {
8868                            t0: std::time::Instant::now(),
8869                            gen0: generated,
8870                            rounds: 0,
8871                        };
8872                    }
8873                    _ => {}
8874                }
8875                spec_watchdog_off = matches!(
8876                    spec_trial,
8877                    SpecTrial::Plain { .. } | SpecTrial::Decided { spec: false, .. }
8878                );
8879            }
8880            // ── MiMo-V2 draft stack: draft K, verify K+1 rows in one batch ──
8881            if mimo_spec && generated + 1 < max_tokens && next_pos > 0 {
8882                let budget = max_tokens - generated - 1;
8883                if let Some(mut st) = self.mimo_mtp.take() {
8884                    let k = st.depth.min(budget);
8885                    let r = self.mimo_spec_round(&mut st, next_pos, &all_ids, k);
8886                    self.mimo_mtp = Some(st);
8887                    let r = match r {
8888                        Ok(r) => r,
8889                        Err(err) => {
8890                            self.finish_generation(&mut mtp, &mut router, true);
8891                            return Err(err);
8892                        }
8893                    };
8894                    if let Some(r) = r {
8895                        drafted += r.drafted;
8896                        accepted += r.accepted.len();
8897                        let mut stopped = false;
8898                        for &id in &r.accepted {
8899                            if self.confidence_on {
8900                                confidence.push(0.0);
8901                            }
8902                            if !commit!(id) {
8903                                stopped = true;
8904                                break;
8905                            }
8906                        }
8907                        if stopped {
8908                            break 'decode;
8909                        }
8910                        next_pos += r.accepted.len() + 1;
8911                        hidden = r.hidden;
8912                        // The loop top chooses the round's own token from
8913                        // these logits — the same sampler, same history.
8914                        self.graph_logits = Some(r.logits);
8915                        continue 'decode;
8916                    }
8917                }
8918            }
8919            // ── A trunk without a draft block: the sidecar's block drafts, the batch graph verifies ──
8920            #[cfg(feature = "gpu")]
8921            if solo_spec && next_pos > 0 {
8922                let now = std::time::Instant::now();
8923                // the step that just ended, on the account of its kind
8924                if let Some((t, tokens)) = solo.last.take() {
8925                    let ms = (now - t).as_secs_f32() * 1e3;
8926                    if tokens == 0 {
8927                        if solo.plain_n > 0 {
8928                            solo.plain_ms = if solo.plain_ms == 0.0 { ms } else { 0.7 * solo.plain_ms + 0.3 * ms };
8929                        }
8930                        solo.plain_n += 1;
8931                    } else if solo.first {
8932                        solo.first = false;
8933                        if spec_time_level() > 0 {
8934                            eprintln!("solo-round wall {ms:.1} ms → {tokens} tokens (the first round: not a sample)");
8935                        }
8936                    } else {
8937                        let per = ms / tokens as f32;
8938                        // a tenth a round: one round that kept nothing (85 ms for its
8939                        // one token against 20 a token before it) must not send a
8940                        // drafter keeping 80 % to rest — at a fifth it did, 36 against
8941                        // 47 tok/s on code
8942                        solo.round_ms = if solo.rounds == 0 { per } else { 0.9 * solo.round_ms + 0.1 * per };
8943                        solo.rounds += 1;
8944                        if spec_time_level() > 0 {
8945                            eprintln!(
8946                                "solo-round wall {ms:.1} ms → {tokens} tokens ({:.1} ms a token, plain {:.1})",
8947                                solo.round_ms, solo.plain_ms
8948                            );
8949                        }
8950                        // Rounds that land tokens no faster than plain steps sit out, longer
8951                        // each time. Judged on the window's summed wall over its summed
8952                        // tokens from its SOLO_JUDGE-th round on: a short answer was over
8953                        // before six rounds at a third kept had sent the drafter to rest
8954                        // (MNN-Pocket-0.3B chat: 237 against 303 tok/s plain), and one
8955                        // round that kept nothing weighs only its share of the sum.
8956                        solo.win_ms += ms;
8957                        solo.win_tok += tokens as u32;
8958                        if solo_pin.is_none() && solo.plain_ms > 0.0 && solo.rounds >= SOLO_JUDGE {
8959                            if solo.win_ms / solo.win_tok.max(1) as f32 > solo.plain_ms {
8960                                solo.rest = solo.back;
8961                                solo.back = (solo.back * 2).min(SOLO_REST_MOST);
8962                                solo.rounds = 0;
8963                                solo.win_ms = 0.0;
8964                                solo.win_tok = 0;
8965                            } else if solo.rounds >= SOLO_TRIAL {
8966                                // a winning window starts over, so the verdict follows the text
8967                                solo.rounds = 0;
8968                                solo.win_ms = 0.0;
8969                                solo.win_tok = 0;
8970                            }
8971                        }
8972                    }
8973                }
8974                if solo.rest == 0 && generated + 1 < max_tokens {
8975                    let k = solo.k.min(max_tokens - generated);
8976                    match self.solo_spec_round(t_next, next_pos, &all_ids, k) {
8977                        Some(r) => {
8978                            drafted += r.drafted;
8979                            accepted += r.accepted.len();
8980                            if solo_pin.is_none() {
8981                                // two past what held: a round that held all of its drafts goes deeper
8982                                solo.k = (r.accepted.len() + 2).clamp(2, SOLO_K_AUTO);
8983                            }
8984                            solo.last = Some((now, r.accepted.len() + 1));
8985                            let mut stopped = false;
8986                            for &id in &r.accepted {
8987                                if self.confidence_on {
8988                                    confidence.push(0.0);
8989                                }
8990                                if trace_on {
8991                                    traces.push(TokenTrace {
8992                                        t: generated,
8993                                        token_id: id,
8994                                        confidence: confidence.last().copied().unwrap_or(0.0),
8995                                        active_skill: None,
8996                                        recon: None,
8997                                        switched: false,
8998                                    });
8999                                }
9000                                if !commit!(id) {
9001                                    stopped = true;
9002                                    break;
9003                                }
9004                            }
9005                            if stopped {
9006                                break 'decode;
9007                            }
9008                            next_pos += r.accepted.len() + 1;
9009                            hidden = r.hidden;
9010                            self.graph_logits = Some(r.logits);
9011                            continue 'decode;
9012                        }
9013                        None => {
9014                            if self.graph_failed.swap(false, std::sync::atomic::Ordering::Relaxed) {
9015                                self.finish_generation(&mut mtp, &mut router, true);
9016                                return Err("GPU batch graph failed during a speculative round".to_string());
9017                            }
9018                            // no round here (the drafter's context is not at the tip, the batch graph declined)
9019                            solo.rest = 8;
9020                        }
9021                    }
9022                }
9023                solo.rest = solo.rest.saturating_sub(1);
9024                solo.last = Some((now, 0));
9025            }
9026            // ── Qwen3.8-Flash-Next draft head: k greedy drafts from the MTP
9027            //    sidecar, one batched verify window on the device ──
9028            #[cfg(feature = "gpu")]
9029            if self.speculative
9030                && self.qwen4_exp.is_some()
9031                && task_mask.is_none()
9032                && self.sampler_config.temperature < 1e-6
9033                && generated + 1 < max_tokens
9034                && next_pos > 0
9035                && std::env::var("CMF_QWEN_MTP").as_deref() != Ok("0")
9036            {
9037                let r = match &mut self.qwen4_exp {
9038                    Some(b) => {
9039                        // a copy frame drafts no further than the request goes
9040                        b.3.set_draft_budget(max_tokens - generated - 1);
9041                        crate::qwen4_exp::spec_round(
9042                            &b.0,
9043                            &b.1,
9044                            &b.2,
9045                            &mut b.3,
9046                            next_pos,
9047                            &all_ids,
9048                            &self.inv_freq,
9049                            self.pool.as_deref(),
9050                        )
9051                    }
9052                    None => None,
9053                };
9054                if let Some(r) = r {
9055                    drafted += r.drafted;
9056                    accepted += r.accepted.len();
9057                    let mut stopped = false;
9058                    for &id in &r.accepted {
9059                        if self.confidence_on {
9060                            confidence.push(0.0);
9061                        }
9062                        if !commit!(id) {
9063                            stopped = true;
9064                            break;
9065                        }
9066                    }
9067                    if stopped {
9068                        break 'decode;
9069                    }
9070                    next_pos += r.accepted.len() + 1;
9071                    hidden.fill(0.0);
9072                    self.graph_logits = Some(r.logits);
9073                    continue 'decode;
9074                }
9075            }
9076            match &mut mtp {
9077                // ── Graph speculation: chain-draft, batch-verify on device ──
9078                #[cfg(feature = "gpu")]
9079                Some(m)
9080                    if graph_spec
9081                        && !spec_watchdog_off
9082                        && !self.spec_over_budget
9083                        && generated + 1 < max_tokens
9084                        && next_pos > 0 =>
9085                {
9086                    let t_round = std::time::Instant::now();
9087                    let drafted0 = drafted;
9088                    if spec_time_level() >= 2 {
9089                        if let Some(t) = spec_round_end.take() {
9090                            eprintln!(
9091                                "spec-gap {:.2} ms (host between rounds)",
9092                                t.elapsed().as_secs_f64() * 1e3
9093                            );
9094                        }
9095                    }
9096                    spec_stamps_begin();
9097                    // device buffers allocated during this round: a
9098                    // first-touch Shared allocation is zero-filled inside
9099                    // the command buffer that uses it, which is what the
9100                    // long outlier rounds were
9101                    #[cfg(target_os = "macos")]
9102                    let allocs0 =
9103                        crate::gpu_metal::IO_BUF_ALLOCS.load(std::sync::atomic::Ordering::Relaxed);
9104                    #[cfg(not(target_os = "macos"))]
9105                    let allocs0 = 0u64;
9106                    if let Some((extra, n_pos, new_h)) = self.graph_spec_step(
9107                        m,
9108                        &hidden,
9109                        t_next,
9110                        next_pos,
9111                        &mut drafted,
9112                        &mut accepted,
9113                        &mut all_ids,
9114                        max_tokens - generated,
9115                    ) {
9116                        next_pos = n_pos;
9117                        hidden = new_h;
9118                        let level = spec_time_level();
9119                        if level > 0 {
9120                            let wall = t_round.elapsed().as_secs_f32() * 1e3;
9121                            let stamps = spec_stamps_take();
9122                            // the running median of the rounds before this
9123                            // one (round 1 pays the scratch: not a sample)
9124                            let median = if spec_walls.len() >= 3 {
9125                                let mut s = spec_walls.clone();
9126                                s.sort_by(|a, b| a.partial_cmp(b).unwrap());
9127                                Some(s[s.len() / 2])
9128                            } else {
9129                                None
9130                            };
9131                            let outlier = median.is_some_and(|m| wall > 1.4 * m);
9132                            #[cfg(target_os = "macos")]
9133                            let allocs = crate::gpu_metal::IO_BUF_ALLOCS
9134                                .load(std::sync::atomic::Ordering::Relaxed)
9135                                - allocs0;
9136                            #[cfg(not(target_os = "macos"))]
9137                            let allocs = allocs0;
9138                            eprintln!(
9139                                "spec-round wall {wall:.1} ms → {} tokens{}{}",
9140                                extra.len() + 1,
9141                                if allocs > 0 {
9142                                    format!(" [{allocs} new device buffers]")
9143                                } else {
9144                                    String::new()
9145                                },
9146                                match (outlier, median) {
9147                                    (true, Some(m)) => format!(" OUTLIER (median {m:.1})"),
9148                                    _ => String::new(),
9149                                }
9150                            );
9151                            if level >= 2 || outlier {
9152                                let sum: f32 = stamps.iter().map(|s| s.1).sum();
9153                                eprintln!(
9154                                    "spec-stamps: {}| untracked {:.1}",
9155                                    spec_stamps_format(&stamps),
9156                                    wall - sum
9157                                );
9158                            }
9159                            if spec_mon.n >= 1 {
9160                                spec_walls.push(wall);
9161                            }
9162                        }
9163                        // One speculative round done: the monitor counts it
9164                        // (round 1 untimed — it pays the batch scratch and
9165                        // the draft mirror), and the trial advances.
9166                        spec_mon.round(t_round.elapsed().as_secs_f64() * 1e3, extra.len() + 1);
9167                        // the round's tokens land in `generated` below; the
9168                        // plain phase must start counting AFTER them
9169                        spec_trial = Self::spec_trial_round(
9170                            spec_trial,
9171                            &mut spec_mon,
9172                            generated + extra.len() + 1,
9173                        );
9174                        let mut stopped = false;
9175                        for &id in &extra {
9176                            if self.confidence_on {
9177                                confidence.push(0.0);
9178                            }
9179                            // `graph_spec_step` commits the accepted MTP
9180                            // drafts as a batch.  They do not pass through
9181                            // the ordinary loop-top sampling block below,
9182                            // which is normally where the telemetry row is
9183                            // created.  Keep the public trace contract
9184                            // (one row per emitted token) here as well.
9185                            //
9186                            // The graph-spec path does not surface a
9187                            // per-row probability for accepted extras.  It
9188                            // deliberately matches the zero placed in the
9189                            // confidence channel above instead of inventing
9190                            // one or adding a separate probability pass.
9191                            if trace_on {
9192                                traces.push(TokenTrace {
9193                                    t: generated,
9194                                    token_id: id,
9195                                    confidence: confidence.last().copied().unwrap_or(0.0),
9196                                    active_skill: None,
9197                                    recon: None,
9198                                    switched: false,
9199                                });
9200                            }
9201                            if !commit!(id) {
9202                                stopped = true;
9203                                break;
9204                            }
9205                        }
9206                        if stopped {
9207                            break 'decode;
9208                        }
9209                        if spec_time_level() >= 2 {
9210                            spec_round_end = Some(std::time::Instant::now());
9211                        }
9212                        continue 'decode;
9213                    }
9214                    if self
9215                        .graph_failed
9216                        .swap(false, std::sync::atomic::Ordering::Relaxed)
9217                    {
9218                        // `graph_spec_step` may have detached MTP while a
9219                        // warm-up was in flight.  Do not reinterpret its
9220                        // terminal device failure as a plain decode step;
9221                        // restore the head, clear both mirrors, and surface
9222                        // one explicit error to the caller.
9223                        self.finish_generation(&mut mtp, &mut router, true);
9224                        return Err("GPU MTP graph failed during speculative decode".to_string());
9225                    }
9226                    // A verify the weight budget refuses (the stack does not fit the card,
9227                    // a device prefix runs the rest on the host) is refused every time:
9228                    // the round's drafts were never checked, so they leave the count, and
9229                    // no draft is made for this model again (an 8 GB Radeon reported "0 of
9230                    // 54 accepted" while every round paid for its drafts).
9231                    if crate::gpu::batch_graph_over_budget() {
9232                        drafted = drafted0;
9233                        self.spec_over_budget = true;
9234                        tracing::info!("drafts off: a verify does not fit the weight budget");
9235                        hidden = self.forward_layers(&self.embed_single(t_next), next_pos, task_mask);
9236                        next_pos += 1;
9237                        continue 'decode;
9238                    }
9239                    // Declined (batch graph refused): plain forward below —
9240                    // and a round that produced one token for the trial's
9241                    // ledger, so a graph that keeps refusing is measured out
9242                    // like a head that keeps missing (it was spinning
9243                    // forever on a file whose batch graph declines).
9244                    // A declined round is not a cheap one-token round — it
9245                    // is a verify that does not exist for this file (a
9246                    // healed q8_2f tail measured 760 drafts, 0 accepted, 33
9247                    // against 48.8 tok/s while the monitor called the draft
9248                    // alone "paying"). Count it as the losing streak in one.
9249                    spec_mon.round(t_round.elapsed().as_secs_f64() * 1e3, 1);
9250                    spec_mon.tokens = 0.0;
9251                    spec_mon.fails = 3;
9252                    spec_trial = Self::spec_trial_round(spec_trial, &mut spec_mon, generated + 1);
9253                    hidden = self.forward_layers(&self.embed_single(t_next), next_pos, task_mask);
9254                    next_pos += 1;
9255                    continue 'decode;
9256                }
9257                // ── Speculative: draft t+2, verify in a fused pair ──
9258                Some(m) if !graph_spec && generated + 1 < max_tokens => {
9259                    let draft = self.mtp_step(m, &hidden, t_next, next_pos - 1);
9260                    drafted += 1;
9261                    let emb1 = self.embed_single(t_next);
9262                    let emb2 = self.embed_single(draft);
9263                    let (h1, h2) = self.forward_pair(&emb1, &emb2, next_pos);
9264
9265                    inference::rms_norm_into(
9266                        &h1,
9267                        &self.weights.final_norm,
9268                        self.rms_eps,
9269                        self.norm_style,
9270                        &mut self.ws.n1,
9271                    );
9272                    let mut logits1 = self.lm_head_forward(&self.ws.n1);
9273                    let t_after = sampler::sample_with_scratch_pool(
9274                        &logits1,
9275                        &self.sampler_config,
9276                        self.sampler_config.penalty_past(&all_ids, bounded_native),
9277                        &mut self.rng,
9278                        &mut self.sampler_scratch,
9279                        self.pool.as_deref(),
9280                    );
9281                    if self.confidence_on {
9282                        confidence.push(sampler::top1_prob_pool(
9283                            self.pool.as_deref(),
9284                            &mut self.sampler_scratch,
9285                            &logits1,
9286                            t_after,
9287                            calib_temp,
9288                        ));
9289                    }
9290                    attention::recycle_buf(&mut logits1);
9291                    if trace_on {
9292                        // Speculative decode is mutually exclusive with
9293                        // dynamic routing (router is None here) — no skill.
9294                        traces.push(TokenTrace {
9295                            t: generated,
9296                            token_id: t_after,
9297                            confidence: confidence.last().copied().unwrap_or(0.0),
9298                            active_skill: None,
9299                            recon: None,
9300                            switched: false,
9301                        });
9302                    }
9303                    let stop = !commit!(t_after);
9304
9305                    if t_after == draft {
9306                        accepted += 1;
9307                        self.commit_linear_scratch();
9308                        let _ = self.mtp_step(m, &h1, t_after, next_pos);
9309                        hidden = h2;
9310                        next_pos += 2;
9311                    } else {
9312                        // The draft lane is wrong: roll its KV entry back.
9313                        for layer in &mut self.kv_cache.layers {
9314                            layer.truncate_last(1);
9315                        }
9316                        if !stop {
9317                            let _ = self.mtp_step(m, &h1, t_after, next_pos);
9318                            hidden = self.forward_layers(
9319                                &self.embed_single(t_after),
9320                                next_pos + 1,
9321                                None,
9322                            );
9323                        }
9324                        next_pos += 2;
9325                    }
9326                    if stop {
9327                        break 'decode;
9328                    }
9329                }
9330                // ── Vanilla: forward the sampled token ──
9331                _ => {
9332                    // ── DeepSeek-V4 speculative decode (CMF_DSV4_SPEC=1):
9333                    // draft five on the card, verify batched, commit the
9334                    // accepted prefix. Greedy only; a rejected token's state
9335                    // is restored and replayed, so output equals the walk. ──
9336                    #[cfg(feature = "gpu")]
9337                    if Self::dsv4_spec_on() && self.dsv4.is_some() {
9338                        static SAID: std::sync::Once = std::sync::Once::new();
9339                        SAID.call_once(|| {
9340                            eprintln!(
9341                                "dsv4-spec gate: mtp={} mask={} router={} trace={} temp={} rep={} ",
9342                                !self.dsv4_mtp.is_empty(),
9343                                task_mask.is_none(),
9344                                router.is_none(),
9345                                !trace_on,
9346                                self.sampler_config.temperature < 1e-6,
9347                                self.sampler_config.repetition_penalty == 1.0,
9348                            );
9349                        });
9350                    }
9351                    #[cfg(feature = "gpu")]
9352                    if Self::dsv4_spec_on()
9353                        && self.dsv4.is_some()
9354                        && !self.dsv4_mtp.is_empty()
9355                        && task_mask.is_none()
9356                        && router.is_none()
9357                        && !trace_on
9358                        && self.sampler_config.temperature < 1e-6
9359                        && self.sampler_config.repetition_penalty == 1.0
9360                        && generated + 1 < max_tokens
9361                        && all_ids.len() >= 2
9362                        && generated >= dsv4_spec_retry_at
9363                    {
9364                        let tip_token = all_ids[all_ids.len() - 2];
9365                        let drafted0 = drafted;
9366                        let round = self.dsv4_spec_step(
9367                            tip_token,
9368                            t_next,
9369                            next_pos,
9370                            max_tokens.saturating_sub(generated),
9371                            &mut drafted,
9372                            &mut accepted,
9373                        );
9374                        if drafted > drafted0 {
9375                            let useful = round.as_ref().is_some_and(|(extra, _)| !extra.is_empty());
9376                            if useful {
9377                                dsv4_spec_bad = 0;
9378                            } else {
9379                                dsv4_spec_bad += 1;
9380                                if dsv4_spec_bad >= 2 {
9381                                    dsv4_spec_bad = 0;
9382                                    dsv4_spec_retry_at = generated.saturating_add(32);
9383                                    tracing::info!(
9384                                        "dsv4: the draft did not pay off twice — exact walk for 32 tokens"
9385                                    );
9386                                }
9387                            }
9388                        }
9389                        if let Some((extra, n_pos)) = round {
9390                            next_pos = n_pos;
9391                            let mut stopped = false;
9392                            for &id in &extra {
9393                                if self.confidence_on {
9394                                    confidence.push(0.0);
9395                                }
9396                                if !commit!(id) {
9397                                    stopped = true;
9398                                    break;
9399                                }
9400                            }
9401                            if stopped {
9402                                break 'decode;
9403                            }
9404                            continue 'decode;
9405                        }
9406                    }
9407                    // ── Inkling 2 DSpark (the file's drafter, greedy): the
9408                    // anchor and its drafts through the target in one call,
9409                    // the agreed prefix kept, the rest rolled back; the output
9410                    // is plain decoding's. ──
9411                    if self.inkling.as_ref().is_some_and(|b| b.0.draft.is_some())
9412                        && crate::inkling::spec_k() > 0
9413                        && task_mask.is_none()
9414                        && router.is_none()
9415                        && !trace_on
9416                        && self.sampler_config.temperature < 1e-6
9417                        && self.sampler_config.repetition_penalty == 1.0
9418                        && generated + 2 < max_tokens
9419                    {
9420                        let room = max_tokens.saturating_sub(generated + 1);
9421                        let mut lg = Vec::new();
9422                        let (round, k) = match &mut self.inkling {
9423                            Some(b) => {
9424                                let k = b.3.spec.pick(next_pos, room);
9425                                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, self.pool.as_deref()) } else { None };
9426                                match &r {
9427                                    Some(extra) => b.3.spec.done(next_pos, k, extra.len()),
9428                                    None => b.3.spec.done(next_pos, 0, 0),
9429                                }
9430                                (r, k)
9431                            }
9432                            None => (None, 0),
9433                        };
9434                        if let Some(extra) = round {
9435                            drafted += k;
9436                            accepted += extra.len();
9437                            self.graph_logits = Some(lg);
9438                            next_pos += 1 + extra.len();
9439                            let mut stopped = false;
9440                            for &id in &extra {
9441                                if self.confidence_on {
9442                                    confidence.push(0.0);
9443                                }
9444                                if !commit!(id) {
9445                                    stopped = true;
9446                                    break;
9447                                }
9448                            }
9449                            if stopped {
9450                                break 'decode;
9451                            }
9452                            continue 'decode;
9453                        }
9454                    }
9455                    self.graph_want_logits = fuse_lm;
9456                    // Greedy burst (CMF_MULTISTEP, off unless explicitly set): while
9457                    // nothing observes per-token state — pure argmax sampling,
9458                    // no router/trace/confidence/mask — decode k tokens per
9459                    // submit and commit them wholesale. The trailing normal
9460                    // forward leaves logits for the loop top, as always.
9461                    let mut t_fwd = t_next;
9462                    let pure_greedy = self.sampler_config.temperature < 1e-6
9463                        && self.sampler_config.repetition_penalty == 1.0
9464                        && self.sampler_config.presence_penalty == 0.0
9465                        && self.sampler_config.suppress_tokens.is_empty();
9466                    // Off by default: at every k the burst measured at or
9467                    // below the plain path on this graph shape (k=1 loses
9468                    // the argmax dispatches vs a 1 MB readback, k>=8 loses
9469                    // inter-step drains vs the saved sync). Experimental.
9470                    let burst_k = std::env::var("CMF_MULTISTEP")
9471                        .ok()
9472                        .and_then(|v| v.parse::<usize>().ok())
9473                        .unwrap_or(0);
9474                    if pure_greedy
9475                        && burst_k >= 1
9476                        && fuse_lm
9477                        && task_mask.is_none()
9478                        && router.is_none()
9479                        && !trace_on
9480                        && !self.confidence_on
9481                        // Diagnostics and teacher forcing observe every
9482                        // individual logit row.  A device-only burst returns
9483                        // only ids, so decline it rather than silently
9484                        // skipping requested evidence or forced ids.
9485                        && std::env::var_os("CMF_FORCE_IDS").is_none()
9486                        && std::env::var_os("CMF_LOGIT_DUMP").is_none()
9487                        && std::env::var_os("CMF_LOGIT_DUMP_ALL").is_none()
9488                    {
9489                        let mut stopped = false;
9490                        loop {
9491                            // The outer loop checks cancellation too, but a
9492                            // long run can stay in this burst loop for many
9493                            // submits.  Bound cancellation latency to one
9494                            // exact k-token frame.
9495                            if self
9496                                .cancel
9497                                .swap(false, std::sync::atomic::Ordering::Relaxed)
9498                            {
9499                                finish_reason = "cancelled".to_string();
9500                                stopped = true;
9501                                break;
9502                            }
9503                            let room = max_tokens.saturating_sub(generated);
9504                            if room <= 2 {
9505                                break;
9506                            }
9507                            let k = burst_k.min(room - 1);
9508                            if k < 1 {
9509                                break;
9510                            }
9511                            let Some(ids) = self.try_multi_burst(t_fwd, next_pos, k) else {
9512                                if self
9513                                    .graph_failed
9514                                    .swap(false, std::sync::atomic::Ordering::Relaxed)
9515                                {
9516                                    self.finish_generation(&mut mtp, &mut router, true);
9517                                    return Err(
9518                                        "GPU token graph failed during greedy burst".to_string()
9519                                    );
9520                                }
9521                                break;
9522                            };
9523                            next_pos += k;
9524                            for &id in &ids {
9525                                if !commit!(id) {
9526                                    stopped = true;
9527                                    break;
9528                                }
9529                            }
9530                            if stopped {
9531                                break;
9532                            }
9533                            t_fwd = *ids.last().unwrap();
9534                        }
9535                        if stopped {
9536                            break 'decode;
9537                        }
9538                    }
9539                    // Metal: keep the draft head's cache in step through
9540                    // the trial's plain phase and a paused speculation —
9541                    // the pair (hidden, t_fwd) at next_pos−1, the step the
9542                    // round's draft 0 would take. Without it the head's
9543                    // cache lagged the trunk by every plain token for the
9544                    // rest of the generation: the batched warm-up declined
9545                    // every later round and its rows went one by one (a
9546                    // whole MTP step per accepted token), and the drafts
9547                    // attended a context with those tokens missing.
9548                    #[cfg(target_os = "macos")]
9549                    if graph_spec
9550                        && spec_watchdog_off
9551                        && next_pos > 0
9552                        && self.mtp_graph_mode == Some(true)
9553                        && crate::gpu::q1_force()
9554                    {
9555                        if let Some(m) = mtp.as_mut() {
9556                            let _ = self.mtp_step_metal(m, &hidden, t_fwd, next_pos - 1, false);
9557                        }
9558                    }
9559                    if let Some(d) = self.dash.as_mut() {
9560                        d.at_decode(t_fwd, next_pos);
9561                    }
9562                    hidden = self.forward_layers(&self.embed_single(t_fwd), next_pos, task_mask);
9563                    next_pos += 1;
9564                    // Dynamic routing: the forward updated φ; ask the
9565                    // router whether to switch skills before the next token.
9566                    if let Some(r) = &mut router {
9567                        let phi = self.dyn_phi_ema.clone();
9568                        let decision = r.step(&phi, generated);
9569                        if let Some(new_active) = decision {
9570                            if self.set_active_skill(new_active).is_ok() && next_pos <= all_ids.len() {
9571                                // The switch is a sequence boundary: every state
9572                                // the old weights made is gone. The context so far
9573                                // is read again under the new ones, so the next
9574                                // token conditions on all of it, not on an empty
9575                                // cache.
9576                                match self.reprefill_context(&all_ids[..next_pos], task_mask) {
9577                                    Ok(h) => hidden = h,
9578                                    Err(e) => tracing::warn!("dynamic routing: re-reading the context after a skill switch failed: {e}"),
9579                                }
9580                            }
9581                        }
9582                        // Backfill this token's coherence + switch flag from
9583                        // the just-run eval (freshest measured values).
9584                        if trace_on {
9585                            if let Some(last) = traces.last_mut() {
9586                                let e = r.last_best_e();
9587                                last.recon = e.is_finite().then_some(e);
9588                                last.switched = decision.is_some();
9589                            }
9590                        }
9591                    }
9592                }
9593            }
9594        }
9595
9596        let cancelled = finish_reason == "cancelled";
9597        // A generation during which the router switched weights holds no
9598        // state any single overlay would produce (each switch cleared the
9599        // cache mid-sequence), so it leaves no reuse key behind either.
9600        let dyn_switched = router.as_ref().is_some_and(|r| !r.switches.is_empty());
9601        if mimo_spec {
9602            if let Some(st) = self.mimo_mtp.as_ref() {
9603                let line = st.stats.line();
9604                tracing::info!("{line}");
9605                if std::env::var_os("CMF_MIMO_MTP_STATS").is_some() {
9606                    eprintln!("{line}");
9607                }
9608            }
9609        }
9610        self.finish_generation(&mut mtp, &mut router, cancelled);
9611
9612        if self.dflash_solo && spec_time_level() > 0 {
9613            if let Some(line) = crate::dflash::stage_report() {
9614                eprintln!("solo-draft: {line}");
9615            }
9616        }
9617        // `CMF_GEN_IDS_OUT=FILE`: the sequence as ids, prompt first (what
9618        // `CMF_SPEC_SCRIPT` reads back).
9619        if let Ok(path) = std::env::var("CMF_GEN_IDS_OUT") {
9620            let text = all_ids.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(" ");
9621            if let Err(e) = std::fs::write(&path, text) {
9622                tracing::warn!("CMF_GEN_IDS_OUT: {path}: {e}");
9623            }
9624        }
9625        let output_ids = &all_ids[input_ids.len()..];
9626        // Forwarded = prompt + all generated but the LAST sampled token
9627        // (emitted without being fed back). Exact only without MTP —
9628        // reuse is gated off when MTP is active.
9629        let forwarded = input_ids.len() + output_ids.len().saturating_sub(1);
9630        // A MiMo speculative round that stopped on an accepted draft (EOS,
9631        // cancel) leaves verify rows past the committed stream in the cache:
9632        // never offer that cache for reuse. Neither does a router that
9633        // switched weights mid-sequence (no single overlay produced it).
9634        let consumed = std::mem::take(&mut all_ids);
9635        if dyn_switched {
9636            self.clear_sequence_state();
9637        } else if cancelled || mimo_spec || prompt_rows.is_some() {
9638            self.clear_history();
9639        } else {
9640            self.record_consumed_prefix(&consumed[..forwarded.min(consumed.len())], reuse_from);
9641        }
9642        all_ids = consumed;
9643        let output_ids = &all_ids[input_ids.len()..];
9644        confidence.truncate(output_ids.len()); // guard against any overshoot
9645        traces.truncate(output_ids.len());
9646        // The loop monitor stopped the answer: it says the repeated block once.
9647        let output_ids = match finish_reason.as_str() {
9648            "loop" => {
9649                let excess = crate::sampler::tail_repeat_excess(output_ids).unwrap_or(0);
9650                &output_ids[..output_ids.len() - excess]
9651            }
9652            _ => output_ids,
9653        };
9654        Ok(GenerateResult {
9655            text: self.tokenizer.decode(output_ids),
9656            token_ids: output_ids.to_vec(),
9657            prompt_tokens: input_ids.len(),
9658            tokens_generated: generated,
9659            finish_reason,
9660            mtp_drafted: drafted,
9661            mtp_accepted: accepted,
9662            token_confidence: confidence,
9663            traces,
9664        })
9665    }
9666
9667    /// One MTP step: feed `(hidden_p, token_{p+1})` into the draft head,
9668    /// advance its KV cache at position `p`, return the drafted token
9669    /// for position `p+2`.
9670    fn mtp_step(
9671        &mut self,
9672        m: &mut MtpModule,
9673        hidden: &[f32],
9674        next_token: u32,
9675        position: usize,
9676    ) -> u32 {
9677        self.mtp_step_h(m, hidden, next_token, position).0
9678    }
9679
9680    /// Tally for `CMF_MTP_CHAIN_PROBE`: per depth, how often the CHAIN is
9681    /// still an exact prefix of the real continuation. Printed every 128
9682    /// depth-0 samples so a killed run still shows its table.
9683    fn chain_probe_note(depth: usize, prefix_ok: bool) {
9684        use std::sync::Mutex;
9685        static T: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
9686        let mut t = T.lock().unwrap();
9687        if t.len() <= depth {
9688            t.resize(depth + 1, (0, 0));
9689        }
9690        t[depth].0 += 1;
9691        t[depth].1 += prefix_ok as u64;
9692        if depth == 0 && t[0].0 % 128 == 0 {
9693            let line: Vec<String> = t
9694                .iter()
9695                .enumerate()
9696                .map(|(d, (n, k))| {
9697                    format!(
9698                        "d{}={:.0}%({n})",
9699                        d + 1,
9700                        100.0 * *k as f64 / (*n).max(1) as f64
9701                    )
9702                })
9703                .collect();
9704            eprintln!("mtp-chain: {}", line.join(" "));
9705        }
9706    }
9707
9708    /// `mtp_step` that also hands back the block's own output hidden — the
9709    /// state a CHAINED draft feeds the next step, the way a multi-token
9710    /// speculative round iterates the head on itself.
9711    /// One MTP block step from (trunk hidden, token): the head's LOGITS
9712    /// and the block's own hidden for chaining. The draft is argmax of the
9713    /// logits on the greedy path and a draw from their post-chain
9714    /// distribution on the sampling path.
9715    fn mtp_step_hl(
9716        &mut self,
9717        m: &mut MtpModule,
9718        hidden: &[f32],
9719        next_token: u32,
9720        position: usize,
9721    ) -> (Vec<f32>, Vec<f32>) {
9722        let position = position.saturating_sub(self.mtp_pos_base);
9723        // The graph arm: the MTP block as a one-layer token graph with the
9724        // head fused — device attention over the block's own KV mirror,
9725        // one submit for block + head, hidden and logits back together.
9726        // Decided once per generation (see `mtp_graph_mode`).
9727        #[cfg(target_os = "macos")]
9728        if self.mtp_graph_mode != Some(false) && crate::gpu::q1_force() {
9729            if let Some(r) = self.mtp_step_metal(m, hidden, next_token, position, true) {
9730                self.mtp_graph_mode = Some(true);
9731                return r;
9732            }
9733            if self.mtp_graph_mode == Some(true) {
9734                tracing::error!("mtp Metal graph failed after admission");
9735                self.clear_sequence_state();
9736                self.graph_failed
9737                    .store(true, std::sync::atomic::Ordering::Relaxed);
9738                self.cancel
9739                    .store(true, std::sync::atomic::Ordering::Relaxed);
9740                return (Vec::new(), Vec::new());
9741            }
9742            self.mtp_graph_mode = Some(false);
9743        }
9744        #[cfg(feature = "gpu")]
9745        if self.mtp_graph_mode != Some(false) {
9746            if !self.mtp_graph_ok(m) {
9747                if self.mtp_graph_mode == Some(true) {
9748                    // A mirror was already admitted, so a capability change
9749                    // cannot safely switch this request to the stale CPU
9750                    // cache.  Keep the same terminal contract as a failed
9751                    // token graph.
9752                    tracing::error!("mtp graph became unavailable after admission");
9753                    self.clear_sequence_state();
9754                    self.graph_failed
9755                        .store(true, std::sync::atomic::Ordering::Relaxed);
9756                    self.cancel
9757                        .store(true, std::sync::atomic::Ordering::Relaxed);
9758                    return (Vec::new(), Vec::new());
9759                }
9760                self.mtp_graph_mode = Some(false);
9761            } else {
9762                if let Some(r) = self.mtp_step_graph(m, hidden, next_token, position) {
9763                    self.mtp_graph_mode = Some(true);
9764                    return r;
9765                }
9766                if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
9767                    // A token graph can have admitted a persistent MTP/GDN
9768                    // mirror before its readback failed.  The CPU MTP cache
9769                    // is not a valid continuation in that state; leave the
9770                    // flag set so the generation caller returns through its
9771                    // terminal error path instead of silently switching
9772                    // arithmetic.
9773                    return (Vec::new(), Vec::new());
9774                }
9775                // `mtp_graph_ok` was true, so a None here means a refusal or
9776                // failure after graph admission.  Do not fall through to a
9777                // CPU cache whose rows may lag the device mirror.
9778                tracing::error!("mtp graph failed or declined after admission");
9779                self.clear_sequence_state();
9780                self.graph_failed
9781                    .store(true, std::sync::atomic::Ordering::Relaxed);
9782                self.cancel
9783                    .store(true, std::sync::atomic::Ordering::Relaxed);
9784                return (Vec::new(), Vec::new());
9785            }
9786        }
9787        // fc concat order is [enorm(embed); hnorm(hidden)] — EMBEDDING
9788        // FIRST. Verified by the oracle (converter/mtp_oracle.py):
9789        // [emb;hid] → 45.8% acceptance, [hid;emb] → 0.00%.
9790        let e = self.embed_single(next_token);
9791        let mut cat = vec![0.0f32; 2 * self.hidden_size];
9792        let (cat_e, cat_h) = cat.split_at_mut(self.hidden_size);
9793        inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
9794        inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
9795        let mut x = vec![0.0f32; self.hidden_size];
9796        m.eh_proj.matvec(&cat, &mut x, self.pool.as_deref());
9797
9798        // One standard transformer block over the MTP's own cache.
9799        let lw = &m.layer;
9800        inference::rms_norm_into(
9801            &x,
9802            &lw.input_norm,
9803            self.rms_eps,
9804            self.norm_style,
9805            &mut self.ws.n1,
9806        );
9807        let attn = match &lw.attn {
9808            // MLA models carry no MTP head; this path cannot see them.
9809            AttnKind::Mla(_) => unreachable!("MLA has no MTP/pair path"),
9810            AttnKind::Kda(_) => unreachable!("KDA has no MTP/pair path"),
9811            AttnKind::Full {
9812                wq,
9813                wk,
9814                wv,
9815                wo,
9816                q_norm,
9817                k_norm,
9818                output_gate,
9819                softplus_gate,
9820                bias,
9821            } => {
9822                let mut cfg = self.attn_cfg(position);
9823                cfg.q_norm = q_norm.as_deref();
9824                cfg.k_norm = k_norm.as_deref();
9825                cfg.output_gate = *output_gate;
9826                cfg.softplus_gate = softplus_gate
9827                    .as_ref()
9828                    .map(|(gate, per_head)| (gate, *per_head));
9829                cfg.bias = bias
9830                    .as_ref()
9831                    .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice()));
9832                attention::qwen_attention(&self.ws.n1, wq, wk, wv, wo, &mut m.kv, &cfg)
9833            }
9834            AttnKind::Linear(_)
9835            | AttnKind::LinearGdn(_)
9836            | AttnKind::ShortConv(_)
9837            | AttnKind::Bounded(_) => {
9838                unreachable!("MTP block is full attention")
9839            }
9840        };
9841        for (i, &a) in attn.iter().enumerate() {
9842            x[i] += a;
9843        }
9844        inference::rms_norm_into(
9845            &x,
9846            &lw.post_norm,
9847            self.rms_eps,
9848            self.norm_style,
9849            &mut self.ws.p1,
9850        );
9851        let ffn = ffn_forward(&lw.ffn, &self.ws.p1, self.pool.as_deref(), None);
9852        for (i, &f) in ffn.iter().enumerate() {
9853            x[i] += f;
9854        }
9855
9856        inference::rms_norm_into(
9857            &x,
9858            &m.final_norm,
9859            self.rms_eps,
9860            self.norm_style,
9861            &mut self.ws.n1,
9862        );
9863        let lg = self.lm_head_forward(&self.ws.n1);
9864        (lg, x)
9865    }
9866
9867    /// `mtp_step_hl` reduced to the greedy draft: argmax of the head.
9868    fn mtp_step_h(
9869        &mut self,
9870        m: &mut MtpModule,
9871        hidden: &[f32],
9872        next_token: u32,
9873        position: usize,
9874    ) -> (u32, Vec<f32>) {
9875        let (mut lg, x) = self.mtp_step_hl(m, hidden, next_token, position);
9876        let draft = sampler::argmax(&lg);
9877        attention::recycle_buf(&mut lg);
9878        (draft, x)
9879    }
9880
9881    /// One speculative round for the trial: rounds 1..5 of a `Spec` phase
9882    /// advance it (the monitor already averaged this round); after five,
9883    /// the plain phase runs (once — a known plain rate decides at once);
9884    /// a decided speculation keeps re-checking the rule every round and
9885    /// stops after four losing rounds in a row.
9886    fn spec_trial_round(trial: SpecTrial, mon: &mut SpecMon, generated: usize) -> SpecTrial {
9887        // CMF_GRAPH_SPEC_PIN=1 keeps the rounds on whatever they cost: a
9888        // count of how a draft head holds has to include the stretches a
9889        // trial would decode plain.
9890        static PIN: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
9891        if *PIN.get_or_init(|| std::env::var("CMF_GRAPH_SPEC_PIN").as_deref() == Ok("1")) {
9892            return SpecTrial::Decided {
9893                spec: true,
9894                recheck_at: usize::MAX,
9895            };
9896        }
9897        match trial {
9898            SpecTrial::Spec { t0, gen0, rounds } => {
9899                let rounds = rounds + 1;
9900                // A round that accepts no draft still has to run the MTP
9901                // chain and a K+1 verifier, but emits only its verifier tip.
9902                // After `SPEC_ZERO_ROUNDS` such real rounds the speculative
9903                // arm cannot win on any backend; time plain immediately
9904                // rather than spend the remaining exploratory rounds on the
9905                // same one-token result. A re-check soon after (the evidence
9906                // is a few rounds) gives the text a chance to re-admit it.
9907                if mon.repeated_zero_acceptance() {
9908                    tracing::info!(
9909                        "speculation trial: no accepted drafts in two rounds — timing plain"
9910                    );
9911                    return SpecTrial::Plain {
9912                        t0: std::time::Instant::now(),
9913                        gen0: generated,
9914                    };
9915                }
9916                if rounds >= 5 {
9917                    if mon.plain_ms > 0.0 {
9918                        let keep = mon.pays();
9919                        mon.fails = 0;
9920                        tracing::info!(
9921                            "speculation re-check: {:.2} tok/round in {:.1} ms vs plain {:.1} ms/tok — {}",
9922                            mon.tokens,
9923                            mon.round_ms,
9924                            mon.plain_ms,
9925                            if keep { "speculating" } else { "plain" }
9926                        );
9927                        SpecTrial::Decided {
9928                            spec: keep,
9929                            recheck_at: if keep { usize::MAX } else { mon.recheck_plain_at(generated) },
9930                        }
9931                    } else if mon.pays() {
9932                        // Metal: the rounds land enough tokens each that no
9933                        // plain measurement is needed — keep speculating,
9934                        // and re-check every round (a losing streak sends
9935                        // the loop to the plain phase, below).
9936                        mon.fails = 0;
9937                        tracing::info!(
9938                            "speculation trial: {:.2} tok/round in {:.1} ms — speculating (plain not timed)",
9939                            mon.tokens,
9940                            mon.round_ms,
9941                        );
9942                        SpecTrial::Decided {
9943                            spec: true,
9944                            recheck_at: usize::MAX,
9945                        }
9946                    } else {
9947                        SpecTrial::Plain {
9948                            t0: std::time::Instant::now(),
9949                            gen0: generated,
9950                        }
9951                    }
9952                } else {
9953                    SpecTrial::Spec { t0, gen0, rounds }
9954                }
9955            }
9956            SpecTrial::Decided { spec: true, .. } => {
9957                if mon.pays() {
9958                    mon.fails = 0;
9959                    trial
9960                } else {
9961                    mon.fails += 1;
9962                    if mon.fails >= 4 {
9963                        if mon.plain_ms <= 0.0 {
9964                            // Metal, plain never timed: four doubtful rounds
9965                            // buy the (bounded) plain measurement, and the
9966                            // exact rule decides from it.
9967                            tracing::info!(
9968                                "speculation doubtful: {:.2} tok/round in {:.1} ms — timing plain",
9969                                mon.tokens,
9970                                mon.round_ms,
9971                            );
9972                            return SpecTrial::Plain {
9973                                t0: std::time::Instant::now(),
9974                                gen0: generated,
9975                            };
9976                        }
9977                        tracing::info!(
9978                            "speculation stopped: {:.2} tok/round in {:.1} ms vs plain {:.1} ms/tok",
9979                            mon.tokens,
9980                            mon.round_ms,
9981                            mon.plain_ms
9982                        );
9983                        SpecTrial::Decided {
9984                            spec: false,
9985                            recheck_at: generated + SPEC_RECHECK_PLAIN,
9986                        }
9987                    } else {
9988                        trial
9989                    }
9990                }
9991            }
9992            other => other,
9993        }
9994    }
9995
9996    /// The MTP block's device-mirror id: the trunk's id with a high bit,
9997    /// so the (kv_id, layer) mirror keys never collide.
9998    fn mtp_kv_id(&self) -> u64 {
9999        self.graph_kv_id | (1u64 << 40)
10000    }
10001
10002    /// The MTP block's mirror layer index: 0 — its own kv_id keeps it
10003    /// apart from the trunk, and the BATCH graph (the warm-up path) keys
10004    /// its mirrors at layer 0 with no base of its own, so the draft's
10005    /// token graph must key the same slot.
10006    const MTP_LAYER_BASE: usize = 0;
10007
10008    /// The wgpu MTP draft writes speculative rows straight into its device
10009    /// mirror while the CPU owner retains only the real prompt/decode anchor.
10010    /// After verification, move that mirror cursor back to the anchor before
10011    /// replaying accepted pairs.  The next graph append then sees the same
10012    /// contiguous position as the CPU/Metal path without uploading stale
10013    /// speculative rows.
10014    #[cfg(feature = "gpu")]
10015    fn rewind_mtp_graph_mirror(&self, stored: usize) -> bool {
10016        let stored = stored.saturating_sub(self.mtp_pos_base);
10017        self.mtp_graph_mode != Some(true)
10018            || crate::gpu::graph_kv_set_stored(self.mtp_kv_id(), Self::MTP_LAYER_BASE, stored)
10019    }
10020
10021    /// A speculative verify graph appends the full `k+1` trunk rows before
10022    /// the acceptance count is known.  GDN state already has a snapshot
10023    /// restore; Full-attention mirrors need the matching logical cursor
10024    /// rewind so the next graph call does not reject an ahead-of-position KV
10025    /// cache after a partial acceptance.
10026    #[cfg(feature = "gpu")]
10027    fn rewind_trunk_graph_mirrors(&self, stored: usize) -> bool {
10028        let mut ok = true;
10029        let mut expected = false;
10030        for li in 0..self.num_layers {
10031            if matches!(
10032                self.weights.layers[self.phys_layer(li)].attn,
10033                AttnKind::Full { .. }
10034            ) {
10035                // A sealed layer has no mirror: its state moved by `o1_spec_commit`.
10036                if self.o1_flags.get(li).copied().unwrap_or(false) && self.kv_cache.layers[li].o1_sealed() {
10037                    continue;
10038                }
10039                expected = true;
10040                ok &= crate::gpu::graph_kv_set_stored(self.graph_kv_id, li, stored);
10041            }
10042        }
10043        !expected || ok
10044    }
10045
10046    /// Count the recurrent layers participating in the trunk verify graph.
10047    /// Snapshot restore is all-or-nothing across that set; deriving the count
10048    /// from the model keeps the restore contract valid for looped models too.
10049    fn graph_gdn_layer_count(&self) -> usize {
10050        // stacks that keep their own layers (qwen4, DSV4) leave the generic
10051        // ones empty: no generic GDN layer, nothing to index
10052        (0..self.num_layers)
10053            .filter(|&li| {
10054                self.weights
10055                    .layers
10056                    .get(self.phys_layer(li))
10057                    .is_some_and(|l| matches!(&l.attn, AttnKind::LinearGdn(_)))
10058            })
10059            .count()
10060    }
10061
10062    /// The block's input from (trunk hidden, token): eh_proj · [enorm(e);
10063    /// hnorm(h)] — the same arithmetic the per-op path starts with.
10064    fn mtp_block_input(&mut self, m: &MtpModule, hidden: &[f32], next_token: u32) -> Vec<f32> {
10065        self.mtp_block_inputs(m, &[(hidden, next_token)])
10066    }
10067
10068    /// The block inputs of several (trunk hidden, token) pairs, `[n][hidden]`.
10069    /// On the CUDA hybrid arm eh_proj runs on the card for all of them at
10070    /// once (about 1 ms a pair on the host for Qwen3.8-27B's 27 MB matrix,
10071    /// tens of microseconds there); everywhere else one host matvec a pair.
10072    fn mtp_block_inputs(&mut self, m: &MtpModule, pairs: &[(&[f32], u32)]) -> Vec<f32> {
10073        let hs = self.hidden_size;
10074        let mut cats = vec![0.0f32; pairs.len() * 2 * hs];
10075        for (i, (hidden, tok)) in pairs.iter().enumerate() {
10076            let e = self.embed_single(*tok);
10077            let cat = &mut cats[i * 2 * hs..(i + 1) * 2 * hs];
10078            let (cat_e, cat_h) = cat.split_at_mut(hs);
10079            inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
10080            inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
10081        }
10082        let mut xs = vec![0.0f32; pairs.len() * hs];
10083        #[cfg(feature = "gpu")]
10084        if crate::gpu::cuda_active() {
10085            if let Some((model, idx, kind, rs)) = m.eh_proj.graph_weight() {
10086                let gw = crate::gpu::GraphW {
10087                    idx,
10088                    kind,
10089                    row_scale: rs,
10090                    data: &[],
10091                    prism: crate::gpu::GraphPrismOp::None,
10092                    affine: false,
10093                };
10094                let model = model.clone();
10095                if crate::gpu::rows_matvec(&model, &gw, hs, 2 * hs, &cats, pairs.len(), &mut xs) {
10096                    return xs;
10097                }
10098            }
10099        }
10100        if pairs.len() > 1 && std::env::var("CMF_MTP_EH_BATCH").as_deref() != Ok("0") {
10101            m.eh_proj.matmat(&cats, pairs.len(), &mut xs, self.pool.as_deref());
10102            return xs;
10103        }
10104        for i in 0..pairs.len() {
10105            m.eh_proj.matvec(&cats[i * 2 * hs..(i + 1) * 2 * hs], &mut xs[i * hs..(i + 1) * hs], self.pool.as_deref());
10106        }
10107        xs
10108    }
10109
10110    /// Is the MTP block graphable at all (device up, full attention
10111    /// without softplus, dense FFN)? The plan itself is built per call.
10112    #[cfg(feature = "gpu")]
10113    fn mtp_block_graph_ok(&self, m: &MtpModule) -> bool {
10114        if std::env::var("CMF_MTP_GRAPH").as_deref() == Ok("0") {
10115            return false;
10116        }
10117        if !crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode) || !crate::gpu::enabled_here() {
10118            return false;
10119        }
10120        self.mtp_block_shape_ok(m)
10121    }
10122
10123    /// The shape a device MTP step takes (the wgpu token graph and native
10124    /// Metal's `mtp_step_metal` alike): one dense block of full attention
10125    /// without a softplus gate, V as wide as K, no softcap. A MoE draft block
10126    /// drafts op by op on the host and costs more than it saves.
10127    fn mtp_block_shape_ok(&self, m: &MtpModule) -> bool {
10128        if std::env::var("CMF_MTP_GRAPH").as_deref() == Ok("0")
10129            || self.attn_softcap > 0.0
10130            || self.attention_heads_per_layer.is_some()
10131            // The block graph caches V as wide as K and feeds o_proj
10132            // nh·head_dim; a narrow-V model keeps its MTP block per-op.
10133            || self.v_head_dim.is_some()
10134        {
10135            return false;
10136        }
10137        matches!(
10138            &m.layer.attn,
10139            AttnKind::Full {
10140                softplus_gate: None,
10141                ..
10142            }
10143        ) && matches!(&m.layer.ffn, FfnKind::Dense(_))
10144    }
10145
10146    /// Full MTP token-graph eligibility, including the fused lm-head and all
10147    /// block projection weights.  Keep this distinct from the block-only
10148    /// check: prompt warm-up does not need the head, while a draft step does.
10149    #[cfg(feature = "gpu")]
10150    fn mtp_graph_ok(&self, m: &MtpModule) -> bool {
10151        if !self.mtp_block_graph_ok(m) {
10152            return false;
10153        }
10154        let AttnKind::Full { wq, wk, wv, wo, .. } = &m.layer.attn else {
10155            return false;
10156        };
10157        let FfnKind::Dense(d) = &m.layer.ffn else {
10158            return false;
10159        };
10160        d.segs.is_empty()
10161            && wq.graph_weight().is_some()
10162            && wk.graph_weight().is_some()
10163            && wv.graph_weight().is_some()
10164            && wo.graph_weight().is_some()
10165            && d.gate_proj.graph_weight().is_some()
10166            && d.up_proj.graph_weight().is_some()
10167            && d.down_proj.graph_weight().is_some()
10168            && self.weights.lm_head.graph_weight().is_some()
10169    }
10170
10171    /// One MTP block step on the wgpu token graph: block + fused head in
10172    /// one submit, the block hidden and the logits read back together.
10173    /// None = the graph cannot take this block (softplus gate, non-dense
10174    /// FFN, unquantized head, no device) — the caller keeps the per-op
10175    /// path for the whole generation.
10176    #[cfg(feature = "gpu")]
10177    fn mtp_step_graph(
10178        &mut self,
10179        m: &mut MtpModule,
10180        hidden: &[f32],
10181        next_token: u32,
10182        position: usize,
10183    ) -> Option<(Vec<f32>, Vec<f32>)> {
10184        if !self.mtp_graph_ok(m) {
10185            return None;
10186        }
10187        let lw = &m.layer;
10188        let AttnKind::Full {
10189            wq,
10190            wk,
10191            wv,
10192            wo,
10193            q_norm,
10194            k_norm,
10195            output_gate,
10196            softplus_gate,
10197            bias,
10198        } = &lw.attn
10199        else {
10200            return None;
10201        };
10202        if softplus_gate.is_some() {
10203            return None;
10204        }
10205        let FfnKind::Dense(d) = &lw.ffn else {
10206            return None;
10207        };
10208        if !d.segs.is_empty() {
10209            return None; // tube layers run on the segmented path
10210        }
10211        // The block's input first: it borrows `self` mutably (embed scratch,
10212        // pool), the plan below borrows the weights immutably.
10213        let mut x = self.mtp_block_input(m, hidden, next_token);
10214        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
10215            let (_, i, kind, rs) = t.graph_weight()?;
10216            Some(crate::gpu::GraphW {
10217                idx: i,
10218                kind,
10219                row_scale: rs,
10220                data: &[],
10221                prism: crate::gpu::GraphPrismOp::None,
10222                affine: false,
10223            })
10224        }
10225        let (model, _, _, _) = wq.graph_weight()?;
10226        let model = model.clone();
10227        let (lm_gw, lm_rows) = {
10228            let (_, i, kind, rs) = self.weights.lm_head.graph_weight()?;
10229            // The draft's head over the CMF_DRAFT_VOCAB shortlist (the same
10230            // cut the native Metal draft takes): 662 MB a step on Qwen3.8
10231            // becomes 170 MB at 65536; the verify keeps the full head.
10232            let rows = if kind == 6 {
10233                self.draft_head_rows(self.weights.lm_head.rows())
10234            } else {
10235                self.weights.lm_head.rows()
10236            };
10237            (
10238                crate::gpu::GraphW {
10239                    idx: i,
10240                    kind,
10241                    row_scale: rs,
10242                    data: &[],
10243                    prism: crate::gpu::GraphPrismOp::None,
10244                    affine: false,
10245                },
10246                rows,
10247            )
10248        };
10249        let layer = crate::gpu::GraphLayer {
10250            engram: None,
10251            mhc: None,
10252            input_norm: &lw.input_norm,
10253            attn: crate::gpu::GraphAttn::Full {
10254                wq: gw(wq)?,
10255                wk: gw(wk)?,
10256                wv: gw(wv)?,
10257                wo: gw(wo)?,
10258                q_norm: q_norm.as_deref(),
10259                k_norm: k_norm.as_deref(),
10260                late_qk_norm: self.qk_norm_after_rope,
10261                bias: bias
10262                    .as_ref()
10263                    .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
10264                output_gate: *output_gate,
10265                cpu_k: m.kv.k_heads(),
10266                cpu_v: m.kv.v_heads(),
10267                cpu_base: m.kv.base(),
10268                geom: None,
10269                head_gate: None,
10270            },
10271            post_norm: &lw.post_norm,
10272            attn_out_norm: None,
10273            ffn_out_norm: None,
10274            layer_scale: None,
10275            ffn: crate::gpu::GraphFfn::Dense {
10276                gate: gw(&d.gate_proj)?,
10277                up: gw(&d.up_proj)?,
10278                down: gw(&d.down_proj)?,
10279                act: d.act.graph_act()?,
10280                limit: 0.0,
10281                hot: None,
10282            },
10283        };
10284        let nh = self.num_heads;
10285        let (nkv, hd, rd) = self.layer_geom(0);
10286        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
10287        let mut logits = Vec::new();
10288        let ok = crate::gpu::forward_token_graph(
10289            &model,
10290            self.mtp_kv_id(),
10291            std::slice::from_ref(&layer),
10292            &[None],
10293            self.o1_epoch,
10294            &self.inv_freq,
10295            &mut x,
10296            nh,
10297            nkv,
10298            hd,
10299            self.attn_scale,
10300            rd,
10301            self.hidden_size,
10302            // An MTP draft can have an independently compacted FFN. The
10303            // graph must use the checked local tensor width, not the trunk
10304            // arch-wide intermediate size.
10305            d.gate_proj.rows(),
10306            position,
10307            self.kv_cache.max_seq_len,
10308            gemma,
10309            self.rms_eps as f32,
10310            Some((&lm_gw, lm_rows)),
10311            &m.final_norm,
10312            &mut logits,
10313            &[],
10314            1,
10315            None,
10316            None,
10317            None,
10318            Self::MTP_LAYER_BASE,
10319            true,
10320        );
10321        match ok {
10322            crate::gpu::TokenGraphOutcome::Completed => {}
10323            crate::gpu::TokenGraphOutcome::Declined => return None,
10324            crate::gpu::TokenGraphOutcome::Failed => {
10325                // The backend has already admitted persistent state.  Keep
10326                // this distinct from a capability refusal so the caller
10327                // cannot switch to the stale CPU MTP cache.
10328                self.clear_sequence_state();
10329                self.graph_failed
10330                    .store(true, std::sync::atomic::Ordering::Relaxed);
10331                self.cancel
10332                    .store(true, std::sync::atomic::Ordering::Relaxed);
10333                return None;
10334            }
10335        }
10336        // The graph may deliberately evaluate only a prefix of the draft
10337        // head.  Do not turn every omitted token into a zero-logit candidate:
10338        // that can win an all-negative shortlist and collapses acceptance.
10339        pad_mtp_draft_logits(&mut logits, self.vocab_size);
10340        Some((logits, x))
10341    }
10342
10343    /// The round's `k` greedy drafts on the CUDA hybrid arm as ONE graph
10344    /// (`gpu_cuda::mtp_chain`): the block input, the block and the shortlist
10345    /// head k times, each step's token embedding gathered on the card from
10346    /// the argmax before it. Err(false): declined before any state changed
10347    /// (the per-step loop takes the round); Err(true): failed after the
10348    /// block's mirror moved.
10349    #[cfg(feature = "cuda")]
10350    fn mtp_draft_chain_cuda(&self, m: &MtpModule, hidden: &[f32], t_next: u32, position: usize, k: usize) -> Result<Vec<u32>, bool> {
10351        let position = position.saturating_sub(self.mtp_pos_base);
10352        if !crate::gpu::cuda_active()
10353            || !Self::mtp_chain_on()
10354            || std::env::var("CMF_MTP_GRAPH").as_deref() == Ok("0")
10355            || self.draft_full_streak > 0
10356            || !self.mtp_graph_ok(m)
10357            || hidden.len() != self.hidden_size
10358        {
10359            return Err(false);
10360        }
10361        let lw = &m.layer;
10362        let AttnKind::Full { wq, wk, wv, wo, q_norm, k_norm, output_gate, softplus_gate: None, bias } = &lw.attn else {
10363            return Err(false);
10364        };
10365        let FfnKind::Dense(d) = &lw.ffn else {
10366            return Err(false);
10367        };
10368        if !d.segs.is_empty() {
10369            return Err(false);
10370        }
10371        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
10372            let (_, i, kind, rs) = t.graph_weight()?;
10373            Some(crate::gpu::GraphW { idx: i, kind, row_scale: rs, data: &[], prism: crate::gpu::GraphPrismOp::None, affine: false })
10374        }
10375        let mk = || -> Option<_> {
10376            let (model, _, _, _) = wq.graph_weight()?;
10377            let (_, li, lkind, lrs) = self.weights.lm_head.graph_weight()?;
10378            if lkind != 6 {
10379                return None;
10380            }
10381            let rows = Self::draft_vocab_rows(self.weights.lm_head.rows());
10382            let lm = crate::gpu::GraphW { idx: li, kind: lkind, row_scale: lrs, data: &[], prism: crate::gpu::GraphPrismOp::None, affine: false };
10383            let eh = gw(&m.eh_proj)?;
10384            let layer = crate::gpu::GraphLayer {
10385                engram: None,
10386                mhc: None,
10387                input_norm: &lw.input_norm,
10388                attn: crate::gpu::GraphAttn::Full {
10389                    wq: gw(wq)?,
10390                    wk: gw(wk)?,
10391                    wv: gw(wv)?,
10392                    wo: gw(wo)?,
10393                    q_norm: q_norm.as_deref(),
10394                    k_norm: k_norm.as_deref(),
10395                    late_qk_norm: self.qk_norm_after_rope,
10396                    bias: bias.as_ref().map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
10397                    output_gate: *output_gate,
10398                    cpu_k: m.kv.k_heads(),
10399                    cpu_v: m.kv.v_heads(),
10400                    cpu_base: m.kv.base(),
10401                    geom: None,
10402                    head_gate: None,
10403                },
10404                post_norm: &lw.post_norm,
10405                attn_out_norm: None,
10406                ffn_out_norm: None,
10407                layer_scale: None,
10408                ffn: crate::gpu::GraphFfn::Dense {
10409                    gate: gw(&d.gate_proj)?,
10410                    up: gw(&d.up_proj)?,
10411                    down: gw(&d.down_proj)?,
10412                    act: d.act.graph_act()?,
10413                    limit: 0.0,
10414                    hot: None,
10415                },
10416            };
10417            // the embedding: q4tp in the same file (the chain gathers its rows)
10418            let (emodel, ei, ekind, ers) = self.weights.embed_tokens.graph_weight()?;
10419            if ekind != 6 || !std::sync::Arc::ptr_eq(emodel, model) || crate::prism::is_inverse_embedding(model, &model.tensors[ei].name) {
10420                return None;
10421            }
10422            let emb = crate::gpu::GraphW { idx: ei, kind: ekind, row_scale: ers, data: &[], prism: crate::gpu::GraphPrismOp::None, affine: false };
10423            Some((model.clone(), lm, rows, eh, layer, emb))
10424        };
10425        let Some((model, lm, rows, eh, layer, emb)) = mk() else {
10426            return Err(false);
10427        };
10428        let (nkv, hd, rd) = self.layer_geom(0);
10429        let e0 = self.embed_single(t_next);
10430        crate::gpu_cuda::mtp_chain(
10431            &model,
10432            self.mtp_kv_id(),
10433            &layer,
10434            &self.inv_freq,
10435            hidden,
10436            &e0,
10437            t_next,
10438            k,
10439            self.num_heads,
10440            nkv,
10441            hd,
10442            self.attn_scale,
10443            rd,
10444            self.hidden_size,
10445            position,
10446            self.kv_cache.max_seq_len,
10447            self.norm_style == cortiq_core::NormStyle::Gemma,
10448            self.rms_eps as f32,
10449            (&lm, rows),
10450            &m.final_norm,
10451            &eh,
10452            &m.enorm,
10453            &m.hnorm,
10454            &emb,
10455            Self::MTP_LAYER_BASE,
10456        )
10457    }
10458
10459    /// The warm-ups of one speculative round on the device: every accepted
10460    /// (hidden, token) pair as ONE batched graph run over the MTP block
10461    /// (no head) — its kv_append lands the pairs in the block's mirror.
10462    /// `pairs` are consecutive positions from `first_pos`.  The tri-state
10463    /// result is intentional: a refusal before admission may use the
10464    /// per-row/CPU route, while a failure after admission must terminate the
10465    /// sequence rather than fall through to a stale CPU cache.
10466    #[cfg(feature = "gpu")]
10467    fn mtp_warm_graph(
10468        &mut self,
10469        m: &mut MtpModule,
10470        pairs: &[(&[f32], u32)],
10471        first_pos: usize,
10472    ) -> crate::gpu::BatchGraphOutcome {
10473        let first_pos = first_pos.saturating_sub(self.mtp_pos_base);
10474        if pairs.is_empty() {
10475            return crate::gpu::BatchGraphOutcome::Completed;
10476        }
10477        if !self.mtp_block_graph_ok(m) {
10478            return crate::gpu::BatchGraphOutcome::Declined;
10479        }
10480        let hs = self.hidden_size;
10481        // Block inputs for every pair (eh_proj on the per-op path, one
10482        // matvec each — the plan's own prologue).
10483        let mut hiddens = self.mtp_block_inputs(m, pairs);
10484        debug_assert_eq!(hiddens.len(), pairs.len() * hs);
10485        spec_stamp("w.inp");
10486        let lw = &m.layer;
10487        let AttnKind::Full {
10488            wq,
10489            wk,
10490            wv,
10491            wo,
10492            q_norm,
10493            k_norm,
10494            output_gate,
10495            bias,
10496            ..
10497        } = &lw.attn
10498        else {
10499            return crate::gpu::BatchGraphOutcome::Declined;
10500        };
10501        let FfnKind::Dense(d) = &lw.ffn else {
10502            return crate::gpu::BatchGraphOutcome::Declined;
10503        };
10504        if !d.segs.is_empty() {
10505            return crate::gpu::BatchGraphOutcome::Declined; // tube layers run on the segmented path
10506        }
10507        // The graph has no arm for a projected output gate, and only the
10508        // activations `graph_act` names.
10509        let (
10510            AttnKind::Full {
10511                softplus_gate: None,
10512                ..
10513            },
10514            Some(gact),
10515        ) = (&lw.attn, d.act.graph_act())
10516        else {
10517            return crate::gpu::BatchGraphOutcome::Declined;
10518        };
10519        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
10520            let (_, i, kind, rs) = t.graph_weight()?;
10521            Some(crate::gpu::GraphW {
10522                idx: i,
10523                kind,
10524                row_scale: rs,
10525                data: &[],
10526                prism: crate::gpu::GraphPrismOp::None,
10527                affine: false,
10528            })
10529        }
10530        let Some((model, _, _, _)) = wq.graph_weight() else {
10531            return crate::gpu::BatchGraphOutcome::Declined;
10532        };
10533        let model = model.clone();
10534        let (Some(gwq), Some(gwk), Some(gwv), Some(gwo), Some(gg), Some(gu), Some(gd)) = (
10535            gw(wq),
10536            gw(wk),
10537            gw(wv),
10538            gw(wo),
10539            gw(&d.gate_proj),
10540            gw(&d.up_proj),
10541            gw(&d.down_proj),
10542        ) else {
10543            return crate::gpu::BatchGraphOutcome::Declined;
10544        };
10545        let layer = crate::gpu::GraphLayer {
10546            engram: None,
10547            mhc: None,
10548            input_norm: &lw.input_norm,
10549            attn: crate::gpu::GraphAttn::Full {
10550                wq: gwq,
10551                wk: gwk,
10552                wv: gwv,
10553                wo: gwo,
10554                q_norm: q_norm.as_deref(),
10555                k_norm: k_norm.as_deref(),
10556                late_qk_norm: self.qk_norm_after_rope,
10557                bias: bias
10558                    .as_ref()
10559                    .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
10560                output_gate: *output_gate,
10561                cpu_k: m.kv.k_heads(),
10562                cpu_v: m.kv.v_heads(),
10563                cpu_base: m.kv.base(),
10564                geom: None,
10565                head_gate: None,
10566            },
10567            post_norm: &lw.post_norm,
10568            attn_out_norm: None,
10569            ffn_out_norm: None,
10570            layer_scale: None,
10571            ffn: crate::gpu::GraphFfn::Dense {
10572                gate: gg,
10573                up: gu,
10574                down: gd,
10575                act: gact,
10576                limit: 0.0,
10577                hot: None,
10578            },
10579        };
10580        let positions: Vec<usize> = (first_pos..first_pos + pairs.len()).collect();
10581        let nh = self.num_heads;
10582        let (nkv, hd, rd) = self.layer_geom(0);
10583        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
10584        // nothing reads the block's rows back: the warm-up is its K/V rows
10585        // (no readback, no wait; the next prompt chunk is encoded while the
10586        // card runs it — on wgpu too: SenseNova-Loop-9B over Vulkan waited
10587        // ~0.35 s a 512-row chunk). `CMF_MTP_WARM_DEFER=0` waits.
10588        let defer = (crate::gpu::cuda_active() || crate::gpu::wgpu_active())
10589            && std::env::var("CMF_MTP_WARM_DEFER").as_deref() != Ok("0");
10590        if defer {
10591            crate::gpu::set_batch_defer(true);
10592        }
10593        let out = crate::gpu::forward_batch_graph(
10594            &model,
10595            self.mtp_kv_id(),
10596            std::slice::from_ref(&layer),
10597            &self.inv_freq,
10598            &mut hiddens,
10599            nh,
10600            nkv,
10601            hd,
10602            rd,
10603            hs,
10604            // See `mtp_step_graph`: draft FFN geometry is local to this
10605            // block after independent MTP compaction.
10606            d.gate_proj.rows(),
10607            &positions,
10608            self.kv_cache.max_seq_len,
10609            gemma,
10610            self.rms_eps as f32,
10611            self.attn_scale,
10612            pairs.len(),
10613            &[],
10614            0,
10615            None,
10616            None,
10617        );
10618        if defer {
10619            crate::gpu::set_batch_defer(false);
10620        }
10621        spec_stamp("w.run");
10622        out
10623    }
10624
10625    /// Complete an MTP warm-up after the batched graph has refused.  A
10626    /// graphable block is retried one row at a time; once any device row has
10627    /// been admitted, a CPU fallback would observe a stale mirror, so every
10628    /// token-graph refusal is terminal.  If the block is not graphable and no
10629    /// mirror exists yet, warming on the CPU is safe and records the CPU mode
10630    /// for the rest of the generation.
10631    #[cfg(feature = "gpu")]
10632    fn mtp_warm_graph_fallback(
10633        &mut self,
10634        m: &mut MtpModule,
10635        pairs: &[(&[f32], u32)],
10636        first_pos: usize,
10637    ) -> bool {
10638        let first_pos = first_pos.saturating_sub(self.mtp_pos_base);
10639        if pairs.is_empty() {
10640            return true;
10641        }
10642        let graphable = self.mtp_block_graph_ok(m);
10643        if !graphable {
10644            // A previously admitted mirror cannot be made coherent by
10645            // appending to the host cache.  The caller turns this into a
10646            // terminal generation error and clears both mirrors.
10647            if self.mtp_graph_mode == Some(true) {
10648                return false;
10649            }
10650            self.mtp_graph_mode = Some(false);
10651            for (j, (h, t)) in pairs.iter().enumerate() {
10652                self.mtp_warm(m, h, *t, first_pos + j);
10653            }
10654            return true;
10655        }
10656
10657        // The batch refusal is recoverable only through the same device
10658        // state.  Keep rows owned until each token graph has completed; a
10659        // None is treated as unsafe because the token-graph API deliberately
10660        // collapses its backend refusal/failure into that result.
10661        for (j, (h, t)) in pairs.iter().enumerate() {
10662            if self.mtp_step_graph(m, h, *t, first_pos + j).is_none() {
10663                return false;
10664            }
10665        }
10666        self.mtp_graph_mode = Some(true);
10667        true
10668    }
10669
10670    /// Warm a contiguous set of MTP pairs using the existing graph seam, with
10671    /// an all-or-nothing error contract for callers that already admitted the
10672    /// trunk batch.  The non-GPU build keeps the same pair accounting while
10673    /// using the established CPU warm path.
10674    #[cfg(feature = "gpu")]
10675    fn mtp_warm_prefill_pairs(
10676        &mut self,
10677        m: &mut MtpModule,
10678        pairs: &[(&[f32], u32)],
10679        first_pos: usize,
10680    ) -> Result<(), &'static str> {
10681        // Keep unsupported token-graph heads on the established CPU MTP
10682        // route before admitting any block mirror.  Once a device mirror is
10683        // active, the same condition is terminal because CPU rows cannot
10684        // repair its state.
10685        if self.mtp_graph_mode == Some(false) || !self.mtp_graph_ok(m) {
10686            if self.mtp_graph_mode == Some(true) {
10687                return Err("MTP token graph became unavailable after admission");
10688            }
10689            self.mtp_graph_mode = Some(false);
10690            for (j, (h, t)) in pairs.iter().enumerate() {
10691                self.mtp_warm(m, h, *t, first_pos + j);
10692            }
10693            return Ok(());
10694        }
10695        match self.mtp_warm_graph(m, pairs, first_pos) {
10696            crate::gpu::BatchGraphOutcome::Completed => {
10697                if !pairs.is_empty() {
10698                    self.mtp_graph_mode = Some(true);
10699                }
10700                Ok(())
10701            }
10702            crate::gpu::BatchGraphOutcome::Declined => {
10703                if self.mtp_warm_graph_fallback(m, pairs, first_pos) {
10704                    Ok(())
10705                } else {
10706                    Err("MTP warm-up fallback failed after device admission")
10707                }
10708            }
10709            crate::gpu::BatchGraphOutcome::Failed => {
10710                Err("MTP warm batch graph failed after admission")
10711            }
10712        }
10713    }
10714
10715    #[cfg(not(feature = "gpu"))]
10716    fn mtp_warm_prefill_pairs(
10717        &mut self,
10718        m: &mut MtpModule,
10719        pairs: &[(&[f32], u32)],
10720        first_pos: usize,
10721    ) -> Result<(), &'static str> {
10722        for (j, (h, t)) in pairs.iter().enumerate() {
10723            self.mtp_warm(m, h, *t, first_pos + j);
10724        }
10725        Ok(())
10726    }
10727
10728    /// The MTP block alone — advance its KV with a (hidden, token) pair the
10729    /// verify just proved, without paying the head. What keeps the draft's
10730    /// attention context warm between speculative rounds.
10731    fn mtp_warm(&mut self, m: &mut MtpModule, hidden: &[f32], next_token: u32, position: usize) {
10732        let position = position.saturating_sub(self.mtp_pos_base);
10733        let e = self.embed_single(next_token);
10734        let mut cat = vec![0.0f32; 2 * self.hidden_size];
10735        let (cat_e, cat_h) = cat.split_at_mut(self.hidden_size);
10736        inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
10737        inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
10738        let mut x = vec![0.0f32; self.hidden_size];
10739        m.eh_proj.matvec(&cat, &mut x, self.pool.as_deref());
10740        inference::rms_norm_into(
10741            &x,
10742            &m.layer.input_norm,
10743            self.rms_eps,
10744            self.norm_style,
10745            &mut self.ws.n1,
10746        );
10747        let attn = match &m.layer.attn {
10748            AttnKind::Full {
10749                wq,
10750                wk,
10751                wv,
10752                wo,
10753                q_norm,
10754                k_norm,
10755                output_gate,
10756                softplus_gate,
10757                bias,
10758            } => {
10759                let mut cfg = self.attn_cfg(position);
10760                cfg.q_norm = q_norm.as_deref();
10761                cfg.k_norm = k_norm.as_deref();
10762                cfg.output_gate = *output_gate;
10763                cfg.softplus_gate = softplus_gate.as_ref().map(|(g, p)| (g, *p));
10764                cfg.bias = bias
10765                    .as_ref()
10766                    .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice()));
10767                attention::qwen_attention(&self.ws.n1, wq, wk, wv, wo, &mut m.kv, &cfg)
10768            }
10769            _ => return,
10770        };
10771        let _ = attn;
10772    }
10773
10774    /// Speculative decode ON the wgpu whole-token graph: draft k with the
10775    /// MTP head, verify all of them plus the tip in ONE batched graph
10776    /// submit whose tail folds the head, commit the accepted prefix and
10777    /// roll the GDN state back to the last real position. Greedy only —
10778    /// output equals the plain graph's token for token, the way the DSV4
10779    /// verify equals the walk.
10780    #[cfg(feature = "gpu")]
10781    #[allow(clippy::too_many_arguments)]
10782    fn graph_spec_step(
10783        &mut self,
10784        m: &mut MtpModule,
10785        hidden: &[f32],
10786        t_next: u32,
10787        next_pos: usize,
10788        drafted: &mut usize,
10789        accepted: &mut usize,
10790        // The committed stream (prompt + generated so far, `t_next`
10791        // included): the sampler chain's penalties read it, and the
10792        // sampling arm extends it with the drafts position by position.
10793        all_ids: &mut Vec<u32>,
10794        // Tokens left before `max_tokens`. A round commits up to k
10795        // accepted drafts, and those positions are already in the cache,
10796        // so the depth is capped here — trimming the output afterwards
10797        // would leave cache rows the committed stream does not have.
10798        room: usize,
10799    ) -> Option<(Vec<u32>, usize, Vec<f32>)> {
10800        // 3 is the measured optimum on Qwen3.6-27B / RTX 5090 (medians
10801        // of three, greedy): 51.1 tok/s against a plain 49.4, where k=2
10802        // gives 46.1, k=4 50.0, k=5 47.4, k=6 45.2. Acceptance is 89-91%
10803        // throughout — what turns the curve over is the verify, which
10804        // costs ~7.4 ms per extra position, and the draft ~3 ms a step.
10805        // 4 since the draft moved onto the graph (Qwen3.8-27B / 5090:
10806        // k=3 51.2, k=4 51.8 with the per-op draft; the graph draft
10807        // halves the draft cost, so the extra draft is cheaper still).
10808        // 5 with the int8 verify (the default: measured 76.5 against
10809        // k=4's 72-74 and k=6's 74 on the 5090), 4 with the f32 one.
10810        #[cfg(target_os = "macos")]
10811        let metal_native = crate::gpu::q1_force();
10812        #[cfg(not(target_os = "macos"))]
10813        let metal_native = false;
10814        #[cfg(feature = "gpu")]
10815        let k_default = if metal_native {
10816            // the Metal verify's GEMM tile is 8 rows wide and flat in b:
10817            // seven drafts + the tip fill it for free
10818            7
10819        } else if crate::gpu_wgpu::verify_i8_on() {
10820            5
10821        } else {
10822            4
10823        };
10824        #[cfg(not(feature = "gpu"))]
10825        let k_default = 4;
10826        let k_env: Option<usize> = std::env::var("CMF_GRAPH_SPEC_K")
10827            .ok()
10828            .and_then(|v| v.parse().ok())
10829            .filter(|&v| (1..=8).contains(&v));
10830        // Adaptive depth: start below the card's flat-verify optimum and
10831        // let the accepted fraction move it — predictable text climbs to
10832        // the old default within a few rounds, prose settles at 2-3 where
10833        // the shorter verify pays.
10834        // Native Metal over a q4tp trunk: two rows verify at about a plain
10835        // token's price and three at a quarter more, so the depth follows
10836        // each depth's running acceptance instead of filling the GEMM tile.
10837        let metal_small = metal_native && self.metal_small_batch_verify();
10838        // Greedy without penalties verifies by argmax equality (bit-exact
10839        // against the plain path). Anything else is speculative SAMPLING:
10840        // each draft is a DRAW from the MTP head's post-chain distribution
10841        // q_j, kept for the accept test; the verify's rows give p_j.
10842        let cfg = self.sampler_config.clone();
10843        let penalized = !(cfg.repetition_penalty == 1.0
10844            && cfg.presence_penalty == 0.0
10845            && cfg.suppress_tokens.is_empty());
10846        // Three verify regimes: plain greedy (argmax of the raw rows),
10847        // greedy WITH penalties (argmax of the penalized rows — a single
10848        // pass each, no distributions), and sampling (draw / accept /
10849        // correct on post-chain distributions).
10850        let greedy_pen = cfg.temperature < 1e-6 && penalized;
10851        let sampling = cfg.temperature >= 1e-6;
10852        // A DFlash drafter beside the model drafts a round in one block
10853        // (plain greedy on native Metal, where the verify hands it the
10854        // trunk's rows). Its block costs the same at any depth, so its
10855        // rounds go deep where its drafts hold; the MTP chain's are short
10856        // and nearly free. Each keeps its own account of what it holds, and
10857        // the round goes to the one that lands more tokens in a unit of time
10858        // (the one in turn has to be beaten by more than the noise). The
10859        // block was trained on Latin-script text: while the committed tokens
10860        // come from the high table (`draft_full_streak`) the chain keeps the
10861        // rounds. A turn the chain takes back makes the block sit out, longer
10862        // each time it is a short one.
10863        // The wgpu graphs keep the drafter's rows on their way (`layer_taps`):
10864        // they become context here, and a round is the block's only while that
10865        // context reaches the tip. There the block is for measuring, pinned
10866        // with `CMF_DFLASH_PICK=dflash`, and the chain keeps the rounds
10867        // otherwise: the block is a matrix a submission, and on a 16 GB card
10868        // the Turbo trunk leaves its 1.3 GB no room among the resident weights
10869        // (RTX 2000 Ada: 135 ms a block against 11 ms for the chain's drafts,
10870        // and a verify of eight rows costs two plain tokens).
10871        if !metal_native {
10872            self.dflash_taps_absorb();
10873        }
10874        // The CUDA hybrid arm keeps the drafter's context at the tip every
10875        // call (its graphs copy the tapped rows out) and verifies eight rows
10876        // at about one price: the round goes to the drafter that lands more
10877        // tokens at that card's prices, as on Metal.
10878        let cuda_rate = !metal_native && crate::gpu::cuda_active();
10879        let dflash_ok = !sampling
10880            && !greedy_pen
10881            && match &self.dflash {
10882                Some(d) => metal_native || ((dflash_pick() == Some(true) || cuda_rate) && d.next_position() == next_pos),
10883                None => false,
10884            };
10885        if !metal_native && !cuda_rate && self.dflash.is_some() && dflash_pick() != Some(true) {
10886            static SAID: std::sync::Once = std::sync::Once::new();
10887            SAID.call_once(|| {
10888                tracing::info!(
10889                    "DFlash drafter: on wgpu the MTP chain keeps the rounds (CMF_DFLASH_PICK=dflash pins the block)"
10890                )
10891            });
10892        }
10893        let (k_flash, rate_flash) = if cuda_rate {
10894            spec_plan_at(&CUDA_ROUND_COST, &self.dflash_hold, CUDA_BLOCK_DRAFT, 0.0)
10895        } else {
10896            metal_spec_plan(&self.dflash_hold, DFLASH_ROUND_DRAFT)
10897        };
10898        let (_, rate_mtp) = if cuda_rate {
10899            spec_plan_at(&CUDA_ROUND_COST, &self.spec_hold, 0.0, CUDA_DRAFT_STEP)
10900        } else {
10901            metal_spec_plan(&self.spec_hold, 0.0)
10902        };
10903        // A sidecar that carries a router says which drafter the text at the
10904        // tip is for, from the target's own row there: two subspaces of such
10905        // rows, one of the rounds the block won and one of the chain's, and
10906        // the row goes to the one that holds it better (`dflash::Route`).
10907        // A few rounds are averaged, and the drafter in turn keeps a round
10908        // the average does not clearly give away.
10909        let routed = match (&self.dflash, dflash_ok) {
10910            (Some(d), true) => d.route.as_ref().map(|r| r.margin(hidden)),
10911            _ => None,
10912        };
10913        if let Some(m) = routed {
10914            self.dflash_lean += DFLASH_LEAN_STEP * (m - self.dflash_lean);
10915        }
10916        // CUDA verifies a lookup of sixteen rows at about one price: while the
10917        // lookups land (their running gain past `DFLASH_LOOKUP_KEEPS`), an
10918        // edit or a quote stays the chain's, which the router (fitted where
10919        // the lookup was eight rows) would give the block
10920        let copying = (routed.is_some() || cuda_rate)
10921            && dflash_pick().is_none()
10922            && (tail_repeat(all_ids) >= DFLASH_COPY_MIN || (cuda_rate && self.spec_lookup_gain > DFLASH_LOOKUP_KEEPS));
10923        let dflash_round = dflash_ok
10924            && match (dflash_pick(), routed) {
10925                (Some(pin), _) => pin,
10926                (None, Some(_)) if copying => false,
10927                // the block drafts over the head's shortlist: text from the
10928                // high table is the chain's (CUDA, where the router alone
10929                // sent a Danish article to the block: 55 against 73 tok/s)
10930                (None, Some(_)) if cuda_rate && self.draft_full_streak > 0 => false,
10931                (None, Some(_)) if self.dflash_last => self.dflash_lean > -DFLASH_LEAN_BAND,
10932                (None, Some(_)) => self.dflash_lean > DFLASH_LEAN_BAND,
10933                // the chain's short round with the prompt lookup copies for less
10934                (None, None) if copying => false,
10935                (None, None) if !metal_small && !cuda_rate => true,
10936                (None, None) if self.draft_full_streak > 0 => false,
10937                (None, None) if self.dflash_last => rate_flash * 1.05 >= rate_mtp,
10938                (None, None) if self.dflash_wait > 0 => {
10939                    self.dflash_wait -= 1;
10940                    false
10941                }
10942                (None, None) => rate_flash > rate_mtp * 1.05,
10943            };
10944        if dflash_ok && dflash_round != self.dflash_last {
10945            if dflash_round {
10946                (self.dflash_turn, self.dflash_turn_sum) = (0, (0.0, 0.0));
10947            } else {
10948                // the block's turn is over: it comes back to a fresh account
10949                let (tokens, cost) = self.dflash_turn_sum;
10950                if self.dflash_turn >= DFLASH_TURN && tokens >= rate_mtp * cost {
10951                    self.dflash_wait = DFLASH_WAIT_DIP;
10952                } else {
10953                    self.dflash_back = if self.dflash_turn < DFLASH_TURN {
10954                        (self.dflash_back * 2).min(DFLASH_WAIT_MOST)
10955                    } else {
10956                        DFLASH_WAIT
10957                    };
10958                    self.dflash_wait = self.dflash_back;
10959                }
10960                self.dflash_hold = DFLASH_HOLD_PRIOR;
10961            }
10962            if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
10963                eprintln!(
10964                    "spec-drafter: {} ({rate_flash:.2} against {rate_mtp:.2} tokens in a plain token's time)",
10965                    if dflash_round { "the DFlash block" } else { "the MTP chain" }
10966                );
10967            }
10968        }
10969        self.dflash_turn += u32::from(dflash_round);
10970        self.dflash_last = dflash_round;
10971        // a pinned block never hands a round to the chain: its cache may lapse
10972        let mtp_in_step = dflash_pick() != Some(true) || dflash_rows_log().is_some();
10973        let (k_start, k_max) = if dflash_round && metal_small {
10974            (k_flash, 7)
10975        } else if metal_small {
10976            (metal_spec_depth(&self.spec_hold), 7)
10977        } else if metal_native || dflash_round {
10978            // (a block costs the same at any depth: its rounds start at all seven)
10979            (7, 7)
10980        } else {
10981            (3, k_default.max(5))
10982        };
10983        let k_full: usize = k_env.unwrap_or_else(|| {
10984            if metal_small {
10985                k_start
10986            } else if dflash_round && !metal_native {
10987                self.dflash_k_adapt.unwrap_or(k_start)
10988            } else {
10989                self.spec_k_adapt.unwrap_or(k_start)
10990            }
10991        });
10992        let k_spec = k_full.min(room).max(1);
10993        // a tail round cut short by `room` says nothing about the text:
10994        // it must not move the adaptive depth the next request starts at
10995        let k_capped = k_spec < k_full;
10996        if next_pos == 0 {
10997            return None;
10998        }
10999        let t_round = std::time::Instant::now();
11000        // Submissions per phase — and they say where the round's money is.
11001        // Qwen3.6-27B on an RTX 5090, k=3:
11002        //
11003        //   draft   9.3 ms / 12 submissions   (four per MTP step)
11004        //   verify 52.8 ms /  1               (the batched graph)
11005        //   commit  5.4 ms /  6               (two per warm)
11006        //
11007        // The verify is already one submit. The draft's own work is 834 MB
11008        // a step — 0.8 ms at this card's measured 1056 GB/s — against 3.1
11009        // ms measured, so ~0.58 ms of every step is round trip, not
11010        // arithmetic, and the same holds for the warms. Eighteen round
11011        // trips a round at roughly half a millisecond each is ~11 ms of a
11012        // 68 ms round: fusing the MTP block into ONE submit the way the
11013        // trunk already is projects to ~64 tok/s against today's 50.9.
11014        // That is the largest measured item left on this path.
11015        let subs = || crate::gpu_wgpu::SUBMITS.load(std::sync::atomic::Ordering::Relaxed);
11016        let sub0 = subs();
11017        let k_spec = match &self.dflash {
11018            Some(d) if dflash_round => k_spec.min(d.g.block - 1),
11019            _ => k_spec,
11020        };
11021        // Sampling with a top-k goes through the SPARSE chain: the dense
11022        // one builds nine 248k-float distributions a round (four drafts,
11023        // five verify rows) and measured 19-22 tok/s against a plain 40 —
11024        // the host, not the card. Sparse, the same nine cost tens of
11025        // microseconds each.
11026        let sparse = sampling && sampler::sparse_ok(&cfg);
11027        let base_len = all_ids.len();
11028        if sampling && !sparse && self.spec_q.len() < k_spec {
11029            self.spec_q.resize_with(k_spec, Vec::new);
11030        }
11031        if sparse && self.spec_qs.len() < k_spec {
11032            self.spec_qs.resize_with(k_spec, Vec::new);
11033        }
11034        // Draft the chain: first from the trunk's tip hidden, then the head
11035        // iterating on itself. Rows land in the MTP KV; the chain rows past
11036        // the first are speculation over speculative state and roll back
11037        // below, replaced by verified pairs.
11038        let mut drafts = Vec::with_capacity(k_spec);
11039        let mut hx = hidden.to_vec();
11040        // CMF_SPEC_DBG=1: draft 0 through BOTH MTP arms (graph and per-op)
11041        // from the same inputs — are the arms the difference, or the inputs?
11042        let spec_dbg = std::env::var("CMF_SPEC_DBG").is_ok();
11043        spec_stamp("pro");
11044        if dflash_round {
11045            drafts = self.dflash_draft(t_next, next_pos, k_spec);
11046            spec_stamp("d.flash");
11047        }
11048        // the chain's drafts of a round the block has, for the rows log: its
11049        // cache is then cut and warmed as after a round of its own
11050        let mut beside: Vec<u32> = Vec::new();
11051        #[cfg(target_os = "macos")]
11052        if dflash_round && dflash_rows_log().is_some() && self.mtp_graph_mode != Some(false) {
11053            match self.mtp_draft_chain_metal(m, hidden, t_next, next_pos - 1, 7) {
11054                Ok(ids) => {
11055                    self.mtp_graph_mode = Some(true);
11056                    beside = ids;
11057                }
11058                Err(true) => {
11059                    tracing::error!("mtp Metal draft chain failed after commit");
11060                    self.clear_sequence_state();
11061                    self.graph_failed
11062                        .store(true, std::sync::atomic::Ordering::Relaxed);
11063                    self.cancel
11064                        .store(true, std::sync::atomic::Ordering::Relaxed);
11065                    return None;
11066                }
11067                Err(false) => {}
11068            }
11069        }
11070        // Plain greedy on native Metal: the whole chain as one command
11071        // buffer (device argmax + embedding gather between the steps).
11072        // A decline before commit hands the round to the per-step loop
11073        // below; a failure after commit is terminal, like any graph
11074        // failure after admission.
11075        #[cfg(target_os = "macos")]
11076        if metal_native && !dflash_round && !sampling && !greedy_pen && self.mtp_graph_mode != Some(false) {
11077            match self.mtp_draft_chain_metal(m, hidden, t_next, next_pos - 1, k_spec) {
11078                Ok(ids) => {
11079                    self.mtp_graph_mode = Some(true);
11080                    drafts = ids;
11081                }
11082                Err(true) => {
11083                    tracing::error!("mtp Metal draft chain failed after commit");
11084                    self.clear_sequence_state();
11085                    self.graph_failed
11086                        .store(true, std::sync::atomic::Ordering::Relaxed);
11087                    self.cancel
11088                        .store(true, std::sync::atomic::Ordering::Relaxed);
11089                    return None;
11090                }
11091                Err(false) => {}
11092            }
11093        }
11094        // CUDA hybrid arm, greedy: the whole chain as one graph (device
11095        // argmax and embedding gather between the steps). A suppress list
11096        // whose ids all sit past the draft shortlist cannot change its
11097        // argmax. A decline hands the round to the per-step loop below; a
11098        // failure after admission is terminal, like any graph failure.
11099        #[cfg(feature = "cuda")]
11100        if crate::gpu::cuda_active()
11101            && !dflash_round
11102            && !sampling
11103            && !spec_dbg
11104            && drafts.is_empty()
11105            && self.mtp_graph_mode != Some(false)
11106            && (!greedy_pen
11107                || (cfg.repetition_penalty == 1.0
11108                    && cfg.presence_penalty == 0.0
11109                    && cfg.suppress_tokens.iter().all(|&t| (t as usize) >= Self::draft_vocab_rows(self.weights.lm_head.rows()))))
11110        {
11111            match self.mtp_draft_chain_cuda(m, &hx, t_next, next_pos - 1, k_spec) {
11112                Ok(ids) => {
11113                    self.mtp_graph_mode = Some(true);
11114                    drafts = ids;
11115                    spec_stamp("d.chain");
11116                }
11117                Err(true) => {
11118                    tracing::error!("cuda draft chain failed after admission");
11119                    self.clear_sequence_state();
11120                    self.graph_failed
11121                        .store(true, std::sync::atomic::Ordering::Relaxed);
11122                    self.cancel
11123                        .store(true, std::sync::atomic::Ordering::Relaxed);
11124                    return None;
11125                }
11126                Err(false) => {}
11127            }
11128        }
11129        for j in drafts.len()..k_spec {
11130            let tok_in = if j == 0 { t_next } else { drafts[j - 1] };
11131            let mut dbg_ref: Option<(Vec<f32>, Vec<f32>)> = None;
11132            if spec_dbg {
11133                let saved = self.mtp_graph_mode;
11134                self.mtp_graph_mode = Some(false);
11135                let r = self.mtp_step_hl(m, &hx, tok_in, next_pos - 1 + j);
11136                self.mtp_graph_mode = saved;
11137                if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
11138                    return None;
11139                }
11140                m.kv.truncate_last(1);
11141                dbg_ref = Some(r);
11142            }
11143            let (mut lg, hj) = self.mtp_step_hl(m, &hx, tok_in, next_pos - 1 + j);
11144            if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
11145                return None;
11146            }
11147            if let Some((lg_cpu, h_cpu)) = dbg_ref {
11148                let n = |v: &[f32]| v.iter().map(|x| x * x).sum::<f32>().sqrt();
11149                let dl = lg
11150                    .iter()
11151                    .zip(&lg_cpu)
11152                    .fold(0f32, |m, (a, b)| m.max((a - b).abs()));
11153                let dh = hj
11154                    .iter()
11155                    .zip(&h_cpu)
11156                    .fold(0f32, |m, (a, b)| m.max((a - b).abs()));
11157                eprintln!(
11158                    "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 {}",
11159                    next_pos - 1 + j,
11160                    sampler::argmax(&lg_cpu),
11161                    sampler::argmax(&lg),
11162                    n(&h_cpu),
11163                    n(&hj),
11164                    m.kv.seq_len
11165                );
11166            }
11167            let dj = if sparse {
11168                let mut q = std::mem::take(&mut self.spec_qs[j]);
11169                let ok = sampler::sparse_distribution_into(
11170                    &lg,
11171                    &cfg,
11172                    all_ids,
11173                    &mut self.sampler_scratch,
11174                    self.pool.as_deref(),
11175                    &mut q,
11176                );
11177                let d = if ok {
11178                    sampler::draw_sparse(&q, &mut self.rng)
11179                } else {
11180                    // everything filtered: the dense chain's greedy fallback
11181                    let t = sampler::argmax(&lg);
11182                    q.clear();
11183                    q.push((t, 1.0));
11184                    t
11185                };
11186                self.spec_qs[j] = q;
11187                all_ids.push(d);
11188                d
11189            } else if sampling {
11190                let mut q = std::mem::take(&mut self.spec_q[j]);
11191                sampler::distribution_into(
11192                    &lg,
11193                    &cfg,
11194                    all_ids,
11195                    &mut self.sampler_scratch,
11196                    self.pool.as_deref(),
11197                    &mut q,
11198                );
11199                let d = sampler::draw(&q, &mut self.rng);
11200                self.spec_q[j] = q;
11201                all_ids.push(d); // the next draft's penalties see this one
11202                d
11203            } else if greedy_pen {
11204                let d = sampler::argmax_penalized(
11205                    &lg,
11206                    &cfg,
11207                    all_ids,
11208                    &mut self.sampler_scratch,
11209                    self.pool.as_deref(),
11210                );
11211                all_ids.push(d);
11212                d
11213            } else {
11214                sampler::argmax(&lg)
11215            };
11216            attention::recycle_buf(&mut lg);
11217            drafts.push(dj);
11218            hx = hj;
11219            spec_stamp("d.pick");
11220        }
11221        all_ids.truncate(base_len);
11222        // Prompt lookup, plain greedy on native Metal, where a verify of
11223        // four to eight rows has one price: when the tip and the head's
11224        // drafts repeat an earlier stretch of the sequence, the tokens that
11225        // followed it there go on as drafts. The head's drafts are the
11226        // test: a lookup continues only what they agree with.
11227        let k_mtp = k_spec;
11228        // steps the MTP block took this round: its own round's drafts, the
11229        // chain run beside a DFlash block, or none
11230        let mtp_steps = if dflash_round { beside.len() } else { k_mtp };
11231        // The CUDA hybrid arm verifies up to 16 rows on the tensor cores at
11232        // about one price (8 rows 1.05x a plain token, 16 about 1.6x on a
11233        // 3090): a copy may run 15 drafts deep there.
11234        let cuda_window = crate::gpu::cuda_active();
11235        let k_room = room.min(if cuda_window && self.spec_lookup_wide { 15 } else { 7 });
11236        // A suppress list alone scores a continuation the same at any
11237        // history, so the CUDA window takes lookups under it too.
11238        let history_free = cfg.repetition_penalty == 1.0 && cfg.presence_penalty == 0.0;
11239        if (metal_native || cuda_window)
11240            && !sampling
11241            && (!greedy_pen || (cuda_window && history_free))
11242            && k_mtp < k_room
11243            && drafts.len() == k_mtp
11244            && Self::spec_lookup_on()
11245        {
11246            if self.spec_lookup_rest > 0 {
11247                self.spec_lookup_rest -= 1;
11248            } else {
11249                all_ids.extend_from_slice(&drafts);
11250                let more =
11251                    lookup_continuation(all_ids, k_mtp + LOOKUP_MIN_REAL, k_room - k_mtp).to_vec();
11252                all_ids.truncate(base_len);
11253                drafts.extend(more);
11254            }
11255        }
11256        let k_spec = drafts.len();
11257        spec_stamp("d.look");
11258        *drafted += k_spec;
11259        let t_draft = t_round.elapsed();
11260        let sub_draft = subs();
11261        // Verify batch: [t_next, d1 .. d_{k-1}] at next_pos.. — every row's
11262        // logits come back from the graph's own head.
11263        let b = k_spec + 1;
11264        let mut hiddens = vec![0.0f32; b * self.hidden_size];
11265        for (i, &t) in std::iter::once(&t_next).chain(drafts.iter()).enumerate() {
11266            let e = self.embed_single(t);
11267            hiddens[i * self.hidden_size..(i + 1) * self.hidden_size].copy_from_slice(&e);
11268        }
11269        let positions: Vec<usize> = (next_pos..next_pos + b).collect();
11270        spec_stamp("v.emb");
11271        let (lm_gw, lm_rows) = {
11272            let (_, i, kind, rs) = self.weights.lm_head.graph_weight()?;
11273            (
11274                crate::gpu::GraphW {
11275                    idx: i,
11276                    kind,
11277                    row_scale: rs,
11278                    data: &[],
11279                    prism: crate::gpu::GraphPrismOp::None,
11280                    affine: false,
11281                },
11282                self.weights.lm_head.rows(),
11283            )
11284        };
11285        let mut logits = Vec::new();
11286        let final_norm = self.weights.final_norm.clone();
11287        // Plain greedy on Metal: the b argmaxes come from the device
11288        // (`argmax_rows` after the head) and the 7.9 MB logits plane is
11289        // never read back — the round's decision needs only the ids, and
11290        // the loop top takes the last verified id as `spec_forced`, which
11291        // is exactly what its argmax of the row would give. The full rows
11292        // stay for anything that reads them: sampling, penalties,
11293        // confidence, the verify oracle, the logit dump.
11294        // `CMF_METAL_DEV_ARGMAX=0` keeps the host path.
11295        #[cfg(target_os = "macos")]
11296        let greedy_dev = metal_native
11297            && !sampling
11298            && !greedy_pen
11299            && !self.confidence_on
11300            && self.final_softcap.is_none()
11301            // The host acceptance argmax scans the WHOLE head row
11302            // (`lm_rows`), the sampler's own row only `vocab_size`: they
11303            // coincide exactly when the head has no padding rows, and
11304            // only then is the device argmax (which scores `vocab_size`)
11305            // bit-identical to both.
11306            && self.vocab_size == lm_rows
11307            && std::env::var_os("CMF_METAL_VERIFY_CHECK").is_none()
11308            && std::env::var_os("CMF_LOGIT_DUMP").is_none()
11309            && std::env::var("CMF_METAL_DEV_ARGMAX").as_deref() != Ok("0");
11310        // The CUDA hybrid arm the same way: each verify row's argmax on the
11311        // card (the host's tie rule), 5 MB of logits not read back.
11312        // `CMF_CUDA_DEV_ARGMAX=0` keeps the host path.
11313        #[cfg(all(not(target_os = "macos"), feature = "cuda"))]
11314        let greedy_dev = crate::gpu::cuda_active()
11315            && !sampling
11316            && !greedy_pen
11317            && !self.confidence_on
11318            && self.final_softcap.is_none()
11319            && self.vocab_size == lm_rows
11320            && std::env::var_os("CMF_LOGIT_DUMP").is_none()
11321            && std::env::var("CMF_CUDA_DEV_ARGMAX").as_deref() != Ok("0");
11322        #[cfg(all(not(target_os = "macos"), not(feature = "cuda")))]
11323        let greedy_dev = false;
11324        let mut dev_ids: Vec<u32> = Vec::new();
11325        #[cfg(target_os = "macos")]
11326        let verify_outcome = if metal_native {
11327            let lm = self.weights.lm_head.q1_parts()?;
11328            let n_score = self.vocab_size.min(lm_rows);
11329            self.try_batch_graph_metal(
11330                &mut hiddens,
11331                &positions,
11332                b,
11333                Some((lm, &final_norm, &mut logits)),
11334                if greedy_dev {
11335                    Some((n_score, &mut dev_ids))
11336                } else {
11337                    None
11338                },
11339            )
11340        } else {
11341            self.try_batch_graph_wgpu(
11342                &mut hiddens,
11343                &positions,
11344                b,
11345                Some(crate::gpu::SpecTail {
11346                    lm: lm_gw,
11347                    lm_rows,
11348                    final_norm: &final_norm,
11349                    logits_out: &mut logits,
11350                    pick: None,
11351                }),
11352            )
11353        };
11354        #[cfg(all(not(target_os = "macos"), feature = "cuda"))]
11355        crate::gpu_cuda::verify_argmax_arm(greedy_dev);
11356        #[cfg(not(target_os = "macos"))]
11357        let verify_outcome = self.try_batch_graph_wgpu(
11358            &mut hiddens,
11359            &positions,
11360            b,
11361            Some(crate::gpu::SpecTail {
11362                lm: lm_gw,
11363                lm_rows,
11364                final_norm: &final_norm,
11365                logits_out: &mut logits,
11366                pick: None,
11367            }),
11368        );
11369        #[cfg(all(not(target_os = "macos"), feature = "cuda"))]
11370        if greedy_dev {
11371            if let Some(ids) = crate::gpu_cuda::verify_argmax_take() {
11372                dev_ids = ids;
11373            }
11374        }
11375        match verify_outcome {
11376            crate::gpu::BatchGraphOutcome::Completed => {}
11377            crate::gpu::BatchGraphOutcome::Declined => {
11378                // The verifier refused before admission.  Its draft MTP
11379                // rows are still device-resident, so rewind the separate
11380                // mirror before the caller takes the exact one-token path.
11381                // (A DFlash round put no rows there.)
11382                self.dflash_rows = None;
11383                m.kv.truncate_last(mtp_steps);
11384                if !metal_native && mtp_steps > 0 && !self.rewind_mtp_graph_mirror(next_pos) {
11385                    self.clear_sequence_state();
11386                    self.graph_failed
11387                        .store(true, std::sync::atomic::Ordering::Relaxed);
11388                    self.cancel
11389                        .store(true, std::sync::atomic::Ordering::Relaxed);
11390                    tracing::error!("MTP graph mirror rewind failed after verify decline");
11391                }
11392                return None;
11393            }
11394            crate::gpu::BatchGraphOutcome::Failed => {
11395                // A failed batch may have advanced trunk/GDN state.  Clear
11396                // both mirrors and preserve the terminal outcome rather than
11397                // falling through to stale CPU state.
11398                self.clear_sequence_state();
11399                self.graph_failed
11400                    .store(true, std::sync::atomic::Ordering::Relaxed);
11401                self.cancel
11402                    .store(true, std::sync::atomic::Ordering::Relaxed);
11403                tracing::error!("MTP verify batch graph failed after admission");
11404                self.dflash_rows = None;
11405                return None;
11406            }
11407        }
11408        // `CMF_METAL_VERIFY_CHECK=1`: run the same b tokens through the
11409        // plain per-token path and compare each row's argmax + logits with
11410        // the verify's — the bring-up oracle for the batched graph. The
11411        // plain forwards mutate the CPU state; it is snapshotted and put
11412        // back, and the K/V mirrors re-pointed, before the round goes on.
11413        #[cfg(target_os = "macos")]
11414        if metal_native && std::env::var("CMF_METAL_VERIFY_CHECK").as_deref() == Ok("1") {
11415            let snap: Vec<Vec<f32>> = self
11416                .kv_cache
11417                .layers
11418                .iter()
11419                .map(|l| l.linear_state.clone())
11420                .collect();
11421            let attn_lens: Vec<usize> = self.kv_cache.layers.iter().map(|l| l.seq_len).collect();
11422            let toks: Vec<u32> = std::iter::once(t_next)
11423                .chain(drafts.iter().copied())
11424                .collect();
11425            let want_save = self.graph_want_logits;
11426            self.graph_want_logits = false;
11427            for (i, &t) in toks.iter().enumerate() {
11428                let hi = self.forward_layers(&self.embed_single(t), next_pos + i, None);
11429                let _ = self.graph_logits.take();
11430                // CMF_SPEC_PLAIN_HIDDEN=1: the next round drafts from the
11431                // plain path's hidden instead of the verify's (an experiment
11432                // on the chain's sensitivity to the half-GEMM noise)
11433                if std::env::var("CMF_SPEC_PLAIN_HIDDEN").as_deref() == Ok("1") {
11434                    hiddens[i * self.hidden_size..(i + 1) * self.hidden_size].copy_from_slice(&hi);
11435                }
11436                let ref_lg = self.logits_from_hidden(&hi);
11437                let row = &logits[i * lm_rows..(i + 1) * lm_rows];
11438                let ra = sampler::argmax(&ref_lg);
11439                let va = sampler::argmax(row);
11440                let mut md = 0f32;
11441                let mut rms = 0f64;
11442                for j in 0..lm_rows.min(ref_lg.len()) {
11443                    let d = (ref_lg[j] - row[j]).abs();
11444                    md = md.max(d);
11445                    rms += (d as f64) * (d as f64);
11446                }
11447                let mut hd = 0f32;
11448                for j in 0..self.hidden_size {
11449                    hd = hd.max((hi[j] - hiddens[i * self.hidden_size + j]).abs());
11450                }
11451                eprintln!(
11452                    "verify-check row {i} tok {t} pos {}: ref argmax {ra} verify argmax {va} {} | max|dlogit| {md:.3e} rms {:.3e} | max|dhidden| {hd:.3e}",
11453                    next_pos + i,
11454                    if ra == va { "OK" } else { "MISMATCH" },
11455                    (rms / lm_rows as f64).sqrt()
11456                );
11457            }
11458            self.graph_want_logits = want_save;
11459            // restore IN PLACE: the pending verify graph wraps these very
11460            // allocations (zero-copy) — replacing the Vec would strand it
11461            for (l, st) in self.kv_cache.layers.iter_mut().zip(snap) {
11462                if l.linear_state.len() == st.len() {
11463                    l.linear_state.copy_from_slice(&st);
11464                } else {
11465                    l.linear_state = st;
11466                }
11467            }
11468            for (li, (l, n0)) in self.kv_cache.layers.iter_mut().zip(attn_lens).enumerate() {
11469                let extra = l.seq_len.saturating_sub(n0);
11470                if extra > 0 {
11471                    l.truncate_last(extra);
11472                    crate::gpu_metal::kv_mirror_set_stored(self.graph_kv_id, li, n0);
11473                }
11474            }
11475        }
11476        let t_verify = t_round.elapsed();
11477        let sub_verify = subs();
11478        // Acceptance. Greedy: row i's argmax is the trunk's token after
11479        // input i. Sampling: accept draft i with min(1, p_i/q_i), and on
11480        // the first rejection draw the correction from max(0, p_i − q_i)
11481        // — that token is committed by the loop top as-is (spec_forced).
11482        let mut a = 0usize;
11483        let mut forced: Option<u32> = None;
11484        let ids: Vec<u32> = if sparse {
11485            let mut p = std::mem::take(&mut self.spec_ps);
11486            let mut res = std::mem::take(&mut self.spec_ress);
11487            while a < k_spec {
11488                let ok = sampler::sparse_distribution_into(
11489                    &logits[a * lm_rows..(a + 1) * lm_rows],
11490                    &cfg,
11491                    all_ids,
11492                    &mut self.sampler_scratch,
11493                    self.pool.as_deref(),
11494                    &mut p,
11495                );
11496                if !ok {
11497                    let t = sampler::argmax(&logits[a * lm_rows..(a + 1) * lm_rows]);
11498                    p.clear();
11499                    p.push((t, 1.0));
11500                }
11501                match sampler::spec_accept_or_correct_sparse(
11502                    &p,
11503                    &self.spec_qs[a],
11504                    drafts[a],
11505                    &mut self.rng,
11506                    &mut res,
11507                ) {
11508                    None => {
11509                        all_ids.push(drafts[a]);
11510                        a += 1;
11511                    }
11512                    Some(c) => {
11513                        forced = Some(c);
11514                        break;
11515                    }
11516                }
11517            }
11518            all_ids.truncate(base_len);
11519            self.spec_ps = p;
11520            self.spec_ress = res;
11521            drafts.clone()
11522        } else if sampling {
11523            let mut p = std::mem::take(&mut self.spec_p);
11524            let mut res = std::mem::take(&mut self.spec_res);
11525            while a < k_spec {
11526                sampler::distribution_into(
11527                    &logits[a * lm_rows..(a + 1) * lm_rows],
11528                    &cfg,
11529                    all_ids,
11530                    &mut self.sampler_scratch,
11531                    self.pool.as_deref(),
11532                    &mut p,
11533                );
11534                match sampler::spec_accept_or_correct(
11535                    &p,
11536                    &self.spec_q[a],
11537                    drafts[a],
11538                    &mut self.rng,
11539                    &mut res,
11540                    self.pool.as_deref(),
11541                ) {
11542                    None => {
11543                        all_ids.push(drafts[a]);
11544                        a += 1;
11545                    }
11546                    Some(c) => {
11547                        forced = Some(c);
11548                        break;
11549                    }
11550                }
11551            }
11552            all_ids.truncate(base_len);
11553            self.spec_p = p;
11554            self.spec_res = res;
11555            // the accepted drafts ARE the verified tokens after inputs 0..a
11556            drafts.clone()
11557        } else if greedy_pen {
11558            // Row i's penalized argmax, penalties over the stream that
11559            // includes the accepted drafts before it — the plain loop's
11560            // exact arithmetic, one pass per row, no working copy.
11561            let mut ids: Vec<u32> = Vec::with_capacity(b);
11562            for i in 0..b {
11563                let t = sampler::argmax_penalized(
11564                    &logits[i * lm_rows..(i + 1) * lm_rows],
11565                    &cfg,
11566                    all_ids,
11567                    &mut self.sampler_scratch,
11568                    self.pool.as_deref(),
11569                );
11570                ids.push(t);
11571                if i < k_spec && t == drafts[i] {
11572                    all_ids.push(t);
11573                } else {
11574                    break;
11575                }
11576            }
11577            all_ids.truncate(base_len);
11578            while a < k_spec && a < ids.len() && ids[a] == drafts[a] {
11579                a += 1;
11580            }
11581            // rows past the first mismatch were never scored; the loop
11582            // top re-samples the last verified row itself.
11583            ids
11584        } else if greedy_dev && dev_ids.len() == b {
11585            let ids = std::mem::take(&mut dev_ids);
11586            while a < k_spec && ids[a] == drafts[a] {
11587                a += 1;
11588            }
11589            ids
11590        } else {
11591            if logits.len() < b * lm_rows {
11592                // the device argmax was asked for and came back short:
11593                // no rows to fall back on — terminal like a failed batch
11594                self.clear_sequence_state();
11595                self.graph_failed
11596                    .store(true, std::sync::atomic::Ordering::Relaxed);
11597                self.cancel
11598                    .store(true, std::sync::atomic::Ordering::Relaxed);
11599                tracing::error!("Metal verify returned neither logits nor argmax ids");
11600                return None;
11601            }
11602            let ids: Vec<u32> = (0..b)
11603                .map(|i| sampler::argmax(&logits[i * lm_rows..(i + 1) * lm_rows]))
11604                .collect();
11605            while a < k_spec && ids[a] == drafts[a] {
11606                a += 1;
11607            }
11608            ids
11609        };
11610        spec_stamp("acc");
11611        if dflash_round {
11612            if let Some(log) = dflash_rows_log() {
11613                let mut rec = [u32::MAX; 24];
11614                (rec[0], rec[1], rec[2], rec[3]) = (next_pos as u32, t_next, k_spec as u32, a as u32);
11615                for (o, &d) in rec[4..11].iter_mut().zip(&drafts) {
11616                    *o = d;
11617                }
11618                for (o, &d) in rec[11..18].iter_mut().zip(&beside) {
11619                    *o = d;
11620                }
11621                // what a round of the chain's own would have added from the context
11622                let mut more: Vec<u32> = Vec::new();
11623                if beside.len() >= 2 && Self::spec_lookup_on() {
11624                    all_ids.extend_from_slice(&beside[..2]);
11625                    more = lookup_continuation(all_ids, 2 + LOOKUP_MIN_REAL, 5).to_vec();
11626                    all_ids.truncate(base_len);
11627                }
11628                rec[18] = more.len() as u32;
11629                for (o, &d) in rec[19..24].iter_mut().zip(&more) {
11630                    *o = d;
11631                }
11632                let mut bytes: Vec<u8> = rec.iter().flat_map(|v| v.to_le_bytes()).collect();
11633                bytes.extend(hidden.iter().flat_map(|v| v.to_le_bytes()));
11634                use std::io::Write as _;
11635                // the stream through the first logged round's first token, once:
11636                // a lookup reads the prompt, and the fit has to as well
11637                static IDS: std::sync::Once = std::sync::Once::new();
11638                IDS.call_once(|| {
11639                    if let Ok(path) = std::env::var("CMF_DFLASH_ROWS") {
11640                        let ids: Vec<u8> = all_ids.iter().flat_map(|v| v.to_le_bytes()).collect();
11641                        if let Err(e) = std::fs::write(format!("{path}.ids"), ids) {
11642                            tracing::warn!("CMF_DFLASH_ROWS: {path}.ids: {e}");
11643                        }
11644                    }
11645                });
11646                if let Ok(mut f) = log.lock() {
11647                    let _ = f.write_all(&bytes);
11648                }
11649            }
11650        }
11651        if spec_dbg {
11652            eprintln!(
11653                "spec-dbg round: t_next {t_next} drafts {:?} verified {:?} accepted {a}",
11654                drafts, ids
11655            );
11656        }
11657        // CMF_METAL_VERIFY_CHECK=2: the commit oracle — plain-forward the
11658        // a+1 accepted tokens from a snapshot, then diff the replayed GDN
11659        // states and the appended K/V rows against that.
11660        #[cfg(target_os = "macos")]
11661        let commit_ref: Option<(Vec<Vec<f32>>, Vec<(usize, Vec<f32>, Vec<f32>)>)> = if metal_native
11662            && std::env::var("CMF_METAL_VERIFY_CHECK").as_deref() == Ok("2")
11663        {
11664            let snap: Vec<Vec<f32>> = self
11665                .kv_cache
11666                .layers
11667                .iter()
11668                .map(|l| l.linear_state.clone())
11669                .collect();
11670            let attn_lens: Vec<usize> = self.kv_cache.layers.iter().map(|l| l.seq_len).collect();
11671            let toks: Vec<u32> = std::iter::once(t_next)
11672                .chain(drafts.iter().copied())
11673                .collect();
11674            let want_save = self.graph_want_logits;
11675            self.graph_want_logits = false;
11676            for (i, &t) in toks.iter().take(a + 1).enumerate() {
11677                let _ = self.forward_layers(&self.embed_single(t), next_pos + i, None);
11678                let _ = self.graph_logits.take();
11679            }
11680            self.graph_want_logits = want_save;
11681            let plain_states: Vec<Vec<f32>> = self
11682                .kv_cache
11683                .layers
11684                .iter()
11685                .map(|l| l.linear_state.clone())
11686                .collect();
11687            let (nkv, hd) = (self.num_kv_heads, self.head_dim);
11688            let mut rows = Vec::new();
11689            for (li, (l, n0)) in self
11690                .kv_cache
11691                .layers
11692                .iter_mut()
11693                .zip(attn_lens.iter())
11694                .enumerate()
11695            {
11696                let extra = l.seq_len.saturating_sub(*n0);
11697                if extra > 0 {
11698                    let mut kk = Vec::new();
11699                    let mut vv = Vec::new();
11700                    for g in 0..nkv {
11701                        kk.extend_from_slice(&l.head_keys(g)[n0 * hd..]);
11702                        vv.extend_from_slice(&l.head_values(g)[n0 * hd..]);
11703                    }
11704                    rows.push((li, kk, vv));
11705                    l.truncate_last(extra);
11706                    crate::gpu_metal::kv_mirror_set_stored(self.graph_kv_id, li, *n0);
11707                }
11708            }
11709            for (l, st) in self.kv_cache.layers.iter_mut().zip(snap) {
11710                if l.linear_state.len() == st.len() {
11711                    l.linear_state.copy_from_slice(&st);
11712                } else {
11713                    l.linear_state = st;
11714                }
11715            }
11716            Some((plain_states, rows))
11717        } else {
11718            None
11719        };
11720        let warm_off = std::env::var("CMF_SPEC_WARM").is_ok_and(|v| v == "0");
11721        // Metal: the MTP cache cut and the round's warm-up SUBMIT come
11722        // BEFORE the trunk commit, so the warm-up's command buffer is
11723        // queued ahead of the GDN replay (second queue) and its wait
11724        // below no longer sits behind the replay — measured: the warm-up's
11725        // wait grew with the accepted count exactly like the replay does
11726        // (8 ms at a=1, 17 ms at a=3, 25 ms at a=5 for ~2 ms of its own
11727        // work). The replay now overlaps the warm-up's readback, the
11728        // round's return and the next draft chain.
11729        #[cfg(target_os = "macos")]
11730        let mut warm_pending: Option<MetalWarmPending> = None;
11731        // The pairs the MTP cache has to hold of this round: the accepted
11732        // ones and, before them, the tip's own when the block was DFlash's
11733        // (an MTP chain's first step is that pair). The MTP block stays in
11734        // step through DFlash rounds, so either drafter can take the next.
11735        let hs_w = self.hidden_size;
11736        let warm_first = usize::from(mtp_steps == 0);
11737        let warm_n = if dflash_round && !mtp_in_step { 0 } else { a + warm_first };
11738        let warm_pos = next_pos - warm_first;
11739        let warm_pair = |j: usize| -> (&[f32], u32) {
11740            if j < warm_first {
11741                (hidden, t_next)
11742            } else {
11743                let j = j - warm_first;
11744                (&hiddens[j * hs_w..(j + 1) * hs_w], ids[j])
11745            }
11746        };
11747        #[cfg(target_os = "macos")]
11748        if metal_native {
11749            if mtp_steps > 0 {
11750                m.kv.truncate_last(mtp_steps - 1);
11751            }
11752            if self.mtp_graph_mode == Some(true) {
11753                // the mirror rows below the cut are the CPU rows: re-point,
11754                // no re-upload
11755                crate::gpu_metal::kv_mirror_set_stored(
11756                    self.mtp_kv_id(),
11757                    Self::MTP_LAYER_BASE,
11758                    m.kv.seq_len,
11759                );
11760                if !warm_off && warm_n > 0 {
11761                    let pairs: Vec<(&[f32], u32)> = (0..warm_n).map(&warm_pair).collect();
11762                    warm_pending = self.mtp_warm_batch_submit(m, &pairs, warm_pos);
11763                }
11764            }
11765            spec_stamp("c.wsub");
11766        }
11767        // a fully-accepted round needs no restore: every input was real.
11768        #[cfg(target_os = "macos")]
11769        if metal_native {
11770            // the Metal verify never wrote its states: the commit replays the
11771            // accepted prefix into the CPU owners and appends the K/V rows
11772            if !self.metal_verify_commit(a) {
11773                self.clear_sequence_state();
11774                self.graph_failed
11775                    .store(true, std::sync::atomic::Ordering::Relaxed);
11776                self.cancel
11777                    .store(true, std::sync::atomic::Ordering::Relaxed);
11778                tracing::error!("Metal verify state/KV handoff failed after admission");
11779                return None;
11780            }
11781            // the rows the round keeps are the drafter's next context
11782            if let (Some((pos0, rows)), Some(d)) = (self.dflash_rows.take(), self.dflash.as_mut()) {
11783                let tw = d.g.tap_width();
11784                d.queue_context(pos0, &rows[..(a + 1) * tw], self.pool.as_deref());
11785                spec_stamp("c.flash");
11786            }
11787            if let Some((plain_states, rows)) = commit_ref {
11788                crate::gpu_metal::queue_fence();
11789                // the commit's replay runs on the second queue: collect it
11790                // before the oracle reads the CPU owners it writes into
11791                let _ = crate::gpu_metal::wait_replay();
11792                let (nkv, hd) = (self.num_kv_heads, self.head_dim);
11793                let mut worst_s = 0f32;
11794                let mut worst_li = 0usize;
11795                for (li, (l, ps)) in self.kv_cache.layers.iter().zip(&plain_states).enumerate() {
11796                    if l.linear_state.len() != ps.len() || ps.is_empty() {
11797                        continue;
11798                    }
11799                    let d = l
11800                        .linear_state
11801                        .iter()
11802                        .zip(ps)
11803                        .fold(0f32, |m, (x, y)| m.max((x - y).abs()));
11804                    let n = ps.iter().fold(0f32, |m, y| m.max(y.abs()));
11805                    let rel = d / n.max(1e-6);
11806                    if rel > worst_s {
11807                        worst_s = rel;
11808                        worst_li = li;
11809                    }
11810                }
11811                let mut worst_k = 0f32;
11812                for (li, kk, vv) in &rows {
11813                    let l = &self.kv_cache.layers[*li];
11814                    let n0 = l.seq_len - (kk.len() / (nkv * hd));
11815                    let mut ck = Vec::new();
11816                    let mut cv = Vec::new();
11817                    for g in 0..nkv {
11818                        ck.extend_from_slice(&l.head_keys(g)[n0 * hd..]);
11819                        cv.extend_from_slice(&l.head_values(g)[n0 * hd..]);
11820                    }
11821                    if ck.len() == kk.len() {
11822                        let dk = ck
11823                            .iter()
11824                            .zip(kk)
11825                            .fold(0f32, |m, (x, y)| m.max((x - y).abs()));
11826                        let dv = cv
11827                            .iter()
11828                            .zip(vv)
11829                            .fold(0f32, |m, (x, y)| m.max((x - y).abs()));
11830                        worst_k = worst_k.max(dk).max(dv);
11831                    } else {
11832                        eprintln!(
11833                            "commit-check L{li}: kv row count mismatch {} vs {}",
11834                            ck.len(),
11835                            kk.len()
11836                        );
11837                    }
11838                }
11839                eprintln!(
11840                    "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}"
11841                );
11842            }
11843        }
11844        if !metal_native && a + 1 < b {
11845            let expected_gdn_layers = self.graph_gdn_layer_count();
11846            if expected_gdn_layers > 0
11847                && !crate::gpu::gdn_spec_restore(self.graph_kv_id, a, next_pos, expected_gdn_layers)
11848            {
11849                self.clear_sequence_state();
11850                self.graph_failed
11851                    .store(true, std::sync::atomic::Ordering::Relaxed);
11852                self.cancel
11853                    .store(true, std::sync::atomic::Ordering::Relaxed);
11854                tracing::error!("GDN speculative restore failed after verify");
11855                return None;
11856            }
11857        }
11858        if self.o1_active() && !crate::gpu::o1_spec_commit(self.graph_kv_id, next_pos, a + 1) {
11859            self.clear_sequence_state();
11860            self.graph_failed
11861                .store(true, std::sync::atomic::Ordering::Relaxed);
11862            self.cancel
11863                .store(true, std::sync::atomic::Ordering::Relaxed);
11864            tracing::error!("far field commit failed after verify");
11865            return None;
11866        }
11867        // the rows a wgpu verify kept for the drafter: those the round keeps
11868        // are its next context
11869        if !metal_native {
11870            let kept = self.dflash_taps.lock().unwrap().pop();
11871            if let (Some((pos0, rows)), Some(d)) = (kept, self.dflash.as_mut()) {
11872                let tw = d.g.tap_width();
11873                if pos0 == next_pos && rows.len() >= (a + 1) * tw {
11874                    d.queue_context(pos0, &rows[..(a + 1) * tw], self.pool.as_deref());
11875                }
11876            }
11877        }
11878        if !metal_native && !self.rewind_trunk_graph_mirrors(next_pos + a + 1) {
11879            // The verify graph committed the full batch, but one of its
11880            // persistent Full-attention mirrors could not be re-pointed to
11881            // the accepted prefix.  Treat that as terminal state failure;
11882            // an exact CPU fallback would otherwise consume stale GDN/KV.
11883            self.clear_sequence_state();
11884            self.graph_failed
11885                .store(true, std::sync::atomic::Ordering::Relaxed);
11886            self.cancel
11887                .store(true, std::sync::atomic::Ordering::Relaxed);
11888            tracing::error!("trunk graph KV rewind failed after speculative verify");
11889            return None;
11890        }
11891        *accepted += a;
11892        // MTP cache: keep the first draft row (its inputs were real), drop
11893        // the chain's, then append the verified pairs the round produced.
11894        // Each of those is a whole MTP block on the per-op path and they
11895        // cost 5.8 ms of a 69 ms round at k=3 — a third of what the
11896        // round's own draft costs. PRICED, and they earn it: skipping
11897        // them (`CMF_SPEC_WARM=0`) drops acceptance from 89% to 81% at
11898        // k=3 and 85% to 74% at k=4, and the tok/s goes nowhere at k=3
11899        // (50.3 against 50.5) and backwards at k=4 (48.1 against 50.1).
11900        // The knob stays so the next person can re-price it after the
11901        // warms are batched instead of assuming either way.
11902        if !metal_native && mtp_steps > 0 {
11903            // (Metal cut its MTP cache before the trunk commit, above)
11904            m.kv.truncate_last(mtp_steps - 1);
11905        }
11906        spec_stamp("c.trunc");
11907        // (the block's round put no row there: the mirror already ends where
11908        // the warm-up starts)
11909        if !metal_native
11910            && self.mtp_graph_mode == Some(true)
11911            && (mtp_steps > 0 || warm_n > 0)
11912            && !self.rewind_mtp_graph_mirror(warm_pos)
11913        {
11914            // The graph draft was admitted, so inability to move its cursor
11915            // back to the real anchor is a state failure, not a capability
11916            // refusal.  Do not warm or continue with a stale mirror.
11917            self.clear_sequence_state();
11918            self.graph_failed
11919                .store(true, std::sync::atomic::Ordering::Relaxed);
11920            self.cancel
11921                .store(true, std::sync::atomic::Ordering::Relaxed);
11922            tracing::error!("MTP graph mirror rewind failed after verify commit");
11923            return None;
11924        }
11925        if !warm_off && warm_n > 0 {
11926            // Graph arm: all accepted pairs in ONE batched run over the
11927            // MTP block; the token graph one by one if the batch declines.
11928            let mut warmed = false;
11929            #[cfg(target_os = "macos")]
11930            if metal_native && self.mtp_graph_mode == Some(true) {
11931                // the batched warm-up was submitted before the trunk
11932                // commit: collect it here; one by one on the token graph
11933                // if it declined (or failed)
11934                warmed = match warm_pending.take() {
11935                    Some(p) => self.mtp_warm_batch_finish(m, p),
11936                    None => false,
11937                };
11938                if !warmed {
11939                    warmed = true;
11940                    for j in 0..warm_n {
11941                        let (row, tok) = warm_pair(j);
11942                        let row = row.to_vec();
11943                        if self
11944                            .mtp_step_metal(m, &row, tok, warm_pos + j, false)
11945                            .is_none()
11946                        {
11947                            warmed = false;
11948                            break;
11949                        }
11950                    }
11951                }
11952            }
11953            if !warmed && self.mtp_graph_mode != Some(false) && !metal_native {
11954                let rows: Vec<(Vec<f32>, u32)> = (0..warm_n)
11955                    .map(|j| {
11956                        let (row, tok) = warm_pair(j);
11957                        (row.to_vec(), tok)
11958                    })
11959                    .collect();
11960                let pairs: Vec<(&[f32], u32)> = rows.iter().map(|(r, t)| (r.as_slice(), *t)).collect();
11961                match self.mtp_warm_prefill_pairs(m, &pairs, warm_pos) {
11962                    Ok(()) => warmed = true,
11963                    Err(err) => {
11964                        // A warm-up failure after graph admission cannot
11965                        // fall back to `mtp_warm`: the detached CPU cache is
11966                        // not authoritative for the device mirror.  Mark it
11967                        // terminal so the generation caller clears state and
11968                        // returns instead of drafting from stale attention.
11969                        tracing::error!("{err}");
11970                        self.clear_sequence_state();
11971                        self.graph_failed
11972                            .store(true, std::sync::atomic::Ordering::Relaxed);
11973                        self.cancel
11974                            .store(true, std::sync::atomic::Ordering::Relaxed);
11975                        return None;
11976                    }
11977                }
11978            }
11979            if !warmed {
11980                for j in 0..warm_n {
11981                    let (row, tok) = warm_pair(j);
11982                    let row = row.to_vec();
11983                    self.mtp_warm(m, &row, tok, warm_pos + j);
11984                }
11985            }
11986        }
11987        // The sampler's contract: logits of the LAST verified position —
11988        // unless a rejected draft already drew the correction, in which
11989        // case the loop top commits that token and samples nothing.
11990        spec_stamp("c.warm");
11991        if let Some(c) = forced {
11992            self.spec_forced = Some(c);
11993            self.graph_logits = None;
11994        } else if greedy_dev && logits.is_empty() {
11995            // the row's argmax IS the token the loop top would pick from
11996            // it (plain greedy, no penalties): commit it as forced
11997            self.spec_forced = Some(ids[a]);
11998            self.graph_logits = None;
11999        } else {
12000            let mut row = logits[a * lm_rows..(a + 1) * lm_rows].to_vec();
12001            row.resize(self.vocab_size, 0.0);
12002            if let Some(c) = self.final_softcap {
12003                for l in row.iter_mut() {
12004                    *l = c * (*l / c).tanh();
12005                }
12006            }
12007            self.graph_logits = Some(row);
12008        }
12009        let new_hidden = hiddens[a * self.hidden_size..(a + 1) * self.hidden_size].to_vec();
12010        spec_stamp("c.row");
12011        // Three phases, not two. The round's wall clock was 4 ms longer
12012        // than draft+verify and the difference had nowhere to be seen:
12013        // the accepted prefix re-runs the MTP block once per token to
12014        // keep the draft head's attention cache warm, and the GDN state
12015        // rolls back on any rejection. Both live here, after the verify.
12016        if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
12017            let end = subs();
12018            eprintln!(
12019                "spec-round: draft {:.1} ms/{} sub | verify {:.1} ms/{} sub | \
12020                 commit {:.1} ms/{} sub (accepted {a} of {k_spec}, full-head streak {})",
12021                t_draft.as_secs_f64() * 1e3,
12022                sub_draft - sub0,
12023                (t_verify - t_draft).as_secs_f64() * 1e3,
12024                sub_verify - sub_draft,
12025                (t_round.elapsed() - t_verify).as_secs_f64() * 1e3,
12026                end - sub_verify,
12027                self.draft_full_streak,
12028            );
12029        }
12030        // Native Metal's verify tile is flat in b (eight rows for the price
12031        // of one), so a shorter round only forfeits tokens — measured on
12032        // the M4: an essay round at k=2 still verified in 260 ms. The
12033        // adaptation is for cards whose verify grows with the rows.
12034        if k_spec > k_mtp {
12035            // a lookup's round: what it added over the head's own drafts
12036            let extra = a.saturating_sub(k_mtp) as f32;
12037            self.spec_lookup_gain += 0.2 * (extra - self.spec_lookup_gain);
12038            // a copy that holds whole earns the long window; a miss goes back
12039            self.spec_lookup_wide = a == k_spec;
12040            if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
12041                eprintln!(
12042                    "spec-lookup: {} drafts from the context, {extra} held (average {:.2})",
12043                    k_spec - k_mtp,
12044                    self.spec_lookup_gain
12045                );
12046            }
12047            if self.spec_lookup_gain < LOOKUP_PAYS {
12048                self.spec_lookup_rest = 24;
12049                self.spec_lookup_gain = 1.6;
12050            }
12051        }
12052        if metal_small && !k_capped {
12053            // (the chain's account stands as its last rounds on this text
12054            // left it while the block has the rounds: that is what the block
12055            // has to beat)
12056            if dflash_round {
12057                self.dflash_turn_sum.0 += (a + 1) as f32;
12058                self.dflash_turn_sum.1 += METAL_ROUND_COST[k_spec.clamp(1, 7) - 1] + DFLASH_ROUND_DRAFT;
12059            }
12060            let hold = if dflash_round { &mut self.dflash_hold } else { &mut self.spec_hold };
12061            spec_hold_update(hold, k_mtp, a.min(k_mtp));
12062            if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
12063                let next = metal_spec_plan(hold, if dflash_round { DFLASH_ROUND_DRAFT } else { 0.0 }).0;
12064                if next != k_mtp && k_env.is_none() {
12065                    eprintln!("spec-k: {k_mtp} → {next} (a draft holds after the last {hold:.2?})");
12066                }
12067            }
12068        }
12069
12070        if k_env.is_none() && !metal_native && !k_capped {
12071            // The depth is the drafter's own: a round the context lookup
12072            // lengthened (CUDA) adapts by the chain's drafts and what of them
12073            // held, and its wall (a longer verify) is not a depth's price.
12074            let lookup_round = k_spec > k_mtp;
12075            let (k_spec, a) = (k_mtp, a.min(k_mtp));
12076            // Slow average and a wide band: a fast one oscillated 2↔3 on
12077            // an essay every other round (measured), which forfeits the
12078            // draft it just paid for. Each drafter has its own depth.
12079            if cuda_rate && dflash_round && !k_capped {
12080                self.dflash_turn_sum.0 += (a + 1) as f32;
12081                self.dflash_turn_sum.1 += CUDA_ROUND_COST[k_spec.clamp(1, 7) - 1] + CUDA_BLOCK_DRAFT;
12082                spec_hold_update(&mut self.dflash_hold, k_spec, a.min(k_spec));
12083            }
12084            let (ewma, k_min) = if dflash_round { (&mut self.dflash_acc_ewma, 3) } else { (&mut self.spec_acc_ewma, 2) };
12085            let f = a as f32 / k_spec.max(1) as f32;
12086            *ewma += 0.2 * (f - *ewma);
12087            let mut k_next = k_spec;
12088            if *ewma >= 0.75 && k_spec < k_max {
12089                k_next = k_spec + 1;
12090            } else if *ewma < 0.4 && k_spec > k_min {
12091                k_next = k_spec - 1;
12092            }
12093            // The chain's rounds are timed by depth, and once two depths
12094            // are, the depth is the one that lands the most tokens in a unit
12095            // of time at this device's prices (`wgpu_spec_depth`): the share
12096            // of drafts kept climbs to five on text that holds whatever a
12097            // fifth row costs. A depth's first round pays its scratch and
12098            // is not counted; a change stands for six rounds.
12099            let mut planned = false;
12100            if !dflash_round && !lookup_round {
12101                spec_hold_update(&mut self.spec_hold, k_spec, a);
12102                let d = k_spec.clamp(1, 7) - 1;
12103                let w = t_round.elapsed().as_secs_f32() * 1e3;
12104                match self.spec_wall_n[d] {
12105                    0 => self.spec_wall_n[d] = 1,
12106                    1 => (self.spec_wall[d], self.spec_wall_n[d]) = (w, 2),
12107                    _ => self.spec_wall[d] += 0.2 * (w - self.spec_wall[d]),
12108                }
12109                if let Some(k_plan) = wgpu_spec_depth(&self.spec_hold, &self.spec_wall, k_spec, k_min, k_max) {
12110                    planned = true;
12111                    k_next = if self.spec_k_dwell > 0 {
12112                        self.spec_k_dwell -= 1;
12113                        k_spec
12114                    } else {
12115                        k_plan
12116                    };
12117                    if k_next != k_spec {
12118                        self.spec_k_dwell = 6;
12119                    }
12120                }
12121            }
12122            if k_next != k_spec {
12123                *ewma = 0.6;
12124                if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
12125                    if planned {
12126                        eprintln!(
12127                            "spec-k: {k_spec} → {k_next} (a round costs {:.0?} ms, a draft holds after the last {:.2?})",
12128                            self.spec_wall, self.spec_hold
12129                        );
12130                    } else {
12131                        eprintln!("spec-k: {k_spec} → {k_next}");
12132                    }
12133                }
12134            }
12135            if dflash_round {
12136                self.dflash_k_adapt = Some(k_next);
12137            } else {
12138                self.spec_k_adapt = Some(k_next);
12139            }
12140        }
12141        spec_stamp("end");
12142        Some((drafts[..a].to_vec(), next_pos + a + 1, new_hidden))
12143    }
12144
12145    /// A round's drafts from the DFlash drafter: the block behind the anchor
12146    /// `t_next` at `next_pos`, its first `k` tokens. The block reads the
12147    /// context the trunk's rows before `next_pos` left; the tokens come from
12148    /// the trunk's own head through the drafter's selector.
12149    fn dflash_draft(&mut self, t_next: u32, next_pos: usize, k: usize) -> Vec<u32> {
12150        let Some(mut d) = self.dflash.take() else {
12151            return Vec::new();
12152        };
12153        let (hs, rows) = (self.hidden_size, d.g.block);
12154        let mut h = vec![0f32; rows * hs];
12155        h[..hs].copy_from_slice(&self.embed_single(t_next));
12156        let mask = self.embed_single(d.g.mask_token);
12157        for r in 1..rows {
12158            h[r * hs..(r + 1) * hs].copy_from_slice(&mask);
12159        }
12160        // A trunk that scales its embeddings on the way in (Ripple): the
12161        // block reads the table's rows as they are (`CMF_DFLASH_EMBED=scaled`
12162        // hands it the trunk's input rows).
12163        if self.embed_multiplier != 1.0 && std::env::var("CMF_DFLASH_EMBED").as_deref() != Ok("scaled") {
12164            let inv = 1.0 / self.embed_multiplier;
12165            h.iter_mut().for_each(|v| *v *= inv);
12166        }
12167        let pool = self.pool.as_deref();
12168        let t0 = std::time::Instant::now();
12169        d.settle(pool);
12170        spec_stamp("d.ctx");
12171        let t_ctx = t0.elapsed();
12172        // the block, the head and the selector's projection as one
12173        // submission on wgpu; the host block below where it declines
12174        #[cfg(feature = "gpu")]
12175        if let Some((logits, hp)) = d.block_dev(next_pos, &h, k.min(rows - 1), &self.weights.lm_head) {
12176            spec_stamp("d.block");
12177            let t_block = t0.elapsed();
12178            let n = k.min(rows - 1);
12179            let (mut ids, _) = d.select_with(&hp, &logits, t_next, n);
12180            ids.truncate(k);
12181            // `CMF_DFLASH_DEV_CHECK=1`: the host block on the same rows, and
12182            // how far the device's logits, selector rows and drafts are from it
12183            if std::env::var_os("CMF_DFLASH_DEV_CHECK").is_some() {
12184                let out = d.block(next_pos, h.clone(), pool);
12185                let head = &self.weights.lm_head;
12186                let mut hl = vec![0f32; n * head.rows()];
12187                head.matmat(&out[hs..(n + 1) * hs], n, &mut hl, pool);
12188                // the device may score only the head's first rows (CUDA: the shortlist)
12189                let width = logits.len() / n.max(1);
12190                let hl: Vec<f32> = (0..n).flat_map(|j| hl[j * head.rows()..j * head.rows() + width].to_vec()).collect();
12191                let (hids, _) = d.select(&out[hs..(n + 1) * hs], &hl, t_next);
12192                let (mut dmax, mut ref_max, mut dsum, mut cnt) = (0f32, 0f32, 0f64, 0usize);
12193                for (a, b) in logits.iter().zip(&hl) {
12194                    dmax = dmax.max((a - b).abs());
12195                    ref_max = ref_max.max(b.abs());
12196                    dsum += ((a - b) * (a - b)) as f64;
12197                    cnt += 1;
12198                }
12199                let arg = |v: &[f32]| (0..n).map(|j| sampler::argmax(&v[j * width..(j + 1) * width])).collect::<Vec<u32>>();
12200                eprintln!(
12201                    "dflash-dev-check: logits max|Δ| {dmax:.4} of max {ref_max:.2}, rms Δ {:.5} | argmax device {:?} host {:?} | drafts device {:?} host {:?}",
12202                    (dsum / cnt.max(1) as f64).sqrt(),
12203                    arg(&logits),
12204                    arg(&hl),
12205                    ids,
12206                    &hids[..k.min(hids.len())]
12207                );
12208            }
12209            if self.dflash_solo && spec_time_level() > 0 {
12210                eprintln!(
12211                    "solo-draft: context {:.1} ms | device block + head {:.1} ms | selector {:.1} ms",
12212                    t_ctx.as_secs_f64() * 1e3,
12213                    (t_block - t_ctx).as_secs_f64() * 1e3,
12214                    (t0.elapsed() - t_block).as_secs_f64() * 1e3
12215                );
12216            }
12217            spec_stamp("d.head");
12218            self.dflash = Some(d);
12219            return ids;
12220        }
12221        let out = d.block(next_pos, h, pool);
12222        spec_stamp("d.block");
12223        let t_block = t0.elapsed();
12224        // the head over the round's shortlist of the vocabulary, as the MTP
12225        // draft has it (the full head while `draft_full_streak` runs). The
12226        // shortlist is the low ids of Qwen's vocabulary: a trunk with another
12227        // tokenizer (`dflash_solo`) scores the whole head.
12228        let (n, head) = (rows - 1, &self.weights.lm_head);
12229        let width = if self.dflash_solo { head.rows() } else { self.draft_head_rows(head.rows()) };
12230        let mut logits = vec![0f32; n * width];
12231        // the block's rows on the narrow kernel; any other head as a batch
12232        let narrow = head.mapped_q4tp().is_some_and(|(m, idx)| {
12233            crate::gpu::q4tp_rows8_many(m, &[(idx, head.rows(), head.cols(), width)], &out[hs..], n, &mut [&mut logits[..]])
12234        });
12235        if !narrow {
12236            logits = vec![0f32; n * head.rows()];
12237            if !head.device_matmat(&out[hs..], n, &mut logits) {
12238                head.matmat(&out[hs..], n, &mut logits, pool);
12239            }
12240        }
12241        spec_stamp("d.head");
12242        let t_head = t0.elapsed();
12243        let (mut ids, _) = d.select(&out[hs..], &logits, t_next);
12244        ids.truncate(k);
12245        if self.dflash_solo && spec_time_level() > 0 {
12246            eprintln!(
12247                "solo-draft: context {:.1} ms | block {:.1} ms | head {:.1} ms | selector {:.1} ms",
12248                t_ctx.as_secs_f64() * 1e3,
12249                (t_block - t_ctx).as_secs_f64() * 1e3,
12250                (t_head - t_block).as_secs_f64() * 1e3,
12251                (t0.elapsed() - t_head).as_secs_f64() * 1e3
12252            );
12253        }
12254        if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() && d.next_position() != next_pos {
12255            eprintln!("dflash: the context ends at {} for a block at {next_pos}", d.next_position());
12256        }
12257        self.dflash = Some(d);
12258        ids
12259    }
12260
12261    /// A speculative round of a trunk that has no draft block of its own.
12262    /// The drafts are the DFlash sidecar's block behind the tip `t_next` (or
12263    /// the next ids of `CMF_SPEC_SCRIPT`); the batch graph verifies them with
12264    /// the tip in one submission, and the cache keeps the rows of the drafts
12265    /// that held and of the tip. None: no round was made (plain greedy goes
12266    /// on), or the graph failed after admission (`graph_failed` is set).
12267    #[cfg(feature = "gpu")]
12268    fn solo_spec_round(&mut self, t_next: u32, next_pos: usize, all_ids: &[u32], k: usize) -> Option<SoloRound> {
12269        self.dflash_taps_absorb();
12270        let t0 = std::time::Instant::now();
12271        let drafts: Vec<u32> = match solo_script() {
12272            Some(script) => script.iter().skip(all_ids.len()).take(k).copied().collect(),
12273            None => {
12274                if self.dflash.as_ref().is_none_or(|d| d.next_position() != next_pos) {
12275                    return None;
12276                }
12277                self.dflash_draft(t_next, next_pos, k)
12278            }
12279        };
12280        if drafts.is_empty() {
12281            return None;
12282        }
12283        let t_draft = t0.elapsed();
12284        let (b, hs) = (drafts.len() + 1, self.hidden_size);
12285        let mut hiddens = vec![0f32; b * hs];
12286        for (i, &t) in std::iter::once(&t_next).chain(drafts.iter()).enumerate() {
12287            hiddens[i * hs..(i + 1) * hs].copy_from_slice(&self.embed_single(t));
12288        }
12289        let positions: Vec<usize> = (next_pos..next_pos + b).collect();
12290        let (lm_gw, lm_rows) = {
12291            let (_, i, kind, rs) = self.weights.lm_head.graph_weight()?;
12292            (
12293                crate::gpu::GraphW { idx: i, kind, row_scale: rs, data: &[], prism: crate::gpu::GraphPrismOp::None, affine: false },
12294                self.weights.lm_head.rows(),
12295            )
12296        };
12297        let mut logits = Vec::new();
12298        let final_norm = self.weights.final_norm.clone();
12299        let outcome = self.try_batch_graph_wgpu(
12300            &mut hiddens,
12301            &positions,
12302            b,
12303            Some(crate::gpu::SpecTail { lm: lm_gw, lm_rows, final_norm: &final_norm, logits_out: &mut logits, pick: None }),
12304        );
12305        let fail = |p: &mut Self, what: &str| {
12306            p.clear_sequence_state();
12307            p.graph_failed.store(true, std::sync::atomic::Ordering::Relaxed);
12308            p.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
12309            tracing::error!("{what}");
12310        };
12311        match outcome {
12312            crate::gpu::BatchGraphOutcome::Completed if logits.len() >= b * lm_rows => {}
12313            crate::gpu::BatchGraphOutcome::Declined => return None,
12314            _ => {
12315                fail(self, "the verify of a speculative round failed after admission");
12316                return None;
12317            }
12318        }
12319        let t_verify = t0.elapsed();
12320        // row i's argmax is the trunk's token after input i
12321        let ids: Vec<u32> = (0..b).map(|i| sampler::argmax(&logits[i * lm_rows..(i + 1) * lm_rows])).collect();
12322        let mut a = 0usize;
12323        while a < drafts.len() && ids[a] == drafts[a] {
12324            a += 1;
12325        }
12326        if std::env::var_os("CMF_SPEC_DBG").is_some() {
12327            eprintln!(
12328                "solo-dbg: tip {t_next} at {next_pos} | context {:?} | drafts {drafts:?} | the trunk's {ids:?} | kept {a}",
12329                self.dflash.as_ref().map(|d| d.span())
12330            );
12331        }
12332        if self.o1_active() && !crate::gpu::o1_spec_commit(self.graph_kv_id, next_pos, a + 1) {
12333            fail(self, "far field commit failed after a speculative round");
12334            return None;
12335        }
12336        // a hybrid trunk (Arete-27B, no draft block of its own): its GDN
12337        // states back to the rows the round kept, as after a chain's round
12338        if a + 1 < b {
12339            let gdn = self.graph_gdn_layer_count();
12340            if gdn > 0 && !crate::gpu::gdn_spec_restore(self.graph_kv_id, a, next_pos, gdn) {
12341                fail(self, "GDN restore failed after a speculative round");
12342                return None;
12343            }
12344        }
12345        // the rows the round keeps are the drafter's next context
12346        let kept = self.dflash_taps.lock().unwrap().pop();
12347        if let (Some((pos0, rows)), Some(d)) = (kept, self.dflash.as_mut()) {
12348            let tw = d.g.tap_width();
12349            if pos0 == next_pos && rows.len() >= (a + 1) * tw {
12350                d.queue_context(pos0, &rows[..(a + 1) * tw], self.pool.as_deref());
12351            }
12352        }
12353        if !self.rewind_trunk_graph_mirrors(next_pos + a + 1) {
12354            fail(self, "trunk graph KV rewind failed after a speculative round");
12355            return None;
12356        }
12357        let mut row = logits[a * lm_rows..(a + 1) * lm_rows].to_vec();
12358        row.resize(self.vocab_size, 0.0);
12359        if let Some(c) = self.final_softcap {
12360            for l in row.iter_mut() {
12361                *l = c * (*l / c).tanh();
12362            }
12363        }
12364        if spec_time_level() > 0 {
12365            eprintln!(
12366                "solo-round: draft {:.1} ms | verify {:.1} ms | commit {:.1} ms | kept {a} of {}",
12367                t_draft.as_secs_f64() * 1e3,
12368                (t_verify - t_draft).as_secs_f64() * 1e3,
12369                (t0.elapsed() - t_verify).as_secs_f64() * 1e3,
12370                drafts.len()
12371            );
12372        }
12373        Some(SoloRound { accepted: drafts[..a].to_vec(), drafted: drafts.len(), hidden: hiddens[a * hs..(a + 1) * hs].to_vec(), logits: row })
12374    }
12375
12376    /// Micro-benchmark: two single-position forwards vs one fused pair
12377    /// from the current cache state (KV rewound after each probe).
12378    /// Returns (two_singles_ms, fused_pair_ms) per probe, or the (0, 0)
12379    /// sentinel when this model has no pair path to measure — the same
12380    /// answer the o1 arm gives, and the bench prints it the same way.
12381    /// (An architecture that loads its own layers leaves `weights.layers`
12382    /// empty; walking it here was an index panic, found by `bench` on
12383    /// deepseek_v4.)
12384    pub fn measure_pair_fusion(&mut self, iters: usize) -> (f64, f64) {
12385        if !self.pair_supported() {
12386            return (0.0, 0.0);
12387        }
12388        // A GDN model that needs an automatic device prefix never uses this
12389        // fused-pair path in normal generation: its recurrence is serial and
12390        // the speculative pair is disabled by default.  More importantly,
12391        // this diagnostic suppresses the token graph, so measuring it would
12392        // stream the non-resident tail through per-op Vulkan just to print a
12393        // non-production number.  Leave inference untouched and report the
12394        // established unavailable sentinel instead.
12395        if self.gdn_cfg.is_some()
12396            && self.graph_prefill_preferred()
12397            && self.automatic_gpu_prefix().is_some()
12398        {
12399            tracing::info!(
12400                "pair micro-benchmark skipped: GDN device-prefix path has no production pair route"
12401            );
12402            return (0.0, 0.0);
12403        }
12404        // Routed experts past the card live in the graphs' placement only
12405        // (system-memory banks under card slots): per op they run on the
12406        // host and the matrices' device copies outgrow the card (MiniMax-M3.1
12407        // on a whole A40: out of memory before the timed run).
12408        #[cfg(feature = "gpu")]
12409        let past = crate::gpu_wgpu::experts_past_card();
12410        #[cfg(not(feature = "gpu"))]
12411        let past = false;
12412        #[cfg(feature = "cuda")]
12413        let past = past || crate::gpu_cuda::experts_streamed();
12414        if past {
12415            tracing::info!("pair micro-benchmark skipped: routed experts past the card have no per-op route");
12416            return (0.0, 0.0);
12417        }
12418        // This is a host-side pair micro-benchmark. It truncates the host KV
12419        // after every probe, so letting the whole-token graph participate
12420        // would leave its device GDN/KV mirror ahead of the next probe and
12421        // poison the process-wide graph verdict before the real generation
12422        // benchmark starts. Keep the existing per-op/GPU arithmetic while
12423        // suppressing only the stateful token graph for this measurement.
12424        let graph_env = std::env::var_os("CMF_GPU_WGPU_GRAPH");
12425        unsafe { std::env::set_var("CMF_GPU_WGPU_GRAPH", "0") };
12426        let emb1 = self.embed_single(1);
12427        let emb2 = self.embed_single(2);
12428        let pos = self.kv_cache.seq_len();
12429
12430        let t0 = std::time::Instant::now();
12431        for _ in 0..iters {
12432            let _ = self.forward_layers(&emb1, pos, None);
12433            let _ = self.forward_layers(&emb2, pos + 1, None);
12434            for l in &mut self.kv_cache.layers {
12435                l.truncate_last(2);
12436            }
12437        }
12438        let singles_ms = t0.elapsed().as_secs_f64() * 1000.0 / iters as f64;
12439
12440        let t1 = std::time::Instant::now();
12441        for _ in 0..iters {
12442            let _ = self.forward_pair(&emb1, &emb2, pos);
12443            for l in &mut self.kv_cache.layers {
12444                l.truncate_last(2);
12445            }
12446        }
12447        let pair_ms = t1.elapsed().as_secs_f64() * 1000.0 / iters as f64;
12448        match graph_env {
12449            Some(value) => unsafe { std::env::set_var("CMF_GPU_WGPU_GRAPH", value) },
12450            None => unsafe { std::env::remove_var("CMF_GPU_WGPU_GRAPH") },
12451        }
12452        (singles_ms, pair_ms)
12453    }
12454
12455    /// Fused two-position forward: weight rows are streamed from memory
12456    /// once per layer for both positions. Full layers → fused GQA pair;
12457    /// linear layers → vmf_phase pair (lane 2 state is tentative in the
12458    /// per-layer scratch until the draft is accepted).
12459    /// Whether the fused two-position path covers every layer kind in
12460    /// this model. MLA and KDA run per position (their pair arms are
12461    /// unreachable); the seq prefill falls back to singles for them.
12462    fn pair_supported(&self) -> bool {
12463        // An EMPTY layer stack means the architecture loaded its own and
12464        // this path has nothing to walk. Checking that directly, rather
12465        // than naming each such architecture, is what makes the guard hold
12466        // for the next one: `any()` over no layers is false, so a
12467        // feature-by-feature test says "supported" for a model that has no
12468        // layers here at all.
12469        !self.weights.layers.is_empty()
12470            && !self.per_token_stack()
12471            && !self
12472                .weights
12473                .layers
12474                .iter()
12475                .any(|lw| matches!(&lw.attn, AttnKind::Mla(_) | AttnKind::Kda(_)))
12476    }
12477
12478    fn forward_pair(
12479        &mut self,
12480        emb1: &[f32],
12481        emb2: &[f32],
12482        position: usize,
12483    ) -> (Vec<f32>, Vec<f32>) {
12484        // A two-token prompt starts here, not in the layer walk: decide the
12485        // MiMo placement before the pair's per-op MoE uploads any expert.
12486        self.mimo_moe_prepare();
12487        let mut h1 = emb1.to_vec();
12488        let mut h2 = emb2.to_vec();
12489        if self.value_blend.is_some() {
12490            self.vres_e0.clear();
12491            self.vres_e0.extend_from_slice(emb1);
12492            self.vres_e0.extend_from_slice(emb2);
12493        }
12494        let (_nkv, _hd, hs, _rd, eps) = (
12495            self.num_kv_heads,
12496            self.head_dim,
12497            self.hidden_size,
12498            self.rotary_dim,
12499            self.rms_eps,
12500        );
12501        let pool = self.pool.clone();
12502        // `forward_pair` bypasses `forward_layers_span`, but its per-op
12503        // body must still obey the ordinary layer placement. In particular,
12504        // an over-capacity Vulkan model has a device prefix and a CPU tail;
12505        // letting the pair walk submit the tail's selected MoE experts would
12506        // stream the whole tail through the residency arena and defeat the
12507        // measured VRAM bound.
12508        let automatic_gpu_prefix = self.automatic_gpu_prefix();
12509
12510        for li in 0..self.num_layers {
12511            let _capacity_tail = automatic_gpu_prefix
12512                .filter(|&prefix| li >= prefix && !self.mimo_moe.is_dynamic(li, false))
12513                .map(|_| crate::gpu::enter_cpu_scope());
12514            // Also makes an explicit CMF_GPU_LAYERS split apply to fused
12515            // pairs, just as it does to the ordinary layer walk.
12516            crate::gpu::set_layer(li as i64);
12517            let lw = &self.weights.layers[self.phys_layer(li)];
12518            // Norms into pipeline scratch (4 allocs/layer on the MTP
12519            // decode hot path before this).
12520            inference::rms_norm_into(
12521                &h1,
12522                &lw.input_norm,
12523                self.rms_eps,
12524                self.norm_style,
12525                &mut self.ws.n1,
12526            );
12527            inference::rms_norm_into(
12528                &h2,
12529                &lw.input_norm,
12530                self.rms_eps,
12531                self.norm_style,
12532                &mut self.ws.n2,
12533            );
12534            // The two rows V projects, when the layer blends the embeddings into them.
12535            let vres = match self.layer_value_blend(li) {
12536                Some(blend) => {
12537                    let mut second = Vec::new();
12538                    vres_lerp(&self.vres_e0[..hs], &self.ws.n1, blend, &mut self.vres_in);
12539                    vres_lerp(&self.vres_e0[hs..], &self.ws.n2, blend, &mut second);
12540                    self.vres_in.extend_from_slice(&second);
12541                    true
12542                }
12543                None => false,
12544            };
12545
12546            let (a1, a2) = match &lw.attn {
12547                AttnKind::Mla(_) => unreachable!("MLA has no MTP/pair path"),
12548                AttnKind::Kda(_) => unreachable!("KDA has no MTP/pair path"),
12549                AttnKind::Bounded(w) => {
12550                    // Two sequential positions of the bounded operator
12551                    // (the ring's causal order is the pair's order).
12552                    let rope = self
12553                        .bounded_rope
12554                        .clone()
12555                        .expect("bounded layer without an installed rotation table");
12556                    let cfg = crate::bounded::BoundedAttnCfg {
12557                        num_heads: self.num_heads,
12558                        num_kv_heads: self.num_kv_heads,
12559                        head_dim: self.head_dim,
12560                        hidden_size: hs,
12561                        scale: self.attn_scale,
12562                        rope: &rope,
12563                        pool: pool.as_deref(),
12564                    };
12565                    let a1 = crate::bounded::bounded_attention(
12566                        &self.ws.n1,
12567                        w,
12568                        &mut self.kv_cache.layers[li],
12569                        &cfg,
12570                    );
12571                    let a2 = crate::bounded::bounded_attention(
12572                        &self.ws.n2,
12573                        w,
12574                        &mut self.kv_cache.layers[li],
12575                        &cfg,
12576                    );
12577                    (a1, a2)
12578                }
12579                AttnKind::Linear(w) => {
12580                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
12581                    let layer = &mut self.kv_cache.layers[li];
12582                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
12583                    vmf_phase_pair(
12584                        &self.ws.n1,
12585                        &self.ws.n2,
12586                        w,
12587                        &cfg,
12588                        state,
12589                        scratch,
12590                        self.pool.as_deref(),
12591                    )
12592                }
12593                AttnKind::LinearGdn(w) => {
12594                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
12595                    let layer = &mut self.kv_cache.layers[li];
12596                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
12597                    gdn_pair(
12598                        &self.ws.n1,
12599                        &self.ws.n2,
12600                        w,
12601                        &cfg,
12602                        state,
12603                        scratch,
12604                        self.pool.as_deref(),
12605                    )
12606                }
12607                AttnKind::ShortConv(w) => {
12608                    let cfg = self
12609                        .short_conv_cfg
12610                        .expect("short-conv layer without short_conv_cfg");
12611                    let layer = &mut self.kv_cache.layers[li];
12612                    let (state, scratch) = (&mut layer.linear_state, &mut layer.linear_scratch);
12613                    short_conv_pair(
12614                        &self.ws.n1,
12615                        &self.ws.n2,
12616                        w,
12617                        &cfg,
12618                        state,
12619                        scratch,
12620                        self.pool.as_deref(),
12621                    )
12622                }
12623                AttnKind::Full {
12624                    wq,
12625                    wk,
12626                    wv,
12627                    wo,
12628                    q_norm,
12629                    k_norm,
12630                    output_gate,
12631                    softplus_gate,
12632                    bias,
12633                } => {
12634                    let inv_freq_l = self.layer_inv_freq(li);
12635                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
12636                    let cfg = QwenAttnCfg {
12637                        mrope: None,
12638                        num_heads: self.layer_num_heads(li),
12639                        num_kv_heads: nkv_l,
12640                        head_dim: hd_l,
12641                        hidden_size: hs,
12642                        position,
12643                        inv_freq: &inv_freq_l,
12644                        rotary_dim: rd_l,
12645                        scale: self.attn_scale,
12646                        softcap: self.attn_softcap,
12647                        window: self.layer_window(li),
12648                        v_norm: self.attn_v_norm,
12649                        qk_norm_after_rope: self.qk_norm_after_rope,
12650                        gate_sigmoid: self.proj_gate_sigmoid,
12651                        q_norm: q_norm.as_deref(),
12652                        k_norm: k_norm.as_deref(),
12653                        output_gate: *output_gate,
12654                        softplus_gate: softplus_gate
12655                            .as_ref()
12656                            .map(|(gate, per_head)| (gate, *per_head)),
12657                        rope_scale: self.layer_rope_scale(li),
12658                        bias: bias
12659                            .as_ref()
12660                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
12661                        rms_eps: eps,
12662                        norm_style: self.norm_style,
12663                        pool: pool.as_deref(),
12664                        v_head_dim: self.layer_v_dim(li),
12665                        value_in: vres.then(|| self.vres_in.as_slice()),
12666                    };
12667                    attention::qwen_attention_pair(
12668                        &self.ws.n1,
12669                        &self.ws.n2,
12670                        wq,
12671                        wk,
12672                        wv,
12673                        wo,
12674                        &mut self.kv_cache.layers[li],
12675                        &cfg,
12676                    )
12677                }
12678            };
12679            let (a1, a2) = match &self.weights.layers[self.phys_layer(li)].attn_out_norm {
12680                Some(w) => (
12681                    inference::rms_norm(&a1, w, self.rms_eps, self.norm_style),
12682                    inference::rms_norm(&a2, w, self.rms_eps, self.norm_style),
12683                ),
12684                None => (a1, a2),
12685            };
12686            for i in 0..self.hidden_size {
12687                h1[i] += a1[i];
12688                h2[i] += a2[i];
12689            }
12690            let (mut a1, mut a2) = (a1, a2);
12691            attention::recycle_buf(&mut a1);
12692            attention::recycle_buf(&mut a2);
12693
12694            let lw = &self.weights.layers[self.phys_layer(li)];
12695            inference::rms_norm_into(
12696                &h1,
12697                &lw.post_norm,
12698                self.rms_eps,
12699                self.norm_style,
12700                &mut self.ws.p1,
12701            );
12702            inference::rms_norm_into(
12703                &h2,
12704                &lw.post_norm,
12705                self.rms_eps,
12706                self.norm_style,
12707                &mut self.ws.p2,
12708            );
12709            let (f1, f2) = match &lw.ffn {
12710                // Dual-branch layers need the raw residuals — run the
12711                // two positions through the same fn decode uses.
12712                FfnKind::DenseMoe(dm) => (
12713                    dense_moe_ffn(
12714                        dm,
12715                        &self.ws.p1,
12716                        &h1,
12717                        self.rms_eps,
12718                        self.norm_style,
12719                        self.pool.as_deref(),
12720                    ),
12721                    dense_moe_ffn(
12722                        dm,
12723                        &self.ws.p2,
12724                        &h2,
12725                        self.rms_eps,
12726                        self.norm_style,
12727                        self.pool.as_deref(),
12728                    ),
12729                ),
12730                FfnKind::Moe(m) if self.mimo_moe.is_dynamic(li, false) => (
12731                    moe_ffn_banked(&mut self.mimo_moe, li, m, &self.ws.p1, self.pool.as_deref()),
12732                    moe_ffn_banked(&mut self.mimo_moe, li, m, &self.ws.p2, self.pool.as_deref()),
12733                ),
12734                _ => ffn_forward_pair(
12735                    &lw.ffn,
12736                    &self.ws.p1,
12737                    &self.ws.p2,
12738                    self.pool.as_deref(),
12739                    None,
12740                ),
12741            };
12742            let (f1, f2) = match &self.weights.layers[self.phys_layer(li)].ffn_out_norm {
12743                Some(w) => (
12744                    inference::rms_norm(&f1, w, self.rms_eps, self.norm_style),
12745                    inference::rms_norm(&f2, w, self.rms_eps, self.norm_style),
12746                ),
12747                None => (f1, f2),
12748            };
12749            for i in 0..self.hidden_size {
12750                h1[i] += f1[i];
12751                h2[i] += f2[i];
12752            }
12753            let (mut f1, mut f2) = (f1, f2);
12754            attention::recycle_buf(&mut f1);
12755            attention::recycle_buf(&mut f2);
12756            if let Some(sc) = self.weights.layers[self.phys_layer(li)].layer_scale {
12757                for i in 0..self.hidden_size {
12758                    h1[i] *= sc;
12759                    h2[i] *= sc;
12760                }
12761            }
12762            // Looped Transformer: apply final norm at the end of each loop iteration.
12763            if self.is_loop_end(li) && li + 1 < self.num_layers {
12764                h1 = inference::rms_norm(
12765                    &h1,
12766                    &self.weights.final_norm,
12767                    self.rms_eps,
12768                    self.norm_style,
12769                );
12770                h2 = inference::rms_norm(
12771                    &h2,
12772                    &self.weights.final_norm,
12773                    self.rms_eps,
12774                    self.norm_style,
12775                );
12776            }
12777        }
12778        crate::gpu::set_layer(-1); // final/O(1) work is outside layer placement
12779        // Real O(1) prefill pairs may also carry tentative lane-2 recurrent
12780        // state. Commit it before publishing the transition epoch so the
12781        // next serial/device row cannot observe a new attention epoch with an
12782        // old GDN state. Speculative pairs run only when O(1) is inactive and
12783        // retain their existing caller-controlled commit/rollback semantics.
12784        if self.o1_active() {
12785            self.commit_linear_scratch();
12786        }
12787        self.o1_progress();
12788        self.swa_trim_tails();
12789        (h1, h2)
12790    }
12791
12792    /// Commit lane-2 linear states after an accepted draft.
12793    fn commit_linear_scratch(&mut self) {
12794        for layer in &mut self.kv_cache.layers {
12795            if !layer.linear_scratch.is_empty() {
12796                std::mem::swap(&mut layer.linear_state, &mut layer.linear_scratch);
12797                layer.linear_scratch.clear();
12798            }
12799        }
12800    }
12801
12802    /// This is the encoder counterpart to `forward_ids`: it runs a fresh
12803    /// sequence through the existing full/GDN hybrid stack and returns the
12804    /// final RMS-normalized hidden row for *every* token.  It is used by
12805    /// component pipelines whose text tower intentionally has no LM head
12806    /// (such as an image-conditioner Qwen3.5 model).  The sequence state is
12807    /// always released before returning, so a large text tower can be dropped
12808    /// immediately after conditioning a subsequent stage.
12809    pub fn encode_hidden_states(&mut self, ids: &[u32]) -> 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
12816        self.nll_begin()?;
12817        let result = (|| {
12818            let hidden = self.prefill_input_rows(PrefillIn::Ids(ids), 0, None)?;
12819            self.nll_check_graph("encoder prefill", 0)?;
12820            let expected = ids.len() * self.hidden_size;
12821            if hidden.len() != expected {
12822                return Err(format!(
12823                    "encoder prefill returned {} values for {} rows of hidden size {}",
12824                    hidden.len(),
12825                    ids.len(),
12826                    self.hidden_size
12827                ));
12828            }
12829
12830            let mut out = vec![0.0f32; expected];
12831            for (src, dst) in hidden
12832                .chunks_exact(self.hidden_size)
12833                .zip(out.chunks_exact_mut(self.hidden_size))
12834            {
12835                inference::rms_norm_into(
12836                    src,
12837                    &self.weights.final_norm,
12838                    self.rms_eps,
12839                    self.norm_style,
12840                    dst,
12841                );
12842            }
12843            Ok(out)
12844        })();
12845        self.nll_end();
12846        result
12847    }
12848
12849    /// The last layer's hidden row (before the final norm) for every token
12850    /// of `ids`, from a fresh sequence, through the whole-stack prefill (the
12851    /// device chunk graph where there is one) — what a distillation cache of
12852    /// teacher outputs needs, at prefill speed.
12853    pub fn final_hidden_rows(&mut self, ids: &[u32]) -> Result<Vec<f32>, String> {
12854        #[cfg(target_os = "macos")]
12855        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
12856        if ids.is_empty() {
12857            return Err("empty id sequence".to_string());
12858        }
12859        self.nll_begin()?;
12860        let result = (|| {
12861            let hidden = self.prefill_input_rows(PrefillIn::Ids(ids), 0, None)?;
12862            self.nll_check_graph("hidden prefill", 0)?;
12863            if hidden.len() != ids.len() * self.hidden_size {
12864                return Err(format!("hidden prefill returned {} values for {} rows", hidden.len(), ids.len()));
12865            }
12866            Ok(hidden)
12867        })();
12868        self.nll_end();
12869        result
12870    }
12871
12872    /// Forward a full id sequence from a fresh cache and return the
12873    /// logits after the last position (golden-parity harness, bench).
12874    pub fn forward_ids(
12875        &mut self,
12876        ids: &[u32],
12877        task_mask: Option<&TaskMask>,
12878    ) -> Result<Vec<f32>, String> {
12879        #[cfg(target_os = "macos")]
12880        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
12881        if ids.is_empty() {
12882            return Err("empty id sequence".to_string());
12883        }
12884        self.clear_sequence_state();
12885        self.check_forward_graph("forward_ids setup", 0)?;
12886        if task_mask.is_none() {
12887            self.o1_begin();
12888        }
12889        let mut hidden = vec![0.0f32; self.hidden_size];
12890        let mut pos = 0usize;
12891        if self.dory.is_some() {
12892            return Ok(self.dory_forward(ids, 0, crate::dory::Want::Last));
12893        }
12894        if let Some(b) = &mut self.dsv41 {
12895            let pool = self.pool.clone();
12896            let mut logits = Vec::new();
12897            crate::dsv41::forward_chunk(
12898                &b.0,
12899                &b.1,
12900                &b.2,
12901                &mut b.3,
12902                ids,
12903                0,
12904                pool.as_deref(),
12905                &mut logits,
12906            );
12907            if let Err(err) = self.o1_seal_checked() {
12908                self.clear_sequence_state();
12909                return Err(err);
12910            }
12911            return Ok(logits);
12912        }
12913        // Inkling-2-Mini: the prompt as generation reads it (the card's
12914        // prompt calls, else host chunks), so bench times that route
12915        if let Some(b) = &mut self.inkling {
12916            let mut logits = Vec::new();
12917            let taken = crate::inkling::forward_prompt(&b.0, &b.1, &b.2, &mut b.3, ids, 0, self.pool.as_deref(), &mut logits);
12918            for (i, &t) in ids.iter().enumerate().skip(taken) {
12919                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());
12920            }
12921            self.graph_logits = Some(logits.clone());
12922            return Ok(logits);
12923        }
12924        // Same routing predicate generation uses. Two reasons it must be
12925        // the same one: (1) a GDN hybrid's recurrent state is GPU-
12926        // resident, and a batched CPU prefill would build it on the host
12927        // only — decode then reads buffers the prefill never wrote;
12928        // (2) bench times THIS function and calls the result "prefill",
12929        // so a different path here reports a number production never
12930        // sees (W2 on 2×5090: 8.7 tok/s reported against 125 real).
12931        // Gemma-4: generation's batched-graph ingest (`g4_batch_ingest`),
12932        // so bench and the parity tools time and score the route run/serve
12933        // take; a refusal leaves the rest to the chunked host prefill.
12934        #[cfg(not(target_os = "macos"))]
12935        if task_mask.is_none() && ids.len() > 2 && self.g4_batch_prefill() {
12936            let (n, last) = match self.g4_batch_ingest(ids, 0, false) {
12937                Ok(r) => r,
12938                Err(e) => {
12939                    self.clear_sequence_state();
12940                    return Err(e);
12941                }
12942            };
12943            if n > 0 {
12944                hidden.copy_from_slice(&last);
12945                pos = n;
12946            }
12947        }
12948        if self.can_prefill_batched() && !self.graph_prefill_preferred() && ids.len() > 2 {
12949            // prefill-GEMM in chunks; only the last position's hidden is
12950            // needed. (o1-compatible: the batch path attends per position
12951            // through qwen_attention, which carries the collection hook.)
12952            let chunk = self.prefill_chunk();
12953            let hs = self.hidden_size;
12954            while pos < ids.len() {
12955                let end = (pos + chunk).min(ids.len());
12956                let hb = self.prefill_rows(&ids[pos..end], pos, task_mask)?;
12957                self.check_forward_graph("forward_ids batched prefill", end - 1)?;
12958                hidden.copy_from_slice(&hb[(end - pos - 1) * hs..]);
12959                pos = end;
12960            }
12961        }
12962        // Same guards as generation's prefill — INCLUDING the graph one.
12963        // The CPU pair walk was intercepting positions that the resident
12964        // token graph would have run itself: on a GDN hybrid over wgpu
12965        // that is 89 ms of host forward against 7 ms of device submit,
12966        // and it made prefill look 12× slower than it is (W2 on an RTX
12967        // 5090, ctx 512: 11.2 tok/s with the walk, 136.6 without).
12968        // CMF_PAIR=0 opts out; a model whose layers live outside
12969        // `weights.layers` has no pair walk to take.
12970        if task_mask.is_none()
12971            && !self.graph_prefill_preferred()
12972            && !std::env::var("CMF_PAIR").is_ok_and(|v| v == "0")
12973            && self.pair_supported()
12974        {
12975            while pos + 1 < ids.len() {
12976                let e1 = self.embed_single(ids[pos]);
12977                let e2 = self.embed_single(ids[pos + 1]);
12978                let (_, h2) = self.forward_pair(&e1, &e2, pos);
12979                self.check_forward_graph("forward_ids pair", pos + 1)?;
12980                self.commit_linear_scratch();
12981                hidden = h2;
12982                pos += 2;
12983            }
12984        }
12985        // Resident Embryo graph: the prompt in chunks of one submit each
12986        // (the same device state and logits as the per-position walk).
12987        if task_mask.is_none() && pos == 0 && ids.len() > 1 {
12988            if let Some(lg) = self.embryo_prefill_chunked(ids, 0) {
12989                self.graph_logits = Some(lg);
12990                hidden = vec![0.0; self.hidden_size];
12991                pos = ids.len();
12992            }
12993        }
12994        // Flash-Next class: the prompt in the frames generation reads it in
12995        // (`qwen4_exp::forward_tokens`, a chunk a call) — the per-position
12996        // walk below read a 4096-token prompt on Vulkan at 46 tok/s where
12997        // generation's own prefill took 6.4 s.
12998        if task_mask.is_none() && pos == 0 && self.qwen4_exp.is_some() {
12999            while pos < ids.len() && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
13000                let end = (pos + crate::qwen4_exp::prefill_chunk()).min(ids.len());
13001                let want = end == ids.len();
13002                let mut lg = Vec::new();
13003                if let Some(b) = &mut self.qwen4_exp {
13004                    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);
13005                }
13006                if want {
13007                    self.graph_logits = Some(lg);
13008                }
13009                pos = end;
13010            }
13011            hidden = vec![0.0; self.hidden_size];
13012        }
13013        while pos < ids.len() {
13014            hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, task_mask);
13015            self.check_forward_graph("forward_ids", pos)?;
13016            pos += 1;
13017        }
13018        if let Some(logits) = self.graph_logits.take() {
13019            // Resident stacks already applied final norm and their head in
13020            // the same submit; do not run a second norm/head over the zero
13021            // hidden sentinel returned by forward_layers_span.
13022            if let Err(err) = self.o1_seal_checked() {
13023                self.clear_sequence_state();
13024                return Err(err);
13025            }
13026            return Ok(logits);
13027        }
13028        // Harness contract: after forward_ids the cache is decode-ready —
13029        // under o1 that means sealed (bench measures the seal as part of
13030        // prefill, honestly).
13031        if let Err(err) = self.o1_seal_checked() {
13032            self.clear_sequence_state();
13033            return Err(err);
13034        }
13035        let normed = inference::rms_norm(
13036            &hidden,
13037            &self.weights.final_norm,
13038            self.rms_eps,
13039            self.norm_style,
13040        );
13041        Ok(self.lm_head_forward(&normed))
13042    }
13043
13044    /// Run the V4.1 stack one token at a time and retain logits for every
13045    /// position. This is a diagnostic surface for comparing a converted
13046    /// checkpoint with a tokenwise reference implementation.
13047    #[doc(hidden)]
13048    pub fn dsv41_serial_logits(&mut self, ids: &[u32]) -> Result<Vec<Vec<f32>>, String> {
13049        #[cfg(target_os = "macos")]
13050        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
13051        if ids.is_empty() {
13052            return Err("empty id sequence".to_string());
13053        }
13054        self.clear_sequence_state();
13055        self.dsv41
13056            .as_ref()
13057            .ok_or_else(|| "dsv41 serial logits require a DeepSeek-V4.1 model".to_string())?;
13058        self.o1_begin();
13059        let rows = {
13060            let pool = self.pool.clone();
13061            let b = self
13062                .dsv41
13063                .as_mut()
13064                .expect("dsv41 checked above; state cannot change during forward");
13065            let mut rows = Vec::with_capacity(ids.len());
13066            for (position, &id) in ids.iter().enumerate() {
13067                let mut logits = Vec::new();
13068                crate::dsv41::forward_token(
13069                    &b.0,
13070                    &b.1,
13071                    &b.2,
13072                    &mut b.3,
13073                    id,
13074                    position,
13075                    pool.as_deref(),
13076                    &mut logits,
13077                );
13078                rows.push(logits);
13079            }
13080            rows
13081        };
13082        self.o1_seal();
13083        Ok(rows)
13084    }
13085
13086    /// GPTQ calibration of DeepSeek-V4.1 (`cortiq quantize-moe`): the MoE
13087    /// input rows and routed expert ids of layers `lo..hi` for `ids` (a fresh
13088    /// sequence), see [`crate::dsv41::Dsv41MoeCapture`].
13089    pub fn dsv41_moe_capture(
13090        &mut self,
13091        ids: &[u32],
13092        lo: usize,
13093        hi: usize,
13094    ) -> Result<crate::dsv41::Dsv41MoeCapture, String> {
13095        #[cfg(target_os = "macos")]
13096        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
13097        if ids.is_empty() {
13098            return Err("empty id sequence".to_string());
13099        }
13100        self.dsv41
13101            .as_ref()
13102            .ok_or_else(|| "not a DeepSeek-V4.1 model".to_string())?;
13103        self.clear_sequence_state();
13104        let res = {
13105            let pool = self.pool.clone();
13106            let b = self.dsv41.as_mut().expect("dsv41 checked above");
13107            crate::dsv41::capture_window(&b.0, &b.1, &b.2, &mut b.3, ids, lo, hi, pool.as_deref())
13108        };
13109        self.clear_sequence_state();
13110        res
13111    }
13112
13113    /// GPTQ calibration of Maxwell's routed experts (`cortiq quantize-moe`):
13114    /// the routed FFNs' input rows and expert ids of layers `lo..hi` for
13115    /// `ids` (a fresh sequence), see [`crate::maxwell::MoeCapture`].
13116    pub fn maxwell_moe_capture(&mut self, ids: &[u32], lo: usize, hi: usize) -> Result<crate::maxwell::MoeCapture, String> {
13117        if ids.is_empty() {
13118            return Err("empty id sequence".to_string());
13119        }
13120        self.maxwell.as_ref().ok_or_else(|| "not a Maxwell model".to_string())?;
13121        self.clear_sequence_state();
13122        let res = {
13123            let pool = self.pool.clone();
13124            let b = self.maxwell.as_mut().expect("maxwell checked above");
13125            crate::maxwell::capture_window(&b.0, &b.1, &b.2, &mut b.3, ids, lo, hi, pool.as_deref())
13126        };
13127        self.clear_sequence_state();
13128        res
13129    }
13130
13131    /// Teacher-forced perplexity over a token sequence (phase-C gate:
13132    /// honest quant comparisons instead of prompt vibes).
13133    ///
13134    /// Attention is EXACT even on a model whose layers are flagged for
13135    /// the O(1) kernel — scoring the backbone is the default on purpose
13136    /// (it is the yardstick). `nll_ids_o1` scores the CONVERTED model.
13137    pub fn ppl_ids(&mut self, ids: &[u32]) -> Result<f64, String> {
13138        let (nll, cnt) = self.nll_ids_from(ids, 0)?;
13139        Ok((nll / cnt.max(1) as f64).exp())
13140    }
13141
13142    /// GPTQ calibration forward: `ids` through layers `0..upto` only, in
13143    /// layer-major chunks of `chunk` positions, with no vocabulary head and
13144    /// no scoring. The Hessian hook (`gptq_capture`) folds every
13145    /// projection's input on the way; the layers above the captured span
13146    /// and the head would only cost time. Falls back to a scored forward
13147    /// where the batched prefill does not apply.
13148    pub fn calib_forward(&mut self, ids: &[u32], upto: usize, chunk: usize) -> Result<(), String> {
13149        if !self.can_prefill_batched() {
13150            return self.nll_ids_from(ids, 0).map(|_| ());
13151        }
13152        self.nll_begin()?;
13153        let result: Result<(), String> = (|| {
13154            let chunk = chunk.max(1);
13155            let mut pos = 0usize;
13156            while pos < ids.len() {
13157                let end = (pos + chunk).min(ids.len());
13158                let _ = self.prefill_batch_span(PrefillIn::Ids(&ids[pos..end]), pos, None, 0, upto);
13159                self.nll_check_graph("calibration prefill", pos)?;
13160                pos = end;
13161            }
13162            Ok(())
13163        })();
13164        self.nll_end();
13165        result
13166    }
13167
13168    /// Layer-streamed calibration of one fresh window: layers `from..mid` run
13169    /// on `input` (the hidden state entering layer `from`; `None` = the
13170    /// token embeddings of `ids`) and their output is returned, then layers
13171    /// `mid..upto` run on that output for the capture hooks (their output is
13172    /// dropped). A caller that keeps the returned state per window runs each
13173    /// layer once over the whole conversion instead of re-running the stack
13174    /// below every layer. With `mid == from` the input is returned as is
13175    /// (`None` input: an empty vector).
13176    pub fn calib_window_span(
13177        &mut self,
13178        ids: &[u32],
13179        input: Option<&[f32]>,
13180        from: usize,
13181        mid: usize,
13182        upto: usize,
13183    ) -> Result<Vec<f32>, String> {
13184        if !self.can_prefill_batched() {
13185            return Err("calib_window_span: this architecture has no batched prefill".into());
13186        }
13187        self.nll_begin()?;
13188        let result: Result<Vec<f32>, String> = (|| {
13189            let h = if mid > from {
13190                let inp = match input {
13191                    Some(h) => PrefillIn::Hidden(h),
13192                    None => PrefillIn::Ids(ids),
13193                };
13194                let h = self.prefill_batch_span(inp, 0, None, from, mid);
13195                self.nll_check_graph("calibration span", 0)?;
13196                h
13197            } else {
13198                input.map(<[f32]>::to_vec).unwrap_or_default()
13199            };
13200            if upto > mid {
13201                let inp = if mid > from || input.is_some() {
13202                    PrefillIn::Hidden(&h)
13203                } else {
13204                    PrefillIn::Ids(ids)
13205                };
13206                let _ = self.prefill_batch_span(inp, 0, None, mid, upto);
13207                self.nll_check_graph("calibration span", 0)?;
13208            }
13209            Ok(h)
13210        })();
13211        self.nll_end();
13212        result
13213    }
13214
13215    /// GPTQ calibration of a Flash-Next-class MoE (`qwen4_exp`): MoE input
13216    /// rows and router logits of layers `lo..hi` for `ids` (a fresh
13217    /// sequence), per layer `[ids.len()][hidden + n_experts]`.
13218    #[cfg(feature = "gpu")]
13219    pub fn qwen4_capture(
13220        &mut self,
13221        ids: &[u32],
13222        lo: usize,
13223        hi: usize,
13224    ) -> Result<Vec<Vec<f32>>, String> {
13225        let b = self.qwen4_exp.as_mut().ok_or("not a qwen4_exp model")?;
13226        crate::qwen4_exp::capture_window(
13227            &b.0,
13228            &b.1,
13229            &b.2,
13230            &mut b.3,
13231            ids,
13232            lo,
13233            hi,
13234            &self.inv_freq,
13235            self.pool.as_deref(),
13236        )
13237    }
13238
13239    /// GPTQ calibration capture of an ordinary MoE stack (Qwen3.5/3.6
13240    /// MoE, Clover): `ids` from position 0 through the batched device graph
13241    /// in prefill-sized chunks, the MoE input rows and router logits of
13242    /// layers `lo..hi` copied out after routing. Returns per layer
13243    /// `[ids.len()][hidden + n_experts]`; the sequence state is left fresh.
13244    #[cfg(feature = "gpu")]
13245    pub fn moe_capture(&mut self, ids: &[u32], lo: usize, hi: usize) -> Result<Vec<Vec<f32>>, String> {
13246        use crate::gpu_wgpu::clover as cap;
13247        let (hs, hi) = (self.hidden_size, hi.min(self.num_layers));
13248        let ne = (lo..hi)
13249            .find_map(|li| match &self.weights.layers[self.phys_layer(li)].ffn {
13250                FfnKind::Moe(m) => Some(m.experts.len()),
13251                _ => None,
13252            })
13253            .ok_or("no MoE layer in the capture range")?;
13254        let chunk = self.prefill_chunk().max(1);
13255        self.clear_sequence_state();
13256        if !cap::moe_capture_begin(lo, hi, chunk, hs, ne) {
13257            return Err("capture unavailable (no wgpu device)".into());
13258        }
13259        let mut out: Vec<Vec<f32>> = (lo..hi).map(|_| Vec::with_capacity(ids.len() * (hs + ne))).collect();
13260        let res = (|| {
13261            for (ci, part) in ids.chunks(chunk).enumerate() {
13262                let mut hiddens = Vec::with_capacity(part.len() * hs);
13263                for &id in part {
13264                    hiddens.extend_from_slice(&self.embed_single(id));
13265                }
13266                let positions: Vec<usize> = (ci * chunk..ci * chunk + part.len()).collect();
13267                match self.try_batch_graph_wgpu(&mut hiddens, &positions, part.len(), None) {
13268                    crate::gpu::BatchGraphOutcome::Completed => {}
13269                    _ => return Err("the batched graph declined the calibration forward (VRAM budget?)".to_string()),
13270                }
13271                let (rows, written) = cap::moe_capture_read(part.len()).ok_or("capture readback")?;
13272                if written < hi - lo {
13273                    return Err(format!("{written} of {} captured layers ran through the device MoE arm", hi - lo));
13274                }
13275                for (o, r) in out.iter_mut().zip(rows) {
13276                    o.extend_from_slice(&r);
13277                }
13278            }
13279            Ok(())
13280        })();
13281        cap::moe_capture_end();
13282        self.clear_sequence_state();
13283        res.map(|_| out)
13284    }
13285
13286    /// Expert directory triples (gate, up, down) of an ordinary MoE layer,
13287    /// routed and shared.
13288    pub fn moe_expert_dirs(
13289        &self,
13290        li: usize,
13291    ) -> Option<(Vec<(usize, usize, usize)>, Option<(usize, usize, usize)>)> {
13292        let FfnKind::Moe(m) = &self.weights.layers.get(self.phys_layer(li))?.ffn else {
13293            return None;
13294        };
13295        let dirs = |d: &DenseFfn| Some((d.gate_proj.model_idx()?, d.up_proj.model_idx()?, d.down_proj.model_idx()?));
13296        let routed = m.experts.iter().map(dirs).collect::<Option<Vec<_>>>()?;
13297        let shared = match &m.shared {
13298            Some((se, _)) => Some(dirs(se)?),
13299            None => None,
13300        };
13301        Some((routed, shared))
13302    }
13303
13304    /// Expert directory triples of a `qwen4_exp` layer (routed, shared).
13305    pub fn qwen4_expert_dirs(
13306        &self,
13307        li: usize,
13308    ) -> Option<(Vec<(usize, usize, usize)>, Option<(usize, usize, usize)>)> {
13309        let b = self.qwen4_exp.as_ref()?;
13310        crate::qwen4_exp::expert_dirs(&b.1, li)
13311    }
13312
13313    /// Teacher-force the installed MTP draft stack and collect each draft
13314    /// FFN's own pre-down activation statistics.
13315    ///
13316    /// This is deliberately separate from [`Self::probe_ffn_mass`]: canonical
13317    /// MTP and MiMo sidecars can have independently compacted FFNs, and MiMo
13318    /// draft layers can differ in width from one another and from the trunk.
13319    /// The returned vector follows the actual draft stack (one entry for a
13320    /// canonical MTP head; one per MiMo draft layer). MiMo layer `k` replays
13321    /// the teacher-forced pairs `(hidden[j], ids[j + k + 1])`.
13322    ///
13323    /// Calibration starts from a fresh sequence and leaves the trunk, draft
13324    /// KVs, history, and device mirrors fresh on both success and error. It
13325    /// is therefore unsuitable for the middle of a conversation whose KV
13326    /// cache must be retained.
13327    pub fn probe_mtp_ffn(&mut self, ids: &[u32]) -> Result<Vec<MtpFfnProbe>, String> {
13328        self.reset_mtp_probe_state();
13329        // The trunk runs as one prefill (the device graph where there is
13330        // one); the draft replays on the host under a CPU scope, where its
13331        // FFN input can be measured. This guard also suppresses gate/oracle
13332        // sparsity experiments for the duration so the statistics and
13333        // admission replay always execute the full dense FFN.
13334        let _exact_calibration = ExactMtpCalibrationGuard::enter();
13335        let result = if ids.len() < 2 {
13336            Err("MTP FFN probe needs at least two token ids".into())
13337        } else if ids
13338            .iter()
13339            .any(|&id| id as usize >= self.weights.embed_tokens.rows())
13340        {
13341            Err("MTP FFN probe received a token id outside the embedding table".into())
13342        } else if self.mtp.is_some() && self.mimo_mtp.is_some() {
13343            // A synthetic pipeline can carry both mechanisms, but merging
13344            // unlike draft semantics into one compaction plan is unsafe.
13345            Err("MTP FFN probe found both canonical and MiMo draft stacks".into())
13346        } else if self.mimo_mtp.is_some() {
13347            let mut st = self
13348                .mimo_mtp
13349                .take()
13350                .expect("checked MiMo MTP before detaching it");
13351            let result = match self.probe_trunk_rows(ids) {
13352                Ok(trunk) => crate::gpu::cpu_scope(|| {
13353                    self.mimo_mtp_ffn_probe_teacher_forced(&mut st, ids, &trunk)
13354                }),
13355                Err(e) => Err(e),
13356            };
13357            // The owner is detached during the replay, so the common trunk
13358            // reset cannot clear its KVs. Restore it even on an error.
13359            st.reset();
13360            self.mimo_mtp = Some(st);
13361            result
13362        } else if self.mtp.is_some() {
13363            let mut mtp = self
13364                .mtp
13365                .take()
13366                .expect("checked canonical MTP before detaching it");
13367            let result = match self.probe_trunk_rows(ids) {
13368                Ok(trunk) => crate::gpu::cpu_scope(|| {
13369                    self.mtp_ffn_probe_teacher_forced(&mut mtp, ids, &trunk)
13370                }),
13371                Err(e) => Err(e),
13372            };
13373            mtp.kv.clear();
13374            self.mtp = Some(mtp);
13375            result
13376        } else {
13377            Err("MTP FFN probe: this pipeline has no draft stack".into())
13378        };
13379        // Cover every early/error arm above: no failed calibration can leak
13380        // a partially populated trunk or draft cache into the next request.
13381        self.reset_mtp_probe_state();
13382        result
13383    }
13384
13385    /// Reset every state owner touched by [`Self::probe_mtp_ffn`].
13386    fn reset_mtp_probe_state(&mut self) {
13387        self.clear_sequence_state();
13388        if let Some(mtp) = self.mtp.as_mut() {
13389            mtp.kv.clear();
13390        }
13391        if let Some(mimo) = self.mimo_mtp.as_mut() {
13392            mimo.reset();
13393        }
13394        self.mtp_graph_mode = None;
13395    }
13396
13397    /// The trunk's last hidden row (before the final norm) at every
13398    /// position a teacher-forced draft probe reads (`ids[..len-1]`), from
13399    /// the whole-stack prefill — the device graph where there is one. One
13400    /// position at a time through `forward_layers` on the host this was the
13401    /// probe's whole cost: a 14B's 96k calibration tokens ran for hours.
13402    pub(crate) fn probe_trunk_rows(&mut self, ids: &[u32]) -> Result<Vec<f32>, String> {
13403        if ids.len() < 2 {
13404            return Err("MTP FFN probe needs at least two token ids".into());
13405        }
13406        let rows = self.final_hidden_rows(&ids[..ids.len() - 1])?;
13407        self.clear_sequence_state();
13408        Ok(rows)
13409    }
13410
13411    /// Canonical one-layer MTP teacher-forced replay over the trunk rows
13412    /// of [`Self::probe_trunk_rows`]. Its cache advances for every row so
13413    /// later attention inputs match a real draft warm-up rather than a
13414    /// collection of independent one-token measurements. The FFN inputs are
13415    /// measured in batches: nothing after the FFN feeds a later row.
13416    fn mtp_ffn_probe_teacher_forced(
13417        &mut self,
13418        mtp: &mut MtpModule,
13419        ids: &[u32],
13420        trunk: &[f32],
13421    ) -> Result<Vec<MtpFfnProbe>, String> {
13422        let FfnKind::Dense(dense) = &mtp.layer.ffn else {
13423            return Err("MTP FFN probe: canonical draft FFN is not dense".into());
13424        };
13425        let inter = dense.gate_proj.rows();
13426        let (hs, n) = (self.hidden_size, ids.len() - 1);
13427        if trunk.len() != n * hs {
13428            return Err(format!(
13429                "MTP FFN probe: {} trunk values for {n} rows of width {hs}",
13430                trunk.len()
13431            ));
13432        }
13433        let mut mass = vec![0.0f64; inter];
13434        let mut squared_mass = vec![0.0f64; inter];
13435        let mut inputs = Vec::with_capacity(MTP_PROBE_FFN_ROWS.min(n) * hs);
13436        for position in 0..n {
13437            self.mtp_probe_ffn_input(
13438                mtp,
13439                &trunk[position * hs..(position + 1) * hs],
13440                ids[position + 1],
13441                position,
13442            )?;
13443            inputs.extend_from_slice(&self.ws.p1[..hs]);
13444            if inputs.len() == MTP_PROBE_FFN_ROWS * hs || position + 1 == n {
13445                let FfnKind::Dense(dense) = &mtp.layer.ffn else {
13446                    unreachable!("checked dense above");
13447                };
13448                accumulate_dense_ffn_activation_mass(
13449                    dense,
13450                    &inputs,
13451                    inputs.len() / hs,
13452                    self.pool.as_deref(),
13453                    &mut mass,
13454                    &mut squared_mass,
13455                )?;
13456                inputs.clear();
13457            }
13458        }
13459        Ok(vec![MtpFfnProbe {
13460            mass,
13461            squared_mass,
13462            observed_positions: n,
13463        }])
13464    }
13465
13466    /// CPU-only MTP block replay up to the FFN's input (the post-attention
13467    /// norm, left in `ws.p1`), where the probe measures. The ordinary
13468    /// `mtp_step_hl` device path keeps these values resident and therefore
13469    /// cannot truthfully provide a per-neuron calibration statistic. The
13470    /// FFN arm itself is not run: its output feeds only this row's logits.
13471    fn mtp_probe_ffn_input(
13472        &mut self,
13473        mtp: &mut MtpModule,
13474        hidden: &[f32],
13475        next_token: u32,
13476        position: usize,
13477    ) -> Result<(), String> {
13478        let e = self.embed_single(next_token);
13479        let mut cat = vec![0.0f32; 2 * self.hidden_size];
13480        let (cat_e, cat_h) = cat.split_at_mut(self.hidden_size);
13481        inference::rms_norm_into(&e, &mtp.enorm, self.rms_eps, self.norm_style, cat_e);
13482        inference::rms_norm_into(
13483            hidden,
13484            &mtp.hnorm,
13485            self.rms_eps,
13486            self.norm_style,
13487            cat_h,
13488        );
13489        let mut x = vec![0.0f32; self.hidden_size];
13490        mtp.eh_proj.matvec(&cat, &mut x, self.pool.as_deref());
13491
13492        let lw = &mtp.layer;
13493        inference::rms_norm_into(
13494            &x,
13495            &lw.input_norm,
13496            self.rms_eps,
13497            self.norm_style,
13498            &mut self.ws.n1,
13499        );
13500        let attn = match &lw.attn {
13501            AttnKind::Full {
13502                wq,
13503                wk,
13504                wv,
13505                wo,
13506                q_norm,
13507                k_norm,
13508                output_gate,
13509                softplus_gate,
13510                bias,
13511            } => {
13512                let mut cfg = self.attn_cfg(position);
13513                cfg.q_norm = q_norm.as_deref();
13514                cfg.k_norm = k_norm.as_deref();
13515                cfg.output_gate = *output_gate;
13516                cfg.softplus_gate = softplus_gate
13517                    .as_ref()
13518                    .map(|(gate, per_head)| (gate, *per_head));
13519                cfg.bias = bias
13520                    .as_ref()
13521                    .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice()));
13522                attention::qwen_attention(&self.ws.n1, wq, wk, wv, wo, &mut mtp.kv, &cfg)
13523            }
13524            _ => return Err("MTP FFN probe: draft attention is not full attention".into()),
13525        };
13526        for (dst, src) in x.iter_mut().zip(attn) {
13527            *dst += src;
13528        }
13529        inference::rms_norm_into(
13530            &x,
13531            &lw.post_norm,
13532            self.rms_eps,
13533            self.norm_style,
13534            &mut self.ws.p1,
13535        );
13536        Ok(())
13537    }
13538
13539    /// DTG-MA calibration pass (Patent 2): run `ids` through the model
13540    /// (CPU path, per position) and return each layer's per-neuron
13541    /// activation mass Σ|silu(gate)·up| — the statistic the task-guided
13542    /// FFN mask is derived from.
13543    pub fn probe_ffn_mass(&mut self, ids: &[u32]) -> Vec<Vec<f64>> {
13544        self.clear_sequence_state();
13545        FFN_PROBE.with(|p| {
13546            *p.borrow_mut() = Some(vec![vec![0f64; self.intermediate_size]; self.num_layers]);
13547        });
13548        crate::gpu::cpu_scope(|| {
13549            for (pos, &id) in ids.iter().enumerate() {
13550                let emb = self.embed_single(id);
13551                let _ = self.forward_layers(&emb, pos, None);
13552            }
13553        });
13554        self.clear_sequence_state();
13555        FFN_PROBE
13556            .with(|p| p.borrow_mut().take())
13557            .unwrap_or_default()
13558    }
13559
13560    /// `probe_ffn_mass` over the BATCHED prefill: same accumulator, one
13561    /// sweep instead of one forward per token. What makes the statistic
13562    /// affordable on a 27B.
13563    pub fn probe_ffn_mass_batch(&mut self, ids: &[u32]) -> Result<Vec<Vec<f64>>, String> {
13564        if let Err(err) = self.nll_begin() {
13565            // A recorder can be left by a caller that was interrupted before
13566            // this request entered its scoring block.  Consume it even when
13567            // the preflight failure prevents initialization of a new one.
13568            let _ = FFN_PROBE.with(|p| p.borrow_mut().take());
13569            self.nll_end();
13570            return Err(err);
13571        }
13572        FFN_PROBE.with(|p| {
13573            *p.borrow_mut() = Some(vec![vec![0f64; self.intermediate_size]; self.num_layers]);
13574        });
13575        let result: Result<(), String> = (|| {
13576            for chunk in ids.chunks(256) {
13577                if chunk.len() < 2 {
13578                    continue;
13579                }
13580                self.nll_ids_masked(chunk, 0, None)?;
13581            }
13582            Ok(())
13583        })();
13584        self.nll_end();
13585        let probe = FFN_PROBE
13586            .with(|p| p.borrow_mut().take())
13587            .unwrap_or_default();
13588        match result {
13589            Ok(()) => Ok(probe),
13590            Err(err) => {
13591                drop(probe);
13592                Err(err)
13593            }
13594        }
13595    }
13596
13597    /// The FFN probe over one window of the layer-major batched walk
13598    /// (`calib_forward`): the statistic of `probe_ffn_mass`, the window's rows
13599    /// in one context, every projection a GEMM on the device where one is up.
13600    pub fn probe_ffn_mass_span(&mut self, ids: &[u32], chunk: usize) -> Result<Vec<Vec<f64>>, String> {
13601        FFN_PROBE.with(|p| {
13602            *p.borrow_mut() = Some(vec![vec![0f64; self.intermediate_size]; self.num_layers]);
13603        });
13604        let result = self.calib_forward(ids, self.num_layers, chunk);
13605        let probe = FFN_PROBE.with(|p| p.borrow_mut().take()).unwrap_or_default();
13606        result.map(|()| probe)
13607    }
13608
13609    /// The hot-neuron statistic of a MoE model's routed experts over `ids`:
13610    /// per layer `[expert · inter + neuron]` of Σ (w·act)², `w` the expert's
13611    /// final routing weight (a layer without experts gives an empty row).
13612    /// Qwen-3.5/3.8 MoE models only, on the host path: the caller runs with
13613    /// `CMF_GPU=0`, since the device frames and the fused expert kernels do
13614    /// not report activations.
13615    pub fn probe_moe_mass(&mut self, ids: &[u32]) -> Result<Vec<Vec<f64>>, String> {
13616        let Some(b) = self.qwen4_exp.as_mut() else {
13617            return Err("hot-probe --experts: not a Qwen MoE model (the probe reads the qwen4 host path)".into());
13618        };
13619        let geom: Vec<(usize, usize)> = b.1.iter().map(crate::qwen4_exp::Layer::expert_geometry).collect();
13620        let inter = geom.iter().map(|g| g.1).max().unwrap_or(0);
13621        if inter == 0 || ids.is_empty() {
13622            return Err("hot-probe --experts: the model has no routed experts".into());
13623        }
13624        MOE_PROBE.with(|p| {
13625            *p.borrow_mut() = Some(MoeProbe {
13626                acc: geom.iter().map(|&(ne, _)| vec![0f64; ne * inter]).collect(),
13627                inter,
13628                cur: None,
13629            });
13630        });
13631        b.3.reset();
13632        let mut pos = 0usize;
13633        while pos < ids.len() {
13634            let end = (pos + crate::qwen4_exp::prefill_chunk()).min(ids.len());
13635            let mut lg = Vec::new();
13636            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);
13637            pos = end;
13638        }
13639        b.3.reset();
13640        let probe = MOE_PROBE.with(|p| p.borrow_mut().take()).map_or_else(Vec::new, |p| p.acc);
13641        if !probe.iter().any(|r| r.iter().any(|&v| v > 0.0)) {
13642            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());
13643        }
13644        Ok(probe)
13645    }
13646
13647    /// Teacher-forced PPL with a task mask active (sparse execution) —
13648    /// the quality gate for a DTG-MA-masked skill. Sequential per
13649    /// position: the batched prefill path is dense-only.
13650    pub fn ppl_ids_masked(&mut self, ids: &[u32], mask: &TaskMask) -> Result<f64, String> {
13651        self.nll_begin()?;
13652        let result: Result<f64, String> = (|| {
13653            let mut nll = 0f64;
13654            let mut cnt = 0usize;
13655            let mut hidden = vec![0f32; self.hidden_size];
13656            for (pos, &id) in ids.iter().enumerate() {
13657                if pos > 0 {
13658                    inference::rms_norm_into(
13659                        &hidden,
13660                        &self.weights.final_norm,
13661                        self.rms_eps,
13662                        self.norm_style,
13663                        &mut self.ws.n1,
13664                    );
13665                    let mut logits = self.lm_head_forward(&self.ws.n1);
13666                    let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
13667                    let sum: f64 = logits.iter().map(|&v| ((v - max) as f64).exp()).sum();
13668                    let p = ((logits[id as usize] - max) as f64).exp() / sum.max(1e-300);
13669                    nll -= p.max(1e-300).ln();
13670                    cnt += 1;
13671                    attention::recycle_buf(&mut logits);
13672                }
13673                let emb = self.embed_single(id);
13674                hidden = self.forward_layers(&emb, pos, Some(mask));
13675                self.nll_check_graph("masked serial forward", pos)?;
13676                // Consume a possible graph logits side channel before the
13677                // next row.  Masked scoring normally disables that route,
13678                // but stale channel state must never survive a request.
13679                let _ = self.graph_logits.take();
13680            }
13681            Ok((nll / cnt.max(1) as f64).exp())
13682        })();
13683        self.nll_end();
13684        result
13685    }
13686
13687    /// Teacher-forced NLL sum + scored-token count over positions
13688    /// `start..len-1`, attention EXACT. Positions below `start` still
13689    /// run — they are the context — they are just not scored, so this
13690    /// pairs with `nll_ids_o1(ids, start)` over the very same tokens.
13691    ///
13692    /// Returning (nll, cnt) rather than a ppl is what lets a windowed
13693    /// caller combine windows before the exp, so every scored token
13694    /// weighs the same regardless of how the windows are cut.
13695    /// `nll_ids_from` with a task mask held active at every position.
13696    ///
13697    /// The batched prefill path does not thread masks, so this walks the
13698    /// per-position forward — slower, but it scores the file exactly the
13699    /// way `run --task` will serve it, which is the point of the gate
13700    /// that calls it. With `None` it defers to the fast path.
13701    /// Masked scoring rides the SAME batched sweep as unmasked scoring —
13702    /// the masked-inference fast path: `prefill_batch_masked` lands the
13703    /// per-visit FFN rows on the activations inside the fused arms. The
13704    /// per-position loop below remains only as the no-batch fallback.
13705    pub fn nll_ids_masked(
13706        &mut self,
13707        ids: &[u32],
13708        start: usize,
13709        task_mask: Option<&TaskMask>,
13710    ) -> Result<(f64, usize), String> {
13711        let task_mask = self.drop_open_mask(task_mask);
13712        self.nll_ids_inner(ids, start, task_mask)
13713    }
13714
13715    pub fn nll_ids_from(&mut self, ids: &[u32], start: usize) -> Result<(f64, usize), String> {
13716        self.nll_ids_inner(ids, start, None)
13717    }
13718
13719    /// Diagnostic (`CMF_PREFILL_PARITY=split[,k]` on `cortiq ppl`): the same
13720    /// tokens through three ingests, each from a clean sequence — H the host
13721    /// chunked prefill, G the wgpu batch graph in k-row chunks, M the host
13722    /// prefill up to `split` and the batch graph after it, seeded from the
13723    /// host state — and where they part: NLL and top-1 per 256-position bin
13724    /// from each arm's post-stack rows, every GDN layer's recurrent state
13725    /// (the host `linear_state` against the graph's) at `split` and at the
13726    /// end, and every exact-attention layer's K/V rows.
13727    pub fn prefill_parity_probe(
13728        &mut self,
13729        ids: &[u32],
13730        split: usize,
13731        bk: usize,
13732    ) -> Result<String, String> {
13733        use std::fmt::Write as _;
13734        let (n, hs) = (ids.len(), self.hidden_size);
13735        if split == 0 || split >= n || bk == 0 || !self.can_prefill_batched() {
13736            return Err(format!(
13737                "prefill parity: needs 0 < split < {n} tokens, k > 0 and a batched host prefill"
13738            ));
13739        }
13740        // 1 = GDN, 2 = exact attention, 0 = anything else (not compared).
13741        let kinds: Vec<u8> = (0..self.num_layers)
13742            .map(|li| match &self.weights.layers[self.phys_layer(li)].attn {
13743                AttnKind::LinearGdn(_) => 1,
13744                AttnKind::Full { .. } => 2,
13745                _ => 0,
13746            })
13747            .collect();
13748        let kv_id = self.graph_kv_id;
13749        let host_chunk = self.prefill_chunk().max(1);
13750        let host_states = |p: &Self| -> Vec<Vec<f32>> {
13751            (0..p.num_layers)
13752                .map(|li| {
13753                    if kinds[li] == 1 {
13754                        p.kv_cache.layers[li].linear_state.clone()
13755                    } else {
13756                        Vec::new()
13757                    }
13758                })
13759                .collect()
13760        };
13761        let graph_states = |_p: &Self| -> Vec<Vec<f32>> {
13762            (0..kinds.len())
13763                .map(|li| {
13764                    if kinds[li] == 1 {
13765                        crate::gpu::graph_gdn_state_read(kv_id, li).unwrap_or_default()
13766                    } else {
13767                        Vec::new()
13768                    }
13769                })
13770                .collect()
13771        };
13772        // Position-major K/V rows [0, n) of every exact-attention layer.
13773        let host_kv = |p: &Self| -> Vec<(Vec<f32>, Vec<f32>)> {
13774            (0..p.num_layers)
13775                .map(|li| {
13776                    let c = &p.kv_cache.layers[li];
13777                    if kinds[li] != 2
13778                        || c.mode != crate::kv_cache::KvMode::F32
13779                        || c.base() != 0
13780                        || c.seq_len != n
13781                    {
13782                        return (Vec::new(), Vec::new());
13783                    }
13784                    let (nkv, hd) = (c.num_kv_heads, c.head_dim);
13785                    let (mut k, mut v) = (vec![0f32; n * nkv * hd], vec![0f32; n * nkv * hd]);
13786                    for (h, (kh, vh)) in c.k_heads().iter().zip(c.v_heads()).enumerate() {
13787                        for pos in 0..n {
13788                            let d = (pos * nkv + h) * hd;
13789                            k[d..d + hd].copy_from_slice(&kh[pos * hd..(pos + 1) * hd]);
13790                            v[d..d + hd].copy_from_slice(&vh[pos * hd..(pos + 1) * hd]);
13791                        }
13792                    }
13793                    (k, v)
13794                })
13795                .collect()
13796        };
13797        let graph_kv = |p: &Self| -> Vec<(Vec<f32>, Vec<f32>)> {
13798            (0..p.num_layers)
13799                .map(|li| {
13800                    let c = &p.kv_cache.layers[li];
13801                    if kinds[li] != 2 {
13802                        return (Vec::new(), Vec::new());
13803                    }
13804                    crate::gpu::graph_kv_read_rows(kv_id, &[(li, 0, n)], c.num_kv_heads, c.head_dim)
13805                        .and_then(|mut v| v.pop())
13806                        .unwrap_or_default()
13807                })
13808                .collect()
13809        };
13810        let host_walk = |p: &mut Self,
13811                         from: usize,
13812                         to: usize,
13813                         rows: &mut [f32],
13814                         at_split: &mut Option<Vec<Vec<f32>>>| {
13815            let mut pos = from;
13816            while pos < to {
13817                let mut end = (pos + host_chunk).min(to);
13818                if pos < split && end > split {
13819                    end = split;
13820                }
13821                let hb = p.prefill_batch(&ids[pos..end], pos);
13822                rows[pos * hs..end * hs].copy_from_slice(&hb[..(end - pos) * hs]);
13823                pos = end;
13824                if pos == split {
13825                    *at_split = Some(host_states(p));
13826                }
13827            }
13828        };
13829        let graph_walk = |p: &mut Self,
13830                          from: usize,
13831                          to: usize,
13832                          rows: &mut [f32],
13833                          at_split: &mut Option<Vec<Vec<f32>>>|
13834         -> Result<(), String> {
13835            let mut pos = from;
13836            while pos < to {
13837                let mut end = (pos + bk).min(to);
13838                if pos < split && end > split {
13839                    end = split;
13840                }
13841                let k = end - pos;
13842                let mut hid = vec![0f32; k * hs];
13843                for (j, &id) in ids[pos..end].iter().enumerate() {
13844                    hid[j * hs..(j + 1) * hs].copy_from_slice(&p.embed_single(id));
13845                }
13846                let positions: Vec<usize> = (pos..end).collect();
13847                let outcome = p.try_batch_graph_wgpu(&mut hid, &positions, k, None);
13848                if outcome != crate::gpu::BatchGraphOutcome::Completed {
13849                    return Err(format!(
13850                        "prefill parity: batch graph {outcome:?} at position {pos}"
13851                    ));
13852                }
13853                rows[pos * hs..end * hs].copy_from_slice(&hid);
13854                pos = end;
13855                if pos == split {
13856                    *at_split = Some(graph_states(p));
13857                }
13858            }
13859            Ok(())
13860        };
13861        let score = |p: &Self, rows: &[f32], from: usize| p.parity_score(ids, rows, from);
13862
13863        let t = std::time::Instant::now();
13864        self.clear_sequence_state();
13865        let (mut hh, mut h_split) = (vec![0f32; n * hs], None);
13866        host_walk(self, 0, n, &mut hh, &mut h_split);
13867        let (h_end, h_kv) = (host_states(self), host_kv(self));
13868        let t_h = t.elapsed().as_secs_f64();
13869
13870        let t = std::time::Instant::now();
13871        self.clear_sequence_state();
13872        let (mut hg, mut g_split) = (vec![0f32; n * hs], None);
13873        let g_run = graph_walk(self, 0, n, &mut hg, &mut g_split);
13874        let (g_end, g_kv) = (graph_states(self), graph_kv(self));
13875        let t_g = t.elapsed().as_secs_f64();
13876
13877        let t = std::time::Instant::now();
13878        self.clear_sequence_state();
13879        let (mut hm, mut m_split) = (vec![0f32; n * hs], None);
13880        host_walk(self, 0, split, &mut hm, &mut m_split);
13881        let m_run = graph_walk(self, split, n, &mut hm, &mut None);
13882        let (m_end, m_kv) = (graph_states(self), graph_kv(self));
13883        let t_m = t.elapsed().as_secs_f64();
13884        self.clear_sequence_state();
13885        g_run?;
13886        m_run?;
13887
13888        let (sh, sg, sm) = (
13889            score(self, &hh, 0),
13890            score(self, &hg, 0),
13891            score(self, &hm, split),
13892        );
13893        let mut r = String::new();
13894        let _ = writeln!(
13895            r,
13896            "prefill parity: {n} tokens, split {split}, host chunk {host_chunk}, graph k {bk} \
13897             (host {t_h:.1} s, graph {t_g:.1} s, host+graph {t_m:.1} s)"
13898        );
13899        let _ = writeln!(
13900            r,
13901            "  bin          | NLL host  graph  h+g   | top1 host=graph h+g=graph | hidden rel host:graph h+g:graph"
13902        );
13903        let bin = 256usize;
13904        let mut b0 = 0;
13905        while b0 + 1 < n {
13906            let b1 = (b0 + bin).min(n - 1);
13907            let mean = |s: &[(f64, usize)], off: usize| -> Option<f64> {
13908                let v: Vec<f64> = (b0.max(off)..b1).map(|p| s[p - off].0).collect();
13909                (!v.is_empty()).then(|| v.iter().sum::<f64>() / v.len() as f64)
13910            };
13911            let agree = |a: &[(f64, usize)], ao: usize, b: &[(f64, usize)], bo: usize| {
13912                let ps: Vec<usize> = (b0.max(ao).max(bo)..b1).collect();
13913                if ps.is_empty() {
13914                    return None;
13915                }
13916                let same = ps.iter().filter(|&&p| a[p - ao].1 == b[p - bo].1).count();
13917                Some(100.0 * same as f64 / ps.len() as f64)
13918            };
13919            let hid_rel = |a: &[f32], from: usize| -> Option<f64> {
13920                (b0.max(from)..b1)
13921                    .map(|p| rel_l2(&a[p * hs..(p + 1) * hs], &hg[p * hs..(p + 1) * hs]))
13922                    .reduce(f64::max)
13923            };
13924            let f =
13925                |v: Option<f64>, prec: usize| v.map_or("-".to_string(), |x| format!("{x:.prec$}"));
13926            let e = |v: Option<f64>| v.map_or("-".to_string(), |x| format!("{x:.1e}"));
13927            let _ = writeln!(
13928                r,
13929                "  {b0:5}..{b1:<5} | {:>8} {:>6} {:>6} | {:>14} {:>9} | {:>16} {:>9}",
13930                f(mean(&sh, 0), 3),
13931                f(mean(&sg, 0), 3),
13932                f(mean(&sm, split), 3),
13933                f(agree(&sh, 0, &sg, 0), 1),
13934                f(agree(&sm, split, &sg, 0), 1),
13935                e(hid_rel(&hh, 0)),
13936                e(hid_rel(&hm, split)),
13937            );
13938            b0 = b1;
13939        }
13940        // Recurrent state, layer by layer: [conv ring | S] split at the ring.
13941        let ring_len = self
13942            .gdn_cfg
13943            .map(|c| c.conv_dim() * c.conv_kernel.saturating_sub(1))
13944            .unwrap_or(0);
13945        let state_line = |r: &mut String, label: &str, a: &[Vec<f32>], b: &[Vec<f32>]| {
13946            let _ = write!(r, "  GDN {label} (ring/S rel):");
13947            let mut first = None;
13948            for li in (0..kinds.len()).filter(|&li| kinds[li] == 1) {
13949                let (x, y) = (&a[li], &b[li]);
13950                if x.len() != y.len() || x.len() <= ring_len {
13951                    let _ = write!(r, " L{li} len {}/{}", x.len(), y.len());
13952                    continue;
13953                }
13954                let (rr, rs) = (
13955                    rel_l2(&x[..ring_len], &y[..ring_len]),
13956                    rel_l2(&x[ring_len..], &y[ring_len..]),
13957                );
13958                if first.is_none() && rr.max(rs) > 1e-2 {
13959                    first = Some(li);
13960                }
13961                let _ = write!(r, " L{li} {rr:.0e}/{rs:.0e}");
13962            }
13963            let _ = writeln!(
13964                r,
13965                "\n    first GDN layer past 1e-2: {}",
13966                first.map_or("none".to_string(), |l| l.to_string())
13967            );
13968        };
13969        match (&h_split, &g_split) {
13970            (Some(a), Some(b)) => state_line(&mut r, "host vs graph at split", a, b),
13971            _ => {
13972                let _ = writeln!(r, "  GDN at split: not captured");
13973            }
13974        }
13975        if let (Some(a), Some(b)) = (&m_split, &h_split) {
13976            state_line(&mut r, "h+g host part vs host at split", a, b);
13977        }
13978        state_line(&mut r, "host vs graph at end", &h_end, &g_end);
13979        state_line(&mut r, "h+g vs graph at end", &m_end, &g_end);
13980        // Exact-attention K/V: the worst 256-row bin per layer and the first
13981        // bin past 1e-2.
13982        let kv_line = |r: &mut String, label: &str, a: &[(Vec<f32>, Vec<f32>)], from: usize| {
13983            let _ = writeln!(r, "  K/V {label} (worst bin K/V rel, first bin past 1e-2):");
13984            for li in (0..kinds.len()).filter(|&li| kinds[li] == 2) {
13985                let ((ak, av), (gk, gv)) = (&a[li], &g_kv[li]);
13986                if ak.len() != gk.len() || ak.is_empty() {
13987                    let _ = writeln!(r, "    L{li}: rows {}/{}", ak.len(), gk.len());
13988                    continue;
13989                }
13990                let row = ak.len() / n;
13991                let (mut wk, mut wv, mut first) = (0f64, 0f64, None);
13992                let mut b0 = from;
13993                while b0 < n {
13994                    let b1 = (b0 + bin).min(n);
13995                    let (s0, s1) = (b0 * row, b1 * row);
13996                    let (rk, rv) = (
13997                        rel_l2(&ak[s0..s1], &gk[s0..s1]),
13998                        rel_l2(&av[s0..s1], &gv[s0..s1]),
13999                    );
14000                    (wk, wv) = (wk.max(rk), wv.max(rv));
14001                    if first.is_none() && rk.max(rv) > 1e-2 {
14002                        first = Some(b0);
14003                    }
14004                    b0 = b1;
14005                }
14006                let _ = writeln!(
14007                    r,
14008                    "    L{li}: {wk:.1e}/{wv:.1e} first {}",
14009                    first.map_or("none".to_string(), |p| p.to_string())
14010                );
14011            }
14012        };
14013        kv_line(&mut r, "host vs graph", &h_kv, 0);
14014        kv_line(&mut r, "h+g vs graph", &m_kv, 0);
14015        Ok(r)
14016    }
14017
14018    /// (nll, top-1 id) of every position in [from, len − 1) from post-stack
14019    /// rows (`rows` indexed by absolute position), through the scorer's
14020    /// final norm and head.
14021    fn parity_score(&self, ids: &[u32], rows: &[f32], from: usize) -> Vec<(f64, usize)> {
14022        let (n, hs) = (ids.len(), self.hidden_size);
14023        let vrows = self.weights.lm_head.rows();
14024        let vs = self.vocab_size.min(vrows);
14025        let mut out = Vec::with_capacity(n.saturating_sub(from + 1));
14026        let mut pos = from;
14027        while pos + 1 < n {
14028            let end = (pos + 32).min(n - 1);
14029            let sb = end - pos;
14030            let mut normed = vec![0f32; sb * hs];
14031            for j in 0..sb {
14032                let r = inference::rms_norm(
14033                    &rows[(pos + j) * hs..(pos + j + 1) * hs],
14034                    &self.weights.final_norm,
14035                    self.rms_eps,
14036                    self.norm_style,
14037                );
14038                normed[j * hs..(j + 1) * hs].copy_from_slice(&r);
14039            }
14040            let mut logits = vec![0f32; sb * vrows];
14041            self.weights
14042                .lm_head
14043                .matmat(&normed, sb, &mut logits, self.pool.as_deref());
14044            for j in 0..sb {
14045                let lg = &mut logits[j * vrows..j * vrows + vs];
14046                if let Some(mu) = self.logit_multiplier {
14047                    lg.iter_mut().for_each(|v| *v *= mu);
14048                }
14049                if let Some(c) = self.final_softcap {
14050                    softcap_in_place(lg, c, self.pool.as_deref());
14051                }
14052                let (mut max, mut top) = (f32::NEG_INFINITY, 0usize);
14053                for (i, &v) in lg.iter().enumerate() {
14054                    if v > max {
14055                        (max, top) = (v, i);
14056                    }
14057                }
14058                let lse = lg
14059                    .iter()
14060                    .map(|&v| ((v - max) as f64).exp())
14061                    .sum::<f64>()
14062                    .ln()
14063                    + max as f64;
14064                out.push((lse - lg[ids[pos + j + 1] as usize] as f64, top));
14065            }
14066            pos = end;
14067        }
14068        out
14069    }
14070
14071    /// Diagnostic (`CMF_PREFILL_PARITY_O1=k` on `cortiq ppl --o1 …
14072    /// --o1-prefill P`): how much the O(1) seal depends on where its exact
14073    /// prefix ran. Every arm continues on the batch graph from the boundary
14074    /// in k-row chunks:
14075    /// - OH: prefix on the host chunked prefill; seal from the host's
14076    ///   queries and K/V; recurrent state seeded from the host.
14077    /// - OG: prefix on the batch graph (recurrent state stays on the
14078    ///   device); seal from OH's host queries and host K/V.
14079    /// - OD: prefix on the batch graph; seal from OH's queries and the
14080    ///   graph's own K/V rows (read back).
14081    ///
14082    /// OH vs OG isolates the recurrent-state hand-off, OG vs OD the seal's
14083    /// response to the host/graph K/V difference. X is the exact graph.
14084    pub fn o1_seal_parity_probe(
14085        &mut self,
14086        ids: &[u32],
14087        cfg: crate::nystrom::O1Cfg,
14088        requested: usize,
14089        bk: usize,
14090    ) -> Result<String, String> {
14091        use std::fmt::Write as _;
14092        let (n, hs) = (ids.len(), self.hidden_size);
14093        self.set_o1(Some(cfg));
14094        let split = self
14095            .o1_effective_boundary(requested)
14096            .ok_or("o1 parity: no O(1) configuration")?;
14097        if split + 1 >= n || bk == 0 || !self.can_prefill_batched() {
14098            return Err(format!(
14099                "o1 parity: needs the boundary {split} inside {n} tokens, k > 0 and a batched host prefill"
14100            ));
14101        }
14102        let o1_layers: Vec<usize> = (0..self.num_layers)
14103            .filter(|&li| self.o1_flags.get(li).copied().unwrap_or(false))
14104            .collect();
14105        let graph_rows = |p: &mut Self, from: usize, to: usize, rows: &mut [f32]| {
14106            let mut pos = from;
14107            while pos < to {
14108                let end = (pos + bk).min(to);
14109                let k = end - pos;
14110                let mut hid = vec![0f32; k * hs];
14111                for (j, &id) in ids[pos..end].iter().enumerate() {
14112                    hid[j * hs..(j + 1) * hs].copy_from_slice(&p.embed_single(id));
14113                }
14114                let positions: Vec<usize> = (pos..end).collect();
14115                let outcome = p.try_batch_graph_wgpu(&mut hid, &positions, k, None);
14116                if outcome != crate::gpu::BatchGraphOutcome::Completed {
14117                    return Err(format!(
14118                        "o1 parity: batch graph {outcome:?} at position {pos}"
14119                    ));
14120                }
14121                rows[pos * hs..end * hs].copy_from_slice(&hid);
14122                pos = end;
14123            }
14124            Ok(())
14125        };
14126        // Seal every O(1) layer from the given rows; `trace` = (q, k, v) per
14127        // O(1) layer, position-major.
14128        let seal_from = |p: &mut Self, trace: &[(Vec<f32>, Vec<f32>, Vec<f32>)]| {
14129            for (&li, (q, k, v)) in o1_layers.iter().zip(trace) {
14130                let c = &mut p.kv_cache.layers[li];
14131                let (row, qrow) = (k.len() / split, q.len() / split);
14132                for pos in 0..split {
14133                    c.append(
14134                        &k[pos * row..(pos + 1) * row],
14135                        &v[pos * row..(pos + 1) * row],
14136                        &[],
14137                    );
14138                    c.o1_push_q(&q[pos * qrow..(pos + 1) * qrow]);
14139                }
14140            }
14141            p.o1_seal_checked()
14142        };
14143        // Greedy continuation (`CMF_PARITY_GREEDY` tokens, default 40) from
14144        // the last prompt row, one batch-graph row per step.
14145        let steps: usize = std::env::var("CMF_PARITY_GREEDY")
14146            .ok()
14147            .and_then(|v| v.parse().ok())
14148            .unwrap_or(40);
14149        // `CMF_PARITY_DECODE=token`: the steps through `decode_step_logits`
14150        // (the token graph generation decodes on) instead of the batch graph.
14151        let token_decode = std::env::var("CMF_PARITY_DECODE").as_deref() == Ok("token");
14152        let greedy = |p: &mut Self, rows: &[f32]| -> Result<Vec<u32>, String> {
14153            let argmax = |lg: &[f32], vs: usize| {
14154                (0..vs.min(lg.len())).fold(0, |b, i| if lg[i] > lg[b] { i } else { b }) as u32
14155            };
14156            let normed = inference::rms_norm(
14157                &rows[(n - 1) * hs..n * hs],
14158                &p.weights.final_norm,
14159                p.rms_eps,
14160                p.norm_style,
14161            );
14162            let mut out = vec![argmax(&p.lm_head_forward(&normed), p.vocab_size)];
14163            for s in 1..steps {
14164                let (tok, at) = (out[s - 1], n + s - 1);
14165                let lg = if token_decode {
14166                    p.decode_step_logits(tok, at)
14167                } else {
14168                    let mut hid = p.embed_single(tok);
14169                    let outcome = p.try_batch_graph_wgpu(&mut hid, &[at], 1, None);
14170                    if outcome != crate::gpu::BatchGraphOutcome::Completed {
14171                        return Err(format!("o1 parity: greedy step {s} {outcome:?}"));
14172                    }
14173                    let normed =
14174                        inference::rms_norm(&hid, &p.weights.final_norm, p.rms_eps, p.norm_style);
14175                    p.lm_head_forward(&normed)
14176                };
14177                out.push(argmax(&lg, p.vocab_size));
14178            }
14179            Ok(out)
14180        };
14181
14182        // OW first, in a fresh process as `run` starts: the host prefix
14183        // exactly as generation runs it — boundary at `split`, the
14184        // pipeline's prefill chunk, the layers sealing after the chunk that
14185        // reaches the boundary (`CMF_O1_WALK_BOUNDARY=1`: that chunk walks
14186        // its rows one at a time, each layer sealing after the boundary row).
14187        self.clear_sequence_state();
14188        self.o1_begin_with_prefix(Some(requested));
14189        let walk_chunk = self.prefill_chunk().max(1);
14190        let walk_from = (split - 1) / walk_chunk * walk_chunk;
14191        let mut ow = vec![0f32; n * hs];
14192        let mut pos = 0;
14193        while pos < split {
14194            let end = (pos + walk_chunk).min(split);
14195            let hb = self.prefill_batch(&ids[pos..end], pos);
14196            ow[pos * hs..end * hs].copy_from_slice(&hb[..(end - pos) * hs]);
14197            pos = end;
14198        }
14199        self.o1_seal_checked()?;
14200        let ow_run = graph_rows(self, split, n, &mut ow);
14201        let ow_text = ow_run.clone().and_then(|_| greedy(self, &ow));
14202
14203        // OH. Collect one row past the boundary's natural barrier so the
14204        // host walk does not seal inside the last chunk, copy the trace,
14205        // then seal at `split` exactly.
14206        let t = std::time::Instant::now();
14207        self.clear_sequence_state();
14208        self.o1_begin_with_prefix(Some(split + 1));
14209        let mut oh = vec![0f32; n * hs];
14210        let mut pos = 0;
14211        while pos < split {
14212            let end = (pos + 128).min(split);
14213            let hb = self.prefill_batch(&ids[pos..end], pos);
14214            oh[pos * hs..end * hs].copy_from_slice(&hb[..(end - pos) * hs]);
14215            pos = end;
14216        }
14217        let mut host = Vec::with_capacity(o1_layers.len());
14218        for &li in &o1_layers {
14219            let c = &self.kv_cache.layers[li];
14220            let q = c
14221                .o1_q_trace()
14222                .ok_or("o1 parity: host walk sealed early")?
14223                .to_vec();
14224            let (nkv, hd) = (c.num_kv_heads, c.head_dim);
14225            let (mut k, mut v) = (vec![0f32; split * nkv * hd], vec![0f32; split * nkv * hd]);
14226            for (h, (kh, vh)) in c.k_heads().iter().zip(c.v_heads()).enumerate() {
14227                for p in 0..split {
14228                    let d = (p * nkv + h) * hd;
14229                    k[d..d + hd].copy_from_slice(&kh[p * hd..(p + 1) * hd]);
14230                    v[d..d + hd].copy_from_slice(&vh[p * hd..(p + 1) * hd]);
14231                }
14232            }
14233            host.push((q, k, v));
14234        }
14235        for &li in &o1_layers {
14236            self.kv_cache.layers[li].o1_set_boundary(split);
14237        }
14238        self.o1_seal_checked()?;
14239        let oh_run = graph_rows(self, split, n, &mut oh);
14240        let t_oh = t.elapsed().as_secs_f64();
14241        let oh_text = oh_run.clone().and_then(|_| greedy(self, &oh));
14242
14243        // OG: graph prefix, host seal inputs. `CMF_PARITY_PERTURB=eps`
14244        // scales every host K/V value by (1 ± eps), signs from a fixed
14245        // xorshift stream: the seal's sensitivity to rounding-size noise.
14246        self.clear_sequence_state();
14247        self.o1_begin_with_prefix(Some(requested));
14248        let mut og = vec![0f32; n * hs];
14249        graph_rows(self, 0, split, &mut og)?;
14250        let perturb: f32 = std::env::var("CMF_PARITY_PERTURB")
14251            .ok()
14252            .and_then(|v| v.parse().ok())
14253            .unwrap_or(0.0);
14254        if perturb > 0.0 {
14255            let mut seed = 0x9e37_79b9_7f4a_7c15u64;
14256            let noisy: Vec<_> = host
14257                .iter()
14258                .map(|(q, k, v)| {
14259                    let mut jitter = |x: &f32| {
14260                        seed ^= seed << 13;
14261                        seed ^= seed >> 7;
14262                        seed ^= seed << 17;
14263                        x * if seed & 1 == 0 {
14264                            1.0 + perturb
14265                        } else {
14266                            1.0 - perturb
14267                        }
14268                    };
14269                    let k: Vec<f32> = k.iter().map(&mut jitter).collect();
14270                    let v: Vec<f32> = v.iter().map(&mut jitter).collect();
14271                    (q.clone(), k, v)
14272                })
14273                .collect();
14274            seal_from(self, &noisy)?;
14275        } else {
14276            seal_from(self, &host)?;
14277        }
14278        let og_run = graph_rows(self, split, n, &mut og);
14279        let og_text = og_run.clone().and_then(|_| greedy(self, &og));
14280
14281        // OD: graph prefix, the graph's own K/V with the host queries.
14282        self.clear_sequence_state();
14283        self.o1_begin_with_prefix(Some(requested));
14284        let mut od = vec![0f32; n * hs];
14285        graph_rows(self, 0, split, &mut od)?;
14286        let mut dev = Vec::with_capacity(o1_layers.len());
14287        let mut kv_rel = Vec::with_capacity(o1_layers.len());
14288        for (&li, (q, hk, hv)) in o1_layers.iter().zip(&host) {
14289            let c = &self.kv_cache.layers[li];
14290            let (k, v) = crate::gpu::graph_kv_read_rows(
14291                self.graph_kv_id,
14292                &[(li, 0, split)],
14293                c.num_kv_heads,
14294                c.head_dim,
14295            )
14296            .and_then(|mut rows| rows.pop())
14297            .ok_or_else(|| format!("o1 parity: no graph K/V rows for layer {li}"))?;
14298            kv_rel.push((li, rel_l2(hk, &k), rel_l2(hv, &v)));
14299            dev.push((q.clone(), k, v));
14300        }
14301        seal_from(self, &dev)?;
14302        let od_run = graph_rows(self, split, n, &mut od);
14303        let od_text = od_run.clone().and_then(|_| greedy(self, &od));
14304
14305        // X: exact batch graph.
14306        self.clear_sequence_state();
14307        self.set_o1(None);
14308        let mut xx = vec![0f32; n * hs];
14309        let x_run = graph_rows(self, 0, n, &mut xx);
14310        let x_text = x_run.clone().and_then(|_| greedy(self, &xx));
14311        self.clear_sequence_state();
14312        oh_run?;
14313        ow_run?;
14314        og_run?;
14315        od_run?;
14316        x_run?;
14317
14318        let sx = self.parity_score(ids, &xx, split);
14319        let arms = [
14320            ("OH", self.parity_score(ids, &oh, split)),
14321            ("OG", self.parity_score(ids, &og, split)),
14322            ("OD", self.parity_score(ids, &od, split)),
14323            ("OW", self.parity_score(ids, &ow, split)),
14324        ];
14325        let mut r = String::new();
14326        let _ = writeln!(
14327            r,
14328            "o1 seal parity: {n} tokens, boundary {split}, graph k {bk} (OH {t_oh:.1} s), \
14329             OW chunk {walk_chunk}, boundary chunk {walk_from}..{split}"
14330        );
14331        let _ = write!(r, "  seal K/V rel host vs graph:");
14332        for (li, rk, rv) in &kv_rel {
14333            let _ = write!(r, " L{li} {rk:.0e}/{rv:.0e}");
14334        }
14335        // Post-stack prefix rows against the exact graph: the batched rows,
14336        // then the rows OW walks one at a time.
14337        let worst = |a: &[f32], p0: usize, p1: usize| {
14338            (p0..p1)
14339                .map(|p| rel_l2(&a[p * hs..(p + 1) * hs], &xx[p * hs..(p + 1) * hs]))
14340                .fold(0f64, f64::max)
14341        };
14342        let _ = writeln!(
14343            r,
14344            "\n  prefix rows rel vs exact graph, [0,{walk_from}) / [{walk_from},{split}): \
14345             OH {:.1e} / {:.1e}, OW {:.1e} / {:.1e}",
14346            worst(&oh, 0, walk_from),
14347            worst(&oh, walk_from, split),
14348            worst(&ow, 0, walk_from),
14349            worst(&ow, walk_from, split),
14350        );
14351        let _ = writeln!(
14352            r,
14353            "  bin          | NLL exact    OH     OG     OD     OW | top1=exact  OH    OG    OD    OW"
14354        );
14355        let mean = |s: &[(f64, usize)], b0: usize, b1: usize| {
14356            (b0..b1).map(|p| s[p - split].0).sum::<f64>() / (b1 - b0).max(1) as f64
14357        };
14358        let agree = |s: &[(f64, usize)], b0: usize, b1: usize| {
14359            let same = (b0..b1)
14360                .filter(|&p| s[p - split].1 == sx[p - split].1)
14361                .count();
14362            100.0 * same as f64 / (b1 - b0).max(1) as f64
14363        };
14364        let mut b0 = split;
14365        let mut total = [0f64; 5];
14366        while b0 + 1 < n {
14367            let b1 = ((b0 / 256 + 1) * 256).min(n - 1);
14368            let _ = writeln!(
14369                r,
14370                "  {b0:5}..{b1:<5} | {:>9.3} {:>6.3} {:>6.3} {:>6.3} {:>6.3} | {:>12.1} {:>5.1} {:>5.1} {:>5.1}",
14371                mean(&sx, b0, b1),
14372                mean(&arms[0].1, b0, b1),
14373                mean(&arms[1].1, b0, b1),
14374                mean(&arms[2].1, b0, b1),
14375                mean(&arms[3].1, b0, b1),
14376                agree(&arms[0].1, b0, b1),
14377                agree(&arms[1].1, b0, b1),
14378                agree(&arms[2].1, b0, b1),
14379                agree(&arms[3].1, b0, b1),
14380            );
14381            b0 = b1;
14382        }
14383        for (i, s) in std::iter::once(&sx)
14384            .chain(arms.iter().map(|a| &a.1))
14385            .enumerate()
14386        {
14387            total[i] = s.iter().map(|x| x.0).sum::<f64>() / s.len().max(1) as f64;
14388        }
14389        let _ = writeln!(
14390            r,
14391            "  all          | {:>9.3} {:>6.3} {:>6.3} {:>6.3} {:>6.3} | ppl ratio vs exact OH ×{:.3} OG ×{:.3} OD ×{:.3} OW ×{:.3}",
14392            total[0],
14393            total[1],
14394            total[2],
14395            total[3],
14396            total[4],
14397            (total[1] - total[0]).exp(),
14398            (total[2] - total[0]).exp(),
14399            (total[3] - total[0]).exp(),
14400            (total[4] - total[0]).exp(),
14401        );
14402        for (name, text) in [
14403            ("X ", x_text),
14404            ("OH", oh_text),
14405            ("OG", og_text),
14406            ("OD", od_text),
14407            ("OW", ow_text),
14408        ] {
14409            let s = text.map_or_else(|e| e, |t| self.tokenizer.decode(&t));
14410            let _ = writeln!(r, "  greedy {name}: {:?}", s);
14411        }
14412        Ok(r)
14413    }
14414
14415    /// The positions of `input_ids` a Dory sequence already holds: the common
14416    /// prefix, unless going back to it passes what a sliding ring still keeps.
14417    fn dory_cached_prefix(&self, input_ids: &[u32]) -> usize {
14418        if std::env::var("CMF_KV_REUSE").is_ok_and(|v| v == "0") {
14419            return 0;
14420        }
14421        let h = &self.kv_history;
14422        let lcp = h.iter().zip(input_ids).take_while(|(a, b)| a == b).count();
14423        let n = lcp.min(input_ids.len().saturating_sub(1));
14424        if n == 0 || h.len() - n > crate::dory::REWIND {
14425            return 0;
14426        }
14427        // Rows past the prefix have gone through the far field: a sealed sequence can
14428        // only be extended, and a turn that goes back starts over.
14429        let sealed = crate::gpu::dory_sealed(self.graph_kv_id)
14430            || self.dory.as_ref().is_some_and(|b| b.1.slots.iter().flatten().any(|s| !s.far.is_empty()));
14431        if n < h.len() && sealed {
14432            return 0;
14433        }
14434        n
14435    }
14436
14437    /// Dory's score: chunks through its own stack, logits of every row.
14438    fn dory_nll(&mut self, ids: &[u32], start: usize) -> Result<(f64, usize), String> {
14439        self.clear_sequence_state();
14440        let chunk: usize = std::env::var("CMF_NLL_CHUNK")
14441            .ok()
14442            .and_then(|v| v.parse().ok())
14443            .filter(|&c: &usize| c > 0)
14444            .unwrap_or(128);
14445        let vocab = self.vocab_size;
14446        let n = ids.len().saturating_sub(1);
14447        // `CMF_NLL_SKIP`: a prompt of so many rows goes in as a prompt does.
14448        let skip: usize = std::env::var("CMF_NLL_SKIP").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
14449        let start = start.max(skip.min(n));
14450        let (mut nll, mut cnt, mut pos) = (0f64, 0usize, 0usize);
14451        while pos < n {
14452            if pos < skip {
14453                let end = (pos + 64).min(skip).min(n);
14454                self.dory_forward(&ids[pos..end], pos, crate::dory::Want::None);
14455                pos = end;
14456                continue;
14457            }
14458            let end = (pos + chunk).min(n);
14459            let lg = self.dory_forward(&ids[pos..end], pos, crate::dory::Want::All);
14460            for (r, row) in lg.chunks_exact(vocab).enumerate() {
14461                if pos + r < start {
14462                    continue;
14463                }
14464                let target = ids[pos + r + 1] as usize;
14465                let best = row.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b)) as f64;
14466                let den: f64 = row.iter().map(|&x| ((x as f64) - best).exp()).sum();
14467                nll += den.ln() - (row[target] as f64 - best);
14468                cnt += 1;
14469            }
14470            pos = end;
14471        }
14472        Ok((nll, cnt))
14473    }
14474
14475    /// Dory's forward over a chunk: the device path when it takes the file.
14476    fn dory_forward(&mut self, ids: &[u32], pos: usize, want: crate::dory::Want) -> Vec<f32> {
14477        let pool = self.pool.clone();
14478        let id = self.graph_kv_id;
14479        let b = self.dory.as_mut().expect("a Dory file");
14480        let (m, st) = (&b.0, &mut b.1);
14481        let mut logits = Vec::new();
14482        let loops = m.cfg.loops;
14483        // GPTQ's Hessian hook sees a matrix's input only on the host stack.
14484        let host = crate::gptq_capture::capturing();
14485        let file = m.file.clone();
14486        if host || !crate::gpu::dory_forward(id, file.as_ref(), m, ids, pos, loops, want, &mut logits) {
14487            logits.clear();
14488            crate::dory::forward_host(m, st, ids, pos, loops, want, pool.as_deref(), None, &mut logits);
14489        }
14490        if m.o1.is_some() && std::env::var_os("CMF_DORY_KV_REPORT").is_some() {
14491            let (e, f) = crate::dory::host_kv_bytes(st);
14492            eprintln!("dory kv at {}: exact {:.1} MB, far {:.1} MB", pos + ids.len(), e as f64 / 1e6, f as f64 / 1e6);
14493        }
14494        if let Ok(dir) = std::env::var("CMF_DORY_DUMP") {
14495            let bytes: Vec<u8> = logits.iter().flat_map(|v| v.to_le_bytes()).collect();
14496            let _ = std::fs::write(format!("{dir}/{pos}.bin"), bytes);
14497        }
14498        logits
14499    }
14500
14501    fn nll_ids_inner(
14502        &mut self,
14503        ids: &[u32],
14504        start: usize,
14505        task_mask: Option<&TaskMask>,
14506    ) -> Result<(f64, usize), String> {
14507        if self.dory.is_some() && task_mask.is_none() {
14508            return self.dory_nll(ids, start);
14509        }
14510        // Hy4-flash: the window on the card's prompt graph, the head on the host
14511        if task_mask.is_none()
14512            && let Some(b) = &mut self.hy4
14513            && let Some(r) = crate::hy4::nll(&b.0, &b.1, &b.2, &mut b.3, ids, start, self.pool.as_deref())
14514        {
14515            return Ok(r);
14516        }
14517        // Maxwell-V1-Flash: the same, through its own stack
14518        if task_mask.is_none()
14519            && let Some(b) = &mut self.maxwell
14520            && let Some(r) = crate::maxwell::nll(&b.0, &b.1, &b.2, &mut b.3, ids, start, self.pool.as_deref())
14521        {
14522            return Ok(r);
14523        }
14524        // Inkling-2-Mini: the same, through its own stack
14525        if task_mask.is_none()
14526            && let Some(b) = &mut self.inkling
14527            && let Some(r) = crate::inkling::nll(&b.0, &b.1, &b.2, &mut b.3, ids, start, self.pool.as_deref())
14528        {
14529            return Ok(r);
14530        }
14531        self.nll_begin()?;
14532        // Block diffusion on Apple silicon: the Metal executor's causal path.
14533        #[cfg(target_os = "macos")]
14534        if task_mask.is_none() && self.is_block_diffusion() {
14535            if let Some(r) = self.clover_metal_nll(ids, start) {
14536                self.nll_end();
14537                return r;
14538            }
14539        }
14540        let result: Result<(f64, usize), String> = (|| {
14541            let mut nll = 0f64;
14542            let mut cnt = 0usize;
14543            // An unmasked quality run with the resident wgpu graph must score
14544            // the same stateful path used by generation.  The layer-major
14545            // GEMM prefill below is a valid CPU/GEMM oracle, but it seeds
14546            // neither the graph's device GDN state nor its device KV mirrors;
14547            // using it here would silently score a different execution.  Keep
14548            // masked scoring on the exact per-position path as before, and
14549            // let the serial arm below drive the graph-aware scorer.
14550            // Only native Metal has a fused graph lm_head contract.  Vulkan
14551            // and other graph backends may expose hidden state without the
14552            // optional logits side channel; preserve their established CPU
14553            // norm/head fallback instead of turning that valid route into a
14554            // hard missing-logits error.
14555            let (graph_quality, fused_head_quality) = nll_graph_policy(
14556                task_mask.is_none(),
14557                self.graph_prefill_preferred(),
14558                crate::gpu::q1_force(),
14559            );
14560            self.graph_head_required = fused_head_quality;
14561            self.graph_want_logits = fused_head_quality;
14562            #[cfg(target_os = "macos")]
14563            if graph_quality && std::env::var("CMF_METAL_BATCH_NLL").as_deref() != Ok("0") {
14564                match self.nll_batch_metal(ids, start) {
14565                    MetalBatchNllOutcome::Completed(nll, count) => {
14566                        return Ok((nll, count));
14567                    }
14568                    MetalBatchNllOutcome::Declined => {}
14569                    MetalBatchNllOutcome::Failed(err) => return Err(err),
14570                }
14571            }
14572            // CMF_NLL_SERIAL=1 scores position by position through the
14573            // decode path (the wgpu token graph where it admits the model)
14574            // — the perplexity gate of a decode kernel, which the batched
14575            // prefill arm below never runs.
14576            let force_serial = std::env::var("CMF_NLL_SERIAL").as_deref() == Ok("1");
14577            if self.can_prefill_batched() && !graph_quality && !force_serial {
14578                // prefill-GEMM: layer-major position chunks, lm_head batched
14579                // (254MB lm_head read once per chunk, not per position).
14580                // The layer chunk is large (grouping positions by MoE experts
14581                // wins with size), lm_head in sub-blocks (logit buffer
14582                // 32×vocab ≈ 32MB instead of 128×).
14583                // CMF_NLL_CHUNK: positions per prefill step (default 128).
14584                // A device scorer pays one round trip per projection per
14585                // step, so a 512-position step quarters them.
14586                let chunk_len: usize = std::env::var("CMF_NLL_CHUNK")
14587                    .ok()
14588                    .and_then(|v| v.parse().ok())
14589                    .filter(|&c: &usize| c > 0)
14590                    .unwrap_or(128);
14591                const LM_SUB: usize = 32;
14592                let n = ids.len().saturating_sub(1);
14593                let hs = self.hidden_size;
14594                let rows = self.weights.lm_head.rows();
14595                let mut pos = 0usize;
14596                let state_trace = std::env::var("CMF_STATE_TRACE").is_ok();
14597                while pos < n {
14598                    let end = (pos + chunk_len).min(n);
14599                    let bsz = end - pos;
14600                    let hb = self.prefill_rows(&ids[pos..end], pos, task_mask)?;
14601                    self.nll_check_graph("batched prefill", pos)?;
14602                    if state_trace && end % 256 == 0 {
14603                        self.trace_recurrent_state(end);
14604                    }
14605                    let mut k0 = 0usize;
14606                    while k0 < bsz {
14607                        let k1 = (k0 + LM_SUB).min(bsz);
14608                        let sb = k1 - k0;
14609                        // Sub-block entirely below the scored range: the KV
14610                        // it just built is all this pass needed from it.
14611                        if pos + k1 <= start {
14612                            k0 = k1;
14613                            continue;
14614                        }
14615                        let mut normed = vec![0.0f32; sb * hs];
14616                        for k in 0..sb {
14617                            let r = inference::rms_norm(
14618                                &hb[(k0 + k) * hs..(k0 + k + 1) * hs],
14619                                &self.weights.final_norm,
14620                                self.rms_eps,
14621                                self.norm_style,
14622                            );
14623                            normed[k * hs..(k + 1) * hs].copy_from_slice(&r);
14624                        }
14625                        let mut logits = vec![0.0f32; sb * rows];
14626                        self.weights
14627                            .lm_head
14628                            .matmat(&normed, sb, &mut logits, self.pool.as_deref());
14629                        for k in 0..sb {
14630                            if pos + k0 + k < start {
14631                                continue;
14632                            }
14633                            self.nll_check_graph("batched score row", pos + k0 + k)?;
14634                            let lg = &mut logits[k * rows..k * rows + self.vocab_size.min(rows)];
14635                            if let Some(mu) = self.logit_multiplier {
14636                                for v in lg.iter_mut() {
14637                                    *v *= mu;
14638                                }
14639                            }
14640                            // Gemma-class final-logit soft-capping: the
14641                            // decode paths apply it; scoring must too, or
14642                            // the uncapped softmax misprices every token.
14643                            if let Some(c) = self.final_softcap {
14644                                softcap_in_place(lg, c, self.pool.as_deref());
14645                            }
14646                            // Cortiq Embryo hierarchical head: same correction
14647                            // the decode path applies (lm_head_forward).
14648                            if let Some(cm) = self.head_clusters.clone() {
14649                                self.hierarchical_head_logprobs(
14650                                    &normed[k * hs..(k + 1) * hs],
14651                                    &cm,
14652                                    lg,
14653                                );
14654                            }
14655                            let lg = &logits[k * rows..k * rows + self.vocab_size.min(rows)];
14656                            let target = ids[pos + k0 + k + 1] as usize;
14657                            let max = lg.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
14658                            let lse: f64 = lg
14659                                .iter()
14660                                .map(|&v| ((v - max) as f64).exp())
14661                                .sum::<f64>()
14662                                .ln()
14663                                + max as f64;
14664                            nll += lse - lg[target] as f64;
14665                            cnt += 1;
14666                            if std::env::var("CMF_PPL_TRACE").is_ok() {
14667                                let top = lg
14668                                    .iter()
14669                                    .enumerate()
14670                                    .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
14671                                    .map(|(i, _)| i)
14672                                    .unwrap_or(0);
14673                                eprintln!(
14674                                    "BTRACE pos {} target {} nll {:.4} top {} lg_t {:.3} lg_top {:.3}",
14675                                    pos + k0 + k,
14676                                    target,
14677                                    lse - lg[target] as f64,
14678                                    top,
14679                                    lg[target],
14680                                    lg[top]
14681                                );
14682                            }
14683                        }
14684                        k0 = k1;
14685                    }
14686                    pos = end;
14687                }
14688                return Ok((nll, cnt));
14689            }
14690            for pos in 0..ids.len().saturating_sub(1) {
14691                let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, task_mask);
14692                self.nll_check_graph("serial forward", pos)?;
14693                // Architectures whose head lives inside their own stack return
14694                // the logits out of band and a zero hidden — DeepSeek-V4 folds
14695                // its hyper-connection copies between the last layer and the
14696                // norm, so it cannot hand back a vector this loop could use.
14697                // Scoring the zeros gave a perplexity of exactly the vocabulary
14698                // size, which is a uniform distribution reported as a
14699                // measurement. `generate` already reads this channel.
14700                let out_of_band = self.graph_logits.take();
14701                if self.graph_head_required && out_of_band.is_none() {
14702                    METAL_GRAPH_HEAD_MISS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14703                    return Err(format!(
14704                        "fused Metal graph head did not complete at NLL position {pos}"
14705                    ));
14706                }
14707                if pos < start {
14708                    continue;
14709                }
14710                let logits = match out_of_band {
14711                    Some(lg) => lg,
14712                    None => {
14713                        let normed = inference::rms_norm(
14714                            &hidden,
14715                            &self.weights.final_norm,
14716                            self.rms_eps,
14717                            self.norm_style,
14718                        );
14719                        // lm_head_forward applies the final-logit softcap itself
14720                        // — capping again here double-squashed gemma-class
14721                        // logits (tanh∘tanh) and reported a flattered ppl.
14722                        self.lm_head_forward(&normed)
14723                    }
14724                };
14725                let target = ids[pos + 1] as usize;
14726                let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
14727                let lse: f64 = logits
14728                    .iter()
14729                    .map(|&v| ((v - max) as f64).exp())
14730                    .sum::<f64>()
14731                    .ln()
14732                    + max as f64;
14733                let tok_nll = lse - logits[target] as f64;
14734                if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 10_000 {
14735                    let top = logits
14736                        .iter()
14737                        .enumerate()
14738                        .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
14739                        .map(|(i, _)| i)
14740                        .unwrap_or(0);
14741                    eprintln!(
14742                        "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
14743                        logits[target], logits[top]
14744                    );
14745                }
14746                nll += tok_nll;
14747                cnt += 1;
14748            }
14749            Ok((nll, cnt))
14750        })();
14751        self.nll_end();
14752        result
14753    }
14754
14755    /// Score one post-layer hidden with the same final norm/head path used by
14756    /// decode. Keeping this in one helper is important for the production
14757    /// batch scorer: its rows stop before the final norm, just like the
14758    /// per-position O(1) path below.
14759    fn nll_from_hidden(&mut self, hidden: &[f32], target: u32, pos: usize) -> f64 {
14760        let normed = inference::rms_norm(
14761            hidden,
14762            &self.weights.final_norm,
14763            self.rms_eps,
14764            self.norm_style,
14765        );
14766        // lm_head_forward applies the final-logit softcap itself — capping
14767        // again here double-squashed gemma-class logits in earlier scorers.
14768        let mut logits = self.lm_head_forward(&normed);
14769        let target = target as usize;
14770        let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
14771        let lse: f64 = logits
14772            .iter()
14773            .map(|&v| ((v - max) as f64).exp())
14774            .sum::<f64>()
14775            .ln()
14776            + max as f64;
14777        let tok_nll = lse - logits[target] as f64;
14778        if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 10_000 {
14779            let top = logits
14780                .iter()
14781                .enumerate()
14782                .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
14783                .map(|(i, _)| i)
14784                .unwrap_or(0);
14785            eprintln!(
14786                "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
14787                logits[target], logits[top]
14788            );
14789        }
14790        attention::recycle_buf(&mut logits);
14791        tok_nll
14792    }
14793
14794    /// Why the device scorer ([`Self::score_ids_device`]) does not take
14795    /// this pipeline, `None` when it does: a CUDA or wgpu backend with the
14796    /// batch graph, a plain head the verify tail can run, and none of the
14797    /// architectures that score through a stack of their own.
14798    pub fn device_score_decline(&self) -> Option<&'static str> {
14799        if !crate::gpu::enabled_here() || !(crate::gpu::cuda_active() || crate::gpu::wgpu_active()) {
14800            return Some("no CUDA or wgpu backend in use");
14801        }
14802        if !crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill) {
14803            return Some("the batch graph is off on this device");
14804        }
14805        if self.graph_refused() {
14806            return Some("the token graph is refused for this pipeline");
14807        }
14808        if self.o1_active() {
14809            return Some("an O(1) far field");
14810        }
14811        if self.dory.is_some()
14812            || self.hy4.is_some()
14813            || self.maxwell.is_some()
14814            || self.inkling.is_some()
14815            || self.dash.is_some()
14816            || self.dsv41.is_some()
14817            || self.is_block_diffusion()
14818            || self.embryo_resident_eligible()
14819        {
14820            return Some("an architecture with its own stack");
14821        }
14822        if self.head_clusters.is_some() {
14823            return Some("a hierarchical head");
14824        }
14825        if self.weights.lm_head.has_prism_contract() || self.weights.lm_head.graph_weight().is_none() {
14826            return Some("the lm_head has no plain graph weight");
14827        }
14828        None
14829    }
14830
14831    /// Teacher-forced scores of `ids[start + 1..]` on the device batch
14832    /// graph (CUDA or wgpu): each target's log-probability given every id
14833    /// before it, and whether it is the argmax. The positions before
14834    /// `start` ride prompt chunks of `generation_batch_k` rows with no
14835    /// head; the scored rows go through verify windows of
14836    /// [`DEVICE_SCORE_ROWS`], whose final norm and lm_head run on the card,
14837    /// so only their logits come back. `Ok(None)`: the device route does
14838    /// not take this pipeline and nothing ran (the caller keeps its host
14839    /// scorer). Once a chunk has completed, the device owns the sequence:
14840    /// a later decline is an error, never a silent host fallback.
14841    pub fn score_ids_device(&mut self, ids: &[u32], start: usize) -> Result<Option<Vec<TokenScore>>, String> {
14842        let n = ids.len();
14843        if start + 1 >= n {
14844            return Err(format!("device scorer: start {start} leaves no target among {n} ids"));
14845        }
14846        if self.device_score_decline().is_some() {
14847            return Ok(None);
14848        }
14849        if n > self.kv_cache.max_seq_len {
14850            return Err(format!(
14851                "device scorer: {n} ids exceed the context of {} positions",
14852                self.kv_cache.max_seq_len
14853            ));
14854        }
14855        let lm_rows = self.weights.lm_head.rows();
14856        let vocab = self.vocab_size.min(lm_rows);
14857        if let Some(&bad) = ids[start + 1..].iter().find(|&&t| t as usize >= vocab) {
14858            return Err(format!("device scorer: target {bad} outside the head's {vocab} rows"));
14859        }
14860        self.nll_begin()?;
14861        let hs = self.hidden_size;
14862        let mut ran = false;
14863        // what a decline means: nothing on the device yet, or a broken sequence
14864        let declined = |p: &mut Self, ran: bool, at: usize| -> Result<Option<Vec<TokenScore>>, String> {
14865            p.nll_end();
14866            if ran {
14867                Err(format!("device scorer: the batch graph declined at position {at} after earlier chunks ran"))
14868            } else {
14869                Ok(None)
14870            }
14871        };
14872        let chunk = match self.generation_batch_k() {
14873            0 => 128,
14874            k => k,
14875        };
14876        let mut pos = 0usize;
14877        while pos < start {
14878            let end = (pos + chunk).min(start);
14879            let k = end - pos;
14880            let mut h = vec![0f32; k * hs];
14881            for (r, &id) in ids[pos..end].iter().enumerate() {
14882                h[r * hs..(r + 1) * hs].copy_from_slice(&self.embed_single(id));
14883            }
14884            let positions: Vec<usize> = (pos..end).collect();
14885            let outcome = self.try_batch_graph_wgpu(&mut h, &positions, k, None);
14886            if let Err(e) = self.nll_check_graph("device score prefix", pos) {
14887                self.nll_end();
14888                return Err(e);
14889            }
14890            match outcome {
14891                crate::gpu::BatchGraphOutcome::Completed => ran = true,
14892                crate::gpu::BatchGraphOutcome::Declined => return declined(self, ran, pos),
14893                crate::gpu::BatchGraphOutcome::Failed => {
14894                    self.nll_end();
14895                    return Err(format!("device scorer: the batch graph failed at position {pos}"));
14896                }
14897            }
14898            pos = end;
14899        }
14900        let mut out = Vec::with_capacity(n - 1 - start);
14901        let mut logits = Vec::new();
14902        while pos < n - 1 {
14903            let end = (pos + DEVICE_SCORE_ROWS).min(n - 1);
14904            let w = end - pos;
14905            let mut h = vec![0f32; w * hs];
14906            for (r, &id) in ids[pos..end].iter().enumerate() {
14907                h[r * hs..(r + 1) * hs].copy_from_slice(&self.embed_single(id));
14908            }
14909            let positions: Vec<usize> = (pos..end).collect();
14910            let outcome = match self.weights.lm_head.graph_weight() {
14911                Some((_, idx, kind, row_scale)) => self.try_batch_graph_wgpu(
14912                    &mut h,
14913                    &positions,
14914                    w,
14915                    Some(crate::gpu::SpecTail {
14916                        lm: crate::gpu::GraphW {
14917                            idx,
14918                            kind,
14919                            row_scale,
14920                            data: &[],
14921                            prism: crate::gpu::GraphPrismOp::None,
14922                            affine: false,
14923                        },
14924                        lm_rows,
14925                        final_norm: &self.weights.final_norm,
14926                        logits_out: &mut logits,
14927                        pick: None,
14928                    }),
14929                ),
14930                None => crate::gpu::BatchGraphOutcome::Declined,
14931            };
14932            if let Err(e) = self.nll_check_graph("device score window", pos) {
14933                self.nll_end();
14934                return Err(e);
14935            }
14936            match outcome {
14937                crate::gpu::BatchGraphOutcome::Completed if logits.len() >= w * lm_rows => ran = true,
14938                crate::gpu::BatchGraphOutcome::Declined => return declined(self, ran, pos),
14939                _ => {
14940                    self.nll_end();
14941                    return Err(format!(
14942                        "device scorer: the verify window at position {pos} failed or returned {} of {} logits",
14943                        logits.len(),
14944                        w * lm_rows
14945                    ));
14946                }
14947            }
14948            // the multiplier and the soft cap the host head applies
14949            // (`lm_head_forward`); the verify tail stops at the GEMM
14950            let (mu, cap) = (self.logit_multiplier, self.final_softcap);
14951            let mut rows: Vec<&mut [f32]> = logits.chunks_mut(lm_rows).take(w).map(|r| &mut r[..vocab]).collect();
14952            let mut scored = vec![TokenScore { logprob: 0.0, greedy: false }; w];
14953            std::thread::scope(|s| {
14954                for (r, (lg, sc)) in rows.iter_mut().zip(scored.iter_mut()).enumerate() {
14955                    let target = ids[pos + r + 1] as usize;
14956                    s.spawn(move || {
14957                        if let Some(mu) = mu {
14958                            lg.iter_mut().for_each(|v| *v *= mu);
14959                        }
14960                        if let Some(c) = cap {
14961                            softcap_in_place(lg, c, None);
14962                        }
14963                        let (mut top, mut max) = (0usize, f32::NEG_INFINITY);
14964                        for (i, &v) in lg.iter().enumerate() {
14965                            if v > max {
14966                                (top, max) = (i, v);
14967                            }
14968                        }
14969                        let lse = lg.iter().map(|&v| ((v - max) as f64).exp()).sum::<f64>().ln() + max as f64;
14970                        *sc = TokenScore { logprob: lg[target] as f64 - lse, greedy: top == target };
14971                    });
14972                }
14973            });
14974            out.extend(scored);
14975            pos = end;
14976        }
14977        self.nll_end();
14978        Ok(Some(out))
14979    }
14980
14981    /// `CMF_STATE_TRACE`: per-layer magnitude of the recurrent record at
14982    /// position `pos` — the whole `linear_state` (vmf: S then the conv
14983    /// ring; GDN: conv ring then S), its recurrent S part alone, the
14984    /// bounded ring, and the last per-position KV row count.  The tool
14985    /// that separated the ~4k perplexity cliff of the 500-step exports
14986    /// (a state that keeps climbing past the trained window) from a
14987    /// runtime boundary; one line per layer, `STATE pos=… layer=…`.
14988    fn trace_recurrent_state(&self, pos: usize) {
14989        let stats = |v: &[f32]| -> (f64, f64) {
14990            if v.is_empty() {
14991                return (0.0, 0.0);
14992            }
14993            let (mut ss, mut mx) = (0f64, 0f64);
14994            for &x in v {
14995                ss += (x as f64) * (x as f64);
14996                mx = mx.max((x as f64).abs());
14997            }
14998            ((ss / v.len() as f64).sqrt(), mx)
14999        };
15000        for (li, l) in self.kv_cache.layers.iter().enumerate() {
15001            let lw = &self.weights.layers[self.phys_layer(li)];
15002            let (kind, s_len) = match &lw.attn {
15003                AttnKind::Linear(_) => ("vmf", self.vmf_cfg.map(|c| c.state_len()).unwrap_or(0)),
15004                AttnKind::LinearGdn(_) => ("gdn", self.gdn_cfg.map(|c| c.state_len()).unwrap_or(0)),
15005                AttnKind::Bounded(_) => ("bounded", 0),
15006                AttnKind::Full { .. } => ("full", 0),
15007                _ => ("other", 0),
15008            };
15009            let (rms, max) = stats(&l.linear_state);
15010            let s_part = if kind == "vmf" {
15011                &l.linear_state[..s_len.min(l.linear_state.len())]
15012            } else if kind == "gdn" {
15013                let ring = l
15014                    .linear_state
15015                    .len()
15016                    .saturating_sub(s_len)
15017                    .min(l.linear_state.len());
15018                &l.linear_state[ring..]
15019            } else {
15020                &l.linear_state[..0]
15021            };
15022            let (s_rms, s_max) = stats(s_part);
15023            let (ring_rms, ring_len) = match &l.bounded {
15024                Some(b) => (stats(&b.ring_k).0, b.ring_k.len()),
15025                None => (0.0, 0),
15026            };
15027            eprintln!(
15028                "STATE pos={pos} layer={li} kind={kind} state_len={} rms={rms:.5} max={max:.4} \
15029                 S_rms={s_rms:.5} S_max={s_max:.4} ring_k_rms={ring_rms:.5} ring_len={ring_len} kv_rows={}",
15030                l.linear_state.len(),
15031                l.seq_len
15032            );
15033        }
15034    }
15035
15036    /// Teacher-forced NLL of the CONVERTED model: the O(1) Nyström path
15037    /// is ACTIVE over the scored positions. Returns `Ok((nll sum, scored
15038    /// count))` over `prefill..len-1` and surfaces a post-mutation batch
15039    /// failure instead of returning a partial score.
15040    ///
15041    /// Runtime discipline, deliberately NOT the matrix probe's: the
15042    /// requested prefix plus any required deferred lead-in run the exact
15043    /// prompt pass — that pass is what freezes the landmarks and M — and
15044    /// every post-seal scored position goes through `NystromState::step()`,
15045    /// the same code decode runs.
15046    /// So the landmarks are PREFILL-frozen (what ships), not
15047    /// full-sequence oracles (what the published probe measured). When the
15048    /// requested prefix is shorter than the bounded transition, rows in the
15049    /// exact lead-in are still scored so the shifted target range is stable.
15050    ///
15051    /// Pair with `nll_ids_from(ids, prefill)` for the exact baseline
15052    /// over the identical token set — that ratio is the honest one.
15053    pub fn nll_ids_o1(&mut self, ids: &[u32], prefill: usize) -> Result<(f64, usize), String> {
15054        // This scorer consumes host hiddens, so never request the optional
15055        // token-graph lm_head side channel. `nll_begin` also consumes a
15056        // prior graph failure and clears only the cancel bit that failure
15057        // raised, leaving a caller-owned cancellation observable.
15058        self.nll_begin()?;
15059        let requested_prefix = (prefill > 0).then_some(prefill);
15060        self.o1_begin_with_prefix(requested_prefix);
15061        let n = ids.len().saturating_sub(1);
15062        let requested_start = prefill.min(n);
15063        // The exact prefix must reach the deferred boundary before a
15064        // collecting layer can convert. Rows between the requested start and
15065        // that boundary remain part of the public NLL range and are scored
15066        // from the same hidden pass below.
15067        let exact_end = if self.o1_active() {
15068            match requested_prefix {
15069                Some(requested) => self.o1_effective_boundary(requested),
15070                None => self
15071                    .o1_cfg
15072                    .as_ref()
15073                    .and_then(|c| crate::nystrom::o1_deferred_boundary(c.w, c.sink)),
15074            }
15075            .unwrap_or(requested_start)
15076            .min(n)
15077        } else {
15078            requested_start
15079        };
15080        let mut nll = 0f64;
15081        let mut cnt = 0usize;
15082
15083        // Exact prompt pass over ids[..exact_end]: the seal consumes its
15084        // q/k/v. Rows at or after requested_start are scored here when the
15085        // bounded lead-in is longer than the caller's requested prefix.
15086        let mut pos = 0usize;
15087        if self.can_prefill_batched() {
15088            const CHUNK: usize = 128;
15089            while pos < exact_end {
15090                let end = (pos + CHUNK).min(exact_end);
15091                let hiddens = self.prefill_batch(&ids[pos..end], pos);
15092                if self
15093                    .graph_failed
15094                    .swap(false, std::sync::atomic::Ordering::Relaxed)
15095                {
15096                    self.cancel
15097                        .store(false, std::sync::atomic::Ordering::Relaxed);
15098                    self.nll_end();
15099                    return Err("GPU graph failed during O(1) NLL prefix".into());
15100                }
15101                for row in 0..end - pos {
15102                    let score_pos = pos + row;
15103                    if score_pos >= requested_start && score_pos < n {
15104                        nll += self.nll_from_hidden(
15105                            &hiddens[row * self.hidden_size..(row + 1) * self.hidden_size],
15106                            ids[score_pos + 1],
15107                            score_pos,
15108                        );
15109                        cnt += 1;
15110                    }
15111                }
15112                pos = end;
15113            }
15114        } else {
15115            while pos < exact_end {
15116                let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
15117                if self
15118                    .graph_failed
15119                    .swap(false, std::sync::atomic::Ordering::Relaxed)
15120                {
15121                    self.cancel
15122                        .store(false, std::sync::atomic::Ordering::Relaxed);
15123                    self.nll_end();
15124                    return Err("GPU graph failed during O(1) NLL prefix".into());
15125                }
15126                if pos >= requested_start && pos < n {
15127                    nll += self.nll_from_hidden(&hidden, ids[pos + 1], pos);
15128                    cnt += 1;
15129                }
15130                pos += 1;
15131            }
15132        }
15133        self.o1_seal_checked().map_err(|err| {
15134            self.nll_end();
15135            err
15136        })?;
15137
15138        // Reuse the production whole-token batch graph for the post-seal
15139        // suffix when the caller explicitly enabled both routes. This is a
15140        // teacher-forced scorer, so every row is ids[pos] and its target is
15141        // ids[pos + 1]; no speculative tail or rollback state is involved.
15142        // A first Declined is safe to handle with the established serial O(1)
15143        // path. Once a chunk completes, however, the device recurrent state
15144        // owns the sequence and a later decline must be terminal rather than
15145        // falling back to stale CPU state.
15146        let batch_k = std::env::var("CMF_BATCH_K")
15147            .ok()
15148            .and_then(|v| v.parse::<usize>().ok())
15149            .unwrap_or(0);
15150        let batch_admitted = batch_k > 0
15151            && self.can_prefill_batched()
15152            && self.o1_active()
15153            && self.o1_on_graph()
15154            && (0..self.num_layers).all(|li| {
15155                let cache = &self.kv_cache.layers[self.phys_layer(li)];
15156                cache.o1.is_none() || cache.o1_views().is_some()
15157            });
15158        if std::env::var("CMF_GRAPH_PROF").is_ok() {
15159            eprintln!(
15160                "nll-batch: phase=post-seal admission={} requested_k={} scored_rows={}",
15161                batch_admitted,
15162                batch_k,
15163                n.saturating_sub(exact_end),
15164            );
15165        }
15166        let mut batch_completed = false;
15167        if batch_admitted && exact_end < n {
15168            let hs = self.hidden_size;
15169            let mut batch_pos = exact_end;
15170            while batch_pos < n {
15171                let end = (batch_pos + batch_k).min(n);
15172                let bk = end - batch_pos;
15173                let mut hiddens = vec![0.0f32; bk * hs];
15174                for (row, &id) in ids[batch_pos..end].iter().enumerate() {
15175                    hiddens[row * hs..(row + 1) * hs].copy_from_slice(&self.embed_single(id));
15176                }
15177                let positions: Vec<usize> = (batch_pos..end).collect();
15178                let t_batch = std::time::Instant::now();
15179                let outcome = self.try_batch_graph_wgpu(&mut hiddens, &positions, bk, None);
15180                if std::env::var("CMF_GRAPH_PROF").is_ok() {
15181                    let ms = t_batch.elapsed().as_secs_f64() * 1000.0;
15182                    eprintln!(
15183                        "nll-batch: phase=post-seal mode=o1 k={bk} pos={}..{} outcome={outcome:?} {ms:.1} ms ({:.1} tok/s)",
15184                        batch_pos,
15185                        end.saturating_sub(1),
15186                        bk as f64 / (ms / 1000.0),
15187                    );
15188                }
15189                if let Err(err) = self.nll_check_graph("batch graph", batch_pos) {
15190                    self.nll_end();
15191                    return Err(err);
15192                }
15193                match outcome {
15194                    crate::gpu::BatchGraphOutcome::Completed => {
15195                        batch_completed = true;
15196                        for row in 0..bk {
15197                            nll += self.nll_from_hidden(
15198                                &hiddens[row * hs..(row + 1) * hs],
15199                                ids[batch_pos + row + 1],
15200                                batch_pos + row,
15201                            );
15202                            cnt += 1;
15203                        }
15204                        batch_pos = end;
15205                    }
15206                    crate::gpu::BatchGraphOutcome::Declined => {
15207                        if batch_completed {
15208                            self.nll_end();
15209                            return Err(format!(
15210                                "O(1) NLL batch declined after completed chunk at position {batch_pos}"
15211                            ));
15212                        }
15213                        break;
15214                    }
15215                    crate::gpu::BatchGraphOutcome::Failed => {
15216                        self.nll_end();
15217                        return Err(format!(
15218                            "O(1) NLL batch graph failed after admission at position {batch_pos}"
15219                        ));
15220                    }
15221                }
15222            }
15223            if batch_completed && cnt == n.saturating_sub(requested_start) {
15224                self.nll_end();
15225                return Ok((nll, cnt));
15226            }
15227        }
15228
15229        // Serial O(1) fallback/reference. It is intentionally retained when
15230        // batch admission declines before mutation; callers must label this
15231        // CMF_BATCH_K=0/per-position path separately from the production
15232        // whole-token batch route.
15233        for pos in exact_end..n {
15234            let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
15235            if self
15236                .graph_failed
15237                .swap(false, std::sync::atomic::Ordering::Relaxed)
15238            {
15239                self.cancel
15240                    .store(false, std::sync::atomic::Ordering::Relaxed);
15241                self.nll_end();
15242                return Err(format!(
15243                    "GPU graph failed during O(1) NLL serial scoring at position {pos}"
15244                ));
15245            }
15246            nll += self.nll_from_hidden(&hidden, ids[pos + 1], pos);
15247            cnt += 1;
15248        }
15249        self.nll_end();
15250        Ok((nll, cnt))
15251    }
15252
15253    /// Teacher-forced calibration data (B1): for each position, whether the
15254    /// argmax equals the actual next token, and the top-1 softmax prob
15255    /// (top-1 probability) under EACH temperature in `temps` — all from ONE forward
15256    /// pass (argmax/correctness are temperature-invariant; only p_max
15257    /// reshapes). Feeds `cortiq calibrate` (reliability/ECE + temperature
15258    /// fit): is the model's confidence a true property, or does it need a
15259    /// measured scaling?
15260    pub fn calib_ids(&mut self, ids: &[u32], temps: &[f32]) -> (Vec<bool>, Vec<Vec<f32>>) {
15261        self.clear_sequence_state();
15262        let n = ids.len().saturating_sub(1);
15263        let mut correct = Vec::with_capacity(n);
15264        let mut pmax = Vec::with_capacity(n);
15265        for pos in 0..n {
15266            let emb = self.embed_single(ids[pos]);
15267            let hidden = self.forward_layers(&emb, pos, None);
15268            let logits = if let Some(logits) = self.graph_logits.take() {
15269                logits
15270            } else {
15271                let normed = inference::rms_norm(
15272                    &hidden,
15273                    &self.weights.final_norm,
15274                    self.rms_eps,
15275                    self.norm_style,
15276                );
15277                // lm_head_forward applies the final-logit softcap itself —
15278                // capping again here double-squashed gemma-class logits
15279                // (tanh∘tanh) and reported a flattered ppl.
15280                self.lm_head_forward(&normed)
15281            };
15282            let target = ids[pos + 1] as usize;
15283            let (mut amax, mut mval) = (0usize, f32::NEG_INFINITY);
15284            for (i, &v) in logits.iter().enumerate() {
15285                if v > mval {
15286                    mval = v;
15287                    amax = i;
15288                }
15289            }
15290            correct.push(amax == target);
15291            let row: Vec<f32> = temps
15292                .iter()
15293                .map(|&t| {
15294                    let tt = t.max(1e-3);
15295                    let s: f32 = logits.iter().map(|&v| ((v - mval) / tt).exp()).sum();
15296                    1.0 / s.max(1e-12) // numerator at the max is exp(0)=1
15297                })
15298                .collect();
15299            pmax.push(row);
15300        }
15301        self.clear_sequence_state();
15302        (correct, pmax)
15303    }
15304
15305    /// Teacher-forced PPL with the dynamic router driving per-window
15306    /// skill switches (VMF experiment №2 measurement). Sequential (φ
15307    /// must update per token), returns (ppl, switch_count). The router
15308    /// must be enabled (`enable_dynamic_routing`); else this equals
15309    /// plain `ppl_ids`. The active skill when scoring token t shapes the
15310    /// logits for t+1 — on-policy over the held-out text itself.
15311    pub fn ppl_ids_dynamic(&mut self, ids: &[u32]) -> Result<(f64, usize), String> {
15312        if self.dyn_router.is_none() {
15313            return Ok((self.ppl_ids(ids)?, 0));
15314        }
15315        self.nll_begin()?;
15316        let saved_active = self.dyn_active;
15317        let mut router = self
15318            .dyn_router
15319            .take()
15320            .ok_or_else(|| "dynamic router disappeared before PPL scoring".to_string())?;
15321        router.reset();
15322        self.dyn_phi_seen = 0;
15323        let _ = self.set_active_skill(None);
15324
15325        let result: Result<(f64, usize), String> = (|| {
15326            let mut nll = 0f64;
15327            let mut cnt = 0usize;
15328            for pos in 0..ids.len().saturating_sub(1) {
15329                let hidden = self.forward_layers(&self.embed_single(ids[pos]), pos, None);
15330                self.nll_check_graph("dynamic serial forward", pos)?;
15331                let out_of_band = self.graph_logits.take();
15332                let mut logits = match out_of_band {
15333                    Some(lg) => lg,
15334                    None => {
15335                        let normed = inference::rms_norm(
15336                            &hidden,
15337                            &self.weights.final_norm,
15338                            self.rms_eps,
15339                            self.norm_style,
15340                        );
15341                        // lm_head_forward applies the final-logit softcap itself —
15342                        // capping again here double-squashed gemma-class logits
15343                        // and reported a flattered ppl.
15344                        self.lm_head_forward(&normed)
15345                    }
15346                };
15347                let target = ids[pos + 1] as usize;
15348                let max = logits.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
15349                let lse: f64 = logits
15350                    .iter()
15351                    .map(|&v| ((v - max) as f64).exp())
15352                    .sum::<f64>()
15353                    .ln()
15354                    + max as f64;
15355                let tok_nll = lse - logits[target] as f64;
15356                if std::env::var("CMF_PPL_TRACE").is_ok() && pos < 10_000 {
15357                    let top = logits
15358                        .iter()
15359                        .enumerate()
15360                        .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
15361                        .map(|(i, _)| i)
15362                        .unwrap_or(0);
15363                    eprintln!(
15364                        "pos {pos:3} tgt {target:6} nll {tok_nll:7.3} | top1 {top:6} lg[t]={:.2} lg[top]={:.2}",
15365                        logits[target], logits[top]
15366                    );
15367                }
15368                nll += tok_nll;
15369                cnt += 1;
15370                attention::recycle_buf(&mut logits);
15371                // Route on the evolving phi (drives the NEXT token's skill).
15372                let phi = self.dyn_phi_ema.clone();
15373                if let Some(new_active) = router.step(&phi, pos) {
15374                    // a switch clears the state: positions 0..=pos are read
15375                    // again under the new weights before pos+1 is scored
15376                    if self.set_active_skill(new_active).is_ok() {
15377                        self.reprefill_context(&ids[..=pos], None)?;
15378                        self.graph_logits = None;
15379                    }
15380                }
15381            }
15382            Ok(((nll / cnt.max(1) as f64).exp(), router.switches.len()))
15383        })();
15384
15385        // Restore the detached router and the active overlay on both success
15386        // and failure. The scoring state is cleared independently below.
15387        let _ = self.set_active_skill(saved_active);
15388        self.dyn_router = Some(router);
15389        self.nll_end();
15390        result
15391    }
15392
15393    /// Routing probe φ (spec §9): mean-pooled hidden after `layer`.
15394    pub fn probe_phi(&mut self, ids: &[u32], layer: usize) -> Vec<f32> {
15395        self.clear_sequence_state();
15396        let mut acc = vec![0f32; self.hidden_size];
15397        for (pos, &id) in ids.iter().enumerate() {
15398            let h = self.forward_layers_upto(&self.embed_single(id), pos, None, Some(layer));
15399            for (a, v) in acc.iter_mut().zip(&h) {
15400                *a += v;
15401            }
15402        }
15403        let n = ids.len().max(1) as f32;
15404        for a in acc.iter_mut() {
15405            *a /= n;
15406        }
15407        self.clear_sequence_state();
15408        acc
15409    }
15410
15411    /// Every position's hidden AFTER `layer` (n × hidden, not normalized): the
15412    /// walk of [`Self::probe_phi_span`] without the pooling, for `phi-dump`.
15413    pub fn probe_hidden_rows(&mut self, ids: &[u32], layer: usize) -> Vec<f32> {
15414        #[cfg(target_os = "macos")]
15415        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
15416        self.clear_sequence_state();
15417        let mut rows = Vec::with_capacity(ids.len() * self.hidden_size);
15418        for (pos, &id) in ids.iter().enumerate() {
15419            let h = self.forward_layers_upto(&self.embed_single(id), pos, None, Some(layer));
15420            rows.extend_from_slice(&h);
15421        }
15422        self.clear_sequence_state();
15423        rows
15424    }
15425
15426    /// Router-v2 φ probe (spec §9.4, `phi.pool = "span_mean"`): the hidden
15427    /// AFTER `layer` — the same per-position walk and the same quantity as
15428    /// [`Self::probe_phi`] — averaged over the positions in `span` only
15429    /// (the user text between the template's prefix and suffix ids), NOT
15430    /// unit-normalized (the decision normalizes). The walk stops at
15431    /// `span.end`: causality makes the later positions irrelevant, so the
15432    /// result is bit-identical to probing `ids[..span.end]`. An empty span
15433    /// gives the zero vector, which the decision treats as degenerate.
15434    ///
15435    /// Every sequence state is reset before and after — the host KV/ring/
15436    /// recurrent state, the reuse keys (`kv_history`, `kv_prefix`) and the
15437    /// device graph's sequence — so run it on a pipeline that does not
15438    /// also serve a conversation (its prefix reuse would be lost).
15439    pub fn probe_phi_span(
15440        &mut self,
15441        ids: &[u32],
15442        layer: usize,
15443        span: std::ops::Range<usize>,
15444    ) -> Vec<f32> {
15445        #[cfg(target_os = "macos")]
15446        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
15447        let end = span.end.min(ids.len());
15448        let start = span.start.min(end);
15449        let reset = |p: &mut Self| p.clear_sequence_state();
15450        reset(self);
15451        let mut acc = vec![0f32; self.hidden_size];
15452        for (pos, &id) in ids[..end].iter().enumerate() {
15453            let h = self.forward_layers_upto(&self.embed_single(id), pos, None, Some(layer));
15454            if pos >= start {
15455                for (a, v) in acc.iter_mut().zip(&h) {
15456                    *a += v;
15457                }
15458            }
15459        }
15460        let n = end - start;
15461        if n > 0 {
15462            let n = n as f32;
15463            for a in acc.iter_mut() {
15464                *a /= n;
15465            }
15466        }
15467        reset(self);
15468        acc
15469    }
15470
15471    /// One decode step of the current sequence: forward `token` at
15472    /// `position` (the cache holds positions `[0, position)`, e.g. after
15473    /// [`Self::forward_ids`]) and return the next-token logits — the same
15474    /// forward and head the generation loop runs (resident-graph logits
15475    /// when the graph ran, final norm + lm_head otherwise). The logit-dump
15476    /// tools drive greedy decoding with it so every position is observable.
15477    pub fn decode_step_logits(&mut self, token: u32, position: usize) -> Vec<f32> {
15478        #[cfg(target_os = "macos")]
15479        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
15480        self.graph_logits = None;
15481        let hidden = self.forward_layers(&self.embed_single(token), position, None);
15482        if let Some(logits) = self.graph_logits.take() {
15483            return logits;
15484        }
15485        inference::rms_norm_into(
15486            &hidden,
15487            &self.weights.final_norm,
15488            self.rms_eps,
15489            self.norm_style,
15490            &mut self.ws.n1,
15491        );
15492        self.lm_head_forward(&self.ws.n1)
15493    }
15494
15495    /// Layer-major batched prefill (prefill-GEMM): full-attention —
15496    /// per-position with the existing operators (KV grows naturally,
15497    /// causality preserved), GDN projections / FFN / MoE — batched
15498    /// (a weight row is read from DRAM once per chunk, not per
15499    /// position). Returns the hidden of all positions [b × hidden].
15500    fn prefill_batch(&mut self, ids: &[u32], start_pos: usize) -> Vec<f32> {
15501        self.prefill_batch_masked(ids, start_pos, None)
15502    }
15503
15504    /// `prefill_batch` with a task mask honored on the dense-FFN panels
15505    /// (the masked-inference fast path: full fused compute, mask lands on
15506    /// the activations). The whole-chunk GPU graph is skipped for masked
15507    /// layers by the callers' arms; the per-GEMM device paths stay in
15508    /// play because the zeroing happens on the host between them.
15509    fn prefill_batch_masked(
15510        &mut self,
15511        ids: &[u32],
15512        start_pos: usize,
15513        task_mask: Option<&TaskMask>,
15514    ) -> Vec<f32> {
15515        self.prefill_batch_span(PrefillIn::Ids(ids), start_pos, task_mask, 0, usize::MAX)
15516    }
15517
15518    /// One prompt chunk through the whole stack, post-stack rows out (no
15519    /// final norm) — the ingest generation uses, shared by scoring and
15520    /// `forward_ids` so they measure the same execution: the batched wgpu
15521    /// graph's device prefix plus the host's batched walk for the rest when
15522    /// `batch_prefix_prefill` holds and the graph admits the chunk, else
15523    /// the host's chunked prefill. Err only when a graph that had mutated
15524    /// device state failed.
15525    fn prefill_rows(
15526        &mut self,
15527        ids: &[u32],
15528        pos: usize,
15529        task_mask: Option<&TaskMask>,
15530    ) -> Result<Vec<f32>, String> {
15531        self.prefill_input_rows(PrefillIn::Ids(ids), pos, task_mask)
15532    }
15533
15534    fn prefill_input_rows(
15535        &mut self,
15536        input: PrefillIn<'_>,
15537        pos: usize,
15538        task_mask: Option<&TaskMask>,
15539    ) -> Result<Vec<f32>, String> {
15540        if self.dash.is_some() {
15541            let PrefillIn::Hidden(rows) = input else {
15542                return Err("Unlimited-OCR prompts carry image rows".into());
15543            };
15544            return Ok(self.dash_prefill_rows(rows, pos));
15545        }
15546        self.mimo_moe_prepare();
15547        let hs = self.hidden_size;
15548        let bk = match input {
15549            PrefillIn::Ids(ids) => ids.len(),
15550            PrefillIn::Hidden(rows) => rows.len() / hs,
15551        };
15552        // MiniCPM-OCR's vision rows on native Metal: the rows graph, as an id
15553        // prompt's chunks take it in the generation loop.
15554        #[cfg(target_os = "macos")]
15555        if let PrefillIn::Hidden(rows) = input
15556            && task_mask.is_none()
15557            && self.onevision2_prefill()
15558            && (crate::gpu::q1_force() || crate::gpu::q2tp_gpu_opt_in())
15559            && crate::gpu::enabled_here()
15560            && self.gdn_cfg.is_some()
15561            && !self.per_token_stack()
15562            && bk > 8
15563            && bk <= 512
15564            && std::env::var("CMF_METAL_PREFILL").as_deref() != Ok("0")
15565        {
15566            match self.prefill_hiddens_metal(rows.to_vec(), pos, None) {
15567                MetalPrefillOutcome::Completed(h) => return Ok(h),
15568                MetalPrefillOutcome::Failed => {
15569                    return Err("Metal prefill of the prompt rows failed after admission".into());
15570                }
15571                MetalPrefillOutcome::Declined => {}
15572            }
15573        }
15574        #[cfg(not(target_os = "macos"))]
15575        if task_mask.is_none()
15576            && !self.o1_active()
15577            && bk > 1
15578            && (self.batch_prefix_prefill()
15579                // Ripple: scoring reads its chunks through the batch graph
15580                // too (the host walk attends 80 heads a row on the CPU).
15581                || (self.value_blend.is_some() && self.g4_batch_prefill())
15582                // An embedded prompt (vision rows) on the graph route takes
15583                // the batched graph like an id prompt does.
15584                || (matches!(input, PrefillIn::Hidden(_)) && self.generation_batch_k() > 0)
15585                || (self.verify_exact_moe
15586                    && crate::gpu::enabled_here()
15587                    && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)))
15588        {
15589            let mut hiddens = match input {
15590                PrefillIn::Hidden(rows) => rows.to_vec(),
15591                PrefillIn::Ids(ids) => ids.iter().flat_map(|&id| self.embed_single(id)).collect(),
15592            };
15593            let positions: Vec<usize> = (pos..pos + bk).collect();
15594            let mut run = 0usize;
15595            match self.try_batch_graph_wgpu_prefix(
15596                &mut hiddens,
15597                &positions,
15598                bk,
15599                None,
15600                Some(&mut run),
15601            ) {
15602                crate::gpu::BatchGraphOutcome::Completed => {
15603                    let out = if run < self.num_layers {
15604                        self.mhc_from_device(run, Some(bk));
15605                        self.prefill_batch_span(
15606                            PrefillIn::Hidden(&hiddens),
15607                            pos,
15608                            None,
15609                            run,
15610                            self.num_layers,
15611                        )
15612                    } else {
15613                        hiddens
15614                    };
15615                    return if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
15616                        Err("MiMo attention graph failed after admission".into())
15617                    } else {
15618                        Ok(out)
15619                    };
15620                }
15621                crate::gpu::BatchGraphOutcome::Failed => {
15622                    return Err("batched prefix prefill failed after admission".into());
15623                }
15624                crate::gpu::BatchGraphOutcome::Declined => {
15625                    // Rows an earlier chunk left on the device only.
15626                    #[cfg(feature = "gpu")]
15627                    self.pull_lagging_host_kv(0, self.num_layers, pos);
15628                }
15629            }
15630        }
15631        let out = self.prefill_batch_span(input, pos, task_mask, 0, usize::MAX);
15632        if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
15633            Err("batch tail graph failed after admission".into())
15634        } else {
15635            Ok(out)
15636        }
15637    }
15638
15639    /// Unlimited-OCR's prompt rows, one position at a time: each query has its
15640    /// own coordinates and page candidates.
15641    fn dash_prefill_rows(&mut self, rows: &[f32], pos: usize) -> Vec<f32> {
15642        let hs = self.hidden_size;
15643        let n = rows.len() / hs;
15644        let mut last = vec![0f32; hs];
15645        let mut i = 0usize;
15646        while i < n && !self.cancel.load(std::sync::atomic::Ordering::Relaxed) {
15647            #[cfg(not(target_os = "macos"))]
15648            if self.dash_batch_on {
15649                let k = (n - i).min(crate::gpu::DASH_CHUNK_MAX);
15650                if let Some(d) = self.dash.as_mut() {
15651                    d.at_prompt_chunk(pos + i, k);
15652                }
15653                let mut h = rows[i * hs..(i + k) * hs].to_vec();
15654                let positions: Vec<usize> = (pos + i..pos + i + k).collect();
15655                match self.try_batch_graph_wgpu_prefix(&mut h, &positions, k, None, None) {
15656                    crate::gpu::BatchGraphOutcome::Completed => {
15657                        last.copy_from_slice(&h[(k - 1) * hs..]);
15658                        i += k;
15659                        continue;
15660                    }
15661                    crate::gpu::BatchGraphOutcome::Failed => {
15662                        self.graph_failed.store(true, std::sync::atomic::Ordering::Relaxed);
15663                        return last;
15664                    }
15665                    crate::gpu::BatchGraphOutcome::Declined => self.dash_batch_on = false,
15666                }
15667            }
15668            #[cfg(target_os = "macos")]
15669            if self.dash_batch_on && n - i >= 8 && crate::gpu::backend_name() == "metal" {
15670                let k = (n - i).min(crate::gpu::DASH_CHUNK_MAX);
15671                if let Some(d) = self.dash.as_mut() {
15672                    d.at_prompt_chunk(pos + i, k);
15673                }
15674                let mut h = rows[i * hs..(i + k) * hs].to_vec();
15675                if self.chunk_run_gpu(0, &mut h, k, pos + i, None, self.num_layers) == self.num_layers {
15676                    last.copy_from_slice(&h[(k - 1) * hs..]);
15677                    i += k;
15678                    continue;
15679                }
15680                self.dash_batch_on = false;
15681            }
15682            if let Some(d) = self.dash.as_mut() {
15683                d.at_prompt(pos + i);
15684            }
15685            last = self.forward_layers(&rows[i * hs..(i + 1) * hs], pos + i, None);
15686            i += 1;
15687        }
15688        last
15689    }
15690
15691    /// The layer-major batched walk over a layer span [from..upto_excl):
15692    /// the whole prefill machinery (chunk graph, batched attends, GEMM
15693    /// panels) for a PARTIAL stack — the network split's prefill rides
15694    /// the same canon as the local one. Input is token ids (embeds
15695    /// itself, coordinator side) or ready boundary hiddens (worker side).
15696    fn prefill_batch_span(
15697        &mut self,
15698        input: PrefillIn<'_>,
15699        start_pos: usize,
15700        task_mask: Option<&TaskMask>,
15701        from: usize,
15702        upto_excl: usize,
15703    ) -> Vec<f32> {
15704        let hs = self.hidden_size;
15705        let b = match input {
15706            PrefillIn::Ids(ids) => ids.len(),
15707            PrefillIn::Hidden(hb) => hb.len() / hs,
15708        };
15709        let upto_excl = upto_excl.min(self.num_layers);
15710        // The CPU embed is deferred: when the chunk graph takes the run
15711        // from layer 0 it gathers the embeddings on the device instead.
15712        // A hidden input is ready by definition.
15713        let mut h: Vec<f32>;
15714        let mut h_ready;
15715        match input {
15716            PrefillIn::Ids(_) => {
15717                h = vec![0.0; b * hs];
15718                h_ready = false;
15719            }
15720            PrefillIn::Hidden(hb) => {
15721                h = hb.to_vec();
15722                h_ready = true;
15723            }
15724        }
15725        // Ripple's value residual reads the chunk's embedding rows in every layer.
15726        if self.value_blend.is_some() {
15727            self.vres_e0.clear();
15728            match input {
15729                PrefillIn::Ids(ids) => {
15730                    for &id in ids {
15731                        let e = self.embed_single(id);
15732                        self.vres_e0.extend_from_slice(&e);
15733                    }
15734                }
15735                PrefillIn::Hidden(hb) => {
15736                    assert!(from == 0, "value residual: a layer span past the first layer has no embedding rows");
15737                    self.vres_e0.extend_from_slice(hb);
15738                }
15739            }
15740        }
15741        let fill_h = |h: &mut Vec<f32>, me: &Self| {
15742            if let PrefillIn::Ids(ids) = input {
15743                for (bi, &id) in ids.iter().enumerate() {
15744                    let e = me.embed_single(id);
15745                    h[bi * hs..(bi + 1) * hs].copy_from_slice(&e);
15746                }
15747                if let Ok(tp) = std::env::var("CMF_TRACE_POS") {
15748                    if let Ok(t) = tp.parse::<usize>() {
15749                        if t >= start_pos && t < start_pos + ids.len() {
15750                            let bi = t - start_pos;
15751                            let row = &h[bi * hs..(bi + 1) * hs];
15752                            let n: f32 = row.iter().map(|x| x * x).sum::<f32>().sqrt();
15753                            eprintln!(
15754                                "BATCH pos {t} embed: id {} |h| = {n:.6} h0 {:.6} h1 {:.6} | b={} start={start_pos} ids[..8]={:?}",
15755                                ids[bi],
15756                                row[0],
15757                                row[1],
15758                                ids.len(),
15759                                &ids[..ids.len().min(8)]
15760                            );
15761                        }
15762                    }
15763                }
15764            }
15765        };
15766        let (_nkv, _hd, _rd, eps) = (
15767            self.num_kv_heads,
15768            self.head_dim,
15769            self.rotary_dim,
15770            self.rms_eps,
15771        );
15772        let pool = self.pool.clone();
15773        let norm_style = self.norm_style;
15774        self.mimo_moe_prepare();
15775        let automatic_gpu_prefix = self.automatic_gpu_prefix();
15776
15777        #[cfg(target_os = "macos")]
15778        let mut chunk_skip_until = 0usize;
15779        // SenseNova-Loop: the chunk rows' mHC streams (a device prefix that
15780        // stopped inside the range left them here).
15781        let mut mhc_rs: Vec<f32> = std::mem::take(&mut self.mhc_rows_in);
15782        for li in from..upto_excl {
15783            let _capacity_tail = automatic_gpu_prefix
15784                .filter(|&prefix| {
15785                    li >= prefix && !(self.verify_exact_moe && self.mimo_moe.is_dynamic(li, false))
15786                })
15787                .map(|_| crate::gpu::enter_cpu_scope());
15788            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU
15789            // Spark-X2.5: the layer's int8 matrix-unit GEMMs take the
15790            // `zi_mm` tile, bit-identical to the 64x64 kernel and about
15791            // three times its rate (`gpu_wgpu::zi_gemm_route`).
15792            #[cfg(feature = "gpu")]
15793            let _fast_gemm = self
15794                .proj_gate_sigmoid
15795                .then(crate::gpu::enter_prefill_fast_gemm);
15796            // GPU chunk graph (default-on under CMF_GPU=1): a run of
15797            // consecutive eligible layers for the whole chunk in ONE
15798            // Metal submission — norm, QKV, RoPE with fused mirror
15799            // append, causal attend, O, FFN, hidden device-resident
15800            // across the run. Any refusal falls through to the CPU path.
15801            #[cfg(target_os = "macos")]
15802            if task_mask.is_none() {
15803                if li < chunk_skip_until {
15804                    continue;
15805                }
15806                // Device-side embedding needs a q8_row embedding matrix;
15807                // with any other layout the CPU fills `h` first and the
15808                // graph starts from a ready hidden (refusing the whole
15809                // run over the embedding alone kept q4t models — the
15810                // whole Nanbeige/Bonsai class — on the CPU prefill).
15811                if !h_ready && li == 0 && self.weights.embed_tokens.q8_row_parts().is_none() {
15812                    fill_h(&mut h, self);
15813                    h_ready = true;
15814                }
15815                let ids_for_embed = match input {
15816                    PrefillIn::Ids(ids) => (!h_ready && li == 0).then_some(ids),
15817                    PrefillIn::Hidden(_) => None,
15818                };
15819                let end = self.chunk_run_gpu(li, &mut h, b, start_pos, ids_for_embed, upto_excl);
15820                if end > li {
15821                    h_ready = true;
15822                    chunk_skip_until = end;
15823                    // Looped Transformer: the graph stopped at a loop
15824                    // boundary — apply final norm before the next iteration.
15825                    if self.is_loop_end(end - 1) && end < self.num_layers {
15826                        for bi in 0..b {
15827                            let normed = inference::rms_norm(
15828                                &h[bi * hs..(bi + 1) * hs],
15829                                &self.weights.final_norm,
15830                                eps,
15831                                norm_style,
15832                            );
15833                            h[bi * hs..(bi + 1) * hs].copy_from_slice(&normed);
15834                        }
15835                    }
15836                    continue;
15837                }
15838            }
15839            if !h_ready {
15840                fill_h(&mut h, self);
15841                h_ready = true;
15842            }
15843            if task_mask.is_none() && self.verify_exact_moe {
15844                let positions: Vec<_> = (start_pos..start_pos + b).collect();
15845                match self.mimo_graph_layer_rows(li, &mut h, &positions) {
15846                    crate::gpu::BatchGraphOutcome::Completed => continue,
15847                    crate::gpu::BatchGraphOutcome::Failed => return h,
15848                    crate::gpu::BatchGraphOutcome::Declined => {}
15849                }
15850            }
15851            #[cfg(feature = "gpu")]
15852            self.pull_lagging_host_kv(li, li + 1, start_pos);
15853            // SenseNova-Loop mHC: every row's streams route into `h`; the
15854            // attention below adds onto that branch, so its output is the
15855            // difference from the copy kept here.
15856            let mhc_attn = self.mhc_layer(li).then(|| {
15857                let m = self.mhc.as_deref().expect("mhc layer");
15858                let p = self.phys_layer(li);
15859                let n = m.s.streams * hs;
15860                mhc_rs.resize(b * n, 0.0);
15861                let coefs: Vec<_> = (0..b)
15862                    .map(|bi| {
15863                        let r = &mut mhc_rs[bi * n..(bi + 1) * n];
15864                        if m.enters(p) {
15865                            m.enter(r, &h[bi * hs..(bi + 1) * hs]);
15866                        }
15867                        m.route(p, false, r, &mut h[bi * hs..(bi + 1) * hs])
15868                    })
15869                    .collect();
15870                (h.clone(), coefs)
15871            });
15872            let lw = &self.weights.layers[self.phys_layer(li)];
15873            let t_attn = std::time::Instant::now();
15874            // ── attention ──
15875            match &lw.attn {
15876                AttnKind::Kda(w) => {
15877                    // Projections batched, recurrence sequential.
15878                    let cfg = self.kda_cfg.expect("kda layer without kda_cfg");
15879                    let mut normed = vec![0.0f32; b * hs];
15880                    for bi in 0..b {
15881                        inference::rms_norm_into(
15882                            &h[bi * hs..(bi + 1) * hs],
15883                            &lw.input_norm,
15884                            eps,
15885                            norm_style,
15886                            &mut normed[bi * hs..(bi + 1) * hs],
15887                        );
15888                    }
15889                    let attn = crate::linear_core::kda_forward_batch(
15890                        &normed,
15891                        b,
15892                        w,
15893                        &cfg,
15894                        &mut self.kv_cache.layers[li].linear_state,
15895                        pool.as_deref(),
15896                    );
15897                    for (dst, &a) in h.iter_mut().zip(&attn) {
15898                        *dst += a;
15899                    }
15900                }
15901                AttnKind::LinearGdn(w) => {
15902                    // Projections batched, recurrence sequential.
15903                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
15904                    let mut normed = vec![0.0f32; b * hs];
15905                    for bi in 0..b {
15906                        let r = inference::rms_norm(
15907                            &h[bi * hs..(bi + 1) * hs],
15908                            &lw.input_norm,
15909                            eps,
15910                            norm_style,
15911                        );
15912                        normed[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
15913                    }
15914                    let attn = crate::linear_core::gdn_forward_batch(
15915                        &normed,
15916                        b,
15917                        w,
15918                        &cfg,
15919                        &mut self.kv_cache.layers[li].linear_state,
15920                        pool.as_deref(),
15921                    );
15922                    for (dst, &a) in h.iter_mut().zip(&attn) {
15923                        *dst += a;
15924                    }
15925                }
15926                AttnKind::ShortConv(w) => {
15927                    // Projections batched over the chunk; the conv walks the
15928                    // contiguous positions in order (same ring as decode).
15929                    let cfg = self
15930                        .short_conv_cfg
15931                        .expect("short-conv layer without short_conv_cfg");
15932                    let mut normed = vec![0.0f32; b * hs];
15933                    for bi in 0..b {
15934                        inference::rms_norm_into(
15935                            &h[bi * hs..(bi + 1) * hs],
15936                            &lw.input_norm,
15937                            eps,
15938                            norm_style,
15939                            &mut normed[bi * hs..(bi + 1) * hs],
15940                        );
15941                    }
15942                    let mut attn = short_conv_forward_batch(
15943                        &normed,
15944                        b,
15945                        w,
15946                        &cfg,
15947                        &mut self.kv_cache.layers[li].linear_state,
15948                        pool.as_deref(),
15949                    );
15950                    // LFM3 sandwich: the mixer output is normalized before
15951                    // the residual, as on the decode path.
15952                    if let Some(wn) = &lw.attn_out_norm {
15953                        for bi in 0..b {
15954                            inference::rms_norm_into(
15955                                &attn[bi * hs..(bi + 1) * hs],
15956                                wn,
15957                                eps,
15958                                norm_style,
15959                                &mut normed[bi * hs..(bi + 1) * hs],
15960                            );
15961                        }
15962                        attn.copy_from_slice(&normed);
15963                    }
15964                    for (dst, &a) in h.iter_mut().zip(&attn) {
15965                        *dst += a;
15966                    }
15967                }
15968                AttnKind::Mla(w) => {
15969                    // Per-position prefill (correctness first; latent
15970                    // batching is a later optimization).
15971                    let inv_freq_l = self.layer_inv_freq(li);
15972                    let rs = self.layer_rope_scale(li);
15973                    let mut normed = vec![0.0f32; hs];
15974                    for bi in 0..b {
15975                        inference::rms_norm_into(
15976                            &h[bi * hs..(bi + 1) * hs],
15977                            &lw.input_norm,
15978                            eps,
15979                            norm_style,
15980                            &mut normed,
15981                        );
15982                        let ao = mla_attention(
15983                            w,
15984                            &normed,
15985                            &mut self.kv_cache.layers[li],
15986                            start_pos + bi,
15987                            &inv_freq_l,
15988                            rs,
15989                            eps,
15990                            pool.as_deref(),
15991                        );
15992                        for (dst, &a) in h[bi * hs..(bi + 1) * hs].iter_mut().zip(&ao) {
15993                            *dst += a;
15994                        }
15995                    }
15996                }
15997                AttnKind::Full {
15998                    wq,
15999                    wk,
16000                    wv,
16001                    wo,
16002                    q_norm,
16003                    k_norm,
16004                    output_gate,
16005                    softplus_gate,
16006                    bias,
16007                } => {
16008                    // Chunk-GEMM QKV/O; per-position causal attention
16009                    // inside (roadmap §3 P0 — full-attention prefill no
16010                    // longer re-reads the projection weights b times).
16011                    let mut normed = vec![0.0f32; b * hs];
16012                    for bi in 0..b {
16013                        inference::rms_norm_into(
16014                            &h[bi * hs..(bi + 1) * hs],
16015                            &lw.input_norm,
16016                            eps,
16017                            norm_style,
16018                            &mut normed[bi * hs..(bi + 1) * hs],
16019                        );
16020                    }
16021                    // The rows V projects, when the layer blends the embeddings into them.
16022                    let vres = match self.layer_value_blend(li) {
16023                        Some(blend) => {
16024                            vres_lerp(&self.vres_e0, &normed, blend, &mut self.vres_in);
16025                            true
16026                        }
16027                        None => false,
16028                    };
16029                    let inv_freq_l = self.layer_inv_freq(li);
16030                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
16031                    let cfg = QwenAttnCfg {
16032                        mrope: self.prompt_mrope.as_deref().zip(self.mrope_sections).map(|(pos, sections)| attention::MropeView { base: 0, pos, sections }),
16033                        num_heads: self.layer_num_heads(li),
16034                        num_kv_heads: nkv_l,
16035                        head_dim: hd_l,
16036                        hidden_size: hs,
16037                        position: start_pos,
16038                        inv_freq: &inv_freq_l,
16039                        rotary_dim: rd_l,
16040                        scale: self.attn_scale,
16041                        softcap: self.attn_softcap,
16042                        window: self.layer_window(li),
16043                        v_norm: self.attn_v_norm,
16044                        qk_norm_after_rope: self.qk_norm_after_rope,
16045                        gate_sigmoid: self.proj_gate_sigmoid,
16046                        q_norm: q_norm.as_deref(),
16047                        k_norm: k_norm.as_deref(),
16048                        output_gate: *output_gate,
16049                        softplus_gate: softplus_gate
16050                            .as_ref()
16051                            .map(|(gate, per_head)| (gate, *per_head)),
16052                        rope_scale: self.layer_rope_scale(li),
16053                        bias: bias
16054                            .as_ref()
16055                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
16056                        rms_eps: eps,
16057                        norm_style,
16058                        pool: pool.as_deref(),
16059                        v_head_dim: self.layer_v_dim(li),
16060                        value_in: vres.then(|| self.vres_in.as_slice()),
16061                    };
16062                    #[cfg(feature = "gpu")]
16063                    let _mirror = self
16064                        .prefill_mirror_target(li)
16065                        .map(crate::gpu::enter_prefill_mirror);
16066                    let mut attn = attention::qwen_attention_batch(
16067                        &normed,
16068                        b,
16069                        wq,
16070                        wk,
16071                        wv,
16072                        wo,
16073                        &mut self.kv_cache.layers[li],
16074                        &cfg,
16075                    );
16076                    if let Some(w) = &lw.attn_out_norm {
16077                        for bi in 0..b {
16078                            inference::rms_norm_into(
16079                                &attn[bi * hs..(bi + 1) * hs],
16080                                w,
16081                                eps,
16082                                norm_style,
16083                                &mut normed[bi * hs..(bi + 1) * hs],
16084                            );
16085                        }
16086                        attn.copy_from_slice(&normed);
16087                    }
16088                    for (dst, &a) in h.iter_mut().zip(&attn) {
16089                        *dst += a;
16090                    }
16091                }
16092                AttnKind::Bounded(w) => {
16093                    // Chunk-GEMM projections, the bounded operator per
16094                    // position over ring + chunk — never a growing KV.
16095                    let mut normed = vec![0.0f32; b * hs];
16096                    for bi in 0..b {
16097                        inference::rms_norm_into(
16098                            &h[bi * hs..(bi + 1) * hs],
16099                            &lw.input_norm,
16100                            eps,
16101                            norm_style,
16102                            &mut normed[bi * hs..(bi + 1) * hs],
16103                        );
16104                    }
16105                    let rope = self
16106                        .bounded_rope
16107                        .clone()
16108                        .expect("bounded layer without an installed rotation table");
16109                    let cfg = crate::bounded::BoundedAttnCfg {
16110                        num_heads: self.num_heads,
16111                        num_kv_heads: self.num_kv_heads,
16112                        head_dim: self.head_dim,
16113                        hidden_size: hs,
16114                        scale: self.attn_scale,
16115                        rope: &rope,
16116                        pool: pool.as_deref(),
16117                    };
16118                    let mut attn = crate::bounded::bounded_attention_batch(
16119                        &normed,
16120                        b,
16121                        w,
16122                        &mut self.kv_cache.layers[li],
16123                        &cfg,
16124                    );
16125                    if let Some(wn) = &lw.attn_out_norm {
16126                        for bi in 0..b {
16127                            inference::rms_norm_into(
16128                                &attn[bi * hs..(bi + 1) * hs],
16129                                wn,
16130                                eps,
16131                                norm_style,
16132                                &mut normed[bi * hs..(bi + 1) * hs],
16133                            );
16134                        }
16135                        attn.copy_from_slice(&normed);
16136                    }
16137                    for (dst, &a) in h.iter_mut().zip(&attn) {
16138                        *dst += a;
16139                    }
16140                    attention::recycle_buf(&mut attn);
16141                }
16142                AttnKind::Linear(w) => {
16143                    for bi in 0..b {
16144                        let normed = inference::rms_norm(
16145                            &h[bi * hs..(bi + 1) * hs],
16146                            &lw.input_norm,
16147                            eps,
16148                            norm_style,
16149                        );
16150                        vmf_phase_forward(
16151                            &normed,
16152                            w,
16153                            &self.vmf_cfg.expect("linear layer without vmf_cfg"),
16154                            &mut self.kv_cache.layers[li].linear_state,
16155                            pool.as_deref(),
16156                        )
16157                        .iter()
16158                        .enumerate()
16159                        .for_each(|(i, &a)| h[bi * hs + i] += a);
16160                    }
16161                }
16162            }
16163
16164            // mHC: fold the attention output into the streams, route the
16165            // FFN's branch.
16166            let mhc_ffn = mhc_attn.map(|(branch, coefs)| {
16167                let m = self.mhc.as_deref().expect("mhc layer");
16168                let p = self.phys_layer(li);
16169                let n = m.s.streams * hs;
16170                let mut y = vec![0f32; hs];
16171                (0..b)
16172                    .map(|bi| {
16173                        for (e, v) in y.iter_mut().enumerate() {
16174                            *v = h[bi * hs + e] - branch[bi * hs + e];
16175                        }
16176                        let r = &mut mhc_rs[bi * n..(bi + 1) * n];
16177                        m.merge(r, &y, &coefs[bi]);
16178                        m.route(p, true, r, &mut h[bi * hs..(bi + 1) * hs])
16179                    })
16180                    .collect::<Vec<_>>()
16181            });
16182            // ── FFN batched ──
16183            let lw = &self.weights.layers[self.phys_layer(li)];
16184            let mut post = vec![0.0f32; b * hs];
16185            for bi in 0..b {
16186                let r =
16187                    inference::rms_norm(&h[bi * hs..(bi + 1) * hs], &lw.post_norm, eps, norm_style);
16188                post[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
16189            }
16190            // A restrictive per-visit FFN row lands on the activations
16191            // inside the dense arm; an all-open row costs nothing.
16192            let mask_row = task_mask
16193                .filter(|m| m.ffn_active_count(li) < self.intermediate_size)
16194                .and_then(|m| m.ffn_masks.get(li))
16195                .map(|v| v.as_slice());
16196            let attn_ns = t_attn.elapsed().as_nanos() as u64;
16197            let t_ffn = std::time::Instant::now();
16198            let mut ffn = match &lw.ffn {
16199                FfnKind::Dense(d) if !d.segs.is_empty() => {
16200                    tube_ffn(d, &post, b, pool.as_deref(), mask_row)
16201                }
16202                FfnKind::Dense(d) => dense_ffn_batch(d, &post, b, pool.as_deref(), mask_row),
16203                FfnKind::Moe(m) if self.verify_exact_moe && self.mimo_moe.is_dynamic(li, false) => {
16204                    moe_ffn_banked_rows(&mut self.mimo_moe, li, m, &post, b, hs, pool.as_deref())
16205                }
16206                FfnKind::Moe(m) if self.verify_exact_moe => {
16207                    moe_ffn_rows_exact(m, &post, b, hs, pool.as_deref())
16208                }
16209                // Keep prompt expert panels off the projection arena and
16210                // use their routes to prime the model-wide bank.
16211                FfnKind::Moe(m) if self.mimo_moe.is_dynamic(li, false) => {
16212                    let before = m.stats.borrow().clone();
16213                    let out = crate::gpu::cpu_scope(|| {
16214                        moe_ffn_batch(m, &post, b, hs, pool.as_deref(), None)
16215                    });
16216                    self.mimo_moe.prime(li, m, &before);
16217                    out
16218                }
16219                FfnKind::Moe(m) => moe_ffn_batch(m, &post, b, hs, pool.as_deref(), None),
16220                // Dual-branch layers run per position (the expert branch
16221                // reads the raw residual — nothing to batch yet).
16222                FfnKind::DenseMoe(dm) => {
16223                    let mut out = vec![0.0f32; b * hs];
16224                    for bi in 0..b {
16225                        let r = dense_moe_ffn(
16226                            dm,
16227                            &post[bi * hs..(bi + 1) * hs],
16228                            &h[bi * hs..(bi + 1) * hs],
16229                            eps,
16230                            norm_style,
16231                            pool.as_deref(),
16232                        );
16233                        out[bi * hs..(bi + 1) * hs].copy_from_slice(&r);
16234                    }
16235                    out
16236                }
16237            };
16238            if prefill_prof_on() {
16239                PREFILL_SPLIT[0].fetch_add(attn_ns, std::sync::atomic::Ordering::Relaxed);
16240                PREFILL_SPLIT[1].fetch_add(
16241                    t_ffn.elapsed().as_nanos() as u64,
16242                    std::sync::atomic::Ordering::Relaxed,
16243                );
16244            }
16245            if let Some(w) = &lw.ffn_out_norm {
16246                for bi in 0..b {
16247                    inference::rms_norm_into(
16248                        &ffn[bi * hs..(bi + 1) * hs],
16249                        w,
16250                        eps,
16251                        norm_style,
16252                        &mut post[bi * hs..(bi + 1) * hs],
16253                    );
16254                }
16255                ffn.copy_from_slice(&post);
16256            }
16257            if let Some(coefs) = mhc_ffn {
16258                // mHC: fold the FFN output in; the range's last layer hands
16259                // the streams' mean on as the hidden.
16260                let m = self.mhc.as_deref().expect("mhc layer");
16261                let p = self.phys_layer(li);
16262                let n = m.s.streams * hs;
16263                for bi in 0..b {
16264                    let r = &mut mhc_rs[bi * n..(bi + 1) * n];
16265                    m.merge(r, &ffn[bi * hs..(bi + 1) * hs], &coefs[bi]);
16266                    if m.leaves(p) {
16267                        m.leave(r, &mut h[bi * hs..(bi + 1) * hs]);
16268                    }
16269                }
16270            } else {
16271                for (dst, &f) in h.iter_mut().zip(&ffn) {
16272                    *dst += f;
16273                }
16274            }
16275            if let Some(sc) = lw.layer_scale {
16276                for v in h.iter_mut() {
16277                    *v *= sc;
16278                }
16279            }
16280            // CMF_LAYER_DUMP: every position's hidden after layer li.
16281            if self.layer_dump.is_some() {
16282                for bi in 0..b {
16283                    self.dump_layer_row(start_pos + bi, li, &h[bi * hs..(bi + 1) * hs]);
16284                }
16285            }
16286            if let Ok(tp) = std::env::var("CMF_TRACE_POS") {
16287                if let Ok(t) = tp.parse::<usize>() {
16288                    if t >= start_pos && t < start_pos + b {
16289                        let bi = t - start_pos;
16290                        let row = &h[bi * hs..(bi + 1) * hs];
16291                        let n: f32 = row.iter().map(|x| x * x).sum::<f32>().sqrt();
16292                        eprintln!(
16293                            "BATCH pos {t} after layer {li}: |h| = {n:.6} h0 {:.6} h1 {:.6}",
16294                            row[0], row[1]
16295                        );
16296                    }
16297                }
16298            }
16299            // CMF_DEBUG_LAYERS=1: per-layer hidden-state health of the
16300            // LAST prompt position — the knife for "which layer type
16301            // breaks first" on a new architecture.
16302            if std::env::var("CMF_DEBUG_LAYERS").is_ok() {
16303                let row = &h[(b - 1) * hs..b * hs];
16304                let rms =
16305                    (row.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / hs as f64).sqrt();
16306                let mx = row.iter().fold(0f32, |m, &v| m.max(v.abs()));
16307                eprintln!(
16308                    "layer {li:>3} {:>10} ffn={:<5} rms={rms:>12.4} max={mx:>12.4}",
16309                    match &self.weights.layers[self.phys_layer(li)].attn {
16310                        AttnKind::LinearGdn(_) => "gdn",
16311                        AttnKind::Linear(_) => "vmf",
16312                        AttnKind::ShortConv(_) => "conv",
16313                        _ => "attn",
16314                    },
16315                    match &lw.ffn {
16316                        FfnKind::Moe(_) => "moe",
16317                        FfnKind::Dense(_) => "dense",
16318                        FfnKind::DenseMoe(_) => "dense+moe",
16319                    },
16320                );
16321            }
16322            // Looped Transformer: apply final norm at the end of each loop iteration.
16323            if self.is_loop_end(li) && li + 1 < self.num_layers {
16324                for bi in 0..b {
16325                    let normed = inference::rms_norm(
16326                        &h[bi * hs..(bi + 1) * hs],
16327                        &self.weights.final_norm,
16328                        eps,
16329                        norm_style,
16330                    );
16331                    h[bi * hs..(bi + 1) * hs].copy_from_slice(&normed);
16332                }
16333            }
16334            if std::env::var("CMF_TRACE_H").is_ok() {
16335                let n = h[..hs].iter().map(|v| v.abs()).sum::<f32>() / hs as f32;
16336                let mx = h[..hs].iter().fold(0.0f32, |a, &v| a.max(v.abs()));
16337                eprintln!(
16338                    "layer {li}: mean|h|={n:.4} max|h|={mx:.2} scale={:?}",
16339                    lw.layer_scale
16340                );
16341            }
16342        }
16343        crate::gpu::set_layer(-1); // lm_head/final ops outside layer-split
16344        if prefill_prof_on() {
16345            let ms = |a: &std::sync::atomic::AtomicU64| {
16346                a.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6
16347            };
16348            let sp = &attention::ATTN_SPLIT;
16349            let (qkv_enq, qkv_wait, ca_wait, zi) = wgpu_prefill_counters();
16350            eprintln!(
16351                "prefill-split: attention {:.1} ms (proj {:.1} [qkv enqueue {:.1} wait {:.1}, \
16352                 host gate {:.1}], host loop {:.1}, attend {:.1} \
16353                 [q pack {:.1}, device {:.1} of which readback {:.1}], o-proj {:.1}), \
16354                 ffn {:.1} ms (cumulative; zi_mm GEMMs {zi})",
16355                ms(&PREFILL_SPLIT[0]),
16356                ms(&sp[0]),
16357                qkv_enq,
16358                qkv_wait,
16359                ms(&sp[6]),
16360                ms(&sp[1]),
16361                ms(&sp[2]),
16362                ms(&sp[4]),
16363                ms(&sp[5]),
16364                ca_wait,
16365                ms(&sp[3]),
16366                ms(&PREFILL_SPLIT[1]),
16367            );
16368            let [calls, attended, wo, ring, reseed, f16] = wgpu_mirror_counters();
16369            eprintln!(
16370                "prefill-mirror: {calls} calls, {attended} attended ({wo} with O on the card), \
16371                 {ring} ring refusals, {reseed} reseeds, {f16} f16 fallbacks, {} upload \
16372                 fallbacks (cumulative)",
16373                attention::MIRROR_UPLOADS.load(std::sync::atomic::Ordering::Relaxed),
16374            );
16375        }
16376        // A batched span owns a complete set of positions. Publish any
16377        // collecting→sealed transition only after every layer has finished;
16378        // callers that cross into serial/device work must see the new epoch
16379        // before this function returns.
16380        self.o1_progress();
16381        // Every layer of the chunk has appended and attended its rows.
16382        self.swa_trim_tails();
16383        h
16384    }
16385
16386    /// Embed a single token.
16387    fn embed_single(&self, id: u32) -> Vec<f32> {
16388        let mut out = vec![0.0f32; self.hidden_size];
16389        if (id as usize) < self.weights.embed_tokens.rows() {
16390            self.weights.embed_tokens.row_f32(id as usize, &mut out);
16391        }
16392        if self.embed_multiplier != 1.0 {
16393            for v in out.iter_mut() {
16394                *v *= self.embed_multiplier;
16395            }
16396        }
16397        // DeepSeek-V4's hash layers route by TOKEN ID, so the id has to
16398        // reach the forward. It rides in slot 0 (the forward re-reads the
16399        // real embedding itself from the table).
16400        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() {
16401            let mut v = vec![0.0f32; self.hidden_size.max(1)];
16402            v[0] = id as f32;
16403            return v;
16404        }
16405        // Gemma-3n: the per-layer-embedding half needs the token ID, so
16406        // it rides appended to the embedding; the g3n forward splits it.
16407        // Gemma-4 E-series PLE: same contract, its own table.
16408        if let Some(b) = &self.g4e {
16409            return b.0.extend_embedding(id, &out, self.pool.as_deref());
16410        }
16411        if let Some(b) = &self.g3n {
16412            return b.0.extend_embedding(id, &out, self.pool.as_deref());
16413        }
16414        out
16415    }
16416
16417    /// A run of consecutive prefill layers on the GPU for the whole
16418    /// chunk (default-on under CMF_GPU=1; CMF_GPU_CHUNK=0 disables).
16419    /// Eligibility per layer: q8_row weights, plain full attention
16420    /// (no output gate), F32 KV, no o1/masks/gemma extras. Returns the
16421    /// first layer index NOT processed (== `li0` when the run is empty).
16422    #[cfg(target_os = "macos")]
16423    fn chunk_run_gpu(
16424        &mut self,
16425        li0: usize,
16426        h: &mut [f32],
16427        b: usize,
16428        pos0: usize,
16429        embed_ids: Option<&[u32]>,
16430        cap: usize,
16431    ) -> usize {
16432        // (The old streaming attend needed a depth bound at ~1k; the
16433        // GEMM attention scales like the CPU path and lifted it.)
16434        // CMF_GPU_CHUNK=0 disables the graph.
16435        // Gemma-4 (`metal_gemma4`) brings its own kernels for the global
16436        // layers, V norm, attention scale and sandwich (`ChunkGemma4`).
16437        // `CMF_METAL_GEMMA4_CHUNK=0` keeps its prompt on the host walk.
16438        let gemma4 =
16439            self.metal_gemma4() && std::env::var("CMF_METAL_GEMMA4_CHUNK").as_deref() != Ok("0");
16440        if !crate::gpu::enabled_here()
16441            || std::env::var("CMF_GPU_CHUNK")
16442                .map(|v| v == "0")
16443                .unwrap_or(false)
16444            || (b < self.chunk_min_rows && self.dash.is_none() && !self.o1_chunk_prefix)
16445            // MRoPE rows rotate on the host (`attention::MropeView`).
16446            || self.prompt_mrope.is_some()
16447            // V with rows of its own (Ripple's value residual) stays on the host walk.
16448            || self.value_blend.is_some()
16449            // Sliding windows with per-layer RoPE ride the chunk graph
16450            // (`metal_graph_swa`: causal_softmax_win, per-layer tables).
16451            || (self.swa.is_some() && !self.metal_graph_swa() && !gemma4)
16452            || (self.global_attn.is_some() && !gemma4)
16453            // Chunk attention has no value-less learned-sink column. q1
16454            // decode can carry it through ordinary `gqa_attend`, but prompt
16455            // chunks must stay on the exact host attention path.
16456            || self.kv_cache.layers.iter().any(|l| l.sinks.is_some())
16457            // Per-layer KV heads and narrow V remain outside this chunk
16458            // graph (the q1 sliding-native door checks the same geometry).
16459            || (self.graph_attn_decline_reason().is_some() && !self.metal_graph_swa() && !gemma4)
16460            // Collection owns the exact Q trace and boundary conversion;
16461            // this chunk graph appends dense KV without feeding that trace,
16462            // but for a far field's exact prefix, where it keeps the queries.
16463            || (self.o1_active() && !self.o1_chunk_prefix)
16464            || (self.attn_v_norm && !gemma4)
16465            || !self.metal_rope_scale_ok()
16466            || ((self.attn_scale - 1.0 / (self.head_dim as f32).sqrt()).abs() > 1e-9 && !gemma4)
16467        {
16468            return li0;
16469        }
16470        let Some(model) = self.model.clone() else {
16471            return li0;
16472        };
16473        let (nh, nkv, hd, hs) = (
16474            self.num_heads,
16475            self.num_kv_heads,
16476            self.head_dim,
16477            self.hidden_size,
16478        );
16479        // Collect the longest run of consecutive eligible layers.
16480        // Looped Transformer: stop at the loop boundary so the CPU can
16481        // apply loop_final_norm between iterations.
16482        let loop_end = if self.loop_final_norm {
16483            ((li0 / self.physical_layers) + 1) * self.physical_layers
16484        } else {
16485            self.num_layers
16486        };
16487        let run_end = self.num_layers.min(loop_end).min(cap);
16488        // Each layer's own RoPE table (Spark-X2.5: sliding and full layers
16489        // differ); the global one for every model without sliding layers.
16490        // Declared before `layers`, which borrows it (and drops a routing
16491        // closure on MoE layers).
16492        let tables: Vec<std::sync::Arc<Vec<f32>>> =
16493            (li0..run_end).map(|li| self.layer_inv_freq(li)).collect();
16494        let mut layers: Vec<crate::gpu_metal::ChunkLayer> = Vec::new();
16495        let mut stored_at: Vec<usize> = Vec::new();
16496        for li in li0..run_end {
16497            if self.mhc_layer(li) {
16498                break;
16499            }
16500            let lw = &self.weights.layers[self.phys_layer(li)];
16501            if (lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some())
16502                && !gemma4
16503            {
16504                break;
16505            }
16506            let AttnKind::Full {
16507                wq,
16508                wk,
16509                wv,
16510                wo,
16511                q_norm,
16512                k_norm,
16513                output_gate: false,
16514                softplus_gate,
16515                bias,
16516            } = &lw.attn
16517            else {
16518                break;
16519            };
16520            // Spark-X2.5's per-head sigmoid g_proj gate, from f32 rows.
16521            let head_gate = match softplus_gate {
16522                None => None,
16523                Some((g, true)) if self.proj_gate_sigmoid => match g.f32_parts() {
16524                    Some((d, r, c)) if r == nh && c == hs => Some(d),
16525                    _ => break,
16526                },
16527                Some(_) => break,
16528            };
16529            // The FFN: a dense SiLU/GELU trio, or routed q4tp experts
16530            // (Mellum2.1: softmax router, no shared expert) whose first
16531            // trio stands in for the shape checks.
16532            let (gate_t, up_t, down_t, ffn_act, moe) = match &lw.ffn {
16533                FfnKind::Dense(d)
16534                    if (matches!(d.act, Act::Silu | Act::Gelu)
16535                        || (gemma4 && d.act == Act::GeluTanh))
16536                        && d.segs.is_empty() =>
16537                {
16538                    (&d.gate_proj, &d.up_proj, &d.down_proj, d.act, None)
16539                }
16540                FfnKind::Moe(m) => match chunk_moe_parts(m, hs) {
16541                    Some((router, experts, q8)) => {
16542                        let e0 = &m.experts[0];
16543                        let route = Box::new(move |lg: &[f32]| {
16544                            // `moe_ffn_batch`'s routing and weights, row by row.
16545                            let (idx, p, wsum) = moe_route(lg, m, None);
16546                            let mut st = m.stats.borrow_mut();
16547                            if st.len() < m.experts.len() {
16548                                st.resize(m.experts.len(), 0);
16549                            }
16550                            for &e in &idx {
16551                                st[e] += 1;
16552                            }
16553                            let w = idx.iter().map(|&e| p[e] / wsum).collect();
16554                            (idx, w)
16555                        });
16556                        let detached = m.shared.as_ref().map(|(s, _)| {
16557                            let t = |x: &QTensor| {
16558                                x.q8_2f_parts().map(|p| p.0).or_else(|| x.q4tp_parts().map(|p| p.0)).unwrap_or(usize::MAX)
16559                            };
16560                            ([t(&s.gate_proj), t(&s.up_proj), t(&s.down_proj)], s.gate_proj.rows())
16561                        });
16562                        (
16563                            &e0.gate_proj,
16564                            &e0.up_proj,
16565                            &e0.down_proj,
16566                            Act::Silu,
16567                            Some(crate::gpu_metal::ChunkMoe {
16568                                router,
16569                                experts,
16570                                q8,
16571                                route,
16572                                detached,
16573                            }),
16574                        )
16575                    }
16576                    None => break,
16577                },
16578                _ => break,
16579            };
16580            // q8_row (row_scale populated), q8_2f (plus its input field),
16581            // or q4_tiled / q4tp (row_scale empty — their scales are in the
16582            // payload). Mixing across the seven projections of one layer is
16583            // fine; the encoder branches per weight on the tensor's dtype.
16584            // Anything else refuses.
16585            fn cw(t: &QTensor) -> Option<(usize, usize, usize, &[f32])> {
16586                t.q8_row_parts()
16587                    .or_else(|| t.q8_2f_parts().map(|(i, r, c, rs, _)| (i, r, c, rs)))
16588                    .or_else(|| t.q4t_parts().map(|(i, r, c)| (i, r, c, &[][..])))
16589                    .or_else(|| t.q4tp_parts().map(|(i, r, c)| (i, r, c, &[][..])))
16590            }
16591            fn cf(t: &QTensor) -> &[f32] {
16592                t.q8_2f_parts().map_or(&[][..], |(_, _, _, _, cf)| cf)
16593            }
16594            let col = [cf(wq), cf(wk), cf(wv), cf(wo)];
16595            let ffn_col = [cf(gate_t), cf(up_t), cf(down_t)];
16596            // q8_2f projections ride the chunk graph on the MoE layers it
16597            // was measured on (Mellum2.1) and on the dense exact-GELU FFN
16598            // (Spark-X2.6-4B q8_2f on the M4: the gate/up inputs staged as
16599            // x·col, the down field applied after the activation —
16600            // `ChunkLayer::ffn_col`). A dense SiLU q8_2f stack keeps the host
16601            // walk: its down GEMM fuses the activation into the X-tile load
16602            // and has no input field (0.8.14 refused every q8_2f weight here).
16603            // Gemma-4 reads every q8_2f weight through the blob GEMM with its
16604            // own field (`ChunkGemma4`), so its dense q8_2f stack rides.
16605            if moe.is_none()
16606                && !gemma4
16607                && self.dash.is_none()
16608                && ffn_act != Act::Gelu
16609                && (col.iter().any(|c| !c.is_empty()) || ffn_col.iter().any(|c| !c.is_empty()))
16610            {
16611                break;
16612            }
16613            let parts = (
16614                cw(wq),
16615                cw(wk),
16616                cw(wv),
16617                cw(wo),
16618                cw(gate_t),
16619                cw(up_t),
16620                cw(down_t),
16621            );
16622            let (Some(pq), Some(pk), Some(pv), Some(po), Some(pg), Some(pu), Some(pd)) = parts
16623            else {
16624                break;
16625            };
16626            let layer = &self.kv_cache.layers[li];
16627            if layer.mode != crate::kv_cache::KvMode::F32
16628                || (layer.o1.is_some() && !(self.o1_chunk_prefix && layer.o1_is_collecting()))
16629            {
16630                break;
16631            }
16632            // A trimmed tail holds every row the chunk's first query reads.
16633            debug_assert!(
16634                layer.base() == 0
16635                    || self
16636                        .layer_window(li)
16637                        .is_some_and(|w| layer.head_len(0) + 1 >= w)
16638            );
16639            stored_at.push(layer.head_len(0));
16640            // Per-layer geometry for Gemma-4 (512-wide global layers over
16641            // one KV head); every other model keeps the pipeline-wide one.
16642            let (nkv, hd) = if gemma4 {
16643                let (a, bb, _) = self.layer_geom(li);
16644                (a, bb)
16645            } else {
16646                (nkv, hd)
16647            };
16648            layers.push(crate::gpu_metal::ChunkLayer {
16649                model: &model,
16650                kv_id: self.graph_kv_id,
16651                layer: li,
16652                wq: pq,
16653                wk: pk,
16654                wv: pv,
16655                wo: po,
16656                gate: pg,
16657                up: pu,
16658                down: pd,
16659                input_norm: &lw.input_norm,
16660                post_norm: &lw.post_norm,
16661                bias: bias
16662                    .as_ref()
16663                    .map(|(a, bb, cc)| (a.as_slice(), bb.as_slice(), cc.as_slice())),
16664                q_norm: q_norm.as_deref(),
16665                k_norm: k_norm.as_deref(),
16666                inv_freq: &tables[li - li0],
16667                rope_scale: self.layer_rope_scale(li),
16668                rd: self.layer_geom(li).2,
16669                nh,
16670                nkv,
16671                hd,
16672                hs,
16673                inter: gate_t.rows(),
16674                gemma: matches!(self.norm_style, cortiq_core::NormStyle::Gemma),
16675                late_qk_norm: self.qk_norm_after_rope,
16676                eps: self.rms_eps as f32,
16677                window: self.layer_window(li),
16678                head_gate,
16679                act: ffn_act.graph_act().map_or(0, |a| a.code() as u8),
16680                g4: gemma4.then(|| crate::gpu_metal::ChunkGemma4 {
16681                    v_norm: self.attn_v_norm,
16682                    scale: self.attn_scale,
16683                    attn_out_norm: lw.attn_out_norm.as_deref(),
16684                    ffn_out_norm: lw.ffn_out_norm.as_deref(),
16685                    layer_scale: lw.layer_scale,
16686                }),
16687                col,
16688                // The plain dense branch alone reads it: routed experts and
16689                // Gemma-4 carry their own fields.
16690                ffn_col: if moe.is_none() && !gemma4 {
16691                    ffn_col
16692                } else {
16693                    [&[][..]; 3]
16694                },
16695                moe,
16696                dash: self.graph_dash(li),
16697            });
16698        }
16699        if layers.is_empty() {
16700            return li0;
16701        }
16702        // Unlimited-OCR: all of it or none of it (the router state).
16703        if self.dash.is_some() && (li0 != 0 || layers.len() != self.num_layers) {
16704            return li0;
16705        }
16706        // KV row width per layer (uniform but for Gemma-4).
16707        let rows_kv: Vec<(usize, usize)> = layers.iter().map(|l| (l.nkv, l.nkv * l.hd)).collect();
16708        let mut store: Vec<(Vec<f32>, Vec<f32>, Vec<f32>)> = stored_at
16709            .iter()
16710            .zip(&rows_kv)
16711            .map(|(&st, &(_, row))| (vec![0f32; b * row], vec![0f32; b * row], vec![0f32; st + b]))
16712            .collect();
16713        let mut io: Vec<crate::gpu_metal::ChunkIo> = Vec::with_capacity(layers.len());
16714        for (i, (ok, ov, oi)) in store.iter_mut().enumerate() {
16715            let li = layers[i].layer;
16716            let layer = &self.kv_cache.layers[li];
16717            let nkv = rows_kv[i].0;
16718            io.push(crate::gpu_metal::ChunkIo {
16719                cpu_stored: stored_at[i],
16720                cpu_gen: layer.generation(),
16721                cpu_k: (0..nkv).map(|g| layer.head_keys(g)).collect(),
16722                cpu_v: (0..nkv).map(|g| layer.head_values(g)).collect(),
16723                out_k: ok,
16724                out_v: ov,
16725                imp: oi,
16726            });
16727        }
16728        let n_run = layers.len();
16729        let last = layers.last().map(|l| l.layer + 1).unwrap_or(li0);
16730        // Device-side embedding when the run starts the model and the
16731        // embedding matrix is q8_row-mapped.
16732        let ep = embed_ids.and_then(|ids| {
16733            self.weights
16734                .embed_tokens
16735                .q8_row_parts()
16736                .map(|(idx, rows, _c, rs)| crate::gpu_metal::ChunkEmbed {
16737                    idx,
16738                    rows,
16739                    row_scale: rs,
16740                    ids,
16741                    mult: self.embed_multiplier,
16742                })
16743        });
16744        if embed_ids.is_some() && ep.is_none() {
16745            return li0;
16746        }
16747        if !crate::gpu_metal::chunk_run_gpu(&layers, &mut io, h, b, pos0, ep.as_ref()) {
16748            return li0;
16749        }
16750        drop(io);
16751        drop(layers);
16752        // CPU caches stay the owners of record: append the chunk rows
16753        // and bank the importance masses per layer.
16754        for (i, (ok, ov, oi)) in store.iter().enumerate().take(n_run) {
16755            let li = li0 + i;
16756            let row = rows_kv[i].1;
16757            let layer = &mut self.kv_cache.layers[li];
16758            for bi in 0..b {
16759                layer.append(
16760                    &ok[bi * row..(bi + 1) * row],
16761                    &ov[bi * row..(bi + 1) * row],
16762                    &[],
16763                );
16764            }
16765            layer.accumulate_imp(oi);
16766        }
16767        last
16768    }
16769
16770    /// Is layer `li` a sliding-window (local-RoPE) layer? Gemma-3:
16771    /// every `pattern`-th layer is global, the rest are local.
16772    fn layer_is_local(&self, li: usize) -> bool {
16773        if let Some(layers) = &self.sliding_layers {
16774            return layers.get(li).copied().unwrap_or(false);
16775        }
16776        match self.swa {
16777            Some((_, pattern)) => (li + 1) % pattern.max(1) != 0,
16778            None => false,
16779        }
16780    }
16781
16782    /// The RoPE table for layer `li` (local layers may have their own;
16783    /// Gemma-4 global layers use the proportional padded table).
16784    fn layer_inv_freq(&self, li: usize) -> std::sync::Arc<Vec<f32>> {
16785        if self.layer_is_local(li) {
16786            if let Some(f) = &self.inv_freq_local {
16787                return f.clone();
16788            }
16789        } else if let Some(f) = &self.inv_freq_global {
16790            return f.clone();
16791        }
16792        self.inv_freq.clone()
16793    }
16794
16795    /// Layer `li`'s value-residual blend (None = V reads the normed input).
16796    fn layer_value_blend(&self, li: usize) -> Option<f32> {
16797        self.value_blend
16798            .as_ref()
16799            .and_then(|v| v.get(self.phys_layer(li)).copied())
16800    }
16801
16802    /// The attend window for layer `li` (None = full context).
16803    fn layer_window(&self, li: usize) -> Option<usize> {
16804        self.swa
16805            .and_then(|(w, _)| self.layer_is_local(li).then_some(w))
16806    }
16807
16808    /// Drop every sliding layer's rows its window can no longer read
16809    /// (`LayerKvCache::trim_window`). Call only at a safe point — after a
16810    /// complete position / pair / chunk walk, never between a layer's
16811    /// appends and its attend. One comparison per layer below the trigger.
16812    ///
16813    /// Off with an MTP head: its verify oracles and rollbacks snapshot and
16814    /// compare per-layer row counts as positions (`CMF_METAL_VERIFY_CHECK`,
16815    /// the MTP caches), which a trimmed tail would break.
16816    fn swa_trim_tails(&mut self) {
16817        let Some((slack, align)) = self.swa_trim else {
16818            return;
16819        };
16820        if self.mtp.is_some() || self.mimo_mtp.is_some() || !self.dsv4_mtp.is_empty() {
16821            return;
16822        }
16823        for li in 0..self.num_layers.min(self.kv_cache.layers.len()) {
16824            if let Some(w) = self.layer_window(li) {
16825                self.kv_cache.layers[li].trim_window_anchored(w, slack, align, self.swa_trim_anchor);
16826            }
16827        }
16828    }
16829
16830    fn layer_num_heads(&self, li: usize) -> usize {
16831        self.attention_heads_per_layer
16832            .as_ref()
16833            .and_then(|v| v.get(li).copied())
16834            .unwrap_or(self.num_heads)
16835    }
16836
16837    fn layer_rope_scale(&self, li: usize) -> f32 {
16838        if self.layer_is_local(li) {
16839            self.rope_scale_local
16840        } else {
16841            self.rope_scale
16842        }
16843    }
16844
16845    /// Attention geometry of layer `li`: (num_kv_heads, head_dim,
16846    /// rotary_dim). Gemma-4 global layers override all three.
16847    fn layer_geom(&self, li: usize) -> (usize, usize, usize) {
16848        if !self.layer_is_local(li) {
16849            if let Some((ghd, gkv)) = self.global_attn {
16850                return (gkv, ghd, ghd);
16851            }
16852        }
16853        let rd = if self.layer_is_local(li) {
16854            self.rotary_dim_local.unwrap_or(self.rotary_dim)
16855        } else {
16856            self.rotary_dim
16857        };
16858        // A layer without positional encoding rotates nothing.
16859        let rd = if self
16860            .no_rope_layers
16861            .as_ref()
16862            .and_then(|v| v.get(li))
16863            .copied()
16864            == Some(true)
16865        {
16866            0
16867        } else {
16868            rd
16869        };
16870        (self.layer_num_kv_heads(li), self.head_dim, rd)
16871    }
16872
16873    /// KV heads of layer `li` (virtual index): the per-layer count when the
16874    /// model has one (MiMo-V2), else the uniform `num_kv_heads`.
16875    fn layer_num_kv_heads(&self, li: usize) -> usize {
16876        self.kv_heads_per_layer
16877            .as_ref()
16878            .and_then(|v| v.get(self.phys_layer(li)).copied())
16879            .unwrap_or(self.num_kv_heads)
16880    }
16881
16882    /// V head width of layer `li` (≤ its head_dim).
16883    fn layer_v_dim(&self, li: usize) -> usize {
16884        let (_, hd, _) = self.layer_geom(li);
16885        self.v_head_dim.unwrap_or(hd).min(hd)
16886    }
16887
16888    /// Install a per-layer KV geometry: KV heads per PHYSICAL layer and/or
16889    /// a V head width narrower than `head_dim` (MiMo-V2). Validates it and
16890    /// reshapes the caches of every layer whose KV head count differs from
16891    /// `num_kv_heads`. The loader and the tests share this one path, so a
16892    /// hand-built pipeline cannot hold a geometry the loader would refuse.
16893    /// Call before the first forward (it drops cached rows of reshaped
16894    /// layers). Refuses combinations whose paths would read it wrong:
16895    /// Gemma-4 global layers and MLA carry their own geometry.
16896    pub fn set_attn_geometry(
16897        &mut self,
16898        kv_heads_per_layer: Option<Vec<usize>>,
16899        v_head_dim: Option<usize>,
16900    ) -> Result<(), String> {
16901        if kv_heads_per_layer.is_some() || v_head_dim.is_some() {
16902            if self.global_attn.is_some() {
16903                return Err(
16904                    "per-layer KV heads / v_head_dim cannot combine with Gemma-4 global \
16905                     attention geometry"
16906                        .into(),
16907                );
16908            }
16909            if self
16910                .weights
16911                .layers
16912                .iter()
16913                .any(|lw| matches!(lw.attn, AttnKind::Mla(_)))
16914            {
16915                return Err("per-layer KV heads / v_head_dim cannot combine with MLA".into());
16916            }
16917        }
16918        if let Some(vd) = v_head_dim {
16919            if vd == 0 || vd > self.head_dim {
16920                return Err(format!(
16921                    "v_head_dim {vd} must be in 1..={} (head_dim)",
16922                    self.head_dim
16923                ));
16924            }
16925        }
16926        if let Some(v) = &kv_heads_per_layer {
16927            if v.len() != self.physical_layers {
16928                return Err(format!(
16929                    "kv_heads_per_layer has {} entries, expected {} layers",
16930                    v.len(),
16931                    self.physical_layers
16932                ));
16933            }
16934            for (li, &nkv) in v.iter().enumerate() {
16935                let is_attn = matches!(
16936                    self.weights.layers.get(li).map(|lw| &lw.attn),
16937                    Some(AttnKind::Full { .. }) | None
16938                );
16939                if !is_attn {
16940                    continue;
16941                }
16942                let nh = self
16943                    .attention_heads_per_layer
16944                    .as_ref()
16945                    .and_then(|h| h.get(li).copied())
16946                    .unwrap_or(self.num_heads);
16947                if nkv == 0 || nh % nkv != 0 {
16948                    return Err(format!(
16949                        "layer {li}: {nkv} KV heads must be nonzero and divide {nh} Q heads"
16950                    ));
16951                }
16952            }
16953        }
16954        self.kv_heads_per_layer = kv_heads_per_layer;
16955        self.v_head_dim = v_head_dim.filter(|&vd| vd != self.head_dim);
16956        if self.kv_heads_per_layer.is_some() {
16957            for li in 0..self.kv_cache.layers.len() {
16958                let full = matches!(
16959                    self.weights
16960                        .layers
16961                        .get(self.phys_layer(li))
16962                        .map(|lw| &lw.attn),
16963                    Some(AttnKind::Full { .. })
16964                );
16965                let nkv = self.layer_num_kv_heads(li);
16966                let cache = &self.kv_cache.layers[li];
16967                if full && (cache.num_kv_heads != nkv || cache.head_dim != self.head_dim) {
16968                    let sinks = cache.sinks.clone();
16969                    self.kv_cache.layers[li] =
16970                        crate::kv_cache::LayerKvCache::new(nkv, self.head_dim);
16971                    self.kv_cache.layers[li].sinks = sinks;
16972                }
16973            }
16974        }
16975        Ok(())
16976    }
16977
16978    /// Attach learned attention-sink logits (one per Q head) to PHYSICAL
16979    /// layer `phys` — every virtual layer that runs it. The loader calls
16980    /// this for each `model.layers.N.self_attn.sinks` tensor.
16981    pub fn set_layer_sinks(&mut self, phys: usize, sinks: Vec<f32>) -> Result<(), String> {
16982        let Some(lw) = self.weights.layers.get(phys) else {
16983            return Err(format!("sinks for layer {phys}: no such layer"));
16984        };
16985        if !matches!(lw.attn, AttnKind::Full { .. }) {
16986            return Err(format!(
16987                "sinks for layer {phys}: only softmax (Full) attention layers take sinks"
16988            ));
16989        }
16990        let nh = self
16991            .attention_heads_per_layer
16992            .as_ref()
16993            .and_then(|h| h.get(phys).copied())
16994            .unwrap_or(self.num_heads);
16995        if sinks.len() != nh {
16996            return Err(format!(
16997                "sinks for layer {phys}: {} values, expected one per Q head ({nh})",
16998                sinks.len()
16999            ));
17000        }
17001        if let Some(bad) = sinks.iter().find(|v| !v.is_finite()) {
17002            return Err(format!("sinks for layer {phys}: non-finite value {bad}"));
17003        }
17004        for li in 0..self.kv_cache.layers.len() {
17005            if self.phys_layer(li) == phys {
17006                self.kv_cache.layers[li].sinks = Some(sinks.clone());
17007            }
17008        }
17009        Ok(())
17010    }
17011
17012    /// Why the GPU attention graphs cannot serve this model, if they
17013    /// cannot: the wgpu whole-token and batched graphs, the greedy
17014    /// multi-burst, the q1 attention dropin and the Metal block/chunk/rows
17015    /// graphs all assume ONE (num_kv_heads, head_dim) geometry, V heads as
17016    /// wide as K, a single RoPE table, full-context attention and a plain
17017    /// softmax. A model outside that contract runs on the CPU layer walk
17018    /// (and the per-op GPU matvecs) until a graph learns it — never on a
17019    /// graph that would read it wrong. None = no attention-level reason
17020    /// (the graph builders still check weights and layer kinds).
17021    pub fn graph_attn_decline_reason(&self) -> Option<&'static str> {
17022        if self.kv_heads_per_layer.is_some() {
17023            return Some("per-layer KV head counts");
17024        }
17025        if self.v_head_dim.is_some_and(|vd| vd != self.head_dim) {
17026            return Some("V heads narrower than Q/K heads");
17027        }
17028        if self.kv_cache.layers.iter().any(|l| l.sinks.is_some()) {
17029            return Some("learned attention sinks");
17030        }
17031        if self.swa.is_some() || self.sliding_layers.is_some() {
17032            return Some("sliding-window layers");
17033        }
17034        None
17035    }
17036
17037    /// Can the Metal kernels apply this model's RoPE amplitude? Every
17038    /// rotation kernel (`attn_rope_qkn[_b]`, `chunk_rope_kv`) multiplies the
17039    /// rotated pair by the layer's `rope_scale` (YaRN `attention_factor`,
17040    /// Mellum2.1's global layers) exactly where the CPU's
17041    /// `rope_rotate_scaled` does. With the Q/K norm AFTER RoPE the kernels'
17042    /// shared sum of squares would be the unscaled one, so that pairing
17043    /// (no known model) declines.
17044    #[cfg(target_os = "macos")]
17045    fn metal_rope_scale_ok(&self) -> bool {
17046        !(self.qk_norm_after_rope
17047            && (0..self.num_layers).any(|li| self.layer_rope_scale(li) != 1.0))
17048    }
17049
17050    /// Can the Metal block graph carry this model's sliding-window layers?
17051    /// Both of its attention forms take a layer's own window, RoPE table
17052    /// and rotary width: the device attend (`AttnDeviceParams::window`, the
17053    /// layer's `inv_freq`/`rd`) and the sandwich's host attend (exactly the
17054    /// CPU path's attention). True when the sliding window is the model's
17055    /// only attention-level decline (Spark-X2.5). Learned, value-less
17056    /// sinks may accompany that geometry: q1's ordinary device GQA
17057    /// includes the sink in its softmax denominator and disables split-K.
17058    /// Per-layer KV heads, narrow V and Gemma-4 global geometry still
17059    /// decline; a YaRN amplitude per layer rides along
17060    /// (`metal_rope_scale_ok`).
17061    ///
17062    /// Per-layer Q heads (Laguna) and capped scores (Gemma-2) decline here
17063    /// too, with V norm (Gemma-4): the chunk prefill's own gate checks
17064    /// neither of the first two, and before this door opened its `swa`
17065    /// refusal kept every sliding model with them off the chunk graph.
17066    #[cfg(target_os = "macos")]
17067    fn metal_graph_swa(&self) -> bool {
17068        (self.swa.is_some() || self.sliding_layers.is_some())
17069            && self.attention_heads_per_layer.is_none()
17070            && !self.attn_v_norm
17071            && self.attn_softcap == 0.0
17072            && self.kv_heads_per_layer.is_none()
17073            && self.v_head_dim.map_or(true, |vd| vd == self.head_dim)
17074            && self.global_attn.is_none()
17075            && self.inv_freq_global.is_none()
17076            && self.metal_rope_scale_ok()
17077            && !(0..self.num_layers).any(|li| {
17078                self.layer_is_local(li)
17079                    && self.inv_freq_local.is_none()
17080                    && self.rotary_dim_local.is_some_and(|r| r != self.rotary_dim)
17081            })
17082    }
17083
17084    /// Can the Metal graphs carry this Gemma-4 model (`gpu_metal::gemma4`)?
17085    /// Its sliding layers (window, local RoPE table, 256-wide heads)
17086    /// device-attend like Spark-X2.5's; the 512-wide global layers (one KV
17087    /// head, proportional RoPE in the zero-padded table) take the 16-slot
17088    /// kernels; the V norm, sandwich norms, layer scalar and tanh-GELU come
17089    /// from the Gemma-4 library. Dense FFNs only (no Gemma-4 MoE measured).
17090    /// `CMF_METAL_GEMMA4=0` declines it as before (CPU attention).
17091    #[cfg(target_os = "macos")]
17092    fn metal_gemma4(&self) -> bool {
17093        crate::gpu_metal::gemma4::enabled()
17094            && (self.global_attn.is_some() || self.attn_v_norm)
17095            && self.attention_heads_per_layer.is_none()
17096            && self.kv_heads_per_layer.is_none()
17097            && self.v_head_dim.is_none()
17098            && !self.kv_cache.layers.iter().any(|l| l.sinks.is_some())
17099            && self.attn_softcap == 0.0
17100            && !self.qk_norm_after_rope
17101            && self.metal_rope_scale_ok()
17102            && self
17103                .weights
17104                .layers
17105                .iter()
17106                .all(|lw| matches!(&lw.ffn, FfnKind::Dense(d) if d.segs.is_empty()))
17107            && !(0..self.num_layers).any(|li| {
17108                self.layer_is_local(li)
17109                    && self.inv_freq_local.is_none()
17110                    && self.rotary_dim_local.is_some_and(|r| r != self.rotary_dim)
17111            })
17112    }
17113
17114    /// Why the WGPU graphs (whole-token, batched prefill, greedy burst)
17115    /// cannot run this model's attention, if they cannot. Per-layer KV
17116    /// heads, V narrower than K, learned sinks and sliding windows ride
17117    /// their per-layer geometry (`GraphAttnGeom`, the ATTEND_X kernels);
17118    /// what that geometry does not express keeps the decline, by name.
17119    /// None for every model with one attention geometry.
17120    pub fn wgpu_graph_attn_decline(&self) -> Option<&'static str> {
17121        if self.value_blend.is_some() && !crate::gpu::vres_graph_on() {
17122            return Some("value residual");
17123        }
17124        // Keep the ordinary (uniform) fast arms off YaRN until they carry a
17125        // scale field too. A non-uniform geometry gets a `GraphAttnGeom` and
17126        // is handled below by the generic graph kernels.
17127        let geometry_reason = self.graph_attn_decline_reason();
17128        let has_scaled_rope = (0..self.num_layers).any(|li| self.layer_rope_scale(li) != 1.0);
17129        if has_scaled_rope && geometry_reason.is_none() {
17130            return Some("scaled RoPE without per-layer geometry");
17131        }
17132        // For Q/K norm after partial RoPE, the scale changes only the rotary
17133        // slice's RMS denominator. The generic graph deliberately declines
17134        // that uncommon combination until it carries a separate rotary sum;
17135        // Mellum has q/k norm before RoPE, so it remains on this path.
17136        if has_scaled_rope && self.qk_norm_after_rope {
17137            return Some("scaled RoPE with post-RoPE Q/K norm");
17138        }
17139        geometry_reason?;
17140        // Gemma-4: global layers 512 wide over 256-wide sliding ones
17141        // (`GraphAttnGeom::hd`), the scale-less V norm (`v_norm`), and the
17142        // sandwich norms + layer scalar (`GraphLayer`) ride the TOKEN graph.
17143        // The batch graph has none of the three and refuses them itself
17144        // (`batch_graph_gemma_decline`).
17145        if self.attention_heads_per_layer.is_some() {
17146            return Some("per-layer Q head counts with per-layer geometry");
17147        }
17148        // Sandwich norms are measured on Gemma-4 (the humanizer port) and
17149        // LFM3, both with plain x̂·w weights, against HF transformers;
17150        // Gemma-2/3's (1+w) norms keep the per-op path until they are
17151        // measured the same way, and a layer scale stays Gemma-4's.
17152        let gemma4 = self.global_attn.is_some() || self.attn_v_norm;
17153        let plain_norms = self.norm_style == cortiq_core::NormStyle::Qwen;
17154        if !gemma4
17155            && self.weights.layers.iter().any(|lw| {
17156                lw.layer_scale.is_some()
17157                    || (!plain_norms && (lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some()))
17158            })
17159        {
17160            return Some("sandwich norms / layer scale with per-layer geometry");
17161        }
17162        // `GraphAttnGeom::rope_scale` carries YaRN's post-rotation
17163        // attention-amplitude factor to the WGPU RoPE kernel. It is not an
17164        // angular position scale, so it must not be folded into `invf`.
17165        if self.weights.layers.iter().any(|lw| {
17166            matches!(
17167                &lw.attn,
17168                AttnKind::Full {
17169                    output_gate: true,
17170                    ..
17171                }
17172            )
17173        }) && self.v_head_dim.is_some()
17174        {
17175            return Some("gated attention with V narrower than K");
17176        }
17177        if (0..self.num_layers).any(|li| {
17178            self.layer_is_local(li)
17179                && self.inv_freq_local.is_none()
17180                && self.rotary_dim_local.is_some_and(|r| r != self.rotary_dim)
17181        }) {
17182            return Some("local rotary width without a local RoPE table");
17183        }
17184        None
17185    }
17186
17187    /// What the wgpu BATCH graph (and the attention-only singleton graphs)
17188    /// cannot run of Gemma-4, which the token graph does run: per-layer
17189    /// head widths, the V norm, sandwich norms and the layer scalar.
17190    fn batch_graph_gemma_decline(&self) -> Option<&'static str> {
17191        // Gemma-4 rides `gemma_batch` (per-layer head width, V norm,
17192        // sandwich norms, layer scalar) unless CMF_G4_BATCH=0.
17193        if (self.global_attn.is_some() || self.attn_v_norm) && crate::gpu::g4_batch_on() {
17194            return None;
17195        }
17196        if self.global_attn.is_some() {
17197            return Some("per-layer head width (Gemma-4 global layers)");
17198        }
17199        if self.attn_v_norm {
17200            return Some("V norm");
17201        }
17202        // Sandwich norms alone ride the batch graph's plain tails (Ripple).
17203        if self.weights.layers.iter().any(|lw| lw.layer_scale.is_some()) {
17204            return Some("layer scale");
17205        }
17206        // CUDA's hybrid prompt path takes plain sandwich norms itself (LFM3's,
17207        // beside its short convolutions and head gate): its batch arm decides.
17208        // So does wgpu's batch graph for the LFM stacks (short convolutions):
17209        // their sandwich norms ride its plain tails, as Ripple's do.
17210        let lfm = self.short_conv_cfg.is_some() && self.weights.layers.iter().any(|lw| matches!(lw.attn, AttnKind::ShortConv(_)));
17211        if self.value_blend.is_none()
17212            && !lfm
17213            && !crate::gpu::cuda_active()
17214            && self
17215                .weights
17216                .layers
17217                .iter()
17218                .any(|lw| lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some())
17219        {
17220            return Some("sandwich norms");
17221        }
17222        None
17223    }
17224
17225    /// The wgpu graphs' attention geometry for layer `li` (virtual index):
17226    /// Some only for a model whose layers do not share one (MiMo-V2) — KV
17227    /// heads, V width, rotary width and RoPE table, window and sinks of
17228    /// THIS layer, exactly what the CPU attention reads for it.
17229    /// Unlimited-OCR: layer `li`'s router for the device graphs.
17230    /// Kimi-Linear's mixers for the graphs (`GraphAttn::Kda` / `Mla`), with
17231    /// the model the weights live in; `gw` the caller's weight resolver.
17232    fn graph_attn_kimi<'s>(
17233        &'s self,
17234        li: usize,
17235        attn: &'s AttnKind,
17236        gw: &dyn Fn(&'s QTensor) -> Option<crate::gpu::GraphW<'s>>,
17237    ) -> Option<(crate::gpu::GraphAttn<'s>, std::sync::Arc<cortiq_core::CmfModel>)> {
17238        match attn {
17239            AttnKind::Kda(w) => {
17240                let cfg = self.kda_cfg?;
17241                let (m, _, _, _) = w.q_proj.graph_weight_or_blr()?;
17242                let (g_a, g_b) = match &w.gate {
17243                    crate::linear_core::KdaOutGate::Full(g) => (gw(g)?, None),
17244                    crate::linear_core::KdaOutGate::LowRank(a, b) => (gw(a)?, Some(gw(b)?)),
17245                };
17246                Some((
17247                    crate::gpu::GraphAttn::Kda {
17248                        q: gw(&w.q_proj)?,
17249                        k: gw(&w.k_proj)?,
17250                        v: gw(&w.v_proj)?,
17251                        conv_q: &w.conv_q,
17252                        conv_k: &w.conv_k,
17253                        conv_v: &w.conv_v,
17254                        f_a: gw(&w.f_a)?,
17255                        f_b: gw(&w.f_b)?,
17256                        dt_bias: &w.dt_bias,
17257                        a_log: &w.a_log,
17258                        b: gw(&w.b_proj)?,
17259                        g_a,
17260                        g_b,
17261                        o_norm: &w.o_norm,
17262                        out: gw(&w.o_proj)?,
17263                        nh: cfg.num_heads,
17264                        dk: cfg.head_k_dim,
17265                        dv: cfg.head_v_dim,
17266                        kk: cfg.conv_kernel,
17267                        lower_bound: w.gate_lower_bound,
17268                        cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
17269                    },
17270                    m.clone(),
17271                ))
17272            }
17273            AttnKind::Mla(w) => {
17274                let (m, _, _, _) = w.kv_a.graph_weight_or_blr()?;
17275                let q_a = match &w.q_a {
17276                    Some(t) => Some(gw(t)?),
17277                    None => None,
17278                };
17279                Some((
17280                    crate::gpu::GraphAttn::Mla {
17281                        hy: None,
17282                        q_a,
17283                        q_a_norm: w.q_a_norm.as_deref(),
17284                        q: gw(&w.q_proj)?,
17285                        kv_a: gw(&w.kv_a)?,
17286                        kv_a_norm: &w.kv_a_norm,
17287                        kv_b: gw(&w.kv_b)?,
17288                        o: gw(&w.o_proj)?,
17289                        nh: w.nh,
17290                        rope: w.qk_rope,
17291                        nope: w.qk_nope,
17292                        v_dim: w.v_dim,
17293                        lora: w.lora,
17294                        scale: w.scale,
17295                        no_rope: w.nope,
17296                        cpu_k: self.kv_cache.layers[li].k_heads(),
17297                        cpu_v: self.kv_cache.layers[li].v_heads(),
17298                        cpu_base: self.kv_cache.layers[li].base(),
17299                        dsa: None,
17300                    },
17301                    m.clone(),
17302                ))
17303            }
17304            _ => None,
17305        }
17306    }
17307
17308    fn graph_dash(&self, li: usize) -> Option<crate::gpu::GraphDash<'_>> {
17309        self.dash.as_deref().map(|d| {
17310            let l = &d.layers[li];
17311            crate::gpu::GraphDash {
17312                qk_proj: &l.qk_proj,
17313                q_norm: &l.q_norm,
17314                k_norm: &l.k_norm,
17315                head_cls: &l.head_cls,
17316                idx_scale: l.route.idx_scale,
17317                floor: l.route.floor,
17318                sigma: l.route.sigma,
17319                k: l.route.k,
17320                block: d.block,
17321                local_blocks: d.local_blocks,
17322                nblk: d.allow.len(),
17323                cands: &d.cands,
17324                coff: &d.coff,
17325                angles: &d.angles,
17326            }
17327        })
17328    }
17329
17330    fn graph_attn_geom(&self, li: usize) -> Option<crate::gpu::GraphAttnGeom<'_>> {
17331        if self.dash.is_none() {
17332            self.graph_attn_decline_reason()?;
17333        }
17334        let (nkv, hd, rd) = self.layer_geom(li);
17335        let dash = self.graph_dash(li);
17336        let invf: &[f32] = if let Some(d) = self.dash.as_deref() {
17337            &d.angles
17338        } else if self.layer_is_local(li) {
17339            match &self.inv_freq_local {
17340                Some(f) => f.as_slice(),
17341                None => self.inv_freq.as_slice(),
17342            }
17343        } else {
17344            match &self.inv_freq_global {
17345                Some(f) => f.as_slice(),
17346                None => self.inv_freq.as_slice(),
17347            }
17348        };
17349        Some(crate::gpu::GraphAttnGeom {
17350            nkv,
17351            hd,
17352            dv: self.layer_v_dim(li),
17353            rd,
17354            invf,
17355            rope_scale: self.layer_rope_scale(li),
17356            window: self.layer_window(li),
17357            sink: self.kv_cache.layers[li].sinks.as_deref(),
17358            v_norm: self.attn_v_norm,
17359            dash,
17360            vres: None,
17361            route: None,
17362        })
17363    }
17364
17365    /// The decode graph's geometry of layer `li`: `graph_attn_geom`, except
17366    /// that a full-attention layer of the call's own geometry takes the
17367    /// uniform arms (None) on the wgpu token graph of a stack that asked for
17368    /// it (`uniform_full_layers`). Its mirror is the one the prompt's
17369    /// per-layer-geometry arm filled — one f32 row a position either way —
17370    /// and the decode reads it through the flash-decoding attend instead of
17371    /// one workgroup a head over every row (Aion-2.3B q4tp on an L4 at 16k /
17372    /// 30k tokens: 54 / 41 → see CHANGELOG). The prompt keeps the geometry
17373    /// arm: its matrix-unit tile takes 128-wide heads, the uniform one 256.
17374    fn graph_attn_geom_decode<'a>(&'a self, li: usize, e0: &'a [f32]) -> Option<crate::gpu::GraphAttnGeom<'a>> {
17375        let (nkv, hd, rd) = self.layer_geom(li);
17376        if self.uniform_full_layers
17377            && crate::gpu::wgpu_active()
17378            && self.dash.is_none()
17379            && !self.layer_is_local(li)
17380            && self.kv_cache.layers[li].sinks.is_none()
17381            && (nkv, hd, rd) == (self.num_kv_heads, self.head_dim, self.rotary_dim)
17382            && self.layer_v_dim(li) == hd
17383            && self.inv_freq_global.is_none()
17384            && self.layer_rope_scale(li) == 1.0
17385            && !self.attn_v_norm
17386            && self.value_blend.is_none()
17387        {
17388            return None;
17389        }
17390        self.graph_attn_geom_vres(li, e0)
17391    }
17392
17393    /// `graph_attn_geom` with Ripple's value residual: the layer's blend and
17394    /// `e0`, the embedding rows of the graph call.
17395    fn graph_attn_geom_vres<'a>(&'a self, li: usize, e0: &'a [f32]) -> Option<crate::gpu::GraphAttnGeom<'a>> {
17396        let mut g = self.graph_attn_geom(li)?;
17397        g.vres = self.layer_value_blend(li).map(|b| (b, e0));
17398        Some(g)
17399    }
17400
17401    /// The decode graph's device K/V mirror that layer `li`'s batched
17402    /// prefill appends its chunk to and attends against (wgpu), instead
17403    /// of uploading the layer's whole K/V prefix every chunk and the whole
17404    /// cache again at the first decode token. Only where the token graph
17405    /// will read that very mirror: the decode graph on, not refused, and
17406    /// this layer's geometry what it requests (`graph_attn_geom`: KV heads,
17407    /// V as wide as K, the window as a ring, no sink).
17408    ///
17409    /// Spark-X2.5 only (`proj_gate_sigmoid`), the one architecture whose
17410    /// output was measured identical on it. `CMF_PREFILL_MIRROR=0` keeps
17411    /// the host upload (A/B).
17412    #[cfg(feature = "gpu")]
17413    fn prefill_mirror_target(&self, li: usize) -> Option<crate::gpu::PrefillMirror> {
17414        if !self.proj_gate_sigmoid
17415            || std::env::var("CMF_PREFILL_MIRROR").as_deref() == Ok("0")
17416            || !crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)
17417            || self.graph_refused()
17418            || self.o1_active()
17419            || self.attn_softcap > 0.0
17420            || self.wgpu_graph_attn_decline().is_some()
17421        {
17422            return None;
17423        }
17424        let g = self.graph_attn_geom(li)?;
17425        let (nkv, hd, _) = self.layer_geom(li);
17426        // The token graph passes the call-wide head width (layer 0's).
17427        if g.nkv != nkv || g.dv != hd || g.sink.is_some() || hd != self.layer_geom(0).1 {
17428            return None;
17429        }
17430        Some(crate::gpu::PrefillMirror {
17431            kv_id: self.graph_kv_id,
17432            layer: li,
17433            limit: self.kv_cache.max_seq_len,
17434        })
17435    }
17436
17437    /// Bring the host KV cache of every Full-attention layer in
17438    /// `[from, upto)` up to `position` rows from the wgpu mirrors, where a
17439    /// device graph advanced a layer that the host is about to run: a
17440    /// device prefix that shrank since the prompt (or a batched prefill
17441    /// prefix longer than the decode one). A layer whose mirror does not
17442    /// hold the missing rows is left alone. Rows a sliding layer's ring
17443    /// no longer holds come back as zeros — outside every window that
17444    /// will read them.
17445    #[cfg(feature = "gpu")]
17446    fn pull_lagging_host_kv(&mut self, from: usize, upto: usize, position: usize) {
17447        let kv_id = self.graph_kv_id;
17448        for li in from..upto.min(self.num_layers) {
17449            if !matches!(
17450                self.weights.layers[self.phys_layer(li)].attn,
17451                AttnKind::Full { .. }
17452            ) {
17453                continue;
17454            }
17455            // Absolute: a trimmed sliding tail holds positions base.. only.
17456            let host = self.kv_cache.layers[li].pos_len();
17457            if host >= position {
17458                continue;
17459            }
17460            let Some(dev) = crate::gpu::graph_kv_stored(kv_id, li) else {
17461                continue;
17462            };
17463            let to = dev.min(position);
17464            if to <= host {
17465                continue;
17466            }
17467            let (nkv, hd) = {
17468                let c = &self.kv_cache.layers[li];
17469                (c.num_kv_heads, c.head_dim)
17470            };
17471            let Some((k, v, first_valid)) =
17472                crate::gpu::graph_kv_pull_host(kv_id, li, host, to, nkv, hd)
17473            else {
17474                continue;
17475            };
17476            // A sliding layer only ever reads its last `window` rows; a
17477            // full-context layer needs every row it did not have.
17478            let need_from = match self.layer_window(li) {
17479                Some(w) => host.max((position + 1).saturating_sub(w)),
17480                None => host,
17481            };
17482            if first_valid > need_from {
17483                tracing::warn!(
17484                    "layer {li}: device KV rows {host}..{to} no longer resident \
17485                     (from {first_valid}); host attention will miss them"
17486                );
17487            }
17488            let row = nkv * hd;
17489            let cache = &mut self.kv_cache.layers[li];
17490            for p in 0..to - host {
17491                cache.append(&k[p * row..(p + 1) * row], &v[p * row..(p + 1) * row], &[]);
17492            }
17493        }
17494    }
17495
17496    /// Log (once per graph site and pipeline) that `site` declined for
17497    /// `reason`. The lines are kept so a caller or a test can read them.
17498    fn note_graph_decline(&self, site: &'static str, reason: &'static str) {
17499        let mut seen = self.graph_declines.borrow_mut();
17500        if !seen.iter().any(|&(s, r)| s == site && r == reason) {
17501            tracing::warn!("{site} declined: {reason} (CPU attention path)");
17502            seen.push((site, reason));
17503        }
17504    }
17505
17506    /// The GPU-graph declines this pipeline has logged so far, as the
17507    /// logged lines.
17508    pub fn graph_declines(&self) -> Vec<String> {
17509        self.graph_declines
17510            .borrow()
17511            .iter()
17512            .map(|(site, reason)| format!("{site} declined: {reason} (CPU attention path)"))
17513            .collect()
17514    }
17515
17516    /// Does layer `li` have the plain attention geometry the historical
17517    /// head-masked f32 path (`multi_head_attention`) assumes — pipeline-wide
17518    /// KV heads / head_dim / RoPE table, full context, no sink, V as wide
17519    /// as K? Anything else runs the dense `qwen_attention` instead.
17520    /// `CMF_LAYER_DUMP` writer (see `Pipeline::layer_dump`): one position's
17521    /// hidden after layer `li` as raw little-endian f32 into
17522    /// `<dir>/p{pos:06}_l{li:02}.f32`. A failed write is reported once and
17523    /// never stops the forward — the dump is a diagnostic.
17524    fn dump_layer_row(&self, pos: usize, li: usize, row: &[f32]) {
17525        let Some(dir) = &self.layer_dump else {
17526            return;
17527        };
17528        let mut bytes = Vec::with_capacity(row.len() * 4);
17529        for v in row {
17530            bytes.extend_from_slice(&v.to_le_bytes());
17531        }
17532        let path = dir.join(format!("p{pos:06}_l{li:02}.f32"));
17533        if let Err(e) = std::fs::create_dir_all(dir).and_then(|_| std::fs::write(&path, &bytes)) {
17534            use std::sync::atomic::{AtomicBool, Ordering};
17535            static SAID: AtomicBool = AtomicBool::new(false);
17536            if !SAID.swap(true, Ordering::Relaxed) {
17537                tracing::error!("CMF_LAYER_DUMP: cannot write {}: {e}", path.display());
17538            }
17539        }
17540    }
17541
17542    /// Decide the MiMo-V2 expert placement once (`crate::mimo_moe`). Any
17543    /// other model turns the slot off on the first call.
17544    fn mimo_moe_prepare(&mut self) {
17545        if !self.mimo_moe.is_undecided() {
17546            return;
17547        }
17548        let slot = {
17549            let layers: Vec<(usize, &MoeFfn)> = (0..self.num_layers)
17550                .filter_map(
17551                    |li| match &self.weights.layers.get(self.phys_layer(li))?.ffn {
17552                        FfnKind::Moe(m) => Some((li, m)),
17553                        _ => None,
17554                    },
17555                )
17556                .collect();
17557            // One bank lives on one device: an in-process multi-GPU split
17558            // keeps the whole-layer path.
17559            if layers.is_empty()
17560                || self.physical_layers != self.num_layers
17561                || self.gpu_plan.is_some()
17562            {
17563                crate::mimo_moe::Slot::Off
17564            } else {
17565                // Whether a whole-token graph could run this model's layers
17566                // (then a whole-layer prefix is one submit, not per-layer
17567                // fences).
17568                let graph_prefix =
17569                    self.wgpu_graph_attn_decline().is_none() && crate::gpu::wgpu_graph_default();
17570                crate::mimo_moe::Slot::decide(&layers, self.num_layers, graph_prefix)
17571            }
17572        };
17573        self.mimo_moe = slot;
17574    }
17575
17576    #[cfg(test)]
17577    pub(crate) fn test_graph_kv_id(&self) -> u64 {
17578        self.graph_kv_id
17579    }
17580
17581    /// Dynamic MiMo layer: one device attention graph, followed by a bank
17582    /// frame. Both decode and short verification use this same attention
17583    /// path and absolute layer key; the host KV may intentionally lag.
17584    pub(crate) fn mimo_graph_layer_rows(
17585        &mut self,
17586        li: usize,
17587        h: &mut [f32],
17588        positions: &[usize],
17589    ) -> crate::gpu::BatchGraphOutcome {
17590        use crate::gpu::BatchGraphOutcome as Out;
17591        let b = positions.len();
17592        if !(1..=4).contains(&b)
17593            || h.len() != b * self.hidden_size
17594            || !self.mimo_moe.is_dynamic(li, true)
17595            || !crate::gpu::enabled_here()
17596            || !crate::gpu::wgpu_active()
17597            || self.o1_active()
17598            || self.physical_layers != self.num_layers
17599            // The pair-fusion diagnostic (and an explicit graph-off run)
17600            // rewinds only host KV. A hidden singleton attention graph here
17601            // would leave device mirrors ahead of the next host position.
17602            || std::env::var("CMF_GPU_WGPU_GRAPH").as_deref() == Ok("0")
17603            || std::env::var("CMF_MIMO_ATTN_GRAPH").as_deref() == Ok("0")
17604            || self.wgpu_graph_attn_decline().is_some()
17605        {
17606            return Out::Declined;
17607        }
17608        let attn_started = std::time::Instant::now();
17609        let outcome = {
17610            let lw = &self.weights.layers[li];
17611            if lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some() {
17612                return Out::Declined;
17613            }
17614            let FfnKind::Moe(m) = &lw.ffn else {
17615                return Out::Declined;
17616            };
17617            let AttnKind::Full {
17618                wq,
17619                wk,
17620                wv,
17621                wo,
17622                q_norm,
17623                k_norm,
17624                output_gate,
17625                softplus_gate,
17626                bias,
17627            } = &lw.attn
17628            else {
17629                return Out::Declined;
17630            };
17631            if *output_gate || softplus_gate.is_some() {
17632                return Out::Declined;
17633            }
17634            let Some(model) = wq.graph_weight().map(|(m, ..)| m.clone()).or_else(|| {
17635                m.experts
17636                    .first()?
17637                    .gate_proj
17638                    .mapped_q4tp()
17639                    .map(|(m, _)| m.clone())
17640            }) else {
17641                return Out::Declined;
17642            };
17643            fn gw<'a>(
17644                t: &'a QTensor,
17645                owner: &std::sync::Arc<cortiq_core::CmfModel>,
17646            ) -> Option<crate::gpu::GraphW<'a>> {
17647                if let Some((m, idx, kind, rs)) = t.graph_weight() {
17648                    if m.uid() != owner.uid() || t.has_prism_contract() {
17649                        return None;
17650                    }
17651                    return Some(crate::gpu::GraphW {
17652                        idx,
17653                        kind,
17654                        row_scale: rs,
17655                        data: &[],
17656                        prism: crate::gpu::GraphPrismOp::None,
17657                        affine: false,
17658                    });
17659                }
17660                t.as_f32().map(|data| crate::gpu::GraphW {
17661                    idx: 0,
17662                    kind: 4,
17663                    row_scale: &[],
17664                    data,
17665                    prism: crate::gpu::GraphPrismOp::None,
17666                    affine: false,
17667                })
17668            }
17669            let (Some(q), Some(k), Some(v), Some(o)) = (
17670                gw(wq, &model),
17671                gw(wk, &model),
17672                gw(wv, &model),
17673                gw(wo, &model),
17674            ) else {
17675                return Out::Declined;
17676            };
17677            let layer = crate::gpu::GraphLayer {
17678                engram: None,
17679                mhc: None,
17680                input_norm: &lw.input_norm,
17681                post_norm: &lw.post_norm,
17682                attn_out_norm: None,
17683                ffn_out_norm: None,
17684                layer_scale: None,
17685                ffn: crate::gpu::GraphFfn::AttentionOnly,
17686                attn: crate::gpu::GraphAttn::Full {
17687                    wq: q,
17688                    wk: k,
17689                    wv: v,
17690                    wo: o,
17691                    q_norm: q_norm.as_deref(),
17692                    k_norm: k_norm.as_deref(),
17693                    late_qk_norm: self.qk_norm_after_rope,
17694                    bias: bias
17695                        .as_ref()
17696                        .map(|(q, k, v)| (q.as_slice(), k.as_slice(), v.as_slice())),
17697                    output_gate: false,
17698                    cpu_k: self.kv_cache.layers[li].k_heads(),
17699                    cpu_v: self.kv_cache.layers[li].v_heads(),
17700                    cpu_base: self.kv_cache.layers[li].base(),
17701                    geom: self.graph_attn_geom(li),
17702                    head_gate: None,
17703                },
17704            };
17705            let (nkv, hd, rd) = self.layer_geom(li);
17706            crate::gpu::forward_batch_graph_at(
17707                &model,
17708                self.graph_kv_id,
17709                li,
17710                &[layer],
17711                &self.inv_freq,
17712                h,
17713                self.layer_num_heads(li),
17714                nkv,
17715                hd,
17716                rd,
17717                self.hidden_size,
17718                1,
17719                positions,
17720                self.kv_cache.max_seq_len,
17721                self.norm_style == cortiq_core::NormStyle::Gemma,
17722                self.rms_eps as f32,
17723                self.attn_scale,
17724                b,
17725                &[],
17726                self.o1_epoch,
17727                None,
17728                None,
17729            )
17730        };
17731        match outcome {
17732            Out::Completed => {}
17733            Out::Declined => return Out::Declined,
17734            Out::Failed => {
17735                self.graph_failed
17736                    .store(true, std::sync::atomic::Ordering::Relaxed);
17737                return Out::Failed;
17738            }
17739        }
17740        let attn_ns = attn_started.elapsed().as_nanos() as u64;
17741        let hs = self.hidden_size;
17742        let lw = &self.weights.layers[li];
17743        let FfnKind::Moe(m) = &lw.ffn else {
17744            unreachable!()
17745        };
17746        let mut post = vec![0.0; h.len()];
17747        for (x, y) in h.chunks_exact(hs).zip(post.chunks_exact_mut(hs)) {
17748            inference::rms_norm_into(x, &lw.post_norm, self.rms_eps, self.norm_style, y);
17749        }
17750        let mut ffn = if b == 1 {
17751            moe_ffn_banked(&mut self.mimo_moe, li, m, &post, self.pool.as_deref())
17752        } else {
17753            moe_ffn_banked_rows(
17754                &mut self.mimo_moe,
17755                li,
17756                m,
17757                &post,
17758                b,
17759                hs,
17760                self.pool.as_deref(),
17761            )
17762        };
17763        for (x, &f) in h.iter_mut().zip(&ffn) {
17764            *x += f;
17765        }
17766        attention::recycle_buf(&mut ffn);
17767        if self.layer_dump.is_some() {
17768            for (&pos, row) in positions.iter().zip(h.chunks_exact(hs)) {
17769                self.dump_layer_row(pos, li, row);
17770            }
17771        }
17772        crate::mimo_moe::note_attention_graph(b, attn_ns);
17773        Out::Completed
17774    }
17775
17776    fn layer_attn_plain(&self, li: usize) -> bool {
17777        self.kv_heads_per_layer.is_none()
17778            && self.v_head_dim.is_none()
17779            && self.global_attn.is_none()
17780            && self.layer_window(li).is_none()
17781            && self.kv_cache.layers[li].sinks.is_none()
17782    }
17783
17784    /// Forward one position through all layers (hybrid dispatch).
17785    fn forward_layers(
17786        &mut self,
17787        hidden: &[f32],
17788        position: usize,
17789        task_mask: Option<&TaskMask>,
17790    ) -> Vec<f32> {
17791        let out = self.forward_layers_upto(hidden, position, task_mask, None);
17792        self.o1_progress();
17793        self.swa_trim_tails();
17794        out
17795    }
17796
17797    // ── Network pipeline-split building blocks (coordinator/worker) ──
17798    // A remote worker owns layers [from ..= upto] and their KV; the
17799    // coordinator owns the rest plus embed / final norm / head. Attention
17800    // causality is per-layer, so a whole prompt's boundary hiddens ship
17801    // as one batch and decode ships one vector per token.
17802
17803    /// Embed one token id (embed multiplier applied).
17804    pub fn embed_id(&self, id: u32) -> Vec<f32> {
17805        self.embed_single(id)
17806    }
17807
17808    /// Refuse the archs/modes whose forward cannot be cut at a layer
17809    /// boundary. Loud by design: a split that silently changed the math
17810    /// would be a chimera.
17811    pub fn split_supported(&self) -> Result<(), String> {
17812        if self.dsv4.is_some() {
17813            return Err(
17814                "network split: DeepSeek-V4 runs its own fused stack (not splittable yet)".into(),
17815            );
17816        }
17817        if self.dory.is_some() {
17818            return Err("network split: Dory's looped stack is not splittable".into());
17819        }
17820        if self.dsv41.is_some() {
17821            return Err(
17822                "network split: DeepSeek-V4.1 owns the shared CED/CSA2 state (not splittable)"
17823                    .into(),
17824            );
17825        }
17826        if self.qwen4_exp.is_some() {
17827            return Err(
17828                "network split: Qwen3.8-Flash-Next hyper/QSA stack is not splittable yet".into(),
17829            );
17830        }
17831        if self.glm5_next.is_some() {
17832            return Err("network split: GLM-5.3-Flash mHC/KDA/DSA stack is not splittable yet".into());
17833        }
17834        if self.hy4.is_some() {
17835            return Err("network split: the Hy4-flash iHC/Engram stack is not splittable yet".into());
17836        }
17837        if self.maxwell.is_some() {
17838            return Err("network split: the Maxwell mHC stack is not splittable yet".into());
17839        }
17840        if self.inkling.is_some() {
17841            return Err("network split: the Inkling looped stack is not splittable yet".into());
17842        }
17843        if self.per_token_stack() {
17844            return Err(
17845                "network split: the per-token stack (gemma-3n AltUp / gemma-4 E-series) is not splittable yet".into(),
17846            );
17847        }
17848        if self.value_blend.is_some() {
17849            return Err(
17850                "network split: a value-residual stack (Ripple) reads the embedding row in every layer".into(),
17851            );
17852        }
17853        Ok(())
17854    }
17855
17856    /// Forward `hidden` through layers [from ..= upto] at `position`,
17857    /// appending those layers' KV/state. Both split sides call this
17858    /// over their own range; a task mask applies to the span's own
17859    /// layers (each side masks what it runs).
17860    pub fn forward_span(
17861        &mut self,
17862        hidden: &[f32],
17863        position: usize,
17864        from: usize,
17865        upto: usize,
17866        task_mask: Option<&TaskMask>,
17867    ) -> Result<Vec<f32>, String> {
17868        self.split_supported()?;
17869        if from > upto || upto >= self.num_layers {
17870            return Err(format!(
17871                "forward_span: layer range {from}..={upto} outside 0..{}",
17872                self.num_layers
17873            ));
17874        }
17875        if hidden.len() != self.hidden_size {
17876            return Err(format!(
17877                "forward_span: hidden len {} ≠ hidden_size {}",
17878                hidden.len(),
17879                self.hidden_size
17880            ));
17881        }
17882        let out = self.forward_layers_span(hidden, position, task_mask, from, Some(upto));
17883        self.o1_progress();
17884        self.swa_trim_tails();
17885        if self
17886            .graph_failed
17887            .swap(false, std::sync::atomic::Ordering::Relaxed)
17888        {
17889            self.cancel
17890                .store(false, std::sync::atomic::Ordering::Relaxed);
17891            self.clear_sequence_state();
17892            return Err("forward_span: deferred O(1) transition failed".into());
17893        }
17894        Ok(out)
17895    }
17896
17897    /// Final norm + lm_head over a boundary hidden (the final-logit
17898    /// softcap is applied by lm_head_forward itself).
17899    pub fn logits_from_hidden(&mut self, hidden: &[f32]) -> Vec<f32> {
17900        let normed = inference::rms_norm(
17901            hidden,
17902            &self.weights.final_norm,
17903            self.rms_eps,
17904            self.norm_style,
17905        );
17906        self.lm_head_forward(&normed)
17907    }
17908
17909    /// Sample the next token with this pipeline's sampler state.
17910    pub fn sample_next(&mut self, logits: &[f32], past_tokens: &[u32]) -> u32 {
17911        sampler::sample_with_scratch(
17912            logits,
17913            &self.sampler_config,
17914            past_tokens,
17915            &mut self.rng,
17916            &mut self.sampler_scratch,
17917        )
17918    }
17919
17920    /// Fresh sequence: clear KV, reuse history and device mirrors.
17921    pub fn reset_session(&mut self) {
17922        self.clear_sequence_state();
17923    }
17924
17925    /// Batched span prefill from token ids (coordinator side): embed +
17926    /// layers [0 ..= upto]; returns the boundary hiddens of ALL positions
17927    /// (ids.len() × hidden). Rides the same layer-major machinery as the
17928    /// local prefill; falls back to the per-position walk under
17929    /// CMF_PREFILL=seq.
17930    pub fn prefill_span_ids(
17931        &mut self,
17932        ids: &[u32],
17933        start_pos: usize,
17934        upto: usize,
17935        task_mask: Option<&TaskMask>,
17936    ) -> Result<Vec<f32>, String> {
17937        self.split_supported()?;
17938        if upto >= self.num_layers {
17939            return Err(format!(
17940                "prefill_span_ids: upto {upto} outside 0..{}",
17941                self.num_layers
17942            ));
17943        }
17944        // Same predicate as the whole-stack prefill: a span whose GDN
17945        // state lives on the device must walk positions through the
17946        // graph, not through the batched CPU span.
17947        if self.can_prefill_batched() && !self.graph_prefill_preferred() {
17948            let out =
17949                self.prefill_batch_span(PrefillIn::Ids(ids), start_pos, task_mask, 0, upto + 1);
17950            self.check_o1_progress_failure("prefill_span_ids")?;
17951            Ok(out)
17952        } else {
17953            let hs = self.hidden_size;
17954            let mut out = Vec::with_capacity(ids.len() * hs);
17955            for (i, &id) in ids.iter().enumerate() {
17956                let emb = self.embed_id(id);
17957                out.extend_from_slice(&self.forward_span(
17958                    &emb,
17959                    start_pos + i,
17960                    0,
17961                    upto,
17962                    task_mask,
17963                )?);
17964            }
17965            Ok(out)
17966        }
17967    }
17968
17969    /// Batched span prefill from boundary hiddens (worker side): layers
17970    /// [from ..= upto] for every position in the batch; returns the batch.
17971    pub fn prefill_span_hidden(
17972        &mut self,
17973        hidden: &[f32],
17974        start_pos: usize,
17975        from: usize,
17976        upto: usize,
17977        task_mask: Option<&TaskMask>,
17978    ) -> Result<Vec<f32>, String> {
17979        self.split_supported()?;
17980        let hs = self.hidden_size;
17981        if hidden.is_empty() || hidden.len() % hs != 0 {
17982            return Err(format!(
17983                "prefill_span_hidden: {} floats is not a multiple of hidden {hs}",
17984                hidden.len()
17985            ));
17986        }
17987        if from > upto || upto >= self.num_layers {
17988            return Err(format!(
17989                "prefill_span_hidden: layer range {from}..={upto} outside 0..{}",
17990                self.num_layers
17991            ));
17992        }
17993        if self.can_prefill_batched() && !self.graph_prefill_preferred() {
17994            let out = self.prefill_batch_span(
17995                PrefillIn::Hidden(hidden),
17996                start_pos,
17997                task_mask,
17998                from,
17999                upto + 1,
18000            );
18001            self.check_o1_progress_failure("prefill_span_hidden")?;
18002            Ok(out)
18003        } else {
18004            let b = hidden.len() / hs;
18005            let mut out = Vec::with_capacity(hidden.len());
18006            for i in 0..b {
18007                let h = self.forward_span(
18008                    &hidden[i * hs..(i + 1) * hs],
18009                    start_pos + i,
18010                    from,
18011                    upto,
18012                    task_mask,
18013                )?;
18014                out.extend_from_slice(&h);
18015            }
18016            Ok(out)
18017        }
18018    }
18019
18020    /// Build the whole-token wgpu graph for a pure-attention q1 model (every
18021    /// layer Full q1 + dense q1 FFN, no gate/bias). Returns the post-stack
18022    /// hidden (caller does final norm + lm_head), or None to fall back.
18023    fn try_token_graph_wgpu(
18024        &self,
18025        hidden: &[f32],
18026        position: usize,
18027        logits_out: &mut Vec<f32>,
18028        layers_run: &mut usize,
18029    ) -> Option<Result<Vec<f32>, ()>> {
18030        self.try_token_graph_wgpu_steps(
18031            hidden,
18032            position,
18033            logits_out,
18034            1,
18035            None,
18036            Some(layers_run),
18037            0,
18038            self.num_layers,
18039        )
18040    }
18041
18042    /// The span twin (network split): the graph covers [from..upto_excl)
18043    /// — one submit per SEGMENT per token. lm_head folds in only when
18044    /// the span reaches the last layer.
18045    fn try_token_graph_wgpu_span(
18046        &self,
18047        hidden: &[f32],
18048        position: usize,
18049        logits_out: &mut Vec<f32>,
18050        from: usize,
18051        upto_excl: usize,
18052        layers_run: &mut usize,
18053    ) -> Option<Result<Vec<f32>, ()>> {
18054        self.try_token_graph_wgpu_steps(
18055            hidden,
18056            position,
18057            logits_out,
18058            1,
18059            None,
18060            Some(layers_run),
18061            from,
18062            upto_excl,
18063        )
18064    }
18065
18066    /// A device token graph (wgpu or CUDA) decodes this pipeline: the head
18067    /// of a row the graph did not run — the first token after a prompt —
18068    /// takes the graph's head pass as well (`CMF_HEAD_GRAPH=0`: the host
18069    /// head, as before).
18070    ///
18071    /// The host head of a q8 file on a GPU run is a hybrid: half of the
18072    /// vocabulary's rows on the card in f32, the other half on the CPU with
18073    /// integer activations (`gpu_split_frac`). Every later token's logits
18074    /// come from the graph's fused head, so that one row alone carried the
18075    /// integer half. Spark-X2.6-4B q8_2f on an A40 over Vulkan, against the
18076    /// host with float activations: first-token logits 0.29 off (and a
18077    /// near-tie token flipped on one prompt in four), every other token
18078    /// 0.015; through the graph's head the first token is 0.014 off too.
18079    /// On wgpu only those two codecs take it (`m3_device_logits`): a q4tp
18080    /// head measured the same either way.
18081    #[cfg(feature = "gpu")]
18082    fn graph_head_after_prompt(&self) -> bool {
18083        (crate::gpu::wgpu_active() || crate::gpu::cuda_active())
18084            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)
18085            && !self.graph_refused()
18086            && std::env::var("CMF_HEAD_GRAPH").as_deref() != Ok("0")
18087    }
18088
18089    /// The pooled tail's device lm_head: final-norm + head as one
18090    /// layer-less graph pass, so decode stops paying the double-digit
18091    /// millisecond host matvec every token. `None` keeps the host head.
18092    /// Also the head of the first token after a prompt wherever a device
18093    /// graph decodes (`graph_head_after_prompt`).
18094    #[cfg(feature = "gpu")]
18095    fn m3_device_logits(&self, hidden: &[f32]) -> Option<Vec<f32>> {
18096        let pooled = crate::minicpm_tail::minimax_pool_on();
18097        if !(pooled || self.graph_head_after_prompt())
18098            || !crate::gpu::enabled_here()
18099            || self.head_clusters.is_some()
18100            || self.graph_failed.load(std::sync::atomic::Ordering::Relaxed)
18101            || std::env::var("CMF_GPU_LMHEAD").map(|v| v != "0") == Ok(false)
18102        {
18103            return None;
18104        }
18105        let (model, i, kind, rs) = self
18106            .weights
18107            .lm_head
18108            .graph_weight()
18109            .or_else(|| self.weights.lm_head.graph_weight_descriptor())?;
18110        // After a prompt on wgpu: the codecs whose host head is the hybrid
18111        // (q8 by rows, q8_2f). CUDA has no host GPU head at all.
18112        if !pooled && !crate::gpu::cuda_active() && !matches!(kind, 0 | 7) {
18113            return None;
18114        }
18115        let name = &model.tensors[i].name;
18116        let prism = if crate::prism::is_inverse_embedding(&model, name) {
18117            crate::gpu::GraphPrismOp::InverseEmbedding
18118        } else if crate::prism::is_forward_weight(&model, name) {
18119            crate::gpu::GraphPrismOp::Forward
18120        } else {
18121            crate::gpu::GraphPrismOp::None
18122        };
18123        let gw = crate::gpu::GraphW {
18124            idx: i,
18125            kind,
18126            row_scale: rs,
18127            data: &[],
18128            prism,
18129            affine: crate::prism::is_affine_target(&model, name),
18130        };
18131        let rows = self.weights.lm_head.rows();
18132        let mut h = hidden.to_vec();
18133        let mut lg = Vec::new();
18134        let mut layers_run = 0usize;
18135        let outcome = crate::gpu::forward_token_graph(
18136            &model,
18137            self.graph_kv_id,
18138            &[],
18139            &[],
18140            self.o1_epoch,
18141            &self.inv_freq,
18142            &mut h,
18143            self.num_heads,
18144            self.num_kv_heads,
18145            self.head_dim,
18146            self.attn_scale,
18147            self.head_dim,
18148            self.hidden_size,
18149            self.intermediate_size,
18150            0,
18151            self.kv_cache.max_seq_len,
18152            self.norm_style == cortiq_core::NormStyle::Gemma,
18153            self.rms_eps as f32,
18154            Some((&gw, rows)),
18155            &self.weights.final_norm,
18156            &mut lg,
18157            &[],
18158            1,
18159            None,
18160            None,
18161            Some(&mut layers_run),
18162            0,
18163            false,
18164        );
18165        if outcome != crate::gpu::TokenGraphOutcome::Completed || lg.is_empty() {
18166            return None;
18167        }
18168        // The same post-steps the host head applies — keep sampling
18169        // identical whichever arm produced the logits.
18170        lg.resize(self.vocab_size, 0.0);
18171        if let Some(m) = self.logit_multiplier {
18172            for l in lg.iter_mut() {
18173                *l *= m;
18174            }
18175        }
18176        if let Some(c) = self.final_softcap {
18177            softcap_in_place(&mut lg, c, self.pool.as_deref());
18178        }
18179        Some(lg)
18180    }
18181
18182    /// Record one token-layer's winners into the route-frequency profile and
18183    /// write it out every 16 tokens when `CMF_M3_PROFILE_SAVE=<path>` is set.
18184    fn m3_note_route(&mut self, li: usize, winners: &[u32]) {
18185        if winners.is_empty() {
18186            return;
18187        }
18188        if self.m3_n_exp == 0 {
18189            self.m3_n_exp = crate::minicpm_tail::minimax_n_experts(&self.weights.layers, self.phys_layer(0)).max(1);
18190            self.m3_counts = vec![0; self.num_layers * self.m3_n_exp];
18191        }
18192        for &e in winners {
18193            let e = e as usize;
18194            if e < self.m3_n_exp && li < self.num_layers {
18195                self.m3_counts[li * self.m3_n_exp + e] = self.m3_counts[li * self.m3_n_exp + e].saturating_add(1);
18196            }
18197        }
18198        if li + 1 == self.num_layers {
18199            self.m3_tokens += 1;
18200            if self.m3_tokens % 16 == 0 {
18201                if let Ok(path) = std::env::var("CMF_M3_PROFILE_SAVE") {
18202                    let bytes: Vec<u8> = self.m3_counts.iter().flat_map(|c| c.to_le_bytes()).collect();
18203                    let _ = std::fs::write(&path, bytes);
18204                }
18205            }
18206        }
18207    }
18208
18209    /// Admit the most frequent (layer, expert) pairs of a saved profile into
18210    /// the bank before the first token: `CMF_M3_PROFILE=<path>` names the
18211    /// file, `CMF_M3_PREWARM_N` (default 300) bounds how many experts go in.
18212    /// The bank's own eviction stays in charge; prewarm only chooses order.
18213    fn m3_prewarm(&mut self) {
18214        let Ok(path) = std::env::var("CMF_M3_PROFILE") else {
18215            return;
18216        };
18217        let Ok(bytes) = std::fs::read(&path) else {
18218            tracing::warn!("m3 prewarm: cannot read profile {path}");
18219            return;
18220        };
18221        let counts: Vec<u32> = bytes
18222            .chunks_exact(4)
18223            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
18224            .collect();
18225        let n_exp = crate::minicpm_tail::minimax_n_experts(&self.weights.layers, self.phys_layer(0)).max(1);
18226        if counts.len() != self.num_layers * n_exp {
18227            tracing::warn!("m3 prewarm: profile size {} does not match {}x{}", counts.len(), self.num_layers, n_exp);
18228            return;
18229        }
18230        let limit: usize = std::env::var("CMF_M3_PREWARM_N")
18231            .ok()
18232            .and_then(|v| v.parse().ok())
18233            .unwrap_or(300);
18234        let mut ranked: Vec<(u32, usize, usize)> = counts
18235            .iter()
18236            .enumerate()
18237            .filter(|(_, c)| **c > 0)
18238            .map(|(i, &c)| (c, i / n_exp, i % n_exp))
18239            .collect();
18240        ranked.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)).then(a.2.cmp(&b.2)));
18241        ranked.truncate(limit);
18242        let mut per_layer: Vec<Vec<usize>> = vec![Vec::new(); self.num_layers];
18243        for (_, li, e) in ranked {
18244            per_layer[li].push(e);
18245        }
18246        let mut admitted = 0usize;
18247        for (li, ids) in per_layer.iter().enumerate() {
18248            if ids.is_empty() {
18249                continue;
18250            }
18251            let lw = &self.weights.layers[self.phys_layer(li)];
18252            let FfnKind::Moe(m) = &lw.ffn else {
18253                continue;
18254            };
18255            // Arming installs the layer's layout; nothing predicted yet.
18256            let _ = crate::minicpm_tail::minimax_pool_arm(m, li, self.num_layers, &[]);
18257            if crate::minicpm_tail::minimax_pool_ensure(m, li, self.num_layers, ids) {
18258                admitted += ids.len();
18259            }
18260        }
18261        tracing::info!("m3 prewarm: admitted {admitted} experts from {path}");
18262    }
18263
18264    /// One MiniMax tail layer through the pooled token-graph arm: attention,
18265    /// the pre-FFN norm, device routing and the descriptor-indexed expert
18266    /// bank in ONE submit (one sync instead of host attention + a MoE
18267    /// frame), with cold experts finished on the host against the read-back
18268    /// FFN input and admitted for the next token.
18269    ///
18270    /// `Ok(true)` — the layer is done (hidden replaced). `Ok(false)` —
18271    /// decline before any device mutation; the ordinary host path owns this
18272    /// position. `Err(())` — the device failed after admission; the caller
18273    /// must stop the sequence exactly like a failed span run.
18274    #[cfg(feature = "gpu")]
18275    fn m3_pooled_layer(&mut self, li: usize, position: usize, h: &mut Vec<f32>) -> Result<bool, ()> {
18276        if self.o1_active() || self.attn_softcap > 0.0 {
18277            return Ok(false);
18278        }
18279        if !self.m3_prewarmed {
18280            self.m3_prewarmed = true;
18281            self.m3_prewarm();
18282        }
18283        let frame = {
18284            let lw = &self.weights.layers[self.phys_layer(li)];
18285            let FfnKind::Moe(m) = &lw.ffn else {
18286                return Ok(false);
18287            };
18288            if !crate::minicpm_tail::MiniCpmTail::is_requested_target(m) {
18289                return Ok(false);
18290            }
18291            let t_arm = std::time::Instant::now();
18292            if self.m3_winners.len() != self.num_layers {
18293                self.m3_winners = vec![Vec::new(); self.num_layers];
18294            }
18295            let pred = std::mem::take(&mut self.m3_winners[li]);
18296            let armed = crate::minicpm_tail::minimax_pool_arm(m, li, self.num_layers, &pred);
18297            if armed.is_none() {
18298                self.m3_winners[li] = pred; // declined before anything ran
18299            }
18300            M3_ARM_NS.fetch_add(t_arm.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
18301            match armed {
18302                Some(frame) => frame,
18303                // First-call refusal (geometry/bank): the host layer still
18304                // runs; nothing was mutated.
18305                None => return Ok(false),
18306            }
18307        };
18308        crate::gpu_wgpu::pooled_frame_enter(frame);
18309        // The pooled call must not fold lm_head: its cold experts have to
18310        // land before any final norm. The decode loop re-arms this flag for
18311        // the next position anyway.
18312        let want_logits = self.graph_want_logits;
18313        self.graph_want_logits = false;
18314        let mut lg = Vec::new();
18315        let mut gl = 0usize;
18316        let t_span = std::time::Instant::now();
18317        let span = crate::gpu::gpu_scope(|| {
18318            self.try_token_graph_wgpu_span(h, position, &mut lg, li, li + 1, &mut gl)
18319        });
18320        self.graph_want_logits = want_logits;
18321        M3_SPAN_NS.fetch_add(t_span.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
18322        let hh = match span {
18323            Some(Ok(hh)) => hh,
18324            Some(Err(())) => return Err(()),
18325            None => {
18326                // Declined before submission (seed/resolve/refusal): the
18327                // device mirror has not moved, so the host path is exact.
18328                return Ok(false);
18329            }
18330        };
18331        if gl != 1 {
18332            // A single-layer run that reports no layer mutated nothing we
18333            // may build on; anything else is a contract break.
18334            return if gl == 0 { Ok(false) } else { Err(()) };
18335        }
18336        *h = hh;
18337        let winners = crate::gpu_wgpu::pooled_frame_take_winners();
18338        self.m3_note_route(li, &winners);
18339        if self.m3_winners.len() != self.num_layers {
18340            self.m3_winners = vec![Vec::new(); self.num_layers];
18341        }
18342        self.m3_winners[li] = winners;
18343        let mut cold = crate::gpu_wgpu::pooled_frame_take_cold();
18344        // A non-finite parsed weight would poison the residual for the rest
18345        // of the sequence — drop such entries loudly instead.
18346        cold.retain(|&(_, w)| {
18347            if w.is_finite() {
18348                true
18349            } else {
18350                tracing::error!("pooled tail: non-finite cold weight from expert route");
18351                false
18352            }
18353        });
18354        if cold.is_empty() {
18355            return Ok(true);
18356        }
18357        let x = crate::gpu_wgpu::pooled_frame_take_input();
18358        if x.len() != self.hidden_size {
18359            return Err(());
18360        }
18361        // Cold experts: on the device first (admit, then one prepared frame
18362        // over exactly those slots — one submit for the layer). The host
18363        // computes them only when the device declines, and then they are
18364        // admitted for the next token. `CMF_M3_COLD_CPU=1` forces the host
18365        // arm for an A/B measurement.
18366        let lw = &self.weights.layers[self.phys_layer(li)];
18367        let FfnKind::Moe(m) = &lw.ffn else {
18368            return Err(());
18369        };
18370        let t_cold = std::time::Instant::now();
18371        let force_host = std::env::var("CMF_M3_COLD_CPU").as_deref() == Ok("1");
18372        let mut out = crate::attention::take_buf(self.hidden_size);
18373        let on_device = !force_host
18374            && crate::minicpm_tail::minimax_cold_device(m, li, self.num_layers, &cold, &x, &mut out);
18375        if !on_device {
18376            crate::attention::recycle_buf(&mut out);
18377            let jobs: Vec<(&crate::pipeline::DenseFfn, f32)> = cold
18378                .iter()
18379                .map(|&(e, w)| m.experts.get(e).map(|ex| (ex, w)).ok_or(()))
18380                .collect::<Result<_, ()>>()?;
18381            out = crate::gpu::cpu_scope(|| {
18382                crate::pipeline::moe_cold_experts_cpu(&jobs, &x, self.pool.as_deref())
18383            });
18384            let ids: Vec<usize> = cold.iter().map(|&(e, _)| e).collect();
18385            let _ = crate::minicpm_tail::minimax_pool_ensure(m, li, self.num_layers, &ids);
18386        }
18387        M3_COLD_NS.fetch_add(t_cold.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
18388        M3_COLD_N.fetch_add(cold.len() as u64, std::sync::atomic::Ordering::Relaxed);
18389        if out.len() != h.len() {
18390            crate::attention::recycle_buf(&mut out);
18391            return Err(());
18392        }
18393        for (dst, src) in h.iter_mut().zip(out.iter()) {
18394            *dst += src;
18395        }
18396        crate::attention::recycle_buf(&mut out);
18397        if on_device {
18398            M3_COLD_DEV_N.fetch_add(cold.len() as u64, std::sync::atomic::Ordering::Relaxed);
18399        }
18400        Ok(true)
18401    }
18402
18403    #[cfg(not(feature = "gpu"))]
18404    fn m3_pooled_layer(
18405        &mut self,
18406        _li: usize,
18407        _position: usize,
18408        _h: &mut Vec<f32>,
18409    ) -> Result<bool, ()> {
18410        Ok(false)
18411    }
18412
18413    /// Greedy burst: forward `t_next` and let the device pick + re-embed
18414    /// the next k−1 tokens — k frames, ONE submit, k ids back. The ZML
18415    /// trade, on wgpu. None ⇒ caller keeps the per-token path.
18416    fn try_multi_burst(&self, t_next: u32, position: usize, k: usize) -> Option<Vec<u32>> {
18417        if self.o1_active() || self.attn_softcap > 0.0 {
18418            return None;
18419        }
18420        // The burst builds the whole-token graph; attention the graph's
18421        // per-layer geometry cannot express keeps the per-token path.
18422        if let Some(reason) = self.wgpu_graph_attn_decline() {
18423            self.note_graph_decline("wgpu multi-burst", reason);
18424            return None;
18425        }
18426        let graph_on = crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode);
18427        if !graph_on || self.graph_refused() {
18428            // Same memo as the decode site: this path builds the very
18429            // same graph, so a model it cannot build for must not be
18430            // walked again here either. Missing this guard was worth
18431            // 2.5x on an Adreno — 0.361 tok/s against 0.905 — because
18432            // the burst retried per token what decode had already given
18433            // up on.
18434            return None;
18435        }
18436        let emb = self.embed_single(t_next);
18437        let mut lg = Vec::new();
18438        let mut ids = Vec::new();
18439        match self.try_token_graph_wgpu_steps(
18440            &emb,
18441            position,
18442            &mut lg,
18443            k,
18444            Some(&mut ids),
18445            None,
18446            0,
18447            self.num_layers,
18448        ) {
18449            Some(Ok(_)) => {}
18450            Some(Err(())) => {
18451                // Preserve the backend's post-admission failure through the
18452                // Option-based burst API.  The decode caller consumes this
18453                // flag and clears the sequence instead of falling through
18454                // to a stale CPU recurrent state.
18455                self.graph_failed
18456                    .store(true, std::sync::atomic::Ordering::Relaxed);
18457                return None;
18458            }
18459            None => return None,
18460        }
18461        (ids.len() == k).then_some(ids)
18462    }
18463
18464    /// The sequence may keep f16 K/V mirrors on the wgpu graphs (`kv16`):
18465    /// nothing it runs reads f32 mirror rows — no MTP head, no drafter, no
18466    /// O(1) seal, no block preview.
18467    fn kv16_allowed(&self) -> bool {
18468        self.mtp.is_none()
18469            && self.dflash.is_none()
18470            && !self.o1_active()
18471            && !self.is_block_diffusion()
18472            && self.clover.is_none()
18473    }
18474
18475    /// Multi-step greedy: k whole frames in ONE submit, argmax and re-embed
18476    /// on the device. `ids_out` receives the k winner ids; the hidden/logits
18477    /// outputs are NOT produced in that mode.
18478    fn try_token_graph_wgpu_steps(
18479        &self,
18480        hidden: &[f32],
18481        position: usize,
18482        logits_out: &mut Vec<f32>,
18483        steps: usize,
18484        ids_out: Option<&mut Vec<u32>>,
18485        layers_run: Option<&mut usize>,
18486        from: usize,
18487        upto_excl: usize,
18488    ) -> Option<Result<Vec<f32>, ()>> {
18489        crate::gpu::graph_kv16_note(self.graph_kv_id, self.kv16_allowed());
18490        // SenseNova-Loop: MRoPE prompt rows rotate on the host; the graph's
18491        // mHC kernels take two streams only, and a graph must not enter an
18492        // mHC range midway (its streams would be the host's).
18493        if self.prompt_mrope.is_some()
18494            || self.mhc.as_deref().is_some_and(|m| {
18495                from < self.num_layers && m.on(self.phys_layer(from)) && !m.enters(self.phys_layer(from))
18496            })
18497            || self.mhc.as_ref().is_some_and(|m| m.s.streams != 2 || m.s.fixed_identity)
18498            || std::env::var("CMF_MHC_GRAPH").as_deref() == Ok("0")
18499                && (from..upto_excl.min(self.num_layers)).any(|li| self.mhc_layer(li))
18500        {
18501            return None;
18502        }
18503        // The bank has already reserved its VRAM. Never build a second
18504        // all-expert arena across bank-owned layers (including bursts).
18505        let upto_excl = match self.mimo_moe.graph_prefix_end() {
18506            Some(end) if end < upto_excl => {
18507                if steps != 1 || layers_run.is_none() || from >= end {
18508                    return None;
18509                }
18510                end
18511            }
18512            _ => upto_excl,
18513        };
18514        // O(1) Nyström decode runs off the sealed state, not the KV cache the
18515        // graph mirrors — never take the graph while o1 is active.
18516        let o1_gpu = self.o1_on_graph();
18517        if (self.o1_active() && !o1_gpu) || self.attn_softcap > 0.0 {
18518            // Softcapped scores have no graph kernel yet — CPU owns them.
18519            // o1 rides the graph only behind CMF_O1_GPU=1 while the port
18520            // proves itself; without it the CPU path owns o1 as before.
18521            return None;
18522        }
18523        // Per-layer KV heads, narrow V, sinks and sliding windows ride
18524        // `GraphAttn::Full::geom` (the ATTEND_X kernels). Anything that
18525        // geometry cannot express declines here, by name — before the
18526        // per-layer gate existed a sliding/sink model ran the graph as
18527        // full-context attention, fluent and wrong. The caller memoizes
18528        // the refusal.
18529        if let Some(reason) = self.wgpu_graph_attn_decline() {
18530            self.note_graph_decline("wgpu token graph", reason);
18531            return None;
18532        }
18533        // Per-layer sealed o1 state for the graph. During prefill the
18534        // state is still Collecting -> views are None -> the graph
18535        // refuses below and the CPU prefill records the q trace and
18536        // seals, exactly as the o1 design requires.
18537        let o1_views: Vec<Option<Vec<crate::nystrom::O1DeviceView<'_>>>> = (from..upto_excl)
18538            .map(|li| {
18539                if !o1_gpu {
18540                    return None;
18541                }
18542                self.kv_cache.layers[self.phys_layer(li)].o1_views()
18543            })
18544            .collect();
18545        if self.o1_active() && o1_gpu {
18546            // Any o1 layer not sealed (or degenerate exact-only) keeps the
18547            // whole token on the CPU: half-graph forwards would desync.
18548            let want: usize = (from..upto_excl)
18549                .filter(|li| self.kv_cache.layers[self.phys_layer(*li)].o1.is_some())
18550                .count();
18551            let have = o1_views.iter().filter(|v| v.is_some()).count();
18552            if want == 0 || have != want {
18553                // The silent twin of the gpu-side o1 gates, found the
18554                // same way: a 15x decode drop with an empty log. Views
18555                // stay None until the layer's state SEALS, so `have`
18556                // lagging `want` early in a run is the o1 design working
18557                // — but it must say so, or the next reader spends a
18558                // night proving the kernels innocent.
18559                // On CHANGE, not once: the first decline is the legal
18560                // unsealed prefill, and a once-print buries the state
18561                // that matters — what the count reads AFTER the seal.
18562                use std::sync::atomic::{AtomicUsize, Ordering};
18563                static LAST: AtomicUsize = AtomicUsize::new(usize::MAX);
18564                let code = have * 1000 + want;
18565                if LAST.swap(code, Ordering::Relaxed) != code {
18566                    tracing::warn!(
18567                        "o1 graph: {have} of {want} layers sealed — per-op until all seal"
18568                    );
18569                }
18570                return None;
18571            }
18572        }
18573        let nh = self.num_heads;
18574        let (nkv, hd, rd) = self.layer_geom(0);
18575        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
18576        // Ripple's value residual: the embedding row of this position. A
18577        // span past the first layer reads the one `forward_layers_span` kept.
18578        let vres_e0: &[f32] = if from == 0 { hidden } else { &self.vres_e0 };
18579        let mut layers = Vec::with_capacity(upto_excl - from);
18580        let mut model = None;
18581        let dbg = std::env::var("CMF_GRAPH_DEBUG").is_ok();
18582        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
18583            // `blr` rides as GRAPH_KIND_BLR (two stage dispatches).
18584            if let Some((m, i, kind, rs)) = t.graph_weight_or_blr() {
18585                let name = &m.tensors[i].name;
18586                let prism = if crate::prism::is_inverse_embedding(m, name) {
18587                    crate::gpu::GraphPrismOp::InverseEmbedding
18588                } else if crate::prism::is_forward_weight(m, name) {
18589                    crate::gpu::GraphPrismOp::Forward
18590                } else {
18591                    crate::gpu::GraphPrismOp::None
18592                };
18593                return Some(crate::gpu::GraphW {
18594                    idx: i,
18595                    kind,
18596                    row_scale: rs,
18597                    data: &[],
18598                    prism,
18599                    affine: crate::prism::is_affine_target(m, name),
18600                });
18601            }
18602            // Small unquantized projections (GDN in_proj_a/b) stay f32.
18603            match t.as_f32() {
18604                Some(d) => Some(crate::gpu::GraphW {
18605                    idx: 0,
18606                    kind: 4,
18607                    row_scale: &[],
18608                    data: d,
18609                    prism: crate::gpu::GraphPrismOp::None,
18610                    affine: false,
18611                }),
18612                None => {
18613                    if std::env::var_os("CMF_BATCH_DEBUG").is_some() {
18614                        eprintln!("batch graph: weight has no graph/f32 representation");
18615                    }
18616                    None
18617                }
18618            }
18619        }
18620        for li in from..upto_excl {
18621            let lw = &self.weights.layers[self.phys_layer(li)];
18622            if dbg {
18623                let ak = match &lw.attn {
18624                    AttnKind::Mla(_) => "Mla".into(),
18625                    AttnKind::Full {
18626                        output_gate, bias, ..
18627                    } => format!("Full gate={output_gate} bias={}", bias.is_some()),
18628                    AttnKind::LinearGdn(_) => "LinearGdn".into(),
18629                    AttnKind::Kda(_) => "Kda".into(),
18630                    AttnKind::Linear(_) => "Linear".into(),
18631                    AttnKind::ShortConv(_) => "ShortConv".into(),
18632                    AttnKind::Bounded(_) => "Bounded".into(),
18633                };
18634                let fk = match &lw.ffn {
18635                    FfnKind::Dense(_) => "Dense",
18636                    FfnKind::Moe(_) => "Moe",
18637                    FfnKind::DenseMoe(_) => "DenseMoe",
18638                };
18639                eprintln!("graph L{li}: attn={ak} ffn={fk}");
18640            }
18641            let gffn = match &lw.ffn {
18642                FfnKind::DenseMoe(_) => return None, // dual branch: CPU path
18643                // A tube layer is several matrices, not one. The graph has
18644                // a shape for the core with one more triple that is always
18645                // on (a hot-neuron file); task tubes keep the segmented path.
18646                FfnKind::Dense(d) if d.segs.len() > 1 => return None,
18647                FfnKind::Dense(d) => {
18648                    // An activation the graph has no kernel arm for keeps
18649                    // the CPU/per-op owner, by name — the dense graph FFN
18650                    // used to compute SiLU for whatever the model asked.
18651                    let Some((act, limit)) = d.act.dense_graph_contract() else {
18652                        self.note_graph_decline(
18653                            "wgpu token graph",
18654                            "dense FFN activation without a graph kernel",
18655                        );
18656                        return None;
18657                    };
18658                    crate::gpu::GraphFfn::Dense {
18659                        gate: gw(&d.gate_proj)?,
18660                        up: gw(&d.up_proj)?,
18661                        down: gw(&d.down_proj)?,
18662                        act,
18663                        limit,
18664                        hot: match d.segs.first() {
18665                            Some(seg) => Some(crate::gpu::GraphMoeDetachedShared {
18666                                gate: gw(&seg.gate)?,
18667                                up: gw(&seg.up)?,
18668                                down: gw(&seg.down)?,
18669                                width: seg.width,
18670                            }),
18671                            None => None,
18672                        },
18673                    }
18674                }
18675                FfnKind::Moe(m) => {
18676                    // Adaptive τ and expert masks keep the CPU path, where
18677                    // they are implemented. Sigmoid routing with a selection
18678                    // bias (LFM2-MoE / DeepSeek noaux_tc), a routed scale ≠ 1
18679                    // and an UNGATED shared expert (HunYuan hy_v3: ×2.826 on
18680                    // the routed mix, the shared expert at weight 1) are all
18681                    // graphed — before, every such token fell to the per-op
18682                    // path whole (145 submits/token on Hy-MT2-30B-A3B).
18683                    if m.route_tau.is_some() || m.mask.is_some() {
18684                        return None;
18685                    }
18686                    let shared = m.shared.as_ref();
18687                    // The resident MoE kernels do not yet carry the
18688                    // descriptor-aware transform through router/shared-gate
18689                    // selection.  Refuse the complete layer instead of
18690                    // scoring with an untransformed Prism plane (the dense
18691                    // path has an explicit FWHT boundary below).
18692                    let inter = m.experts.first()?.gate_proj.rows();
18693                    // Flint's shared expert is a 1024-wide SwiGLU while its
18694                    // routed bank is 512-wide.  The resident MoE shader
18695                    // indexes a uniform-width packed bank, so keep that
18696                    // expert out of the routed slots and add it through the
18697                    // dense q4tp path after routed accumulation.  This is
18698                    // also the safe route for a mixed q2-routed/q4-shared
18699                    // artifact: neither layout nor row stride is faked.
18700                    let detached_shared = match shared {
18701                        Some((se, None))
18702                            if se.gate_proj.rows() != inter || se.up_proj.rows() != inter =>
18703                        {
18704                            let q4 = se.gate_proj.mapped_q4tp().is_some()
18705                                && se.up_proj.mapped_q4tp().is_some()
18706                                && se.down_proj.mapped_q4tp().is_some();
18707                            let q8 = se.gate_proj.mapped_q8_2f().is_some()
18708                                && se.up_proj.mapped_q8_2f().is_some()
18709                                && se.down_proj.mapped_q8_2f().is_some();
18710                            if !matches!(se.act, Act::Silu) || !(q4 || q8) {
18711                                return None;
18712                            }
18713                            Some(crate::gpu::GraphMoeDetachedShared {
18714                                gate: gw(&se.gate_proj)?,
18715                                up: gw(&se.up_proj)?,
18716                                down: gw(&se.down_proj)?,
18717                                width: se.gate_proj.rows(),
18718                            })
18719                        }
18720                        // A separately shaped gated shared expert needs a
18721                        // second sigmoid gate path.  Do not turn it into an
18722                        // ungated one merely to make the graph run.
18723                        Some((se, Some(_)))
18724                            if se.gate_proj.rows() != inter || se.up_proj.rows() != inter =>
18725                        {
18726                            return None;
18727                        }
18728                        _ => None,
18729                    };
18730                    let has_shared = shared.is_some() && detached_shared.is_none();
18731                    let shared_gated = has_shared && matches!(shared, Some((_, Some(_))));
18732                    let sgate = match shared {
18733                        Some((_, Some(sg))) if has_shared => gw(sg)?,
18734                        // No gate, no shared expert, or a detached shared
18735                        // expert: the router only keeps the binding total;
18736                        // the selection shader does not read it.
18737                        _ => gw(&m.router)?,
18738                    };
18739                    let router = gw(&m.router)?;
18740                    // The resident MoE kernels do not yet carry the
18741                    // descriptor-aware transform through router/shared-gate
18742                    // selection.  Refuse the complete layer instead of
18743                    // scoring with an untransformed Prism plane (the dense
18744                    // path has an explicit FWHT boundary below).
18745                    if router.prism != crate::gpu::GraphPrismOp::None
18746                        || sgate.prism != crate::gpu::GraphPrismOp::None
18747                        || router.affine
18748                        || sgate.affine
18749                    {
18750                        tracing::warn!(
18751                            "resident MoE declined: Prism/affine router or shared gate transform is not implemented"
18752                        );
18753                        return None;
18754                    }
18755                    let in_bank_shared = shared.filter(|_| has_shared).map(|(se, _)| se);
18756                    let edge = |t: &QTensor| {
18757                        t.graph_weight()
18758                            .or_else(|| t.graph_weight_descriptor())
18759                            .map(|(mm, i, _, _)| (std::sync::Arc::as_ptr(mm) as usize, i))
18760                    };
18761                    let bank_key: Option<GraphMoeKey> = match (
18762                        m.experts.first().and_then(|e| edge(&e.gate_proj)),
18763                        m.experts.last().and_then(|e| edge(&e.down_proj)),
18764                    ) {
18765                        (Some((fm, fi)), Some((_, di))) if graph_moe_bank_on() => Some((
18766                            self.phys_layer(li),
18767                            m.experts.as_ptr() as usize,
18768                            m.experts.len(),
18769                            in_bank_shared.map_or(0, |se| std::ptr::from_ref(se) as usize),
18770                            fm,
18771                            fi,
18772                            di,
18773                        )),
18774                        _ => None,
18775                    };
18776                    let cached =
18777                        bank_key.and_then(|k| self.graph_moe_banks.lock().unwrap().get(&k).cloned());
18778                    let bank = if let Some(b) = cached {
18779                        b
18780                    } else {
18781                    let mut experts = Vec::with_capacity(m.experts.len() + 1);
18782                    let mut bank_model: Option<std::sync::Arc<cortiq_core::CmfModel>> = None;
18783                    // q4t or q4tp, but not both in one layer — the kernels
18784                    // are picked per layer, not per expert.
18785                    let mut q4tp: Option<bool> = None;
18786                    // The mixed 2-bit profile: q2tp gate/up over a q4tp
18787                    // down. Uniform across the layer, like `q4tp` itself.
18788                    let mut gu_q2: Option<bool> = None;
18789                    // q8_2f experts (gate, up and down): their own kernels.
18790                    let mut q82: Option<bool> = None;
18791                    // One MoE gate/up kernel serves the complete packed bank.
18792                    // Bind an activation only when every routed (and in-bank
18793                    // shared) expert owns the same exact WGPU contract.
18794                    let mut moe_act = None;
18795                    for e in m.experts.iter().chain(in_bank_shared.into_iter()) {
18796                        let Some(e_act) = e.act.wgpu_graph_act() else {
18797                            return None;
18798                        };
18799                        match moe_act {
18800                            Some(existing) if existing != e_act => return None,
18801                            None => moe_act = Some(e_act),
18802                            _ => {}
18803                        }
18804                        if e.gate_proj.rows() != inter || e.up_proj.rows() != inter {
18805                            return None;
18806                        }
18807                        // Expert tensors are packed into one resident buffer
18808                        // and the MoE kernels have no transform slot per
18809                        // expert.  Keep the CPU/per-op owner for Prism or
18810                        // affine experts rather than silently using raw bytes.
18811                        for expert_weight in [&e.gate_proj, &e.up_proj, &e.down_proj] {
18812                            let Some((em, ei, _, _)) = expert_weight
18813                                .graph_weight()
18814                                .or_else(|| expert_weight.graph_weight_descriptor())
18815                            else {
18816                                return None;
18817                            };
18818                            let name = &em.tensors[ei].name;
18819                            if crate::prism::is_forward_weight(em, name)
18820                                || crate::prism::is_inverse_embedding(em, name)
18821                                || crate::prism::is_affine_target(em, name)
18822                            {
18823                                tracing::warn!(
18824                                    "resident MoE declined: expert Prism/affine transform is not implemented"
18825                                );
18826                                return None;
18827                            }
18828                        }
18829                        let (mm, gi, ui, di, is_p, is_q2, is_8) = match e.gate_proj.mapped_q4t() {
18830                            Some((mm, gi)) => (
18831                                mm,
18832                                gi,
18833                                e.up_proj.mapped_q4t()?.1,
18834                                e.down_proj.mapped_q4t()?.1,
18835                                false,
18836                                false,
18837                                false,
18838                            ),
18839                            None => match e.gate_proj.mapped_q2tp() {
18840                                Some((mm, gi)) => (
18841                                    mm,
18842                                    gi,
18843                                    e.up_proj.mapped_q2tp()?.1,
18844                                    e.down_proj.mapped_q4tp()?.1,
18845                                    true,
18846                                    true,
18847                                    false,
18848                                ),
18849                                None => match e.gate_proj.mapped_q4tp() {
18850                                    Some((mm, gi)) => (
18851                                        mm,
18852                                        gi,
18853                                        e.up_proj.mapped_q4tp()?.1,
18854                                        e.down_proj.mapped_q4tp()?.1,
18855                                        true,
18856                                        false,
18857                                        false,
18858                                    ),
18859                                    // q8_2f experts: all three projections,
18860                                    // each with its own column field.
18861                                    None => {
18862                                        if !crate::gpu::moe_q82_graph_on() {
18863                                            return None;
18864                                        }
18865                                        let (mm, gi) = e.gate_proj.mapped_q8_2f()?;
18866                                        (
18867                                            mm,
18868                                            gi,
18869                                            e.up_proj.mapped_q8_2f()?.1,
18870                                            e.down_proj.mapped_q8_2f()?.1,
18871                                            false,
18872                                            false,
18873                                            true,
18874                                        )
18875                                    }
18876                                },
18877                            },
18878                        };
18879                        if *q4tp.get_or_insert(is_p) != is_p
18880                            || *gu_q2.get_or_insert(is_q2) != is_q2
18881                            || *q82.get_or_insert(is_8) != is_8
18882                        {
18883                            // The shared expert rides in the same packed
18884                            // buffer as the routed ones, so a layer that
18885                            // mixes layouts cannot be indexed by one stride.
18886                            // Say so: the symptom is a whole model quietly
18887                            // running its MoE on the CPU.
18888                            tracing::warn!(
18889                                "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."
18890                            );
18891                            return None;
18892                        }
18893                        bank_model.get_or_insert_with(|| mm.clone());
18894                        experts.push((gi, ui, di));
18895                    }
18896                    let b = GraphMoeBank {
18897                        experts,
18898                        q4tp,
18899                        gu_q2,
18900                        q82,
18901                        act: moe_act,
18902                        model: bank_model,
18903                    };
18904                    if let Some(k) = bank_key {
18905                        self.graph_moe_banks.lock().unwrap().insert(k, b.clone());
18906                    }
18907                    b
18908                    };
18909                    if let Some(mm) = &bank.model {
18910                        model.get_or_insert_with(|| mm.clone());
18911                    }
18912                    crate::gpu::GraphFfn::Moe {
18913                        latent: None,
18914                        shared_limit: None,
18915                        router,
18916                        shared_gate: sgate,
18917                        experts: bank.experts,
18918                        n_exp: m.experts.len(),
18919                        // CMF_TOPK_PROBE: timing probe only — output is WRONG.
18920                        // Fewer experts shrink the MoE arithmetic while the
18921                        // dispatch count stays identical, which is the only
18922                        // clean way to tell a launch-bound decode from a
18923                        // compute-bound one.
18924                        top_k: std::env::var("CMF_TOPK_PROBE")
18925                            .ok()
18926                            .and_then(|v| v.parse::<usize>().ok())
18927                            .filter(|k| *k > 0 && *k <= m.top_k)
18928                            .unwrap_or(m.top_k),
18929                        inter,
18930                        act: bank.act?,
18931                        norm_topk: m.norm_topk_prob,
18932                        q4tp: bank.q4tp?,
18933                        gu_q2: bank.gu_q2.unwrap_or(false),
18934                        q82: bank.q82.unwrap_or(false),
18935                        sigmoid: m.router_sigmoid,
18936                        sigmoid_denom_eps: m.sigmoid_denom_eps,
18937                        bias: m.expert_bias.as_deref(),
18938                        has_shared,
18939                        detached_shared,
18940                        shared_gated,
18941                        route_scale: m.routed_scaling,
18942                        limit: 0.0,
18943                    }
18944                }
18945            };
18946            let attn = match &lw.attn {
18947                AttnKind::Full {
18948                    wq,
18949                    wk,
18950                    wv,
18951                    wo,
18952                    q_norm,
18953                    k_norm,
18954                    output_gate,
18955                    softplus_gate,
18956                    bias,
18957                } => {
18958                    if self.attention_heads_per_layer.is_some() {
18959                        return None;
18960                    }
18961                    // A projected output gate rides the graph in one form:
18962                    // Spark-X2.5's head-wise sigmoid (one g_proj row per Q
18963                    // head). Laguna's softplus gate keeps the CPU path.
18964                    let head_gate = match softplus_gate {
18965                        None => None,
18966                        Some((g, true)) if self.proj_gate_sigmoid && !*output_gate => Some(gw(g)?),
18967                        Some(_) => {
18968                            self.note_graph_decline(
18969                                "wgpu token graph",
18970                                "projected softplus / per-element output gate",
18971                            );
18972                            return None;
18973                        }
18974                    };
18975                    model = Some(self.graph_model_of(&[wq, wk, wv, wo])?);
18976                    crate::gpu::GraphAttn::Full {
18977                        wq: gw(wq)?,
18978                        wk: gw(wk)?,
18979                        wv: gw(wv)?,
18980                        wo: gw(wo)?,
18981                        q_norm: q_norm.as_deref(),
18982                        k_norm: k_norm.as_deref(),
18983                        late_qk_norm: self.qk_norm_after_rope,
18984                        bias: bias
18985                            .as_ref()
18986                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
18987                        output_gate: *output_gate,
18988                        cpu_k: self.kv_cache.layers[li].k_heads(),
18989                        cpu_v: self.kv_cache.layers[li].v_heads(),
18990                        cpu_base: self.kv_cache.layers[li].base(),
18991                        geom: self.graph_attn_geom_decode(li, vres_e0),
18992                        head_gate,
18993                    }
18994                }
18995                AttnKind::LinearGdn(w) => {
18996                    let cfg = self.gdn_cfg?;
18997                    model = Some(self.graph_model_of(&[&w.in_proj_qkv, &w.in_proj_z, &w.out_proj])?);
18998                    crate::gpu::GraphAttn::Gdn {
18999                        qkv: gw(&w.in_proj_qkv)?,
19000                        z: gw(&w.in_proj_z)?,
19001                        a: gw(&w.in_proj_a)?,
19002                        b: gw(&w.in_proj_b)?,
19003                        out: gw(&w.out_proj)?,
19004                        conv1d: &w.conv1d,
19005                        a_log: &w.a_log,
19006                        dt_bias: &w.dt_bias,
19007                        norm: &w.norm,
19008                        nv: cfg.num_v_heads,
19009                        nk: cfg.num_k_heads,
19010                        dk: cfg.key_head_dim,
19011                        dv: cfg.value_head_dim,
19012                        kk: cfg.conv_kernel,
19013                        cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
19014                        preview: None,
19015                    }
19016                }
19017                AttnKind::ShortConv(w) => {
19018                    let cfg = self.short_conv_cfg?;
19019                    let (m, _, _, _) = w
19020                        .in_proj
19021                        .graph_weight()
19022                        .or_else(|| w.in_proj.graph_weight_descriptor())?;
19023                    model = Some(m.clone());
19024                    crate::gpu::GraphAttn::ShortConv {
19025                        inp: gw(&w.in_proj)?,
19026                        out: gw(&w.out_proj)?,
19027                        taps: &w.conv,
19028                        kernel: cfg.kernel,
19029                        cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
19030                    }
19031                }
19032                // Kimi-Linear's mixers: the CUDA hybrid arm runs them, the
19033                // wgpu graphs decline them at their entry
19034                AttnKind::Kda(_) | AttnKind::Mla(_) => {
19035                    let (attn, m) = self.graph_attn_kimi(li, &lw.attn, &gw)?;
19036                    model = Some(m);
19037                    attn
19038                }
19039                _ => return None,
19040            };
19041            layers.push(crate::gpu::GraphLayer {
19042                engram: None,
19043                mhc: crate::sensenova::graph_mhc(self.mhc.as_deref(), self.phys_layer(li)),
19044                input_norm: &lw.input_norm,
19045                attn,
19046                post_norm: &lw.post_norm,
19047                attn_out_norm: lw.attn_out_norm.as_deref(),
19048                ffn_out_norm: lw.ffn_out_norm.as_deref(),
19049                layer_scale: lw.layer_scale,
19050                ffn: gffn,
19051            });
19052        }
19053        let model = model?;
19054        // Fold final-norm + lm_head into the graph when this call wants logits
19055        // and the lm_head is a graphable (quantized) weight — the graph then
19056        // reads back logits (into logits_out) instead of the hidden, dropping
19057        // the separate CPU/GPU lm_head op + its sync. Never the f32 fallback:
19058        // an unquantized lm_head is vocab·hidden and must not be uploaded.
19059        let lm_gw = if upto_excl == self.num_layers
19060            && self.graph_want_logits
19061            && std::env::var("CMF_GPU_LMHEAD")
19062                .map(|v| v != "0")
19063                .unwrap_or(true)
19064        {
19065            self.weights
19066                .lm_head
19067                .graph_weight()
19068                .or_else(|| self.weights.lm_head.graph_weight_descriptor())
19069                .map(|(m, i, kind, rs)| {
19070                    let name = &m.tensors[i].name;
19071                    let prism = if crate::prism::is_inverse_embedding(m, name) {
19072                        crate::gpu::GraphPrismOp::InverseEmbedding
19073                    } else if crate::prism::is_forward_weight(m, name) {
19074                        crate::gpu::GraphPrismOp::Forward
19075                    } else {
19076                        crate::gpu::GraphPrismOp::None
19077                    };
19078                    (
19079                        crate::gpu::GraphW {
19080                            idx: i,
19081                            kind,
19082                            row_scale: rs,
19083                            data: &[],
19084                            prism,
19085                            affine: crate::prism::is_affine_target(m, name),
19086                        },
19087                        self.weights.lm_head.rows(),
19088                    )
19089                })
19090        } else {
19091            None
19092        };
19093        let lm = lm_gw.as_ref().map(|(gw, rows)| (gw, *rows));
19094        // Multi-step re-embeds the winner on the device.
19095        let emb_gw = if steps > 1 {
19096            self.weights
19097                .embed_tokens
19098                .graph_weight()
19099                .or_else(|| self.weights.embed_tokens.graph_weight_descriptor())
19100                .map(|(m, i, kind, rs)| {
19101                    let name = &m.tensors[i].name;
19102                    let prism = if crate::prism::is_inverse_embedding(m, name) {
19103                        crate::gpu::GraphPrismOp::InverseEmbedding
19104                    } else if crate::prism::is_forward_weight(m, name) {
19105                        crate::gpu::GraphPrismOp::Forward
19106                    } else {
19107                        crate::gpu::GraphPrismOp::None
19108                    };
19109                    (
19110                        crate::gpu::GraphW {
19111                            idx: i,
19112                            kind,
19113                            row_scale: rs,
19114                            data: &[],
19115                            prism,
19116                            affine: crate::prism::is_affine_target(m, name),
19117                        },
19118                        self.weights.embed_tokens.rows(),
19119                        self.embed_multiplier,
19120                    )
19121                })
19122        } else {
19123            None
19124        };
19125
19126        // Loop boundaries: virtual layer indices after which final_norm is
19127        // applied (mid-stack only; the GLOBAL last layer's norm folds into
19128        // lm_head). Span-relative — the executor compares its enumerate
19129        // index. A span ending mid-stack keeps its boundary norm even when
19130        // it is the span's own last layer.
19131        let loop_norm_at: Vec<usize> = if self.loop_final_norm {
19132            (from..upto_excl.min(self.num_layers - 1))
19133                .filter(|&li| (li + 1) % self.physical_layers == 0)
19134                .map(|li| li - from)
19135                .collect()
19136        } else {
19137            Vec::new()
19138        };
19139        let mut h = hidden.to_vec();
19140        // The normal decode path only needs the fused lm-head logits.  A
19141        // CMF_LOGIT_DUMP diagnostic, however, promises a prompt-boundary
19142        // post-stack hidden alongside those logits; request the existing
19143        // second readback only for that explicit probe instead of dumping
19144        // the input copy left in `h` by a folded-head graph.
19145        let dump_hidden = std::env::var_os("CMF_LOGIT_DUMP").is_some();
19146        let mut taps = if steps == 1 { self.dflash_taps_wanted(from, upto_excl) } else { Vec::new() };
19147        let n_dflash = taps.len();
19148        // Dynamic skill routing reads φ, the residual after the router's
19149        // layer, every token: the graph keeps that row the way it keeps a
19150        // drafter's, and `forward_layers_upto` folds it into the EMA.
19151        let phi_slot = match self.dyn_phi_layer {
19152            Some(l) if steps == 1 && (from..upto_excl).contains(&l) => {
19153                Some(taps.iter().position(|&t| t == l).unwrap_or_else(|| {
19154                    taps.push(l);
19155                    taps.len() - 1
19156                }))
19157            }
19158            _ => None,
19159        };
19160        *self.dyn_phi_tap.lock().unwrap() = None;
19161        crate::gpu::layer_taps_arm(&taps);
19162        let outcome = crate::gpu::forward_token_graph(
19163            &model,
19164            self.graph_kv_id,
19165            &layers,
19166            &o1_views,
19167            self.o1_epoch,
19168            &self.inv_freq,
19169            &mut h,
19170            nh,
19171            nkv,
19172            hd,
19173            self.attn_scale,
19174            rd,
19175            self.hidden_size,
19176            self.intermediate_size,
19177            position,
19178            self.kv_cache.max_seq_len,
19179            gemma,
19180            self.rms_eps as f32,
19181            lm,
19182            &self.weights.final_norm,
19183            logits_out,
19184            &loop_norm_at,
19185            steps,
19186            emb_gw.as_ref().map(|(gw, rows, m)| (gw, *rows, *m)),
19187            ids_out,
19188            layers_run,
19189            from,
19190            dump_hidden,
19191        );
19192        self.graph_taps_keep(&taps, n_dflash, phi_slot, position, 1, outcome == crate::gpu::TokenGraphOutcome::Completed);
19193        match outcome {
19194            crate::gpu::TokenGraphOutcome::Completed => Some(Ok(h)),
19195            crate::gpu::TokenGraphOutcome::Failed => Some(Err(())),
19196            crate::gpu::TokenGraphOutcome::Declined => None,
19197        }
19198    }
19199
19200    /// Batched prefill: k contiguous prompt positions through the whole wgpu
19201    /// graph in ONE submit (projections/FFN as GEMMs). `hiddens` is [k·hidden]
19202    /// in/out (embeddings in, layer output out); KV mirror / GDN state advance.
19203    /// false ⇒ unsupported → caller keeps the per-position graph.
19204    /// The b-row Metal graph plan for the whole model: every layer as a
19205    /// GDN run or a full-attention item, all-or-nothing (a layer outside the
19206    /// graph's contract → None, the caller runs plain). Shared by the
19207    /// speculative verify and the batched prefill.
19208    #[cfg(target_os = "macos")]
19209    #[allow(clippy::type_complexity)]
19210    fn metal_rows_plan(
19211        &self,
19212    ) -> Option<(
19213        Vec<MetalRowsItem<'_>>,
19214        std::sync::Arc<cortiq_core::CmfModel>,
19215        Option<crate::gpu_metal::GdnGpuCfg>,
19216    )> {
19217        use crate::gpu_metal::{AttnGpuLayer, GdnGpuCfg, GdnGpuLayer, MetalFfn};
19218        let graph_force = crate::gpu::q1_force() || crate::gpu::q2tp_gpu_opt_in();
19219        if !graph_force
19220            || !crate::gpu::enabled_here()
19221            || std::env::var("CMF_GPU_BLOCK")
19222                .map(|v| v == "0")
19223                .unwrap_or(false)
19224            || self.attn_softcap > 0.0
19225            || (self.o1_active() && !self.o1_on_graph())
19226            // Sliding windows with per-layer RoPE (Spark-X2.6) ride the rows graph
19227            // as they ride the chunk graph (`metal_graph_swa`).
19228            || (self.swa.is_some() && !self.metal_graph_swa())
19229            || self.global_attn.is_some()
19230            || self.attention_heads_per_layer.is_some()
19231            // per-layer KV heads, narrow V, learned sinks (MiMo-V2)
19232            || (self.graph_attn_decline_reason().is_some() && !self.metal_graph_swa())
19233            || self.attn_v_norm
19234            || self.loop_final_norm
19235            || !self.metal_rope_scale_ok()
19236        {
19237            return None;
19238        }
19239        let attend_contract = self.head_dim % 4 == 0
19240            && self.head_dim <= 256
19241            && self.rotary_dim >= 2
19242            && self.rotary_dim <= self.head_dim
19243            && (self.rotary_dim / 2) % 32 == 0
19244            && self.num_kv_heads > 0
19245            && self.num_heads % self.num_kv_heads == 0;
19246        if !attend_contract {
19247            return None;
19248        }
19249        let mut plan: Vec<MetalRowsItem> = Vec::new();
19250        let mut model_ref: Option<std::sync::Arc<cortiq_core::CmfModel>> = None;
19251        // SenseNova-Loop's mHC streams ride the rows graph as they ride the token graph:
19252        // two streams, the Sinkhorn mix, kernels that compiled. `CMF_METAL_ROWS_MHC=0`
19253        // keeps such a prompt on the token graph, a row at a time.
19254        if self.mhc.as_ref().is_some_and(|m| m.s.streams != 2 || m.s.fixed_identity)
19255            || (self.mhc.is_some()
19256                && (!crate::gpu_metal::mhc::available()
19257                    || std::env::var("CMF_MHC_GRAPH").as_deref() == Ok("0")
19258                    || std::env::var("CMF_METAL_ROWS_MHC").as_deref() == Ok("0")))
19259        {
19260            return None;
19261        }
19262        for li in 0..self.num_layers {
19263            let lw = &self.weights.layers[self.phys_layer(li)];
19264            if lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some() {
19265                return None;
19266            }
19267            let mhc = if self.mhc_layer(li) {
19268                Some(crate::sensenova::graph_mhc(self.mhc.as_deref(), self.phys_layer(li))?)
19269            } else {
19270                None
19271            };
19272            let ffn = match &lw.ffn {
19273                FfnKind::Dense(d) if matches!(d.act, Act::Silu | Act::Gelu) && d.segs.is_empty() => {
19274                    let (Some(g), Some(u), Some(dn)) = (
19275                        d.gate_proj.metal_graph_parts(),
19276                        d.up_proj.metal_graph_parts(),
19277                        d.down_proj.metal_graph_parts(),
19278                    ) else {
19279                        return None;
19280                    };
19281                    MetalFfn::Dense {
19282                        gate: g,
19283                        up: u,
19284                        down: dn,
19285                        // SiLU, or the exact GELU of Spark-X2.6 (`gelu_rows`).
19286                        act: if d.act == Act::Gelu { 1 } else { 0 },
19287                    }
19288                }
19289                _ => return None,
19290            };
19291            match &lw.attn {
19292                AttnKind::LinearGdn(w) if self.gdn_cfg.is_some() => {
19293                    let (Some(qkv), Some(z), Some(a), Some(bb), Some(out)) = (
19294                        w.in_proj_qkv.metal_graph_parts(),
19295                        w.in_proj_z.metal_graph_parts(),
19296                        w.in_proj_a.f32_parts(),
19297                        w.in_proj_b.f32_parts(),
19298                        w.out_proj.metal_graph_parts(),
19299                    ) else {
19300                        return None;
19301                    };
19302                    if let QTensor::Mapped { model, .. } = &w.in_proj_qkv {
19303                        model_ref.get_or_insert_with(|| model.clone());
19304                    }
19305                    let gl = GdnGpuLayer {
19306                        mhc,
19307                        attn_norm: &lw.input_norm,
19308                        post_norm: &lw.post_norm,
19309                        qkv,
19310                        z,
19311                        a,
19312                        b: bb,
19313                        out,
19314                        ffn,
19315                        conv1d: &w.conv1d,
19316                        a_log: &w.a_log,
19317                        dt_bias: &w.dt_bias,
19318                        gnorm: &w.norm,
19319                    };
19320                    match plan.last_mut() {
19321                        Some(MetalRowsItem::Gdn { run, .. }) => run.push(gl),
19322                        _ => plan.push(MetalRowsItem::Gdn {
19323                            run: vec![gl],
19324                            first: li,
19325                        }),
19326                    }
19327                }
19328                AttnKind::Full {
19329                    wq,
19330                    wk,
19331                    wv,
19332                    wo,
19333                    q_norm,
19334                    k_norm,
19335                    output_gate,
19336                    softplus_gate,
19337                    bias: None,
19338                } => {
19339                    // Spark-X2.6's per-head sigmoid g_proj gate, from f32 rows.
19340                    let head_gate = match softplus_gate {
19341                        None => None,
19342                        Some((g, true)) if self.proj_gate_sigmoid && !*output_gate => match g.f32_parts() {
19343                            Some((d, r, c)) if r == self.num_heads && c == self.hidden_size => Some(d),
19344                            _ => return None,
19345                        },
19346                        Some(_) => return None,
19347                    };
19348                    let (Some(pq), Some(pk), Some(pv), Some(po)) = (
19349                        wq.metal_graph_parts(),
19350                        wk.metal_graph_parts(),
19351                        wv.metal_graph_parts(),
19352                        wo.metal_graph_parts(),
19353                    ) else {
19354                        return None;
19355                    };
19356                    if let QTensor::Mapped { model, .. } = wq {
19357                        model_ref.get_or_insert_with(|| model.clone());
19358                    }
19359                    let cache = &self.kv_cache.layers[li];
19360                    if cache.mode != crate::kv_cache::KvMode::F32 || (cache.o1.is_some() && !self.o1_on_graph()) {
19361                        return None;
19362                    }
19363                    plan.push(MetalRowsItem::Attn {
19364                        l: AttnGpuLayer {
19365                            mhc,
19366                            attn_norm: &lw.input_norm,
19367                            post_norm: &lw.post_norm,
19368                            wq: pq,
19369                            wk: pk,
19370                            wv: pv,
19371                            wo: po,
19372                            ffn,
19373                            attn_out_norm: None,
19374                            ffn_out_norm: None,
19375                            layer_scale: None,
19376                        },
19377                        li,
19378                        q_norm: q_norm.as_deref(),
19379                        k_norm: k_norm.as_deref(),
19380                        output_gate: *output_gate,
19381                        head_gate,
19382                    });
19383                }
19384                _ => return None,
19385            }
19386        }
19387        let model = model_ref?;
19388        let gcfg = self.gdn_cfg.map(|cfg| GdnGpuCfg {
19389            nv: cfg.num_v_heads,
19390            nk: cfg.num_k_heads,
19391            dk: cfg.key_head_dim,
19392            dv: cfg.value_head_dim,
19393            kk: cfg.conv_kernel,
19394            hidden: self.hidden_size,
19395            inter: self.intermediate_size,
19396            c_dim: cfg.conv_dim(),
19397            eps: cfg.rms_eps as f32,
19398            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
19399        });
19400        Some((plan, model, gcfg))
19401    }
19402
19403    /// `AttnDeviceParams` for a plan item over the CPU cache as it stands.
19404    #[cfg(target_os = "macos")]
19405    #[allow(clippy::too_many_arguments)]
19406    fn metal_attn_params<'a>(
19407        li: usize,
19408        cache: &'a crate::kv_cache::LayerKvCache,
19409        q_norm: Option<&'a [f32]>,
19410        k_norm: Option<&'a [f32]>,
19411        output_gate: bool,
19412        inv_freq: &'a [f32],
19413        rope_scale: f32,
19414        geom: (usize, usize, usize, usize),
19415        pos0: usize,
19416        kv_id: u64,
19417        scale: f32,
19418        eps: f32,
19419        gemma: bool,
19420        late_qk_norm: bool,
19421        o1_epoch: u64,
19422        head_gate: Option<&'a [f32]>,
19423        window: Option<usize>,
19424    ) -> (crate::gpu_metal::AttnDeviceParams<'a>, usize) {
19425        let (nh, nkv, hd, rd) = geom;
19426        let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
19427        let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
19428        let cpu_stored = cpu_k[0].len() / hd;
19429        (
19430            crate::gpu_metal::AttnDeviceParams {
19431                kv_id,
19432                layer: li,
19433                nh,
19434                nkv,
19435                hd,
19436                rd,
19437                position: pos0,
19438                scale,
19439                eps,
19440                gemma,
19441                late_qk_norm,
19442                output_gate,
19443                q_norm,
19444                k_norm,
19445                inv_freq,
19446                rope_scale,
19447                cpu_k,
19448                cpu_v,
19449                cpu_stored,
19450                cpu_gen: cache.generation(),
19451                // A layer still collecting has no views, and its rows go through the mirror.
19452                o1: cache.o1_views().map(|views| crate::gpu_metal::O1AttnParams { views, epoch: o1_epoch }),
19453                window,
19454                softmax_sink: cache.sinks.as_deref(),
19455                head_gate,
19456                v_norm: false,
19457                dash: None,
19458            },
19459            cpu_stored,
19460        )
19461    }
19462
19463    /// Run the rows plan over `hiddens` (b rows at `pos0..`): validate,
19464    /// encode every item, optionally the head, sync. Returns the graph
19465    /// (for the commit / state finish) plus the GDN layer indices and the
19466    /// attention layers with the row count they were encoded against.
19467    #[cfg(target_os = "macos")]
19468    #[allow(clippy::type_complexity)]
19469    fn metal_rows_run(
19470        &mut self,
19471        hiddens: &mut [f32],
19472        pos0: usize,
19473        b: usize,
19474        prefill: bool,
19475        spec: Option<((usize, usize, usize), &[f32], &mut Vec<f32>)>,
19476        // Greedy verify: (row length scored, the b argmax ids out) — the
19477        // head's argmax runs on the device and the logits plane is NOT
19478        // read back (`spec.2` stays empty).
19479        mut argmax_out: Option<(usize, &mut Vec<u32>)>,
19480    ) -> MetalRowsRun {
19481        use crate::gpu_metal::{GraphDims, VerifyGraph};
19482        // The previous round's commit may still be replaying into the
19483        // trunk GDN owners on the second queue: this graph reads them
19484        // (zero-copy wraps) and may reallocate them below — collect the
19485        // replay first. Normally already complete (the draft chain ran
19486        // in between); a failed replay is terminal like a failed commit.
19487        if !crate::gpu_metal::wait_replay() {
19488            tracing::error!("Metal rows graph: the pending async replay failed");
19489            return MetalRowsRun::Failed;
19490        }
19491        spec_stamp("v.wait");
19492        // Seed the GDN recurrent records the rows graph reads — GDN layers
19493        // ONLY (the record the CPU path would allocate anyway).  Sizing
19494        // every layer here planted a zero GDN-sized record on a bounded
19495        // anchor of a natively bounded file this path then refused, and
19496        // that record counted as recurrent state on macOS.
19497        let want = self.gdn_cfg.map(|c| c.state_len()).unwrap_or(0);
19498        if want > 0 {
19499            // a looped stack's visit runs its physical layer (`phys_layer`), not `li % phys`
19500            let gdn: Vec<bool> = (0..self.kv_cache.layers.len())
19501                .map(|li| {
19502                    self.weights
19503                        .layers
19504                        .get(self.phys_layer(li))
19505                        .is_some_and(|lw| matches!(lw.attn, AttnKind::LinearGdn(_)))
19506                })
19507                .collect();
19508            for (l, is_gdn) in self.kv_cache.layers.iter_mut().zip(gdn) {
19509                if is_gdn && l.linear_state.len() != want {
19510                    l.linear_state = vec![0f32; want];
19511                }
19512            }
19513        }
19514        let Some((plan, model, gcfg)) = self.metal_rows_plan() else {
19515            return MetalRowsRun::Declined;
19516        };
19517        spec_stamp("v.plan");
19518        let dims = GraphDims {
19519            hidden: self.hidden_size,
19520            eps: self.rms_eps as f32,
19521            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
19522        };
19523        // A prompt chunk for the Neural Engine goes as two halves, a thread each: one is on the
19524        // ANE while the GPU has the other.
19525        let hs = self.hidden_size;
19526        let relay = prefill
19527            && spec.is_none()
19528            && b >= 128
19529            && crate::gpu_metal::ane::wanted()
19530            && std::env::var("CMF_ANE_RELAY").as_deref() != Ok("0");
19531        let cuts: Vec<(usize, usize)> = if relay { vec![(0, b / 2), (b / 2, b - b / 2)] } else { vec![(0, b)] };
19532        let gate = crate::gpu_metal::LaneGate::new();
19533        let mut lanes: Vec<VerifyGraph> = Vec::with_capacity(cuts.len());
19534        for (ln, &(r0, n)) in cuts.iter().enumerate() {
19535            let h = &hiddens[r0 * hs..(r0 + n) * hs];
19536            let g = if relay {
19537                VerifyGraph::new_prefill_lane(&model, dims, h, n, ln, b - r0 - n, &gate)
19538            } else if prefill {
19539                VerifyGraph::new_prefill(&model, dims, h, n)
19540            } else {
19541                VerifyGraph::new(&model, dims, h, n)
19542            };
19543            let Some(g) = g else {
19544                return MetalRowsRun::Declined;
19545            };
19546            lanes.push(g);
19547        }
19548        if prefill {
19549            use crate::gpu_metal::{AneWants, MetalFfn};
19550            // SiLU or the exact GELU (Spark-X2.6), one activation for the file's FFNs.
19551            let mut ane_act = None;
19552            let ffn = |f: &MetalFfn<'_>, ane_act: &mut Option<u8>| match f {
19553                MetalFfn::Dense { gate, up, down, act } if *act <= 1 && ane_act.is_none_or(|a| a == *act) => {
19554                    *ane_act = Some(*act);
19555                    Some([*gate, *up, *down])
19556                }
19557                _ => None,
19558            };
19559            let mut wants = Vec::new();
19560            for item in &plan {
19561                match item {
19562                    MetalRowsItem::Gdn { run, .. } => {
19563                        wants.extend(run.iter().map(|l| AneWants {
19564                            ffn: ffn(&l.ffn, &mut ane_act),
19565                            mix: if crate::gpu_metal::ane_takes_qkv() { vec![l.qkv, l.z] } else { vec![l.z] },
19566                        }))
19567                    }
19568                    MetalRowsItem::Attn { l, .. } => wants.push(AneWants {
19569                        ffn: ffn(&l.ffn, &mut ane_act),
19570                        mix: if crate::gpu_metal::ane_takes_qkv() {
19571                            vec![l.wk, l.wv, l.wq]
19572                        } else if crate::gpu_metal::ane_takes_q() {
19573                            vec![l.wq]
19574                        } else {
19575                            Vec::new()
19576                        },
19577                    }),
19578                }
19579            }
19580            crate::gpu_metal::ane::set_act(ane_act.unwrap_or(0));
19581            for g in lanes.iter_mut() {
19582                g.ane_attach(&wants);
19583            }
19584            lanes[0].ane_begin(lanes.len());
19585        }
19586        // With the Neural Engine a layer's command is committed as it ends, so a refusal past
19587        // the first one leaves states half written.
19588        let hard = relay || lanes[0].has_ane();
19589        let geom = (
19590            self.num_heads,
19591            self.num_kv_heads,
19592            self.head_dim,
19593            self.rotary_dim,
19594        );
19595        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
19596        let eps = self.rms_eps as f32;
19597        let kv_id = self.graph_kv_id;
19598        // Each layer's own RoPE table and width (Spark-X2.6: sliding and full layers differ).
19599        let tables: Vec<std::sync::Arc<Vec<f32>>> = (0..self.num_layers).map(|li| self.layer_inv_freq(li)).collect();
19600        let lgeom = |li: usize| (geom.0, geom.1, geom.2, self.layer_geom(li).2);
19601        for item in &plan {
19602            let ok = match item {
19603                MetalRowsItem::Gdn { run, .. } => gcfg
19604                    .as_ref()
19605                    .map(|gc| lanes.iter().all(|g| run.iter().all(|l| g.gdn_ok(l, gc))))
19606                    .unwrap_or(false),
19607                MetalRowsItem::Attn {
19608                    l,
19609                    li,
19610                    q_norm,
19611                    k_norm,
19612                    output_gate,
19613                    head_gate,
19614                } => {
19615                    let (p, _) = Self::metal_attn_params(
19616                        *li,
19617                        &self.kv_cache.layers[*li],
19618                        *q_norm,
19619                        *k_norm,
19620                        *output_gate,
19621                        &tables[*li],
19622                        self.layer_rope_scale(*li),
19623                        lgeom(*li),
19624                        pos0,
19625                        kv_id,
19626                        self.attn_scale,
19627                        eps,
19628                        gemma,
19629                        self.qk_norm_after_rope,
19630                        self.o1_epoch,
19631                        *head_gate,
19632                        self.layer_window(*li),
19633                    );
19634                    lanes.iter().all(|g| g.attn_ok(l, &p))
19635                }
19636            };
19637            if !ok {
19638                use std::sync::atomic::{AtomicBool, Ordering};
19639                static SAID: AtomicBool = AtomicBool::new(false);
19640                if !SAID.swap(true, Ordering::Relaxed) {
19641                    tracing::warn!("metal rows graph: a layer failed preflight — declining");
19642                }
19643                return MetalRowsRun::Declined;
19644            }
19645        }
19646        let lm = match &spec {
19647            Some((lm, _, _)) => {
19648                if !lanes[0].lm_head_ok(*lm) {
19649                    return MetalRowsRun::Declined;
19650                }
19651                Some(*lm)
19652            }
19653            None => None,
19654        };
19655        // What each half encodes, layer by layer: nothing here changes while they run.
19656        enum Step<'a> {
19657            Gdn(&'a crate::gpu_metal::GdnGpuLayer<'a>, &'a [f32]),
19658            Attn(&'a crate::gpu_metal::AttnGpuLayer<'a>, crate::gpu_metal::AttnDeviceParams<'a>),
19659        }
19660        let mut gdn_layers = Vec::new();
19661        let mut attn_layers = Vec::new();
19662        let mut steps: Vec<Vec<Step<'_>>> = cuts.iter().map(|_| Vec::new()).collect();
19663        // the layer each step is, for the rows a DFlash drafter reads
19664        let mut step_layer: Vec<usize> = Vec::new();
19665        for item in &plan {
19666            match item {
19667                MetalRowsItem::Gdn { run, first } => {
19668                    for (l, kv) in run.iter().zip(&self.kv_cache.layers[*first..*first + run.len()]) {
19669                        for st in steps.iter_mut() {
19670                            st.push(Step::Gdn(l, kv.linear_state.as_slice()));
19671                        }
19672                    }
19673                    gdn_layers.extend(*first..*first + run.len());
19674                    step_layer.extend(*first..*first + run.len());
19675                }
19676                MetalRowsItem::Attn {
19677                    l,
19678                    li,
19679                    q_norm,
19680                    k_norm,
19681                    output_gate,
19682                    head_gate,
19683                } => {
19684                    for (ln, st) in steps.iter_mut().enumerate() {
19685                        let (mut p, cpu_stored) = Self::metal_attn_params(
19686                            *li,
19687                            &self.kv_cache.layers[*li],
19688                            *q_norm,
19689                            *k_norm,
19690                            *output_gate,
19691                            &tables[*li],
19692                            self.layer_rope_scale(*li),
19693                            lgeom(*li),
19694                            pos0 + cuts[ln].0,
19695                            kv_id,
19696                            self.attn_scale,
19697                            eps,
19698                            gemma,
19699                            self.qk_norm_after_rope,
19700                            self.o1_epoch,
19701                            *head_gate,
19702                            self.layer_window(*li),
19703                        );
19704                        // The half before leaves its rows in the mirror, not yet in the host's.
19705                        p.cpu_stored += cuts[ln].0;
19706                        // A sealed layer leaves no mirror row to pull.
19707                        if ln == 0 && p.o1.is_none() {
19708                            attn_layers.push((*li, cpu_stored));
19709                        }
19710                        st.push(Step::Attn(l, p));
19711                    }
19712                    step_layer.push(*li);
19713                }
19714            }
19715        }
19716        // The outputs of the layers a DFlash drafter reads are kept on the way
19717        // (one graph only: a chunk in halves through the Neural Engine keeps none).
19718        let taps: Vec<usize> = match &self.dflash {
19719            Some(d) if !relay => d.g.taps.clone(),
19720            _ => Vec::new(),
19721        };
19722        let tap_slot: Vec<Option<usize>> = step_layer.iter().map(|l| taps.iter().position(|t| t == l)).collect();
19723        let tapped = std::sync::atomic::AtomicUsize::new(0);
19724        // One half's layers in order; `Err` tells whether a command was already committed.
19725        let gc = gcfg.as_ref();
19726        let walk = |g: &mut VerifyGraph, steps: &[Step<'_>]| -> Result<(), bool> {
19727            for (i, step) in steps.iter().enumerate() {
19728                let ok = match step {
19729                    Step::Gdn(l, state) => match gc {
19730                        Some(gc) => g.encode_gdn_run_b(std::slice::from_ref(*l), &[*state], gc),
19731                        None => false,
19732                    },
19733                    Step::Attn(l, p) => g.encode_attn_b(l, p),
19734                };
19735                if !ok {
19736                    return Err(i > 0);
19737                }
19738                if let Some(slot) = tap_slot.get(i).copied().flatten() {
19739                    if g.tap(slot, taps.len()) {
19740                        tapped.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
19741                    }
19742                }
19743            }
19744            Ok(())
19745        };
19746        let refused = |started: bool| if hard && started { MetalRowsRun::Failed } else { MetalRowsRun::Declined };
19747        if relay {
19748            let (first, second) = lanes.split_at_mut(1);
19749            let (sa, sb) = (&steps[0], &steps[1]);
19750            let (ra, rb) = std::thread::scope(|sc| {
19751                let other = sc.spawn(|| {
19752                    let r = walk(&mut second[0], sb);
19753                    if r.is_err() {
19754                        // The first half must not wait for this one's turn on the ANE.
19755                        crate::gpu_metal::ane::retire("a half of the chunk stopped");
19756                    }
19757                    r
19758                });
19759                let r = walk(&mut first[0], sa);
19760                if r.is_err() {
19761                    gate.fail();
19762                }
19763                (r, other.join().unwrap_or(Err(true)))
19764            });
19765            if ra.is_err() || rb.is_err() {
19766                return MetalRowsRun::Failed;
19767            }
19768        } else if let Err(started) = walk(&mut lanes[0], &steps[0]) {
19769            return refused(started);
19770        }
19771        drop(steps);
19772        if let (Some(lm), Some((_, final_norm, _))) = (lm, spec.as_ref()) {
19773            if !lanes[0].encode_lm_head_b(final_norm, lm) {
19774                return refused(true);
19775            }
19776            // The device argmax is an OPTIMISATION, never a reason to
19777            // decline the round: if it will not encode, drop it and read
19778            // the logits plane back the old way (the head is encoded
19779            // either way, so the rows are there).
19780            if let Some((n, _)) = argmax_out.as_ref() {
19781                if !lanes[0].encode_argmax_b(*n) {
19782                    argmax_out = None;
19783                }
19784            }
19785        }
19786        spec_stamp("v.enc");
19787        for g in lanes.iter_mut() {
19788            if !g.sync() {
19789                return MetalRowsRun::Failed;
19790            }
19791        }
19792        spec_stamp("v.gpu");
19793        match (spec, argmax_out) {
19794            (Some(_), Some((_, ids))) => {
19795                ids.resize(b, 0);
19796                if !lanes[0].read_argmax(ids) {
19797                    return MetalRowsRun::Failed;
19798                }
19799                spec_stamp("v.am");
19800            }
19801            (Some((lm, _, logits)), None) => {
19802                logits.resize(b * lm.1, 0.0);
19803                if !lanes[0].read_logits(logits) {
19804                    return MetalRowsRun::Failed;
19805                }
19806                spec_stamp("v.lg");
19807            }
19808            (None, _) => {}
19809        }
19810        for (g, &(r0, n)) in lanes.iter().zip(&cuts) {
19811            if !g.read_hidden(&mut hiddens[r0 * hs..(r0 + n) * hs]) {
19812                return MetalRowsRun::Failed;
19813            }
19814        }
19815        spec_stamp("v.hid");
19816        // The tapped rows, a row's layers joined: a prompt's rows are context at
19817        // once, a verify's wait for the round to say which of them it keeps.
19818        self.dflash_rows = None;
19819        if !taps.is_empty() && tapped.load(std::sync::atomic::Ordering::Relaxed) == taps.len() && lanes.len() == 1 {
19820            let nt = taps.len();
19821            let mut raw = vec![0f32; nt * b * hs];
19822            if lanes[0].read_taps(&mut raw) {
19823                let mut joined = vec![0f32; b * nt * hs];
19824                for s in 0..nt {
19825                    for r in 0..b {
19826                        joined[(r * nt + s) * hs..][..hs].copy_from_slice(&raw[(s * b + r) * hs..][..hs]);
19827                    }
19828                }
19829                if prefill {
19830                    if let Some(d) = self.dflash.as_mut() {
19831                        d.queue_context(pos0, &joined, self.pool.as_deref());
19832                    }
19833                } else {
19834                    self.dflash_rows = Some((pos0, joined));
19835                }
19836                spec_stamp("v.taps");
19837            }
19838        }
19839        // The last half's graph: the layers' states are the chunk's.
19840        let graph = lanes.pop().unwrap();
19841        MetalRowsRun::Completed(MetalVerifyPending {
19842            graph,
19843            gdn_layers,
19844            attn_layers,
19845        })
19846    }
19847
19848    /// Native-Metal twin of `try_batch_graph_wgpu`: the b rows through the
19849    /// whole model on the `VerifyGraph` (one submit), the head folded in
19850    /// when `spec` asks; `hiddens` come back as the last layer's output
19851    /// rows, `spec.2` as `[b][lm_rows]` logits. The graph is parked in
19852    /// `metal_verify` for `metal_verify_commit`.
19853    #[cfg(target_os = "macos")]
19854    fn try_batch_graph_metal(
19855        &mut self,
19856        hiddens: &mut [f32],
19857        positions: &[usize],
19858        b: usize,
19859        spec: Option<((usize, usize, usize), &[f32], &mut Vec<f32>)>,
19860        argmax_out: Option<(usize, &mut Vec<u32>)>,
19861    ) -> crate::gpu::BatchGraphOutcome {
19862        let _t0 = std::time::Instant::now();
19863        if positions.len() != b
19864            || self.prompt_mrope.is_some()
19865            || self.value_blend.is_some()
19866            || positions.windows(2).any(|w| w[1] != w[0] + 1)
19867            || hiddens.len() != b * self.hidden_size
19868        {
19869            return crate::gpu::BatchGraphOutcome::Declined;
19870        }
19871        let pending = match self.metal_rows_run(hiddens, positions[0], b, false, spec, argmax_out) {
19872            MetalRowsRun::Declined => return crate::gpu::BatchGraphOutcome::Declined,
19873            MetalRowsRun::Failed => return crate::gpu::BatchGraphOutcome::Failed,
19874            MetalRowsRun::Completed(pending) => pending,
19875        };
19876        if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
19877            eprintln!(
19878                "metal-verify: {:.1} ms | b={b}",
19879                _t0.elapsed().as_secs_f64() * 1e3
19880            );
19881        }
19882        self.metal_verify = Some(pending);
19883        crate::gpu::BatchGraphOutcome::Completed
19884    }
19885
19886    /// Batched prefill on the Metal rows graph: `ids` (≤ 512) at
19887    /// `start_pos..`, states written in place, K/V rows appended to the
19888    /// CPU caches; optional final norm/head logits are returned in `spec`.
19889    /// Declined means no command buffer was admitted; Failed is terminal.
19890    #[cfg(target_os = "macos")]
19891    fn prefill_rows_metal(
19892        &mut self,
19893        ids: &[u32],
19894        start_pos: usize,
19895        spec: Option<((usize, usize, usize), &[f32], &mut Vec<f32>)>,
19896    ) -> MetalPrefillOutcome {
19897        let b = ids.len();
19898        if b == 0 || b > 512 {
19899            return MetalPrefillOutcome::Declined;
19900        }
19901        let hs = self.hidden_size;
19902        let mut hiddens = vec![0f32; b * hs];
19903        for (j, &id) in ids.iter().enumerate() {
19904            let e = self.embed_single(id);
19905            hiddens[j * hs..(j + 1) * hs].copy_from_slice(&e);
19906        }
19907        self.prefill_hiddens_metal(hiddens, start_pos, spec)
19908    }
19909
19910    /// Ready prompt rows (`b <= 512`) through the rows graph.
19911    #[cfg(target_os = "macos")]
19912    fn prefill_hiddens_metal(
19913        &mut self,
19914        mut hiddens: Vec<f32>,
19915        start_pos: usize,
19916        spec: Option<((usize, usize, usize), &[f32], &mut Vec<f32>)>,
19917    ) -> MetalPrefillOutcome {
19918        let b = hiddens.len() / self.hidden_size;
19919        METAL_PREFILL_CHUNKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
19920        let with_head = spec.is_some();
19921        let mut pending = match self.metal_rows_run(&mut hiddens, start_pos, b, true, spec, None) {
19922            MetalRowsRun::Declined => return MetalPrefillOutcome::Declined,
19923            MetalRowsRun::Failed => {
19924                METAL_PREFILL_ERRORS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
19925                return MetalPrefillOutcome::Failed;
19926            }
19927            MetalRowsRun::Completed(pending) => pending,
19928        };
19929        // states are final: copy them to the owners
19930        let idxs = pending.gdn_layers.clone();
19931        let mut outs: Vec<&mut [f32]> = self
19932            .kv_cache
19933            .layers
19934            .iter_mut()
19935            .enumerate()
19936            .filter(|(i, _)| idxs.binary_search(i).is_ok())
19937            .map(|(_, l)| l.linear_state.as_mut_slice())
19938            .collect();
19939        if !pending.graph.finish_states(&mut outs) {
19940            METAL_PREFILL_ERRORS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
19941            return MetalPrefillOutcome::Failed;
19942        }
19943        let (nkv, hd) = (self.num_kv_heads, self.head_dim);
19944        // Read every layer before mutating any CPU cache.  A missing mirror
19945        // row is a terminal graph failure, not a reason to append a partial
19946        // prefix and replay the remainder serially.
19947        let mut rows = Vec::with_capacity(pending.attn_layers.len());
19948        for (li, cpu_stored) in &pending.attn_layers {
19949            let mut kbuf = vec![0f32; b * nkv * hd];
19950            let mut vbuf = vec![0f32; b * nkv * hd];
19951            if !crate::gpu_metal::kv_mirror_read_rows(
19952                self.graph_kv_id,
19953                *li,
19954                nkv,
19955                hd,
19956                *cpu_stored,
19957                b,
19958                &mut kbuf,
19959                &mut vbuf,
19960            ) {
19961                METAL_PREFILL_ERRORS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
19962                return MetalPrefillOutcome::Failed;
19963            }
19964            rows.push((*li, *cpu_stored, kbuf, vbuf));
19965        }
19966        for (li, cpu_stored, kbuf, vbuf) in rows {
19967            let cache = &mut self.kv_cache.layers[li];
19968            for r in 0..b {
19969                cache.append(
19970                    &kbuf[r * nkv * hd..(r + 1) * nkv * hd],
19971                    &vbuf[r * nkv * hd..(r + 1) * nkv * hd],
19972                    &[],
19973                );
19974            }
19975            crate::gpu_metal::kv_mirror_set_stored(self.graph_kv_id, li, cpu_stored + b);
19976        }
19977        METAL_PREFILL_ROWS.fetch_add(b as u64, std::sync::atomic::Ordering::Relaxed);
19978        if with_head {
19979            METAL_PREFILL_HEAD_ROWS.fetch_add(b as u64, std::sync::atomic::Ordering::Relaxed);
19980        }
19981        // Every layer appended the chunk: sliding layers keep their tails only.
19982        self.swa_trim_tails();
19983        MetalPrefillOutcome::Completed(hiddens)
19984    }
19985
19986    #[cfg(target_os = "macos")]
19987    fn prefill_batch_metal(&mut self, ids: &[u32], start_pos: usize) -> MetalPrefillOutcome {
19988        self.prefill_rows_metal(ids, start_pos, None)
19989    }
19990
19991    /// Exact teacher-forced NLL through the ordinary Metal rows graph.  This
19992    /// is intentionally separate from the serial TokenGraph scorer: every
19993    /// chunk owns a real b-row graph/head completion and the recurrent/KV
19994    /// handoff is committed before the next chunk begins.
19995    #[cfg(target_os = "macos")]
19996    fn nll_batch_metal(&mut self, ids: &[u32], start: usize) -> MetalBatchNllOutcome {
19997        if ids.len() < 2 || self.o1_active() || self.head_clusters.is_some() {
19998            return MetalBatchNllOutcome::Declined;
19999        }
20000        let Some(lm) = self.weights.lm_head.metal_graph_parts() else {
20001            return MetalBatchNllOutcome::Declined;
20002        };
20003        let chunk = std::env::var("CMF_METAL_PREFILL_CHUNK")
20004            .ok()
20005            .and_then(|v| v.parse::<usize>().ok())
20006            .filter(|&v| (1..=512).contains(&v))
20007            .unwrap_or(32);
20008        let final_norm = self.weights.final_norm.clone();
20009        let mut nll = 0.0f64;
20010        let mut count = 0usize;
20011        let mut pos = 0usize;
20012        let mut completed = 0usize;
20013        while pos < ids.len() {
20014            let end = (pos + chunk).min(ids.len());
20015            let mut logits = Vec::new();
20016            let outcome =
20017                self.prefill_rows_metal(&ids[pos..end], pos, Some((lm, &final_norm, &mut logits)));
20018            match outcome {
20019                MetalPrefillOutcome::Declined => {
20020                    return if completed == 0 {
20021                        MetalBatchNllOutcome::Declined
20022                    } else {
20023                        MetalBatchNllOutcome::Failed(format!(
20024                            "ordinary Metal NLL batch declined after {completed} chunks"
20025                        ))
20026                    };
20027                }
20028                MetalPrefillOutcome::Failed => {
20029                    return MetalBatchNllOutcome::Failed(
20030                        "ordinary Metal NLL batch failed after admission".to_string(),
20031                    );
20032                }
20033                MetalPrefillOutcome::Completed(_) => {}
20034            }
20035            completed += 1;
20036            let vocab = self.vocab_size.min(lm.1);
20037            if logits.len() != (end - pos) * lm.1 || vocab == 0 {
20038                return MetalBatchNllOutcome::Failed(
20039                    "ordinary Metal NLL head returned an invalid shape".to_string(),
20040                );
20041            }
20042            for row in 0..(end - pos) {
20043                let absolute = pos + row;
20044                if absolute < start || absolute + 1 >= ids.len() {
20045                    continue;
20046                }
20047                let lg = &mut logits[row * lm.1..row * lm.1 + vocab];
20048                if let Some(mu) = self.logit_multiplier {
20049                    for v in lg.iter_mut() {
20050                        *v *= mu;
20051                    }
20052                }
20053                if let Some(c) = self.final_softcap {
20054                    softcap_in_place(lg, c, self.pool.as_deref());
20055                }
20056                let target = ids[absolute + 1] as usize;
20057                if target >= vocab {
20058                    return MetalBatchNllOutcome::Failed(format!(
20059                        "target token {target} exceeds Metal head rows {vocab}"
20060                    ));
20061                }
20062                let max = lg.iter().fold(f32::NEG_INFINITY, |m, &v| m.max(v));
20063                let lse: f64 = lg
20064                    .iter()
20065                    .map(|&v| ((v - max) as f64).exp())
20066                    .sum::<f64>()
20067                    .ln()
20068                    + max as f64;
20069                nll += lse - lg[target] as f64;
20070                count += 1;
20071            }
20072            pos = end;
20073        }
20074        MetalBatchNllOutcome::Completed(nll, count)
20075    }
20076
20077    /// Commit a Metal verify round: replay the GDN recurrences over the
20078    /// `a + 1` accepted positions into the CPU states, append the accepted
20079    /// K/V rows from the mirrors to the CPU caches, re-point the mirrors.
20080    #[cfg(target_os = "macos")]
20081    fn metal_verify_commit(&mut self, a: usize) -> bool {
20082        let Some(mut pending) = self.metal_verify.take() else {
20083            return false;
20084        };
20085        let n = a + 1;
20086        // encode order == ascending layer order (the plan walks 0..layers)
20087        let idxs = pending.gdn_layers.clone();
20088        let mut outs: Vec<&mut [f32]> = self
20089            .kv_cache
20090            .layers
20091            .iter_mut()
20092            .enumerate()
20093            .filter(|(i, _)| idxs.binary_search(i).is_ok())
20094            .map(|(_, l)| l.linear_state.as_mut_slice())
20095            .collect();
20096        if !pending.graph.commit(n, &mut outs) {
20097            return false;
20098        }
20099        spec_stamp("c.replay");
20100        let (nkv, hd) = (self.num_kv_heads, self.head_dim);
20101        // Read every layer before mutating any CPU cache.  Missing rows are
20102        // terminal after the replay has executed; never append a partial KV
20103        // prefix and continue on a serial path.
20104        let mut rows = Vec::with_capacity(pending.attn_layers.len());
20105        for (li, cpu_stored) in &pending.attn_layers {
20106            let mut kbuf = vec![0f32; n * nkv * hd];
20107            let mut vbuf = vec![0f32; n * nkv * hd];
20108            if !crate::gpu_metal::kv_mirror_read_rows(
20109                self.graph_kv_id,
20110                *li,
20111                nkv,
20112                hd,
20113                *cpu_stored,
20114                n,
20115                &mut kbuf,
20116                &mut vbuf,
20117            ) {
20118                return false;
20119            }
20120            rows.push((*li, *cpu_stored, kbuf, vbuf));
20121        }
20122        for (li, cpu_stored, kbuf, vbuf) in rows {
20123            let cache = &mut self.kv_cache.layers[li];
20124            for r in 0..n {
20125                cache.append(
20126                    &kbuf[r * nkv * hd..(r + 1) * nkv * hd],
20127                    &vbuf[r * nkv * hd..(r + 1) * nkv * hd],
20128                    &[],
20129                );
20130            }
20131            crate::gpu_metal::kv_mirror_set_stored(self.graph_kv_id, li, cpu_stored + n);
20132        }
20133        spec_stamp("c.kv");
20134        true
20135    }
20136
20137    /// The round's warm-ups as ONE b-row graph run over the MTP block on
20138    /// Metal: `pairs` = (trunk hidden, next token) at consecutive positions
20139    /// from `first_pos`; the block's input projection is folded in. This
20140    /// half encodes and SUBMITS (no wait); `mtp_warm_batch_finish` waits
20141    /// and pulls the appended K/V rows into the CPU MTP cache. None = the
20142    /// graph declined (nothing submitted, nothing appended).
20143    #[cfg(target_os = "macos")]
20144    fn mtp_warm_batch_submit(
20145        &mut self,
20146        m: &mut MtpModule,
20147        pairs: &[(&[f32], u32)],
20148        first_pos: usize,
20149    ) -> Option<MetalWarmPending> {
20150        use crate::gpu_metal::{AttnDeviceParams, AttnGpuLayer, GraphDims, MetalFfn, VerifyGraph};
20151        let first_pos = first_pos.saturating_sub(self.mtp_pos_base);
20152        let b = pairs.len();
20153        if b == 0 || b > 512 || m.kv.mode != crate::kv_cache::KvMode::F32 || m.kv.o1.is_some() {
20154            return None;
20155        }
20156        let AttnKind::Full {
20157            wq,
20158            wk,
20159            wv,
20160            wo,
20161            q_norm,
20162            k_norm,
20163            output_gate,
20164            softplus_gate: None,
20165            bias: None,
20166        } = &m.layer.attn
20167        else {
20168            return None;
20169        };
20170        let FfnKind::Dense(d) = &m.layer.ffn else {
20171            return None;
20172        };
20173        if !d.segs.is_empty() {
20174            return None;
20175        }
20176        let (Some(pq), Some(pk), Some(pv), Some(po)) =
20177            (wq.q1_parts(), wk.q1_parts(), wv.q1_parts(), wo.q1_parts())
20178        else {
20179            return None;
20180        };
20181        let (Some(g), Some(u), Some(dn)) = (
20182            d.gate_proj.q1_parts(),
20183            d.up_proj.q1_parts(),
20184            d.down_proj.q1_parts(),
20185        ) else {
20186            return None;
20187        };
20188        let Some(eh) = m.eh_proj.q1_parts() else {
20189            return None;
20190        };
20191        let QTensor::Mapped { model, .. } = wq else {
20192            return None;
20193        };
20194        let model = model.clone();
20195        let hs = self.hidden_size;
20196        // [enorm(embed(tok)); hnorm(hidden)] rows
20197        let mut cat = vec![0f32; b * 2 * hs];
20198        for (j, (h, tok)) in pairs.iter().enumerate() {
20199            let e = self.embed_single(*tok);
20200            let (ce, ch) = cat[j * 2 * hs..(j + 1) * 2 * hs].split_at_mut(hs);
20201            inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, ce);
20202            inference::rms_norm_into(h, &m.hnorm, self.rms_eps, self.norm_style, ch);
20203        }
20204        let dims = GraphDims {
20205            hidden: hs,
20206            eps: self.rms_eps as f32,
20207            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
20208        };
20209        spec_stamp("w.cat");
20210        let Some(mut graph) = VerifyGraph::new_via_proj(&model, dims, eh, &cat, b) else {
20211            return None;
20212        };
20213        spec_stamp("w.new");
20214        let l = AttnGpuLayer {
20215            mhc: None,
20216            attn_norm: &m.layer.input_norm,
20217            post_norm: &m.layer.post_norm,
20218            wq: pq,
20219            wk: pk,
20220            wv: pv,
20221            wo: po,
20222            ffn: MetalFfn::Dense {
20223                gate: g,
20224                up: u,
20225                down: dn,
20226                act: (d.act == Act::Gelu) as u8,
20227            },
20228            attn_out_norm: None,
20229            ffn_out_norm: None,
20230            layer_scale: None,
20231        };
20232        let (nh, nkv, hd, rd) = (
20233            self.num_heads,
20234            self.num_kv_heads,
20235            self.head_dim,
20236            self.rotary_dim,
20237        );
20238        let inv_freq = self.inv_freq.clone();
20239        let cpu_stored;
20240        {
20241            let cache = &m.kv;
20242            let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
20243            let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
20244            cpu_stored = cpu_k[0].len() / hd;
20245            // The cache may LAG the position (rows nobody warmed): the
20246            // pairs land at cpu_stored.. with their true RoPE positions
20247            // first_pos.., exactly what the one-by-one warm does. A cache
20248            // AHEAD of the position is a real inconsistency.
20249            if cpu_stored > first_pos {
20250                spec_stamp("w.decl");
20251                return None;
20252            }
20253            let p = AttnDeviceParams {
20254                kv_id: self.mtp_kv_id(),
20255                layer: Self::MTP_LAYER_BASE,
20256                nh,
20257                nkv,
20258                hd,
20259                rd,
20260                position: first_pos,
20261                scale: self.attn_scale,
20262                eps: self.rms_eps as f32,
20263                gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
20264                late_qk_norm: self.qk_norm_after_rope,
20265                output_gate: *output_gate,
20266                q_norm: q_norm.as_deref(),
20267                k_norm: k_norm.as_deref(),
20268                inv_freq: &inv_freq,
20269                rope_scale: self.rope_scale,
20270                cpu_k,
20271                cpu_v,
20272                cpu_stored,
20273                cpu_gen: cache.generation(),
20274                o1: None,
20275                window: None,
20276                softmax_sink: None,
20277                head_gate: None,
20278                v_norm: false,
20279                dash: None,
20280            };
20281            if !graph.attn_ok(&l, &p) || !graph.encode_attn_b(&l, &p) {
20282                return None;
20283            }
20284        }
20285        spec_stamp("w.enc");
20286        if !graph.submit() {
20287            return None;
20288        }
20289        spec_stamp("w.sub");
20290        Some(MetalWarmPending {
20291            graph,
20292            cpu_stored,
20293            b,
20294        })
20295    }
20296
20297    /// Submit and finish in one call (the prefill's MTP warm-up, where
20298    /// nothing runs in between).
20299    #[cfg(target_os = "macos")]
20300    fn mtp_warm_batch_metal(
20301        &mut self,
20302        m: &mut MtpModule,
20303        pairs: &[(&[f32], u32)],
20304        first_pos: usize,
20305    ) -> bool {
20306        match self.mtp_warm_batch_submit(m, pairs, first_pos) {
20307            Some(p) => self.mtp_warm_batch_finish(m, p),
20308            None => false,
20309        }
20310    }
20311
20312    /// Second half of the batched warm-up: wait for the submitted graph,
20313    /// pull its b appended K/V rows into the CPU MTP cache, re-point the
20314    /// mirror. False = the command buffer failed or the rows are missing
20315    /// (nothing appended; the caller falls back to the one-by-one warm).
20316    #[cfg(target_os = "macos")]
20317    fn mtp_warm_batch_finish(&mut self, m: &mut MtpModule, pending: MetalWarmPending) -> bool {
20318        let MetalWarmPending {
20319            mut graph,
20320            cpu_stored,
20321            b,
20322        } = pending;
20323        let (nkv, hd) = (self.num_kv_heads, self.head_dim);
20324        if !graph.sync() {
20325            return false;
20326        }
20327        spec_stamp("w.gpu");
20328        let mut kbuf = vec![0f32; b * nkv * hd];
20329        let mut vbuf = vec![0f32; b * nkv * hd];
20330        if !crate::gpu_metal::kv_mirror_read_rows(
20331            self.mtp_kv_id(),
20332            Self::MTP_LAYER_BASE,
20333            nkv,
20334            hd,
20335            cpu_stored,
20336            b,
20337            &mut kbuf,
20338            &mut vbuf,
20339        ) {
20340            return false;
20341        }
20342        for r in 0..b {
20343            m.kv.append(
20344                &kbuf[r * nkv * hd..(r + 1) * nkv * hd],
20345                &vbuf[r * nkv * hd..(r + 1) * nkv * hd],
20346                &[],
20347            );
20348        }
20349        crate::gpu_metal::kv_mirror_set_stored(
20350            self.mtp_kv_id(),
20351            Self::MTP_LAYER_BASE,
20352            cpu_stored + b,
20353        );
20354        spec_stamp("w.kv");
20355        true
20356    }
20357
20358    /// A committed token id from the high table (Cyrillic, CJK and the
20359    /// like sit above 131072 in Qwen's vocabulary; Latin subwords past
20360    /// the 65536 cut are rare enough to lose as rejected drafts) switches
20361    /// the draft to the full head for the next 16 tokens; other ids count
20362    /// down. On an M4 the full 660 MB head costs 5.5 ms a draft step
20363    /// against 1.4 for the shortlist, so the streak is kept short.
20364    pub(crate) fn note_draft_id(&mut self, id: u32) {
20365        let cut = Self::draft_vocab_rows(usize::MAX).max(131_072);
20366        if (id as usize) >= cut {
20367            self.draft_full_streak = 16;
20368        } else {
20369            self.draft_full_streak = self.draft_full_streak.saturating_sub(1);
20370        }
20371    }
20372
20373    /// The draft head's rows for the next step: the shortlist, or the full
20374    /// head while `draft_full_streak` runs.
20375    fn draft_head_rows(&self, head_rows: usize) -> usize {
20376        if self.draft_full_streak > 0 {
20377            head_rows
20378        } else {
20379            Self::draft_vocab_rows(head_rows)
20380        }
20381    }
20382
20383    /// Draft-head shortlist size: `CMF_DRAFT_VOCAB` rows (default 65536,
20384    /// capped at the head; 0 = full head).
20385    fn draft_vocab_rows(head_rows: usize) -> usize {
20386        static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
20387        let n = *N.get_or_init(|| {
20388            std::env::var("CMF_DRAFT_VOCAB")
20389                .ok()
20390                .and_then(|v| v.parse().ok())
20391                .unwrap_or(65536)
20392        });
20393        if n == 0 { head_rows } else { n.min(head_rows) }
20394    }
20395
20396    /// One MTP block step on the native Metal token graph: block input on
20397    /// the host, the attention layer + FFN device-resident over the MTP
20398    /// mirror, the head folded in when `want_logits`. The appended K/V row
20399    /// is pulled into the CPU MTP cache (owner of record) after the sync.
20400    #[cfg(target_os = "macos")]
20401    fn mtp_step_metal(
20402        &mut self,
20403        m: &mut MtpModule,
20404        hidden: &[f32],
20405        next_token: u32,
20406        position: usize,
20407        want_logits: bool,
20408    ) -> Option<(Vec<f32>, Vec<f32>)> {
20409        use crate::gpu_metal::{AttnDeviceParams, AttnGpuLayer, GraphDims, MetalFfn, TokenGraph};
20410        let position = position.saturating_sub(self.mtp_pos_base);
20411        if std::env::var("CMF_MTP_GRAPH").as_deref() == Ok("0")
20412            || !crate::gpu::q1_force()
20413            || !crate::gpu::enabled_here()
20414            || self.attn_softcap > 0.0
20415            || self.attention_heads_per_layer.is_some()
20416            || m.kv.mode != crate::kv_cache::KvMode::F32
20417            || m.kv.o1.is_some()
20418        {
20419            return None;
20420        }
20421        let AttnKind::Full {
20422            wq,
20423            wk,
20424            wv,
20425            wo,
20426            q_norm,
20427            k_norm,
20428            output_gate,
20429            softplus_gate: None,
20430            bias: None,
20431        } = &m.layer.attn
20432        else {
20433            return None;
20434        };
20435        let FfnKind::Dense(d) = &m.layer.ffn else {
20436            return None;
20437        };
20438        if d.act != Act::Silu || !d.segs.is_empty() {
20439            return None;
20440        }
20441        let (pq, pk, pv, po) = (
20442            wq.q1_parts()?,
20443            wk.q1_parts()?,
20444            wv.q1_parts()?,
20445            wo.q1_parts()?,
20446        );
20447        let (g, u, dn) = (
20448            d.gate_proj.q1_parts()?,
20449            d.up_proj.q1_parts()?,
20450            d.down_proj.q1_parts()?,
20451        );
20452        let QTensor::Mapped { model, .. } = wq else {
20453            return None;
20454        };
20455        let model = model.clone();
20456        let lm = if want_logits {
20457            Some(self.weights.lm_head.q1_parts()?)
20458        } else {
20459            None
20460        };
20461        let dims = GraphDims {
20462            hidden: self.hidden_size,
20463            eps: self.rms_eps as f32,
20464            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
20465        };
20466        // The block input `eh_proj · [enorm(e); hnorm(h)]` rides in the
20467        // graph (one submit a step); the host per-op matvec if it cannot.
20468        let hs = self.hidden_size;
20469        let mut x = vec![0f32; hs];
20470        // Let an eligible q4tp MTP draft use the measured masked-nibble
20471        // matvec.  Unlike fused epilogues, this reduces the draft's
20472        // projection work without changing its residual-update schedule;
20473        // the target verifier remains the authority over emitted tokens.
20474        // The guard keeps `CMF_METAL_MVFAST=0` as an immediate rollback
20475        // switch and restores the caller's setting on every early return.
20476        let _mtp_fast = crate::gpu_metal::MvFastGuard::set_bits(
20477            crate::gpu_metal::DENSE_MV,
20478        );
20479        let mut graph = TokenGraph::new(&model, dims, &x)?;
20480        let mut folded = false;
20481        if let Some(eh) = m.eh_proj.q1_parts() {
20482            let e = self.embed_single(next_token);
20483            let mut cat = vec![0.0f32; 2 * hs];
20484            let (cat_e, cat_h) = cat.split_at_mut(hs);
20485            inference::rms_norm_into(&e, &m.enorm, self.rms_eps, self.norm_style, cat_e);
20486            inference::rms_norm_into(hidden, &m.hnorm, self.rms_eps, self.norm_style, cat_h);
20487            folded = graph.encode_input_proj(eh, &cat);
20488        }
20489        if !folded {
20490            x = self.mtp_block_input(m, hidden, next_token);
20491            graph = TokenGraph::new(&model, dims, &x)?;
20492        }
20493        spec_stamp("d.in");
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        {
20520            let cache = &m.kv;
20521            let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
20522            let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
20523            let cpu_stored = cpu_k[0].len() / hd;
20524            let p = AttnDeviceParams {
20525                kv_id: self.mtp_kv_id(),
20526                layer: Self::MTP_LAYER_BASE,
20527                nh,
20528                nkv,
20529                hd,
20530                rd,
20531                position,
20532                scale: self.attn_scale,
20533                eps: self.rms_eps as f32,
20534                gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
20535                late_qk_norm: self.qk_norm_after_rope,
20536                output_gate: *output_gate,
20537                q_norm: q_norm.as_deref(),
20538                k_norm: k_norm.as_deref(),
20539                inv_freq: &inv_freq,
20540                rope_scale: self.rope_scale,
20541                cpu_k,
20542                cpu_v,
20543                cpu_stored,
20544                cpu_gen: cache.generation(),
20545                o1: None,
20546                window: None,
20547                softmax_sink: None,
20548                head_gate: None,
20549                v_norm: false,
20550                dash: None,
20551            };
20552            if !graph.attn_device_ok(&l, &p) || !graph.encode_attn_device(&l, &p) {
20553                return None;
20554            }
20555        }
20556        // The draft's head over a vocabulary SHORTLIST (the first
20557        // CMF_DRAFT_VOCAB rows — BPE ids run roughly by merge rank, so the
20558        // low ids carry the mass): the verify keeps the full head, so a true
20559        // token past the cut is only a rejected draft, never a wrong token.
20560        // 662 MB a step on Qwen3.8 becomes 170 MB at 65536.
20561        let draft_rows = if let Some(lm) = lm {
20562            self.draft_head_rows(lm.1)
20563        } else {
20564            0
20565        };
20566        if let Some(lm) = lm {
20567            if !graph.lm_head_ok(lm) {
20568                return None;
20569            }
20570            if draft_rows < lm.1 {
20571                if !graph.encode_lm_head_part(&m.final_norm, lm, draft_rows) {
20572                    return None;
20573                }
20574            } else {
20575                graph.encode_lm_head(&m.final_norm, lm);
20576            }
20577        }
20578        spec_stamp("d.enc");
20579        if graph.sync_checked().is_err() {
20580            return None;
20581        }
20582        spec_stamp("d.gpu");
20583        let mut logits = Vec::new();
20584        if let Some(lm) = lm {
20585            let n_read = draft_rows.min(lm.1).min(self.vocab_size);
20586            logits = attention::take_buf(n_read);
20587            graph.read_logits(&mut logits);
20588            // ids past the shortlist: never drafted (−∞ in every chain)
20589            pad_mtp_draft_logits(&mut logits, self.vocab_size);
20590        }
20591        graph.finish(&mut x);
20592        let mut krow = attention::take_buf(nkv * hd);
20593        let mut vrow = attention::take_buf(nkv * hd);
20594        if crate::gpu_metal::kv_mirror_read_last(
20595            self.mtp_kv_id(),
20596            Self::MTP_LAYER_BASE,
20597            nkv,
20598            hd,
20599            &mut krow,
20600            &mut vrow,
20601        ) {
20602            m.kv.append(&krow, &vrow, &[]);
20603        }
20604        attention::recycle_buf(&mut krow);
20605        attention::recycle_buf(&mut vrow);
20606        spec_stamp("d.rd");
20607        Some((logits, x))
20608    }
20609
20610    /// `CMF_MTP_CHAIN=0` keeps the per-step draft (one submit and one
20611    /// host round trip per MTP step); the default drafts the whole chain
20612    /// in one command buffer when the round is plain greedy.
20613    ///
20614    /// Measured on an M4 (24 GB), Qwen3.8-27B q4tp, P3 at 160 tokens,
20615    /// k=7, six runs per arm alternating inside one lock window — the
20616    /// round's draft phase (median over the 34 rounds of a run) is
20617    /// 34.5 ms per round old against 30.1 new, i.e. 4.93 → 4.31 ms per
20618    /// draft step. That is the whole prize: the 7 submits cost ~0.6 ms
20619    /// each in host and submit latency and nothing else changes —
20620    /// acceptance (3.41 of 7) and tokens per round (4.41) are identical,
20621    /// and the round is 289 → 285 ms, decode 13.8 → 14.0 tok/s.
20622    fn mtp_chain_on() -> bool {
20623        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
20624        *ON.get_or_init(|| std::env::var("CMF_MTP_CHAIN").as_deref() != Ok("0"))
20625    }
20626
20627    /// The round's k greedy drafts as ONE command buffer on Metal: the MTP
20628    /// block k times back to back, each step's token embedding gathered
20629    /// on the device from the argmax the step before it wrote, the head
20630    /// over the round's shortlist (or the full head during a full-head
20631    /// streak — decided once, before the chain, exactly as the per-step
20632    /// path decides it per step, since `draft_full_streak` only moves on
20633    /// a commit). One wait, then the k ids and the k appended K/V rows
20634    /// come back; the CPU MTP cache ends where k `mtp_step_metal` calls
20635    /// would have left it. `Err(false)` = declined before anything was
20636    /// committed (the per-step path takes the round); `Err(true)` = the
20637    /// command buffer failed after commit.
20638    #[cfg(target_os = "macos")]
20639    fn mtp_draft_chain_metal(
20640        &mut self,
20641        m: &mut MtpModule,
20642        hidden: &[f32],
20643        t_next: u32,
20644        position: usize,
20645        k: usize,
20646    ) -> Result<Vec<u32>, bool> {
20647        use crate::gpu_metal::{AttnDeviceParams, AttnGpuLayer, GraphDims, MetalFfn, TokenGraph};
20648        let position = position.saturating_sub(self.mtp_pos_base);
20649        if k == 0
20650            || k > 64
20651            || !Self::mtp_chain_on()
20652            || std::env::var("CMF_MTP_GRAPH").as_deref() == Ok("0")
20653            || !crate::gpu::q1_force()
20654            || !crate::gpu::enabled_here()
20655            || self.attn_softcap > 0.0
20656            || self.attention_heads_per_layer.is_some()
20657            || m.kv.mode != crate::kv_cache::KvMode::F32
20658            || m.kv.o1.is_some()
20659            // the chain gathers embeddings itself: only the plain table
20660            || self.dsv4.is_some()
20661            || self.dsv41.is_some()
20662            || self.dory.is_some()
20663            || self.qwen4_exp.is_some()
20664            || self.glm5_next.is_some()
20665            || self.hy4.is_some()
20666            || self.maxwell.is_some()
20667            || self.inkling.is_some()
20668            || self.per_token_stack()
20669        {
20670            return Err(false);
20671        }
20672        let AttnKind::Full {
20673            wq,
20674            wk,
20675            wv,
20676            wo,
20677            q_norm,
20678            k_norm,
20679            output_gate,
20680            softplus_gate: None,
20681            bias: None,
20682        } = &m.layer.attn
20683        else {
20684            return Err(false);
20685        };
20686        let FfnKind::Dense(d) = &m.layer.ffn else {
20687            return Err(false);
20688        };
20689        if d.act != Act::Silu || !d.segs.is_empty() {
20690            return Err(false);
20691        }
20692        let (Some(pq), Some(pk), Some(pv), Some(po)) =
20693            (wq.q1_parts(), wk.q1_parts(), wv.q1_parts(), wo.q1_parts())
20694        else {
20695            return Err(false);
20696        };
20697        let (Some(g), Some(u), Some(dn)) = (
20698            d.gate_proj.q1_parts(),
20699            d.up_proj.q1_parts(),
20700            d.down_proj.q1_parts(),
20701        ) else {
20702            return Err(false);
20703        };
20704        let (Some(eh), Some(lm)) = (m.eh_proj.q1_parts(), self.weights.lm_head.q1_parts()) else {
20705            return Err(false);
20706        };
20707        let QTensor::Mapped { model, .. } = wq else {
20708            return Err(false);
20709        };
20710        let model = model.clone();
20711        // the embedding table: a q4tp tensor of the SAME blob, no Prism
20712        // inverse-embedding post-pass
20713        let QTensor::Mapped {
20714            model: em,
20715            idx: eidx,
20716            dtype: cortiq_core::TensorDtype::Q4TiledP,
20717            ..
20718        } = &self.weights.embed_tokens
20719        else {
20720            return Err(false);
20721        };
20722        if !std::sync::Arc::ptr_eq(em, &model)
20723            || crate::prism::is_inverse_embedding(&model, &model.tensors[*eidx].name)
20724        {
20725            return Err(false);
20726        }
20727        let embed = (
20728            *eidx,
20729            self.weights.embed_tokens.rows(),
20730            self.weights.embed_tokens.cols(),
20731        );
20732        if embed.2 != self.hidden_size || hidden.len() != self.hidden_size {
20733            return Err(false);
20734        }
20735        let dims = GraphDims {
20736            hidden: self.hidden_size,
20737            eps: self.rms_eps as f32,
20738            gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
20739        };
20740        // Keep the chained MTP draft on the masked-nibble Metal matvec
20741        // path.  This scope covers every encode in the chain; the guard
20742        // restores its predecessor when this round returns or declines.
20743        let _mtp_fast = crate::gpu_metal::MvFastGuard::set_bits(
20744            crate::gpu_metal::DENSE_MV,
20745        );
20746        let Some(mut graph) = TokenGraph::new(&model, dims, hidden) else {
20747            return Err(false);
20748        };
20749        if !graph.chain_embed_ok(embed) || !graph.lm_head_ok(lm) {
20750            return Err(false);
20751        }
20752        let l = AttnGpuLayer {
20753            mhc: None,
20754            attn_norm: &m.layer.input_norm,
20755            post_norm: &m.layer.post_norm,
20756            wq: pq,
20757            wk: pk,
20758            wv: pv,
20759            wo: po,
20760            ffn: MetalFfn::Dense {
20761                gate: g,
20762                up: u,
20763                down: dn,
20764                act: (d.act == Act::Gelu) as u8,
20765            },
20766            attn_out_norm: None,
20767            ffn_out_norm: None,
20768            layer_scale: None,
20769        };
20770        let (nh, nkv, hd, rd) = (
20771            self.num_heads,
20772            self.num_kv_heads,
20773            self.head_dim,
20774            self.rotary_dim,
20775        );
20776        let inv_freq = self.inv_freq.clone();
20777        let draft_rows = self.draft_head_rows(lm.1);
20778        let n_arg = draft_rows.min(lm.1).min(self.vocab_size);
20779        if n_arg == 0 {
20780            return Err(false);
20781        }
20782        // `CMF_MTP_CHAIN_SPLIT=1` commits each step as it is encoded, so
20783        // the GPU starts on step 0 while the host is still encoding step
20784        // 1 — a probe for whether the host encode is on the critical
20785        // path. It is not: three runs each, draft 30.0 ms per round split
20786        // against 30.1 whole, and the whole chain's host encode measures
20787        // 0.3 ms against a 29.7 ms wait. Kept as a probe, off by default.
20788        let split = std::env::var("CMF_MTP_CHAIN_SPLIT").as_deref() == Ok("1");
20789        // The input stage, the embedding and the block's input projection, goes as a command
20790        // of its own. The weights are one buffer of 13.6 GB on a Mac, the embedding table lies
20791        // 1.5 GB into it and the draft block 13.1 GB: in one command with the block the driver
20792        // held the command 150 to 170 ms before the GPU ran its 9 ms, in every round until the
20793        // first one without a warm-up. MacBook Air M4, Qwen3.8-27B, a round of two drafts:
20794        // 362 → 204 ms. `CMF_MTP_CHAIN_JOIN=1` keeps one command.
20795        let join = std::env::var("CMF_MTP_CHAIN_JOIN").as_deref() == Ok("1");
20796        let t_chain = std::time::Instant::now();
20797        graph.chain_ids_init(t_next, k);
20798        let cpu_stored;
20799        {
20800            let cache = &m.kv;
20801            let cpu_k: Vec<&[f32]> = (0..nkv).map(|g| cache.head_keys(g)).collect();
20802            let cpu_v: Vec<&[f32]> = (0..nkv).map(|g| cache.head_values(g)).collect();
20803            cpu_stored = cpu_k[0].len() / hd;
20804            for j in 0..k {
20805                if !graph.encode_chain_input(
20806                    embed,
20807                    j as u32,
20808                    &m.enorm,
20809                    &m.hnorm,
20810                    self.embed_multiplier,
20811                    eh,
20812                ) {
20813                    return Err(false);
20814                }
20815                // step j's mirror row: the mirror is re-pointed at the CPU
20816                // rows before step 0 and advances by one per step; its
20817                // resync (never taken past step 0) reads the CPU rows
20818                let p = AttnDeviceParams {
20819                    kv_id: self.mtp_kv_id(),
20820                    layer: Self::MTP_LAYER_BASE,
20821                    nh,
20822                    nkv,
20823                    hd,
20824                    rd,
20825                    position: position + j,
20826                    scale: self.attn_scale,
20827                    eps: self.rms_eps as f32,
20828                    gemma: self.norm_style == cortiq_core::NormStyle::Gemma,
20829                    late_qk_norm: self.qk_norm_after_rope,
20830                    output_gate: *output_gate,
20831                    q_norm: q_norm.as_deref(),
20832                    k_norm: k_norm.as_deref(),
20833                    inv_freq: &inv_freq,
20834                    rope_scale: self.rope_scale,
20835                    cpu_k: cpu_k.clone(),
20836                    cpu_v: cpu_v.clone(),
20837                    cpu_stored: cpu_stored + j,
20838                    cpu_gen: cache.generation(),
20839                    o1: None,
20840                    window: None,
20841                    softmax_sink: None,
20842                    head_gate: None,
20843                    v_norm: false,
20844                    dash: None,
20845                };
20846                if !join {
20847                    graph.commit();
20848                }
20849                if !graph.attn_device_ok(&l, &p) || !graph.encode_attn_device(&l, &p) {
20850                    return Err(false);
20851                }
20852                if draft_rows < lm.1 {
20853                    if !graph.encode_lm_head_part(&m.final_norm, lm, draft_rows) {
20854                        return Err(false);
20855                    }
20856                } else {
20857                    graph.encode_lm_head(&m.final_norm, lm);
20858                }
20859                if !graph.encode_argmax(n_arg, j as u32 + 1) {
20860                    return Err(false);
20861                }
20862                if split {
20863                    // CMF_MTP_CHAIN_SPLIT=1: commit every step so the GPU
20864                    // starts on step 0 while the host encodes the rest
20865                    graph.commit();
20866                }
20867            }
20868        }
20869        let t_enc = t_chain.elapsed();
20870        if graph.sync_checked().is_err() {
20871            return Err(true);
20872        }
20873        if std::env::var_os("CMF_GRAPH_SPEC_TIME").is_some() {
20874            eprintln!(
20875                "mtp-chain: encode {:.1} ms | wait {:.1} ms (k={k}, head rows {draft_rows}{})",
20876                t_enc.as_secs_f64() * 1e3,
20877                (t_chain.elapsed() - t_enc).as_secs_f64() * 1e3,
20878                if split { ", split" } else { "" }
20879            );
20880            if std::env::var("CMF_METAL_CMD_TIMES").as_deref() == Ok("1") {
20881                eprintln!("metal-set: {}", crate::gpu_metal::working_set_report());
20882            }
20883        }
20884        let mut ids = vec![0u32; k];
20885        if !graph.chain_ids_read(&mut ids) {
20886            return Err(true);
20887        }
20888        let mut kbuf = vec![0f32; k * nkv * hd];
20889        let mut vbuf = vec![0f32; k * nkv * hd];
20890        if !crate::gpu_metal::kv_mirror_read_rows(
20891            self.mtp_kv_id(),
20892            Self::MTP_LAYER_BASE,
20893            nkv,
20894            hd,
20895            cpu_stored,
20896            k,
20897            &mut kbuf,
20898            &mut vbuf,
20899        ) {
20900            return Err(true);
20901        }
20902        for r in 0..k {
20903            m.kv.append(
20904                &kbuf[r * nkv * hd..(r + 1) * nkv * hd],
20905                &vbuf[r * nkv * hd..(r + 1) * nkv * hd],
20906                &[],
20907            );
20908        }
20909        Ok(ids)
20910    }
20911
20912    fn try_batch_graph_wgpu(
20913        &self,
20914        hiddens: &mut [f32],
20915        positions: &[usize],
20916        k: usize,
20917        spec: Option<crate::gpu::SpecTail<'_>>,
20918    ) -> crate::gpu::BatchGraphOutcome {
20919        self.try_batch_graph_wgpu_prefix(hiddens, positions, k, spec, None)
20920    }
20921
20922    /// `try_batch_graph_wgpu` with the device-prefix mode: `layers_run`
20923    /// Some lets a stack that does not fit run its leading layers (the
20924    /// token graph's prefix rule) and reports how many; `hiddens` then
20925    /// holds the boundary rows and the caller runs the rest on the host.
20926    fn try_batch_graph_wgpu_prefix(
20927        &self,
20928        hiddens: &mut [f32],
20929        positions: &[usize],
20930        k: usize,
20931        spec: Option<crate::gpu::SpecTail<'_>>,
20932        layers_run: Option<&mut usize>,
20933    ) -> crate::gpu::BatchGraphOutcome {
20934        crate::gpu::graph_kv16_note(self.graph_kv_id, self.kv16_allowed());
20935        // SenseNova-Loop: the mHC kernels take two streams (the
20936        // CMF_MHC_GRAPH=0 knob keeps the host); MRoPE prompt rows ride the
20937        // per-row attention loop with their own angle tables.
20938        if self.mhc.as_ref().is_some_and(|m| {
20939                m.s.streams != 2 || m.s.fixed_identity || std::env::var("CMF_MHC_GRAPH").as_deref() == Ok("0")
20940            })
20941        {
20942            return crate::gpu::BatchGraphOutcome::Declined;
20943        }
20944        let graph_end = match self.mimo_moe.graph_prefix_end() {
20945            Some(end) if end < self.num_layers => {
20946                if layers_run.is_none() || spec.is_some() || end == 0 {
20947                    return crate::gpu::BatchGraphOutcome::Declined;
20948                }
20949                end
20950            }
20951            _ => self.num_layers,
20952        };
20953        let _tb = std::time::Instant::now();
20954        let batch_debug = std::env::var_os("CMF_BATCH_DEBUG").is_some();
20955        if self.attn_softcap > 0.0 {
20956            return crate::gpu::BatchGraphOutcome::Declined; // capped scores: no graph kernel — CPU path
20957        }
20958        // Same attention contract as the token graph: per-layer geometry
20959        // rides `geom`, anything it cannot express declines by name.
20960        if let Some(reason) = self
20961            .wgpu_graph_attn_decline()
20962            .or_else(|| self.batch_graph_gemma_decline())
20963        {
20964            self.note_graph_decline("wgpu batch graph", reason);
20965            return crate::gpu::BatchGraphOutcome::Declined;
20966        }
20967        let nh = self.num_heads;
20968        let (nkv, hd, rd) = self.layer_geom(0);
20969        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
20970        // `blr` rides as GRAPH_KIND_BLR on CUDA, whose hybrid arm runs it
20971        // the small path's rows at a time (the wgpu batch graph declines it)
20972        fn bw(t: &QTensor) -> Option<(&std::sync::Arc<cortiq_core::CmfModel>, usize, u8, &[f32])> {
20973            if crate::gpu::cuda_active() {
20974                t.graph_weight_or_blr()
20975            } else {
20976                t.graph_weight().or_else(|| t.graph_weight_descriptor())
20977            }
20978        }
20979        fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
20980            if let Some((m, i, kind, rs)) = bw(t)
20981            {
20982                let name = &m.tensors[i].name;
20983                let prism = if crate::prism::is_inverse_embedding(m, name) {
20984                    crate::gpu::GraphPrismOp::InverseEmbedding
20985                } else if crate::prism::is_forward_weight(m, name) {
20986                    crate::gpu::GraphPrismOp::Forward
20987                } else {
20988                    crate::gpu::GraphPrismOp::None
20989                };
20990                return Some(crate::gpu::GraphW {
20991                    idx: i,
20992                    kind,
20993                    row_scale: rs,
20994                    data: &[],
20995                    prism,
20996                    affine: crate::prism::is_affine_target(m, name),
20997                });
20998            }
20999            if std::env::var_os("CMF_BATCH_DEBUG").is_some() {
21000                eprintln!(
21001                    "batch graph: tensor has no graph descriptor/f32 fallback rows={} cols={}",
21002                    t.rows(),
21003                    t.cols()
21004                );
21005            }
21006            t.as_f32().map(|d| crate::gpu::GraphW {
21007                idx: 0,
21008                kind: 4,
21009                row_scale: &[],
21010                data: d,
21011                prism: crate::gpu::GraphPrismOp::None,
21012                affine: false,
21013            })
21014        }
21015        // Ripple's value residual: the chunk's embedding rows, as they enter
21016        // the first layer (the graph overwrites `hiddens`).
21017        let vres_e0: Vec<f32> = if self.value_blend.is_some() {
21018            hiddens[..k * self.hidden_size].to_vec()
21019        } else {
21020            Vec::new()
21021        };
21022        let built: Option<(
21023            Vec<crate::gpu::GraphLayer<'_>>,
21024            std::sync::Arc<cortiq_core::CmfModel>,
21025        )> = (|| {
21026            let mut layers = Vec::with_capacity(graph_end);
21027            let mut model = None;
21028            for li in 0..graph_end {
21029                let lw = &self.weights.layers[self.phys_layer(li)];
21030                // MoE routes per token, so its experts are encoded token by
21031                // token inside the batched submit while attention and the
21032                // projections stay GEMMs. Refusing MoE here is what left
21033                // prefill running one position at a time: 33 tok/s against
21034                // 54 on decode, i.e. reading the prompt was slower than
21035                // writing the answer.
21036                let gffn = match &lw.ffn {
21037                    FfnKind::Dense(d) if d.segs.len() > 1 => {
21038                        if batch_debug {
21039                            eprintln!("batch graph: dense segmented FFN at layer {li}");
21040                        }
21041                        return None;
21042                    }
21043                    FfnKind::Dense(d) => {
21044                        let Some((act, limit)) = d.act.dense_graph_contract() else {
21045                            if batch_debug {
21046                                eprintln!(
21047                                    "batch graph: dense FFN activation {:?} without a graph kernel at layer {li}",
21048                                    d.act
21049                                );
21050                            }
21051                            return None;
21052                        };
21053                        crate::gpu::GraphFfn::Dense {
21054                            gate: gw(&d.gate_proj)?,
21055                            up: gw(&d.up_proj)?,
21056                            down: gw(&d.down_proj)?,
21057                            act,
21058                            limit,
21059                            // The layer's one tube (hot neurons), always on.
21060                            hot: match d.segs.first() {
21061                                Some(seg) => Some(crate::gpu::GraphMoeDetachedShared {
21062                                    gate: gw(&seg.gate)?,
21063                                    up: gw(&seg.up)?,
21064                                    down: gw(&seg.down)?,
21065                                    width: seg.width,
21066                                }),
21067                                None => None,
21068                            },
21069                        }
21070                    }
21071                    FfnKind::Moe(m) => {
21072                        // Adaptive τ and expert masks stay on the CPU path.
21073                        // Sigmoid scores, the selection bias, a routed scale
21074                        // ≠ 1 and an ungated shared expert (hy_v3) ride the
21075                        // same flags word as the token graph — before, this
21076                        // refusal sent every Hy-MT2-30B prompt to the chunked
21077                        // fallback (8 tok/s of ingest against 53 of decode).
21078                        if m.route_tau.is_some() || m.mask.is_some() {
21079                            return None;
21080                        }
21081                        // A shared expert rides as slot top_k (gated or
21082                        // not is a flag on the select kernel); without one
21083                        // (MiMo-V2, LFM2-MoE) the kernels run top_k slots.
21084                        let inter0 = m.experts.first()?.gate_proj.rows();
21085                        // A wider shared expert (Unlimited-OCR) stays out of
21086                        // the packed bank, as on the token graph.
21087                        let detached_shared = match m.shared.as_ref() {
21088                            Some((se, None)) if se.gate_proj.rows() != inter0 || se.up_proj.rows() != inter0 => {
21089                                if !matches!(se.act, Act::Silu) {
21090                                    return None;
21091                                }
21092                                Some(crate::gpu::GraphMoeDetachedShared {
21093                                    gate: gw(&se.gate_proj)?,
21094                                    up: gw(&se.up_proj)?,
21095                                    down: gw(&se.down_proj)?,
21096                                    width: se.gate_proj.rows(),
21097                                })
21098                            }
21099                            _ => None,
21100                        };
21101                        let shared = m.shared.as_ref().filter(|_| detached_shared.is_none());
21102                        let has_shared = shared.is_some();
21103                        let shared_gated = matches!(shared, Some((_, Some(_))));
21104                        let sgate = match shared {
21105                            Some((_, Some(sg))) => gw(sg)?,
21106                            // Ungated or absent: the router plane stands in
21107                            // so the plumbing stays total; the kernel pins
21108                            // weight 1 or never reads it.
21109                            _ => gw(&m.router)?,
21110                        };
21111                        let router = gw(&m.router)?;
21112                        // The batch MoE kernels still consume raw per-token
21113                        // rows and do not carry the descriptor-aware Prism
21114                        // transform/affine bit for router or shared-gate
21115                        // planes.  Refuse rather than route an untransformed
21116                        // source activation.
21117                        if router.prism != crate::gpu::GraphPrismOp::None
21118                            || router.affine
21119                            || sgate.prism != crate::gpu::GraphPrismOp::None
21120                            || sgate.affine
21121                        {
21122                            return None;
21123                        }
21124                        let inter = m.experts.first()?.gate_proj.rows();
21125                        let mut experts = Vec::with_capacity(m.experts.len() + 1);
21126                        let mut q4tp: Option<bool> = None;
21127                        let mut gu_q2: Option<bool> = None;
21128                        let mut q82: Option<bool> = None;
21129                        // The packed MoE graph has one gate/up program per
21130                        // layer, so accept only one exact activation contract
21131                        // across routed and in-bank shared experts.
21132                        let mut moe_act = None;
21133                        for e in m.experts.iter().chain(shared.map(|(se, _)| se)) {
21134                            let Some(e_act) = e.act.wgpu_graph_act() else {
21135                                return None;
21136                            };
21137                            match moe_act {
21138                                Some(existing) if existing != e_act => return None,
21139                                None => moe_act = Some(e_act),
21140                                _ => {}
21141                            }
21142                            if e.gate_proj.rows() != inter || e.up_proj.rows() != inter {
21143                                return None;
21144                            }
21145                            // Same ladder as the token graph: q4t → q2tp
21146                            // (mixed profile: 2-bit gate/up over a q4tp
21147                            // down) → q4tp → q8_2f. Uniform across the layer.
21148                            let (mm, gi, ui, di, is_p, is_q2, is_8) = match e.gate_proj.mapped_q4t()
21149                            {
21150                                Some((mm, gi)) => (
21151                                    mm,
21152                                    gi,
21153                                    e.up_proj.mapped_q4t()?.1,
21154                                    e.down_proj.mapped_q4t()?.1,
21155                                    false,
21156                                    false,
21157                                    false,
21158                                ),
21159                                None => match e.gate_proj.mapped_q2tp() {
21160                                    Some((mm, gi)) => (
21161                                        mm,
21162                                        gi,
21163                                        e.up_proj.mapped_q2tp()?.1,
21164                                        e.down_proj.mapped_q4tp()?.1,
21165                                        true,
21166                                        true,
21167                                        false,
21168                                    ),
21169                                    None => match e.gate_proj.mapped_q4tp() {
21170                                        Some((mm, gi)) => (
21171                                            mm,
21172                                            gi,
21173                                            e.up_proj.mapped_q4tp()?.1,
21174                                            e.down_proj.mapped_q4tp()?.1,
21175                                            true,
21176                                            false,
21177                                            false,
21178                                        ),
21179                                        None => {
21180                                            if !crate::gpu::moe_q82_graph_on() {
21181                                                return None;
21182                                            }
21183                                            let (mm, gi) = e.gate_proj.mapped_q8_2f()?;
21184                                            (
21185                                                mm,
21186                                                gi,
21187                                                e.up_proj.mapped_q8_2f()?.1,
21188                                                e.down_proj.mapped_q8_2f()?.1,
21189                                                false,
21190                                                false,
21191                                                true,
21192                                            )
21193                                        }
21194                                    },
21195                                },
21196                            };
21197                            if *q4tp.get_or_insert(is_p) != is_p
21198                                || *gu_q2.get_or_insert(is_q2) != is_q2
21199                                || *q82.get_or_insert(is_8) != is_8
21200                            {
21201                                return None;
21202                            }
21203                            if [gi, ui, di].into_iter().any(|idx| {
21204                                mm.tensors.get(idx).is_some_and(|t| {
21205                                    crate::prism::is_forward_weight(mm, &t.name)
21206                                        || crate::prism::is_affine_target(mm, &t.name)
21207                                })
21208                            }) {
21209                                return None;
21210                            }
21211                            model.get_or_insert_with(|| mm.clone());
21212                            experts.push((gi, ui, di));
21213                        }
21214                        crate::gpu::GraphFfn::Moe {
21215                            latent: None,
21216                            shared_limit: None,
21217                            router,
21218                            shared_gate: sgate,
21219                            experts,
21220                            n_exp: m.experts.len(),
21221                            top_k: m.top_k,
21222                            inter,
21223                            act: moe_act?,
21224                            norm_topk: m.norm_topk_prob,
21225                            q4tp: q4tp?,
21226                            gu_q2: gu_q2.unwrap_or(false),
21227                            q82: q82.unwrap_or(false),
21228                            sigmoid: m.router_sigmoid,
21229                            sigmoid_denom_eps: m.sigmoid_denom_eps,
21230                            bias: m.expert_bias.as_deref(),
21231                            has_shared,
21232                            detached_shared,
21233                            shared_gated,
21234                            route_scale: m.routed_scaling,
21235                            limit: 0.0,
21236                        }
21237                    }
21238                    _ => return None,
21239                };
21240                let attn = match &lw.attn {
21241                    AttnKind::Full {
21242                        wq,
21243                        wk,
21244                        wv,
21245                        wo,
21246                        q_norm,
21247                        k_norm,
21248                        output_gate,
21249                        softplus_gate,
21250                        bias,
21251                    } => {
21252                        // Spark-X2.6's head-wise sigmoid gate rides the batch graph
21253                        // (one g_proj row per Q head); Laguna's softplus gate does not.
21254                        let head_gate = match softplus_gate {
21255                            Some((g, true)) if self.proj_gate_sigmoid && !*output_gate => Some(gw(g)?),
21256                            None => None,
21257                            Some(_) => {
21258                                if batch_debug {
21259                                    eprintln!("batch graph: unsupported Full attention gate at layer {li}");
21260                                }
21261                                return None;
21262                            }
21263                        };
21264                        if self.attention_heads_per_layer.is_some() {
21265                            if batch_debug {
21266                                eprintln!("batch graph: per-layer Q heads at layer {li}");
21267                            }
21268                            return None;
21269                        }
21270                        model = Some(self.graph_model_of(&[wq, wk, wv, wo])?);
21271                        crate::gpu::GraphAttn::Full {
21272                            wq: gw(wq)?,
21273                            wk: gw(wk)?,
21274                            wv: gw(wv)?,
21275                            wo: gw(wo)?,
21276                            q_norm: q_norm.as_deref(),
21277                            k_norm: k_norm.as_deref(),
21278                            late_qk_norm: self.qk_norm_after_rope,
21279                            bias: bias
21280                                .as_ref()
21281                                .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
21282                            output_gate: *output_gate,
21283                            cpu_k: self.kv_cache.layers[li].k_heads(),
21284                            cpu_v: self.kv_cache.layers[li].v_heads(),
21285                            cpu_base: self.kv_cache.layers[li].base(),
21286                            geom: self.graph_attn_geom_vres(li, &vres_e0),
21287                            head_gate,
21288                        }
21289                    }
21290                    AttnKind::LinearGdn(w) => {
21291                        let Some(cfg) = self.gdn_cfg else {
21292                            if batch_debug {
21293                                eprintln!("batch graph: no GDN config at layer {li}");
21294                            }
21295                            return None;
21296                        };
21297                        model = Some(self.graph_model_of(&[&w.in_proj_qkv, &w.in_proj_z, &w.out_proj])?);
21298                        crate::gpu::GraphAttn::Gdn {
21299                            qkv: gw(&w.in_proj_qkv)?,
21300                            z: gw(&w.in_proj_z)?,
21301                            a: gw(&w.in_proj_a)?,
21302                            b: gw(&w.in_proj_b)?,
21303                            out: gw(&w.out_proj)?,
21304                            conv1d: &w.conv1d,
21305                            a_log: &w.a_log,
21306                            dt_bias: &w.dt_bias,
21307                            norm: &w.norm,
21308                            nv: cfg.num_v_heads,
21309                            nk: cfg.num_k_heads,
21310                            dk: cfg.key_head_dim,
21311                            dv: cfg.value_head_dim,
21312                            kk: cfg.conv_kernel,
21313                            cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
21314                            preview: self.clover.as_ref().and_then(|c| c.graph_preview(li)),
21315                        }
21316                    }
21317                    AttnKind::Kda(_) | AttnKind::Mla(_) => {
21318                        let (attn, m) = self.graph_attn_kimi(li, &lw.attn, &gw)?;
21319                        model = Some(m);
21320                        attn
21321                    }
21322                    // LFM2/3's short convolution: the CUDA hybrid arm's prompt
21323                    // path and the wgpu batch graph (`sconv_batch`) run it
21324                    AttnKind::ShortConv(w) => {
21325                        let cfg = self.short_conv_cfg?;
21326                        let (m, _, _, _) = bw(&w.in_proj)?;
21327                        model = Some(m.clone());
21328                        crate::gpu::GraphAttn::ShortConv {
21329                            inp: gw(&w.in_proj)?,
21330                            out: gw(&w.out_proj)?,
21331                            taps: &w.conv,
21332                            kernel: cfg.kernel,
21333                            cpu_state: &self.kv_cache.layers[self.phys_layer(li)].linear_state,
21334                        }
21335                    }
21336                    _ => return None,
21337                };
21338                // Gemma-4's sandwich norms and layer scalar (`gemma_batch`),
21339                // Ripple's and the LFM stacks' sandwich norms (wgpu's plain
21340                // tails), and on CUDA any plain sandwich norms (the hybrid
21341                // prompt path's `sandwich_rows`); every other model hands the
21342                // graph none.
21343                let g4 = self.global_attn.is_some() || self.attn_v_norm;
21344                let lfm = self.short_conv_cfg.is_some();
21345                let sandwich = g4 || self.value_blend.is_some() || lfm || crate::gpu::cuda_active();
21346                layers.push(crate::gpu::GraphLayer {
21347                    engram: None,
21348                    mhc: crate::sensenova::graph_mhc(self.mhc.as_deref(), self.phys_layer(li)),
21349                    input_norm: &lw.input_norm,
21350                    attn,
21351                    post_norm: &lw.post_norm,
21352                    attn_out_norm: if sandwich {
21353                        lw.attn_out_norm.as_deref()
21354                    } else {
21355                        None
21356                    },
21357                    ffn_out_norm: if sandwich { lw.ffn_out_norm.as_deref() } else { None },
21358                    layer_scale: if g4 { lw.layer_scale } else { None },
21359                    ffn: gffn,
21360                });
21361            }
21362            Some((layers, model?))
21363        })();
21364        let Some((layers, model)) = built else {
21365            {
21366                use std::sync::atomic::{AtomicBool, Ordering};
21367                static SAID: AtomicBool = AtomicBool::new(false);
21368                if !SAID.swap(true, Ordering::Relaxed) {
21369                    tracing::warn!("batch graph: BUILDER refused (layer weights/kinds)");
21370                }
21371            }
21372            return crate::gpu::BatchGraphOutcome::Declined;
21373        };
21374        if std::env::var("CMF_GRAPH_SPEC_TIME").is_ok() {
21375            eprintln!("batch-build: {:.1} ms", _tb.elapsed().as_secs_f64() * 1e3);
21376        }
21377        // SenseNova-Loop and Mage-VL: their q8_2f prompt chunks take the
21378        // batched int8 GEMM.
21379        #[cfg(feature = "gpu")]
21380        crate::gpu_wgpu::set_batch_q82_mm(self.mhc.is_some() || self.onevision2_prefill());
21381        // SenseNova-Loop image prompt: each row's absolute MRoPE angles.
21382        #[cfg(feature = "gpu")]
21383        let _mrope = self.prompt_mrope.as_deref().zip(self.mrope_sections).map(|(pos, sections)| {
21384            let half = rd / 2;
21385            let mut tab = vec![0f32; k * 64];
21386            for (i, &p) in positions.iter().enumerate() {
21387                for j in 0..half.min(64) {
21388                    let a = pos.get(p).map_or(p as f32, |q| q[crate::sensenova::mrope_axis(j, sections)] as f32);
21389                    tab[i * 64 + j] = a * self.inv_freq[j];
21390                }
21391            }
21392            crate::gpu_wgpu::set_batch_mrope(Some(tab));
21393            struct Clear;
21394            impl Drop for Clear {
21395                fn drop(&mut self) {
21396                    crate::gpu_wgpu::set_batch_mrope(None);
21397                }
21398            }
21399            Clear
21400        });
21401        // A Looped Transformer: the final norm on the stream after each
21402        // loop's last layer, as the token graph's `loop_norm_at` (the
21403        // stack's own last layer aside: the head norms it). Without them
21404        // the batch graph ran the loops back to back: Nanbeige's long
21405        // prompts read as noise on both GPU backends.
21406        let _loop = self.loop_final_norm.then(|| {
21407            let at: Vec<usize> = (0..graph_end.min(self.num_layers - 1)).filter(|&li| self.is_loop_end(li)).collect();
21408            crate::gpu::set_batch_loop_norm(Some((at, self.weights.final_norm.to_vec())));
21409            struct Clear;
21410            impl Drop for Clear {
21411                fn drop(&mut self) {
21412                    crate::gpu::set_batch_loop_norm(None);
21413                }
21414            }
21415            Clear
21416        });
21417        // a prompt chunk wholly before what the drafter's windows reach keeps none
21418        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) };
21419        let n_dflash = taps.len();
21420        // a routed prompt's rows at the router's layer, φ in row order
21421        let phi_slot = match self.dyn_phi_layer {
21422            Some(l) if l < graph_end => Some(taps.iter().position(|&t| t == l).unwrap_or_else(|| {
21423                taps.push(l);
21424                taps.len() - 1
21425            })),
21426            _ => None,
21427        };
21428        *self.dyn_phi_tap.lock().unwrap() = None;
21429        crate::gpu::layer_taps_arm(&taps);
21430        let outcome = crate::gpu::forward_batch_graph(
21431            &model,
21432            self.graph_kv_id,
21433            &layers,
21434            &self.inv_freq,
21435            hiddens,
21436            nh,
21437            nkv,
21438            hd,
21439            rd,
21440            self.hidden_size,
21441            self.intermediate_size,
21442            positions,
21443            self.kv_cache.max_seq_len,
21444            gemma,
21445            self.rms_eps as f32,
21446            self.attn_scale,
21447            k,
21448            &(0..graph_end)
21449                .map(|li| self.kv_cache.layers[self.phys_layer(li)].o1_views())
21450                .collect::<Vec<_>>(),
21451            self.o1_epoch,
21452            spec,
21453            layers_run,
21454        );
21455        self.graph_taps_keep(&taps, n_dflash, phi_slot, positions[0], k, outcome == crate::gpu::BatchGraphOutcome::Completed);
21456        outcome
21457    }
21458
21459    /// The layers a DFlash drafter reads, when a wgpu graph over layers
21460    /// `from..upto_excl` is the whole stack (nothing otherwise).
21461    fn dflash_taps_wanted(&self, from: usize, upto_excl: usize) -> Vec<usize> {
21462        match &self.dflash {
21463            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(),
21464            _ => Vec::new(),
21465        }
21466    }
21467
21468    /// Collect what the armed graph kept for `rows` rows from `pos0`
21469    /// (`ok`: it completed) into `dflash_taps`, a row's layers joined.
21470    fn dflash_taps_keep(&self, taps: &[usize], pos0: usize, rows: usize, ok: bool) {
21471        self.graph_taps_keep(taps, taps.len(), None, pos0, rows, ok);
21472    }
21473
21474    /// What the armed graph kept, `[slot][row][hidden]`: the first
21475    /// `n_dflash` slots are the drafter's (`dflash_taps`), `phi_slot` the
21476    /// router's φ rows (`dyn_phi_tap`).
21477    fn graph_taps_keep(&self, taps: &[usize], n_dflash: usize, phi_slot: Option<usize>, pos0: usize, rows: usize, ok: bool) {
21478        if taps.is_empty() {
21479            return;
21480        }
21481        let (nt, hs) = (taps.len(), self.hidden_size);
21482        let mut raw = Vec::new();
21483        if !crate::gpu::layer_taps_take(&mut raw) || !ok || raw.len() != nt * rows * hs {
21484            return;
21485        }
21486        if let Some(s) = phi_slot {
21487            *self.dyn_phi_tap.lock().unwrap() = Some(raw[s * rows * hs..(s + 1) * rows * hs].to_vec());
21488        }
21489        if n_dflash > 0 {
21490            raw.truncate(n_dflash * rows * hs);
21491            self.dflash_taps_join(&taps[..n_dflash], raw, pos0, rows);
21492        }
21493    }
21494
21495    /// The drafter's slots of a graph's taps into `dflash_taps`.
21496    fn dflash_taps_join(&self, taps: &[usize], raw: Vec<f32>, pos0: usize, rows: usize) {
21497        let (nt, hs) = (taps.len(), self.hidden_size);
21498        let mut joined = vec![0f32; rows * nt * hs];
21499        for s in 0..nt {
21500            for r in 0..rows {
21501                joined[(r * nt + s) * hs..][..hs].copy_from_slice(&raw[(s * rows + r) * hs..][..hs]);
21502            }
21503        }
21504        if std::env::var_os("CMF_SPEC_DBG").is_some() {
21505            let rms = (joined.iter().map(|v| (*v as f64) * (*v as f64)).sum::<f64>() / joined.len().max(1) as f64).sqrt();
21506            eprintln!("solo-dbg: {rows} rows of {nt} layers kept from position {pos0} (rms {rms:.3})");
21507        }
21508        if let Some(dir) = std::env::var_os("CMF_DFLASH_DUMP") {
21509            self.dflash_dump(std::path::Path::new(&dir), pos0, rows, &joined);
21510        }
21511        let mut kept = self.dflash_taps.lock().unwrap();
21512        kept.push((pos0, joined));
21513        // a long prompt's rows wait here until the first round: past
21514        // `DFLASH_TAPS_ROWS` the oldest chunks go, and the drafter's context
21515        // starts at what is left
21516        let mut rows: usize = kept.iter().map(|(_, r)| r.len()).sum::<usize>() / (nt * hs);
21517        let cap = match &self.dflash {
21518            Some(d) if (0..d.g.layers).all(|l| d.g.window_of(l) > 0) => {
21519                DFLASH_TAPS_ROWS.min((0..d.g.layers).map(|l| d.g.window_of(l)).max().unwrap_or(0) + crate::dflash::BLOCK_SLACK)
21520            }
21521            _ => DFLASH_TAPS_ROWS,
21522        };
21523        while rows > cap && kept.len() > 1 {
21524            rows -= kept.remove(0).1.len() / (nt * hs);
21525        }
21526    }
21527
21528    /// `CMF_DFLASH_DUMP=DIR`: what a reference run of the published drafter
21529    /// reads (`scripts/ripple/ripple_dflash_ref.py`). `taps.bin` grows by a
21530    /// record a kept chunk (position and row count as u64, then the rows'
21531    /// f32, a row's layers joined); the embedding table and the head are
21532    /// written once as f32, the table without the trunk's input scale.
21533    fn dflash_dump(&self, dir: &std::path::Path, pos0: usize, rows: usize, joined: &[f32]) {
21534        use std::io::Write;
21535        let _ = std::fs::create_dir_all(dir);
21536        let table = |name: &str, t: &QTensor| {
21537            let p = dir.join(name);
21538            if p.exists() {
21539                return;
21540            }
21541            let Ok(f) = std::fs::File::create(&p) else { return };
21542            let mut w = std::io::BufWriter::new(f);
21543            let mut row = vec![0f32; t.cols()];
21544            for r in 0..t.rows() {
21545                t.row_f32(r, &mut row);
21546                let _ = w.write_all(&f32_bytes(&row));
21547            }
21548        };
21549        table("embed.f32", &self.weights.embed_tokens);
21550        table("head.f32", &self.weights.lm_head);
21551        let meta = dir.join("meta.json");
21552        if !meta.exists() {
21553            let _ = std::fs::write(
21554                &meta,
21555                format!(
21556                    "{{\"hidden\": {}, \"vocab\": {}, \"embed_multiplier\": {}}}\n",
21557                    self.hidden_size,
21558                    self.weights.lm_head.rows(),
21559                    self.embed_multiplier
21560                ),
21561            );
21562        }
21563        if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("taps.bin")) {
21564            let _ = f.write_all(&(pos0 as u64).to_le_bytes());
21565            let _ = f.write_all(&(rows as u64).to_le_bytes());
21566            let _ = f.write_all(&f32_bytes(joined));
21567        }
21568    }
21569
21570    /// Rows the wgpu graphs kept become the drafter's context, oldest first.
21571    fn dflash_taps_absorb(&mut self) {
21572        let kept = std::mem::take(&mut *self.dflash_taps.lock().unwrap());
21573        if let Some(d) = self.dflash.as_mut() {
21574            for (pos0, rows) in kept {
21575                d.queue_context(pos0, &rows, self.pool.as_deref());
21576            }
21577        }
21578    }
21579
21580    /// Same, stopping after layer `upto` inclusive (routing probe φ).
21581    /// `CMF_DSV4_DRAFT_PROBE=1` — grade the draft against what the trunk goes on
21582    /// to produce. Off by default; it runs a whole draft per decoded token.
21583    fn draft_probe() -> bool {
21584        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
21585        *ON.get_or_init(|| std::env::var("CMF_DSV4_DRAFT_PROBE").is_ok_and(|v| v != "0"))
21586    }
21587
21588    /// `CMF_DSV4_DRAFT_PROBE=1`: measure how much of the draft the trunk
21589    /// would have agreed with, WITHOUT verifying or rolling anything back.
21590    ///
21591    /// The number this produces decides the whole speculation design — at
21592    /// acceptance a, a block of B positions yields 1 + a + a² + ... tokens
21593    /// per trunk pass — so it is worth measuring before any of the machinery
21594    /// that would exploit it exists. Each draft is parked with the position
21595    /// it was made at, and graded as the real tokens arrive.
21596    /// `CMF_DSV4_SPEC=1` — the DeepSeek-V4 speculative decode: draft five
21597    /// on the card, verify them in one batched trunk pass, commit the
21598    /// accepted prefix, roll the rest back.
21599    #[cfg(feature = "gpu")]
21600    fn dsv4_spec_on() -> bool {
21601        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
21602        *ON.get_or_init(|| {
21603            // Test-only runtime gate: model loading still performs the same
21604            // reservation and trunk packing, which gives rollback parity a
21605            // topology-identical non-speculative control arm.
21606            if let Ok(v) = std::env::var("CMF_DSV4_SPEC_RUN") {
21607                return v != "0";
21608            }
21609            // An explicit value is a diagnostic force/escape hatch.  With no
21610            // knob, speculation is eligible only when model loading reserved
21611            // its bounded pack.  On small q4tp cards the geometric reserve
21612            // gate deliberately leaves this at zero: trying to build DSpark
21613            // after the exact trunk filled VRAM is both slower and a device
21614            // OOM (measured on A40).
21615            std::env::var("CMF_DSV4_SPEC")
21616                .map(|v| v != "0")
21617                .unwrap_or_else(|_| {
21618                    crate::gpu_wgpu::DRAFT_RESERVE.load(std::sync::atomic::Ordering::Relaxed) > 0
21619                })
21620        })
21621    }
21622
21623    /// One speculative round at the decode tip. `t_next` is the token the
21624    /// sampler just committed for `next_pos`. Returns the EXTRA accepted
21625    /// tokens (possibly none) and the new position, with `graph_logits`
21626    /// left holding the last accepted position's logits — exactly what the
21627    /// loop top expects. `None` means "speculate not this round": nothing
21628    /// was committed, the caller forwards normally.
21629    #[cfg(feature = "gpu")]
21630    fn dsv4_spec_step(
21631        &mut self,
21632        tip_token: u32,
21633        t_next: u32,
21634        next_pos: usize,
21635        max_extra: usize,
21636        drafted: &mut usize,
21637        accepted_ctr: &mut usize,
21638    ) -> Option<(Vec<u32>, usize)> {
21639        let t_all = std::time::Instant::now();
21640        if std::env::var("CMF_DSV4_SPEC_TIME").is_ok() {
21641            thread_local! {
21642                static LAST: std::cell::Cell<Option<std::time::Instant>> =
21643                    const { std::cell::Cell::new(None) };
21644            }
21645            LAST.with(|l| {
21646                if let Some(prev) = l.get() {
21647                    eprintln!(
21648                        "between rounds {:.1} ms",
21649                        prev.elapsed().as_secs_f64() * 1e3
21650                    );
21651                }
21652                l.set(Some(std::time::Instant::now()));
21653            });
21654        }
21655        if std::env::var("CMF_DSV4_SPEC_DEBUG").is_ok() {
21656            eprintln!("spec_step: enter pos={next_pos}");
21657        }
21658        let n_layers = self.dsv4.as_ref().map(|b| b.1.len())?;
21659        let cfg = self.dsv4.as_ref().map(|b| b.2)?;
21660        // The draft state and its capture, armed exactly as the probe does.
21661        if self.dspark.is_none() {
21662            let t = crate::dsv4::dspark_targets(&self.dsv4_mtp, &cfg, n_layers);
21663            if t.is_empty() {
21664                return None;
21665            }
21666            crate::dsv4::dspark_arm(&t, cfg.dim);
21667            self.dspark = Some(crate::dsv4::DsparkState::new(
21668                self.dsv4_mtp.len(),
21669                &cfg,
21670                t.len(),
21671            ));
21672        }
21673        let targets = crate::dsv4::dspark_targets(&self.dsv4_mtp, &cfg, n_layers);
21674        let pack = crate::dsv4::dspark_pack_get(&self.dsv4_mtp, &cfg);
21675        if pack.is_none() && std::env::var("CMF_DSV4_SPEC_DEBUG").is_ok() {
21676            eprintln!("spec_step: the pack was not built (targets {targets:?})");
21677        }
21678        let pack = pack?;
21679        let block = crate::dsv4::dspark_block();
21680        let b_box = self.dsv4.as_mut()?;
21681        let (g, layers, st) = (&b_box.0, &b_box.1, &mut b_box.3);
21682        let ds = self.dspark.as_mut()?;
21683        // The tip's captures: either this token ran on a normal path that
21684        // filled the thread-local, or the previous spec round left them.
21685        let dbg = std::env::var("CMF_DSV4_SPEC_DEBUG").is_ok();
21686        if !crate::dsv4::dspark_take(&mut ds.main_hidden) && !ds.have_hidden {
21687            if dbg {
21688                eprintln!("spec_step: no capture");
21689            }
21690            return None;
21691        }
21692        ds.have_hidden = true;
21693        let tip_pos = next_pos.checked_sub(1)?;
21694        let draft_started = std::time::Instant::now();
21695        let mut conf = Vec::new();
21696        let props = crate::dsv4::dspark_draft_gpu(
21697            g,
21698            &self.dsv4_mtp,
21699            &cfg,
21700            ds,
21701            pack,
21702            st.kv_id,
21703            tip_token,
21704            tip_pos,
21705            self.pool.as_deref(),
21706            &mut conf,
21707        );
21708        self.dspark_draft_ns += draft_started.elapsed().as_nanos();
21709        *drafted += block;
21710        if props.is_empty() || props[0] != t_next {
21711            if dbg {
21712                eprintln!(
21713                    "spec_step: draft {} (props0={:?} t_next={t_next})",
21714                    if props.is_empty() {
21715                        "empty"
21716                    } else {
21717                        "miss"
21718                    },
21719                    props.first()
21720                );
21721            }
21722            return None;
21723        }
21724        // `fed[0]` is `t_next`, which the outer loop has already committed;
21725        // only `fed[1..]` become additional output tokens. Cap the verify
21726        // transaction itself to the caller's remaining output budget instead
21727        // of merely truncating the returned vector: otherwise the KV/state
21728        // would advance past `max_tokens` and a 64-token request could return
21729        // 66 tokens (and poison a reused session with two invisible steps).
21730        let mut k_verify = crate::dsv4::dspark_verify_k()
21731            .min(props.len())
21732            .min(max_extra.saturating_add(1));
21733        // Adaptive depth: positions the draft itself doubts are paid for on
21734        // every verify and delivered almost never (natural-text survival
21735        // [.67 .50 .29 .08 .04]). `CMF_DSPARK_CONF_MIN=p` trims the fed
21736        // prefix at the first proposal whose confidence drops below p; on
21737        // predictable text the confidences stay high and nothing changes.
21738        let conf_min = {
21739            static M: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
21740            *M.get_or_init(|| {
21741                std::env::var("CMF_DSPARK_CONF_MIN")
21742                    .ok()
21743                    .and_then(|v| v.parse().ok())
21744                    .unwrap_or(0.0)
21745            })
21746        };
21747        if conf_min > 0.0 && conf.len() >= props.len() {
21748            let mut keep = 1usize;
21749            while keep < k_verify && conf.get(keep).copied().unwrap_or(0.0) >= conf_min {
21750                keep += 1;
21751            }
21752            k_verify = k_verify.min(keep.max(2));
21753        }
21754        if k_verify < 2 {
21755            return None;
21756        }
21757        let mut fed = Vec::with_capacity(k_verify);
21758        fed.push(t_next);
21759        fed.extend_from_slice(&props[1..k_verify]);
21760        let mut argmax = Vec::new();
21761        let mut logits_all = Vec::new();
21762        let mut walked = Vec::new();
21763        let txn = crate::dsv4::dsv4_verify_chunk(
21764            g,
21765            layers,
21766            &cfg,
21767            st,
21768            &fed,
21769            next_pos,
21770            &self.inv_freq,
21771            self.pool.as_deref(),
21772            &targets,
21773            &mut argmax,
21774            &mut logits_all,
21775            &mut walked,
21776        );
21777        if txn.is_none() && dbg {
21778            eprintln!("spec_step: verify declined");
21779        }
21780        let txn = txn?;
21781        let spec_gpu_end = txn.gpu_end;
21782        let b = fed.len();
21783        let mut accepted = 1usize;
21784        while accepted < b && fed[accepted] == argmax[accepted - 1] {
21785            accepted += 1;
21786        }
21787        // `CMF_DSV4_SPEC_FORCE_REJECT=1` — accept nothing beyond the known
21788        // token, every round: the pure rollback exerciser. The output must
21789        // stay byte-identical to the plain walk; anything else is a
21790        // transaction bug, isolated from the acceptance logic.
21791        if std::env::var("CMF_DSV4_SPEC_FORCE_REJECT").is_ok_and(|v| v != "0") {
21792            accepted = 1;
21793        }
21794        if std::env::var("CMF_DSV4_SPEC_TRACE").is_ok() {
21795            eprintln!("spec@{next_pos}: fed={fed:?} argmax={argmax:?} accepted={accepted}");
21796        }
21797        let t_fin = std::time::Instant::now();
21798        if !crate::dsv4::dsv4_spec_finish(
21799            g,
21800            layers,
21801            &cfg,
21802            st,
21803            txn,
21804            accepted,
21805            &fed,
21806            &self.inv_freq,
21807            self.pool.as_deref(),
21808        ) {
21809            tracing::warn!("dsv4: the speculative rollback failed — the state is suspect");
21810            return None;
21811        }
21812        if std::env::var("CMF_DSV4_SPEC_TIME").is_ok() {
21813            eprintln!(
21814                "finish(k={accepted}): {:.1} ms",
21815                t_fin.elapsed().as_secs_f64() * 1e3
21816            );
21817        }
21818        *accepted_ctr += accepted - 1;
21819        // Captures per accepted token: device targets photographed by the
21820        // batch, host targets from the verify's own walk. The last one
21821        // becomes the new tip's draft input; every one owes the ring an
21822        // entry for its position.
21823        let (hc, dim) = (cfg.hc_mult, cfg.dim);
21824        // Complete-chain layers are photographed by the fused submission;
21825        // partial device layers overwrite that slot after exact host cold-
21826        // expert correction.  Thus every target in the contiguous device
21827        // prefix has a valid per-token capture.
21828        let dev_caps: Vec<usize> = targets
21829            .iter()
21830            .copied()
21831            .filter(|&t| t < spec_gpu_end)
21832            .collect();
21833        let mut caps_all = vec![0.0f32; dev_caps.len() * b * hc * dim];
21834        if !crate::gpu_wgpu::dsv4_spec_cap_read_all(b, dev_caps.len(), hc * dim, &mut caps_all) {
21835            return None;
21836        }
21837        for t in 0..accepted {
21838            let tip = t + 1 == accepted;
21839            for (slot, &tl) in targets.iter().enumerate() {
21840                if let Some(di) = dev_caps.iter().position(|&d| d == tl) {
21841                    let lo = (di * b + t) * hc * dim;
21842                    crate::dsv4::dspark_capture(
21843                        &caps_all[lo..lo + hc * dim],
21844                        &cfg,
21845                        slot,
21846                        &mut ds.main_hidden,
21847                    );
21848                } else if tip
21849                    && crate::dsv4::dspark_peek_slot(slot, dim, {
21850                        let lo = slot * dim;
21851                        &mut ds.main_hidden[lo..lo + dim]
21852                    })
21853                {
21854                    // The tip's host-layer captures are the walk's own
21855                    // per-layer notes — exact. (The walk that ran last ended
21856                    // on exactly this token, on both the accept-all and the
21857                    // rollback path.)
21858                } else {
21859                    // Intermediate tokens: the post-tail state stands in for
21860                    // the per-layer capture on host targets below the last
21861                    // layer. Ring-entry quality only; the tip is exact.
21862                    crate::dsv4::dspark_capture(
21863                        &walked[t * hc * dim..(t + 1) * hc * dim],
21864                        &cfg,
21865                        slot,
21866                        &mut ds.main_hidden,
21867                    );
21868                }
21869            }
21870            crate::dsv4::dspark_ring_append(
21871                g,
21872                &self.dsv4_mtp,
21873                &cfg,
21874                ds,
21875                next_pos + t,
21876                self.pool.as_deref(),
21877            );
21878        }
21879        let row = logits_all[(accepted - 1) * cfg.vocab..accepted * cfg.vocab].to_vec();
21880        self.graph_logits = Some(row);
21881        // The speculative loop never runs the probe, so the trunk tally has
21882        // no other place to cycle. Armed only when someone asked for the
21883        // dump; the host tail is the only tallying path here, which is
21884        // precisely the population a partial pack would serve.
21885        if std::env::var("CMF_DSV4_TRUNK_PICK_DUMP").is_ok() {
21886            crate::dsv4::trunk_freq_note(&crate::dsv4::pick_tally_take());
21887            crate::dsv4::pick_tally_arm();
21888        }
21889        if std::env::var("CMF_DSV4_SPEC_TIME").is_ok() {
21890            eprintln!(
21891                "spec_step total {:.1} ms (k={accepted})",
21892                t_all.elapsed().as_secs_f64() * 1e3
21893            );
21894        }
21895        Some((fed[1..accepted].to_vec(), next_pos + accepted))
21896    }
21897
21898    fn dspark_probe(&mut self, position: usize, token_id: u32) {
21899        if self.dsv4_mtp.is_empty() || !Self::draft_probe() {
21900            return;
21901        }
21902        // What the trunk just routed to, for this token.
21903        let trunk_now = crate::dsv4::pick_tally_take();
21904        crate::dsv4::trunk_freq_note(&trunk_now);
21905        if !trunk_now.is_empty() {
21906            self.dspark_trunk_picks.push(trunk_now);
21907            let keep = crate::dsv4::dspark_block();
21908            if self.dspark_trunk_picks.len() > keep {
21909                self.dspark_trunk_picks.remove(0);
21910            }
21911        }
21912        // Grade whatever is waiting: the token just decoded sits at
21913        // `position`, so it answers the draft made at `position - 1 - i`.
21914        for p in std::mem::take(&mut self.dspark_pending) {
21915            let Some(i) = position.checked_sub(p.0 + 1) else {
21916                continue;
21917            };
21918            let mut p = p;
21919            if i < p.1.len() {
21920                if p.2 && p.1[i] == token_id {
21921                    p.3 = i + 1;
21922                } else {
21923                    p.2 = false;
21924                }
21925                if i + 1 < p.1.len() {
21926                    self.dspark_pending.push(p);
21927                    continue;
21928                }
21929            }
21930            self.dspark_hist.push(p.3);
21931            self.dspark_real.push(token_id);
21932        }
21933        let Some(b) = &mut self.dsv4 else { return };
21934        let (g, layers, cfg) = (&b.0, &b.1, b.2);
21935        let n_layers = layers.len();
21936        if self.dspark.is_none() {
21937            let t = crate::dsv4::dspark_targets(&self.dsv4_mtp, &cfg, n_layers);
21938            if t.is_empty() {
21939                return;
21940            }
21941            eprintln!(
21942                "DSpark: capture from layers {t:?}, block {}",
21943                crate::dsv4::dspark_block()
21944            );
21945            crate::dsv4::dspark_arm(&t, cfg.dim);
21946            self.dspark = Some(crate::dsv4::DsparkState::new(
21947                self.dsv4_mtp.len(),
21948                &cfg,
21949                t.len(),
21950            ));
21951        }
21952        let ds = self.dspark.as_mut().unwrap();
21953        if !crate::dsv4::dspark_take(&mut ds.main_hidden) {
21954            return; // this token ran on a path that captures nothing
21955        }
21956        let mut conf = Vec::new();
21957        crate::dsv4::pick_tally_arm();
21958        // The trunk has already consumed the adaptive VRAM budget. Until the
21959        // draft owns an explicit bounded device pack, its tensors are an
21960        // out-of-core CPU/disk tier by contract: never let per-op probes try
21961        // to squeeze another multi-gigabyte MTP expert cache onto the card.
21962        let draft_started = std::time::Instant::now();
21963        #[cfg(feature = "gpu")]
21964        let gpu_draft = crate::dsv4::dspark_gpu_on();
21965        #[cfg(not(feature = "gpu"))]
21966        let gpu_draft = false;
21967        let props = if gpu_draft {
21968            #[cfg(feature = "gpu")]
21969            {
21970                let kv_id = b.3.kv_id;
21971                match crate::dsv4::dspark_pack_get(&self.dsv4_mtp, &cfg) {
21972                    Some(pk) => crate::dsv4::dspark_draft_gpu(
21973                        g,
21974                        &self.dsv4_mtp,
21975                        &cfg,
21976                        ds,
21977                        pk,
21978                        kv_id,
21979                        token_id,
21980                        position,
21981                        self.pool.as_deref(),
21982                        &mut conf,
21983                    ),
21984                    None => Vec::new(),
21985                }
21986            }
21987            #[cfg(not(feature = "gpu"))]
21988            Vec::new()
21989        } else {
21990            crate::gpu::cpu_scope(|| {
21991                crate::dsv4::dspark_draft(
21992                    g,
21993                    &self.dsv4_mtp,
21994                    &cfg,
21995                    ds,
21996                    token_id,
21997                    position,
21998                    self.pool.as_deref(),
21999                    &mut conf,
22000                )
22001            })
22002        };
22003        self.dspark_draft_ns += draft_started.elapsed().as_nanos();
22004        let draft_picks = crate::dsv4::pick_tally_take();
22005        crate::dsv4::dspark_freq_note(&draft_picks);
22006        // Re-arm for the NEXT trunk token; the probe runs after the forward,
22007        // so this is the only place that can.
22008        crate::dsv4::pick_tally_arm();
22009        if !props.is_empty() {
22010            // Two ratios, side by side: what a batched verify over the trunk
22011            // would read against what it asks for, and the same for the
22012            // draft's three stages. Near 1.0 means a batch amortises nothing.
22013            let (tu, tt) = {
22014                let flat: Vec<(usize, Vec<usize>)> = self
22015                    .dspark_trunk_picks
22016                    .iter()
22017                    .flat_map(|v| v.iter().cloned())
22018                    .collect();
22019                // Per layer, across the window of tokens.
22020                let mut per: std::collections::HashMap<usize, Vec<usize>> =
22021                    std::collections::HashMap::new();
22022                for (li, picks) in flat {
22023                    per.entry(li).or_default().extend(picks);
22024                }
22025                let n = per.len().max(1);
22026                let mut u = 0usize;
22027                let mut t = 0usize;
22028                for (_, v) in per {
22029                    t += v.len();
22030                    u += v.iter().collect::<std::collections::HashSet<_>>().len();
22031                }
22032                (u / n, t / n)
22033            };
22034            let (du, dt) = crate::dsv4::tally_unique(&draft_picks);
22035            self.dspark_exp.push((tu, tt, du, dt));
22036            self.dspark_pending.push((position, props, true, 0));
22037        }
22038        if self.dspark_hist.len() >= 8 && self.dspark_hist.len() % 8 == 0 {
22039            let n = self.dspark_hist.len() as f32;
22040            let mean: f32 = self.dspark_hist.iter().sum::<usize>() as f32 / n;
22041            let block = crate::dsv4::dspark_block();
22042            let mut at = vec![0usize; block + 1];
22043            for &k in &self.dspark_hist {
22044                at[k] += 1;
22045            }
22046            // Prefix survival: S_i = P(the first i positions all held).
22047            let mut surv = Vec::with_capacity(block);
22048            for i in 1..=block {
22049                let k = at[i..].iter().sum::<usize>() as f32 / n;
22050                surv.push(format!("{k:.2}"));
22051            }
22052            let distinct = self
22053                .dspark_real
22054                .iter()
22055                .collect::<std::collections::HashSet<_>>()
22056                .len();
22057            let (tu, tt, du, dt) = self.dspark_exp.iter().fold((0, 0, 0, 0), |a, b| {
22058                (a.0 + b.0, a.1 + b.1, a.2 + b.2, a.3 + b.3)
22059            });
22060            let m = self.dspark_exp.len().max(1);
22061            eprintln!(
22062                "DSpark: {} drafts, {mean:.2} of {block} accepted on average \
22063                 (tokens per pass {:.2}), distribution {at:?}, survival [{}]",
22064                self.dspark_hist.len(),
22065                mean + 1.0,
22066                surv.join(" ")
22067            );
22068            eprintln!(
22069                "DSpark: {distinct} distinct tokens of {} (degeneracy), \
22070                 trunk experts {}/{} per layer over {block} tokens, \
22071                 draft {}/{} per block, draft {:.2} ms/block",
22072                self.dspark_real.len(),
22073                tu / m,
22074                tt / m,
22075                du / m,
22076                dt / m,
22077                self.dspark_draft_ns as f64 / self.dspark_exp.len().max(1) as f64 / 1e6
22078            );
22079        }
22080    }
22081
22082    fn forward_layers_upto(
22083        &mut self,
22084        hidden: &[f32],
22085        position: usize,
22086        task_mask: Option<&TaskMask>,
22087        upto: Option<usize>,
22088    ) -> Vec<f32> {
22089        // In-process multi-GPU: each segment runs pinned to its card,
22090        // and the only thing crossing the boundary is one hidden vector
22091        // that never leaves this address space. Same layer split the
22092        // network mode does, minus the second process, the socket, the
22093        // serialization and the dir_hash handshake.
22094        if let Some(plan) = self.gpu_plan.clone() {
22095            if upto.is_none() && plan.len() > 1 {
22096                let mut h = hidden.to_vec();
22097                for &(dev, from, upto_incl) in plan.iter() {
22098                    h = crate::gpu::with_device(dev, || {
22099                        self.forward_layers_span(&h, position, task_mask, from, Some(upto_incl))
22100                    });
22101                }
22102                return h;
22103            }
22104        }
22105        self.forward_layers_span(hidden, position, task_mask, 0, upto)
22106    }
22107
22108    /// Split this pipeline's layer stack across local GPUs: segment i
22109    /// runs on `devices[i]`. Contiguous and even by layer count — the
22110    /// VRAM-weighted planner is the next step, and an uneven card pair
22111    /// is why it will be needed. `None` clears the plan.
22112    pub fn set_gpu_plan(&mut self, devices: Option<&[usize]>) -> Result<(), String> {
22113        self.set_gpu_plan_at(devices, None)
22114    }
22115
22116    /// The same, with an explicit first boundary (`--peer-split`): card
22117    /// 0 takes layers `[0..at)`, the rest split what remains. Uneven
22118    /// cards, or an attention-heavy head, are why this knob exists.
22119    pub fn set_gpu_plan_at(
22120        &mut self,
22121        devices: Option<&[usize]>,
22122        at: Option<usize>,
22123    ) -> Result<(), String> {
22124        let Some(devs) = devices.filter(|d| d.len() > 1) else {
22125            self.gpu_plan = None;
22126            return Ok(());
22127        };
22128        self.split_supported()?;
22129        let n = self.num_layers;
22130        if devs.len() > n {
22131            return Err(format!("{} devices for {n} layers", devs.len()));
22132        }
22133        if let Some(k) = at {
22134            if k == 0 || k >= n {
22135                return Err(format!("split at {k}: the model has {n} layers"));
22136            }
22137            if devs.len() == 2 {
22138                self.gpu_plan = Some(std::sync::Arc::new(vec![
22139                    (devs[0], 0, k - 1),
22140                    (devs[1], k, n - 1),
22141                ]));
22142                return Ok(());
22143            }
22144            return Err(format!(
22145                "an explicit split point takes exactly 2 devices, got {}",
22146                devs.len()
22147            ));
22148        }
22149        let per = n.div_ceil(devs.len());
22150        let mut plan = Vec::with_capacity(devs.len());
22151        let mut from = 0usize;
22152        for &d in devs {
22153            if from >= n {
22154                break;
22155            }
22156            let upto = (from + per - 1).min(n - 1);
22157            plan.push((d, from, upto));
22158            from = upto + 1;
22159        }
22160        self.gpu_plan = Some(std::sync::Arc::new(plan));
22161        Ok(())
22162    }
22163
22164    /// The active in-process split, if any: (device, first layer, last).
22165    pub fn gpu_plan(&self) -> Option<Vec<(usize, usize, usize)>> {
22166        self.gpu_plan.as_ref().map(|p| p.as_ref().clone())
22167    }
22168
22169    /// Layer span [from ..= upto] (upto None = last layer): the building
22170    /// block the network pipeline-split rides on. `from > 0` skips the
22171    /// arch escape hatches (the pub `forward_span` refuses those archs
22172    /// first) and the whole-token graph — the plain per-layer loop is
22173    /// the canonical executor for a partial stack.
22174    fn embryo_qtensor_f32(t: &QTensor) -> Vec<f32> {
22175        if let Some(x) = t.as_f32() {
22176            return x.to_vec();
22177        }
22178        let mut out = vec![0.0; t.rows() * t.cols()];
22179        for r in 0..t.rows() {
22180            t.row_f32(r, &mut out[r * t.cols()..(r + 1) * t.cols()]);
22181        }
22182        out
22183    }
22184
22185    fn embryo_resident_eligible(&self) -> bool {
22186        fn served(t: &QTensor) -> bool {
22187            t.as_f32().is_some() || t.q8_2f_codes().is_some()
22188        }
22189        // One mixer family per file: vmf_phase (kind 0/1) or
22190        // gated_delta_net (kind 4); the anchors are full (2) or bounded (3).
22191        if (self.vmf_cfg.is_none() && self.gdn_cfg.is_none())
22192            || self.num_layers != self.physical_layers
22193            || self.loop_final_norm
22194            || self.weights.layers.len() != self.num_layers
22195            || self.head_clusters.is_none()
22196            || self.final_softcap.is_some()
22197            || self.logit_multiplier.is_some()
22198            || self.attn_softcap != 0.0
22199            || self.mtp.is_some()
22200            || self.per_token_stack()
22201            || self.dsv4.is_some()
22202            || self.dsv41.is_some()
22203            || self.dory.is_some()
22204            || self.qwen4_exp.is_some()
22205            || self.glm5_next.is_some()
22206            || self.hy4.is_some()
22207            || self.maxwell.is_some()
22208            || self.inkling.is_some()
22209            // Dynamic routing swaps FFN weights mid-sequence under the
22210            // packed graph; a blend has no single overlay. A STATIC skill
22211            // (`from_model_with_skill`) is fine: the pack reads the live
22212            // `weights.layers[*].ffn`, i.e. the skill's tensors, and a
22213            // later `set_active_skill` change drops the pack
22214            // (`invalidate_for_weight_change`).
22215            || self.dyn_router.is_some()
22216            || self.dyn_phi_layer.is_some()
22217            || self.dyn_blend_loaded
22218            || self.o1_cfg.is_some()
22219            || self.swa.is_some()
22220            || self.sliding_layers.is_some()
22221            || self.global_attn.is_some()
22222            || self.attention_heads_per_layer.is_some()
22223            || self.attn_v_norm
22224            || self
22225                .kv_cache
22226                .layers
22227                .iter()
22228                .any(|l| l.mode != crate::kv_cache::KvMode::F32)
22229            || self.rope_scale != 1.0
22230            || self.rope_scale_local != 1.0
22231            || self.attn_scale != 1.0 / (self.head_dim as f32).sqrt()
22232            || self.hidden_size == 0
22233            || self.hidden_size > 1024
22234            || self.intermediate_size > 1024
22235            || self.num_heads == 0
22236            || self.num_kv_heads == 0
22237            || self.num_heads % self.num_kv_heads != 0
22238            || self.num_heads.saturating_mul(self.head_dim) > 1024
22239            || self.num_kv_heads.saturating_mul(self.head_dim) > 1024
22240            || self.vocab_size == 0
22241            || self.kv_cache.max_seq_len == 0
22242            || self.rotary_dim == 0
22243            || self.rotary_dim > self.head_dim
22244            || self.rotary_dim % 2 != 0
22245            || self.inv_freq.len() < self.rotary_dim / 2
22246        {
22247            return false;
22248        }
22249        // The resident shaders read f32 or f16 values, or q8_2f codes through
22250        // the same formula as the CPU path. Other quantized files keep the
22251        // ordinary executor: dequantizing a Q4 tensor into the packed buffer
22252        // would silently change the operator relative to the CPU quantized
22253        // path. Measured consequence (RTX PRO 4000, S4 bounded export requantized
22254        // with `cortiq requant --quant q4tp-quantize`): `eligible=false`,
22255        // the generic wgpu whole-token graph refuses too, and the per-op
22256        // path decodes at ~73 tok/s against ~200 tok/s on the CPU q4tp path.
22257        if self.weights.lm_head.q8_2f_codes().is_some() && !self.embryo_wide_candidate(true) {
22258            return false;
22259        }
22260        if !served(&self.weights.lm_head)
22261            || !served(&self.weights.embed_tokens)
22262            || self.weights.lm_head.rows() < self.vocab_size
22263            || self.weights.lm_head.cols() != self.hidden_size
22264            || self.weights.embed_tokens.rows() < self.vocab_size
22265            || self.weights.embed_tokens.cols() != self.hidden_size
22266            || self.weights.final_norm.len() != self.hidden_size
22267        {
22268            return false;
22269        }
22270        if let Some(cfg) = self.vmf_cfg {
22271            if cfg.num_heads.saturating_mul(cfg.nphase) > 1024
22272                || cfg.num_heads.saturating_mul(cfg.nphase.saturating_add(1)) > 1024
22273                || cfg.num_heads.saturating_mul(cfg.value_head_dim) > 1024
22274                || cfg.state_len() == 0
22275            {
22276                return false;
22277            }
22278        }
22279        if let Some(g) = self.gdn_cfg {
22280            // The resident GDN kernels (gpu_wgpu.rs `embryo_core_gdn_*`):
22281            // fused projection ≤ 2048 rows, nv·dv ≤ 1024, dk ≤ 128 lanes,
22282            // dv ≤ 256 lanes in vec4 rows, SiLU output gate (the Embryo
22283            // export), same rms eps as the stack.
22284            if g.num_v_heads == 0
22285                || g.num_k_heads == 0
22286                || g.num_v_heads % g.num_k_heads != 0
22287                || g.key_head_dim == 0
22288                || g.key_head_dim > 128
22289                || g.value_head_dim == 0
22290                || g.value_head_dim > 256
22291                || g.value_head_dim % 4 != 0
22292                || g.conv_kernel == 0
22293                || g.num_v_heads > 512
22294                || g.num_v_heads.saturating_mul(g.value_head_dim) > 1024
22295                || g.conv_dim() > 2048
22296                || g.conv_dim() % 4 != 0
22297                || g.hidden_size != self.hidden_size
22298                || g.output_gate_sigmoid
22299                || g.rms_eps != self.rms_eps
22300                || g.state_len() == 0
22301            {
22302                return false;
22303            }
22304        }
22305        let mut full_seen = false;
22306        for lw in &self.weights.layers {
22307            if lw.attn_out_norm.is_some() || lw.ffn_out_norm.is_some() || lw.layer_scale.is_some() {
22308                return false;
22309            }
22310            match &lw.attn {
22311                AttnKind::LinearGdn(w) => {
22312                    let Some(g) = self.gdn_cfg else {
22313                        return false;
22314                    };
22315                    let (nv, dv, kk) = (g.num_v_heads, g.value_head_dim, g.conv_kernel);
22316                    if w.in_proj_qkv.rows() != g.conv_dim()
22317                        || w.in_proj_qkv.cols() != self.hidden_size
22318                        || !served(&w.in_proj_qkv)
22319                        || w.in_proj_z.rows() != nv * dv
22320                        || w.in_proj_z.cols() != self.hidden_size
22321                        || !served(&w.in_proj_z)
22322                        || w.in_proj_a.rows() != nv
22323                        || w.in_proj_a.cols() != self.hidden_size
22324                        || !served(&w.in_proj_a)
22325                        || w.in_proj_b.rows() != nv
22326                        || w.in_proj_b.cols() != self.hidden_size
22327                        || !served(&w.in_proj_b)
22328                        || w.conv1d.len() != g.conv_dim() * kk
22329                        || w.a_log.len() != nv
22330                        || w.dt_bias.len() != nv
22331                        || w.norm.len() != dv
22332                        || w.out_proj.rows() != self.hidden_size
22333                        || w.out_proj.cols() != nv * dv
22334                        || !served(&w.out_proj)
22335                    {
22336                        return false;
22337                    }
22338                }
22339                AttnKind::Linear(w) => {
22340                    let Some(cfg) = self.vmf_cfg else {
22341                        return false;
22342                    };
22343                    if w.thq.rows() != cfg.num_heads * cfg.nphase
22344                        || w.thq.cols() != self.hidden_size
22345                        || !served(&w.thq)
22346                        || w.thk.rows() != cfg.num_heads * cfg.nphase
22347                        || w.thk.cols() != self.hidden_size
22348                        || !served(&w.thk)
22349                        || w.v_proj.rows() != cfg.num_heads * cfg.value_head_dim
22350                        || w.v_proj.cols() != self.hidden_size
22351                        || !served(&w.v_proj)
22352                        || w.out_proj.rows() != self.hidden_size
22353                        || w.out_proj.cols() != cfg.num_heads * cfg.value_head_dim
22354                        || !served(&w.out_proj)
22355                        || w.decay.len() != cfg.num_heads * 2 * cfg.nphase
22356                    {
22357                        return false;
22358                    }
22359                    if let Some((kg, kb)) = &w.k_gate {
22360                        if kg.rows() != cfg.num_heads
22361                            || kg.cols() != self.hidden_size
22362                            || !served(&kg)
22363                            || kb.len() != cfg.num_heads
22364                        {
22365                            return false;
22366                        }
22367                    }
22368                    if let Some(conv) = &w.conv {
22369                        if conv.len() % self.hidden_size != 0 || conv.len() / self.hidden_size < 2 {
22370                            return false;
22371                        }
22372                    }
22373                }
22374                AttnKind::Full {
22375                    wq,
22376                    wk,
22377                    wv,
22378                    wo,
22379                    q_norm,
22380                    k_norm,
22381                    output_gate,
22382                    softplus_gate,
22383                    bias,
22384                } => {
22385                    if full_seen
22386                        || q_norm.is_some()
22387                        || k_norm.is_some()
22388                        || *output_gate
22389                        || softplus_gate.is_some()
22390                        || bias.is_some()
22391                        || !served(&wq)
22392                        || !served(&wk)
22393                        || !served(&wv)
22394                        || !served(&wo)
22395                        || wq.rows() != self.num_heads * self.head_dim
22396                        || wk.rows() != self.num_kv_heads * self.head_dim
22397                        || wv.rows() != self.num_kv_heads * self.head_dim
22398                        || wq.cols() != self.hidden_size
22399                        || wk.cols() != self.hidden_size
22400                        || wv.cols() != self.hidden_size
22401                        || wo.rows() != self.hidden_size
22402                        || wo.cols() != self.num_heads * self.head_dim
22403                    {
22404                        return false;
22405                    }
22406                    full_seen = true;
22407                }
22408                AttnKind::Bounded(w) => {
22409                    // The resident bounded attend walks S + W keys in
22410                    // 256-lane tiles (online softmax), any window the format
22411                    // allows; per-group windows come from header word 22.
22412                    let Some(ac) = self.anchor_core.as_ref() else {
22413                        return false;
22414                    };
22415                    if self.bounded_rope.is_none()
22416                        || w.window != ac.window
22417                        || w.sink != ac.sink
22418                        || w.group_windows != ac.group_windows
22419                        || w.window == 0
22420                        || w.sink_k.len() != self.num_kv_heads * w.sink * self.head_dim
22421                        || w.sink_v.len() != self.num_kv_heads * w.sink * self.head_dim
22422                        || !served(&w.wq)
22423                        || !served(&w.wk)
22424                        || !served(&w.wv)
22425                        || !served(&w.wo)
22426                        || w.wq.rows() != self.num_heads * self.head_dim
22427                        || w.wk.rows() != self.num_kv_heads * self.head_dim
22428                        || w.wv.rows() != self.num_kv_heads * self.head_dim
22429                        || w.wq.cols() != self.hidden_size
22430                        || w.wk.cols() != self.hidden_size
22431                        || w.wv.cols() != self.hidden_size
22432                        || w.wo.rows() != self.hidden_size
22433                        || w.wo.cols() != self.num_heads * self.head_dim
22434                    {
22435                        return false;
22436                    }
22437                }
22438                _ => return false,
22439            }
22440            match &lw.ffn {
22441                FfnKind::Dense(d) => {
22442                    if d.act != Act::Silu
22443                        || !d.segs.is_empty()
22444                        || !served(&d.gate_proj)
22445                        || !served(&d.up_proj)
22446                        || !served(&d.down_proj)
22447                        || d.gate_proj.rows() != self.intermediate_size
22448                        || d.gate_proj.cols() != self.hidden_size
22449                        || d.up_proj.rows() != self.intermediate_size
22450                        || d.up_proj.cols() != self.hidden_size
22451                        || d.down_proj.rows() != self.hidden_size
22452                        || d.down_proj.cols() != self.intermediate_size
22453                    {
22454                        return false;
22455                    }
22456                }
22457                FfnKind::Moe(m) => {
22458                    if m.resonance.is_none()
22459                        || m.top_k != 1
22460                        || m.router_sigmoid
22461                        || !m.norm_topk_prob
22462                        || m.expert_bias.is_some()
22463                        || m.routed_scaling != 1.0
22464                        || m.route_tau.is_some()
22465                        || m.shared.is_none()
22466                        || m.mask.is_some()
22467                        || m.per_expert_scale.is_some()
22468                        || m.router_input_norm
22469                        || m.experts.is_empty()
22470                        || m.experts.len() > 8
22471                    {
22472                        return false;
22473                    }
22474                    let r = m.resonance.as_ref().unwrap();
22475                    if r.mu.len() != m.experts.len() * self.hidden_size
22476                        || r.bias.len() != m.experts.len()
22477                        || r.u.len() != m.experts.len() * r.k * self.hidden_size
22478                        || r.k > 128
22479                    {
22480                        return false;
22481                    }
22482                    let Some((shared, gate)) = &m.shared else {
22483                        return false;
22484                    };
22485                    if gate.is_some() || shared.act != Act::Silu || !shared.segs.is_empty() {
22486                        return false;
22487                    }
22488                    if !served(&shared.gate_proj)
22489                        || !served(&shared.up_proj)
22490                        || !served(&shared.down_proj)
22491                        || shared.gate_proj.rows() != self.intermediate_size
22492                        || shared.gate_proj.cols() != self.hidden_size
22493                        || shared.up_proj.rows() != self.intermediate_size
22494                        || shared.up_proj.cols() != self.hidden_size
22495                        || shared.down_proj.rows() != self.hidden_size
22496                        || shared.down_proj.cols() != self.intermediate_size
22497                    {
22498                        return false;
22499                    }
22500                    for e in &m.experts {
22501                        if e.act != Act::Silu
22502                            || !e.segs.is_empty()
22503                            || !served(&e.gate_proj)
22504                            || !served(&e.up_proj)
22505                            || !served(&e.down_proj)
22506                            || e.gate_proj.rows() != self.intermediate_size
22507                            || e.gate_proj.cols() != self.hidden_size
22508                            || e.up_proj.rows() != self.intermediate_size
22509                            || e.up_proj.cols() != self.hidden_size
22510                            || e.down_proj.rows() != self.hidden_size
22511                            || e.down_proj.cols() != self.intermediate_size
22512                        {
22513                            return false;
22514                        }
22515                    }
22516                }
22517                FfnKind::DenseMoe(_) => return false,
22518            }
22519            if lw.input_norm.len() != self.hidden_size || lw.post_norm.len() != self.hidden_size {
22520                return false;
22521            }
22522        }
22523        if full_seen && self.anchor_core.is_some() {
22524            return false;
22525        }
22526        full_seen || self.num_layers > 0
22527    }
22528
22529    /// The resident Embryo graph is the owner of this pipeline's forward:
22530    /// the same gate `forward_layers_span` applies before handing a token
22531    /// to `forward_embryo_graph` (both graph phases on, the explicit
22532    /// opt-in, a wgpu device, no earlier refusal, an eligible stack).
22533    fn embryo_resident_wanted(&self) -> bool {
22534        crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)
22535            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill)
22536            && matches!(
22537                std::env::var("CMF_EMBRYO_RESIDENT").as_deref(),
22538                Ok("1") | Ok("parallel")
22539            )
22540            && crate::gpu::enabled_here()
22541            && !self.graph_refused()
22542            && self.embryo_resident_eligible()
22543    }
22544
22545    /// Chunked prefill on the resident graph: `ids` from `start` in
22546    /// chunks of `EMBRYO_CHUNK_MAX`, one submit each, projections/FFN as
22547    /// chunk GEMMs and the recurrent layers walked in time on the device.
22548    /// Returns the last position's logits when the whole span ran there.
22549    /// `None` = refused before any device work (the per-position path
22550    /// takes the span).  `CMF_EMBRYO_CHUNK=0` keeps the per-position
22551    /// prefill (A/B and the parity reference).
22552    fn embryo_prefill_chunked(&mut self, ids: &[u32], start: usize) -> Option<Vec<f32>> {
22553        if ids.len() < 2
22554            || std::env::var("CMF_EMBRYO_CHUNK").as_deref() == Ok("0")
22555            || !self.embryo_resident_wanted()
22556        {
22557            return None;
22558        }
22559        let model = self.ensure_embryo_graph()?;
22560        let cmax = std::env::var("CMF_EMBRYO_CHUNK")
22561            .ok()
22562            .and_then(|v| v.parse::<usize>().ok())
22563            .filter(|&v| v >= 1)
22564            .unwrap_or(crate::gpu::EMBRYO_CHUNK_MAX)
22565            .min(crate::gpu::EMBRYO_CHUNK_MAX);
22566        let hs = self.hidden_size;
22567        let n = ids.len();
22568        let mut pos = start;
22569        let mut last = None;
22570        let mut rows = Vec::with_capacity(cmax * hs);
22571        while pos < n {
22572            let end = (pos + cmax).min(n);
22573            rows.clear();
22574            for &id in &ids[pos..end] {
22575                rows.extend_from_slice(&self.embed_single(id));
22576            }
22577            let mut lg = Vec::new();
22578            if !crate::gpu::forward_embryo_graph_chunk(
22579                &model,
22580                self.graph_kv_id,
22581                &rows,
22582                pos,
22583                end - pos,
22584                &mut lg,
22585            ) {
22586                if pos == start {
22587                    if std::env::var("CMF_EMBRYO_DBG").as_deref() == Ok("1") {
22588                        eprintln!("embryo-dbg: chunk prefill refused at position {pos}");
22589                    }
22590                    return None;
22591                }
22592                // The device sequence advanced through the earlier chunks;
22593                // a host continuation would mix two owners of the state.
22594                // Fail this sequence alone, leaving no stale state or key.
22595                self.kv_cache.clear();
22596                self.clear_history();
22597                crate::gpu::graph_kv_reset(self.graph_kv_id);
22598                panic!(
22599                    "resident Embryo chunk prefill refused at position {pos}; refusing an in-flight host fallback"
22600                );
22601            }
22602            last = Some(lg);
22603            pos = end;
22604        }
22605        if std::env::var("CMF_EMBRYO_DBG").as_deref() == Ok("1") {
22606            eprintln!(
22607                "embryo-dbg: chunk prefill {} ids from {start} in {} submits (chunk {cmax})",
22608                n - start,
22609                (n - start).div_ceil(cmax)
22610            );
22611        }
22612        last
22613    }
22614
22615    /// Can this file run the wide token path? GDN mixers, bounded anchors, and
22616    /// rows and columns that fit the kernels' four-row, eight-column grid.
22617    fn embryo_wide_candidate(&self, q8: bool) -> bool {
22618        if self.embryo_wide_refused
22619            || std::env::var("CMF_EMBRYO_WIDE").as_deref() == Ok("0")
22620            || !crate::gpu::embryo_wide_ready(q8)
22621        {
22622            return false;
22623        }
22624        let Some(g) = self.gdn_cfg else {
22625            return false;
22626        };
22627        let (hidden, inter, hd) = (self.hidden_size, self.intermediate_size, self.head_dim);
22628        let (nv, nk, dk, dv) = (g.num_v_heads, g.num_k_heads, g.key_head_dim, g.value_head_dim);
22629        let (q, kv) = (self.num_heads, self.num_kv_heads);
22630        // A q8_2f row is read 16 codes at a time, an f16 row 8 values at a time.
22631        let step = if q8 { 16 } else { 8 };
22632        let geometry = hidden % step == 0
22633            && hidden <= 1024
22634            && inter % step == 0
22635            && inter <= 1024
22636            && self.vocab_size % 4 == 0
22637            && self.head_clusters.as_ref().is_some_and(|c| {
22638                let nc = c.len() / hidden.max(1);
22639                // A workgroup holds a cluster's rows.
22640                nc > 0 && nc <= 256 && self.vocab_size % nc == 0 && self.vocab_size / nc <= 256
22641            })
22642            && dk % 4 == 0
22643            && dv % 4 == 0
22644            && (nv * dv) % step == 0
22645            && nv * dv <= 1024
22646            && nv <= 508
22647            && nk > 0
22648            && nv % nk == 0
22649            && g.conv_dim() % 4 == 0
22650            && g.conv_dim() <= 2048
22651            && hd % 4 == 0
22652            && (q * hd) % step == 0
22653            && q * hd <= 1024
22654            && kv > 0
22655            && q % kv == 0
22656            && (kv * hd) % 4 == 0
22657            && (self.rotary_dim / 2) % 4 == 0;
22658        if !geometry {
22659            return false;
22660        }
22661        self.weights.layers.iter().all(|lw| {
22662            matches!(lw.attn, AttnKind::Bounded(_) | AttnKind::LinearGdn(_))
22663                && match &lw.ffn {
22664                    FfnKind::Moe(m) => m.resonance.as_ref().is_some_and(|r| m.experts.len() * (r.k + 1) <= 256) && m.shared.is_some(),
22665                    FfnKind::Dense(_) => true,
22666                    FfnKind::DenseMoe(_) => false,
22667                }
22668        })
22669    }
22670
22671    fn ensure_embryo_graph(&mut self) -> Option<std::sync::Arc<crate::gpu::EmbryoGraphModel>> {
22672        if self.embryo_graph.is_none() && self.embryo_resident_eligible() {
22673            const UMAX: u32 = u32::MAX;
22674            const HEADER: usize = crate::gpu::EMBRYO_META_HEADER;
22675            const REC: usize = 64;
22676            struct Pack {
22677                data: Vec<f32>,
22678                /// The wide token path: matrices in their packed form in `mats`.
22679                wide: bool,
22680                q8: bool,
22681                mats: Vec<u8>,
22682                /// q8_2f: (codes, row scales, column field) of each matrix; its
22683                /// word in the layer record is its index in the meta after the layers.
22684                table: Vec<u32>,
22685                table_base: u32,
22686                refused: bool,
22687            }
22688            impl Pack {
22689                fn put(&mut self, x: &[f32]) -> u32 {
22690                    if x.is_empty() {
22691                        return u32::MAX;
22692                    }
22693                    // The wide kernels read the small tensors as vec4
22694                    if self.wide {
22695                        self.data.resize(self.data.len().next_multiple_of(4), 0.0);
22696                    }
22697                    let off = self.data.len();
22698                    self.data.extend_from_slice(x);
22699                    off as u32
22700                }
22701                /// A matrix a token reads in full.
22702                fn mat(&mut self, t: &QTensor) -> u32 {
22703                    if !self.wide {
22704                        return self.put(&Pipeline::embryo_qtensor_f32(t));
22705                    }
22706                    if self.q8 {
22707                        let Some((q, rows, cols)) = t.q8_2f_codes() else {
22708                            self.refused = true;
22709                            return 0;
22710                        };
22711                        self.mats.resize(self.mats.len().next_multiple_of(16), 0);
22712                        let off = self.mats.len() as u32;
22713                        self.mats.extend_from_slice(&q[..t.rows() * t.cols()]);
22714                        let (rs, cs) = (self.put(rows), self.put(cols));
22715                        let e = self.table_base + self.table.len() as u32;
22716                        self.table.extend_from_slice(&[off, rs, cs]);
22717                        return e;
22718                    }
22719                    self.mats.resize(self.mats.len().next_multiple_of(16), 0);
22720                    let off = self.mats.len() / 2;
22721                    for v in Pipeline::embryo_qtensor_f32(t) {
22722                        let h = cortiq_core::quant::f32_to_f16(v);
22723                        self.refused |= cortiq_core::quant::f16_to_f32(h).to_bits() != v.to_bits();
22724                        self.mats.extend_from_slice(&h.to_le_bytes());
22725                    }
22726                    off as u32
22727                }
22728            }
22729            // The mixer family of the file: vmf_phase geometry fills the
22730            // phase header words, gated_delta_net fills words 24..29.  A
22731            // file has exactly one linear core, so at most one is live.
22732            let vmf = self.vmf_cfg;
22733            let gdn = self.gdn_cfg;
22734            // A file of q8_2f matrices or of matrices exact in f16 runs the wide path.
22735            let q8 = self.weights.lm_head.q8_2f_codes().is_some();
22736            let wide = self.embryo_wide_candidate(q8);
22737            let mut pack = Pack {
22738                data: Vec::new(),
22739                wide,
22740                q8,
22741                mats: Vec::new(),
22742                table: Vec::new(),
22743                table_base: (HEADER + self.num_layers * REC) as u32,
22744                refused: false,
22745            };
22746            let mut meta = vec![0u32; HEADER];
22747            meta[0] = self.hidden_size as u32;
22748            meta[1] = self.intermediate_size as u32;
22749            meta[2] = self.vocab_size as u32;
22750            meta[3] = self.num_layers as u32;
22751            meta[4] = vmf.map(|c| c.num_heads).unwrap_or(0) as u32;
22752            meta[5] = vmf.map(|c| c.nphase).unwrap_or(0) as u32;
22753            meta[6] = vmf.map(|c| c.value_head_dim).unwrap_or(0) as u32;
22754            if let Some(g) = gdn {
22755                meta[24] = g.num_v_heads as u32;
22756                meta[25] = g.num_k_heads as u32;
22757                meta[26] = g.key_head_dim as u32;
22758                meta[27] = g.value_head_dim as u32;
22759                meta[28] = g.conv_kernel as u32;
22760                meta[29] = g.conv_dim() as u32;
22761            }
22762            meta[7] = self.num_heads as u32;
22763            meta[8] = self.num_kv_heads as u32;
22764            meta[9] = self.head_dim as u32;
22765            meta[10] = self.kv_cache.max_seq_len as u32;
22766            let clusters = self.head_clusters.as_ref().unwrap();
22767            let cluster_count = clusters.len() / self.hidden_size;
22768            if clusters.len() % self.hidden_size != 0
22769                || cluster_count == 0
22770                || cluster_count > 1024
22771                || self.vocab_size % cluster_count != 0
22772                || self.weights.lm_head.rows() < self.vocab_size
22773                || self.weights.final_norm.len() != self.hidden_size
22774            {
22775                return None;
22776            }
22777            meta[11] = cluster_count as u32;
22778            meta[12] = (self.vocab_size / cluster_count) as u32;
22779            meta[13] = vmf.map(|c| c.state_len()).unwrap_or(0) as u32;
22780            meta[16] = self.rotary_dim as u32;
22781            meta[17] = matches!(self.norm_style, NormStyle::Gemma) as u32;
22782            meta[19] = (self.rms_eps as f32).to_bits();
22783            let max_conv = self
22784                .weights
22785                .layers
22786                .iter()
22787                .filter_map(|lw| match &lw.attn {
22788                    AttnKind::Linear(w) => w.conv.as_ref().map(|v| v.len() / self.hidden_size),
22789                    _ => None,
22790                })
22791                .max()
22792                .unwrap_or(1);
22793            // One state slot per recurrent layer: the phase state plus its
22794            // hidden-wide conv ring, or the GDN record `[conv ring | S]`
22795            // (`GdnCfg::state_len`).  A file carries one mixer family, so
22796            // the stride is exactly that family's record and the device
22797            // state buffer equals the header's recurrent bytes.
22798            let phase_stride = vmf
22799                .map(|c| c.state_len() + max_conv.saturating_sub(1) * self.hidden_size)
22800                .unwrap_or(0);
22801            let gdn_stride = gdn.map(|g| g.state_len()).unwrap_or(0);
22802            let state_stride = phase_stride.max(gdn_stride);
22803            // Bounded genome: the KV plane of an anchor is its ring
22804            // `[kvh][W][hd]` K + V, and only anchors own one.  Legacy full
22805            // anchors keep the `max_seq` planes indexed by layer.
22806            let bounded = self.anchor_core.clone();
22807            let (anchor_window, anchor_sink) = bounded
22808                .as_ref()
22809                .map(|ac| (ac.window, ac.sink))
22810                .unwrap_or((0, 0));
22811            let kv_stride = if bounded.is_some() {
22812                2usize
22813                    .saturating_mul(self.num_kv_heads)
22814                    .saturating_mul(anchor_window)
22815                    .saturating_mul(self.head_dim)
22816            } else {
22817                2usize
22818                    .saturating_mul(self.num_kv_heads)
22819                    .saturating_mul(self.kv_cache.max_seq_len)
22820                    .saturating_mul(self.head_dim)
22821            };
22822            meta[14] = state_stride as u32;
22823            meta[15] = kv_stride as u32;
22824            meta[18] = anchor_window as u32;
22825            meta[20] = anchor_sink as u32;
22826            // Scores, weights and the key list of each head fit the wide scratch plane.
22827            pack.refused |= pack.wide
22828                && 3 * self.num_heads * (anchor_window + anchor_sink + 3) + 256 > 65_536;
22829            meta[21] = match &self.bounded_rope {
22830                // The wide path rotates by the absolute position: no table.
22831                _ if pack.wide => UMAX,
22832                Some(rope) => {
22833                    // [W][half] cos then [W][half] sin, one contiguous table.
22834                    let off = pack.put(&rope.cos);
22835                    let _ = pack.put(&rope.sin);
22836                    off
22837                }
22838                None => UMAX,
22839            };
22840            // swa_sink_v2: one window per KV group (f32 in the pack; exact
22841            // for any window the format allows); UMAX = every group `W`.
22842            meta[22] = match bounded.as_ref().filter(|ac| !ac.group_windows.is_empty()) {
22843                Some(ac) => {
22844                    let gw: Vec<f32> = ac.group_windows.iter().map(|&w| w as f32).collect();
22845                    pack.put(&gw)
22846                }
22847                None => UMAX,
22848            };
22849            let mut full_seen = false;
22850            let mut bounded_seen = 0usize;
22851            // Recurrent state slots belong to mixer layers only (phase or
22852            // GDN): an anchor owns a ring, not a state stride, so the
22853            // device state buffer is exactly the header's recurrent bytes.
22854            let mut phase_seen = 0usize;
22855            let mut gdn_seen = 0usize;
22856            for (li, lw) in self.weights.layers.iter().enumerate() {
22857                let base = meta.len();
22858                meta.resize(base + REC, UMAX);
22859                meta[base] = match &lw.attn {
22860                    AttnKind::Linear(w) if w.phase_delta => 1,
22861                    AttnKind::Linear(_) => 0,
22862                    AttnKind::Full { .. } => 2,
22863                    AttnKind::Bounded(_) => 3,
22864                    AttnKind::LinearGdn(_) => 4,
22865                    _ => UMAX,
22866                };
22867                meta[base + 1] = pack.put(&lw.input_norm);
22868                meta[base + 2] = pack.put(&lw.post_norm);
22869                meta[base + 25] = match &lw.attn {
22870                    AttnKind::Linear(_) => {
22871                        let off = ((phase_seen + gdn_seen) * state_stride) as u32;
22872                        phase_seen += 1;
22873                        off
22874                    }
22875                    AttnKind::LinearGdn(_) => {
22876                        let off = ((phase_seen + gdn_seen) * state_stride) as u32;
22877                        gdn_seen += 1;
22878                        off
22879                    }
22880                    _ => UMAX,
22881                };
22882                match &lw.attn {
22883                    AttnKind::LinearGdn(w) => {
22884                        // Layer record words 56..63 + 29, as the resident
22885                        // kernels read them (gpu_wgpu.rs `embryo_core_gdn_*`).
22886                        meta[base + 56] = pack.mat(&w.in_proj_qkv);
22887                        meta[base + 57] = pack.mat(&w.in_proj_z);
22888                        meta[base + 58] = pack.mat(&w.in_proj_a);
22889                        meta[base + 59] = pack.mat(&w.in_proj_b);
22890                        meta[base + 60] = pack.put(&w.conv1d);
22891                        meta[base + 61] = pack.put(&w.a_log);
22892                        meta[base + 62] = pack.put(&w.dt_bias);
22893                        meta[base + 63] = pack.put(&w.norm);
22894                        meta[base + 29] = pack.mat(&w.out_proj);
22895                        meta[base + 24] = 0;
22896                    }
22897                    AttnKind::Linear(w) => {
22898                        meta[base + 3] = pack.mat(&w.thq);
22899                        meta[base + 4] = pack.mat(&w.thk);
22900                        meta[base + 5] = pack.mat(&w.v_proj);
22901                        meta[base + 6] = pack.mat(&w.out_proj);
22902                        let decay: Vec<f32> = w.decay.iter().map(|&x| x as f32).collect();
22903                        meta[base + 7] = pack.put(&decay);
22904                        if let Some((kg, kb)) = &w.k_gate {
22905                            meta[base + 8] = pack.mat(&kg);
22906                            meta[base + 9] = pack.put(kb);
22907                        }
22908                        if let Some(conv) = &w.conv {
22909                            meta[base + 10] = pack.put(conv);
22910                            meta[base + 24] = (conv.len() / self.hidden_size) as u32;
22911                        } else {
22912                            meta[base + 24] = 0;
22913                        }
22914                    }
22915                    AttnKind::Full { wq, wk, wv, wo, .. } => {
22916                        full_seen = true;
22917                        meta[base + 11] = pack.mat(&wq);
22918                        meta[base + 12] = pack.mat(&wk);
22919                        meta[base + 13] = pack.mat(&wv);
22920                        meta[base + 14] = pack.mat(&wo);
22921                        meta[base + 26] = (li * kv_stride) as u32;
22922                    }
22923                    AttnKind::Bounded(w) => {
22924                        meta[base + 11] = pack.mat(&w.wq);
22925                        meta[base + 12] = pack.mat(&w.wk);
22926                        meta[base + 13] = pack.mat(&w.wv);
22927                        meta[base + 14] = pack.mat(&w.wo);
22928                        // Ring slot of this anchor (anchors only, packed).
22929                        meta[base + 26] = (bounded_seen * kv_stride) as u32;
22930                        meta[base + 27] = pack.put(&w.sink_k);
22931                        meta[base + 28] = pack.put(&w.sink_v);
22932                        bounded_seen += 1;
22933                    }
22934                    _ => return None,
22935                }
22936                match &lw.ffn {
22937                    FfnKind::Dense(d) => {
22938                        meta[base + 15] = 0;
22939                        meta[base + 16] = 0;
22940                        meta[base + 21] = pack.mat(&d.gate_proj);
22941                        meta[base + 22] = pack.mat(&d.up_proj);
22942                        meta[base + 23] = pack.mat(&d.down_proj);
22943                    }
22944                    FfnKind::Moe(m) => {
22945                        let r = m.resonance.as_ref().unwrap();
22946                        let (shared, _) = m.shared.as_ref().unwrap();
22947                        meta[base + 15] = 1;
22948                        meta[base + 16] = m.experts.len() as u32;
22949                        meta[base + 17] = pack.put(&r.mu);
22950                        meta[base + 18] = pack.put(&r.u);
22951                        meta[base + 19] = pack.put(&r.bias);
22952                        meta[base + 20] = r.k as u32;
22953                        // Word 30: the growth shell as the runtime applies
22954                        // it now (`+inf` on trunk rows, the stored finite
22955                        // shell on grown rows, all `+inf` under
22956                        // `CMF_GROWTH_SHELL=off`), followed by one `−∞`
22957                        // sentinel at index E the kernel writes as the
22958                        // score of an expert outside its shell — WGSL has
22959                        // no infinity literal, so the value travels as
22960                        // data (`embryo_core_route_finalize`).
22961                        let mut shell = r.effective_shell(m.experts.len());
22962                        shell.push(f32::NEG_INFINITY);
22963                        meta[base + 30] = pack.put(&shell);
22964                        meta[base + 21] = pack.mat(&shared.gate_proj);
22965                        meta[base + 22] = pack.mat(&shared.up_proj);
22966                        meta[base + 23] = pack.mat(&shared.down_proj);
22967                        for (e, ex) in m.experts.iter().enumerate() {
22968                            meta[base + 32 + e * 3] =
22969                                pack.mat(&ex.gate_proj);
22970                            meta[base + 33 + e * 3] =
22971                                pack.mat(&ex.up_proj);
22972                            meta[base + 34 + e * 3] =
22973                                pack.mat(&ex.down_proj);
22974                        }
22975                    }
22976                    FfnKind::DenseMoe(_) => return None,
22977                }
22978            }
22979            if !full_seen && self.num_layers == 0 {
22980                return None;
22981            }
22982            let mut lm_head = Vec::new();
22983            let mut lm_head_packed = Vec::new();
22984            if wide && q8 {
22985                let parts = self.weights.lm_head.q8_2f_codes();
22986                if let Some((q, rows, cols)) = parts {
22987                    lm_head_packed = q[..self.weights.lm_head.rows() * self.weights.lm_head.cols()].to_vec();
22988                    let (rs, cs) = (pack.put(rows), pack.put(cols));
22989                    meta[30] = pack.table_base + pack.table.len() as u32;
22990                    pack.table.extend_from_slice(&[0, rs, cs]);
22991                }
22992                meta.extend_from_slice(&pack.table);
22993            } else if wide {
22994                for v in Self::embryo_qtensor_f32(&self.weights.lm_head) {
22995                    let h = cortiq_core::quant::f32_to_f16(v);
22996                    pack.refused |= cortiq_core::quant::f16_to_f32(h).to_bits() != v.to_bits();
22997                    lm_head_packed.extend_from_slice(&h.to_le_bytes());
22998                }
22999            } else {
23000                lm_head = Self::embryo_qtensor_f32(&self.weights.lm_head);
23001            }
23002            if pack.refused {
23003                self.embryo_wide_refused = true;
23004                return self.ensure_embryo_graph();
23005            }
23006            let id = {
23007                static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
23008                NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
23009            };
23010            let model = crate::gpu::EmbryoGraphModel {
23011                id,
23012                hidden: self.hidden_size,
23013                intermediate: self.intermediate_size,
23014                vocab: self.vocab_size,
23015                layers: self.num_layers,
23016                phase_heads: vmf.map(|c| c.num_heads).unwrap_or(0),
23017                nphase: vmf.map(|c| c.nphase).unwrap_or(0),
23018                phase_dv: vmf.map(|c| c.value_head_dim).unwrap_or(0),
23019                anchor_q_heads: self.num_heads,
23020                anchor_kv_heads: self.num_kv_heads,
23021                anchor_head_dim: self.head_dim,
23022                rotary_dim: self.rotary_dim,
23023                rope_freq: if wide { self.inv_freq[..self.rotary_dim / 2].to_vec() } else { Vec::new() },
23024                max_seq: self.kv_cache.max_seq_len,
23025                cluster_count,
23026                cluster_size: self.vocab_size / cluster_count,
23027                phase_state_len: vmf.map(|c| c.state_len()).unwrap_or(0),
23028                state_stride,
23029                kv_stride,
23030                norm_gemma: matches!(self.norm_style, NormStyle::Gemma),
23031                phase_mass: vmf.map(|c| c.phase_mass).unwrap_or(0.0),
23032                weights: pack.data,
23033                meta,
23034                lm_head,
23035                wide,
23036                wide_q8: wide && q8,
23037                mats: pack.mats,
23038                lm_head_packed,
23039                clusters: clusters.as_ref().clone(),
23040                final_norm: self.weights.final_norm.clone(),
23041                inv_freq: self.inv_freq.as_ref().clone(),
23042                bounded: bounded.is_some(),
23043                kv_layers: if bounded.is_some() {
23044                    bounded_seen
23045                } else {
23046                    self.num_layers
23047                },
23048                state_layers: phase_seen + gdn_seen,
23049                anchor_window,
23050                anchor_sink,
23051                phase_layers: phase_seen,
23052                gdn_layers: gdn_seen,
23053                gdn_heads: gdn.map(|g| g.num_v_heads).unwrap_or(0),
23054                gdn_k_heads: gdn.map(|g| g.num_k_heads).unwrap_or(0),
23055                gdn_dk: gdn.map(|g| g.key_head_dim).unwrap_or(0),
23056                gdn_dv: gdn.map(|g| g.value_head_dim).unwrap_or(0),
23057                gdn_kk: gdn.map(|g| g.conv_kernel).unwrap_or(0),
23058            };
23059            self.embryo_graph = Some(std::sync::Arc::new(model));
23060        }
23061        self.embryo_graph.clone()
23062    }
23063
23064    fn forward_layers_span(
23065        &mut self,
23066        hidden: &[f32],
23067        position: usize,
23068        task_mask: Option<&TaskMask>,
23069        from: usize,
23070        upto: Option<usize>,
23071    ) -> Vec<f32> {
23072        #[cfg(target_os = "macos")]
23073        let _metal_pager_token_prof = crate::gpu_metal::MoePagerTokenScope::new(
23074            position,
23075            from,
23076            upto.map_or(self.num_layers, |u| u.saturating_add(1)),
23077        );
23078        debug_assert!(
23079            from == 0
23080                || (self.dsv4.is_none()
23081                    && self.dsv41.is_none()
23082                    && self.qwen4_exp.is_none()
23083                    && self.glm5_next.is_none()
23084                    && self.hy4.is_none()
23085                    && self.maxwell.is_none()
23086                    && self.inkling.is_none()
23087                    && !self.per_token_stack())
23088        );
23089        // Every plain forward — the whole-token Metal graph (`q1_graph_gpu`
23090        // wraps the GDN owners zero-copy and reallocates them on a size
23091        // change) and the CPU layer loop (reads/swaps `linear_state`) —
23092        // must see the previous speculative commit's asynchronous replay
23093        // complete. One mutex probe when nothing is pending.
23094        #[cfg(target_os = "macos")]
23095        if !crate::gpu_metal::wait_replay() {
23096            self.fail_metal_graph("the pending async replay failed before a plain forward");
23097            return vec![0.0; self.hidden_size];
23098        }
23099        if let Some(b) = &mut self.glm5_next {
23100            let _ = (task_mask, upto);
23101            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
23102            let mut logits = Vec::new();
23103            crate::glm5_next::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, position, self.pool.as_deref(), &mut logits, true);
23104            self.graph_logits = Some(logits);
23105            return vec![0.0; self.hidden_size];
23106        }
23107        if let Some(b) = &mut self.hy4 {
23108            let _ = (task_mask, upto);
23109            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
23110            let mut logits = Vec::new();
23111            crate::hy4::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, position, self.pool.as_deref(), &mut logits, true);
23112            self.graph_logits = Some(logits);
23113            return vec![0.0; self.hidden_size];
23114        }
23115        if let Some(b) = &mut self.maxwell {
23116            let _ = (task_mask, upto);
23117            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
23118            let mut logits = Vec::new();
23119            crate::maxwell::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, position, self.pool.as_deref(), &mut logits, true);
23120            self.graph_logits = Some(logits);
23121            return vec![0.0; self.hidden_size];
23122        }
23123        if let Some(b) = &mut self.inkling {
23124            let _ = (task_mask, upto);
23125            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
23126            let mut logits = Vec::new();
23127            crate::inkling::forward_token(&b.0, &b.1, &b.2, &mut b.3, token_id, position, self.pool.as_deref(), &mut logits, true);
23128            self.graph_logits = Some(logits);
23129            return vec![0.0; self.hidden_size];
23130        }
23131        if let Some(b) = &mut self.qwen4_exp {
23132            let _ = (task_mask, upto);
23133            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
23134            let mut logits = Vec::new();
23135            crate::qwen4_exp::forward_token(
23136                &b.0,
23137                &b.1,
23138                &b.2,
23139                &mut b.3,
23140                token_id,
23141                position,
23142                &self.inv_freq,
23143                self.pool.as_deref(),
23144                &mut logits,
23145                true,
23146            );
23147            self.graph_logits = Some(logits);
23148            return vec![0.0; self.hidden_size];
23149        }
23150        // DeepSeek-V4 runs its own stack: the state is hc_mult copies, and
23151        // the forward returns LOGITS, not a hidden — the head is inside it
23152        // (the final fold sits between the last layer and the norm). The
23153        // token id rides in `hidden[0]`, written by embed_single, because
23154        // the hash layers route by id rather than by content.
23155        if let Some(b) = &mut self.dsv4 {
23156            let _ = (task_mask, upto);
23157            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
23158            let (g, layers, cfg, st) = (&b.0, &b.1, b.2, &mut b.3);
23159            st.pos = position;
23160            let mut logits = Vec::new();
23161            crate::dsv4::forward_token(
23162                g,
23163                layers,
23164                &cfg,
23165                st,
23166                token_id,
23167                &self.inv_freq,
23168                self.pool.as_deref(),
23169                &mut logits,
23170            );
23171            self.graph_logits = Some(logits);
23172            self.dspark_probe(position, token_id);
23173            // The caller expects a hidden; the logits went out of band, as
23174            // with the fused lm_head path.
23175            return vec![0.0; self.hidden_size];
23176        }
23177        // Dory owns its complete stack and emits logits out of band.
23178        if self.dory.is_some() {
23179            let _ = (task_mask, upto);
23180            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
23181            let lg = self.dory_forward(&[token_id], position, crate::dory::Want::Last);
23182            self.graph_logits = Some(lg);
23183            return vec![0.0; self.hidden_size];
23184        }
23185        // DeepSeek-V4.1 owns its complete stack and emits logits out of band.
23186        if let Some(b) = &mut self.dsv41 {
23187            let _ = (task_mask, upto);
23188            let token_id = hidden.first().copied().unwrap_or(0.0) as u32;
23189            let mut logits = Vec::new();
23190            crate::dsv41::forward_token(
23191                &b.0,
23192                &b.1,
23193                &b.2,
23194                &mut b.3,
23195                token_id,
23196                position,
23197                self.pool.as_deref(),
23198                &mut logits,
23199            );
23200            self.graph_logits = Some(logits);
23201            return vec![0.0; self.hidden_size];
23202        }
23203        // Gemma-3n runs its own stack (4 AltUp replicas don't fit this
23204        // loop); `hidden` is the extended embedding from embed_single.
23205        // Gemma-4 E-series: same hand-off — its dual-geometry attention
23206        // with shared-KV tail layers and the PLE injection live in
23207        // `g4e_forward`.
23208        if let Some(b) = &self.g4e {
23209            let _ = (task_mask, upto);
23210            return crate::g4e::g4e_forward(
23211                &b.0,
23212                &b.1,
23213                hidden,
23214                position,
23215                &mut self.kv_cache.layers,
23216                self.num_heads,
23217                self.num_kv_heads,
23218                self.pool.as_deref(),
23219            );
23220        }
23221        if let Some(b) = &self.g3n {
23222            let _ = (task_mask, upto);
23223            return crate::g3n::g3n_forward(
23224                &b.0,
23225                &b.1,
23226                hidden,
23227                position,
23228                &mut self.kv_cache.layers,
23229                self.num_heads,
23230                self.num_kv_heads,
23231                self.head_dim,
23232                self.pool.as_deref(),
23233            );
23234        }
23235        // Cortiq Embryo owns a separate resident graph: phase recurrent
23236        // state, resonance routing, the GQA anchor KV and hierarchical head
23237        // all execute in one Vulkan submit. It is limited to a complete
23238        // unmasked stack; spans and task masks retain the exact host path.
23239        // `CMF_EMBRYO_DBG=1` names the gate that keeps a token off the
23240        // resident graph — every refusal below is otherwise silent.
23241        if from == 0
23242            && upto.is_none()
23243            && task_mask.is_none()
23244            && self.anchor_core.is_some()
23245            && std::env::var("CMF_EMBRYO_DBG").as_deref() == Ok("1")
23246        {
23247            static ONCE: std::sync::Once = std::sync::Once::new();
23248            ONCE.call_once(|| {
23249                eprintln!(
23250                    "embryo-dbg: graph_on decode={} prefill={} resident_env={:?} enabled_here={} \
23251                     unsupported={} eligible={}",
23252                    crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode),
23253                    crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill),
23254                    std::env::var("CMF_EMBRYO_RESIDENT").ok(),
23255                    crate::gpu::enabled_here(),
23256                    self.graph_refused(),
23257                    self.embryo_resident_eligible(),
23258                );
23259            });
23260        }
23261        if from == 0
23262            && upto.is_none()
23263            && task_mask.is_none()
23264            // Embryo's recurrent/KV state has no host import path.  Do not
23265            // seed it for a prefill-only graph and then silently decode from
23266            // an empty CPU cache; both phases must select the resident owner.
23267            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Decode)
23268            && crate::gpu::wgpu_graph_on(crate::gpu::GraphPhase::Prefill)
23269            // This whole-token Embryo path remains explicitly opt-in.
23270            // `CMF_GPU_WGPU_GRAPH=1` still enables the mature generic graph,
23271            // but must not silently select this model-specific resident path.
23272            && matches!(
23273                std::env::var("CMF_EMBRYO_RESIDENT").as_deref(),
23274                Ok("1") | Ok("parallel")
23275            )
23276            && crate::gpu::enabled_here()
23277            && !self.graph_refused()
23278            // Sequence owner: past position zero the device continues only
23279            // a sequence it holds. A host-owned sequence (the graph refused
23280            // at its start, or its prefix was prefilled on the host) keeps
23281            // the host path to its end — never a device attempt at p > 0
23282            // over an empty device image.
23283            && (position == 0 || self.device_sequence_position().is_some())
23284            && self.embryo_resident_eligible()
23285            && let Some(model) = self.ensure_embryo_graph()
23286        {
23287            let mut lg = Vec::new();
23288            if crate::gpu::forward_embryo_graph(&model, self.graph_kv_id, hidden, position, &mut lg)
23289            {
23290                self.graph_logits = Some(lg);
23291                return vec![0.0; self.hidden_size];
23292            }
23293            if std::env::var("CMF_EMBRYO_DBG").as_deref() == Ok("1") {
23294                eprintln!("embryo-dbg: forward_embryo_graph refused at position {position}");
23295            }
23296            // The refusal is THIS pipeline's: falling through once is safe
23297            // at position zero (the host owns the sequence from here),
23298            // while a refusal at a later position of a device-owned
23299            // sequence would mix a host KV/state path with a partial
23300            // device sequence.
23301            self.mark_graph_refused();
23302            if position != 0 {
23303                // Fail this sequence alone and leave nothing stale behind:
23304                // no reuse key, no host or device state for the next
23305                // request on this slot to "extend".
23306                self.kv_cache.clear();
23307                self.clear_history();
23308                crate::gpu::graph_kv_reset(self.graph_kv_id);
23309                panic!(
23310                    "resident Embryo graph refused at position {position}; refusing an in-flight host fallback"
23311                );
23312            }
23313        }
23314        let mut h = hidden.to_vec();
23315        // Ripple's value residual reads this position's embedding row in every layer.
23316        // A later span of the same position (a stack split across cards)
23317        // keeps the row its first span stored.
23318        if self.value_blend.is_some() {
23319            if from == 0 {
23320                self.vres_e0.clear();
23321                self.vres_e0.extend_from_slice(hidden);
23322            }
23323            assert!(
23324                self.vres_e0.len() == hidden.len(),
23325                "value residual: a layer span past the first layer has no embedding row"
23326            );
23327        }
23328        // MiMo-V2 expert placement: decided before the graph or the per-op
23329        // arena can claim the budget the expert bank needs.
23330        self.mimo_moe_prepare();
23331        let _mimo_q8 = self
23332            .mimo_moe
23333            .is_on()
23334            .then(crate::qtensor::enter_full_gpu_q8_scope);
23335        // Split borrows: copy scalars / clone handles so the per-layer
23336        // cfg does not hold `&self` while the KV cache is `&mut`.
23337        let (nh, _nkv, _hd, hs, _rd, eps) = (
23338            self.num_heads,
23339            self.num_kv_heads,
23340            self.head_dim,
23341            self.hidden_size,
23342            self.rotary_dim,
23343            self.rms_eps,
23344        );
23345        let pool = self.pool.clone();
23346        // Opt-in wgpu token-graph attention (discrete Vulkan/DX12): the whole
23347        // attention sub-block runs resident in one submit. Off by default.
23348        // Whole-token wgpu graph: eligibility + arbitration.
23349        //  - explicit CMF_GPU_WGPU_GRAPH forces it on/off;
23350        //  - discrete adapters (4090: decode 76 -> 137 tok/s) and GDN
23351        //    hybrids (recurrent state device-resident, no CPU twin to
23352        //    race) TRUST it;
23353        //  - integrated/mobile adapters RACE it against the normal path
23354        //    at generation granularity (gpu::graph_race_*) — tiled
23355        //    mobile GPUs can turn the ~300-dispatch graph into seconds
23356        //    per token, while a fast phone GPU keeps its win.
23357        let graph_env = std::env::var("CMF_GPU_WGPU_GRAPH").ok();
23358        let graph_on = match graph_env.as_deref() {
23359            Some("0") => false,
23360            Some("prefill") => false, // decode keeps the per-op path
23361            Some(_) => true,
23362            // Unset: same discrete-only default as every other graph
23363            // site. "Is the GPU on" used to stand in here — which made
23364            // the 0.2 tok/s whole-token graph race-eligible on mobile
23365            // adapters and cost 12-14× on first tokens (cmfmobile
23366            // TUNING.md); integrated GPUs keep the per-op probe path.
23367            None => crate::gpu::wgpu_graph_default(),
23368        };
23369        let graph_trusted =
23370            graph_env.is_some() || crate::gpu::wgpu_graph_default() || self.gdn_cfg.is_some();
23371        let race_eligible =
23372            graph_on && upto.is_none() && task_mask.is_none() && from == 0 && !self.graph_refused();
23373        let mut tail_start = 0usize;
23374        if race_eligible && crate::gpu::graph_race_use_graph(graph_trusted) {
23375            let t_graph = std::time::Instant::now();
23376            let mut lg = Vec::new();
23377            let mut gl = 0usize;
23378            let built = self.try_token_graph_wgpu(hidden, position, &mut lg, &mut gl);
23379            let declined = built.is_none();
23380            let built = match built {
23381                // The card ran out of memory in this call (`gpu::mark_lost`): its rows and
23382                // states for this sequence are gone with it, so the request ends here
23383                // with an error, the next one runs on the host.
23384                Some(_) if crate::gpu::device_lost() => {
23385                    self.clear_sequence_state();
23386                    self.graph_failed
23387                        .store(true, std::sync::atomic::Ordering::Relaxed);
23388                    self.cancel
23389                        .store(true, std::sync::atomic::Ordering::Relaxed);
23390                    tracing::error!("the GPU ran out of memory in the token graph; request stopped, later ones run on the CPU");
23391                    return vec![0.0; self.hidden_size];
23392                }
23393                Some(Ok(hh)) => Some(hh),
23394                Some(Err(())) => {
23395                    // O(1) state was admitted before the device failure; the
23396                    // CPU mirrors are stale by construction.  Clear the whole
23397                    // sequence and stop rather than walking that stale state.
23398                    self.clear_sequence_state();
23399                    self.graph_failed
23400                        .store(true, std::sync::atomic::Ordering::Relaxed);
23401                    self.cancel
23402                        .store(true, std::sync::atomic::Ordering::Relaxed);
23403                    tracing::error!("token graph failed after admission; sequence state cleared");
23404                    return vec![0.0; self.hidden_size];
23405                }
23406                None => None,
23407            };
23408            // Past the transient guards (o1 still collecting, a softcap)
23409            // a refusal is about the weights and will never change —
23410            // remember it instead of walking every layer again next
23411            // token.
23412            if declined && !self.o1_active() && self.attn_softcap == 0.0 {
23413                self.mark_graph_refused();
23414            }
23415            graph_note(built.is_some(), gl, self.num_layers);
23416            if let Some(hh) = built {
23417                let dur = t_graph.elapsed();
23418                if std::env::var("CMF_GRAPH_PROF").is_ok() {
23419                    eprintln!("graph-call: {:.2} ms total", dur.as_secs_f64() * 1000.0);
23420                }
23421                if gl > 0 && gl < self.num_layers {
23422                    // Device prefix: the graph ran layers 0..gl and handed
23423                    // back the boundary hidden — the loop below owns the
23424                    // tail. The prefix layers' KV/state advanced on the
23425                    // device; the tail's advances on the host below. One
23426                    // boundary crossing per token.
23427                    h = hh;
23428                    tail_start = gl;
23429                    self.mhc_from_device(gl, None);
23430                    self.absorb_phi_tap(0..gl);
23431                } else if graph_trusted || !crate::gpu::graph_race_first_token_hopeless(dur) {
23432                    if !graph_trusted {
23433                        crate::gpu::graph_race_record(true, dur);
23434                    }
23435                    self.absorb_phi_tap(0..self.num_layers);
23436                    if !lg.is_empty() {
23437                        // Graph produced logits (final-norm + lm_head folded in) —
23438                        // pad/cap to vocab and hand them to the sampler directly.
23439                        lg.resize(self.vocab_size, 0.0);
23440                        if let Some(c) = self.final_softcap {
23441                            softcap_in_place(&mut lg, c, self.pool.as_deref());
23442                        }
23443                        self.graph_logits = Some(lg);
23444                    }
23445                    return hh;
23446                }
23447                // Hopeless first graph token: discard it and fall through
23448                // to the normal path. Safe exactly here — the prompt KV is
23449                // still CPU-owned (chunked prefill), so recomputing this
23450                // position is exact; the mirror's extra row is never read
23451                // (the race just settled on the normal path).
23452            }
23453        }
23454        // KIMI-LINEAR HAS NO SPLIT BUG. The 2.6× reported from the
23455        // model rotation (12.2 tok/s on one card against 4.6 on two)
23456        // was a single measurement of a model whose arm arbitration is
23457        // borderline, and it did not survive repetition. Three runs an
23458        // arm, same binary, back to back:
23459        //   probe on : 1 GPU 9.5 / 5.7 / 5.9   2 GPU 7.8 / 13.0 / 13.3
23460        //   pinned   : 1 GPU 5.6 / 5.3 / 5.2   2 GPU 3.5 / 4.2 / 3.4
23461        // With the arms pinned the split costs about 1.45×, which is
23462        // what a layer split costs. With the probe free, TWO CARDS RUN
23463        // FASTER — because for this model the CPU arm wins some op
23464        // classes and the probe finds that.
23465        //
23466        // Two things do stand, and both are measured. The token graph
23467        // builds NOTHING here (`covered 0 of 14 layers [0..14)`), so
23468        // every layer walks per-op on either arm — that is where the
23469        // headroom is, not in the split. And this model's benchmark is
23470        // unusable without `CMF_GPU_PROBE=0`: the arbitration alone
23471        // moves it by more than 2×.
23472        //
23473        // Span runs (network split): the graph covers exactly [from..=upto]
23474        // — one submit per SEGMENT per token. No race: its state is global
23475        // and calibrated on full stacks, so spans take the graph only where
23476        // it is trusted by default (discrete adapters / CMF_GPU_WGPU_GRAPH).
23477        let span = from > 0 || upto.is_some();
23478        if span && graph_on && task_mask.is_none() && graph_trusted {
23479            let upto_excl = upto.map_or(self.num_layers, |u| u + 1);
23480            let mut lg = Vec::new();
23481            let mut gl = 0usize;
23482            let span_res =
23483                self.try_token_graph_wgpu_span(hidden, position, &mut lg, from, upto_excl, &mut gl);
23484            let span_res = match span_res {
23485                Some(_) if crate::gpu::device_lost() => {
23486                    self.clear_sequence_state();
23487                    self.graph_failed
23488                        .store(true, std::sync::atomic::Ordering::Relaxed);
23489                    self.cancel
23490                        .store(true, std::sync::atomic::Ordering::Relaxed);
23491                    tracing::error!("the GPU ran out of memory in the span graph; request stopped, later ones run on the CPU");
23492                    return vec![0.0; self.hidden_size];
23493                }
23494                Some(Ok(hh)) => Some(hh),
23495                Some(Err(())) => {
23496                    self.clear_sequence_state();
23497                    self.graph_failed
23498                        .store(true, std::sync::atomic::Ordering::Relaxed);
23499                    self.cancel
23500                        .store(true, std::sync::atomic::Ordering::Relaxed);
23501                    tracing::error!(
23502                        "span token graph failed after admission; sequence state cleared"
23503                    );
23504                    return vec![0.0; self.hidden_size];
23505                }
23506                None => None,
23507            };
23508            graph_note(span_res.is_some(), gl, upto_excl - from);
23509            if std::env::var("CMF_GPU_DEBUG").is_ok() {
23510                // How much of the span the graph actually covered. A
23511                // prefix of nothing means every layer walks per-op and
23512                // the split's extra cost is elsewhere.
23513                static SEEN: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
23514                if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 {
23515                    eprintln!(
23516                        "span graph: covered {gl} of {} layers [{from}..{upto_excl}) res={}",
23517                        upto_excl - from,
23518                        span_res.is_some()
23519                    );
23520                }
23521            }
23522            if let Some(hh) = span_res {
23523                self.absorb_phi_tap(from..from + gl);
23524                if gl == upto_excl - from {
23525                    if !lg.is_empty() {
23526                        lg.resize(self.vocab_size, 0.0);
23527                        if let Some(c) = self.final_softcap {
23528                            softcap_in_place(&mut lg, c, self.pool.as_deref());
23529                        }
23530                        self.graph_logits = Some(lg);
23531                    }
23532                    crate::gpu::set_layer(-1);
23533                    return hh;
23534                }
23535                // Partial device prefix of the span: CPU owns the tail.
23536                h = hh;
23537                tail_start = from + gl;
23538                self.mhc_from_device(tail_start, None);
23539            }
23540        }
23541        // Layers the host is about to run whose device mirror moved ahead
23542        // of the host cache (a device prefix that shrank since the prompt,
23543        // a batched-prefill prefix longer than this token's): bring their
23544        // rows over first. One comparison per layer when nothing lags.
23545        let t_race_cpu = (race_eligible && !graph_trusted).then(std::time::Instant::now);
23546
23547        // A partial graph is an explicit GPU-prefix / CPU-tail split. Keep
23548        // the tail PURE host-side: letting its QTensor hooks re-enter the
23549        // residency arena streams every omitted layer through Vulkan and the
23550        // driver's freed-allocation cache can grow to the full model size
23551        // (25.4 GiB observed with a 14 GiB budget on Granite 30B Q8_2F).
23552        // With a MiMo expert bank the tail is not a whole-layer host
23553        // stream: its experts run from the bank (never the arena) and its
23554        // projections stay per-op on the device, which the bank's placement
23555        // left room for.
23556        let host_tail = tail_start > from;
23557        let _host_tail = (host_tail && !self.mimo_moe.is_on()).then(crate::gpu::enter_cpu_scope);
23558        let automatic_gpu_prefix = self.automatic_gpu_prefix();
23559
23560        let _prof_layers = crate::cpuprof::time(crate::cpuprof::Slot::Layers);
23561        #[cfg(target_os = "macos")]
23562        let mut gpu_skip_until = 0usize;
23563        for li in tail_start.max(from)..self.num_layers {
23564            let _capacity_tail = automatic_gpu_prefix
23565                .filter(|&prefix| li >= prefix && !self.mimo_moe.is_dynamic(li, host_tail))
23566                .map(|_| crate::gpu::enter_cpu_scope());
23567            crate::gpu::set_layer(li as i64); // layer-split GPU/CPU (CMF_GPU_LAYERS)
23568            if let Some(u) = upto {
23569                if li > u {
23570                    break;
23571                }
23572            }
23573            if let Some(mask) = task_mask {
23574                if !mask.layer_alive(li) {
23575                    continue; // dead layer: residual pass-through
23576                }
23577            }
23578            // MiniMax's dynamic tail: attention + pooled MoE of this layer as
23579            // ONE device frame (single-layer graph call), cold experts on
23580            // the host. Any decline falls through to the ordinary host
23581            // layer; a post-admission device failure stops the sequence.
23582            if host_tail && task_mask.is_none() {
23583                match self.m3_pooled_layer(li, position, &mut h) {
23584                    Ok(true) => {
23585                        crate::gpu::set_layer(-1);
23586                        continue;
23587                    }
23588                    Ok(false) => {}
23589                    Err(()) => {
23590                        self.clear_sequence_state();
23591                        self.graph_failed
23592                            .store(true, std::sync::atomic::Ordering::Relaxed);
23593                        self.cancel
23594                            .store(true, std::sync::atomic::Ordering::Relaxed);
23595                        tracing::error!(
23596                            "pooled tail token graph failed after admission; sequence state cleared"
23597                        );
23598                        return vec![0.0; self.hidden_size];
23599                    }
23600                }
23601            }
23602            // Whole-block q1 token graph: a run of consecutive q1
23603            // layers — GDN and full attention — executes with one sync
23604            // per CPU attend instead of per op (macOS/Metal).
23605            #[cfg(target_os = "macos")]
23606            {
23607                if li < gpu_skip_until {
23608                    continue;
23609                }
23610                if task_mask.is_none() {
23611                    let end = self.q1_graph_gpu(li, upto, position, &mut h);
23612                    if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
23613                        // The graph may have mutated device state before a
23614                        // command-buffer error. Never continue with a CPU
23615                        // tail or read a stale host mirror after admission.
23616                        return vec![0.0; self.hidden_size];
23617                    }
23618                    if end > li {
23619                        gpu_skip_until = end;
23620                        // Looped Transformer: the graph stopped at a loop
23621                        // boundary — apply final norm before the next iteration.
23622                        if self.is_loop_end(end - 1) && end < self.num_layers {
23623                            h = inference::rms_norm(
23624                                &h,
23625                                &self.weights.final_norm,
23626                                self.rms_eps,
23627                                self.norm_style,
23628                            );
23629                        }
23630                        continue;
23631                    }
23632                }
23633            }
23634
23635            if task_mask.is_none() {
23636                match self.mimo_graph_layer_rows(li, &mut h, &[position]) {
23637                    crate::gpu::BatchGraphOutcome::Completed => continue,
23638                    crate::gpu::BatchGraphOutcome::Failed => return vec![0.0; self.hidden_size],
23639                    crate::gpu::BatchGraphOutcome::Declined => {}
23640                }
23641            }
23642            #[cfg(feature = "gpu")]
23643            self.pull_lagging_host_kv(li, li + 1, position);
23644            // SenseNova-Loop mHC: the attention reads the routed branch of
23645            // the streams.
23646            let mhc_attn = self.mhc_layer(li).then(|| self.mhc_pre(li, false, &mut h));
23647            let lw = &self.weights.layers[self.phys_layer(li)];
23648            if let Ok(tp) = std::env::var("CMF_TRACE_POS") {
23649                if tp.parse::<usize>().ok() == Some(position) {
23650                    let n: f32 = h.iter().map(|x| x * x).sum::<f32>().sqrt();
23651                    eprintln!(
23652                        "TRACE pos {position} layer {li}: |h| = {n:.6} h0 {:.6} h1 {:.6}",
23653                        h[0], h[1]
23654                    );
23655                }
23656            }
23657            // Norm into the pipeline scratch — the returning rms_norm
23658            // allocated twice per layer per token (roadmap §3 P0).
23659            let prof = crate::cpuprof::time(crate::cpuprof::Slot::Norms);
23660            inference::rms_norm_into(
23661                &h,
23662                &lw.input_norm,
23663                self.rms_eps,
23664                self.norm_style,
23665                &mut self.ws.n1,
23666            );
23667            drop(prof);
23668            // The row V projects, when the layer blends the embedding into it.
23669            let vres = match self.layer_value_blend(li) {
23670                Some(blend) => {
23671                    vres_lerp(&self.vres_e0, &self.ws.n1, blend, &mut self.vres_in);
23672                    true
23673                }
23674                None => false,
23675            };
23676
23677            let attn_out = match &lw.attn {
23678                AttnKind::Mla(w) => {
23679                    let inv_freq_l = self.layer_inv_freq(li);
23680                    let rs = self.layer_rope_scale(li);
23681                    let eps = self.rms_eps;
23682                    let pool = self.pool.clone();
23683                    mla_attention(
23684                        w,
23685                        &self.ws.n1,
23686                        &mut self.kv_cache.layers[li],
23687                        position,
23688                        &inv_freq_l,
23689                        rs,
23690                        eps,
23691                        pool.as_deref(),
23692                    )
23693                }
23694                AttnKind::Linear(w) => {
23695                    let cfg = self.vmf_cfg.expect("linear layer without vmf_cfg");
23696                    vmf_phase_forward(
23697                        &self.ws.n1,
23698                        w,
23699                        &cfg,
23700                        &mut self.kv_cache.layers[li].linear_state,
23701                        self.pool.as_deref(),
23702                    )
23703                }
23704                AttnKind::Kda(w) => {
23705                    let cfg = self.kda_cfg.expect("kda layer without kda_cfg");
23706                    crate::linear_core::kda_forward(
23707                        &self.ws.n1,
23708                        w,
23709                        &cfg,
23710                        &mut self.kv_cache.layers[li].linear_state,
23711                        self.pool.as_deref(),
23712                    )
23713                }
23714                AttnKind::LinearGdn(w) => {
23715                    let cfg = self.gdn_cfg.expect("gdn layer without gdn_cfg");
23716                    gdn_forward(
23717                        &self.ws.n1,
23718                        w,
23719                        &cfg,
23720                        &mut self.kv_cache.layers[li].linear_state,
23721                        self.pool.as_deref(),
23722                    )
23723                }
23724                AttnKind::ShortConv(w) => {
23725                    let cfg = self
23726                        .short_conv_cfg
23727                        .expect("short-conv layer without short_conv_cfg");
23728                    short_conv_forward(
23729                        &self.ws.n1,
23730                        w,
23731                        &cfg,
23732                        &mut self.kv_cache.layers[li].linear_state,
23733                        self.pool.as_deref(),
23734                    )
23735                }
23736                AttnKind::Bounded(w) => {
23737                    // Natively bounded anchor: insert into the ring, attend
23738                    // over sinks ∪ window. No position, nothing appended.
23739                    let rope = self
23740                        .bounded_rope
23741                        .clone()
23742                        .expect("bounded layer without an installed rotation table");
23743                    let cfg = crate::bounded::BoundedAttnCfg {
23744                        num_heads: self.num_heads,
23745                        num_kv_heads: self.num_kv_heads,
23746                        head_dim: self.head_dim,
23747                        hidden_size: hs,
23748                        scale: self.attn_scale,
23749                        rope: &rope,
23750                        pool: pool.as_deref(),
23751                    };
23752                    crate::bounded::bounded_attention(
23753                        &self.ws.n1,
23754                        w,
23755                        &mut self.kv_cache.layers[li],
23756                        &cfg,
23757                    )
23758                }
23759                AttnKind::Full { wq, wk, wv, wo, .. } if self.dash.is_some() => {
23760                    let (nh_l, hd_l) = (self.num_heads, self.head_dim);
23761                    let mut ao = vec![0f32; nh_l * hd_l];
23762                    let dash = self.dash.as_mut().expect("guarded");
23763                    crate::uocr::attention_host(
23764                        dash,
23765                        li,
23766                        &self.ws.n1,
23767                        wq,
23768                        wk,
23769                        wv,
23770                        &mut self.kv_cache.layers[li],
23771                        position,
23772                        nh_l,
23773                        hd_l,
23774                        self.rms_eps as f32,
23775                        pool.as_deref(),
23776                        &mut ao,
23777                    );
23778                    let mut out = vec![0f32; hs];
23779                    wo.matvec(&ao, &mut out, pool.as_deref());
23780                    out
23781                }
23782                AttnKind::Full {
23783                    wq,
23784                    wk,
23785                    wv,
23786                    wo,
23787                    q_norm,
23788                    k_norm,
23789                    output_gate,
23790                    softplus_gate,
23791                    bias,
23792                } if self.kv_cache.layers[li].o1_sealed() => {
23793                    // O(1) override: decode on the sealed Nyström state
23794                    // instead of the growing KV cache.
23795                    let inv_freq_l = self.layer_inv_freq(li);
23796                    let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
23797                    let cfg = QwenAttnCfg {
23798                        mrope: None,
23799                        num_heads: self.layer_num_heads(li),
23800                        num_kv_heads: nkv_l,
23801                        head_dim: hd_l,
23802                        hidden_size: hs,
23803                        position,
23804                        inv_freq: &inv_freq_l,
23805                        rotary_dim: rd_l,
23806                        scale: self.attn_scale,
23807                        softcap: self.attn_softcap,
23808                        window: None,
23809                        v_norm: self.attn_v_norm,
23810                        qk_norm_after_rope: self.qk_norm_after_rope,
23811                        gate_sigmoid: self.proj_gate_sigmoid,
23812                        q_norm: q_norm.as_deref(),
23813                        k_norm: k_norm.as_deref(),
23814                        output_gate: *output_gate,
23815                        softplus_gate: softplus_gate
23816                            .as_ref()
23817                            .map(|(gate, per_head)| (gate, *per_head)),
23818                        rope_scale: self.layer_rope_scale(li),
23819                        bias: bias
23820                            .as_ref()
23821                            .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
23822                        rms_eps: eps,
23823                        norm_style: self.norm_style,
23824                        pool: pool.as_deref(),
23825                        v_head_dim: self.layer_v_dim(li),
23826                        value_in: vres.then(|| self.vres_in.as_slice()),
23827                    };
23828                    attention::qwen_attention_nystrom(
23829                        &self.ws.n1,
23830                        wq,
23831                        wk,
23832                        wv,
23833                        wo,
23834                        &mut self.kv_cache.layers[li],
23835                        &cfg,
23836                    )
23837                }
23838                AttnKind::Full {
23839                    wq,
23840                    wk,
23841                    wv,
23842                    wo,
23843                    q_norm,
23844                    k_norm,
23845                    output_gate,
23846                    softplus_gate,
23847                    bias,
23848                } => 'attn: {
23849                    // wgpu token-graph attention (opt-in): whole sub-block in
23850                    // one submit, device K/V mirror. q1 only, no gate/bias/mask.
23851                    // Its kernel has no window, sink or narrow-V slot and
23852                    // one mirror geometry: such models stay on the CPU attend.
23853                    let dropin_reason =
23854                        graph_on.then(|| self.graph_attn_decline_reason()).flatten();
23855                    if let Some(reason) = dropin_reason {
23856                        self.note_graph_decline("wgpu attn dropin", reason);
23857                    }
23858                    if graph_on
23859                        && dropin_reason.is_none()
23860                        && !*output_gate
23861                        && softplus_gate.is_none()
23862                        && self.attention_heads_per_layer.is_none()
23863                        && bias.is_none()
23864                        && task_mask.is_none()
23865                    {
23866                        let inv_freq_l = self.layer_inv_freq(li);
23867                        let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
23868                        let gemma = self.norm_style == cortiq_core::NormStyle::Gemma;
23869                        if let (Some((gm, qi)), Some((_, ki)), Some((_, vi)), Some((_, oi))) = (
23870                            wq.mapped_q1(),
23871                            wk.mapped_q1(),
23872                            wv.mapped_q1(),
23873                            wo.mapped_q1(),
23874                        ) {
23875                            let gm = gm.clone();
23876                            let mut out = vec![0f32; hs];
23877                            let cache = &self.kv_cache.layers[li];
23878                            if crate::gpu::attn_dropin(
23879                                &gm,
23880                                self.graph_kv_id,
23881                                li,
23882                                &self.ws.n1,
23883                                qi,
23884                                ki,
23885                                vi,
23886                                oi,
23887                                q_norm.as_deref(),
23888                                k_norm.as_deref(),
23889                                self.qk_norm_after_rope,
23890                                &inv_freq_l,
23891                                nh,
23892                                nkv_l,
23893                                hd_l,
23894                                rd_l,
23895                                hs,
23896                                position,
23897                                self.kv_cache.max_seq_len,
23898                                gemma,
23899                                eps as f32,
23900                                cache.k_heads(),
23901                                cache.v_heads(),
23902                                &mut out,
23903                            ) {
23904                                break 'attn out;
23905                            }
23906                        }
23907                    }
23908                    let masked = task_mask
23909                        .map(|m| m.head_flags(li, self.num_heads).iter().any(|&a| !a))
23910                        .unwrap_or(false);
23911                    let f32_view = (wq.as_f32(), wk.as_f32(), wv.as_f32(), wo.as_f32());
23912                    // The masked kernel knows one pipeline-wide geometry and
23913                    // RoPE table, no window and no sink.
23914                    let plain = self.layer_attn_plain(li);
23915                    match (masked, f32_view) {
23916                        // Historical masked path (f32 slices; the loader
23917                        // keeps masked models in f32).
23918                        (true, (Some(q), Some(k), Some(v), Some(o))) if plain => {
23919                            let active_heads = task_mask.unwrap().head_flags(li, self.num_heads);
23920                            attention::multi_head_attention(
23921                                &self.ws.n1,
23922                                q,
23923                                k,
23924                                v,
23925                                o,
23926                                &mut self.kv_cache.layers[li],
23927                                self.num_heads,
23928                                self.num_kv_heads,
23929                                self.head_dim,
23930                                self.hidden_size,
23931                                position,
23932                                &active_heads,
23933                                &self.inv_freq,
23934                            )
23935                        }
23936                        (masked, _) => {
23937                            if masked {
23938                                tracing::warn!(
23939                                    "layer {li}: head mask on quantized weights or on a \
23940                                     window/sink/per-layer-geometry layer not supported \
23941                                     yet — executing dense"
23942                                );
23943                            }
23944                            let inv_freq_l = self.layer_inv_freq(li);
23945                            let (nkv_l, hd_l, rd_l) = self.layer_geom(li);
23946                            let cfg = QwenAttnCfg {
23947                                mrope: self.prompt_mrope.as_deref().zip(self.mrope_sections).map(|(pos, sections)| attention::MropeView { base: 0, pos, sections }),
23948                                num_heads: self.layer_num_heads(li),
23949                                num_kv_heads: nkv_l,
23950                                head_dim: hd_l,
23951                                hidden_size: hs,
23952                                position,
23953                                inv_freq: &inv_freq_l,
23954                                rotary_dim: rd_l,
23955                                scale: self.attn_scale,
23956                                softcap: self.attn_softcap,
23957                                window: self.layer_window(li),
23958                                v_norm: self.attn_v_norm,
23959                                qk_norm_after_rope: self.qk_norm_after_rope,
23960                                gate_sigmoid: self.proj_gate_sigmoid,
23961                                q_norm: q_norm.as_deref(),
23962                                k_norm: k_norm.as_deref(),
23963                                output_gate: *output_gate,
23964                                softplus_gate: softplus_gate
23965                                    .as_ref()
23966                                    .map(|(gate, per_head)| (gate, *per_head)),
23967                                rope_scale: self.layer_rope_scale(li),
23968                                bias: bias
23969                                    .as_ref()
23970                                    .map(|(a, b, c)| (a.as_slice(), b.as_slice(), c.as_slice())),
23971                                rms_eps: eps,
23972                                norm_style: self.norm_style,
23973                                pool: pool.as_deref(),
23974                                v_head_dim: self.layer_v_dim(li),
23975                                value_in: vres.then(|| self.vres_in.as_slice()),
23976                            };
23977                            attention::qwen_attention(
23978                                &self.ws.n1,
23979                                wq,
23980                                wk,
23981                                wv,
23982                                wo,
23983                                &mut self.kv_cache.layers[li],
23984                                &cfg,
23985                            )
23986                        }
23987                    }
23988                }
23989            };
23990            // Gemma sandwich norm: normalize the attention branch before
23991            // it joins the residual stream.
23992            let attn_out = match &self.weights.layers[self.phys_layer(li)].attn_out_norm {
23993                Some(w) => inference::rms_norm(&attn_out, w, self.rms_eps, self.norm_style),
23994                None => attn_out,
23995            };
23996            let mhc_ffn = match mhc_attn {
23997                Some(c) => {
23998                    // mHC: fold the attention output in, route the FFN's
23999                    // branch, and norm that.
24000                    self.mhc_post(li, false, &attn_out, &c, &mut h);
24001                    let cf = self.mhc_pre(li, true, &mut h);
24002                    let lw = &self.weights.layers[self.phys_layer(li)];
24003                    inference::rms_norm_into(&h, &lw.post_norm, self.rms_eps, self.norm_style, &mut self.ws.p1);
24004                    Some(cf)
24005                }
24006                None => {
24007                    let lw = &self.weights.layers[self.phys_layer(li)];
24008                    let prof = crate::cpuprof::time(crate::cpuprof::Slot::Norms);
24009                    inference::add_rmsnorm_fused_into(
24010                        &mut h,
24011                        &attn_out,
24012                        &lw.post_norm,
24013                        self.rms_eps,
24014                        self.norm_style,
24015                        &mut self.ws.p1,
24016                    );
24017                    drop(prof);
24018                    None
24019                }
24020            };
24021            let lw = &self.weights.layers[self.phys_layer(li)];
24022            let mut attn_out = attn_out;
24023            attention::recycle_buf(&mut attn_out);
24024            let post_normed = &self.ws.p1;
24025
24026            let ffn_masked = task_mask
24027                .map(|m| m.ffn_active_count(li) < self.intermediate_size)
24028                .unwrap_or(false);
24029            // One masked dense CONTRACT, dispatched by cost. The
24030            // activation-zeroing arm (the batched sweep's, validated
24031            // against the replica to 0.8%) computes the FULL fused FFN
24032            // and zeroes the dead — right whenever most neurons live.
24033            // The sparse arm reads ONLY active rows and down columns —
24034            // per-row dots are slower per element than the fused kernel,
24035            // so it pays only once the mask is deep enough. The 0.5
24036            // crossover is first-principles (fused kernels run ~2x the
24037            // per-row dot throughput); a shallow specialist (95% alive)
24038            // stays fused, a --target-sparsity bake flips arms on its
24039            // own weight.
24040            let ffn_out = match (ffn_masked, &lw.ffn) {
24041                // A defragged tube layer answers its own mask: the core
24042                // always runs, each tube runs when its bit is on, and
24043                // the tubes that are off are never read from the mmap.
24044                (_, FfnKind::Dense(d)) if !d.segs.is_empty() => {
24045                    let row = task_mask
24046                        .and_then(|tm| tm.ffn_masks.get(li))
24047                        .map(|v| v.as_slice());
24048                    tube_ffn(d, post_normed, 1, self.pool.as_deref(), row)
24049                }
24050                (true, FfnKind::Dense(d)) => {
24051                    let tm = task_mask.unwrap();
24052                    let alive = tm.ffn_active_count(li);
24053                    let deep = alive * 2 <= self.intermediate_size;
24054                    if deep && d.down_proj.sparse_col_ok() && !d.gate_proj.has_prism_contract() {
24055                        let active = tm.ffn_active_indices(li);
24056                        sparse_ffn_quant(
24057                            d,
24058                            post_normed,
24059                            &active,
24060                            self.hidden_size,
24061                            self.pool.as_deref(),
24062                        )
24063                    } else if deep
24064                        && let (Some(g), Some(u), Some(dn)) = (
24065                            d.gate_proj.as_f32(),
24066                            d.up_proj.as_f32(),
24067                            d.down_proj.as_f32(),
24068                        )
24069                    {
24070                        let active = tm.ffn_active_indices(li);
24071                        inference::sparse_ffn_forward(
24072                            post_normed,
24073                            g,
24074                            u,
24075                            dn,
24076                            self.hidden_size,
24077                            self.intermediate_size,
24078                            &active,
24079                            self.pool.as_deref(),
24080                        )
24081                    } else {
24082                        let row = tm.ffn_masks.get(li).map(|v| v.as_slice());
24083                        dense_ffn_batch(d, post_normed, 1, self.pool.as_deref(), row)
24084                    }
24085                }
24086                (true, FfnKind::Moe(m)) => {
24087                    // MoE is sparse by expert selection; a task mask
24088                    // narrows the ROUTABLE set via its expert fields
24089                    // (spec §5) when it carries them.
24090                    let allowed = task_mask.and_then(|tm| tm.expert_flags(li, m.experts.len()));
24091                    ffn_forward(
24092                        &lw.ffn,
24093                        post_normed,
24094                        self.pool.as_deref(),
24095                        allowed.as_deref(),
24096                    )
24097                }
24098                (true, FfnKind::DenseMoe(dm)) => dense_moe_ffn(
24099                    dm,
24100                    post_normed,
24101                    &h,
24102                    self.rms_eps,
24103                    self.norm_style,
24104                    self.pool.as_deref(),
24105                ),
24106                (false, _) => match &lw.ffn {
24107                    FfnKind::DenseMoe(dm) => dense_moe_ffn(
24108                        dm,
24109                        post_normed,
24110                        &h,
24111                        self.rms_eps,
24112                        self.norm_style,
24113                        self.pool.as_deref(),
24114                    ),
24115                    FfnKind::Moe(m)
24116                        if task_mask.is_none()
24117                            && host_tail
24118                            && li >= tail_start
24119                            && crate::minicpm_tail::MiniCpmTail::is_requested_target(m) =>
24120                    {
24121                        moe_ffn_minicpm_tail(
24122                            &mut self.minicpm_tail,
24123                            li,
24124                            self.num_layers,
24125                            m,
24126                            post_normed,
24127                            self.pool.as_deref(),
24128                        )
24129                    }
24130                    FfnKind::Moe(m)
24131                        if task_mask.is_none() && self.mimo_moe.is_dynamic(li, host_tail) =>
24132                    {
24133                        moe_ffn_banked(&mut self.mimo_moe, li, m, post_normed, self.pool.as_deref())
24134                    }
24135                    _ => {
24136                        let allowed = match (&lw.ffn, task_mask) {
24137                            (FfnKind::Moe(m), Some(tm)) => tm.expert_flags(li, m.experts.len()),
24138                            _ => None,
24139                        };
24140                        ffn_forward(
24141                            &lw.ffn,
24142                            post_normed,
24143                            self.pool.as_deref(),
24144                            allowed.as_deref(),
24145                        )
24146                    }
24147                },
24148            };
24149            let ffn_out = match &self.weights.layers[self.phys_layer(li)].ffn_out_norm {
24150                Some(w) => inference::rms_norm(&ffn_out, w, self.rms_eps, self.norm_style),
24151                None => ffn_out,
24152            };
24153            match mhc_ffn {
24154                Some(c) => self.mhc_post(li, true, &ffn_out, &c, &mut h),
24155                None => {
24156                    for (i, &f) in ffn_out.iter().enumerate() {
24157                        h[i] += f;
24158                    }
24159                }
24160            }
24161            let mut ffn_out = ffn_out;
24162            attention::recycle_buf(&mut ffn_out);
24163
24164            // Gemma-4: the layer output is scaled by a learned scalar.
24165            if let Some(sc) = self.weights.layers[self.phys_layer(li)].layer_scale {
24166                for v in h.iter_mut() {
24167                    *v *= sc;
24168                }
24169            }
24170            // CMF_LAYER_DUMP: this position's hidden after layer li.
24171            if self.layer_dump.is_some() {
24172                self.dump_layer_row(position, li, &h);
24173            }
24174
24175            // Looped Transformer: apply final norm at the end of each loop iteration.
24176            // Nanbeige 4.2: after layer 21 (virtual), apply norm before looping back to layer 0.
24177            if self.is_loop_end(li) && li + 1 < self.num_layers {
24178                h = inference::rms_norm(
24179                    &h,
24180                    &self.weights.final_norm,
24181                    self.rms_eps,
24182                    self.norm_style,
24183                );
24184            }
24185
24186            // Dynamic routing φ capture (on-policy): the
24187            // EMA of the post-residual hidden at the router's phi_layer,
24188            // updated as the context evolves during decode.
24189            if self.dyn_phi_layer == Some(li) {
24190                self.update_dyn_phi(&h);
24191            }
24192        }
24193        crate::gpu::set_layer(-1); // layers done — lm_head outside layer-split
24194        if let Some(t) = t_race_cpu {
24195            crate::gpu::graph_race_record(false, t.elapsed());
24196        }
24197
24198        h
24199    }
24200
24201    /// Read `ids` (positions `0..len`) into a sequence the weights just
24202    /// changed under (`set_active_skill` cleared it): all but the last
24203    /// position through the prompt ingest (`prefill_rows`: the batch graph
24204    /// where it admits them, else the host's chunked prefill), the last as
24205    /// a decode step. Returns that step's post-stack hidden; logits the
24206    /// graph folded in are its own, never the old weights'. The router's φ
24207    /// does not take these rows — they are context it has already seen.
24208    fn reprefill_context(&mut self, ids: &[u32], task_mask: Option<&TaskMask>) -> Result<Vec<f32>, String> {
24209        let n = ids.len();
24210        if n == 0 {
24211            return Err("nothing to read".into());
24212        }
24213        let phi = self.dyn_phi_layer.take();
24214        self.graph_logits = None;
24215        let r = (|| {
24216            let chunk = self.prefill_chunk().max(1);
24217            // the device's own prompt path where generation takes it (the
24218            // batch graph, chunks of `generation_batch_k`), else the host's
24219            let batch_k = self.generation_batch_k();
24220            let mut graphed = batch_k > 1 && task_mask.is_none() && !self.o1_active() && self.graph_prefill_preferred();
24221            let mut pos = 0usize;
24222            while pos + 1 < n {
24223                if graphed {
24224                    let end = (pos + batch_k).min(n - 1);
24225                    let hs = self.hidden_size;
24226                    let mut hiddens = vec![0f32; (end - pos) * hs];
24227                    for (j, &id) in ids[pos..end].iter().enumerate() {
24228                        hiddens[j * hs..(j + 1) * hs].copy_from_slice(&self.embed_single(id));
24229                    }
24230                    let positions: Vec<usize> = (pos..end).collect();
24231                    match self.try_batch_graph_wgpu(&mut hiddens, &positions, end - pos, None) {
24232                        crate::gpu::BatchGraphOutcome::Completed => {
24233                            pos = end;
24234                            continue;
24235                        }
24236                        crate::gpu::BatchGraphOutcome::Failed => {
24237                            return Err(format!("the batch graph failed at position {pos}"));
24238                        }
24239                        crate::gpu::BatchGraphOutcome::Declined => graphed = false,
24240                    }
24241                }
24242                let end = (pos + chunk).min(n - 1);
24243                let _ = self.prefill_rows(&ids[pos..end], pos, task_mask)?;
24244                // a failed graph stays flagged for the caller's own check
24245                if self.graph_failed.load(std::sync::atomic::Ordering::Relaxed) {
24246                    return Err(format!("the device graph failed at position {pos}"));
24247                }
24248                pos = end;
24249            }
24250            Ok(self.forward_layers(&self.embed_single(ids[n - 1]), n - 1, task_mask))
24251        })();
24252        self.dyn_phi_layer = phi;
24253        r
24254    }
24255
24256    /// The file a graph layer's weights come from: the first of `ws` that is
24257    /// a mapped graph weight. A soft skill blend holds its working tensors
24258    /// in f32 (no file entry); on CUDA, whose hybrid arm keeps such a
24259    /// matrix on the card as int8 tiles, the pipeline's own file stands in.
24260    fn graph_model_of(&self, ws: &[&QTensor]) -> Option<std::sync::Arc<cortiq_core::CmfModel>> {
24261        if let Some(m) = ws.iter().find_map(|t| t.graph_weight_or_blr().map(|r| r.0.clone())) {
24262            return Some(m);
24263        }
24264        if self.dyn_blend_loaded && crate::gpu::cuda_active() {
24265            return self.model.clone();
24266        }
24267        None
24268    }
24269
24270    /// Fold the φ rows a device graph kept (`dyn_phi_tap`) into the EMA,
24271    /// in row order. `ran`: the layers the graph ran; a router layer outside
24272    /// them runs on the host, whose own hook takes it. A router layer the
24273    /// graph ran without keeping its row is a φ the router never sees —
24274    /// said once, never silent.
24275    fn absorb_phi_tap(&mut self, ran: std::ops::Range<usize>) {
24276        let Some(l) = self.dyn_phi_layer else {
24277            return;
24278        };
24279        let rows = self.dyn_phi_tap.get_mut().unwrap().take();
24280        match rows {
24281            Some(rows) => {
24282                let hs = self.hidden_size;
24283                for r in rows.chunks_exact(hs) {
24284                    self.update_dyn_phi(r);
24285                }
24286            }
24287            None if ran.contains(&l) => {
24288                static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
24289                if !SAID.swap(true, std::sync::atomic::Ordering::Relaxed) {
24290                    tracing::warn!(
24291                        "dynamic routing: the device graph ran the router's layer {l} without keeping its row — φ is not updated on this backend"
24292                    );
24293                }
24294            }
24295            None => {}
24296        }
24297    }
24298
24299    /// EMA of φ at the router layer (rolling, weight 0.2 = ~5-token
24300    /// horizon). First observation seeds it exactly.
24301    fn update_dyn_phi(&mut self, h: &[f32]) {
24302        const A: f32 = 0.2;
24303        if self.dyn_phi_ema.len() != h.len() {
24304            self.dyn_phi_ema = vec![0.0; h.len()];
24305            self.dyn_phi_seen = 0;
24306        }
24307        if self.dyn_phi_seen == 0 {
24308            self.dyn_phi_ema.copy_from_slice(h);
24309        } else {
24310            for (e, &v) in self.dyn_phi_ema.iter_mut().zip(h) {
24311                *e = (1.0 - A) * *e + A * v;
24312            }
24313        }
24314        self.dyn_phi_seen += 1;
24315    }
24316
24317    /// Current router φ (EMA at phi_layer); empty until first capture.
24318    pub fn dyn_phi(&self) -> &[f32] {
24319        &self.dyn_phi_ema
24320    }
24321
24322    /// Enable/disable φ capture at the router layer, reset the EMA.
24323    pub fn set_dyn_phi_layer(&mut self, layer: Option<usize>) {
24324        self.dyn_phi_layer = layer;
24325        self.dyn_phi_ema.clear();
24326        self.dyn_phi_seen = 0;
24327    }
24328
24329    /// Skills eligible for dynamic switching: (index, id, phi_layer).
24330    pub fn dynamic_skills(&self) -> Vec<(usize, String, usize)> {
24331        let Some(model) = &self.model else {
24332            return Vec::new();
24333        };
24334        model
24335            .header
24336            .skills
24337            .iter()
24338            .enumerate()
24339            .filter_map(|(i, sk)| {
24340                // A v2 record routes only through the request-level
24341                // backbone-gated decision (its status and gate are
24342                // checked there), never per token.
24343                if sk.is_v2() {
24344                    return None;
24345                }
24346                let ok = matches!(self.dyn_skill_layers.get(i), Some(Some(_)));
24347                let sel = sk.selection.as_ref()?;
24348                (ok).then(|| (i, sk.id.clone(), sel.phi_layer))
24349            })
24350            .collect()
24351    }
24352
24353    /// Index of the currently overlaid skill (None = backbone).
24354    pub fn active_skill(&self) -> Option<usize> {
24355        self.dyn_active
24356    }
24357
24358    /// Enable dynamic per-token skill routing: build the hysteresis
24359    /// router from the container's routable skills, start φ capture at
24360    /// their (shared) phi_layer. Returns the number of routable skills
24361    /// (0 = nothing to route; router stays off). Idempotent.
24362    pub fn enable_dynamic_routing(&mut self) -> usize {
24363        use crate::swarm::{DynRouter, RoutableSkill};
24364        let Some(model) = self.model.clone() else {
24365            return 0;
24366        };
24367        // Router policy v2 (spec §9.4) routes per REQUEST: the backbone is
24368        // the default and only the backbone-gated decision may pick a
24369        // skill. A per-token switch would bypass that gate (and change
24370        // the O(1) state mid-sequence), so the hysteresis router never
24371        // runs on such a file; the caller keeps the request-level
24372        // decision.
24373        if let Some(r) = &model.header.router {
24374            tracing::warn!(
24375                "dynamic routing disabled: this file declares router policy '{}' with \
24376                 granularity \"{}\" — the request-level decision applies instead",
24377                r.policy,
24378                r.granularity
24379            );
24380            return 0;
24381        }
24382        // Format-v2 skill records (bit SKILLS_V2) without a router policy:
24383        // their status/gate contract ("auto-routing requires active +
24384        // measured") lives in the backbone-gated decision only — the
24385        // hysteresis router would switch into a quarantined record
24386        // (fail-open). Refuse the whole file, not just its v2 records.
24387        if model.required_features & cortiq_core::format::features::SKILLS_V2 != 0
24388            || model.header.skills.iter().any(|s| s.is_v2())
24389        {
24390            tracing::warn!(
24391                "dynamic routing disabled: this file carries format-v2 skill records \
24392                 (SKILLS_V2) — they route per request through a router policy only"
24393            );
24394            return 0;
24395        }
24396        // A blend materialized f32 working tensors into the layers; there
24397        // is no single skill index to revert from → refuse (honest).
24398        if self.dyn_blend_loaded {
24399            tracing::warn!("dynamic routing unavailable on a blend-loaded pipeline");
24400            return 0;
24401        }
24402        // A statically-overlaid skill that is NOT FFN-eligible can't be
24403        // cheaply reverted at generation start → refuse rather than
24404        // silently keep it overlaid.
24405        if let Some(a) = self.dyn_active {
24406            if !matches!(self.dyn_skill_layers.get(a), Some(Some(_))) {
24407                tracing::warn!("loaded skill is not FFN-eligible — dynamic routing unavailable");
24408                return 0;
24409            }
24410        }
24411        let hidden = self.hidden_size;
24412        let mut skills = Vec::new();
24413        for (idx, id, _phi) in self.dynamic_skills() {
24414            if let Some(sel) = model.header.skills[idx].selection.as_ref() {
24415                if let Some(rs) = RoutableSkill::from_descriptor(idx, id, sel, hidden) {
24416                    skills.push(rs);
24417                }
24418            }
24419        }
24420        if skills.is_empty() {
24421            return 0;
24422        }
24423        // Skills should share a phi_layer; warn (not fail) if they don't.
24424        let phi = skills[0].phi_layer;
24425        if skills.iter().any(|s| s.phi_layer != phi) {
24426            tracing::warn!("routable skills disagree on phi_layer; using {phi}");
24427        }
24428        let n = skills.len();
24429        self.set_dyn_phi_layer(Some(phi));
24430        self.dyn_router = Some(DynRouter::new(skills));
24431        n
24432    }
24433
24434    /// Human-readable switch log from the last dynamic-routed generation.
24435    pub fn route_switches(&self) -> Vec<(usize, Option<String>, Option<String>)> {
24436        self.dyn_router
24437            .as_ref()
24438            .map(|r| r.switches.clone())
24439            .unwrap_or_default()
24440    }
24441
24442    /// LM head: hidden → logits [vocab_size]. The dominant matvec of
24443    /// every decode step — row-parallel on the worker pool.
24444    fn lm_head_forward(&self, hidden: &[f32]) -> Vec<f32> {
24445        let _mimo_q8 = self
24446            .mimo_moe
24447            .is_on()
24448            .then(crate::qtensor::enter_full_gpu_q8_scope);
24449        let rows = self.weights.lm_head.rows();
24450        let mut logits = attention::take_buf(rows.min(self.vocab_size));
24451        // Banked MiMo uses the same exact projection family for the
24452        // plain/draft head and the batched verification head. Read both
24453        // scale planes in-place instead of preparing per-op scale buffers.
24454        let served = self.mimo_moe.is_on()
24455            && crate::gpu::mimo_q8_short_enabled()
24456            && rows == self.vocab_size
24457            && !self.weights.lm_head.has_prism_contract()
24458            && self
24459                .weights
24460                .lm_head
24461                .graph_weight()
24462                .is_some_and(|(model, idx, kind, _)| {
24463                    kind == 7
24464                        && crate::gpu::q82_short_rows(
24465                            model,
24466                            idx,
24467                            hidden,
24468                            1,
24469                            rows,
24470                            self.hidden_size,
24471                            &mut logits,
24472                        )
24473                });
24474        if !served {
24475            self.weights
24476                .lm_head
24477                .matvec(hidden, &mut logits, self.pool.as_deref());
24478        }
24479        logits.resize(self.vocab_size, 0.0);
24480        if let Some(m) = self.logit_multiplier {
24481            for l in logits.iter_mut() {
24482                *l *= m;
24483            }
24484        }
24485        if let Some(c) = self.final_softcap {
24486            softcap_in_place(&mut logits, c, self.pool.as_deref());
24487        }
24488        if let Some(cm) = self.head_clusters.as_ref() {
24489            self.hierarchical_head_logprobs(hidden, cm, &mut logits);
24490        }
24491        logits
24492    }
24493
24494    /// Two-level head (Cortiq Embryo): in place, logits[v] ← log p(v) =
24495    /// (lc[c] − lse(lc)) + (logit[v] − lse over v's cluster block), c = v / S.
24496    fn hierarchical_head_logprobs(&self, hidden: &[f32], cm: &[f32], logits: &mut [f32]) {
24497        let h = hidden.len();
24498        let ncl = cm.len() / h.max(1);
24499        if ncl == 0 || logits.len() % ncl != 0 {
24500            return;
24501        }
24502        let cs = logits.len() / ncl;
24503        // cluster logits + log-softmax
24504        let mut lc = vec![0.0f32; ncl];
24505        for c in 0..ncl {
24506            let row = &cm[c * h..(c + 1) * h];
24507            let mut s = 0.0f32;
24508            for j in 0..h {
24509                s += row[j] * hidden[j];
24510            }
24511            lc[c] = s;
24512        }
24513        let mx = lc.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
24514        let lse: f32 = mx + lc.iter().map(|v| (v - mx).exp()).sum::<f32>().ln();
24515        for c in 0..ncl {
24516            let blk = &mut logits[c * cs..(c + 1) * cs];
24517            let bm = blk.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
24518            let bl: f32 = bm + blk.iter().map(|v| (v - bm).exp()).sum::<f32>().ln();
24519            let add = lc[c] - lse - bl;
24520            for v in blk.iter_mut() {
24521                *v += add;
24522            }
24523        }
24524    }
24525
24526    /// The next-token logits after `ids` through generation's own prompt path
24527    /// (the batched prefill, the device graphs): one generation step whose
24528    /// token is discarded, on a fresh sequence as `prefill_next_logits` —
24529    /// which walks the prompt a position at a time and stays the reference.
24530    /// The classification endpoint scores with this: a 231-token prompt of
24531    /// Qwen3.5-0.8B on CUDA took 0.69 s through the per-position walk, a
24532    /// one-token generation 0.04 s.
24533    pub fn prompt_next_logits(&mut self, ids: &[u32], task_mask: Option<&TaskMask>) -> Result<Vec<f32>, String> {
24534        self.clear_sequence_state();
24535        self.want_first_logits = true;
24536        self.first_logits = None;
24537        let out = self.generate_from_ids(ids, 1, task_mask, None);
24538        self.want_first_logits = false;
24539        out?;
24540        self.first_logits.take().ok_or_else(|| "generation produced no first-step logits".to_string())
24541    }
24542
24543    /// Prefill `ids` and return the next-token logits — what the model
24544    /// would predict next, WITHOUT committing to generation (introspection
24545    /// for `cortiq explain`). Clears and repopulates the KV cache; leaves
24546    /// the active overlay untouched.
24547    pub fn prefill_next_logits(&mut self, ids: &[u32], task_mask: Option<&TaskMask>) -> Vec<f32> {
24548        #[cfg(target_os = "macos")]
24549        crate::gpu_metal::set_io_namespace(self.graph_kv_id);
24550        self.clear_sequence_state();
24551        // This helper is used by the pooled classification endpoint, where
24552        // every request is a fresh sequence. The shared reset also clears the
24553        // wgpu token graph's device-side recurrent state.
24554        crate::gpu::graph_race_begin_generation();
24555        if task_mask.is_none() {
24556            self.o1_begin();
24557        }
24558        let mut hidden = vec![0.0f32; self.hidden_size];
24559        for (pos, &id) in ids.iter().enumerate() {
24560            let emb = self.embed_single(id);
24561            hidden = self.forward_layers(&emb, pos, task_mask);
24562        }
24563        if let Err(err) = self.o1_seal_checked() {
24564            self.o1_fail(err);
24565        }
24566        // Stacks that own their head (V4, V4.1, Qwen3.8-Flash-Next, GLM-5)
24567        // return a zero hidden and hand the logits out of band.
24568        if let Some(logits) = self.graph_logits.take() {
24569            return logits;
24570        }
24571        inference::rms_norm_into(
24572            &hidden,
24573            &self.weights.final_norm,
24574            self.rms_eps,
24575            self.norm_style,
24576            &mut self.ws.n1,
24577        );
24578        self.lm_head_forward(&self.ws.n1)
24579    }
24580}
24581
24582/// Convenience: deterministic tiny pipeline for tests.
24583pub fn create_test_pipeline(
24584    hidden_size: usize,
24585    intermediate_size: usize,
24586    num_heads: usize,
24587    num_kv_heads: usize,
24588    head_dim: usize,
24589    num_layers: usize,
24590    vocab_size: usize,
24591) -> Pipeline {
24592    // Small pseudo-random weights: constant weights make attention
24593    // degenerate and hide indexing bugs.
24594    let synth = |n: usize, salt: usize| -> Vec<f32> {
24595        (0..n)
24596            .map(|i| (((i * 31 + salt * 17 + 7) % 97) as f32 / 97.0 - 0.5) * 0.2)
24597            .collect()
24598    };
24599    let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
24600        QTensor::from_f32(synth(rows * cols, salt), rows, cols)
24601    };
24602    let layer_weights: Vec<LayerWeights> = (0..num_layers)
24603        .map(|li| LayerWeights {
24604            input_norm: vec![1.0; hidden_size],
24605            post_norm: vec![1.0; hidden_size],
24606            attn_out_norm: None,
24607            ffn_out_norm: None,
24608            layer_scale: None,
24609            ffn: FfnKind::Dense(DenseFfn {
24610                gate_proj: qt(intermediate_size, hidden_size, li * 10 + 5),
24611                up_proj: qt(intermediate_size, hidden_size, li * 10 + 6),
24612                down_proj: qt(hidden_size, intermediate_size, li * 10 + 7),
24613                act: Act::Silu,
24614                down_t: None,
24615                segs: Vec::new(),
24616            }),
24617            attn: AttnKind::Full {
24618                bias: None,
24619                wq: qt(num_heads * head_dim, hidden_size, li * 10 + 1),
24620                wk: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 2),
24621                wv: qt(num_kv_heads * head_dim, hidden_size, li * 10 + 3),
24622                wo: qt(hidden_size, num_heads * head_dim, li * 10 + 4),
24623                q_norm: None,
24624                k_norm: None,
24625                output_gate: false,
24626                softplus_gate: None,
24627            },
24628        })
24629        .collect();
24630
24631    Pipeline::new(
24632        Tokenizer::byte_level(),
24633        PipelineWeights {
24634            embed_tokens: qt(vocab_size, hidden_size, 100),
24635            layers: layer_weights,
24636            lm_head: qt(vocab_size, hidden_size, 200),
24637            final_norm: vec![1.0; hidden_size],
24638        },
24639        hidden_size,
24640        intermediate_size,
24641        num_heads,
24642        num_kv_heads,
24643        head_dim,
24644        num_layers,
24645        num_layers, // physical_layers = num_layers (non-looped)
24646        false,      // loop_final_norm
24647        vocab_size,
24648        1e-6,
24649        10_000.0,
24650        NormStyle::Qwen,
24651        4096,
24652        SamplerConfig {
24653            seed: Some(42),
24654            ..Default::default()
24655        },
24656    )
24657}
24658
24659/// Batched dense-FFN: gate/up/down via matmat (element-wise the same
24660/// math as b × dense_ffn — the same dot kernels).
24661/// One mask bit, LSB-first per byte — `TaskMask::ffn_active_indices`'s
24662/// convention.
24663#[inline]
24664fn mask_bit(row: &[u8], j: usize) -> bool {
24665    (row.get(j >> 3).copied().unwrap_or(0) >> (j & 7)) & 1 != 0
24666}
24667
24668/// Zero the CLOSED neurons' activations in a [rows × inter] panel — the
24669/// masked-inference fast path's whole trick: full fused quant compute,
24670/// then the mask lands on the ACTIVATIONS, which is arithmetically the
24671/// pruned network without touching a quantized weight byte. Whole open
24672/// bytes (0xFF = 8 open neurons) skip in one test.
24673/// `CMF_FFN_MASK_GAIN` — Patent 12 FIG. 4, variance-preserving
24674/// rescaling: truncation removes a share of the layer's output energy,
24675/// so the survivors are scaled up to put the variance back where the
24676/// downstream norm expects it. A scalar here; per layer it is
24677/// `sqrt(total energy / kept energy)`.
24678fn mask_gain() -> f32 {
24679    static G: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
24680    *G.get_or_init(|| {
24681        std::env::var("CMF_FFN_MASK_GAIN")
24682            .ok()
24683            .and_then(|v| v.parse().ok())
24684            .unwrap_or(1.0)
24685    })
24686}
24687
24688fn zero_masked_cols(g: &mut [f32], rows: usize, inter: usize, row: &[u8]) {
24689    // With CMF_FFN_MEANFILL a closed neuron contributes its average
24690    // instead of nothing — same bytes read, one constant restored.
24691    let fill = meanfill().and_then(|(i, v)| {
24692        let li = crate::gpu::cur_layer();
24693        (*i == inter && li >= 0).then(|| &v[li as usize * inter..(li as usize + 1) * inter])
24694    });
24695    for r in 0..rows {
24696        let base = r * inter;
24697        for (bi, &byte) in row.iter().enumerate() {
24698            if byte == 0xFF {
24699                continue;
24700            }
24701            let j0 = bi * 8;
24702            for bit in 0..8 {
24703                let j = j0 + bit;
24704                if j < inter && byte & (1 << bit) == 0 {
24705                    g[base + j] = fill.map_or(0.0, |f| f[j]);
24706                }
24707            }
24708        }
24709    }
24710    let gain = mask_gain();
24711    if gain != 1.0 {
24712        for v in g[..rows * inter].iter_mut() {
24713            *v *= gain;
24714        }
24715    }
24716}
24717
24718/// True when neuron `i`'s bit is set (no mask = everything runs).
24719#[inline]
24720fn tube_bit(row: Option<&[u8]>, i: usize) -> bool {
24721    row.is_none_or(|r| mask_bit(r, i))
24722}
24723
24724/// Every bit below `n` set — the common case for a tube file's CORE,
24725/// where only the tube bits vary per task.
24726fn all_bits_on(row: &[u8], n: usize) -> bool {
24727    (0..n).all(|i| mask_bit(row, i))
24728}
24729
24730/// `CMF_TUBE_TOPK` — how many tubes a TOKEN may open (0 = the task mask
24731/// decides alone). This is the dense FFN read as a mixture: the tubes
24732/// are the experts a k-means over `gate_proj` rows found, and the token
24733/// picks among them. `CMF_TUBE_SCORE=gate` scores a tube by its own
24734/// gate (realizable: only `up`/`down` of the losers go unread),
24735/// `=oracle` scores by the true `silu(gate)·up` mass (the ceiling —
24736/// only `down` is saved, and the selection has read what it predicts).
24737fn tube_topk() -> usize {
24738    static K: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
24739    *K.get_or_init(|| {
24740        std::env::var("CMF_TUBE_TOPK")
24741            .ok()
24742            .and_then(|v| v.parse().ok())
24743            .unwrap_or(0)
24744    })
24745}
24746
24747fn tube_score_oracle() -> bool {
24748    static O: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
24749    *O.get_or_init(|| std::env::var("CMF_TUBE_SCORE").is_ok_and(|v| v == "oracle"))
24750}
24751
24752/// The routed arm of `tube_ffn`: a token opens only its best `k` tubes.
24753/// At `b == 1` (decode) the losers are genuinely never read — that is
24754/// the speed. At `b > 1` (the scoring sweep) every tube is computed and
24755/// the losers' activations are zeroed instead: same arithmetic, so the
24756/// perplexity is the routed model's, measured without a per-token
24757/// gather in the middle of a GEMM.
24758fn tube_ffn_routed(
24759    d: &DenseFfn,
24760    xs: &[f32],
24761    b: usize,
24762    pool: Option<&Pool>,
24763    mask_row: Option<&[u8]>,
24764    k: usize,
24765) -> Vec<f32> {
24766    let hidden = d.down_proj.rows();
24767    let core = d.gate_proj.rows();
24768    let core_full = mask_row.is_none_or(|r| all_bits_on(r, core));
24769    let mut out = match (b, core_full, mask_row) {
24770        (1, true, _) => dense_ffn(d, xs, pool),
24771        (1, false, Some(row)) => dense_ffn_masked(d, xs, pool, row),
24772        (_, true, _) => dense_ffn_batch(d, xs, b, pool, None),
24773        (_, false, row) => dense_ffn_batch(d, xs, b, pool, row),
24774    };
24775    let cand: Vec<usize> = (0..d.segs.len())
24776        .filter(|&i| tube_bit(mask_row, d.segs[i].start))
24777        .collect();
24778    if cand.is_empty() {
24779        return out;
24780    }
24781    // gate (and, where the score or the batch needs it, up) per tube.
24782    // The SCORE is taken at the point the serving path could take it:
24783    // off the gate alone, or off the finished activation for the oracle.
24784    let oracle = tube_score_oracle();
24785    let mut acts: Vec<Vec<f32>> = Vec::with_capacity(cand.len());
24786    let mut scores = vec![0f32; b * cand.len()];
24787    for (ci, &i) in cand.iter().enumerate() {
24788        let seg = &d.segs[i];
24789        let w = seg.width;
24790        let mut g = vec![0.0f32; b * w];
24791        if b == 1 {
24792            seg.gate.matvec(xs, &mut g, pool);
24793        } else {
24794            seg.gate.matmat(xs, b, &mut g, pool);
24795        }
24796        for v in g.iter_mut() {
24797            *v = Act::Silu.combine(*v, 1.0);
24798        }
24799        if !oracle {
24800            for t in 0..b {
24801                scores[t * cand.len() + ci] =
24802                    g[t * w..(t + 1) * w].iter().map(|v| v * v).sum::<f32>();
24803            }
24804        }
24805        if oracle || b > 1 {
24806            let mut u = vec![0.0f32; b * w];
24807            if b == 1 {
24808                seg.up.matvec(xs, &mut u, pool);
24809            } else {
24810                seg.up.matmat(xs, b, &mut u, pool);
24811            }
24812            for (a, &v) in g.iter_mut().zip(u.iter()) {
24813                *a *= v;
24814            }
24815            if oracle {
24816                for t in 0..b {
24817                    scores[t * cand.len() + ci] =
24818                        g[t * w..(t + 1) * w].iter().map(|v| v * v).sum::<f32>();
24819                }
24820            }
24821        }
24822        acts.push(g);
24823    }
24824    // per-token scores and the winners
24825    let keep = k.min(cand.len());
24826    let mut scratch: Vec<f32> = Vec::new();
24827    for t in 0..b {
24828        let mut sc: Vec<(f32, usize)> = (0..cand.len())
24829            .map(|ci| (scores[t * cand.len() + ci], ci))
24830            .collect();
24831        sc.sort_unstable_by(|x, y| y.0.total_cmp(&x.0));
24832        let mut alive = vec![false; cand.len()];
24833        for &(_, ci) in sc.iter().take(keep) {
24834            alive[ci] = true;
24835        }
24836        if b > 1 {
24837            for (ci, a) in acts.iter_mut().enumerate() {
24838                if !alive[ci] {
24839                    let w = d.segs[cand[ci]].width;
24840                    a[t * w..(t + 1) * w].fill(0.0);
24841                }
24842            }
24843        } else {
24844            // decode: finish only the winners — the losers' up/down
24845            // (and, with the gate score, everything but their gate)
24846            // are never touched.
24847            for (ci, &i) in cand.iter().enumerate() {
24848                if !alive[ci] {
24849                    continue;
24850                }
24851                let seg = &d.segs[i];
24852                let w = seg.width;
24853                let g = &mut acts[ci];
24854                if !tube_score_oracle() {
24855                    scratch.clear();
24856                    scratch.resize(w, 0.0);
24857                    seg.up.matvec(xs, &mut scratch, pool);
24858                    for (a, &v) in g.iter_mut().zip(scratch.iter()) {
24859                        *a *= v;
24860                    }
24861                }
24862                let mut acc = vec![0.0f32; hidden];
24863                seg.down.matvec(g, &mut acc, pool);
24864                for (o, a) in out.iter_mut().zip(&acc) {
24865                    *o += *a;
24866                }
24867            }
24868        }
24869    }
24870    if b > 1 {
24871        for (ci, &i) in cand.iter().enumerate() {
24872            let seg = &d.segs[i];
24873            let mut acc = vec![0.0f32; b * hidden];
24874            seg.down.matmat(&acts[ci], b, &mut acc, pool);
24875            for (o, a) in out.iter_mut().zip(&acc) {
24876                *o += *a;
24877            }
24878        }
24879    }
24880    out
24881}
24882
24883/// FFN of a defragged tube layer: the always-on core plus the tubes the
24884/// task mask switches on. Each tube is a normal tensor triple, so the
24885/// same kernels run it and an inactive tube's bytes are never read —
24886/// that is the whole point of the defrag (a scattered mask cannot skip
24887/// bytes; a contiguous one is just a smaller matrix).
24888fn tube_ffn(
24889    d: &DenseFfn,
24890    xs: &[f32],
24891    b: usize,
24892    pool: Option<&Pool>,
24893    mask_row: Option<&[u8]>,
24894) -> Vec<f32> {
24895    if tube_topk() > 0 {
24896        return tube_ffn_routed(d, xs, b, pool, mask_row, tube_topk());
24897    }
24898    let hidden = d.down_proj.rows();
24899    let core = d.gate_proj.rows();
24900    let core_full = mask_row.is_none_or(|r| all_bits_on(r, core));
24901    let mut out = match (b, core_full, mask_row) {
24902        (1, true, _) => dense_ffn(d, xs, pool),
24903        (1, false, Some(row)) => dense_ffn_masked(d, xs, pool, row),
24904        (_, true, _) => dense_ffn_batch(d, xs, b, pool, None),
24905        (_, false, row) => dense_ffn_batch(d, xs, b, pool, row),
24906    };
24907    TUBE_SCRATCH.with(|sc| {
24908        let mut sc = sc.borrow_mut();
24909        let [g, u, acc] = &mut *sc;
24910        for seg in &d.segs {
24911            if !tube_bit(mask_row, seg.start) {
24912                continue;
24913            }
24914            let w = seg.width;
24915            g.resize(b * w, 0.0);
24916            if b == 1
24917                && d.act == Act::Silu
24918                && QTensor::matvec_silu_mul(&seg.gate, &seg.up, xs, g, pool)
24919            {
24920                // g holds silu(gate)·up.
24921            } else {
24922                u.resize(b * w, 0.0);
24923                if b == 1 {
24924                    QTensor::matvec_many([&seg.gate, &seg.up], xs, [g, u], pool);
24925                } else {
24926                    seg.gate.matmat(xs, b, g, pool);
24927                    seg.up.matmat(xs, b, u, pool);
24928                }
24929                for i in 0..b * w {
24930                    g[i] = d.act.combine(g[i], u[i]);
24931                }
24932            }
24933            acc.resize(b * hidden, 0.0);
24934            acc.fill(0.0);
24935            if b == 1 {
24936                seg.down.matvec(g, acc, pool);
24937            } else {
24938                seg.down.matmat(g, b, acc, pool);
24939            }
24940            for (o, a) in out.iter_mut().zip(acc.iter()) {
24941                *o += *a;
24942            }
24943        }
24944        out
24945    })
24946}
24947
24948thread_local! {
24949    /// gate / up / down-accumulator scratch for the tube loop — a tube
24950    /// runs once per layer per token, and a fresh Vec each time is a
24951    /// malloc per tube per layer per token.
24952    static TUBE_SCRATCH: std::cell::RefCell<[Vec<f32>; 3]> =
24953        const { std::cell::RefCell::new([Vec::new(), Vec::new(), Vec::new()]) };
24954}
24955
24956/// An expert's tubes (`mlp.experts.{e}.*_proj.tube1.weight`: its hot neurons at eight
24957/// bits, their rows zero in the expert's own triple) added to `out` with the expert's
24958/// routing weight. The MoE paths compute the triple themselves; this is the rest.
24959pub(crate) fn expert_tubes_add(d: &DenseFfn, x: &[f32], weight: f32, out: &mut [f32], pool: Option<&Pool>) {
24960    if d.segs.is_empty() {
24961        return;
24962    }
24963    TUBE_SCRATCH.with(|sc| {
24964        let mut sc = sc.borrow_mut();
24965        let [g, u, acc] = &mut *sc;
24966        for seg in &d.segs {
24967            let w = seg.width;
24968            g.resize(w, 0.0);
24969            if !(d.act == Act::Silu && QTensor::matvec_silu_mul(&seg.gate, &seg.up, x, g, pool)) {
24970                u.resize(w, 0.0);
24971                QTensor::matvec_many([&seg.gate, &seg.up], x, [g, u], pool);
24972                for i in 0..w {
24973                    g[i] = d.act.combine(g[i], u[i]);
24974                }
24975            }
24976            acc.resize(out.len(), 0.0);
24977            acc.fill(0.0);
24978            seg.down.matvec(g, acc, pool);
24979            for (o, a) in out.iter_mut().zip(acc.iter()) {
24980                *o += weight * *a;
24981            }
24982        }
24983    });
24984}
24985
24986/// The shared expert's weight on one token: σ of its gate, or 1 without one.
24987pub(crate) fn shared_expert_weight(gate: Option<&QTensor>, x: &[f32], pool: Option<&Pool>) -> f32 {
24988    gate.map_or(1.0, |gate| {
24989        let mut gl = [0.0f32; 1];
24990        gate.matvec(x, &mut gl, pool);
24991        1.0 / (1.0 + (-gl[0]).exp())
24992    })
24993}
24994
24995/// The shared expert's tubes (`mlp.shared_expert.*_proj.tube1.weight`, `hot-bake
24996/// --shared-q8`: the whole expert at eight bits) added to `out` with its weight.
24997pub(crate) fn shared_tubes_add(m: &MoeFfn, x: &[f32], out: &mut [f32], pool: Option<&Pool>) {
24998    if let Some((se, gate)) = &m.shared
24999        && !se.segs.is_empty()
25000    {
25001        let g = shared_expert_weight(gate.as_ref(), x, pool);
25002        expert_tubes_add(se, x, g, out, pool);
25003    }
25004}
25005
25006/// CMF_PREFILL_PROF: cumulative ns of the batched walk's attention and
25007/// FFN halves (all layers, all chunks).
25008static PREFILL_SPLIT: [std::sync::atomic::AtomicU64; 2] = [
25009    std::sync::atomic::AtomicU64::new(0),
25010    std::sync::atomic::AtomicU64::new(0),
25011];
25012
25013/// The wgpu side of `CMF_PREFILL_PROF`: q|k|v GEMMs' enqueue and readback
25014/// wait, the chunk attend's readback wait (ms, cumulative) and the int8
25015/// GEMMs the `zi_mm` route took.
25016fn wgpu_prefill_counters() -> (f64, f64, f64, u64) {
25017    #[cfg(feature = "gpu")]
25018    {
25019        use std::sync::atomic::Ordering::Relaxed;
25020        let ms = |a: &std::sync::atomic::AtomicU64| a.load(Relaxed) as f64 / 1e6;
25021        (
25022            ms(&crate::gpu_wgpu::GEMM_MANY_NS[0]),
25023            ms(&crate::gpu_wgpu::GEMM_MANY_NS[1]),
25024            ms(&crate::gpu_wgpu::CHUNK_ATTEND_WAIT_NS),
25025            crate::gpu_wgpu::ZI_GEMM_CALLS.load(Relaxed),
25026        )
25027    }
25028    #[cfg(not(feature = "gpu"))]
25029    (0.0, 0.0, 0.0, 0)
25030}
25031
25032/// The wgpu prefill mirror attend's outcome counters
25033/// (`gpu_wgpu::MIRROR_EVENTS`).
25034fn wgpu_mirror_counters() -> [u64; 6] {
25035    #[cfg(feature = "gpu")]
25036    {
25037        crate::gpu_wgpu::MIRROR_EVENTS
25038            .each_ref()
25039            .map(|a| a.load(std::sync::atomic::Ordering::Relaxed))
25040    }
25041    #[cfg(not(feature = "gpu"))]
25042    [0; 6]
25043}
25044
25045fn prefill_prof_on() -> bool {
25046    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
25047    *ON.get_or_init(|| std::env::var_os("CMF_PREFILL_PROF").is_some())
25048}
25049
25050/// Accumulate the dense FFN activations which feed the down projection.
25051///
25052/// MTP calibration intentionally calls this independently of the trunk's
25053/// `FFN_PROBE` TLS recorder: an MTP sidecar can use a different FFN width,
25054/// and borrowing the trunk's layer-numbered accumulator would silently turn
25055/// draft statistics into trunk proxies.  The caller owns the execution scope
25056/// (the public MTP probe uses `gpu::cpu_scope`) and supplies one accumulator
25057/// per actual MTP FFN channel.
25058pub(crate) fn accumulate_dense_ffn_activation_mass(
25059    d: &DenseFfn,
25060    xs: &[f32],
25061    b: usize,
25062    pool: Option<&Pool>,
25063    mass: &mut [f64],
25064    squared_mass: &mut [f64],
25065) -> Result<(), String> {
25066    let inter = d.gate_proj.rows();
25067    let hidden = d.gate_proj.cols();
25068    if mass.len() != inter || squared_mass.len() != inter {
25069        return Err(format!(
25070            "MTP FFN probe: accumulator widths ({}, {}) != gate width {inter}",
25071            mass.len(),
25072            squared_mass.len()
25073        ));
25074    }
25075    if d.up_proj.rows() != inter
25076        || d.up_proj.cols() != hidden
25077        || d.down_proj.cols() != inter
25078        || d.down_proj.rows() != hidden
25079    {
25080        return Err("MTP FFN probe: inconsistent dense FFN shapes".into());
25081    }
25082    if !d.segs.is_empty() {
25083        return Err("MTP FFN probe: tube-segmented draft FFNs are not supported".into());
25084    }
25085    if xs.len() != b.saturating_mul(hidden) {
25086        return Err(format!(
25087            "MTP FFN probe: {} input values for {b} × {hidden} rows",
25088            xs.len()
25089        ));
25090    }
25091    if b == 0 {
25092        return Ok(());
25093    }
25094    let mut gate = vec![0.0f32; b * inter];
25095    let mut up = vec![0.0f32; b * inter];
25096    d.gate_proj.matmat(xs, b, &mut gate, pool);
25097    d.up_proj.matmat(xs, b, &mut up, pool);
25098    for row in 0..b {
25099        for i in 0..inter {
25100            let a = d.act.combine(gate[row * inter + i], up[row * inter + i]);
25101            let a = a as f64;
25102            mass[i] += a.abs();
25103            squared_mass[i] += a * a;
25104        }
25105    }
25106    Ok(())
25107}
25108
25109fn dense_ffn_batch(
25110    d: &DenseFfn,
25111    xs: &[f32],
25112    b: usize,
25113    pool: Option<&Pool>,
25114    mask_row: Option<&[u8]>,
25115) -> Vec<f32> {
25116    let inter = d.gate_proj.rows();
25117    let hidden = d.down_proj.rows();
25118    // Fused on-device SwiGLU when the device is in play: three separate
25119    // `matmat` calls are three round trips per layer, and the gate/up
25120    // panels (b × inter — 22 MB each at a 512-token chunk) cross the bus
25121    // twice for nothing. The kernel already existed for the image DiT;
25122    // the LLM prefill was simply never wired to it. A task mask needs the
25123    // activations on the host between the halves, so it keeps the CPU
25124    // arm below.
25125    // SiLU/GELU have device arms everywhere they are admitted.  MiniMax
25126    // M3's frozen OAI contract has an additional WGPU-only arm; callers on
25127    // native Metal still get an honest decline from `q4_ffn_act` rather than
25128    // an accidental SiLU evaluation.
25129    let fused_act = d.act.wgpu_graph_act();
25130    if mask_row.is_none()
25131        && fused_act.is_some()
25132        && b >= 32
25133        && crate::gpu::enabled_here()
25134        && !crate::gpu::mm_killed()
25135        // The refit pass needs this layer's activations on the host; the
25136        // fused chain keeps them on the device. Refusing it here costs
25137        // one round trip and keeps every GEMM on the card — the
25138        // alternative was running the whole calibration on the CPU.
25139        && refit_dir().is_none()
25140        // Same for the mass/hit probes. The accumulator at the bottom of
25141        // this function only sees `g` when `g` came back to the host, so
25142        // a fused batch would leave it summing nothing — a probe that
25143        // reports zeros rather than failing, which is worse.
25144        && !ffn_probe_active()
25145        // GPTQ calibration folds every projection's input on the host
25146        // (`QTensor::matmat`); the fused chain would hand gate/up/down
25147        // their inputs on the card and leave the FFN uncalibrated.
25148        && !crate::gptq_capture::capturing()
25149    {
25150        if let (Some((model, w1)), Some((_, w3)), Some((_, w2))) = (
25151            d.gate_proj.mapped_q4t(),
25152            d.up_proj.mapped_q4t(),
25153            d.down_proj.mapped_q4t(),
25154        ) {
25155            let mut out = vec![0.0f32; b * hidden];
25156            let act = fused_act.expect("checked above");
25157            if crate::gpu::q4_ffn_act(
25158                model, w1, w3, w2, xs, b, hidden, inter, false, act, &mut out,
25159            ) {
25160                return out;
25161            }
25162        }
25163        // The q4tp twin (same kernel family, scale from the row ladder) —
25164        // the DiT has run it in production since the pipeline containers;
25165        // the LLM prefill was simply never wired to it, so a q4tp model's
25166        // prefill panels stayed on the CPU.
25167        if let (Some((model, w1)), Some((_, w3)), Some((_, w2))) = (
25168            d.gate_proj.mapped_q4tp(),
25169            d.up_proj.mapped_q4tp(),
25170            d.down_proj.mapped_q4tp(),
25171        ) {
25172            let mut out = vec![0.0f32; b * hidden];
25173            let act = fused_act.expect("checked above");
25174            if crate::gpu::q4_ffn_act(model, w1, w3, w2, xs, b, hidden, inter, true, act, &mut out)
25175            {
25176                return out;
25177            }
25178        }
25179        // Every other device codec — int8, or gate/up and down in different
25180        // codecs: the three GEMMs with the panels kept on the card. Without
25181        // it a q8_2f prefill read both b·inter panels home, folded them on
25182        // one host thread, and sent the result back for down.
25183        // CMF_FFN_KEEP=0 keeps the per-GEMM path (A/B).
25184        if let (true, Some((model, w1)), Some((_, w3)), Some((_, w2))) = (
25185            std::env::var("CMF_FFN_KEEP").as_deref() != Ok("0"),
25186            d.gate_proj.mapped_device_gemm(),
25187            d.up_proj.mapped_device_gemm(),
25188            d.down_proj.mapped_device_gemm(),
25189        ) {
25190            let mut out = vec![0.0f32; b * hidden];
25191            let act = fused_act.expect("checked above");
25192            if crate::gpu::ffn_act_keep(model, w1, w3, w2, xs, b, hidden, inter, act, &mut out) {
25193                return out;
25194            }
25195        }
25196    }
25197    let mut g = vec![0.0f32; b * inter];
25198    d.gate_proj.matmat(xs, b, &mut g, pool);
25199    let mut u = vec![0.0f32; b * inter];
25200    d.up_proj.matmat(xs, b, &mut u, pool);
25201    if gate_topk() > 0 && d.act == Act::Silu {
25202        for t in 0..b {
25203            let row = &mut g[t * inter..(t + 1) * inter];
25204            for v in row.iter_mut() {
25205                *v = Act::Silu.combine(*v, 1.0);
25206            }
25207            keep_top_k(row, gate_topk());
25208        }
25209        for i in 0..b * inter {
25210            g[i] *= u[i];
25211        }
25212    } else {
25213        combine_pooled(d.act, &mut g[..b * inter], &u[..b * inter], pool);
25214    }
25215    if let Some(row) = mask_row {
25216        zero_masked_cols(&mut g, b, inter, row);
25217    }
25218    if oracle_topk() > 0 {
25219        for t in 0..b {
25220            keep_top_k(&mut g[t * inter..(t + 1) * inter], oracle_topk());
25221        }
25222    }
25223    let mut out = vec![0.0f32; b * hidden];
25224    d.down_proj.matmat(&g, b, &mut out, pool);
25225    if refit_dir().is_some() {
25226        let li = crate::gpu::cur_layer();
25227        if li >= 0 {
25228            refit_accumulate(li as usize, &g, b, inter, &out, hidden, pool);
25229        }
25230    }
25231    // The DTG-MA probe, on the batched path: one prefill sweep gives the
25232    // same per-neuron statistic the per-position probe does, and on a 27B
25233    // that is minutes instead of hours.
25234    FFN_PROBE.with(|pr| {
25235        if let Some(acc) = pr.borrow_mut().as_mut() {
25236            let li = crate::gpu::cur_layer();
25237            if li < 0 {
25238                return;
25239            }
25240            let Some(row) = acc.get_mut(li as usize) else {
25241                return;
25242            };
25243            let (sq, topk) = (probe_sq(), probe_topk().min(inter));
25244            let mut mag: Vec<f32> = Vec::new();
25245            for t in 0..b {
25246                let gr = &g[t * inter..(t + 1) * inter];
25247                if topk > 0 {
25248                    // The hit count of the per-position probe: a position's
25249                    // `topk` loudest neurons each get one.
25250                    mag.clear();
25251                    mag.extend(gr.iter().map(|v| v.abs()));
25252                    let (_, kth, _) = mag.select_nth_unstable_by(topk - 1, |a, b| {
25253                        b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
25254                    });
25255                    let thr = *kth;
25256                    for (a, &v) in row.iter_mut().zip(gr) {
25257                        if v.abs() >= thr {
25258                            *a += 1.0;
25259                        }
25260                    }
25261                    continue;
25262                }
25263                for (a, &v) in row.iter_mut().zip(gr) {
25264                    *a += if sq {
25265                        (v as f64) * (v as f64)
25266                    } else {
25267                        (v as f64).abs()
25268                    };
25269                }
25270            }
25271        }
25272    });
25273    out
25274}
25275
25276/// Batched MoE-FFN: router batched, positions are GROUPED by expert —
25277/// an expert's weights are read once for all its positions in the chunk
25278/// (the main prefill-GEMM win on MoE: 960MB/token of 35B experts).
25279/// Accumulate per-channel activation energy for `CMF_RMS_TRACE`.
25280fn accumulate_act(m: &MoeFfn, xs: &[f32], b: usize) {
25281    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
25282    static DUMP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
25283    let on = *ON.get_or_init(|| std::env::var("CMF_RMS_TRACE").is_ok());
25284    let dump = *DUMP.get_or_init(|| std::env::var("CMF_ACT_DUMP").is_ok());
25285    if (!on && !dump) || b == 0 {
25286        return;
25287    }
25288    let hidden = xs.len() / b;
25289    if on {
25290        let mut acc = m.act_sq.borrow_mut();
25291        if acc.len() < hidden {
25292            acc.resize(hidden, 0.0);
25293        }
25294        for t in 0..b {
25295            let row = &xs[t * hidden..(t + 1) * hidden];
25296            for (a, &v) in acc.iter_mut().zip(row) {
25297                *a += (v as f64) * (v as f64);
25298            }
25299        }
25300    }
25301    if dump {
25302        // Cap the capture: the covariance needs a few thousand rows, and a
25303        // whole prefill of every layer would be gigabytes for no extra rank.
25304        let cap: usize = std::env::var("CMF_ACT_DUMP_ROWS")
25305            .ok()
25306            .and_then(|v| v.parse().ok())
25307            .unwrap_or(4096);
25308        let mut rows = m.act_rows.borrow_mut();
25309        if rows.len() < cap * hidden {
25310            let take = b.min((cap * hidden - rows.len()) / hidden.max(1));
25311            rows.extend_from_slice(&xs[..take * hidden]);
25312        }
25313    }
25314}
25315
25316/// Send-able cursor over a Vec-of-Vecs: each pool worker writes only its
25317/// own slots (disjoint by construction in the caller).
25318#[derive(Clone, Copy)]
25319struct SendVecs(*mut Vec<f32>);
25320unsafe impl Send for SendVecs {}
25321unsafe impl Sync for SendVecs {}
25322impl SendVecs {
25323    #[inline]
25324    fn at(self, i: usize) -> *mut Vec<f32> {
25325        unsafe { self.0.add(i) }
25326    }
25327}
25328
25329fn moe_ffn_batch(
25330    m: &MoeFfn,
25331    xs: &[f32],
25332    b: usize,
25333    hidden: usize,
25334    pool: Option<&Pool>,
25335    allowed: Option<&[bool]>,
25336) -> Vec<f32> {
25337    accumulate_act(m, xs, b);
25338    let ne = m.experts.len();
25339    let mut logits = vec![0.0f32; b * ne];
25340    match &m.resonance {
25341        Some(r) => {
25342            let hdim = xs.len() / b.max(1);
25343            for bi in 0..b {
25344                r.scores(
25345                    &xs[bi * hdim..(bi + 1) * hdim],
25346                    &mut logits[bi * ne..(bi + 1) * ne],
25347                );
25348            }
25349        }
25350        None => m.router.matmat(xs, b, &mut logits, pool),
25351    }
25352
25353    // Assignments: expert → [(position, weight)] — same routing as
25354    // moe_ffn, per position (see `moe_route`).
25355    let mut assign: Vec<Vec<(usize, f32)>> = vec![Vec::new(); ne];
25356    {
25357        let mut st = m.stats.borrow_mut();
25358        if st.len() < ne {
25359            st.resize(ne, 0);
25360        }
25361        for bi in 0..b {
25362            let (idx, p, wsum) = moe_route(&logits[bi * ne..(bi + 1) * ne], m, allowed);
25363            for &e in &idx {
25364                st[e] += 1;
25365                assign[e].push((bi, p[e] / wsum));
25366            }
25367        }
25368    }
25369
25370    let mut out = vec![0.0f32; b * hidden];
25371    let cols = m.experts[0].gate_proj.cols();
25372    let run_expert = |d: &DenseFfn, list: &[(usize, f32)], out: &mut [f32]| {
25373        let sb = list.len();
25374        let mut sub = vec![0.0f32; sb * cols];
25375        for (k, &(bi, _)) in list.iter().enumerate() {
25376            sub[k * cols..(k + 1) * cols].copy_from_slice(&xs[bi * cols..(bi + 1) * cols]);
25377        }
25378        let eo = dense_ffn_batch(d, &sub, sb, pool, None);
25379        for (k, &(bi, w)) in list.iter().enumerate() {
25380            for i in 0..hidden {
25381                out[bi * hidden + i] += w * eo[k * hidden + i];
25382            }
25383        }
25384    };
25385    // Routed experts: the panels are TINY (b·top_k spread over every
25386    // expert — a few positions each), so a pool dispatch per expert is
25387    // pure barrier cost. Invert the parallelism: workers take WHOLE
25388    // experts (serial math inside), then one deterministic scatter in
25389    // expert order — the exact accumulation order the serial loop had.
25390    let active: Vec<usize> = (0..ne).filter(|&e| !assign[e].is_empty()).collect();
25391    if pool.is_some() && active.len() >= 8 {
25392        let mut panels: Vec<Vec<f32>> = vec![Vec::new(); active.len()];
25393        {
25394            let panel_ptr = SendVecs(panels.as_mut_ptr());
25395            // Capture only the expert table: `m` itself carries RefCell
25396            // stats and must not cross the pool boundary.
25397            let experts = &m.experts;
25398            let (active_r, assign_r) = (&active, &assign);
25399            let inherit_cpu = crate::gpu::inherit_cpu_scope();
25400            let run = |start: usize, end: usize| {
25401                let _cpu_scope = inherit_cpu();
25402                // Native Metal: the per-op device helpers (`q4tp_ffn`,
25403                // `q8_matmat`, …) stage through size-keyed shared io
25404                // buffers and are not re-entrant — two workers whose experts
25405                // drew the same row count wrote one buffer at once, so a
25406                // Mellum2.1 prompt came out different on every run. The
25407                // workers keep whole experts on the CPU there; the device
25408                // prefill is the MoE chunk graph.
25409                #[cfg(target_os = "macos")]
25410                let _metal_cpu = crate::gpu::enter_cpu_scope();
25411                for ai in start..end {
25412                    let e = active_r[ai];
25413                    let list = &assign_r[e];
25414                    let sb = list.len();
25415                    let mut sub = vec![0.0f32; sb * cols];
25416                    for (k, &(bi, _)) in list.iter().enumerate() {
25417                        sub[k * cols..(k + 1) * cols]
25418                            .copy_from_slice(&xs[bi * cols..(bi + 1) * cols]);
25419                    }
25420                    // SAFETY: each worker owns a disjoint panels[ai].
25421                    unsafe {
25422                        *panel_ptr.at(ai) = dense_ffn_batch(&experts[e], &sub, sb, None, None);
25423                    }
25424                }
25425            };
25426            match pool {
25427                Some(p) => p.run_rows(active.len(), &run),
25428                None => run(0, active.len()),
25429            }
25430        }
25431        for (ai, &e) in active.iter().enumerate() {
25432            for (k, &(bi, w)) in assign[e].iter().enumerate() {
25433                let eo = &panels[ai][k * hidden..(k + 1) * hidden];
25434                for i in 0..hidden {
25435                    out[bi * hidden + i] += w * eo[i];
25436                }
25437            }
25438        }
25439    } else {
25440        for &e in &active {
25441            run_expert(&m.experts[e], &assign[e], &mut out);
25442        }
25443    }
25444    if let Some((se, gate)) = &m.shared {
25445        let all: Vec<(usize, f32)> = if let Some(gate) = gate {
25446            let mut gl = vec![0.0f32; b];
25447            gate.matmat(xs, b, &mut gl, pool);
25448            (0..b)
25449                .map(|bi| (bi, 1.0 / (1.0 + (-gl[bi]).exp())))
25450                .collect()
25451        } else {
25452            (0..b).map(|bi| (bi, 1.0)).collect()
25453        };
25454        run_expert(se, &all, &mut out);
25455    }
25456    out
25457}
25458
25459/// Decode-exact multi-token MoE — the MiMo speculative verify's FFN. Row
25460/// `r` of the result is bit-identical to `moe_ffn(m, x_r)` on the CPU
25461/// (`moe_ffn_cpu` → `moe_ffn_cpu_batched`): router matvec per row, the same
25462/// routing, the same int8 gate/up/SiLU and down terms
25463/// (`QTensor::moe_gate_up_rows` / `moe_down_rows`), and the row's experts
25464/// summed in ITS route order from 0. What the rows share is the weight
25465/// traffic: each routed expert is read once for every row that picked it.
25466/// (`moe_ffn_batch`, the prompt path, groups the same way but sums in
25467/// expert-index order and runs blocked kernels on wide groups — close, not
25468/// bit-equal to decode.) Any layer the kernels do not cover, or a device
25469/// that could answer `moe_ffn` itself, walks `moe_ffn` row by row.
25470fn moe_ffn_rows_exact(
25471    m: &MoeFfn,
25472    xs: &[f32],
25473    b: usize,
25474    hidden: usize,
25475    pool: Option<&Pool>,
25476) -> Vec<f32> {
25477    let mut out = vec![0.0f32; b * hidden];
25478    let per_row = |out: &mut [f32]| {
25479        for r in 0..b {
25480            let o = moe_ffn(m, &xs[r * hidden..(r + 1) * hidden], pool, None);
25481            out[r * hidden..(r + 1) * hidden].copy_from_slice(&o);
25482        }
25483    };
25484    let covered = !crate::gpu::enabled_here()
25485        && moe_batch_enabled()
25486        && m.shared.is_none()
25487        && m.resonance.is_none()
25488        && FFN_PROBE.with(|pr| pr.borrow().is_none())
25489        && m.experts.iter().all(|d| d.act == Act::Silu);
25490    if !covered {
25491        per_row(&mut out);
25492        return out;
25493    }
25494    let ne = m.experts.len();
25495    // Routing, row by row, exactly as `moe_ffn`.
25496    let mut routes: Vec<(Vec<usize>, Vec<f32>)> = Vec::with_capacity(b);
25497    for r in 0..b {
25498        let x = &xs[r * hidden..(r + 1) * hidden];
25499        accumulate_act(m, x, 1);
25500        let mut logits = vec![0.0f32; ne];
25501        m.router.matvec(x, &mut logits, pool);
25502        let (idx, p, wsum) = moe_route(&logits, m, None);
25503        {
25504            let mut st = m.stats.borrow_mut();
25505            if st.len() < ne {
25506                st.resize(ne, 0);
25507            }
25508            for &e in &idx {
25509                st[e] += 1;
25510            }
25511        }
25512        let w: Vec<f32> = idx
25513            .iter()
25514            .map(|&e| p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]))
25515            .collect();
25516        routes.push((idx, w));
25517    }
25518    if routes.iter().any(|(idx, _)| idx.is_empty()) {
25519        per_row(&mut out);
25520        return out;
25521    }
25522    // Group the (row, expert) picks by expert, in first-seen order.
25523    let mut experts: Vec<usize> = Vec::new();
25524    let mut groups: Vec<Vec<usize>> = Vec::new();
25525    for (r, (idx, _)) in routes.iter().enumerate() {
25526        for &e in idx {
25527            match experts.iter().position(|&x| x == e) {
25528                Some(g) => groups[g].push(r),
25529                None => {
25530                    experts.push(e);
25531                    groups.push(vec![r]);
25532                }
25533            }
25534        }
25535    }
25536    let n_pairs: usize = groups.iter().map(|g| g.len()).sum();
25537    let inter = m.experts[experts[0]].gate_proj.rows();
25538    let pairs: Vec<(&QTensor, &QTensor)> = experts
25539        .iter()
25540        .map(|&e| (&m.experts[e].gate_proj, &m.experts[e].up_proj))
25541        .collect();
25542    let mut gs: Vec<Vec<f32>> = (0..n_pairs).map(|_| vec![0f32; inter]).collect();
25543    if !QTensor::moe_gate_up_rows(&pairs, &groups, xs, &mut gs, pool) {
25544        per_row(&mut out);
25545        return out;
25546    }
25547    let downs: Vec<&QTensor> = experts.iter().map(|&e| &m.experts[e].down_proj).collect();
25548    let lens: Vec<usize> = groups.iter().map(|g| g.len()).collect();
25549    let mut ds: Vec<Vec<f32>> = (0..n_pairs).map(|_| vec![0f32; hidden]).collect();
25550    if !QTensor::moe_down_rows(&downs, &lens, &gs, &mut ds, pool) {
25551        per_row(&mut out);
25552        return out;
25553    }
25554    // Where each (row, expert) term landed in the flat pair list.
25555    let mut slot = std::collections::HashMap::with_capacity(n_pairs);
25556    let mut p = 0usize;
25557    for (g, &e) in experts.iter().enumerate() {
25558        for &r in &groups[g] {
25559            slot.insert((r, e), p);
25560            p += 1;
25561        }
25562    }
25563    for (r, (idx, w)) in routes.iter().enumerate() {
25564        let terms: Vec<(&[f32], f32)> = idx
25565            .iter()
25566            .zip(w)
25567            .map(|(&e, &we)| (ds[slot[&(r, e)]].as_slice(), we))
25568            .collect();
25569        let row = &mut out[r * hidden..(r + 1) * hidden];
25570        for (i, dst) in row.iter_mut().enumerate() {
25571            // `moe_down_many`'s per-row sum: from 0, in route order.
25572            let mut acc = 0f32;
25573            for (d, we) in &terms {
25574                acc += we * d[i];
25575            }
25576            *dst = acc;
25577        }
25578    }
25579    out
25580}
25581
25582/// Gemma's final-logit soft-capping, `c·tanh(x/c)`, over a whole vocab row —
25583/// element for element the serial expression, split across the pool: at a
25584/// 262k vocab the serial `tanh` pass was ~5 ms of a 36 ms decode token.
25585/// Ripple's value residual: the rows V projects, `torch.lerp(e0, normed, blend)` term for term
25586/// (the two forms torch picks between at a weight of one half).
25587pub(crate) fn vres_lerp(e0: &[f32], normed: &[f32], blend: f32, out: &mut Vec<f32>) {
25588    debug_assert_eq!(e0.len(), normed.len());
25589    out.clear();
25590    if blend < 0.5 {
25591        out.extend(e0.iter().zip(normed).map(|(&e, &n)| e + blend * (n - e)));
25592    } else {
25593        out.extend(e0.iter().zip(normed).map(|(&e, &n)| n - (n - e) * (1.0 - blend)));
25594    }
25595}
25596
25597pub(crate) fn softcap_in_place(v: &mut [f32], c: f32, pool: Option<&Pool>) {
25598    match pool {
25599        Some(p) if v.len() >= 1 << 15 => {
25600            let base = v.as_mut_ptr() as usize;
25601            p.run_rows(v.len(), &|s, e| {
25602                // SAFETY: run_rows hands out disjoint [s, e) ranges of `v`,
25603                // which outlives the (blocking) dispatch.
25604                let sl =
25605                    unsafe { std::slice::from_raw_parts_mut((base as *mut f32).add(s), e - s) };
25606                for x in sl {
25607                    *x = c * (*x / c).tanh();
25608                }
25609            });
25610        }
25611        _ => {
25612            for x in v.iter_mut() {
25613                *x = c * (*x / c).tanh();
25614            }
25615        }
25616    }
25617}
25618
25619thread_local! {
25620    /// gate/up activation scratch for the dense FFN paths (single uses
25621    /// two slots, the fused pair all four) — these were fresh
25622    /// intermediate-size Vecs on every layer of every token.
25623    static FFN_SCRATCH: std::cell::RefCell<[Vec<f32>; 4]> =
25624        const { std::cell::RefCell::new([Vec::new(), Vec::new(), Vec::new(), Vec::new()]) };
25625}
25626
25627/// Dense SwiGLU FFN through QTensor matvecs (any storage).
25628pub(crate) fn dense_ffn(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
25629    // Per-token sparsity, when the file was built for it: gate first,
25630    // then only the chosen neurons' up/down rows leave the mmap.
25631    if gate_topk() > 0
25632        && let Some(out) = dense_ffn_dynamic(d, x, pool, gate_topk())
25633    {
25634        return out;
25635    }
25636    // Whole-FFN GPU submit (этап 4.2 increment): gate → silu·up → down
25637    // chained in ONE command buffer with the intermediate activations
25638    // resident on the device — 3 per-op polls become 1 per layer. The
25639    // moe_block backend already implements exactly this chain; a dense
25640    // FFN is one expert with weight 1. Runtime probe: the chain still
25641    // pays one submit+poll per layer — alternate it against the pure-CPU
25642    // FFN and keep whichever is faster on this machine.
25643    // q1 FFNs offload at any practical size: the q1 CPU kernel is
25644    // compute-bound, so the UMA threshold logic does not apply — the
25645    // probe measures and decides either way.
25646    // The fused GPU block has no descriptor-aware Prism path: it would either
25647    // consume an unrotated activation or decline after inspecting the mixed
25648    // q2tp/q4tp tensors.  Do not let that structural refusal enter the FFN
25649    // probe's CPU_ONLY scope; the ordinary body below dispatches each matrix
25650    // through QTensor::matvec, which owns the signed FWHT + affine q2tp route.
25651    let prism_body = d.gate_proj.has_prism_contract()
25652        || d.up_proj.has_prism_contract()
25653        || d.down_proj.has_prism_contract();
25654    if !prism_body
25655        && crate::gpu::enabled_here()
25656        && (d.gate_proj.rows() >= crate::gpu::min_rows() || d.gate_proj.is_q1())
25657    {
25658        let arm = if d.gate_proj.is_q1() && crate::gpu::q1_force() {
25659            crate::gpu::ProbeArm::Gpu
25660        } else {
25661            crate::gpu::probe_arm(crate::gpu::OpClass::Ffn)
25662        };
25663        match arm {
25664            crate::gpu::ProbeArm::Gpu => {
25665                let t0 = std::time::Instant::now();
25666                if let Some(out) = dense_ffn_gpu(d, x, pool) {
25667                    crate::gpu::probe_record(crate::gpu::OpClass::Ffn, true, t0.elapsed());
25668                    return out;
25669                }
25670                // Declined: no timing exists, so say so. Silence here is
25671                // what left `ffn` undecided for 9000 calls and cost a
25672                // failed device attempt on half of them.
25673                crate::gpu::probe_note_decline(crate::gpu::OpClass::Ffn);
25674            }
25675            crate::gpu::ProbeArm::CpuTimed => {
25676                let t0 = std::time::Instant::now();
25677                let out = crate::gpu::cpu_scope(|| dense_ffn_cpu(d, x, pool));
25678                crate::gpu::probe_record(crate::gpu::OpClass::Ffn, false, t0.elapsed());
25679                return out;
25680            }
25681            crate::gpu::ProbeArm::Cpu => {
25682                return crate::gpu::cpu_scope(|| dense_ffn_cpu(d, x, pool));
25683            }
25684        }
25685    }
25686    dense_ffn_cpu(d, x, pool)
25687}
25688
25689/// `g[i] = act.combine(g[i], u[i])`, spread over the pool from 8192
25690/// elements: elementwise, so the same bits as the serial loop. An exact
25691/// GELU is one `erf` an element — 1.3 M a layer for a 128-row chunk of
25692/// Spark-X2.6, 10 240 a decode step — and the main thread paid them alone
25693/// while the workers waited for the down projection.
25694fn combine_pooled(act: Act, g: &mut [f32], u: &[f32], pool: Option<&Pool>) {
25695    debug_assert_eq!(g.len(), u.len());
25696    match pool {
25697        Some(p) if g.len() >= 8192 => {
25698            let gp = crate::pool::SendMut::new(g.as_mut_ptr());
25699            p.run_rows(g.len(), &|start, end| {
25700                for i in start..end {
25701                    // SAFETY: each worker owns elements [start, end).
25702                    unsafe {
25703                        let v = gp.at(i);
25704                        *v = act.combine(*v, u[i]);
25705                    }
25706                }
25707            });
25708        }
25709        _ => {
25710            for (gv, &uv) in g.iter_mut().zip(u) {
25711                *gv = act.combine(*gv, uv);
25712            }
25713        }
25714    }
25715}
25716
25717/// The pure-CPU dense-FFN body (also the fallback of every GPU refusal).
25718fn dense_ffn_cpu(d: &DenseFfn, x: &[f32], pool: Option<&Pool>) -> Vec<f32> {
25719    let inter = d.gate_proj.rows();
25720    FFN_SCRATCH.with(|s| {
25721        let mut s = s.borrow_mut();
25722        let [g, u, ..] = &mut *s;
25723        g.resize(inter, 0.0);
25724        // Fused gate+up+silu: one dispatch, no separate silu pass.
25725        // Falls back to matvec_many + silu loop for unsupported dtypes.
25726        if gate_topk() > 0 {
25727            // Gate first, select, and only then pay for `up`: the
25728            // measurement arm computes both and zeroes the losers, which
25729            // is the same arithmetic.
25730            u.resize(inter, 0.0);
25731            QTensor::matvec_many([&d.gate_proj, &d.up_proj], x, [g, u], pool);
25732            for i in 0..inter {
25733                g[i] = Act::Silu.combine(g[i], 1.0);
25734            }
25735            keep_top_k(g, gate_topk());
25736            for i in 0..inter {
25737                g[i] *= u[i];
25738            }
25739        } else if d.act == Act::Silu && {
25740            let _prof = crate::cpuprof::time(crate::cpuprof::Slot::FfnGateUp);
25741            QTensor::matvec_silu_mul(&d.gate_proj, &d.up_proj, x, g, pool)
25742        } {
25743            // g now holds silu(gate)·up directly.
25744        } else if d.act.clamp_limit() > 0.0 && {
25745            let _prof = crate::cpuprof::time(crate::cpuprof::Slot::FfnGateUp);
25746            QTensor::matvec_silu_mul_limited(&d.gate_proj, &d.up_proj, x, g, d.act.clamp_limit(), pool)
25747        } {
25748            // g holds silu(min(gate, limit))·clamp(up).
25749        } else {
25750            u.resize(inter, 0.0);
25751            // Multi-matrix job: gate+up under one pool dispatch.
25752            let _prof = crate::cpuprof::time(crate::cpuprof::Slot::FfnGateUp);
25753            QTensor::matvec_many([&d.gate_proj, &d.up_proj], x, [g, u], pool);
25754            let _c = crate::cpuprof::time(crate::cpuprof::Slot::FfnCombine);
25755            combine_pooled(d.act, &mut g[..inter], &u[..inter], pool);
25756        }
25757        // DTG-MA bake probe (Patent 2): accumulate this layer's
25758        // per-neuron activation mass while a probe pass is active.
25759        // `CMF_FFN_PROBE_TOPK=k` switches the statistic from mass to a
25760        // HIT COUNT — how many tokens rank the neuron in their own top
25761        // k. Mass asks "how loud is this neuron overall", the count
25762        // asks "how often does this task actually need it", and the two
25763        // rank neurons differently whenever a few tokens are loud.
25764        FFN_PROBE.with(|pr| {
25765            if let Some(acc) = pr.borrow_mut().as_mut() {
25766                let li = crate::gpu::cur_layer();
25767                if li >= 0 {
25768                    if let Some(row) = acc.get_mut(li as usize) {
25769                        match probe_topk() {
25770                            0 if probe_sq() => {
25771                                for (a, &v) in row.iter_mut().zip(g.iter()) {
25772                                    *a += (v as f64) * (v as f64);
25773                                }
25774                            }
25775                            0 if probe_signed() => {
25776                                for (a, &v) in row.iter_mut().zip(g.iter()) {
25777                                    *a += v as f64;
25778                                }
25779                            }
25780                            0 => {
25781                                for (a, &v) in row.iter_mut().zip(g.iter()) {
25782                                    *a += (v as f64).abs();
25783                                }
25784                            }
25785                            k => {
25786                                let n = g.len();
25787                                let k = k.min(n);
25788                                let mut mag: Vec<f32> = g.iter().map(|v| v.abs()).collect();
25789                                let (_, kth, _) = mag.select_nth_unstable_by(k - 1, |a, b| {
25790                                    b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
25791                                });
25792                                let thr = *kth;
25793                                for (a, &v) in row.iter_mut().zip(g.iter()) {
25794                                    if v.abs() >= thr {
25795                                        *a += 1.0;
25796                                    }
25797                                }
25798                            }
25799                        }
25800                    }
25801                }
25802            }
25803        });
25804        MOE_PROBE.with(|pr| {
25805            if let Some(pr) = pr.borrow_mut().as_mut()
25806                && let Some((e, w)) = pr.cur
25807            {
25808                let li = crate::gpu::cur_layer();
25809                if li >= 0
25810                    && let Some(row) = pr.acc.get_mut(li as usize)
25811                    && let Some(cell) = row.get_mut(e * pr.inter..(e + 1) * pr.inter)
25812                {
25813                    for (a, &v) in cell.iter_mut().zip(g.iter()) {
25814                        let s = (w * v) as f64;
25815                        *a += s * s;
25816                    }
25817                }
25818            }
25819        });
25820        if oracle_topk() > 0 {
25821            keep_top_k(g, oracle_topk());
25822        }
25823        {
25824            let li = crate::gpu::cur_layer();
25825            if li >= 0 {
25826                adump_row(li as usize, g);
25827            }
25828        }
25829        let mut out = attention::take_buf(d.down_proj.rows());
25830        let _prof = crate::cpuprof::time(crate::cpuprof::Slot::FfnDown);
25831        d.down_proj.matvec(g, &mut out, pool);
25832        out
25833    })
25834}
25835
25836/// Online accumulators for the AWNP refit of a narrowed FFN.
25837///
25838/// The refit needs `Gss = A_SᵀA_S` and `YA = YᵀA_S` per layer, where `A_S`
25839/// are the calibration activations of the KEPT neurons and `Y` the full
25840/// FFN output. Both are small enough to hold; the thing that is not is
25841/// the activations they are built from — a 27B layer would dump a
25842/// gigabyte per thousand tokens. So they are accumulated as the
25843/// calibration runs and written once at the end.
25844///
25845/// `CMF_FFN_REFIT=<dir>` holds `support.<L>.u32` (a u32 count then the
25846/// kept indices) for every layer to accumulate; `CMF_FFN_REFIT_FROM/TO`
25847/// bound the layer span so the accumulators fit in RAM.
25848pub struct RefitAcc {
25849    pub support: Vec<u32>,
25850    pub gss: Vec<f32>,
25851    pub ya: Vec<f32>,
25852    pub hidden: usize,
25853    pub tokens: u64,
25854    /// Activations staged transposed ([ns, t] and [hidden, t]) until the
25855    /// batch is worth a GEMM. The product costs `ns²` to move and add
25856    /// REGARDLESS of how many tokens went into it, so folding 16 chunks
25857    /// into one call cuts that cost 16× — it was 15 TB of traffic per
25858    /// calibration pass at one call per 256 tokens.
25859    pub buf_g: Vec<f32>,
25860    pub buf_o: Vec<f32>,
25861    pub buf_t: usize,
25862}
25863
25864/// The product buffer is SHARED across layers — one 473 MB allocation,
25865/// not one per layer (that was 30 GB of nothing on a 64-layer model).
25866/// It lives under the same lock as the accumulators.
25867type RefitState = (std::collections::HashMap<usize, RefitAcc>, Vec<f32>);
25868
25869static REFIT: std::sync::OnceLock<Option<(String, std::sync::Mutex<RefitState>)>> =
25870    std::sync::OnceLock::new();
25871
25872/// Is an FFN probe accumulator installed on this thread? The fused GPU
25873/// FFN must decline while one is, or the probe silently measures zero.
25874fn ffn_probe_active() -> bool {
25875    FFN_PROBE.with(|p| p.borrow().is_some())
25876}
25877
25878fn refit_dir() -> Option<&'static (String, std::sync::Mutex<RefitState>)> {
25879    REFIT
25880        .get_or_init(|| {
25881            std::env::var("CMF_FFN_REFIT").ok().map(|d| {
25882                (
25883                    d,
25884                    std::sync::Mutex::new((std::collections::HashMap::new(), Vec::new())),
25885                )
25886            })
25887        })
25888        .as_ref()
25889}
25890
25891/// Accumulate one prefill panel into the layer's refit statistics.
25892fn refit_accumulate(
25893    li: usize,
25894    g: &[f32],
25895    b: usize,
25896    inter: usize,
25897    out: &[f32],
25898    hidden: usize,
25899    pool: Option<&Pool>,
25900) {
25901    let Some((dir, map)) = refit_dir() else {
25902        return;
25903    };
25904    static SPAN: std::sync::OnceLock<(usize, usize)> = std::sync::OnceLock::new();
25905    let (from, to) = *SPAN.get_or_init(|| {
25906        let g = |k: &str, d: usize| {
25907            std::env::var(k)
25908                .ok()
25909                .and_then(|v| v.parse().ok())
25910                .unwrap_or(d)
25911        };
25912        (
25913            g("CMF_FFN_REFIT_FROM", 0),
25914            g("CMF_FFN_REFIT_TO", usize::MAX),
25915        )
25916    });
25917    if li < from || li > to {
25918        return;
25919    }
25920    let mut guard = map.lock().unwrap();
25921    let (map, shared) = &mut *guard;
25922    let acc = match map.entry(li) {
25923        std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
25924        std::collections::hash_map::Entry::Vacant(e) => {
25925            let path = format!("{dir}/support.{li}.u32");
25926            let Ok(bytes) = std::fs::read(&path) else {
25927                eprintln!("refit: no {path} — layer {li} skipped");
25928                return;
25929            };
25930            let n = u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize;
25931            let support: Vec<u32> = bytes[4..4 + n * 4]
25932                .chunks_exact(4)
25933                .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
25934                .collect();
25935            eprintln!(
25936                "refit: layer {li} support {n} ({:.0} MB of accumulator)",
25937                (n * n + hidden * n) as f64 * 4.0 / 1e6
25938            );
25939            e.insert(RefitAcc {
25940                gss: vec![0.0; n * n],
25941                ya: vec![0.0; hidden * n],
25942                buf_g: Vec::new(),
25943                buf_o: Vec::new(),
25944                buf_t: 0,
25945                support,
25946                hidden,
25947                tokens: 0,
25948            })
25949        }
25950    };
25951    let ns = acc.support.len();
25952    // Stage this chunk transposed; the GEMM fires once the batch is full.
25953    let cap = refit_batch();
25954    if acc.buf_g.is_empty() {
25955        acc.buf_g = vec![0.0; ns * cap];
25956        acc.buf_o = vec![0.0; hidden * cap];
25957    }
25958    let take = b.min(cap - acc.buf_t);
25959    for t in 0..take {
25960        let col = acc.buf_t + t;
25961        for (j, &n) in acc.support.iter().enumerate() {
25962            acc.buf_g[j * cap + col] = g[t * inter + n as usize];
25963        }
25964        for h in 0..hidden {
25965            acc.buf_o[h * cap + col] = out[t * hidden + h];
25966        }
25967    }
25968    acc.buf_t += take;
25969    acc.tokens += take as u64;
25970    if acc.buf_t < cap {
25971        return;
25972    }
25973    let bt = acc.buf_t;
25974    acc.buf_t = 0;
25975    // The GEMM WRITES its C (it zeroes the accumulators it uses), so the
25976    // chunk product lands in scratch and is added on — the one thing that
25977    // silently turns a Gram over 13 000 tokens into a Gram over 256.
25978    // Both products are `C[n, m] += X[n, b] · Yᵀ[b, m]` with X and Y
25979    // stored row-major [·, b] — exactly `gemm_nt_f32`'s shape, so the
25980    // card does them when it is up (this is the whole calibration's
25981    // cost: O(|S|²) per token, 2.9 PFLOP for a 27B pass). The tiled CPU
25982    // loop stays as the fallback. Neither accumulates, so the product
25983    // lands in scratch and is added on.
25984    let RefitAcc {
25985        gss,
25986        ya,
25987        buf_g,
25988        buf_o,
25989        ..
25990    } = acc;
25991    let need = (ns * ns).max(hidden * ns);
25992    if shared.len() < need {
25993        shared.resize(need, 0.0);
25994    }
25995    let scratch = &mut shared[..];
25996    let _ = bt;
25997    if crate::gpu::gemm_nt_f32_transient(buf_g, buf_g, &mut scratch[..ns * ns], ns, cap, ns) {
25998        add_into(gss, &scratch[..ns * ns], pool);
25999        if crate::gpu::gemm_nt_f32_transient(
26000            buf_o,
26001            buf_g,
26002            &mut scratch[..hidden * ns],
26003            hidden,
26004            cap,
26005            ns,
26006        ) {
26007            add_into(ya, &scratch[..hidden * ns], pool);
26008        } else {
26009            accum_outer_t(ya, hidden, ns, cap, buf_o, buf_g, pool);
26010        }
26011    } else {
26012        accum_outer_t(gss, ns, ns, cap, buf_g, buf_g, pool);
26013        accum_outer_t(ya, hidden, ns, cap, buf_o, buf_g, pool);
26014    }
26015    // No zeroing: the batch is always filled exactly (cap is a multiple
26016    // of the prefill chunk), and a memset of 178 MB a layer would cost
26017    // more than the GEMM.
26018}
26019
26020/// `CMF_FFN_REFIT_BATCH` — tokens staged before each GEMM (default 4096).
26021fn refit_batch() -> usize {
26022    static B: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
26023    *B.get_or_init(|| {
26024        std::env::var("CMF_FFN_REFIT_BATCH")
26025            .ok()
26026            .and_then(|v| v.parse().ok())
26027            .unwrap_or(4096)
26028    })
26029}
26030
26031/// `c[m, n] += Σ_t left[m, t]·right[n, t]` — both operands transposed,
26032/// the CPU fallback for the staged batch.
26033fn accum_outer_t(
26034    c: &mut [f32],
26035    m: usize,
26036    n: usize,
26037    b: usize,
26038    left: &[f32],
26039    right: &[f32],
26040    pool: Option<&Pool>,
26041) {
26042    let ptr = SendMut(c.as_mut_ptr());
26043    let body = |i: usize| {
26044        let ptr = &ptr;
26045        let row = unsafe { std::slice::from_raw_parts_mut(ptr.0.add(i * n), n) };
26046        for t in 0..b {
26047            let a = left[i * b + t];
26048            if a == 0.0 {
26049                continue;
26050            }
26051            for (j, o) in row.iter_mut().enumerate() {
26052                *o += a * right[j * b + t];
26053            }
26054        }
26055    };
26056    match pool {
26057        Some(p) if m > 1 => p.run_rows(m, &|s, e| {
26058            for i in s..e {
26059                body(i);
26060            }
26061        }),
26062        _ => {
26063            for i in 0..m {
26064                body(i);
26065            }
26066        }
26067    }
26068}
26069
26070/// `dst += src`, spread over the pool — at 118 M floats a layer this is
26071/// not a loop to leave on one core.
26072fn add_into(dst: &mut [f32], src: &[f32], pool: Option<&Pool>) {
26073    let n = dst.len().min(src.len());
26074    match pool {
26075        Some(p) if n >= 1 << 16 => {
26076            let ptr = SendMut(dst.as_mut_ptr());
26077            let f = |s: usize, e: usize| {
26078                let ptr = &ptr;
26079                for blk in s..e {
26080                    let (a, b) = (blk * 4096, ((blk + 1) * 4096).min(n));
26081                    for i in a..b {
26082                        unsafe { *ptr.0.add(i) += src[i] };
26083                    }
26084                }
26085            };
26086            p.run_rows(n.div_ceil(4096), &f);
26087        }
26088        _ => {
26089            for (d, v) in dst.iter_mut().zip(&src[..n]) {
26090                *d += *v;
26091            }
26092        }
26093    }
26094}
26095
26096/// `c[m, n] += Σ_t left[t, m]·right[t, n]`, with `left` stored [m, t] and
26097/// `right` [t, n]. Tiled over the rows of `c` so a tile stays in cache
26098/// while each token's `right` row streams past it once, and parallel
26099/// over tiles.
26100fn accum_outer(
26101    c: &mut [f32],
26102    m: usize,
26103    n: usize,
26104    b: usize,
26105    left: &[f32],
26106    right: &[f32],
26107    pool: Option<&Pool>,
26108) {
26109    const TILE: usize = 32;
26110    let tiles = m.div_ceil(TILE);
26111    let cp = SendMut(c.as_mut_ptr());
26112    let body = |ti: usize| {
26113        let cp = &cp;
26114        let i0 = ti * TILE;
26115        let i1 = (i0 + TILE).min(m);
26116        for t in 0..b {
26117            let r = &right[t * n..t * n + n];
26118            for i in i0..i1 {
26119                let a = left[i * b + t];
26120                if a == 0.0 {
26121                    continue;
26122                }
26123                // SAFETY: tiles partition c's rows; workers never overlap.
26124                let row = unsafe { std::slice::from_raw_parts_mut(cp.0.add(i * n), n) };
26125                for (o, v) in row.iter_mut().zip(r) {
26126                    *o += a * *v;
26127                }
26128            }
26129        }
26130    };
26131    match pool {
26132        Some(p) if tiles > 1 => p.run_rows(tiles, &|s, e| {
26133            for ti in s..e {
26134                body(ti);
26135            }
26136        }),
26137        _ => {
26138            for ti in 0..tiles {
26139                body(ti);
26140            }
26141        }
26142    }
26143}
26144
26145/// Write what the calibration accumulated: `gss.<L>.f32` and `ya.<L>.f32`.
26146pub fn refit_flush() -> usize {
26147    let Some((dir, map)) = refit_dir() else {
26148        return 0;
26149    };
26150    let guard = map.lock().unwrap();
26151    let mut n = 0;
26152    for (li, acc) in guard.0.iter() {
26153        // A silently truncated write here is a Gram that reshapes to
26154        // nothing an hour later — say it out loud instead.
26155        let w = |name: &str, v: &[f32]| {
26156            let path = format!("{dir}/{name}.{li}.f32");
26157            let bytes: Vec<u8> = v.iter().flat_map(|x| x.to_le_bytes()).collect();
26158            match std::fs::write(&path, &bytes) {
26159                Ok(()) => {}
26160                Err(e) => eprintln!(
26161                    "refit: FAILED to write {path} ({} MB): {e}",
26162                    bytes.len() / 1_000_000
26163                ),
26164            }
26165        };
26166        w("gss", &acc.gss);
26167        w("ya", &acc.ya);
26168        println!(
26169            "refit L{li}: {} support, {} tokens, hidden {}",
26170            acc.support.len(),
26171            acc.tokens,
26172            acc.hidden
26173        );
26174        n += 1;
26175    }
26176    n
26177}
26178
26179/// `CMF_FFN_ADUMP=<prefix>` — append every probed token's FFN activation
26180/// row to `<prefix>.<layer>.f16`. The co-activation record: which
26181/// neurons fire together, which is what a tube has to group if a token
26182/// is ever going to open one tube instead of sixteen.
26183fn adump_row(li: usize, g: &[f32]) {
26184    use std::io::Write as _;
26185    static FILES: std::sync::OnceLock<
26186        Option<(
26187            String,
26188            std::sync::Mutex<std::collections::HashMap<usize, std::fs::File>>,
26189        )>,
26190    > = std::sync::OnceLock::new();
26191    let Some((prefix, map)) = FILES
26192        .get_or_init(|| {
26193            std::env::var("CMF_FFN_ADUMP")
26194                .ok()
26195                .map(|p| (p, std::sync::Mutex::new(std::collections::HashMap::new())))
26196        })
26197        .as_ref()
26198    else {
26199        return;
26200    };
26201    // `CMF_FFN_ADUMP_FROM/_TO` narrow the dump to a layer span, so a big
26202    // calibration run fits on disk in a few passes instead of one.
26203    static SPAN: std::sync::OnceLock<(usize, usize)> = std::sync::OnceLock::new();
26204    let (from, to) = *SPAN.get_or_init(|| {
26205        let g = |k: &str, d: usize| {
26206            std::env::var(k)
26207                .ok()
26208                .and_then(|v| v.parse().ok())
26209                .unwrap_or(d)
26210        };
26211        (
26212            g("CMF_FFN_ADUMP_FROM", 0),
26213            g("CMF_FFN_ADUMP_TO", usize::MAX),
26214        )
26215    });
26216    if li < from || li > to {
26217        return;
26218    }
26219    let mut map = map.lock().unwrap();
26220    let f = map.entry(li).or_insert_with(|| {
26221        std::fs::File::create(format!("{prefix}.{li}.f16")).expect("adump file")
26222    });
26223    let mut bytes = Vec::with_capacity(g.len() * 2);
26224    for v in g {
26225        bytes.extend_from_slice(&cortiq_core::quant::f32_to_f16(*v).to_le_bytes());
26226    }
26227    let _ = f.write_all(&bytes);
26228}
26229
26230/// `CMF_FFN_ORACLE_TOPK` — keep only the k largest |silu(g)·u| of each
26231/// token and zero the rest. Not a serving mode: it is the CEILING of
26232/// contextual sparsity — what a per-token router would be chasing —
26233/// measured by cheating, since the selection reads the very activations
26234/// it would have to predict.
26235fn oracle_topk() -> usize {
26236    if exact_mtp_calibration_active() {
26237        return 0;
26238    }
26239    static K: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
26240    *K.get_or_init(|| {
26241        std::env::var("CMF_FFN_ORACLE_TOPK")
26242            .ok()
26243            .and_then(|v| v.parse().ok())
26244            .unwrap_or(0)
26245    })
26246}
26247
26248/// `CMF_FFN_GATE_TOPK` — the REALIZABLE cousin of the oracle: rank the
26249/// neurons by their gate alone (which the kernel has computed anyway
26250/// before it reads `up`), keep the k best, and drop the rest. Every
26251/// dropped neuron's `up` row and `down` column stay unread, so this is
26252/// the sparsity a serving path can actually take without a router.
26253fn gate_topk() -> usize {
26254    if exact_mtp_calibration_active() {
26255        return 0;
26256    }
26257    static K: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
26258    *K.get_or_init(|| {
26259        std::env::var("CMF_FFN_GATE_TOPK")
26260            .ok()
26261            .and_then(|v| v.parse().ok())
26262            .unwrap_or(0)
26263    })
26264}
26265
26266/// `CMF_FFN_GATE_BLOCK` — select in blocks of B neurons instead of one
26267/// by one. A scattered per-neuron choice cannot be read efficiently (a
26268/// row at a time, no prefetch runway); a block of 32 is a contiguous
26269/// 32-row slab of `up` and of the transposed `down`, which the ordinary
26270/// kernels stream. The question the measurement answers is what the
26271/// block costs in quality.
26272fn gate_block() -> usize {
26273    static B: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
26274    *B.get_or_init(|| {
26275        std::env::var("CMF_FFN_GATE_BLOCK")
26276            .ok()
26277            .and_then(|v| v.parse().ok())
26278            .unwrap_or(1)
26279    })
26280}
26281
26282/// Zero all but the `k` largest BLOCKS (by summed square) of a row.
26283fn keep_top_blocks(g: &mut [f32], keep_n: usize, block: usize) {
26284    let n = g.len();
26285    let nb = n.div_ceil(block);
26286    let kb = (keep_n.div_ceil(block)).clamp(1, nb);
26287    if kb >= nb {
26288        return;
26289    }
26290    let mut score: Vec<f32> = (0..nb)
26291        .map(|b| {
26292            g[b * block..((b + 1) * block).min(n)]
26293                .iter()
26294                .map(|v| v * v)
26295                .sum::<f32>()
26296        })
26297        .collect();
26298    let mut ord = score.clone();
26299    let (_, kth, _) = ord.select_nth_unstable_by(kb - 1, |a, b| {
26300        b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
26301    });
26302    let thr = *kth;
26303    for b in 0..nb {
26304        if score[b] < thr {
26305            g[b * block..((b + 1) * block).min(n)].fill(0.0);
26306        }
26307    }
26308    score.clear();
26309}
26310
26311/// Zero all but the `k` largest magnitudes of one token's activation row.
26312fn keep_top_k(g: &mut [f32], k: usize) {
26313    if gate_block() > 1 {
26314        return keep_top_blocks(g, k, gate_block());
26315    }
26316    let n = g.len();
26317    if k == 0 || k >= n {
26318        return;
26319    }
26320    let mut mag: Vec<f32> = g.iter().map(|v| v.abs()).collect();
26321    let (_, kth, _) = mag.select_nth_unstable_by(k - 1, |a, b| {
26322        b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
26323    });
26324    let thr = *kth;
26325    for v in g.iter_mut() {
26326        if v.abs() < thr {
26327            *v = 0.0;
26328        }
26329    }
26330}
26331
26332/// `CMF_FFN_PROBE_SQ` — accumulate Σa², so the dump divided by the token
26333/// count and square-rooted is the RMS activation trace Patent 12 weights
26334/// its matrices by.
26335fn probe_sq() -> bool {
26336    static S: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
26337    *S.get_or_init(|| std::env::var("CMF_FFN_PROBE_SQ").is_ok())
26338}
26339
26340/// `CMF_FFN_PROBE_SIGNED` — accumulate the SIGNED activation sum
26341/// instead of its magnitude: what a dropped neuron contributes ON
26342/// AVERAGE, which is the bias a narrowed FFN can add back for free.
26343fn probe_signed() -> bool {
26344    static S: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
26345    *S.get_or_init(|| std::env::var("CMF_FFN_PROBE_SIGNED").is_ok())
26346}
26347
26348/// `CMF_FFN_MEANFILL=<file>` — a masked-out neuron contributes its MEAN
26349/// activation instead of zero (`u32 layers, u32 inter, f32[…]`, the mass
26350/// dump layout, holding per-neuron means). Dropping a neuron outright
26351/// also drops its average contribution, which shifts the layer output by
26352/// a constant; filling the mean back is one add per layer and costs no
26353/// bytes off the bus. This is the measurement arm — in a tube file the
26354/// same correction ships as a per-task bias vector.
26355fn meanfill() -> Option<&'static (usize, Vec<f32>)> {
26356    static M: std::sync::OnceLock<Option<(usize, Vec<f32>)>> = std::sync::OnceLock::new();
26357    M.get_or_init(|| {
26358        let p = std::env::var("CMF_FFN_MEANFILL").ok()?;
26359        let b = std::fs::read(&p).ok()?;
26360        let inter = u32::from_le_bytes(b[4..8].try_into().ok()?) as usize;
26361        let vals: Vec<f32> = b[8..]
26362            .chunks_exact(4)
26363            .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
26364            .collect();
26365        eprintln!("meanfill: {} value(s), inter {inter}", vals.len());
26366        Some((inter, vals))
26367    })
26368    .as_ref()
26369}
26370
26371/// `CMF_FFN_PROBE_TOPK` — 0 (default) = accumulate mass, k>0 = count
26372/// how often a neuron lands in a token's top k.
26373fn probe_topk() -> usize {
26374    static K: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
26375    *K.get_or_init(|| {
26376        std::env::var("CMF_FFN_PROBE_TOPK")
26377            .ok()
26378            .and_then(|v| v.parse().ok())
26379            .unwrap_or(0)
26380    })
26381}
26382
26383thread_local! {
26384    /// DTG-MA activation probe: per-layer per-neuron Σ|silu(g)·u|
26385    /// accumulator, alive only during `Pipeline::probe_ffn_mass`.
26386    static FFN_PROBE: std::cell::RefCell<Option<Vec<Vec<f64>>>> =
26387        const { std::cell::RefCell::new(None) };
26388}
26389
26390/// Hot-neuron probe of a MoE layer's routed experts (`cortiq hot-probe --experts`):
26391/// per layer, per expert and neuron, Σ (w·act)² over the tokens the router sent
26392/// there, `w` the expert's final weight — what the neuron's down column sees.
26393pub(crate) struct MoeProbe {
26394    /// `[layer][expert · inter + neuron]`; a layer without experts keeps an empty row.
26395    acc: Vec<Vec<f64>>,
26396    inter: usize,
26397    /// The routed expert `dense_ffn` is running for, and its weight; `None`
26398    /// outside the routed loop (the shared expert is not probed).
26399    cur: Option<(usize, f32)>,
26400}
26401
26402thread_local! {
26403    /// Alive only during `Pipeline::probe_moe_mass`.
26404    static MOE_PROBE: std::cell::RefCell<Option<MoeProbe>> = const { std::cell::RefCell::new(None) };
26405}
26406
26407fn moe_probe_active() -> bool {
26408    MOE_PROBE.with(|p| p.borrow().is_some())
26409}
26410
26411/// Per-token structured sparsity, paid for in bytes.
26412///
26413/// The gate is the cheapest third of an FFN and it already says which
26414/// neurons matter: `silu(gate)` near zero means the neuron contributes
26415/// nothing whatever `up` says. So compute every gate, keep the `k`
26416/// loudest, and read ONLY those neurons' `up` rows and `down` rows —
26417/// the latter needs `down_proj` stored transposed, otherwise a neuron's
26418/// down weights are a strided column and "reading only those" costs a
26419/// full cache line each.
26420///
26421/// Returns `None` when the file has no transposed `down` (the caller
26422/// then runs the ordinary dense path).
26423fn dense_ffn_dynamic(d: &DenseFfn, x: &[f32], pool: Option<&Pool>, k: usize) -> Option<Vec<f32>> {
26424    // The scatter path reads individual rows/columns and cannot express the
26425    // per-matrix signed FWHT boundary.  Let the descriptor-aware dense path
26426    // handle Prism files rather than silently running an unrotated sparse
26427    // approximation.
26428    if d.gate_proj.has_prism_contract()
26429        || d.up_proj.has_prism_contract()
26430        || d.down_proj.has_prism_contract()
26431    {
26432        return None;
26433    }
26434    let dt = d.down_t.as_ref()?;
26435    let inter = d.gate_proj.rows();
26436    let hidden = dt.cols();
26437    if k == 0 || k >= inter || d.act != Act::Silu {
26438        return None;
26439    }
26440    DYN_SCRATCH.with(|sc| {
26441        let mut sc = sc.borrow_mut();
26442        let DynScratch {
26443            g,
26444            mag,
26445            live,
26446            parts,
26447        } = &mut *sc;
26448        g.resize(inter, 0.0);
26449        d.gate_proj.matvec(x, g, pool);
26450        for v in g.iter_mut() {
26451            *v = inference::silu(*v);
26452        }
26453        // The k-th largest |silu(gate)| is the threshold; ties keep more,
26454        // which is the safe side.
26455        mag.clear();
26456        mag.extend(g.iter().map(|v| v.abs()));
26457        let (_, kth, _) = mag.select_nth_unstable_by(k - 1, |a, b| {
26458            b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal)
26459        });
26460        let thr = *kth;
26461        live.clear();
26462        live.extend((0..inter as u32).filter(|&n| g[n as usize].abs() >= thr));
26463        let mut out = vec![0.0f32; hidden];
26464        match pool {
26465            Some(p) if live.len() >= 64 => {
26466                let nw = p.n_workers() + 1;
26467                parts.clear();
26468                parts.resize(nw * hidden, 0.0);
26469                let ptr = SendMut(parts.as_mut_ptr());
26470                let n = live.len();
26471                let live_ref: &[u32] = live;
26472                let g_ref: &[f32] = g;
26473                p.run(&|w, workers| {
26474                    let chunk = n.div_ceil(workers);
26475                    let (s, e) = (w * chunk, ((w + 1) * chunk).min(n));
26476                    if s >= e {
26477                        return;
26478                    }
26479                    WORKER_SCRATCH.with(|ws| {
26480                        let mut ws = ws.borrow_mut();
26481                        let [scratch, acc] = &mut *ws;
26482                        scratch.resize(hidden.max(x.len()), 0.0);
26483                        acc.clear();
26484                        acc.resize(hidden, 0.0);
26485                        for (o, &nrm) in live_ref[s..e].iter().enumerate() {
26486                            // One neuron of runway: the next row's lines
26487                            // start moving while this one is multiplied.
26488                            if let Some(&nx) = live_ref[s..e].get(o + 1) {
26489                                d.up_proj.prefetch_row(nx as usize);
26490                                dt.prefetch_row(nx as usize);
26491                            }
26492                            let idx = nrm as usize;
26493                            let up = d.up_proj.row_dot(idx, x, scratch);
26494                            let a = g_ref[idx] * up;
26495                            if a != 0.0 {
26496                                dt.add_row_scaled(idx, a, acc, scratch);
26497                            }
26498                        }
26499                        for (j, v) in acc.iter().enumerate() {
26500                            unsafe { *ptr.at(w * hidden + j) = *v };
26501                        }
26502                    });
26503                });
26504                for w in 0..nw {
26505                    for (j, o) in out.iter_mut().enumerate() {
26506                        *o += parts[w * hidden + j];
26507                    }
26508                }
26509            }
26510            _ => {
26511                WORKER_SCRATCH.with(|ws| {
26512                    let mut ws = ws.borrow_mut();
26513                    let [scratch, _acc] = &mut *ws;
26514                    scratch.resize(hidden.max(x.len()), 0.0);
26515                    for &nrm in live.iter() {
26516                        let idx = nrm as usize;
26517                        let up = d.up_proj.row_dot(idx, x, scratch);
26518                        let a = g[idx] * up;
26519                        if a != 0.0 {
26520                            dt.add_row_scaled(idx, a, &mut out, scratch);
26521                        }
26522                    }
26523                });
26524            }
26525        }
26526        Some(out)
26527    })
26528}
26529
26530/// Caller-side scratch of the dynamic path — one allocation per thread,
26531/// not one per layer per token (that alone cost a third of the decode).
26532struct DynScratch {
26533    g: Vec<f32>,
26534    mag: Vec<f32>,
26535    live: Vec<u32>,
26536    parts: Vec<f32>,
26537}
26538
26539thread_local! {
26540    static DYN_SCRATCH: std::cell::RefCell<DynScratch> = const {
26541        std::cell::RefCell::new(DynScratch {
26542            g: Vec::new(),
26543            mag: Vec::new(),
26544            live: Vec::new(),
26545            parts: Vec::new(),
26546        })
26547    };
26548    /// Pool-worker scratch: the row buffer and this worker's partial sum.
26549    static WORKER_SCRATCH: std::cell::RefCell<[Vec<f32>; 2]> =
26550        const { std::cell::RefCell::new([Vec::new(), Vec::new()]) };
26551}
26552
26553/// `dense_ffn_cpu` with a per-visit mask landing on the activations —
26554/// the masked-inference fast path's decode arm. Full fused quant
26555/// compute, closed neurons zeroed before down: arithmetically the
26556/// pruned network, no dequant, no weight bytes touched.
26557fn dense_ffn_masked(d: &DenseFfn, x: &[f32], pool: Option<&Pool>, mask_row: &[u8]) -> Vec<f32> {
26558    let inter = d.gate_proj.rows();
26559    FFN_SCRATCH.with(|s| {
26560        let mut s = s.borrow_mut();
26561        let [g, u, ..] = &mut *s;
26562        g.resize(inter, 0.0);
26563        if d.act == Act::Silu && QTensor::matvec_silu_mul(&d.gate_proj, &d.up_proj, x, g, pool) {
26564            // g holds silu(gate)·up.
26565        } else {
26566            u.resize(inter, 0.0);
26567            QTensor::matvec_many([&d.gate_proj, &d.up_proj], x, [g, u], pool);
26568            for i in 0..inter {
26569                g[i] = d.act.combine(g[i], u[i]);
26570            }
26571        }
26572        zero_masked_cols(g, 1, inter, mask_row);
26573        let mut out = attention::take_buf(d.down_proj.rows());
26574        d.down_proj.matvec(g, &mut out, pool);
26575        out
26576    })
26577}
26578
26579/// Dense FFN as one GPU submission via the MoE block path (single
26580/// expert, weight 1.0): gate → silu·up → down chained in one command
26581/// buffer, intermediate activations device-resident. None → weights
26582/// not q8-mapped in the primary shard / over the VRAM budget / backend
26583/// refusal → honest CPU path.
26584fn dense_ffn_gpu(d: &DenseFfn, x: &[f32], _pool: Option<&Pool>) -> Option<Vec<f32>> {
26585    if d.gate_proj.has_prism_contract()
26586        || d.up_proj.has_prism_contract()
26587        || d.down_proj.has_prism_contract()
26588    {
26589        return None;
26590    }
26591    // The GPU block applies the standard graph activations plus the exact
26592    // MiniMax-M3 OAI contract; any other activation stays on the CPU.
26593    d.act.moe_job_graph_contract()?;
26594    // Threshold: tiny FFNs are not worth a submission (q1 excepted —
26595    // see the caller's gate).
26596    if d.gate_proj.rows() < crate::gpu::min_rows() && !d.gate_proj.is_q1() {
26597        return None;
26598    }
26599    let mut jobs: Vec<crate::gpu::MoeJob> = Vec::with_capacity(1);
26600    let mut model_ref = None;
26601    moe_push_job(d, x, 1.0, &mut jobs, &mut model_ref)?;
26602    let model = model_ref?;
26603    let hidden = jobs[0].down.1;
26604    let mut out = attention::take_buf(hidden);
26605    if crate::gpu::moe_block(&model, &jobs, &mut out) {
26606        Some(out)
26607    } else {
26608        let mut out = out;
26609        attention::recycle_buf(&mut out);
26610        None
26611    }
26612}
26613
26614/// q8-mapped primary-shard tensor parts for a GPU job: q8_2f carries
26615/// its column field, q8_row runs with empty col slices (the backend
26616/// skips the multiply). Shared by the MoE block and the dense-FFN
26617/// single-job path.
26618#[allow(clippy::type_complexity)]
26619#[allow(clippy::type_complexity)]
26620pub(crate) fn moe_parts(
26621    t: &QTensor,
26622) -> Option<(
26623    &std::sync::Arc<cortiq_core::CmfModel>,
26624    usize,
26625    usize,
26626    usize,
26627    &[f32],
26628    &[f32],
26629    bool,
26630    bool,
26631    bool,
26632)> {
26633    match t {
26634        QTensor::Mapped {
26635            model,
26636            idx,
26637            dtype: dt @ (cortiq_core::TensorDtype::Q8_2f | cortiq_core::TensorDtype::Q8Row),
26638            rows,
26639            cols,
26640            row_scale,
26641            col_field,
26642            ..
26643        } if (*dt == cortiq_core::TensorDtype::Q8Row) || !col_field.is_empty() => Some((
26644            model, *idx, *rows, *cols, row_scale, col_field, false, false, false,
26645        )),
26646        // q1: tile-embedded scales — empty rs/col slices, raw xs.
26647        QTensor::Mapped {
26648            model,
26649            idx,
26650            dtype: cortiq_core::TensorDtype::Q1,
26651            rows,
26652            cols,
26653            ..
26654        } => Some((
26655            model,
26656            *idx,
26657            *rows,
26658            *cols,
26659            &[][..],
26660            &[][..],
26661            true,
26662            false,
26663            false,
26664        )),
26665        // q4_tiled: 18-byte tiles with embedded f16 scales — raw xs.
26666        QTensor::Mapped {
26667            model,
26668            idx,
26669            dtype: cortiq_core::TensorDtype::Q4Tiled,
26670            rows,
26671            cols,
26672            ..
26673        } => Some((
26674            model,
26675            *idx,
26676            *rows,
26677            *cols,
26678            &[][..],
26679            &[][..],
26680            false,
26681            true,
26682            false,
26683        )),
26684        // q4tp: same raw-xs contract, different stride and scale plane.
26685        QTensor::Mapped {
26686            model,
26687            idx,
26688            dtype: cortiq_core::TensorDtype::Q4TiledP,
26689            rows,
26690            cols,
26691            ..
26692        } => Some((
26693            model,
26694            *idx,
26695            *rows,
26696            *cols,
26697            &[][..],
26698            &[][..],
26699            false,
26700            true,
26701            false,
26702        )),
26703        // q2tp: the 2-bit expert plane of the mixed profile — q4 family
26704        // for stride bookkeeping, flagged q2 so the trio validation can
26705        // demand a q4tp down.
26706        QTensor::Mapped {
26707            model,
26708            idx,
26709            dtype: cortiq_core::TensorDtype::Q2TiledP,
26710            rows,
26711            cols,
26712            ..
26713        } => Some((
26714            model,
26715            *idx,
26716            *rows,
26717            *cols,
26718            &[][..],
26719            &[][..],
26720            false,
26721            true,
26722            true,
26723        )),
26724        _ => None,
26725    }
26726}
26727
26728/// The routed experts of a MoE layer as the Metal chunk prefill takes
26729/// them: f32 router rows and every expert's q4tp (gate, up, down) tensor
26730/// indices, uniform SiLU shapes. Only the plain routed form — no shared
26731/// expert, no per-expert scale, no resonance or τ router, no router input
26732/// norm; the batched host walk keeps the rest. The routing itself stays the
26733/// host's (`moe_route`), so mask and selection bias need nothing here.
26734#[cfg(target_os = "macos")]
26735#[allow(clippy::type_complexity)]
26736fn chunk_moe_parts(
26737    m: &MoeFfn,
26738    hidden: usize,
26739) -> Option<(&[f32], Vec<(usize, usize, usize)>, bool)> {
26740    // Only a shared expert of its own width, without a gate: it adds to the
26741    // routed mix (`ChunkMoe::detached`).
26742    if m.shared.as_ref().is_some_and(|(s, g)| {
26743        g.is_some()
26744            || m.experts.is_empty()
26745            || s.gate_proj.rows() == m.experts[0].gate_proj.rows()
26746            || !(s.gate_proj.q8_2f_parts().is_some() || s.gate_proj.q4tp_parts().is_some())
26747            || !(s.up_proj.q8_2f_parts().is_some() || s.up_proj.q4tp_parts().is_some())
26748            || !(s.down_proj.q8_2f_parts().is_some() || s.down_proj.q4tp_parts().is_some())
26749    }) || m.per_expert_scale.is_some()
26750        || m.resonance.is_some()
26751        || m.route_tau.is_some()
26752        || m.router_input_norm
26753        || m.experts.is_empty()
26754        || m.top_k == 0
26755        || std::env::var("CMF_RMS_TRACE").is_ok()
26756        || std::env::var("CMF_ACT_DUMP").is_ok()
26757        || std::env::var("CMF_METAL_MOE_PREFILL").as_deref() == Ok("0")
26758    {
26759        return None;
26760    }
26761    let (rf, rr, rc) = m.router.f32_parts()?;
26762    if rr != m.experts.len() || rc != hidden {
26763        return None;
26764    }
26765    let inter = m.experts[0].gate_proj.rows();
26766    // All-q8_2f experts (Mellum2.1 q8_2f) ride the `moe_q8` GEMMs;
26767    // `CMF_METAL_MOE_Q8=0` keeps them on the host walk.
26768    let q8 = crate::gpu_metal::moe_q8::enabled() && m.experts[0].gate_proj.q8_2f_parts().is_some();
26769    let experts = m
26770        .experts
26771        .iter()
26772        .map(|e| {
26773            if e.act != Act::Silu
26774                || !e.segs.is_empty()
26775                || e.gate_proj.rows() != inter
26776                || e.up_proj.rows() != inter
26777                || e.down_proj.cols() != inter
26778                || e.gate_proj.cols() != hidden
26779                || e.down_proj.rows() != hidden
26780            {
26781                return None;
26782            }
26783            if q8 {
26784                let q8i = |t: &QTensor| t.q8_2f_parts().map(|p| p.0);
26785                return Some((q8i(&e.gate_proj)?, q8i(&e.up_proj)?, q8i(&e.down_proj)?));
26786            }
26787            Some((
26788                e.gate_proj.mapped_q4tp()?.1,
26789                e.up_proj.mapped_q4tp()?.1,
26790                e.down_proj.mapped_q4tp()?.1,
26791            ))
26792        })
26793        .collect::<Option<Vec<_>>>()?;
26794    Some((rf, experts, q8))
26795}
26796
26797/// Map a MoE onto the Metal token graph's contract: f32 router, a
26798/// shared expert (gated — Qwen — or ungated at weight 1 — DeepSeek-V3 /
26799/// HunYuan hy_v3), softmax or sigmoid scores with an optional selection
26800/// bias and routed scale, experts uniformly q4tp (or the mixed profile:
26801/// q2tp gate/up over a q4tp down). τ routers, masks, per-expert scales
26802/// and Gemma's router-input norm refuse here — those semantics stay on
26803/// the CPU path.
26804/// Map Flint's released ragged MoE into the native page graph.  This stays
26805/// separate from `metal_moe_graph_parts`: its six routed slots are Q2TP and
26806/// 512-wide, while its ungated shared SwiGLU is Q4TP and 1024-wide.  Feeding
26807/// the shared tuple into the uniform jobs descriptor would make the shader
26808/// use the routed stride on a different payload.
26809#[cfg(target_os = "macos")]
26810fn metal_flint_moe_graph_parts(
26811    m: &MoeFfn,
26812    hidden: usize,
26813    scratch_key: usize,
26814) -> Option<crate::gpu::GpuFlintMoe<'_>> {
26815    use std::sync::Arc;
26816
26817    const HIDDEN: usize = 2_048;
26818    const ROUTED_INTER: usize = 512;
26819    const SHARED_INTER: usize = 1_024;
26820    const EXPERTS: usize = 256;
26821    const TOP_K: usize = 6;
26822
26823    if hidden != HIDDEN || !strict_flint_metal_pager_candidate(m) {
26824        return None;
26825    }
26826    let routed0 = m.experts.first()?;
26827    let (model, _) = routed0.gate_proj.mapped_q2tp()?;
26828    let (router, router_rows, router_cols) = m.router.f32_parts()?;
26829    if router_rows != EXPERTS || router_cols != HIDDEN {
26830        return None;
26831    }
26832    if m.expert_bias.as_ref().is_some_and(|b| b.len() != EXPERTS) {
26833        return None;
26834    }
26835    let same_q2 = |t: &QTensor| -> Option<usize> {
26836        let (owner, idx) = t.mapped_q2tp()?;
26837        Arc::ptr_eq(&owner, &model).then_some(idx)
26838    };
26839    let same_q4 = |t: &QTensor| -> Option<usize> {
26840        let (owner, idx) = t.mapped_q4tp()?;
26841        Arc::ptr_eq(&owner, &model).then_some(idx)
26842    };
26843    let routed = |e: &DenseFfn| -> Option<(usize, usize, usize)> {
26844        if e.act != Act::Silu
26845            || !e.segs.is_empty()
26846            || e.gate_proj.rows() != ROUTED_INTER
26847            || e.gate_proj.cols() != HIDDEN
26848            || e.up_proj.rows() != ROUTED_INTER
26849            || e.up_proj.cols() != HIDDEN
26850            || e.down_proj.rows() != HIDDEN
26851            || e.down_proj.cols() != ROUTED_INTER
26852        {
26853            return None;
26854        }
26855        Some((
26856            same_q2(&e.gate_proj)?,
26857            same_q2(&e.up_proj)?,
26858            same_q4(&e.down_proj)?,
26859        ))
26860    };
26861    let shared = |e: &DenseFfn| -> Option<(usize, usize, usize)> {
26862        if e.act != Act::Silu
26863            || !e.segs.is_empty()
26864            || e.gate_proj.rows() != SHARED_INTER
26865            || e.gate_proj.cols() != HIDDEN
26866            || e.up_proj.rows() != SHARED_INTER
26867            || e.up_proj.cols() != HIDDEN
26868            || e.down_proj.rows() != HIDDEN
26869            || e.down_proj.cols() != SHARED_INTER
26870        {
26871            return None;
26872        }
26873        Some((
26874            same_q4(&e.gate_proj)?,
26875            same_q4(&e.up_proj)?,
26876            same_q4(&e.down_proj)?,
26877        ))
26878    };
26879    let experts = m.experts.iter().map(routed).collect::<Option<Vec<_>>>()?;
26880    if experts.len() != EXPERTS {
26881        return None;
26882    }
26883    let (shared_ffn, shared_gate) = m.shared.as_ref()?;
26884    if shared_gate.is_some() {
26885        return None;
26886    }
26887    Some(crate::gpu::GpuFlintMoe {
26888        router,
26889        bias: m.expert_bias.as_deref(),
26890        experts,
26891        scratch_key,
26892        shared: shared(shared_ffn)?,
26893        top_k: m.top_k,
26894        norm_topk: m.norm_topk_prob,
26895        route_scale: m.routed_scaling,
26896        sigmoid: m.router_sigmoid,
26897        sigmoid_denom_eps: m.sigmoid_denom_eps,
26898    })
26899}
26900
26901#[cfg(target_os = "macos")]
26902fn metal_moe_graph_parts(m: &MoeFfn, hidden: usize) -> Option<crate::gpu::GpuMoe<'_>> {
26903    if m.router_input_norm
26904        || m.route_tau.is_some()
26905        || m.mask.is_some()
26906        || m.per_expert_scale.is_some()
26907        || m.experts.is_empty()
26908        || m.top_k == 0
26909        || m.resonance.is_some()
26910    {
26911        return None;
26912    }
26913    // An ungated shared expert of its own width stays out of the jobs ladder:
26914    // it runs after the routed mix (`GpuMoe::detached`).
26915    let detached = m.shared.as_ref().filter(|(s, g)| {
26916        g.is_none() && !m.router_sigmoid && s.gate_proj.rows() != m.experts[0].gate_proj.rows()
26917    });
26918    // Without a shared expert the select kernel fills the k routed jobs
26919    // only (flag 32). Measured on Mellum2.1's softmax router; the sigmoid /
26920    // biased routers without one (LFM2-MoE) keep the CPU path until they
26921    // are measured too.
26922    let (sh, sg) = match &m.shared {
26923        Some((sh, sg)) if detached.is_none() => (Some(sh), sg.as_ref()),
26924        _ if !m.router_sigmoid && m.expert_bias.is_none() => (None, None),
26925        _ => return None,
26926    };
26927    let (rf, rr, rc) = m.router.f32_parts()?;
26928    if rr != m.experts.len() || rc != hidden {
26929        return None;
26930    }
26931    let shared_gated = sg.is_some();
26932    let sf = match sg {
26933        Some(sg) => {
26934            let (sf, sr, sc) = sg.f32_parts()?;
26935            if sr * sc != hidden {
26936                return None;
26937            }
26938            sf
26939        }
26940        // Ungated: the router's first row stands in for the gate matvec
26941        // (its logit is never read — the kernel pins weight 1).
26942        None => &rf[..hidden],
26943    };
26944    if let Some(b) = &m.expert_bias {
26945        if b.len() != m.experts.len() {
26946            return None;
26947        }
26948    }
26949    let inter = m.experts[0].gate_proj.rows();
26950    // The first expert's gate decides the profile; every trio (shared
26951    // included) must agree — the jobs ladder flips ONE kernel for all.
26952    let gu_q2 = m.experts[0].gate_proj.mapped_q2tp().is_some();
26953    // All-q8_2f routed experts (Mellum2.1 q8_2f: no shared expert, the
26954    // contract they were measured on) take the `moe_q8` kernels;
26955    // `CMF_METAL_MOE_Q8=0` keeps them off the graph (per-op path).
26956    let q8 = crate::gpu_metal::moe_q8::enabled()
26957        && (m.shared.is_none() || detached.is_some())
26958        && m.experts[0].gate_proj.q8_2f_parts().is_some();
26959    let trio = |e: &DenseFfn| -> Option<(usize, usize, usize)> {
26960        if e.act != Act::Silu
26961            || e.gate_proj.rows() != inter
26962            || e.gate_proj.cols() != hidden
26963            || e.up_proj.rows() != inter
26964            || e.up_proj.cols() != hidden
26965            || e.down_proj.rows() != hidden
26966            || e.down_proj.cols() != inter
26967        {
26968            return None;
26969        }
26970        if q8 {
26971            let q8i = |t: &QTensor| t.q8_2f_parts().map(|p| p.0);
26972            return Some((q8i(&e.gate_proj)?, q8i(&e.up_proj)?, q8i(&e.down_proj)?));
26973        }
26974        let pick = |t: &QTensor| -> Option<usize> {
26975            if gu_q2 {
26976                t.mapped_q2tp().map(|(_, i)| i)
26977            } else {
26978                t.mapped_q4tp().map(|(_, i)| i)
26979            }
26980        };
26981        Some((
26982            pick(&e.gate_proj)?,
26983            pick(&e.up_proj)?,
26984            e.down_proj.mapped_q4tp().map(|(_, i)| i)?,
26985        ))
26986    };
26987    let experts = m.experts.iter().map(trio).collect::<Option<Vec<_>>>()?;
26988    let shared = match sh {
26989        Some(sh) => Some(trio(sh)?),
26990        None => None,
26991    };
26992    let detached = match detached {
26993        Some((s, _)) => Some([
26994            s.gate_proj.metal_graph_parts()?,
26995            s.up_proj.metal_graph_parts()?,
26996            s.down_proj.metal_graph_parts()?,
26997        ]),
26998        None => None,
26999    };
27000    Some(crate::gpu::GpuMoe {
27001        router: rf,
27002        sgate: sf,
27003        experts,
27004        shared,
27005        n_exp: m.experts.len(),
27006        top_k: m.top_k,
27007        inter,
27008        norm_topk: m.norm_topk_prob,
27009        route_scale: m.routed_scaling,
27010        gu_q2,
27011        q8,
27012        sigmoid: m.router_sigmoid,
27013        sigmoid_denom_eps: m.sigmoid_denom_eps,
27014        bias: m.expert_bias.as_deref(),
27015        shared_gated,
27016        detached,
27017    })
27018}
27019
27020/// `CMF_FORCE_IDS=<file>` (diagnostics): decode step n commits the n-th
27021/// whitespace-separated token id of the file instead of sampling, while the
27022/// logits are still computed (and dumped by `CMF_LOGIT_DUMP_ALL`) — one
27023/// backend teacher-forced along another's greedy sequence, so top-1
27024/// agreement can be counted past a near-tie divergence.
27025fn forced_ids_at(step: usize) -> Option<u32> {
27026    static IDS: std::sync::OnceLock<Vec<u32>> = std::sync::OnceLock::new();
27027    IDS.get_or_init(|| {
27028        std::env::var("CMF_FORCE_IDS")
27029            .ok()
27030            .and_then(|p| std::fs::read_to_string(p).ok())
27031            .map(|s| {
27032                s.split_whitespace()
27033                    .filter_map(|t| t.parse().ok())
27034                    .collect()
27035            })
27036            .unwrap_or_default()
27037    })
27038    .get(step)
27039    .copied()
27040}
27041
27042/// Build one gate/up/down GPU job from three tensors. `moe_push_job` is the
27043/// DenseFfn-shaped caller; architectures that keep their experts in their own
27044/// structs (DeepSeek-V4) come here directly.
27045pub(crate) fn moe_push_job_parts<'a>(
27046    gate: &'a QTensor,
27047    up: &'a QTensor,
27048    down: &'a QTensor,
27049    x: &[f32],
27050    w: f32,
27051    swiglu_limit: f32,
27052    jobs: &mut Vec<crate::gpu::MoeJob<'a>>,
27053    model_ref: &mut Option<std::sync::Arc<cortiq_core::CmfModel>>,
27054) -> Option<()> {
27055    use crate::qtensor::prescale;
27056    let (gm, gi, gr, gc, grs, gcf, gq1, gq4, gq2) = moe_parts(gate)?;
27057    let (_, ui, ur, uc, urs, ucf, uq1, uq4, uq2) = moe_parts(up)?;
27058    let (_, di, dr, dc, drs, dcf, dq1, dq4, dq2) = moe_parts(down)?;
27059    if gq1 != uq1 || uq1 != dq1 || gq4 != uq4 || uq4 != dq4 || gq2 != uq2 {
27060        return None; // mixed-dtype trio — honest CPU path
27061    }
27062    // The 2-bit profile is gate/up q2tp over a PLAIN q4tp down; any other
27063    // 2-bit arrangement stays on the CPU.
27064    if gq2 && (dq2 || !dq4 || down.mapped_q4tp().is_none()) {
27065        return None;
27066    }
27067    if !gq2 && dq2 {
27068        return None;
27069    }
27070    model_ref.get_or_insert_with(|| gm.clone());
27071    let dt = |cf: &[f32]| {
27072        if cf.is_empty() {
27073            cortiq_core::TensorDtype::Q8Row
27074        } else {
27075            cortiq_core::TensorDtype::Q8_2f
27076        }
27077    };
27078    jobs.push(crate::gpu::MoeJob {
27079        gate: (gi, gr, gc, grs),
27080        up: (ui, ur, uc, urs),
27081        down: (di, dr, dc, drs),
27082        xs_gate: prescale(x, gcf, dt(gcf)).into_owned(),
27083        xs_up: prescale(x, ucf, dt(ucf)).into_owned(),
27084        down_col: dcf,
27085        w,
27086        q1: gq1,
27087        q4t: gq4 && !gq2 && gate.mapped_q4tp().is_none(),
27088        q4tp: gq4 && (gq2 || gate.mapped_q4tp().is_some()),
27089        gu_q2: gq2,
27090        swiglu_limit,
27091        act: 0,
27092    });
27093    Some(())
27094}
27095
27096/// Build one gate/up/down GPU job (see `moe_parts`).
27097fn moe_push_job<'a>(
27098    d: &'a DenseFfn,
27099    x: &[f32],
27100    w: f32,
27101    jobs: &mut Vec<crate::gpu::MoeJob<'a>>,
27102    model_ref: &mut Option<std::sync::Arc<cortiq_core::CmfModel>>,
27103) -> Option<()> {
27104    use crate::qtensor::prescale;
27105    // The block's act(gate)·up pass takes an exact device contract.  For
27106    // ordinary SiLU/GELU this is a zero clamp; MiniMax M3 contributes its
27107    // dedicated OAI marker and frozen 7.0 source limit.  Anything without a
27108    // device contract stays on the CPU.
27109    let (graph_act, swiglu_limit) = d.act.moe_job_graph_contract()?;
27110    let act = graph_act.code();
27111    let (gm, gi, gr, gc, grs, gcf, gq1, gq4, gq2) = moe_parts(&d.gate_proj)?;
27112    let (_, ui, ur, uc, urs, ucf, uq1, uq4, uq2) = moe_parts(&d.up_proj)?;
27113    let (_, di, dr, dc, drs, dcf, dq1, dq4, dq2) = moe_parts(&d.down_proj)?;
27114    if gq1 != uq1 || uq1 != dq1 || gq4 != uq4 || uq4 != dq4 || gq2 != uq2 {
27115        return None; // mixed-dtype trio — honest CPU path
27116    }
27117    if gq2 && (dq2 || !dq4 || d.down_proj.mapped_q4tp().is_none()) {
27118        return None;
27119    }
27120    if !gq2 && dq2 {
27121        return None;
27122    }
27123    model_ref.get_or_insert_with(|| gm.clone());
27124    let gdt = if gcf.is_empty() {
27125        cortiq_core::TensorDtype::Q8Row
27126    } else {
27127        cortiq_core::TensorDtype::Q8_2f
27128    };
27129    let udt = if ucf.is_empty() {
27130        cortiq_core::TensorDtype::Q8Row
27131    } else {
27132        cortiq_core::TensorDtype::Q8_2f
27133    };
27134    jobs.push(crate::gpu::MoeJob {
27135        gate: (gi, gr, gc, grs),
27136        up: (ui, ur, uc, urs),
27137        down: (di, dr, dc, drs),
27138        xs_gate: prescale(x, gcf, gdt).into_owned(),
27139        xs_up: prescale(x, ucf, udt).into_owned(),
27140        down_col: dcf,
27141        w,
27142        q1: gq1,
27143        q4t: gq4 && !gq2 && d.gate_proj.mapped_q4tp().is_none(),
27144        q4tp: gq4 && (gq2 || d.gate_proj.mapped_q4tp().is_some()),
27145        gu_q2: gq2,
27146        swiglu_limit,
27147        act,
27148    });
27149    Some(())
27150}
27151
27152/// Sparse dense-FFN directly on QUANTIZED weights (mask × mmap): reads
27153/// ONLY the active neurons' gate/up rows and down columns from the mmap
27154/// — no full-matrix dequant, no f32 model copy. This is what lets a
27155/// masked big model run at quantized RSS (the historical mask path
27156/// forced the whole model to f32). Semantics identical to the f32
27157/// sparse path within quant tolerance.
27158fn sparse_ffn_quant(
27159    d: &DenseFfn,
27160    x: &[f32],
27161    active: &[u16],
27162    hidden: usize,
27163    pool: Option<&Pool>,
27164) -> Vec<f32> {
27165    let n = active.len();
27166    let inter = d.gate_proj.rows();
27167    let mut act = vec![0.0f32; n];
27168    // Scratch is needed if EITHER projection is group-packed (q4/vbit);
27169    // gate/up normally share a dtype but sizing on both is robust.
27170    let need_scratch = !(d.gate_proj.sparse_col_ok() && d.up_proj.sparse_col_ok());
27171    let compute = |ai: usize| -> f32 {
27172        let idx = active[ai] as usize;
27173        if idx >= inter {
27174            return 0.0; // defensive parity with the f32 sparse path
27175        }
27176        let mut s = if need_scratch {
27177            vec![0.0f32; hidden]
27178        } else {
27179            Vec::new()
27180        };
27181        let gate = d.gate_proj.row_dot(idx, x, &mut s);
27182        let up = d.up_proj.row_dot(idx, x, &mut s);
27183        d.act.combine(gate, up)
27184    };
27185    match pool {
27186        Some(p) if n >= 256 => {
27187            let ptr = SendMut(act.as_mut_ptr());
27188            p.run(&|widx, nw| {
27189                let chunk = n.div_ceil(nw);
27190                let (s, e) = (widx * chunk, ((widx + 1) * chunk).min(n));
27191                for ai in s..e {
27192                    unsafe { *ptr.at(ai) = compute(ai) };
27193                }
27194            });
27195        }
27196        _ => {
27197            for (ai, a) in act.iter_mut().enumerate() {
27198                *a = compute(ai);
27199            }
27200        }
27201    }
27202    // Scatter through active down columns (reads only those columns).
27203    let mut out = vec![0.0f32; hidden];
27204    for (ai, &idx) in active.iter().enumerate() {
27205        let w = act[ai];
27206        if w.abs() >= 1e-12 && (idx as usize) < inter {
27207            d.down_proj.add_col_scaled(idx as usize, w, &mut out);
27208        }
27209    }
27210    out
27211}
27212
27213/// Test-only re-export of the private sparse-quant FFN (mask × mmap gate).
27214#[doc(hidden)]
27215pub fn sparse_ffn_quant_for_test(
27216    d: &DenseFfn,
27217    x: &[f32],
27218    active: &[u16],
27219    hidden: usize,
27220) -> Vec<f32> {
27221    sparse_ffn_quant(d, x, active, hidden, None)
27222}
27223
27224/// Dequantize a DenseFfn's three matrices to f32 (transient; only the
27225/// q4/vbit-masked fallback uses it — the memory-lean path is
27226/// sparse_ffn_quant). Reuses row_f32 row-by-row.
27227fn dequant_dense_f32(d: &DenseFfn) -> (Vec<f32>, Vec<f32>, Vec<f32>) {
27228    let deq = |t: &QTensor| -> Vec<f32> {
27229        let (rows, cols) = (t.rows(), t.cols());
27230        let mut out = vec![0.0f32; rows * cols];
27231        for r in 0..rows {
27232            t.row_f32(r, &mut out[r * cols..(r + 1) * cols]);
27233        }
27234        out
27235    };
27236    (deq(&d.gate_proj), deq(&d.up_proj), deq(&d.down_proj))
27237}
27238
27239/// Pointer wrapper for the worker-pool scatter (same pattern as qtensor).
27240struct SendMut(*mut f32);
27241unsafe impl Send for SendMut {}
27242unsafe impl Sync for SendMut {}
27243impl SendMut {
27244    #[inline]
27245    // Deliberate unsynchronized scatter: pool workers write disjoint indices
27246    // in parallel, so returning `&mut` from `&self` is intentional here.
27247    #[allow(clippy::mut_from_ref)]
27248    unsafe fn at(&self, i: usize) -> &mut f32 {
27249        unsafe { &mut *self.0.add(i) }
27250    }
27251}
27252
27253/// Router → (selected experts in torch.topk order, per-expert score
27254/// vector, normalizer). The final weight of expert `e` is `p[e] / wsum`.
27255///
27256/// Two regimes share this. Qwen: softmax over ALL experts, top-k of the
27257/// probabilities, optional renorm — `router_sigmoid=false`, no bias,
27258/// scale 1 → bit-identical to the historical path. LFM2-MoE /
27259/// DeepSeek-V3 `noaux_tc`: per-expert sigmoid scores, an optional
27260/// selection bias (top-k CHOICE only; weights stay unbiased), an
27261/// architecture-specified renorm floor and a routed scale.  The ordinary
27262/// loader contract is `1e-6`; Flint and MiniMax M3.1 preserve their
27263/// reference runtime's selected-score `sum + 1e-20`.
27264pub(crate) fn moe_route(
27265    logits: &[f32],
27266    m: &MoeFfn,
27267    allowed: Option<&[bool]>,
27268) -> (Vec<usize>, Vec<f32>, f32) {
27269    moe_route_with_eps(logits, m, allowed, m.sigmoid_denom_eps)
27270}
27271
27272/// Router implementation with an explicit sigmoid renormalization floor.
27273///
27274/// Flint and MiniMax M3.1 reference runtimes compute
27275/// `sum(selected_scores) + 1e-20` in FP32. Using the generic 1e-6 floor is
27276/// not a harmless tolerance difference when all logits are very negative: it
27277/// collapses the routed branch toward zero instead of normalizing the selected
27278/// experts. Keeping the epsilon parameter here avoids changing the established
27279/// Qwen/LFM2 contract while allowing each architecture to preserve its own
27280/// numerical semantics.
27281pub(crate) fn moe_route_with_eps(
27282    logits: &[f32],
27283    m: &MoeFfn,
27284    allowed: Option<&[bool]>,
27285    sigmoid_denom_eps: f32,
27286) -> (Vec<usize>, Vec<f32>, f32) {
27287    let ne = logits.len();
27288    // Expert restriction: the static env mask (CMF_MOE_MASK) AND the
27289    // active task mask's expert fields (spec §5) both narrow the
27290    // candidate set; selection happens over the admitted experts only.
27291    // With norm_topk the kept weights renormalize below; without it
27292    // the excluded mass is honestly dropped.
27293    let admit = |e: usize| {
27294        m.mask.as_ref().is_none_or(|mk| mk[e])
27295            && allowed.is_none_or(|a| a.get(e).copied().unwrap_or(false))
27296    };
27297    // The resonance router (spec §9.5.1) selects by the RAW score: the
27298    // trainer (`resonance_winner`) and the resident graph
27299    // (`embryo_core_route_pick`) take the first maximum of the scores
27300    // and run the winner with weight 1.0. Selecting through the softmax
27301    // instead is not the same decision: `exp(l − max)` rounds two scores
27302    // closer than 2^-25 (possible below |score| 0.25) to the same 1.0, and
27303    // the lower index would take a token whose score is strictly smaller
27304    // — the trainer's trace and the graph would disagree with this path.
27305    // `−∞` (outside the shell) never wins; with no finite admitted expert
27306    // the generic path below degrades to uniform. The winner's
27307    // probability is 1.0 by construction (a one-hot `p`), so its
27308    // renormalized weight is `routed_scaling` on both norm_topk settings.
27309    if m.resonance.is_some() && m.top_k == 1 {
27310        let mut best: Option<usize> = None;
27311        for e in (0..ne).filter(|&e| admit(e)) {
27312            let l = logits[e];
27313            if l == f32::NEG_INFINITY || l.is_nan() {
27314                continue;
27315            }
27316            if best.is_none_or(|b| l > logits[b]) {
27317                best = Some(e);
27318            }
27319        }
27320        if let Some(b) = best {
27321            let mut p = vec![0.0f32; ne];
27322            p[b] = 1.0;
27323            return (vec![b], p, 1.0 / m.routed_scaling);
27324        }
27325    }
27326    // A `−∞` logit (a grown expert outside its shell, `Resonance::scores`)
27327    // takes probability 0 on both paths: sigmoid(−∞) = 0, exp(−∞ − max) = 0
27328    // — top-1 is the best FINITE expert, its renormalized weight exactly
27329    // 1.0. Every expert at −∞ cannot happen (trunk experts have no shell);
27330    // should it, the softmax would be NaN, so it degrades to uniform.
27331    let p: Vec<f32> = if m.router_sigmoid {
27332        logits.iter().map(|&l| 1.0 / (1.0 + (-l).exp())).collect()
27333    } else {
27334        let mx = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
27335        if mx == f32::NEG_INFINITY {
27336            vec![1.0 / ne.max(1) as f32; ne]
27337        } else {
27338            let mut e: Vec<f32> = logits.iter().map(|&l| (l - mx).exp()).collect();
27339            let s: f32 = e.iter().sum();
27340            for v in &mut e {
27341                *v /= s;
27342            }
27343            e
27344        }
27345    };
27346    let mut idx: Vec<usize> = (0..ne).filter(|&e| admit(e)).collect();
27347    // Descending by selection score, lower index wins ties (torch.topk).
27348    match &m.expert_bias {
27349        Some(b) => idx.sort_unstable_by(|&x, &y| {
27350            (p[y] + b[y])
27351                .partial_cmp(&(p[x] + b[x]))
27352                .unwrap()
27353                .then(x.cmp(&y))
27354        }),
27355        None => idx.sort_unstable_by(|&x, &y| p[y].partial_cmp(&p[x]).unwrap().then(x.cmp(&y))),
27356    }
27357    idx.truncate(m.top_k);
27358    // Adaptive τ-routing: trim the tail experts once the kept mass is
27359    // enough. wsum below renormalizes over the KEPT set, so the output
27360    // stays a proper weighted average.
27361    if let Some(tau) = m.route_tau {
27362        let total: f32 = idx.iter().map(|&e| p[e]).sum();
27363        if total > 0.0 {
27364            let mut acc = 0.0f32;
27365            let mut keep = idx.len();
27366            for (i, &e) in idx.iter().enumerate() {
27367                acc += p[e];
27368                if acc >= tau * total {
27369                    keep = i + 1;
27370                    break;
27371                }
27372            }
27373            idx.truncate(keep);
27374        }
27375    }
27376    let wsum: f32 = if m.norm_topk_prob {
27377        let s: f32 = idx.iter().map(|&e| p[e]).sum();
27378        // Sigmoid routers use their architecture's reference floor; the
27379        // softmax path's probs already sum near 1, so it stays exactly as
27380        // before.
27381        (if m.router_sigmoid {
27382            s + sigmoid_denom_eps
27383        } else {
27384            s
27385        }) / m.routed_scaling
27386    } else {
27387        1.0 / m.routed_scaling
27388    };
27389    (idx, p, wsum)
27390}
27391
27392/// See the call site: one `layer:e1,e2,…` line per routed token.
27393fn moe_trace(idx: &[usize]) {
27394    moe_trace_at(crate::gpu::cur_layer() as i32, idx)
27395}
27396
27397/// The same, for callers that know their layer (DSV4 owns its layers and
27398/// never sets the pipeline's current-layer marker).
27399pub(crate) fn moe_trace_at(li: i32, idx: &[usize]) {
27400    use std::io::Write;
27401    static F: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
27402        std::sync::OnceLock::new();
27403    let Some(f) = F.get_or_init(|| {
27404        let p = std::env::var("CMF_MOE_TRACE").ok()?;
27405        Some(std::sync::Mutex::new(
27406            std::fs::OpenOptions::new()
27407                .create(true)
27408                .append(true)
27409                .open(p)
27410                .ok()?,
27411        ))
27412    }) else {
27413        return;
27414    };
27415    let ids: Vec<String> = idx.iter().map(|e| e.to_string()).collect();
27416    let _ = writeln!(f.lock().unwrap(), "{li}:{}", ids.join(","));
27417}
27418
27419/// MoE FFN: router → top-k experts (see `moe_route`). Only selected
27420/// experts' pages are touched in mmap.
27421pub(crate) fn moe_ffn(
27422    m: &MoeFfn,
27423    x: &[f32],
27424    pool: Option<&Pool>,
27425    allowed: Option<&[bool]>,
27426) -> Vec<f32> {
27427    let r = moe_ffn_route(m, x, pool, allowed);
27428    moe_ffn_experts(m, x, &r, pool)
27429}
27430
27431/// One token's host route through a MoE layer: the chosen experts in
27432/// selection order, the per-expert scores and the normalizer (see
27433/// `moe_route`), plus the raw router logits.
27434pub(crate) struct MoeRoute {
27435    pub idx: Vec<usize>,
27436    pub p: Vec<f32>,
27437    pub wsum: f32,
27438    pub logits: Vec<f32>,
27439}
27440
27441/// The routing half of `moe_ffn`, shared by every executor of the chosen
27442/// experts (the host/per-op path below and the MiMo dynamic device cache,
27443/// `crate::mimo_moe`): activation accounting, router logits, `moe_route`,
27444/// the selection statistics and the `CMF_MOE_TRACE` line — so switching
27445/// executors can never change which experts a token gets.
27446pub(crate) fn moe_ffn_route(
27447    m: &MoeFfn,
27448    x: &[f32],
27449    pool: Option<&Pool>,
27450    allowed: Option<&[bool]>,
27451) -> MoeRoute {
27452    accumulate_act(m, x, 1);
27453    let ne = m.experts.len();
27454    let mut logits = vec![0.0f32; ne];
27455    match &m.resonance {
27456        Some(r) => r.scores(x, &mut logits),
27457        None => m.router.matvec(x, &mut logits, pool),
27458    }
27459    let (idx, p, wsum) = moe_route(&logits, m, allowed);
27460    {
27461        let mut st = m.stats.borrow_mut();
27462        if st.len() < ne {
27463            st.resize(ne, 0);
27464        }
27465        for &e in &idx {
27466            st[e] += 1;
27467        }
27468    }
27469    // `CMF_MOE_TRACE=<file>`: append one line per (layer, token) with the
27470    // selected expert ids. The cumulative `stats` above answer "which
27471    // experts are popular"; a residency design needs the question they
27472    // cannot answer — whether CONSECUTIVE tokens reuse experts (the
27473    // temporal locality an LRU cache lives on, FreeToken §4).
27474    moe_trace(&idx);
27475    MoeRoute {
27476        idx,
27477        p,
27478        wsum,
27479        logits,
27480    }
27481}
27482
27483/// Flint's released mixed MoE profile has a native-Metal selected-expert
27484/// pager with a different numerical contract from the generic CPU probe:
27485/// the pager keeps activations in f32, whereas the fast host arm normally
27486/// uses its A8W8 activation path.  Timing those two approximations against
27487/// one another can make the probe reject the exact pager even when it is the
27488/// faster exact-f32 implementation.  Keep this gate deliberately narrower
27489/// than the pager itself; the pager revalidates every selected tuple before
27490/// it binds a no-copy view and an honest refusal still takes the CPU path.
27491#[cfg(target_os = "macos")]
27492fn strict_flint_metal_pager_candidate(m: &MoeFfn) -> bool {
27493    const HIDDEN: usize = 2_048;
27494    const ROUTED_INTER: usize = 512;
27495    const SHARED_INTER: usize = 1_024;
27496    const EXPERTS: usize = 256;
27497    const TOP_K: usize = 6;
27498
27499    let Some(routed) = m.experts.first() else {
27500        return false;
27501    };
27502    let Some((model, _)) = routed.gate_proj.mapped_q2tp() else {
27503        return false;
27504    };
27505    let Some((shared, shared_gate)) = &m.shared else {
27506        return false;
27507    };
27508    if shared_gate.is_some()
27509        || model.header.arch.arch_name != "flint"
27510        || model.header.arch.prism_hadamard.is_some()
27511        || model.header.arch.hidden_size != HIDDEN
27512        || m.experts.len() != EXPERTS
27513        || m.top_k != TOP_K
27514        || !m.router_sigmoid
27515        || !m.norm_topk_prob
27516        || m.sigmoid_denom_eps.to_bits() != (1e-20f32).to_bits()
27517        || m.routed_scaling.to_bits() != 1.0f32.to_bits()
27518        || m.route_tau.is_some()
27519        || m.mask.is_some()
27520        || m.per_expert_scale.is_some()
27521        || m.router_input_norm
27522        || m.resonance.is_some()
27523        || !m.grown.is_empty()
27524    {
27525        return false;
27526    }
27527
27528    let routed_q2 = routed.act == Act::Silu
27529        && routed.segs.is_empty()
27530        && routed.gate_proj.rows() == ROUTED_INTER
27531        && routed.gate_proj.cols() == HIDDEN
27532        && routed.up_proj.rows() == ROUTED_INTER
27533        && routed.up_proj.cols() == HIDDEN
27534        && routed.down_proj.rows() == HIDDEN
27535        && routed.down_proj.cols() == ROUTED_INTER
27536        && routed.up_proj.mapped_q2tp().is_some()
27537        && routed.down_proj.mapped_q4tp().is_some();
27538    let shared_q4 = shared.act == Act::Silu
27539        && shared.segs.is_empty()
27540        && shared.gate_proj.rows() == SHARED_INTER
27541        && shared.gate_proj.cols() == HIDDEN
27542        && shared.up_proj.rows() == SHARED_INTER
27543        && shared.up_proj.cols() == HIDDEN
27544        && shared.down_proj.rows() == HIDDEN
27545        && shared.down_proj.cols() == SHARED_INTER
27546        && shared.gate_proj.mapped_q4tp().is_some()
27547        && shared.up_proj.mapped_q4tp().is_some()
27548        && shared.down_proj.mapped_q4tp().is_some();
27549    routed_q2 && shared_q4
27550}
27551
27552/// The expert half of `moe_ffn`: run a route's experts on the per-op GPU
27553/// block or the host.
27554pub(crate) fn moe_ffn_experts(
27555    m: &MoeFfn,
27556    x: &[f32],
27557    r: &MoeRoute,
27558    pool: Option<&Pool>,
27559) -> Vec<f32> {
27560    let (idx, p, wsum) = (&r.idx, &r.p, r.wsum);
27561    // D5: the whole layer MoE block in one GPU command buffer (experts — the
27562    // same mmap via a no-copy buffer; intermediate activations on the GPU).
27563    // MoE owns a separate probe class from dense FFN: its selected-span pager
27564    // has materially different residency and latency costs.
27565    if crate::gpu::enabled_here() {
27566        #[cfg(target_os = "macos")]
27567        if crate::gpu_metal::enabled() && strict_flint_metal_pager_candidate(m) {
27568            // Do not compare the pager's exact-f32 result with the CPU's
27569            // optional A8W8 activation approximation.  The strict pager is
27570            // the validated Flint path; if a directory/view/device check
27571            // declines, preserve the existing CPU fallback rather than
27572            // leaving the probe in a half-sampled state.
27573            return moe_ffn_gpu(m, x, &idx, &p, wsum, pool).unwrap_or_else(|| {
27574                crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool))
27575            });
27576        }
27577        match crate::gpu::probe_arm(crate::gpu::OpClass::Moe) {
27578            crate::gpu::ProbeArm::Gpu => {
27579                let t0 = std::time::Instant::now();
27580                if let Some(out) = moe_ffn_gpu(m, x, &idx, &p, wsum, pool) {
27581                    crate::gpu::probe_record(crate::gpu::OpClass::Moe, true, t0.elapsed());
27582                    return out;
27583                }
27584                crate::gpu::probe_note_decline(crate::gpu::OpClass::Moe);
27585            }
27586            crate::gpu::ProbeArm::CpuTimed => {
27587                let t0 = std::time::Instant::now();
27588                let out = crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool));
27589                crate::gpu::probe_record(crate::gpu::OpClass::Moe, false, t0.elapsed());
27590                return out;
27591            }
27592            crate::gpu::ProbeArm::Cpu => {
27593                return crate::gpu::cpu_scope(|| moe_ffn_cpu(m, x, &idx, &p, wsum, pool));
27594            }
27595        }
27596    }
27597    moe_ffn_cpu(m, x, &idx, &p, wsum, pool)
27598}
27599
27600/// One MiniCPM CPU-tail MoE through its opt-in dynamic bank, or through the
27601/// same-route host fallback.  The route is formed exactly once so statistics,
27602/// tracing, and model semantics remain owned by `moe_ffn_route`.
27603fn moe_ffn_minicpm_tail(
27604    slot: &mut crate::minicpm_tail::MiniCpmTail,
27605    li: usize,
27606    total_layers: usize,
27607    m: &MoeFfn,
27608    x: &[f32],
27609    pool: Option<&Pool>,
27610) -> Vec<f32> {
27611    let route = moe_ffn_route(m, x, pool, None);
27612    match slot.forward(li, m, x, &route, pool, total_layers) {
27613        Some(out) => out,
27614        // A cache refusal must be observationally identical to the generic
27615        // CPU-tail path. The surrounding host-tail scope already disables the
27616        // per-op arena, so do not introduce a float-activation policy change
27617        // merely because this explicit opt-in cache declined a model/layout.
27618        None => moe_ffn_experts(m, x, &route, pool),
27619    }
27620}
27621
27622/// One MoE token through the MiMo expert bank (`crate::mimo_moe`), or —
27623/// when the bank does not serve it — through the host path with the SAME
27624/// route, so the routing statistics and `CMF_MOE_TRACE` see it once.
27625fn moe_ffn_banked(
27626    slot: &mut crate::mimo_moe::Slot,
27627    li: usize,
27628    m: &MoeFfn,
27629    x: &[f32],
27630    pool: Option<&Pool>,
27631) -> Vec<f32> {
27632    let t0 = std::time::Instant::now();
27633    let r = moe_ffn_route(m, x, pool, None);
27634    slot.note_route(t0.elapsed().as_nanos() as u64);
27635    match slot.forward(li, m, x, &r, pool) {
27636        Some(out) => out,
27637        None => crate::qtensor::float_activations_scope(|| {
27638            crate::gpu::cpu_scope(|| moe_ffn_experts(m, x, &r, pool))
27639        }),
27640    }
27641}
27642
27643/// Verify rows share a bank frame; routing and fallback are decode's.
27644fn moe_ffn_banked_rows(
27645    slot: &mut crate::mimo_moe::Slot,
27646    li: usize,
27647    m: &MoeFfn,
27648    xs: &[f32],
27649    b: usize,
27650    hidden: usize,
27651    pool: Option<&Pool>,
27652) -> Vec<f32> {
27653    let t0 = std::time::Instant::now();
27654    let routes: Vec<_> = xs
27655        .chunks_exact(hidden)
27656        .map(|x| moe_ffn_route(m, x, pool, None))
27657        .collect();
27658    slot.note_route(t0.elapsed().as_nanos() as u64);
27659    if let Some(out) = slot.forward_rows(li, m, xs, &routes, pool) {
27660        return out;
27661    }
27662    let mut out = Vec::with_capacity(b * hidden);
27663    for (x, r) in xs.chunks_exact(hidden).zip(&routes) {
27664        let row = slot.forward(li, m, x, r, pool).unwrap_or_else(|| {
27665            // A failed bank must not stream missing experts into the arena.
27666            crate::qtensor::float_activations_scope(|| {
27667                crate::gpu::cpu_scope(|| moe_ffn_experts(m, x, r, pool))
27668            })
27669        });
27670        out.extend(row);
27671    }
27672    out
27673}
27674
27675/// One-shot report of whether the whole-token wgpu graph actually formed.
27676/// A refusal silently reverts to the per-op path, which is how a model can
27677/// look "GPU-accelerated" while every layer walks the host.  A device prefix
27678/// is tracked separately because it still pays a host boundary for the tail.
27679fn graph_note(built: bool, layers_run: usize, total_layers: usize) {
27680    use std::sync::atomic::{AtomicBool, Ordering};
27681    if built {
27682        GRAPH_TOK_OK.fetch_add(1, Ordering::Relaxed);
27683        if total_layers > 0 && layers_run < total_layers {
27684            GRAPH_TOK_PREFIX.fetch_add(1, Ordering::Relaxed);
27685        } else {
27686            GRAPH_TOK_FULL.fetch_add(1, Ordering::Relaxed);
27687        }
27688    } else {
27689        GRAPH_TOK_MISS.fetch_add(1, Ordering::Relaxed);
27690    }
27691    static SAID: AtomicBool = AtomicBool::new(false);
27692    if !SAID.swap(true, Ordering::Relaxed) {
27693        if built {
27694            tracing::info!("wgpu whole-token graph: ACTIVE");
27695        } else {
27696            tracing::warn!("wgpu whole-token graph refused — per-op path");
27697        }
27698    }
27699}
27700
27701/// Whole-token graph outcomes, process-wide: a benchmark that claims a
27702/// GPU number while MISS climbs is measuring the CPU — the honest-bench
27703/// contract makes that an error, not a footnote.
27704pub static GRAPH_TOK_OK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27705pub static GRAPH_TOK_MISS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27706/// Graph calls that returned a hidden after running only a leading device
27707/// prefix.  These are valid hybrid executions but must not be reported as a
27708/// full GPU graph in benchmark evidence.
27709pub static GRAPH_TOK_PREFIX: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27710/// Graph calls that covered the complete requested layer span.
27711pub static GRAPH_TOK_FULL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27712
27713/// Native Metal TokenGraph completion counters. These are incremented only
27714/// after checked command-buffer completion and successful readback, so a
27715/// fused-head NLL report can prove the route rather than infer it from env.
27716pub static METAL_GRAPH_TOK_OK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27717pub static METAL_GRAPH_HEAD_OK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27718pub static METAL_GRAPH_HEAD_MISS: std::sync::atomic::AtomicU64 =
27719    std::sync::atomic::AtomicU64::new(0);
27720pub static METAL_GRAPH_LAYERS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27721pub static METAL_GRAPH_ERRORS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27722/// Ordinary native-Metal rows-prefill admissions and completed rows.  These
27723/// counters are separate from TokenGraph token/head counts so a batch NLL
27724/// receipt cannot accidentally claim serial execution as batched.
27725pub static METAL_PREFILL_CHUNKS: std::sync::atomic::AtomicU64 =
27726    std::sync::atomic::AtomicU64::new(0);
27727pub static METAL_PREFILL_ROWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27728pub static METAL_PREFILL_HEAD_ROWS: std::sync::atomic::AtomicU64 =
27729    std::sync::atomic::AtomicU64::new(0);
27730pub static METAL_PREFILL_ERRORS: std::sync::atomic::AtomicU64 =
27731    std::sync::atomic::AtomicU64::new(0);
27732
27733/// `CMF_MOE_BATCH=0` restores the per-expert serial loop — the A/B lever
27734/// for the batched kernel, and how its bit-identity is checked.
27735fn moe_batch_enabled() -> bool {
27736    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
27737    *ON.get_or_init(|| std::env::var("CMF_MOE_BATCH").as_deref() != Ok("0"))
27738}
27739
27740/// Two-dispatch CPU MoE: every routed expert (and the shared one) fused
27741/// into one gate/up/SiLU dispatch and one down dispatch, instead of two
27742/// pool barriers per expert. Bit-identical to the serial loop below —
27743/// see `moe_gate_up_many` / `moe_down_many`. `None` = the batched kernel
27744/// does not cover this layer, walk the serial path.
27745fn moe_ffn_cpu_batched(
27746    m: &MoeFfn,
27747    x: &[f32],
27748    idx: &[usize],
27749    p: &[f32],
27750    wsum: f32,
27751    pool: Option<&Pool>,
27752) -> Option<Vec<f32>> {
27753    if idx.is_empty() || !moe_batch_enabled() {
27754        return None;
27755    }
27756    // The bake probe reads per-neuron activation mass out of the
27757    // single-expert path; batching would skip it. Rare and offline —
27758    // hand those runs to the serial loop.
27759    if FFN_PROBE.with(|pr| pr.borrow().is_some()) || moe_probe_active() {
27760        return None;
27761    }
27762    let n = idx.len() + usize::from(m.shared.is_some());
27763    let mut pairs = Vec::with_capacity(n);
27764    let mut downs = Vec::with_capacity(n);
27765    let mut ws = Vec::with_capacity(n);
27766    for &e in idx {
27767        let d = &m.experts[e];
27768        if d.act != Act::Silu {
27769            return None;
27770        }
27771        pairs.push((&d.gate_proj, &d.up_proj));
27772        downs.push(&d.down_proj);
27773        ws.push(p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]));
27774    }
27775    // The shared expert goes last, matching the serial loop's order —
27776    // the f32 accumulation order is part of the bit-identity claim.
27777    if let Some((se, gate)) = &m.shared {
27778        if se.act != Act::Silu {
27779            return None;
27780        }
27781        let g = gate.as_ref().map_or(1.0, |gate| {
27782            let mut gl = [0.0f32; 1];
27783            gate.matvec(x, &mut gl, pool);
27784            1.0 / (1.0 + (-gl[0]).exp())
27785        });
27786        pairs.push((&se.gate_proj, &se.up_proj));
27787        downs.push(&se.down_proj);
27788        ws.push(g);
27789    }
27790    let inter = pairs[0].0.rows();
27791    let mut gs: Vec<Vec<f32>> = (0..pairs.len()).map(|_| vec![0f32; inter]).collect();
27792    if !QTensor::moe_gate_up_many(&pairs, x, &mut gs, pool) {
27793        return None;
27794    }
27795    let mut out = attention::take_buf(x.len());
27796    if !QTensor::moe_down_many(&downs, &gs, &ws, &mut out, pool) {
27797        attention::recycle_buf(&mut out);
27798        return None;
27799    }
27800    Some(out)
27801}
27802
27803/// Exact CPU completion for the routed experts a dynamic device cache did
27804/// not contain. The weights are already the router's final normalized mix.
27805/// Keeping this independent of `MoeFfn` makes the job `Sync`: its routing
27806/// statistics live in a `RefCell`, while the immutable expert tensors can be
27807/// evaluated safely in parallel with the GPU's resident subset.
27808/// Pooled-tail stage timers, reported per token by the bench JSON
27809/// (`m3_span_ms_per_tok`, `m3_cold_ms_per_tok`, `m3_arm_ms_per_tok`).
27810pub static M3_SPAN_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27811pub static M3_COLD_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27812pub static M3_ARM_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27813pub static M3_COLD_N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27814pub static M3_COLD_DEV_N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
27815
27816pub(crate) fn moe_cold_experts_cpu(
27817    experts: &[(&DenseFfn, f32)],
27818    x: &[f32],
27819    pool: Option<&Pool>,
27820) -> Vec<f32> {
27821    moe_cold_experts_cpu_with(experts, x, pool, true)
27822}
27823
27824/// [`moe_cold_experts_cpu`] with the experts' tubes (`expert_tubes_add`) optional: the
27825/// Flash-Next device path computes every winner's tube on the card.
27826pub(crate) fn moe_cold_experts_cpu_with(
27827    experts: &[(&DenseFfn, f32)],
27828    x: &[f32],
27829    pool: Option<&Pool>,
27830    tubes: bool,
27831) -> Vec<f32> {
27832    let mut out = attention::take_buf(x.len());
27833    if experts.is_empty() {
27834        return out;
27835    }
27836    let pairs: Vec<_> = experts
27837        .iter()
27838        .map(|(e, _)| (&e.gate_proj, &e.up_proj))
27839        .collect();
27840    let downs: Vec<_> = experts.iter().map(|(e, _)| &e.down_proj).collect();
27841    let weights: Vec<_> = experts.iter().map(|(_, w)| *w).collect();
27842    let inter = experts[0].0.gate_proj.rows();
27843    let mut activations: Vec<Vec<f32>> = (0..experts.len()).map(|_| vec![0.0; inter]).collect();
27844    // The batched gate/up kernels implement PLAIN SiLU only (their legacy
27845    // helper passes limit 0 and no activation code). MiniMax's SwiGLU-OAI
27846    // (alpha 1.702, shifted up) must take the per-expert path that reads
27847    // each tensor's own activation — otherwise every cold expert computes
27848    // silu and the residual walks away from the reference (measured: the
27849    // pooled tail shipped cos 0.047 hidden while the resident path was
27850    // bit-close).
27851    let silu_only = experts
27852        .iter()
27853        .all(|(e, _)| matches!(e.act, crate::pipeline::Act::Silu));
27854    if silu_only
27855        && QTensor::moe_gate_up_many(&pairs, x, &mut activations, pool)
27856        && QTensor::moe_down_many(&downs, &activations, &weights, &mut out, pool)
27857    {
27858        if tubes {
27859            for &(expert, weight) in experts {
27860                expert_tubes_add(expert, x, weight, &mut out, pool);
27861            }
27862        }
27863        return out;
27864    }
27865    out.fill(0.0);
27866    for &(expert, weight) in experts {
27867        if tubes {
27868            expert_tubes_add(expert, x, weight, &mut out, pool);
27869        }
27870        let mut one = dense_ffn(expert, x, pool);
27871        for (o, v) in out.iter_mut().zip(&one) {
27872            *o += weight * v;
27873        }
27874        attention::recycle_buf(&mut one);
27875    }
27876    out
27877}
27878
27879/// Cold part of a short bank batch. Share each expert's weight stream
27880/// across its tokens, but reduce contributions in each token's route order.
27881/// On an unsupported CPU/layout, retain the single-token cold kernels.
27882pub(crate) fn moe_cold_experts_rows_cpu(
27883    jobs: &[Vec<(&DenseFfn, f32)>],
27884    xs: &[f32],
27885    hidden: usize,
27886    pool: Option<&Pool>,
27887) -> Vec<f32> {
27888    let mut out = vec![0.0; xs.len()];
27889    let mut experts: Vec<&DenseFfn> = Vec::new();
27890    let mut groups: Vec<Vec<usize>> = Vec::new();
27891    let mut terms = vec![Vec::new(); jobs.len()];
27892    for (r, row) in jobs.iter().enumerate() {
27893        for &(e, w) in row {
27894            let g = match experts.iter().position(|&d| std::ptr::eq(d, e)) {
27895                Some(g) => g,
27896                None => {
27897                    experts.push(e);
27898                    groups.push(Vec::new());
27899                    groups.len() - 1
27900                }
27901            };
27902            terms[r].push((g, groups[g].len(), w));
27903            groups[g].push(r);
27904        }
27905    }
27906    if experts.is_empty() {
27907        return out;
27908    }
27909    let pairs: Vec<_> = experts.iter().map(|e| (&e.gate_proj, &e.up_proj)).collect();
27910    let downs: Vec<_> = experts.iter().map(|e| &e.down_proj).collect();
27911    let lens: Vec<_> = groups.iter().map(Vec::len).collect();
27912    let count: usize = lens.iter().sum();
27913    let mut acts = vec![vec![0.0; experts[0].gate_proj.rows()]; count];
27914    let mut ds = vec![vec![0.0; hidden]; count];
27915    if QTensor::moe_gate_up_rows(&pairs, &groups, xs, &mut acts, pool)
27916        && QTensor::moe_down_rows(&downs, &lens, &acts, &mut ds, pool)
27917    {
27918        let mut offset = 0;
27919        let offsets: Vec<_> = lens
27920            .iter()
27921            .map(|&n| {
27922                let start = offset;
27923                offset += n;
27924                start
27925            })
27926            .collect();
27927        for (r, terms) in terms.iter().enumerate() {
27928            for &(g, slot, w) in terms {
27929                for (o, &v) in out[r * hidden..(r + 1) * hidden]
27930                    .iter_mut()
27931                    .zip(&ds[offsets[g] + slot])
27932                {
27933                    *o += w * v;
27934                }
27935            }
27936        }
27937    } else {
27938        for (r, jobs) in jobs.iter().enumerate() {
27939            if !jobs.is_empty() {
27940                let mut row = moe_cold_experts_cpu(jobs, &xs[r * hidden..(r + 1) * hidden], pool);
27941                out[r * hidden..(r + 1) * hidden].copy_from_slice(&row);
27942                attention::recycle_buf(&mut row);
27943            }
27944        }
27945    }
27946    out
27947}
27948
27949/// The pure-CPU MoE expert loop (also the fallback of every GPU refusal).
27950fn moe_ffn_cpu(
27951    m: &MoeFfn,
27952    x: &[f32],
27953    idx: &[usize],
27954    p: &[f32],
27955    wsum: f32,
27956    pool: Option<&Pool>,
27957) -> Vec<f32> {
27958    if let Some(mut out) = moe_ffn_cpu_batched(m, x, idx, p, wsum, pool) {
27959        for &e in idx {
27960            let w = p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]);
27961            expert_tubes_add(&m.experts[e], x, w, &mut out, pool);
27962        }
27963        shared_tubes_add(m, x, &mut out, pool);
27964        return out;
27965    }
27966    let mut out = attention::take_buf(x.len());
27967    for &e in idx {
27968        let w = p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]);
27969        MOE_PROBE.with(|pr| {
27970            if let Some(pr) = pr.borrow_mut().as_mut() {
27971                pr.cur = Some((e, w));
27972            }
27973        });
27974        let mut eo = dense_ffn(&m.experts[e], x, pool);
27975        MOE_PROBE.with(|pr| {
27976            if let Some(pr) = pr.borrow_mut().as_mut() {
27977                pr.cur = None;
27978            }
27979        });
27980        for i in 0..out.len() {
27981            out[i] += w * eo[i];
27982        }
27983        attention::recycle_buf(&mut eo);
27984        expert_tubes_add(&m.experts[e], x, w, &mut out, pool);
27985    }
27986    if let Some((se, gate)) = &m.shared {
27987        let mut so = dense_ffn(se, x, pool);
27988        let g = gate.as_ref().map_or(1.0, |gate| {
27989            let mut gl = [0.0f32; 1];
27990            gate.matvec(x, &mut gl, pool);
27991            1.0 / (1.0 + (-gl[0]).exp())
27992        });
27993        for i in 0..out.len() {
27994            out[i] += g * so[i];
27995        }
27996        attention::recycle_buf(&mut so);
27997        expert_tubes_add(se, x, g, &mut out, pool);
27998    }
27999    out
28000}
28001
28002/// DeepSeek-V2 MLA forward, expand-to-MHA form (see `AttnKind::Mla`):
28003/// per token the latent expands to every head's K/V and the ordinary
28004/// cache + grouped attend do the rest. K head layout is [rope | nope]
28005/// (rotary_dim = qk_rope rotates the shared rope key and each q head's
28006/// prefix); V rows are zero-padded to the K head_dim inside the cache
28007/// and the pad is sliced off before O. Attention importance is not
28008/// accumulated for MLA yet (no eviction interplay).
28009#[allow(clippy::too_many_arguments)]
28010pub(crate) fn mla_attention(
28011    w: &MlaWeights,
28012    normed: &[f32],
28013    cache: &mut crate::kv_cache::LayerKvCache,
28014    position: usize,
28015    inv_freq: &[f32],
28016    rope_scale: f32,
28017    eps: f64,
28018    pool: Option<&Pool>,
28019) -> Vec<f32> {
28020    let (nh, dr, dn, dv, lora) = (w.nh, w.qk_rope, w.qk_nope, w.v_dim, w.lora);
28021    let hd = dr + dn;
28022    let mut q = vec![0.0f32; nh * hd];
28023    match (&w.q_a, &w.q_a_norm) {
28024        (Some(qa), Some(qn)) => {
28025            let mut t = vec![0.0f32; qa.rows()];
28026            qa.matvec(normed, &mut t, pool);
28027            let tn = inference::rms_norm(&t, qn, eps, NormStyle::Qwen);
28028            w.q_proj.matvec(&tn, &mut q, pool);
28029        }
28030        _ => w.q_proj.matvec(normed, &mut q, pool),
28031    }
28032    let mut ca = vec![0.0f32; lora + dr];
28033    w.kv_a.matvec(normed, &mut ca, pool);
28034    let (c_lat, k_rope) = ca.split_at_mut(lora);
28035    let latn = inference::rms_norm(c_lat, &w.kv_a_norm, eps, NormStyle::Qwen);
28036    let mut kvb = vec![0.0f32; nh * (dn + dv)];
28037    w.kv_b.matvec(&latn, &mut kvb, pool);
28038    if !w.nope {
28039        attention::rope_rotate_scaled(k_rope, position, inv_freq, rope_scale);
28040    }
28041    for h in 0..nh {
28042        if !w.nope {
28043            attention::rope_rotate_scaled(
28044                &mut q[h * hd..h * hd + dr],
28045                position,
28046                inv_freq,
28047                rope_scale,
28048            );
28049        }
28050    }
28051    let mut k = vec![0.0f32; nh * hd];
28052    let mut v = vec![0.0f32; nh * hd];
28053    for h in 0..nh {
28054        k[h * hd..h * hd + dr].copy_from_slice(k_rope);
28055        k[h * hd + dr..(h + 1) * hd].copy_from_slice(&kvb[h * (dn + dv)..h * (dn + dv) + dn]);
28056        v[h * hd..h * hd + dv].copy_from_slice(&kvb[h * (dn + dv) + dn..(h + 1) * (dn + dv)]);
28057    }
28058    cache.append(&k, &v, &vec![true; nh]);
28059    let (ao, mut imp) = attention::attend_all_heads(&q, cache, nh, 1, hd, w.scale, None, 0.0);
28060    attention::recycle_buf(&mut imp);
28061    let mut ov = vec![0.0f32; nh * dv];
28062    for h in 0..nh {
28063        ov[h * dv..(h + 1) * dv].copy_from_slice(&ao[h * hd..h * hd + dv]);
28064    }
28065    let mut out = vec![0.0f32; w.o_proj.rows()];
28066    w.o_proj.matvec(&ov, &mut out, pool);
28067    out
28068}
28069
28070/// Gemma-4 dual-branch FFN (spec: see `FfnKind::DenseMoe`). The dense
28071/// branch reads the pre-FFN-normed activation; the router and the
28072/// expert branch read the RAW residual — the router through a
28073/// scale-less rms norm (its constant gain is folded into the weights),
28074/// the experts through `pre_norm_2`. CPU path; GPU graphs refuse the
28075/// layer kind honestly.
28076fn dense_moe_ffn(
28077    dm: &DenseMoeFfn,
28078    x_normed: &[f32],
28079    h_raw: &[f32],
28080    eps: f64,
28081    norm_style: NormStyle,
28082    pool: Option<&Pool>,
28083) -> Vec<f32> {
28084    let mut d = dense_ffn(&dm.dense, x_normed, pool);
28085    d = inference::rms_norm(&d, &dm.post_norm_1, eps, norm_style);
28086    let m = &dm.moe;
28087    let ne = m.experts.len();
28088    let mut logits = vec![0.0f32; ne];
28089    if m.router_input_norm {
28090        let ss: f32 = h_raw.iter().map(|v| v * v).sum::<f32>() / h_raw.len() as f32;
28091        let inv = 1.0 / (ss + eps as f32).sqrt();
28092        let xr: Vec<f32> = h_raw.iter().map(|v| v * inv).collect();
28093        m.router.matvec(&xr, &mut logits, pool);
28094    } else {
28095        m.router.matvec(h_raw, &mut logits, pool);
28096    }
28097    let (idx, p, wsum) = moe_route(&logits, m, None);
28098    {
28099        let mut st = m.stats.borrow_mut();
28100        if st.len() < ne {
28101            st.resize(ne, 0);
28102        }
28103        for &e in &idx {
28104            st[e] += 1;
28105        }
28106    }
28107    let x2 = inference::rms_norm(h_raw, &dm.pre_norm_2, eps, norm_style);
28108    let mo = moe_ffn_cpu(m, &x2, &idx, &p, wsum, pool);
28109    let mo = inference::rms_norm(&mo, &dm.post_norm_2, eps, norm_style);
28110    for (di, mi) in d.iter_mut().zip(&mo) {
28111        *di += mi;
28112    }
28113    d
28114}
28115
28116/// Building the MoE-layer GPU jobs: all selected experts (+shared) must
28117/// be q8_2f-Mapped from the primary mapping; otherwise None → CPU path.
28118/// One-shot report of why the MoE GPU block refused. A silent `?` here
28119/// sends every expert to the CPU with nothing in the logs to say so —
28120/// which is exactly how a q4tp MoE model looked "GPU-accelerated" while
28121/// running entirely on the host.
28122fn moe_gpu_refused(why: &'static str) {
28123    use std::sync::atomic::{AtomicBool, Ordering};
28124    static SAID: AtomicBool = AtomicBool::new(false);
28125    if !SAID.swap(true, Ordering::Relaxed) {
28126        tracing::warn!("MoE GPU block refused ({why}) — experts run on the CPU");
28127    }
28128}
28129
28130fn moe_ffn_gpu(
28131    m: &MoeFfn,
28132    x: &[f32],
28133    idx: &[usize],
28134    p: &[f32],
28135    wsum: f32,
28136    pool: Option<&Pool>,
28137) -> Option<Vec<f32>> {
28138    use crate::gpu::MoeJob;
28139
28140    let mut jobs: Vec<MoeJob> = Vec::with_capacity(idx.len() + 1);
28141    let mut model_ref = None;
28142    for &e in idx {
28143        if moe_push_job(&m.experts[e], x, p[e] / wsum, &mut jobs, &mut model_ref).is_none() {
28144            moe_gpu_refused("push_job(expert)");
28145            return None;
28146        }
28147    }
28148    if let Some((se, gate)) = &m.shared {
28149        let g = gate.as_ref().map_or(1.0, |gate| {
28150            let mut gl = [0.0f32; 1];
28151            gate.matvec(x, &mut gl, pool);
28152            1.0 / (1.0 + (-gl[0]).exp())
28153        });
28154        if moe_push_job(se, x, g, &mut jobs, &mut model_ref).is_none() {
28155            moe_gpu_refused("push_job(shared)");
28156            return None;
28157        }
28158    }
28159    let Some(model) = model_ref else {
28160        moe_gpu_refused("no model_ref");
28161        return None;
28162    };
28163    let hidden = jobs[0].down.1;
28164    let mut out = vec![0.0f32; hidden];
28165    if crate::gpu::moe_block(&model, &jobs, &mut out) {
28166        // The block knows no tubes (`hot-bake --experts`): the winners' and the
28167        // shared expert's come here, as the CPU paths add them.
28168        for &e in idx {
28169            expert_tubes_add(&m.experts[e], x, p[e] / wsum, &mut out, pool);
28170        }
28171        shared_tubes_add(m, x, &mut out, pool);
28172        Some(out)
28173    } else {
28174        moe_gpu_refused("gpu::moe_block");
28175        None
28176    }
28177}
28178
28179/// Single-position FFN dispatch.
28180fn ffn_forward(
28181    ffn: &FfnKind,
28182    x: &[f32],
28183    pool: Option<&Pool>,
28184    experts_allowed: Option<&[bool]>,
28185) -> Vec<f32> {
28186    match ffn {
28187        FfnKind::Dense(d) if !d.segs.is_empty() => tube_ffn(d, x, 1, pool, None),
28188        FfnKind::Dense(d) => dense_ffn(d, x, pool),
28189        FfnKind::Moe(m) => moe_ffn(m, x, pool, experts_allowed),
28190        // Dual-branch layers need the raw residual — their callers
28191        // dispatch dense_moe_ffn directly; the auxiliary paths that land
28192        // here (MTP draft, o1 replay) do not co-occur with gemma-4 MoE.
28193        FfnKind::DenseMoe(_) => unreachable!("DenseMoe dispatches via dense_moe_ffn"),
28194    }
28195}
28196
28197/// Fused two-position FFN: gate/up/down streamed once (dense). MoE
28198/// falls back to two singles — expert sets differ per position, there
28199/// is nothing to fuse.
28200fn ffn_forward_pair(
28201    ffn: &FfnKind,
28202    x1: &[f32],
28203    x2: &[f32],
28204    pool: Option<&Pool>,
28205    experts_allowed: Option<&[bool]>,
28206) -> (Vec<f32>, Vec<f32>) {
28207    let d = match ffn {
28208        // A tube layer has nothing to fuse across the pair — the tubes
28209        // are separate matrices; two singles are the honest path.
28210        FfnKind::Dense(d) if !d.segs.is_empty() => {
28211            return (
28212                tube_ffn(d, x1, 1, pool, None),
28213                tube_ffn(d, x2, 1, pool, None),
28214            );
28215        }
28216        FfnKind::Dense(d) => d,
28217        FfnKind::Moe(m) => {
28218            return (
28219                moe_ffn(m, x1, pool, experts_allowed),
28220                moe_ffn(m, x2, pool, experts_allowed),
28221            );
28222        }
28223        FfnKind::DenseMoe(_) => unreachable!("DenseMoe dispatches via dense_moe_ffn"),
28224    };
28225    let inter = d.gate_proj.rows();
28226    FFN_SCRATCH.with(|s| {
28227        let mut s = s.borrow_mut();
28228        let [g1, g2, u1, u2] = &mut *s;
28229        g1.resize(inter, 0.0);
28230        g2.resize(inter, 0.0);
28231        u1.resize(inter, 0.0);
28232        u2.resize(inter, 0.0);
28233        // Multi-matrix pair job: gate+up under one pool dispatch
28234        // (o1s = lane-1 outputs across tensors, o2s = lane-2).
28235        QTensor::matvec2_many(
28236            [&d.gate_proj, &d.up_proj],
28237            x1,
28238            x2,
28239            [g1.as_mut_slice(), u1.as_mut_slice()],
28240            [g2.as_mut_slice(), u2.as_mut_slice()],
28241            pool,
28242        );
28243        for i in 0..inter {
28244            g1[i] = d.act.combine(g1[i], u1[i]);
28245            g2[i] = d.act.combine(g2[i], u2[i]);
28246        }
28247        let mut o1 = attention::take_buf(d.down_proj.rows());
28248        let mut o2 = attention::take_buf(d.down_proj.rows());
28249        d.down_proj.matvec2(g1, g2, &mut o1, &mut o2, pool);
28250        (o1, o2)
28251    })
28252}
28253
28254/// Rows a far-field prompt chunk keeps at least when it is the last before
28255/// `stop`: a chunk of a few rows can go a backend's decode-sized path (the
28256/// CUDA hybrid arm's 16-row small path), which captures neither the seal's
28257/// queries nor the archive's K/V rows. Aion-2.3B, 26 626 rows: the whole-prompt
28258/// prefix in 1024-row chunks ended in 2 rows ("0 query values"), the sealed
28259/// 512-row chunks before the tail in 2 rows (an archive two rows short, exact
28260/// rows read from the wrong place, a garbled answer).
28261const O1_MIN_LAST_CHUNK: usize = 32;
28262
28263/// The end of a far-field prompt chunk from `pos`, at most `chunk` rows and not
28264/// past `stop`, that leaves the chunk after it at least [`O1_MIN_LAST_CHUNK`] rows.
28265fn o1_chunk_end(pos: usize, chunk: usize, stop: usize) -> usize {
28266    let end = (pos + chunk).min(stop);
28267    let rest = stop - end;
28268    if rest > 0 && rest < O1_MIN_LAST_CHUNK && stop - O1_MIN_LAST_CHUNK > pos + O1_MIN_LAST_CHUNK {
28269        stop - O1_MIN_LAST_CHUNK
28270    } else {
28271        end
28272    }
28273}
28274
28275#[cfg(test)]
28276mod tests {
28277
28278    #[test]
28279    fn o1_chunks_never_end_in_a_sliver() {
28280        // 26 626 rows in 1024-row chunks: the last but one stops 32 short
28281        let mut ends = Vec::new();
28282        let mut pos = 0;
28283        while pos < 26_626 {
28284            let e = super::o1_chunk_end(pos, 1024, 26_626);
28285            ends.push(e - pos);
28286            pos = e;
28287        }
28288        assert_eq!(pos, 26_626);
28289        assert!(ends.iter().all(|&b| b >= 32 && b <= 1024), "{ends:?}");
28290        assert_eq!(*ends.last().unwrap(), 32);
28291        // an exact multiple and a short span are left alone
28292        assert_eq!(super::o1_chunk_end(0, 512, 1024), 512);
28293        assert_eq!(super::o1_chunk_end(1000, 512, 1010), 1010);
28294        assert_eq!(super::o1_chunk_end(0, 512, 530), 498);
28295    }
28296    use std::ffi::OsString;
28297    use std::sync::Mutex;
28298
28299    // Environment switches are process-global. Keep the speculative-path
28300    // tests serialized and restore every prior value even during unwinding.
28301    static MTP_ENV_LOCK: Mutex<()> = Mutex::new(());
28302
28303    struct ScopedTestEnv {
28304        previous: Vec<(&'static str, Option<OsString>)>,
28305    }
28306
28307    impl ScopedTestEnv {
28308        fn set(vars: &[(&'static str, Option<&'static str>)]) -> Self {
28309            let previous = vars
28310                .iter()
28311                .map(|(name, _)| (*name, std::env::var_os(name)))
28312                .collect();
28313            for &(name, value) in vars {
28314                unsafe {
28315                    match value {
28316                        Some(value) => std::env::set_var(name, value),
28317                        None => std::env::remove_var(name),
28318                    }
28319                }
28320            }
28321            Self { previous }
28322        }
28323    }
28324
28325    impl Drop for ScopedTestEnv {
28326        fn drop(&mut self) {
28327            for (name, value) in self.previous.drain(..).rev() {
28328                unsafe {
28329                    match value {
28330                        Some(value) => std::env::set_var(name, value),
28331                        None => std::env::remove_var(name),
28332                    }
28333                }
28334            }
28335        }
28336    }
28337
28338    #[test]
28339    fn tail_repeat_counts_the_copied_stretch() {
28340        assert_eq!(tail_repeat(&[]), 0);
28341        assert_eq!(tail_repeat(&[5]), 0);
28342        assert_eq!(tail_repeat(&[1, 2, 3, 4]), 0);
28343        // the last three repeat the first three
28344        assert_eq!(tail_repeat(&[1, 2, 3, 9, 1, 2, 3]), 3);
28345        // the longest repeat wins over a later, shorter one
28346        assert_eq!(tail_repeat(&[1, 2, 3, 4, 8, 3, 4, 7, 1, 2, 3, 4]), 4);
28347        // a repeat reaching the start of the sequence
28348        assert_eq!(tail_repeat(&[1, 2, 1, 2]), 2);
28349        let long: Vec<u32> = (0..40).chain(0..40).collect();
28350        assert_eq!(tail_repeat(&long), 32);
28351    }
28352
28353    /// The chain's depth on wgpu follows the device's own round prices: a
28354    /// card whose verify climbs with its rows comes back from five drafts
28355    /// to three on the same acceptance that keeps a flat card at five.
28356    #[test]
28357    fn wgpu_spec_depth_follows_the_round_prices() {
28358        // RTX 2000 Ada, Qwen3.8-27B Turbo: rounds of 2..5 drafts, ms
28359        let steep = [0.0, 100.5, 111.3, 126.3, 144.6, 0.0, 0.0];
28360        let hold = [0.90, 0.85, 0.80, 0.60, 0.60, 0.60, 0.60];
28361        assert_eq!(wgpu_spec_depth(&hold, &steep, 5, 2, 5), Some(3));
28362        // the depth in turn stays while no other is 4 % better
28363        assert_eq!(wgpu_spec_depth(&hold, &steep, 4, 2, 5), Some(4));
28364        let flat = [0.0, 0.0, 60.0, 62.0, 64.0, 0.0, 0.0];
28365        assert_eq!(wgpu_spec_depth(&[0.9; 7], &flat, 3, 2, 5), Some(5));
28366        // an untimed depth is priced on the line through the two nearest
28367        let two = [0.0, 0.0, 111.3, 126.3, 0.0, 0.0, 0.0];
28368        assert_eq!(wgpu_spec_depth(&[0.5; 7], &two, 4, 2, 5), Some(2));
28369        // one timed depth says nothing of the slope
28370        assert_eq!(wgpu_spec_depth(&hold, &[0.0, 0.0, 111.3, 0.0, 0.0, 0.0, 0.0], 3, 2, 5), None);
28371    }
28372
28373    #[test]
28374    fn dflash_round_values_price_a_round_of_each_drafter() {
28375        // the block holds all seven of its drafts, the chain its first only
28376        let after: Vec<u32> = (10..30).collect();
28377        let seq: Vec<u32> = (100..140).collect();
28378        let block: Vec<u32> = (10..17).collect();
28379        let chain: Vec<u32> = vec![10, 99, 99, 99, 99, 99, 99];
28380        let starts: Vec<DflashStart<'_>> =
28381            (0..40).map(|_| DflashStart { seq: &seq, after: &after, block: &block, chain: &chain }).collect();
28382        let v = dflash_round_values(&starts);
28383        let (b, c) = v[39];
28384        // a block seven deep: eight tokens for a round of seven drafts and the block's own price
28385        assert_eq!(b, (8.0, METAL_ROUND_COST[6] + DFLASH_ROUND_DRAFT));
28386        // the chain has settled at one draft, which holds
28387        assert_eq!(c, (2.0, METAL_ROUND_COST[0]));
28388        assert!(b.0 / b.1 > c.0 / c.1);
28389    }
28390
28391    #[test]
28392    fn lookup_continues_a_repeated_stretch() {
28393        // 1 2 3 4 5 6 7 | 9 9 | 2 3 4 → the stretch 2 3 4 was followed by 5 6 7
28394        let seq = [1, 2, 3, 4, 5, 6, 7, 9, 9, 2, 3, 4];
28395        assert_eq!(lookup_continuation(&seq, 3, 3), &[5, 6, 7]);
28396        assert_eq!(lookup_continuation(&seq, 3, 2), &[5, 6]);
28397        // a repeat shorter than asked gives nothing
28398        assert!(lookup_continuation(&seq, 4, 3).is_empty());
28399        // the longest repeat wins over a later, shorter one
28400        let seq = [5, 2, 3, 4, 8, 0, 3, 4, 7, 0, 5, 2, 3, 4];
28401        assert_eq!(lookup_continuation(&seq, 2, 1), &[8]);
28402        // of equal ones the latest
28403        let seq = [2, 3, 4, 8, 0, 2, 3, 4, 7, 0, 2, 3, 4];
28404        assert_eq!(lookup_continuation(&seq, 2, 1), &[7]);
28405        // a period continues through the tail itself
28406        let seq = [1, 2, 1, 2, 1, 2];
28407        assert_eq!(lookup_continuation(&seq, 3, 4), &[1, 2]);
28408        assert!(lookup_continuation(&[1, 2, 3], 3, 2).is_empty());
28409        assert!(lookup_continuation(&[], 1, 2).is_empty());
28410    }
28411
28412    #[test]
28413    fn metal_spec_depth_follows_what_the_chain_holds() {
28414        // before any round: two drafts
28415        assert_eq!(metal_spec_depth(&SPEC_HOLD_PRIOR), 2);
28416        // a second draft that seldom holds is not worth its verify
28417        assert_eq!(metal_spec_depth(&[0.6, 0.15, 0.5, 0.5, 0.5, 0.5, 0.5]), 1);
28418        // predictable text fills the GEMM tile
28419        assert_eq!(metal_spec_depth(&[0.97; 7]), 7);
28420        // rounds of two drafts that both hold reach for a longer chain
28421        let mut h = SPEC_HOLD_PRIOR;
28422        let mut k = metal_spec_depth(&h);
28423        let mut rounds = 0;
28424        while k == 2 && rounds < 200 {
28425            spec_hold_update(&mut h, k, 2);
28426            k = metal_spec_depth(&h);
28427            rounds += 1;
28428        }
28429        assert!(k > 2 && rounds < 60, "depth {k} after {rounds} rounds");
28430        // ... and come back once the longer chain shows that a third never holds
28431        let mut back = 0;
28432        while k > 2 && back < 200 {
28433            spec_hold_update(&mut h, k, 2);
28434            k = metal_spec_depth(&h);
28435            back += 1;
28436        }
28437        assert!(k == 2 && back < 10, "depth {k} after {back} rounds");
28438        // most rounds of such text stay at two drafts
28439        let mut deep = 0;
28440        for _ in 0..400 {
28441            let k = metal_spec_depth(&h);
28442            deep += (k > 2) as usize;
28443            spec_hold_update(&mut h, k, 2);
28444        }
28445        assert!(deep < 40, "{deep} of 400 rounds went deeper");
28446        // a chain that holds one draft in two rounds of three, two in one of three: never deeper
28447        let mut h = SPEC_HOLD_PRIOR;
28448        for i in 0..300 {
28449            let k = metal_spec_depth(&h);
28450            assert!(k <= 2, "depth {k} at round {i}");
28451            spec_hold_update(&mut h, k, (i % 3).min(k));
28452        }
28453    }
28454
28455    #[test]
28456    fn mtp_draft_shortlist_masks_unevaluated_vocab_rows() {
28457        use super::pad_mtp_draft_logits;
28458
28459        let mut logits = vec![-3.0, -1.0, -2.0];
28460        pad_mtp_draft_logits(&mut logits, 6);
28461        assert_eq!(&logits[..3], &[-3.0, -1.0, -2.0]);
28462        assert!(logits[3..].iter().all(|&x| x == f32::NEG_INFINITY));
28463        assert_eq!(
28464            logits
28465                .iter()
28466                .enumerate()
28467                .max_by(|(_, a), (_, b)| a.total_cmp(b))
28468                .map(|(i, _)| i),
28469            Some(1),
28470            "an unevaluated row cannot win an all-negative shortlist"
28471        );
28472    }
28473
28474    #[test]
28475    fn speculative_trial_fast_exits_after_three_zero_acceptance_rounds() {
28476        use super::{Pipeline, SpecMon, SpecTrial};
28477
28478        let mut mon = SpecMon::default();
28479        let start = std::time::Instant::now();
28480        mon.round(1.0, 1);
28481        let first = Pipeline::spec_trial_round(
28482            SpecTrial::Spec {
28483                t0: start,
28484                gen0: 0,
28485                rounds: 0,
28486            },
28487            &mut mon,
28488            1,
28489        );
28490        assert!(matches!(first, SpecTrial::Spec { rounds: 1, .. }));
28491
28492        // Two empty rounds in a row happen to a good head: the trial goes on.
28493        mon.round(1.0, 1);
28494        let second = Pipeline::spec_trial_round(first, &mut mon, 2);
28495        assert!(
28496            matches!(second, SpecTrial::Spec { rounds: 2, .. }),
28497            "two empty rounds are not evidence enough to leave the drafts"
28498        );
28499        mon.round(1.0, 1);
28500        let third = Pipeline::spec_trial_round(second, &mut mon, 3);
28501        assert!(
28502            matches!(third, SpecTrial::Plain { gen0: 3, .. }),
28503            "three verifier-tip-only rounds must stop the losing MTP trial"
28504        );
28505        // A plain decision on three rounds is tried again soon.
28506        assert_eq!(mon.recheck_plain_at(3), 3 + super::SPEC_RECHECK_THIN);
28507
28508        // One successful draft resets the streak, so a viable head retains
28509        // the normal five-round measurement budget.
28510        let mut viable = SpecMon::default();
28511        viable.round(1.0, 1);
28512        viable.round(1.0, 2);
28513        let continued = Pipeline::spec_trial_round(
28514            SpecTrial::Spec {
28515                t0: start,
28516                gen0: 0,
28517                rounds: 1,
28518            },
28519            &mut viable,
28520            3,
28521        );
28522        assert!(matches!(continued, SpecTrial::Spec { rounds: 2, .. }));
28523    }
28524
28525    #[test]
28526    fn fresh_mtp_request_does_not_inherit_full_head_streak() {
28527        let mut p = spark_test_pipeline(None);
28528        let head_rows = 248_070;
28529        p.draft_full_streak = 7;
28530        assert_eq!(p.draft_head_rows(head_rows), head_rows);
28531
28532        p.reset_fresh_mtp_draft_state();
28533        assert_eq!(
28534            p.draft_head_rows(head_rows),
28535            super::Pipeline::draft_vocab_rows(head_rows),
28536            "a fresh request returns to its configured shortlist"
28537        );
28538
28539        // A high-id first token of the NEW request still restores the
28540        // full-head protection immediately.
28541        p.note_draft_id(u32::MAX);
28542        assert_eq!(p.draft_head_rows(head_rows), head_rows);
28543    }
28544
28545    #[test]
28546    fn native_metal_batch_spec_defaults_on_over_a_q4tp_trunk() {
28547        use super::graph_spec_wanted_by_policy;
28548
28549        // A default-eligible (q4tp trunk) native Metal model drafts unless
28550        // told not to; any value other than 0/1 means the default there.
28551        assert!(graph_spec_wanted_by_policy(None, true, false, false, true));
28552        assert!(graph_spec_wanted_by_policy(
28553            Some("anything-but-1"),
28554            true,
28555            false,
28556            false,
28557            true,
28558        ));
28559        // A trunk outside the default (not q4tp) stays plain until asked.
28560        assert!(!graph_spec_wanted_by_policy(None, false, false, false, true));
28561        assert!(!graph_spec_wanted_by_policy(
28562            Some("anything-but-1"),
28563            false,
28564            false,
28565            false,
28566            true,
28567        ));
28568        assert!(graph_spec_wanted_by_policy(
28569            Some("1"),
28570            false,
28571            true,
28572            false,
28573            true,
28574        ));
28575        assert!(!graph_spec_wanted_by_policy(
28576            Some("0"),
28577            true,
28578            false,
28579            false,
28580            true,
28581        ));
28582
28583        // Do not regress the established discrete/wgpu policy while closing
28584        // the native-Metal quality gate.
28585        assert!(graph_spec_wanted_by_policy(None, true, false, false, false));
28586        assert!(graph_spec_wanted_by_policy(
28587            Some("legacy-force"),
28588            false,
28589            true,
28590            true,
28591            false,
28592        ));
28593    }
28594
28595    #[test]
28596    fn encoder_hidden_states_are_normalized_and_reusable() {
28597        let mut p = super::create_test_pipeline(8, 12, 2, 1, 4, 2, 32);
28598        let ids = [1, 7, 11, 19];
28599
28600        let first = p.encode_hidden_states(&ids).expect("encoder forward");
28601        let second = p
28602            .encode_hidden_states(&ids)
28603            .expect("reusable encoder forward");
28604        assert_eq!(first.len(), ids.len() * 8);
28605        assert!(first.iter().all(|v| v.is_finite()));
28606        assert_eq!(
28607            first, second,
28608            "encoder forward must start from a fresh state"
28609        );
28610
28611        // An encoder call must not leave stale KV/GDN state behind for the
28612        // regular generative API sharing the same Pipeline implementation.
28613        assert!(p.forward_ids(&ids, None).is_ok());
28614    }
28615
28616    /// The 0.7.6 prefill-chunk rule: a plain dense stack wholly on a
28617    /// discrete card reads the prompt in wide chunks on x86; every other
28618    /// case keeps the width it had (the GDN-hybrid, MoE and DeepSeek paths
28619    /// were tuned on hardware not measured for this change).
28620    #[test]
28621    fn prefill_chunk_rule_widens_only_dense_on_discrete() {
28622        use super::{ChunkHost, ChunkStackFacts, DISCRETE_DENSE_PREFILL_CHUNK, prefill_chunk_rule};
28623        let dense_card = ChunkStackFacts {
28624            plain_dense: true,
28625            discrete: true,
28626            gpu_on: true,
28627            ..Default::default()
28628        };
28629        assert!(dense_card.dense_on_discrete());
28630        // The bug: a dense Llama on a Vulkan RTX 3090 got 48.
28631        assert_eq!(
28632            prefill_chunk_rule(None, ChunkHost::Other, dense_card.dense_on_discrete()),
28633            DISCRETE_DENSE_PREFILL_CHUNK
28634        );
28635        assert!(DISCRETE_DENSE_PREFILL_CHUNK > 48);
28636        for (label, facts) in [
28637            (
28638                "GDN hybrid / MoE / DeepSeek stack",
28639                ChunkStackFacts {
28640                    plain_dense: false,
28641                    ..dense_card
28642                },
28643            ),
28644            (
28645                "integrated GPU",
28646                ChunkStackFacts {
28647                    discrete: false,
28648                    ..dense_card
28649                },
28650            ),
28651            (
28652                "CPU only",
28653                ChunkStackFacts {
28654                    gpu_on: false,
28655                    discrete: false,
28656                    ..dense_card
28657                },
28658            ),
28659            (
28660                "capacity split",
28661                ChunkStackFacts {
28662                    capacity_split: true,
28663                    ..dense_card
28664                },
28665            ),
28666            (
28667                "multi-GPU plan",
28668                ChunkStackFacts {
28669                    multi_gpu: true,
28670                    ..dense_card
28671                },
28672            ),
28673            (
28674                "O(1) layers",
28675                ChunkStackFacts {
28676                    o1: true,
28677                    ..dense_card
28678                },
28679            ),
28680        ] {
28681            assert!(!facts.dense_on_discrete(), "{label}");
28682            assert_eq!(
28683                prefill_chunk_rule(None, ChunkHost::Other, facts.dense_on_discrete()),
28684                48,
28685                "{label} keeps the historical x86 chunk"
28686            );
28687        }
28688        // Other hosts are untouched whatever the model.
28689        for dense in [false, true] {
28690            assert_eq!(prefill_chunk_rule(None, ChunkHost::Macos, dense), 512);
28691            assert_eq!(prefill_chunk_rule(None, ChunkHost::Aarch64, dense), 256);
28692        }
28693        // CMF_PREFILL_CHUNK still wins everywhere (and is clamped to ≥ 1).
28694        for host in [ChunkHost::Macos, ChunkHost::Aarch64, ChunkHost::Other] {
28695            for dense in [false, true] {
28696                assert_eq!(prefill_chunk_rule(Some(48), host, dense), 48);
28697                assert_eq!(prefill_chunk_rule(Some(0), host, dense), 1);
28698            }
28699        }
28700    }
28701
28702    #[test]
28703    fn kv_reuse_plan_pulls_rows_decode_wrote_only_on_the_device() {
28704        use super::{ReuseLayer, ReusePlan, kv_reuse_plan};
28705        let full = |host_rows, device_rows| ReuseLayer {
28706            full: true,
28707            host_rows,
28708            device_rows,
28709            device_state: false,
28710        };
28711        // Turn 1: 300-token prompt prefilled on the host, 40 tokens decoded
28712        // by the wgpu graph into the device mirror only. Turn 2 reuses 339.
28713        assert_eq!(
28714            kv_reuse_plan(339, &[full(300, Some(339)), full(300, Some(339))]),
28715            ReusePlan::Pull(vec![(0, 300, 339), (1, 300, 339)])
28716        );
28717        // CPU / Metal: the host owner already holds every forwarded row.
28718        assert_eq!(kv_reuse_plan(339, &[full(339, None)]), ReusePlan::Ready);
28719        // A mirror past the prefix is fine for the host (it gets rewound).
28720        assert_eq!(
28721            kv_reuse_plan(339, &[full(339, Some(345))]),
28722            ReusePlan::Ready
28723        );
28724        // GPU prefix / CPU tail: only the device layers lag.
28725        assert_eq!(
28726            kv_reuse_plan(339, &[full(300, Some(339)), full(339, None)]),
28727            ReusePlan::Pull(vec![(0, 300, 339)])
28728        );
28729        // The device cannot supply the missing rows: never continue.
28730        assert_eq!(
28731            kv_reuse_plan(339, &[full(300, Some(320))]),
28732            ReusePlan::Fresh
28733        );
28734        assert_eq!(kv_reuse_plan(339, &[full(300, None)]), ReusePlan::Fresh);
28735        assert_eq!(kv_reuse_plan(339, &[full(350, None)]), ReusePlan::Fresh);
28736        // A recurrent state advanced on the device cannot be handed to a
28737        // host prefill (it is not rewindable and the host copy is stale).
28738        let conv = |device_state| ReuseLayer {
28739            full: false,
28740            host_rows: 0,
28741            device_rows: None,
28742            device_state,
28743        };
28744        assert_eq!(
28745            kv_reuse_plan(339, &[conv(true), full(300, Some(339))]),
28746            ReusePlan::Fresh
28747        );
28748        assert_eq!(
28749            kv_reuse_plan(339, &[conv(false), full(339, None)]),
28750            ReusePlan::Ready
28751        );
28752    }
28753
28754    #[test]
28755    fn nll_graph_policy_scopes_only_the_fused_head() {
28756        for (label, unmasked, prefer_graph, native_metal, want_graph, want_head) in [
28757            // A Vulkan/Wgpu hidden-only graph remains the quality route.
28758            ("vulkan graph", true, true, false, true, false),
28759            // Native Metal adds the strict fused graph-head contract.
28760            ("native Metal graph", true, true, true, true, true),
28761            // Masked NLL and the explicit non-graph fallback remain unchanged.
28762            ("masked", false, true, false, false, false),
28763            ("graph disabled", true, false, true, false, false),
28764        ] {
28765            let (graph_quality, graph_head_required) =
28766                super::nll_graph_policy(unmasked, prefer_graph, native_metal);
28767            assert_eq!(graph_quality, want_graph, "{label}: graph quality");
28768            assert_eq!(graph_head_required, want_head, "{label}: fused head");
28769        }
28770    }
28771
28772    #[test]
28773    fn mtp_prefill_pair_boundaries_skip_only_final_prompt_row() {
28774        assert_eq!(mtp_prefill_pair_count(0, 128, 256), 128);
28775        assert_eq!(mtp_prefill_pair_count(128, 256, 256), 127);
28776        assert_eq!(mtp_prefill_pair_count(0, 256, 256), 255);
28777        assert_eq!(mtp_prefill_pair_count(256, 256, 256), 0);
28778        assert_eq!(mtp_prefill_pair_count(300, 320, 256), 0);
28779    }
28780
28781    #[test]
28782    fn cancel_flag_stops_generation() {
28783        let mut p = create_test_pipeline(16, 32, 2, 2, 8, 2, 32);
28784        // Set before the call: the prefill loops honour it, the run
28785        // returns immediately with the cancelled reason and no tokens.
28786        p.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
28787        let r = p.generate_from_ids(&[1, 2, 3], 8, None, None).unwrap();
28788        assert_eq!(r.finish_reason, "cancelled");
28789        assert!(
28790            r.token_ids.is_empty(),
28791            "no tokens after cancel: {:?}",
28792            r.token_ids
28793        );
28794        assert_eq!(p.kv_cache.seq_len(), 0);
28795        assert!(p.kv_history.is_empty());
28796        assert!(!p.graph_want_logits);
28797        assert!(p.graph_logits.is_none());
28798        // Flag auto-cleared: the next call generates normally.
28799        let r2 = p.generate_from_ids(&[1, 2, 3], 4, None, None).unwrap();
28800        assert_ne!(r2.finish_reason, "cancelled");
28801    }
28802    use super::*;
28803
28804    #[test]
28805    fn minimax_m3_arch_selects_checked_oai_activation_only() {
28806        // Keep this fixture minimal: `Act::from_arch_full` needs only the
28807        // architecture id and activation name, while serde supplies stable
28808        // defaults for unrelated CMF fields.
28809        let arch = |arch_name: &str, hidden_act: &str| {
28810            serde_json::from_value::<cortiq_core::ModelArch>(serde_json::json!({
28811                "arch_name": arch_name,
28812                "hidden_size": 8,
28813                "intermediate_size": 16,
28814                "num_layers": 1,
28815                "num_attention_heads": 1,
28816                "num_kv_heads": 1,
28817                "head_dim": 8,
28818                "vocab_size": 16,
28819                "layer_types": ["FullAttention"],
28820                "rms_norm_eps": 1e-6,
28821                "max_position_embeddings": 16,
28822                "hidden_act": hidden_act
28823            }))
28824            .expect("minimal architecture")
28825        };
28826        let minimax = arch("minimax_m3_vl", "swigluoai");
28827        assert_eq!(
28828            Act::from_arch_full(&minimax),
28829            Act::SwiGluOai {
28830                alpha: 1.702,
28831                limit: 7.0,
28832            }
28833        );
28834
28835        // The same spelling must not turn into MiniMax math on a generic
28836        // model.  Only the source-validated M3 architecture owns it.
28837        let unrelated = arch("qwen2", "swigluoai");
28838        assert_eq!(Act::from_arch_full(&unrelated), Act::Silu);
28839
28840        // Conversely, an M3-tagged header with a normal activation keeps the
28841        // normal path; this prevents the architecture id from overriding the
28842        // explicit serialized contract.
28843        let non_oai = arch("minimax_m3_vl", "gelu");
28844        assert_eq!(Act::from_arch_full(&non_oai), Act::Gelu);
28845    }
28846
28847    #[test]
28848    fn minimax_swiglu_oai_act_matches_scalar_contract() {
28849        let act = Act::swiglu_oai(1.702, 7.0);
28850        let got = act.combine(10.0, -10.0);
28851        let expected = crate::inference::swiglu_oai(10.0, -10.0, 1.702, 1.0, Some(7.0));
28852        assert!((got - expected).abs() < 1e-6);
28853        assert_eq!(act.graph_act(), None, "no inexact generic graph fallback");
28854        assert_eq!(
28855            act.wgpu_graph_act(),
28856            Some(crate::gpu::GraphAct::SwiGluOaiM3),
28857            "the WGPU-only arm accepts only the frozen M3 constants"
28858        );
28859        assert_eq!(
28860            Act::swiglu_oai(1.701, 7.0).wgpu_graph_act(),
28861            None,
28862            "nearby OAI constants must not borrow MiniMax's kernel"
28863        );
28864        assert_eq!(
28865            act.moe_job_graph_contract(),
28866            Some((crate::gpu::GraphAct::SwiGluOaiM3, 7.0)),
28867            "the direct MoE path carries the frozen clamp with the marker"
28868        );
28869        assert_eq!(
28870            Act::swiglu_oai(1.702, 6.999).moe_job_graph_contract(),
28871            None,
28872            "a nearby clamp must not borrow MiniMax's device contract"
28873        );
28874
28875        // `apply` is the gate half only; `combine` owns the up clamp and
28876        // +1 offset. The two must not accidentally collapse to ordinary SiLU.
28877        let gate_only = act.apply(-10.0);
28878        let expected_gate = -10.0 / (1.0 + (17.02f32).exp());
28879        assert!((gate_only - expected_gate).abs() < 1e-10);
28880    }
28881
28882    #[test]
28883    fn explicit_sliding_schedule_selects_local_rope_profile() {
28884        // Mellum alternates three local 1,024-token layers with one global
28885        // YaRN layer.  An explicit schedule deliberately overrides the
28886        // cadence sentinel in `swa`, so test both RoPE table and scale
28887        // dispatch rather than merely checking that the metadata loaded.
28888        let mut p = create_test_pipeline(32, 64, 4, 1, 8, 4, 32);
28889        p.swa = Some((1024, usize::MAX));
28890        p.sliding_layers = Some(vec![true, true, true, false]);
28891        p.inv_freq = std::sync::Arc::new(vec![0.125; 4]);
28892        p.inv_freq_local = Some(std::sync::Arc::new(vec![0.25; 4]));
28893        p.rope_scale = 1.277_258_9;
28894        p.rope_scale_local = 1.0;
28895
28896        for li in 0..3 {
28897            assert_eq!(p.layer_window(li), Some(1024), "local layer {li}");
28898            assert_eq!(p.layer_inv_freq(li).as_slice(), &[0.25; 4]);
28899            assert_eq!(p.layer_rope_scale(li), 1.0, "local layer {li}");
28900        }
28901        assert_eq!(p.layer_window(3), None);
28902        assert_eq!(p.layer_inv_freq(3).as_slice(), &[0.125; 4]);
28903        assert_eq!(p.layer_rope_scale(3), 1.277_258_9);
28904    }
28905
28906    /// sparse_ffn_quant must equal a dense FFN where inactive neurons are
28907    /// zeroed (mask × mmap correctness). On F32 tensors this is EXACT —
28908    /// it validates the row_dot / add_col_scaled / scatter indexing, the
28909    /// bug-prone part. The q8 branches reuse the golden-tested linear
28910    /// The per-token sparse path reads a transposed `down`; it must
28911    /// agree with the arm that computes everything and zeroes the
28912    /// losers, or the speed measurement is measuring a different model.
28913    #[test]
28914    fn dynamic_ffn_equals_the_zeroing_arm() {
28915        let (hidden, inter) = (8usize, 32usize);
28916        let synth = |n: usize, salt: usize| -> Vec<f32> {
28917            (0..n)
28918                .map(|i| (((i * 29 + salt * 13 + 7) % 89) as f32 / 89.0 - 0.5) * 0.6)
28919                .collect()
28920        };
28921        let down = synth(hidden * inter, 3);
28922        let mut down_t = vec![0.0f32; inter * hidden];
28923        for r in 0..hidden {
28924            for c in 0..inter {
28925                down_t[c * hidden + r] = down[r * inter + c];
28926            }
28927        }
28928        let d = DenseFfn {
28929            gate_proj: QTensor::from_f32(synth(inter * hidden, 1), inter, hidden),
28930            up_proj: QTensor::from_f32(synth(inter * hidden, 2), inter, hidden),
28931            down_proj: QTensor::from_f32(down.clone(), hidden, inter),
28932            act: Act::Silu,
28933            down_t: Some(QTensor::from_f32(down_t, inter, hidden)),
28934            segs: Vec::new(),
28935        };
28936        let x = synth(hidden, 11);
28937        let k = 12usize;
28938        let got = dense_ffn_dynamic(&d, &x, None, k).expect("down_t present");
28939        // Reference: full compute, keep the k loudest |silu(gate)|.
28940        let mut g = vec![0.0f32; inter];
28941        d.gate_proj.matvec(&x, &mut g, None);
28942        let mut u = vec![0.0f32; inter];
28943        d.up_proj.matvec(&x, &mut u, None);
28944        for v in g.iter_mut() {
28945            *v = inference::silu(*v);
28946        }
28947        keep_top_k(&mut g, k);
28948        for i in 0..inter {
28949            g[i] *= u[i];
28950        }
28951        let mut want = vec![0.0f32; hidden];
28952        d.down_proj.matvec(&g, &mut want, None);
28953        for (a, b) in want.iter().zip(&got) {
28954            assert!((a - b).abs() < 1e-5, "dynamic {b} vs reference {a}");
28955        }
28956    }
28957
28958    /// A tube layer is the same layer, re-cut. With every tube open the
28959    /// answer must equal the dense FFN over the concatenated neurons
28960    /// (the permutation is an identity on the layer's function); with a
28961    /// tube closed it must equal the dense FFN with those neurons
28962    /// zeroed — the mask semantics, now paid for in bytes not read.
28963    #[test]
28964    fn tube_ffn_open_equals_dense_and_closed_equals_masked() {
28965        let (hidden, core, tube) = (8usize, 12usize, 8usize);
28966        let inter = core + tube;
28967        let synth = |n: usize, salt: usize| -> Vec<f32> {
28968            (0..n)
28969                .map(|i| (((i * 41 + salt * 17 + 5) % 97) as f32 / 97.0 - 0.5) * 0.5)
28970                .collect()
28971        };
28972        let (g_all, u_all) = (synth(inter * hidden, 1), synth(inter * hidden, 2));
28973        let d_all = synth(hidden * inter, 3);
28974        // The dense layer, and the same weights cut into core + tube.
28975        let dense = DenseFfn {
28976            gate_proj: QTensor::from_f32(g_all.clone(), inter, hidden),
28977            up_proj: QTensor::from_f32(u_all.clone(), inter, hidden),
28978            down_proj: QTensor::from_f32(d_all.clone(), hidden, inter),
28979            act: Act::Silu,
28980            down_t: None,
28981            segs: Vec::new(),
28982        };
28983        let rows =
28984            |v: &[f32], a: usize, b: usize| -> Vec<f32> { v[a * hidden..b * hidden].to_vec() };
28985        let cols = |v: &[f32], a: usize, b: usize| -> Vec<f32> {
28986            let mut o = Vec::with_capacity(hidden * (b - a));
28987            for r in 0..hidden {
28988                o.extend_from_slice(&v[r * inter + a..r * inter + b]);
28989            }
28990            o
28991        };
28992        let tubed = DenseFfn {
28993            down_t: None,
28994            gate_proj: QTensor::from_f32(rows(&g_all, 0, core), core, hidden),
28995            up_proj: QTensor::from_f32(rows(&u_all, 0, core), core, hidden),
28996            down_proj: QTensor::from_f32(cols(&d_all, 0, core), hidden, core),
28997            act: Act::Silu,
28998            segs: vec![FfnSeg {
28999                gate: QTensor::from_f32(rows(&g_all, core, inter), tube, hidden),
29000                up: QTensor::from_f32(rows(&u_all, core, inter), tube, hidden),
29001                down: QTensor::from_f32(cols(&d_all, core, inter), hidden, tube),
29002                start: core,
29003                width: tube,
29004            }],
29005        };
29006        let x = synth(hidden, 7);
29007        let want = dense_ffn(&dense, &x, None);
29008        let got = tube_ffn(&tubed, &x, 1, None, None);
29009        for (a, b) in want.iter().zip(&got) {
29010            assert!((a - b).abs() < 1e-5, "open tube: {a} vs {b}");
29011        }
29012        // Closed tube: bits on for the core, off for the tube.
29013        let mut bits = vec![0u8; inter.div_ceil(8)];
29014        for n in 0..core {
29015            bits[n / 8] |= 1 << (n % 8);
29016        }
29017        let closed = tube_ffn(&tubed, &x, 1, None, Some(&bits));
29018        let masked = dense_ffn_masked(&dense, &x, None, &bits);
29019        for (a, b) in masked.iter().zip(&closed) {
29020            assert!((a - b).abs() < 1e-5, "closed tube: {a} vs {b}");
29021        }
29022        // The batched arm must agree with the single-position one.
29023        let batch = tube_ffn(&tubed, &x, 1, None, Some(&bits));
29024        for (a, b) in closed.iter().zip(&batch) {
29025            assert_eq!(a, b, "batch arm disagrees with decode arm");
29026        }
29027    }
29028
29029    /// scale, structurally identical to the matvec kernels.
29030    #[test]
29031    fn sparse_ffn_quant_equals_dense_with_inactive_zeroed() {
29032        let (hidden, inter) = (16usize, 40usize);
29033        let synth = |n: usize, salt: usize| -> Vec<f32> {
29034            (0..n)
29035                .map(|i| (((i * 37 + salt * 11 + 3) % 101) as f32 / 101.0 - 0.5) * 0.4)
29036                .collect()
29037        };
29038        let d = DenseFfn {
29039            gate_proj: QTensor::from_f32(synth(inter * hidden, 1), inter, hidden),
29040            up_proj: QTensor::from_f32(synth(inter * hidden, 2), inter, hidden),
29041            down_proj: QTensor::from_f32(synth(hidden * inter, 3), hidden, inter),
29042            act: Act::Silu,
29043            down_t: None,
29044            segs: Vec::new(),
29045        };
29046        let x = synth(hidden, 9);
29047        // Active = every 3rd neuron.
29048        let active: Vec<u16> = (0..inter as u16).filter(|i| i % 3 == 0).collect();
29049
29050        let sparse = sparse_ffn_quant(&d, &x, &active, hidden, None);
29051
29052        // Reference: full dense FFN but g[i]=0 for inactive neurons.
29053        let mut g = vec![0.0f32; inter];
29054        d.gate_proj.matvec(&x, &mut g, None);
29055        let mut u = vec![0.0f32; inter];
29056        d.up_proj.matvec(&x, &mut u, None);
29057        let act_set: std::collections::HashSet<u16> = active.iter().copied().collect();
29058        for i in 0..inter {
29059            g[i] = if act_set.contains(&(i as u16)) {
29060                inference::silu(g[i]) * u[i]
29061            } else {
29062                0.0
29063            };
29064        }
29065        let mut reference = vec![0.0f32; hidden];
29066        d.down_proj.matvec(&g, &mut reference, None);
29067
29068        let max_d = sparse
29069            .iter()
29070            .zip(&reference)
29071            .map(|(a, b)| (a - b).abs())
29072            .fold(0.0f32, f32::max);
29073        assert!(max_d < 1e-5, "sparse != dense-zeroed: max|Δ| = {max_d}");
29074    }
29075
29076    /// Attach a synthetic MTP head. `inter` deliberately stays independent
29077    /// from the trunk width so calibration tests can catch a trunk-proxy bug.
29078    fn attach_test_mtp_width(p: &mut Pipeline, inter: usize) {
29079        let (h, inter, heads, kv, hd) = (
29080            p.hidden_size,
29081            inter,
29082            p.num_heads,
29083            p.num_kv_heads,
29084            p.head_dim,
29085        );
29086        let synth = |n: usize, salt: usize| -> Vec<f32> {
29087            (0..n)
29088                .map(|i| (((i * 29 + salt * 23 + 5) % 101) as f32 / 101.0 - 0.5) * 0.2)
29089                .collect()
29090        };
29091        let qt = |rows: usize, cols: usize, salt: usize| -> QTensor {
29092            QTensor::from_f32(synth(rows * cols, salt), rows, cols)
29093        };
29094        p.mtp = Some(MtpModule {
29095            enorm: vec![1.0; h],
29096            hnorm: vec![1.0; h],
29097            eh_proj: qt(h, 2 * h, 301),
29098            layer: LayerWeights {
29099                input_norm: vec![1.0; h],
29100                post_norm: vec![1.0; h],
29101                attn_out_norm: None,
29102                ffn_out_norm: None,
29103                layer_scale: None,
29104                ffn: FfnKind::Dense(DenseFfn {
29105                    gate_proj: qt(inter, h, 315),
29106                    up_proj: qt(inter, h, 316),
29107                    down_proj: qt(h, inter, 317),
29108                    act: Act::Silu,
29109                    down_t: None,
29110                    segs: Vec::new(),
29111                }),
29112                attn: AttnKind::Full {
29113                    bias: None,
29114                    wq: qt(heads * hd, h, 311),
29115                    wk: qt(kv * hd, h, 312),
29116                    wv: qt(kv * hd, h, 313),
29117                    wo: qt(h, heads * hd, 314),
29118                    q_norm: None,
29119                    k_norm: None,
29120                    output_gate: false,
29121                    softplus_gate: None,
29122                },
29123            },
29124            final_norm: vec![1.0; h],
29125            kv: crate::kv_cache::LayerKvCache::new(kv, hd),
29126        });
29127    }
29128
29129    /// Attach a synthetic MTP head with the trunk's conventional width.
29130    fn attach_test_mtp(p: &mut Pipeline) {
29131        attach_test_mtp_width(p, p.intermediate_size);
29132    }
29133
29134    #[test]
29135    fn canonical_mtp_ffn_probe_uses_draft_width_and_cleans_state() {
29136        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 64);
29137        // This differs from the trunk FFN width (16). A result shaped like
29138        // the trunk probe would be a silent, dangerous compaction bug.
29139        attach_test_mtp_width(&mut p, 11);
29140        let ids = [3, 9, 4, 12, 7, 2];
29141        let trunk = p.probe_ffn_mass(&ids);
29142        assert_eq!(trunk[0].len(), p.intermediate_size);
29143
29144        let got = p.probe_mtp_ffn(&ids).expect("canonical MTP probe");
29145        assert_eq!(got.len(), 1);
29146        assert_eq!(got[0].mass.len(), 11);
29147        assert_eq!(got[0].squared_mass.len(), 11);
29148        assert_eq!(got[0].observed_positions, ids.len() - 1);
29149        assert!(got[0].mass.iter().any(|&v| v > 0.0));
29150        assert!(got[0]
29151            .mass
29152            .iter()
29153            .zip(&got[0].squared_mass)
29154            .all(|(&m, &s)| m.is_finite() && s.is_finite() && m >= 0.0 && s >= 0.0));
29155        assert_eq!(p.kv_cache.seq_len(), 0, "probe must leave a fresh trunk");
29156        assert_eq!(p.mtp.as_ref().unwrap().kv.seq_len, 0, "and fresh MTP KV");
29157
29158        // Force an error *after* the MTP attention has appended a draft KV
29159        // row. This proves the error path clears detached draft state, not
29160        // merely the easy invalid-token preflight branch.
29161        let h = p.hidden_size;
29162        let FfnKind::Dense(dense) = &mut p.mtp.as_mut().unwrap().layer.ffn else {
29163            panic!("synthetic MTP must be dense")
29164        };
29165        dense.segs.push(FfnSeg {
29166            gate: QTensor::from_f32(vec![0.0; h], 1, h),
29167            up: QTensor::from_f32(vec![0.0; h], 1, h),
29168            down: QTensor::from_f32(vec![0.0; h], h, 1),
29169            start: dense.gate_proj.rows(),
29170            width: 1,
29171        });
29172        let err = p.probe_mtp_ffn(&ids);
29173        assert!(err
29174            .unwrap_err()
29175            .contains("tube-segmented draft FFNs are not supported"));
29176        assert_eq!(p.kv_cache.seq_len(), 0);
29177        assert_eq!(p.mtp.as_ref().unwrap().kv.seq_len, 0);
29178    }
29179
29180    #[test]
29181    fn speculative_equals_vanilla_greedy() {
29182        let _env_lock = MTP_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
29183        // Exercise the experimental host pair deterministically; the native
29184        // and wgpu batch graphs have independent coverage.
29185        let _gpu_env = crate::gpu::test_gpu_env("0");
29186        let _env = ScopedTestEnv::set(&[
29187            ("CMF_GPU_WGPU_GRAPH", Some("0")),
29188            ("CMF_MTP_PAIR", Some("1")),
29189        ]);
29190        let run = |spec: bool| {
29191            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
29192            p.sampler_config.temperature = 0.0;
29193            attach_test_mtp(&mut p);
29194            p.speculative = spec;
29195            let r = p.generate("abcdef", 12, None, None).unwrap();
29196            (r.token_ids, r.mtp_drafted, r.mtp_accepted)
29197        };
29198        let (vanilla, d0, _) = run(false);
29199        let (spec, d1, a1) = run(true);
29200        assert_eq!(d0, 0, "vanilla path must not draft");
29201        assert!(d1 > 0, "speculative path must draft");
29202        assert!(a1 <= d1, "accepted drafts cannot exceed proposals");
29203        assert_eq!(
29204            vanilla, spec,
29205            "speculative must reproduce the exact greedy sequence (accepted {a1}/{d1})"
29206        );
29207    }
29208
29209    #[test]
29210    fn speculative_accepts_constant_oracle() {
29211        let _env_lock = MTP_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
29212        let _gpu_env = crate::gpu::test_gpu_env("0");
29213        let _env = ScopedTestEnv::set(&[
29214            ("CMF_GPU_WGPU_GRAPH", Some("0")),
29215            ("CMF_MTP_PAIR", Some("1")),
29216        ]);
29217        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
29218        p.sampler_config.temperature = 0.0;
29219        p.sampler_config.repetition_penalty = 1.0;
29220        // Constant lm_head → every logit equal → both the main model and
29221        // the draft head argmax to token 0: acceptance must be 100%.
29222        p.weights.lm_head = QTensor::from_f32(vec![0.01; 64 * 8], 64, 8);
29223        attach_test_mtp(&mut p);
29224        p.speculative = true;
29225        let r = p.generate("abcd", 10, None, None).unwrap();
29226        assert!(r.mtp_drafted > 0);
29227        assert_eq!(
29228            r.mtp_accepted, r.mtp_drafted,
29229            "constant logits → every draft accepted"
29230        );
29231        // Ties resolve to the same token in both the main and draft
29232        // heads — the sequence is one repeated token.
29233        assert!(r.token_ids.windows(2).all(|w| w[0] == w[1]));
29234    }
29235
29236    #[test]
29237    fn host_fused_mtp_pair_is_opt_in() {
29238        let _env_lock = MTP_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
29239        let _gpu_env = crate::gpu::test_gpu_env("0");
29240        let _env = ScopedTestEnv::set(&[
29241            ("CMF_GPU_WGPU_GRAPH", Some("0")),
29242            ("CMF_MTP_PAIR", None),
29243        ]);
29244        let run = |spec: bool| {
29245            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
29246            p.sampler_config.temperature = 0.0;
29247            attach_test_mtp(&mut p);
29248            p.speculative = spec;
29249            let r = p.generate("abcdef", 12, None, None).unwrap();
29250            (r.token_ids, r.mtp_drafted, r.mtp_accepted)
29251        };
29252        let (plain, d0, _) = run(false);
29253        let (guarded, d1, a1) = run(true);
29254        assert_eq!(d0, 0);
29255        assert_eq!(d1, 0, "host MTP pair must remain opt-in");
29256        assert_eq!(a1, 0);
29257        assert_eq!(guarded, plain, "the safe default is ordinary greedy decode");
29258    }
29259
29260    #[test]
29261    fn empty_prompt_is_an_error_not_a_panic() {
29262        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
29263        let r = p.generate("", 4, None, None);
29264        assert!(r.is_err(), "empty prompt must be a clean error");
29265    }
29266
29267    #[test]
29268    fn every_token_enters_kv_exactly_once() {
29269        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
29270        // Greedy so no RNG variance; byte tokenizer → 3 prompt tokens.
29271        p.sampler_config.temperature = 0.0;
29272        let r = p.generate("abc", 2, None, None).unwrap();
29273        assert_eq!(r.prompt_tokens, 3);
29274        // prompt(3) + first sampled token forwarded before second logits:
29275        // step0 samples from prefill hidden (no extra forward), then
29276        // forwards t1 → cache 4; step1 samples, loop ends (max_tokens).
29277        assert_eq!(
29278            p.kv_cache.seq_len(),
29279            3 + r.tokens_generated - 1,
29280            "each token must be cached exactly once (v1 cached the last prompt token twice)"
29281        );
29282    }
29283
29284    #[test]
29285    fn generation_is_reproducible_with_seed() {
29286        let run = || {
29287            let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
29288            p.generate("hello", 8, None, None).unwrap().token_ids
29289        };
29290        assert_eq!(run(), run());
29291    }
29292
29293    #[test]
29294    fn resetting_sampler_restarts_the_seeded_stream() {
29295        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
29296        let config = SamplerConfig {
29297            seed: Some(1234),
29298            ..SamplerConfig::default()
29299        };
29300        p.set_sampler_config(config.clone());
29301        let first = p.generate("hello", 8, None, None).unwrap().token_ids;
29302        p.set_sampler_config(config);
29303        let second = p.generate("hello", 8, None, None).unwrap().token_ids;
29304        assert_eq!(first, second);
29305    }
29306
29307    #[test]
29308    fn eviction_bounds_the_cache() {
29309        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 260);
29310        p.kv_cache.max_seq_len = 6;
29311        p.sampler_config.temperature = 0.0;
29312        let _ = p.generate("abcd", 12, None, None).unwrap();
29313        assert!(
29314            p.kv_cache.seq_len() <= 6 + 1,
29315            "cache must stay bounded by max_seq_len (got {})",
29316            p.kv_cache.seq_len()
29317        );
29318    }
29319
29320    #[test]
29321    fn confidence_matches_tokens_and_is_a_probability() {
29322        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
29323        p.sampler_config.temperature = 0.0;
29324        p.sampler_config.repetition_penalty = 1.0;
29325        let r = p.generate("abcd", 10, None, None).unwrap();
29326        assert_eq!(
29327            r.token_confidence.len(),
29328            r.token_ids.len(),
29329            "one confidence per emitted token"
29330        );
29331        for &c in &r.token_confidence {
29332            assert!((0.0..=1.0).contains(&c), "confidence out of [0,1]: {c}");
29333        }
29334        // top1_prob is a valid softmax probability.
29335        let logits = [1.0f32, 3.0, 0.5, 3.0];
29336        let p0 = top1_prob_t(&logits, 1, 1.0);
29337        let p1 = top1_prob_t(&logits, 3, 1.0);
29338        assert!((p0 - p1).abs() < 1e-6, "equal logits → equal prob");
29339        assert!(p0 > 0.0 && p0 < 1.0);
29340        // Calibration temperature > 1 softens an over-confident peak.
29341        let sharp = top1_prob_t(&logits, 1, 1.0);
29342        let soft = top1_prob_t(&logits, 1, 2.0);
29343        assert!(soft < sharp, "higher temperature lowers peak confidence");
29344    }
29345
29346    #[test]
29347    fn trace_is_opt_in_and_parallels_the_output() {
29348        // Off by default: the runtime is silent unless observation asked.
29349        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
29350        p.sampler_config.temperature = 0.0;
29351        p.sampler_config.repetition_penalty = 1.0;
29352        let r = p.generate("abcd", 10, None, None).unwrap();
29353        assert!(r.traces.is_empty(), "trace must be empty unless enabled");
29354
29355        // On: exactly one row per emitted token, aligned with the output.
29356        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
29357        p.sampler_config.temperature = 0.0;
29358        p.sampler_config.repetition_penalty = 1.0;
29359        p.set_trace(true);
29360        let r = p.generate("abcd", 10, None, None).unwrap();
29361        assert_eq!(r.traces.len(), r.token_ids.len(), "one trace row per token");
29362        for (i, tr) in r.traces.iter().enumerate() {
29363            assert_eq!(tr.t, i, "trace index is sequential");
29364            assert_eq!(tr.token_id, r.token_ids[i], "trace token_id matches output");
29365            assert_eq!(
29366                tr.confidence, r.token_confidence[i],
29367                "trace confidence matches the confidence channel"
29368            );
29369            // No dynamic router in this pipeline → no skill, no coherence.
29370            assert!(tr.active_skill.is_none() && tr.recon.is_none() && !tr.switched);
29371        }
29372    }
29373
29374    #[test]
29375    fn explain_prefill_logits_match_greedy_first_token() {
29376        // `cortiq explain` shows the next-token distribution from
29377        // prefill_next_logits; its argmax must equal what greedy generate
29378        // actually emits first — otherwise explain would lie.
29379        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
29380        p.sampler_config.temperature = 0.0;
29381        p.sampler_config.repetition_penalty = 1.0;
29382        let ids = p.tokenizer.encode("abcd");
29383        let logits = p.prefill_next_logits(&ids, None);
29384        let argmax = logits
29385            .iter()
29386            .enumerate()
29387            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
29388            .unwrap()
29389            .0 as u32;
29390        let r = p.generate("abcd", 1, None, None).unwrap();
29391        assert_eq!(
29392            argmax, r.token_ids[0],
29393            "explain preview must match greedy emit"
29394        );
29395    }
29396
29397    #[test]
29398    fn laguna_shared_expert_is_unconditionally_added() {
29399        let matrix = |values: Vec<f32>| QTensor::from_f32(values, 2, 2);
29400        let identity = || matrix(vec![1.0, 0.0, 0.0, 1.0]);
29401        let zero_dense = || DenseFfn {
29402            gate_proj: matrix(vec![0.0; 4]),
29403            up_proj: matrix(vec![0.0; 4]),
29404            down_proj: matrix(vec![0.0; 4]),
29405            act: Act::Silu,
29406            down_t: None,
29407            segs: Vec::new(),
29408        };
29409        let shared = DenseFfn {
29410            gate_proj: identity(),
29411            up_proj: identity(),
29412            down_proj: identity(),
29413            act: Act::Silu,
29414            down_t: None,
29415            segs: Vec::new(),
29416        };
29417        let x = [1.0, 2.0];
29418        let expected = dense_ffn(&shared, &x, None);
29419        let moe = MoeFfn {
29420            router: QTensor::from_f32(vec![0.0, 0.0], 1, 2),
29421            experts: vec![zero_dense()],
29422            top_k: 1,
29423            norm_topk_prob: true,
29424            router_sigmoid: true,
29425            sigmoid_denom_eps: 1e-6,
29426            expert_bias: None,
29427            routed_scaling: 1.0,
29428            route_tau: None,
29429            shared: Some((shared, None)),
29430            stats: std::cell::RefCell::new(Vec::new()),
29431            act_sq: std::cell::RefCell::new(Vec::new()),
29432            act_rows: std::cell::RefCell::new(Vec::new()),
29433            mask: None,
29434            per_expert_scale: None,
29435            router_input_norm: false,
29436            resonance: None,
29437            grown: Vec::new(),
29438        };
29439        let actual = moe_ffn_cpu(&moe, &x, &[0], &[0.0], 1.0, None);
29440        for (actual, expected) in actual.iter().zip(expected) {
29441            assert!((actual - expected).abs() < 1e-6);
29442        }
29443    }
29444
29445    /// A tiny MiMo-V2-shaped stack (the M3 fixture): layers [full, sliding,
29446    /// sliding, full]; 4 Q heads over 1 (full) / 2 (sliding) KV heads;
29447    /// head_dim 8 with 4-wide V heads; partial rotary 4 at θ 1e7 (full) /
29448    /// 1e4 (sliding); window 3; learned sinks on the sliding layers; layer
29449    /// 0 a dense FFN, layers 1..3 sigmoid-routed MoE with a selection bias
29450    /// (4 experts, top-2, renormalized, no shared expert). Geometry and
29451    /// sinks go through the same `set_attn_geometry` / `set_layer_sinks`
29452    /// the loader calls.
29453    fn mimo_test_pipeline() -> Pipeline {
29454        let (hs, inter, nh, hd, vd, vocab) = (16usize, 24usize, 4usize, 8usize, 4usize, 64usize);
29455        let kvh = [1usize, 2, 2, 1];
29456        let synth = |n: usize, salt: usize| -> Vec<f32> {
29457            (0..n)
29458                .map(|i| (((i * 31 + salt * 17 + 7) % 97) as f32 / 97.0 - 0.5) * 0.4)
29459                .collect()
29460        };
29461        let qt = |rows: usize, cols: usize, salt: usize| {
29462            QTensor::from_f32(synth(rows * cols, salt), rows, cols)
29463        };
29464        let dense = |inter: usize, salt: usize| DenseFfn {
29465            gate_proj: qt(inter, hs, salt),
29466            up_proj: qt(inter, hs, salt + 1),
29467            down_proj: qt(hs, inter, salt + 2),
29468            act: Act::Silu,
29469            down_t: None,
29470            segs: Vec::new(),
29471        };
29472        let layers: Vec<LayerWeights> = (0..4)
29473            .map(|li| LayerWeights {
29474                input_norm: vec![1.0; hs],
29475                post_norm: vec![1.0; hs],
29476                attn_out_norm: None,
29477                ffn_out_norm: None,
29478                layer_scale: None,
29479                ffn: if li == 0 {
29480                    FfnKind::Dense(dense(inter, 50))
29481                } else {
29482                    FfnKind::Moe(MoeFfn {
29483                        router: qt(4, hs, 60 + li),
29484                        experts: (0..4).map(|e| dense(8, 70 + li * 10 + e * 3)).collect(),
29485                        top_k: 2,
29486                        norm_topk_prob: true,
29487                        router_sigmoid: true,
29488                        sigmoid_denom_eps: 1e-6,
29489                        expert_bias: Some(vec![0.02, -0.03, 0.01, 0.0]),
29490                        routed_scaling: 1.0,
29491                        route_tau: None,
29492                        shared: None,
29493                        stats: std::cell::RefCell::new(Vec::new()),
29494                        act_sq: std::cell::RefCell::new(Vec::new()),
29495                        act_rows: std::cell::RefCell::new(Vec::new()),
29496                        mask: None,
29497                        per_expert_scale: None,
29498                        router_input_norm: false,
29499                        resonance: None,
29500                        grown: Vec::new(),
29501                    })
29502                },
29503                attn: AttnKind::Full {
29504                    wq: qt(nh * hd, hs, li * 10 + 1),
29505                    wk: qt(kvh[li] * hd, hs, li * 10 + 2),
29506                    wv: qt(kvh[li] * vd, hs, li * 10 + 3),
29507                    wo: qt(hs, nh * vd, li * 10 + 4),
29508                    q_norm: None,
29509                    k_norm: None,
29510                    output_gate: false,
29511                    softplus_gate: None,
29512                    bias: None,
29513                },
29514            })
29515            .collect();
29516        let mut p = Pipeline::new(
29517            Tokenizer::byte_level(),
29518            PipelineWeights {
29519                embed_tokens: qt(vocab, hs, 100),
29520                layers,
29521                lm_head: qt(vocab, hs, 200),
29522                final_norm: vec![1.0; hs],
29523            },
29524            hs,
29525            inter,
29526            nh,
29527            1, // header num_kv_heads (the full layers')
29528            hd,
29529            4,
29530            4,
29531            false,
29532            vocab,
29533            1e-6,
29534            1e7,
29535            NormStyle::Qwen,
29536            4096,
29537            SamplerConfig {
29538                seed: Some(7),
29539                ..Default::default()
29540            },
29541        );
29542        // Diagnostics stay off whatever the test environment exports.
29543        p.layer_dump = None;
29544        p.set_rotary(4, 1e7);
29545        p.sliding_layers = Some(vec![false, true, true, false]);
29546        p.swa = Some((3, usize::MAX));
29547        p.rotary_dim_local = Some(4);
29548        p.inv_freq_local = Some(std::sync::Arc::new(attention::rope_inv_freq(4, 1e4)));
29549        p.set_attn_geometry(Some(kvh.to_vec()), Some(vd)).unwrap();
29550        p.set_layer_sinks(1, vec![0.5, -1.0, 1.5, 0.0]).unwrap();
29551        p.set_layer_sinks(2, vec![-0.25, 2.0, 0.75, -1.5]).unwrap();
29552        p
29553    }
29554
29555    #[test]
29556    fn mimo_embedded_prompt_uses_rows_and_never_reuses_token_only_kv() {
29557        let mut p = mimo_test_pipeline();
29558        p.speculative = false;
29559        p.ignore_eos = true;
29560        p.sampler_config.temperature = 0.0;
29561        p.sampler_config.repetition_penalty = 1.0;
29562        let a = vec![3, 5, 7, 9, 11, 13];
29563        let b = vec![4, 8, 12, 16, 20, 24];
29564        let rows: Vec<_> = b.iter().flat_map(|&id| p.embed_id(id)).collect();
29565        let expected = p.generate_from_ids(&b, 8, None, None).unwrap().token_ids;
29566        // Same placeholder IDs as an earlier request are not a cache key
29567        // for different media. The actual rows, not a re-embedding of a,
29568        // must determine the continuation.
29569        let actual = p
29570            .generate_from_embeds(&a, &rows, 8, None, None)
29571            .unwrap()
29572            .token_ids;
29573        assert_eq!(actual, expected);
29574        assert!(p.kv_history.is_empty());
29575        let mut extended = a.clone();
29576        extended.push(17);
29577        let after_media = p
29578            .generate_from_ids(&extended, 8, None, None)
29579            .unwrap()
29580            .token_ids;
29581        p.reset_session();
29582        let fresh = p
29583            .generate_from_ids(&extended, 8, None, None)
29584            .unwrap()
29585            .token_ids;
29586        assert_eq!(after_media, fresh);
29587        assert!(
29588            p.generate_from_embeds(&a, &rows[..rows.len() - 1], 1, None, None)
29589                .is_err()
29590        );
29591        // Force a real token-prefix reuse opportunity into the media call.
29592        // Those labels are unchanged, but their embeddings now describe a
29593        // different source sequence and every KV row must be rebuilt.
29594        p.reset_session();
29595        p.generate_from_ids(&a, 1, None, None).unwrap();
29596        let mut media_ids = p.kv_history.clone();
29597        assert!(!media_ids.is_empty());
29598        media_ids.extend_from_slice(&[19, 21, 23]);
29599        let source_ids: Vec<_> = (0..media_ids.len()).map(|i| b[i % b.len()]).collect();
29600        let source_rows: Vec<_> = source_ids.iter().flat_map(|&id| p.embed_id(id)).collect();
29601        let mut oracle = mimo_test_pipeline();
29602        oracle.speculative = false;
29603        oracle.ignore_eos = true;
29604        oracle.sampler_config.temperature = 0.0;
29605        oracle.sampler_config.repetition_penalty = 1.0;
29606        let expected = oracle
29607            .generate_from_ids(&source_ids, 8, None, None)
29608            .unwrap()
29609            .token_ids;
29610        assert_eq!(
29611            p.generate_from_embeds(&media_ids, &source_rows, 8, None, None)
29612                .unwrap()
29613                .token_ids,
29614            expected
29615        );
29616        assert!(p.kv_history.is_empty());
29617        let mut bad = rows;
29618        bad[0] = f32::NAN;
29619        assert!(p.generate_from_embeds(&a, &bad, 1, None, None).is_err());
29620    }
29621
29622    fn f32_bits(v: &[f32]) -> Vec<u32> {
29623        v.iter().map(|x| x.to_bits()).collect()
29624    }
29625
29626    /// M3 acceptance: on the MiMo-shaped stack the decode walk (one
29627    /// position at a time through `forward_layers`) and the batched
29628    /// prefill (`prefill_batch_span`, whole prompt and split in two
29629    /// chunks) give bit-identical logits at all 12 positions — per-layer
29630    /// KV heads, narrow V, sinks, the window and the biased sigmoid MoE all
29631    /// agree across the two walks.
29632    #[test]
29633    fn mimo_shaped_decode_matches_prefill_batch_bitwise() {
29634        let mut p = mimo_test_pipeline();
29635        let kv: Vec<usize> = p.kv_cache.layers.iter().map(|l| l.num_kv_heads).collect();
29636        assert_eq!(kv, vec![1, 2, 2, 1]);
29637        assert!(p.kv_cache.layers[0].sinks.is_none() && p.kv_cache.layers[3].sinks.is_none());
29638        assert!(p.kv_cache.layers[1].sinks.is_some() && p.kv_cache.layers[2].sinks.is_some());
29639        let ids: Vec<u32> = (0..12u32).map(|i| (i * 7 + 3) % 64).collect();
29640        let hs = p.hidden_size;
29641        let mut decode = Vec::new();
29642        for (pos, &id) in ids.iter().enumerate() {
29643            let e = p.embed_single(id);
29644            let h = p.forward_layers(&e, pos, None);
29645            decode.push(p.logits_from_hidden(&h));
29646        }
29647        for l in &p.kv_cache.layers {
29648            assert_eq!(l.seq_len, 12);
29649            // V rows are padded to head_dim inside the cache.
29650            assert_eq!(l.head_values(0).len(), 12 * 8);
29651        }
29652        assert!(decode.iter().flatten().all(|v| v.is_finite()));
29653
29654        p.clear_sequence_state();
29655        let hb = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
29656        for pos in 0..ids.len() {
29657            let lg = p.logits_from_hidden(&hb[pos * hs..(pos + 1) * hs]);
29658            assert_eq!(
29659                f32_bits(&decode[pos]),
29660                f32_bits(&lg),
29661                "whole prompt, pos {pos}"
29662            );
29663        }
29664
29665        p.clear_sequence_state();
29666        let a = p.prefill_batch_span(PrefillIn::Ids(&ids[..5]), 0, None, 0, p.num_layers);
29667        let b = p.prefill_batch_span(PrefillIn::Ids(&ids[5..]), 5, None, 0, p.num_layers);
29668        for pos in 0..ids.len() {
29669            let row = if pos < 5 {
29670                &a[pos * hs..(pos + 1) * hs]
29671            } else {
29672                &b[(pos - 5) * hs..(pos - 4) * hs]
29673            };
29674            let lg = p.logits_from_hidden(row);
29675            assert_eq!(
29676                f32_bits(&decode[pos]),
29677                f32_bits(&lg),
29678                "two chunks, pos {pos}"
29679            );
29680        }
29681
29682        // The fixture is not degenerate: the sinks and the window each
29683        // change the answer.
29684        let last = |p: &mut Pipeline| {
29685            p.clear_sequence_state();
29686            let hb = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
29687            p.logits_from_hidden(&hb[11 * hs..12 * hs])
29688        };
29689        let base = last(&mut p);
29690        let mut no_sinks = mimo_test_pipeline();
29691        for l in &mut no_sinks.kv_cache.layers {
29692            l.sinks = None;
29693        }
29694        assert_ne!(
29695            f32_bits(&last(&mut no_sinks)),
29696            f32_bits(&base),
29697            "sinks are live"
29698        );
29699        let mut wide = mimo_test_pipeline();
29700        wide.swa = Some((64, usize::MAX));
29701        assert_ne!(
29702            f32_bits(&last(&mut wide)),
29703            f32_bits(&base),
29704            "window is live"
29705        );
29706
29707        // Generation runs end to end on the same stack.
29708        p.clear_sequence_state();
29709        p.ignore_eos = true;
29710        let r = p.generate_from_ids(&ids, 4, None, None).unwrap();
29711        assert_eq!(r.token_ids.len(), 4);
29712    }
29713
29714    /// A Spark-X2.5-shaped stack: layers 0..3 slide (window 6), layer 3
29715    /// is global, every attention carries the head-wise sigmoid g_proj gate.
29716    fn spark_test_pipeline(trim: Option<(usize, usize)>) -> Pipeline {
29717        let (hs, nh) = (16usize, 4usize);
29718        let mut p = create_test_pipeline(hs, 24, nh, 2, 8, 4, 64);
29719        p.layer_dump = None;
29720        p.swa = Some((6, 4));
29721        p.proj_gate_sigmoid = true;
29722        for (li, lw) in p.weights.layers.iter_mut().enumerate() {
29723            if let AttnKind::Full { softplus_gate, .. } = &mut lw.attn {
29724                let g: Vec<f32> = (0..nh * hs)
29725                    .map(|i| (((i * 29 + li * 7) % 83) as f32 / 83.0 - 0.5) * 0.8)
29726                    .collect();
29727                *softplus_gate = Some((QTensor::from_f32(g, nh, hs), true));
29728            }
29729        }
29730        p.swa_trim = trim;
29731        p
29732    }
29733
29734    /// Trimming the sliding tails changes nothing but memory: the same
29735    /// prompt in uneven chunks, a decode walk, and fused pairs with a
29736    /// 2-row rollback give bit-identical hiddens with and without it,
29737    /// while the trimmed sliding layers stay bounded and the global layer
29738    /// keeps every row.
29739    #[test]
29740    fn swa_trim_pipeline_matches_untrimmed_bitwise() {
29741        let mut a = spark_test_pipeline(None);
29742        let mut b = spark_test_pipeline(Some((2, 4)));
29743        assert_eq!(
29744            (0..4).map(|li| b.layer_window(li)).collect::<Vec<_>>(),
29745            vec![Some(6), Some(6), Some(6), None]
29746        );
29747        let ids: Vec<u32> = (0..41u32).map(|i| (i * 11 + 5) % 64).collect();
29748        let mut pos = 0usize;
29749        for &n in [5usize, 13, 7, 16].iter().cycle() {
29750            if pos >= ids.len() {
29751                break;
29752            }
29753            let end = (pos + n).min(ids.len());
29754            let ha = a.prefill_batch_span(PrefillIn::Ids(&ids[pos..end]), pos, None, 0, 4);
29755            let hb = b.prefill_batch_span(PrefillIn::Ids(&ids[pos..end]), pos, None, 0, 4);
29756            assert_eq!(f32_bits(&ha), f32_bits(&hb), "prefill chunk at {pos}");
29757            pos = end;
29758        }
29759        for _ in 0..23 {
29760            let e = a.embed_single(((pos * 7) % 64) as u32);
29761            let ha = a.forward_layers(&e, pos, None);
29762            let hb = b.forward_layers(&e, pos, None);
29763            assert_eq!(f32_bits(&ha), f32_bits(&hb), "decode at {pos}");
29764            for li in 0..3 {
29765                assert!(b.kv_cache.layers[li].seq_len <= 12, "layer {li} bounded");
29766            }
29767            pos += 1;
29768        }
29769        for round in 0..9 {
29770            let (e1, e2) = (a.embed_single(round * 3 + 1), a.embed_single(round * 5 + 2));
29771            let (a1, a2) = a.forward_pair(&e1, &e2, pos);
29772            let (b1, b2) = b.forward_pair(&e1, &e2, pos);
29773            assert_eq!(f32_bits(&a1), f32_bits(&b1), "pair lane 1 round {round}");
29774            assert_eq!(f32_bits(&a2), f32_bits(&b2), "pair lane 2 round {round}");
29775            if round % 2 == 1 {
29776                // A rejected draft: both lanes roll back.
29777                for p in [&mut a, &mut b] {
29778                    for l in &mut p.kv_cache.layers {
29779                        l.truncate_last(2);
29780                    }
29781                }
29782            } else {
29783                pos += 2;
29784            }
29785        }
29786        let e = a.embed_single(9);
29787        let (ha, hb) = (
29788            a.forward_layers(&e, pos, None),
29789            b.forward_layers(&e, pos, None),
29790        );
29791        assert_eq!(f32_bits(&ha), f32_bits(&hb), "after the pairs");
29792        for li in 0..3 {
29793            let (la, lb) = (&a.kv_cache.layers[li], &b.kv_cache.layers[li]);
29794            assert!(lb.base() > 0, "layer {li} trimmed");
29795            assert_eq!(la.base(), 0);
29796            assert_eq!(lb.pos_len(), la.seq_len);
29797            assert_eq!(lb.head_keys(0), &la.head_keys(0)[lb.base() * 8..]);
29798        }
29799        let (ga, gb) = (&a.kv_cache.layers[3], &b.kv_cache.layers[3]);
29800        assert_eq!(
29801            (gb.base(), gb.seq_len),
29802            (0, ga.seq_len),
29803            "the global layer keeps all"
29804        );
29805        assert_eq!(b.kv_cache.seq_len(), a.kv_cache.seq_len());
29806        assert!(b.kv_cache.total_memory_bytes() < a.kv_cache.total_memory_bytes());
29807    }
29808
29809    /// The network split's KvFetch hand-off on a trimmed stack: every
29810    /// layer shipped over the wire mid-sequence (the sliding ones as
29811    /// `FullTail`) into a fresh pipeline that never ran a position, which
29812    /// then decodes on — bit for bit what the untrimmed pipeline decodes.
29813    #[test]
29814    fn swa_trim_wire_handoff_continues_bitwise() {
29815        let mut a = spark_test_pipeline(None);
29816        let mut b = spark_test_pipeline(Some((2, 4)));
29817        let ids: Vec<u32> = (0..29u32).map(|i| (i * 13 + 7) % 64).collect();
29818        let ha = a.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, 4);
29819        let hb = b.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, 4);
29820        assert_eq!(f32_bits(&ha), f32_bits(&hb));
29821        let mut pos = ids.len();
29822        for _ in 0..5 {
29823            let e = a.embed_single(((pos * 5) % 64) as u32);
29824            assert_eq!(
29825                f32_bits(&a.forward_layers(&e, pos, None)),
29826                f32_bits(&b.forward_layers(&e, pos, None))
29827            );
29828            pos += 1;
29829        }
29830        let mut c = spark_test_pipeline(Some((2, 4)));
29831        for li in 0..4 {
29832            let bytes = b.kv_cache.layers[li].export_wire(false).unwrap();
29833            c.kv_cache.layers[li].import_wire(&bytes).unwrap();
29834        }
29835        assert!(c.kv_cache.layers[0].base() > 0, "a tail travelled");
29836        assert_eq!(c.kv_cache.seq_len(), pos);
29837        for step in 0..17 {
29838            let e = a.embed_single(((pos * 3 + 1) % 64) as u32);
29839            let ha = a.forward_layers(&e, pos, None);
29840            let hc = c.forward_layers(&e, pos, None);
29841            assert_eq!(
29842                f32_bits(&ha),
29843                f32_bits(&hc),
29844                "after the hand-off, step {step}"
29845            );
29846            pos += 1;
29847        }
29848        assert!(c.kv_cache.layers[0].seq_len <= 12, "the receiver trims on");
29849    }
29850
29851    /// A synthetic MiMo draft stack for `mimo_test_pipeline` (the SWA
29852    /// geometry of its sliding layers: 2 KV heads, head 8 / V 4).  Widths
29853    /// are per-draft-layer so the MTP collector cannot accidentally borrow
29854    /// the trunk's `intermediate_size`.
29855    fn mimo_test_mtp_widths(widths: &[usize], gain: f32) -> mimo_mtp::MimoMtp {
29856        let (hs, nh, hd, vd, nkv) = (16usize, 4usize, 8usize, 4usize, 2usize);
29857        let synth = |len: usize, salt: usize| -> Vec<f32> {
29858            (0..len)
29859                .map(|i| (((i * 37 + salt * 13 + 3) % 89) as f32 / 89.0 - 0.5) * 0.6 * gain)
29860                .collect()
29861        };
29862        let qt = |rows: usize, cols: usize, salt: usize| {
29863            QTensor::from_f32(synth(rows * cols, salt), rows, cols)
29864        };
29865        let layers = widths
29866            .iter()
29867            .copied()
29868            .enumerate()
29869            .map(|(k, inter)| {
29870                let s = 500 + k * 40;
29871                let mut kv = crate::kv_cache::LayerKvCache::new(nkv, hd);
29872                kv.sinks = Some(vec![0.3, -0.7, 1.1, 0.0]);
29873                MtpModule {
29874                    enorm: vec![1.0; hs],
29875                    hnorm: vec![1.0; hs],
29876                    eh_proj: qt(hs, 2 * hs, s),
29877                    layer: LayerWeights {
29878                        input_norm: vec![1.0; hs],
29879                        post_norm: vec![1.0; hs],
29880                        attn_out_norm: None,
29881                        ffn_out_norm: None,
29882                        layer_scale: None,
29883                        attn: AttnKind::Full {
29884                            wq: qt(nh * hd, hs, s + 1),
29885                            wk: qt(nkv * hd, hs, s + 2),
29886                            wv: qt(nkv * vd, hs, s + 3),
29887                            wo: qt(hs, nh * vd, s + 4),
29888                            q_norm: None,
29889                            k_norm: None,
29890                            output_gate: false,
29891                            softplus_gate: None,
29892                            bias: None,
29893                        },
29894                        ffn: FfnKind::Dense(DenseFfn {
29895                            gate_proj: qt(inter, hs, s + 5),
29896                            up_proj: qt(inter, hs, s + 6),
29897                            down_proj: qt(hs, inter, s + 7),
29898                            act: Act::Silu,
29899                            down_t: None,
29900                            segs: Vec::new(),
29901                        }),
29902                    },
29903                    final_norm: vec![1.0; hs],
29904                    kv,
29905                }
29906            })
29907            .collect();
29908        mimo_mtp::MimoMtp::from_layers(layers)
29909    }
29910
29911    fn mimo_test_mtp(n: usize, gain: f32) -> mimo_mtp::MimoMtp {
29912        mimo_test_mtp_widths(&vec![24; n], gain)
29913    }
29914
29915    fn mimo_greedy(p: &mut Pipeline, ids: &[u32], n: usize, spec: bool) -> GenerateResult {
29916        p.clear_sequence_state();
29917        p.speculative = spec;
29918        p.ignore_eos = true;
29919        p.sampler_config.temperature = 0.0;
29920        p.generate_from_ids(ids, n, None, None).unwrap()
29921    }
29922
29923    #[test]
29924    fn mimo_mtp_ffn_probe_tracks_each_independent_draft_width() {
29925        let mut p = mimo_test_pipeline();
29926        let widths = [7usize, 13, 29];
29927        assert_ne!(widths[0], p.intermediate_size);
29928        assert_ne!(widths[1], p.intermediate_size);
29929        assert_ne!(widths[2], p.intermediate_size);
29930        p.mimo_mtp = Some(mimo_test_mtp_widths(&widths, 1.0));
29931        let ids: Vec<u32> = (0..11).map(|i| (i * 9 + 5) % 64).collect();
29932
29933        let trunk = p.probe_ffn_mass(&ids);
29934        assert!(trunk.iter().all(|v| v.len() == p.intermediate_size));
29935        let got = p.probe_mtp_ffn(&ids).expect("MiMo MTP probe");
29936        assert_eq!(got.len(), widths.len());
29937        for (k, (stat, &width)) in got.iter().zip(&widths).enumerate() {
29938            assert_eq!(stat.mass.len(), width, "draft layer {k}");
29939            assert_eq!(stat.squared_mass.len(), width, "draft layer {k}");
29940            assert_eq!(stat.observed_positions, ids.len() - k - 1);
29941            assert!(stat.mass.iter().any(|&v| v > 0.0), "draft layer {k}");
29942            assert!(stat
29943                .mass
29944                .iter()
29945                .zip(&stat.squared_mass)
29946                .all(|(&m, &s)| m.is_finite() && s.is_finite() && m >= 0.0 && s >= 0.0));
29947        }
29948        assert_eq!(p.kv_cache.seq_len(), 0, "probe leaves a fresh trunk");
29949        let st = p.mimo_mtp.as_ref().unwrap();
29950        assert!(st.layers.iter().all(|m| m.kv.seq_len == 0));
29951
29952        // As above, reject only after a MiMo draft KV has been appended.
29953        // The detached multi-layer owner must still be reset on that error.
29954        let h = p.hidden_size;
29955        let FfnKind::Dense(dense) = &mut p.mimo_mtp.as_mut().unwrap().layers[0].layer.ffn else {
29956            panic!("synthetic MiMo MTP must be dense")
29957        };
29958        dense.segs.push(FfnSeg {
29959            gate: QTensor::from_f32(vec![0.0; h], 1, h),
29960            up: QTensor::from_f32(vec![0.0; h], 1, h),
29961            down: QTensor::from_f32(vec![0.0; h], h, 1),
29962            start: dense.gate_proj.rows(),
29963            width: 1,
29964        });
29965        assert!(p
29966            .probe_mtp_ffn(&ids)
29967            .unwrap_err()
29968            .contains("tube-segmented draft FFNs are not supported"));
29969        assert_eq!(p.kv_cache.seq_len(), 0);
29970        assert!(p
29971            .mimo_mtp
29972            .as_ref()
29973            .unwrap()
29974            .layers
29975            .iter()
29976            .all(|m| m.kv.seq_len == 0));
29977    }
29978
29979    #[test]
29980    fn mimo_mtp_ffn_probe_chunking_preserves_teacher_forced_statistics() {
29981        fn collect(p: &mut Pipeline, ids: &[u32], rows: usize) -> Vec<MtpFfnProbe> {
29982            p.clear_sequence_state();
29983            let mut st = p.mimo_mtp.take().expect("synthetic MiMo draft");
29984            let _exact = ExactMtpCalibrationGuard::enter();
29985            let got = crate::gpu::cpu_scope(|| {
29986                let trunk = p.probe_trunk_rows(ids)?;
29987                p.mimo_mtp_ffn_probe_teacher_forced_with_chunk_rows(&mut st, ids, &trunk, rows)
29988            })
29989            .expect("teacher-forced MiMo probe");
29990            st.reset();
29991            p.mimo_mtp = Some(st);
29992            p.reset_mtp_probe_state();
29993            got
29994        }
29995
29996        for post_norm_hidden in [false, true] {
29997            let ids: Vec<u32> = (0..263u32).map(|i| (i * 17 + 5) % 64).collect();
29998            let make = || {
29999                let mut p = mimo_test_pipeline();
30000                let mut st = mimo_test_mtp_widths(&[7, 13, 29], 1.0);
30001                st.post_norm_hidden = post_norm_hidden;
30002                p.mimo_mtp = Some(st);
30003                p
30004            };
30005            let mut full = make();
30006            let expected = collect(&mut full, &ids, usize::MAX);
30007            for rows in [1usize, 7, 128] {
30008                let mut chunked = make();
30009                let got = collect(&mut chunked, &ids, rows);
30010                assert_eq!(got.len(), expected.len(), "post={post_norm_hidden}, rows={rows}");
30011                for (layer, (got, expected)) in got.iter().zip(&expected).enumerate() {
30012                    assert_eq!(
30013                        got.observed_positions, expected.observed_positions,
30014                        "post={post_norm_hidden}, rows={rows}, layer={layer}"
30015                    );
30016                    assert_eq!(
30017                        got.mass.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
30018                        expected.mass.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
30019                        "post={post_norm_hidden}, rows={rows}, layer={layer} mass"
30020                    );
30021                    assert_eq!(
30022                        got.squared_mass
30023                            .iter()
30024                            .map(|v| v.to_bits())
30025                            .collect::<Vec<_>>(),
30026                        expected
30027                            .squared_mass
30028                            .iter()
30029                            .map(|v| v.to_bits())
30030                            .collect::<Vec<_>>(),
30031                        "post={post_norm_hidden}, rows={rows}, layer={layer} squared mass"
30032                    );
30033                }
30034            }
30035        }
30036    }
30037
30038    /// The draft stack's incremental rounds (a few rows per layer, last
30039    /// round's provisional rows dropped) give exactly the teacher-forced
30040    /// table of one causal pass per layer over the whole sequence — the
30041    /// table `tools/mimo_ref.py mtp` computes for variant A: layer k, row
30042    /// j reads (x[j+k+1], norm(h_j)) at RoPE position j.
30043    #[test]
30044    fn mimo_mtp_incremental_rounds_equal_the_teacher_forced_table() {
30045        // Both readings of the backbone hidden: pre-final-norm (default)
30046        // and post-final-norm (`CMF_MIMO_MTP_HIDDEN=post`).
30047        for post in [false, true] {
30048            let mut p = mimo_test_pipeline();
30049            // A non-trivial final norm, so the two readings differ.
30050            p.weights.final_norm = (0..p.hidden_size).map(|i| 0.5 + 0.1 * i as f32).collect();
30051            let mut st0 = mimo_test_mtp(3, 1.0);
30052            st0.post_norm_hidden = post;
30053            p.mimo_mtp = Some(st0);
30054            let ids: Vec<u32> = (0..14u32).map(|i| (i * 11 + 5) % 64).collect();
30055            let hs = p.hidden_size;
30056            let hb = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
30057            p.mimo_note_rows(&hb, 0);
30058            let mut st = p.mimo_mtp.take().unwrap();
30059            // Incremental: one round per t through the decode path (later
30060            // tokens from `ids`, the probe's teacher forcing).
30061            let k = 3;
30062            let mut inc = Vec::new();
30063            for t in 0..ids.len() - k - 1 {
30064                inc.push(p.mimo_mtp_draft(&mut st, t, &ids, k));
30065            }
30066            // Reference: per layer, ONE batched causal pass over all rows
30067            // with fresh caches.
30068            let s = ids.len();
30069            let mut reference = vec![vec![0u32; k]; s - k - 1];
30070            let mut fresh = mimo_test_mtp(3, 1.0);
30071            for (layer, m) in fresh.layers.iter_mut().enumerate() {
30072                let n = s - layer - 1;
30073                let mut cats = vec![0.0f32; n * 2 * hs];
30074                for j in 0..n {
30075                    let e = p.embed_single(ids[j + layer + 1]);
30076                    let raw = &hb[j * hs..(j + 1) * hs];
30077                    let g = if post {
30078                        inference::rms_norm(raw, &p.weights.final_norm, p.rms_eps, p.norm_style)
30079                    } else {
30080                        raw.to_vec()
30081                    };
30082                    let (ce, ch) = cats[j * 2 * hs..(j + 1) * 2 * hs].split_at_mut(hs);
30083                    inference::rms_norm_into(&e, &m.enorm, p.rms_eps, p.norm_style, ce);
30084                    inference::rms_norm_into(&g, &m.hnorm, p.rms_eps, p.norm_style, ch);
30085                }
30086                let mut x = vec![0.0f32; n * hs];
30087                m.eh_proj.matmat(&cats, n, &mut x, None);
30088                p.mimo_mtp_block(m, &mut x, n, 0);
30089                for (t, row) in reference.iter_mut().enumerate() {
30090                    let y = inference::rms_norm(
30091                        &x[t * hs..(t + 1) * hs],
30092                        &m.final_norm,
30093                        p.rms_eps,
30094                        p.norm_style,
30095                    );
30096                    row[layer] = sampler::argmax(&p.lm_head_forward(&y));
30097                }
30098            }
30099            assert_eq!(inc, reference, "post_norm_hidden = {post}");
30100            // Not a degenerate table: the drafts vary.
30101            let distinct: std::collections::HashSet<u32> = inc.iter().flatten().copied().collect();
30102            assert!(distinct.len() > 3, "{inc:?}");
30103            // Each layer's cache ends holding rows up to the last round start.
30104            let last_t = ids.len() - k - 2;
30105            for m in &st.layers {
30106                assert_eq!(m.kv.seq_len, last_t + 1);
30107            }
30108        }
30109    }
30110
30111    /// Greedy with the MiMo draft stack is the plain greedy stream, token
30112    /// for token — with the real draft layers (low acceptance) and with a
30113    /// drafter that is right most of the time (exercises accepted prefixes
30114    /// of every length, the KV truncation of the rejected rows and the
30115    /// logits hand-off to the loop top), under the default repetition
30116    /// penalty.
30117    #[test]
30118    fn mimo_speculative_greedy_equals_plain_greedy() {
30119        let _env_lock = MTP_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
30120        let _gpu_env = crate::gpu::test_gpu_env("0");
30121        let _env = ScopedTestEnv::set(&[
30122            ("CMF_GPU_WGPU_GRAPH", Some("0")),
30123        ]);
30124        let ids: Vec<u32> = (0..9u32).map(|i| (i * 7 + 3) % 64).collect();
30125        let n = 24;
30126        let mut p = mimo_test_pipeline();
30127        let plain = mimo_greedy(&mut p, &ids, n, false);
30128        assert_eq!(plain.mtp_drafted, 0);
30129        assert_eq!(plain.token_ids.len(), n);
30130        let plain_kv = p.kv_cache.layers[0].seq_len;
30131
30132        // Real draft layers.
30133        p.mimo_mtp = Some(mimo_test_mtp(3, 1.0));
30134        let spec = mimo_greedy(&mut p, &ids, n, true);
30135        assert!(spec.mtp_drafted > 0, "the round must draft");
30136        assert_eq!(spec.token_ids, plain.token_ids);
30137        assert_eq!(p.kv_cache.layers[0].seq_len, plain_kv);
30138
30139        // A drafter reading the true continuation with every fifth token
30140        // wrong: accepted prefixes of 0..=3 all occur.
30141        let mut truth: Vec<u32> = ids.clone();
30142        truth.extend(&plain.token_ids);
30143        let mut noisy = truth.clone();
30144        for (i, t) in noisy.iter_mut().enumerate() {
30145            if i % 5 == 0 {
30146                *t = (*t + 1) % 64;
30147            }
30148        }
30149        let mut st = mimo_test_mtp(3, 1.0);
30150        st.draft_override = Some(noisy);
30151        p.mimo_mtp = Some(st);
30152        let spec = mimo_greedy(&mut p, &ids, n, true);
30153        assert_eq!(spec.token_ids, plain.token_ids);
30154        assert_eq!(p.kv_cache.layers[0].seq_len, plain_kv);
30155        let stats = p.mimo_mtp.as_ref().unwrap().stats.clone();
30156        assert_eq!(stats.accepted as usize, spec.mtp_accepted);
30157        assert!(spec.mtp_accepted > 0 && spec.mtp_accepted < spec.mtp_drafted);
30158        assert!(
30159            stats.accept_hist.iter().filter(|&&c| c > 0).count() >= 3,
30160            "{:?}",
30161            stats.accept_hist
30162        );
30163        assert!(stats.tokens_per_round() > 1.5, "{}", stats.line());
30164
30165        // A perfect drafter: every draft accepted, rounds of K+1 tokens,
30166        // and the budget is never overrun.
30167        let mut st = mimo_test_mtp(3, 1.0);
30168        st.draft_override = Some(truth);
30169        p.mimo_mtp = Some(st);
30170        let spec = mimo_greedy(&mut p, &ids, n, true);
30171        assert_eq!(spec.token_ids, plain.token_ids);
30172        assert_eq!(spec.mtp_accepted, spec.mtp_drafted);
30173        assert_eq!(p.kv_cache.layers[0].seq_len, plain_kv);
30174
30175        // CMF_MTP=0 path: the stack is attached but idle.
30176        let off = mimo_greedy(&mut p, &ids, n, false);
30177        assert_eq!(off.token_ids, plain.token_ids);
30178        assert_eq!(off.mtp_drafted, 0);
30179    }
30180
30181    /// The wgpu graphs carry MiMo-V2's attention per layer (KV heads,
30182    /// narrow V, sinks, windows, two RoPE tables): no attention-level
30183    /// decline for it any more, and the geometry each layer hands the
30184    /// graph is exactly what the CPU attention reads for that layer. The
30185    /// descriptive reasons stay (the Metal graphs and the q1 dropin still
30186    /// decline on them), and what the per-layer geometry cannot express
30187    /// keeps a named wgpu decline.
30188
30189    #[test]
30190    fn mimo_shaped_model_rides_the_wgpu_graph_geometry() {
30191        let p = mimo_test_pipeline();
30192        assert_eq!(
30193            p.graph_attn_decline_reason(),
30194            Some("per-layer KV head counts")
30195        );
30196        assert_eq!(p.wgpu_graph_attn_decline(), None);
30197        let g0 = p.graph_attn_geom(0).expect("full layer geometry");
30198        assert_eq!(
30199            (g0.nkv, g0.dv, g0.rd, g0.window, g0.sink.is_some()),
30200            (1, 4, 4, None, false)
30201        );
30202        assert_eq!(g0.invf, p.inv_freq.as_slice());
30203        let g1 = p.graph_attn_geom(1).expect("sliding layer geometry");
30204        assert_eq!((g1.nkv, g1.dv, g1.rd, g1.window), (2, 4, 4, Some(3)));
30205        assert_eq!(g1.sink, Some(&[0.5f32, -1.0, 1.5, 0.0][..]));
30206        assert_eq!(g1.invf, p.inv_freq_local.as_ref().unwrap().as_slice());
30207        assert_ne!(g0.invf, g1.invf, "two RoPE tables");
30208        let g3 = p.graph_attn_geom(3).expect("full layer geometry");
30209        assert_eq!((g3.nkv, g3.window, g3.sink.is_some()), (1, None, false));
30210
30211        // No wgpu device in this process: the builders run and decline on
30212        // the (f32, unmapped) experts — never with an attention line.
30213        let emb = p.embed_single(3);
30214        let mut lg = Vec::new();
30215        assert!(
30216            p.try_token_graph_wgpu_steps(&emb, 0, &mut lg, 1, None, None, 0, p.num_layers)
30217                .is_none()
30218        );
30219        let mut hid = emb.clone();
30220        assert_eq!(
30221            p.try_batch_graph_wgpu(&mut hid, &[0], 1, None),
30222            crate::gpu::BatchGraphOutcome::Declined
30223        );
30224        assert_eq!(hid, emb, "a declined batch graph leaves the rows untouched");
30225        assert!(p.try_multi_burst(3, 0, 4).is_none());
30226        assert!(
30227            p.graph_declines().is_empty(),
30228            "no attention decline logged: {:?}",
30229            p.graph_declines()
30230        );
30231        // (No assertion on graph_prefill_preferred: with no attention
30232        // decline it follows the device — a test process that brought a
30233        // wgpu adapter up routes this resident MoE through the graph.)
30234
30235        let plain = || create_test_pipeline(8, 16, 2, 1, 4, 2, 32);
30236        assert_eq!(plain().graph_attn_decline_reason(), None);
30237        assert_eq!(plain().wgpu_graph_attn_decline(), None);
30238        assert!(
30239            plain().graph_attn_geom(0).is_none(),
30240            "uniform models keep the historical arms"
30241        );
30242        let mut q = plain();
30243        q.set_layer_sinks(1, vec![0.25, -0.25]).unwrap();
30244        assert_eq!(
30245            q.graph_attn_decline_reason(),
30246            Some("learned attention sinks")
30247        );
30248        assert_eq!(
30249            q.graph_attn_geom(1).unwrap().sink,
30250            Some(&[0.25f32, -0.25][..])
30251        );
30252        let mut q = plain();
30253        q.set_attn_geometry(None, Some(2)).unwrap();
30254        assert_eq!(
30255            q.graph_attn_decline_reason(),
30256            Some("V heads narrower than Q/K heads")
30257        );
30258        assert_eq!(q.graph_attn_geom(0).unwrap().dv, 2);
30259        let mut q = plain();
30260        q.sliding_layers = Some(vec![true, false]);
30261        q.swa = Some((4, usize::MAX));
30262        assert_eq!(q.graph_attn_decline_reason(), Some("sliding-window layers"));
30263        assert_eq!(q.graph_attn_geom(0).unwrap().window, Some(4));
30264        assert_eq!(q.graph_attn_geom(1).unwrap().window, None);
30265
30266        // YaRN's post-rotation amplitude factor rides the per-layer graph
30267        // geometry. It is intentionally not an angular scale folded into
30268        // `invf`: the WGPU RoPE kernel receives it separately.
30269        let mut q = mimo_test_pipeline();
30270        q.rope_scale = 2.0;
30271        q.rope_scale_local = 1.25;
30272        assert_eq!(q.wgpu_graph_attn_decline(), None);
30273        assert_eq!(q.graph_attn_geom(0).unwrap().rope_scale, 2.0);
30274        assert_eq!(q.graph_attn_geom(1).unwrap().rope_scale, 1.25);
30275
30276        // A uniform YaRN model cannot yet pass the factor through the fused
30277        // RKV arm; decline safely instead of producing scale-1 output.
30278        let mut q = plain();
30279        q.rope_scale = 2.0;
30280        assert_eq!(
30281            q.wgpu_graph_attn_decline(),
30282            Some("scaled RoPE without per-layer geometry")
30283        );
30284    }
30285
30286    /// The native q1 attention path has a narrower contract than the WGPU
30287    /// per-layer geometry graph, but it must not discard the exact Flint
30288    /// combination of uniform GQA + sliding windows + learned sinks.  The
30289    /// actual Metal kernel is covered independently with a direct sink
30290    /// softmax test; this is the pure admission test, with no model run.
30291    #[cfg(target_os = "macos")]
30292    #[test]
30293    fn metal_swa_admits_uniform_learned_sinks_for_q1_decode() {
30294        // rd=64 is in the native rope kernel's lane-pair contract; the
30295        // synthetic stack otherwise has the same uniform K/V geometry that
30296        // Flint needs for q1 (unlike the deliberately ragged MiMo fixture).
30297        let mut p = create_test_pipeline(256, 512, 4, 1, 64, 2, 64);
30298        p.swa = Some((16, usize::MAX));
30299        p.sliding_layers = Some(vec![true, true]);
30300        p.set_layer_sinks(0, vec![0.25, -0.5, 1.0, -1.25]).unwrap();
30301        p.set_layer_sinks(1, vec![-0.75, 0.5, 0.0, 1.5]).unwrap();
30302
30303        assert_eq!(
30304            p.graph_attn_decline_reason(),
30305            Some("learned attention sinks")
30306        );
30307        let swa_graph = p.metal_graph_swa();
30308        assert!(swa_graph, "uniform sliding sink geometry must reach q1");
30309        let native_sink_attend = p.graph_attn_decline_reason() == Some("learned attention sinks")
30310            && (swa_graph || (p.swa.is_none() && p.sliding_layers.is_none()));
30311        assert!(
30312            native_sink_attend,
30313            "the q1 sink admission must follow the SWA door"
30314        );
30315        // The batched chunk softmax has no value-less sink column, so its
30316        // separate admission gate must keep this prompt on the host path.
30317        assert!(p.kv_cache.layers.iter().any(|l| l.sinks.is_some()));
30318    }
30319
30320    #[test]
30321    fn mimo_verify_rewind_preserves_lagging_host_caches() {
30322        let mut p = mimo_test_pipeline();
30323        for (li, layer) in p.kv_cache.layers.iter_mut().enumerate() {
30324            let row = vec![0.0; layer.num_kv_heads * layer.head_dim];
30325            for _ in 0..if li == 0 { 2 } else { 12 } {
30326                layer.append(&row, &row, &[]);
30327            }
30328        }
30329        p.mimo_verify_rewind(9).unwrap();
30330        assert_eq!(p.kv_cache.layers[0].seq_len, 2);
30331        for layer in &p.kv_cache.layers[1..] {
30332            assert_eq!(layer.seq_len, 9);
30333        }
30334    }
30335
30336    /// CMF_LAYER_DUMP: the decode walk and the batched prefill both write
30337    /// every (position, layer) hidden, the two sets agree byte for byte,
30338    /// and the last layer's file is the stack output.
30339    #[test]
30340    fn layer_dump_covers_every_position_and_layer_on_both_walks() {
30341        let dir = std::env::temp_dir().join(format!("cmf-layer-dump-{}", std::process::id()));
30342        let _ = std::fs::remove_dir_all(&dir);
30343        let mut p = mimo_test_pipeline();
30344        let hs = p.hidden_size;
30345        let ids = [5u32, 9, 11, 2, 40];
30346        p.layer_dump = Some(dir.join("decode"));
30347        for (pos, &id) in ids.iter().enumerate() {
30348            let e = p.embed_single(id);
30349            let _ = p.forward_layers(&e, pos, None);
30350        }
30351        p.clear_sequence_state();
30352        p.layer_dump = Some(dir.join("prefill"));
30353        let hb = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
30354        for pos in 0..ids.len() {
30355            for li in 0..p.num_layers {
30356                let name = format!("p{pos:06}_l{li:02}.f32");
30357                let a = std::fs::read(dir.join("decode").join(&name)).unwrap();
30358                let b = std::fs::read(dir.join("prefill").join(&name)).unwrap();
30359                assert_eq!(a.len(), hs * 4, "{name}");
30360                assert_eq!(a, b, "{name}");
30361            }
30362        }
30363        let last = std::fs::read(dir.join("prefill").join("p000004_l03.f32")).unwrap();
30364        let vals: Vec<f32> = last
30365            .chunks(4)
30366            .map(|c| f32::from_le_bytes(c.try_into().unwrap()))
30367            .collect();
30368        assert_eq!(f32_bits(&vals), f32_bits(&hb[4 * hs..5 * hs]));
30369        let _ = std::fs::remove_dir_all(&dir);
30370    }
30371
30372    #[test]
30373    fn attn_geometry_and_sinks_are_validated() {
30374        let mut p = create_test_pipeline(8, 16, 4, 2, 4, 2, 32);
30375        assert!(
30376            p.set_attn_geometry(Some(vec![2]), None).is_err(),
30377            "one entry per layer"
30378        );
30379        assert!(
30380            p.set_attn_geometry(Some(vec![2, 3]), None).is_err(),
30381            "3 does not divide 4"
30382        );
30383        assert!(p.set_attn_geometry(Some(vec![2, 0]), None).is_err());
30384        assert!(p.set_attn_geometry(None, Some(0)).is_err());
30385        assert!(
30386            p.set_attn_geometry(None, Some(5)).is_err(),
30387            "V wider than the head"
30388        );
30389        p.set_attn_geometry(None, Some(4)).unwrap();
30390        assert_eq!(
30391            p.v_head_dim, None,
30392            "v_head_dim == head_dim is the uniform case"
30393        );
30394        p.set_layer_sinks(1, vec![0.1; 4]).unwrap();
30395        p.set_attn_geometry(Some(vec![1, 4]), None).unwrap();
30396        assert_eq!(p.kv_cache.layers[0].num_kv_heads, 1);
30397        assert_eq!(p.kv_cache.layers[1].num_kv_heads, 4);
30398        assert!(
30399            p.kv_cache.layers[1].sinks.is_some(),
30400            "a reshape keeps the layer's sinks"
30401        );
30402        assert_eq!(p.layer_geom(1).0, 4);
30403        assert!(
30404            p.set_layer_sinks(0, vec![0.0; 3]).is_err(),
30405            "one sink per Q head"
30406        );
30407        assert!(p.set_layer_sinks(7, vec![0.0; 4]).is_err());
30408        assert!(p.set_layer_sinks(0, vec![f32::NAN, 0.0, 0.0, 0.0]).is_err());
30409    }
30410
30411    /// The O(1) Nyström state replaces a plain full-context softmax; it
30412    /// must never be armed on a sliding, sink or narrow-V layer.
30413    #[test]
30414    fn o1_is_never_armed_on_sink_window_or_narrow_v_layers() {
30415        let cfg = || {
30416            Some(crate::nystrom::O1Cfg {
30417                layers: crate::nystrom::O1Layers::All,
30418                m: 4,
30419                w: 8,
30420                sink: 2,
30421                rect: crate::nystrom::O1Rect::Aggregate,
30422            })
30423        };
30424        let mut p = mimo_test_pipeline();
30425        p.set_o1(cfg());
30426        assert!(!p.o1_active(), "every MiMo-shaped layer is ineligible");
30427        let mut q = create_test_pipeline(8, 16, 2, 1, 4, 3, 64);
30428        q.set_layer_sinks(1, vec![0.0, 0.0]).unwrap();
30429        q.sliding_layers = Some(vec![false, false, true]);
30430        q.swa = Some((4, usize::MAX));
30431        q.set_o1(cfg());
30432        assert_eq!(q.o1_flags, vec![true, false, false]);
30433    }
30434
30435    #[test]
30436    fn o1_batch_transition_publishes_one_epoch_before_serial_handoff() {
30437        const B: usize = 19;
30438        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
30439        p.set_o1(Some(crate::nystrom::O1Cfg {
30440            layers: crate::nystrom::O1Layers::All,
30441            m: 4,
30442            w: 8,
30443            sink: 2,
30444            rect: crate::nystrom::O1Rect::Aggregate,
30445        }));
30446        p.o1_begin_with_prefix(Some(B));
30447        let ids: Vec<u32> = (0..B as u32).collect();
30448        let _ = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
30449
30450        assert_eq!(p.o1_epoch, 1, "all layers publish one completed transition");
30451        assert!(p.kv_cache.layers.iter().all(|l| l.o1_sealed()));
30452        let next = p.embed_single(B as u32);
30453        let _ = p.forward_layers(&next, B, None);
30454        assert_eq!(p.o1_epoch, 1, "sealed handoff must not republish the epoch");
30455    }
30456
30457    /// A turbo file's exact rows are chosen across every far-field layer at the
30458    /// boundary. A batched chunk ending on it used to seal each layer as it
30459    /// finished, before the pipeline could choose, so no row stayed exact on the
30460    /// host path (LFM2 on Metal).
30461    #[test]
30462    fn o1_exact_rows_are_chosen_before_a_batched_boundary_seals() {
30463        const B: usize = 19;
30464        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
30465        let cfg = crate::nystrom::O1Cfg {
30466            layers: crate::nystrom::O1Layers::All,
30467            m: 4,
30468            w: 8,
30469            sink: 2,
30470            rect: crate::nystrom::O1Rect::Aggregate,
30471        };
30472        p.set_o1(Some(cfg.clone()));
30473        p.o1_turbo = Some(O1Turbo {
30474            cfg,
30475            seal: B,
30476            exact: crate::dory::ExactRows { weights: std::sync::Arc::new(vec![1.0; 2 * 2]), budget: 3 },
30477        });
30478        p.o1_begin_with_prefix(Some(B));
30479        let ids: Vec<u32> = (0..B as u32).collect();
30480        let _ = p.prefill_batch_span(PrefillIn::Ids(&ids), 0, None, 0, p.num_layers);
30481        // The span's own completion chooses the rows and seals every layer.
30482        assert!(p.kv_cache.layers.iter().all(|l| l.o1_sealed()));
30483        let keep = p.kv_cache.layers[0].o1_keep.clone();
30484        assert_eq!(keep.len(), 3, "the budget of exact rows is spent");
30485        assert_eq!(keep, p.kv_cache.layers[1].o1_keep, "the same rows in every layer");
30486        assert!(keep.iter().all(|&r| (2..B - 8).contains(&r)), "never a sink or a window row");
30487    }
30488
30489    #[test]
30490    fn o1_pair_transition_commits_scratch_before_epoch_publication() {
30491        const B: usize = 19;
30492        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 2, 260);
30493        // Keep a real recurrent layer ahead of the Full O(1) layer so the
30494        // pair test observes the GDN lane-2 scratch swap at the same
30495        // boundary, rather than only exercising an artificial scratch vec.
30496        let gdn_cfg = crate::linear_core::GdnCfg {
30497            num_v_heads: 2,
30498            num_k_heads: 1,
30499            key_head_dim: 2,
30500            value_head_dim: 4,
30501            conv_kernel: 3,
30502            hidden_size: 8,
30503            rms_eps: 1e-6,
30504            output_gate_sigmoid: false,
30505        };
30506        let synth = |n: usize, salt: usize| -> Vec<f32> {
30507            (0..n)
30508                .map(|i| (((i * 13 + salt * 7) % 97) as f32 / 97.0 - 0.5) * 0.4)
30509                .collect()
30510        };
30511        let qt = |rows: usize, cols: usize, salt: usize| {
30512            crate::qtensor::QTensor::from_f32(synth(rows * cols, salt), rows, cols)
30513        };
30514        let c_dim = gdn_cfg.conv_dim();
30515        let vd = gdn_cfg.num_v_heads * gdn_cfg.value_head_dim;
30516        p.weights.layers[0].attn = AttnKind::LinearGdn(crate::linear_core::GdnWeights {
30517            in_proj_qkv: qt(c_dim, 8, 1),
30518            in_proj_z: qt(vd, 8, 2),
30519            in_proj_a: qt(gdn_cfg.num_v_heads, 8, 3),
30520            in_proj_b: qt(gdn_cfg.num_v_heads, 8, 4),
30521            conv1d: synth(c_dim * gdn_cfg.conv_kernel, 5),
30522            a_log: vec![0.2, 0.5],
30523            dt_bias: synth(gdn_cfg.num_v_heads, 6),
30524            norm: vec![1.0; gdn_cfg.value_head_dim],
30525            out_proj: qt(8, vd, 7),
30526        });
30527        p.gdn_cfg = Some(gdn_cfg);
30528        p.set_o1(Some(crate::nystrom::O1Cfg {
30529            layers: crate::nystrom::O1Layers::All,
30530            m: 4,
30531            w: 8,
30532            sink: 2,
30533            rect: crate::nystrom::O1Rect::Aggregate,
30534        }));
30535        p.o1_begin_with_prefix(Some(B));
30536        for pos in 0..B - 2 {
30537            let emb = p.embed_single(pos as u32);
30538            let _ = p.forward_layers(&emb, pos, None);
30539        }
30540        let lane1_state = p.kv_cache.layers[0].linear_state.clone();
30541
30542        let e1 = p.embed_single((B - 2) as u32);
30543        let e2 = p.embed_single((B - 1) as u32);
30544        let _ = p.forward_pair(&e1, &e2, B - 2);
30545
30546        assert_eq!(p.o1_epoch, 1, "pair crossing B publishes one epoch");
30547        assert!(
30548            p.kv_cache
30549                .layers
30550                .iter()
30551                .enumerate()
30552                .all(|(li, l)| !p.o1_flags[li] || l.o1_sealed())
30553        );
30554        assert!(!p.kv_cache.layers[0].linear_state.is_empty());
30555        assert_ne!(
30556            p.kv_cache.layers[0].linear_state, lane1_state,
30557            "real pair must commit GDN lane 2 before returning"
30558        );
30559        assert!(p.kv_cache.layers[0].linear_scratch.is_empty());
30560        let next = p.embed_single(B as u32);
30561        let _ = p.forward_layers(&next, B, None);
30562        assert_eq!(p.o1_epoch, 1, "serial continuation must reuse the epoch");
30563    }
30564
30565    #[test]
30566    fn o1_error_observation_stays_terminal_until_reset() {
30567        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30568        p.set_o1(Some(crate::nystrom::O1Cfg {
30569            layers: crate::nystrom::O1Layers::All,
30570            m: 4,
30571            w: 8,
30572            sink: 2,
30573            rect: crate::nystrom::O1Rect::Aggregate,
30574        }));
30575        p.o1_begin();
30576        p.kv_cache.layers[0].o1_abort("synthetic transition failure".into());
30577
30578        assert!(p.o1_seal_checked().is_err());
30579        assert!(
30580            p.o1_seal_checked().is_err(),
30581            "retry must see the sticky error"
30582        );
30583        let k = vec![0.2f32; 4];
30584        let v = vec![0.3f32; 4];
30585        p.kv_cache.layers[0].append(&k, &v, &[]);
30586        assert_eq!(p.kv_cache.layers[0].seq_len, 0);
30587
30588        p.reset_session();
30589        p.o1_begin();
30590        p.kv_cache.layers[0].append(&k, &v, &[]);
30591        assert_eq!(p.kv_cache.layers[0].seq_len, 1);
30592    }
30593
30594    #[test]
30595    fn nll_graph_failure_is_terminal_and_request_is_reusable() {
30596        let ids = vec![1u32, 2, 3, 4, 5, 6];
30597        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30598        p.graph_logits = Some(vec![123.0]);
30599        p.graph_want_logits = true;
30600        p.graph_failed
30601            .store(true, std::sync::atomic::Ordering::Relaxed);
30602        p.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
30603        let err = p.nll_ids_from(&ids, 0).expect_err("prior graph failure");
30604        assert!(err.contains("before NLL"));
30605        assert!(p.graph_logits.is_none());
30606        assert!(!p.graph_want_logits);
30607        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
30608        assert!(!p.cancel.load(std::sync::atomic::Ordering::Relaxed));
30609
30610        let mut fresh = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30611        let expected = fresh.nll_ids_from(&ids, 0).expect("fresh NLL");
30612        let actual = p.nll_ids_from(&ids, 0).expect("reused NLL");
30613        assert_eq!(actual.1, expected.1);
30614        assert!((actual.0 - expected.0).abs() < 1e-9);
30615    }
30616
30617    #[test]
30618    fn nll_forward_failure_discards_partial_score_and_clears_sidechannels() {
30619        let ids = vec![1u32, 2, 3, 4, 5, 6];
30620        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30621        p.nll_test_fail_at = Some(1);
30622        let err = p
30623            .nll_ids_from(&ids, 0)
30624            .expect_err("one-shot forward failure");
30625        assert!(err.contains("forward") || err.contains("score row"));
30626        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
30627        assert!(!p.graph_want_logits);
30628        assert!(p.graph_logits.is_none());
30629        assert!(p.kv_history.is_empty());
30630
30631        let mut fresh = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30632        let expected = fresh.nll_ids_from(&ids, 0).expect("fresh NLL");
30633        let actual = p.nll_ids_from(&ids, 0).expect("reused NLL");
30634        assert_eq!(actual.1, expected.1);
30635        assert!((actual.0 - expected.0).abs() < 1e-9);
30636    }
30637
30638    #[test]
30639    fn nll_serial_failure_before_first_row_is_reported() {
30640        let ids = vec![1u32, 2, 3, 4];
30641        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30642        p.nll_test_force_serial = true;
30643        p.nll_test_fail_at = Some(0);
30644        let err = p.nll_ids_from(&ids, 0).expect_err("serial forward failure");
30645        assert!(err.contains("serial forward"));
30646        assert!(p.kv_history.is_empty());
30647        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
30648        assert!(!p.cancel.load(std::sync::atomic::Ordering::Relaxed));
30649    }
30650
30651    #[test]
30652    fn ffn_probe_failure_discards_recorder_and_state() {
30653        let ids = vec![1u32, 2, 3, 4];
30654        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30655        p.nll_test_fail_at = Some(0);
30656        let err = p
30657            .probe_ffn_mass_batch(&ids)
30658            .expect_err("probe forward failure");
30659        assert!(err.contains("NLL"));
30660        assert!(FFN_PROBE.with(|probe| probe.borrow().is_none()));
30661        assert!(p.kv_history.is_empty());
30662        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
30663    }
30664
30665    #[test]
30666    fn nll_test_controls_are_pipeline_scoped() {
30667        let ids = vec![1u32, 2, 3, 4];
30668        let mut failing = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30669        let mut unaffected = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30670        failing.nll_test_force_serial = true;
30671        failing.nll_test_fail_at = Some(0);
30672
30673        assert!(!failing.can_prefill_batched());
30674        assert!(unaffected.can_prefill_batched());
30675        let expected = unaffected
30676            .nll_ids_from(&ids, 0)
30677            .expect("unaffected pipeline remains usable");
30678        let err = failing
30679            .nll_ids_from(&ids, 0)
30680            .expect_err("failure injection belongs to failing pipeline");
30681        assert!(err.contains("serial forward"));
30682        assert!(failing.nll_test_fail_at.is_none());
30683        assert!(unaffected.can_prefill_batched());
30684        let actual = unaffected
30685            .nll_ids_from(&ids, 0)
30686            .expect("unaffected pipeline remains reusable");
30687        assert_eq!(actual.1, expected.1);
30688        assert!((actual.0 - expected.0).abs() < 1e-9);
30689    }
30690
30691    #[test]
30692    fn forward_ids_failure_channel_is_terminal_and_reusable() {
30693        let ids = vec![1u32, 2, 3, 4, 5, 6];
30694        let mut p = create_test_pipeline(8, 16, 2, 1, 4, 1, 64);
30695        p.graph_logits = Some(vec![123.0]);
30696        p.graph_want_logits = true;
30697        p.graph_failed
30698            .store(true, std::sync::atomic::Ordering::Relaxed);
30699        p.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
30700
30701        let err = p
30702            .forward_ids(&ids, None)
30703            .expect_err("a failed forward must not become a valid head result");
30704        assert!(err.contains("forward_ids setup"));
30705        assert!(p.graph_logits.is_none());
30706        assert!(!p.graph_want_logits);
30707        assert!(!p.graph_failed.load(std::sync::atomic::Ordering::Relaxed));
30708        assert!(!p.cancel.load(std::sync::atomic::Ordering::Relaxed));
30709        assert_eq!(p.kv_cache.seq_len(), 0);
30710
30711        let expected = create_test_pipeline(8, 16, 2, 1, 4, 1, 64)
30712            .forward_ids(&ids, None)
30713            .expect("fresh forward_ids");
30714        let actual = p
30715            .forward_ids(&ids, None)
30716            .expect("pipeline remains reusable after a failed forward");
30717        assert_eq!(actual.len(), expected.len());
30718        assert!(
30719            actual
30720                .iter()
30721                .zip(expected)
30722                .all(|(a, b)| (a - b).abs() < 1e-9)
30723        );
30724        assert_eq!(p.kv_cache.seq_len(), ids.len());
30725    }
30726
30727    #[test]
30728    fn sigmoid_router_floor_is_explicit_per_architecture() {
30729        // Flint and MiniMax M3.1 reference runtimes use +1e-20, while the
30730        // generic LFM2-compatible path uses +1e-6. At low (but representable)
30731        // sigmoid scores, silently sharing the latter changes expert weights by
30732        // orders of magnitude and can make a routed layer look coherent while
30733        // discarding its expert contribution.
30734        let zero = || DenseFfn {
30735            gate_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30736            up_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30737            down_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30738            act: Act::Silu,
30739            down_t: None,
30740            segs: Vec::new(),
30741        };
30742        let m = MoeFfn {
30743            router: QTensor::from_f32(vec![0.0; 4], 2, 2),
30744            experts: vec![zero(), zero()],
30745            top_k: 1,
30746            norm_topk_prob: true,
30747            router_sigmoid: true,
30748            sigmoid_denom_eps: 1e-20,
30749            expert_bias: None,
30750            routed_scaling: 2.5,
30751            route_tau: None,
30752            shared: None,
30753            stats: std::cell::RefCell::new(Vec::new()),
30754            act_sq: std::cell::RefCell::new(Vec::new()),
30755            act_rows: std::cell::RefCell::new(Vec::new()),
30756            mask: None,
30757            per_expert_scale: None,
30758            router_input_norm: false,
30759            resonance: None,
30760            grown: Vec::new(),
30761        };
30762        let logits = [-20.0f32, -20.0];
30763        let (_, p, flint_wsum) = moe_route(&logits, &m, None);
30764        let (_, _, minimax_wsum) = moe_route_with_eps(&logits, &m, None, 1e-20);
30765        let (_, _, legacy_wsum) = moe_route_with_eps(&logits, &m, None, 1e-6);
30766        let reference_expected = (p[0] + 1e-20) / m.routed_scaling;
30767        assert!((flint_wsum - reference_expected).abs() < 1e-15);
30768        assert_eq!(minimax_wsum.to_bits(), reference_expected.to_bits());
30769        assert!(legacy_wsum > minimax_wsum * 100.0);
30770    }
30771
30772    #[test]
30773    fn resonance_scores_match_formula_and_stable_tie() {
30774        let r = Resonance {
30775            // Three descriptors, hidden=2, one projection row each.
30776            mu: vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0],
30777            u: vec![1.0, 0.0, 0.0, 1.0, 1.0, 1.0],
30778            k: 1,
30779            bias: vec![1.5, 0.5, 0.0],
30780            shell: Vec::new(),
30781        };
30782        let x = [1.0f32, 1.0];
30783        let mut got = vec![0.0; 3];
30784        r.scores(&x, &mut got);
30785        // Expert 0 and 1 are an exact score tie; the CPU top-1 contract uses
30786        // the lower index.  The values also check d² - (U·d)², not just tie
30787        // ordering.
30788        assert!((got[0] - 0.5).abs() < 1e-6);
30789        assert!((got[1] - 0.5).abs() < 1e-6);
30790        assert!(got[2].abs() < 1e-6);
30791        let best = got
30792            .iter()
30793            .enumerate()
30794            .max_by(|(ia, a), (ib, b)| a.partial_cmp(b).unwrap().then(ib.cmp(ia)))
30795            .map(|(i, _)| i);
30796        assert_eq!(best, Some(0));
30797        assert!(got.iter().all(|v| v.is_finite()));
30798    }
30799
30800    /// The growth shell (spec §2): a grown expert whose reconstruction
30801    /// error lies outside its shell scores −∞, one inside keeps the exact
30802    /// resonance score, trunk rows (`+inf` shell) are bit-identical to the
30803    /// shell-less computation; the process-wide switch disables it.
30804    #[test]
30805    fn resonance_shell_masks_outside_keeps_inside_and_trunk_bits() {
30806        // hidden = 2, rank 1. Experts 0/1 = trunk (shell +inf); 2 and 3 =
30807        // grown, the same descriptor (μ = (0, 1), u = (1, 1)) with shells
30808        // 6.0 and 0.25. At x' = (3, 0): d = (3, −1), d² = 10, proj =
30809        // (3 − 1)² = 4, err = 6 exactly — on the boundary of expert 2's
30810        // shell (kept: the rule is strict `>`), outside expert 3's.
30811        let plain = Resonance {
30812            mu: vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0],
30813            u: vec![1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0],
30814            k: 1,
30815            bias: vec![1.5, 0.5, 0.0, 0.0],
30816            shell: Vec::new(),
30817        };
30818        let shelled = Resonance {
30819            mu: plain.mu.clone(),
30820            u: plain.u.clone(),
30821            k: 1,
30822            bias: plain.bias.clone(),
30823            shell: vec![f32::INFINITY, f32::INFINITY, 6.0, 0.25],
30824        };
30825        assert!(!plain.has_shell());
30826        assert!(shelled.has_shell());
30827        let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
30828        let (mut a, mut b) = (vec![0.0; 4], vec![0.0; 4]);
30829        set_growth_shell(Some(true));
30830        assert!(growth_shell_enabled());
30831        // x = (1, 1): the grown experts reconstruct it exactly (err 0):
30832        // inside both shells, every row the shell-less bits.
30833        let x = [1.0f32, 1.0];
30834        plain.scores(&x, &mut a);
30835        shelled.scores(&x, &mut b);
30836        assert_eq!(bits(&a), bits(&b), "inside every shell: unchanged");
30837        assert!(a[2] == 0.0 && a[3] == 0.0);
30838        // x' = (3, 0): expert 3 → −∞, expert 2 (err == shell) and the
30839        // trunk rows keep their exact bits.
30840        let xo = [3.0f32, 0.0];
30841        plain.scores(&xo, &mut a);
30842        shelled.scores(&xo, &mut b);
30843        assert_eq!(a[2], -6.0);
30844        assert_eq!(a[3], -6.0);
30845        assert_eq!(
30846            bits(&a[..3]),
30847            bits(&b[..3]),
30848            "trunk rows + the boundary row"
30849        );
30850        assert_eq!(b[3], f32::NEG_INFINITY, "outside the shell: −∞");
30851        assert_eq!(shelled.effective_shell(4), shelled.shell);
30852        // The switch (`CMF_GROWTH_SHELL=off` / `growth-eval --shell off`):
30853        // all +inf, the shell-less bits everywhere.
30854        set_growth_shell(Some(false));
30855        assert!(!growth_shell_enabled());
30856        assert_eq!(shelled.effective_shell(4), vec![f32::INFINITY; 4]);
30857        shelled.scores(&xo, &mut b);
30858        assert_eq!(bits(&a), bits(&b));
30859        set_growth_shell(None);
30860        // A shell vector shorter than the expert count masks nothing
30861        // beyond it (a legacy layer whose tail has no shell).
30862        let short = Resonance {
30863            shell: vec![f32::INFINITY, f32::INFINITY],
30864            ..shelled
30865        };
30866        set_growth_shell(Some(true));
30867        short.scores(&xo, &mut b);
30868        assert_eq!(bits(&a), bits(&b));
30869        set_growth_shell(None);
30870    }
30871
30872    /// `moe_route` with −∞ logits (a grown expert outside its shell):
30873    /// top-1 is the best finite expert with weight exactly 1.0 on both
30874    /// the softmax and the sigmoid path; all −∞ degrades to uniform.
30875    #[test]
30876    fn moe_route_neg_inf_logits_pick_the_best_finite_expert_with_weight_one() {
30877        let zero = || DenseFfn {
30878            gate_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30879            up_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30880            down_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
30881            act: Act::Silu,
30882            down_t: None,
30883            segs: Vec::new(),
30884        };
30885        let moe = |sigmoid: bool| MoeFfn {
30886            router: QTensor::from_f32(vec![0.0; 8], 4, 2),
30887            experts: vec![zero(), zero(), zero(), zero()],
30888            top_k: 1,
30889            norm_topk_prob: true,
30890            router_sigmoid: sigmoid,
30891            sigmoid_denom_eps: 1e-6,
30892            expert_bias: None,
30893            routed_scaling: 1.0,
30894            route_tau: None,
30895            shared: None,
30896            stats: std::cell::RefCell::new(Vec::new()),
30897            act_sq: std::cell::RefCell::new(Vec::new()),
30898            act_rows: std::cell::RefCell::new(Vec::new()),
30899            mask: None,
30900            per_expert_scale: None,
30901            router_input_norm: false,
30902            resonance: None,
30903            grown: Vec::new(),
30904        };
30905        let logits = [-1.0f32, f32::NEG_INFINITY, -0.5, f32::NEG_INFINITY];
30906        for sigmoid in [false, true] {
30907            let m = moe(sigmoid);
30908            let (idx, p, wsum) = moe_route(&logits, &m, None);
30909            assert_eq!(idx, vec![2], "sigmoid {sigmoid}");
30910            assert_eq!(p[1], 0.0);
30911            assert_eq!(p[3], 0.0);
30912            assert!(p[2] > p[0] && p[0] > 0.0);
30913            assert!(p.iter().all(|v| v.is_finite()));
30914            let w = p[2] / wsum;
30915            if sigmoid {
30916                // The sigmoid renorm keeps its reference floor (+1e-6).
30917                assert!((w - 1.0).abs() < 1e-5, "sigmoid: weight {w}");
30918            } else {
30919                assert_eq!(
30920                    w, 1.0,
30921                    "softmax: the renormalized top-1 weight is exactly 1"
30922                );
30923            }
30924            // Masked experts stay masked even when they are the only ones
30925            // "admitted" by an allow-list that covers everything.
30926            let (idx, _, _) = moe_route(&logits, &m, Some(&[true, true, true, true]));
30927            assert_eq!(idx, vec![2]);
30928        }
30929        // A finite expert always beats −∞ whatever the bias / order.
30930        let m = moe(false);
30931        let (idx, _, _) = moe_route(
30932            &[
30933                f32::NEG_INFINITY,
30934                f32::NEG_INFINITY,
30935                f32::NEG_INFINITY,
30936                -9.0,
30937            ],
30938            &m,
30939            None,
30940        );
30941        assert_eq!(idx, vec![3]);
30942        // Every expert at −∞ (cannot happen on a grown file — trunk rows
30943        // have no shell): uniform, finite, lowest index.
30944        let (idx, p, wsum) = moe_route(&[f32::NEG_INFINITY; 4], &m, None);
30945        assert_eq!(idx, vec![0]);
30946        assert!(p.iter().all(|&v| v == 0.25));
30947        assert!(wsum.is_finite() && wsum > 0.0);
30948    }
30949
30950    /// MiniMax-M3.1's DEVICE route (the pooled token-graph arm's exact
30951    /// flags: sigmoid scoring via n's high bit, +1e-20 floor,
30952    /// routed_scaling 2.0, selection bias on the CHOICE only) must match
30953    /// the host reference in experts, ORDER and weights — the check that
30954    /// caught the flags/slot collision.
30955    #[cfg(feature = "gpu")]
30956    #[test]
30957    fn minimax_device_route_matches_host_sigmoid_contract() {
30958        match crate::gpu_wgpu::selected_and_up() {
30959            None => {
30960                crate::gpu_wgpu::skip_or_fail(module_path!());
30961                return;
30962            }
30963            // Sibling unit tests in THIS process select wgpu by writing
30964            // `CMF_GPU` (the gpu_wgpu test module does it ~70 times), so on a
30965            // headless runner the variable is already set by the time this
30966            // test reads it — "requested" here is test pollution, not an
30967            // operator's ask, and the adapter genuinely does not exist in
30968            // this process. Same treatment as the gpu_wgpu tests themselves:
30969            // a visible skip, never a silent pass.
30970            Some(false) => {
30971                eprintln!(
30972                    "SKIPPED ({}): CMF_GPU names wgpu but no adapter came up in this process",
30973                    module_path!()
30974                );
30975                return;
30976            }
30977            Some(true) => {}
30978        }
30979        let n = 128usize;
30980        let top_k = 4usize;
30981        let logits: Vec<f32> = (0..n)
30982            .map(|i| ((i as f32 * 0.61).sin() * 3.4) + ((i % 23) as f32 * 0.13))
30983            .collect();
30984        let bias: Vec<f32> = (0..n).map(|i| ((i as f32 * 2.3).cos()) * 0.5).collect();
30985        let m = MoeFfn {
30986            router: QTensor::from_f32(vec![0.0; 4], 2, 2),
30987            experts: Vec::new(),
30988            top_k,
30989            norm_topk_prob: true,
30990            router_sigmoid: true,
30991            sigmoid_denom_eps: 1e-20,
30992            expert_bias: Some(bias.clone()),
30993            routed_scaling: 2.0,
30994            route_tau: None,
30995            shared: None,
30996            stats: std::cell::RefCell::new(Vec::new()),
30997            act_sq: std::cell::RefCell::new(Vec::new()),
30998            act_rows: std::cell::RefCell::new(Vec::new()),
30999            mask: None,
31000            per_expert_scale: None,
31001            router_input_norm: false,
31002            resonance: None,
31003            grown: Vec::new(),
31004        };
31005        let (ci, p, wsum) = moe_route_with_eps(&logits, &m, None, 1e-20);
31006        let cw: Vec<f32> = ci.iter().map(|&e| p[e] / wsum).collect();
31007
31008        for shared in [Some(n as u32), None] {
31009            let mut gi = Vec::new();
31010            let mut gw = Vec::new();
31011            assert!(
31012                crate::gpu_wgpu::minimax_moe_route_for_test(
31013                    &logits,
31014                    Some(&bias),
31015                    top_k,
31016                    2.0,
31017                    shared,
31018                    &mut gi,
31019                    &mut gw,
31020                ),
31021                "the device did not come up — the test checked nothing"
31022            );
31023            let routed = if shared.is_some() { top_k } else { gi.len() };
31024            assert_eq!(
31025                &gi[..routed],
31026                &ci[..],
31027                "different experts or order (shared={shared:?})"
31028            );
31029            let d = cw
31030                .iter()
31031                .zip(&gw[..routed])
31032                .map(|(a, b)| (a - b).abs())
31033                .fold(0.0f32, f32::max);
31034            println!("minimax route shared={shared:?}: {ci:?} max|Δw|={d:.3e}");
31035            assert!(d < 1e-6, "the weights diverged by {d:.3e}");
31036            if let Some(s) = shared {
31037                assert_eq!(gi[top_k], s as usize, "shared pin slot");
31038                assert_eq!(gw[top_k], 1.0, "shared weight");
31039            }
31040        }
31041    }
31042
31043    /// The pooled arm's COLD hand-back: `(expert, weight)` pairs for the
31044    /// picks the bank could not serve must carry the host's EXACT final
31045    /// weights — the device ships its resident sum, the host adds this on
31046    /// top of the same residual, so a weight drift compounds per layer.
31047    #[cfg(feature = "gpu")]
31048    #[test]
31049    fn minimax_device_cold_weights_match_host_contract() {
31050        match crate::gpu_wgpu::selected_and_up() {
31051            None => {
31052                crate::gpu_wgpu::skip_or_fail(module_path!());
31053                return;
31054            }
31055            // Sibling unit tests in THIS process select wgpu by writing
31056            // `CMF_GPU` (the gpu_wgpu test module does it ~70 times), so on a
31057            // headless runner the variable is already set by the time this
31058            // test reads it — "requested" here is test pollution, not an
31059            // operator's ask, and the adapter genuinely does not exist in
31060            // this process. Same treatment as the gpu_wgpu tests themselves:
31061            // a visible skip, never a silent pass.
31062            Some(false) => {
31063                eprintln!(
31064                    "SKIPPED ({}): CMF_GPU names wgpu but no adapter came up in this process",
31065                    module_path!()
31066                );
31067                return;
31068            }
31069            Some(true) => {}
31070        }
31071        let n = 128usize;
31072        let top_k = 4usize;
31073        let logits: Vec<f32> = (0..n)
31074            .map(|i| ((i as f32 * 0.61).sin() * 3.4) + ((i % 23) as f32 * 0.13))
31075            .collect();
31076        let bias: Vec<f32> = (0..n).map(|i| ((i as f32 * 2.3).cos()) * 0.5).collect();
31077        let m = MoeFfn {
31078            router: QTensor::from_f32(vec![0.0; 4], 2, 2),
31079            experts: Vec::new(),
31080            top_k,
31081            norm_topk_prob: true,
31082            router_sigmoid: true,
31083            sigmoid_denom_eps: 1e-20,
31084            expert_bias: Some(bias.clone()),
31085            routed_scaling: 2.0,
31086            route_tau: None,
31087            shared: None,
31088            stats: std::cell::RefCell::new(Vec::new()),
31089            act_sq: std::cell::RefCell::new(Vec::new()),
31090            act_rows: std::cell::RefCell::new(Vec::new()),
31091            mask: None,
31092            per_expert_scale: None,
31093            router_input_norm: false,
31094            resonance: None,
31095            grown: Vec::new(),
31096        };
31097        let (ci, p, wsum) = moe_route_with_eps(&logits, &m, None, 1e-20);
31098        assert_eq!(ci.len(), top_k);
31099
31100        // Every pick resident → no cold pairs at all.
31101        let resident: Vec<u32> = (0..n).map(|e| e as u32).collect();
31102        let mut cold = Vec::new();
31103        let mut idx = Vec::new();
31104        let mut dw = Vec::new();
31105        assert!(crate::gpu_wgpu::minimax_moe_route_cold_for_test(
31106            &logits,
31107            Some(&bias),
31108            top_k,
31109            2.0,
31110            &resident,
31111            n as u32,
31112            &mut cold,
31113            &mut idx,
31114            &mut dw,
31115        ));
31116        assert!(cold.is_empty(), "fully resident bank: {cold:?}");
31117        // With subset+pin together: routed slots carry the FLAT remap value
31118        // (here identity = the expert id), weights the host contract, and
31119        // the pinned shared keeps weight 1 — this exact combination is what
31120        // the pooled arm runs with.
31121        for (r, &e) in ci.iter().enumerate() {
31122            assert_eq!(idx[r] as usize, e, "resident slot mapping r={r}");
31123            let host = p[e] / wsum;
31124            let d = (dw[r] - host).abs();
31125            assert!(
31126                d <= 1e-6 * host.abs().max(1.0),
31127                "resident weight r={r} expert {e}: device={:.9e} host={host:.9e}",
31128                dw[r]
31129            );
31130        }
31131        assert_eq!(idx[top_k] as usize, n, "shared pin slot");
31132        assert_eq!(dw[top_k], 1.0, "shared weight");
31133
31134        // Make exactly two of the CHOSEN picks cold.
31135        let mut remap = resident.clone();
31136        remap[ci[0]] = u32::MAX;
31137        remap[ci[2]] = u32::MAX;
31138        let mut cold = Vec::new();
31139        let mut idx2 = Vec::new();
31140        let mut dw2 = Vec::new();
31141        assert!(crate::gpu_wgpu::minimax_moe_route_cold_for_test(
31142            &logits,
31143            Some(&bias),
31144            top_k,
31145            2.0,
31146            &remap,
31147            n as u32,
31148            &mut cold,
31149            &mut idx2,
31150            &mut dw2,
31151        ));
31152        // The resident picks of the partial bank still carry exact weights.
31153        // A COLD rank is a placeholder the device writes as slot 0 / weight
31154        // 0.0 — its real (id, weight) pair rides in `cold` — so weight zero
31155        // is what marks it, not the slot value: reading the placeholder as
31156        // a resident expert compared 0.0 against p[0]/wsum and failed with
31157        // Δ=2.552e-1. The test logits keep every sigmoid score strictly
31158        // positive, so a resident pick can never weigh exactly zero.
31159        let mut resident_weight_checked = 0usize;
31160        for (r, &slot) in idx2.iter().enumerate().take(top_k) {
31161            if dw2[r] == 0.0 {
31162                continue; // cold rank: placeholder, not an expert id
31163            }
31164            let e = slot as usize;
31165            assert!(e < n && remap[e] != u32::MAX, "resident slot {e} escaped the remap");
31166            let host = p[e] / wsum;
31167            let d = (dw2[r] - host).abs();
31168            assert!(
31169                d <= 1e-6 * host.abs().max(1.0),
31170                "partial-bank resident weight expert {e}: Δ={d:.3e}"
31171            );
31172            resident_weight_checked += 1;
31173        }
31174        assert_eq!(resident_weight_checked, 2, "exactly two resident peaks out of four");
31175        println!("partial bank: checked {resident_weight_checked} resident weights");
31176        assert_eq!(dw2.get(top_k).copied(), Some(1.0), "shared weight under subset");
31177        let mut ids: Vec<usize> = cold.iter().map(|&(e, _)| e).collect();
31178        ids.sort_unstable();
31179        let mut want = vec![ci[0], ci[2]];
31180        want.sort_unstable();
31181        assert_eq!(ids, want, "the cold experts diverged: {cold:?} versus {want:?}");
31182        for &(e, w) in &cold {
31183            let host = p[e] / wsum;
31184            let d = (w - host).abs();
31185            println!("cold expert {e}: device={w:.9e} host={host:.9e} Δ={d:.3e}");
31186            assert!(d <= 1e-6 * host.abs().max(1.0), "cold weight of expert {e}: Δ={d:.3e}");
31187        }
31188    }
31189
31190    /// The resonance router (top-1) selects by the raw score as the
31191    /// trainer and the graph do — not by softmax probabilities, where two
31192    /// scores closer than 2^-25 collapse to the same `exp(l − max) = 1.0`
31193    /// and the LOWER index wins a token whose score is strictly smaller.
31194    #[test]
31195    fn resonance_route_picks_the_raw_argmax_not_the_softmax_tie() {
31196        let zero = || DenseFfn {
31197            gate_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
31198            up_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
31199            down_proj: QTensor::from_f32(vec![0.0; 4], 2, 2),
31200            act: Act::Silu,
31201            down_t: None,
31202            segs: Vec::new(),
31203        };
31204        let moe = |resonant: bool, norm_topk: bool| MoeFfn {
31205            router: QTensor::from_f32(vec![0.0; 6], 3, 2),
31206            experts: vec![zero(), zero(), zero()],
31207            top_k: 1,
31208            norm_topk_prob: norm_topk,
31209            router_sigmoid: false,
31210            sigmoid_denom_eps: 1e-6,
31211            expert_bias: None,
31212            routed_scaling: 1.0,
31213            route_tau: None,
31214            shared: None,
31215            stats: std::cell::RefCell::new(Vec::new()),
31216            act_sq: std::cell::RefCell::new(Vec::new()),
31217            act_rows: std::cell::RefCell::new(Vec::new()),
31218            mask: None,
31219            per_expert_scale: None,
31220            router_input_norm: false,
31221            resonance: resonant.then(|| Resonance {
31222                mu: vec![0.0; 6],
31223                u: Vec::new(),
31224                k: 0,
31225                bias: vec![0.0; 3],
31226                shell: Vec::new(),
31227            }),
31228            grown: Vec::new(),
31229        };
31230        // lo = −0.1, hi = the next f32 towards zero: hi − lo = 2^-27 <
31231        // 2^-25, so exp(lo − hi) rounds to exactly 1.0 — a softmax tie.
31232        let lo = -0.1f32;
31233        let hi = f32::from_bits(lo.to_bits() - 1);
31234        assert!(hi > lo && hi - lo < 2f32.powi(-25));
31235        assert_eq!((lo - hi).exp(), 1.0, "the tie this test is about");
31236        // The gated MoE (softmax) path: the tie hands the token to index 0.
31237        let (idx, _, _) = moe_route(&[lo, hi], &moe(false, true), None);
31238        assert_eq!(
31239            idx,
31240            vec![0],
31241            "softmax tie → lower index (the gated contract)"
31242        );
31243        // The resonance path: the strictly larger raw score wins, weight
31244        // exactly 1.0 with and without norm_topk.
31245        for norm in [true, false] {
31246            let m = moe(true, norm);
31247            let (idx, p, wsum) = moe_route(&[lo, hi, f32::NEG_INFINITY], &m, None);
31248            assert_eq!(idx, vec![1], "norm_topk {norm}");
31249            assert_eq!(p, vec![0.0, 1.0, 0.0]);
31250            assert_eq!(p[1] / wsum, 1.0);
31251            // An exact tie: the first maximum (as `resonance_winner` and
31252            // `embryo_core_route_pick`).
31253            let (idx, _, _) = moe_route(&[hi, hi, lo], &m, None);
31254            assert_eq!(idx, vec![0]);
31255            // `−∞` never wins; the admitted set is honoured.
31256            let (idx, _, _) = moe_route(&[f32::NEG_INFINITY, lo, hi], &m, None);
31257            assert_eq!(idx, vec![2]);
31258            let (idx, p, wsum) = moe_route(&[lo, hi, hi], &m, Some(&[true, false, false]));
31259            assert_eq!(idx, vec![0]);
31260            assert_eq!(p[0] / wsum, 1.0);
31261            // Every admitted expert at −∞: the generic path's uniform
31262            // fallback (lowest index, finite weights).
31263            let (idx, p, wsum) = moe_route(&[f32::NEG_INFINITY; 3], &m, None);
31264            assert_eq!(idx, vec![0]);
31265            assert!(p.iter().all(|v| v.is_finite()) && wsum.is_finite() && wsum > 0.0);
31266        }
31267    }
31268}