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/// Tensor source selector (spec §9): backbone, one skill's overlay, or
29/// a soft superposition of top-m skills (claim 14 working tensors).
30pub enum Overlay<'a> {
31    None,
32    One(&'a str),
33    /// (skill_id, weight); weights sum to 1 (softmax(−E/T) upstream).
34    Blend(&'a [(String, f32)]),
35}
36
37impl Overlay<'_> {
38    fn blend_touches(&self, model: &CmfModel, name: &str) -> bool {
39        match self {
40            Overlay::Blend(list) => list
41                .iter()
42                .any(|(sid, _)| model.tensor(&format!("skill.{sid}.{name}")).is_some()),
43            _ => false,
44        }
45    }
46}
47
48fn dequant_by_name(model: &CmfModel, name: &str) -> Result<Vec<f32>, String> {
49    let entry = model
50        .tensor(name)
51        .ok_or_else(|| format!("tensor '{name}' not found in CMF directory"))?;
52    let mut out = vec![0.0f32; entry.n_elems()];
53    dequant_tensor(entry, model.entry_bytes(entry), &mut out)?;
54    Ok(out)
55}
56
57/// Weighted working tensor (claim 14): Σ wᵢ·Tᵢ, where Tᵢ is the
58/// skill's replacement when present, else the backbone tensor.
59fn blend_f32(model: &CmfModel, name: &str, list: &[(String, f32)]) -> Result<Vec<f32>, String> {
60    let mut acc: Option<Vec<f32>> = None;
61    for (sid, w) in list {
62        let sname = format!("skill.{sid}.{name}");
63        let src = if model.tensor(&sname).is_some() {
64            &sname
65        } else {
66            name
67        };
68        let t = dequant_by_name(model, src)?;
69        match &mut acc {
70            None => {
71                let mut t = t;
72                for v in t.iter_mut() {
73                    *v *= w;
74                }
75                acc = Some(t);
76            }
77            Some(a) => {
78                for (av, tv) in a.iter_mut().zip(&t) {
79                    *av += w * tv;
80                }
81            }
82        }
83    }
84    acc.ok_or_else(|| "empty blend".into())
85}
86
87/// Dequantize a tensor fully into f32 (norms, masked models).
88pub(crate) fn load_f32(model: &CmfModel, name: &str, ov: &Overlay) -> Result<Vec<f32>, String> {
89    if ov.blend_touches(model, name) {
90        if let Overlay::Blend(list) = ov {
91            return blend_f32(model, name, list);
92        }
93    }
94    let skill = match ov {
95        Overlay::One(s) => Some(*s),
96        _ => None,
97    };
98    let entry = model
99        .resolve_tensor(name, skill)
100        .ok_or_else(|| format!("tensor '{name}' not found in CMF directory"))?;
101    let bytes = model.entry_bytes(entry);
102    let mut out = vec![0.0f32; entry.n_elems()];
103    dequant_tensor(entry, bytes, &mut out)?;
104    Ok(out)
105}
106
107/// Build one layer's FFN (dense or MoE) under a given overlay. Shared
108/// by the static loader AND dynamic per-token skill switching
109/// (`Pipeline::set_active_skill`): switching skills = rebuilding the
110/// FFN of the touched layers, cheap because Mapped tensors are just
111/// re-resolved mmap pointers (no dequant, no copy).
112pub(crate) fn build_layer_ffn(
113    model: &Arc<CmfModel>,
114    arch: &ModelArch,
115    li: usize,
116    force_f32: bool,
117    ov: &Overlay,
118) -> Result<FfnKind, CmfError> {
119    build_ffn_at(model, arch, &format!("model.layers.{li}."), force_f32, ov)
120}
121
122/// The FFN under an arbitrary prefix. Split out of `build_layer_ffn` so the
123/// MTP block can reuse it: Qwen3.6's MTP layer carries a full MoE mlp
124/// (router + 256 experts + shared expert), not the dense one the head was
125/// first written against.
126pub(crate) fn build_ffn_at(
127    model: &Arc<CmfModel>,
128    arch: &ModelArch,
129    prefix: &str,
130    force_f32: bool,
131    ov: &Overlay,
132) -> Result<FfnKind, CmfError> {
133    let prefix = prefix.to_string();
134    let load_dense = |p: &str| -> Result<DenseFfn, CmfError> {
135        let gate_proj = load_matrix(model, &format!("{p}gate_proj.weight"), force_f32, ov)?;
136        let up_proj = load_matrix(model, &format!("{p}up_proj.weight"), force_f32, ov)?;
137        let down_proj = load_matrix(model, &format!("{p}down_proj.weight"), force_f32, ov)?;
138        // FFN triple invariant (holds for dense and each MoE expert;
139        // enforced loudly so a malformed defrag/repack — spec §11 — fails
140        // at load instead of silently mis-computing). inter' is per-layer.
141        let inter = gate_proj.rows();
142        if up_proj.rows() != inter || down_proj.cols() != inter {
143            return Err(CmfError::Parse(format!(
144                "{p}: FFN dims disagree (gate.rows={inter}, up.rows={}, \
145                 down.cols={}); all three must equal inter'",
146                up_proj.rows(),
147                down_proj.cols()
148            )));
149        }
150        if down_proj.rows() != arch.hidden_size {
151            return Err(CmfError::Parse(format!(
152                "{p}: down_proj.rows={} != hidden_size={}",
153                down_proj.rows(),
154                arch.hidden_size
155            )));
156        }
157        // The transposed down, when the file carries one: the per-token
158        // sparse path needs a neuron's down weights contiguous.
159        let dt_name = format!("{p}down_proj.t.weight");
160        let down_t = match model.tensor(&dt_name) {
161            Some(_) => Some(load_matrix(model, &dt_name, force_f32, ov)?),
162            None => None,
163        };
164        if let Some(t) = &down_t
165            && (t.rows() != inter || t.cols() != arch.hidden_size)
166        {
167            return Err(CmfError::Parse(format!(
168                "{p}down_proj.t: [{}, {}] != [{inter}, {}]",
169                t.rows(),
170                t.cols(),
171                arch.hidden_size
172            )));
173        }
174        // Task tubes (`…gate_proj.tube1.weight`, …): the neurons only
175        // some tasks compute, each stored as its own triple so every
176        // kernel runs it unchanged and an inactive tube's bytes are
177        // never touched. Numbering is dense from 1; the first gap ends
178        // the tube list.
179        let mut segs = Vec::new();
180        let mut start = inter;
181        for k in 1.. {
182            let gn = format!("{p}gate_proj.tube{k}.weight");
183            if model.tensor(&gn).is_none() {
184                break;
185            }
186            let gate = load_matrix(model, &gn, force_f32, ov)?;
187            let up = load_matrix(model, &format!("{p}up_proj.tube{k}.weight"), force_f32, ov)?;
188            let down = load_matrix(model, &format!("{p}down_proj.tube{k}.weight"), force_f32, ov)?;
189            let width = gate.rows();
190            if up.rows() != width || down.cols() != width || down.rows() != arch.hidden_size {
191                return Err(CmfError::Parse(format!(
192                    "{p}tube{k}: dims disagree (gate.rows={width}, up.rows={}, \
193                     down=[{}, {}], hidden={})",
194                    up.rows(),
195                    down.rows(),
196                    down.cols(),
197                    arch.hidden_size
198                )));
199            }
200            segs.push(crate::pipeline::FfnSeg {
201                gate,
202                up,
203                down,
204                start,
205                width,
206            });
207            start += width;
208        }
209        Ok(DenseFfn {
210            gate_proj,
211            up_proj,
212            down_proj,
213            act: crate::pipeline::Act::from_arch_full(arch),
214            down_t,
215            segs,
216        })
217    };
218    let router_name = format!("{prefix}mlp.gate.weight");
219    // Cortiq Embryo: resonance-routed experts carry NO gate tensor — the
220    // MoE is keyed on the first expert + the arch flag (a grown genome
221    // appends `mlp.experts.{E}.*` records without rewriting anything).
222    let resonance_moe = model.tensor(&router_name).is_none()
223        && arch.moe.as_ref().is_some_and(|m| m.router_resonance)
224        && model
225            .tensor(&format!("{prefix}mlp.experts.0.gate_proj.weight"))
226            .is_some();
227    if model.tensor(&router_name).is_none() && !resonance_moe {
228        return Ok(FfnKind::Dense(load_dense(&format!("{prefix}mlp."))?));
229    }
230    let cfg = arch.moe.as_ref().ok_or_else(|| {
231        CmfError::Parse(format!(
232            "{router_name} present but header has no arch.moe block"
233        ))
234    })?;
235    // Experts enumerate by TENSOR PRESENCE up to the header count — a
236    // moe-defrag'd specialist keeps a per-layer contiguous prefix of
237    // renumbered experts (fewer than arch.moe.num_experts), with the
238    // router rows sliced to match.
239    let mut experts = Vec::new();
240    for e in 0..cfg.num_experts {
241        if model
242            .tensor(&format!("{prefix}mlp.experts.{e}.gate_proj.weight"))
243            .is_none()
244        {
245            break;
246        }
247        experts.push(load_dense(&format!("{prefix}mlp.experts.{e}."))?);
248    }
249    if experts.is_empty() {
250        return Err(CmfError::Parse(format!(
251            "{prefix}: router present but no expert tensors"
252        )));
253    }
254    let shared = if model
255        .tensor(&format!("{prefix}mlp.shared_expert.gate_proj.weight"))
256        .is_some()
257    {
258        let gate_name = format!("{prefix}mlp.shared_expert_gate.weight");
259        Some((
260            load_dense(&format!("{prefix}mlp.shared_expert."))?,
261            if model.tensor(&gate_name).is_some() {
262                Some(load_matrix(model, &gate_name, force_f32, ov)?)
263            } else {
264                None
265            },
266        ))
267    } else {
268        None
269    };
270    // LFM2-MoE selection bias (`mlp.expert_bias`): present iff the model
271    // routes with a bias; loaded by tensor presence.
272    let bias_name = format!("{prefix}mlp.expert_bias");
273    let expert_bias = if model.tensor(&bias_name).is_some() {
274        Some(load_f32(model, &bias_name, ov).map_err(CmfError::Parse)?)
275    } else {
276        None
277    };
278    // CMF_MOE_TOPK=N (opt-in): route to fewer experts than the header
279    // asks. MoE decode is memory-bound — every selected expert streams
280    // its three matrices per token — so halving k halves that traffic;
281    // the renormalized top-k keeps the mixture a proper average.
282    // Quality is the experiment — measure ppl before trusting.
283    let top_k = std::env::var("CMF_MOE_TOPK")
284        .ok()
285        .and_then(|v| v.parse::<usize>().ok())
286        .filter(|&k| k >= 1 && k <= cfg.top_k)
287        .inspect(|k| tracing::info!("MoE top_k override: {} (header {})", k, cfg.top_k))
288        .unwrap_or(cfg.top_k);
289    // CMF_MOE_TAU=0.x (opt-in): adaptive routing — see MoeFfn::route_tau.
290    let route_tau = std::env::var("CMF_MOE_TAU")
291        .ok()
292        .and_then(|v| v.parse::<f32>().ok())
293        .filter(|&t| t > 0.0 && t < 1.0)
294        .inspect(|t| tracing::info!("MoE adaptive routing: tau {t}"));
295    let mask = moe_task_mask(&prefix, experts.len());
296    let router = if resonance_moe {
297        // never read (selection is by descriptors); zero placeholder in RAM
298        QTensor::from_f32(vec![0.0; experts.len() * arch.hidden_size], experts.len(), arch.hidden_size)
299    } else {
300        load_matrix(model, &router_name, force_f32, ov)?
301    };
302    if router.rows() != experts.len() {
303        return Err(CmfError::Parse(format!(
304            "{router_name}: {} rows != {} experts",
305            router.rows(),
306            experts.len()
307        )));
308    }
309    let top_k = top_k.min(experts.len());
310    // Gemma-4: per-expert weight scale after the top-k renorm; its
311    // presence also marks the scale-less-rms router input (the folded
312    // router gain — see the converter).
313    let pes_name = format!("{prefix}mlp.per_expert_scale");
314    let per_expert_scale = if model.tensor(&pes_name).is_some() {
315        Some(load_f32(model, &pes_name, ov).map_err(CmfError::Parse)?)
316    } else {
317        None
318    };
319    let router_input_norm = per_expert_scale.is_some();
320    // Cortiq Embryo resonance descriptors: per-expert records
321    // `mlp.experts.{e}.desc.{mu,u,bias}` (append-only growth) or the legacy
322    // per-layer `mlp.desc.{mu,u,bias}` [E, ...]. Present → the router is a
323    // placeholder and selection is by reconstruction error.
324    let per_expert = model.tensor(&format!("{prefix}mlp.experts.0.desc.mu")).is_some();
325    let resonance = if per_expert {
326        let ne_d = experts.len();
327        let hidden = arch.hidden_size;
328        let mut mu = Vec::with_capacity(ne_d * hidden);
329        let mut u = Vec::new();
330        let mut bias = Vec::with_capacity(ne_d);
331        let mut k = 0usize;
332        for e in 0..ne_d {
333            let m = load_f32(model, &format!("{prefix}mlp.experts.{e}.desc.mu"), ov).map_err(CmfError::Parse)?;
334            if m.len() != hidden {
335                return Err(CmfError::Parse(format!("{prefix}mlp.experts.{e}.desc.mu: {} != {hidden}", m.len())));
336            }
337            mu.extend_from_slice(&m);
338            let un = format!("{prefix}mlp.experts.{e}.desc.u");
339            if model.tensor(&un).is_some() {
340                let ue = load_f32(model, &un, ov).map_err(CmfError::Parse)?;
341                let ke = ue.len() / hidden.max(1);
342                if e == 0 {
343                    k = ke;
344                }
345                if ke != k {
346                    return Err(CmfError::Parse(format!("{un}: rank {ke} != {k}")));
347                }
348                u.extend_from_slice(&ue);
349            }
350            let bn = format!("{prefix}mlp.experts.{e}.desc.bias");
351            bias.push(if model.tensor(&bn).is_some() {
352                load_f32(model, &bn, ov).map_err(CmfError::Parse)?.first().copied().unwrap_or(0.0)
353            } else {
354                0.0
355            });
356        }
357        Some(crate::pipeline::Resonance { mu, u, k, bias })
358    } else if model.tensor(&format!("{prefix}mlp.desc.mu")).is_some() {
359        let mu = load_f32(model, &format!("{prefix}mlp.desc.mu"), ov).map_err(CmfError::Parse)?;
360        let ne_d = experts.len();
361        let hidden = arch.hidden_size;
362        if mu.len() != ne_d * hidden {
363            return Err(CmfError::Parse(format!("{prefix}mlp.desc.mu: {} != {ne_d}×{hidden}", mu.len())));
364        }
365        let u_name = format!("{prefix}mlp.desc.u");
366        let (u, k) = if model.tensor(&u_name).is_some() {
367            let u = load_f32(model, &u_name, ov).map_err(CmfError::Parse)?;
368            let k = u.len() / (ne_d * hidden).max(1);
369            (u, k)
370        } else {
371            (Vec::new(), 0)
372        };
373        let b_name = format!("{prefix}mlp.desc.bias");
374        let bias = if model.tensor(&b_name).is_some() {
375            load_f32(model, &b_name, ov).map_err(CmfError::Parse)?
376        } else {
377            vec![0.0; ne_d]
378        };
379        Some(crate::pipeline::Resonance { mu, u, k, bias })
380    } else {
381        None
382    };
383    let moe = MoeFfn {
384        router,
385        experts,
386        top_k,
387        route_tau,
388        norm_topk_prob: cfg.norm_topk_prob,
389        router_sigmoid: cfg.router_sigmoid,
390        expert_bias,
391        routed_scaling: cfg.routed_scaling_factor.unwrap_or(1.0),
392        shared,
393        stats: std::cell::RefCell::new(Vec::new()),
394        act_sq: std::cell::RefCell::new(Vec::new()),
395        act_rows: std::cell::RefCell::new(Vec::new()),
396        mask,
397        per_expert_scale,
398        router_input_norm,
399        resonance,
400    };
401    // Gemma-4 dual-branch layer: a dense MLP coexists with the routed
402    // experts, each branch inside its own norm sandwich.
403    if model
404        .tensor(&format!("{prefix}mlp.gate_proj.weight"))
405        .is_some()
406    {
407        let norm = |suffix: &str| -> Result<Vec<f32>, CmfError> {
408            load_f32(model, &format!("{prefix}{suffix}.weight"), ov).map_err(CmfError::Parse)
409        };
410        return Ok(FfnKind::DenseMoe(Box::new(crate::pipeline::DenseMoeFfn {
411            dense: load_dense(&format!("{prefix}mlp."))?,
412            moe,
413            post_norm_1: norm("post_feedforward_layernorm_1")?,
414            pre_norm_2: norm("pre_feedforward_layernorm_2")?,
415            post_norm_2: norm("post_feedforward_layernorm_2")?,
416        })));
417    }
418    Ok(FfnKind::Moe(moe))
419}
420
421/// Task mask over routed experts (opt-in, experimental): DTG-MA applied
422/// to MoE. `CMF_MOE_MASK=<stats.json>` points at a claim-12 B-field dump
423/// (`CMF_MOE_STATS` output — per-layer expert-selection counts from a
424/// task-representative run); `CMF_MOE_MASK_COVER` (default 0.9) keeps,
425/// per layer, the smallest top set of experts reaching that fraction of
426/// the recorded routing mass. Selection then happens over the allowed
427/// set only (softmax renormalizes). Gate any real use on a ppl A/B.
428pub(crate) fn moe_task_mask(prefix: &str, ne: usize) -> Option<Vec<bool>> {
429    use std::sync::OnceLock;
430    static CFG: OnceLock<Option<(std::collections::HashMap<usize, Vec<u64>>, f64)>> =
431        OnceLock::new();
432    let cfg = CFG.get_or_init(|| {
433        let path = std::env::var("CMF_MOE_MASK").ok()?;
434        let cover = std::env::var("CMF_MOE_MASK_COVER")
435            .ok()
436            .and_then(|v| v.parse::<f64>().ok())
437            .filter(|&c| c > 0.0 && c <= 1.0)
438            .unwrap_or(0.9);
439        let text = std::fs::read_to_string(&path)
440            .map_err(|e| tracing::warn!("CMF_MOE_MASK: cannot read {path}: {e}"))
441            .ok()?;
442        let map: std::collections::HashMap<String, Vec<u64>> = serde_json::from_str(&text)
443            .map_err(|e| tracing::warn!("CMF_MOE_MASK: bad JSON in {path}: {e}"))
444            .ok()?;
445        tracing::info!("MoE task mask: {path}, cover {cover}");
446        Some((
447            map.into_iter()
448                .filter_map(|(k, v)| Some((k.parse::<usize>().ok()?, v)))
449                .collect(),
450            cover,
451        ))
452    });
453    let (stats, cover) = cfg.as_ref()?;
454    // The layer index rides in the tensor prefix ("model.layers.N.").
455    let li: usize = prefix
456        .split("layers.")
457        .nth(1)?
458        .split('.')
459        .next()?
460        .parse()
461        .ok()?;
462    let counts = stats.get(&li)?;
463    if counts.len() != ne {
464        tracing::warn!(
465            "CMF_MOE_MASK: layer {li} has {} counts, model has {ne} experts — skipped",
466            counts.len()
467        );
468        return None;
469    }
470    let total: u64 = counts.iter().sum();
471    if total == 0 {
472        return None;
473    }
474    let mut order: Vec<usize> = (0..ne).collect();
475    order.sort_unstable_by_key(|&e| std::cmp::Reverse(counts[e]));
476    let mut mask = vec![false; ne];
477    let mut acc = 0u64;
478    let mut kept = 0usize;
479    for &e in &order {
480        mask[e] = true;
481        acc += counts[e];
482        kept += 1;
483        if (acc as f64) >= cover * (total as f64) {
484            break;
485        }
486    }
487    tracing::info!(
488        "MoE task mask L{li}: {kept}/{ne} experts for {:.0}% mass",
489        cover * 100.0
490    );
491    Some(mask)
492}
493
494fn load_matrix(
495    model: &Arc<CmfModel>,
496    name: &str,
497    force_f32: bool,
498    ov: &Overlay,
499) -> Result<QTensor, CmfError> {
500    // Claim 14: a blended working tensor is materialized in f32 and
501    // held resident (the overlay-cache slot); single skills stay
502    // zero-copy pointers into the mmap.
503    if ov.blend_touches(model, name) {
504        if let Overlay::Blend(list) = ov {
505            let entry = model
506                .tensor(name)
507                .ok_or_else(|| CmfError::MissingTensor(name.to_string()))?;
508            let data =
509                blend_f32(model, name, list).map_err(|e| CmfError::Parse(format!("blend: {e}")))?;
510            return Ok(QTensor::from_f32(data, entry.shape[0], entry.shape[1]));
511        }
512    }
513    let skill = match ov {
514        Overlay::One(s) => Some(*s),
515        _ => None,
516    };
517    // Tensor-source indirection (spec §9): the skill's replacement is
518    // read in place of the backbone tensor — either/or, never a sum.
519    let name: &str = &match skill {
520        Some(sid) if model.tensor(&format!("skill.{sid}.{name}")).is_some() => {
521            format!("skill.{sid}.{name}")
522        }
523        _ => name.to_string(),
524    };
525    let err = |e: String| CmfError::Parse(format!("weight loading: {e}"));
526    if force_f32 {
527        let entry = model
528            .tensor(name)
529            .ok_or_else(|| CmfError::MissingTensor(name.to_string()))?;
530        if entry.shape.len() != 2 {
531            return Err(err(format!("'{name}' is not 2-D")));
532        }
533        let data = load_f32(model, name, &Overlay::None).map_err(err)?;
534        Ok(QTensor::from_f32(data, entry.shape[0], entry.shape[1]))
535    } else {
536        QTensor::from_model(model, name).map_err(err)
537    }
538}
539
540impl Pipeline {
541    /// Build a runnable pipeline from an opened CMF model.
542    pub fn from_model(
543        model: &Arc<CmfModel>,
544        sampler_config: SamplerConfig,
545    ) -> Result<Self, CmfError> {
546        Self::from_model_with_skill(model, sampler_config, None)
547    }
548
549    /// Same, with a skill overlaid (spec §9): every layer tensor is
550    /// resolved through tensor-source indirection — the skill's
551    /// full-shape replacement is read in place of the backbone tensor.
552    /// No per-skill model is ever assembled: Mapped tensors are
553    /// pointers into the one shared mmap.
554    pub fn from_model_with_skill(
555        model: &Arc<CmfModel>,
556        sampler_config: SamplerConfig,
557        skill: Option<&str>,
558    ) -> Result<Self, CmfError> {
559        match skill {
560            Some(s) => Self::from_model_with_overlay(model, sampler_config, &Overlay::One(s)),
561            None => Self::from_model_with_overlay(model, sampler_config, &Overlay::None),
562        }
563    }
564
565    /// Soft superposition (claim 14): working tensors accumulated from
566    /// the given (skill, weight) list — softmax(−E/T) upstream.
567    pub fn from_model_with_blend(
568        model: &Arc<CmfModel>,
569        sampler_config: SamplerConfig,
570        blend: &[(String, f32)],
571    ) -> Result<Self, CmfError> {
572        Self::from_model_with_overlay(model, sampler_config, &Overlay::Blend(blend))
573    }
574
575    fn skill_file_guard(model: &CmfModel) -> Result<(), CmfError> {
576        // A standalone skill file carries a PARTIAL tensor set cut against
577        // a base; running it would be half a network answering questions.
578        if model.required_features & cortiq_core::format::features::SKILL_FILE != 0 {
579            return Err(CmfError::Parse(
580                "this file is a standalone SKILL, not a runnable model — attach it: \
581                 cortiq skill apply <base.cmf> <this file> -o specialist.cmf"
582                    .into(),
583            ));
584        }
585        Ok(())
586    }
587
588    fn from_model_with_overlay(
589        model: &Arc<CmfModel>,
590        sampler_config: SamplerConfig,
591        ov: &Overlay,
592    ) -> Result<Self, CmfError> {
593        // Small device caches (probe verdicts, compiled pipelines) go
594        // beside the model: it is a directory the caller demonstrably
595        // writes to, which `std::env::temp_dir()` is not inside an
596        // Android app sandbox.
597        if let Some(dir) = model.path.parent() {
598            crate::gpu::set_cache_dir(dir.to_path_buf());
599        }
600        // A new model gets a fresh verdict on whether the token graph can
601        // be built: the refusal is remembered per model, not per process.
602        crate::gpu::graph_unsupported_reset();
603        Self::skill_file_guard(model)?;
604        let skill = match ov {
605            Overlay::One(s) => Some(*s),
606            _ => None,
607        };
608        if let Some(sid) = skill {
609            let known = model.header.skills.iter().any(|s| s.id == sid)
610                || model.skill_tensors(sid).next().is_some();
611            if !known {
612                return Err(CmfError::Parse(format!(
613                    "skill '{sid}' not in this container (header.skills: {:?})",
614                    model
615                        .header
616                        .skills
617                        .iter()
618                        .map(|s| &s.id)
619                        .collect::<Vec<_>>()
620                )));
621            }
622            tracing::info!(
623                "skill '{sid}': {} replacement tensors overlaid",
624                model.skill_tensors(sid).count()
625            );
626        }
627        let arch = model.arch().clone();
628        let err = |e: String| CmfError::Parse(format!("weight loading: {e}"));
629        if let Some(heads) = &arch.attention_heads_per_layer {
630            if heads.len() != arch.num_layers {
631                return Err(CmfError::Parse(format!(
632                    "arch.attention_heads_per_layer has {} entries, expected {}",
633                    heads.len(),
634                    arch.num_layers
635                )));
636            }
637            if let Some((li, &nh)) = heads
638                .iter()
639                .enumerate()
640                .find(|(_, nh)| **nh == 0 || **nh % arch.num_kv_heads != 0)
641            {
642                return Err(CmfError::Parse(format!(
643                    "layer {li} has {nh} Q heads, which must be nonzero and divisible by {} KV heads",
644                    arch.num_kv_heads
645                )));
646            }
647        }
648        if arch
649            .layer_types
650            .iter()
651            .any(|t| matches!(t, LayerType::SlidingAttention))
652            && arch.sliding_window.is_none()
653        {
654            return Err(CmfError::Parse(
655                "model has SlidingAttention layers but no arch.sliding_window".into(),
656            ));
657        }
658
659        // Masks × quantized mmap: only the HEAD-mask path needs f32
660        // slices, so f32 is forced only when some mask actually restricts
661        // attention heads. FFN masks run sparse directly on the quant
662        // bytes (sparse_ffn_quant), and embed/lm_head are never masked.
663        // The old condition forced f32 for ANY mask: a 4.17 B file whose
664        // mask touched only the FFN dequantized to 16.7 GB at load and
665        // ran the bare-f32 GEMMs — 0.0 tok/s on a laptop that swapped,
666        // and a 30× crawl on a 48-core server. A mask with no head rows
667        // costs nothing now.
668        let heads_masked = model.masks.masks.iter().any(|m| {
669            m.head_masks.iter().any(|row| {
670                let mut bits = 0usize;
671                for &b in row.iter() {
672                    bits += b.count_ones() as usize;
673                }
674                !row.is_empty() && bits < arch.num_attention_heads
675            })
676        });
677        let force_f32 = heads_masked; // attention only (head masks)
678
679        // ── Tokenizer: embedded → sidecar → byte-level fallback ──
680        let mut tokenizer = if let Some(vocab_bytes) = &model.vocab {
681            Tokenizer::from_bytes(vocab_bytes)
682                .map_err(|e| CmfError::Parse(format!("embedded tokenizer: {e}")))?
683        } else {
684            let sidecar = model.path.with_file_name("tokenizer.json");
685            if sidecar.exists() {
686                Tokenizer::from_file(&sidecar)
687                    .map_err(|e| CmfError::Parse(format!("sidecar tokenizer: {e}")))?
688            } else {
689                tracing::warn!("no tokenizer in file or sidecar — using byte-level fallback");
690                Tokenizer::byte_level()
691            }
692        };
693        // Chat/eos bundle (spec §6.1): the FILE defines chat behavior.
694        if let Some(tc) = &model.header.tokenizer_config {
695            tokenizer.chat_template = tc.chat_template.clone();
696            tokenizer.extra_eos.extend(tc.eos_token_ids.iter().copied());
697            if tokenizer.bos_token_id.is_none() {
698                tokenizer.bos_token_id = tc.bos_token_id;
699            }
700            tracing::info!(
701                "chat bundle: template {} chars, {} stop ids",
702                tc.chat_template.as_deref().map(str::len).unwrap_or(0),
703                tc.eos_token_ids.len()
704            );
705        }
706        // Gemma's contract requires <bos> at sequence start, but its
707        // tokenizer.json post-processor does not add it (the chat
708        // template does). Raw prompts need it too — word salad without.
709        if arch.arch_name.to_lowercase().contains("gemma") && tokenizer.bos_token_id.is_some() {
710            tokenizer.add_bos = true;
711        }
712
713        // ── Top-level weights (never masked → always quantized) ──
714        let embed_tokens = load_matrix(model, "model.embed_tokens.weight", false, ov)?;
715        let final_norm = load_f32(model, "model.norm.weight", ov).map_err(err)?;
716        let lm_head = if model.tensor("lm_head.weight").is_some() {
717            load_matrix(model, "lm_head.weight", false, ov)?
718        } else if arch.tie_word_embeddings {
719            // Tied: reuse the embedding matrix (re-open, cheap for Mapped).
720            load_matrix(model, "model.embed_tokens.weight", false, ov)?
721        } else {
722            return Err(CmfError::MissingTensor(
723                "lm_head.weight (and tie_word_embeddings is false)".into(),
724            ));
725        };
726
727        // ── Linear-core geometry (required if any linear layer exists) ──
728        let has_linear = arch
729            .layer_types
730            .iter()
731            .any(|t| matches!(t, LayerType::LinearAttention));
732        let mut vmf_cfg = None;
733        let mut gdn_cfg = None;
734        if has_linear {
735            let lc = arch.linear_core.as_ref().ok_or_else(|| {
736                CmfError::Parse(
737                    "model has LinearAttention layers but no arch.linear_core — \
738                     reconvert with the current converter"
739                        .into(),
740                )
741            })?;
742            let need = |v: Option<usize>, name: &str| {
743                v.ok_or_else(|| CmfError::Parse(format!("linear core needs arch.{name}")))
744            };
745            match lc.kind.as_str() {
746                "vmf_phase" => {
747                    vmf_cfg = Some(VmfPhaseCfg {
748                        num_heads: lc.num_heads,
749                        nphase: need(lc.nphase, "linear_core.nphase")?,
750                        value_head_dim: lc.value_head_dim,
751                        hidden_size: arch.hidden_size,
752                        // θ-mass (η′): default 0 (massless); CMF_PHASE_MASS
753                        // widens the phase kernel for folded-unhealed models.
754                        phase_mass: std::env::var("CMF_PHASE_MASS")
755                            .ok()
756                            .and_then(|v| v.parse().ok())
757                            .unwrap_or(0.0),
758                    });
759                }
760                "gated_delta_net" => {
761                    gdn_cfg = Some(GdnCfg {
762                        num_v_heads: lc.num_heads,
763                        num_k_heads: need(arch.linear_num_key_heads, "linear_num_key_heads")?,
764                        key_head_dim: need(arch.linear_key_head_dim, "linear_key_head_dim")?,
765                        value_head_dim: lc.value_head_dim,
766                        conv_kernel: need(arch.linear_conv_kernel_dim, "linear_conv_kernel_dim")?,
767                        hidden_size: arch.hidden_size,
768                        rms_eps: arch.rms_norm_eps,
769                    });
770                }
771                other => {
772                    return Err(CmfError::Parse(format!(
773                        "unknown linear core '{other}' (this runtime executes: \
774                         gated_delta_net, vmf_phase)"
775                    )));
776                }
777            }
778        }
779
780        // ── KDA geometry (Kimi Linear / Kimi-K3 delta-attention layers) ──
781        let has_kda = arch.layer_types.iter().any(|t| matches!(t, LayerType::Kda));
782        let kda_cfg = if has_kda {
783            let need = |v: Option<usize>, name: &str| {
784                v.ok_or_else(|| CmfError::Parse(format!("KDA core needs arch.{name}")))
785            };
786            Some(crate::linear_core::KdaCfg {
787                num_heads: need(arch.linear_num_key_heads, "linear_num_key_heads")?,
788                head_k_dim: need(arch.linear_key_head_dim, "linear_key_head_dim")?,
789                head_v_dim: need(arch.linear_value_head_dim, "linear_value_head_dim")?,
790                conv_kernel: need(arch.linear_conv_kernel_dim, "linear_conv_kernel_dim")?,
791                hidden_size: arch.hidden_size,
792                rms_eps: arch.rms_norm_eps,
793            })
794        } else {
795            None
796        };
797
798        // ── Short-convolution geometry (LFM2 conv mixer layers) ──
799        let has_short_conv = arch
800            .layer_types
801            .iter()
802            .any(|t| matches!(t, LayerType::ShortConv));
803        let short_conv_cfg = if has_short_conv {
804            Some(ShortConvCfg {
805                hidden_size: arch.hidden_size,
806                kernel: arch.linear_conv_kernel_dim.ok_or_else(|| {
807                    CmfError::Parse(
808                        "model has ShortConv layers but no arch.linear_conv_kernel_dim — \
809                         reconvert with the current converter"
810                            .into(),
811                    )
812                })?,
813            })
814        } else {
815            None
816        };
817
818        // ── Layers ──
819        let load_full_attn = |prefix: &str, layer: Option<usize>| -> Result<AttnKind, CmfError> {
820            let t = |suffix: &str| load_matrix(model, &format!("{prefix}{suffix}"), force_f32, ov);
821            let n = |suffix: &str| -> Option<Vec<f32>> {
822                model
823                    .tensor(&format!("{prefix}{suffix}"))
824                    .and_then(|_| load_f32(model, &format!("{prefix}{suffix}"), ov).ok())
825            };
826            // DeepSeek-V2 MLA: the latent projections replace the k/v pair.
827            if let Some(mla) = arch.mla.as_ref() {
828                // Compressed q (K3/V3): q_a → rms → q_b; direct otherwise.
829                let (q_proj, q_a, q_a_norm) = if mla.q_lora_rank.is_some() {
830                    (
831                        t("self_attn.q_b_proj.weight")?,
832                        Some(t("self_attn.q_a_proj.weight")?),
833                        Some(n("self_attn.q_a_layernorm.weight").ok_or_else(|| {
834                            CmfError::Parse(format!("{prefix}: MLA needs q_a_layernorm"))
835                        })?),
836                    )
837                } else {
838                    (t("self_attn.q_proj.weight")?, None, None)
839                };
840                let hd = mla.qk_rope_head_dim + mla.qk_nope_head_dim;
841                let nh = q_proj.rows() / hd;
842                // YaRN mscale²: DeepSeek corrects the softmax scale by
843                // (0.1·mscale_all_dim·ln(factor)+1)².
844                let mut scale = 1.0 / (hd as f32).sqrt();
845                if let Some(y) = arch.yarn.as_ref() {
846                    if let Some(m) = y.mscale_all_dim.filter(|&m| m > 0.0) {
847                        let ms = 0.1 * m * y.factor.ln() + 1.0;
848                        scale *= ms * ms;
849                    }
850                }
851                return Ok(AttnKind::Mla(Box::new(crate::pipeline::MlaWeights {
852                    q_proj,
853                    q_a,
854                    q_a_norm,
855                    kv_a: t("self_attn.kv_a_proj_with_mqa.weight")?,
856                    kv_a_norm: n("self_attn.kv_a_layernorm.weight").ok_or_else(|| {
857                        CmfError::Parse(format!("{prefix}: MLA needs kv_a_layernorm"))
858                    })?,
859                    kv_b: t("self_attn.kv_b_proj.weight")?,
860                    o_proj: t("self_attn.o_proj.weight")?,
861                    nh,
862                    qk_rope: mla.qk_rope_head_dim,
863                    qk_nope: mla.qk_nope_head_dim,
864                    v_dim: mla.v_head_dim,
865                    lora: mla.kv_lora_rank,
866                    scale,
867                    nope: mla.nope,
868                })));
869            }
870            let wq = t("self_attn.q_proj.weight")?;
871            let nh = layer
872                .and_then(|li| {
873                    arch.attention_heads_per_layer
874                        .as_ref()
875                        .and_then(|v| v.get(li).copied())
876                })
877                .unwrap_or(arch.num_attention_heads);
878            // Qwen3.5 output gate: q_proj rows = 2·nh·hd (per-head [q; gate]).
879            // Gemma-4 global layers legitimately have nh·global_head_dim
880            // rows (which can equal 2·nh·hd) — never gated.
881            let output_gate = arch.global_head_dim.is_none() && wq.rows() == 2 * nh * arch.head_dim;
882            // Gemma-4 global layers run MQA at global_head_dim — their
883            // q_proj legitimately carries nh·ghd rows.
884            let is_global_layer = arch.global_head_dim.is_some()
885                && layer.is_some_and(|li| {
886                    arch.sliding_window_pattern
887                        .is_some_and(|p| p > 0 && (li + 1) % p == 0)
888                });
889            let expect = if is_global_layer {
890                nh * arch.global_head_dim.unwrap_or(arch.head_dim)
891            } else {
892                nh * arch.head_dim
893            };
894            if !output_gate && wq.rows() != expect {
895                return Err(CmfError::Parse(format!(
896                    "{prefix}self_attn.q_proj.weight rows={} != heads({nh}) * head_dim({})",
897                    wq.rows(),
898                    expect / nh.max(1)
899                )));
900            }
901            let gate_name = format!("{prefix}self_attn.g_proj.weight");
902            let softplus_gate = if model.tensor(&gate_name).is_some() {
903                let gate = load_matrix(model, &gate_name, force_f32, ov)?;
904                if gate.cols() != arch.hidden_size {
905                    return Err(CmfError::Parse(format!(
906                        "{gate_name} cols={} != hidden_size ({})",
907                        gate.cols(),
908                        arch.hidden_size
909                    )));
910                }
911                let per_head = if gate.rows() == nh {
912                    true
913                } else if gate.rows() == nh * arch.head_dim {
914                    false
915                } else {
916                    return Err(CmfError::Parse(format!(
917                        "{gate_name} rows={} must equal heads ({nh}) or heads*head_dim ({})",
918                        gate.rows(),
919                        nh * arch.head_dim
920                    )));
921                };
922                Some((gate, per_head))
923            } else {
924                None
925            };
926            // Qwen2-family projection biases (by tensor presence).
927            let bias = match (
928                n("self_attn.q_proj.bias"),
929                n("self_attn.k_proj.bias"),
930                n("self_attn.v_proj.bias"),
931            ) {
932                (Some(a), Some(b), Some(c)) => Some((a, b, c)),
933                _ => None,
934            };
935            Ok(AttnKind::Full {
936                wq,
937                wk: t("self_attn.k_proj.weight")?,
938                wv: t("self_attn.v_proj.weight")?,
939                wo: t("self_attn.o_proj.weight")?,
940                q_norm: n("self_attn.q_norm.weight"),
941                k_norm: n("self_attn.k_norm.weight"),
942                output_gate,
943                softplus_gate,
944                bias,
945            })
946        };
947
948        let load_linear_attn = |prefix: &str| -> Result<AttnKind, CmfError> {
949            if gdn_cfg.is_some() {
950                // Faithful vendor operator: tensor names 1:1 with the source.
951                let t = |suffix: &str| {
952                    load_matrix(
953                        model,
954                        &format!("{prefix}linear_attn.{suffix}"),
955                        force_f32,
956                        ov,
957                    )
958                };
959                let f = |suffix: &str| {
960                    load_f32(model, &format!("{prefix}linear_attn.{suffix}"), ov).map_err(err)
961                };
962                return Ok(AttnKind::LinearGdn(GdnWeights {
963                    in_proj_qkv: t("in_proj_qkv.weight")?,
964                    in_proj_z: t("in_proj_z.weight")?,
965                    in_proj_a: t("in_proj_a.weight")?,
966                    in_proj_b: t("in_proj_b.weight")?,
967                    conv1d: f("conv1d.weight")?,
968                    a_log: f("A_log")?,
969                    dt_bias: f("dt_bias")?,
970                    norm: f("norm.weight")?,
971                    out_proj: t("out_proj.weight")?,
972                }));
973            }
974            let t = |suffix: &str| {
975                load_matrix(model, &format!("{prefix}vmf_attn.{suffix}"), force_f32, ov)
976            };
977            let a_log = load_f32(model, &format!("{prefix}vmf_attn.A_log"), ov).map_err(err)?;
978            // Selective-write gate κ (hybrid_k core): optional by tensor
979            // presence — files without it run the classic phase kernel
980            // bit-identically.
981            let k_gate = if model
982                .tensor(&format!("{prefix}vmf_attn.k_gate.weight"))
983                .is_some()
984            {
985                Some((
986                    t("k_gate.weight")?,
987                    load_f32(model, &format!("{prefix}vmf_attn.k_gate.bias"), ov).map_err(err)?,
988                ))
989            } else {
990                None
991            };
992            Ok(AttnKind::Linear(VmfPhaseWeights {
993                thq: t("thq.weight")?,
994                thk: t("thk.weight")?,
995                v_proj: t("v_proj.weight")?,
996                out_proj: t("out_proj.weight")?,
997                decay: a_log.iter().map(|&a| (-(a as f64).exp()).exp()).collect(),
998                k_gate,
999            }))
1000        };
1001
1002        // LFM2 short-conv mixer: in_proj [3·hidden, hidden], a depthwise
1003        // conv (stored f16 as `[hidden, 1, kernel]` → flattened taps), and
1004        // out_proj [hidden, hidden]. Names canonicalized at convert time.
1005        let load_short_conv = |prefix: &str| -> Result<AttnKind, CmfError> {
1006            let t = |suffix: &str| {
1007                load_matrix(
1008                    model,
1009                    &format!("{prefix}short_conv.{suffix}"),
1010                    force_f32,
1011                    ov,
1012                )
1013            };
1014            Ok(AttnKind::ShortConv(ShortConvWeights {
1015                in_proj: t("in_proj.weight")?,
1016                conv: load_f32(model, &format!("{prefix}short_conv.conv.weight"), ov)
1017                    .map_err(err)?,
1018                out_proj: t("out_proj.weight")?,
1019            }))
1020        };
1021
1022        // KDA layer (Kimi Linear / Kimi-K3): faithful vendor tensors under
1023        // the `kda_attn.` canonical prefix. The output gate is full-rank
1024        // (g_proj, K3) or low-rank (g_a/g_b, Kimi-Linear-48B) by presence.
1025        let load_kda = |prefix: &str| -> Result<AttnKind, CmfError> {
1026            let t = |suffix: &str| {
1027                load_matrix(model, &format!("{prefix}kda_attn.{suffix}"), force_f32, ov)
1028            };
1029            let f = |suffix: &str| {
1030                load_f32(model, &format!("{prefix}kda_attn.{suffix}"), ov).map_err(err)
1031            };
1032            let gate = if model
1033                .tensor(&format!("{prefix}kda_attn.g_proj.weight"))
1034                .is_some()
1035            {
1036                crate::linear_core::KdaOutGate::Full(t("g_proj.weight")?)
1037            } else {
1038                crate::linear_core::KdaOutGate::LowRank(
1039                    t("g_a_proj.weight")?,
1040                    t("g_b_proj.weight")?,
1041                )
1042            };
1043            Ok(AttnKind::Kda(Box::new(crate::linear_core::KdaWeights {
1044                q_proj: t("q_proj.weight")?,
1045                k_proj: t("k_proj.weight")?,
1046                v_proj: t("v_proj.weight")?,
1047                conv_q: f("q_conv1d.weight")?,
1048                conv_k: f("k_conv1d.weight")?,
1049                conv_v: f("v_conv1d.weight")?,
1050                f_a: t("f_a_proj.weight")?,
1051                f_b: t("f_b_proj.weight")?,
1052                dt_bias: f("dt_bias")?,
1053                a_log: f("A_log")?,
1054                b_proj: t("b_proj.weight")?,
1055                gate,
1056                o_norm: f("o_norm.weight")?,
1057                o_proj: t("o_proj.weight")?,
1058                gate_lower_bound: arch.kda_gate_lower_bound.map(|v| v as f32),
1059            })))
1060        };
1061
1062        fn anyhow_like(ok: bool) -> Result<(), ()> {
1063            if ok { Ok(()) } else { Err(()) }
1064        }
1065        let mut layers = Vec::with_capacity(arch.num_layers);
1066        let is_g3n = arch.g3n.is_some();
1067        // Architectures that load their own layer stack below. DeepSeek-V4
1068        // has none of the canonical projections — no q/k/v/o_proj, no
1069        // per-layer gate_proj — so the generic loop would demand
1070        // `self_attn.q_proj.weight` and fail before its own loader ever ran.
1071        let owns_its_layers = is_g3n || arch.arch_name == "deepseek_v4";
1072        for li in 0..(if owns_its_layers { 0 } else { arch.num_layers }) {
1073            let prefix = format!("model.layers.{li}.");
1074            let attn = match arch.layer_types.get(li) {
1075                Some(LayerType::LinearAttention) => load_linear_attn(&prefix)?,
1076                Some(LayerType::Kda) => load_kda(&prefix)?,
1077                Some(LayerType::ShortConv) => load_short_conv(&prefix)?,
1078                _ => load_full_attn(&prefix, Some(li))?,
1079            };
1080            // Gemma-2/3 sandwich: `pre_feedforward_layernorm` present →
1081            // it is the pre-FFN norm, and post_attention/post_feedforward
1082            // норms apply to the branch OUTPUTS before their residuals.
1083            let pre_ffn = format!("{prefix}pre_feedforward_layernorm.weight");
1084            let sandwich = model.tensor(&pre_ffn).is_some();
1085            layers.push(LayerWeights {
1086                input_norm: load_f32(model, &format!("{prefix}input_layernorm.weight"), ov)
1087                    .map_err(err)?,
1088                post_norm: if sandwich {
1089                    load_f32(model, &pre_ffn, ov).map_err(err)?
1090                } else {
1091                    load_f32(
1092                        model,
1093                        &format!("{prefix}post_attention_layernorm.weight"),
1094                        ov,
1095                    )
1096                    .map_err(err)?
1097                },
1098                attn_out_norm: if sandwich {
1099                    Some(
1100                        load_f32(
1101                            model,
1102                            &format!("{prefix}post_attention_layernorm.weight"),
1103                            ov,
1104                        )
1105                        .map_err(err)?,
1106                    )
1107                } else {
1108                    None
1109                },
1110                ffn_out_norm: if sandwich {
1111                    Some(
1112                        load_f32(
1113                            model,
1114                            &format!("{prefix}post_feedforward_layernorm.weight"),
1115                            ov,
1116                        )
1117                        .map_err(err)?,
1118                    )
1119                } else {
1120                    None
1121                },
1122                // Gemma-4: learned scalar multiplying the layer output.
1123                layer_scale: model
1124                    .tensor(&format!("{prefix}layer_scalar"))
1125                    .and_then(|_| {
1126                        load_f32(model, &format!("{prefix}layer_scalar"), ov)
1127                            .ok()
1128                            .and_then(|v| v.first().copied())
1129                    }),
1130                // FFN always quantized — masks run sparse on quant bytes.
1131                ffn: build_layer_ffn(model, &arch, li, false, ov)?,
1132                attn,
1133            });
1134        }
1135
1136        // ── MTP head (optional, spec §2.1) ──
1137        //
1138        // The header declaring an MTP head is not the same as the file
1139        // carrying one. DeepSeek-V4's config announces a next-token predictor
1140        // whose weights the converter does not map (they are spelled `mtp.N.*`
1141        // and have none of the canonical projections), so demanding
1142        // `model.mtp.layers.0.self_attn.q_proj.weight` failed a model that is
1143        // otherwise complete. Presence in the directory decides.
1144        let mtp_present = model
1145            .tensor("model.mtp.layers.0.self_attn.q_proj.weight")
1146            .is_some()
1147            || model.tensor("model.mtp.eh_proj.weight").is_some();
1148        // DeepSeek-V4 writes its own stack under `model.mtp.N.*` — three full
1149        // layers, not a V3-style single block — so it cannot go through the
1150        // path below and is loaded by the dsv4 arm instead. Saying the file
1151        // "carries none" was a false negative worth six gigabytes.
1152        let dsv4_mtp = model.tensor("model.mtp.0.main_proj.weight").is_some();
1153        if arch.mtp.is_some() && !mtp_present && !dsv4_mtp {
1154            tracing::info!(
1155                "header declares an MTP head but the file carries none — \
1156                 loading without it"
1157            );
1158        }
1159        let mtp = if let Some(cfg) = arch.mtp.as_ref().filter(|_| mtp_present) {
1160            if cfg.num_layers != 1 {
1161                return Err(CmfError::Parse(format!(
1162                    "MTP with {} blocks not supported yet (only 1)",
1163                    cfg.num_layers
1164                )));
1165            }
1166            let p = "model.mtp.";
1167            let attn = load_full_attn("model.mtp.layers.0.", None)?;
1168            Some(MtpModule {
1169                enorm: load_f32(model, &format!("{p}enorm.weight"), ov).map_err(err)?,
1170                hnorm: load_f32(model, &format!("{p}hnorm.weight"), ov).map_err(err)?,
1171                eh_proj: load_matrix(model, &format!("{p}eh_proj.weight"), false, ov)?,
1172                layer: LayerWeights {
1173                    attn_out_norm: None,
1174                    ffn_out_norm: None,
1175                    layer_scale: None,
1176                    input_norm: load_f32(model, &format!("{p}layers.0.input_layernorm.weight"), ov)
1177                        .map_err(err)?,
1178                    post_norm: load_f32(
1179                        model,
1180                        &format!("{p}layers.0.post_attention_layernorm.weight"),
1181                        ov,
1182                    )
1183                    .map_err(err)?,
1184                    // Whatever the block actually carries: DeepSeek's MTP
1185                    // layer is dense, Qwen3.6's is a full MoE (router + 256
1186                    // experts + shared). Same builder as a backbone layer.
1187                    ffn: build_ffn_at(model, &arch, &format!("{p}layers.0."), false, ov)?,
1188                    attn,
1189                },
1190                final_norm: load_f32(model, &format!("{p}norm.weight"), ov).map_err(err)?,
1191                kv: LayerKvCache::new(arch.num_kv_heads, arch.head_dim),
1192            })
1193        } else {
1194            None
1195        };
1196
1197        tracing::info!(
1198            "Pipeline loaded: {} | {}L ({} linear) | {:.2}B params | storage: {} | MTP: {}",
1199            arch.arch_name,
1200            arch.num_layers,
1201            arch.layer_types
1202                .iter()
1203                .filter(|t| matches!(t, LayerType::LinearAttention))
1204                .count(),
1205            model.total_param_count() as f64 / 1e9,
1206            if force_f32 {
1207                "f32 (masked)"
1208            } else {
1209                "quantized mmap"
1210            },
1211            if mtp.is_some() { "yes" } else { "no" }
1212        );
1213
1214        // KV window: the descriptor's max, capped for dev-box safety;
1215        // CMF_MAX_SEQ overrides the cap (long-context runs).
1216        // 8192 was the silent quality cliff of the Qwen3.8 bring-up: at
1217        // the cap the wgpu token graph declines, the host evicts half the
1218        // KV, and a GDN hybrid's recurrent state goes stale — the model
1219        // stays fluent and loses its mind (Django internals, a Turkish
1220        // essay, an em-dash loop; one failure, three costumes). 32768
1221        // covers every long-form run we actually ship while keeping the
1222        // graph's device KV mirror affordable beside the weights;
1223        // CMF_MAX_SEQ still overrides in either direction.
1224        let cap = std::env::var("CMF_MAX_SEQ")
1225            .ok()
1226            .and_then(|v| v.parse::<usize>().ok())
1227            .unwrap_or(32_768);
1228        let max_seq_len = arch.max_position_embeddings.min(cap);
1229
1230        // Looped Transformer: total virtual layers = physical × num_loops.
1231        let total_layers = arch.num_layers * arch.num_loops;
1232
1233        let mut pipeline = Pipeline::new(
1234            tokenizer,
1235            PipelineWeights {
1236                embed_tokens,
1237                layers,
1238                lm_head,
1239                final_norm,
1240            },
1241            arch.hidden_size,
1242            arch.intermediate_size,
1243            arch.num_attention_heads,
1244            arch.num_kv_heads,
1245            arch.head_dim,
1246            total_layers,
1247            arch.num_layers, // physical layers in weights
1248            arch.loop_final_norm,
1249            arch.vocab_size,
1250            arch.rms_norm_eps,
1251            arch.rope_theta as f32,
1252            arch.norm_style,
1253            max_seq_len,
1254            sampler_config,
1255        );
1256        let rotary = ((arch.head_dim as f32 * arch.partial_rotary_factor) as usize).max(2);
1257        pipeline.set_rotary(rotary, arch.rope_theta as f32);
1258        pipeline.attention_heads_per_layer = arch.attention_heads_per_layer.clone();
1259        if let Some(yarn) = &arch.yarn {
1260            pipeline.inv_freq = std::sync::Arc::new(crate::attention::yarn_inv_freq(
1261                rotary,
1262                arch.rope_theta as f32,
1263                yarn.factor,
1264                yarn.original_max_position_embeddings,
1265                yarn.beta_fast,
1266                yarn.beta_slow,
1267            ));
1268            pipeline.rope_scale = yarn.attention_factor;
1269        }
1270        // Gemma-family extras: embedding scale, attention-scale
1271        // override, and (Gemma-3) sliding-window layers with their own
1272        // local RoPE base.
1273        pipeline.embed_multiplier = arch.embed_multiplier;
1274        pipeline.logit_multiplier = arch.logit_multiplier;
1275        if let Some(qpas) = arch.query_pre_attn_scalar {
1276            pipeline.attn_scale = 1.0 / (qpas as f32).sqrt();
1277        }
1278        if let (Some(w), Some(p)) = (arch.sliding_window, arch.sliding_window_pattern) {
1279            pipeline.swa = Some((w, p));
1280            if let Some(base) = arch.rope_local_base_freq {
1281                pipeline.inv_freq_local = Some(std::sync::Arc::new(
1282                    crate::attention::rope_inv_freq(rotary, base as f32),
1283                ));
1284            }
1285        }
1286        let explicit_sliding: Vec<bool> = arch
1287            .layer_types
1288            .iter()
1289            .map(|t| matches!(t, cortiq_core::LayerType::SlidingAttention))
1290            .collect();
1291        if explicit_sliding.iter().any(|&v| v) {
1292            pipeline.sliding_layers = Some(explicit_sliding);
1293            if let Some(w) = arch.sliding_window {
1294                pipeline.swa = Some((w, usize::MAX));
1295            }
1296            let local_rotary = ((arch.head_dim as f32
1297                * arch
1298                    .local_partial_rotary_factor
1299                    .unwrap_or(arch.partial_rotary_factor))
1300                as usize)
1301                .max(2);
1302            pipeline.rotary_dim_local = Some(local_rotary);
1303            if let Some(base) = arch.rope_local_base_freq {
1304                pipeline.inv_freq_local = Some(std::sync::Arc::new(
1305                    crate::attention::rope_inv_freq(local_rotary, base as f32),
1306                ));
1307            }
1308        }
1309        // Gemma-4: global layers run their own geometry (MQA at
1310        // global_head_dim) with a proportional RoPE — the first
1311        // factor·head_dim dims rotate, the zero-padded tail is identity.
1312        if let (Some(ghd), Some(gkv)) = (arch.global_head_dim, arch.num_global_kv_heads) {
1313            pipeline.global_attn = Some((ghd, gkv));
1314            let prf = arch.global_partial_rotary_factor.unwrap_or(1.0);
1315            let half = ghd / 2;
1316            let ra = (((prf * ghd as f32) as usize) / 2).min(half);
1317            let mut f = vec![0.0f32; half];
1318            for (i, slot) in f.iter_mut().enumerate().take(ra) {
1319                *slot = 1.0 / (arch.rope_theta as f32).powf(2.0 * i as f32 / ghd as f32);
1320            }
1321            pipeline.inv_freq_global = Some(std::sync::Arc::new(f));
1322            // Re-shape the global layers' KV storage to their geometry.
1323            // An explicit layer_types map wins over the numeric pattern
1324            // (explicit tags set swa's pattern to usize::MAX, which
1325            // would otherwise leave every global cache mis-shaped).
1326            let global_at = |li: usize| -> bool {
1327                match &pipeline.sliding_layers {
1328                    Some(map) => !map.get(li).copied().unwrap_or(false),
1329                    None => pipeline
1330                        .swa
1331                        .map(|(_, p)| p > 0 && p != usize::MAX && (li + 1) % p == 0)
1332                        .unwrap_or(false),
1333                }
1334            };
1335            for li in 0..arch.num_layers {
1336                if global_at(li) {
1337                    pipeline.kv_cache.layers[li] = crate::kv_cache::LayerKvCache::new(gkv, ghd);
1338                }
1339            }
1340        }
1341        // MLA (DeepSeek-V2): the expand-to-MHA cache holds nh heads of
1342        // rope+nope dims; rotary covers the rope prefix.
1343        if let Some(mla) = arch.mla.as_ref() {
1344            let hd = mla.qk_rope_head_dim + mla.qk_nope_head_dim;
1345            pipeline.head_dim = hd;
1346            pipeline.num_kv_heads = arch.num_attention_heads;
1347            pipeline.rotary_dim = mla.qk_rope_head_dim;
1348            let half = mla.qk_rope_head_dim / 2;
1349            let mut f = vec![0.0f32; half];
1350            for (i, slot) in f.iter_mut().enumerate() {
1351                *slot = 1.0
1352                    / (arch.rope_theta as f32).powf(2.0 * i as f32 / mla.qk_rope_head_dim as f32);
1353            }
1354            pipeline.inv_freq = std::sync::Arc::new(f);
1355            for li in 0..arch.num_layers {
1356                pipeline.kv_cache.layers[li] =
1357                    crate::kv_cache::LayerKvCache::new(arch.num_attention_heads, hd);
1358            }
1359        }
1360        // Per-frequency rope divisors (MiniCPM3 longrope short_factor):
1361        // served at the native window with the trained per-dim factors.
1362        // Applied after every inv_freq build (plain, YaRN, MLA).
1363        if let Some(fac) = &arch.rope_freq_factors {
1364            let mut f = pipeline.inv_freq.as_ref().clone();
1365            for (i, v) in f.iter_mut().enumerate() {
1366                if let Some(&d) = fac.get(i) {
1367                    *v /= d as f32;
1368                }
1369            }
1370            pipeline.inv_freq = std::sync::Arc::new(f);
1371        }
1372        pipeline.attn_v_norm = arch.attn_v_norm;
1373        pipeline.final_softcap = arch.final_logit_softcapping.map(|c| c as f32);
1374        // Cortiq Embryo hierarchical head: cluster matrix → two-level log-probs.
1375        if let Some(ncl) = arch.head_clusters {
1376            let cm = load_f32(model, "lm_head.clusters.weight", ov).map_err(err)?;
1377            if cm.len() != ncl * arch.hidden_size {
1378                return Err(CmfError::Parse(format!(
1379                    "lm_head.clusters.weight: {} != {ncl}×{}",
1380                    cm.len(),
1381                    arch.hidden_size
1382                )));
1383            }
1384            pipeline.head_clusters = Some(std::sync::Arc::new(cm));
1385        }
1386        pipeline.attn_softcap = arch.attn_logit_softcapping.unwrap_or(0.0) as f32;
1387        pipeline.vmf_cfg = vmf_cfg;
1388        pipeline.gdn_cfg = gdn_cfg;
1389        pipeline.kda_cfg = kda_cfg;
1390        if let Some(gc) = arch.g3n.as_ref() {
1391            use crate::g3n::{G3nAltUp, G3nGlobals, G3nLaurel, G3nLayer};
1392            anyhow_like(gc.altup_num_inputs == crate::g3n::ALTUP_N).map_err(|_| {
1393                CmfError::Parse(format!(
1394                    "g3n: altup_num_inputs {} != supported {}",
1395                    gc.altup_num_inputs,
1396                    crate::g3n::ALTUP_N
1397                ))
1398            })?;
1399            let t = |name: &str| load_matrix(model, name, force_f32, ov);
1400            let f = |name: &str| load_f32(model, name, ov).map_err(err);
1401            let mut altup_proj = Vec::new();
1402            let mut altup_unembed = Vec::new();
1403            for i in 0..crate::g3n::ALTUP_N - 1 {
1404                altup_proj.push(t(&format!("model.altup_projections.{i}.weight"))?);
1405                altup_unembed.push(t(&format!("model.altup_unembed_projections.{i}.weight"))?);
1406            }
1407            let first_shared = arch.num_layers.saturating_sub(gc.num_kv_shared_layers);
1408            let sliding_of = |li: usize| {
1409                matches!(
1410                    arch.layer_types.get(li),
1411                    Some(cortiq_core::LayerType::SlidingAttention)
1412                )
1413            };
1414            let mut g3n_layers = Vec::with_capacity(arch.num_layers);
1415            for li in 0..arch.num_layers {
1416                let pfx = format!("model.layers.{li}.");
1417                let shared = li >= first_shared && first_shared > 0;
1418                let share_src = if shared {
1419                    let want = sliding_of(li);
1420                    (0..first_shared).rev().find(|&j| sliding_of(j) == want)
1421                } else {
1422                    None
1423                };
1424                g3n_layers.push(G3nLayer {
1425                    altup: G3nAltUp {
1426                        router_norm: f(&format!("{pfx}altup.router_norm.weight"))?,
1427                        modality_router: t(&format!("{pfx}altup.modality_router.weight"))?,
1428                        prediction_coefs: t(&format!("{pfx}altup.prediction_coefs.weight"))?,
1429                        correction_coefs: t(&format!("{pfx}altup.correction_coefs.weight"))?,
1430                        correct_output_scale: f(&format!("{pfx}altup.correct_output_scale"))?,
1431                    },
1432                    laurel: G3nLaurel {
1433                        left: t(&format!("{pfx}laurel.linear_left.weight"))?,
1434                        right: t(&format!("{pfx}laurel.linear_right.weight"))?,
1435                        post_norm: f(&format!("{pfx}laurel.post_laurel_norm.weight"))?,
1436                    },
1437                    input_norm: f(&format!("{pfx}input_layernorm.weight"))?,
1438                    post_attn_norm: f(&format!("{pfx}post_attention_layernorm.weight"))?,
1439                    pre_ffw_norm: f(&format!("{pfx}pre_feedforward_layernorm.weight"))?,
1440                    post_ffw_norm: f(&format!("{pfx}post_feedforward_layernorm.weight"))?,
1441                    wq: t(&format!("{pfx}self_attn.q_proj.weight"))?,
1442                    wk: if shared {
1443                        None
1444                    } else {
1445                        Some(t(&format!("{pfx}self_attn.k_proj.weight"))?)
1446                    },
1447                    wv: if shared {
1448                        None
1449                    } else {
1450                        Some(t(&format!("{pfx}self_attn.v_proj.weight"))?)
1451                    },
1452                    wo: t(&format!("{pfx}self_attn.o_proj.weight"))?,
1453                    q_norm: f(&format!("{pfx}self_attn.q_norm.weight"))?,
1454                    k_norm: if shared {
1455                        None
1456                    } else {
1457                        Some(f(&format!("{pfx}self_attn.k_norm.weight"))?)
1458                    },
1459                    kv_share_src: share_src,
1460                    sliding: sliding_of(li),
1461                    gate: t(&format!("{pfx}mlp.gate_proj.weight"))?,
1462                    up: t(&format!("{pfx}mlp.up_proj.weight"))?,
1463                    down: t(&format!("{pfx}mlp.down_proj.weight"))?,
1464                    sparsity: gc.activation_sparsity.get(li).copied().unwrap_or(0.0),
1465                    ple_gate: t(&format!("{pfx}per_layer_input_gate.weight"))?,
1466                    ple_proj: t(&format!("{pfx}per_layer_projection.weight"))?,
1467                    post_ple_norm: f(&format!("{pfx}post_per_layer_input_norm.weight"))?,
1468                });
1469            }
1470            let hd = arch.head_dim;
1471            let globals = G3nGlobals {
1472                altup_proj,
1473                altup_unembed,
1474                ple_embed: t("model.embed_tokens_per_layer.weight")?,
1475                ple_model_proj: t("model.per_layer_model_projection.weight")?,
1476                ple_norm: f("model.per_layer_projection_norm.weight")?,
1477                ple_vocab: gc.ple_vocab,
1478                ple_dim: gc.ple_dim,
1479                num_layers: arch.num_layers,
1480                hidden: arch.hidden_size,
1481                rms_eps: arch.rms_norm_eps,
1482                inv_freq_local: crate::attention::rope_inv_freq(
1483                    hd,
1484                    arch.rope_local_base_freq.unwrap_or(10_000.0) as f32,
1485                ),
1486                inv_freq_global: crate::attention::rope_inv_freq(hd, arch.rope_theta as f32),
1487                window: arch.sliding_window.unwrap_or(512),
1488            };
1489            pipeline.g3n = Some(Box::new((globals, g3n_layers)));
1490        }
1491        // DeepSeek-V4: its own stack, selected by the arch name the
1492        // converter wrote. Loading failure is fatal rather than a silent
1493        // fallback — the generic loop cannot represent this model at all,
1494        // so a fallback would decode noise.
1495        if arch.arch_name == "deepseek_v4" {
1496            let moe = arch
1497                .moe
1498                .as_ref()
1499                .ok_or_else(|| CmfError::Parse("deepseek_v4: no moe config".into()))?;
1500            let cfg = crate::dsv4::Dsv4Cfg {
1501                dim: arch.hidden_size,
1502                n_heads: arch.num_attention_heads,
1503                head_dim: arch.head_dim,
1504                // The rope tail: `partial_rotary_factor` carries it when the
1505                // conversion recorded it (rd/head_dim), which the tensors
1506                // cannot reveal. Files converted before that carry 1.0,
1507                // meaning "unset" here rather than "rotate everything" —
1508                // for those the release's 64 stands in, which is what they
1509                // were converted from.
1510                rope_head_dim: if arch.partial_rotary_factor < 1.0 {
1511                    (((arch.head_dim as f32 * arch.partial_rotary_factor) as usize) & !1)
1512                        .clamp(2, arch.head_dim)
1513                } else {
1514                    64.min(arch.head_dim)
1515                },
1516                // The LoRA ranks and the group count ARE visible in the
1517                // weights, and reading them there means a re-tuned
1518                // checkpoint loads without touching this code.
1519                q_lora_rank: 0,
1520                o_lora_rank: 0,
1521                // Derived below from wo_a's shape — the attention output is
1522                // n_heads*head_dim wide and wo_a takes one group of it per
1523                // row block, so groups = width / wo_a.cols(). A pinned 8 is
1524                // right for the release and wrong for anything else, which
1525                // is exactly what made a toy checkpoint impossible to
1526                // compare against the reference.
1527                o_groups: 8,
1528                hc_mult: 4,
1529                hc_sinkhorn_iters: 20,
1530                hc_eps: 1e-6,
1531                norm_eps: arch.rms_norm_eps as f32,
1532                n_routed_experts: moe.num_experts,
1533                top_k: moe.top_k,
1534                moe_inter: moe.moe_intermediate_size,
1535                route_scale: moe.routed_scaling_factor.unwrap_or(1.0),
1536                // config.json's `swiglu_limit`, which the header has no
1537                // field for. The release ships 10.0; a checkpoint that
1538                // retunes it would need this read from the config, so it
1539                // sits next to the other pinned constants rather than
1540                // hiding inside the expert.
1541                swiglu_limit: 10.0,
1542                window: arch.sliding_window.unwrap_or(128),
1543                index_topk: 512,
1544                vocab: arch.vocab_size,
1545            };
1546            let (g, dl) = crate::dsv4::load(model, &cfg, arch.num_layers)
1547                .map_err(|e| CmfError::Parse(format!("deepseek_v4: {e}")))?;
1548            // Read the ranks off the weights that define them: wq_a's
1549            // rows ARE q_lora_rank, and wo_b's columns are groups x
1550            // o_lora_rank. A header field could disagree with the file;
1551            // these cannot.
1552            let mut cfg = cfg;
1553            if let Some(l0) = dl.first() {
1554                cfg.q_lora_rank = l0.wq_a.rows();
1555                let attn_width = arch.num_attention_heads * arch.head_dim;
1556                if l0.wo_a.cols() > 0 && attn_width % l0.wo_a.cols() == 0 {
1557                    cfg.o_groups = (attn_width / l0.wo_a.cols()).max(1);
1558                }
1559                cfg.o_lora_rank = l0.wo_b.cols() / cfg.o_groups.max(1);
1560                cfg.hc_mult = (l0.hc_attn_fn.len() / l0.hc_attn_base.len().max(1)) / cfg.dim.max(1);
1561                if cfg.hc_mult == 0 {
1562                    cfg.hc_mult = 4;
1563                }
1564            }
1565            // RoPE rides only the last `rope_head_dim` of each head, and the
1566            // reference builds its frequencies over THAT width — not over
1567            // head_dim, which is 512 here. The generic path above sized them
1568            // by head_dim, giving 1/base^(2i/512) where 1/base^(2i/64) is
1569            // wanted: every position rotated by the wrong angle.
1570            //
1571            // YaRN is applied unconditionally by the reference (its guard is
1572            // `original_seq_len > 0`, not the sequence length), so it belongs
1573            // in these frequencies too. Older configs spell the key `type`
1574            // rather than `rope_type`; when the header carries no profile the
1575            // release's own numbers stand in, which is better than silently
1576            // decoding with unscaled frequencies.
1577            let (yf, yo, ybf, ybs) = match &arch.yarn {
1578                Some(y) => (
1579                    y.factor,
1580                    y.original_max_position_embeddings,
1581                    y.beta_fast,
1582                    y.beta_slow,
1583                ),
1584                None => {
1585                    tracing::warn!(
1586                        "deepseek_v4: the header carries no YaRN profile — \
1587                         falling back to the release's (factor 16, original \
1588                         65536, beta 32/1). Re-converting with a build that \
1589                         reads rope_scaling.type would make this exact."
1590                    );
1591                    (16.0, 65536, 32.0, 1.0)
1592                }
1593            };
1594            pipeline.inv_freq = std::sync::Arc::new(crate::attention::yarn_inv_freq(
1595                cfg.rope_head_dim,
1596                arch.rope_theta as f32,
1597                yf,
1598                yo,
1599                ybf,
1600                ybs,
1601            ));
1602            // Keep the working set resident. Everything but the routed
1603            // experts is touched by every token, and of the experts only the
1604            // ones the task actually routes to — the page cache cannot know
1605            // that and evicts by age instead.
1606            if let Ok(stats) = std::env::var("CMF_MOE_PIN") {
1607                let cover = std::env::var("CMF_MOE_PIN_COVER")
1608                    .ok()
1609                    .and_then(|v| v.parse::<f64>().ok())
1610                    .filter(|&c| c > 0.0 && c <= 1.0)
1611                    .unwrap_or(0.95);
1612                let hot = crate::pin::hot_experts(&stats, cover);
1613                let mut names: Vec<String> = Vec::new();
1614                for e in &model.tensors {
1615                    let is_expert = e.name.contains(".mlp.experts.");
1616                    if !is_expert {
1617                        names.push(e.name.clone()); // skeleton: always hot
1618                    }
1619                }
1620                let mut kept_experts = 0usize;
1621                if let Some(hot) = &hot {
1622                    for (li, experts) in hot {
1623                        for e in experts {
1624                            for w in ["gate_proj", "up_proj", "down_proj"] {
1625                                names.push(format!("model.layers.{li}.mlp.experts.{e}.{w}.weight"));
1626                            }
1627                            kept_experts += 1;
1628                        }
1629                    }
1630                }
1631                let r = crate::pin::pin_tensors(model, &names);
1632                tracing::info!(
1633                    "закреплено {:.1} ГБ ({} тензоров, горячих экспертов {kept_experts},                      покрытие {cover}); лимит {}",
1634                    r.bytes as f64 / 1e9,
1635                    r.tensors,
1636                    r.limit
1637                        .map(|l| format!("{:.1} ГБ", l as f64 / 1e9))
1638                        .unwrap_or_else(|| "неизвестен".into())
1639                );
1640                if r.skipped > 0 {
1641                    tracing::warn!("не закреплено тензоров: {}", r.skipped);
1642                }
1643            }
1644            let st = crate::dsv4::Dsv4State::new(arch.num_layers);
1645            // The speculation stack, if the file carries one. Reading it is
1646            // metadata only — the expert weights stay in the mapping until a
1647            // draft actually runs — so it costs nothing to know it is there.
1648            let depth = std::env::var("CMF_DSV4_MTP_DEPTH")
1649                .ok()
1650                .and_then(|v| v.parse::<usize>().ok())
1651                .unwrap_or(3);
1652            pipeline.dsv4_mtp = crate::dsv4::load_mtp(model, &cfg, depth);
1653            // Before any trunk pack is built: leave the draft its VRAM.
1654            crate::dsv4::dspark_reserve_note(&pipeline.dsv4_mtp, &cfg, &dl);
1655            pipeline.dsv4 = Some(Box::new((g, dl, cfg, st)));
1656        }
1657        pipeline.short_conv_cfg = short_conv_cfg;
1658        pipeline.mtp = mtp;
1659        pipeline.install_dynamic_routing(model, false);
1660        // Record the load-time overlay so a later set_active_skill(None)
1661        // correctly reverts it (the union-diff assumes dyn_active mirrors
1662        // the live overlay). Blend loads have no single index to revert.
1663        match ov {
1664            Overlay::One(sid) => {
1665                pipeline.dyn_active = model.header.skills.iter().position(|s| &s.id == sid);
1666            }
1667            Overlay::Blend(_) => pipeline.dyn_blend_loaded = true,
1668            Overlay::None => {}
1669        }
1670        // B1: apply the measured confidence-calibration temperature, if the
1671        // file carries one (softmax(logits / T) for reported Born mass).
1672        if let Some(c) = &model.header.calibration {
1673            pipeline.set_calib_temp(c.temperature);
1674        }
1675        // O(1) Nyström attention (runtime-level, no format change):
1676        // env CMF_O1 decides; unset falls through to the converter hint
1677        // in header.provenance.o1_attn (`cortiq convert --o1`), and
1678        // CMF_O1=off force-disables even the hint. CLI flags override
1679        // later via set_o1().
1680        let o1 = match crate::nystrom::o1_from_env() {
1681            crate::nystrom::O1Env::Off => None,
1682            crate::nystrom::O1Env::On(cfg) => Some(cfg),
1683            crate::nystrom::O1Env::Unset => model
1684                .header
1685                .provenance
1686                .as_ref()
1687                .and_then(|p| p.get("o1_attn"))
1688                .and_then(crate::nystrom::O1Cfg::from_json),
1689        };
1690        if o1.is_some() {
1691            if pipeline.attn_softcap > 0.0 {
1692                return Err(CmfError::Parse(
1693                    "--o1 with attention-logit soft-capping (Gemma-2) is not supported: \
1694                     the streaming operator has no capped-score form"
1695                        .into(),
1696                ));
1697            }
1698            pipeline.set_o1(o1);
1699        }
1700        Ok(pipeline)
1701    }
1702
1703    /// Record per-skill dynamic-routing metadata: which FFN layers each
1704    /// skill actually replaces (derived from the tensors present, not
1705    /// the meta `layers` field), and whether the skill is eligible for
1706    /// cheap dynamic switching (FFN-only). Called once at load.
1707    pub(crate) fn install_dynamic_routing(&mut self, model: &Arc<CmfModel>, force_f32: bool) {
1708        self.model = Some(model.clone());
1709        self.dyn_force_f32 = force_f32;
1710        let mut per_skill = Vec::with_capacity(model.header.skills.len());
1711        for sk in &model.header.skills {
1712            let mut ffn_layers = std::collections::BTreeSet::new();
1713            let mut non_ffn = false;
1714            let prefix = format!("skill.{}.", sk.id);
1715            for t in model.skill_tensors(&sk.id) {
1716                let rel = &t.name[prefix.len()..]; // e.g. model.layers.20.mlp.down_proj.weight
1717                let toks: Vec<&str> = rel.split('.').collect();
1718                if toks.len() >= 5 && toks[0] == "model" && toks[1] == "layers" && toks[3] == "mlp"
1719                {
1720                    if let Ok(li) = toks[2].parse::<usize>() {
1721                        ffn_layers.insert(li);
1722                        continue;
1723                    }
1724                }
1725                non_ffn = true; // replaces attention / embed / lm_head
1726            }
1727            if non_ffn {
1728                tracing::warn!(
1729                    "skill '{}' replaces non-FFN tensors — excluded from dynamic \
1730                     routing (static overlay still works)",
1731                    sk.id
1732                );
1733                per_skill.push(None);
1734            } else {
1735                per_skill.push(Some(ffn_layers.into_iter().collect::<Vec<_>>()));
1736            }
1737        }
1738        self.dyn_skill_layers = per_skill;
1739    }
1740
1741    /// Switch the overlaid skill for subsequent forwards (dynamic
1742    /// routing). `idx` = index into model.header.skills; None = backbone.
1743    /// Rebuilds the FFN of the union of the old and new skill's touched
1744    /// layers with the new overlay — tensor-source indirection made
1745    /// dynamic. Cheap: Mapped tensors are re-resolved mmap pointers.
1746    /// Result is bit-identical to loading the pipeline with that skill.
1747    pub fn set_active_skill(&mut self, idx: Option<usize>) -> Result<(), CmfError> {
1748        // Overlay swap changes weights → every cached K/V is stale.
1749        self.kv_cache.clear();
1750        self.kv_history.clear();
1751        if self.dyn_active == idx {
1752            return Ok(());
1753        }
1754        let model = self.model.clone().ok_or_else(|| {
1755            CmfError::Parse("dynamic routing needs a model-backed pipeline".into())
1756        })?;
1757        let mut union: std::collections::BTreeSet<usize> = std::collections::BTreeSet::new();
1758        if let Some(old) = self.dyn_active {
1759            if let Some(Some(ls)) = self.dyn_skill_layers.get(old) {
1760                union.extend(ls.iter().copied());
1761            }
1762        }
1763        let new_id: Option<String> = match idx {
1764            Some(n) => match self.dyn_skill_layers.get(n) {
1765                Some(Some(ls)) => {
1766                    union.extend(ls.iter().copied());
1767                    Some(model.header.skills[n].id.clone())
1768                }
1769                _ => {
1770                    return Err(CmfError::Parse(format!(
1771                        "skill index {n} not dynamic-eligible"
1772                    )));
1773                }
1774            },
1775            None => None,
1776        };
1777        let ov = match &new_id {
1778            Some(s) => Overlay::One(s),
1779            None => Overlay::None,
1780        };
1781        let arch = model.arch();
1782        for li in union {
1783            self.weights.layers[li].ffn =
1784                build_layer_ffn(&model, arch, li, self.dyn_force_f32, &ov)?;
1785        }
1786        self.dyn_active = idx;
1787        Ok(())
1788    }
1789}