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