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