Skip to main content

ferrox_models/
decoder.rs

1//! Generic decoder-only transformer forward pass, assembled from a
2//! ModelConfig. Each layer is: RMSNorm -> GQA attention (+RoPE) ->
3//! residual -> RMSNorm -> MoE FFN (router + routed experts + shared
4//! experts) -> residual. This is the standard decoder block shape
5//! shared by the LLaMA/DeepSeek/GLM/Kimi family of open-weight models.
6//!
7//! Weight loading from a real GGUF checkpoint lives in `loader`
8//! (`Decoder::from_gguf`); `Decoder::new_random` builds
9//! correctly-shaped, randomly initialized weights so the full pipeline
10//! -- embedding lookup, N decoder layers, output head -- can be
11//! exercised end to end with real assertions about shapes, finiteness,
12//! and determinism, without requiring a multi-hundred-gigabyte
13//! checkpoint to be present.
14
15mod attn_block;
16mod ffn_act;
17pub mod kv_window;
18mod lm_head;
19mod qk_norm;
20mod rope;
21
22use std::sync::atomic::{AtomicU64, Ordering};
23
24pub(crate) use attn_block::KvStep;
25use ferrox_core::attention::{
26    causal_gqa_attention_prefill_shared_kv_windowed, causal_gqa_attention_softcap,
27};
28use ferrox_core::cache::{KvCache, PagedKvCache, PagedStoreExhausted, SharedPagedKv};
29use ferrox_core::matmul::rms_norm;
30pub use kv_window::{KvWindowPolicy, KV_WINDOW_ENV};
31#[cfg(feature = "metal")]
32use lm_head::FoldedLmHead;
33use lm_head::Logits;
34use rayon::prelude::*;
35
36/// Whether the CUDA `gqa_decode` kernel should serve the per-token GQA
37/// reduction (`FERROX_CUDA_GQA=1`). Off by default and only compiled with
38/// `--features cuda`; the host path is byte-identical when unset.
39#[cfg(feature = "cuda")]
40fn cuda_gqa_enabled() -> bool {
41    use std::sync::OnceLock;
42    static ENABLED: OnceLock<bool> = OnceLock::new();
43    *ENABLED.get_or_init(|| {
44        matches!(
45            std::env::var("FERROX_CUDA_GQA").ok().as_deref(),
46            Some("1") | Some("true") | Some("on")
47        )
48    })
49}
50use ferrox_core::tensor::Tensor;
51use ferrox_core::weight_matrix::WeightMatrix;
52use ferrox_moe::{
53    combine_expert_outputs, route_top_k, run_expert, run_expert_placed, ExpertPlacement,
54    ExpertWeights, GluAct, PlacementPlan,
55};
56
57use crate::config::ModelConfig;
58
59pub struct AttnWeights {
60    pub q_proj: WeightMatrix, // [n_heads*head_dim, hidden_dim]
61    pub k_proj: WeightMatrix, // [n_kv_heads*head_dim, hidden_dim]
62    pub v_proj: WeightMatrix, // [n_kv_heads*head_dim, hidden_dim]
63    pub o_proj: WeightMatrix, // [hidden_dim, n_heads*head_dim]
64    pub norm_weight: Vec<f32>,
65    /// OLMoE-style QK-RMSNorm (`attn_q_norm`/`attn_k_norm` GGUF tensors),
66    /// applied to the *whole* q_proj/k_proj output (width `n_heads*head_dim`
67    /// / `n_kv_heads*head_dim`) before RoPE -- confirmed against
68    /// `OlmoeAttention.forward` in `transformers/models/olmoe/modeling_olmoe.py`
69    /// (`q_norm(q_proj(x))`, `k_norm(k_proj(x))`, both plain whole-vector
70    /// RMSNorm, not per-head). `None` for every model that doesn't ship
71    /// these tensors -- absent, not zero/identity-weighted, so existing
72    /// presets/fixtures are byte-for-byte unaffected.
73    ///
74    /// Qwen3 / Gemma3 ship the same tensor names with length `head_dim`
75    /// (per-head). Which style is used is selected by
76    /// [`ModelConfig::qk_norm_style`] (refined at load from weight length).
77    pub q_norm: Option<Vec<f32>>,
78    pub k_norm: Option<Vec<f32>>,
79    /// Qwen2/Qwen2-MoE-family QKV attention bias (`attn_{q,k,v}.bias`
80    /// GGUF tensors, real `config.qkv_bias`), added elementwise to the
81    /// corresponding projection's output before QK-norm/RoPE -- confirmed
82    /// against the real `transformers` source
83    /// (`Qwen2MoeAttention.__init__`: `q_proj = nn.Linear(..., bias=
84    /// config.qkv_bias)`, same for `k_proj`/`v_proj`; `o_proj` has no
85    /// bias). Found as a real, previously-unhandled architecture gap:
86    /// ferrox's generic GGUF loader silently ignored these real tensors
87    /// entirely, producing fluent-but-wrong output on a real downloaded
88    /// Qwen1.5-MoE checkpoint (same failure class as OLMoE's missing
89    /// QK-norm). `None` for every model that doesn't ship these tensors.
90    pub q_bias: Option<Vec<f32>>,
91    pub k_bias: Option<Vec<f32>>,
92    pub v_bias: Option<Vec<f32>>,
93    /// Gemma 2+/3 post-attention RMSNorm (`blk.N.post_attention_norm.weight`
94    /// / llama.cpp `attn_post_norm`). Applied to attention output before
95    /// the residual add. `None` for Llama/Qwen/OLMoE.
96    pub post_attn_norm: Option<Vec<f32>>,
97    /// Gemma 2+/3 post-FFN RMSNorm (`blk.N.post_ffw_norm.weight`).
98    pub post_ffn_norm: Option<Vec<f32>>,
99}
100
101/// How a layer's routed experts are held. `Resident` is the original
102/// always-in-memory form (owned f32 or zero-copy mmap views).
103/// `Stored` holds only byte-range layouts; each use acquires the
104/// expert's bytes from a bounded, lease-protected
105/// `ferrox_core::expert_store::ExpertStore` shared by every layer
106/// (one global byte budget), builds temporary `WeightMatrix` views
107/// over the leased buffer (`WeightBytes::Shared`, which pins the
108/// cache entry for the views' lifetime), and drops them after the
109/// expert runs. Dequantized math over identical bytes is identical,
110/// so the two backings are bit-equivalent by construction -- pinned
111/// by an integration test against the MoE fixture.
112pub enum ExpertBacking {
113    Resident(Vec<ExpertWeights>),
114    Stored {
115        store:
116            std::sync::Arc<ferrox_core::expert_store::ExpertStore<crate::loader::GgufExpertSource>>,
117        layouts: Vec<crate::loader::StoredExpertLayout>,
118        layer: u32,
119    },
120}
121
122impl ExpertBacking {
123    pub fn n_experts(&self) -> usize {
124        match self {
125            ExpertBacking::Resident(v) => v.len(),
126            ExpertBacking::Stored { layouts, .. } => layouts.len(),
127        }
128    }
129}
130
131pub struct MoeWeights {
132    pub router: WeightMatrix, // [n_experts, hidden_dim]
133    pub experts: ExpertBacking,
134    pub shared_experts: Vec<ExpertWeights>,
135    /// Qwen2-MoE-specific: when present, the shared experts' combined
136    /// output is scaled by `sigmoid(shared_expert_gate . x)` before
137    /// being added to the routed output, instead of added unconditionally
138    /// -- confirmed against the real `transformers` source
139    /// (`Qwen2MoeSparseMoeBlock.forward`: `shared_expert_output =
140    /// F.sigmoid(self.shared_expert_gate(hidden_states)) *
141    /// shared_expert_output`) and llama.cpp's real `qwen2moe.cpp`
142    /// (`ffn_gate_inp_shexp` dotted against the hidden state, sigmoid,
143    /// multiplied into the shared-expert branch before the final add).
144    /// Real on-disk shape is `[hidden_dim]` (a `Linear(hidden_dim, 1,
145    /// bias=false)`'s weight, flattened -- ggml's real `create_tensor`
146    /// call declares it as `{n_embd}`, not a 2D matrix), so this is a
147    /// plain owned vector dotted with the normed hidden state directly,
148    /// not a `WeightMatrix`. `None` for every other architecture
149    /// (DeepSeek-V3's shared experts, for one real confirmed contrast,
150    /// add unconditionally with no gate at all).
151    pub shared_expert_gate: Option<Vec<f32>>,
152    pub norm_weight: Vec<f32>,
153    /// DeepSeek-V3's aux-loss-free expert-selection bias, on disk as
154    /// `blk.{N}.exp_probs_b.bias` (llama.cpp's `LLM_TENSOR_FFN_EXP_PROBS_B`
155    /// -- note the on-disk name has no `ffn_` prefix, `llama-arch.cpp:416`).
156    /// It is added to the *selection* score only: the top-k is taken over
157    /// `gating(logit) + bias[expert]`, while each winner's combine weight
158    /// comes from the unbiased `gating(logit)`
159    /// (`build_moe_ffn`: "leave probs unbiased as it's later used to get
160    /// expert weights"). Biasing the weight too would silently skew every
161    /// routed contribution away from what the router learned.
162    ///
163    /// `None` for every checkpoint that does not ship the tensor. When it
164    /// *is* present, the GPU MoE fast paths refuse the layer rather than
165    /// route without it -- their kernels have no bias input.
166    pub exp_probs_bias: Option<Vec<f32>>,
167    /// How many times each routed expert (index into `experts`) has been
168    /// selected by `route_top_k` across every `forward_token`/
169    /// `forward_batch` call so far. Real observed hotness, not a
170    /// placeholder -- feeds `placement_plan` below, which is what
171    /// `PlacementPlan::from_budget` needs to prioritize actually-hot
172    /// experts for GPU residency instead of guessing by index.
173    pub activation_counts: Vec<AtomicU64>,
174    /// Verified-at-load contiguous expert planes for Metal MoE
175    /// (`mul_mm_sg` gather/id). Built in `loader` when every routed expert
176    /// is mmap-backed with a simdgroup-GEMM quant (Q4_0 / Q4_K / Q8_0 / …)
177    /// and back-to-back gate/up/down slices. Gate/up/down kinds may differ
178    /// (Qwen1.5-MoE: Q4_K gate/up + Q8_0 down). `None` for store-backed,
179    /// F32, or non-contiguous layouts.
180    #[cfg(feature = "metal")]
181    pub packed_q4: Option<MoePackedQ4Planes>,
182}
183
184/// Load-time validated contiguous expert tensor planes (any `mul_mm_sg` quant).
185#[cfg(feature = "metal")]
186pub struct MoePackedQ4Planes {
187    gate: ferrox_core::weight_matrix::WeightBytes,
188    up: ferrox_core::weight_matrix::WeightBytes,
189    down: ferrox_core::weight_matrix::WeightBytes,
190    gate_stride: usize,
191    up_stride: usize,
192    down_stride: usize,
193    n_experts: usize,
194    ffn_rows: usize,
195    hidden_rows: usize,
196    gate_row_bytes: usize,
197    down_row_bytes: usize,
198    gate_kind: &'static str,
199    up_kind: &'static str,
200    down_kind: &'static str,
201}
202
203#[cfg(feature = "metal")]
204impl MoePackedQ4Planes {
205    #[allow(clippy::too_many_arguments)]
206    pub(crate) fn new(
207        gate: ferrox_core::weight_matrix::WeightBytes,
208        up: ferrox_core::weight_matrix::WeightBytes,
209        down: ferrox_core::weight_matrix::WeightBytes,
210        gate_stride: usize,
211        up_stride: usize,
212        down_stride: usize,
213        n_experts: usize,
214        ffn_rows: usize,
215        hidden_rows: usize,
216        gate_kind: &'static str,
217        up_kind: &'static str,
218        down_kind: &'static str,
219    ) -> Self {
220        Self {
221            gate,
222            up,
223            down,
224            gate_stride,
225            up_stride,
226            down_stride,
227            n_experts,
228            ffn_rows,
229            hidden_rows,
230            gate_row_bytes: gate_stride / ffn_rows,
231            down_row_bytes: down_stride / hidden_rows,
232            gate_kind,
233            up_kind,
234            down_kind,
235        }
236    }
237
238    pub fn view(&self) -> ferrox_metal::gpu::MoePackedQ4<'_> {
239        ferrox_metal::gpu::MoePackedQ4 {
240            gate: self.gate.as_slice(),
241            up: self.up.as_slice(),
242            down: self.down.as_slice(),
243            gate_stride: self.gate_stride,
244            up_stride: self.up_stride,
245            down_stride: self.down_stride,
246            n_experts: self.n_experts,
247            ffn_rows: self.ffn_rows,
248            hidden_rows: self.hidden_rows,
249            gate_row_bytes: self.gate_row_bytes,
250            down_row_bytes: self.down_row_bytes,
251            gate_kind: self.gate_kind,
252            up_kind: self.up_kind,
253            down_kind: self.down_kind,
254        }
255    }
256}
257
258impl MoeWeights {
259    pub fn n_experts(&self) -> usize {
260        self.experts.n_experts()
261    }
262
263    /// This routed expert's weight byte footprint, from resident
264    /// matrices or the stored layout -- identical numbers either way,
265    /// so residency planning is backing-independent.
266    pub fn expert_bytes(&self, e: usize) -> usize {
267        match &self.experts {
268            ExpertBacking::Resident(v) => {
269                let ex = &v[e];
270                ex.gate.resident_bytes() + ex.up.resident_bytes() + ex.down.resident_bytes()
271            }
272            ExpertBacking::Stored { layouts, .. } => layouts[e].total_bytes(),
273        }
274    }
275
276    /// Runs `f` against expert `e`'s weights, materializing them from
277    /// the store first when this layer is store-backed. The lease (and
278    /// therefore the cache entry's pin) lives exactly as long as `f`'s
279    /// borrow.
280    pub fn with_expert<R>(&self, e: usize, f: impl FnOnce(&ExpertWeights) -> R) -> R {
281        match &self.experts {
282            ExpertBacking::Resident(v) => f(&v[e]),
283            ExpertBacking::Stored {
284                store,
285                layouts,
286                layer,
287            } => {
288                let lease = store
289                    .acquire(ferrox_core::expert_store::ExpertKey {
290                        layer: *layer,
291                        expert: e as u32,
292                    })
293                    .unwrap_or_else(|err| {
294                        panic!(
295                            "expert store read failed for layer {layer} expert {e}: {err} \
296                             (checkpoint file unreadable mid-decode)"
297                        )
298                    });
299                let tmp = layouts[e].materialize(&lease);
300                f(&tmp)
301            }
302        }
303    }
304
305    fn record_activations(&self, expert_ids: &[usize]) {
306        for &eid in expert_ids {
307            if let Some(counter) = self.activation_counts.get(eid) {
308                counter.fetch_add(1, Ordering::Relaxed);
309            }
310        }
311    }
312
313    /// A real VRAM-budget-and-hotness-driven placement plan for this
314    /// layer's routed experts, built from each expert's actual resident
315    /// byte size (`WeightMatrix::resident_bytes()` summed across its
316    /// gate/up/down matrices, so it reflects the real quantization
317    /// format in use, not an estimate) and the activation counts
318    /// observed so far. See `ferrox_moe::PlacementPlan::from_budget`.
319    pub fn placement_plan(&self, vram_budget_bytes: u64) -> PlacementPlan {
320        let sizes: Vec<usize> = (0..self.n_experts())
321            .map(|e| self.expert_bytes(e))
322            .collect();
323        let counts: Vec<u64> = self
324            .activation_counts
325            .iter()
326            .map(|c| c.load(Ordering::Relaxed))
327            .collect();
328        let has_observations = counts.iter().any(|&c| c > 0);
329        PlacementPlan::from_budget(
330            &sizes,
331            has_observations.then_some(counts.as_slice()),
332            vram_budget_bytes,
333        )
334    }
335}
336
337pub struct LayerWeights {
338    pub attn: AttnWeights,
339    pub moe: MoeWeights,
340}
341
342/// The per-layer weights the gpt-oss graph carries and the generic GQA
343/// layer structs do not.
344///
345/// Held as a side table on [`Decoder`] rather than as new `Option`
346/// fields on [`AttnWeights`]/[`MoeWeights`] for two reasons. The first
347/// is mechanical: those two structs have thirty construction sites
348/// across seven loaders and every dedicated engine, and none of them
349/// will ever set these. The second is the point of the exercise — a
350/// checkpoint either has the whole gpt-oss graph or none of it, so
351/// `Decoder::gpt_oss.is_some()` is a single, checkable predicate for
352/// "this model needs the gpt-oss path", which is what the CPU-only and
353/// paged-attention refusals below key off. Scattering five independent
354/// `Option`s would make "half the graph is wired" representable, and
355/// that state is precisely the silent-wrong-answer bug this work exists
356/// to remove.
357pub struct GptOssLayer {
358    /// `blk.N.attn_sinks.weight`, one learned logit per query head.
359    pub attn_sinks: Vec<f32>,
360    /// `blk.N.attn_output.bias`, added after the output projection.
361    pub o_bias: Vec<f32>,
362    /// `blk.N.ffn_gate_inp.bias`, added to the router logits.
363    pub router_bias: Vec<f32>,
364    /// `blk.N.ffn_{gate,up,down}_exps.bias`, one entry per expert.
365    pub expert_bias: Vec<ferrox_moe::ExpertBias>,
366}
367
368/// gpt-oss side table: one entry per layer, in layer order.
369pub struct GptOssWeights {
370    pub layers: Vec<GptOssLayer>,
371}
372
373pub struct Decoder {
374    pub config: ModelConfig,
375    /// `[vocab_size, hidden_dim]`. A `WeightMatrix` rather than an
376    /// eagerly-widened f32 `Tensor`, so a quantized `token_embd.weight`
377    /// stays quantized on disk/mmap and token lookup dequantizes one
378    /// row at a time (`WeightMatrix::dequant_row`) -- a large-vocab
379    /// model's embedding table is multi-GB in f32 and only ever read
380    /// row-wise.
381    pub embedding: WeightMatrix,
382    pub layers: Vec<LayerWeights>,
383    pub final_norm: Vec<f32>,
384    pub output_head: WeightMatrix, // [vocab_size, hidden_dim]
385    /// Real VRAM budget for GPU-resident routed experts.
386    /// `None` (both constructors below
387    /// set it) means every expert always runs on CPU -- the exact
388    /// behavior this field's absence had before it existed. `Some(bytes)`
389    /// makes each forward call build ONE global `ResidencyPlan`
390    /// (`Decoder::residency_plan`) across every layer's actual
391    /// resident expert sizes and observed activation counts against
392    /// this single budget -- the budget is never re-spent per layer --
393    /// dispatching device-placed routed experts through
394    /// `ferrox_moe::run_expert_placed` (a real CUDA kernel when the
395    /// `cuda` feature is compiled in and the expert's quant kind has
396    /// one; a correct CPU fallback otherwise, so setting this on a
397    /// non-`cuda` build is harmless, just never GPU-accelerated).
398    /// Shared experts and a dense layer's sole expert always run on
399    /// CPU regardless -- every token activates them, so there's no
400    /// routing decision to offload the way routed-expert placement is.
401    /// Rebuilding the plan on every forward call is real but not yet
402    /// performance-tuned; a real, disclosed limit, not a correctness
403    /// gap.
404    pub gpu_vram_budget_bytes: Option<u64>,
405    /// `Some` only for the gpt-oss family. See [`GptOssWeights`]. When
406    /// set, every layer runs the gpt-oss CPU graph (attention sinks,
407    /// alternating SWA, biased router + experts, `swiglu_oai`), GPU
408    /// offload is refused at load time, and the paged-KV decode path is
409    /// refused at call time — neither implements sinks, and answering
410    /// with a different distribution is the failure this replaces.
411    pub gpt_oss: Option<GptOssWeights>,
412    /// Does this architecture norm Q and K AFTER RoPE rather than
413    /// before? `maincoder` and `hunyuan-moe` do; see [`qk_norm`] for
414    /// the llama.cpp lines and for why no GGUF key can answer this.
415    /// Set by the loader from the architecture string; refused by
416    /// `layer_supports_metal_attn`, because no fused kernel can express
417    /// the order.
418    pub qk_norm_after_rope: bool,
419    /// Per-layer Metal-resident KV for fused decode/prefill attention
420    /// (`FERROX_METAL_ATTN`). Lazily allocated. After
421    /// [`ferrox_metal::attn::launch_decode_dense_stack`], Metal KV is
422    /// authoritative for the next decode step; host [`KvCache`] may lag
423    /// until [`Self::sync_metal_attn_kv_to_host`] or a CPU fallback.
424    /// Prefill / prefix restore still upload host → Metal when lengths
425    /// diverge for other reasons.
426    #[cfg(feature = "metal")]
427    pub(crate) metal_attn_kv: std::sync::Mutex<Option<Vec<ferrox_metal::attn::MetalKvBuffers>>>,
428    /// Load-time execution plan (family, fused-op caps, SWA/RoPE
429    /// policy). Built once; hot path must not re-resolve architecture
430    /// strings. See [`crate::execution_plan`].
431    pub execution_plan: crate::execution_plan::ExecutionPlan,
432    /// May a windowed layer's host [`KvCache`] drop rows that have
433    /// fallen behind its window? Off unless `FERROX_KV_WINDOW` says
434    /// otherwise; see [`kv_window`] for what else turns it off. A field
435    /// rather than a cached global so a test can run both arms in one
436    /// process and compare tokens.
437    pub kv_window: KvWindowPolicy,
438    /// Cache key hit → fused caps last used for that geometry (enables
439    /// decode/prefill plan reuse without rebuilding residency).
440    pub plan_cache: std::sync::Mutex<
441        std::collections::HashMap<
442            crate::execution_plan::PlanGeometry,
443            crate::execution_plan::FusedOpCaps,
444        >,
445    >,
446}
447
448/// Simple deterministic pseudo-random generator so tests are
449/// reproducible without pulling in an external `rand` dependency.
450struct Lcg(u64);
451impl Lcg {
452    fn new(seed: u64) -> Self {
453        Lcg(seed)
454    }
455    fn next_f32(&mut self) -> f32 {
456        // xorshift64*
457        self.0 ^= self.0 << 13;
458        self.0 ^= self.0 >> 7;
459        self.0 ^= self.0 << 17;
460        ((self.0 >> 40) as f32 / (1u64 << 24) as f32) - 0.5
461    }
462    fn vec(&mut self, n: usize) -> Vec<f32> {
463        (0..n).map(|_| self.next_f32() * 0.1).collect()
464    }
465}
466
467/// Where a batch of independent sequences keeps its KV.
468///
469/// `forward_multi_seq` batches the projections across sequences but
470/// must attend per sequence, because each has its own length and its
471/// own history. That per-sequence step is the ONLY place the batched
472/// path touches a cache, which is why paging it is a parameter here
473/// rather than a second copy of a 300-line function -- the lesson the
474/// paged decode path taught by losing five model features one at a
475/// time to exactly that kind of copy.
476pub enum MultiSeqKv<'a> {
477    Contiguous(&'a mut [Vec<KvCache>]),
478    Paged {
479        caches: &'a mut [Vec<PagedKvCache>],
480        stores: &'a SharedPagedKv,
481    },
482}
483
484impl MultiSeqKv<'_> {
485    /// Sequences in the batch.
486    pub fn len(&self) -> usize {
487        match self {
488            MultiSeqKv::Contiguous(c) => c.len(),
489            MultiSeqKv::Paged { caches, .. } => caches.len(),
490        }
491    }
492
493    pub fn is_empty(&self) -> bool {
494        self.len() == 0
495    }
496
497    /// Layers each sequence carries, for the shape assertion.
498    fn layers_per_seq(&self, seq: usize) -> usize {
499        match self {
500            MultiSeqKv::Contiguous(c) => c[seq].len(),
501            MultiSeqKv::Paged { caches, .. } => caches[seq].len(),
502        }
503    }
504}
505
506impl Decoder {
507    /// Eagerly resolve every kernel lookup this model's dispatch paths
508    /// will make, and record it in
509    /// [`ferrox_core::kernel_registry`] before anything runs.
510    ///
511    /// Call once, at the end of loading, immediately before
512    /// [`ferrox_core::kernel_registry::seal`]. Nothing here dispatches
513    /// or decides anything: it asks the same predicates the hot path
514    /// asks and writes the answers down, so a kernel that is missing
515    /// becomes a startup line instead of an unexplained benchmark row.
516    ///
517    /// Routed experts held in an [`ExpertBacking::Stored`] layer are not
518    /// probed -- they exist only as byte ranges until a token routes to
519    /// them, and materialising every expert here would defeat the
520    /// bounded expert store. Their kinds are the same as the resident
521    /// case, and a dispatch-site miss still trips the sealed registry.
522    pub fn probe_kernels(&self) {
523        use ferrox_core::kernel_registry as reg;
524
525        if !reg::enabled() {
526            return;
527        }
528        self.embedding.probe_kernels("token_embd");
529        self.output_head.probe_kernels("output_head");
530        for layer in &self.layers {
531            layer.attn.q_proj.probe_kernels("attn_q");
532            layer.attn.k_proj.probe_kernels("attn_k");
533            layer.attn.v_proj.probe_kernels("attn_v");
534            layer.attn.o_proj.probe_kernels("attn_o");
535            layer.moe.router.probe_kernels("moe_router");
536            for e in &layer.moe.shared_experts {
537                e.gate.probe_kernels("shexp_gate");
538                e.up.probe_kernels("shexp_up");
539                e.down.probe_kernels("shexp_down");
540            }
541            if let ExpertBacking::Resident(experts) = &layer.moe.experts {
542                for e in experts {
543                    e.gate.probe_kernels("ffn_gate");
544                    e.up.probe_kernels("ffn_up");
545                    e.down.probe_kernels("ffn_down");
546                }
547            }
548        }
549        // The generic decoder has a real batched prefill
550        // (`forward_hidden_batch`), so a `pp512` here is one GEMM per
551        // projection, not 512 matvecs. Recorded as a hit so that an
552        // engine which lacks it stands out as a miss rather than as an
553        // absence.
554        reg::record_build(
555            reg::Lookup::new(
556                ferrox_core::weight_matrix::active_backend(),
557                reg::op::ENGINE_PREFILL_BATCH,
558                None,
559            )
560            .with_role("generic_decoder"),
561            reg::Outcome::Hit,
562        );
563    }
564
565    /// Builds a decoder with correctly-shaped, randomly initialized
566    /// weights for `config`, but overrides `n_layers` and `vocab_size`
567    /// with small test-scale numbers so it can actually be allocated and
568    /// run inside a CI sandbox. Use this to validate the forward-pass
569    /// plumbing only, never to draw conclusions about real model
570    /// quality.
571    pub fn new_random_small(config: ModelConfig, n_layers: usize, vocab_size: usize) -> Self {
572        let mut rng = Lcg::new(42);
573        let mut config = config;
574        config.n_layers = n_layers;
575        config.vocab_size = vocab_size;
576        let hidden = config.hidden_dim;
577        let head_dim = config.head_dim;
578        let n_heads = config.n_heads;
579        let n_kv_heads = config.n_kv_heads;
580
581        let embedding = WeightMatrix::F32(Tensor::new(
582            rng.vec(vocab_size * hidden),
583            vec![vocab_size, hidden],
584        ));
585
586        let wm = |data: Vec<f32>, shape: Vec<usize>| WeightMatrix::F32(Tensor::new(data, shape));
587
588        let mut layers = Vec::with_capacity(n_layers);
589        for layer_idx in 0..n_layers {
590            let attn = AttnWeights {
591                q_proj: wm(
592                    rng.vec(n_heads * head_dim * hidden),
593                    vec![n_heads * head_dim, hidden],
594                ),
595                k_proj: wm(
596                    rng.vec(n_kv_heads * head_dim * hidden),
597                    vec![n_kv_heads * head_dim, hidden],
598                ),
599                v_proj: wm(
600                    rng.vec(n_kv_heads * head_dim * hidden),
601                    vec![n_kv_heads * head_dim, hidden],
602                ),
603                o_proj: wm(
604                    rng.vec(hidden * n_heads * head_dim),
605                    vec![hidden, n_heads * head_dim],
606                ),
607                norm_weight: vec![1.0; hidden],
608                q_norm: None,
609                k_norm: None,
610                q_bias: None,
611                k_bias: None,
612                v_bias: None,
613                post_attn_norm: None,
614                post_ffn_norm: None,
615            };
616
617            // Leading dense layers (see ModelConfig::layer_is_dense's
618            // doc comment) get a single-expert, no-shared-expert
619            // dense-equivalent FFN regardless of this model's global
620            // MoE topology, matching the DeepSeek-2/3-family
621            // convention found in ik_llama.cpp's source.
622            let is_dense_layer = config.layer_is_dense(layer_idx);
623            let n_experts = if is_dense_layer {
624                1
625            } else {
626                config.moe.n_experts
627            };
628            let n_shared = if is_dense_layer {
629                0
630            } else {
631                config.moe.n_shared_experts
632            };
633            let ffn_dim = config.moe.expert_ffn_dim;
634            let make_expert = |rng: &mut Lcg| ExpertWeights {
635                gate: WeightMatrix::F32(Tensor::new(
636                    rng.vec(ffn_dim * hidden),
637                    vec![ffn_dim, hidden],
638                )),
639                up: WeightMatrix::F32(Tensor::new(
640                    rng.vec(ffn_dim * hidden),
641                    vec![ffn_dim, hidden],
642                )),
643                down: WeightMatrix::F32(Tensor::new(
644                    rng.vec(hidden * ffn_dim),
645                    vec![hidden, ffn_dim],
646                )),
647            };
648            let experts: Vec<ExpertWeights> =
649                (0..n_experts).map(|_| make_expert(&mut rng)).collect();
650            let shared_experts = (0..n_shared).map(|_| make_expert(&mut rng)).collect();
651            let activation_counts = (0..experts.len()).map(|_| AtomicU64::new(0)).collect();
652
653            let moe = MoeWeights {
654                exp_probs_bias: None,
655                router: wm(rng.vec(n_experts * hidden), vec![n_experts, hidden]),
656                experts: ExpertBacking::Resident(experts),
657                shared_experts,
658                shared_expert_gate: None,
659                norm_weight: vec![1.0; hidden],
660                activation_counts,
661                #[cfg(feature = "metal")]
662                packed_q4: None,
663            };
664
665            layers.push(LayerWeights { attn, moe });
666        }
667
668        let final_norm = vec![1.0; hidden];
669        let output_head = wm(rng.vec(vocab_size * hidden), vec![vocab_size, hidden]);
670        let execution_plan = crate::execution_plan::ExecutionPlan::from_config(
671            &config,
672            crate::capability::DecoderFamily::StandardGqa,
673            crate::capability::MemoryKind::KvGqa,
674            crate::execution_plan::ExecutionPlan::probe_metal_caps(),
675        );
676
677        Decoder {
678            config,
679            embedding,
680            layers,
681            final_norm,
682            output_head,
683            gpu_vram_budget_bytes: None,
684            // Synthetic-weights constructor: no checkpoint, no gpt-oss.
685            gpt_oss: None,
686            // Synthetic-weights constructor: the preset families it
687            // serves all norm before RoPE.
688            qk_norm_after_rope: false,
689            #[cfg(feature = "metal")]
690            metal_attn_kv: std::sync::Mutex::new(None),
691            execution_plan,
692            kv_window: KvWindowPolicy::from_env(),
693            plan_cache: std::sync::Mutex::new(std::collections::HashMap::new()),
694        }
695    }
696
697    /// Builds a Metal [`MatvecLaunch`] for a quantized matrix, or `None`
698    /// if the storage/kind cannot run on Metal.
699    #[cfg(feature = "metal")]
700    fn metal_matvec_launch<'a>(m: &'a WeightMatrix) -> Option<ferrox_metal::gpu::MatvecLaunch<'a>> {
701        match m {
702            WeightMatrix::F32(t) => {
703                let rows = t.shape[0];
704                let cols = t.shape[1];
705                let (src, fn_name, block_bytes, block_elems, rows_per_tg) =
706                    ferrox_metal::gpu::matvec_launch_meta("F32")?;
707                // SAFETY: f32 ↔ little-endian byte view for Metal upload/alias.
708                let bytes = unsafe {
709                    std::slice::from_raw_parts(t.data.as_ptr() as *const u8, t.data.len() * 4)
710                };
711                Some(ferrox_metal::gpu::MatvecLaunch {
712                    kernel_src: src,
713                    fn_name,
714                    block_bytes,
715                    block_elems,
716                    weights: bytes,
717                    rows,
718                    row_bytes: cols * 4,
719                    rows_per_tg,
720                })
721            }
722            WeightMatrix::Quantized {
723                data,
724                rows,
725                cols: _,
726                kind,
727            } => {
728                let kind_name = match kind {
729                    ferrox_core::QuantKind::Q8_0 => "Q8_0",
730                    ferrox_core::QuantKind::Q4_0 => "Q4_0",
731                    ferrox_core::QuantKind::Q4K => "Q4_K",
732                    ferrox_core::QuantKind::Q5K => "Q5_K",
733                    ferrox_core::QuantKind::Q6K => "Q6_K",
734                    ferrox_core::QuantKind::IQ4XS => "IQ4_XS",
735                    _ => return None,
736                };
737                let (src, fn_name, block_bytes, block_elems, rows_per_tg) =
738                    ferrox_metal::gpu::matvec_launch_meta(kind_name)?;
739                // A zero-row matrix has no rows to stride over, so
740                // there is no meaningful row size; `checked_div`
741                // says that once instead of splitting it across a
742                // guard and a bare division.
743                let row_bytes = data.as_slice().len().checked_div(*rows).unwrap_or(0);
744                Some(ferrox_metal::gpu::MatvecLaunch {
745                    kernel_src: src,
746                    fn_name,
747                    block_bytes,
748                    block_elems,
749                    weights: data.as_slice(),
750                    rows: *rows,
751                    row_bytes,
752                    rows_per_tg,
753                })
754            }
755            _ => None,
756        }
757    }
758
759    /// True when this layer can use the fused Metal attention block
760    /// (Norm or NeoX RoPE, quantized projections; QKV bias + QK-norm
761    /// via [`ferrox_metal::attn::AttnExtras`]).
762    #[cfg(feature = "metal")]
763    fn layer_supports_metal_attn(&self, layer: &LayerWeights) -> bool {
764        use crate::config::RopeLayout;
765        // gpt-oss: no Metal kernel implements attention sinks, so the
766        // fused stacks would compute a *different* attention than the
767        // CPU path for the same weights. Keep this family on CPU rather
768        // than letting the two backends disagree. See `Decoder::gpt_oss`.
769        if self.gpt_oss.is_some() {
770            return false;
771        }
772        if !matches!(self.config.rope_layout, RopeLayout::Norm | RopeLayout::Neox) {
773            return false;
774        }
775        // QKV bias (Qwen2) and QK-norm — per-head (Qwen3/Gemma-3) or
776        // whole-vector (OLMoE) — run on Metal via AttnExtras.
777        let q_len = self.config.n_heads * self.config.head_dim;
778        let k_len = self.config.n_kv_heads * self.config.head_dim;
779        let qk_norm_ok = |w: Option<&Vec<f32>>, vec_len: usize| -> bool {
780            match w {
781                None => true,
782                Some(w) if w.len() == self.config.head_dim => true,
783                Some(w) if w.len() == vec_len => true,
784                _ => false,
785            }
786        };
787        if !qk_norm_ok(layer.attn.q_norm.as_ref(), q_len)
788            || !qk_norm_ok(layer.attn.k_norm.as_ref(), k_len)
789        {
790            return false;
791        }
792        // NOT the QK-norm ORDER. `AttnExtras` hands the norm weights to
793        // kernels that apply them before their own RoPE, so a
794        // `maincoder` / `hunyuan-moe` layer would be normed on the wrong
795        // side of the rotation by every fused launch while the host
796        // bodies got it right — the same weights answering differently
797        // depending on which backend served the token. Same fence, same
798        // reason, as `attention_scale` below.
799        if self.qk_norm_after_rope {
800            return false;
801        }
802        // Softcaps: final logit softcap is applied on the host after
803        // lm_head (Metal-safe). Attention softcap runs on Metal FA-vec /
804        // legacy GQA (decode + prefill).
805        //
806        // NOT attention_scale, and this is now a refusal rather than a
807        // comment. `AttnExtras` has no field for it and no Metal kernel
808        // applies it, so a checkpoint carrying one would be scaled by
809        // the four host bodies and not by any of the seven fused
810        // launches -- the same weights answering at two different
811        // temperatures depending on which backend served the token.
812        //
813        // LIVE, not latent: `capability::attention_scale_override` sets
814        // it for Gemma-2-27B and Gemma-3-27B, so those two checkpoints
815        // take the host path here and are scaled exactly once. It was
816        // written down as a fence while `loader.rs` still hardcoded
817        // `None`, which is why the day the loader started setting it
818        // cost nothing.
819        if self.config.attention_scale.is_some() {
820            return false;
821        }
822        if self.config.head_dim > 256 {
823            return false;
824        }
825        // Partial rotary (`n_rot < head_dim`) and LongRoPE's `mscale`
826        // now ride the Metal RoPE kernels as the `rot_dim` / `mscale`
827        // uniforms on [`ferrox_metal::attn::MetalRope`], so Phi-3/Phi-4
828        // are admitted here. `n_rot` must still be even — ggml's
829        // `ggml_rope_impl` asserts it, and an odd width would leave one
830        // channel's pairing undefined rather than merely unrotated.
831        if self
832            .config
833            .rope_dim
834            .is_some_and(|rot| rot == 0 || rot % 2 != 0 || rot > self.config.head_dim)
835        {
836            return false;
837        }
838        Self::metal_matvec_launch(&layer.attn.q_proj).is_some()
839            && Self::metal_matvec_launch(&layer.attn.k_proj).is_some()
840            && Self::metal_matvec_launch(&layer.attn.v_proj).is_some()
841            && Self::metal_matvec_launch(&layer.attn.o_proj).is_some()
842    }
843
844    /// Layer features only the fused dense stack implements — the
845    /// per-layer Metal launches would silently skip them (wrong output).
846    #[cfg(feature = "metal")]
847    fn layer_needs_metal_stack(&self, layer: &LayerWeights, layer_idx: usize) -> bool {
848        layer.attn.post_attn_norm.is_some()
849            || layer.attn.post_ffn_norm.is_some()
850            || self.config.layer_sliding_window(layer_idx).is_some()
851            || !GluAct::from(self.config.ffn_activation).is_swiglu()
852            || self.config.layer_rope_theta(layer_idx) != self.config.rope_theta
853    }
854
855    /// BOTH halves of layer `il`'s RoPE, in the shape the Metal
856    /// launches take.
857    ///
858    /// One conversion, every Metal call site, because
859    /// `ModelConfig::layer_rope` returning a pair and the launches
860    /// taking a pair is only worth anything while nothing in between
861    /// gets to take one half and default the other. That is exactly
862    /// what the fused stacks used to do: a per-layer `rope_theta` beside
863    /// ONE `freq_factors` slice for the whole run, which refused
864    /// Gemma-3 4B/12B/27B off the fused path entirely rather than rope
865    /// five layers in six at the wrong scale.
866    #[cfg(feature = "metal")]
867    fn metal_layer_rope(&self, layer_idx: usize) -> ferrox_metal::attn::LayerRope<'_> {
868        let (theta, freq_factors) = self.config.layer_rope(layer_idx);
869        ferrox_metal::attn::LayerRope {
870            theta,
871            freq_factors,
872        }
873    }
874
875    /// Optional QKV bias / QK-norm ops for the Metal attn paths.
876    #[cfg(feature = "metal")]
877    fn metal_attn_extras<'a>(&self, layer: &'a LayerWeights) -> ferrox_metal::attn::AttnExtras<'a> {
878        ferrox_metal::attn::AttnExtras {
879            q_bias: layer.attn.q_bias.as_deref(),
880            k_bias: layer.attn.k_bias.as_deref(),
881            v_bias: layer.attn.v_bias.as_deref(),
882            q_norm: layer.attn.q_norm.as_deref(),
883            k_norm: layer.attn.k_norm.as_deref(),
884            attn_logit_softcap: self.config.attn_logit_softcap,
885        }
886    }
887
888    /// GPU expert residency only when Metal attention stays on-device
889    /// (when the Metal dense+attn path is active). Avoids CPU-attention
890    /// ↔ GPU-expert activation ping-pong on Metal MoE.
891    #[cfg(feature = "metal")]
892    fn expert_residency_plan(&self, use_metal_attn: bool) -> Option<ferrox_moe::ResidencyPlan> {
893        if ferrox_core::metal_dense_enabled()
894            && ferrox_metal::attn::metal_attn_enabled()
895            && !use_metal_attn
896        {
897            return None;
898        }
899        self.gpu_vram_budget_bytes.map(|b| self.residency_plan(b))
900    }
901
902    #[cfg(not(feature = "metal"))]
903    fn expert_residency_plan(&self, _use_metal_attn: bool) -> Option<ferrox_moe::ResidencyPlan> {
904        self.gpu_vram_budget_bytes.map(|b| self.residency_plan(b))
905    }
906
907    /// Map this checkpoint's RoPE onto the Metal kernel uniforms:
908    /// pairing convention, rotary width (`n_rot`), and ggml `rope_yarn`'s
909    /// `mscale`. The last two are what
910    /// [`Decoder::apply_rope_head_theta`] and
911    /// [`Decoder::apply_rope_attn_factor`] do on the CPU side, so the
912    /// two backends stay one graph.
913    #[cfg(feature = "metal")]
914    fn metal_rope(&self) -> ferrox_metal::attn::MetalRope {
915        use crate::config::RopeLayout;
916        let layout = match self.config.rope_layout {
917            RopeLayout::Norm => ferrox_metal::attn::MetalRopeLayout::Norm,
918            RopeLayout::Neox => ferrox_metal::attn::MetalRopeLayout::Neox,
919        };
920        ferrox_metal::attn::MetalRope {
921            layout,
922            rot_dim: self
923                .config
924                .rope_dim
925                .filter(|rot| *rot < self.config.head_dim),
926            attn_factor: self.config.rope_attn_factor,
927        }
928    }
929
930    /// Dense FFN (single expert) with Metal-capable gate/up/down.
931    #[cfg(feature = "metal")]
932    fn layer_supports_metal_dense_ffn(layer: &LayerWeights) -> bool {
933        Self::is_dense_layer(layer)
934            && layer.moe.with_expert(0, |ex| {
935                Self::metal_matvec_launch(&ex.gate).is_some()
936                    && Self::metal_matvec_launch(&ex.up).is_some()
937                    && Self::metal_matvec_launch(&ex.down).is_some()
938            })
939    }
940
941    /// Dense layer eligible for the one-CB `mul_mm_sg` prefill stack.
942    /// QKV bias / QK-norm are applied on-GPU via [`AttnExtras`] (same as
943    /// decode); SWA fit is checked separately.
944    #[cfg(feature = "metal")]
945    fn metal_prefill_dense_layer_eligible(layer: &LayerWeights) -> bool {
946        Self::is_dense_layer(layer)
947    }
948
949    #[cfg(feature = "metal")]
950    fn metal_prefill_dense_swa_fits(
951        &self,
952        layer_idx: usize,
953        start_pos: usize,
954        batch_size: usize,
955    ) -> bool {
956        match self.config.layer_sliding_window(layer_idx) {
957            Some(window) => start_pos + batch_size <= window,
958            None => true,
959        }
960    }
961
962    /// Routed-expert FFN for the fused prefill stack, or `None` when this
963    /// layer must keep the host-routed path (`launch_moe_prefill_q4_0`).
964    ///
965    /// Note: routing happens on the GPU here, so prefill no longer feeds
966    /// `record_activations`. Expert hotness for `inspect-plan` comes from
967    /// decode, which still routes on the host.
968    #[cfg(feature = "metal")]
969    fn metal_prefill_moe<'a>(
970        layer: &'a LayerWeights,
971        config: &ModelConfig,
972    ) -> Option<ferrox_metal::gpu::PrefillMoeMetal<'a>> {
973        if Self::is_dense_layer(layer)
974            || !layer.moe.shared_experts.is_empty()
975            || !GluAct::from(config.ffn_activation).is_swiglu()
976            // See `gpu_router_matches_host_routing`: the GPU router
977            // takes router weights and nothing else.
978            || !Self::gpu_router_matches_host_routing(layer, config)
979        {
980            return None;
981        }
982        let ferrox_core::weight_matrix::WeightMatrix::F32(router) = &layer.moe.router else {
983            return None;
984        };
985        let packed = Self::moe_packed_q4(&layer.moe)?;
986        let moe = ferrox_metal::gpu::PrefillMoeMetal {
987            router_w: &router.data,
988            top_k: config.moe.n_experts_active,
989            renormalize: config.moe.norm_topk_prob,
990            packed,
991        };
992        moe.is_supported().then_some(moe)
993    }
994
995    /// FFN half of a fused-prefill-stack layer: dense `mul_mm_sg` launches
996    /// or (MoE) the routed-expert description.
997    #[cfg(feature = "metal")]
998    fn metal_prefill_ffn<'a>(
999        layer: &'a LayerWeights,
1000        config: &ModelConfig,
1001    ) -> Option<ferrox_metal::attn::PrefillFfnMetal<'a>> {
1002        if let Some(moe) = Self::metal_prefill_moe(layer, config) {
1003            return Some(ferrox_metal::attn::PrefillFfnMetal::Moe(moe));
1004        }
1005        if !Self::is_dense_layer(layer) {
1006            return None;
1007        }
1008        let ExpertBacking::Resident(experts) = &layer.moe.experts else {
1009            return None;
1010        };
1011        let ex = experts.first()?;
1012        Some(ferrox_metal::attn::PrefillFfnMetal::Dense {
1013            gate: ex.gate.mul_mm_sg_launch()?,
1014            up: ex.up.mul_mm_sg_launch()?,
1015            down: ex.down.mul_mm_sg_launch()?,
1016        })
1017    }
1018
1019    /// Length of a consecutive run of Metal prefill-stack layers from
1020    /// `start`, or `None` when fewer than two layers qualify.
1021    #[cfg(feature = "metal")]
1022    fn metal_prefill_dense_stack_run_len(
1023        &self,
1024        start: usize,
1025        start_pos: usize,
1026        batch_size: usize,
1027        kv_caches: &[KvCache],
1028        metal_kvs: Option<&[ferrox_metal::attn::MetalKvBuffers]>,
1029    ) -> Option<usize> {
1030        // See `layer_supports_metal_attn`: gpt-oss stays on CPU.
1031        if self.gpt_oss.is_some() {
1032            return None;
1033        }
1034        let metal_kvs = metal_kvs?;
1035        let mut run = 0usize;
1036        for li in start..self.layers.len() {
1037            let layer = &self.layers[li];
1038            let cache = &kv_caches[li];
1039            if !self.metal_prefill_dense_swa_fits(li, start_pos, batch_size) {
1040                break;
1041            }
1042            // POSITIONS: compared against `start_pos`, and against
1043            // Metal's own count of the same sequence.
1044            if metal_kvs[li].seq_len != cache.positions() || start_pos != cache.positions() {
1045                break;
1046            }
1047            let ok = layer.attn.q_proj.mul_mm_sg_launch().is_some()
1048                && layer.attn.k_proj.mul_mm_sg_launch().is_some()
1049                && layer.attn.v_proj.mul_mm_sg_launch().is_some()
1050                && layer.attn.o_proj.mul_mm_sg_launch().is_some()
1051                && Self::metal_prefill_ffn(layer, &self.config).is_some();
1052            if !ok {
1053                break;
1054            }
1055            run += 1;
1056        }
1057        (run >= 2).then_some(run)
1058    }
1059
1060    /// Try [`ferrox_metal::attn::launch_prefill_dense_stack`] for
1061    /// `run_len` layers starting at `start`. Advances host + Metal KV
1062    /// on success.
1063    #[cfg(feature = "metal")]
1064    #[allow(clippy::too_many_arguments)]
1065    fn try_metal_prefill_dense_stack(
1066        &self,
1067        start: usize,
1068        run_len: usize,
1069        hidden_batch: &[f32],
1070        start_pos: usize,
1071        batch_size: usize,
1072        n_heads: usize,
1073        metal_kvs: &mut [ferrox_metal::attn::MetalKvBuffers],
1074        kv_caches: &mut [KvCache],
1075        host_kv_authoritative: bool,
1076    ) -> Option<Vec<f32>> {
1077        let gelu = !GluAct::from(self.config.ffn_activation).is_swiglu();
1078        let mut prefill_layers = Vec::with_capacity(run_len);
1079        for li in start..start + run_len {
1080            let layer = &self.layers[li];
1081            let ffn = Self::metal_prefill_ffn(layer, &self.config)?;
1082            if matches!(ffn, ferrox_metal::attn::PrefillFfnMetal::Dense { .. }) {
1083                layer.moe.record_activations(&[0]);
1084            }
1085            let (q, k, v, o) = (
1086                layer.attn.q_proj.mul_mm_sg_launch()?,
1087                layer.attn.k_proj.mul_mm_sg_launch()?,
1088                layer.attn.v_proj.mul_mm_sg_launch()?,
1089                layer.attn.o_proj.mul_mm_sg_launch()?,
1090            );
1091            prefill_layers.push(ferrox_metal::attn::PrefillDenseLayerMetal {
1092                attn_norm_w: &layer.attn.norm_weight,
1093                ffn_norm_w: &layer.moe.norm_weight,
1094                q,
1095                k,
1096                v,
1097                o,
1098                ffn,
1099                post_attn_norm: layer.attn.post_attn_norm.as_deref(),
1100                post_ffn_norm: layer.attn.post_ffn_norm.as_deref(),
1101                extras: self.metal_attn_extras(layer),
1102                rope: self.metal_layer_rope(li),
1103                layer_idx: li as u32,
1104            });
1105        }
1106        let kvs = &mut metal_kvs[start..start + run_len];
1107        let h_out = ferrox_metal::attn::launch_prefill_dense_stack(
1108            hidden_batch,
1109            &prefill_layers,
1110            kvs,
1111            n_heads,
1112            batch_size,
1113            self.metal_rope(),
1114            start_pos,
1115            self.config.rms_norm_eps,
1116            gelu,
1117            self.config.attn_logit_softcap,
1118        )
1119        .ok()?;
1120        for (mkv, cache) in kvs.iter().zip(&mut kv_caches[start..start + run_len]) {
1121            Self::advance_host_kv_after_metal_prefill(
1122                mkv,
1123                cache,
1124                batch_size,
1125                host_kv_authoritative,
1126            );
1127        }
1128        Some(h_out)
1129    }
1130
1131    /// True when a plain top-k softmax over the raw router logits picks
1132    /// the SAME experts with the SAME weights that
1133    /// [`Self::route_for_layer`] would.
1134    ///
1135    /// Every Metal MoE path either routes on the GPU (which implements
1136    /// exactly that plain top-k and takes no other input) or, in
1137    /// `launch_moe_decode_pre`'s case, used to re-implement it on the
1138    /// host. `route_for_layer` has three arms this does not: grouped
1139    /// routing, a per-expert router bias (`exp_probs_bias`), and
1140    /// `expert_weights_scale`. A checkpoint carrying any of them routes
1141    /// to DIFFERENT experts with DIFFERENT weights depending on which
1142    /// backend served the token -- not an error, a different model.
1143    ///
1144    /// One predicate rather than the four hand-copied `.is_none()` lists
1145    /// this used to be, because those lists had already drifted three
1146    /// ways: the prefill sites checked all three conditions, the fused
1147    /// decode layer checked two of them, and the whole-stack decode
1148    /// checked none. Mirror `route_for_layer` arm for arm when either
1149    /// changes.
1150    // Read by the three Metal MoE eligibility predicates, and by
1151    // `the_gpu_router_predicate_admits_only_routing_it_reproduces`. A
1152    // CPU-only build has no Metal path to gate, so it is dead there.
1153    #[cfg_attr(not(feature = "metal"), allow(dead_code))]
1154    fn gpu_router_matches_host_routing(layer: &LayerWeights, config: &ModelConfig) -> bool {
1155        matches!(config.moe.gating, ferrox_moe::GatingFunction::Softmax)
1156            // Conservative on purpose: `route_for_layer` only takes its
1157            // grouped arm for `n_groups > 1`, but a checkpoint that
1158            // declares the key at all is one this kernel was never
1159            // checked against.
1160            && config.moe.expert_group_count.is_none()
1161            && layer.moe.exp_probs_bias.is_none()
1162            && config.moe.expert_weights_scale == 1.0
1163    }
1164
1165    /// MoE layer eligible for resident Metal decode (attn+router+experts
1166    /// without host residual ping-pong). Requires SwiGLU, no shared
1167    /// experts, Resident expert backing, Metal router/QKV/O, and a
1168    /// routing decision the GPU router reproduces exactly.
1169    #[cfg(feature = "metal")]
1170    fn layer_supports_metal_moe_resident(layer: &LayerWeights, config: &ModelConfig) -> bool {
1171        !Self::is_dense_layer(layer)
1172            && layer.moe.shared_experts.is_empty()
1173            && Self::gpu_router_matches_host_routing(layer, config)
1174            && GluAct::from(config.ffn_activation).is_swiglu()
1175            // Streamed experts are eligible too. They were excluded
1176            // while the fused launch could not hold all of top-k at
1177            // once; it can now, by materialising each expert into an
1178            // owned view that carries its own pin on the store entry.
1179            && matches!(
1180                layer.moe.experts,
1181                ExpertBacking::Resident(_) | ExpertBacking::Stored { .. }
1182            )
1183            && Self::metal_matvec_launch(&layer.moe.router).is_some()
1184            && Self::metal_matvec_launch(&layer.attn.q_proj).is_some()
1185            && Self::metal_matvec_launch(&layer.attn.k_proj).is_some()
1186            && Self::metal_matvec_launch(&layer.attn.v_proj).is_some()
1187            && Self::metal_matvec_launch(&layer.attn.o_proj).is_some()
1188    }
1189
1190    /// One Metal CB for all top-k routed experts (weighted sum). Returns
1191    /// `None` if any expert lacks a Metal launch (caller falls back).
1192    #[cfg(feature = "metal")]
1193    fn try_metal_moe_topk(
1194        layer: &LayerWeights,
1195        normed2: &[f32],
1196        decision: &ferrox_moe::RoutingDecision,
1197    ) -> Option<Vec<f32>> {
1198        if decision.expert_ids.is_empty() {
1199            return Some(vec![0f32; normed2.len()]);
1200        }
1201        // Build launches while holding each expert briefly; collect owned
1202        // weight refs via with_expert into temporary MatvecLaunch list.
1203        let mut launches: Vec<ferrox_metal::gpu::MoeExpertLaunch<'_>> =
1204            Vec::with_capacity(decision.expert_ids.len());
1205        // Lifetime: MatvecLaunch borrows WeightMatrix bytes that live in
1206        // layer.moe for the duration of this call. Collect via a scoped
1207        // approach — we need all launches alive together.
1208        // Use indices + rebuild inside a single with_experts loop.
1209        struct Pending {
1210            eid: usize,
1211            weight: f32,
1212        }
1213        let pending: Vec<Pending> = decision
1214            .expert_ids
1215            .iter()
1216            .zip(decision.weights.iter())
1217            .map(|(&eid, &w)| Pending { eid, weight: w })
1218            .collect();
1219
1220        // Validate all experts have Metal launches first.
1221        for p in &pending {
1222            let ok = layer.moe.with_expert(p.eid, |ex| {
1223                Self::metal_matvec_launch(&ex.gate).is_some()
1224                    && Self::metal_matvec_launch(&ex.up).is_some()
1225                    && Self::metal_matvec_launch(&ex.down).is_some()
1226            });
1227            if !ok {
1228                return None;
1229            }
1230        }
1231
1232        // A `MatvecLaunch` borrows the expert's bytes, so every expert
1233        // in the batch has to stay alive until the command buffer is
1234        // encoded. Resident experts live in a `Vec` and can simply be
1235        // indexed. Streamed experts used to fall back to the CPU here,
1236        // on the reasoning that `with_expert` lends one at a time so
1237        // all of top-k could not be held at once.
1238        //
1239        // That was true of `with_expert` and not of the store beneath
1240        // it: `StoredExpertLayout::materialize` returns an OWNED
1241        // `ExpertWeights` whose `WeightBytes::Shared` clones the
1242        // lease's `Arc`, so each one carries its own pin and the store
1243        // cannot evict it while the view is alive. Materialising all of
1244        // top-k into a vector that outlives the launches is therefore
1245        // sound, and the vector is what holds the pins.
1246        //
1247        // The fallback was not a small loss. Expert streaming is how a
1248        // model larger than memory runs at all, so refusing the fused
1249        // path here meant that turning streaming on silently disabled
1250        // the Metal MoE kernels: exactly the configuration where the
1251        // GPU matters most ran on the CPU instead.
1252        let streamed: Vec<ExpertWeights>;
1253        match &layer.moe.experts {
1254            ExpertBacking::Resident(experts) => {
1255                for p in &pending {
1256                    let ex = &experts[p.eid];
1257                    launches.push(ferrox_metal::gpu::MoeExpertLaunch {
1258                        gate: Self::metal_matvec_launch(&ex.gate)?,
1259                        up: Self::metal_matvec_launch(&ex.up)?,
1260                        down: Self::metal_matvec_launch(&ex.down)?,
1261                        weight: p.weight,
1262                    });
1263                }
1264            }
1265            ExpertBacking::Stored {
1266                store,
1267                layouts,
1268                layer: layer_idx,
1269            } => {
1270                // Ask for the whole batch before touching any of it, so
1271                // a miss on the last expert cannot evict the first: the
1272                // store is bounded, and top-k reads are what compete
1273                // for it.
1274                let keys: Vec<_> = pending
1275                    .iter()
1276                    .map(|p| ferrox_core::expert_store::ExpertKey {
1277                        layer: *layer_idx,
1278                        expert: p.eid as u32,
1279                    })
1280                    .collect();
1281                store.prefetch(&keys);
1282
1283                let mut held = Vec::with_capacity(pending.len());
1284                for (p, key) in pending.iter().zip(keys) {
1285                    // A read failure here is not fatal: the CPU path
1286                    // reads the same bytes and will report it. Falling
1287                    // back beats panicking mid-decode.
1288                    let lease = store.acquire(key).ok()?;
1289                    held.push(layouts[p.eid].materialize(&lease));
1290                }
1291                streamed = held;
1292
1293                for (p, ex) in pending.iter().zip(streamed.iter()) {
1294                    launches.push(ferrox_metal::gpu::MoeExpertLaunch {
1295                        gate: Self::metal_matvec_launch(&ex.gate)?,
1296                        up: Self::metal_matvec_launch(&ex.up)?,
1297                        down: Self::metal_matvec_launch(&ex.down)?,
1298                        weight: p.weight,
1299                    });
1300                }
1301            }
1302        }
1303
1304        match ferrox_metal::gpu::launch_moe_topk_swiglu(normed2, &launches) {
1305            Ok(out) => Some(out),
1306            Err(e) => {
1307                eprintln!("ferrox: Metal MoE top-k fuse failed, falling back: {e}");
1308                None
1309            }
1310        }
1311    }
1312
1313    /// Contiguous Q4_0 expert planes for llama-style `mul_mv_id` MoE.
1314    #[cfg(feature = "metal")]
1315    fn moe_packed_q4(moe: &MoeWeights) -> Option<ferrox_metal::gpu::MoePackedQ4<'_>> {
1316        moe.packed_q4.as_ref().map(MoePackedQ4Planes::view)
1317    }
1318
1319    /// Prefill MoE FFN on Metal: host route over T, then one packed-id CB
1320    /// (`launch_moe_prefill_q4_0`). Shared experts (if any) run as dense
1321    /// batch FFN on the host/GPU path afterwards — not through `mul_mm_id`.
1322    /// Returns FFN outs `[T, H]` or `None`.
1323    #[cfg(feature = "metal")]
1324    fn try_metal_moe_prefill_batch(
1325        layer: &LayerWeights,
1326        normed2_batch: &[f32],
1327        router_logits_batch: &[f32],
1328        batch_size: usize,
1329        hidden_dim: usize,
1330        config: &ModelConfig,
1331    ) -> Option<Vec<f32>> {
1332        if batch_size == 0
1333            || !ferrox_core::metal_dense_enabled()
1334            || !GluAct::from(config.ffn_activation).is_swiglu()
1335            // The GPU router kernels take router weights and nothing
1336            // else: no `exp_probs_b` input, no `expert_weights_scale`
1337            // uniform, no groups. See `gpu_router_matches_host_routing`.
1338            || !Self::gpu_router_matches_host_routing(layer, config)
1339        {
1340            return None;
1341        }
1342        let ExpertBacking::Resident(_) = &layer.moe.experts else {
1343            return None;
1344        };
1345        let packed = Self::moe_packed_q4(&layer.moe)?;
1346        if !ferrox_metal::gpu::moe_packed_mul_mv_id_supported(
1347            packed.gate_kind,
1348            packed.up_kind,
1349            packed.down_kind,
1350        ) {
1351            return None;
1352        }
1353        let top_k = config.moe.n_experts_active;
1354        if top_k == 0 || top_k > 8 || packed.hidden_rows != hidden_dim {
1355            return None;
1356        }
1357        let n_experts = layer.moe.n_experts().max(1);
1358        let mut ids = Vec::with_capacity(batch_size * top_k);
1359        let mut route = Vec::with_capacity(batch_size * top_k);
1360        for b in 0..batch_size {
1361            let logits = &router_logits_batch[b * n_experts..(b + 1) * n_experts];
1362            let decision = route_top_k(logits, top_k, config.moe.gating, config.moe.norm_topk_prob);
1363            layer.moe.record_activations(&decision.expert_ids);
1364            if decision.expert_ids.len() != top_k {
1365                return None;
1366            }
1367            for (&eid, &w) in decision.expert_ids.iter().zip(decision.weights.iter()) {
1368                ids.push(eid as i32);
1369                route.push(w);
1370            }
1371        }
1372        let mut out = match ferrox_metal::gpu::launch_moe_prefill_q4_0(
1373            normed2_batch,
1374            batch_size,
1375            &packed,
1376            &ids,
1377            &route,
1378            top_k,
1379        ) {
1380            Ok(out) => out,
1381            Err(e) => {
1382                eprintln!("ferrox: Metal MoE prefill failed, CPU fallback: {e}");
1383                return None;
1384            }
1385        };
1386        Self::accumulate_shared_experts_batch(
1387            layer,
1388            normed2_batch,
1389            batch_size,
1390            hidden_dim,
1391            &mut out,
1392            // Guaranteed `Swiglu` by the fence at the top of this
1393            // function; read from the config anyway so the two cannot
1394            // drift apart.
1395            GluAct::from(config.ffn_activation),
1396        );
1397        Some(out)
1398    }
1399
1400    /// Shared expert as dense batch FFN (llama qwen2moe: not through
1401    /// `mul_mat_id`). Optional sigmoid gate scales per token.
1402    fn accumulate_shared_experts_batch(
1403        layer: &LayerWeights,
1404        normed2_batch: &[f32],
1405        batch_size: usize,
1406        hidden_dim: usize,
1407        acc: &mut [f32],
1408        act: GluAct,
1409    ) {
1410        for shex in &layer.moe.shared_experts {
1411            // Prefer one Metal FFN CB (gate∥up→SiLU→down) over three
1412            // `apply_batch` round-trips — Qwen shexp is 4× routed width.
1413            #[cfg(feature = "metal")]
1414            let down = if ferrox_core::metal_dense_enabled() && batch_size >= 4 {
1415                match (
1416                    shex.gate.mul_mm_sg_launch(),
1417                    shex.up.mul_mm_sg_launch(),
1418                    shex.down.mul_mm_sg_launch(),
1419                ) {
1420                    (Some(g), Some(u), Some(d)) => {
1421                        // The launch's last argument selects GELU over
1422                        // SiLU inside the kernel; hardcoding `false` here
1423                        // ran a shared expert as SwiGLU on a GeGLU model.
1424                        ferrox_metal::gpu::launch_dense_ffn_swiglu_batch(
1425                            &g,
1426                            &u,
1427                            &d,
1428                            normed2_batch,
1429                            batch_size,
1430                            !act.is_swiglu(),
1431                        )
1432                        .ok()
1433                    }
1434                    _ => None,
1435                }
1436            } else {
1437                None
1438            };
1439            #[cfg(not(feature = "metal"))]
1440            let down: Option<Vec<f32>> = None;
1441            // Without `metal` the binding above is a literal `None`; the
1442            // fallback is the only arm and clippy flags the unwrap.
1443            #[cfg_attr(not(feature = "metal"), allow(clippy::unnecessary_literal_unwrap))]
1444            let down = down.unwrap_or_else(|| {
1445                let ffn_acts = shex.gate.quantize_batch_acts(normed2_batch, batch_size);
1446                let gate =
1447                    shex.gate
1448                        .apply_batch_with_acts(normed2_batch, batch_size, ffn_acts.as_ref());
1449                let up =
1450                    shex.up
1451                        .apply_batch_with_acts(normed2_batch, batch_size, ffn_acts.as_ref());
1452                let activated = act.apply(&gate, &up);
1453                shex.down.apply_batch(&activated, batch_size)
1454            });
1455            if let Some(gate_w) = &layer.moe.shared_expert_gate {
1456                for b in 0..batch_size {
1457                    let x = &normed2_batch[b * hidden_dim..(b + 1) * hidden_dim];
1458                    let logit: f32 = gate_w.iter().zip(x.iter()).map(|(g, v)| g * v).sum();
1459                    let scale = 1.0 / (1.0 + (-logit).exp());
1460                    let out = &down[b * hidden_dim..(b + 1) * hidden_dim];
1461                    let row = &mut acc[b * hidden_dim..(b + 1) * hidden_dim];
1462                    for (a, &o) in row.iter_mut().zip(out.iter()) {
1463                        *a += scale * o;
1464                    }
1465                }
1466            } else {
1467                for (a, &o) in acc.iter_mut().zip(down.iter()) {
1468                    *a += o;
1469                }
1470            }
1471        }
1472    }
1473
1474    /// Phase-2 of resident MoE decode: experts on GPU `x2`, add into GPU `h`.
1475    #[cfg(feature = "metal")]
1476    fn try_metal_moe_experts_resident(
1477        layer: &LayerWeights,
1478        decision: &ferrox_moe::RoutingDecision,
1479    ) -> Option<()> {
1480        if decision.expert_ids.is_empty() {
1481            return Some(());
1482        }
1483        let pending: Vec<(usize, f32)> = decision
1484            .expert_ids
1485            .iter()
1486            .zip(decision.weights.iter())
1487            .map(|(&eid, &w)| (eid, w))
1488            .collect();
1489        // Bail on the backing BEFORE validating the experts. The
1490        // validation loop below calls `with_expert`, which for
1491        // `Stored` backing acquires a lease and so can read from the
1492        // checkpoint file. Refusing afterwards meant a streamed layer
1493        // paid one read per top-k expert and then threw all of them
1494        // away, before `try_metal_moe_topk` read the same experts
1495        // again. This path stays resident-only for now, but it must
1496        // decline for free.
1497        let ExpertBacking::Resident(experts) = &layer.moe.experts else {
1498            return None;
1499        };
1500        for &(eid, _) in &pending {
1501            let ex = &experts[eid];
1502            if Self::metal_matvec_launch(&ex.gate).is_none()
1503                || Self::metal_matvec_launch(&ex.up).is_none()
1504                || Self::metal_matvec_launch(&ex.down).is_none()
1505            {
1506                return None;
1507            }
1508        }
1509        let mut launches = Vec::with_capacity(pending.len());
1510        for &(eid, weight) in &pending {
1511            let ex = &experts[eid];
1512            launches.push(ferrox_metal::gpu::MoeExpertLaunch {
1513                gate: Self::metal_matvec_launch(&ex.gate)?,
1514                up: Self::metal_matvec_launch(&ex.up)?,
1515                down: Self::metal_matvec_launch(&ex.down)?,
1516                weight,
1517            });
1518        }
1519        match ferrox_metal::attn::launch_moe_decode_experts(&launches) {
1520            Ok(()) => Some(()),
1521            Err(e) => {
1522                eprintln!("ferrox: Metal MoE experts failed, falling back: {e}");
1523                None
1524            }
1525        }
1526    }
1527
1528    /// Advance the host [`KvCache`] over the positions a Metal prefill
1529    /// kernel just wrote to the device.
1530    ///
1531    /// Two ways to do that, and which one is right depends on whether
1532    /// anyone will READ the host rows.
1533    ///
1534    /// The contiguous path never does: Metal stays authoritative from
1535    /// prefill through decode, so [`KvCache::advance_len`]'s zero fill
1536    /// is a placeholder that only has to keep `seq_len` in step for the
1537    /// sync checks, and skipping the download is the whole point.
1538    ///
1539    /// The PAGED path does. `forward_batch_last_paged` scatters these
1540    /// rows into the page store, and a caller that reads placeholders
1541    /// gets a prompt the model never saw -- which is exactly how paged
1542    /// KV on Metal came to answer fluent nonsense while paged-on-CPU
1543    /// and contiguous-on-Metal were each correct. So it asks for the
1544    /// real rows and pays one download per layer, against a gather and
1545    /// a scatter it was already paying.
1546    ///
1547    /// Done here, per layer, immediately after the launch, rather than
1548    /// once at the end: the Metal KV buffers are dropped outright when
1549    /// a later layer's launch fails, and rows nobody downloaded before
1550    /// that are simply gone.
1551    #[cfg(feature = "metal")]
1552    fn advance_host_kv_after_metal_prefill(
1553        mkv: &ferrox_metal::attn::MetalKvBuffers,
1554        cache: &mut KvCache,
1555        batch_size: usize,
1556        host_kv_authoritative: bool,
1557    ) {
1558        if host_kv_authoritative {
1559            Self::catch_up_host_kv_from_metal(mkv, cache);
1560            debug_assert_eq!(cache.positions(), mkv.seq_len);
1561        } else {
1562            cache
1563                .advance_len(batch_size)
1564                .expect("unbounded/planned KvCache growth is infallible");
1565        }
1566    }
1567
1568    /// Append host [`KvCache`] positions that Metal already holds but host
1569    /// skipped (dense-stack fast path). No-op when `cache.seq_len` is caught up.
1570    #[cfg(feature = "metal")]
1571    fn catch_up_host_kv_from_metal(mkv: &ferrox_metal::attn::MetalKvBuffers, cache: &mut KvCache) {
1572        // ROWS on both sides: this fills the host buffer with rows
1573        // Metal already holds, and `push` below advances positions with
1574        // them. Neither store evicts, so the two agree; when one learns
1575        // to (#61) this is a place that has to say which it meant.
1576        if cache.rows() >= mkv.seq_len {
1577            return;
1578        }
1579        let start = cache.rows();
1580        let n = mkv.seq_len - start;
1581        let (k, v) = mkv.tokens_host(start, n);
1582        let per = cache.n_kv_heads * cache.head_dim;
1583        for i in 0..n {
1584            let off = i * per;
1585            cache
1586                .push(&k[off..off + per], &v[off..off + per])
1587                .expect("unbounded/planned KvCache growth is infallible");
1588        }
1589    }
1590
1591    /// Pull every layer's Metal-ahead suffix into `kv_caches` (prefix-cache
1592    /// Poison-tolerant lock for the shared Metal KV arena. A panicked
1593    /// holder must not permanently brick every later decode.
1594    #[cfg(feature = "metal")]
1595    fn lock_metal_attn_kv(
1596        mutex: &std::sync::Mutex<Option<Vec<ferrox_metal::attn::MetalKvBuffers>>>,
1597    ) -> std::sync::MutexGuard<'_, Option<Vec<ferrox_metal::attn::MetalKvBuffers>>> {
1598        mutex
1599            .lock()
1600            .unwrap_or_else(|poisoned| poisoned.into_inner())
1601    }
1602
1603    /// store, continuous-batch / CPU readers). Safe no-op without Metal KV.
1604    #[cfg(feature = "metal")]
1605    pub fn sync_metal_attn_kv_to_host(&self, kv_caches: &mut [KvCache]) {
1606        assert_eq!(kv_caches.len(), self.layers.len());
1607        let guard = Self::lock_metal_attn_kv(&self.metal_attn_kv);
1608        let Some(metal_kvs) = guard.as_ref() else {
1609            return;
1610        };
1611        if metal_kvs.len() != kv_caches.len() {
1612            return;
1613        }
1614        for (mkv, cache) in metal_kvs.iter().zip(kv_caches.iter_mut()) {
1615            Self::catch_up_host_kv_from_metal(mkv, cache);
1616        }
1617    }
1618
1619    /// GQA decode reduction for one token. Uses the CUDA `gqa_decode`
1620    /// kernel when built with `--features cuda` and `FERROX_CUDA_GQA=1`
1621    /// (falling back to the host path on any launch error), else the
1622    /// portable [`causal_gqa_attention`]. With residency enabled the
1623    /// K/V append stays in [`ferrox_cuda::attn::CudaKvBuffers`] so only
1624    /// Q crosses the bus per call (plus a prefix refresh on append).
1625    #[allow(clippy::too_many_arguments)]
1626    fn gqa_attention(
1627        &self,
1628        layer: usize,
1629        q: &[f32],
1630        k: &[f32],
1631        v: &[f32],
1632        n_heads: usize,
1633        n_kv_heads: usize,
1634        head_dim: usize,
1635        seq_len: usize,
1636    ) -> Vec<f32> {
1637        #[cfg(feature = "cuda")]
1638        {
1639            if cuda_gqa_enabled() {
1640                match ferrox_cuda::attn::launch_gqa_decode_resident(
1641                    layer, q, k, v, n_heads, n_kv_heads, head_dim, seq_len,
1642                ) {
1643                    Ok(out) => return out,
1644                    Err(e) => {
1645                        eprintln!(
1646                            "ferrox: CUDA GQA resident decode failed, trying full upload: {e}"
1647                        );
1648                    }
1649                }
1650                match ferrox_cuda::attn::launch_gqa_decode(
1651                    q, k, v, n_heads, n_kv_heads, head_dim, seq_len,
1652                ) {
1653                    Ok(out) => return out,
1654                    Err(e) => {
1655                        eprintln!("ferrox: CUDA GQA decode failed, host fallback: {e}");
1656                    }
1657                }
1658            }
1659        }
1660        let _ = layer;
1661        causal_gqa_attention_softcap(
1662            q,
1663            k,
1664            v,
1665            n_heads,
1666            n_kv_heads,
1667            head_dim,
1668            seq_len,
1669            self.config.attn_logit_softcap,
1670        )
1671    }
1672
1673    /// Runs one decode step for `token_id` at position `pos`, updating
1674    /// `kv_caches` (one per layer) in place, and returns the logits over
1675    /// the (test-scale) vocabulary.
1676    pub fn forward_token(
1677        &self,
1678        token_id: usize,
1679        pos: usize,
1680        kv_caches: &mut [KvCache],
1681    ) -> Vec<f32> {
1682        // Clear stale dense-stack activation TLS. MoE scratch buffers are
1683        // reused across tokens (re-seeded); cleared after lm_head below.
1684        #[cfg(feature = "metal")]
1685        ferrox_metal::gpu::clear_resident_activation();
1686
1687        assert_eq!(kv_caches.len(), self.layers.len());
1688        let hidden_dim = self.config.hidden_dim;
1689        // Read only by the Metal arms below: the host layer body moved
1690        // into `attn_block`, which reads the geometry off `self.config`
1691        // itself.
1692        #[cfg(feature = "metal")]
1693        let head_dim = self.config.head_dim;
1694        #[cfg(feature = "metal")]
1695        let n_heads = self.config.n_heads;
1696        #[cfg(feature = "metal")]
1697        let n_kv_heads = self.config.n_kv_heads;
1698
1699        #[cfg(feature = "metal")]
1700        let metal_embd_kind = {
1701            let metal_path = ferrox_core::metal_dense_enabled()
1702                && ferrox_metal::attn::metal_attn_enabled()
1703                && self
1704                    .layers
1705                    .iter()
1706                    .all(|l| self.layer_supports_metal_attn(l))
1707                && self.layers.iter().all(Self::layer_supports_metal_dense_ffn);
1708            // Gemma scales the embedding row (`embedding_scale`) — the GPU
1709            // gather has no scale op, so dequant + scale on the host.
1710            if metal_path && self.config.embedding_scale.is_none() {
1711                Self::metal_matvec_launch(&self.embedding)
1712                    .and_then(|l| ferrox_metal::embd::EmbdKind::from_fn_name(l.fn_name))
1713            } else {
1714                None
1715            }
1716        };
1717        // `metal_embd_kind` is only `Some` when `embedding_scale` is
1718        // `None` (the GPU gather has no scale op), so the empty vector
1719        // this leaves behind is one the scale would not have touched.
1720        #[cfg(feature = "metal")]
1721        let mut hidden = if metal_embd_kind.is_some() {
1722            Vec::new()
1723        } else {
1724            self.embed_token(token_id)
1725        };
1726        #[cfg(not(feature = "metal"))]
1727        let mut hidden = self.embed_token(token_id);
1728        #[cfg(feature = "cuda")]
1729        if cuda_gqa_enabled() {
1730            // Fixed capacity so ensure_layer_kv does not recreate (and
1731            // wipe) mid-sequence as pos grows.
1732            const CUDA_KV_CAP: usize = 4096;
1733            if let Err(e) = ferrox_cuda::attn::ensure_layer_kv(
1734                self.layers.len(),
1735                self.config.n_kv_heads,
1736                self.config.head_dim,
1737                CUDA_KV_CAP,
1738            ) {
1739                eprintln!("ferrox: CUDA KV residency init failed: {e}");
1740            }
1741            if pos == 0 {
1742                ferrox_cuda::attn::clear_layer_kv();
1743            }
1744        }
1745
1746        #[cfg(feature = "metal")]
1747        let use_metal_attn = ferrox_core::metal_dense_enabled()
1748            && ferrox_metal::attn::metal_attn_enabled()
1749            && self
1750                .layers
1751                .iter()
1752                .all(|l| self.layer_supports_metal_attn(l));
1753
1754        #[cfg(not(feature = "metal"))]
1755        let use_metal_attn = false;
1756
1757        let residency = self.expert_residency_plan(use_metal_attn);
1758
1759        #[cfg(feature = "metal")]
1760        let mut metal_kv_guard: Option<
1761            std::sync::MutexGuard<'_, Option<Vec<ferrox_metal::attn::MetalKvBuffers>>>,
1762        > = if use_metal_attn {
1763            Some(Self::lock_metal_attn_kv(&self.metal_attn_kv))
1764        } else {
1765            None
1766        };
1767
1768        #[cfg(feature = "metal")]
1769        if let Some(guard) = metal_kv_guard.as_mut() {
1770            let need = self.layers.len();
1771            let cap = kv_caches
1772                .iter()
1773                // POSITIONS: sized against `pos`, which is a position.
1774                .map(|c| c.positions().max(pos + 1).saturating_add(256))
1775                .max()
1776                .unwrap_or(512)
1777                .max(512)
1778                .max(pos + 1);
1779            let reset = match guard.as_ref() {
1780                None => true,
1781                Some(v) => {
1782                    if v.len() != need || v.iter().any(|m| m.capacity() < pos + 1) {
1783                        // Growing / reshaping: preserve Metal-ahead tokens on host first.
1784                        if v.len() == need {
1785                            for (m, c) in v.iter().zip(kv_caches.iter_mut()) {
1786                                Self::catch_up_host_kv_from_metal(m, c);
1787                            }
1788                        }
1789                        true
1790                    } else if v.iter().all(|m| m.seq_len == pos) {
1791                        // Metal already holds tokens [0, pos). Host may lag
1792                        // after dense-stack decode — do not re-upload from host.
1793                        false
1794                    } else {
1795                        // Stale Metal (new request / prefix restore): rebuild from host.
1796                        true
1797                    }
1798                }
1799            };
1800            if reset {
1801                let mut bufs = Vec::with_capacity(need);
1802                for _ in 0..need {
1803                    match ferrox_metal::attn::MetalKvBuffers::with_capacity(
1804                        n_kv_heads, head_dim, cap,
1805                    ) {
1806                        Ok(b) => bufs.push(b),
1807                        Err(_) => {
1808                            **guard = None;
1809                            break;
1810                        }
1811                    }
1812                }
1813                if bufs.len() == need {
1814                    // Sync from host after CPU prefill / prefix restore / capacity grow.
1815                    let mut ok = true;
1816                    for (m, c) in bufs.iter_mut().zip(kv_caches.iter()) {
1817                        // ROWS: this uploads `c.k` / `c.v` themselves, so the
1818                        // count must describe those buffers.
1819                        if c.rows() > 0 && m.upload_from_host(&c.k, &c.v, c.rows()).is_err() {
1820                            ok = false;
1821                            break;
1822                        }
1823                    }
1824                    if ok {
1825                        **guard = Some(bufs);
1826                    } else {
1827                        **guard = None;
1828                    }
1829                } else {
1830                    **guard = None;
1831                }
1832            }
1833        }
1834
1835        #[cfg(feature = "metal")]
1836        let mut metal_stack_done = false;
1837        #[cfg(feature = "metal")]
1838        let mut final_norm_done_in_stack = false;
1839        // OLMoE: all MoE layers in one CB (llama graph style).
1840        #[cfg(feature = "metal")]
1841        if use_metal_attn
1842            && self.layers.iter().enumerate().all(|(i, l)| {
1843                // Both halves are required. `layer_supports_metal_moe_resident`
1844                // answers "is this an MoE layer the GPU router can serve",
1845                // and says nothing about the four features
1846                // `MoeLayerMetal` has no fields for: a per-layer
1847                // `rope_theta`, a sliding `window`, `post_attn_norm`
1848                // and `post_ffn_norm`. `DenseLayerMetal` carries all
1849                // four and `launch_decode_dense_stack` implements
1850                // them; the MoE stack does neither, and nothing here
1851                // refused, so a windowed or sandwich-normed MoE
1852                // checkpoint would have answered as a different
1853                // model with no error.
1854                //
1855                // The per-layer path already pairs these two checks
1856                // (see the `metal_moe_resident` branch in the decode
1857                // loop). Only the whole-stack path was missing it.
1858                // Latent today because OLMoE and Qwen3-MoE ship none
1859                // of the four, which is exactly how `attention_scale`
1860                // stayed latent.
1861                Self::layer_supports_metal_moe_resident(l, &self.config)
1862                    && !self.layer_needs_metal_stack(l, i)
1863            })
1864            && !self.layers.iter().all(Self::layer_supports_metal_dense_ffn)
1865        {
1866            if let Some(guard) = metal_kv_guard.as_mut() {
1867                if let Some(metal_kvs) = guard.as_mut() {
1868                    if metal_kvs.iter().all(|m| m.seq_len == pos) {
1869                        let mut moe_layers = Vec::with_capacity(self.layers.len());
1870                        let mut ok = true;
1871                        for layer in &self.layers {
1872                            let ExpertBacking::Resident(_) = &layer.moe.experts else {
1873                                ok = false;
1874                                break;
1875                            };
1876                            let Some(packed) = Self::moe_packed_q4(&layer.moe) else {
1877                                ok = false;
1878                                break;
1879                            };
1880                            let (Some(q), Some(k), Some(v), Some(o), Some(r)) = (
1881                                Self::metal_matvec_launch(&layer.attn.q_proj),
1882                                Self::metal_matvec_launch(&layer.attn.k_proj),
1883                                Self::metal_matvec_launch(&layer.attn.v_proj),
1884                                Self::metal_matvec_launch(&layer.attn.o_proj),
1885                                Self::metal_matvec_launch(&layer.moe.router),
1886                            ) else {
1887                                ok = false;
1888                                break;
1889                            };
1890                            moe_layers.push(ferrox_metal::attn::MoeLayerMetal {
1891                                attn_norm_w: &layer.attn.norm_weight,
1892                                ffn_norm_w: &layer.moe.norm_weight,
1893                                q,
1894                                k,
1895                                v,
1896                                o,
1897                                router: r,
1898                                packed,
1899                                extras: self.metal_attn_extras(layer),
1900                            });
1901                        }
1902                        if ok {
1903                            // Greedy: fold lm_head+argmax into the stack like the
1904                            // dense path does, and download one u32 instead of a
1905                            // hidden vector.
1906                            let greedy_gpu = ferrox_metal::attn::metal_greedy_argmax_active();
1907                            let lm_head_gpu_launch = Self::metal_matvec_launch(&self.output_head);
1908                            // One value carries both "lm_head runs in the
1909                            // stack" and "the stack returns an argmax id",
1910                            // so the second cannot drift off the first.
1911                            // See `decoder::lm_head`.
1912                            let folded = FoldedLmHead::permit(greedy_gpu, lm_head_gpu_launch);
1913                            let embd_launch = Self::metal_matvec_launch(&self.embedding);
1914                            // Gemma scales embd on host; GPU gather has no scale.
1915                            let embd_gather = if self.config.embedding_scale.is_some() {
1916                                None
1917                            } else {
1918                                match (metal_embd_kind, embd_launch.as_ref()) {
1919                                    (Some(kind), Some(launch)) => {
1920                                        Some(ferrox_metal::attn::EmbdGatherMetal {
1921                                            kind,
1922                                            weights: launch.weights,
1923                                            rows: launch.rows,
1924                                            row_bytes: launch.row_bytes,
1925                                            n_cols: hidden_dim,
1926                                            token_id,
1927                                        })
1928                                    }
1929                                    _ => None,
1930                                }
1931                            };
1932                            if embd_gather.is_none() && hidden.is_empty() {
1933                                hidden = self.embedding.dequant_row(token_id);
1934                                if let Some(scale) = self.config.embedding_scale {
1935                                    for v in hidden.iter_mut() {
1936                                        *v *= scale;
1937                                    }
1938                                }
1939                            }
1940                            let seed = if embd_gather.is_some() {
1941                                ferrox_metal::attn::moe_decode_ensure(hidden_dim)
1942                            } else {
1943                                ferrox_metal::attn::moe_decode_seed(&hidden)
1944                            };
1945                            let hidden_ref: &[f32] =
1946                                if embd_gather.is_some() { &[] } else { &hidden };
1947                            match seed.and_then(|_| {
1948                                ferrox_metal::attn::launch_moe_decode_stack(
1949                                    hidden_ref,
1950                                    &moe_layers,
1951                                    metal_kvs,
1952                                    self.config.moe.n_experts_active,
1953                                    self.config.moe.norm_topk_prob,
1954                                    n_heads,
1955                                    self.metal_rope(),
1956                                    self.config.rope_theta,
1957                                    // The stack-wide theta above is
1958                                    // sound because no layer here
1959                                    // `layer_needs_metal_stack`, which
1960                                    // means none slides; the divisors
1961                                    // are taken through the same
1962                                    // accessor so the two stay one
1963                                    // answer.
1964                                    self.config.layer_rope_freqs(0),
1965                                    pos,
1966                                    self.config.rms_norm_eps,
1967                                    Some(&self.final_norm),
1968                                    folded.as_ref().map(FoldedLmHead::launch),
1969                                    folded.as_ref().is_some_and(FoldedLmHead::argmax_only),
1970                                    true,
1971                                    embd_gather.as_ref(),
1972                                )
1973                            }) {
1974                                Ok((out, per_layer_ids)) => {
1975                                    for (layer, ids) in self.layers.iter().zip(per_layer_ids.iter())
1976                                    {
1977                                        if !ids.is_empty() {
1978                                            layer.moe.record_activations(ids);
1979                                        }
1980                                    }
1981                                    if let Some(folded) = folded.as_ref() {
1982                                        #[cfg(feature = "metal")]
1983                                        ferrox_metal::gpu::clear_resident_activation();
1984                                        // Softcaps anything vocabulary-shaped;
1985                                        // passes a 1-element argmax id through.
1986                                        return folded.interpret(
1987                                            out,
1988                                            self.output_head.rows(),
1989                                            self.config.final_logit_softcap,
1990                                        );
1991                                    }
1992                                    hidden = out;
1993                                    final_norm_done_in_stack = true;
1994                                    metal_stack_done = true;
1995                                }
1996                                Err(e) => {
1997                                    eprintln!(
1998                                        "ferrox: Metal MoE stack failed, per-layer fallback: {e}"
1999                                    );
2000                                    if hidden.is_empty() {
2001                                        hidden = self.embedding.dequant_row(token_id);
2002                                        if let Some(scale) = self.config.embedding_scale {
2003                                            for v in hidden.iter_mut() {
2004                                                *v *= scale;
2005                                            }
2006                                        }
2007                                    }
2008                                }
2009                            }
2010                        }
2011                    }
2012                }
2013            }
2014        }
2015        #[cfg(feature = "metal")]
2016        if !metal_stack_done
2017            && use_metal_attn
2018            && self.layers.iter().all(Self::layer_supports_metal_dense_ffn)
2019        {
2020            if let Some(guard) = metal_kv_guard.as_mut() {
2021                let mut clear_metal_after_stack = false;
2022                if let Some(metal_kvs) = guard.as_mut() {
2023                    let seq_ok = metal_kvs.iter().all(|m| m.seq_len == pos);
2024                    if seq_ok {
2025                        // Build launches only for resident dense experts (Llama path).
2026                        let mut dense_layers = Vec::with_capacity(self.layers.len());
2027                        let mut ok = true;
2028                        for (li, layer) in self.layers.iter().enumerate() {
2029                            let ExpertBacking::Resident(experts) = &layer.moe.experts else {
2030                                ok = false;
2031                                break;
2032                            };
2033                            let ex = &experts[0];
2034                            let (Some(q), Some(k), Some(v), Some(o), Some(g), Some(u), Some(d)) = (
2035                                Self::metal_matvec_launch(&layer.attn.q_proj),
2036                                Self::metal_matvec_launch(&layer.attn.k_proj),
2037                                Self::metal_matvec_launch(&layer.attn.v_proj),
2038                                Self::metal_matvec_launch(&layer.attn.o_proj),
2039                                Self::metal_matvec_launch(&ex.gate),
2040                                Self::metal_matvec_launch(&ex.up),
2041                                Self::metal_matvec_launch(&ex.down),
2042                            ) else {
2043                                ok = false;
2044                                break;
2045                            };
2046                            dense_layers.push(ferrox_metal::attn::DenseLayerMetal {
2047                                attn_norm_w: &layer.attn.norm_weight,
2048                                ffn_norm_w: &layer.moe.norm_weight,
2049                                q,
2050                                k,
2051                                v,
2052                                o,
2053                                gate: g,
2054                                up: u,
2055                                down: d,
2056                                extras: self.metal_attn_extras(layer),
2057                                rope: self.metal_layer_rope(li),
2058                                window: self.config.layer_sliding_window(li),
2059                                post_attn_norm: layer.attn.post_attn_norm.as_deref(),
2060                                post_ffn_norm: layer.attn.post_ffn_norm.as_deref(),
2061                            });
2062                        }
2063                        if ok {
2064                            // Greedy GPU argmax-in-stack (1×u32 download) when
2065                            // generate marked this thread for temperature<=0.
2066                            // Otherwise host lm_head after the hidden download,
2067                            // which measured ~2x the tok/s of a full-vocab one.
2068                            let greedy_gpu = ferrox_metal::attn::metal_greedy_argmax_active();
2069                            let lm_head_gpu_launch = Self::metal_matvec_launch(&self.output_head);
2070                            // See `decoder::lm_head`: folding lm_head into
2071                            // the stack and the stack returning an argmax id
2072                            // are one decision, held in one value.
2073                            let folded = FoldedLmHead::permit(greedy_gpu, lm_head_gpu_launch);
2074                            // Pass final_norm_w when: (1) lm_head runs in stack (folded),
2075                            // OR (2) lm_head will route to GPU after stack (lm_head_gpu_launch
2076                            // but no fold) so we can skip download→reupload via TLS.
2077                            let final_norm_w = if folded.is_some() || lm_head_gpu_launch.is_some() {
2078                                Some(self.final_norm.as_slice())
2079                            } else {
2080                                None
2081                            };
2082                            let embd_launch = Self::metal_matvec_launch(&self.embedding);
2083                            // Gemma scales the embedding row on the host
2084                            // (`hidden` already carries sqrt(hidden_dim));
2085                            // the GPU gather has no scale op — skip it.
2086                            let embd_gather = if self.config.embedding_scale.is_some() {
2087                                None
2088                            } else {
2089                                match (metal_embd_kind, embd_launch.as_ref()) {
2090                                    (Some(kind), Some(launch)) => {
2091                                        Some(ferrox_metal::attn::EmbdGatherMetal {
2092                                            kind,
2093                                            weights: launch.weights,
2094                                            rows: launch.rows,
2095                                            row_bytes: launch.row_bytes,
2096                                            n_cols: hidden_dim,
2097                                            token_id,
2098                                        })
2099                                    }
2100                                    _ => None,
2101                                }
2102                            };
2103                            let hidden_ref: &[f32] =
2104                                if embd_gather.is_some() { &[] } else { &hidden };
2105                            match ferrox_metal::attn::launch_decode_dense_stack(
2106                                hidden_ref,
2107                                &dense_layers,
2108                                metal_kvs,
2109                                n_heads,
2110                                self.metal_rope(),
2111                                pos,
2112                                self.config.rms_norm_eps,
2113                                final_norm_w,
2114                                folded.as_ref().map(FoldedLmHead::launch),
2115                                folded.as_ref().is_some_and(FoldedLmHead::argmax_only),
2116                                embd_gather.as_ref(),
2117                                !GluAct::from(self.config.ffn_activation).is_swiglu(),
2118                            ) {
2119                                Ok(out) => {
2120                                    // Metal KV advanced in-place. Skip host
2121                                    // last_token_host+push — host may lag until
2122                                    // sync_metal_attn_kv_to_host / CPU fallback.
2123                                    // Dense stack has no MoE routing; skip
2124                                    // per-layer hotness atomics on the hot path.
2125                                    if let Some(folded) = folded.as_ref() {
2126                                        // Skip host final_norm/lm_head. Clear TLS.
2127                                        #[cfg(feature = "metal")]
2128                                        ferrox_metal::gpu::clear_resident_activation();
2129                                        // `interpret` is what keeps
2130                                        // `final_logit_softcap` applied: the id
2131                                        // shape passes through, anything
2132                                        // vocabulary-shaped gets capped.
2133                                        return folded.interpret(
2134                                            out,
2135                                            self.output_head.rows(),
2136                                            self.config.final_logit_softcap,
2137                                        );
2138                                    }
2139                                    // Stack downloaded hidden (possibly normalized if
2140                                    // final_norm_w was Some). Track whether host should
2141                                    // skip final_norm.
2142                                    final_norm_done_in_stack = final_norm_w.is_some();
2143                                    hidden = out;
2144                                    metal_stack_done = true;
2145                                }
2146                                Err(e) => {
2147                                    eprintln!(
2148                                        "ferrox: Metal dense stack failed, per-layer fallback: {e}"
2149                                    );
2150                                    if hidden.is_empty() {
2151                                        hidden = self.embedding.dequant_row(token_id);
2152                                        if let Some(scale) = self.config.embedding_scale {
2153                                            for v in hidden.iter_mut() {
2154                                                *v *= scale;
2155                                            }
2156                                        }
2157                                    }
2158                                    // Preserve any prior Metal-ahead tokens on host
2159                                    // before dropping the device buffers.
2160                                    for (m, c) in metal_kvs.iter().zip(kv_caches.iter_mut()) {
2161                                        Self::catch_up_host_kv_from_metal(m, c);
2162                                    }
2163                                    clear_metal_after_stack = true;
2164                                }
2165                            }
2166                        }
2167                    }
2168                }
2169                if clear_metal_after_stack {
2170                    **guard = None;
2171                }
2172            }
2173        }
2174
2175        #[cfg(feature = "metal")]
2176        let run_cpu_layers = !metal_stack_done;
2177        #[cfg(not(feature = "metal"))]
2178        let run_cpu_layers = true;
2179
2180        // When true, residual lives in Metal MoE scratch — host `hidden` is stale.
2181        #[cfg(feature = "metal")]
2182        let mut metal_moe_resident = false;
2183
2184        #[cfg(feature = "metal")]
2185        if run_cpu_layers && hidden.is_empty() && !metal_moe_resident {
2186            // GPU embedding gather or a skipped Metal dense stack can leave
2187            // `hidden` empty; CPU fallback must not call rms_norm on it.
2188            hidden = self.embed_token(token_id);
2189        }
2190
2191        if run_cpu_layers {
2192            for (l, (layer, cache)) in self.layers.iter().zip(kv_caches.iter_mut()).enumerate() {
2193                // --- attention block ---
2194                #[cfg(feature = "metal")]
2195                if metal_moe_resident
2196                    && (!Self::layer_supports_metal_moe_resident(layer, &self.config)
2197                        || self.layer_needs_metal_stack(layer, l))
2198                {
2199                    if let Some(h) = ferrox_metal::attn::moe_decode_take_hidden() {
2200                        hidden = h;
2201                    }
2202                    metal_moe_resident = false;
2203                }
2204
2205                #[cfg(feature = "metal")]
2206                let normed = if metal_moe_resident {
2207                    // Residual is on-device; host rms_norm would use stale hidden.
2208                    Vec::new()
2209                } else {
2210                    rms_norm(&hidden, &layer.attn.norm_weight, self.config.rms_norm_eps)
2211                };
2212                #[cfg(not(feature = "metal"))]
2213                let normed = rms_norm(&hidden, &layer.attn.norm_weight, self.config.rms_norm_eps);
2214
2215                #[cfg(feature = "metal")]
2216                {
2217                    let mut did_metal_attn = false;
2218                    let mut did_metal_dense = false;
2219                    let mut did_metal_moe = false;
2220                    let mut clear_metal_kv = false;
2221                    if let Some(guard) = metal_kv_guard.as_mut() {
2222                        if let Some(metal_kvs) = guard.as_mut() {
2223                            // Metal-authoritative: host may lag after dense-stack skip.
2224                            // Stack-only features (SWA / sandwich norms / GeGLU /
2225                            // per-layer theta) are NOT encoded by the per-layer
2226                            // launches — those layers must go to CPU here.
2227                            if metal_kvs[l].seq_len == pos
2228                                && !self.layer_needs_metal_stack(layer, l)
2229                            {
2230                                if let (Some(q_l), Some(k_l), Some(v_l), Some(o_l)) = (
2231                                    Self::metal_matvec_launch(&layer.attn.q_proj),
2232                                    Self::metal_matvec_launch(&layer.attn.k_proj),
2233                                    Self::metal_matvec_launch(&layer.attn.v_proj),
2234                                    Self::metal_matvec_launch(&layer.attn.o_proj),
2235                                ) {
2236                                    // Full dense layer on one CB when FFN is Metal-capable.
2237                                    if Self::layer_supports_metal_dense_ffn(layer) {
2238                                        let dense_ok = layer.moe.with_expert(0, |ex| {
2239                                        let (Some(g_l), Some(u_l), Some(d_l)) = (
2240                                            Self::metal_matvec_launch(&ex.gate),
2241                                            Self::metal_matvec_launch(&ex.up),
2242                                            Self::metal_matvec_launch(&ex.down),
2243                                        ) else {
2244                                            return false;
2245                                        };
2246                                        match ferrox_metal::attn::launch_decode_dense_layer(
2247                                            &hidden,
2248                                            &layer.attn.norm_weight,
2249                                            &q_l,
2250                                            &k_l,
2251                                            &v_l,
2252                                            &o_l,
2253                                            &mut metal_kvs[l],
2254                                            &layer.moe.norm_weight,
2255                                            &g_l,
2256                                            &u_l,
2257                                            &d_l,
2258                                            n_heads,
2259                                            self.metal_rope(),
2260                                            self.config.rope_theta,
2261                                            self.config.layer_rope_freqs(l),
2262                                            pos,
2263                                            self.config.rms_norm_eps,
2264                                            &self.metal_attn_extras(layer),
2265                                        ) {
2266                                            Ok(new_h) => {
2267                                                // Catch up any dense-stack lag + this token.
2268                                                Self::catch_up_host_kv_from_metal(
2269                                                    &metal_kvs[l],
2270                                                    cache,
2271                                                );
2272                                                layer.moe.record_activations(&[0]);
2273                                                hidden = new_h;
2274                                                true
2275                                            }
2276                                            Err(e) => {
2277                                                eprintln!(
2278                                                    "ferrox: Metal dense layer failed, CPU fallback: {e}"
2279                                                );
2280                                                false
2281                                            }
2282                                        }
2283                                    });
2284                                        if dense_ok {
2285                                            did_metal_dense = true;
2286                                            did_metal_attn = true;
2287                                        } else if metal_kvs[l].seq_len != cache.rows() {
2288                                            // Dense path may have advanced Metal KV before failing.
2289                                            Self::catch_up_host_kv_from_metal(&metal_kvs[l], cache);
2290                                            clear_metal_kv = true;
2291                                        }
2292                                    }
2293
2294                                    // Resident MoE: attn+router on GPU, host top-k only,
2295                                    // then batched experts — no hidden download/upload.
2296                                    if !did_metal_dense
2297                                        && !clear_metal_kv
2298                                        && Self::layer_supports_metal_moe_resident(
2299                                            layer,
2300                                            &self.config,
2301                                        )
2302                                    {
2303                                        if let Some(router_l) =
2304                                            Self::metal_matvec_launch(&layer.moe.router)
2305                                        {
2306                                            let seed_ok = if metal_moe_resident {
2307                                                true
2308                                            } else {
2309                                                match ferrox_metal::attn::moe_decode_seed(&hidden) {
2310                                                    Ok(()) => {
2311                                                        metal_moe_resident = true;
2312                                                        true
2313                                                    }
2314                                                    Err(e) => {
2315                                                        eprintln!(
2316                                                            "ferrox: Metal MoE seed failed: {e}"
2317                                                        );
2318                                                        false
2319                                                    }
2320                                                }
2321                                            };
2322                                            if seed_ok {
2323                                                // Prefer one-CB fused path (GPU top-k + packed experts).
2324                                                // See
2325                                                // `layer_supports_metal_moe_resident`:
2326                                                // the fused decode kernel
2327                                                // routes on the GPU and
2328                                                // has no `exp_probs_b` /
2329                                                // `expert_weights_scale`
2330                                                // input either.
2331                                                let fused_ok = match &layer.moe.experts {
2332                                                    ExpertBacking::Resident(_) => {
2333                                                        if let Some(packed) =
2334                                                            Self::moe_packed_q4(&layer.moe)
2335                                                        {
2336                                                            match ferrox_metal::attn::launch_moe_decode_layer_fused(
2337                                                                &layer.attn.norm_weight,
2338                                                                &q_l,
2339                                                                &k_l,
2340                                                                &v_l,
2341                                                                &o_l,
2342                                                                &mut metal_kvs[l],
2343                                                                &layer.moe.norm_weight,
2344                                                                &router_l,
2345                                                                &packed,
2346                                                                self.config.moe.n_experts_active,
2347                                                                self.config.moe.norm_topk_prob,
2348                                                                n_heads,
2349                                                                self.metal_rope(),
2350                                                                self.config.rope_theta,
2351                                                                self.config.layer_rope_freqs(l),
2352                                                                pos,
2353                                                                self.config.rms_norm_eps,
2354                                                                &self.metal_attn_extras(layer),
2355                                                            ) {
2356                                                                Ok(ids) => {
2357                                                                    layer.moe.record_activations(&ids);
2358                                                                    did_metal_moe = true;
2359                                                                    did_metal_attn = true;
2360                                                                    true
2361                                                                }
2362                                                                Err(e) => {
2363                                                                    eprintln!(
2364                                                                        "ferrox: Metal MoE fused layer failed: {e}"
2365                                                                    );
2366                                                                    false
2367                                                                }
2368                                                            }
2369                                                        } else {
2370                                                            false
2371                                                        }
2372                                                    }
2373                                                    _ => false,
2374                                                };
2375
2376                                                if !fused_ok {
2377                                                    match ferrox_metal::attn::launch_moe_decode_pre(
2378                                                        &layer.attn.norm_weight,
2379                                                        &q_l,
2380                                                        &k_l,
2381                                                        &v_l,
2382                                                        &o_l,
2383                                                        &mut metal_kvs[l],
2384                                                        &layer.moe.norm_weight,
2385                                                        &router_l,
2386                                                        n_heads,
2387                                                        self.metal_rope(),
2388                                                        self.config.rope_theta,
2389                                                        self.config.layer_rope_freqs(l),
2390                                                        pos,
2391                                                        self.config.rms_norm_eps,
2392                                                        &self.metal_attn_extras(layer),
2393                                                    ) {
2394                                                        Ok(logits) => {
2395                                                            // Routing happens HERE, on the host,
2396                                                            // so there is no kernel limitation to
2397                                                            // excuse a second router: call the
2398                                                            // one every other host path calls.
2399                                                            let decision = Self::route_for_layer(
2400                                                                layer,
2401                                                                &logits,
2402                                                                &self.config,
2403                                                            );
2404                                                            layer.moe.record_activations(
2405                                                                &decision.expert_ids,
2406                                                            );
2407                                                            if let Some(()) = Self::try_metal_moe_experts_resident(
2408                                                            layer,
2409                                                            &decision,
2410                                                        ) {
2411                                                            did_metal_moe = true;
2412                                                            did_metal_attn = true;
2413                                                        } else if let Some(h) =
2414                                                            ferrox_metal::attn::moe_decode_take_hidden()
2415                                                        {
2416                                                            hidden = h;
2417                                                            metal_moe_resident = false;
2418                                                            // KV already advanced; finish FFN on host.
2419                                                            let normed2 = rms_norm(
2420                                                                &hidden,
2421                                                                &layer.moe.norm_weight,
2422                                                                self.config.rms_norm_eps,
2423                                                            );
2424                                                            let ffn_out = Self::combine_ffn_outputs_for_position(
2425                                                                layer,
2426                                                                &normed2,
2427                                                                &logits,
2428                                                                &self.config,
2429                                                                hidden_dim,
2430                                                                residency.as_ref().map(|p| p.layer_plan(l)),
2431                                                            );
2432                                                            for (h, f) in
2433                                                                hidden.iter_mut().zip(ffn_out.iter())
2434                                                            {
2435                                                                *h += f;
2436                                                            }
2437                                                            did_metal_attn = true;
2438                                                            did_metal_moe = true; // skip second FFN
2439                                                        }
2440                                                        }
2441                                                        Err(e) => {
2442                                                            eprintln!(
2443                                                            "ferrox: Metal MoE pre failed, fallback: {e}"
2444                                                        );
2445                                                            if let Some(h) =
2446                                                            ferrox_metal::attn::moe_decode_take_hidden()
2447                                                        {
2448                                                            hidden = h;
2449                                                        }
2450                                                            metal_moe_resident = false;
2451                                                            if metal_kvs[l].seq_len != cache.rows()
2452                                                            {
2453                                                                Self::catch_up_host_kv_from_metal(
2454                                                                    &metal_kvs[l],
2455                                                                    cache,
2456                                                                );
2457                                                                clear_metal_kv = true;
2458                                                            }
2459                                                        }
2460                                                    }
2461                                                }
2462                                            }
2463                                        }
2464                                    }
2465
2466                                    if !did_metal_dense && !did_metal_moe && !clear_metal_kv {
2467                                        match ferrox_metal::attn::launch_decode_attn_block(
2468                                            &normed,
2469                                            &q_l,
2470                                            &k_l,
2471                                            &v_l,
2472                                            &o_l,
2473                                            &mut metal_kvs[l],
2474                                            n_heads,
2475                                            self.metal_rope(),
2476                                            self.config.rope_theta,
2477                                            self.config.layer_rope_freqs(l),
2478                                            pos,
2479                                            &self.metal_attn_extras(layer),
2480                                            self.config.rms_norm_eps,
2481                                        ) {
2482                                            Ok(projected) => {
2483                                                // Keep Metal KV authoritative — skip per-layer
2484                                                // host catch-up (dense-stack style). Host is
2485                                                // flushed on CPU fallback / prefix sync.
2486                                                for (h, p) in
2487                                                    hidden.iter_mut().zip(projected.iter())
2488                                                {
2489                                                    *h += p;
2490                                                }
2491                                                did_metal_attn = true;
2492                                            }
2493                                            Err(e) => {
2494                                                eprintln!(
2495                                                "ferrox: Metal attn block failed, CPU fallback: {e}"
2496                                            );
2497                                                Self::catch_up_host_kv_from_metal(
2498                                                    &metal_kvs[l],
2499                                                    cache,
2500                                                );
2501                                                clear_metal_kv = true;
2502                                            }
2503                                        }
2504                                    }
2505                                }
2506                            } else if metal_kvs[l].seq_len > cache.rows() {
2507                                // Leaving Metal path: host must see full KV for CPU attn.
2508                                Self::catch_up_host_kv_from_metal(&metal_kvs[l], cache);
2509                            }
2510                        }
2511                        if clear_metal_kv {
2512                            **guard = None;
2513                        }
2514                    }
2515                    if did_metal_attn {
2516                        if !did_metal_dense && !did_metal_moe {
2517                            let normed2 =
2518                                rms_norm(&hidden, &layer.moe.norm_weight, self.config.rms_norm_eps);
2519                            let ffn_out = Self::run_ffn_block(
2520                                layer,
2521                                &normed2,
2522                                &self.config,
2523                                hidden_dim,
2524                                residency.as_ref().map(|p| p.layer_plan(l)),
2525                            );
2526                            for (h, f) in hidden.iter_mut().zip(ffn_out.iter()) {
2527                                *h += f;
2528                            }
2529                        }
2530                        continue;
2531                    }
2532                }
2533
2534                let oai = self.gpt_oss.as_ref().map(|g| &g.layers[l]);
2535                let projected =
2536                    self.attn_block(l, layer, &normed, pos, KvStep::Decode(&mut *cache));
2537                for (h, p) in hidden.iter_mut().zip(projected.iter()) {
2538                    *h += p;
2539                }
2540
2541                // --- MoE FFN block ---
2542                let normed2 = rms_norm(&hidden, &layer.moe.norm_weight, self.config.rms_norm_eps);
2543                let mut ffn_out = match oai {
2544                    Some(oai) => Self::gpt_oss_ffn(layer, oai, &normed2, &self.config, hidden_dim),
2545                    None => Self::run_ffn_block(
2546                        layer,
2547                        &normed2,
2548                        &self.config,
2549                        hidden_dim,
2550                        residency.as_ref().map(|p| p.layer_plan(l)),
2551                    ),
2552                };
2553                if let Some(post) = &layer.attn.post_ffn_norm {
2554                    ffn_out = rms_norm(&ffn_out, post, self.config.rms_norm_eps);
2555                }
2556                for (h, f) in hidden.iter_mut().zip(ffn_out.iter()) {
2557                    *h += f;
2558                }
2559            }
2560        } // run_cpu_layers
2561
2562        #[cfg(feature = "metal")]
2563        if metal_moe_resident {
2564            if let Some(h) = ferrox_metal::attn::moe_decode_take_hidden() {
2565                hidden = h;
2566            }
2567        }
2568
2569        // If Metal stack already ran final_norm, hidden is normalized; else
2570        // normalize here.
2571        #[cfg(feature = "metal")]
2572        let final_normed = if final_norm_done_in_stack {
2573            hidden.clone()
2574        } else {
2575            rms_norm(&hidden, &self.final_norm, self.config.rms_norm_eps)
2576        };
2577        #[cfg(not(feature = "metal"))]
2578        let final_normed = rms_norm(&hidden, &self.final_norm, self.config.rms_norm_eps);
2579
2580        let logits = self.logits_from_normed(&final_normed);
2581        // Clear dense-stack activation TLS after lm_head (may have consumed it).
2582        // Keep MoE scratch buffers alive across tokens — `moe_decode_seed`
2583        // overwrites `h` each token; clearing here forced full realloc.
2584        #[cfg(feature = "metal")]
2585        ferrox_metal::gpu::clear_resident_activation();
2586        logits
2587    }
2588
2589    /// Same computation as `forward_token`, but each layer's K/V cache
2590    /// is a `PagedKvCache` (block-table-indexed into a per-layer
2591    /// `PagedKvStore`) instead of a `KvCache`'s contiguous buffer --
2592    /// exercises the paged attention kernel in a real decode loop
2593    /// instead of only in isolation. `kv_caches`/`stores` are parallel
2594    /// per-layer arrays, mirroring `forward_token`'s `kv_caches: &mut
2595    /// [KvCache]`. Must produce bit-identical output to `forward_token`
2596    /// given stores sized so no layer ever exhausts its blocks --
2597    /// pinned by
2598    /// `forward_token_paged_matches_forward_token_bit_identical` and,
2599    /// per attention arm, by
2600    /// `every_paged_attention_arm_is_bit_identical_to_its_contiguous_twin`.
2601    ///
2602    /// This used to refuse gpt-oss outright, because the paged kernel
2603    /// had no attention-sink term and no sliding-window arm and would
2604    /// have answered differently from the contiguous path without
2605    /// saying so. It now mirrors all three arms of that dispatch, so
2606    /// the refusal is gone rather than merely relaxed.
2607    pub fn forward_token_paged(
2608        &self,
2609        token_id: usize,
2610        pos: usize,
2611        kv_caches: &mut [PagedKvCache],
2612        stores: &SharedPagedKv,
2613    ) -> Result<Vec<f32>, PagedStoreExhausted> {
2614        assert_eq!(kv_caches.len(), self.layers.len());
2615        assert_eq!(stores.layer_count(), self.layers.len());
2616        // All layers advance or none do. Pushing per layer with `?` and
2617        // failing at layer 3 of 4 leaves layers 0..2 holding a position
2618        // the rest do not, and nothing downstream reports it: the next
2619        // step simply attends over a shorter history in the tail
2620        // layers. Reserving one position everywhere first turns that
2621        // into a clean refusal.
2622        //
2623        // The guards span the check AND the push for the same reason
2624        // the prefill path holds them: otherwise another request takes
2625        // the blocks in between.
2626        {
2627            let mut guards = stores.write_all();
2628            for (cache, store) in kv_caches.iter().zip(guards.iter()) {
2629                if cache.blocks_needed_for(store, 1) > store.free_block_count() {
2630                    return Err(PagedStoreExhausted);
2631                }
2632            }
2633            // Reserve by taking the blocks now, so the per-layer pushes
2634            // below cannot fail. `PagedKvCache::reserve` grows the block
2635            // table without advancing `seq_len`, leaving each push a
2636            // pure write into a block this sequence already owns.
2637            for (cache, store) in kv_caches.iter_mut().zip(guards.iter_mut()) {
2638                cache
2639                    .reserve(store, 1)
2640                    .expect("checked against free_block_count under this same guard");
2641            }
2642        }
2643        let hidden_dim = self.config.hidden_dim;
2644
2645        let mut hidden = self.embed_token(token_id);
2646        let residency = self.gpu_vram_budget_bytes.map(|b| self.residency_plan(b));
2647
2648        for (l, (layer, cache)) in self.layers.iter().zip(kv_caches.iter_mut()).enumerate() {
2649            // --- attention block ---
2650            let normed = rms_norm(&hidden, &layer.attn.norm_weight, self.config.rms_norm_eps);
2651
2652            // The same body the contiguous path runs, with the paged
2653            // backing as its one parameter. It used to be a copy, and
2654            // the copy had silently dropped `attention_scale`,
2655            // `post_attn_norm`, `post_ffn_norm`, gpt-oss's `o_bias` and
2656            // `gpt_oss_ffn` -- five features that each produce a
2657            // plausible distribution rather than an error.
2658            let oai = self.gpt_oss.as_ref().map(|g| &g.layers[l]);
2659            let projected = self.attn_block(
2660                l,
2661                layer,
2662                &normed,
2663                pos,
2664                KvStep::Paged {
2665                    cache: &mut *cache,
2666                    stores,
2667                },
2668            );
2669            for (h, p) in hidden.iter_mut().zip(projected.iter()) {
2670                *h += p;
2671            }
2672
2673            // --- MoE FFN block ---
2674            let normed2 = rms_norm(&hidden, &layer.moe.norm_weight, self.config.rms_norm_eps);
2675            let mut ffn_out = match oai {
2676                Some(oai) => Self::gpt_oss_ffn(layer, oai, &normed2, &self.config, hidden_dim),
2677                None => Self::run_ffn_block(
2678                    layer,
2679                    &normed2,
2680                    &self.config,
2681                    hidden_dim,
2682                    residency.as_ref().map(|p| p.layer_plan(l)),
2683                ),
2684            };
2685            if let Some(post) = &layer.attn.post_ffn_norm {
2686                ffn_out = rms_norm(&ffn_out, post, self.config.rms_norm_eps);
2687            }
2688            for (h, f) in hidden.iter_mut().zip(ffn_out.iter()) {
2689                *h += f;
2690            }
2691        }
2692
2693        let final_normed = rms_norm(&hidden, &self.final_norm, self.config.rms_norm_eps);
2694        Ok(self.logits_from_normed(&final_normed))
2695    }
2696
2697    /// The shared expert store's live counters, when this model runs
2698    /// with store-backed (streamed) routed experts -- `None` for fully
2699    /// resident models. Every store-backed layer shares one store, so
2700    /// the first one found speaks for the whole model.
2701    pub fn expert_store_stats(&self) -> Option<ferrox_core::expert_store::ExpertStoreStats> {
2702        self.layers.iter().find_map(|l| match &l.moe.experts {
2703            ExpertBacking::Stored { store, .. } => Some(store.stats()),
2704            ExpertBacking::Resident(_) => None,
2705        })
2706    }
2707
2708    /// Builds one global device-residency plan across ALL layers'
2709    /// routed experts against the single configured VRAM budget --
2710    /// every `(layer, expert)` candidate competes in one hotness-
2711    /// ordered pass and the running byte total is shared, so the
2712    /// budget cannot be re-spent per layer (the accounting bug the
2713    /// earlier per-layer `placement_plan` calls had: N layers would
2714    /// plan N x the configured bytes). Dense layers contribute no
2715    /// candidates (their sole expert always runs on CPU). Rebuilt per
2716    /// forward call so it tracks observed hotness; not yet
2717    /// performance-tuned, a disclosed limit.
2718    fn residency_plan(&self, vram_budget_bytes: u64) -> ferrox_moe::ResidencyPlan {
2719        let mut sizes_per_layer: Vec<Vec<usize>> = Vec::with_capacity(self.layers.len());
2720        let mut counts_per_layer: Vec<Vec<u64>> = Vec::with_capacity(self.layers.len());
2721        let mut any_observed = false;
2722        for layer in &self.layers {
2723            if Self::is_dense_layer(layer) {
2724                sizes_per_layer.push(Vec::new());
2725                counts_per_layer.push(Vec::new());
2726                continue;
2727            }
2728            sizes_per_layer.push(
2729                (0..layer.moe.n_experts())
2730                    .map(|e| layer.moe.expert_bytes(e))
2731                    .collect(),
2732            );
2733            let counts: Vec<u64> = layer
2734                .moe
2735                .activation_counts
2736                .iter()
2737                .map(|c| c.load(Ordering::Relaxed))
2738                .collect();
2739            any_observed |= counts.iter().any(|&c| c > 0);
2740            counts_per_layer.push(counts);
2741        }
2742        PlacementPlan::plan_layers_against_global_budget(
2743            &sizes_per_layer,
2744            any_observed.then_some(counts_per_layer.as_slice()),
2745            vram_budget_bytes,
2746        )
2747    }
2748
2749    /// True if this layer has nothing to route: exactly one expert and
2750    /// no shared experts, the shape every non-MoE model (and every
2751    /// DeepSeek-style "leading dense layer") loads as. Top-1 selection
2752    /// out of one expert always picks it, and its weight is always
2753    /// exactly 1.0 regardless of gating function (softmax over one
2754    /// logit is trivially 1.0; sigmoid-then-renormalize divides the
2755    /// selected score by itself) -- so skipping the router matmul,
2756    /// `route_top_k`'s sort/exp/renormalize work, and
2757    /// `combine_expert_outputs`'s Vec-wrapping for this case is not an
2758    /// approximation, it produces the exact same result.
2759    fn is_dense_layer(layer: &LayerWeights) -> bool {
2760        layer.moe.n_experts() == 1 && layer.moe.shared_experts.is_empty()
2761    }
2762
2763    /// llama.cpp `mul_mat_id` style: shared Q8 act + one flat parallel
2764    /// region over `(slot, row_pair)` for gate∥up (2-row SDOT), then
2765    /// SwiGLU, then per-slot down. Three regions, none nested, all
2766    /// through `ferrox_core::par` so they follow whichever scheduler
2767    /// `FERROX_CPU_POOL` selected.
2768    fn cpu_moe_topk_parallel_slots(
2769        experts: &[ExpertWeights],
2770        normed2: &[f32],
2771        decision: &ferrox_moe::RoutingDecision,
2772        hidden_dim: usize,
2773        act: GluAct,
2774    ) -> Option<Vec<(Vec<f32>, f32)>> {
2775        if !ferrox_core::weight_matrix::cpu_int_dot_enabled() || !normed2.len().is_multiple_of(32) {
2776            return None;
2777        }
2778        let n_slots = decision.expert_ids.len();
2779        if n_slots == 0 {
2780            return Some(Vec::new());
2781        }
2782        for &eid in &decision.expert_ids {
2783            let ex = experts.get(eid)?;
2784            if ex.gate.rows() == 0
2785                || ex.up.rows() != ex.gate.rows()
2786                || ex.down.rows() != hidden_dim
2787                || ex.gate.cols() != normed2.len()
2788                || ex.up.cols() != normed2.len()
2789                || ex.down.cols() != ex.gate.rows()
2790            {
2791                return None;
2792            }
2793            if !matches!(
2794                &ex.gate,
2795                WeightMatrix::Quantized {
2796                    kind: ferrox_core::QuantKind::Q4_0 | ferrox_core::QuantKind::Q8_0,
2797                    ..
2798                }
2799            ) || !matches!(
2800                &ex.up,
2801                WeightMatrix::Quantized {
2802                    kind: ferrox_core::QuantKind::Q4_0 | ferrox_core::QuantKind::Q8_0,
2803                    ..
2804                }
2805            ) {
2806                return None;
2807            }
2808        }
2809        let ffn_rows = experts[decision.expert_ids[0]].gate.rows();
2810        // Even ffn_rows: par_chunks_mut(2) never crosses a slot boundary.
2811        if !ffn_rows.is_multiple_of(2) {
2812            return None;
2813        }
2814        let q8 = ferrox_quant::quantize_activations_q8(normed2);
2815        let eids = &decision.expert_ids;
2816        let mut gate = vec![0f32; n_slots * ffn_rows];
2817        let mut up = vec![0f32; n_slots * ffn_rows];
2818        ferrox_core::par::chunks_mut2(&mut gate, &mut up, 2, 1, |p, gc, uc| {
2819            let row0 = p * 2;
2820            let slot = row0 / ffn_rows;
2821            let r = row0 % ffn_rows;
2822            let ex = &experts[eids[slot]];
2823            if let (Some((g0, g1)), Some((u0, u1))) = (
2824                ex.gate.dot_pair_cpu_q8(r, &q8),
2825                ex.up.dot_pair_cpu_q8(r, &q8),
2826            ) {
2827                gc[0] = g0;
2828                gc[1] = g1;
2829                uc[0] = u0;
2830                uc[1] = u1;
2831            } else {
2832                gc[0] = ex.gate.dot_row_cpu_q8(r, &q8).unwrap_or(0.0);
2833                gc[1] = ex.gate.dot_row_cpu_q8(r + 1, &q8).unwrap_or(0.0);
2834                uc[0] = ex.up.dot_row_cpu_q8(r, &q8).unwrap_or(0.0);
2835                uc[1] = ex.up.dot_row_cpu_q8(r + 1, &q8).unwrap_or(0.0);
2836            }
2837        });
2838        let mut activated = vec![0f32; n_slots * ffn_rows];
2839        // Generic over the gate nonlinearity rather than two copies of
2840        // the loop, and monomorphised so the call still inlines: the
2841        // combine here is always parallel (decode's `n_slots * ffn_rows`
2842        // sits under `ferrox_core::matmul`'s own fork threshold), which
2843        // is why this does not just call `act.apply`.
2844        fn combine<F: Fn(f32) -> f32 + Sync>(out: &mut [f32], gate: &[f32], up: &[f32], f: F) {
2845            ferrox_core::par::items_mut(out, 1, |idx, a| *a = f(gate[idx]) * up[idx]);
2846        }
2847        match act {
2848            GluAct::Swiglu => combine(&mut activated, &gate, &up, ferrox_core::matmul::silu),
2849            GluAct::Geglu => combine(&mut activated, &gate, &up, ferrox_core::matmul::gelu),
2850        }
2851        let mut outs: Vec<(Vec<f32>, f32)> = decision
2852            .weights
2853            .iter()
2854            .map(|&w| (vec![0f32; hidden_dim], w))
2855            .collect();
2856        ferrox_core::par::items_mut(&mut outs, 1, |slot, (out, _)| {
2857            let ex = &experts[eids[slot]];
2858            let act_slot = &activated[slot * ffn_rows..(slot + 1) * ffn_rows];
2859            if act_slot.len().is_multiple_of(32) {
2860                let down_q8 = ferrox_quant::quantize_activations_q8(act_slot);
2861                if let Some(d) = ex.down.apply_cpu_q8(&down_q8) {
2862                    *out = d;
2863                    return;
2864                }
2865            }
2866            *out = ex.down.apply(act_slot);
2867        });
2868        Some(outs)
2869    }
2870
2871    /// Fallback: serial top-k with shared Q8 act (pre-mul_mat_id path).
2872    fn cpu_moe_serial_experts(
2873        layer: &LayerWeights,
2874        normed2: &[f32],
2875        decision: &ferrox_moe::RoutingDecision,
2876        plan: Option<&PlacementPlan>,
2877        act: GluAct,
2878    ) -> Vec<(Vec<f32>, f32)> {
2879        let shared_act = if ferrox_core::weight_matrix::cpu_int_dot_enabled()
2880            && normed2.len().is_multiple_of(32)
2881            && plan
2882                .map(|p| {
2883                    decision
2884                        .expert_ids
2885                        .iter()
2886                        .all(|&eid| matches!(p.placement_for(eid), ExpertPlacement::Cpu))
2887                })
2888                .unwrap_or(true)
2889        {
2890            Some(ferrox_quant::quantize_activations_q8(normed2))
2891        } else {
2892            None
2893        };
2894        decision
2895            .expert_ids
2896            .iter()
2897            .zip(decision.weights.iter())
2898            .map(|(&eid, &w)| {
2899                let placement = plan
2900                    .map(|p| p.placement_for(eid))
2901                    .unwrap_or(ExpertPlacement::Cpu);
2902                let out = layer.moe.with_expert(eid, |ex| {
2903                    if let Some(ref q8) = shared_act {
2904                        if let (Some(gate), Some(up)) =
2905                            (ex.gate.apply_cpu_q8(q8), ex.up.apply_cpu_q8(q8))
2906                        {
2907                            let activated = act.apply(&gate, &up);
2908                            return ex.down.apply(&activated);
2909                        }
2910                    }
2911                    run_expert_placed(normed2, ex, placement, act)
2912                });
2913                (out, w)
2914            })
2915            .collect()
2916    }
2917
2918    /// Runs one position's normalized hidden state through this
2919    /// layer's MoE FFN block, given already-computed router logits for
2920    /// that position, returning the combined output to add back into
2921    /// the residual stream. Shared by `forward_token` (router computed
2922    /// via a single `apply` call, since there's only one position) and
2923    /// `forward_batch`'s per-position loop (router computed via one
2924    /// batched `apply_batch` call up front, sliced per position here --
2925    /// see `forward_batch`'s doc comment for why that batching matters
2926    /// and must not be lost by calling this per position instead).
2927    /// `gpu_vram_budget_bytes`: see `Decoder::gpu_vram_budget_bytes`'s
2928    /// doc comment -- `None` dispatches every routed expert through
2929    /// `run_expert_placed` with `ExpertPlacement::Cpu`, which is
2930    /// exactly `run_expert`'s own behavior, so this is a real
2931    /// zero-behavior-change default, not just "probably fine."
2932    /// One token's routing decision for one MoE layer.
2933    ///
2934    /// Three shapes, in the order llama.cpp's `build_moe_ffn` decides
2935    /// them: grouped selection when the checkpoint declares expert
2936    /// groups; the biased/scaled port when the layer carries
2937    /// `exp_probs_b` or the model carries a non-unit
2938    /// `expert_weights_scale`; otherwise the plain top-k this decoder has
2939    /// always used. The last arm is kept rather than folded into
2940    /// `route_top_k_biased` so that every checkpoint without those two
2941    /// features routes through byte-identical code to before.
2942    ///
2943    /// `exp_probs_b` together with expert groups is refused at load
2944    /// (`loader.rs`), so that combination cannot reach here.
2945    fn route_for_layer(
2946        layer: &LayerWeights,
2947        router_logits: &[f32],
2948        config: &ModelConfig,
2949    ) -> ferrox_moe::RoutingDecision {
2950        match (
2951            config.moe.expert_group_count,
2952            config.moe.expert_group_used_count,
2953        ) {
2954            (Some(n_groups), Some(k_per_group)) if n_groups > 1 && k_per_group > 0 => {
2955                ferrox_moe::route_top_k_grouped(
2956                    router_logits,
2957                    n_groups,
2958                    k_per_group,
2959                    config.moe.n_experts_active,
2960                    config.moe.gating,
2961                    config.moe.norm_topk_prob,
2962                )
2963            }
2964            _ if layer.moe.exp_probs_bias.is_some() || config.moe.expert_weights_scale != 1.0 => {
2965                ferrox_moe::route_top_k_biased(
2966                    router_logits,
2967                    layer.moe.exp_probs_bias.as_deref(),
2968                    config.moe.n_experts_active,
2969                    config.moe.gating,
2970                    config.moe.norm_topk_prob,
2971                    config.moe.expert_weights_scale,
2972                )
2973            }
2974            _ => route_top_k(
2975                router_logits,
2976                config.moe.n_experts_active,
2977                config.moe.gating,
2978                config.moe.norm_topk_prob,
2979            ),
2980        }
2981    }
2982
2983    fn combine_ffn_outputs_for_position(
2984        layer: &LayerWeights,
2985        normed2: &[f32],
2986        router_logits: &[f32],
2987        config: &ModelConfig,
2988        hidden_dim: usize,
2989        plan: Option<&PlacementPlan>,
2990    ) -> Vec<f32> {
2991        let decision = Self::route_for_layer(layer, router_logits, config);
2992        let act = GluAct::from(config.ffn_activation);
2993        layer.moe.record_activations(&decision.expert_ids);
2994        // Best-effort warm of the routed experts for this layer into
2995        // the store cache (SSD streaming overlap). Resident-backed
2996        // layers skip this entirely.
2997        if let ExpertBacking::Stored {
2998            store,
2999            layer: layer_id,
3000            ..
3001        } = &layer.moe.experts
3002        {
3003            let keys: Vec<ferrox_core::expert_store::ExpertKey> = decision
3004                .expert_ids
3005                .iter()
3006                .map(|&eid| ferrox_core::expert_store::ExpertKey {
3007                    layer: *layer_id,
3008                    expert: eid as u32,
3009                })
3010                .collect();
3011            store.prefetch(&keys);
3012        }
3013
3014        // Metal: fuse all top-k experts into one CB (one wait) when every
3015        // routed expert has Metal matvec launches. Shared experts (rare
3016        // for OLMoE) still run on the host after.
3017        // `launch_moe_topk_swiglu` is SwiGLU-only, so a GeGLU MoE layer
3018        // keeps the host path rather than taking a kernel that computes
3019        // a different activation.
3020        #[cfg(feature = "metal")]
3021        if ferrox_core::metal_dense_enabled()
3022            && act.is_swiglu()
3023            && layer.moe.shared_experts.is_empty()
3024        {
3025            if let Some(fused) = Self::try_metal_moe_topk(layer, normed2, &decision) {
3026                return fused;
3027            }
3028        }
3029
3030        let routed_outputs: Vec<(Vec<f32>, f32)> = {
3031            // llama.cpp mul_mat_id: one shared Q8 act + flat (slot,row)
3032            // parallel over all top-k experts (not serial expert loops each
3033            // with their own rayon fork-join).
3034            let all_cpu = plan
3035                .map(|p| {
3036                    decision
3037                        .expert_ids
3038                        .iter()
3039                        .all(|&eid| matches!(p.placement_for(eid), ExpertPlacement::Cpu))
3040                })
3041                .unwrap_or(true);
3042            if let (true, ExpertBacking::Resident(experts)) = (all_cpu, &layer.moe.experts) {
3043                if let Some(outs) =
3044                    Self::cpu_moe_topk_parallel_slots(experts, normed2, &decision, hidden_dim, act)
3045                {
3046                    outs
3047                } else {
3048                    Self::cpu_moe_serial_experts(layer, normed2, &decision, plan, act)
3049                }
3050            } else {
3051                Self::cpu_moe_serial_experts(layer, normed2, &decision, plan, act)
3052            }
3053        };
3054        // Shared experts fire on every token regardless of routing, so
3055        // there's no offload decision to make for them the way there
3056        // is for routed experts -- always CPU, matching `run_expert`.
3057        let mut shared_outputs: Vec<Vec<f32>> = layer
3058            .moe
3059            .shared_experts
3060            .iter()
3061            .map(|e| run_expert(normed2, e, act))
3062            .collect();
3063        // Qwen2-MoE-specific: see `MoeWeights::shared_expert_gate`'s doc
3064        // comment. Scaling here (before `combine_expert_outputs`, which
3065        // is architecture-agnostic and knows nothing about this gate)
3066        // keeps the gate a decoder-level detail, not a ferrox-moe API
3067        // change.
3068        if let Some(gate) = &layer.moe.shared_expert_gate {
3069            let gate_logit: f32 = gate.iter().zip(normed2.iter()).map(|(g, x)| g * x).sum();
3070            let gate_value = 1.0 / (1.0 + (-gate_logit).exp());
3071            for out in shared_outputs.iter_mut() {
3072                for x in out.iter_mut() {
3073                    *x *= gate_value;
3074                }
3075            }
3076        }
3077
3078        combine_expert_outputs(&routed_outputs, &shared_outputs, hidden_dim)
3079    }
3080
3081    /// The dense FFN for a whole batch of positions in three batched
3082    /// matmuls (gate, up, down) instead of three per position.
3083    ///
3084    /// This is the counterpart of what `forward_hidden_batch` already
3085    /// did for Q/K/V and the router, and it is where a dense model's
3086    /// prefill time actually goes: `WeightMatrix::apply_batch` reads
3087    /// each weight row once and dots it against every position, rather
3088    /// than re-reading the whole FFN for each one.
3089    ///
3090    /// `None` for anything that is not a plain dense layer -- MoE
3091    /// routing is per position by construction, so those keep the
3092    /// sequential path.
3093    ///
3094    /// On a GPU backend the per-position alternative is one *fused*
3095    /// gate+up+SiLU+down launch (`apply_gpu_dense_ffn_swiglu`), so this
3096    /// used to be gated off there: three separate batched launches lost
3097    /// to it while `apply_batch` was still a batched *matvec*.
3098    ///
3099    /// That stopped being true once the simdgroup GEMM landed, and the
3100    /// old gate turned out to be the dominant cost of Metal prefill --
3101    /// a 512-token prompt ran the FFN one position at a time, 512 x
3102    /// n_layers fused launches, which a profile put at 90% of prefill
3103    /// while the GEMM it bypassed accounted for 21%.
3104    ///
3105    /// Decode (`batch_size == 1`) still takes the fused per-position
3106    /// launch, which is the right shape there.
3107    fn dense_ffn_batch(
3108        layer: &LayerWeights,
3109        normed2_batch: &[f32],
3110        batch_size: usize,
3111        config: &ModelConfig,
3112    ) -> Option<Vec<f32>> {
3113        // Match the GPU `mul_mm` threshold: below it the per-call launch
3114        // overhead outweighs the weight reuse.
3115        if !Self::is_dense_layer(layer) || batch_size < 4 {
3116            return None;
3117        }
3118        // On a GPU backend this only wins when the weights have a real
3119        // batched GEMM; otherwise `apply_batch` is a batched matvec and
3120        // loses to the fused per-position launch.
3121        #[cfg(any(feature = "metal", feature = "cuda"))]
3122        {
3123            #[cfg(feature = "metal")]
3124            let gpu_dense = ferrox_core::weight_matrix::metal_dense_enabled();
3125            #[cfg(not(feature = "metal"))]
3126            let gpu_dense = false;
3127            #[cfg(feature = "cuda")]
3128            let gpu_dense = gpu_dense || ferrox_core::weight_matrix::cuda_dense_enabled();
3129            if gpu_dense {
3130                let all_gemm = layer.moe.with_expert(0, |ex| {
3131                    ex.gate.prefers_gpu_batch()
3132                        && ex.up.prefers_gpu_batch()
3133                        && ex.down.prefers_gpu_batch()
3134                });
3135                if !all_gemm {
3136                    return None;
3137                }
3138            }
3139        }
3140        layer.moe.record_activations(&[0]);
3141        // One command buffer for the whole FFN when every matrix has a
3142        // simdgroup GEMM: gate and up feed the activation and the down
3143        // projection without the intermediates ever touching the host.
3144        // Three separate launches cost three round trips per layer plus
3145        // four copies of a `batch x ffn_dim` tensor.
3146        #[cfg(feature = "metal")]
3147        if ferrox_core::weight_matrix::metal_dense_enabled() {
3148            let gelu = !GluAct::from(config.ffn_activation).is_swiglu();
3149            let fused = layer.moe.with_expert(0, |ex| {
3150                let (g, u, d) = (
3151                    ex.gate.mul_mm_sg_launch()?,
3152                    ex.up.mul_mm_sg_launch()?,
3153                    ex.down.mul_mm_sg_launch()?,
3154                );
3155                ferrox_metal::gpu::launch_dense_ffn_swiglu_batch(
3156                    &g,
3157                    &u,
3158                    &d,
3159                    normed2_batch,
3160                    batch_size,
3161                    gelu,
3162                )
3163                .ok()
3164            });
3165            if let Some(out) = fused {
3166                return Some(out);
3167            }
3168        }
3169        Some(layer.moe.with_expert(0, |ex| {
3170            let ffn_acts = ex.gate.quantize_batch_acts(normed2_batch, batch_size);
3171            let gate = ex
3172                .gate
3173                .apply_batch_with_acts(normed2_batch, batch_size, ffn_acts.as_ref());
3174            let up = ex
3175                .up
3176                .apply_batch_with_acts(normed2_batch, batch_size, ffn_acts.as_ref());
3177            let activated = GluAct::from(config.ffn_activation).apply(&gate, &up);
3178            ex.down.apply_batch(&activated, batch_size)
3179        }))
3180    }
3181
3182    /// CPU MoE prefill: bucket tokens by expert, then one
3183    /// `apply_batch` per expert with tokens instead of per-token
3184    /// `combine_ffn_outputs_for_position`. Shared experts append via
3185    /// [`Self::accumulate_shared_experts_batch`]. `None` when gates fail
3186    /// (small batch, dense, Metal preferred, non-resident, or any
3187    /// GPU-placed expert). Both gated activations are served here --
3188    /// the combine goes through [`GluAct`], so GeGLU no longer falls out
3189    /// to the per-position path.
3190    fn moe_ffn_batch(
3191        layer: &LayerWeights,
3192        normed2_batch: &[f32],
3193        router_logits_batch: &[f32],
3194        batch_size: usize,
3195        hidden_dim: usize,
3196        config: &ModelConfig,
3197        plan: Option<&PlacementPlan>,
3198    ) -> Option<Vec<f32>> {
3199        if batch_size < 32 || Self::is_dense_layer(layer) {
3200            return None;
3201        }
3202        // Metal prefill owns MoE when dense Metal is on
3203        // (`try_metal_moe_prefill_batch`); do not steal the path.
3204        #[cfg(feature = "metal")]
3205        if ferrox_core::metal_dense_enabled() {
3206            return None;
3207        }
3208        let act = GluAct::from(config.ffn_activation);
3209        let ExpertBacking::Resident(experts) = &layer.moe.experts else {
3210            return None;
3211        };
3212        let n_experts = experts.len();
3213        let all_cpu = plan
3214            .map(|p| (0..n_experts).all(|eid| matches!(p.placement_for(eid), ExpertPlacement::Cpu)))
3215            .unwrap_or(true);
3216        if !all_cpu || n_experts == 0 {
3217            return None;
3218        }
3219
3220        let mut buckets: Vec<Vec<(usize, f32)>> = vec![Vec::new(); n_experts];
3221        for b in 0..batch_size {
3222            let logits = &router_logits_batch[b * n_experts..(b + 1) * n_experts];
3223            let decision = Self::route_for_layer(layer, logits, config);
3224            layer.moe.record_activations(&decision.expert_ids);
3225            for (&eid, &w) in decision.expert_ids.iter().zip(decision.weights.iter()) {
3226                buckets[eid].push((b, w));
3227            }
3228        }
3229
3230        let mut acc = vec![0f32; batch_size * hidden_dim];
3231        for (eid, toks) in buckets.iter().enumerate() {
3232            if toks.is_empty() {
3233                continue;
3234            }
3235            let n = toks.len();
3236            let mut gathered = vec![0f32; n * hidden_dim];
3237            for (i, &(tok, _)) in toks.iter().enumerate() {
3238                gathered[i * hidden_dim..(i + 1) * hidden_dim]
3239                    .copy_from_slice(&normed2_batch[tok * hidden_dim..(tok + 1) * hidden_dim]);
3240            }
3241            let ex = &experts[eid];
3242            let ffn_acts = ex.gate.quantize_batch_acts(&gathered, n);
3243            let gate = ex
3244                .gate
3245                .apply_batch_with_acts(&gathered, n, ffn_acts.as_ref());
3246            let up = ex.up.apply_batch_with_acts(&gathered, n, ffn_acts.as_ref());
3247            let activated = act.apply(&gate, &up);
3248            let down = ex.down.apply_batch(&activated, n);
3249            for (i, &(tok, w)) in toks.iter().enumerate() {
3250                let out = &down[i * hidden_dim..(i + 1) * hidden_dim];
3251                let row = &mut acc[tok * hidden_dim..(tok + 1) * hidden_dim];
3252                for (a, &o) in row.iter_mut().zip(out.iter()) {
3253                    *a += w * o;
3254                }
3255            }
3256        }
3257
3258        Self::accumulate_shared_experts_batch(
3259            layer,
3260            normed2_batch,
3261            batch_size,
3262            hidden_dim,
3263            &mut acc,
3264            act,
3265        );
3266        Some(acc)
3267    }
3268
3269    /// gpt-oss's MoE FFN for one position.
3270    ///
3271    /// A separate function rather than another branch inside
3272    /// `combine_ffn_outputs_for_position` on purpose: that path carries
3273    /// expert-store prefetch, residency placement, a Metal top-k fusion
3274    /// and a batched parallel-slot kernel, and every one of them would
3275    /// need its own gpt-oss variant to stay honest. This is the whole
3276    /// gpt-oss FFN in one readable block, checked end-to-end against
3277    /// llama.cpp, and slow — routed experts run serially. It is the
3278    /// correct-first shape; making it fast is a separate change with its
3279    /// own A/B, not something to smuggle in under a correctness fix.
3280    ///
3281    /// Ported from `llama-graph.cpp::build_moe_ffn` with
3282    /// `gating_op = LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX_WEIGHT`,
3283    /// `type_op = LLM_FFN_SWIGLU_OAI_MOE`, `norm_w = false`,
3284    /// `w_scale = 1`, all four bias tensors present.
3285    fn gpt_oss_ffn(
3286        layer: &LayerWeights,
3287        oai: &GptOssLayer,
3288        normed2: &[f32],
3289        config: &ModelConfig,
3290        hidden_dim: usize,
3291    ) -> Vec<f32> {
3292        let mut router_logits = layer.moe.router.apply(normed2);
3293        for (x, b) in router_logits.iter_mut().zip(oai.router_bias.iter()) {
3294            *x += b;
3295        }
3296        // Selection on the raw biased logits, softmax over the winners
3297        // only -- see `route_top_k_softmax_weight`.
3298        let decision =
3299            ferrox_moe::route_top_k_softmax_weight(&router_logits, config.moe.n_experts_active);
3300        layer.moe.record_activations(&decision.expert_ids);
3301
3302        let mut out = vec![0f32; hidden_dim];
3303        for (slot, &eid) in decision.expert_ids.iter().enumerate() {
3304            let w = decision.weights[slot];
3305            let expert_out = layer.moe.with_expert(eid, |ex| {
3306                ferrox_moe::run_expert_oai(
3307                    normed2,
3308                    ex,
3309                    &oai.expert_bias[eid],
3310                    ferrox_moe::SWIGLU_OAI_ALPHA,
3311                    ferrox_moe::SWIGLU_OAI_LIMIT,
3312                )
3313            });
3314            for (o, e) in out.iter_mut().zip(expert_out.iter()) {
3315                *o += w * e;
3316            }
3317        }
3318        out
3319    }
3320
3321    /// `forward_token`'s MoE FFN block for one position: the dense
3322    /// fast path (see `is_dense_layer`) or the full router+combine path
3323    /// with the router computed inline via a single-position `apply`.
3324    fn run_ffn_block(
3325        layer: &LayerWeights,
3326        normed2: &[f32],
3327        config: &ModelConfig,
3328        hidden_dim: usize,
3329        plan: Option<&PlacementPlan>,
3330    ) -> Vec<f32> {
3331        if Self::is_dense_layer(layer) {
3332            layer.moe.record_activations(&[0]);
3333            // One expert, run exactly the way a routed one is. The GeGLU
3334            // arm used to be spelled out here and nowhere else, which is
3335            // precisely how the routed paths ended up SwiGLU-only.
3336            let act = GluAct::from(config.ffn_activation);
3337            return layer.moe.with_expert(0, |ex| run_expert(normed2, ex, act));
3338        }
3339        let router_logits = layer.moe.router.apply(normed2);
3340        Self::combine_ffn_outputs_for_position(
3341            layer,
3342            normed2,
3343            &router_logits,
3344            config,
3345            hidden_dim,
3346            plan,
3347        )
3348    }
3349
3350    /// Processes multiple new positions in one call instead of calling
3351    /// `forward_token` once per position. `tokens[i]` is the token at
3352    /// absolute position `start_pos + i`; all positions attend
3353    /// causally (position `i` sees positions `0..=i` of this batch
3354    /// plus everything already in `kv_caches`, nothing later).
3355    ///
3356    /// The attention block's Q/K/V/O projections and the MoE router
3357    /// are computed as batched matmuls (`WeightMatrix::apply_batch`),
3358    /// which for quantized weights means each weight row is read from
3359    /// memory once and dotted against every position in the batch,
3360    /// not once per position -- see `apply_batch`'s doc comment for
3361    /// why that's a real memory-bandwidth saving, not just fewer
3362    /// function calls. The expert FFN stage is *not* batched: which
3363    /// expert(s) a position routes to is data-dependent per position,
3364    /// so positions routed to different experts can't share a single
3365    /// matmul the way the shared Q/K/V/router projections can. RoPE
3366    /// and attention itself (causal masking, softmax) are also
3367    /// per-position, since they're cheap relative to the matmuls and
3368    /// batching them would add complexity for little benefit.
3369    ///
3370    /// This is what makes prompt-lookup speculative decoding
3371    /// (`speculative` module) actually save work rather than just
3372    /// reshuffle it: verifying `k` draft tokens costs one batched call
3373    /// here, not `k` calls to `forward_token`.
3374    ///
3375    /// Thin wrapper over [`Self::forward_hidden_batch`] + `output_head`.
3376    pub fn forward_batch(
3377        &self,
3378        tokens: &[usize],
3379        start_pos: usize,
3380        kv_caches: &mut [KvCache],
3381    ) -> Vec<Vec<f32>> {
3382        let hiddens = self.forward_hidden_batch(tokens, start_pos, kv_caches);
3383        if hiddens.is_empty() {
3384            return Vec::new();
3385        }
3386        let batch_size = hiddens.len();
3387        let flat: Vec<f32> = hiddens.into_iter().flatten().collect();
3388        self.logits_from_flat_hidden(flat, batch_size)
3389    }
3390
3391    /// [`Self::forward_batch`] that also hands back the final-layer
3392    /// hidden state for every position instead of dropping it.
3393    ///
3394    /// `forward_batch` computes these and throws them away; a
3395    /// hidden-state-conditioned drafter (EAGLE, MTP, dFlash) needs
3396    /// exactly the vector for the last *verified* position, so
3397    /// recomputing it would mean running the target model twice for
3398    /// something the first pass already had in hand. The extra cost
3399    /// here is one copy of `[batch x hidden]`, which is why
3400    /// `forward_batch` keeps its move-only path for the prefill case
3401    /// that does not want them.
3402    ///
3403    /// Returns `(logits_per_position, hidden_per_position)`, both
3404    /// indexed by position in `tokens`.
3405    pub fn forward_batch_with_hidden(
3406        &self,
3407        tokens: &[usize],
3408        start_pos: usize,
3409        kv_caches: &mut [KvCache],
3410    ) -> (Vec<Vec<f32>>, Vec<Vec<f32>>) {
3411        let hiddens = self.forward_hidden_batch(tokens, start_pos, kv_caches);
3412        if hiddens.is_empty() {
3413            return (Vec::new(), Vec::new());
3414        }
3415        let batch_size = hiddens.len();
3416        let flat: Vec<f32> = hiddens.iter().flatten().copied().collect();
3417        (self.logits_from_flat_hidden(flat, batch_size), hiddens)
3418    }
3419
3420    /// One token's embedding row, scaled if this checkpoint scales it.
3421    ///
3422    /// `embedding_scale` is `sqrt(hidden_dim)` on the Gemma family and
3423    /// `None` everywhere else, so a path that dequantizes the row and
3424    /// forgets the multiply is wrong on exactly one family and right on
3425    /// every other -- which is why it survived as a drift for as long as
3426    /// it did. The lookup and the scale live in one function so a caller
3427    /// cannot obtain the row without it.
3428    fn embed_token(&self, token_id: usize) -> Vec<f32> {
3429        let mut row = self.embedding.dequant_row(token_id);
3430        if let Some(scale) = self.config.embedding_scale {
3431            for v in row.iter_mut() {
3432                *v *= scale;
3433            }
3434        }
3435        row
3436    }
3437
3438    /// [`Self::embed_token`] for a whole batch: `[batch, hidden]`,
3439    /// flattened row-major.
3440    fn embed_tokens(&self, tokens: &[usize]) -> Vec<f32> {
3441        tokens.iter().flat_map(|&t| self.embed_token(t)).collect()
3442    }
3443
3444    /// The `output_head` half of a single-position forward: project the
3445    /// final-normed hidden state and softcap the result if this
3446    /// checkpoint softcaps it.
3447    ///
3448    /// The counterpart to [`Self::logits_from_flat_hidden`] for the
3449    /// one-row case, and held here for the same reason: Gemma-2 caps its
3450    /// final logits at 30.0, so a path that projects and returns without
3451    /// capping produces a different distribution -- not an error, just a
3452    /// quietly wrong one.
3453    fn logits_from_normed(&self, final_normed: &[f32]) -> Vec<f32> {
3454        Logits::from_output_head(
3455            self.output_head.apply(final_normed),
3456            self.config.final_logit_softcap,
3457        )
3458        .into_vec()
3459    }
3460
3461    /// The `output_head` half of [`Self::forward_batch`], split out so
3462    /// the hidden-state-returning variant cannot drift from it (a
3463    /// second copy of the softcap would be a silent quality bug).
3464    fn logits_from_flat_hidden(&self, flat: Vec<f32>, batch_size: usize) -> Vec<Vec<f32>> {
3465        let vocab_size = self.output_head.rows();
3466        let logits_batch = Logits::from_output_head(
3467            self.output_head.apply_batch(&flat, batch_size),
3468            self.config.final_logit_softcap,
3469        );
3470        logits_batch
3471            .as_slice()
3472            .chunks(vocab_size)
3473            .map(|c| c.to_vec())
3474            .collect()
3475    }
3476
3477    /// [`Self::forward_batch`] for the common case where only the final
3478    /// position's logits are wanted: prefill a prompt, then sample the
3479    /// next token. Runs `output_head` on **one** row instead of all
3480    /// `batch_size` of them.
3481    ///
3482    /// The KV cache and every hidden state are identical either way —
3483    /// only the vocabulary projection is skipped, and only for rows
3484    /// whose logits the caller was going to drop. That projection is not
3485    /// a rounding error: it is `[batch x hidden] x [hidden x vocab]`,
3486    /// which for a large-vocabulary model with a small body is a large
3487    /// share of prefill. `V*H / (V*H + L*P_layer)` comes to 30% on
3488    /// Gemma-3-1B, 21% on Llama-3.2-1B and SmolLM2, 23% on Gemma-2-2B.
3489    /// llama.cpp does not do this work at all during `pp512` —
3490    /// `llama_batch_get_one` leaves `logits` unset, so `inp_out_ids`
3491    /// selects a single row.
3492    ///
3493    /// [`Self::forward_batch`] stays for the callers that genuinely need
3494    /// every row: speculative verification checks each draft position,
3495    /// and `/v1/embeddings` pools over all of them.
3496    pub fn forward_batch_last(
3497        &self,
3498        tokens: &[usize],
3499        start_pos: usize,
3500        kv_caches: &mut [KvCache],
3501    ) -> Vec<f32> {
3502        self.forward_batch_last_inner(tokens, start_pos, kv_caches, false)
3503    }
3504
3505    /// [`Self::forward_batch_last`] for a caller that will READ the
3506    /// caches afterwards rather than only decode from them.
3507    ///
3508    /// A Metal prefill otherwise leaves K/V on the device and the host
3509    /// rows zero-filled, which is invisible to a caller that keeps
3510    /// decoding (the device buffers stay authoritative) and fatal to
3511    /// one that copies the rows somewhere else. Two callers do copy
3512    /// them: `forward_batch_last_paged`, into the page store, and
3513    /// `ferrox-server`'s prefix cache, into a snapshot a later request
3514    /// restores from. Both used to get zeros, and both answered fluent
3515    /// nonsense from a prompt the model never attended over.
3516    ///
3517    /// Costs one KV download per layer. Use [`Self::forward_batch_last`]
3518    /// when nothing will read the caches back.
3519    pub fn forward_batch_last_host_kv(
3520        &self,
3521        tokens: &[usize],
3522        start_pos: usize,
3523        kv_caches: &mut [KvCache],
3524    ) -> Vec<f32> {
3525        self.forward_batch_last_inner(tokens, start_pos, kv_caches, true)
3526    }
3527
3528    /// [`Self::forward_batch_last`], plus the choice of whether the host
3529    /// caches have to hold the real K/V when it returns. See
3530    /// [`Self::advance_host_kv_after_metal_prefill`] for why that is a
3531    /// choice at all.
3532    fn forward_batch_last_inner(
3533        &self,
3534        tokens: &[usize],
3535        start_pos: usize,
3536        kv_caches: &mut [KvCache],
3537        host_kv_authoritative: bool,
3538    ) -> Vec<f32> {
3539        let hiddens =
3540            self.forward_hidden_batch_inner(tokens, start_pos, kv_caches, host_kv_authoritative);
3541        let Some(last) = hiddens.last() else {
3542            return Vec::new();
3543        };
3544        self.logits_from_normed(last)
3545    }
3546
3547    /// [`Self::forward_batch_last`] over paged KV: the prefill twin of
3548    /// [`Self::forward_token_paged`].
3549    ///
3550    /// # Why this gathers instead of paging the kernel
3551    ///
3552    /// `forward_hidden_batch`'s fast arm hands `cache.k` / `cache.v` to
3553    /// `causal_gqa_attention_prefill_shared_kv_windowed`, which is Rayon
3554    /// over `[query-block x head]` against one flat KV buffer. That
3555    /// blocking is why CPU prefill is not the per-query path, and a
3556    /// block table cannot be handed to it as a slice.
3557    ///
3558    /// The alternative was a second blocked kernel that reads through
3559    /// the table. This file has just finished paying for what a second
3560    /// copy of a rule costs: the paged decode path silently lost the
3561    /// window arm, the sink term, the attention softcap, the embedding
3562    /// scale and the final logit softcap, one at a time, because it was
3563    /// a copy. A prefill kernel is a much larger surface to keep in
3564    /// step than any of those. So the pages are materialised, the ONE
3565    /// prefill implementation every other path uses runs against them,
3566    /// and the new rows go back.
3567    ///
3568    /// Bit-identity is therefore by construction rather than by
3569    /// agreement between two kernels: this calls the same function with
3570    /// the same values. What the tests pin is that the gather and the
3571    /// scatter are faithful, not that two implementations of attention
3572    /// happen to match.
3573    ///
3574    /// The cost is one KV-sized copy per layer per call, against the
3575    /// matmuls that dominate prefill. Decode is untouched: it still
3576    /// reads through the block table and copies nothing, which is where
3577    /// page sharing pays.
3578    ///
3579    /// # Failure is checked before anything is written
3580    ///
3581    /// Every layer's blocks are reserved up front, so a store too small
3582    /// for the batch refuses with `PagedStoreExhausted` having mutated
3583    /// no layer. A partial append would leave some layers longer than
3584    /// others, and no caller can recover from that.
3585    pub fn forward_batch_last_paged(
3586        &self,
3587        tokens: &[usize],
3588        start_pos: usize,
3589        kv_caches: &mut [PagedKvCache],
3590        stores: &SharedPagedKv,
3591    ) -> Result<Vec<f32>, PagedStoreExhausted> {
3592        assert_eq!(kv_caches.len(), self.layers.len());
3593        assert_eq!(stores.layer_count(), self.layers.len());
3594        if tokens.is_empty() {
3595            return Ok(Vec::new());
3596        }
3597
3598        // Reserve every layer up front, under guards spanning the check
3599        // AND the take. Each layer has its own store, so one having
3600        // room says nothing about the next -- and under concurrency,
3601        // checking and then taking as separate steps lets another
3602        // request slip in between and leave this one half-written.
3603        //
3604        // Reserving before the forward rather than after also means a
3605        // request that cannot fit is refused before it burns a prefill.
3606        {
3607            let mut guards = stores.write_all();
3608            for (cache, store) in kv_caches.iter().zip(guards.iter()) {
3609                if cache.blocks_needed_for(store, tokens.len()) > store.free_block_count() {
3610                    return Err(PagedStoreExhausted);
3611                }
3612            }
3613            for (cache, store) in kv_caches.iter_mut().zip(guards.iter_mut()) {
3614                cache
3615                    .reserve(store, tokens.len())
3616                    .expect("checked against free_block_count under this same guard");
3617            }
3618        }
3619
3620        // Gather under read guards, one layer at a time: the forward
3621        // below is the expensive part and holds nothing.
3622        let mut scratch: Vec<KvCache> = kv_caches
3623            .iter()
3624            .enumerate()
3625            .map(|(l, cache)| cache.to_contiguous(&stores.read(l)))
3626            .collect();
3627
3628        // `host_kv_authoritative`: the scatter below READS these caches,
3629        // and a Metal prefill otherwise leaves them holding
3630        // `advance_len` placeholders while the real K/V sits on the
3631        // device. Copying those placeholders into the page store is
3632        // what made paged KV on Metal answer fluent nonsense from a
3633        // prompt the model never attended over.
3634        let logits = self.forward_batch_last_inner(tokens, start_pos, &mut scratch, true);
3635
3636        // Scatter into blocks this sequence already owns. Nothing here
3637        // can fail, which is the point of reserving above.
3638        for (l, (cache, gathered)) in kv_caches.iter_mut().zip(&scratch).enumerate() {
3639            let mut store = stores.write(l);
3640            let width = store.n_kv_heads() * store.head_dim();
3641            let base = cache.seq_len() * width;
3642            cache
3643                .append_contiguous(
3644                    &mut store,
3645                    &gathered.k[base..],
3646                    &gathered.v[base..],
3647                    tokens.len(),
3648                )
3649                .expect("blocks reserved above are still held by this sequence");
3650        }
3651        Ok(logits)
3652    }
3653
3654    /// Like [`Self::forward_batch`], but returns final RMS-normed hidden
3655    /// states (pre-`output_head`) — one `hidden_dim` vector per input
3656    /// token. Used by `/v1/embeddings` pooling (mean / last).
3657    pub fn forward_hidden_batch(
3658        &self,
3659        tokens: &[usize],
3660        start_pos: usize,
3661        kv_caches: &mut [KvCache],
3662    ) -> Vec<Vec<f32>> {
3663        self.forward_hidden_batch_inner(tokens, start_pos, kv_caches, false)
3664    }
3665
3666    /// [`Self::forward_hidden_batch`] with one extra promise the public
3667    /// signature cannot express.
3668    ///
3669    /// `host_kv_authoritative` says whether the caller will READ
3670    /// `kv_caches` afterwards. Metal prefill normally leaves K/V on the
3671    /// device and fills the host rows with a `advance_len` placeholder,
3672    /// which is correct only because the contiguous decode path then
3673    /// reads the device buffers too. `forward_batch_last_paged` reads
3674    /// the host rows -- it copies them into the page store -- so it
3675    /// passes `true` and pays for the download.
3676    fn forward_hidden_batch_inner(
3677        &self,
3678        tokens: &[usize],
3679        start_pos: usize,
3680        kv_caches: &mut [KvCache],
3681        host_kv_authoritative: bool,
3682    ) -> Vec<Vec<f32>> {
3683        // Read only by the Metal arms below; a CPU-only build fills the
3684        // host cache with real rows on every path and has nothing to
3685        // choose between.
3686        let _ = host_kv_authoritative;
3687        assert_eq!(kv_caches.len(), self.layers.len());
3688        let batch_size = tokens.len();
3689        if batch_size == 0 {
3690            return Vec::new();
3691        }
3692
3693        let hidden_dim = self.config.hidden_dim;
3694        let head_dim = self.config.head_dim;
3695        let n_heads = self.config.n_heads;
3696        let n_kv_heads = self.config.n_kv_heads;
3697
3698        // [batch, hidden], flattened row-major.
3699        let mut hidden_batch: Vec<f32> = self.embed_tokens(tokens);
3700
3701        #[cfg(feature = "metal")]
3702        let use_metal_attn = ferrox_core::metal_dense_enabled()
3703            && ferrox_metal::attn::metal_attn_enabled()
3704            && self
3705                .layers
3706                .iter()
3707                .all(|l| self.layer_supports_metal_attn(l));
3708
3709        #[cfg(not(feature = "metal"))]
3710        let use_metal_attn = false;
3711
3712        let residency = self.expert_residency_plan(use_metal_attn);
3713
3714        #[cfg(feature = "metal")]
3715        let mut metal_kv_guard: Option<
3716            std::sync::MutexGuard<'_, Option<Vec<ferrox_metal::attn::MetalKvBuffers>>>,
3717        > = if use_metal_attn {
3718            Some(Self::lock_metal_attn_kv(&self.metal_attn_kv))
3719        } else {
3720            None
3721        };
3722
3723        #[cfg(feature = "metal")]
3724        if let Some(guard) = metal_kv_guard.as_mut() {
3725            let need = self.layers.len();
3726            let need_cap = start_pos
3727                .saturating_add(batch_size)
3728                .saturating_add(256)
3729                .max(512);
3730            let reset = match guard.as_ref() {
3731                None => true,
3732                Some(v) => {
3733                    v.len() != need
3734                        || v.iter().any(|m| m.capacity() < need_cap)
3735                        || v.iter()
3736                            .zip(kv_caches.iter())
3737                            // ROWS: Metal holds rows, and this asks whether the
3738                            // host buffer matches them.
3739                            .any(|(m, c)| m.seq_len != c.rows())
3740                }
3741            };
3742            if reset {
3743                let mut bufs = Vec::with_capacity(need);
3744                for _ in 0..need {
3745                    match ferrox_metal::attn::MetalKvBuffers::with_capacity(
3746                        n_kv_heads, head_dim, need_cap,
3747                    ) {
3748                        Ok(b) => bufs.push(b),
3749                        Err(_) => {
3750                            **guard = None;
3751                            break;
3752                        }
3753                    }
3754                }
3755                if bufs.len() == need {
3756                    let mut ok = true;
3757                    for (m, c) in bufs.iter_mut().zip(kv_caches.iter()) {
3758                        if c.rows() > 0 && m.upload_from_host(&c.k, &c.v, c.rows()).is_err() {
3759                            ok = false;
3760                            break;
3761                        }
3762                    }
3763                    if ok {
3764                        **guard = Some(bufs);
3765                    } else {
3766                        **guard = None;
3767                    }
3768                } else {
3769                    **guard = None;
3770                }
3771            }
3772        }
3773
3774        let n_layers = self.layers.len();
3775        let mut l = 0usize;
3776        while l < n_layers {
3777            let layer = &self.layers[l];
3778            let q_width = n_heads * head_dim;
3779            let kv_width = n_kv_heads * head_dim;
3780
3781            // Multi-layer dense prefill: one CB, activations stay on GPU.
3782            #[cfg(feature = "metal")]
3783            if use_metal_attn && batch_size >= 4 {
3784                if let Some(guard) = metal_kv_guard.as_mut() {
3785                    if let Some(metal_kvs) = guard.as_mut() {
3786                        if let Some(run_len) = self.metal_prefill_dense_stack_run_len(
3787                            l,
3788                            start_pos,
3789                            batch_size,
3790                            kv_caches,
3791                            Some(metal_kvs.as_slice()),
3792                        ) {
3793                            if let Some(h_out) = self.try_metal_prefill_dense_stack(
3794                                l,
3795                                run_len,
3796                                &hidden_batch,
3797                                start_pos,
3798                                batch_size,
3799                                n_heads,
3800                                metal_kvs,
3801                                kv_caches,
3802                                host_kv_authoritative,
3803                            ) {
3804                                hidden_batch = h_out;
3805                                l += run_len;
3806                                continue;
3807                            }
3808                        }
3809                    }
3810                }
3811            }
3812
3813            let cache = &mut kv_caches[l];
3814
3815            // One-CB dense prefill (RMSNorm→QKV GEMM→attn→O→FFN) when every
3816            // projection has mul_mm_sg and the layer has no QKV bias / QK-norm.
3817            #[cfg(feature = "metal")]
3818            if use_metal_attn && batch_size >= 4 && Self::metal_prefill_dense_layer_eligible(layer)
3819            {
3820                let swa_fits = self.metal_prefill_dense_swa_fits(l, start_pos, batch_size);
3821                if swa_fits {
3822                    if let Some(guard) = metal_kv_guard.as_mut() {
3823                        if let Some(metal_kvs) = guard.as_mut() {
3824                            // POSITIONS: compared against `start_pos`.
3825                            if metal_kvs[l].seq_len == cache.positions()
3826                                && start_pos == cache.positions()
3827                            {
3828                                layer.moe.record_activations(&[0]);
3829                                let fused = layer.moe.with_expert(0, |ex| {
3830                                    let (q, k, v, o) = (
3831                                        layer.attn.q_proj.mul_mm_sg_launch()?,
3832                                        layer.attn.k_proj.mul_mm_sg_launch()?,
3833                                        layer.attn.v_proj.mul_mm_sg_launch()?,
3834                                        layer.attn.o_proj.mul_mm_sg_launch()?,
3835                                    );
3836                                    let ffn = ferrox_metal::attn::PrefillFfnMetal::Dense {
3837                                        gate: ex.gate.mul_mm_sg_launch()?,
3838                                        up: ex.up.mul_mm_sg_launch()?,
3839                                        down: ex.down.mul_mm_sg_launch()?,
3840                                    };
3841                                    let gelu =
3842                                        !GluAct::from(self.config.ffn_activation).is_swiglu();
3843                                    let prefill_layer =
3844                                        ferrox_metal::attn::PrefillDenseLayerMetal {
3845                                            attn_norm_w: &layer.attn.norm_weight,
3846                                            ffn_norm_w: &layer.moe.norm_weight,
3847                                            q,
3848                                            k,
3849                                            v,
3850                                            o,
3851                                            ffn,
3852                                            post_attn_norm: layer.attn.post_attn_norm.as_deref(),
3853                                            post_ffn_norm: layer.attn.post_ffn_norm.as_deref(),
3854                                            extras: self.metal_attn_extras(layer),
3855                                            rope: self.metal_layer_rope(l),
3856                                            layer_idx: l as u32,
3857                                        };
3858                                    ferrox_metal::attn::launch_prefill_dense_layer(
3859                                        &hidden_batch,
3860                                        &prefill_layer,
3861                                        &mut metal_kvs[l],
3862                                        n_heads,
3863                                        batch_size,
3864                                        self.metal_rope(),
3865                                        start_pos,
3866                                        self.config.rms_norm_eps,
3867                                        gelu,
3868                                        self.config.attn_logit_softcap,
3869                                    )
3870                                    .ok()
3871                                });
3872                                if let Some(h_out) = fused {
3873                                    Self::advance_host_kv_after_metal_prefill(
3874                                        &metal_kvs[l],
3875                                        cache,
3876                                        batch_size,
3877                                        host_kv_authoritative,
3878                                    );
3879                                    hidden_batch = h_out;
3880                                    l += 1;
3881                                    continue;
3882                                }
3883                            }
3884                        }
3885                    }
3886                }
3887            }
3888
3889            // --- attention block ---
3890            let normed_batch: Vec<f32> = hidden_batch
3891                .par_chunks(hidden_dim)
3892                .map(|h| rms_norm(h, &layer.attn.norm_weight, self.config.rms_norm_eps))
3893                .flatten()
3894                .collect();
3895
3896            // One shared activation-quant pass for q/k/v (plan 1e): the
3897            // three projections read the same normed batch, so quantize it
3898            // once instead of once per projection. A kind mismatch inside
3899            // the group just re-quantizes locally.
3900            let qkv_acts = layer
3901                .attn
3902                .q_proj
3903                .quantize_batch_acts(&normed_batch, batch_size);
3904            let mut q_batch = layer.attn.q_proj.apply_batch_with_acts(
3905                &normed_batch,
3906                batch_size,
3907                qkv_acts.as_ref(),
3908            );
3909            let mut k_batch = layer.attn.k_proj.apply_batch_with_acts(
3910                &normed_batch,
3911                batch_size,
3912                qkv_acts.as_ref(),
3913            );
3914            let mut v_batch = layer.attn.v_proj.apply_batch_with_acts(
3915                &normed_batch,
3916                batch_size,
3917                qkv_acts.as_ref(),
3918            );
3919            drop(qkv_acts);
3920
3921            if let Some(bias) = &layer.attn.q_bias {
3922                for row in q_batch.chunks_mut(q_width) {
3923                    for (x, b) in row.iter_mut().zip(bias.iter()) {
3924                        *x += b;
3925                    }
3926                }
3927            }
3928            if let Some(bias) = &layer.attn.k_bias {
3929                for row in k_batch.chunks_mut(kv_width) {
3930                    for (x, b) in row.iter_mut().zip(bias.iter()) {
3931                        *x += b;
3932                    }
3933                }
3934            }
3935            if let Some(bias) = &layer.attn.v_bias {
3936                for row in v_batch.chunks_mut(kv_width) {
3937                    for (x, b) in row.iter_mut().zip(bias.iter()) {
3938                        *x += b;
3939                    }
3940                }
3941            }
3942
3943            self.apply_qk_norms_pre_rope(layer, &mut q_batch, &mut k_batch, q_width, kv_width);
3944            // Host-side `mscale`, applied before either backend ropes.
3945            // The Metal branch below therefore hands its kernels
3946            // `attn_factor_applied_by_caller()` — folding it into cos/sin
3947            // there as well would square it.
3948            self.apply_rope_attn_factor(&mut q_batch, &mut k_batch);
3949
3950            #[cfg(feature = "metal")]
3951            {
3952                let mut did_metal_prefill = false;
3953                // The Metal prefill kernel is full-causal: only safe on a
3954                // SWA layer while every causal position is still inside
3955                // the window. Longer prompts fall back to CPU attention.
3956                let swa_fits = match self.config.layer_sliding_window(l) {
3957                    Some(window) => start_pos + batch_size <= window,
3958                    None => true,
3959                };
3960                // Metal prefill applies attn softcap in FA-vec / legacy GQA.
3961                if let Some(guard) = metal_kv_guard.as_mut() {
3962                    if let Some(metal_kvs) = guard.as_mut() {
3963                        // POSITIONS: compared against `start_pos`.
3964                        if metal_kvs[l].seq_len == cache.positions()
3965                            && start_pos == cache.positions()
3966                            && swa_fits
3967                        {
3968                            let prefill_res = {
3969                                ferrox_metal::attn::launch_prefill_attn_block(
3970                                    &q_batch,
3971                                    &k_batch,
3972                                    &v_batch,
3973                                    &mut metal_kvs[l],
3974                                    n_heads,
3975                                    batch_size,
3976                                    self.metal_rope().attn_factor_applied_by_caller(),
3977                                    self.config.layer_rope_theta(l),
3978                                    self.config.layer_rope_freqs(l),
3979                                    start_pos,
3980                                    self.config.attn_logit_softcap,
3981                                    false,
3982                                )
3983                                .map(|(attn_out_batch, _, _)| {
3984                                    Self::advance_host_kv_after_metal_prefill(
3985                                        &metal_kvs[l],
3986                                        cache,
3987                                        batch_size,
3988                                        host_kv_authoritative,
3989                                    );
3990                                    let projected_batch =
3991                                        layer.attn.o_proj.apply_batch(&attn_out_batch, batch_size);
3992                                    let projected_batch =
3993                                        if let Some(post) = &layer.attn.post_attn_norm {
3994                                            projected_batch
3995                                                .chunks(hidden_dim)
3996                                                .flat_map(|row| {
3997                                                    rms_norm(row, post, self.config.rms_norm_eps)
3998                                                })
3999                                                .collect::<Vec<_>>()
4000                                        } else {
4001                                            projected_batch
4002                                        };
4003                                    for (h, p) in
4004                                        hidden_batch.iter_mut().zip(projected_batch.iter())
4005                                    {
4006                                        *h += p;
4007                                    }
4008                                    true
4009                                })
4010                            };
4011                            match prefill_res {
4012                                Ok(true) => {
4013                                    did_metal_prefill = true;
4014                                }
4015                                Ok(false) => {}
4016                                Err(e) => {
4017                                    eprintln!(
4018                                        "ferrox: Metal prefill attn failed, CPU fallback: {e}"
4019                                    );
4020                                    **guard = None;
4021                                }
4022                            }
4023                        }
4024                    }
4025                }
4026                if did_metal_prefill {
4027                    // --- MoE FFN block (batched Metal when packed Q4) ---
4028                    let normed2_batch: Vec<f32> = hidden_batch
4029                        .chunks(hidden_dim)
4030                        .flat_map(|h| rms_norm(h, &layer.moe.norm_weight, self.config.rms_norm_eps))
4031                        .collect();
4032                    let dense = Self::is_dense_layer(layer);
4033                    let router_logits_batch = if dense {
4034                        Vec::new()
4035                    } else {
4036                        layer.moe.router.apply_batch(&normed2_batch, batch_size)
4037                    };
4038                    let metal_ffn = if !dense {
4039                        Self::try_metal_moe_prefill_batch(
4040                            layer,
4041                            &normed2_batch,
4042                            &router_logits_batch,
4043                            batch_size,
4044                            hidden_dim,
4045                            &self.config,
4046                        )
4047                    } else {
4048                        None
4049                    };
4050                    if let Some(mut ffn_batch) = metal_ffn {
4051                        if let Some(post) = &layer.attn.post_ffn_norm {
4052                            ffn_batch = ffn_batch
4053                                .chunks(hidden_dim)
4054                                .flat_map(|row| rms_norm(row, post, self.config.rms_norm_eps))
4055                                .collect();
4056                        }
4057                        for (h, f) in hidden_batch.iter_mut().zip(ffn_batch.iter()) {
4058                            *h += f;
4059                        }
4060                    } else if let Some(mut ffn_batch) =
4061                        Self::dense_ffn_batch(layer, &normed2_batch, batch_size, &self.config)
4062                    {
4063                        if let Some(post) = &layer.attn.post_ffn_norm {
4064                            ffn_batch = ffn_batch
4065                                .chunks(hidden_dim)
4066                                .flat_map(|row| rms_norm(row, post, self.config.rms_norm_eps))
4067                                .collect();
4068                        }
4069                        for (h, f) in hidden_batch.iter_mut().zip(ffn_batch.iter()) {
4070                            *h += f;
4071                        }
4072                    } else if let Some(mut ffn_batch) = Self::moe_ffn_batch(
4073                        layer,
4074                        &normed2_batch,
4075                        &router_logits_batch,
4076                        batch_size,
4077                        hidden_dim,
4078                        &self.config,
4079                        residency.as_ref().map(|p| p.layer_plan(l)),
4080                    ) {
4081                        if let Some(post) = &layer.attn.post_ffn_norm {
4082                            ffn_batch = ffn_batch
4083                                .chunks(hidden_dim)
4084                                .flat_map(|row| rms_norm(row, post, self.config.rms_norm_eps))
4085                                .collect();
4086                        }
4087                        for (h, f) in hidden_batch.iter_mut().zip(ffn_batch.iter()) {
4088                            *h += f;
4089                        }
4090                    } else {
4091                        let n_experts = layer.moe.n_experts().max(1);
4092                        for b in 0..batch_size {
4093                            let normed2 = &normed2_batch[b * hidden_dim..(b + 1) * hidden_dim];
4094                            let mut ffn_out = if dense {
4095                                Self::run_ffn_block(
4096                                    layer,
4097                                    normed2,
4098                                    &self.config,
4099                                    hidden_dim,
4100                                    residency.as_ref().map(|p| p.layer_plan(l)),
4101                                )
4102                            } else {
4103                                let router_logits =
4104                                    &router_logits_batch[b * n_experts..(b + 1) * n_experts];
4105                                Self::combine_ffn_outputs_for_position(
4106                                    layer,
4107                                    normed2,
4108                                    router_logits,
4109                                    &self.config,
4110                                    hidden_dim,
4111                                    residency.as_ref().map(|p| p.layer_plan(l)),
4112                                )
4113                            };
4114                            if let Some(post) = &layer.attn.post_ffn_norm {
4115                                ffn_out = rms_norm(&ffn_out, post, self.config.rms_norm_eps);
4116                            }
4117                            let hidden_row =
4118                                &mut hidden_batch[b * hidden_dim..(b + 1) * hidden_dim];
4119                            for (h, f) in hidden_row.iter_mut().zip(ffn_out.iter()) {
4120                                *h += f;
4121                            }
4122                        }
4123                    }
4124                    l += 1;
4125                    continue;
4126                }
4127            }
4128
4129            // RoPE per token is independent; parallelize for CPU pp512.
4130            q_batch
4131                .par_chunks_mut(q_width)
4132                .zip(k_batch.par_chunks_mut(kv_width))
4133                .enumerate()
4134                .for_each(|(b, (q_row, k_row))| {
4135                    let pos = start_pos + b;
4136                    for h in 0..n_heads {
4137                        self.apply_rope_head_layer(
4138                            &mut q_row[h * head_dim..(h + 1) * head_dim],
4139                            pos,
4140                            l,
4141                        );
4142                    }
4143                    for h in 0..n_kv_heads {
4144                        self.apply_rope_head_layer(
4145                            &mut k_row[h * head_dim..(h + 1) * head_dim],
4146                            pos,
4147                            l,
4148                        );
4149                    }
4150                });
4151            // `maincoder` / `hunyuan-moe` norm HERE instead. Reachable
4152            // only on the host path, which is why
4153            // `layer_supports_metal_attn` refuses the layer outright
4154            // rather than letting the Metal arms above consume a batch
4155            // that has not been normed yet.
4156            self.apply_qk_norms_post_rope(layer, &mut q_batch, &mut k_batch, q_width, kv_width);
4157            // Elementwise, so the whole Q batch in one call. Like the
4158            // multi-sequence path, this body did not apply it at all
4159            // until the decoration audit. It is placed AFTER the Metal
4160            // arms above deliberately: none of the seven fused launches
4161            // has an `attention_scale` uniform, and Q never returns to
4162            // the host inside `launch_prefill_dense_layer` /
4163            // `launch_prefill_dense_stack` for it to be scaled. The
4164            // refusal that keeps those arms out of reach when
4165            // `attention_scale` is set is in `layer_supports_metal_attn`.
4166            self.apply_attention_scale(&mut q_batch);
4167
4168            // ROWS, not positions: it is added to `b + 1` below to give
4169            // each query in the batch the length of the KV it attends
4170            // over, which is a count of resident rows.
4171            let base_seq_len = cache.rows();
4172            for b in 0..batch_size {
4173                cache
4174                    .push(
4175                        &k_batch[b * kv_width..(b + 1) * kv_width],
4176                        &v_batch[b * kv_width..(b + 1) * kv_width],
4177                    )
4178                    .expect("unbounded/planned KvCache growth is infallible");
4179            }
4180
4181            // Prefill attention over the just-written KV prefix. Parallel
4182            // over query positions — the serial loop was a dominant CPU
4183            // pp512 bottleneck (each query still attends only its causal
4184            // prefix; K/V slices are immutable after the pushes above).
4185            let cache_k = &cache.k;
4186            let cache_v = &cache.v;
4187            let softcap = self.config.attn_logit_softcap;
4188            let window = self.config.layer_sliding_window(l);
4189            let oai = self.gpt_oss.as_ref().map(|g| &g.layers[l]);
4190            // gpt-oss takes the per-query path on every layer, windowed
4191            // or not: the blocked kernel has no sink term. Everything
4192            // else goes through the blocked kernel, which is Rayon over
4193            // `[query-block x head]` against one shared KV buffer,
4194            // windowed or not. SWA layers used to take a per-query
4195            // `causal_gqa_attention_windowed_softcap` instead, which is
4196            // `online_attn_accumulate`: two scalar `exp` and a
4197            // head_dim-wide rescale per KV position, with the head axis
4198            // serial inside each task. On Gemma-3-1B (22 of 26 layers
4199            // are SWA) that arm was 19.6% of non-idle CPU `pp512`
4200            // samples while doing the *same* KV work as this one - at
4201            // `pp512` the 512-wide window covers the whole prompt.
4202            let attn_out_batch = if let Some(oai) = oai {
4203                let mut out = vec![0f32; batch_size * q_width];
4204                out.par_chunks_mut(q_width)
4205                    .enumerate()
4206                    .for_each(|(b, dest)| {
4207                        let seq_len_b = base_seq_len + b + 1;
4208                        let cache_elems = seq_len_b * kv_width;
4209                        let attn_out = ferrox_core::causal_gqa_attention_sinks(
4210                            &q_batch[b * q_width..(b + 1) * q_width],
4211                            &cache_k[..cache_elems],
4212                            &cache_v[..cache_elems],
4213                            n_heads,
4214                            n_kv_heads,
4215                            head_dim,
4216                            seq_len_b,
4217                            window,
4218                            &oai.attn_sinks,
4219                        );
4220                        dest.copy_from_slice(&attn_out);
4221                    });
4222                out
4223            } else {
4224                causal_gqa_attention_prefill_shared_kv_windowed(
4225                    &q_batch,
4226                    cache_k,
4227                    cache_v,
4228                    n_heads,
4229                    n_kv_heads,
4230                    head_dim,
4231                    batch_size,
4232                    base_seq_len,
4233                    softcap,
4234                    window,
4235                )
4236            };
4237
4238            // Every query in this batch has now been answered, so the
4239            // rows behind the window are rows nothing will read again
4240            // (#61). This is why eviction is not inside `KvCache::push`:
4241            // `base_seq_len` above was captured BEFORE the batch's
4242            // pushes and every query's KV length is derived from it, so
4243            // a drop between the push loop and here would attend the
4244            // whole prompt over shifted keys.
4245            //
4246            // Per layer rather than after the stack, and that is where
4247            // most of the prefill saving is: a windowed layer hands its
4248            // prompt rows back before the next layer allocates its own,
4249            // so a 32k prompt holds ONE layer's full history at a time
4250            // instead of every windowed layer's at once.
4251            self.evict_layer_kv(l, cache);
4252
4253            let mut projected_batch = layer.attn.o_proj.apply_batch(&attn_out_batch, batch_size);
4254            if let Some(oai) = oai {
4255                for row in projected_batch.chunks_mut(hidden_dim) {
4256                    for (x, b) in row.iter_mut().zip(oai.o_bias.iter()) {
4257                        *x += b;
4258                    }
4259                }
4260            }
4261            let projected_batch = if let Some(post) = &layer.attn.post_attn_norm {
4262                projected_batch
4263                    .chunks(hidden_dim)
4264                    .flat_map(|row| rms_norm(row, post, self.config.rms_norm_eps))
4265                    .collect::<Vec<_>>()
4266            } else {
4267                projected_batch
4268            };
4269            for (h, p) in hidden_batch.iter_mut().zip(projected_batch.iter()) {
4270                *h += p;
4271            }
4272
4273            // --- MoE FFN block ---
4274            let normed2_batch: Vec<f32> = hidden_batch
4275                .par_chunks(hidden_dim)
4276                .map(|h| rms_norm(h, &layer.moe.norm_weight, self.config.rms_norm_eps))
4277                .flatten()
4278                .collect();
4279            if let Some(oai) = oai {
4280                // gpt-oss: one position at a time through the single
4281                // validated FFN. None of the batched fast paths below
4282                // knows about router bias, expert bias or swiglu_oai.
4283                for b in 0..batch_size {
4284                    let normed2 = &normed2_batch[b * hidden_dim..(b + 1) * hidden_dim];
4285                    let ffn_out = Self::gpt_oss_ffn(layer, oai, normed2, &self.config, hidden_dim);
4286                    let hidden_row = &mut hidden_batch[b * hidden_dim..(b + 1) * hidden_dim];
4287                    for (h, f) in hidden_row.iter_mut().zip(ffn_out.iter()) {
4288                        *h += f;
4289                    }
4290                }
4291                l += 1;
4292                continue;
4293            }
4294            let dense = Self::is_dense_layer(layer);
4295            // Skip the batched router matmul entirely for a dense
4296            // layer -- there's nothing to route (see
4297            // `is_dense_layer`'s doc comment), so computing it here
4298            // just to ignore it below would waste the one matmul this
4299            // fast path exists to avoid.
4300            let router_logits_batch = if dense {
4301                Vec::new()
4302            } else {
4303                layer.moe.router.apply_batch(&normed2_batch, batch_size)
4304            };
4305            #[cfg(feature = "metal")]
4306            let metal_ffn = if !dense {
4307                Self::try_metal_moe_prefill_batch(
4308                    layer,
4309                    &normed2_batch,
4310                    &router_logits_batch,
4311                    batch_size,
4312                    hidden_dim,
4313                    &self.config,
4314                )
4315            } else {
4316                None
4317            };
4318            #[cfg(not(feature = "metal"))]
4319            let metal_ffn: Option<Vec<f32>> = None;
4320            if let Some(mut ffn_batch) = metal_ffn {
4321                if let Some(post) = &layer.attn.post_ffn_norm {
4322                    ffn_batch = ffn_batch
4323                        .chunks(hidden_dim)
4324                        .flat_map(|row| rms_norm(row, post, self.config.rms_norm_eps))
4325                        .collect();
4326                }
4327                for (h, f) in hidden_batch.iter_mut().zip(ffn_batch.iter()) {
4328                    *h += f;
4329                }
4330            } else if let Some(mut ffn_batch) =
4331                Self::dense_ffn_batch(layer, &normed2_batch, batch_size, &self.config)
4332            {
4333                // Dense FFN, batched. Without this the FFN -- the
4334                // majority of a dense model's prefill work -- ran one
4335                // position at a time while Q/K/V and the router were
4336                // already batched, which is why `pp512` measured about
4337                // the same as `tg128`.
4338                if let Some(post) = &layer.attn.post_ffn_norm {
4339                    ffn_batch = ffn_batch
4340                        .chunks(hidden_dim)
4341                        .flat_map(|row| rms_norm(row, post, self.config.rms_norm_eps))
4342                        .collect();
4343                }
4344                for (h, f) in hidden_batch.iter_mut().zip(ffn_batch.iter()) {
4345                    *h += f;
4346                }
4347            } else if let Some(mut ffn_batch) = Self::moe_ffn_batch(
4348                layer,
4349                &normed2_batch,
4350                &router_logits_batch,
4351                batch_size,
4352                hidden_dim,
4353                &self.config,
4354                residency.as_ref().map(|p| p.layer_plan(l)),
4355            ) {
4356                if let Some(post) = &layer.attn.post_ffn_norm {
4357                    ffn_batch = ffn_batch
4358                        .chunks(hidden_dim)
4359                        .flat_map(|row| rms_norm(row, post, self.config.rms_norm_eps))
4360                        .collect();
4361                }
4362                for (h, f) in hidden_batch.iter_mut().zip(ffn_batch.iter()) {
4363                    *h += f;
4364                }
4365            } else {
4366                let n_experts = layer.moe.n_experts().max(1);
4367                for b in 0..batch_size {
4368                    let normed2 = &normed2_batch[b * hidden_dim..(b + 1) * hidden_dim];
4369                    let mut ffn_out = if dense {
4370                        Self::run_ffn_block(
4371                            layer,
4372                            normed2,
4373                            &self.config,
4374                            hidden_dim,
4375                            residency.as_ref().map(|p| p.layer_plan(l)),
4376                        )
4377                    } else {
4378                        let router_logits =
4379                            &router_logits_batch[b * n_experts..(b + 1) * n_experts];
4380                        Self::combine_ffn_outputs_for_position(
4381                            layer,
4382                            normed2,
4383                            router_logits,
4384                            &self.config,
4385                            hidden_dim,
4386                            residency.as_ref().map(|p| p.layer_plan(l)),
4387                        )
4388                    };
4389                    if let Some(post) = &layer.attn.post_ffn_norm {
4390                        ffn_out = rms_norm(&ffn_out, post, self.config.rms_norm_eps);
4391                    }
4392                    let hidden_row = &mut hidden_batch[b * hidden_dim..(b + 1) * hidden_dim];
4393                    for (h, f) in hidden_row.iter_mut().zip(ffn_out.iter()) {
4394                        *h += f;
4395                    }
4396                }
4397            }
4398            l += 1;
4399        }
4400
4401        hidden_batch
4402            .chunks(hidden_dim)
4403            .map(|h| rms_norm(h, &self.final_norm, self.config.rms_norm_eps))
4404            .collect()
4405    }
4406
4407    /// Continuous-batching primitive: one decode step across N
4408    /// independent *sequences*, each contributing exactly one new
4409    /// token at its own current position, sharing every layer's
4410    /// projection/router matmuls the same way `forward_batch` shares
4411    /// them across positions of a single sequence -- but each
4412    /// sequence keeps its own `KvCache`, independent `seq_len`, and
4413    /// independent position, so sequences admitted/evicted at
4414    /// different times can still share one batched matmul per step
4415    /// (this is what "continuous" batching means: the batch
4416    /// membership can change every step, unlike `forward_batch`'s
4417    /// fixed-size prompt-processing batch). `kv_caches[s][l]` is
4418    /// sequence `s`'s layer-`l` cache; `tokens[s]`/`positions[s]` is
4419    /// that sequence's next token and its position within its own
4420    /// history. Returns one logits vector per sequence, same order as
4421    /// `tokens`.
4422    ///
4423    /// Must produce bit-identical output to calling `forward_token`
4424    /// once per sequence with that sequence's own cache/position --
4425    /// batching independent sequences together is a scheduling detail,
4426    /// not a math change (no sequence's attention ever reads another
4427    /// sequence's cache).
4428    pub fn forward_multi_seq(
4429        &self,
4430        tokens: &[usize],
4431        positions: &[usize],
4432        kv_caches: &mut [Vec<KvCache>],
4433    ) -> Vec<Vec<f32>> {
4434        self.forward_multi_seq_kv(tokens, positions, &mut MultiSeqKv::Contiguous(kv_caches))
4435    }
4436
4437    /// Appends one position to sequence `b`'s layer-`l` KV, then
4438    /// attends over everything that sequence holds.
4439    ///
4440    /// The only place `forward_multi_seq_kv` touches a cache, and so
4441    /// the only place the backing matters.
4442    ///
4443    /// Selects sequence `b`'s layer-`l` cache and hands it to
4444    /// [`Decoder::push_and_attend_row`], the one attend body the whole
4445    /// crate shares. This used to spell that body out a second time; the
4446    /// contiguous arm of the copy differed from `forward_token`'s by
4447    /// exactly one call (the CUDA resident hook), which is the kind of
4448    /// difference nobody notices until it is a wrong answer.
4449    #[allow(clippy::too_many_arguments)] // one per thing the step needs
4450    fn push_and_attend(
4451        &self,
4452        kv: &mut MultiSeqKv<'_>,
4453        b: usize,
4454        l: usize,
4455        k: &[f32],
4456        v: &[f32],
4457        q: &[f32],
4458        oai: Option<&GptOssLayer>,
4459    ) -> Vec<f32> {
4460        let step = match kv {
4461            // `Batched`, not `Decode`: the CUDA resident per-layer KV
4462            // holds ONE sequence's history, and this path never seeds
4463            // it. See `KvStep::Batched`.
4464            MultiSeqKv::Contiguous(caches) => KvStep::Batched(&mut caches[b][l]),
4465            MultiSeqKv::Paged { caches, stores } => KvStep::Paged {
4466                cache: &mut caches[b][l],
4467                stores,
4468            },
4469        };
4470        self.push_and_attend_row(step, l, k, v, q, oai)
4471    }
4472
4473    /// [`Self::forward_multi_seq`] over either KV backing.
4474    ///
4475    /// One body for both: the batched projections are identical, and
4476    /// the per-sequence attention step is the only place the backing
4477    /// shows through.
4478    pub fn forward_multi_seq_kv(
4479        &self,
4480        tokens: &[usize],
4481        positions: &[usize],
4482        kv: &mut MultiSeqKv<'_>,
4483    ) -> Vec<Vec<f32>> {
4484        assert_eq!(tokens.len(), positions.len());
4485        assert_eq!(tokens.len(), kv.len());
4486        let batch_size = tokens.len();
4487        if batch_size == 0 {
4488            return Vec::new();
4489        }
4490        for seq in 0..batch_size {
4491            assert_eq!(kv.layers_per_seq(seq), self.layers.len());
4492        }
4493
4494        let hidden_dim = self.config.hidden_dim;
4495        let head_dim = self.config.head_dim;
4496        let n_heads = self.config.n_heads;
4497        let n_kv_heads = self.config.n_kv_heads;
4498
4499        // [batch, hidden], flattened row-major.
4500        let mut hidden_batch: Vec<f32> = self.embed_tokens(tokens);
4501
4502        let residency = self.gpu_vram_budget_bytes.map(|b| self.residency_plan(b));
4503
4504        for (l, layer) in self.layers.iter().enumerate() {
4505            // --- attention block ---
4506            let normed_batch: Vec<f32> = hidden_batch
4507                .par_chunks(hidden_dim)
4508                .map(|h| rms_norm(h, &layer.attn.norm_weight, self.config.rms_norm_eps))
4509                .flatten()
4510                .collect();
4511
4512            // One shared activation-quant pass for q/k/v (plan 1e): the
4513            // three projections read the same normed batch, so quantize it
4514            // once instead of once per projection. A kind mismatch inside
4515            // the group just re-quantizes locally.
4516            let qkv_acts = layer
4517                .attn
4518                .q_proj
4519                .quantize_batch_acts(&normed_batch, batch_size);
4520            let mut q_batch = layer.attn.q_proj.apply_batch_with_acts(
4521                &normed_batch,
4522                batch_size,
4523                qkv_acts.as_ref(),
4524            );
4525            let mut k_batch = layer.attn.k_proj.apply_batch_with_acts(
4526                &normed_batch,
4527                batch_size,
4528                qkv_acts.as_ref(),
4529            );
4530            let mut v_batch = layer.attn.v_proj.apply_batch_with_acts(
4531                &normed_batch,
4532                batch_size,
4533                qkv_acts.as_ref(),
4534            );
4535            drop(qkv_acts);
4536
4537            let q_width = n_heads * head_dim;
4538            let kv_width = n_kv_heads * head_dim;
4539
4540            if let Some(bias) = &layer.attn.q_bias {
4541                for row in q_batch.chunks_mut(q_width) {
4542                    for (x, b) in row.iter_mut().zip(bias.iter()) {
4543                        *x += b;
4544                    }
4545                }
4546            }
4547            if let Some(bias) = &layer.attn.k_bias {
4548                for row in k_batch.chunks_mut(kv_width) {
4549                    for (x, b) in row.iter_mut().zip(bias.iter()) {
4550                        *x += b;
4551                    }
4552                }
4553            }
4554            if let Some(bias) = &layer.attn.v_bias {
4555                for row in v_batch.chunks_mut(kv_width) {
4556                    for (x, b) in row.iter_mut().zip(bias.iter()) {
4557                        *x += b;
4558                    }
4559                }
4560            }
4561
4562            self.apply_qk_norms_pre_rope(layer, &mut q_batch, &mut k_batch, q_width, kv_width);
4563            self.apply_rope_attn_factor(&mut q_batch, &mut k_batch);
4564
4565            for b in 0..batch_size {
4566                let pos = positions[b];
4567                let q_row = &mut q_batch[b * q_width..(b + 1) * q_width];
4568                for h in 0..n_heads {
4569                    self.apply_rope_head_layer(
4570                        &mut q_row[h * head_dim..(h + 1) * head_dim],
4571                        pos,
4572                        l,
4573                    );
4574                }
4575                let k_row = &mut k_batch[b * kv_width..(b + 1) * kv_width];
4576                for h in 0..n_kv_heads {
4577                    self.apply_rope_head_layer(
4578                        &mut k_row[h * head_dim..(h + 1) * head_dim],
4579                        pos,
4580                        l,
4581                    );
4582                }
4583            }
4584            self.apply_qk_norms_post_rope(layer, &mut q_batch, &mut k_batch, q_width, kv_width);
4585            // Applied to the whole Q batch at once because it is
4586            // elementwise. This path did not apply it at all until the
4587            // decoration audit: `attention_scale` reached only
4588            // `forward_token`'s CPU arm and `forward_token_paged`, so a
4589            // checkpoint carrying one answered at one temperature when
4590            // decoded alone and another when batched with its neighbours.
4591            self.apply_attention_scale(&mut q_batch);
4592
4593            let oai = self.gpt_oss.as_ref().map(|g| &g.layers[l]);
4594            let mut attn_out_batch = vec![0f32; batch_size * q_width];
4595            for b in 0..batch_size {
4596                let attn_out = self.push_and_attend(
4597                    kv,
4598                    b,
4599                    l,
4600                    &k_batch[b * kv_width..(b + 1) * kv_width],
4601                    &v_batch[b * kv_width..(b + 1) * kv_width],
4602                    &q_batch[b * q_width..(b + 1) * q_width],
4603                    oai,
4604                );
4605                attn_out_batch[b * q_width..(b + 1) * q_width].copy_from_slice(&attn_out);
4606            }
4607
4608            let mut projected_batch = layer.attn.o_proj.apply_batch(&attn_out_batch, batch_size);
4609            if let Some(oai) = oai {
4610                for row in projected_batch.chunks_mut(hidden_dim) {
4611                    for (x, b) in row.iter_mut().zip(oai.o_bias.iter()) {
4612                        *x += b;
4613                    }
4614                }
4615            }
4616            let projected_batch = if let Some(post) = &layer.attn.post_attn_norm {
4617                projected_batch
4618                    .chunks(hidden_dim)
4619                    .flat_map(|row| rms_norm(row, post, self.config.rms_norm_eps))
4620                    .collect::<Vec<_>>()
4621            } else {
4622                projected_batch
4623            };
4624            for (h, p) in hidden_batch.iter_mut().zip(projected_batch.iter()) {
4625                *h += p;
4626            }
4627
4628            // --- MoE FFN block ---
4629            let normed2_batch: Vec<f32> = hidden_batch
4630                .par_chunks(hidden_dim)
4631                .map(|h| rms_norm(h, &layer.moe.norm_weight, self.config.rms_norm_eps))
4632                .flatten()
4633                .collect();
4634            let dense = Self::is_dense_layer(layer);
4635            let router_logits_batch = if dense || oai.is_some() {
4636                Vec::new()
4637            } else {
4638                layer.moe.router.apply_batch(&normed2_batch, batch_size)
4639            };
4640            let n_experts = layer.moe.n_experts().max(1);
4641
4642            for b in 0..batch_size {
4643                let normed2 = &normed2_batch[b * hidden_dim..(b + 1) * hidden_dim];
4644                let mut ffn_out = if let Some(oai) = oai {
4645                    Self::gpt_oss_ffn(layer, oai, normed2, &self.config, hidden_dim)
4646                } else if dense {
4647                    Self::run_ffn_block(
4648                        layer,
4649                        normed2,
4650                        &self.config,
4651                        hidden_dim,
4652                        residency.as_ref().map(|p| p.layer_plan(l)),
4653                    )
4654                } else {
4655                    let router_logits = &router_logits_batch[b * n_experts..(b + 1) * n_experts];
4656                    Self::combine_ffn_outputs_for_position(
4657                        layer,
4658                        normed2,
4659                        router_logits,
4660                        &self.config,
4661                        hidden_dim,
4662                        residency.as_ref().map(|p| p.layer_plan(l)),
4663                    )
4664                };
4665                if let Some(post) = &layer.attn.post_ffn_norm {
4666                    ffn_out = rms_norm(&ffn_out, post, self.config.rms_norm_eps);
4667                }
4668                let hidden_row = &mut hidden_batch[b * hidden_dim..(b + 1) * hidden_dim];
4669                for (h, f) in hidden_row.iter_mut().zip(ffn_out.iter()) {
4670                    *h += f;
4671                }
4672            }
4673        }
4674
4675        let final_normed_batch: Vec<f32> = hidden_batch
4676            .par_chunks(hidden_dim)
4677            .map(|h| rms_norm(h, &self.final_norm, self.config.rms_norm_eps))
4678            .flatten()
4679            .collect();
4680        self.logits_from_flat_hidden(final_normed_batch, batch_size)
4681    }
4682}
4683
4684#[cfg(test)]
4685mod tests {
4686    use super::*;
4687    use crate::config::glm_5_2;
4688    use ferrox_core::cache::PagedKvStore;
4689
4690    /// Small config used purely to keep the test fast: same
4691    /// architecture *shape* (GQA ratio, MoE topology) as GLM-5.2, but
4692    /// with tiny dims so the whole thing runs in milliseconds.
4693    fn tiny_test_config() -> ModelConfig {
4694        let mut cfg = glm_5_2();
4695        cfg.hidden_dim = 16;
4696        cfg.n_heads = 4;
4697        cfg.n_kv_heads = 2;
4698        cfg.head_dim = 4;
4699        cfg.moe.hidden_dim = 16;
4700        cfg.moe.n_experts = 6;
4701        cfg.moe.n_experts_active = 2;
4702        cfg.moe.n_shared_experts = 1;
4703        cfg.moe.expert_ffn_dim = 8;
4704        cfg
4705    }
4706
4707    /// A GeGLU model's ROUTED experts must run GeGLU.
4708    ///
4709    /// `run_ffn_block` used to consult `ffn_activation` only in its dense
4710    /// arm; `combine_ffn_outputs_for_position` and everything under it
4711    /// was unconditionally SwiGLU, so a GeGLU MoE would have produced
4712    /// fluent, wrong logits with nothing in the tree to notice. That is
4713    /// not hypothetical: llama.cpp's `grok` passes `LLM_FFN_GELU` to
4714    /// `build_moe_ffn` (`.scratch/llama.cpp/src/models/grok.cpp`), and
4715    /// `grok` sits on `ArchPath::GenericGqa` in `capability.rs`.
4716    ///
4717    /// The reference is written out here in plain loops -- its own GELU
4718    /// and SiLU, not `ferrox_core`'s -- so it cannot agree with the code
4719    /// under test by sharing its bug. The second assertion is the one
4720    /// that makes this a test rather than a smoke check: the SwiGLU
4721    /// answer must be visibly different, so an implementation that
4722    /// ignores the activation cannot pass.
4723    #[test]
4724    fn a_geglu_moe_layer_runs_geglu_in_its_routed_experts_not_swiglu() {
4725        let mut cfg = tiny_test_config();
4726        cfg.ffn_activation = crate::config::FfnActivation::Gelu;
4727        let decoder = Decoder::new_random_small(cfg, 2, 8);
4728        let hidden_dim = decoder.config.hidden_dim;
4729        let layer = &decoder.layers[1];
4730        assert!(
4731            !Decoder::is_dense_layer(layer),
4732            "this test is about the ROUTED path; layer 1 must be a real MoE layer"
4733        );
4734
4735        // Larger than the usual unit inputs on purpose: GELU and SiLU
4736        // are close near zero, and a reference that cannot tell them
4737        // apart cannot catch the bug this test exists for.
4738        let normed2: Vec<f32> = (0..hidden_dim)
4739            .map(|i| (i as f32 * 0.37).sin() * 12.0)
4740            .collect();
4741
4742        let gelu = |x: f32| {
4743            let t = (0.797_884_6f32 * (x + 0.044_715 * x * x * x)).tanh();
4744            0.5 * x * (1.0 + t)
4745        };
4746        let silu = |x: f32| x / (1.0 + (-x).exp());
4747        let expert_ref = |ex: &ExpertWeights, f: &dyn Fn(f32) -> f32| -> Vec<f32> {
4748            let g = ex.gate.apply(&normed2);
4749            let u = ex.up.apply(&normed2);
4750            let a: Vec<f32> = g.iter().zip(u.iter()).map(|(&g, &u)| f(g) * u).collect();
4751            ex.down.apply(&a)
4752        };
4753
4754        let ExpertBacking::Resident(experts) = &layer.moe.experts else {
4755            panic!("new_random_small builds resident experts");
4756        };
4757        let router_logits = layer.moe.router.apply(&normed2);
4758        let decision = Decoder::route_for_layer(layer, &router_logits, &decoder.config);
4759        let block_ref = |f: &dyn Fn(f32) -> f32| -> Vec<f32> {
4760            let mut out = vec![0f32; hidden_dim];
4761            for (&eid, &w) in decision.expert_ids.iter().zip(decision.weights.iter()) {
4762                for (o, e) in out.iter_mut().zip(expert_ref(&experts[eid], f).iter()) {
4763                    *o += w * e;
4764                }
4765            }
4766            assert!(
4767                layer.moe.shared_expert_gate.is_none(),
4768                "tiny_test_config's shared experts are ungated; reference assumes it"
4769            );
4770            for shex in &layer.moe.shared_experts {
4771                for (o, e) in out.iter_mut().zip(expert_ref(shex, f).iter()) {
4772                    *o += e;
4773                }
4774            }
4775            out
4776        };
4777        let expected_geglu = block_ref(&gelu);
4778        let expected_swiglu = block_ref(&silu);
4779
4780        let got = Decoder::run_ffn_block(layer, &normed2, &decoder.config, hidden_dim, None);
4781        assert_eq!(got.len(), hidden_dim);
4782        for (i, (a, b)) in got.iter().zip(expected_geglu.iter()).enumerate() {
4783            assert!(
4784                (a - b).abs() < 1e-4 * b.abs().max(1.0),
4785                "routed GeGLU FFN element {i}: got {a}, expected {b}"
4786            );
4787        }
4788        assert!(
4789            expected_geglu
4790                .iter()
4791                .zip(expected_swiglu.iter())
4792                .any(|(a, b)| (a - b).abs() > 1e-3),
4793            "GeGLU and SwiGLU must differ measurably on this input, or this test \
4794             could not detect a routed expert that silently ran SwiGLU"
4795        );
4796    }
4797
4798    #[test]
4799    fn forward_pass_produces_finite_logits_of_correct_shape() {
4800        let vocab = 10;
4801        let decoder = Decoder::new_random_small(tiny_test_config(), 2, vocab);
4802        let mut caches: Vec<KvCache> = (0..2)
4803            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
4804            .collect();
4805
4806        let logits = decoder.forward_token(3, 0, &mut caches);
4807        assert_eq!(logits.len(), vocab);
4808        assert!(
4809            logits.iter().all(|v| v.is_finite()),
4810            "logits must not contain NaN/Inf"
4811        );
4812    }
4813
4814    /// `gpu_vram_budget_bytes` must be a real zero-behavior-change
4815    /// default at `None`, and a *real placement plan that places
4816    /// nothing* (a zero VRAM budget, so `PlacementPlan::from_budget`
4817    /// fits no expert at all) must produce byte-identical output to
4818    /// `None` too -- proving the new plumbing (building a plan,
4819    /// looking up each routed expert's placement, dispatching through
4820    /// `run_expert_placed`) doesn't change results when nothing is
4821    /// actually GPU-placed, without needing real CUDA hardware to
4822    /// check (that hardware-dependent half is
4823    /// `ferrox-moe`'s/`ferrox-core`'s own `#[ignore]`d tests).
4824    #[test]
4825    fn gpu_vram_budget_bytes_with_nothing_placed_matches_the_default() {
4826        let mut decoder = Decoder::new_random_small(tiny_test_config(), 2, 10);
4827        let mut caches_default: Vec<KvCache> = (0..2)
4828            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
4829            .collect();
4830        let default_logits = decoder.forward_token(3, 0, &mut caches_default);
4831
4832        decoder.gpu_vram_budget_bytes = Some(0);
4833        let mut caches_zero_budget: Vec<KvCache> = (0..2)
4834            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
4835            .collect();
4836        let zero_budget_logits = decoder.forward_token(3, 0, &mut caches_zero_budget);
4837
4838        assert_eq!(
4839            default_logits, zero_budget_logits,
4840            "a placement plan that places nothing on GPU must match the None default exactly"
4841        );
4842    }
4843
4844    /// Qwen2-MoE's real shared-expert sigmoid gate
4845    /// (`MoeWeights::shared_expert_gate`): exact math check by mutating
4846    /// `layer.moe.shared_expert_gate` in place on an already-built
4847    /// decoder (no need to reconstruct a `LayerWeights`/`MoeWeights`
4848    /// from scratch) and comparing against a hand-derived expectation:
4849    /// the *only* thing the gate changes is the shared experts' own
4850    /// contribution, scaled by `sigmoid(gate . x)` -- so
4851    /// `gated_shared_output == ungated_shared_output * sigmoid_value`
4852    /// exactly, computed independently here via `run_expert` on the
4853    /// same layer's shared expert.
4854    #[test]
4855    fn shared_expert_gate_scales_shared_output_by_sigmoid_of_the_gate_logit() {
4856        let cfg = tiny_test_config();
4857        let mut decoder = Decoder::new_random_small(cfg, 2, 8);
4858        let hidden_dim = decoder.config.hidden_dim;
4859        assert_eq!(
4860            decoder.layers[1].moe.shared_experts.len(),
4861            1,
4862            "test assumes tiny_test_config's real MoE layer has exactly one shared expert"
4863        );
4864
4865        let normed2: Vec<f32> = (0..hidden_dim).map(|i| (i as f32 * 0.37).sin()).collect();
4866        let gate_vec: Vec<f32> = (0..hidden_dim).map(|i| i as f32 * 0.13 - 0.5).collect();
4867
4868        // Independently compute what the shared expert alone produces,
4869        // and what sigmoid(gate . x) should scale it by -- this is the
4870        // ground truth the gated code path must reproduce exactly.
4871        let shared_out_raw = run_expert(
4872            &normed2,
4873            &decoder.layers[1].moe.shared_experts[0],
4874            GluAct::from(decoder.config.ffn_activation),
4875        );
4876        let gate_logit: f32 = gate_vec
4877            .iter()
4878            .zip(normed2.iter())
4879            .map(|(g, x)| g * x)
4880            .sum();
4881        let gate_value = 1.0 / (1.0 + (-gate_logit).exp());
4882        let expected_gated_shared: Vec<f32> =
4883            shared_out_raw.iter().map(|x| x * gate_value).collect();
4884
4885        // Run the real FFN combine path twice (gate absent, then
4886        // present) and recover each run's shared-only contribution by
4887        // subtracting the routed contribution, which the gate never
4888        // touches and is identical between the two runs (same router,
4889        // same experts, same input).
4890        let router_logits = decoder.layers[1].moe.router.apply(&normed2);
4891        let ungated_total = Decoder::combine_ffn_outputs_for_position(
4892            &decoder.layers[1],
4893            &normed2,
4894            &router_logits,
4895            &decoder.config,
4896            hidden_dim,
4897            None,
4898        );
4899        decoder.layers[1].moe.shared_expert_gate = Some(gate_vec);
4900        let gated_total = Decoder::combine_ffn_outputs_for_position(
4901            &decoder.layers[1],
4902            &normed2,
4903            &router_logits,
4904            &decoder.config,
4905            hidden_dim,
4906            None,
4907        );
4908
4909        for (i, ((u, g), expected_shared)) in ungated_total
4910            .iter()
4911            .zip(gated_total.iter())
4912            .zip(expected_gated_shared.iter())
4913            .enumerate()
4914        {
4915            let routed_contribution = u - shared_out_raw[i];
4916            let gated_shared_recovered = g - routed_contribution;
4917            assert!(
4918                (gated_shared_recovered - expected_shared).abs() < 1e-4,
4919                "index {i}: recovered gated shared output {gated_shared_recovered} != expected {expected_shared} (sigmoid({gate_logit})={gate_value})"
4920            );
4921        }
4922    }
4923
4924    #[test]
4925    fn kv_cache_grows_by_one_position_per_layer_per_step() {
4926        let decoder = Decoder::new_random_small(tiny_test_config(), 3, 5);
4927        let mut caches: Vec<KvCache> = (0..3)
4928            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
4929            .collect();
4930
4931        decoder.forward_token(0, 0, &mut caches);
4932        decoder.forward_token(1, 1, &mut caches);
4933        decoder.forward_token(2, 2, &mut caches);
4934
4935        for cache in &caches {
4936            assert_eq!(cache.positions(), 3);
4937        }
4938    }
4939
4940    #[test]
4941    fn same_token_same_position_is_deterministic() {
4942        let decoder = Decoder::new_random_small(tiny_test_config(), 2, 8);
4943        let mut caches_a: Vec<KvCache> = (0..2)
4944            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
4945            .collect();
4946        let mut caches_b: Vec<KvCache> = (0..2)
4947            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
4948            .collect();
4949
4950        let out_a = decoder.forward_token(4, 0, &mut caches_a);
4951        let out_b = decoder.forward_token(4, 0, &mut caches_b);
4952        assert_eq!(out_a, out_b, "identical input state must yield identical output (no hidden randomness in the forward pass)");
4953    }
4954
4955    #[test]
4956    fn multi_step_decode_stays_finite_across_positions() {
4957        let decoder = Decoder::new_random_small(tiny_test_config(), 2, 8);
4958        let mut caches: Vec<KvCache> = (0..2)
4959            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
4960            .collect();
4961
4962        for pos in 0..16 {
4963            let logits = decoder.forward_token(pos % 8, pos, &mut caches);
4964            assert!(
4965                logits.iter().all(|v| v.is_finite()),
4966                "position {pos}: logits must stay finite across an extended decode run"
4967            );
4968        }
4969    }
4970
4971    /// `forward_token_paged` must produce bit-identical output to
4972    /// `forward_token` across a multi-step decode (each layer's paged
4973    /// store sized generously so no layer ever exhausts its blocks) --
4974    /// the block-table indirection is a storage-layout detail, not a
4975    /// math change.
4976    #[test]
4977    fn forward_token_paged_matches_forward_token_bit_identical() {
4978        paged_matches_contiguous(tiny_test_config());
4979    }
4980
4981    /// Every arm of the attention dispatch, not just the plain one.
4982    ///
4983    /// The paged path used to implement only full causal attention, and
4984    /// `forward_token_paged` asserted rather than run gpt-oss, because a
4985    /// missing sink term would have changed the distribution silently.
4986    /// Now that it mirrors all three arms, each one has to be held to
4987    /// the same bar the plain arm always was: BIT-identical, not close.
4988    ///
4989    /// A sliding window and a softcap are both driven from the config
4990    /// here, so a future edit that wires one arm and forgets another
4991    /// fails on the arm it forgot rather than on a model nobody tests.
4992    #[test]
4993    fn every_paged_attention_arm_is_bit_identical_to_its_contiguous_twin() {
4994        let windowed = || {
4995            let mut cfg = tiny_test_config();
4996            // Smaller than the decode length below, so the window really
4997            // drops positions rather than degenerating to full causal.
4998            cfg.sliding_window = Some(2);
4999            cfg.swa_pattern = None;
5000            cfg
5001        };
5002        let softcapped = || {
5003            let mut cfg = tiny_test_config();
5004            // Small enough that `sc * tanh(s / sc)` actually compresses.
5005            // A realistic 30.0 is numerically indistinguishable from no
5006            // cap at these tiny weights, so a test using it would pass
5007            // whether or not the arm was wired -- checked by breaking
5008            // the arm on purpose and watching it still pass.
5009            cfg.attn_logit_softcap = Some(0.05);
5010            cfg
5011        };
5012        let both = || {
5013            let mut cfg = windowed();
5014            cfg.attn_logit_softcap = Some(0.05);
5015            cfg
5016        };
5017        // Alternating window/full layers: the per-layer arm choice has
5018        // to be honoured per layer, not decided once for the model.
5019        let alternating = || {
5020            let mut cfg = tiny_test_config();
5021            cfg.sliding_window = Some(2);
5022            cfg.swa_pattern = Some(2);
5023            cfg
5024        };
5025
5026        for cfg in [windowed(), softcapped(), both(), alternating()] {
5027            paged_matches_contiguous(cfg);
5028        }
5029    }
5030
5031    /// Five MORE model features the paged path had lost the same way
5032    /// the first five went: by being a copy of the contiguous loop that
5033    /// nothing forced to stay in step.
5034    ///
5035    /// Found by running Gemma-2-2B through paged KV and watching it
5036    /// answer differently from the same model on the same backend with
5037    /// a contiguous cache -- on CPU, with no GPU involved at all. None
5038    /// of the arm tests above could see it, because `tiny_test_config`
5039    /// sets none of these and `new_random_small` builds every layer
5040    /// without the two sandwich norms.
5041    ///
5042    /// - `attention_scale`: Gemma scales Q itself and asks the kernel
5043    ///   for a score scale of 1.0, so the built-in `1/sqrt(head_dim)`
5044    ///   has to be compensated for. Missing, the model answers at a
5045    ///   different temperature.
5046    /// - `post_attn_norm` / `post_ffn_norm`: Gemma-2's sandwich norms,
5047    ///   applied to each branch before it rejoins the residual.
5048    /// - gpt-oss's `o_bias`, and its own FFN (`gpt_oss_ffn`, which
5049    ///   biases the router and runs the clamped OAI SwiGLU) instead of
5050    ///   the generic one.
5051    ///
5052    /// Every one of them produces a plausible distribution rather than
5053    /// an error, which is exactly why they are pinned rather than
5054    /// trusted. Values are chosen so each really bites: a scale of 1.0
5055    /// or an all-ones norm would let this pass either way.
5056    #[test]
5057    fn the_paged_path_keeps_every_per_layer_feature_the_contiguous_one_applies() {
5058        // Gemma's query pre-attention scalar, well away from the
5059        // kernel's own 1/sqrt(head_dim).
5060        let mut scaled = tiny_test_config();
5061        scaled.attention_scale = Some(0.37);
5062        paged_matches_contiguous_with(scaled, |_| {});
5063
5064        // Sandwich norms, one at a time and then together, so a wired
5065        // half is not covered for by the other.
5066        for (attn, ffn) in [(true, false), (false, true), (true, true)] {
5067            paged_matches_contiguous_with(tiny_test_config(), with_sandwich_norms(attn, ffn));
5068        }
5069
5070        // gpt-oss: the O bias and the OAI FFN, which the paged path was
5071        // substituting the generic router+SwiGLU for.
5072        paged_matches_contiguous_with(tiny_test_config(), with_gpt_oss_graph);
5073    }
5074
5075    /// The same feature list as
5076    /// [`the_paged_path_keeps_every_per_layer_feature_the_contiguous_one_applies`],
5077    /// checked against `forward_hidden_batch_inner` instead.
5078    ///
5079    /// Necessary because `forward_token` and `forward_token_paged` now
5080    /// share ONE body (`Decoder::attn_block`) that differs only in its
5081    /// `KvStep`, so the paged test can no longer see a decoration
5082    /// dropped from that body -- deleting `post_attn_norm` or gpt-oss's
5083    /// `o_bias` from it leaves the whole suite green, which was measured
5084    /// rather than assumed. `forward_hidden_batch_inner` is deliberately
5085    /// NOT collapsed into the same body, so it is the independent
5086    /// ground truth that keeps these features pinned.
5087    #[test]
5088    fn the_batched_path_keeps_every_per_layer_feature_the_token_path_applies() {
5089        for (attn, ffn) in [(true, false), (false, true), (true, true)] {
5090            batched_matches_contiguous_with(tiny_test_config(), with_sandwich_norms(attn, ffn));
5091        }
5092        batched_matches_contiguous_with(tiny_test_config(), with_gpt_oss_graph);
5093    }
5094
5095    /// Gemma-2's two sandwich norms, as a switch both parity helpers
5096    /// take, so the paged and batched tests cannot drift over WHICH
5097    /// features they claim to cover.
5098    ///
5099    /// Per-layer values, so a path that applied layer 0's norm
5100    /// everywhere would still fail.
5101    fn with_sandwich_norms(attn: bool, ffn: bool) -> impl Fn(&mut Decoder) {
5102        move |d: &mut Decoder| {
5103            let hidden = d.config.hidden_dim;
5104            for (i, layer) in d.layers.iter_mut().enumerate() {
5105                let w: Vec<f32> = (0..hidden)
5106                    .map(|j| 0.5 + (i * hidden + j) as f32 * 0.01)
5107                    .collect();
5108                if attn {
5109                    layer.attn.post_attn_norm = Some(w.clone());
5110                }
5111                if ffn {
5112                    layer.attn.post_ffn_norm = Some(w);
5113                }
5114            }
5115        }
5116    }
5117
5118    /// The whole gpt-oss side table: attention sinks, the O bias, the
5119    /// router bias and the per-expert biases `gpt_oss_ffn` reads.
5120    fn with_gpt_oss_graph(d: &mut Decoder) {
5121        let hidden = d.config.hidden_dim;
5122        let n_heads = d.config.n_heads;
5123        let n_experts = d.config.moe.n_experts;
5124        let ffn = d.config.moe.expert_ffn_dim;
5125        let n_layers = d.layers.len();
5126        d.gpt_oss = Some(GptOssWeights {
5127            layers: (0..n_layers)
5128                .map(|l| GptOssLayer {
5129                    attn_sinks: (0..n_heads).map(|h| 0.1 + (l + h) as f32 * 0.05).collect(),
5130                    o_bias: (0..hidden).map(|j| 0.02 * (j as f32 - 8.0)).collect(),
5131                    router_bias: (0..n_experts).map(|e| 0.03 * e as f32).collect(),
5132                    expert_bias: (0..n_experts)
5133                        .map(|e| ferrox_moe::ExpertBias {
5134                            gate: vec![0.01 * (e + 1) as f32; ffn],
5135                            up: vec![-0.02 * (e + 1) as f32; ffn],
5136                            down: vec![0.005 * (e + 1) as f32; hidden],
5137                        })
5138                        .collect(),
5139                })
5140                .collect(),
5141        });
5142    }
5143
5144    /// [`paged_matches_contiguous_with`] for `forward_batch` against
5145    /// sequential `forward_token`.
5146    ///
5147    /// Not bit-identity: batched prefill runs the blocked three-pass
5148    /// softmax while decode keeps the online accumulator, so the two
5149    /// agree to a tolerance rather than to the bit -- the same reason
5150    /// `decoder_via_engine_trait_matches_forward_batch_ground_truth`
5151    /// gives. 1e-5 is four orders below the ~1e-1 a dropped decoration
5152    /// moves these logits by.
5153    fn batched_matches_contiguous_with(config: ModelConfig, prepare: impl Fn(&mut Decoder)) {
5154        let n_layers = 2;
5155        let vocab = 10;
5156        let tokens = [3usize, 5, 7, 2, 9, 1];
5157
5158        let mut seq_decoder = Decoder::new_random_small(config.clone(), n_layers, vocab);
5159        prepare(&mut seq_decoder);
5160        let mut seq_caches: Vec<KvCache> = (0..n_layers)
5161            .map(|_| KvCache::new(seq_decoder.config.n_kv_heads, seq_decoder.config.head_dim))
5162            .collect();
5163        let sequential: Vec<Vec<f32>> = tokens
5164            .iter()
5165            .enumerate()
5166            .map(|(pos, &t)| seq_decoder.forward_token(t, pos, &mut seq_caches))
5167            .collect();
5168
5169        // Same seed -> identical weights before `prepare`, and `prepare`
5170        // is deterministic, so this is a like-for-like comparison.
5171        let mut batch_decoder = Decoder::new_random_small(config, n_layers, vocab);
5172        prepare(&mut batch_decoder);
5173        let mut batch_caches: Vec<KvCache> = (0..n_layers)
5174            .map(|_| {
5175                KvCache::new(
5176                    batch_decoder.config.n_kv_heads,
5177                    batch_decoder.config.head_dim,
5178                )
5179            })
5180            .collect();
5181        let batched = batch_decoder.forward_batch(&tokens, 0, &mut batch_caches);
5182
5183        assert_eq!(sequential.len(), batched.len());
5184        for (pos, (a, b)) in sequential.iter().zip(batched.iter()).enumerate() {
5185            assert_eq!(a.len(), b.len(), "position {pos}: logit count");
5186            for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() {
5187                assert!(
5188                    (x - y).abs() < 1e-5,
5189                    "position {pos}, logit {i}: token path={x} batched={y}"
5190                );
5191            }
5192        }
5193    }
5194
5195    /// The two rules that live OUTSIDE the layer loop, which the arm
5196    /// test above cannot reach.
5197    ///
5198    /// The paged path had drifted from the contiguous one at both ends
5199    /// of the stack, and neither drift was visible to any existing test
5200    /// because `tiny_test_config` sets neither field:
5201    ///
5202    /// - it called `embedding.dequant_row` directly instead of scaling
5203    ///   the row by `embedding_scale`, so every Gemma token entered the
5204    ///   stack `sqrt(hidden_dim)` times too small;
5205    /// - it returned `output_head.apply(..)` raw instead of applying
5206    ///   `final_logit_softcap`, so Gemma-2's 30.0 cap never ran.
5207    ///
5208    /// Both produce a plausible distribution rather than an error, which
5209    /// is the whole reason to pin them: a wrong answer that still looks
5210    /// like an answer is what a parity test is for. Values here are
5211    /// chosen so each one actually bites -- a scale of 1.0 or a cap far
5212    /// above the logit range would let this pass either way.
5213    #[test]
5214    fn the_paged_path_scales_embeddings_and_softcaps_logits_like_the_contiguous_one() {
5215        let scaled = || {
5216            let mut cfg = tiny_test_config();
5217            cfg.embedding_scale = Some(7.5);
5218            cfg
5219        };
5220        let capped = || {
5221            let mut cfg = tiny_test_config();
5222            // Small enough that `sc * tanh(x / sc)` really compresses at
5223            // this model's logit magnitudes, on the same reasoning as
5224            // the attention softcap above.
5225            cfg.final_logit_softcap = Some(0.05);
5226            cfg
5227        };
5228        let both = || {
5229            let mut cfg = scaled();
5230            cfg.final_logit_softcap = Some(0.05);
5231            cfg
5232        };
5233
5234        for cfg in [scaled(), capped(), both()] {
5235            paged_matches_contiguous(cfg);
5236        }
5237    }
5238
5239    /// Paged prefill must agree with contiguous prefill, and must leave
5240    /// the KV in a state a paged DECODE can continue from.
5241    ///
5242    /// The second half is the one worth having. `forward_batch_last`
5243    /// returns only the last row's logits, so a gather/scatter that
5244    /// mangled the KV -- wrote the rows in the wrong order, dropped the
5245    /// part-full tail block, mis-sized a copy -- could still return the
5246    /// right logits for THIS call and only surface on the next token.
5247    /// Decoding four more tokens after the prefill is what makes the
5248    /// stored KV observable, so both paths are compared over the whole
5249    /// continuation rather than at the seam.
5250    ///
5251    /// A block size of 2 against a 5-token prompt is deliberate: it
5252    /// leaves the tail block part-full, which is the case
5253    /// `blocks_needed_for` exists for and the one a `n / block_size`
5254    /// reservation would get wrong.
5255    fn paged_prefill_matches_contiguous(config: ModelConfig) {
5256        let n_layers = 2;
5257        let decoder = Decoder::new_random_small(config, n_layers, 10);
5258        let prompt = [3usize, 1, 4, 1, 5];
5259        let continuation = [9usize, 2, 6, 5];
5260
5261        let mut caches: Vec<KvCache> = (0..n_layers)
5262            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
5263            .collect();
5264        let mut plain = vec![decoder.forward_batch_last(&prompt, 0, &mut caches)];
5265        for (i, &tok) in continuation.iter().enumerate() {
5266            plain.push(decoder.forward_token(tok, prompt.len() + i, &mut caches));
5267        }
5268
5269        let mut paged_caches: Vec<PagedKvCache> =
5270            (0..n_layers).map(|_| PagedKvCache::new()).collect();
5271        let stores = SharedPagedKv::from_stores(
5272            (0..n_layers)
5273                .map(|_| {
5274                    PagedKvStore::new(
5275                        /* block_size = */ 2,
5276                        /* total_blocks = */ 16,
5277                        decoder.config.n_kv_heads,
5278                        decoder.config.head_dim,
5279                    )
5280                })
5281                .collect(),
5282        );
5283        let mut paged = vec![decoder
5284            .forward_batch_last_paged(&prompt, 0, &mut paged_caches, &stores)
5285            .expect("store sized generously, must not exhaust")];
5286        for (i, &tok) in continuation.iter().enumerate() {
5287            paged.push(
5288                decoder
5289                    .forward_token_paged(tok, prompt.len() + i, &mut paged_caches, &stores)
5290                    .expect("store sized generously, must not exhaust"),
5291            );
5292        }
5293
5294        assert_eq!(
5295            paged_caches[0].seq_len(),
5296            prompt.len() + continuation.len(),
5297            "paged prefill must advance seq_len by exactly the batch size"
5298        );
5299        assert_eq!(plain.len(), paged.len());
5300        for (step, (a, b)) in plain.iter().zip(paged.iter()).enumerate() {
5301            assert_eq!(a.len(), b.len(), "step {step}: logit count");
5302            for (x, y) in a.iter().zip(b.iter()) {
5303                assert_eq!(
5304                    x.to_bits(),
5305                    y.to_bits(),
5306                    "step {step}: paged prefill + decode must be bit-identical to contiguous"
5307                );
5308            }
5309        }
5310    }
5311
5312    /// Every arm again, this time through the prefill entry point. The
5313    /// gather is shared, but the kernel the gathered buffer reaches is
5314    /// the BLOCKED prefill one rather than the per-query decode one, so
5315    /// arm coverage here is not implied by the decode tests above.
5316    #[test]
5317    fn paged_prefill_is_bit_identical_across_every_arm() {
5318        let windowed = || {
5319            let mut cfg = tiny_test_config();
5320            cfg.sliding_window = Some(2);
5321            cfg.swa_pattern = None;
5322            cfg
5323        };
5324        let scaled_and_capped = || {
5325            let mut cfg = tiny_test_config();
5326            cfg.embedding_scale = Some(7.5);
5327            cfg.final_logit_softcap = Some(0.05);
5328            cfg.attn_logit_softcap = Some(0.05);
5329            cfg
5330        };
5331        let alternating = || {
5332            let mut cfg = tiny_test_config();
5333            cfg.sliding_window = Some(2);
5334            cfg.swa_pattern = Some(2);
5335            cfg
5336        };
5337
5338        for cfg in [
5339            tiny_test_config(),
5340            windowed(),
5341            scaled_and_capped(),
5342            alternating(),
5343        ] {
5344            paged_prefill_matches_contiguous(cfg);
5345        }
5346    }
5347
5348    /// A prefill the stores cannot hold refuses having written NOTHING
5349    /// -- checked on the case that actually needs the up-front loop.
5350    ///
5351    /// Each layer owns its own store, so layer 0 having room says
5352    /// nothing about layer 1. `append_contiguous` already refuses
5353    /// rather than half-writing a single layer, so a test whose layers
5354    /// are sized alike passes with the cross-layer reservation deleted
5355    /// -- it would be asserting a property it never exercises. Here
5356    /// layer 0 has room for the whole prompt and layer 1 does not, so
5357    /// without the up-front check layer 0 is written, layer 1 refuses,
5358    /// and the sequence ends up with its layers at DIFFERENT lengths.
5359    /// No caller can recover from that, and nothing downstream would
5360    /// report it: the next decode step simply attends over a shorter
5361    /// history in one layer than the others.
5362    ///
5363    /// Verified by deleting the reservation loop and watching this fail
5364    /// on `layer 1 must be untouched`.
5365    /// Three requests sharing one set of per-layer stores must get
5366    /// exactly what they would get alone.
5367    ///
5368    /// This is the property the RwLock exists for, and it cannot be
5369    /// asserted single-threaded. Every request writes only blocks it
5370    /// owns, so sharing changes where rows live and nothing else --
5371    /// bit-identical, not close. A store that let one request's rows
5372    /// land in another's blocks shows up here and nowhere else.
5373    #[test]
5374    fn concurrent_decodes_against_one_shared_store_match_running_them_alone() {
5375        use std::sync::Arc;
5376
5377        let decoder = Arc::new(Decoder::new_random_small(tiny_test_config(), 2, 10));
5378        let prompts: [&[usize]; 3] = [&[3, 1, 4], &[1, 5, 9], &[2, 6, 5]];
5379        let continuation = [7usize, 8, 3];
5380
5381        // Each request run alone, against its own store, is the answer
5382        // sharing must not change.
5383        let solo: Vec<Vec<Vec<f32>>> = prompts
5384            .iter()
5385            .map(|prompt| {
5386                let stores = SharedPagedKv::new(
5387                    2,
5388                    4,
5389                    32,
5390                    decoder.config.n_kv_heads,
5391                    decoder.config.head_dim,
5392                );
5393                let mut caches: Vec<PagedKvCache> = (0..2).map(|_| PagedKvCache::new()).collect();
5394                run_one(&decoder, prompt, &continuation, &mut caches, &stores)
5395            })
5396            .collect();
5397
5398        // The same three, concurrently, sharing ONE set of per-layer
5399        // stores. Every request writes only blocks it owns, so the
5400        // answers must be identical -- not close, identical. A store
5401        // that let one request's rows land in another's blocks would
5402        // show up here and nowhere else.
5403        let shared = Arc::new(SharedPagedKv::new(
5404            2,
5405            4,
5406            96,
5407            decoder.config.n_kv_heads,
5408            decoder.config.head_dim,
5409        ));
5410        let together: Vec<Vec<Vec<f32>>> = std::thread::scope(|scope| {
5411            let handles: Vec<_> = prompts
5412                .iter()
5413                .map(|prompt| {
5414                    let decoder = Arc::clone(&decoder);
5415                    let shared = Arc::clone(&shared);
5416                    scope.spawn(move || {
5417                        let mut caches: Vec<PagedKvCache> =
5418                            (0..2).map(|_| PagedKvCache::new()).collect();
5419                        run_one(&decoder, prompt, &continuation, &mut caches, &shared)
5420                    })
5421                })
5422                .collect();
5423            handles.into_iter().map(|h| h.join().unwrap()).collect()
5424        });
5425
5426        for (r, (alone, concurrent)) in solo.iter().zip(together.iter()).enumerate() {
5427            assert_eq!(alone.len(), concurrent.len(), "request {r}: step count");
5428            for (step, (a, b)) in alone.iter().zip(concurrent.iter()).enumerate() {
5429                for (x, y) in a.iter().zip(b.iter()) {
5430                    assert_eq!(
5431                        x.to_bits(),
5432                        y.to_bits(),
5433                        "request {r} step {step}: sharing a store changed the answer"
5434                    );
5435                }
5436            }
5437        }
5438    }
5439
5440    /// Prefill then decode, returning every step's logits.
5441    fn run_one(
5442        decoder: &Decoder,
5443        prompt: &[usize],
5444        continuation: &[usize],
5445        caches: &mut [PagedKvCache],
5446        stores: &SharedPagedKv,
5447    ) -> Vec<Vec<f32>> {
5448        let mut out = vec![decoder
5449            .forward_batch_last_paged(prompt, 0, caches, stores)
5450            .expect("sized generously")];
5451        for (i, &tok) in continuation.iter().enumerate() {
5452            out.push(
5453                decoder
5454                    .forward_token_paged(tok, prompt.len() + i, caches, stores)
5455                    .expect("sized generously"),
5456            );
5457        }
5458        out
5459    }
5460
5461    /// A decode step the stores cannot hold advances NO layer.
5462    ///
5463    /// This was a real defect until the reservation moved into
5464    /// `forward_token_paged`: it pushed per layer with `?`, so a store
5465    /// exhausting at layer 1 of 2 left layer 0 holding a position layer
5466    /// 1 did not. Nothing downstream reports that -- the next step just
5467    /// attends over a shorter history in the tail layers -- and the
5468    /// prefill path had the guard while decode never did.
5469    ///
5470    /// Layer 0 is given room and layer 1 none, so the bug is reachable:
5471    /// with the reservation removed, layer 0 advances and layer 1
5472    /// refuses.
5473    #[test]
5474    fn a_decode_step_the_stores_cannot_hold_advances_no_layer() {
5475        let decoder = Decoder::new_random_small(tiny_test_config(), 2, 10);
5476        let mut caches: Vec<PagedKvCache> = (0..2).map(|_| PagedKvCache::new()).collect();
5477        // Block size 1 so "one more position" always needs a block.
5478        // Layer 0 gets two, layer 1 exactly one: the prompt fills layer
5479        // 1 completely, so the decode step below cannot fit there.
5480        let stores = SharedPagedKv::from_stores(
5481            [2usize, 1]
5482                .into_iter()
5483                .map(|blocks| {
5484                    PagedKvStore::new(
5485                        1,
5486                        blocks,
5487                        decoder.config.n_kv_heads,
5488                        decoder.config.head_dim,
5489                    )
5490                })
5491                .collect(),
5492        );
5493
5494        decoder
5495            .forward_batch_last_paged(&[1usize], 0, &mut caches, &stores)
5496            .expect("one position fits in both layers");
5497        assert_eq!(caches[0].seq_len(), 1);
5498        assert_eq!(caches[1].seq_len(), 1);
5499
5500        let result = decoder.forward_token_paged(2, 1, &mut caches, &stores);
5501        assert!(result.is_err(), "layer 1 has no block left");
5502        assert_eq!(
5503            caches[0].seq_len(),
5504            1,
5505            "layer 0 must not advance past a layer that could not"
5506        );
5507        assert_eq!(caches[1].seq_len(), 1);
5508    }
5509
5510    #[test]
5511    fn a_prefill_the_stores_cannot_hold_refuses_before_writing_any_layer() {
5512        let decoder = Decoder::new_random_small(tiny_test_config(), 2, 10);
5513        let prompt = [1usize, 2, 3, 4, 5, 6];
5514        let mut paged_caches: Vec<PagedKvCache> = (0..2).map(|_| PagedKvCache::new()).collect();
5515        // Layer 0 fits the prompt with room to spare; layer 1's two
5516        // blocks of 2 hold 4 positions against a prompt of 6.
5517        let stores = SharedPagedKv::from_stores(
5518            [8usize, 2]
5519                .into_iter()
5520                .map(|blocks| {
5521                    PagedKvStore::new(
5522                        2,
5523                        blocks,
5524                        decoder.config.n_kv_heads,
5525                        decoder.config.head_dim,
5526                    )
5527                })
5528                .collect(),
5529        );
5530
5531        let result = decoder.forward_batch_last_paged(&prompt, 0, &mut paged_caches, &stores);
5532        assert!(result.is_err(), "layer 1's store cannot hold the prompt");
5533        for (i, cache) in paged_caches.iter().enumerate() {
5534            assert_eq!(cache.seq_len(), 0, "layer {i} must be untouched");
5535            assert!(cache.block_table().is_empty(), "layer {i} holds no block");
5536        }
5537        for (i, expected) in [8usize, 2].into_iter().enumerate() {
5538            assert_eq!(stores.free_blocks(i), expected, "layer {i} leaked no block");
5539        }
5540    }
5541
5542    /// Chunked prefill: two calls appending into the same sequence must
5543    /// equal one call over the concatenation.
5544    ///
5545    /// This is the case the part-full tail block breaks if
5546    /// `to_contiguous` or the reservation is wrong, and it is how the
5547    /// serving path actually prefills long prompts.
5548    #[test]
5549    fn two_paged_prefill_chunks_equal_one_call_over_the_whole_prompt() {
5550        let decoder = Decoder::new_random_small(tiny_test_config(), 2, 10);
5551        let prompt = [3usize, 1, 4, 1, 5, 9, 2];
5552        let split = 3;
5553
5554        let run = |chunks: &[&[usize]]| {
5555            let mut caches: Vec<PagedKvCache> = (0..2).map(|_| PagedKvCache::new()).collect();
5556            let stores = SharedPagedKv::from_stores(
5557                (0..2)
5558                    .map(|_| {
5559                        PagedKvStore::new(2, 16, decoder.config.n_kv_heads, decoder.config.head_dim)
5560                    })
5561                    .collect(),
5562            );
5563            let mut pos = 0;
5564            let mut last = Vec::new();
5565            for chunk in chunks {
5566                last = decoder
5567                    .forward_batch_last_paged(chunk, pos, &mut caches, &stores)
5568                    .expect("sized generously");
5569                pos += chunk.len();
5570            }
5571            last
5572        };
5573
5574        let whole = run(&[&prompt]);
5575        let chunked = run(&[&prompt[..split], &prompt[split..]]);
5576        assert_eq!(whole.len(), chunked.len());
5577        for (x, y) in whole.iter().zip(chunked.iter()) {
5578            assert_eq!(
5579                x.to_bits(),
5580                y.to_bits(),
5581                "a chunked prefill must equal one call over the same tokens"
5582            );
5583        }
5584    }
5585
5586    fn paged_matches_contiguous(config: ModelConfig) {
5587        paged_matches_contiguous_with(config, |_| {});
5588    }
5589
5590    /// [`paged_matches_contiguous`] for the features that live on the
5591    /// WEIGHTS rather than in the config, and so cannot be switched on
5592    /// by handing a different `ModelConfig` in.
5593    fn paged_matches_contiguous_with(config: ModelConfig, prepare: impl FnOnce(&mut Decoder)) {
5594        let n_layers = 2;
5595        let mut decoder = Decoder::new_random_small(config, n_layers, 10);
5596        prepare(&mut decoder);
5597        let decoder = decoder;
5598
5599        let mut caches: Vec<KvCache> = (0..n_layers)
5600            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
5601            .collect();
5602        let steps = [3usize, 5, 7, 2, 9, 1];
5603        let mut plain_logits = Vec::new();
5604        for (pos, &tok) in steps.iter().enumerate() {
5605            plain_logits.push(decoder.forward_token(tok, pos, &mut caches));
5606        }
5607
5608        let block_size = 2;
5609        let mut paged_caches: Vec<PagedKvCache> =
5610            (0..n_layers).map(|_| PagedKvCache::new()).collect();
5611        let stores = SharedPagedKv::from_stores(
5612            (0..n_layers)
5613                .map(|_| {
5614                    PagedKvStore::new(
5615                        block_size,
5616                        /* total_blocks = */ 16,
5617                        decoder.config.n_kv_heads,
5618                        decoder.config.head_dim,
5619                    )
5620                })
5621                .collect(),
5622        );
5623        let mut paged_logits = Vec::new();
5624        for (pos, &tok) in steps.iter().enumerate() {
5625            paged_logits.push(
5626                decoder
5627                    .forward_token_paged(tok, pos, &mut paged_caches, &stores)
5628                    .expect("store sized generously, must not exhaust"),
5629            );
5630        }
5631
5632        assert_eq!(plain_logits.len(), paged_logits.len());
5633        for (a, b) in plain_logits.iter().zip(paged_logits.iter()) {
5634            assert_eq!(a.len(), b.len());
5635            for (x, y) in a.iter().zip(b.iter()) {
5636                assert_eq!(
5637                    x.to_bits(),
5638                    y.to_bits(),
5639                    "paged decode must be bit-identical to contiguous decode"
5640                );
5641            }
5642        }
5643    }
5644
5645    /// The single most important correctness property of
5646    /// `forward_batch`: batching positions together for shared matmuls
5647    /// must produce EXACTLY the same result as processing them one at
5648    /// a time with `forward_token`, since causal masking guarantees
5649    /// position `i` only ever sees positions `<= i`. If this test
5650    /// fails, `forward_batch` is not a safe drop-in replacement for
5651    /// sequential decode, which would make speculative decoding built
5652    /// on top of it produce silently wrong output.
5653    #[test]
5654    fn forward_batch_matches_sequential_forward_token_exactly() {
5655        let cfg = tiny_test_config();
5656        let vocab = 8;
5657        let tokens = [1usize, 3, 5, 2, 7];
5658
5659        let decoder_a = Decoder::new_random_small(cfg.clone(), 2, vocab);
5660        let mut caches_a: Vec<KvCache> = (0..2)
5661            .map(|_| KvCache::new(decoder_a.config.n_kv_heads, decoder_a.config.head_dim))
5662            .collect();
5663        let sequential: Vec<Vec<f32>> = tokens
5664            .iter()
5665            .enumerate()
5666            .map(|(pos, &t)| decoder_a.forward_token(t, pos, &mut caches_a))
5667            .collect();
5668
5669        // A second decoder built with the same seed produces identical
5670        // weights (Decoder::new_random_small is deterministic), so
5671        // this is a fair like-for-like comparison against a fresh
5672        // cache rather than reusing decoder_a's now-mutated cache.
5673        let decoder_b = Decoder::new_random_small(cfg, 2, vocab);
5674        let mut caches_b: Vec<KvCache> = (0..2)
5675            .map(|_| KvCache::new(decoder_b.config.n_kv_heads, decoder_b.config.head_dim))
5676            .collect();
5677        let batched = decoder_b.forward_batch(&tokens, 0, &mut caches_b);
5678
5679        assert_eq!(batched.len(), sequential.len());
5680        for (pos, (seq_logits, batch_logits)) in sequential.iter().zip(batched.iter()).enumerate() {
5681            assert_eq!(seq_logits.len(), batch_logits.len());
5682            for (i, (s, b)) in seq_logits.iter().zip(batch_logits.iter()).enumerate() {
5683                assert!(
5684                    (s - b).abs() < 1e-3,
5685                    "position {pos}, logit {i}: sequential={s} batched={b}"
5686                );
5687            }
5688        }
5689    }
5690
5691    /// `forward_batch_last` exists to skip the vocabulary projection for
5692    /// every position but the last, so the one thing that must hold is
5693    /// that the row it *does* produce is the same row `forward_batch`
5694    /// would have produced. It must also leave the KV cache in the same
5695    /// state -- prefill's whole purpose -- which is checked by decoding
5696    /// one more token from each cache and comparing.
5697    #[test]
5698    fn forward_batch_last_matches_the_final_row_of_forward_batch() {
5699        let cfg = tiny_test_config();
5700        let vocab = 16;
5701        let tokens = vec![1usize, 4, 7, 2, 9];
5702
5703        let decoder_a = Decoder::new_random_small(cfg.clone(), 2, vocab);
5704        let mut caches_a: Vec<KvCache> = (0..2)
5705            .map(|_| KvCache::new(decoder_a.config.n_kv_heads, decoder_a.config.head_dim))
5706            .collect();
5707        let all_rows = decoder_a.forward_batch(&tokens, 0, &mut caches_a);
5708
5709        let decoder_b = Decoder::new_random_small(cfg, 2, vocab);
5710        let mut caches_b: Vec<KvCache> = (0..2)
5711            .map(|_| KvCache::new(decoder_b.config.n_kv_heads, decoder_b.config.head_dim))
5712            .collect();
5713        let last = decoder_b.forward_batch_last(&tokens, 0, &mut caches_b);
5714
5715        let expected = all_rows.last().expect("one row per prompt token");
5716        assert_eq!(last.len(), expected.len());
5717        for (i, (a, b)) in expected.iter().zip(last.iter()).enumerate() {
5718            assert!(
5719                (a - b).abs() < 1e-4,
5720                "logit {i}: forward_batch={a} forward_batch_last={b}"
5721            );
5722        }
5723
5724        // Same KV state: the next token's logits must agree too.
5725        let next_a = decoder_a.forward_token(3, tokens.len(), &mut caches_a);
5726        let next_b = decoder_b.forward_token(3, tokens.len(), &mut caches_b);
5727        for (i, (a, b)) in next_a.iter().zip(next_b.iter()).enumerate() {
5728            assert!(
5729                (a - b).abs() < 1e-4,
5730                "post-prefill decode logit {i}: {a} vs {b}"
5731            );
5732        }
5733
5734        // Empty prompt is the degenerate case both paths must survive.
5735        let mut caches_c: Vec<KvCache> = (0..2)
5736            .map(|_| KvCache::new(decoder_b.config.n_kv_heads, decoder_b.config.head_dim))
5737            .collect();
5738        assert!(decoder_b
5739            .forward_batch_last(&[], 0, &mut caches_c)
5740            .is_empty());
5741    }
5742
5743    /// `forward_multi_seq`'s core correctness property: batching N
5744    /// independent sequences (different token histories, different
5745    /// current positions, different KV caches) together must produce
5746    /// EXACTLY the same per-sequence output as running each sequence
5747    /// through `forward_token` alone, one step at a time. This is what
5748    /// makes continuous batching safe -- no sequence's attention may
5749    /// ever be perturbed by another sequence sharing its batched
5750    /// matmul step.
5751    /// The PAGED batch step must equal the contiguous one, bit for bit.
5752    ///
5753    /// Continuous batching and paging are independent choices, so a
5754    /// deployment can have either, both or neither; if they disagree,
5755    /// the answer depends on two switches nobody thinks of as changing
5756    /// the model. Every sequence here is at a different position with a
5757    /// different length, which is the case the batched path exists for
5758    /// and the one where a shared-KV mistake would surface.
5759    #[test]
5760    fn a_paged_multi_seq_step_is_bit_identical_to_the_contiguous_one() {
5761        for cfg in [
5762            tiny_test_config(),
5763            {
5764                let mut c = tiny_test_config();
5765                c.sliding_window = Some(2);
5766                c.swa_pattern = None;
5767                c
5768            },
5769            {
5770                let mut c = tiny_test_config();
5771                c.embedding_scale = Some(7.5);
5772                c.final_logit_softcap = Some(0.05);
5773                c.attn_logit_softcap = Some(0.05);
5774                c
5775            },
5776        ] {
5777            let n_layers = 2;
5778            let decoder = Decoder::new_random_small(cfg, n_layers, 10);
5779            let histories: [&[usize]; 3] = [&[1, 3, 5], &[2, 7], &[4, 4, 4, 6]];
5780            let next = [6usize, 1, 2];
5781
5782            // Contiguous: build each sequence's history, then one step.
5783            let mut contiguous: Vec<Vec<KvCache>> = histories
5784                .iter()
5785                .map(|h| {
5786                    let mut caches: Vec<KvCache> = (0..n_layers)
5787                        .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
5788                        .collect();
5789                    for (pos, &tok) in h.iter().enumerate() {
5790                        decoder.forward_token(tok, pos, &mut caches);
5791                    }
5792                    caches
5793                })
5794                .collect();
5795            let positions: Vec<usize> = histories.iter().map(|h| h.len()).collect();
5796            let want = decoder.forward_multi_seq(&next, &positions, &mut contiguous);
5797
5798            // Paged: same histories through the paged decode path, then
5799            // one batched step over the shared store.
5800            let stores = SharedPagedKv::new(
5801                n_layers,
5802                /* block_size = */ 2,
5803                /* blocks_per_layer = */ 64,
5804                decoder.config.n_kv_heads,
5805                decoder.config.head_dim,
5806            );
5807            let mut paged: Vec<Vec<PagedKvCache>> = histories
5808                .iter()
5809                .map(|h| {
5810                    let mut caches: Vec<PagedKvCache> =
5811                        (0..n_layers).map(|_| PagedKvCache::new()).collect();
5812                    for (pos, &tok) in h.iter().enumerate() {
5813                        decoder
5814                            .forward_token_paged(tok, pos, &mut caches, &stores)
5815                            .expect("sized generously");
5816                    }
5817                    caches
5818                })
5819                .collect();
5820            let got = decoder.forward_multi_seq_kv(
5821                &next,
5822                &positions,
5823                &mut MultiSeqKv::Paged {
5824                    caches: &mut paged,
5825                    stores: &stores,
5826                },
5827            );
5828
5829            assert_eq!(want.len(), got.len());
5830            for (s, (a, b)) in want.iter().zip(got.iter()).enumerate() {
5831                assert_eq!(a.len(), b.len(), "sequence {s}: logit count");
5832                for (x, y) in a.iter().zip(b.iter()) {
5833                    assert_eq!(
5834                        x.to_bits(),
5835                        y.to_bits(),
5836                        "sequence {s}: paged batching changed the answer"
5837                    );
5838                }
5839            }
5840        }
5841    }
5842
5843    #[test]
5844    fn forward_multi_seq_matches_independent_forward_token_per_sequence() {
5845        let cfg = tiny_test_config();
5846        let vocab = 8;
5847        // 3 independent sequences, deliberately different lengths/
5848        // histories/current tokens, so no two sequences are at the
5849        // same position when batched together.
5850        let seq_histories: [&[usize]; 3] = [&[1, 3, 5], &[2, 7], &[4, 4, 4, 6]];
5851
5852        let decoder_a = Decoder::new_random_small(cfg.clone(), 2, vocab);
5853        let mut independent_logits: Vec<Vec<f32>> = Vec::new();
5854        for history in seq_histories.iter() {
5855            let mut caches: Vec<KvCache> = (0..2)
5856                .map(|_| KvCache::new(decoder_a.config.n_kv_heads, decoder_a.config.head_dim))
5857                .collect();
5858            let mut logits = Vec::new();
5859            for (pos, &tok) in history.iter().enumerate() {
5860                logits = decoder_a.forward_token(tok, pos, &mut caches);
5861            }
5862            independent_logits.push(logits);
5863        }
5864
5865        // Same seed -> identical weights, fresh caches for a fair
5866        // comparison (mirrors forward_batch_matches_sequential_forward_token_exactly).
5867        let decoder_b = Decoder::new_random_small(cfg, 2, vocab);
5868        let mut per_seq_caches: Vec<Vec<KvCache>> = seq_histories
5869            .iter()
5870            .map(|_| {
5871                (0..2)
5872                    .map(|_| KvCache::new(decoder_b.config.n_kv_heads, decoder_b.config.head_dim))
5873                    .collect()
5874            })
5875            .collect();
5876
5877        // Feed every sequence's prefix (all but its last token)
5878        // through forward_multi_seq one shared step at a time, then
5879        // do a final batched step for the last token of every
5880        // sequence so all three arrive at their final position in
5881        // the same batched call -- exercising genuinely different
5882        // per-sequence positions/histories within one batch, not just
5883        // parallel identical-length sequences.
5884        let max_len = seq_histories.iter().map(|h| h.len()).max().unwrap();
5885        let mut batched_logits: Vec<Vec<f32>> = vec![Vec::new(); seq_histories.len()];
5886        for step in 0..max_len {
5887            let mut tokens = Vec::new();
5888            let mut positions = Vec::new();
5889            let mut active: Vec<usize> = Vec::new();
5890            for (s, history) in seq_histories.iter().enumerate() {
5891                if step < history.len() {
5892                    tokens.push(history[step]);
5893                    positions.push(step);
5894                    active.push(s);
5895                }
5896            }
5897            if tokens.is_empty() {
5898                continue;
5899            }
5900            let mut active_caches: Vec<Vec<KvCache>> = active
5901                .iter()
5902                .map(|&s| std::mem::take(&mut per_seq_caches[s]))
5903                .collect();
5904            let step_logits = decoder_b.forward_multi_seq(&tokens, &positions, &mut active_caches);
5905            for ((&s, caches), logits) in active.iter().zip(active_caches).zip(step_logits) {
5906                per_seq_caches[s] = caches;
5907                batched_logits[s] = logits;
5908            }
5909        }
5910
5911        assert_eq!(batched_logits.len(), independent_logits.len());
5912        for (s, (seq_logits, batch_logits)) in independent_logits
5913            .iter()
5914            .zip(batched_logits.iter())
5915            .enumerate()
5916        {
5917            assert_eq!(seq_logits.len(), batch_logits.len());
5918            for (i, (a, b)) in seq_logits.iter().zip(batch_logits.iter()).enumerate() {
5919                assert!(
5920                    (a - b).abs() < 1e-3,
5921                    "sequence {s}, logit {i}: independent={a} batched={b}"
5922                );
5923            }
5924        }
5925    }
5926
5927    /// The gap the decoration audit found, from the side the existing
5928    /// guard could not see.
5929    ///
5930    /// `the_paged_path_keeps_every_per_layer_feature_the_contiguous_one_applies`
5931    /// sets `attention_scale` and compares `forward_token` against
5932    /// `forward_token_paged` -- the two bodies that AGREED. It never
5933    /// compared them against `forward_hidden_batch_inner`, which applied
5934    /// the scale nowhere, so a Gemma-shaped checkpoint would answer at
5935    /// one temperature when decoded a token at a time and at another
5936    /// when its prompt was prefilled. Not an error; a plausible
5937    /// distribution from the wrong model.
5938    ///
5939    /// The first assertion is the one that makes this a guard rather
5940    /// than an assertion: 0.37 is well away from the kernel's own
5941    /// `1/sqrt(head_dim)`, so if setting it does not move the logits
5942    /// then both sides are ignoring it and the comparison below proves
5943    /// nothing.
5944    /// The Metal attention kernels infer Q/K norm style from the weight
5945    /// LENGTH; the host branches on `ModelConfig::qk_norm_style`. Two
5946    /// mechanisms for one decision, so they have to agree.
5947    ///
5948    /// They do, and not by luck: `loader.rs`'s `refined_qk_norm` DERIVES
5949    /// the enum from the same length rule, and refuses to load anything
5950    /// that matches neither width. This pins that, because the failure
5951    /// would be silent and would land on audited architectures --
5952    /// OLMoE is whole-vector, Qwen3 and Gemma-3 are per-head, and all
5953    /// three are in `AUDITED_GENERIC_GQA`, so an inference that assumed
5954    /// one style would answer wrong on the others at full speed.
5955    ///
5956    /// Raised by the decoration audit as unverifiable from the host
5957    /// side, which is exactly why it is written down here rather than
5958    /// left as a comment on one of the two sides.
5959    #[test]
5960    fn the_metal_qk_norm_length_rule_is_the_one_the_loader_derives_the_style_from() {
5961        use crate::capability::QkNormStyle;
5962        let head_dim = 8usize;
5963        let n_heads = 4usize;
5964
5965        // The rule `ferrox-metal/src/attn.rs` applies, transcribed.
5966        let metal_says_per_head = |len: usize| len == head_dim;
5967        // The rule `loader.rs::refined_qk_norm` applies, transcribed.
5968        let loader_style = |len: usize| -> Option<QkNormStyle> {
5969            if len == head_dim {
5970                Some(QkNormStyle::PerHead)
5971            } else if len == n_heads * head_dim {
5972                Some(QkNormStyle::WholeVector)
5973            } else {
5974                None
5975            }
5976        };
5977
5978        for len in [head_dim, n_heads * head_dim] {
5979            let style = loader_style(len).expect("both widths load");
5980            assert_eq!(
5981                metal_says_per_head(len),
5982                style == QkNormStyle::PerHead,
5983                "length {len} loads as {style:?} but Metal would infer the other style"
5984            );
5985        }
5986
5987        // A width neither side handles must be refused at load rather
5988        // than reaching a kernel that would pick a branch anyway.
5989        assert!(
5990            loader_style(head_dim + 1).is_none(),
5991            "an unrecognised norm width must be a load error, not a coin flip"
5992        );
5993
5994        // The one ambiguous case, and it is harmless: with a single
5995        // head the two widths coincide, so both rules take their PerHead
5996        // branch and per-head RMS over one head IS whole-vector RMS.
5997        let single_head = |len: usize| len == head_dim;
5998        assert!(single_head(head_dim));
5999        assert_eq!(
6000            loader_style(head_dim),
6001            Some(QkNormStyle::PerHead),
6002            "with n_heads == 1 both widths are head_dim, and both sides must land \
6003             on the same branch rather than one falling through"
6004        );
6005    }
6006
6007    #[test]
6008    fn the_batched_path_applies_attention_scale_like_the_contiguous_one() {
6009        let vocab = 8;
6010        let tokens = [1usize, 3, 5, 2, 7];
6011        let scaled = || {
6012            let mut cfg = tiny_test_config();
6013            // Far from the kernel's own 1/sqrt(head_dim) on purpose:
6014            // at this model's scale a scalar near 1 moves the logits by
6015            // ~2e-4, which is below the noise a tolerance test can see.
6016            cfg.attention_scale = Some(8.0);
6017            cfg
6018        };
6019        let fresh_caches = |d: &Decoder| -> Vec<KvCache> {
6020            (0..d.layers.len())
6021                .map(|_| KvCache::new(d.config.n_kv_heads, d.config.head_dim))
6022                .collect()
6023        };
6024
6025        // Same seed -> identical weights, so the only difference between
6026        // these three decoders is the config field under test.
6027        let seq_decoder = Decoder::new_random_small(scaled(), 2, vocab);
6028        let mut seq_caches = fresh_caches(&seq_decoder);
6029        let sequential: Vec<Vec<f32>> = tokens
6030            .iter()
6031            .enumerate()
6032            .map(|(pos, &t)| seq_decoder.forward_token(t, pos, &mut seq_caches))
6033            .collect();
6034
6035        let batch_decoder = Decoder::new_random_small(scaled(), 2, vocab);
6036        let mut batch_caches = fresh_caches(&batch_decoder);
6037        let batched = batch_decoder.forward_batch(&tokens, 0, &mut batch_caches);
6038
6039        let plain_decoder = Decoder::new_random_small(tiny_test_config(), 2, vocab);
6040        let mut plain_caches = fresh_caches(&plain_decoder);
6041        let unscaled = plain_decoder.forward_batch(&tokens, 0, &mut plain_caches);
6042        assert!(
6043            batched
6044                .iter()
6045                .zip(unscaled.iter())
6046                .any(|(s, u)| s.iter().zip(u.iter()).any(|(a, b)| (a - b).abs() > 1e-3)),
6047            "attention_scale must change the batched answer, or this test cannot fail"
6048        );
6049
6050        assert_eq!(batched.len(), sequential.len());
6051        for (pos, (seq_logits, batch_logits)) in sequential.iter().zip(batched.iter()).enumerate() {
6052            assert_eq!(seq_logits.len(), batch_logits.len());
6053            for (i, (s, b)) in seq_logits.iter().zip(batch_logits.iter()).enumerate() {
6054                assert!(
6055                    (s - b).abs() < 1e-5,
6056                    "position {pos}, logit {i}: sequential={s} batched={b}"
6057                );
6058            }
6059        }
6060    }
6061
6062    /// [`the_batched_path_applies_attention_scale_like_the_contiguous_one`]
6063    /// for the fourth host body.
6064    ///
6065    /// `forward_multi_seq_kv` did not apply `attention_scale` either, so
6066    /// a served request answered differently the moment it was batched
6067    /// with another request -- the same weights, the same position, a
6068    /// different temperature, decided by how busy the server was.
6069    #[test]
6070    fn the_multi_seq_path_applies_attention_scale_like_the_contiguous_one() {
6071        let vocab = 8;
6072        let histories: [&[usize]; 3] = [&[1, 3, 5], &[2, 7], &[4, 4, 4, 6]];
6073        let next = [6usize, 1, 2];
6074        let n_layers = 2;
6075        let scaled = || {
6076            let mut cfg = tiny_test_config();
6077            // See the batched twin: a scalar near 1 does not move this
6078            // model's logits far enough for a tolerance to see it.
6079            cfg.attention_scale = Some(8.0);
6080            cfg
6081        };
6082
6083        // Builds every sequence's history with `forward_token`, then
6084        // takes the next step either per sequence or as one batch.
6085        let run = |cfg: ModelConfig, batched: bool| -> Vec<Vec<f32>> {
6086            let decoder = Decoder::new_random_small(cfg, n_layers, vocab);
6087            let mut per_seq: Vec<Vec<KvCache>> = histories
6088                .iter()
6089                .map(|h| {
6090                    let mut caches: Vec<KvCache> = (0..n_layers)
6091                        .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
6092                        .collect();
6093                    for (pos, &tok) in h.iter().enumerate() {
6094                        decoder.forward_token(tok, pos, &mut caches);
6095                    }
6096                    caches
6097                })
6098                .collect();
6099            let positions: Vec<usize> = histories.iter().map(|h| h.len()).collect();
6100            if batched {
6101                decoder.forward_multi_seq(&next, &positions, &mut per_seq)
6102            } else {
6103                next.iter()
6104                    .zip(positions.iter())
6105                    .zip(per_seq.iter_mut())
6106                    .map(|((&tok, &pos), caches)| decoder.forward_token(tok, pos, caches))
6107                    .collect()
6108            }
6109        };
6110
6111        let want = run(scaled(), false);
6112        let got = run(scaled(), true);
6113        let unscaled = run(tiny_test_config(), true);
6114
6115        assert!(
6116            got.iter()
6117                .zip(unscaled.iter())
6118                .any(|(g, u)| g.iter().zip(u.iter()).any(|(a, b)| (a - b).abs() > 1e-3)),
6119            "attention_scale must change the multi-seq answer, or this test cannot fail"
6120        );
6121
6122        assert_eq!(want.len(), got.len());
6123        for (s, (a, b)) in want.iter().zip(got.iter()).enumerate() {
6124            assert_eq!(a.len(), b.len(), "sequence {s}: logit count");
6125            for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() {
6126                assert!(
6127                    (x - y).abs() < 1e-5,
6128                    "sequence {s}, logit {i}: independent={x} batched={y}"
6129                );
6130            }
6131        }
6132    }
6133
6134    /// The predicate that decides whether a MoE layer may be routed by
6135    /// the GPU must admit ONLY the routing the GPU actually computes.
6136    ///
6137    /// Every Metal MoE path -- `launch_moe_decode_stack`,
6138    /// `launch_moe_decode_layer_fused`, `launch_moe_prefill_q4_0` and
6139    /// the fused prefill stack -- routes with a plain top-k softmax over
6140    /// the raw router logits. `Decoder::route_for_layer` has three more
6141    /// arms: grouped routing, a per-expert router bias, and
6142    /// `expert_weights_scale`. The audit found those four call sites
6143    /// disagreeing about which of the three to refuse -- prefill checked
6144    /// all three, the fused decode layer checked two, the whole-stack
6145    /// decode checked none -- so a Softmax-gated MoE checkpoint carrying
6146    /// a router bias would have routed to different experts on Metal
6147    /// than on CPU, with no error.
6148    ///
6149    /// This asserts the invariant directly rather than the predicate's
6150    /// spelling: whenever it says yes, plain `route_top_k` and
6151    /// `route_for_layer` must return the same decision; and each of the
6152    /// three features on its own must make it say no.
6153    #[test]
6154    fn the_gpu_router_predicate_admits_only_routing_it_reproduces() {
6155        // `tiny_test_config` is GLM-shaped and so gates with sigmoid;
6156        // the GPU router implements softmax, so start from the case the
6157        // predicate is supposed to ADMIT.
6158        let mut base = tiny_test_config();
6159        base.moe.gating = ferrox_moe::GatingFunction::Softmax;
6160        let decoder = Decoder::new_random_small(base.clone(), 2, 8);
6161        let plain_layer = &decoder.layers[0];
6162        let n_experts = base.moe.n_experts;
6163        // Chosen so each feature really bites: the top two experts sit
6164        // in DIFFERENT groups of two (so grouped routing must reorder
6165        // them), and the runners-up are close enough behind that a
6166        // per-expert bias flips the order.
6167        assert_eq!(n_experts, 6, "the logits below are written for six experts");
6168        let logits: Vec<f32> = vec![0.90, 0.10, 0.20, 0.85, 0.30, 0.05];
6169
6170        let agrees = |layer: &LayerWeights, cfg: &ModelConfig| -> bool {
6171            let host = Decoder::route_for_layer(layer, &logits, cfg);
6172            let gpu = route_top_k(
6173                &logits,
6174                cfg.moe.n_experts_active,
6175                cfg.moe.gating,
6176                cfg.moe.norm_topk_prob,
6177            );
6178            host.expert_ids == gpu.expert_ids
6179                && host.weights.len() == gpu.weights.len()
6180                && host
6181                    .weights
6182                    .iter()
6183                    .zip(gpu.weights.iter())
6184                    .all(|(a, b)| a.to_bits() == b.to_bits())
6185        };
6186
6187        // The admitted case: the predicate says yes, and the two
6188        // routers really do agree.
6189        assert!(
6190            Decoder::gpu_router_matches_host_routing(plain_layer, &base),
6191            "a plain softmax MoE layer must stay eligible, or this test proves nothing"
6192        );
6193        assert!(agrees(plain_layer, &base));
6194
6195        // A per-expert router bias.
6196        let mut biased_decoder = Decoder::new_random_small(base.clone(), 2, 8);
6197        biased_decoder.layers[0].moe.exp_probs_bias =
6198            Some((0..n_experts).map(|e| 0.9 - 0.4 * e as f32).collect());
6199        let biased_layer = &biased_decoder.layers[0];
6200        assert!(
6201            !Decoder::gpu_router_matches_host_routing(biased_layer, &base),
6202            "exp_probs_bias must make the layer ineligible for the GPU router"
6203        );
6204        assert!(
6205            !agrees(biased_layer, &base),
6206            "the bias must actually change the routing, or the check above is vacuous"
6207        );
6208
6209        // `expert_weights_scale`.
6210        let mut scaled = base.clone();
6211        scaled.moe.expert_weights_scale = 2.5;
6212        assert!(
6213            !Decoder::gpu_router_matches_host_routing(plain_layer, &scaled),
6214            "expert_weights_scale must make the layer ineligible for the GPU router"
6215        );
6216        assert!(
6217            !agrees(plain_layer, &scaled),
6218            "the scale must actually change the routing, or the check above is vacuous"
6219        );
6220
6221        // Grouped routing.
6222        let mut grouped = base.clone();
6223        grouped.moe.expert_group_count = Some(3);
6224        grouped.moe.expert_group_used_count = Some(1);
6225        assert!(
6226            !Decoder::gpu_router_matches_host_routing(plain_layer, &grouped),
6227            "grouped routing must make the layer ineligible for the GPU router"
6228        );
6229        assert!(
6230            !agrees(plain_layer, &grouped),
6231            "the grouping must actually change the routing, or the check above is vacuous"
6232        );
6233
6234        // A non-softmax gate: the GPU kernel implements softmax only.
6235        let mut sigmoid = base;
6236        sigmoid.moe.gating = ferrox_moe::GatingFunction::Sigmoid;
6237        assert!(
6238            !Decoder::gpu_router_matches_host_routing(plain_layer, &sigmoid),
6239            "a non-softmax gate must make the layer ineligible for the GPU router"
6240        );
6241    }
6242
6243    /// OLMoE-style QK-norm (`attn_q_norm`/`attn_k_norm`, see `AttnWeights`'
6244    /// doc comment): with both set, `forward_batch` must still match
6245    /// sequential `forward_token` calls exactly -- the same consistency
6246    /// property `forward_batch_matches_sequential_forward_token_exactly`
6247    /// checks for the no-QK-norm path, now exercising the norm-applied
6248    /// per-row slicing (`q_batch.chunks_mut(q_width)`,
6249    /// `k_batch.chunks_mut(kv_width)`) instead of trusting it by
6250    /// inspection.
6251    #[test]
6252    fn forward_batch_matches_forward_token_with_qk_norm_present() {
6253        let cfg = tiny_test_config();
6254        let vocab = 8;
6255        let tokens = [1usize, 3, 5, 2, 7];
6256        let q_width = cfg.n_heads * cfg.head_dim;
6257        let kv_width = cfg.n_kv_heads * cfg.head_dim;
6258
6259        let mut decoder_a = Decoder::new_random_small(cfg.clone(), 2, vocab);
6260        for layer in &mut decoder_a.layers {
6261            layer.attn.q_norm = Some((0..q_width).map(|i| 1.0 + i as f32 * 0.1).collect());
6262            layer.attn.k_norm = Some((0..kv_width).map(|i| 0.5 + i as f32 * 0.05).collect());
6263        }
6264        let mut caches_a: Vec<KvCache> = (0..2)
6265            .map(|_| KvCache::new(decoder_a.config.n_kv_heads, decoder_a.config.head_dim))
6266            .collect();
6267        let sequential: Vec<Vec<f32>> = tokens
6268            .iter()
6269            .enumerate()
6270            .map(|(pos, &t)| decoder_a.forward_token(t, pos, &mut caches_a))
6271            .collect();
6272
6273        let mut decoder_b = Decoder::new_random_small(cfg, 2, vocab);
6274        for layer in &mut decoder_b.layers {
6275            layer.attn.q_norm = Some((0..q_width).map(|i| 1.0 + i as f32 * 0.1).collect());
6276            layer.attn.k_norm = Some((0..kv_width).map(|i| 0.5 + i as f32 * 0.05).collect());
6277        }
6278        let mut caches_b: Vec<KvCache> = (0..2)
6279            .map(|_| KvCache::new(decoder_b.config.n_kv_heads, decoder_b.config.head_dim))
6280            .collect();
6281        let batched = decoder_b.forward_batch(&tokens, 0, &mut caches_b);
6282
6283        assert_eq!(batched.len(), sequential.len());
6284        for (pos, (seq_logits, batch_logits)) in sequential.iter().zip(batched.iter()).enumerate() {
6285            for (i, (s, b)) in seq_logits.iter().zip(batch_logits.iter()).enumerate() {
6286                assert!(
6287                    (s - b).abs() < 1e-3,
6288                    "position {pos}, logit {i}: sequential={s} batched={b}"
6289                );
6290            }
6291        }
6292    }
6293
6294    /// QK-norm being present must actually change the output -- otherwise
6295    /// the `Some(...)` branches in `forward_token`/`forward_batch` could
6296    /// silently be dead code and this feature would ship unverified. Must
6297    /// decode at least 2 positions: at position 0 with a fresh cache,
6298    /// causal softmax has exactly one candidate (the token attending to
6299    /// itself) and always evaluates to weight 1.0 regardless of the Q*K
6300    /// dot product -- so the attention output there is Q/K-invariant by
6301    /// construction, and a single-position version of this test would
6302    /// pass even with `q_norm`/`k_norm` silently never applied.
6303    #[test]
6304    fn qk_norm_present_changes_output_versus_absent() {
6305        let cfg = tiny_test_config();
6306        let vocab = 8;
6307        let q_width = cfg.n_heads * cfg.head_dim;
6308        let kv_width = cfg.n_kv_heads * cfg.head_dim;
6309        let tokens = [3usize, 5];
6310
6311        let without_norm = Decoder::new_random_small(cfg.clone(), 1, vocab);
6312        let mut with_norm = Decoder::new_random_small(cfg, 1, vocab);
6313        for layer in &mut with_norm.layers {
6314            layer.attn.q_norm = Some(vec![2.0; q_width]);
6315            layer.attn.k_norm = Some(vec![2.0; kv_width]);
6316        }
6317
6318        let mut caches_a: Vec<KvCache> = (0..1)
6319            .map(|_| KvCache::new(without_norm.config.n_kv_heads, without_norm.config.head_dim))
6320            .collect();
6321        let mut caches_b: Vec<KvCache> = (0..1)
6322            .map(|_| KvCache::new(with_norm.config.n_kv_heads, with_norm.config.head_dim))
6323            .collect();
6324
6325        let mut out_a = Vec::new();
6326        let mut out_b = Vec::new();
6327        for (pos, &t) in tokens.iter().enumerate() {
6328            out_a = without_norm.forward_token(t, pos, &mut caches_a);
6329            out_b = with_norm.forward_token(t, pos, &mut caches_b);
6330        }
6331
6332        let differs = out_a
6333            .iter()
6334            .zip(out_b.iter())
6335            .any(|(a, b)| (a - b).abs() > 1e-4);
6336        assert!(
6337            differs,
6338            "QK-norm weights changed nothing -- forward_token likely isn't applying q_norm/k_norm"
6339        );
6340    }
6341
6342    /// Qwen2/Qwen2-MoE-family QKV attention bias (`AttnWeights::q_bias`/
6343    /// `k_bias`/`v_bias`): a real, previously-unhandled gap found by
6344    /// running ferrox's generic GGUF loader against a real downloaded
6345    /// Qwen1.5-MoE-A2.7B-Chat checkpoint, which produced fluent-but-wrong
6346    /// output because these real `attn_{q,k,v}.bias` tensors were
6347    /// silently never added anywhere. Same two real properties checked
6348    /// as the QK-norm tests above: (1) `forward_batch` must match
6349    /// sequential `forward_token` exactly with bias present (batched
6350    /// per-row broadcast must be correct, not just the single-token
6351    /// path), and (2) bias must actually change the output at position
6352    /// 0 or later (not silently dead code) -- checked at position 1
6353    /// specifically, since position 0's causal softmax has exactly one
6354    /// candidate and is Q/K-invariant regardless of any additive bias
6355    /// shifting Q/K, for the same reason the QK-norm test above needs
6356    /// >=2 positions.
6357    #[test]
6358    fn forward_batch_matches_forward_token_with_qkv_bias_present() {
6359        let cfg = tiny_test_config();
6360        let vocab = 8;
6361        let tokens = [1usize, 3, 5, 2, 7];
6362        let q_width = cfg.n_heads * cfg.head_dim;
6363        let kv_width = cfg.n_kv_heads * cfg.head_dim;
6364
6365        let mut decoder_a = Decoder::new_random_small(cfg.clone(), 2, vocab);
6366        for layer in &mut decoder_a.layers {
6367            layer.attn.q_bias = Some((0..q_width).map(|i| 0.3 + i as f32 * 0.02).collect());
6368            layer.attn.k_bias = Some((0..kv_width).map(|i| -0.2 + i as f32 * 0.03).collect());
6369            layer.attn.v_bias = Some((0..kv_width).map(|i| 0.1 - i as f32 * 0.01).collect());
6370        }
6371        let mut caches_a: Vec<KvCache> = (0..2)
6372            .map(|_| KvCache::new(decoder_a.config.n_kv_heads, decoder_a.config.head_dim))
6373            .collect();
6374        let sequential: Vec<Vec<f32>> = tokens
6375            .iter()
6376            .enumerate()
6377            .map(|(pos, &t)| decoder_a.forward_token(t, pos, &mut caches_a))
6378            .collect();
6379
6380        let mut decoder_b = Decoder::new_random_small(cfg, 2, vocab);
6381        for layer in &mut decoder_b.layers {
6382            layer.attn.q_bias = Some((0..q_width).map(|i| 0.3 + i as f32 * 0.02).collect());
6383            layer.attn.k_bias = Some((0..kv_width).map(|i| -0.2 + i as f32 * 0.03).collect());
6384            layer.attn.v_bias = Some((0..kv_width).map(|i| 0.1 - i as f32 * 0.01).collect());
6385        }
6386        let mut caches_b: Vec<KvCache> = (0..2)
6387            .map(|_| KvCache::new(decoder_b.config.n_kv_heads, decoder_b.config.head_dim))
6388            .collect();
6389        let batched = decoder_b.forward_batch(&tokens, 0, &mut caches_b);
6390
6391        assert_eq!(batched.len(), sequential.len());
6392        for (pos, (seq_logits, batch_logits)) in sequential.iter().zip(batched.iter()).enumerate() {
6393            for (i, (s, b)) in seq_logits.iter().zip(batch_logits.iter()).enumerate() {
6394                assert!(
6395                    (s - b).abs() < 1e-3,
6396                    "position {pos}, logit {i}: sequential={s} batched={b}"
6397                );
6398            }
6399        }
6400    }
6401
6402    #[test]
6403    fn qkv_bias_present_changes_output_versus_absent() {
6404        let cfg = tiny_test_config();
6405        let vocab = 8;
6406        let q_width = cfg.n_heads * cfg.head_dim;
6407        let kv_width = cfg.n_kv_heads * cfg.head_dim;
6408        let tokens = [3usize, 5];
6409
6410        let without_bias = Decoder::new_random_small(cfg.clone(), 1, vocab);
6411        let mut with_bias = Decoder::new_random_small(cfg, 1, vocab);
6412        for layer in &mut with_bias.layers {
6413            layer.attn.q_bias = Some(vec![0.5; q_width]);
6414            layer.attn.k_bias = Some(vec![0.5; kv_width]);
6415            layer.attn.v_bias = Some(vec![0.5; kv_width]);
6416        }
6417
6418        let mut caches_a: Vec<KvCache> = (0..1)
6419            .map(|_| KvCache::new(without_bias.config.n_kv_heads, without_bias.config.head_dim))
6420            .collect();
6421        let mut caches_b: Vec<KvCache> = (0..1)
6422            .map(|_| KvCache::new(with_bias.config.n_kv_heads, with_bias.config.head_dim))
6423            .collect();
6424
6425        let mut out_a = Vec::new();
6426        let mut out_b = Vec::new();
6427        for (pos, &t) in tokens.iter().enumerate() {
6428            out_a = without_bias.forward_token(t, pos, &mut caches_a);
6429            out_b = with_bias.forward_token(t, pos, &mut caches_b);
6430        }
6431
6432        let differs = out_a
6433            .iter()
6434            .zip(out_b.iter())
6435            .any(|(a, b)| (a - b).abs() > 1e-4);
6436        assert!(
6437            differs,
6438            "QKV bias changed nothing -- forward_token likely isn't applying q_bias/k_bias/v_bias"
6439        );
6440    }
6441
6442    #[test]
6443    fn forward_batch_and_forward_token_leave_kv_caches_in_the_same_state() {
6444        let cfg = tiny_test_config();
6445        let tokens = [2usize, 4, 6];
6446
6447        let decoder_a = Decoder::new_random_small(cfg.clone(), 2, 8);
6448        let mut caches_a: Vec<KvCache> = (0..2)
6449            .map(|_| KvCache::new(decoder_a.config.n_kv_heads, decoder_a.config.head_dim))
6450            .collect();
6451        for (pos, &t) in tokens.iter().enumerate() {
6452            decoder_a.forward_token(t, pos, &mut caches_a);
6453        }
6454
6455        let decoder_b = Decoder::new_random_small(cfg, 2, 8);
6456        let mut caches_b: Vec<KvCache> = (0..2)
6457            .map(|_| KvCache::new(decoder_b.config.n_kv_heads, decoder_b.config.head_dim))
6458            .collect();
6459        decoder_b.forward_batch(&tokens, 0, &mut caches_b);
6460
6461        for (ca, cb) in caches_a.iter().zip(caches_b.iter()) {
6462            assert_eq!(ca.positions(), cb.positions());
6463            assert_eq!(ca.k.len(), cb.k.len());
6464            for (a, b) in ca.k.iter().zip(cb.k.iter()) {
6465                assert!((a - b).abs() < 1e-4);
6466            }
6467        }
6468    }
6469
6470    /// Same architecture shape as `tiny_test_config` but genuinely
6471    /// dense (one expert, no shared experts) -- the shape every non-MoE
6472    /// model, and every DeepSeek-style leading dense layer, loads as.
6473    /// Exercises `Decoder::is_dense_layer`'s fast path.
6474    fn tiny_dense_test_config() -> ModelConfig {
6475        let mut cfg = tiny_test_config();
6476        cfg.moe.n_experts = 1;
6477        cfg.moe.n_experts_active = 1;
6478        cfg.moe.n_shared_experts = 0;
6479        cfg
6480    }
6481
6482    #[test]
6483    fn dense_layer_forward_pass_produces_finite_logits_of_correct_shape() {
6484        let vocab = 10;
6485        let decoder = Decoder::new_random_small(tiny_dense_test_config(), 2, vocab);
6486        let mut caches: Vec<KvCache> = (0..2)
6487            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
6488            .collect();
6489
6490        let logits = decoder.forward_token(3, 0, &mut caches);
6491        assert_eq!(logits.len(), vocab);
6492        assert!(
6493            logits.iter().all(|v| v.is_finite()),
6494            "logits must not contain NaN/Inf"
6495        );
6496    }
6497
6498    #[test]
6499    fn dense_layer_forward_batch_matches_sequential_forward_token_exactly() {
6500        let cfg = tiny_dense_test_config();
6501        let vocab = 8;
6502        let tokens = [1usize, 3, 5, 2, 7];
6503
6504        let decoder_a = Decoder::new_random_small(cfg.clone(), 2, vocab);
6505        let mut caches_a: Vec<KvCache> = (0..2)
6506            .map(|_| KvCache::new(decoder_a.config.n_kv_heads, decoder_a.config.head_dim))
6507            .collect();
6508        let sequential: Vec<Vec<f32>> = tokens
6509            .iter()
6510            .enumerate()
6511            .map(|(pos, &t)| decoder_a.forward_token(t, pos, &mut caches_a))
6512            .collect();
6513
6514        let decoder_b = Decoder::new_random_small(cfg, 2, vocab);
6515        let mut caches_b: Vec<KvCache> = (0..2)
6516            .map(|_| KvCache::new(decoder_b.config.n_kv_heads, decoder_b.config.head_dim))
6517            .collect();
6518        let batched = decoder_b.forward_batch(&tokens, 0, &mut caches_b);
6519
6520        assert_eq!(batched.len(), sequential.len());
6521        for (pos, (seq_logits, batch_logits)) in sequential.iter().zip(batched.iter()).enumerate() {
6522            for (i, (s, b)) in seq_logits.iter().zip(batch_logits.iter()).enumerate() {
6523                assert!(
6524                    (s - b).abs() < 1e-3,
6525                    "position {pos}, logit {i}: sequential={s} batched={b}"
6526                );
6527            }
6528        }
6529    }
6530
6531    #[test]
6532    fn dense_layer_fast_path_still_records_expert_zero_activations() {
6533        // The dense fast path bypasses `route_top_k` entirely, but
6534        // must still record an activation for expert 0 every step --
6535        // `MoeWeights::placement_plan` and hotness-based GPU placement
6536        // depend on this being real for every model shape, not just
6537        // genuinely-MoE ones.
6538        let decoder = Decoder::new_random_small(tiny_dense_test_config(), 1, 8);
6539        let mut caches: Vec<KvCache> = (0..1)
6540            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
6541            .collect();
6542
6543        decoder.forward_token(0, 0, &mut caches);
6544        decoder.forward_token(1, 1, &mut caches);
6545        decoder.forward_token(2, 2, &mut caches);
6546
6547        let count =
6548            decoder.layers[0].moe.activation_counts[0].load(std::sync::atomic::Ordering::Relaxed);
6549        assert_eq!(count, 3);
6550    }
6551
6552    #[test]
6553    fn forward_batch_with_empty_tokens_returns_empty() {
6554        let decoder = Decoder::new_random_small(tiny_test_config(), 2, 8);
6555        let mut caches: Vec<KvCache> = (0..2)
6556            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
6557            .collect();
6558        let out = decoder.forward_batch(&[], 0, &mut caches);
6559        assert!(out.is_empty());
6560    }
6561
6562    #[test]
6563    fn forward_batch_continues_correctly_after_prior_forward_token_calls() {
6564        // Realistic usage pattern: some tokens processed one at a time
6565        // (e.g. the first generated token), then a batch verifying
6566        // several draft tokens at once, continuing from the same
6567        // cache. The batch's positions must be numbered starting from
6568        // wherever the cache left off, not from zero.
6569        let cfg = tiny_test_config();
6570
6571        let decoder_a = Decoder::new_random_small(cfg.clone(), 2, 8);
6572        let mut caches_a: Vec<KvCache> = (0..2)
6573            .map(|_| KvCache::new(decoder_a.config.n_kv_heads, decoder_a.config.head_dim))
6574            .collect();
6575        decoder_a.forward_token(1, 0, &mut caches_a);
6576        decoder_a.forward_token(3, 1, &mut caches_a);
6577        let seq_next = decoder_a.forward_token(5, 2, &mut caches_a);
6578
6579        let decoder_b = Decoder::new_random_small(cfg, 2, 8);
6580        let mut caches_b: Vec<KvCache> = (0..2)
6581            .map(|_| KvCache::new(decoder_b.config.n_kv_heads, decoder_b.config.head_dim))
6582            .collect();
6583        decoder_b.forward_token(1, 0, &mut caches_b);
6584        let batch_next = decoder_b.forward_batch(&[3, 5], 1, &mut caches_b);
6585
6586        for (s, b) in seq_next.iter().zip(batch_next[1].iter()) {
6587            assert!((s - b).abs() < 1e-3, "sequential={s} batched={b}");
6588        }
6589    }
6590
6591    /// `PlacementPlan::from_budget` is
6592    /// real and tested in isolation, but only meaningful once it's fed
6593    /// genuinely observed per-expert activation counts rather than
6594    /// zeros. This proves the full loop: run real forward passes,
6595    /// confirm `MoeWeights::activation_counts` actually reflects what
6596    /// `route_top_k` selected, and confirm `placement_plan` prioritizes
6597    /// the expert that was genuinely hottest -- not just that the
6598    /// budget/size arithmetic works on synthetic inputs.
6599    #[test]
6600    fn placement_plan_reflects_real_observed_expert_activations() {
6601        let cfg = tiny_test_config(); // 6 experts, top-2 active/token
6602        let decoder = Decoder::new_random_small(cfg, 2, 16);
6603        let mut caches: Vec<KvCache> = (0..2)
6604            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
6605            .collect();
6606
6607        let n_calls = 20;
6608        for pos in 0..n_calls {
6609            decoder.forward_token(pos % 16, pos, &mut caches);
6610        }
6611
6612        let layer0 = &decoder.layers[0].moe;
6613        let counts: Vec<u64> = layer0
6614            .activation_counts
6615            .iter()
6616            .map(|c| c.load(std::sync::atomic::Ordering::Relaxed))
6617            .collect();
6618        let total: u64 = counts.iter().sum();
6619        assert_eq!(
6620            total,
6621            (n_calls as u64) * (decoder.config.moe.n_experts_active as u64),
6622            "total recorded activations must equal calls * experts_active_per_call"
6623        );
6624
6625        // Ties are realistic at this small a sample size; break them the
6626        // same way `PlacementPlan::from_budget` does (lowest index
6627        // wins), so this assertion can't spuriously fail on a tie that
6628        // `from_budget` resolves differently than a naive `max_by_key`
6629        // (which returns the *last* max element) would.
6630        let hottest_count = *counts.iter().max().unwrap();
6631        let hottest_idx = counts.iter().position(|&c| c == hottest_count).unwrap();
6632        assert!(hottest_count > 0);
6633
6634        // A per-expert resident size big enough for exactly one expert.
6635        let per_expert_bytes = layer0.expert_bytes(0);
6636        let plan = layer0.placement_plan(per_expert_bytes as u64);
6637
6638        assert_eq!(
6639            plan.placement_for(hottest_idx),
6640            ferrox_moe::ExpertPlacement::GpuDevice(0),
6641            "the genuinely hottest expert (index {hottest_idx}, {hottest_count} activations) \
6642             must be the one the plan places on GPU when only one expert fits the budget"
6643        );
6644    }
6645}
6646
6647/// The Metal side of Phi-3/Phi-4's RoPE: partial rotary and LongRoPE's
6648/// `attn_factor` used to be a refusal in `layer_supports_metal_attn`
6649/// and are now two uniforms on [`ferrox_metal::attn::MetalRope`].
6650#[cfg(all(test, feature = "metal"))]
6651mod metal_rope_tests {
6652    use super::*;
6653
6654    fn phi_like_config() -> ModelConfig {
6655        let mut cfg = crate::config::test_dense_fixture();
6656        cfg.head_dim = 128;
6657        cfg.rope_layout = crate::config::RopeLayout::Neox;
6658        cfg.rope_dim = Some(96);
6659        cfg.rope_attn_factor = 1.1902381;
6660        cfg
6661    }
6662
6663    /// Both values must reach the kernels, and they must be the same two
6664    /// the CPU path reads — otherwise the backends compute different
6665    /// attention for the same weights, which is the whole reason the
6666    /// model was refused Metal in the first place.
6667    #[test]
6668    fn metal_rope_carries_partial_rotary_and_mscale() {
6669        let decoder = Decoder::new_random_small(phi_like_config(), 1, 32);
6670        let rope = decoder.metal_rope();
6671        assert_eq!(rope.layout, ferrox_metal::attn::MetalRopeLayout::Neox);
6672        assert_eq!(rope.rot_dim, Some(96));
6673        assert_eq!(rope.attn_factor, 1.1902381);
6674    }
6675
6676    /// `rope.dimension_count == head_dim` is "the whole head rotates",
6677    /// which must reach the kernel as `None` rather than as a width —
6678    /// same graph, one code path.
6679    #[test]
6680    fn rot_dim_equal_to_head_dim_becomes_none() {
6681        let mut cfg = phi_like_config();
6682        cfg.rope_dim = Some(cfg.head_dim);
6683        let decoder = Decoder::new_random_small(cfg, 1, 32);
6684        assert_eq!(decoder.metal_rope().rot_dim, None);
6685    }
6686
6687    /// A non-unit `attn_factor` is no longer a reason to refuse Metal;
6688    /// an odd `n_rot` still is, because ggml's `ggml_rope_impl` asserts
6689    /// an even width and the split-half pairing is otherwise undefined
6690    /// for the last channel.
6691    #[test]
6692    fn odd_rot_dim_is_still_refused_but_mscale_is_not() {
6693        let supported = |cfg: ModelConfig| {
6694            let d = Decoder::new_random_small(cfg, 1, 32);
6695            d.layer_supports_metal_attn(&d.layers[0])
6696        };
6697
6698        // The control: with no rope oddity the fixture is admitted, so
6699        // the two assertions below are about the rope config and not
6700        // about the fixture failing some other check.
6701        let mut plain = phi_like_config();
6702        plain.rope_dim = None;
6703        plain.rope_attn_factor = 1.0;
6704        assert!(supported(plain), "fixture must be Metal-eligible to start");
6705
6706        assert!(
6707            supported(phi_like_config()),
6708            "partial rotary + a non-unit attn_factor must no longer refuse Metal"
6709        );
6710
6711        let mut odd = phi_like_config();
6712        odd.rope_dim = Some(95);
6713        assert!(!supported(odd), "odd n_rot must keep the model off Metal");
6714    }
6715
6716    /// A Gemma-3-4B-shaped config: `rope_scaling {linear, factor 8}`
6717    /// folded into the full-attention layers' divisors, nothing on the
6718    /// sliding ones, `sliding_window_pattern = 6` last-dense.
6719    fn gemma3_4b_shaped_config() -> ModelConfig {
6720        let mut cfg = crate::config::test_dense_fixture();
6721        cfg.head_dim = 8;
6722        cfg.rope_layout = crate::config::RopeLayout::Norm;
6723        cfg.rope_theta = 1_000_000.0;
6724        cfg.rope_theta_swa = Some(10_000.0);
6725        cfg.sliding_window = Some(4);
6726        cfg.swa_pattern = Some(6);
6727        cfg.rope_freqs = Some(crate::config::RopeFreqs {
6728            full: vec![8.0; 4],
6729            swa: Some(vec![1.0; 4]),
6730        });
6731        // One full period, so the run holds five sliding layers and one
6732        // full-attention layer -- Gemma-3's ratio, and the smallest one
6733        // that makes `rope_freqs_vary_by_layer` true.
6734        cfg.n_layers = 6;
6735        cfg
6736    }
6737
6738    /// What the fused Metal stacks are handed per layer must be BOTH
6739    /// halves of `ModelConfig::layer_rope`, layer by layer.
6740    ///
6741    /// `Decoder::metal_stack_needs_per_layer_rope_freqs` used to refuse
6742    /// exactly this config off the fused prefill/decode stacks, because
6743    /// those took one `freq_factors` slice for a whole run beside a
6744    /// per-layer theta -- half the answer varying and half not, which is
6745    /// this repo's dominant bug shape. `LayerRope` carries the pair, and
6746    /// this pins that the decoder fills it from the pair rather than
6747    /// re-deriving either half on its own.
6748    #[test]
6749    fn the_metal_stacks_are_handed_each_layer_s_own_rope_pair() {
6750        let cfg = gemma3_4b_shaped_config();
6751        assert!(
6752            cfg.rope_freqs_vary_by_layer(),
6753            "fixture must be the shape that used to be refused"
6754        );
6755        let decoder = Decoder::new_random_small(cfg, 6, 32);
6756
6757        for il in 0..decoder.layers.len() {
6758            let (theta, ff) = decoder.config.layer_rope(il);
6759            let sent = decoder.metal_layer_rope(il);
6760            assert_eq!(sent.theta, theta, "layer {il} base");
6761            assert_eq!(sent.freq_factors, ff, "layer {il} divisors");
6762        }
6763
6764        // Not vacuous: with `swa_pattern = 6` last-dense, layers 0..=4
6765        // slide and layer 5 does not, so the run really does hold two
6766        // different answers.
6767        let sliding = decoder.metal_layer_rope(0);
6768        let full = decoder.metal_layer_rope(5);
6769        assert_eq!(sliding.freq_factors, Some(&[1.0f32; 4][..]));
6770        assert_eq!(full.freq_factors, Some(&[8.0f32; 4][..]));
6771        assert_ne!(
6772            sliding, full,
6773            "a run of layers that all rope alike proves nothing here"
6774        );
6775    }
6776}