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