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