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