Skip to main content

cortiq_engine/
loader.rs

1//! Weight loader: CMF tensor directory → Pipeline.
2//!
3//! Storage rule: models WITH task masks are dequantized to f32 (masked
4//! execution needs f32 row access; skill files are small by design).
5//! Models without masks keep quantized matrices zero-copy from the mmap
6//! (`QTensor::Mapped`) — this is what lets a 15B file run in a few GB
7//! of RSS instead of 60 GB of f32.
8//!
9//! Layer kinds come from `arch.layer_types`: FullAttention loads
10//! `self_attn.*` (with auto-detected Qwen3.5 extras: per-head qk-norm by
11//! tensor presence, output gate by q_proj row count); LinearAttention
12//! loads the canonical core `vmf_attn.*` (folded at convert time).
13
14use crate::kv_cache::LayerKvCache;
15use crate::linear_core::{
16    GdnCfg, GdnWeights, ShortConvCfg, ShortConvWeights, VmfPhaseCfg, VmfPhaseWeights,
17};
18use crate::pipeline::{
19    AttnKind, DenseFfn, FfnKind, LayerWeights, MoeFfn, MtpModule, Pipeline, PipelineWeights,
20};
21use crate::qtensor::QTensor;
22use crate::sampler::SamplerConfig;
23use crate::tokenizer::Tokenizer;
24use cortiq_core::quant::dequant_tensor;
25use cortiq_core::{CmfError, CmfModel, LayerType, ModelArch};
26use std::sync::Arc;
27
28/// The refusal every generative entry point (`Pipeline::from_model*`, and
29/// through it run/chat/route/bench) gives a file carrying the DECISION
30/// feature bit. Such a file is served by the decision runtime instead.
31pub const DECISION_MODEL_REFUSAL: &str =
32    "this is a DECISION model; use `cortiq decide` or `cortiq serve`";
33
34const FLINT_NO_ROPE_LAYERS: [usize; 14] = [0, 1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 48];
35
36/// Flint's attention profile is an execution contract, not a converter hint.
37/// Reject headers produced before it was represented rather than silently
38/// decoding their learned sinks with RoPE/softmax semantics.
39fn validate_flint_profile(model: &CmfModel, arch: &ModelArch) -> Result<(), CmfError> {
40    if arch.arch_name != "flint" {
41        return Ok(());
42    }
43    if arch.num_layers != 49
44        || arch.hidden_size != 2048
45        || arch.num_attention_heads != 32
46        || arch.num_kv_heads != 4
47        || arch.head_dim != 128
48        || arch.vocab_size != 150_144
49    {
50        return Err(CmfError::Parse(
51            "Flint geometry is not the released RecursiveSI/flint profile".into(),
52        ));
53    }
54    if arch.sliding_window != Some(513) {
55        return Err(CmfError::Parse(
56            "Flint requires arch.sliding_window=513; run `cortiq repair-flint <model.cmf>` for legacy exports"
57                .into(),
58        ));
59    }
60    let expected_no_rope: Vec<bool> = (0..arch.num_layers)
61        .map(|li| FLINT_NO_ROPE_LAYERS.contains(&li))
62        .collect();
63    if arch.no_rope_layers.as_deref() != Some(expected_no_rope.as_slice()) {
64        return Err(CmfError::Parse(
65            "Flint requires its exact 14-layer no-RoPE schedule; run `cortiq repair-flint <model.cmf>` for legacy exports"
66                .into(),
67        ));
68    }
69    if !arch.attention_sink {
70        return Err(CmfError::Parse(
71            "Flint requires arch.attention_sink=true; run `cortiq repair-flint <model.cmf>` for legacy exports"
72                .into(),
73        ));
74    }
75    let Some(moe) = arch.moe.as_ref() else {
76        return Err(CmfError::Parse("Flint requires an MoE descriptor".into()));
77    };
78    if !(moe.router_sigmoid
79        && moe.norm_topk_prob
80        && moe.num_experts == 256
81        && moe.top_k == 6
82        && moe.moe_intermediate_size == 512
83        && moe.shared_expert_intermediate_size == Some(1024))
84    {
85        return Err(CmfError::Parse(
86            "Flint requires sigmoid top-6 normalized routing with its 256×512 + shared-1024 MoE profile"
87                .into(),
88        ));
89    }
90    for li in 0..arch.num_layers {
91        let name = format!("model.layers.{li}.self_attn.softmax_offset");
92        let Some(sink) = model.tensor(&name) else {
93            return Err(CmfError::MissingTensor(name));
94        };
95        if sink.shape.as_slice() != [arch.num_attention_heads] {
96            return Err(CmfError::Parse(format!(
97                "{name} has shape {:?}, expected [{}]",
98                sink.shape, arch.num_attention_heads
99            )));
100        }
101    }
102    Ok(())
103}
104
105/// Tensor source selector (spec §9): backbone, one skill's overlay, or
106/// a soft superposition of top-m skills (claim 14 working tensors).
107pub enum Overlay<'a> {
108    None,
109    One(&'a str),
110    /// (skill_id, weight); weights sum to 1 (softmax(−E/T) upstream).
111    Blend(&'a [(String, f32)]),
112}
113
114impl Overlay<'_> {
115    fn blend_touches(&self, model: &CmfModel, name: &str) -> bool {
116        match self {
117            Overlay::Blend(list) => list
118                .iter()
119                .any(|(sid, _)| model.tensor(&format!("skill.{sid}.{name}")).is_some()),
120            _ => false,
121        }
122    }
123}
124
125fn dequant_by_name(model: &CmfModel, name: &str) -> Result<Vec<f32>, String> {
126    let entry = model
127        .tensor(name)
128        .ok_or_else(|| format!("tensor '{name}' not found in CMF directory"))?;
129    let mut out = vec![0.0f32; entry.n_elems()];
130    dequant_tensor(entry, model.entry_bytes(entry), &mut out)?;
131    Ok(out)
132}
133
134/// Weighted working tensor (claim 14): Σ wᵢ·Tᵢ, where Tᵢ is the
135/// skill's replacement when present, else the backbone tensor.
136fn blend_f32(model: &CmfModel, name: &str, list: &[(String, f32)]) -> Result<Vec<f32>, String> {
137    let mut acc: Option<Vec<f32>> = None;
138    for (sid, w) in list {
139        let sname = format!("skill.{sid}.{name}");
140        let src = if model.tensor(&sname).is_some() {
141            &sname
142        } else {
143            name
144        };
145        let t = dequant_by_name(model, src)?;
146        match &mut acc {
147            None => {
148                let mut t = t;
149                for v in t.iter_mut() {
150                    *v *= w;
151                }
152                acc = Some(t);
153            }
154            Some(a) => {
155                for (av, tv) in a.iter_mut().zip(&t) {
156                    *av += w * tv;
157                }
158            }
159        }
160    }
161    acc.ok_or_else(|| "empty blend".into())
162}
163
164/// Dequantize a tensor fully into f32 (norms, masked models).
165pub(crate) fn load_f32(model: &CmfModel, name: &str, ov: &Overlay) -> Result<Vec<f32>, String> {
166    if ov.blend_touches(model, name) {
167        if let Overlay::Blend(list) = ov {
168            return blend_f32(model, name, list);
169        }
170    }
171    let skill = match ov {
172        Overlay::One(s) => Some(*s),
173        _ => None,
174    };
175    let entry = model
176        .resolve_tensor(name, skill)
177        .ok_or_else(|| format!("tensor '{name}' not found in CMF directory"))?;
178    let bytes = model.entry_bytes(entry);
179    let mut out = vec![0.0f32; entry.n_elems()];
180    dequant_tensor(entry, bytes, &mut out)?;
181    Ok(out)
182}
183
184/// Build one layer's FFN (dense or MoE) under a given overlay. Shared
185/// by the static loader AND dynamic per-token skill switching
186/// (`Pipeline::set_active_skill`): switching skills = rebuilding the
187/// FFN of the touched layers, cheap because Mapped tensors are just
188/// re-resolved mmap pointers (no dequant, no copy).
189pub(crate) fn build_layer_ffn(
190    model: &Arc<CmfModel>,
191    arch: &ModelArch,
192    li: usize,
193    force_f32: bool,
194    ov: &Overlay,
195) -> Result<FfnKind, CmfError> {
196    build_ffn_at(model, arch, &format!("model.layers.{li}."), force_f32, ov)
197}
198
199/// The FFN under an arbitrary prefix. Split out of `build_layer_ffn` so the
200/// MTP block can reuse it: Qwen3.6's MTP layer carries a full MoE mlp
201/// (router + 256 experts + shared expert), not the dense one the head was
202/// first written against.
203pub(crate) fn build_ffn_at(
204    model: &Arc<CmfModel>,
205    arch: &ModelArch,
206    prefix: &str,
207    force_f32: bool,
208    ov: &Overlay,
209) -> Result<FfnKind, CmfError> {
210    let prefix = prefix.to_string();
211    let load_dense = |p: &str| -> Result<DenseFfn, CmfError> {
212        let gate_proj = load_matrix(model, &format!("{p}gate_proj.weight"), force_f32, ov)?;
213        let up_proj = load_matrix(model, &format!("{p}up_proj.weight"), force_f32, ov)?;
214        let down_proj = load_matrix(model, &format!("{p}down_proj.weight"), force_f32, ov)?;
215        // FFN triple invariant (holds for dense and each MoE expert;
216        // enforced loudly so a malformed defrag/repack — spec §11 — fails
217        // at load instead of silently mis-computing). inter' is per-layer.
218        let inter = gate_proj.rows();
219        if up_proj.rows() != inter || down_proj.cols() != inter {
220            return Err(CmfError::Parse(format!(
221                "{p}: FFN dims disagree (gate.rows={inter}, up.rows={}, \
222                 down.cols={}); all three must equal inter'",
223                up_proj.rows(),
224                down_proj.cols()
225            )));
226        }
227        // a latent MoE's routed experts (Edge0) work in the latent width
228        let latent = arch.qwen4_exp.as_ref().and_then(|q| q.latent_dim);
229        let latent_expert = p.contains(".mlp.experts.") && latent == Some(down_proj.rows()) && gate_proj.cols() == down_proj.rows();
230        if down_proj.rows() != arch.hidden_size && !latent_expert {
231            return Err(CmfError::Parse(format!(
232                "{p}: down_proj.rows={} != hidden_size={}",
233                down_proj.rows(),
234                arch.hidden_size
235            )));
236        }
237        // The transposed down, when the file carries one: the per-token
238        // sparse path needs a neuron's down weights contiguous.
239        let dt_name = format!("{p}down_proj.t.weight");
240        let down_t = match model.tensor(&dt_name) {
241            Some(_) => Some(load_matrix(model, &dt_name, force_f32, ov)?),
242            None => None,
243        };
244        if let Some(t) = &down_t
245            && (t.rows() != inter || t.cols() != arch.hidden_size)
246        {
247            return Err(CmfError::Parse(format!(
248                "{p}down_proj.t: [{}, {}] != [{inter}, {}]",
249                t.rows(),
250                t.cols(),
251                arch.hidden_size
252            )));
253        }
254        // Task tubes (`…gate_proj.tube1.weight`, …): the neurons only
255        // some tasks compute, each stored as its own triple so every
256        // kernel runs it unchanged and an inactive tube's bytes are
257        // never touched. Numbering is dense from 1; the first gap ends
258        // the tube list.
259        let mut segs = Vec::new();
260        let mut start = inter;
261        for k in 1.. {
262            let gn = format!("{p}gate_proj.tube{k}.weight");
263            if model.tensor(&gn).is_none() {
264                break;
265            }
266            let gate = load_matrix(model, &gn, force_f32, ov)?;
267            let up = load_matrix(model, &format!("{p}up_proj.tube{k}.weight"), force_f32, ov)?;
268            let down = load_matrix(
269                model,
270                &format!("{p}down_proj.tube{k}.weight"),
271                force_f32,
272                ov,
273            )?;
274            let width = gate.rows();
275            if up.rows() != width || down.cols() != width || down.rows() != arch.hidden_size {
276                return Err(CmfError::Parse(format!(
277                    "{p}tube{k}: dims disagree (gate.rows={width}, up.rows={}, \
278                     down=[{}, {}], hidden={})",
279                    up.rows(),
280                    down.rows(),
281                    down.cols(),
282                    arch.hidden_size
283                )));
284            }
285            segs.push(crate::pipeline::FfnSeg {
286                gate,
287                up,
288                down,
289                start,
290                width,
291            });
292            start += width;
293        }
294        Ok(DenseFfn {
295            gate_proj,
296            up_proj,
297            down_proj,
298            act: crate::pipeline::Act::from_arch_full(arch),
299            down_t,
300            segs,
301        })
302    };
303    let router_name = format!("{prefix}mlp.gate.weight");
304    // Cortiq Embryo: resonance-routed experts carry NO gate tensor — the
305    // MoE is keyed on the first expert + the arch flag (a grown genome
306    // appends `mlp.experts.{E}.*` records without rewriting anything).
307    let resonance_moe = model.tensor(&router_name).is_none()
308        && arch.moe.as_ref().is_some_and(|m| m.router_resonance)
309        && model
310            .tensor(&format!("{prefix}mlp.experts.0.gate_proj.weight"))
311            .is_some();
312    if model.tensor(&router_name).is_none() && !resonance_moe {
313        return Ok(FfnKind::Dense(load_dense(&format!("{prefix}mlp."))?));
314    }
315    let cfg = arch.moe.as_ref().ok_or_else(|| {
316        CmfError::Parse(format!(
317            "{router_name} present but header has no arch.moe block"
318        ))
319    })?;
320    // Experts enumerate by TENSOR PRESENCE up to the header count — a
321    // moe-defrag'd specialist keeps a per-layer contiguous prefix of
322    // renumbered experts (fewer than arch.moe.num_experts), with the
323    // router rows sliced to match.
324    let mut experts = Vec::new();
325    for e in 0..cfg.num_experts {
326        if model
327            .tensor(&format!("{prefix}mlp.experts.{e}.gate_proj.weight"))
328            .is_none()
329        {
330            break;
331        }
332        experts.push(load_dense(&format!("{prefix}mlp.experts.{e}."))?);
333    }
334    if experts.is_empty() {
335        return Err(CmfError::Parse(format!(
336            "{prefix}: router present but no expert tensors"
337        )));
338    }
339    // Growth records (`kind = "expert_append"`, spec §9.5.1): the experts
340    // the records append to THIS layer, mounted behind the trunk experts
341    // in header order. `arch.moe.num_experts` stays E0; the trunk count
342    // is `e0`, the tail `experts[e0..]` is described by `grown`.
343    let e0 = experts.len();
344    let grown_loads = if resonance_moe {
345        mount_growth(model, &prefix, ov, &load_dense)?
346    } else {
347        Vec::new()
348    };
349    let mut grown_desc: Vec<(Vec<f32>, Vec<f32>, f32, f32)> = Vec::new();
350    let mut grown: Vec<crate::pipeline::GrownExpert> = Vec::new();
351    for g in grown_loads {
352        experts.push(g.ffn);
353        grown_desc.push((g.mu, g.u, g.bias, g.shell));
354        grown.push(g.meta);
355    }
356    let shared = if model
357        .tensor(&format!("{prefix}mlp.shared_expert.gate_proj.weight"))
358        .is_some()
359    {
360        let gate_name = format!("{prefix}mlp.shared_expert_gate.weight");
361        Some((
362            load_dense(&format!("{prefix}mlp.shared_expert."))?,
363            if model.tensor(&gate_name).is_some() {
364                Some(load_matrix(model, &gate_name, force_f32, ov)?)
365            } else {
366                None
367            },
368        ))
369    } else {
370        None
371    };
372    // LFM2-MoE selection bias (`mlp.expert_bias`): present iff the model
373    // routes with a bias; loaded by tensor presence.
374    let bias_name = format!("{prefix}mlp.expert_bias");
375    let expert_bias = if model.tensor(&bias_name).is_some() {
376        Some(load_f32(model, &bias_name, ov).map_err(CmfError::Parse)?)
377    } else {
378        None
379    };
380    // CMF_MOE_TOPK=N (opt-in): route to fewer experts than the header
381    // asks. MoE decode is memory-bound — every selected expert streams
382    // its three matrices per token — so halving k halves that traffic;
383    // the renormalized top-k keeps the mixture a proper average.
384    // Quality is the experiment — measure ppl before trusting.
385    let top_k = std::env::var("CMF_MOE_TOPK")
386        .ok()
387        .and_then(|v| v.parse::<usize>().ok())
388        .filter(|&k| k >= 1 && k <= cfg.top_k)
389        .inspect(|k| tracing::info!("MoE top_k override: {} (header {})", k, cfg.top_k))
390        .unwrap_or(cfg.top_k);
391    // CMF_MOE_TAU=0.x (opt-in): adaptive routing — see MoeFfn::route_tau.
392    let route_tau = std::env::var("CMF_MOE_TAU")
393        .ok()
394        .and_then(|v| v.parse::<f32>().ok())
395        .filter(|&t| t > 0.0 && t < 1.0)
396        .inspect(|t| tracing::info!("MoE adaptive routing: tau {t}"));
397    let mask = moe_task_mask(model, &prefix, experts.len());
398    let router = if resonance_moe {
399        // never read (selection is by descriptors); zero placeholder in RAM
400        QTensor::from_f32(
401            vec![0.0; experts.len() * arch.hidden_size],
402            experts.len(),
403            arch.hidden_size,
404        )
405    } else {
406        load_matrix(model, &router_name, force_f32, ov)?
407    };
408    if router.rows() != experts.len() {
409        return Err(CmfError::Parse(format!(
410            "{router_name}: {} rows != {} experts",
411            router.rows(),
412            experts.len()
413        )));
414    }
415    let top_k = top_k.min(experts.len());
416    // Gemma-4: per-expert weight scale after the top-k renorm; its
417    // presence also marks the scale-less-rms router input (the folded
418    // router gain — see the converter).
419    let pes_name = format!("{prefix}mlp.per_expert_scale");
420    let per_expert_scale = if model.tensor(&pes_name).is_some() {
421        Some(load_f32(model, &pes_name, ov).map_err(CmfError::Parse)?)
422    } else {
423        None
424    };
425    let router_input_norm = per_expert_scale.is_some();
426    // Cortiq Embryo resonance descriptors: per-expert records
427    // `mlp.experts.{e}.desc.{mu,u,bias}` (append-only growth) or the legacy
428    // per-layer `mlp.desc.{mu,u,bias}` [E, ...]. Present → the router is a
429    // placeholder and selection is by reconstruction error.
430    let per_expert = model
431        .tensor(&format!("{prefix}mlp.experts.0.desc.mu"))
432        .is_some();
433    if !per_expert && !grown.is_empty() {
434        return Err(CmfError::Parse(format!(
435            "{prefix}: expert_append records need per-expert descriptors \
436             (mlp.experts.0.desc.mu); the stacked mlp.desc.* form cannot be grown"
437        )));
438    }
439    let resonance = if per_expert {
440        // Trunk descriptors first (E0 rows), then the grown rows behind
441        // them: `shell` is +inf on the trunk, the record's finite
442        // `desc.shell` on a grown expert.
443        let ne_d = e0;
444        let hidden = arch.hidden_size;
445        let mut mu = Vec::with_capacity(experts.len() * hidden);
446        let mut u = Vec::new();
447        let mut bias = Vec::with_capacity(experts.len());
448        let mut k = 0usize;
449        for e in 0..ne_d {
450            let m = load_f32(model, &format!("{prefix}mlp.experts.{e}.desc.mu"), ov)
451                .map_err(CmfError::Parse)?;
452            if m.len() != hidden {
453                return Err(CmfError::Parse(format!(
454                    "{prefix}mlp.experts.{e}.desc.mu: {} != {hidden}",
455                    m.len()
456                )));
457            }
458            mu.extend_from_slice(&m);
459            let un = format!("{prefix}mlp.experts.{e}.desc.u");
460            if model.tensor(&un).is_some() {
461                let ue = load_f32(model, &un, ov).map_err(CmfError::Parse)?;
462                let ke = ue.len() / hidden.max(1);
463                if e == 0 {
464                    k = ke;
465                }
466                if ke != k {
467                    return Err(CmfError::Parse(format!("{un}: rank {ke} != {k}")));
468                }
469                u.extend_from_slice(&ue);
470            }
471            let bn = format!("{prefix}mlp.experts.{e}.desc.bias");
472            bias.push(if model.tensor(&bn).is_some() {
473                load_f32(model, &bn, ov)
474                    .map_err(CmfError::Parse)?
475                    .first()
476                    .copied()
477                    .unwrap_or(0.0)
478            } else {
479                0.0
480            });
481        }
482        let mut shell = vec![f32::INFINITY; ne_d];
483        for (gm, gu, gb, gs) in &grown_desc {
484            if gm.len() != hidden || gu.len() != k * hidden {
485                return Err(CmfError::Parse(format!(
486                    "{prefix}: grown expert descriptor {}×{} != trunk {hidden}×{k}",
487                    gm.len(),
488                    gu.len() / hidden.max(1)
489                )));
490            }
491            mu.extend_from_slice(gm);
492            u.extend_from_slice(gu);
493            bias.push(*gb);
494            shell.push(*gs);
495        }
496        Some(crate::pipeline::Resonance {
497            mu,
498            u,
499            k,
500            bias,
501            shell,
502        })
503    } else if model.tensor(&format!("{prefix}mlp.desc.mu")).is_some() {
504        let mu = load_f32(model, &format!("{prefix}mlp.desc.mu"), ov).map_err(CmfError::Parse)?;
505        let ne_d = experts.len();
506        let hidden = arch.hidden_size;
507        if mu.len() != ne_d * hidden {
508            return Err(CmfError::Parse(format!(
509                "{prefix}mlp.desc.mu: {} != {ne_d}×{hidden}",
510                mu.len()
511            )));
512        }
513        let u_name = format!("{prefix}mlp.desc.u");
514        let (u, k) = if model.tensor(&u_name).is_some() {
515            let u = load_f32(model, &u_name, ov).map_err(CmfError::Parse)?;
516            let k = u.len() / (ne_d * hidden).max(1);
517            (u, k)
518        } else {
519            (Vec::new(), 0)
520        };
521        let b_name = format!("{prefix}mlp.desc.bias");
522        let bias = if model.tensor(&b_name).is_some() {
523            load_f32(model, &b_name, ov).map_err(CmfError::Parse)?
524        } else {
525            vec![0.0; ne_d]
526        };
527        Some(crate::pipeline::Resonance {
528            mu,
529            u,
530            k,
531            bias,
532            shell: Vec::new(),
533        })
534    } else {
535        None
536    };
537    let moe = MoeFfn {
538        grown,
539        router,
540        experts,
541        top_k,
542        route_tau,
543        norm_topk_prob: cfg.norm_topk_prob,
544        router_sigmoid: cfg.router_sigmoid,
545        // Source-specific selected-sigmoid renormalization law. Recursive
546        // Flint and MiniMax M3.1 both preserve their reference runtime's
547        // FP32 `sum + 1e-20`; the older LFM2/DeepSeek noaux contract keeps
548        // its established `+1e-6` floor.
549        sigmoid_denom_eps: match arch.arch_name.as_str() {
550            // GLM-5.3 routes with the same `sum + 1e-20` floor (`glm5_next`)
551            "flint" | "minimax_m3_vl" | "glm5_next" => 1e-20,
552            _ => 1e-6,
553        },
554        expert_bias,
555        routed_scaling: cfg.routed_scaling_factor.unwrap_or(1.0),
556        shared,
557        stats: std::cell::RefCell::new(Vec::new()),
558        act_sq: std::cell::RefCell::new(Vec::new()),
559        act_rows: std::cell::RefCell::new(Vec::new()),
560        mask,
561        per_expert_scale,
562        router_input_norm,
563        resonance,
564    };
565    // Gemma-4 dual-branch layer: a dense MLP coexists with the routed
566    // experts, each branch inside its own norm sandwich.
567    if model
568        .tensor(&format!("{prefix}mlp.gate_proj.weight"))
569        .is_some()
570    {
571        let norm = |suffix: &str| -> Result<Vec<f32>, CmfError> {
572            load_f32(model, &format!("{prefix}{suffix}.weight"), ov).map_err(CmfError::Parse)
573        };
574        return Ok(FfnKind::DenseMoe(Box::new(crate::pipeline::DenseMoeFfn {
575            dense: load_dense(&format!("{prefix}mlp."))?,
576            moe,
577            post_norm_1: norm("post_feedforward_layernorm_1")?,
578            pre_norm_2: norm("pre_feedforward_layernorm_2")?,
579            post_norm_2: norm("post_feedforward_layernorm_2")?,
580        })));
581    }
582    Ok(FfnKind::Moe(moe))
583}
584
585/// Check the optional, tensor-derived MTP width declaration against the
586/// dense block actually loaded from the directory.  An MTP draft is allowed
587/// to have an independently compacted FFN, so the trunk-wide
588/// `arch.intermediate_size` is intentionally not part of this comparison.
589///
590/// `ffn_intermediate_sizes` has no unambiguous meaning for a routed or
591/// segmented FFN.  Refuse such a combination rather than interpreting a
592/// dense-width declaration as an expert width (or a core-vs-tube width).
593fn validate_generic_mtp_ffn_width(
594    cfg: &cortiq_core::MtpConfig,
595    ffn: &FfnKind,
596) -> Result<(), CmfError> {
597    let Some(widths) = cfg.ffn_intermediate_sizes.as_deref() else {
598        return Ok(());
599    };
600    if widths.len() != cfg.num_layers {
601        return Err(CmfError::Parse(format!(
602            "MTP ffn_intermediate_sizes has {} entries, expected {} (one per draft layer)",
603            widths.len(),
604            cfg.num_layers
605        )));
606    }
607    if widths.iter().any(|&width| width == 0) {
608        return Err(CmfError::Parse(
609            "MTP ffn_intermediate_sizes must contain only positive widths".into(),
610        ));
611    }
612    let FfnKind::Dense(dense) = ffn else {
613        return Err(CmfError::Parse(
614            "MTP ffn_intermediate_sizes is valid only for a dense MTP FFN; omit it for routed MTP"
615                .into(),
616        ));
617    };
618    if !dense.segs.is_empty() {
619        return Err(CmfError::Parse(
620            "MTP ffn_intermediate_sizes requires an unsplit dense MTP FFN; omit it for tube-segmented MTP"
621                .into(),
622        ));
623    }
624    let actual = dense.gate_proj.rows();
625    let declared = widths[0];
626    if declared != actual {
627        return Err(CmfError::Parse(format!(
628            "MTP ffn_intermediate_sizes[0]={declared}, but model.mtp.layers.0.mlp.gate_proj.weight has {actual} rows"
629        )));
630    }
631    Ok(())
632}
633
634// ───────────────────────── growth records ─────────────────────────
635
636/// Which `expert_append` records the loader mounts (`CMF_GROWTH`).
637#[derive(Clone, Copy, PartialEq, Eq, Debug)]
638pub enum GrowthMode {
639    /// Records with `status == "active"` (the default).
640    Active,
641    /// Every record that is not retired (`CMF_GROWTH=all`: quarantine
642    /// and stale_regate too — the gate measurement of a fresh record).
643    All,
644    /// None (`CMF_GROWTH=off`: the plain genome, F0's forward).
645    Off,
646}
647
648impl GrowthMode {
649    pub fn label(self) -> &'static str {
650        match self {
651            Self::Active => "active",
652            Self::All => "all",
653            Self::Off => "off",
654        }
655    }
656
657    /// Does this mode mount a record of `status`?
658    pub fn admits(self, status: Option<&str>) -> bool {
659        match self {
660            Self::Off => false,
661            Self::Active => status == Some("active"),
662            Self::All => status != Some("retired"),
663        }
664    }
665}
666
667/// `CMF_GROWTH` = `active` (unset) | `all` | `off`.
668pub fn growth_mode() -> GrowthMode {
669    match std::env::var("CMF_GROWTH")
670        .ok()
671        .as_deref()
672        .map(|v| v.trim().to_ascii_lowercase())
673        .as_deref()
674    {
675        Some("off") | Some("0") | Some("none") => GrowthMode::Off,
676        Some("all") => GrowthMode::All,
677        _ => GrowthMode::Active,
678    }
679}
680
681/// The `expert_append` records the current [`growth_mode`] mounts, with
682/// their positions in `header.skills` (the chain rule of the format is
683/// evaluated at that position).
684pub fn mounted_growth_records(
685    header: &cortiq_core::CmfHeader,
686) -> Vec<(usize, &cortiq_core::SkillRecord)> {
687    let mode = growth_mode();
688    header
689        .skills
690        .iter()
691        .enumerate()
692        .filter(|(_, s)| {
693            s.kind.as_deref() == Some(cortiq_core::knowledge::skill_kind::EXPERT_APPEND)
694                && mode.admits(s.status.as_deref())
695        })
696        .collect()
697}
698
699/// One grown expert as the loader read it from a record.
700struct GrownLoad {
701    ffn: DenseFfn,
702    mu: Vec<f32>,
703    u: Vec<f32>,
704    bias: f32,
705    shell: f32,
706    meta: crate::pipeline::GrownExpert,
707}
708
709/// The layer index of a `model.layers.{l}.` prefix (None for the MTP
710/// block and other prefixes — no growth record addresses those).
711fn layer_of_prefix(prefix: &str) -> Option<usize> {
712    prefix
713        .strip_prefix("model.layers.")?
714        .strip_suffix('.')?
715        .parse()
716        .ok()
717}
718
719/// The grown experts of the mounted `expert_append` records that grow the
720/// layer `prefix` addresses, in header order, each read from the record's
721/// own tensors (`skill.{id}.model.layers.{l}.mlp.experts.{e}.*`, the
722/// names the format's layout plan gives for the record's position). One
723/// log line per mounted record and layer.
724fn mount_growth(
725    model: &Arc<CmfModel>,
726    prefix: &str,
727    ov: &Overlay,
728    load_dense: &dyn Fn(&str) -> Result<DenseFfn, CmfError>,
729) -> Result<Vec<GrownLoad>, CmfError> {
730    use cortiq_core::knowledge::expert_leaf;
731    let Some(layer) = layer_of_prefix(prefix) else {
732        return Ok(Vec::new());
733    };
734    let records = mounted_growth_records(&model.header);
735    let mut out = Vec::new();
736    for (at, rec) in records {
737        if !rec.layers.contains(&layer) {
738            continue;
739        }
740        let plan = cortiq_core::expert_append_layout(&model.header, &model.tensors, at, rec)
741            .map_err(|e| CmfError::Parse(format!("{prefix}: growth record '{}': {e}", rec.id)))?;
742        let mut by_expert: std::collections::BTreeMap<usize, Vec<&cortiq_core::ExpertTensorSpec>> =
743            Default::default();
744        for p in plan.iter().filter(|p| p.layer == layer) {
745            by_expert.entry(p.expert).or_default().push(p);
746        }
747        let first = out.len();
748        for (e, leaves) in &by_expert {
749            let name = |leaf: &str| -> Result<String, CmfError> {
750                leaves
751                    .iter()
752                    .find(|p| p.leaf == leaf)
753                    .map(|p| p.name.clone())
754                    .ok_or_else(|| {
755                        CmfError::Parse(format!(
756                            "{prefix}: growth record '{}' expert {e}: layout has no '{leaf}'",
757                            rec.id
758                        ))
759                    })
760            };
761            let ffn = load_dense(&format!("skill.{}.{prefix}mlp.experts.{e}.", rec.id))?;
762            let mu = load_f32(model, &name(expert_leaf::MU)?, ov).map_err(CmfError::Parse)?;
763            let u = if leaves.iter().any(|p| p.leaf == expert_leaf::U) {
764                load_f32(model, &name(expert_leaf::U)?, ov).map_err(CmfError::Parse)?
765            } else {
766                Vec::new()
767            };
768            let scalar = |leaf: &str| -> Result<f32, CmfError> {
769                load_f32(model, &name(leaf)?, ov)
770                    .map_err(CmfError::Parse)?
771                    .first()
772                    .copied()
773                    .ok_or_else(|| {
774                        CmfError::Parse(format!(
775                            "{prefix}: growth record '{}' expert {e}: empty '{leaf}'",
776                            rec.id
777                        ))
778                    })
779            };
780            let bias = scalar(expert_leaf::BIAS)?;
781            let shell = scalar(expert_leaf::SHELL)?;
782            if !shell.is_finite() {
783                return Err(CmfError::Parse(format!(
784                    "{prefix}: growth record '{}' expert {e}: desc.shell {shell} is not finite",
785                    rec.id
786                )));
787            }
788            out.push(GrownLoad {
789                ffn,
790                mu,
791                u,
792                bias,
793                shell,
794                meta: crate::pipeline::GrownExpert {
795                    record: rec.id.clone(),
796                    record_index: at,
797                    layer,
798                    expert: *e,
799                },
800            });
801        }
802        let declared: Vec<usize> = by_expert.keys().copied().collect();
803        tracing::info!(
804            "growth: layer {layer}: mounted expert_append '{}' (status {}) — {} experts, declared {:?}, shells {:?}",
805            rec.id,
806            rec.status.as_deref().unwrap_or("?"),
807            by_expert.len(),
808            declared,
809            out[first..].iter().map(|g| g.shell).collect::<Vec<_>>()
810        );
811    }
812    Ok(out)
813}
814
815/// Task mask over routed experts: DTG-MA applied to MoE.
816///
817/// This is deliberately diagnostic-only. A route-mass sidecar can look good
818/// on a short perplexity window and still collapse during a long
819/// autoregressive generation: excluding a low-mass expert changes the model,
820/// and the changed prefix changes every later route. Consequently a nearby
821/// `<model>.moe-mass.json` is NEVER adopted implicitly. `CMF_MOE_MASK=...`
822/// remains an explicit experiment and accepts both weighted and legacy count
823/// files; production acceleration must preserve the full router and treat a
824/// non-resident winner as an exact cold completion.
825pub(crate) fn moe_task_mask(
826    _model: &std::sync::Arc<CmfModel>,
827    prefix: &str,
828    ne: usize,
829) -> Option<Vec<bool>> {
830    use std::sync::OnceLock;
831    static CFG: OnceLock<Option<(std::collections::HashMap<usize, Vec<u64>>, f64)>> =
832        OnceLock::new();
833    let cfg = CFG.get_or_init(|| {
834        let path = std::path::PathBuf::from(std::env::var("CMF_MOE_MASK").ok()?);
835        let shown = path.display();
836        let text = std::fs::read_to_string(&path)
837            .map_err(|e| tracing::warn!("CMF_MOE_MASK: cannot read {shown}: {e}"))
838            .ok()?;
839        let map: std::collections::HashMap<String, Vec<u64>> = serde_json::from_str(&text)
840            .map_err(|e| tracing::warn!("CMF_MOE_MASK: bad JSON in {shown}: {e}"))
841            .ok()?;
842        // Weighted dumps store normalized route mass in fixed-point units
843        // and therefore have per-layer totals many orders above the old
844        // top-k vote counts. The magnitude distinguishes the two explicit
845        // diagnostic formats without relying on a special filename.
846        let weighted = map
847            .values()
848            .any(|row| row.iter().copied().sum::<u64>() >= 1_000_000);
849        let cover = std::env::var("CMF_MOE_MASK_COVER")
850            .ok()
851            .and_then(|v| v.parse::<f64>().ok())
852            .filter(|&c| c > 0.0 && c <= 1.0)
853            .unwrap_or(if weighted { 0.925 } else { 0.9 });
854        tracing::info!("MoE task mask: {shown}, cover {cover}");
855        Some((
856            map.into_iter()
857                .filter_map(|(k, v)| Some((k.parse::<usize>().ok()?, v)))
858                .collect(),
859            cover,
860        ))
861    });
862    let (stats, cover) = cfg.as_ref()?;
863    // The layer index rides in the tensor prefix ("model.layers.N.").
864    let li: usize = prefix
865        .split("layers.")
866        .nth(1)?
867        .split('.')
868        .next()?
869        .parse()
870        .ok()?;
871    let counts = stats.get(&li)?;
872    if counts.len() != ne {
873        tracing::warn!(
874            "CMF_MOE_MASK: layer {li} has {} counts, model has {ne} experts — skipped",
875            counts.len()
876        );
877        return None;
878    }
879    let total: u64 = counts.iter().sum();
880    if total == 0 {
881        return None;
882    }
883    let mut order: Vec<usize> = (0..ne).collect();
884    order.sort_unstable_by_key(|&e| std::cmp::Reverse(counts[e]));
885    let mut mask = vec![false; ne];
886    let mut acc = 0u64;
887    let mut kept = 0usize;
888    for &e in &order {
889        mask[e] = true;
890        acc += counts[e];
891        kept += 1;
892        if (acc as f64) >= cover * (total as f64) {
893            break;
894        }
895    }
896    tracing::info!(
897        "MoE task mask L{li}: {kept}/{ne} experts for {:.0}% mass",
898        cover * 100.0
899    );
900    Some(mask)
901}
902
903pub(crate) fn load_matrix(
904    model: &Arc<CmfModel>,
905    name: &str,
906    force_f32: bool,
907    ov: &Overlay,
908) -> Result<QTensor, CmfError> {
909    // Claim 14: a blended working tensor is materialized in f32 and
910    // held resident (the overlay-cache slot); single skills stay
911    // zero-copy pointers into the mmap.
912    if ov.blend_touches(model, name) {
913        if let Overlay::Blend(list) = ov {
914            let entry = model
915                .tensor(name)
916                .ok_or_else(|| CmfError::MissingTensor(name.to_string()))?;
917            let data =
918                blend_f32(model, name, list).map_err(|e| CmfError::Parse(format!("blend: {e}")))?;
919            return Ok(QTensor::from_f32(data, entry.shape[0], entry.shape[1]));
920        }
921    }
922    let skill = match ov {
923        Overlay::One(s) => Some(*s),
924        _ => None,
925    };
926    // Tensor-source indirection (spec §9): the skill's replacement is
927    // read in place of the backbone tensor — either/or, never a sum.
928    let name: &str = &match skill {
929        Some(sid) if model.tensor(&format!("skill.{sid}.{name}")).is_some() => {
930            format!("skill.{sid}.{name}")
931        }
932        _ => name.to_string(),
933    };
934    let err = |e: String| CmfError::Parse(format!("weight loading: {e}"));
935    if force_f32 {
936        let entry = model
937            .tensor(name)
938            .ok_or_else(|| CmfError::MissingTensor(name.to_string()))?;
939        if entry.shape.len() != 2 {
940            return Err(err(format!("'{name}' is not 2-D")));
941        }
942        let data = load_f32(model, name, &Overlay::None).map_err(err)?;
943        Ok(QTensor::from_f32(data, entry.shape[0], entry.shape[1]))
944    } else {
945        QTensor::from_model(model, name).map_err(err)
946    }
947}
948
949impl Pipeline {
950    /// Build a runnable pipeline from an opened CMF model.
951    pub fn from_model(
952        model: &Arc<CmfModel>,
953        sampler_config: SamplerConfig,
954    ) -> Result<Self, CmfError> {
955        Self::from_model_with_skill(model, sampler_config, None)
956    }
957
958    /// Build an encoder-only pipeline from an opened CMF model.
959    ///
960    /// Some component models (for example a text tower used by an image
961    /// pipeline) intentionally end at the final normalized hidden states and
962    /// therefore have no language-model head.  Keep that exception explicit:
963    /// regular [`Self::from_model`] continues to reject a non-tied model
964    /// without `lm_head.weight`, so a partially packed generative model can
965    /// never be mistaken for a runnable one.
966    ///
967    /// The returned pipeline is for [`Self::encode_hidden_states`] only.  Its
968    /// placeholder head is deliberately one row wide and must not be exposed
969    /// as a generative model.
970    pub fn from_encoder_model(
971        model: &Arc<CmfModel>,
972        sampler_config: SamplerConfig,
973    ) -> Result<Self, CmfError> {
974        Self::from_model_with_overlay(model, sampler_config, &Overlay::None, true)
975    }
976
977    /// Same, with a skill overlaid (spec §9): every layer tensor is
978    /// resolved through tensor-source indirection — the skill's
979    /// full-shape replacement is read in place of the backbone tensor.
980    /// No per-skill model is ever assembled: Mapped tensors are
981    /// pointers into the one shared mmap.
982    pub fn from_model_with_skill(
983        model: &Arc<CmfModel>,
984        sampler_config: SamplerConfig,
985        skill: Option<&str>,
986    ) -> Result<Self, CmfError> {
987        match skill {
988            Some(s) => {
989                Self::from_model_with_overlay(model, sampler_config, &Overlay::One(s), false)
990            }
991            None => Self::from_model_with_overlay(model, sampler_config, &Overlay::None, false),
992        }
993    }
994
995    /// Soft superposition (claim 14): working tensors accumulated from
996    /// the given (skill, weight) list — softmax(−E/T) upstream.
997    pub fn from_model_with_blend(
998        model: &Arc<CmfModel>,
999        sampler_config: SamplerConfig,
1000        blend: &[(String, f32)],
1001    ) -> Result<Self, CmfError> {
1002        Self::from_model_with_overlay(model, sampler_config, &Overlay::Blend(blend), false)
1003    }
1004
1005    fn skill_file_guard(model: &CmfModel) -> Result<(), CmfError> {
1006        // A decision profile (encoder + resonance skills) has no language
1007        // model in it at all; the generative pipeline must not try to
1008        // assemble one from its tensors.
1009        if model.required_features & cortiq_core::format::features::DECISION != 0 {
1010            return Err(CmfError::Parse(DECISION_MODEL_REFUSAL.into()));
1011        }
1012        // A standalone skill file carries a PARTIAL tensor set cut against
1013        // a base; running it would be half a network answering questions.
1014        if model.required_features & cortiq_core::format::features::SKILL_FILE != 0 {
1015            return Err(CmfError::Parse(
1016                "this file is a standalone SKILL, not a runnable model — attach it: \
1017                 cortiq skill apply <base.cmf> <this file> -o specialist.cmf"
1018                    .into(),
1019            ));
1020        }
1021        Ok(())
1022    }
1023
1024    fn from_model_with_overlay(
1025        model: &Arc<CmfModel>,
1026        sampler_config: SamplerConfig,
1027        ov: &Overlay,
1028        encoder_only: bool,
1029    ) -> Result<Self, CmfError> {
1030        // Refuse non-runnable files first, before any process-wide state
1031        // (the device cache directory, the graph verdict) is touched on
1032        // their behalf.
1033        Self::skill_file_guard(model)?;
1034        // Small device caches (probe verdicts, compiled pipelines) go
1035        // beside the model: it is a directory the caller demonstrably
1036        // writes to, which `std::env::temp_dir()` is not inside an
1037        // Android app sandbox.
1038        if let Some(dir) = model.path.parent() {
1039            crate::gpu::set_cache_dir(dir.to_path_buf());
1040        }
1041        // The token-graph refusal verdict lives in each pipeline
1042        // (`Pipeline::graph_refused`): a new pipeline starts clean and
1043        // loading one — a skill lane mid-traffic — never touches the
1044        // verdict of the others (R4/NF-2; this used to reset a
1045        // process-wide flag under running slots).
1046        let skill = match ov {
1047            Overlay::One(s) => Some(*s),
1048            _ => None,
1049        };
1050        if let Some(sid) = skill {
1051            let known = model.header.skills.iter().any(|s| s.id == sid)
1052                || model.skill_tensors(sid).next().is_some();
1053            if !known {
1054                return Err(CmfError::Parse(format!(
1055                    "skill '{sid}' not in this container (header.skills: {:?})",
1056                    model
1057                        .header
1058                        .skills
1059                        .iter()
1060                        .map(|s| &s.id)
1061                        .collect::<Vec<_>>()
1062                )));
1063            }
1064            tracing::info!(
1065                "skill '{sid}': {} replacement tensors overlaid",
1066                model.skill_tensors(sid).count()
1067            );
1068        }
1069        let arch = model.arch().clone();
1070        let err = |e: String| CmfError::Parse(format!("weight loading: {e}"));
1071        if let Some(heads) = &arch.attention_heads_per_layer {
1072            if heads.len() != arch.num_layers {
1073                return Err(CmfError::Parse(format!(
1074                    "arch.attention_heads_per_layer has {} entries, expected {}",
1075                    heads.len(),
1076                    arch.num_layers
1077                )));
1078            }
1079            if let Some((li, &nh)) = heads
1080                .iter()
1081                .enumerate()
1082                .find(|(_, nh)| **nh == 0 || **nh % arch.num_kv_heads != 0)
1083            {
1084                return Err(CmfError::Parse(format!(
1085                    "layer {li} has {nh} Q heads, which must be nonzero and divisible by {} KV heads",
1086                    arch.num_kv_heads
1087                )));
1088            }
1089        }
1090        if arch
1091            .layer_types
1092            .iter()
1093            .any(|t| matches!(t, LayerType::SlidingAttention))
1094            && arch.sliding_window.is_none()
1095        {
1096            return Err(CmfError::Parse(
1097                "model has SlidingAttention layers but no arch.sliding_window".into(),
1098            ));
1099        }
1100        validate_flint_profile(model, &arch)?;
1101
1102        // Masks × quantized mmap: only the HEAD-mask path needs f32
1103        // slices, so f32 is forced only when some mask actually restricts
1104        // attention heads. FFN masks run sparse directly on the quant
1105        // bytes (sparse_ffn_quant), and embed/lm_head are never masked.
1106        // The old condition forced f32 for ANY mask: a 4.17 B file whose
1107        // mask touched only the FFN dequantized to 16.7 GB at load and
1108        // ran the bare-f32 GEMMs — 0.0 tok/s on a laptop that swapped,
1109        // and a 30× crawl on a 48-core server. A mask with no head rows
1110        // costs nothing now.
1111        let heads_masked = model.masks.masks.iter().any(|m| {
1112            m.head_masks.iter().any(|row| {
1113                let mut bits = 0usize;
1114                for &b in row.iter() {
1115                    bits += b.count_ones() as usize;
1116                }
1117                !row.is_empty() && bits < arch.num_attention_heads
1118            })
1119        });
1120        let force_f32 = heads_masked; // attention only (head masks)
1121
1122        // ── Tokenizer: embedded → sidecar → byte-level fallback ──
1123        let mut tokenizer = if let Some(vocab_bytes) = &model.vocab {
1124            Tokenizer::from_bytes(vocab_bytes)
1125                .map_err(|e| CmfError::Parse(format!("embedded tokenizer: {e}")))?
1126        } else if let Some(g) = &model.header.genome {
1127            // A genome binds its tokenizer (the trunk hash covers the VOCAB
1128            // section): whatever tokenizer.json lies beside the file is not
1129            // part of it (NF-5; core refuses such a file at open as well).
1130            return Err(CmfError::Parse(format!(
1131                "genome '{}' carries no embedded tokenizer (VOCAB) — a sidecar tokenizer.json \
1132                 is not part of the genome; refusing",
1133                g.id
1134            )));
1135        } else {
1136            let sidecar = model.path.with_file_name("tokenizer.json");
1137            if sidecar.exists() {
1138                Tokenizer::from_file(&sidecar)
1139                    .map_err(|e| CmfError::Parse(format!("sidecar tokenizer: {e}")))?
1140            } else {
1141                tracing::warn!("no tokenizer in file or sidecar — using byte-level fallback");
1142                Tokenizer::byte_level()
1143            }
1144        };
1145        // Chat/eos bundle (spec §6.1): the FILE defines chat behavior.
1146        if let Some(tc) = &model.header.tokenizer_config {
1147            tokenizer.chat_template = tc.chat_template.clone();
1148            tokenizer.extra_eos.extend(tc.eos_token_ids.iter().copied());
1149            if tokenizer.bos_token_id.is_none() {
1150                tokenizer.bos_token_id = tc.bos_token_id;
1151            }
1152            tracing::info!(
1153                "chat bundle: template {} chars, {} stop ids",
1154                tc.chat_template.as_deref().map(str::len).unwrap_or(0),
1155                tc.eos_token_ids.len()
1156            );
1157        }
1158        // Gemma's contract requires <bos> at sequence start, but its
1159        // tokenizer.json post-processor does not add it (the chat
1160        // template does). Raw prompts need it too — word salad without.
1161        if arch.arch_name.to_lowercase().contains("gemma") && tokenizer.bos_token_id.is_some() {
1162            tokenizer.add_bos = true;
1163        }
1164
1165        // ── Top-level weights (never masked → always quantized) ──
1166        let embed_tokens = load_matrix(model, "model.embed_tokens.weight", false, ov)?;
1167        let final_norm = if arch.qwen4_exp.is_some() || arch.dory.is_some() {
1168            // qwen4_exp folds its four streams through a learned global
1169            // hyper mixer and has no conventional final RMSNorm; Dory's hidden
1170            // state is on the unit sphere and goes straight to the head.
1171            vec![0.0; arch.hidden_size]
1172        } else {
1173            load_f32(model, "model.norm.weight", ov).map_err(err)?
1174        };
1175        let lm_head = if model.tensor("lm_head.weight").is_some() {
1176            load_matrix(model, "lm_head.weight", false, ov)?
1177        } else if arch.tie_word_embeddings {
1178            // Tied: reuse the embedding matrix (re-open, cheap for Mapped).
1179            load_matrix(model, "model.embed_tokens.weight", false, ov)?
1180        } else if encoder_only {
1181            // `Pipeline` owns an LM-head slot for the generative APIs, but an
1182            // encoder component correctly has none.  Keep the inert stand-in
1183            // tiny: `encode_hidden_states` never reads it, and the public
1184            // generative constructors above still fail before reaching here.
1185            QTensor::from_f32(vec![0.0; arch.hidden_size], 1, arch.hidden_size)
1186        } else {
1187            return Err(CmfError::MissingTensor(
1188                "lm_head.weight (and tie_word_embeddings is false)".into(),
1189            ));
1190        };
1191
1192        // ── Linear-core geometry (required if any linear layer exists) ──
1193        let has_linear = arch
1194            .layer_types
1195            .iter()
1196            .any(|t| matches!(t, LayerType::LinearAttention));
1197        let mut vmf_cfg = None;
1198        let mut gdn_cfg = None;
1199        // `Some` means this file uses the versioned Phase-Delta operator;
1200        // the sorted indices are threaded into each layer's weights below.
1201        // Legacy kinds must not carry selector metadata: accepting and
1202        // ignoring it would recreate the original silent semantic break.
1203        let mut phase_delta_layers: Option<Vec<usize>> = None;
1204        if !has_linear
1205            && arch
1206                .linear_core
1207                .as_ref()
1208                .is_some_and(|lc| lc.phase_delta_layers.is_some())
1209        {
1210            return Err(CmfError::Parse(
1211                "phase_delta_layers is only valid with LinearAttention and \
1212                 vmf_phase_delta_v1"
1213                    .into(),
1214            ));
1215        }
1216        if has_linear {
1217            let lc = arch.linear_core.as_ref().ok_or_else(|| {
1218                CmfError::Parse(
1219                    "model has LinearAttention layers but no arch.linear_core — \
1220                     reconvert with the current converter"
1221                        .into(),
1222                )
1223            })?;
1224            let need = |v: Option<usize>, name: &str| {
1225                v.ok_or_else(|| CmfError::Parse(format!("linear core needs arch.{name}")))
1226            };
1227            match lc.kind.as_str() {
1228                "vmf_phase" => {
1229                    if lc.phase_delta_layers.is_some() {
1230                        return Err(CmfError::Parse(
1231                            "legacy vmf_phase cannot carry phase_delta_layers; use vmf_phase_delta_v1"
1232                                .into(),
1233                        ));
1234                    }
1235                    vmf_cfg = Some(VmfPhaseCfg {
1236                        num_heads: lc.num_heads,
1237                        nphase: need(lc.nphase, "linear_core.nphase")?,
1238                        value_head_dim: lc.value_head_dim,
1239                        hidden_size: arch.hidden_size,
1240                        // Phase-mass correction: default 0 (disabled); CMF_PHASE_MASS
1241                        // widens the phase kernel for folded-unhealed models.
1242                        phase_mass: std::env::var("CMF_PHASE_MASS")
1243                            .ok()
1244                            .and_then(|v| v.parse().ok())
1245                            .unwrap_or(0.0),
1246                    });
1247                }
1248                "vmf_phase_delta_v1" => {
1249                    let mut selected = lc.phase_delta_layers.clone().ok_or_else(|| {
1250                        CmfError::Parse(
1251                            "vmf_phase_delta_v1 requires a non-empty phase_delta_layers selector"
1252                                .into(),
1253                        )
1254                    })?;
1255                    if selected.is_empty() {
1256                        return Err(CmfError::Parse(
1257                            "vmf_phase_delta_v1 phase_delta_layers is empty".into(),
1258                        ));
1259                    }
1260                    if arch.layer_types.len() != arch.num_layers {
1261                        return Err(CmfError::Parse(format!(
1262                            "phase_delta layer schedule has {} entries, expected {}",
1263                            arch.layer_types.len(),
1264                            arch.num_layers
1265                        )));
1266                    }
1267                    selected.sort_unstable();
1268                    for pair in selected.windows(2) {
1269                        if pair[0] == pair[1] {
1270                            return Err(CmfError::Parse(format!(
1271                                "phase_delta_layers contains duplicate layer {}",
1272                                pair[0]
1273                            )));
1274                        }
1275                    }
1276                    for &li in &selected {
1277                        if li >= arch.num_layers {
1278                            return Err(CmfError::Parse(format!(
1279                                "phase_delta layer {li} out of range for {} layers",
1280                                arch.num_layers
1281                            )));
1282                        }
1283                        if !matches!(arch.layer_types[li], LayerType::LinearAttention) {
1284                            return Err(CmfError::Parse(format!(
1285                                "phase_delta layer {li} is not a LinearAttention layer"
1286                            )));
1287                        }
1288                    }
1289                    let nphase = need(lc.nphase, "linear_core.nphase")?;
1290                    if lc.num_heads == 0 || nphase == 0 || lc.value_head_dim == 0 {
1291                        return Err(CmfError::Parse(
1292                            "vmf_phase_delta_v1 requires positive heads, nphase, and value_head_dim"
1293                                .into(),
1294                        ));
1295                    }
1296                    phase_delta_layers = Some(selected);
1297                    vmf_cfg = Some(VmfPhaseCfg {
1298                        num_heads: lc.num_heads,
1299                        nphase,
1300                        value_head_dim: lc.value_head_dim,
1301                        hidden_size: arch.hidden_size,
1302                        // Phase-Delta's normalized features are a closed
1303                        // operator contract. CMF_PHASE_MASS is a legacy
1304                        // tuning knob and is intentionally ignored by the
1305                        // phase_delta branch in linear_core.
1306                        phase_mass: 0.0,
1307                    });
1308                }
1309                "gated_delta_net" => {
1310                    if lc.phase_delta_layers.is_some() {
1311                        return Err(CmfError::Parse(
1312                            "gated_delta_net cannot carry phase_delta_layers".into(),
1313                        ));
1314                    }
1315                    gdn_cfg = Some(GdnCfg {
1316                        num_v_heads: lc.num_heads,
1317                        num_k_heads: need(arch.linear_num_key_heads, "linear_num_key_heads")?,
1318                        key_head_dim: need(arch.linear_key_head_dim, "linear_key_head_dim")?,
1319                        value_head_dim: lc.value_head_dim,
1320                        conv_kernel: need(arch.linear_conv_kernel_dim, "linear_conv_kernel_dim")?,
1321                        hidden_size: arch.hidden_size,
1322                        rms_eps: arch.rms_norm_eps,
1323                        output_gate_sigmoid: false,
1324                    });
1325                }
1326                other => {
1327                    return Err(CmfError::Parse(format!(
1328                        "unknown linear core '{other}' (this runtime executes: \
1329                         gated_delta_net, vmf_phase, vmf_phase_delta_v1)"
1330                    )));
1331                }
1332            }
1333        }
1334
1335        // ── KDA geometry (Kimi Linear / Kimi-K3 delta-attention layers) ──
1336        let has_kda = arch.layer_types.iter().any(|t| matches!(t, LayerType::Kda));
1337        let kda_cfg = if has_kda {
1338            let need = |v: Option<usize>, name: &str| {
1339                v.ok_or_else(|| CmfError::Parse(format!("KDA core needs arch.{name}")))
1340            };
1341            Some(crate::linear_core::KdaCfg {
1342                num_heads: need(arch.linear_num_key_heads, "linear_num_key_heads")?,
1343                head_k_dim: need(arch.linear_key_head_dim, "linear_key_head_dim")?,
1344                head_v_dim: need(arch.linear_value_head_dim, "linear_value_head_dim")?,
1345                conv_kernel: need(arch.linear_conv_kernel_dim, "linear_conv_kernel_dim")?,
1346                hidden_size: arch.hidden_size,
1347                rms_eps: arch.rms_norm_eps,
1348            })
1349        } else {
1350            None
1351        };
1352
1353        // ── Short-convolution geometry (LFM2 conv mixer layers) ──
1354        let has_short_conv = arch
1355            .layer_types
1356            .iter()
1357            .any(|t| matches!(t, LayerType::ShortConv));
1358        let short_conv_cfg = if has_short_conv {
1359            Some(ShortConvCfg {
1360                hidden_size: arch.hidden_size,
1361                kernel: arch.linear_conv_kernel_dim.ok_or_else(|| {
1362                    CmfError::Parse(
1363                        "model has ShortConv layers but no arch.linear_conv_kernel_dim — \
1364                         reconvert with the current converter"
1365                            .into(),
1366                    )
1367                })?,
1368            })
1369        } else {
1370            None
1371        };
1372
1373        // ── Layers ──
1374        let load_full_attn = |prefix: &str, layer: Option<usize>| -> Result<AttnKind, CmfError> {
1375            let t = |suffix: &str| load_matrix(model, &format!("{prefix}{suffix}"), force_f32, ov);
1376            let n = |suffix: &str| -> Option<Vec<f32>> {
1377                model
1378                    .tensor(&format!("{prefix}{suffix}"))
1379                    .and_then(|_| load_f32(model, &format!("{prefix}{suffix}"), ov).ok())
1380            };
1381            // DeepSeek-V2 MLA: the latent projections replace the k/v pair.
1382            if let Some(mla) = arch.mla.as_ref() {
1383                // Compressed q (K3/V3): q_a → rms → q_b; direct otherwise.
1384                let (q_proj, q_a, q_a_norm) = if mla.q_lora_rank.is_some() {
1385                    (
1386                        t("self_attn.q_b_proj.weight")?,
1387                        Some(t("self_attn.q_a_proj.weight")?),
1388                        Some(n("self_attn.q_a_layernorm.weight").ok_or_else(|| {
1389                            CmfError::Parse(format!("{prefix}: MLA needs q_a_layernorm"))
1390                        })?),
1391                    )
1392                } else {
1393                    (t("self_attn.q_proj.weight")?, None, None)
1394                };
1395                let hd = mla.qk_rope_head_dim + mla.qk_nope_head_dim;
1396                let nh = q_proj.rows() / hd;
1397                // YaRN mscale²: DeepSeek corrects the softmax scale by
1398                // (0.1·mscale_all_dim·ln(factor)+1)².
1399                let mut scale = 1.0 / (hd as f32).sqrt();
1400                if let Some(y) = arch.yarn.as_ref() {
1401                    if let Some(m) = y.mscale_all_dim.filter(|&m| m > 0.0) {
1402                        let ms = 0.1 * m * y.factor.ln() + 1.0;
1403                        scale *= ms * ms;
1404                    }
1405                }
1406                return Ok(AttnKind::Mla(Box::new(crate::pipeline::MlaWeights {
1407                    q_proj,
1408                    q_a,
1409                    q_a_norm,
1410                    kv_a: t("self_attn.kv_a_proj_with_mqa.weight")?,
1411                    kv_a_norm: n("self_attn.kv_a_layernorm.weight").ok_or_else(|| {
1412                        CmfError::Parse(format!("{prefix}: MLA needs kv_a_layernorm"))
1413                    })?,
1414                    kv_b: t("self_attn.kv_b_proj.weight")?,
1415                    o_proj: t("self_attn.o_proj.weight")?,
1416                    nh,
1417                    qk_rope: mla.qk_rope_head_dim,
1418                    qk_nope: mla.qk_nope_head_dim,
1419                    v_dim: mla.v_head_dim,
1420                    lora: mla.kv_lora_rank,
1421                    scale,
1422                    nope: mla.nope,
1423                })));
1424            }
1425            let wq = t("self_attn.q_proj.weight")?;
1426            let nh = layer
1427                .and_then(|li| {
1428                    arch.attention_heads_per_layer
1429                        .as_ref()
1430                        .and_then(|v| v.get(li).copied())
1431                })
1432                .unwrap_or(arch.num_attention_heads);
1433            // Qwen3.5 output gate: q_proj rows = 2·nh·hd (per-head [q; gate]).
1434            // Gemma-4 global layers legitimately have nh·global_head_dim
1435            // rows (which can equal 2·nh·hd) — never gated.
1436            let output_gate = arch.global_head_dim.is_none() && wq.rows() == 2 * nh * arch.head_dim;
1437            // Gemma-4 global layers run MQA at global_head_dim — their
1438            // q_proj legitimately carries nh·ghd rows.
1439            let is_global_layer = arch.global_head_dim.is_some()
1440                && layer.is_some_and(|li| {
1441                    arch.sliding_window_pattern
1442                        .is_some_and(|p| p > 0 && (li + 1) % p == 0)
1443                });
1444            let expect = if is_global_layer {
1445                nh * arch.global_head_dim.unwrap_or(arch.head_dim)
1446            } else {
1447                nh * arch.head_dim
1448            };
1449            if !output_gate && wq.rows() != expect {
1450                return Err(CmfError::Parse(format!(
1451                    "{prefix}self_attn.q_proj.weight rows={} != heads({nh}) * head_dim({})",
1452                    wq.rows(),
1453                    expect / nh.max(1)
1454                )));
1455            }
1456            let gate_name = format!("{prefix}self_attn.g_proj.weight");
1457            let softplus_gate = if model.tensor(&gate_name).is_some() {
1458                let gate = load_matrix(model, &gate_name, force_f32, ov)?;
1459                if gate.cols() != arch.hidden_size {
1460                    return Err(CmfError::Parse(format!(
1461                        "{gate_name} cols={} != hidden_size ({})",
1462                        gate.cols(),
1463                        arch.hidden_size
1464                    )));
1465                }
1466                let per_head = if gate.rows() == nh {
1467                    true
1468                } else if gate.rows() == nh * arch.head_dim {
1469                    false
1470                } else {
1471                    return Err(CmfError::Parse(format!(
1472                        "{gate_name} rows={} must equal heads ({nh}) or heads*head_dim ({})",
1473                        gate.rows(),
1474                        nh * arch.head_dim
1475                    )));
1476                };
1477                Some((gate, per_head))
1478            } else {
1479                None
1480            };
1481            // Qwen2-family projection biases (by tensor presence).
1482            let bias = match (
1483                n("self_attn.q_proj.bias"),
1484                n("self_attn.k_proj.bias"),
1485                n("self_attn.v_proj.bias"),
1486            ) {
1487                (Some(a), Some(b), Some(c)) => Some((a, b, c)),
1488                _ => None,
1489            };
1490            let wk = t("self_attn.k_proj.weight")?;
1491            let wv = t("self_attn.v_proj.weight")?;
1492            let wo = t("self_attn.o_proj.weight")?;
1493            // K/V/O geometry, checked here and never at run time: a
1494            // mapped matvec accepts any `out`/`x` at least as long as its
1495            // rows/cols, so a V narrower than the cache's head or an
1496            // o_proj wider than nh·v would otherwise run silently wrong.
1497            // KV heads come from the header — per layer when the model
1498            // varies them (MiMo-V2: 4 full / 8 sliding), Gemma-4 global
1499            // layers carry their own (heads, width).
1500            let (nkv_l, hd_l) = if is_global_layer {
1501                (
1502                    arch.num_global_kv_heads.unwrap_or(arch.num_kv_heads),
1503                    arch.global_head_dim.unwrap_or(arch.head_dim),
1504                )
1505            } else {
1506                (
1507                    layer
1508                        .and_then(|li| {
1509                            arch.kv_heads_per_layer
1510                                .as_ref()
1511                                .and_then(|v| v.get(li).copied())
1512                        })
1513                        .unwrap_or(arch.num_kv_heads),
1514                    arch.head_dim,
1515                )
1516            };
1517            let vd = if is_global_layer {
1518                hd_l
1519            } else {
1520                arch.v_head_dim.unwrap_or(hd_l)
1521            };
1522            let shape_err = |what: String| {
1523                CmfError::Parse(format!(
1524                    "{prefix}self_attn: {what} (heads {nh}, kv heads {nkv_l}, head_dim {hd_l}, \
1525                     v_head_dim {vd}) — file and header disagree"
1526                ))
1527            };
1528            if nkv_l == 0 || nh % nkv_l != 0 {
1529                return Err(shape_err(format!(
1530                    "{nkv_l} KV heads must be nonzero and divide {nh} Q heads"
1531                )));
1532            }
1533            if vd == 0 || vd > hd_l {
1534                return Err(shape_err(format!("v_head_dim {vd} must be in 1..={hd_l}")));
1535            }
1536            if wk.rows() != nkv_l * hd_l {
1537                return Err(shape_err(format!(
1538                    "k_proj rows={} != kv_heads*head_dim={}",
1539                    wk.rows(),
1540                    nkv_l * hd_l
1541                )));
1542            }
1543            if wv.rows() != nkv_l * vd {
1544                return Err(shape_err(format!(
1545                    "v_proj rows={} != kv_heads*v_head_dim={}",
1546                    wv.rows(),
1547                    nkv_l * vd
1548                )));
1549            }
1550            if wo.cols() != nh * vd {
1551                return Err(shape_err(format!(
1552                    "o_proj cols={} != heads*v_head_dim={}",
1553                    wo.cols(),
1554                    nh * vd
1555                )));
1556            }
1557            if vd < hd_l && (output_gate || softplus_gate.is_some()) {
1558                return Err(shape_err(
1559                    "an attention output gate with V heads narrower than Q/K is not supported"
1560                        .into(),
1561                ));
1562            }
1563            Ok(AttnKind::Full {
1564                wq,
1565                wk,
1566                wv,
1567                wo,
1568                q_norm: n("self_attn.q_norm.weight"),
1569                k_norm: n("self_attn.k_norm.weight"),
1570                output_gate,
1571                softplus_gate,
1572                bias,
1573            })
1574        };
1575
1576        let load_linear_attn = |prefix: &str, li: usize| -> Result<AttnKind, CmfError> {
1577            if gdn_cfg.is_some() {
1578                // Faithful vendor operator: tensor names 1:1 with the source.
1579                let t = |suffix: &str| {
1580                    load_matrix(
1581                        model,
1582                        &format!("{prefix}linear_attn.{suffix}"),
1583                        force_f32,
1584                        ov,
1585                    )
1586                };
1587                let f = |suffix: &str| {
1588                    load_f32(model, &format!("{prefix}linear_attn.{suffix}"), ov).map_err(err)
1589                };
1590                return Ok(AttnKind::LinearGdn(GdnWeights {
1591                    in_proj_qkv: t("in_proj_qkv.weight")?,
1592                    in_proj_z: t("in_proj_z.weight")?,
1593                    in_proj_a: t("in_proj_a.weight")?,
1594                    in_proj_b: t("in_proj_b.weight")?,
1595                    conv1d: f("conv1d.weight")?,
1596                    a_log: f("A_log")?,
1597                    dt_bias: f("dt_bias")?,
1598                    norm: f("norm.weight")?,
1599                    out_proj: t("out_proj.weight")?,
1600                }));
1601            }
1602            let t = |suffix: &str| {
1603                load_matrix(model, &format!("{prefix}vmf_attn.{suffix}"), force_f32, ov)
1604            };
1605            let a_log = load_f32(model, &format!("{prefix}vmf_attn.A_log"), ov).map_err(err)?;
1606            // Selective-write gate κ (hybrid_k core): optional by tensor
1607            // presence — files without it run the classic phase kernel
1608            // bit-identically.
1609            let k_gate = if model
1610                .tensor(&format!("{prefix}vmf_attn.k_gate.weight"))
1611                .is_some()
1612            {
1613                Some((
1614                    t("k_gate.weight")?,
1615                    load_f32(model, &format!("{prefix}vmf_attn.k_gate.bias"), ov).map_err(err)?,
1616                ))
1617            } else {
1618                None
1619            };
1620            // Optional short causal conv (embryo genomes born with
1621            // --conv-k): `[hidden, 1, k]` taps, flattened.
1622            let conv = if model
1623                .tensor(&format!("{prefix}vmf_attn.conv1d.weight"))
1624                .is_some()
1625            {
1626                Some(load_f32(model, &format!("{prefix}vmf_attn.conv1d.weight"), ov).map_err(err)?)
1627            } else {
1628                None
1629            };
1630            let thq = t("thq.weight")?;
1631            let thk = t("thk.weight")?;
1632            let v_proj = t("v_proj.weight")?;
1633            let out_proj = t("out_proj.weight")?;
1634            let phase_delta = phase_delta_layers
1635                .as_ref()
1636                .is_some_and(|layers| layers.binary_search(&li).is_ok());
1637            if phase_delta {
1638                let cfg = vmf_cfg.ok_or_else(|| {
1639                    CmfError::Parse("phase_delta layer has no VMF geometry".into())
1640                })?;
1641                let expect = |name: &str, got: (usize, usize), want: (usize, usize)| {
1642                    if got != want {
1643                        Err(CmfError::Parse(format!(
1644                            "phase_delta {name} geometry [{}, {}] != [{}, {}]",
1645                            got.0, got.1, want.0, want.1
1646                        )))
1647                    } else {
1648                        Ok(())
1649                    }
1650                };
1651                expect(
1652                    "thq",
1653                    (thq.rows(), thq.cols()),
1654                    (cfg.num_heads * cfg.nphase, cfg.hidden_size),
1655                )?;
1656                expect(
1657                    "thk",
1658                    (thk.rows(), thk.cols()),
1659                    (cfg.num_heads * cfg.nphase, cfg.hidden_size),
1660                )?;
1661                expect(
1662                    "v_proj",
1663                    (v_proj.rows(), v_proj.cols()),
1664                    (cfg.num_heads * cfg.value_head_dim, cfg.hidden_size),
1665                )?;
1666                expect(
1667                    "out_proj",
1668                    (out_proj.rows(), out_proj.cols()),
1669                    (cfg.hidden_size, cfg.num_heads * cfg.value_head_dim),
1670                )?;
1671                if a_log.len() != cfg.num_heads * 2 * cfg.nphase {
1672                    return Err(CmfError::Parse(format!(
1673                        "phase_delta A_log length {} != {}",
1674                        a_log.len(),
1675                        cfg.num_heads * 2 * cfg.nphase
1676                    )));
1677                }
1678                if let Some((kw, kb)) = &k_gate {
1679                    expect(
1680                        "k_gate",
1681                        (kw.rows(), kw.cols()),
1682                        (cfg.num_heads, cfg.hidden_size),
1683                    )?;
1684                    if kb.len() != cfg.num_heads {
1685                        return Err(CmfError::Parse(format!(
1686                            "phase_delta k_gate.bias length {} != {}",
1687                            kb.len(),
1688                            cfg.num_heads
1689                        )));
1690                    }
1691                }
1692                if let Some(c) = &conv {
1693                    let n = model
1694                        .tensor(&format!("{prefix}vmf_attn.conv1d.weight"))
1695                        .ok_or_else(|| {
1696                            CmfError::Parse(
1697                                "phase_delta conv tensor disappeared during load".into(),
1698                            )
1699                        })?;
1700                    if n.shape.len() != 3
1701                        || n.shape[0] != cfg.hidden_size
1702                        || n.shape[1] != 1
1703                        || n.shape[2] < 2
1704                        || c.len() != n.shape.iter().product::<usize>()
1705                    {
1706                        return Err(CmfError::Parse(format!(
1707                            "phase_delta conv geometry {:?} / {} bytes is incompatible",
1708                            n.shape,
1709                            c.len()
1710                        )));
1711                    }
1712                }
1713            }
1714            Ok(AttnKind::Linear(VmfPhaseWeights {
1715                thq,
1716                conv,
1717                thk,
1718                v_proj,
1719                out_proj,
1720                decay: a_log.iter().map(|&a| (-(a as f64).exp()).exp()).collect(),
1721                k_gate,
1722                phase_delta,
1723            }))
1724        };
1725
1726        // LFM2 short-conv mixer: in_proj [3·hidden, hidden], a depthwise
1727        // conv (stored f16 as `[hidden, 1, kernel]` → flattened taps), and
1728        // out_proj [hidden, hidden]. Names canonicalized at convert time.
1729        let load_short_conv = |prefix: &str| -> Result<AttnKind, CmfError> {
1730            let t = |suffix: &str| {
1731                load_matrix(
1732                    model,
1733                    &format!("{prefix}short_conv.{suffix}"),
1734                    force_f32,
1735                    ov,
1736                )
1737            };
1738            Ok(AttnKind::ShortConv(ShortConvWeights {
1739                in_proj: t("in_proj.weight")?,
1740                conv: load_f32(model, &format!("{prefix}short_conv.conv.weight"), ov)
1741                    .map_err(err)?,
1742                out_proj: t("out_proj.weight")?,
1743            }))
1744        };
1745
1746        // KDA layer (Kimi Linear / Kimi-K3): faithful vendor tensors under
1747        // the `kda_attn.` canonical prefix. The output gate is full-rank
1748        // (g_proj, K3) or low-rank (g_a/g_b, Kimi-Linear-48B) by presence.
1749        let load_kda = |prefix: &str| -> Result<AttnKind, CmfError> {
1750            let t = |suffix: &str| {
1751                load_matrix(model, &format!("{prefix}kda_attn.{suffix}"), force_f32, ov)
1752            };
1753            let f = |suffix: &str| {
1754                load_f32(model, &format!("{prefix}kda_attn.{suffix}"), ov).map_err(err)
1755            };
1756            let gate = if model
1757                .tensor(&format!("{prefix}kda_attn.g_proj.weight"))
1758                .is_some()
1759            {
1760                crate::linear_core::KdaOutGate::Full(t("g_proj.weight")?)
1761            } else {
1762                crate::linear_core::KdaOutGate::LowRank(
1763                    t("g_a_proj.weight")?,
1764                    t("g_b_proj.weight")?,
1765                )
1766            };
1767            Ok(AttnKind::Kda(Box::new(crate::linear_core::KdaWeights {
1768                q_proj: t("q_proj.weight")?,
1769                k_proj: t("k_proj.weight")?,
1770                v_proj: t("v_proj.weight")?,
1771                conv_q: f("q_conv1d.weight")?,
1772                conv_k: f("k_conv1d.weight")?,
1773                conv_v: f("v_conv1d.weight")?,
1774                f_a: t("f_a_proj.weight")?,
1775                f_b: t("f_b_proj.weight")?,
1776                dt_bias: f("dt_bias")?,
1777                a_log: f("A_log")?,
1778                b_proj: t("b_proj.weight")?,
1779                gate,
1780                o_norm: f("o_norm.weight")?,
1781                o_proj: t("o_proj.weight")?,
1782                gate_lower_bound: arch.kda_gate_lower_bound.map(|v| v as f32),
1783            })))
1784        };
1785
1786        // Natively bounded anchor (Embryo-O1 `swa_sink_v1`): the plain
1787        // q/k/v/o projections plus the TRAINED sink vectors
1788        // `self_attn.sink_k/sink_v.weight [kvh, S, hd]` (f32, weights —
1789        // not positions). The operator carries no qk-norm, gate or bias:
1790        // their presence is a contract violation, not something to
1791        // silently execute differently from the trainer.
1792        let load_bounded_attn = |prefix: &str, li: usize| -> Result<AttnKind, CmfError> {
1793            let ac = arch.anchor_core.as_ref().ok_or_else(|| {
1794                CmfError::Parse(format!(
1795                    "layer {li} is BoundedAttention but the header carries no anchor_core"
1796                ))
1797            })?;
1798            let t = |suffix: &str| load_matrix(model, &format!("{prefix}{suffix}"), force_f32, ov);
1799            let (nkv, hd, nh) = (arch.num_kv_heads, arch.head_dim, arch.num_attention_heads);
1800            for extra in [
1801                "self_attn.q_norm.weight",
1802                "self_attn.k_norm.weight",
1803                "self_attn.g_proj.weight",
1804                "self_attn.q_proj.bias",
1805                "self_attn.k_proj.bias",
1806                "self_attn.v_proj.bias",
1807            ] {
1808                if model.tensor(&format!("{prefix}{extra}")).is_some() {
1809                    return Err(CmfError::Parse(format!(
1810                        "{prefix}{extra}: the bounded anchor operator carries no qk-norm, \
1811                         gate or bias (docs/EMBRYO_BOUNDED_ANCHOR.md §1)"
1812                    )));
1813                }
1814            }
1815            let sink = |name: &str| -> Result<Vec<f32>, CmfError> {
1816                let full = format!("{prefix}self_attn.{name}.weight");
1817                let e = model.tensor(&full).ok_or_else(|| {
1818                    CmfError::MissingTensor(format!(
1819                        "{full} (a bounded anchor needs its trained sinks)"
1820                    ))
1821                })?;
1822                if e.shape.len() != 3
1823                    || e.shape[0] != nkv
1824                    || e.shape[1] != ac.sink
1825                    || e.shape[2] != hd
1826                {
1827                    return Err(CmfError::Parse(format!(
1828                        "{full}: shape {:?} != [{nkv}, {}, {hd}] (num_kv_heads, anchor_core.sink, head_dim)",
1829                        e.shape, ac.sink
1830                    )));
1831                }
1832                load_f32(model, &full, ov).map_err(err)
1833            };
1834            let wq = t("self_attn.q_proj.weight")?;
1835            let wk = t("self_attn.k_proj.weight")?;
1836            let wv = t("self_attn.v_proj.weight")?;
1837            let wo = t("self_attn.o_proj.weight")?;
1838            let expect = |name: &str, got: (usize, usize), want: (usize, usize)| {
1839                if got != want {
1840                    Err(CmfError::Parse(format!(
1841                        "{prefix}self_attn.{name}.weight is {}x{}, expected {}x{}",
1842                        got.0, got.1, want.0, want.1
1843                    )))
1844                } else {
1845                    Ok(())
1846                }
1847            };
1848            expect("q_proj", (wq.rows(), wq.cols()), (nh * hd, arch.hidden_size))?;
1849            expect("k_proj", (wk.rows(), wk.cols()), (nkv * hd, arch.hidden_size))?;
1850            expect("v_proj", (wv.rows(), wv.cols()), (nkv * hd, arch.hidden_size))?;
1851            expect("o_proj", (wo.rows(), wo.cols()), (arch.hidden_size, nh * hd))?;
1852            Ok(AttnKind::Bounded(Box::new(crate::bounded::BoundedWeights {
1853                wq,
1854                wk,
1855                wv,
1856                wo,
1857                sink_k: sink("sink_k")?,
1858                sink_v: sink("sink_v")?,
1859                sink: ac.sink,
1860                window: ac.window,
1861                group_windows: ac.group_windows.clone(),
1862            })))
1863        };
1864
1865        fn anyhow_like(ok: bool) -> Result<(), ()> {
1866            if ok { Ok(()) } else { Err(()) }
1867        }
1868        let mut layers = Vec::with_capacity(arch.num_layers);
1869        let is_g3n = arch.g3n.is_some();
1870        // Architectures that load their own layer stack below. DeepSeek-V4
1871        // has none of the canonical projections — no q/k/v/o_proj, no
1872        // per-layer gate_proj — so the generic loop would demand
1873        // `self_attn.q_proj.weight` and fail before its own loader ever ran.
1874        let owns_its_layers = is_g3n
1875            || arch.arch_name == "deepseek_v4"
1876            || arch.arch_name == "deepseek_v41"
1877            || arch.dory.is_some()
1878            || arch.qwen4_exp.is_some()
1879            || arch.glm5_next.is_some()
1880            || arch.arch_name == crate::hy4::ARCH_NAME
1881            || arch.arch_name == crate::maxwell::ARCH_NAME
1882            || arch.arch_name == crate::inkling::ARCH_NAME;
1883        for li in 0..(if owns_its_layers { 0 } else { arch.num_layers }) {
1884            let prefix = format!("model.layers.{li}.");
1885            let attn = match arch.layer_types.get(li) {
1886                Some(LayerType::LinearAttention) => load_linear_attn(&prefix, li)?,
1887                Some(LayerType::Kda) => load_kda(&prefix)?,
1888                Some(LayerType::ShortConv) => load_short_conv(&prefix)?,
1889                Some(LayerType::BoundedAttention) => load_bounded_attn(&prefix, li)?,
1890                _ => load_full_attn(&prefix, Some(li))?,
1891            };
1892            // Gemma-2/3 sandwich: `pre_feedforward_layernorm` present →
1893            // it is the pre-FFN norm, and post_attention/post_feedforward
1894            // норms apply to the branch OUTPUTS before their residuals.
1895            let pre_ffn = format!("{prefix}pre_feedforward_layernorm.weight");
1896            let sandwich = model.tensor(&pre_ffn).is_some();
1897            layers.push(LayerWeights {
1898                input_norm: load_f32(model, &format!("{prefix}input_layernorm.weight"), ov)
1899                    .map_err(err)?,
1900                post_norm: if sandwich {
1901                    load_f32(model, &pre_ffn, ov).map_err(err)?
1902                } else {
1903                    load_f32(
1904                        model,
1905                        &format!("{prefix}post_attention_layernorm.weight"),
1906                        ov,
1907                    )
1908                    .map_err(err)?
1909                },
1910                attn_out_norm: if sandwich {
1911                    Some(
1912                        load_f32(
1913                            model,
1914                            &format!("{prefix}post_attention_layernorm.weight"),
1915                            ov,
1916                        )
1917                        .map_err(err)?,
1918                    )
1919                } else {
1920                    None
1921                },
1922                ffn_out_norm: if sandwich {
1923                    Some(
1924                        load_f32(
1925                            model,
1926                            &format!("{prefix}post_feedforward_layernorm.weight"),
1927                            ov,
1928                        )
1929                        .map_err(err)?,
1930                    )
1931                } else {
1932                    None
1933                },
1934                // Gemma-4: learned scalar multiplying the layer output.
1935                layer_scale: model
1936                    .tensor(&format!("{prefix}layer_scalar"))
1937                    .and_then(|_| {
1938                        load_f32(model, &format!("{prefix}layer_scalar"), ov)
1939                            .ok()
1940                            .and_then(|v| v.first().copied())
1941                    }),
1942                // FFN always quantized — masks run sparse on quant bytes.
1943                ffn: build_layer_ffn(model, &arch, li, false, ov)?,
1944                attn,
1945            });
1946        }
1947
1948        // ── MTP head (optional, spec §2.1) ──
1949        //
1950        // The header declaring an MTP head is not the same as the file
1951        // carrying one. DeepSeek-V4's config announces a next-token predictor
1952        // whose weights the converter does not map (they are spelled `mtp.N.*`
1953        // and have none of the canonical projections), so demanding
1954        // `model.mtp.layers.0.self_attn.q_proj.weight` failed a model that is
1955        // otherwise complete. Presence in the directory decides.
1956        let mtp_present = model
1957            .tensor("model.mtp.layers.0.self_attn.q_proj.weight")
1958            .is_some()
1959            || model.tensor("model.mtp.eh_proj.weight").is_some();
1960        // DeepSeek-V4 writes its own stack under `model.mtp.N.*` — three full
1961        // layers, not a V3-style single block — so it cannot go through the
1962        // path below and is loaded by the dsv4 arm instead. Saying the file
1963        // "carries none" was a false negative worth six gigabytes.
1964        let dsv4_mtp = model.tensor("model.mtp.0.main_proj.weight").is_some();
1965        if arch.mtp.is_some() && !mtp_present && !dsv4_mtp {
1966            tracing::info!(
1967                "header declares an MTP head but the file carries none — \
1968                 loading without it"
1969            );
1970        }
1971        // MiMo-V2 carries its own three-layer stack (sidecar or main file),
1972        // loaded by `mimo_mtp::load_for` below — never this single block.
1973        let mtp = if let Some(cfg) = arch
1974            .mtp
1975            .as_ref()
1976            .filter(|_| mtp_present && arch.arch_name != "mimo_v2")
1977        {
1978            if cfg.num_layers != 1 {
1979                return Err(CmfError::Parse(format!(
1980                    "MTP with {} blocks not supported yet (only 1)",
1981                    cfg.num_layers
1982                )));
1983            }
1984            let p = "model.mtp.";
1985            let attn = load_full_attn("model.mtp.layers.0.", None)?;
1986            // The MTP MLP may be physically narrower than the trunk after
1987            // draft-only compaction. `build_ffn_at` establishes the local
1988            // tensor triple geometry; the optional header declaration is a
1989            // checked assertion, never a replacement for those dimensions.
1990            let ffn = build_ffn_at(model, &arch, &format!("{p}layers.0."), false, ov)?;
1991            validate_generic_mtp_ffn_width(cfg, &ffn)?;
1992            Some(MtpModule {
1993                enorm: load_f32(model, &format!("{p}enorm.weight"), ov).map_err(err)?,
1994                hnorm: load_f32(model, &format!("{p}hnorm.weight"), ov).map_err(err)?,
1995                eh_proj: load_matrix(model, &format!("{p}eh_proj.weight"), false, ov)?,
1996                layer: LayerWeights {
1997                    attn_out_norm: None,
1998                    ffn_out_norm: None,
1999                    layer_scale: None,
2000                    input_norm: load_f32(model, &format!("{p}layers.0.input_layernorm.weight"), ov)
2001                        .map_err(err)?,
2002                    post_norm: load_f32(
2003                        model,
2004                        &format!("{p}layers.0.post_attention_layernorm.weight"),
2005                        ov,
2006                    )
2007                    .map_err(err)?,
2008                    // Whatever the block actually carries: DeepSeek's MTP
2009                    // layer is dense, Qwen3.6's is a full MoE (router + 256
2010                    // experts + shared). Same builder as a backbone layer.
2011                    ffn,
2012                    attn,
2013                },
2014                final_norm: load_f32(model, &format!("{p}norm.weight"), ov).map_err(err)?,
2015                kv: LayerKvCache::new(arch.num_kv_heads, arch.head_dim),
2016            })
2017        } else {
2018            None
2019        };
2020
2021        tracing::info!(
2022            "Pipeline loaded: {} | {}L ({} linear) | {:.2}B params | storage: {} | MTP: {}",
2023            arch.arch_name,
2024            arch.num_layers,
2025            arch.layer_types
2026                .iter()
2027                .filter(|t| matches!(t, LayerType::LinearAttention))
2028                .count(),
2029            model.total_param_count() as f64 / 1e9,
2030            if force_f32 {
2031                "f32 (masked)"
2032            } else {
2033                "quantized mmap"
2034            },
2035            if mtp.is_some() { "yes" } else { "no" }
2036        );
2037
2038        // KV window: the descriptor's max, capped for dev-box safety;
2039        // CMF_MAX_SEQ overrides the cap (long-context runs).
2040        // 8192 was the silent quality cliff of the Qwen3.8 bring-up: at
2041        // the cap the wgpu token graph declines, the host evicts half the
2042        // KV, and a GDN hybrid's recurrent state goes stale — the model
2043        // stays fluent and loses its mind (Django internals, a Turkish
2044        // essay, an em-dash loop; one failure, three costumes). 32768
2045        // covers every long-form run we actually ship while keeping the
2046        // graph's device KV mirror affordable beside the weights;
2047        // CMF_MAX_SEQ still overrides in either direction.
2048        let cap = std::env::var("CMF_MAX_SEQ")
2049            .ok()
2050            .and_then(|v| v.parse::<usize>().ok())
2051            // A turbo file's rows past the seal take no device memory.
2052            .unwrap_or(if model.header.provenance.as_ref().is_some_and(|p| p.get("o1_turbo").is_some()) {
2053                usize::MAX
2054            } else {
2055                32_768
2056            });
2057        let max_seq_len = arch.max_position_embeddings.min(cap);
2058
2059        // Looped Transformer: total virtual layers = physical × num_loops.
2060        // SenseNova-Loop: [0, s) + [s, e) × count + [e, n), one virtual
2061        // layer (and cache) per visit.
2062        let sensenova = crate::sensenova::settings(model).map_err(CmfError::Parse)?;
2063        let layer_map = sensenova
2064            .map(|(span, _)| crate::sensenova::execution_plan(arch.num_layers, span));
2065        let total_layers = layer_map
2066            .as_ref()
2067            .map_or(arch.num_layers * arch.num_loops, Vec::len);
2068
2069        let mut pipeline = Pipeline::new(
2070            tokenizer,
2071            PipelineWeights {
2072                embed_tokens,
2073                layers,
2074                lm_head,
2075                final_norm,
2076            },
2077            arch.hidden_size,
2078            arch.intermediate_size,
2079            arch.num_attention_heads,
2080            arch.num_kv_heads,
2081            arch.head_dim,
2082            total_layers,
2083            arch.num_layers, // physical layers in weights
2084            arch.loop_final_norm,
2085            arch.vocab_size,
2086            arch.rms_norm_eps,
2087            arch.rope_theta as f32,
2088            arch.norm_style,
2089            max_seq_len,
2090            sampler_config,
2091        );
2092        // Unlimited-OCR: the DASH router and its page state.
2093        if arch.arch_name == crate::uocr::ARCH {
2094            pipeline.dash = Some(Box::new(crate::uocr::Dash::from_model(model).map_err(CmfError::Parse)?));
2095        }
2096        if let Some((_, mhc)) = sensenova {
2097            pipeline.layer_map = layer_map;
2098            if let Some(ms) = mhc {
2099                pipeline.mhc = Some(Box::new(
2100                    crate::sensenova::Mhc::from_model(model, ms, arch.num_layers, arch.hidden_size)
2101                        .map_err(CmfError::Parse)?,
2102                ));
2103            }
2104            pipeline.mrope_sections = model
2105                .header
2106                .provenance
2107                .as_ref()
2108                .and_then(|p| p.pointer("/sensenova_loop/config/text_config/rope_parameters/mrope_section"))
2109                .and_then(|v| v.as_array())
2110                .filter(|a| a.len() == 3)
2111                .map(|a| {
2112                    let g = |i: usize| a[i].as_u64().unwrap_or(0) as usize;
2113                    [g(0), g(1), g(2)]
2114                });
2115        }
2116        let rotary = ((arch.head_dim as f32 * arch.partial_rotary_factor) as usize).max(2);
2117        pipeline.set_rotary(rotary, arch.rope_theta as f32);
2118        pipeline.attention_heads_per_layer = arch.attention_heads_per_layer.clone();
2119        if let Some(yarn) = &arch.yarn {
2120            pipeline.inv_freq = std::sync::Arc::new(crate::attention::yarn_inv_freq(
2121                rotary,
2122                arch.rope_theta as f32,
2123                yarn.factor,
2124                yarn.original_max_position_embeddings,
2125                yarn.beta_fast,
2126                yarn.beta_slow,
2127            ));
2128            pipeline.rope_scale = yarn.attention_factor;
2129        }
2130        // Gemma-family extras: embedding scale, attention-scale
2131        // override, and (Gemma-3) sliding-window layers with their own
2132        // local RoPE base.
2133        pipeline.embed_multiplier = arch.embed_multiplier;
2134        pipeline.logit_multiplier = arch.logit_multiplier;
2135        if let Some(qpas) = arch.query_pre_attn_scalar {
2136            pipeline.attn_scale = 1.0 / (qpas as f32).sqrt();
2137        }
2138        if let (Some(w), Some(p)) = (arch.sliding_window, arch.sliding_window_pattern) {
2139            pipeline.swa = Some((w, p));
2140            if let Some(base) = arch.rope_local_base_freq {
2141                pipeline.inv_freq_local = Some(std::sync::Arc::new(
2142                    crate::attention::rope_inv_freq(rotary, base as f32),
2143                ));
2144            }
2145        }
2146        let explicit_sliding: Vec<bool> = arch
2147            .layer_types
2148            .iter()
2149            .map(|t| matches!(t, cortiq_core::LayerType::SlidingAttention))
2150            .collect();
2151        if explicit_sliding.iter().any(|&v| v) {
2152            pipeline.sliding_layers = Some(explicit_sliding);
2153            if let Some(w) = arch.sliding_window {
2154                pipeline.swa = Some((w, usize::MAX));
2155            }
2156            let local_rotary = ((arch.head_dim as f32
2157                * arch
2158                    .local_partial_rotary_factor
2159                    .unwrap_or(arch.partial_rotary_factor))
2160                as usize)
2161                .max(2);
2162            pipeline.rotary_dim_local = Some(local_rotary);
2163            if let Some(base) = arch.rope_local_base_freq {
2164                pipeline.inv_freq_local = Some(std::sync::Arc::new(
2165                    crate::attention::rope_inv_freq(local_rotary, base as f32),
2166                ));
2167            }
2168        }
2169        // Gemma-4: global layers run their own geometry (MQA at
2170        // global_head_dim) with a proportional RoPE — the first
2171        // factor·head_dim dims rotate, the zero-padded tail is identity.
2172        if let (Some(ghd), Some(gkv)) = (arch.global_head_dim, arch.num_global_kv_heads) {
2173            pipeline.global_attn = Some((ghd, gkv));
2174            let prf = arch.global_partial_rotary_factor.unwrap_or(1.0);
2175            let half = ghd / 2;
2176            let ra = (((prf * ghd as f32) as usize) / 2).min(half);
2177            let mut f = vec![0.0f32; half];
2178            for (i, slot) in f.iter_mut().enumerate().take(ra) {
2179                *slot = 1.0 / (arch.rope_theta as f32).powf(2.0 * i as f32 / ghd as f32);
2180            }
2181            pipeline.inv_freq_global = Some(std::sync::Arc::new(f));
2182            // Re-shape the global layers' KV storage to their geometry.
2183            // An explicit layer_types map wins over the numeric pattern
2184            // (explicit tags set swa's pattern to usize::MAX, which
2185            // would otherwise leave every global cache mis-shaped).
2186            let global_at = |li: usize| -> bool {
2187                match &pipeline.sliding_layers {
2188                    Some(map) => !map.get(li).copied().unwrap_or(false),
2189                    None => pipeline
2190                        .swa
2191                        .map(|(_, p)| p > 0 && p != usize::MAX && (li + 1) % p == 0)
2192                        .unwrap_or(false),
2193                }
2194            };
2195            for li in 0..arch.num_layers {
2196                if global_at(li) {
2197                    pipeline.kv_cache.layers[li] = crate::kv_cache::LayerKvCache::new(gkv, ghd);
2198                }
2199            }
2200        }
2201        // The same proportional RoPE on full-attention layers that keep the
2202        // model's head geometry (LFM3): the whole head rotates (header
2203        // factor 1.0) with the full-head frequency progression, and the
2204        // frequencies past `factor·head_dim/2` are zero (identity pairs).
2205        if let (Some(prf), None) = (arch.global_partial_rotary_factor, arch.global_head_dim) {
2206            if arch.yarn.is_some() || pipeline.rotary_dim != arch.head_dim {
2207                return Err(CmfError::Parse(format!(
2208                    "global_partial_rotary_factor {prf} needs partial_rotary_factor 1.0 and no \
2209                     YaRN profile (rotary width {} of head {})",
2210                    pipeline.rotary_dim, arch.head_dim
2211                )));
2212            }
2213            let mut f = crate::attention::rope_inv_freq(arch.head_dim, arch.rope_theta as f32);
2214            let ra = (((prf * arch.head_dim as f32) as usize) / 2).min(f.len());
2215            for slot in f.iter_mut().skip(ra) {
2216                *slot = 0.0;
2217            }
2218            pipeline.inv_freq = std::sync::Arc::new(f);
2219        }
2220        // MLA (DeepSeek-V2): the expand-to-MHA cache holds nh heads of
2221        // rope+nope dims; rotary covers the rope prefix.
2222        if let Some(mla) = arch.mla.as_ref() {
2223            let hd = mla.qk_rope_head_dim + mla.qk_nope_head_dim;
2224            pipeline.head_dim = hd;
2225            pipeline.num_kv_heads = arch.num_attention_heads;
2226            pipeline.rotary_dim = mla.qk_rope_head_dim;
2227            let half = mla.qk_rope_head_dim / 2;
2228            let mut f = vec![0.0f32; half];
2229            for (i, slot) in f.iter_mut().enumerate() {
2230                *slot = 1.0
2231                    / (arch.rope_theta as f32).powf(2.0 * i as f32 / mla.qk_rope_head_dim as f32);
2232            }
2233            pipeline.inv_freq = std::sync::Arc::new(f);
2234            for li in 0..arch.num_layers {
2235                pipeline.kv_cache.layers[li] =
2236                    crate::kv_cache::LayerKvCache::new(arch.num_attention_heads, hd);
2237            }
2238        }
2239        // Per-layer KV geometry (MiMo-V2): KV heads per layer and V heads
2240        // narrower than Q/K. The per-layer shapes were checked against the
2241        // header in load_full_attn; this installs the geometry and gives
2242        // every layer whose KV head count differs its own cache shape.
2243        if !owns_its_layers {
2244            pipeline
2245                .set_attn_geometry(arch.kv_heads_per_layer.clone(), arch.v_head_dim)
2246                .map_err(|e| CmfError::Parse(format!("attention geometry: {e}")))?;
2247        } else if (arch.kv_heads_per_layer.is_some() || arch.v_head_dim.is_some()) && arch.arch_name != crate::hy4::ARCH_NAME {
2248            // Hy4-flash's stack reads its MLA geometry itself
2249            return Err(CmfError::Parse(format!(
2250                "{}: kv_heads_per_layer / v_head_dim are not supported by its own layer stack",
2251                arch.arch_name
2252            )));
2253        }
2254        // Learned attention sinks (gpt-oss / MiMo-V2 SWA layers), by tensor
2255        // presence: `model.layers.N.self_attn.sinks`, one f32 logit per Q
2256        // head (`attention_sink_bias` is the HF spelling, accepted too).
2257        // They fold into the grouped softmax; every attention path that
2258        // cannot carry them (chunk GEMM attend, O(1), the GPU graphs)
2259        // refuses the layer.
2260        if !owns_its_layers {
2261            for li in 0..arch.num_layers {
2262                let name = [
2263                    format!("model.layers.{li}.self_attn.sinks"),
2264                    format!("model.layers.{li}.self_attn.attention_sink_bias"),
2265                    // Recursive Flint spells the same thing `softmax_offset`:
2266                    // one learned logit per Q head, added to the attention
2267                    // logits before the softmax.
2268                    format!("model.layers.{li}.self_attn.softmax_offset"),
2269                ]
2270                .into_iter()
2271                .find(|n| model.tensor(n).is_some());
2272                if let Some(name) = name {
2273                    let sinks = load_f32(model, &name, ov).map_err(err)?;
2274                    pipeline
2275                        .set_layer_sinks(li, sinks)
2276                        .map_err(|e| CmfError::Parse(format!("{name}: {e}")))?;
2277                }
2278            }
2279        }
2280        // Flint serializes the no-RoPE schedule explicitly.  Do not infer it
2281        // from a layer class: a later variant may combine a full window with
2282        // RoPE, and changing it changes every attention score.
2283        if arch.arch_name == "flint" || arch.arch_name == "ricursive" {
2284            pipeline.no_rope_layers = arch.no_rope_layers.clone();
2285        }
2286        // Ripple's value residual, by tensor presence: one scalar a layer,
2287        // `model.layers.N.self_attn.value_res_lambda`; V reads
2288        // `lerp(embedding, normed, sigmoid(lambda))`. A layer without one reads the normed
2289        // input (blend 1).
2290        if !owns_its_layers {
2291            let mut blend = vec![1.0f32; arch.num_layers];
2292            let mut any = false;
2293            for (li, b) in blend.iter_mut().enumerate() {
2294                let name = format!("model.layers.{li}.self_attn.value_res_lambda");
2295                if model.tensor(&name).is_some() {
2296                    let lam = load_f32(model, &name, ov).map_err(err)?;
2297                    if lam.len() != 1 {
2298                        return Err(CmfError::Parse(format!("{name}: one scalar expected, got {}", lam.len())));
2299                    }
2300                    *b = 1.0 / (1.0 + (-lam[0]).exp());
2301                    any = true;
2302                }
2303            }
2304            if any {
2305                pipeline.value_blend = Some(blend);
2306            }
2307        }
2308        if pipeline.kv_heads_per_layer.is_some()
2309            || pipeline.v_head_dim.is_some()
2310            || pipeline.kv_cache.layers.iter().any(|l| l.sinks.is_some())
2311        {
2312            let per_token: usize = pipeline
2313                .kv_cache
2314                .layers
2315                .iter()
2316                .map(|l| 2 * l.num_kv_heads * l.head_dim * std::mem::size_of::<f32>())
2317                .sum();
2318            tracing::info!(
2319                "attention geometry: kv heads per layer {:?}, v_head_dim {:?}, {} sink layer(s); \
2320                 f32 KV {} B/token (V padded to head_dim), cap {} tokens",
2321                pipeline.kv_heads_per_layer,
2322                pipeline.v_head_dim,
2323                pipeline
2324                    .kv_cache
2325                    .layers
2326                    .iter()
2327                    .filter(|l| l.sinks.is_some())
2328                    .count(),
2329                per_token,
2330                pipeline.kv_cache.max_seq_len
2331            );
2332        }
2333        // Per-frequency rope divisors (MiniCPM3 longrope short_factor):
2334        // served at the native window with the trained per-dim factors.
2335        // Applied after every inv_freq build (plain, YaRN, MLA).
2336        if let Some(fac) = &arch.rope_freq_factors {
2337            let mut f = pipeline.inv_freq.as_ref().clone();
2338            for (i, v) in f.iter_mut().enumerate() {
2339                if let Some(&d) = fac.get(i) {
2340                    *v /= d as f32;
2341                }
2342            }
2343            pipeline.inv_freq = std::sync::Arc::new(f);
2344        }
2345        if let Some(selected) = &phase_delta_layers {
2346            for &li in selected {
2347                pipeline.kv_cache.layers[li].set_linear_wire_allowed(false);
2348            }
2349        }
2350        pipeline.attn_v_norm = arch.attn_v_norm;
2351        pipeline.qk_norm_after_rope = arch.qk_norm_after_rope;
2352        // One sigmoid gate per head from its own projection: Spark-X2.5's
2353        // `g_proj`, LFM3's `gate_proj` (renamed at convert time).
2354        pipeline.proj_gate_sigmoid = arch.arch_name == "spark2_5" || arch.arch_name == "lfm3";
2355        pipeline.final_softcap = arch.final_logit_softcapping.map(|c| c as f32);
2356        // Cortiq Embryo hierarchical head: cluster matrix → two-level log-probs.
2357        if let Some(ncl) = arch.head_clusters {
2358            let cm = load_f32(model, "lm_head.clusters.weight", ov).map_err(err)?;
2359            if cm.len() != ncl * arch.hidden_size {
2360                return Err(CmfError::Parse(format!(
2361                    "lm_head.clusters.weight: {} != {ncl}×{}",
2362                    cm.len(),
2363                    arch.hidden_size
2364                )));
2365            }
2366            pipeline.head_clusters = Some(std::sync::Arc::new(cm));
2367        }
2368        pipeline.attn_softcap = arch.attn_logit_softcapping.unwrap_or(0.0) as f32;
2369        pipeline.vmf_cfg = vmf_cfg;
2370        pipeline.gdn_cfg = gdn_cfg;
2371        pipeline.kda_cfg = kda_cfg;
2372        if arch.block_diffusion.is_some() {
2373            let c = crate::pipeline::clover::load(model, &arch, gdn_cfg.as_ref(), ov)?;
2374            pipeline.clover = Some(std::sync::Arc::new(c));
2375        }
2376        if arch.qwen4_exp.is_some() {
2377            let (globals, layers, cfg, state) = crate::qwen4_exp::load(model, &arch)?;
2378            pipeline.qwen4_exp = Some(Box::new((globals, layers, cfg, state)));
2379        }
2380        if arch.glm5_next.is_some() {
2381            let (globals, layers, cfg, state) = crate::glm5_next::load(model, &arch)?;
2382            pipeline.glm5_next = Some(Box::new((globals, layers, cfg, state)));
2383        }
2384        if arch.arch_name == crate::hy4::ARCH_NAME {
2385            let (globals, layers, cfg, state) = crate::hy4::load(model, &arch)?;
2386            pipeline.hy4 = Some(Box::new((globals, layers, cfg, state)));
2387        }
2388        if arch.arch_name == crate::maxwell::ARCH_NAME {
2389            let (globals, layers, cfg, state) = crate::maxwell::load(model, &arch)?;
2390            pipeline.maxwell = Some(Box::new((globals, layers, cfg, state)));
2391        }
2392        if arch.arch_name == crate::inkling::ARCH_NAME {
2393            let (globals, layers, cfg, state) = crate::inkling::load(model, &arch)?;
2394            pipeline.inkling = Some(Box::new((globals, layers, cfg, state)));
2395        }
2396        // Gemma-4 E-series (E4B): the E block rides in `g3n` — altup/
2397        // laurel are zeroed for gemma4 — but the layer body is the
2398        // gemma4 stack (dual geometry, proportional RoPE, PLE, shared
2399        // KV), so it loads into its own runtime stack instead.
2400        if arch.g3n.is_some() && arch.arch_name.starts_with("gemma4") {
2401            use crate::g4e::{G4eGlobals, G4eLayer};
2402            let gc = arch.g3n.as_ref().expect("checked above");
2403            let t = |name: &str| load_matrix(model, name, force_f32, ov);
2404            let f = |name: &str| load_f32(model, name, ov).map_err(err);
2405            let first_shared = arch.num_layers.saturating_sub(gc.num_kv_shared_layers);
2406            let sliding_of = |li: usize| {
2407                matches!(
2408                    arch.layer_types.get(li),
2409                    Some(cortiq_core::LayerType::SlidingAttention)
2410                )
2411            };
2412            let hd_g = arch.global_head_dim.unwrap_or(arch.head_dim);
2413            let mut g4e_layers = Vec::with_capacity(arch.num_layers);
2414            for li in 0..arch.num_layers {
2415                let pfx = format!("model.layers.{li}.");
2416                let shared = li >= first_shared && first_shared > 0;
2417                // Same sharing rule as transformers/llama.cpp/gemma-3n:
2418                // a tail layer reuses the KV of the LAST non-shared
2419                // layer of its own attention type.
2420                let share_src = if shared {
2421                    let want = sliding_of(li);
2422                    (0..first_shared).rev().find(|&j| sliding_of(j) == want)
2423                } else {
2424                    None
2425                };
2426                let sliding = sliding_of(li);
2427                let scalar_name = format!("{pfx}layer_scalar");
2428                g4e_layers.push(G4eLayer {
2429                    input_norm: f(&format!("{pfx}input_layernorm.weight"))?,
2430                    attn_out_norm: f(&format!("{pfx}post_attention_layernorm.weight"))?,
2431                    pre_ffn_norm: f(&format!("{pfx}pre_feedforward_layernorm.weight"))?,
2432                    post_ffw_norm: f(&format!("{pfx}post_feedforward_layernorm.weight"))?,
2433                    wq: t(&format!("{pfx}self_attn.q_proj.weight"))?,
2434                    wk: if shared {
2435                        None
2436                    } else {
2437                        Some(t(&format!("{pfx}self_attn.k_proj.weight"))?)
2438                    },
2439                    wv: if shared {
2440                        None
2441                    } else {
2442                        Some(t(&format!("{pfx}self_attn.v_proj.weight"))?)
2443                    },
2444                    wo: t(&format!("{pfx}self_attn.o_proj.weight"))?,
2445                    q_norm: f(&format!("{pfx}self_attn.q_norm.weight"))?,
2446                    k_norm: if shared {
2447                        None
2448                    } else {
2449                        Some(f(&format!("{pfx}self_attn.k_norm.weight"))?)
2450                    },
2451                    kv_share_src: share_src,
2452                    sliding,
2453                    hd: if sliding { arch.head_dim } else { hd_g },
2454                    gate: t(&format!("{pfx}mlp.gate_proj.weight"))?,
2455                    up: t(&format!("{pfx}mlp.up_proj.weight"))?,
2456                    down: t(&format!("{pfx}mlp.down_proj.weight"))?,
2457                    ple_gate: t(&format!("{pfx}per_layer_input_gate.weight"))?,
2458                    ple_proj: t(&format!("{pfx}per_layer_projection.weight"))?,
2459                    post_ple_norm: f(&format!("{pfx}post_per_layer_input_norm.weight"))?,
2460                    layer_scalar: if model.tensor(&scalar_name).is_some() {
2461                        f(&scalar_name)?.first().copied()
2462                    } else {
2463                        None
2464                    },
2465                });
2466            }
2467            // Proportional RoPE for the full layers — the same
2468            // construction the generic loader installs for dense
2469            // gemma4: the first prf·ghd dims rotate (exponent over
2470            // ghd), the zero tail is identity under rope_rotate_scaled.
2471            let ghd = hd_g;
2472            let prf = arch.global_partial_rotary_factor.unwrap_or(1.0);
2473            let half = ghd / 2;
2474            let ra = (((prf * ghd as f32) as usize) / 2).min(half);
2475            let mut inv_freq_global = vec![0.0f32; half];
2476            for (i, slot) in inv_freq_global.iter_mut().enumerate().take(ra) {
2477                *slot = 1.0 / (arch.rope_theta as f32).powf(2.0 * i as f32 / ghd as f32);
2478            }
2479            let globals = G4eGlobals {
2480                ple_embed: t("model.embed_tokens_per_layer.weight")?,
2481                ple_model_proj: t("model.per_layer_model_projection.weight")?,
2482                ple_norm: f("model.per_layer_projection_norm.weight")?,
2483                ple_vocab: gc.ple_vocab,
2484                ple_dim: gc.ple_dim,
2485                num_layers: arch.num_layers,
2486                hidden: arch.hidden_size,
2487                rms_eps: arch.rms_norm_eps,
2488                inv_freq_local: crate::attention::rope_inv_freq(
2489                    arch.head_dim,
2490                    arch.rope_local_base_freq.unwrap_or(10_000.0) as f32,
2491                ),
2492                inv_freq_global,
2493                window: arch.sliding_window.unwrap_or(512),
2494                nh: arch.num_attention_heads,
2495                nkv: arch.num_kv_heads,
2496            };
2497            pipeline.g4e = Some(Box::new((globals, g4e_layers)));
2498        }
2499        if let Some(gc) = arch
2500            .g3n
2501            .as_ref()
2502            .filter(|_| !arch.arch_name.starts_with("gemma4"))
2503        {
2504            use crate::g3n::{G3nAltUp, G3nGlobals, G3nLaurel, G3nLayer};
2505            anyhow_like(gc.altup_num_inputs == crate::g3n::ALTUP_N).map_err(|_| {
2506                CmfError::Parse(format!(
2507                    "g3n: altup_num_inputs {} != supported {}",
2508                    gc.altup_num_inputs,
2509                    crate::g3n::ALTUP_N
2510                ))
2511            })?;
2512            let t = |name: &str| load_matrix(model, name, force_f32, ov);
2513            let f = |name: &str| load_f32(model, name, ov).map_err(err);
2514            let mut altup_proj = Vec::new();
2515            let mut altup_unembed = Vec::new();
2516            for i in 0..crate::g3n::ALTUP_N - 1 {
2517                altup_proj.push(t(&format!("model.altup_projections.{i}.weight"))?);
2518                altup_unembed.push(t(&format!("model.altup_unembed_projections.{i}.weight"))?);
2519            }
2520            let first_shared = arch.num_layers.saturating_sub(gc.num_kv_shared_layers);
2521            let sliding_of = |li: usize| {
2522                matches!(
2523                    arch.layer_types.get(li),
2524                    Some(cortiq_core::LayerType::SlidingAttention)
2525                )
2526            };
2527            let mut g3n_layers = Vec::with_capacity(arch.num_layers);
2528            for li in 0..arch.num_layers {
2529                let pfx = format!("model.layers.{li}.");
2530                let shared = li >= first_shared && first_shared > 0;
2531                let share_src = if shared {
2532                    let want = sliding_of(li);
2533                    (0..first_shared).rev().find(|&j| sliding_of(j) == want)
2534                } else {
2535                    None
2536                };
2537                g3n_layers.push(G3nLayer {
2538                    altup: G3nAltUp {
2539                        router_norm: f(&format!("{pfx}altup.router_norm.weight"))?,
2540                        modality_router: t(&format!("{pfx}altup.modality_router.weight"))?,
2541                        prediction_coefs: t(&format!("{pfx}altup.prediction_coefs.weight"))?,
2542                        correction_coefs: t(&format!("{pfx}altup.correction_coefs.weight"))?,
2543                        correct_output_scale: f(&format!("{pfx}altup.correct_output_scale"))?,
2544                    },
2545                    laurel: G3nLaurel {
2546                        left: t(&format!("{pfx}laurel.linear_left.weight"))?,
2547                        right: t(&format!("{pfx}laurel.linear_right.weight"))?,
2548                        post_norm: f(&format!("{pfx}laurel.post_laurel_norm.weight"))?,
2549                    },
2550                    input_norm: f(&format!("{pfx}input_layernorm.weight"))?,
2551                    post_attn_norm: f(&format!("{pfx}post_attention_layernorm.weight"))?,
2552                    pre_ffw_norm: f(&format!("{pfx}pre_feedforward_layernorm.weight"))?,
2553                    post_ffw_norm: f(&format!("{pfx}post_feedforward_layernorm.weight"))?,
2554                    wq: t(&format!("{pfx}self_attn.q_proj.weight"))?,
2555                    wk: if shared {
2556                        None
2557                    } else {
2558                        Some(t(&format!("{pfx}self_attn.k_proj.weight"))?)
2559                    },
2560                    wv: if shared {
2561                        None
2562                    } else {
2563                        Some(t(&format!("{pfx}self_attn.v_proj.weight"))?)
2564                    },
2565                    wo: t(&format!("{pfx}self_attn.o_proj.weight"))?,
2566                    q_norm: f(&format!("{pfx}self_attn.q_norm.weight"))?,
2567                    k_norm: if shared {
2568                        None
2569                    } else {
2570                        Some(f(&format!("{pfx}self_attn.k_norm.weight"))?)
2571                    },
2572                    kv_share_src: share_src,
2573                    sliding: sliding_of(li),
2574                    gate: t(&format!("{pfx}mlp.gate_proj.weight"))?,
2575                    up: t(&format!("{pfx}mlp.up_proj.weight"))?,
2576                    down: t(&format!("{pfx}mlp.down_proj.weight"))?,
2577                    sparsity: gc.activation_sparsity.get(li).copied().unwrap_or(0.0),
2578                    ple_gate: t(&format!("{pfx}per_layer_input_gate.weight"))?,
2579                    ple_proj: t(&format!("{pfx}per_layer_projection.weight"))?,
2580                    post_ple_norm: f(&format!("{pfx}post_per_layer_input_norm.weight"))?,
2581                });
2582            }
2583            let hd = arch.head_dim;
2584            let globals = G3nGlobals {
2585                altup_proj,
2586                altup_unembed,
2587                ple_embed: t("model.embed_tokens_per_layer.weight")?,
2588                ple_model_proj: t("model.per_layer_model_projection.weight")?,
2589                ple_norm: f("model.per_layer_projection_norm.weight")?,
2590                ple_vocab: gc.ple_vocab,
2591                ple_dim: gc.ple_dim,
2592                num_layers: arch.num_layers,
2593                hidden: arch.hidden_size,
2594                rms_eps: arch.rms_norm_eps,
2595                inv_freq_local: crate::attention::rope_inv_freq(
2596                    hd,
2597                    arch.rope_local_base_freq.unwrap_or(10_000.0) as f32,
2598                ),
2599                inv_freq_global: crate::attention::rope_inv_freq(hd, arch.rope_theta as f32),
2600                window: arch.sliding_window.unwrap_or(512),
2601            };
2602            pipeline.g3n = Some(Box::new((globals, g3n_layers)));
2603        }
2604        // Dory: its own stack (`dory`), selected by the arch record.
2605        if arch.dory.is_some() {
2606            let m = crate::dory::Dory::from_model(model).map_err(CmfError::Parse)?;
2607            pipeline.dory = Some(Box::new((m, crate::dory::DoryState::default())));
2608        }
2609        // DeepSeek-V4.1: its own stack, selected by the preserved source
2610        // configuration. The generic layer loop cannot represent shared
2611        // CED/CSA2 state or native Engram tables, so loading failure is
2612        // fatal instead of falling back to an unrelated attention layout.
2613        if arch.arch_name == "deepseek_v41" {
2614            let source = arch.deepseek_v41.as_ref().ok_or_else(|| {
2615                CmfError::Parse("deepseek_v41: missing preserved source config".into())
2616            })?;
2617            let (cfg, n_layers) = crate::dsv41::Dsv41Cfg::from_source(source, &arch)
2618                .map_err(|e| CmfError::Parse(format!("deepseek_v41: {e}")))?;
2619            let token_map = crate::dsv41::token_map_from_model(model, cfg.vocab);
2620            let (g, dl, hash) = crate::dsv41::load(model, &cfg, n_layers, token_map)
2621                .map_err(|e| CmfError::Parse(format!("deepseek_v41: {e}")))?;
2622            let st = crate::dsv41::Dsv41State::new(&cfg, hash);
2623            // Vision tensors are optional in text-only exports, but when
2624            // present they stay mmap-backed through the dedicated tower.
2625            // Do not make a text-only CMF fail merely because its source
2626            // config still carries the multimodal section.
2627            if let Ok(vision_cfg) = crate::dsv41_vision::VisionConfig::from_source(source) {
2628                if vision_cfg.vision_enabled()
2629                    && model.tensor("vision.patch_embed.proj.weight").is_some()
2630                {
2631                    pipeline.dsv41_vision = Some(
2632                        crate::dsv41_vision::VisionModel::from_model(model, vision_cfg)
2633                            .map_err(|e| CmfError::Parse(format!("deepseek_v41 vision: {e}")))?,
2634                    );
2635                }
2636            }
2637            tracing::info!(
2638                "deepseek_v41: loaded {} layers, {} KV sources, {} index sources, {} Engram layers; experts remain mmap-backed",
2639                dl.len(),
2640                cfg.kv_sources.len(),
2641                cfg.index_sources.len(),
2642                cfg.engram_layers.len()
2643            );
2644            pipeline.dsv41 = Some(Box::new((g, dl, cfg, st)));
2645        }
2646        // DeepSeek-V4: its own stack, selected by the arch name the
2647        // converter wrote. Loading failure is fatal rather than a silent
2648        // fallback — the generic loop cannot represent this model at all,
2649        // so a fallback would decode noise.
2650        if arch.arch_name == "deepseek_v4" {
2651            let moe = arch
2652                .moe
2653                .as_ref()
2654                .ok_or_else(|| CmfError::Parse("deepseek_v4: no moe config".into()))?;
2655            let cfg = crate::dsv4::Dsv4Cfg {
2656                dim: arch.hidden_size,
2657                n_heads: arch.num_attention_heads,
2658                head_dim: arch.head_dim,
2659                // The rope tail: `partial_rotary_factor` carries it when the
2660                // conversion recorded it (rd/head_dim), which the tensors
2661                // cannot reveal. Files converted before that carry 1.0,
2662                // meaning "unset" here rather than "rotate everything" —
2663                // for those the release's 64 stands in, which is what they
2664                // were converted from.
2665                rope_head_dim: if arch.partial_rotary_factor < 1.0 {
2666                    (((arch.head_dim as f32 * arch.partial_rotary_factor) as usize) & !1)
2667                        .clamp(2, arch.head_dim)
2668                } else {
2669                    64.min(arch.head_dim)
2670                },
2671                // The LoRA ranks and the group count ARE visible in the
2672                // weights, and reading them there means a re-tuned
2673                // checkpoint loads without touching this code.
2674                q_lora_rank: 0,
2675                o_lora_rank: 0,
2676                // Derived below from wo_a's shape — the attention output is
2677                // n_heads*head_dim wide and wo_a takes one group of it per
2678                // row block, so groups = width / wo_a.cols(). A pinned 8 is
2679                // right for the release and wrong for anything else, which
2680                // is exactly what made a toy checkpoint impossible to
2681                // compare against the reference.
2682                o_groups: 8,
2683                hc_mult: 4,
2684                hc_sinkhorn_iters: 20,
2685                hc_eps: 1e-6,
2686                norm_eps: arch.rms_norm_eps as f32,
2687                n_routed_experts: moe.num_experts,
2688                top_k: moe.top_k,
2689                moe_inter: moe.moe_intermediate_size,
2690                route_scale: moe.routed_scaling_factor.unwrap_or(1.0),
2691                // config.json's `swiglu_limit`, which the header has no
2692                // field for. The release ships 10.0; a checkpoint that
2693                // retunes it would need this read from the config, so it
2694                // sits next to the other pinned constants rather than
2695                // hiding inside the expert.
2696                swiglu_limit: 10.0,
2697                window: arch.sliding_window.unwrap_or(128),
2698                index_topk: 512,
2699                vocab: arch.vocab_size,
2700            };
2701            let (g, dl) = crate::dsv4::load(model, &cfg, arch.num_layers)
2702                .map_err(|e| CmfError::Parse(format!("deepseek_v4: {e}")))?;
2703            // Read the ranks off the weights that define them: wq_a's
2704            // rows ARE q_lora_rank, and wo_b's columns are groups x
2705            // o_lora_rank. A header field could disagree with the file;
2706            // these cannot.
2707            let mut cfg = cfg;
2708            if let Some(l0) = dl.first() {
2709                cfg.q_lora_rank = l0.wq_a.rows();
2710                let attn_width = arch.num_attention_heads * arch.head_dim;
2711                if l0.wo_a.cols() > 0 && attn_width % l0.wo_a.cols() == 0 {
2712                    cfg.o_groups = (attn_width / l0.wo_a.cols()).max(1);
2713                }
2714                cfg.o_lora_rank = l0.wo_b.cols() / cfg.o_groups.max(1);
2715                cfg.hc_mult = (l0.hc_attn_fn.len() / l0.hc_attn_base.len().max(1)) / cfg.dim.max(1);
2716                if cfg.hc_mult == 0 {
2717                    cfg.hc_mult = 4;
2718                }
2719            }
2720            // RoPE rides only the last `rope_head_dim` of each head, and the
2721            // reference builds its frequencies over THAT width — not over
2722            // head_dim, which is 512 here. The generic path above sized them
2723            // by head_dim, giving 1/base^(2i/512) where 1/base^(2i/64) is
2724            // wanted: every position rotated by the wrong angle.
2725            //
2726            // YaRN is applied unconditionally by the reference (its guard is
2727            // `original_seq_len > 0`, not the sequence length), so it belongs
2728            // in these frequencies too. Older configs spell the key `type`
2729            // rather than `rope_type`; when the header carries no profile the
2730            // release's own numbers stand in, which is better than silently
2731            // decoding with unscaled frequencies.
2732            let (yf, yo, ybf, ybs) = match &arch.yarn {
2733                Some(y) => (
2734                    y.factor,
2735                    y.original_max_position_embeddings,
2736                    y.beta_fast,
2737                    y.beta_slow,
2738                ),
2739                None => {
2740                    tracing::warn!(
2741                        "deepseek_v4: the header carries no YaRN profile — \
2742                         falling back to the release's (factor 16, original \
2743                         65536, beta 32/1). Re-converting with a build that \
2744                         reads rope_scaling.type would make this exact."
2745                    );
2746                    (16.0, 65536, 32.0, 1.0)
2747                }
2748            };
2749            pipeline.inv_freq = std::sync::Arc::new(crate::attention::yarn_inv_freq(
2750                cfg.rope_head_dim,
2751                arch.rope_theta as f32,
2752                yf,
2753                yo,
2754                ybf,
2755                ybs,
2756            ));
2757            // Keep the working set resident. Everything but the routed
2758            // experts is touched by every token, and of the experts only the
2759            // ones the task actually routes to — the page cache cannot know
2760            // that and evicts by age instead.
2761            if let Ok(stats) = std::env::var("CMF_MOE_PIN") {
2762                let cover = std::env::var("CMF_MOE_PIN_COVER")
2763                    .ok()
2764                    .and_then(|v| v.parse::<f64>().ok())
2765                    .filter(|&c| c > 0.0 && c <= 1.0)
2766                    .unwrap_or(0.95);
2767                let hot = crate::pin::hot_experts(&stats, cover);
2768                let mut names: Vec<String> = Vec::new();
2769                for e in &model.tensors {
2770                    let is_expert = e.name.contains(".mlp.experts.");
2771                    if !is_expert {
2772                        names.push(e.name.clone()); // skeleton: always hot
2773                    }
2774                }
2775                let mut kept_experts = 0usize;
2776                if let Some(hot) = &hot {
2777                    for (li, experts) in hot {
2778                        for e in experts {
2779                            for w in ["gate_proj", "up_proj", "down_proj"] {
2780                                names.push(format!("model.layers.{li}.mlp.experts.{e}.{w}.weight"));
2781                            }
2782                            kept_experts += 1;
2783                        }
2784                    }
2785                }
2786                let r = crate::pin::pin_tensors(model, &names);
2787                tracing::info!(
2788                    "pinned {:.1} GB ({} tensors, hot experts {kept_experts},                      coverage {cover}); limit {}",
2789                    r.bytes as f64 / 1e9,
2790                    r.tensors,
2791                    r.limit
2792                        .map(|l| format!("{:.1} GB", l as f64 / 1e9))
2793                        .unwrap_or_else(|| "unknown".into())
2794                );
2795                if r.skipped > 0 {
2796                    tracing::warn!("tensors left unpinned: {}", r.skipped);
2797                }
2798            }
2799            let st = crate::dsv4::Dsv4State::new(arch.num_layers);
2800            // The speculation stack, if the file carries one. Reading it is
2801            // metadata only — the expert weights stay in the mapping until a
2802            // draft actually runs — so it costs nothing to know it is there.
2803            let depth = std::env::var("CMF_DSV4_MTP_DEPTH")
2804                .ok()
2805                .and_then(|v| v.parse::<usize>().ok())
2806                .unwrap_or(3);
2807            pipeline.dsv4_mtp = crate::dsv4::load_mtp(model, &cfg, depth);
2808            // Before any trunk pack is built: leave the draft its VRAM.
2809            crate::dsv4::dspark_reserve_note(&pipeline.dsv4_mtp, &cfg, &dl);
2810            pipeline.dsv4 = Some(Box::new((g, dl, cfg, st)));
2811        }
2812        pipeline.short_conv_cfg = short_conv_cfg;
2813        pipeline.mtp = mtp;
2814        // Beside sliding layers only where it was measured (Aion); Mellum's
2815        // full layers keep their scale in the rotation.
2816        fold_yarn_scale_into_qk_norms(&mut pipeline, arch.arch_name == "aion_instruct");
2817        // A DFlash block drafter beside the file drafts the rounds when asked to.
2818        if std::env::var("CMF_DFLASH").as_deref() == Ok("1") {
2819            match crate::dflash::Drafter::for_target(model) {
2820                Some(Ok(d)) => {
2821                    tracing::info!("DFlash drafter: {} layers on the trunk's layers {:?}, blocks of {}", d.g.layers, d.g.taps, d.g.block);
2822                    #[cfg(feature = "gpu")]
2823                    let _ = d.dev_ready();
2824                    pipeline.dflash = Some(Box::new(d));
2825                    pipeline.dflash_solo = pipeline.mtp.is_none();
2826                }
2827                Some(Err(e)) => tracing::warn!("DFlash sidecar ignored: {e}"),
2828                None => tracing::warn!("CMF_DFLASH=1, and {} is not there", crate::dflash::sidecar_path(&model.path).display()),
2829            }
2830        }
2831        if arch.arch_name == "mimo_v2" {
2832            pipeline.mimo_mtp = crate::pipeline::mimo_mtp::load_for(model, &arch)?;
2833        }
2834        // Spark-X2.5's sliding layers (27 of the 4B's 36, window 512) and
2835        // LFM3's (5 of 11 attention layers, window 256) keep only the rows
2836        // their window can still read: 64 rows of rollback slack, the cut
2837        // on a 64-row grid so the Metal chunk GEMMs keep their K-tile
2838        // partition (see `LayerKvCache::trim_window`). Other windowed
2839        // architectures keep every row until one is measured.
2840        // Off with a speculation head (its verify paths read row counts as
2841        // positions) and under CMF_ATTN_DUMP (the dump header assumes row
2842        // = position). CMF_SWA_TRIM=0 turns it off for an A/B.
2843        // Aion-2.3B (21 of 28 layers, window 2048): at 16 384 tokens the host
2844        // held 3.77 GB of rows on a MacBook Air, 2.9 GB of them past any window.
2845        pipeline.swa_trim = (matches!(arch.arch_name.as_str(), "spark2_5" | "lfm3" | "aion_instruct")
2846            && pipeline.swa.is_some()
2847            && pipeline.mtp.is_none()
2848            && pipeline.mimo_mtp.is_none()
2849            && pipeline.dsv4_mtp.is_empty()
2850            && std::env::var_os("CMF_ATTN_DUMP").is_none()
2851            && std::env::var("CMF_SWA_TRIM").as_deref() != Ok("0"))
2852            .then_some((64, 64));
2853        // Aion on the wgpu graphs: its 7 full layers on the uniform arms.
2854        pipeline.uniform_full_layers = arch.arch_name == "aion_instruct"
2855            && std::env::var("CMF_MIXED_GEOM").as_deref() != Ok("0");
2856        // Spark-X2.6's KV mirrors in f16 on Metal: at 14 000 tokens a token read 1.03 GB of f32
2857        // rows on the M4 (`CMF_METAL_KV_F16=0` keeps f32).
2858        #[cfg(target_os = "macos")]
2859        if matches!(arch.arch_name.as_str(), "spark2_5" | "aion_instruct") {
2860            crate::gpu_metal::set_kv_f16_default(true);
2861        }
2862        // Spark-X2.6-4B q8_2f on the M4: an 8..31-token prompt prefills in
2863        // ~105 ms on the chunk graph against 0.5-1.2 s on the host layer walk
2864        // (shorter prompts keep their faster per-position path).
2865        // CMF_CHUNK_MIN_B overrides for every model.
2866        pipeline.chunk_min_rows = std::env::var("CMF_CHUNK_MIN_B")
2867            .ok()
2868            .and_then(|v| v.parse().ok())
2869            .unwrap_or(if arch.arch_name == "spark2_5" { 8 } else { 32 });
2870        pipeline.install_dynamic_routing(model, false);
2871        // Record the load-time overlay so a later set_active_skill(None)
2872        // correctly reverts it (the union-diff assumes dyn_active mirrors
2873        // the live overlay). Blend loads have no single index to revert.
2874        match ov {
2875            Overlay::One(sid) => {
2876                pipeline.dyn_active = model.header.skills.iter().position(|s| &s.id == sid);
2877            }
2878            Overlay::Blend(_) => pipeline.dyn_blend_loaded = true,
2879            Overlay::None => {}
2880        }
2881        // B1: apply the measured confidence-calibration temperature, if the
2882        // file carries one (softmax(logits / T) for reported confidence).
2883        if let Some(c) = &model.header.calibration {
2884            pipeline.set_calib_temp(c.temperature);
2885        }
2886        // Versioned state wire: every layer carries the operator identity
2887        // so a peer holding another operator is refused, not guessed at.
2888        let identity = arch
2889            .linear_core_identity()
2890            .and_then(|v| serde_json::to_vec(&v).ok())
2891            .map(|b| cortiq_core::hash64(&b))
2892            .unwrap_or(0);
2893        pipeline.install_wire_identity(identity);
2894        // Natively bounded anchor: the file's operator, installed from the
2895        // header (rings sized once, not per prompt). The file governs —
2896        // a post-hoc O(1) knob on such a file is an error, not a warning.
2897        if let Some(ac) = &arch.anchor_core {
2898            pipeline.install_bounded(ac).map_err(CmfError::Parse)?;
2899            let why = pipeline.o1_refusal().unwrap_or_default();
2900            let mut knobs: Vec<String> = std::env::vars()
2901                .filter(|(k, v)| {
2902                    (k == "CMF_O1" && !(v == "off" || v == "0")) || k.starts_with("CMF_O1_")
2903                })
2904                .map(|(k, _)| k)
2905                .collect();
2906            knobs.sort();
2907            if !knobs.is_empty() {
2908                return Err(CmfError::Parse(format!("{why} (set: {})", knobs.join(", "))));
2909            }
2910            if model
2911                .header
2912                .provenance
2913                .as_ref()
2914                .and_then(|p| p.get("o1_attn"))
2915                .is_some()
2916            {
2917                return Err(CmfError::Parse(format!(
2918                    "{why} (the header carries a provenance.o1_attn hint)"
2919                )));
2920            }
2921            return Ok(pipeline);
2922        }
2923        // O(1) Nyström attention (runtime-level, no format change):
2924        // env CMF_O1 decides; unset falls through to the converter hint
2925        // in header.provenance.o1_attn (`cortiq convert --o1`), and
2926        // CMF_O1=off force-disables even the hint. CLI flags override
2927        // later via set_o1().
2928        // A genome's attention operator is its arch (hashed into the
2929        // trunk); a provenance hint is not part of the genome and must not
2930        // switch the backbone to Nyström (NF-6 — core refuses the hint on
2931        // a GENOME file at open; this keeps the loader fail-closed too).
2932        let genome_hint = model.header.genome.is_some()
2933            && model
2934                .header
2935                .provenance
2936                .as_ref()
2937                .and_then(|p| p.get("o1_attn"))
2938                .is_some();
2939        if genome_hint {
2940            return Err(CmfError::Parse(
2941                "genome file with a provenance.o1_attn hint: the trunk's attention operator is \
2942                 set by the genome's arch only — refusing"
2943                    .into(),
2944            ));
2945        }
2946        let o1_env = crate::nystrom::o1_from_env();
2947        // A turbo file: the far field comes on for long prompts only, so nothing is set now.
2948        // The Flash-Next device path reads the header itself (`qwen4_o1`): the generic seal
2949        // has no layers of its own there.
2950        if matches!(o1_env, crate::nystrom::O1Env::Unset) && pipeline.qwen4_exp.is_none() {
2951            let hint = model.header.provenance.as_ref().and_then(|p| p.get("o1_turbo"));
2952            if let Some(h) = hint {
2953                let field = |k: &str| h.get(k).and_then(|v| v.as_u64()).map(|v| v as usize);
2954                let weights = load_f32(model, "o1.exact.weights", &Overlay::None).unwrap_or_default();
2955                if let (Some(cfg), Some(seal), Some(rows)) = (crate::nystrom::O1Cfg::from_json(h), field("seal"), field("exact_rows")) {
2956                    pipeline.o1_turbo = Some(crate::pipeline::O1Turbo {
2957                        cfg,
2958                        seal: crate::pipeline::o1_seal_for_card(seal, model.tensors.iter().map(|e| e.nbytes).sum()),
2959                        exact: crate::dory::ExactRows { weights: std::sync::Arc::new(weights), budget: rows },
2960                    });
2961                }
2962            }
2963        }
2964        let o1 = match o1_env {
2965            crate::nystrom::O1Env::Off => None,
2966            crate::nystrom::O1Env::On(cfg) => Some(cfg),
2967            crate::nystrom::O1Env::Unset => model
2968                .header
2969                .provenance
2970                .as_ref()
2971                .and_then(|p| p.get("o1_attn"))
2972                .and_then(crate::nystrom::O1Cfg::from_json),
2973        };
2974        if o1.is_some() {
2975            if pipeline.attn_softcap > 0.0 {
2976                return Err(CmfError::Parse(
2977                    "--o1 with attention-logit soft-capping (Gemma-2) is not supported: \
2978                     the streaming operator has no capped-score form"
2979                        .into(),
2980                ));
2981            }
2982            pipeline.set_o1(o1);
2983        }
2984        Ok(pipeline)
2985    }
2986
2987    /// Record per-skill dynamic-routing metadata: which FFN layers each
2988    /// skill actually replaces (derived from the tensors present, not
2989    /// the meta `layers` field), and whether the skill is eligible for
2990    /// cheap dynamic switching (FFN-only). Called once at load.
2991    pub(crate) fn install_dynamic_routing(&mut self, model: &Arc<CmfModel>, force_f32: bool) {
2992        self.model = Some(model.clone());
2993        self.dyn_force_f32 = force_f32;
2994        let mut per_skill = Vec::with_capacity(model.header.skills.len());
2995        for sk in &model.header.skills {
2996            // A lookup record replaces nothing: its tensors are the key →
2997            // card table (u64/u32/u8), never weights. No lane, no switch.
2998            if sk.kind.as_deref() == Some(cortiq_core::knowledge::skill_kind::LOOKUP) {
2999                per_skill.push(None);
3000                continue;
3001            }
3002            let mut ffn_layers = std::collections::BTreeSet::new();
3003            let mut non_ffn = false;
3004            let prefix = format!("skill.{}.", sk.id);
3005            for t in model.skill_tensors(&sk.id) {
3006                let rel = &t.name[prefix.len()..]; // e.g. model.layers.20.mlp.down_proj.weight
3007                let toks: Vec<&str> = rel.split('.').collect();
3008                if toks.len() >= 5 && toks[0] == "model" && toks[1] == "layers" && toks[3] == "mlp"
3009                {
3010                    if let Ok(li) = toks[2].parse::<usize>() {
3011                        ffn_layers.insert(li);
3012                        continue;
3013                    }
3014                }
3015                non_ffn = true; // replaces attention / embed / lm_head
3016            }
3017            if non_ffn {
3018                tracing::warn!(
3019                    "skill '{}' replaces non-FFN tensors — excluded from dynamic \
3020                     routing (static overlay still works)",
3021                    sk.id
3022                );
3023                per_skill.push(None);
3024            } else {
3025                per_skill.push(Some(ffn_layers.into_iter().collect::<Vec<_>>()));
3026            }
3027        }
3028        self.dyn_skill_layers = per_skill;
3029    }
3030
3031    /// Switch the overlaid skill for subsequent forwards (dynamic
3032    /// routing). `idx` = index into model.header.skills; None = backbone.
3033    /// Rebuilds the FFN of the union of the old and new skill's touched
3034    /// layers with the new overlay — tensor-source indirection made
3035    /// dynamic. Cheap: Mapped tensors are re-resolved mmap pointers.
3036    /// Result is bit-identical to loading the pipeline with that skill.
3037    ///
3038    /// Asking for the skill that is already active is a true no-op: the
3039    /// weights do not change, so the sequence state (KV, rings, recurrent
3040    /// state, the prefix-reuse key) stays — clearing it here used to wipe
3041    /// a live conversation on every idempotent call. A real change
3042    /// rebuilds the touched FFNs first (all or nothing: on an error the
3043    /// old overlay and state are untouched), then invalidates every state
3044    /// the old weights produced, including `kv_prefix`.
3045    pub fn set_active_skill(&mut self, idx: Option<usize>) -> Result<(), CmfError> {
3046        if self.dyn_active == idx {
3047            return Ok(());
3048        }
3049        let model = self.model.clone().ok_or_else(|| {
3050            CmfError::Parse("dynamic routing needs a model-backed pipeline".into())
3051        })?;
3052        let mut union: std::collections::BTreeSet<usize> = std::collections::BTreeSet::new();
3053        if let Some(old) = self.dyn_active {
3054            if let Some(Some(ls)) = self.dyn_skill_layers.get(old) {
3055                union.extend(ls.iter().copied());
3056            }
3057        }
3058        let new_id: Option<String> = match idx {
3059            Some(n) => match self.dyn_skill_layers.get(n) {
3060                Some(Some(ls)) => {
3061                    union.extend(ls.iter().copied());
3062                    Some(model.header.skills[n].id.clone())
3063                }
3064                _ => {
3065                    return Err(CmfError::Parse(format!(
3066                        "skill index {n} not dynamic-eligible"
3067                    )));
3068                }
3069            },
3070            None => None,
3071        };
3072        let ov = match &new_id {
3073            Some(s) => Overlay::One(s),
3074            None => Overlay::None,
3075        };
3076        let arch = model.arch();
3077        let mut rebuilt = Vec::with_capacity(union.len());
3078        for li in union {
3079            rebuilt.push((
3080                li,
3081                build_layer_ffn(&model, arch, li, self.dyn_force_f32, &ov)?,
3082            ));
3083        }
3084        for (li, ffn) in rebuilt {
3085            self.weights.layers[li].ffn = ffn;
3086        }
3087        // Overlay swap changed weights → every cached state is stale.
3088        self.invalidate_for_weight_change();
3089        self.dyn_active = idx;
3090        Ok(())
3091    }
3092}
3093
3094/// Fixed per-sequence state a file declares, from its header alone (no
3095/// weights loaded): bytes of bounded-anchor rings, bytes of recurrent
3096/// vectors (S + conv rings), and how many layers still hold a growing
3097/// per-position KV. A strictly-O(1) file has `growing_layers == 0`.
3098/// YaRN's cos/sin scale (`attention_factor`) moved into the q/k norms.
3099///
3100/// RoPE is linear, so `s·R(q̂·w)` on the rotary channels equals `R(q̂·(s·w))`:
3101/// on a model whose q/k norms run before RoPE and whose layers share one
3102/// rotary profile, the scale becomes those channels' norm gain (`s·(1+w) − 1`
3103/// for the `(1+w)` style) and `rope_scale` drops to 1. Every backend then reads
3104/// the same numbers, and the device graphs' uniform attention arms (which
3105/// decline a scale of their own) carry the model. SenseNova-Loop-9B: YaRN
3106/// factor 2 on 64 rotary channels of 256, scale 1.0693, every length.
3107/// `CMF_YARN_FOLD=0` keeps the scale in the rotation.
3108pub(crate) fn fold_yarn_scale_into_qk_norms(p: &mut crate::pipeline::Pipeline, beside_sliding: bool) {
3109    let s = p.rope_scale;
3110    // Sliding layers with a scale of their own of 1 (Aion: plain RoPE on the
3111    // 21 window layers, YaRN ×16 on the 7 full ones) take no part: the scale
3112    // folds into the full layers' norms alone, the local tables stay. Only
3113    // for a stack that asked (`beside_sliding`): any other sliding stack
3114    // keeps the scale in the rotation, as before.
3115    let sliding = p.sliding_layers.is_some() || p.swa.is_some() || p.inv_freq_local.is_some();
3116    if s == 1.0
3117        || p.qk_norm_after_rope
3118        || p.rope_scale_local != 1.0
3119        || (sliding && (!beside_sliding || p.mtp.is_some()))
3120        || p.global_attn.is_some()
3121        || p.inv_freq_global.is_some()
3122        || std::env::var("CMF_YARN_FOLD").as_deref() == Ok("0")
3123    {
3124        return;
3125    }
3126    let local: Vec<bool> = (0..p.weights.layers.len())
3127        .map(|li| match &p.sliding_layers {
3128            Some(m) => m.get(li).copied().unwrap_or(false),
3129            None => p.swa.is_some_and(|(_, pat)| pat != usize::MAX && (li + 1) % pat.max(1) != 0),
3130        })
3131        .collect();
3132    let (rd, hd, gemma) = (p.rotary_dim.min(p.head_dim), p.head_dim, p.norm_style == cortiq_core::NormStyle::Gemma);
3133    let norms_ok = |a: &AttnKind| match a {
3134        AttnKind::Full { q_norm: Some(q), k_norm: Some(k), .. } => q.len() == hd && k.len() == hd,
3135        AttnKind::Full { .. } => false,
3136        _ => true,
3137    };
3138    let full_layers = p.weights.layers.iter().filter(|l| matches!(l.attn, AttnKind::Full { .. })).count();
3139    if full_layers == 0
3140        || !p.weights.layers.iter().all(|l| norms_ok(&l.attn))
3141        || p.mtp.as_ref().is_some_and(|m| !norms_ok(&m.layer.attn))
3142    {
3143        return;
3144    }
3145    let fold_attn = |a: &mut AttnKind| {
3146        if let AttnKind::Full { q_norm: Some(q), k_norm: Some(k), .. } = a {
3147            fold_rope_scale_gain(q, rd, s, gemma);
3148            fold_rope_scale_gain(k, rd, s, gemma);
3149        }
3150    };
3151    let mut folded = 0;
3152    for (li, l) in p.weights.layers.iter_mut().enumerate() {
3153        if !local[li] {
3154            fold_attn(&mut l.attn);
3155            folded += 1;
3156        }
3157    }
3158    if let Some(m) = p.mtp.as_mut() {
3159        fold_attn(&mut m.layer.attn);
3160    }
3161    p.rope_scale = 1.0;
3162    let _ = full_layers;
3163    tracing::info!("YaRN scale {s} folded into the q/k norms of {folded} layers ({rd} rotary channels of {hd})");
3164}
3165
3166/// One q/k norm's gain with a RoPE cos/sin scale `s` folded into its first `rd`
3167/// (rotary) channels: `s·w` for the `x̂·w` style, `s·(1+w) − 1` for `x̂·(1+w)`.
3168pub(crate) fn fold_rope_scale_gain(w: &mut [f32], rd: usize, s: f32, gemma: bool) {
3169    for v in w.iter_mut().take(rd) {
3170        *v = if gemma { s * (1.0 + *v) - 1.0 } else { s * *v };
3171    }
3172}
3173
3174#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
3175pub struct PerSequenceState {
3176    pub bounded_bytes: usize,
3177    pub recurrent_bytes: usize,
3178    pub growing_layers: usize,
3179}
3180
3181pub fn per_sequence_state_bytes(model: &CmfModel) -> Result<PerSequenceState, String> {
3182    let arch = model.arch();
3183    let f = std::mem::size_of::<f32>();
3184    let mut st = PerSequenceState::default();
3185    let need = |v: Option<usize>, name: &str| {
3186        v.ok_or_else(|| format!("linear core needs arch.{name}"))
3187    };
3188    for li in 0..arch.num_layers {
3189        match arch.layer_types.get(li) {
3190            Some(LayerType::BoundedAttention) => {
3191                let ac = arch
3192                    .anchor_core
3193                    .as_ref()
3194                    .ok_or("BoundedAttention layer without anchor_core")?;
3195                st.bounded_bytes += ac.ring_state_elems(arch.num_kv_heads, arch.head_dim) * f;
3196            }
3197            Some(LayerType::LinearAttention) => {
3198                let lc = arch
3199                    .linear_core
3200                    .as_ref()
3201                    .ok_or("LinearAttention layer without linear_core")?;
3202                let elems = match lc.kind.as_str() {
3203                    "gated_delta_net" => GdnCfg {
3204                        num_v_heads: lc.num_heads,
3205                        num_k_heads: need(arch.linear_num_key_heads, "linear_num_key_heads")?,
3206                        key_head_dim: need(arch.linear_key_head_dim, "linear_key_head_dim")?,
3207                        value_head_dim: lc.value_head_dim,
3208                        conv_kernel: need(arch.linear_conv_kernel_dim, "linear_conv_kernel_dim")?,
3209                        hidden_size: arch.hidden_size,
3210                        rms_eps: arch.rms_norm_eps,
3211                        output_gate_sigmoid: false,
3212                    }
3213                    .state_len(),
3214                    _ => {
3215                        let nphase = need(lc.nphase, "linear_core.nphase")?;
3216                        let mut n = lc.num_heads * 2 * nphase * lc.value_head_dim;
3217                        if let Some(c) = model.tensor(&format!("model.layers.{li}.vmf_attn.conv1d.weight")) {
3218                            if c.shape.len() == 3 && c.shape[2] >= 2 {
3219                                n += (c.shape[2] - 1) * arch.hidden_size;
3220                            }
3221                        }
3222                        n
3223                    }
3224                };
3225                st.recurrent_bytes += elems * f;
3226            }
3227            Some(LayerType::ShortConv) => {
3228                let k = need(arch.linear_conv_kernel_dim, "linear_conv_kernel_dim")?;
3229                st.recurrent_bytes += ShortConvCfg {
3230                    hidden_size: arch.hidden_size,
3231                    kernel: k,
3232                }
3233                .state_len()
3234                    * f;
3235            }
3236            Some(LayerType::Kda) => {
3237                st.recurrent_bytes += crate::linear_core::KdaCfg {
3238                    num_heads: need(arch.linear_num_key_heads, "linear_num_key_heads")?,
3239                    head_k_dim: need(arch.linear_key_head_dim, "linear_key_head_dim")?,
3240                    head_v_dim: need(arch.linear_value_head_dim, "linear_value_head_dim")?,
3241                    conv_kernel: need(arch.linear_conv_kernel_dim, "linear_conv_kernel_dim")?,
3242                    hidden_size: arch.hidden_size,
3243                    rms_eps: arch.rms_norm_eps,
3244                }
3245                .state_len()
3246                    * f;
3247            }
3248            _ => st.growing_layers += 1,
3249        }
3250    }
3251    Ok(st)
3252}
3253
3254#[cfg(test)]
3255mod tests {
3256    use super::*;
3257
3258    /// The YaRN fold: a norm with the scale in its rotary channels, then RoPE
3259    /// at scale 1, equals the norm, then RoPE at the scale — for both norm
3260    /// styles, on a partial-rotary head (SenseNova-Loop: 64 of 256, s 1.0693).
3261    #[test]
3262    fn yarn_scale_fold_matches_scaled_rope() {
3263        let (hd, rd, s) = (256usize, 64usize, 1.069_314_7_f32);
3264        let inv = crate::attention::yarn_inv_freq(rd, 1e7, 2.0, 262_144, 32.0, 1.0);
3265        let x: Vec<f32> = (0..hd).map(|i| ((i * 37 % 101) as f32 - 50.0) * 0.03).collect();
3266        let w: Vec<f32> = (0..hd).map(|i| 0.4 + ((i * 13 % 17) as f32) * 0.05).collect();
3267        for style in [cortiq_core::NormStyle::Qwen, cortiq_core::NormStyle::Gemma] {
3268            let gemma = style == cortiq_core::NormStyle::Gemma;
3269            for pos in [0usize, 7, 4099, 300_000] {
3270                let mut a = x.clone();
3271                crate::attention::rmsnorm_head(&mut a, &w, 1e-6, style);
3272                crate::attention::rope_rotate_scaled(&mut a[..rd], pos, &inv, s);
3273                let mut wf = w.clone();
3274                fold_rope_scale_gain(&mut wf, rd, s, gemma);
3275                let mut b = x.clone();
3276                crate::attention::rmsnorm_head(&mut b, &wf, 1e-6, style);
3277                crate::attention::rope_rotate_scaled(&mut b[..rd], pos, &inv, 1.0);
3278                let d = a.iter().zip(&b).map(|(p, q)| (p - q).abs()).fold(0.0f32, f32::max);
3279                assert!(d < 2e-5, "{style:?} pos {pos}: max |d| {d}");
3280                assert_eq!(a[rd..], b[rd..], "{style:?}: the pass-through channels moved");
3281            }
3282        }
3283    }
3284
3285    fn dense_mtp_ffn(width: usize) -> FfnKind {
3286        const HIDDEN: usize = 4;
3287        let matrix = |rows, cols| QTensor::from_f32(vec![0.0; rows * cols], rows, cols);
3288        FfnKind::Dense(DenseFfn {
3289            gate_proj: matrix(width, HIDDEN),
3290            up_proj: matrix(width, HIDDEN),
3291            down_proj: matrix(HIDDEN, width),
3292            act: crate::pipeline::Act::Silu,
3293            down_t: None,
3294            segs: Vec::new(),
3295        })
3296    }
3297
3298    fn mtp_config(widths: Vec<usize>) -> cortiq_core::MtpConfig {
3299        cortiq_core::MtpConfig {
3300            num_layers: 1,
3301            ffn_intermediate_sizes: Some(widths),
3302            share_lm_head: true,
3303            share_embed: true,
3304        }
3305    }
3306
3307    #[test]
3308    fn generic_mtp_declared_width_is_checked_against_its_local_ffn() {
3309        assert!(validate_generic_mtp_ffn_width(&mtp_config(vec![6]), &dense_mtp_ffn(6)).is_ok());
3310
3311        let err = validate_generic_mtp_ffn_width(&mtp_config(vec![5]), &dense_mtp_ffn(6))
3312            .unwrap_err()
3313            .to_string();
3314        assert!(err.contains("ffn_intermediate_sizes[0]=5"), "{err}");
3315        assert!(err.contains("has 6 rows"), "{err}");
3316
3317        let err = validate_generic_mtp_ffn_width(&mtp_config(vec![6, 6]), &dense_mtp_ffn(6))
3318            .unwrap_err()
3319            .to_string();
3320        assert!(err.contains("has 2 entries, expected 1"), "{err}");
3321    }
3322}