1use 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
28pub enum Overlay<'a> {
31 None,
32 One(&'a str),
33 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
57fn 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
87pub(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
107pub(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
122pub(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 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 Ok(DenseFfn {
158 gate_proj,
159 up_proj,
160 down_proj,
161 act: crate::pipeline::Act::from_arch_full(arch),
162 })
163 };
164 let router_name = format!("{prefix}mlp.gate.weight");
165 if model.tensor(&router_name).is_none() {
166 return Ok(FfnKind::Dense(load_dense(&format!("{prefix}mlp."))?));
167 }
168 let cfg = arch.moe.as_ref().ok_or_else(|| {
169 CmfError::Parse(format!(
170 "{router_name} present but header has no arch.moe block"
171 ))
172 })?;
173 let mut experts = Vec::new();
178 for e in 0..cfg.num_experts {
179 if model
180 .tensor(&format!("{prefix}mlp.experts.{e}.gate_proj.weight"))
181 .is_none()
182 {
183 break;
184 }
185 experts.push(load_dense(&format!("{prefix}mlp.experts.{e}."))?);
186 }
187 if experts.is_empty() {
188 return Err(CmfError::Parse(format!(
189 "{prefix}: router present but no expert tensors"
190 )));
191 }
192 let shared = if model
193 .tensor(&format!("{prefix}mlp.shared_expert.gate_proj.weight"))
194 .is_some()
195 {
196 let gate_name = format!("{prefix}mlp.shared_expert_gate.weight");
197 Some((
198 load_dense(&format!("{prefix}mlp.shared_expert."))?,
199 if model.tensor(&gate_name).is_some() {
200 Some(load_matrix(model, &gate_name, force_f32, ov)?)
201 } else {
202 None
203 },
204 ))
205 } else {
206 None
207 };
208 let bias_name = format!("{prefix}mlp.expert_bias");
211 let expert_bias = if model.tensor(&bias_name).is_some() {
212 Some(load_f32(model, &bias_name, ov).map_err(CmfError::Parse)?)
213 } else {
214 None
215 };
216 let top_k = std::env::var("CMF_MOE_TOPK")
222 .ok()
223 .and_then(|v| v.parse::<usize>().ok())
224 .filter(|&k| k >= 1 && k <= cfg.top_k)
225 .inspect(|k| tracing::info!("MoE top_k override: {} (header {})", k, cfg.top_k))
226 .unwrap_or(cfg.top_k);
227 let route_tau = std::env::var("CMF_MOE_TAU")
229 .ok()
230 .and_then(|v| v.parse::<f32>().ok())
231 .filter(|&t| t > 0.0 && t < 1.0)
232 .inspect(|t| tracing::info!("MoE adaptive routing: tau {t}"));
233 let mask = moe_task_mask(&prefix, experts.len());
234 let router = load_matrix(model, &router_name, force_f32, ov)?;
235 if router.rows() != experts.len() {
236 return Err(CmfError::Parse(format!(
237 "{router_name}: {} rows != {} experts",
238 router.rows(),
239 experts.len()
240 )));
241 }
242 let top_k = top_k.min(experts.len());
243 let pes_name = format!("{prefix}mlp.per_expert_scale");
247 let per_expert_scale = if model.tensor(&pes_name).is_some() {
248 Some(load_f32(model, &pes_name, ov).map_err(CmfError::Parse)?)
249 } else {
250 None
251 };
252 let router_input_norm = per_expert_scale.is_some();
253 let moe = MoeFfn {
254 router,
255 experts,
256 top_k,
257 route_tau,
258 norm_topk_prob: cfg.norm_topk_prob,
259 router_sigmoid: cfg.router_sigmoid,
260 expert_bias,
261 routed_scaling: cfg.routed_scaling_factor.unwrap_or(1.0),
262 shared,
263 stats: std::cell::RefCell::new(Vec::new()),
264 act_sq: std::cell::RefCell::new(Vec::new()),
265 act_rows: std::cell::RefCell::new(Vec::new()),
266 mask,
267 per_expert_scale,
268 router_input_norm,
269 };
270 if model
273 .tensor(&format!("{prefix}mlp.gate_proj.weight"))
274 .is_some()
275 {
276 let norm = |suffix: &str| -> Result<Vec<f32>, CmfError> {
277 load_f32(model, &format!("{prefix}{suffix}.weight"), ov).map_err(CmfError::Parse)
278 };
279 return Ok(FfnKind::DenseMoe(Box::new(crate::pipeline::DenseMoeFfn {
280 dense: load_dense(&format!("{prefix}mlp."))?,
281 moe,
282 post_norm_1: norm("post_feedforward_layernorm_1")?,
283 pre_norm_2: norm("pre_feedforward_layernorm_2")?,
284 post_norm_2: norm("post_feedforward_layernorm_2")?,
285 })));
286 }
287 Ok(FfnKind::Moe(moe))
288}
289
290pub(crate) fn moe_task_mask(prefix: &str, ne: usize) -> Option<Vec<bool>> {
298 use std::sync::OnceLock;
299 static CFG: OnceLock<Option<(std::collections::HashMap<usize, Vec<u64>>, f64)>> =
300 OnceLock::new();
301 let cfg = CFG.get_or_init(|| {
302 let path = std::env::var("CMF_MOE_MASK").ok()?;
303 let cover = std::env::var("CMF_MOE_MASK_COVER")
304 .ok()
305 .and_then(|v| v.parse::<f64>().ok())
306 .filter(|&c| c > 0.0 && c <= 1.0)
307 .unwrap_or(0.9);
308 let text = std::fs::read_to_string(&path)
309 .map_err(|e| tracing::warn!("CMF_MOE_MASK: cannot read {path}: {e}"))
310 .ok()?;
311 let map: std::collections::HashMap<String, Vec<u64>> = serde_json::from_str(&text)
312 .map_err(|e| tracing::warn!("CMF_MOE_MASK: bad JSON in {path}: {e}"))
313 .ok()?;
314 tracing::info!("MoE task mask: {path}, cover {cover}");
315 Some((
316 map.into_iter()
317 .filter_map(|(k, v)| Some((k.parse::<usize>().ok()?, v)))
318 .collect(),
319 cover,
320 ))
321 });
322 let (stats, cover) = cfg.as_ref()?;
323 let li: usize = prefix
325 .split("layers.")
326 .nth(1)?
327 .split('.')
328 .next()?
329 .parse()
330 .ok()?;
331 let counts = stats.get(&li)?;
332 if counts.len() != ne {
333 tracing::warn!(
334 "CMF_MOE_MASK: layer {li} has {} counts, model has {ne} experts — skipped",
335 counts.len()
336 );
337 return None;
338 }
339 let total: u64 = counts.iter().sum();
340 if total == 0 {
341 return None;
342 }
343 let mut order: Vec<usize> = (0..ne).collect();
344 order.sort_unstable_by_key(|&e| std::cmp::Reverse(counts[e]));
345 let mut mask = vec![false; ne];
346 let mut acc = 0u64;
347 let mut kept = 0usize;
348 for &e in &order {
349 mask[e] = true;
350 acc += counts[e];
351 kept += 1;
352 if (acc as f64) >= cover * (total as f64) {
353 break;
354 }
355 }
356 tracing::info!(
357 "MoE task mask L{li}: {kept}/{ne} experts for {:.0}% mass",
358 cover * 100.0
359 );
360 Some(mask)
361}
362
363fn load_matrix(
364 model: &Arc<CmfModel>,
365 name: &str,
366 force_f32: bool,
367 ov: &Overlay,
368) -> Result<QTensor, CmfError> {
369 if ov.blend_touches(model, name) {
373 if let Overlay::Blend(list) = ov {
374 let entry = model
375 .tensor(name)
376 .ok_or_else(|| CmfError::MissingTensor(name.to_string()))?;
377 let data =
378 blend_f32(model, name, list).map_err(|e| CmfError::Parse(format!("blend: {e}")))?;
379 return Ok(QTensor::from_f32(data, entry.shape[0], entry.shape[1]));
380 }
381 }
382 let skill = match ov {
383 Overlay::One(s) => Some(*s),
384 _ => None,
385 };
386 let name: &str = &match skill {
389 Some(sid) if model.tensor(&format!("skill.{sid}.{name}")).is_some() => {
390 format!("skill.{sid}.{name}")
391 }
392 _ => name.to_string(),
393 };
394 let err = |e: String| CmfError::Parse(format!("weight loading: {e}"));
395 if force_f32 {
396 let entry = model
397 .tensor(name)
398 .ok_or_else(|| CmfError::MissingTensor(name.to_string()))?;
399 if entry.shape.len() != 2 {
400 return Err(err(format!("'{name}' is not 2-D")));
401 }
402 let data = load_f32(model, name, &Overlay::None).map_err(err)?;
403 Ok(QTensor::from_f32(data, entry.shape[0], entry.shape[1]))
404 } else {
405 QTensor::from_model(model, name).map_err(err)
406 }
407}
408
409impl Pipeline {
410 pub fn from_model(
412 model: &Arc<CmfModel>,
413 sampler_config: SamplerConfig,
414 ) -> Result<Self, CmfError> {
415 Self::from_model_with_skill(model, sampler_config, None)
416 }
417
418 pub fn from_model_with_skill(
424 model: &Arc<CmfModel>,
425 sampler_config: SamplerConfig,
426 skill: Option<&str>,
427 ) -> Result<Self, CmfError> {
428 match skill {
429 Some(s) => Self::from_model_with_overlay(model, sampler_config, &Overlay::One(s)),
430 None => Self::from_model_with_overlay(model, sampler_config, &Overlay::None),
431 }
432 }
433
434 pub fn from_model_with_blend(
437 model: &Arc<CmfModel>,
438 sampler_config: SamplerConfig,
439 blend: &[(String, f32)],
440 ) -> Result<Self, CmfError> {
441 Self::from_model_with_overlay(model, sampler_config, &Overlay::Blend(blend))
442 }
443
444 fn skill_file_guard(model: &CmfModel) -> Result<(), CmfError> {
445 if model.required_features & cortiq_core::format::features::SKILL_FILE != 0 {
448 return Err(CmfError::Parse(
449 "this file is a standalone SKILL, not a runnable model — attach it: \
450 cortiq skill apply <base.cmf> <this file> -o specialist.cmf"
451 .into(),
452 ));
453 }
454 Ok(())
455 }
456
457 fn from_model_with_overlay(
458 model: &Arc<CmfModel>,
459 sampler_config: SamplerConfig,
460 ov: &Overlay,
461 ) -> Result<Self, CmfError> {
462 if let Some(dir) = model.path.parent() {
467 crate::gpu::set_cache_dir(dir.to_path_buf());
468 }
469 Self::skill_file_guard(model)?;
470 let skill = match ov {
471 Overlay::One(s) => Some(*s),
472 _ => None,
473 };
474 if let Some(sid) = skill {
475 let known = model.header.skills.iter().any(|s| s.id == sid)
476 || model.skill_tensors(sid).next().is_some();
477 if !known {
478 return Err(CmfError::Parse(format!(
479 "skill '{sid}' not in this container (header.skills: {:?})",
480 model
481 .header
482 .skills
483 .iter()
484 .map(|s| &s.id)
485 .collect::<Vec<_>>()
486 )));
487 }
488 tracing::info!(
489 "skill '{sid}': {} replacement tensors overlaid",
490 model.skill_tensors(sid).count()
491 );
492 }
493 let arch = model.arch().clone();
494 let err = |e: String| CmfError::Parse(format!("weight loading: {e}"));
495 if let Some(heads) = &arch.attention_heads_per_layer {
496 if heads.len() != arch.num_layers {
497 return Err(CmfError::Parse(format!(
498 "arch.attention_heads_per_layer has {} entries, expected {}",
499 heads.len(),
500 arch.num_layers
501 )));
502 }
503 if let Some((li, &nh)) = heads
504 .iter()
505 .enumerate()
506 .find(|(_, nh)| **nh == 0 || **nh % arch.num_kv_heads != 0)
507 {
508 return Err(CmfError::Parse(format!(
509 "layer {li} has {nh} Q heads, which must be nonzero and divisible by {} KV heads",
510 arch.num_kv_heads
511 )));
512 }
513 }
514 if arch
515 .layer_types
516 .iter()
517 .any(|t| matches!(t, LayerType::SlidingAttention))
518 && arch.sliding_window.is_none()
519 {
520 return Err(CmfError::Parse(
521 "model has SlidingAttention layers but no arch.sliding_window".into(),
522 ));
523 }
524
525 let heads_masked = model.masks.masks.iter().any(|m| {
535 m.head_masks.iter().any(|row| {
536 let mut bits = 0usize;
537 for &b in row.iter() {
538 bits += b.count_ones() as usize;
539 }
540 !row.is_empty() && bits < arch.num_attention_heads
541 })
542 });
543 let force_f32 = heads_masked; let mut tokenizer = if let Some(vocab_bytes) = &model.vocab {
547 Tokenizer::from_bytes(vocab_bytes)
548 .map_err(|e| CmfError::Parse(format!("embedded tokenizer: {e}")))?
549 } else {
550 let sidecar = model.path.with_file_name("tokenizer.json");
551 if sidecar.exists() {
552 Tokenizer::from_file(&sidecar)
553 .map_err(|e| CmfError::Parse(format!("sidecar tokenizer: {e}")))?
554 } else {
555 tracing::warn!("no tokenizer in file or sidecar — using byte-level fallback");
556 Tokenizer::byte_level()
557 }
558 };
559 if let Some(tc) = &model.header.tokenizer_config {
561 tokenizer.chat_template = tc.chat_template.clone();
562 tokenizer.extra_eos.extend(tc.eos_token_ids.iter().copied());
563 if tokenizer.bos_token_id.is_none() {
564 tokenizer.bos_token_id = tc.bos_token_id;
565 }
566 tracing::info!(
567 "chat bundle: template {} chars, {} stop ids",
568 tc.chat_template.as_deref().map(str::len).unwrap_or(0),
569 tc.eos_token_ids.len()
570 );
571 }
572 if arch.arch_name.to_lowercase().contains("gemma") && tokenizer.bos_token_id.is_some() {
576 tokenizer.add_bos = true;
577 }
578
579 let embed_tokens = load_matrix(model, "model.embed_tokens.weight", false, ov)?;
581 let final_norm = load_f32(model, "model.norm.weight", ov).map_err(err)?;
582 let lm_head = if model.tensor("lm_head.weight").is_some() {
583 load_matrix(model, "lm_head.weight", false, ov)?
584 } else if arch.tie_word_embeddings {
585 load_matrix(model, "model.embed_tokens.weight", false, ov)?
587 } else {
588 return Err(CmfError::MissingTensor(
589 "lm_head.weight (and tie_word_embeddings is false)".into(),
590 ));
591 };
592
593 let has_linear = arch
595 .layer_types
596 .iter()
597 .any(|t| matches!(t, LayerType::LinearAttention));
598 let mut vmf_cfg = None;
599 let mut gdn_cfg = None;
600 if has_linear {
601 let lc = arch.linear_core.as_ref().ok_or_else(|| {
602 CmfError::Parse(
603 "model has LinearAttention layers but no arch.linear_core — \
604 reconvert with the current converter"
605 .into(),
606 )
607 })?;
608 let need = |v: Option<usize>, name: &str| {
609 v.ok_or_else(|| CmfError::Parse(format!("linear core needs arch.{name}")))
610 };
611 match lc.kind.as_str() {
612 "vmf_phase" => {
613 vmf_cfg = Some(VmfPhaseCfg {
614 num_heads: lc.num_heads,
615 nphase: need(lc.nphase, "linear_core.nphase")?,
616 value_head_dim: lc.value_head_dim,
617 hidden_size: arch.hidden_size,
618 phase_mass: std::env::var("CMF_PHASE_MASS")
621 .ok()
622 .and_then(|v| v.parse().ok())
623 .unwrap_or(0.0),
624 });
625 }
626 "gated_delta_net" => {
627 gdn_cfg = Some(GdnCfg {
628 num_v_heads: lc.num_heads,
629 num_k_heads: need(arch.linear_num_key_heads, "linear_num_key_heads")?,
630 key_head_dim: need(arch.linear_key_head_dim, "linear_key_head_dim")?,
631 value_head_dim: lc.value_head_dim,
632 conv_kernel: need(arch.linear_conv_kernel_dim, "linear_conv_kernel_dim")?,
633 hidden_size: arch.hidden_size,
634 rms_eps: arch.rms_norm_eps,
635 });
636 }
637 other => {
638 return Err(CmfError::Parse(format!(
639 "unknown linear core '{other}' (this runtime executes: \
640 gated_delta_net, vmf_phase)"
641 )));
642 }
643 }
644 }
645
646 let has_kda = arch.layer_types.iter().any(|t| matches!(t, LayerType::Kda));
648 let kda_cfg = if has_kda {
649 let need = |v: Option<usize>, name: &str| {
650 v.ok_or_else(|| CmfError::Parse(format!("KDA core needs arch.{name}")))
651 };
652 Some(crate::linear_core::KdaCfg {
653 num_heads: need(arch.linear_num_key_heads, "linear_num_key_heads")?,
654 head_k_dim: need(arch.linear_key_head_dim, "linear_key_head_dim")?,
655 head_v_dim: need(arch.linear_value_head_dim, "linear_value_head_dim")?,
656 conv_kernel: need(arch.linear_conv_kernel_dim, "linear_conv_kernel_dim")?,
657 hidden_size: arch.hidden_size,
658 rms_eps: arch.rms_norm_eps,
659 })
660 } else {
661 None
662 };
663
664 let has_short_conv = arch
666 .layer_types
667 .iter()
668 .any(|t| matches!(t, LayerType::ShortConv));
669 let short_conv_cfg = if has_short_conv {
670 Some(ShortConvCfg {
671 hidden_size: arch.hidden_size,
672 kernel: arch.linear_conv_kernel_dim.ok_or_else(|| {
673 CmfError::Parse(
674 "model has ShortConv layers but no arch.linear_conv_kernel_dim — \
675 reconvert with the current converter"
676 .into(),
677 )
678 })?,
679 })
680 } else {
681 None
682 };
683
684 let load_full_attn = |prefix: &str, layer: Option<usize>| -> Result<AttnKind, CmfError> {
686 let t = |suffix: &str| load_matrix(model, &format!("{prefix}{suffix}"), force_f32, ov);
687 let n = |suffix: &str| -> Option<Vec<f32>> {
688 model
689 .tensor(&format!("{prefix}{suffix}"))
690 .and_then(|_| load_f32(model, &format!("{prefix}{suffix}"), ov).ok())
691 };
692 if let Some(mla) = arch.mla.as_ref() {
694 let (q_proj, q_a, q_a_norm) = if mla.q_lora_rank.is_some() {
696 (
697 t("self_attn.q_b_proj.weight")?,
698 Some(t("self_attn.q_a_proj.weight")?),
699 Some(n("self_attn.q_a_layernorm.weight").ok_or_else(|| {
700 CmfError::Parse(format!("{prefix}: MLA needs q_a_layernorm"))
701 })?),
702 )
703 } else {
704 (t("self_attn.q_proj.weight")?, None, None)
705 };
706 let hd = mla.qk_rope_head_dim + mla.qk_nope_head_dim;
707 let nh = q_proj.rows() / hd;
708 let mut scale = 1.0 / (hd as f32).sqrt();
711 if let Some(y) = arch.yarn.as_ref() {
712 if let Some(m) = y.mscale_all_dim.filter(|&m| m > 0.0) {
713 let ms = 0.1 * m * y.factor.ln() + 1.0;
714 scale *= ms * ms;
715 }
716 }
717 return Ok(AttnKind::Mla(Box::new(crate::pipeline::MlaWeights {
718 q_proj,
719 q_a,
720 q_a_norm,
721 kv_a: t("self_attn.kv_a_proj_with_mqa.weight")?,
722 kv_a_norm: n("self_attn.kv_a_layernorm.weight").ok_or_else(|| {
723 CmfError::Parse(format!("{prefix}: MLA needs kv_a_layernorm"))
724 })?,
725 kv_b: t("self_attn.kv_b_proj.weight")?,
726 o_proj: t("self_attn.o_proj.weight")?,
727 nh,
728 qk_rope: mla.qk_rope_head_dim,
729 qk_nope: mla.qk_nope_head_dim,
730 v_dim: mla.v_head_dim,
731 lora: mla.kv_lora_rank,
732 scale,
733 nope: mla.nope,
734 })));
735 }
736 let wq = t("self_attn.q_proj.weight")?;
737 let nh = layer
738 .and_then(|li| {
739 arch.attention_heads_per_layer
740 .as_ref()
741 .and_then(|v| v.get(li).copied())
742 })
743 .unwrap_or(arch.num_attention_heads);
744 let output_gate = arch.global_head_dim.is_none() && wq.rows() == 2 * nh * arch.head_dim;
748 let is_global_layer = arch.global_head_dim.is_some()
751 && layer.is_some_and(|li| {
752 arch.sliding_window_pattern
753 .is_some_and(|p| p > 0 && (li + 1) % p == 0)
754 });
755 let expect = if is_global_layer {
756 nh * arch.global_head_dim.unwrap_or(arch.head_dim)
757 } else {
758 nh * arch.head_dim
759 };
760 if !output_gate && wq.rows() != expect {
761 return Err(CmfError::Parse(format!(
762 "{prefix}self_attn.q_proj.weight rows={} != heads({nh}) * head_dim({})",
763 wq.rows(),
764 expect / nh.max(1)
765 )));
766 }
767 let gate_name = format!("{prefix}self_attn.g_proj.weight");
768 let softplus_gate = if model.tensor(&gate_name).is_some() {
769 let gate = load_matrix(model, &gate_name, force_f32, ov)?;
770 if gate.cols() != arch.hidden_size {
771 return Err(CmfError::Parse(format!(
772 "{gate_name} cols={} != hidden_size ({})",
773 gate.cols(),
774 arch.hidden_size
775 )));
776 }
777 let per_head = if gate.rows() == nh {
778 true
779 } else if gate.rows() == nh * arch.head_dim {
780 false
781 } else {
782 return Err(CmfError::Parse(format!(
783 "{gate_name} rows={} must equal heads ({nh}) or heads*head_dim ({})",
784 gate.rows(),
785 nh * arch.head_dim
786 )));
787 };
788 Some((gate, per_head))
789 } else {
790 None
791 };
792 let bias = match (
794 n("self_attn.q_proj.bias"),
795 n("self_attn.k_proj.bias"),
796 n("self_attn.v_proj.bias"),
797 ) {
798 (Some(a), Some(b), Some(c)) => Some((a, b, c)),
799 _ => None,
800 };
801 Ok(AttnKind::Full {
802 wq,
803 wk: t("self_attn.k_proj.weight")?,
804 wv: t("self_attn.v_proj.weight")?,
805 wo: t("self_attn.o_proj.weight")?,
806 q_norm: n("self_attn.q_norm.weight"),
807 k_norm: n("self_attn.k_norm.weight"),
808 output_gate,
809 softplus_gate,
810 bias,
811 })
812 };
813
814 let load_linear_attn = |prefix: &str| -> Result<AttnKind, CmfError> {
815 if gdn_cfg.is_some() {
816 let t = |suffix: &str| {
818 load_matrix(
819 model,
820 &format!("{prefix}linear_attn.{suffix}"),
821 force_f32,
822 ov,
823 )
824 };
825 let f = |suffix: &str| {
826 load_f32(model, &format!("{prefix}linear_attn.{suffix}"), ov).map_err(err)
827 };
828 return Ok(AttnKind::LinearGdn(GdnWeights {
829 in_proj_qkv: t("in_proj_qkv.weight")?,
830 in_proj_z: t("in_proj_z.weight")?,
831 in_proj_a: t("in_proj_a.weight")?,
832 in_proj_b: t("in_proj_b.weight")?,
833 conv1d: f("conv1d.weight")?,
834 a_log: f("A_log")?,
835 dt_bias: f("dt_bias")?,
836 norm: f("norm.weight")?,
837 out_proj: t("out_proj.weight")?,
838 }));
839 }
840 let t = |suffix: &str| {
841 load_matrix(model, &format!("{prefix}vmf_attn.{suffix}"), force_f32, ov)
842 };
843 let a_log = load_f32(model, &format!("{prefix}vmf_attn.A_log"), ov).map_err(err)?;
844 let k_gate = if model
848 .tensor(&format!("{prefix}vmf_attn.k_gate.weight"))
849 .is_some()
850 {
851 Some((
852 t("k_gate.weight")?,
853 load_f32(model, &format!("{prefix}vmf_attn.k_gate.bias"), ov).map_err(err)?,
854 ))
855 } else {
856 None
857 };
858 Ok(AttnKind::Linear(VmfPhaseWeights {
859 thq: t("thq.weight")?,
860 thk: t("thk.weight")?,
861 v_proj: t("v_proj.weight")?,
862 out_proj: t("out_proj.weight")?,
863 decay: a_log.iter().map(|&a| (-(a as f64).exp()).exp()).collect(),
864 k_gate,
865 }))
866 };
867
868 let load_short_conv = |prefix: &str| -> Result<AttnKind, CmfError> {
872 let t = |suffix: &str| {
873 load_matrix(
874 model,
875 &format!("{prefix}short_conv.{suffix}"),
876 force_f32,
877 ov,
878 )
879 };
880 Ok(AttnKind::ShortConv(ShortConvWeights {
881 in_proj: t("in_proj.weight")?,
882 conv: load_f32(model, &format!("{prefix}short_conv.conv.weight"), ov)
883 .map_err(err)?,
884 out_proj: t("out_proj.weight")?,
885 }))
886 };
887
888 let load_kda = |prefix: &str| -> Result<AttnKind, CmfError> {
892 let t = |suffix: &str| {
893 load_matrix(model, &format!("{prefix}kda_attn.{suffix}"), force_f32, ov)
894 };
895 let f = |suffix: &str| {
896 load_f32(model, &format!("{prefix}kda_attn.{suffix}"), ov).map_err(err)
897 };
898 let gate = if model
899 .tensor(&format!("{prefix}kda_attn.g_proj.weight"))
900 .is_some()
901 {
902 crate::linear_core::KdaOutGate::Full(t("g_proj.weight")?)
903 } else {
904 crate::linear_core::KdaOutGate::LowRank(
905 t("g_a_proj.weight")?,
906 t("g_b_proj.weight")?,
907 )
908 };
909 Ok(AttnKind::Kda(Box::new(crate::linear_core::KdaWeights {
910 q_proj: t("q_proj.weight")?,
911 k_proj: t("k_proj.weight")?,
912 v_proj: t("v_proj.weight")?,
913 conv_q: f("q_conv1d.weight")?,
914 conv_k: f("k_conv1d.weight")?,
915 conv_v: f("v_conv1d.weight")?,
916 f_a: t("f_a_proj.weight")?,
917 f_b: t("f_b_proj.weight")?,
918 dt_bias: f("dt_bias")?,
919 a_log: f("A_log")?,
920 b_proj: t("b_proj.weight")?,
921 gate,
922 o_norm: f("o_norm.weight")?,
923 o_proj: t("o_proj.weight")?,
924 gate_lower_bound: arch.kda_gate_lower_bound.map(|v| v as f32),
925 })))
926 };
927
928 fn anyhow_like(ok: bool) -> Result<(), ()> {
929 if ok { Ok(()) } else { Err(()) }
930 }
931 let mut layers = Vec::with_capacity(arch.num_layers);
932 let is_g3n = arch.g3n.is_some();
933 let owns_its_layers = is_g3n || arch.arch_name == "deepseek_v4";
938 for li in 0..(if owns_its_layers { 0 } else { arch.num_layers }) {
939 let prefix = format!("model.layers.{li}.");
940 let attn = match arch.layer_types.get(li) {
941 Some(LayerType::LinearAttention) => load_linear_attn(&prefix)?,
942 Some(LayerType::Kda) => load_kda(&prefix)?,
943 Some(LayerType::ShortConv) => load_short_conv(&prefix)?,
944 _ => load_full_attn(&prefix, Some(li))?,
945 };
946 let pre_ffn = format!("{prefix}pre_feedforward_layernorm.weight");
950 let sandwich = model.tensor(&pre_ffn).is_some();
951 layers.push(LayerWeights {
952 input_norm: load_f32(model, &format!("{prefix}input_layernorm.weight"), ov)
953 .map_err(err)?,
954 post_norm: if sandwich {
955 load_f32(model, &pre_ffn, ov).map_err(err)?
956 } else {
957 load_f32(
958 model,
959 &format!("{prefix}post_attention_layernorm.weight"),
960 ov,
961 )
962 .map_err(err)?
963 },
964 attn_out_norm: if sandwich {
965 Some(
966 load_f32(
967 model,
968 &format!("{prefix}post_attention_layernorm.weight"),
969 ov,
970 )
971 .map_err(err)?,
972 )
973 } else {
974 None
975 },
976 ffn_out_norm: if sandwich {
977 Some(
978 load_f32(
979 model,
980 &format!("{prefix}post_feedforward_layernorm.weight"),
981 ov,
982 )
983 .map_err(err)?,
984 )
985 } else {
986 None
987 },
988 layer_scale: model
990 .tensor(&format!("{prefix}layer_scalar"))
991 .and_then(|_| {
992 load_f32(model, &format!("{prefix}layer_scalar"), ov)
993 .ok()
994 .and_then(|v| v.first().copied())
995 }),
996 ffn: build_layer_ffn(model, &arch, li, false, ov)?,
998 attn,
999 });
1000 }
1001
1002 let mtp_present = model
1011 .tensor("model.mtp.layers.0.self_attn.q_proj.weight")
1012 .is_some()
1013 || model.tensor("model.mtp.eh_proj.weight").is_some();
1014 let dsv4_mtp = model.tensor("model.mtp.0.main_proj.weight").is_some();
1019 if arch.mtp.is_some() && !mtp_present && !dsv4_mtp {
1020 tracing::info!(
1021 "header declares an MTP head but the file carries none — \
1022 loading without it"
1023 );
1024 }
1025 let mtp = if let Some(cfg) = arch.mtp.as_ref().filter(|_| mtp_present) {
1026 if cfg.num_layers != 1 {
1027 return Err(CmfError::Parse(format!(
1028 "MTP with {} blocks not supported yet (only 1)",
1029 cfg.num_layers
1030 )));
1031 }
1032 let p = "model.mtp.";
1033 let attn = load_full_attn("model.mtp.layers.0.", None)?;
1034 Some(MtpModule {
1035 enorm: load_f32(model, &format!("{p}enorm.weight"), ov).map_err(err)?,
1036 hnorm: load_f32(model, &format!("{p}hnorm.weight"), ov).map_err(err)?,
1037 eh_proj: load_matrix(model, &format!("{p}eh_proj.weight"), false, ov)?,
1038 layer: LayerWeights {
1039 attn_out_norm: None,
1040 ffn_out_norm: None,
1041 layer_scale: None,
1042 input_norm: load_f32(model, &format!("{p}layers.0.input_layernorm.weight"), ov)
1043 .map_err(err)?,
1044 post_norm: load_f32(
1045 model,
1046 &format!("{p}layers.0.post_attention_layernorm.weight"),
1047 ov,
1048 )
1049 .map_err(err)?,
1050 ffn: build_ffn_at(model, &arch, &format!("{p}layers.0."), false, ov)?,
1054 attn,
1055 },
1056 final_norm: load_f32(model, &format!("{p}norm.weight"), ov).map_err(err)?,
1057 kv: LayerKvCache::new(arch.num_kv_heads, arch.head_dim),
1058 })
1059 } else {
1060 None
1061 };
1062
1063 tracing::info!(
1064 "Pipeline loaded: {} | {}L ({} linear) | {:.2}B params | storage: {} | MTP: {}",
1065 arch.arch_name,
1066 arch.num_layers,
1067 arch.layer_types
1068 .iter()
1069 .filter(|t| matches!(t, LayerType::LinearAttention))
1070 .count(),
1071 model.total_param_count() as f64 / 1e9,
1072 if force_f32 {
1073 "f32 (masked)"
1074 } else {
1075 "quantized mmap"
1076 },
1077 if mtp.is_some() { "yes" } else { "no" }
1078 );
1079
1080 let cap = std::env::var("CMF_MAX_SEQ")
1083 .ok()
1084 .and_then(|v| v.parse::<usize>().ok())
1085 .unwrap_or(8192);
1086 let max_seq_len = arch.max_position_embeddings.min(cap);
1087
1088 let total_layers = arch.num_layers * arch.num_loops;
1090
1091 let mut pipeline = Pipeline::new(
1092 tokenizer,
1093 PipelineWeights {
1094 embed_tokens,
1095 layers,
1096 lm_head,
1097 final_norm,
1098 },
1099 arch.hidden_size,
1100 arch.intermediate_size,
1101 arch.num_attention_heads,
1102 arch.num_kv_heads,
1103 arch.head_dim,
1104 total_layers,
1105 arch.num_layers, arch.loop_final_norm,
1107 arch.vocab_size,
1108 arch.rms_norm_eps,
1109 arch.rope_theta as f32,
1110 arch.norm_style,
1111 max_seq_len,
1112 sampler_config,
1113 );
1114 let rotary = ((arch.head_dim as f32 * arch.partial_rotary_factor) as usize).max(2);
1115 pipeline.set_rotary(rotary, arch.rope_theta as f32);
1116 pipeline.attention_heads_per_layer = arch.attention_heads_per_layer.clone();
1117 if let Some(yarn) = &arch.yarn {
1118 pipeline.inv_freq = std::sync::Arc::new(crate::attention::yarn_inv_freq(
1119 rotary,
1120 arch.rope_theta as f32,
1121 yarn.factor,
1122 yarn.original_max_position_embeddings,
1123 yarn.beta_fast,
1124 yarn.beta_slow,
1125 ));
1126 pipeline.rope_scale = yarn.attention_factor;
1127 }
1128 pipeline.embed_multiplier = arch.embed_multiplier;
1132 pipeline.logit_multiplier = arch.logit_multiplier;
1133 if let Some(qpas) = arch.query_pre_attn_scalar {
1134 pipeline.attn_scale = 1.0 / (qpas as f32).sqrt();
1135 }
1136 if let (Some(w), Some(p)) = (arch.sliding_window, arch.sliding_window_pattern) {
1137 pipeline.swa = Some((w, p));
1138 if let Some(base) = arch.rope_local_base_freq {
1139 pipeline.inv_freq_local = Some(std::sync::Arc::new(
1140 crate::attention::rope_inv_freq(rotary, base as f32),
1141 ));
1142 }
1143 }
1144 let explicit_sliding: Vec<bool> = arch
1145 .layer_types
1146 .iter()
1147 .map(|t| matches!(t, cortiq_core::LayerType::SlidingAttention))
1148 .collect();
1149 if explicit_sliding.iter().any(|&v| v) {
1150 pipeline.sliding_layers = Some(explicit_sliding);
1151 if let Some(w) = arch.sliding_window {
1152 pipeline.swa = Some((w, usize::MAX));
1153 }
1154 let local_rotary = ((arch.head_dim as f32
1155 * arch
1156 .local_partial_rotary_factor
1157 .unwrap_or(arch.partial_rotary_factor))
1158 as usize)
1159 .max(2);
1160 pipeline.rotary_dim_local = Some(local_rotary);
1161 if let Some(base) = arch.rope_local_base_freq {
1162 pipeline.inv_freq_local = Some(std::sync::Arc::new(
1163 crate::attention::rope_inv_freq(local_rotary, base as f32),
1164 ));
1165 }
1166 }
1167 if let (Some(ghd), Some(gkv)) = (arch.global_head_dim, arch.num_global_kv_heads) {
1171 pipeline.global_attn = Some((ghd, gkv));
1172 let prf = arch.global_partial_rotary_factor.unwrap_or(1.0);
1173 let half = ghd / 2;
1174 let ra = (((prf * ghd as f32) as usize) / 2).min(half);
1175 let mut f = vec![0.0f32; half];
1176 for (i, slot) in f.iter_mut().enumerate().take(ra) {
1177 *slot = 1.0 / (arch.rope_theta as f32).powf(2.0 * i as f32 / ghd as f32);
1178 }
1179 pipeline.inv_freq_global = Some(std::sync::Arc::new(f));
1180 let global_at = |li: usize| -> bool {
1185 match &pipeline.sliding_layers {
1186 Some(map) => !map.get(li).copied().unwrap_or(false),
1187 None => pipeline
1188 .swa
1189 .map(|(_, p)| p > 0 && p != usize::MAX && (li + 1) % p == 0)
1190 .unwrap_or(false),
1191 }
1192 };
1193 for li in 0..arch.num_layers {
1194 if global_at(li) {
1195 pipeline.kv_cache.layers[li] = crate::kv_cache::LayerKvCache::new(gkv, ghd);
1196 }
1197 }
1198 }
1199 if let Some(mla) = arch.mla.as_ref() {
1202 let hd = mla.qk_rope_head_dim + mla.qk_nope_head_dim;
1203 pipeline.head_dim = hd;
1204 pipeline.num_kv_heads = arch.num_attention_heads;
1205 pipeline.rotary_dim = mla.qk_rope_head_dim;
1206 let half = mla.qk_rope_head_dim / 2;
1207 let mut f = vec![0.0f32; half];
1208 for (i, slot) in f.iter_mut().enumerate() {
1209 *slot = 1.0
1210 / (arch.rope_theta as f32).powf(2.0 * i as f32 / mla.qk_rope_head_dim as f32);
1211 }
1212 pipeline.inv_freq = std::sync::Arc::new(f);
1213 for li in 0..arch.num_layers {
1214 pipeline.kv_cache.layers[li] =
1215 crate::kv_cache::LayerKvCache::new(arch.num_attention_heads, hd);
1216 }
1217 }
1218 if let Some(fac) = &arch.rope_freq_factors {
1222 let mut f = pipeline.inv_freq.as_ref().clone();
1223 for (i, v) in f.iter_mut().enumerate() {
1224 if let Some(&d) = fac.get(i) {
1225 *v /= d as f32;
1226 }
1227 }
1228 pipeline.inv_freq = std::sync::Arc::new(f);
1229 }
1230 pipeline.attn_v_norm = arch.attn_v_norm;
1231 pipeline.final_softcap = arch.final_logit_softcapping.map(|c| c as f32);
1232 pipeline.attn_softcap = arch.attn_logit_softcapping.unwrap_or(0.0) as f32;
1233 pipeline.vmf_cfg = vmf_cfg;
1234 pipeline.gdn_cfg = gdn_cfg;
1235 pipeline.kda_cfg = kda_cfg;
1236 if let Some(gc) = arch.g3n.as_ref() {
1237 use crate::g3n::{G3nAltUp, G3nGlobals, G3nLaurel, G3nLayer};
1238 anyhow_like(gc.altup_num_inputs == crate::g3n::ALTUP_N).map_err(|_| {
1239 CmfError::Parse(format!(
1240 "g3n: altup_num_inputs {} != supported {}",
1241 gc.altup_num_inputs,
1242 crate::g3n::ALTUP_N
1243 ))
1244 })?;
1245 let t = |name: &str| load_matrix(model, name, force_f32, ov);
1246 let f = |name: &str| load_f32(model, name, ov).map_err(err);
1247 let mut altup_proj = Vec::new();
1248 let mut altup_unembed = Vec::new();
1249 for i in 0..crate::g3n::ALTUP_N - 1 {
1250 altup_proj.push(t(&format!("model.altup_projections.{i}.weight"))?);
1251 altup_unembed.push(t(&format!("model.altup_unembed_projections.{i}.weight"))?);
1252 }
1253 let first_shared = arch.num_layers.saturating_sub(gc.num_kv_shared_layers);
1254 let sliding_of = |li: usize| {
1255 matches!(
1256 arch.layer_types.get(li),
1257 Some(cortiq_core::LayerType::SlidingAttention)
1258 )
1259 };
1260 let mut g3n_layers = Vec::with_capacity(arch.num_layers);
1261 for li in 0..arch.num_layers {
1262 let pfx = format!("model.layers.{li}.");
1263 let shared = li >= first_shared && first_shared > 0;
1264 let share_src = if shared {
1265 let want = sliding_of(li);
1266 (0..first_shared).rev().find(|&j| sliding_of(j) == want)
1267 } else {
1268 None
1269 };
1270 g3n_layers.push(G3nLayer {
1271 altup: G3nAltUp {
1272 router_norm: f(&format!("{pfx}altup.router_norm.weight"))?,
1273 modality_router: t(&format!("{pfx}altup.modality_router.weight"))?,
1274 prediction_coefs: t(&format!("{pfx}altup.prediction_coefs.weight"))?,
1275 correction_coefs: t(&format!("{pfx}altup.correction_coefs.weight"))?,
1276 correct_output_scale: f(&format!("{pfx}altup.correct_output_scale"))?,
1277 },
1278 laurel: G3nLaurel {
1279 left: t(&format!("{pfx}laurel.linear_left.weight"))?,
1280 right: t(&format!("{pfx}laurel.linear_right.weight"))?,
1281 post_norm: f(&format!("{pfx}laurel.post_laurel_norm.weight"))?,
1282 },
1283 input_norm: f(&format!("{pfx}input_layernorm.weight"))?,
1284 post_attn_norm: f(&format!("{pfx}post_attention_layernorm.weight"))?,
1285 pre_ffw_norm: f(&format!("{pfx}pre_feedforward_layernorm.weight"))?,
1286 post_ffw_norm: f(&format!("{pfx}post_feedforward_layernorm.weight"))?,
1287 wq: t(&format!("{pfx}self_attn.q_proj.weight"))?,
1288 wk: if shared {
1289 None
1290 } else {
1291 Some(t(&format!("{pfx}self_attn.k_proj.weight"))?)
1292 },
1293 wv: if shared {
1294 None
1295 } else {
1296 Some(t(&format!("{pfx}self_attn.v_proj.weight"))?)
1297 },
1298 wo: t(&format!("{pfx}self_attn.o_proj.weight"))?,
1299 q_norm: f(&format!("{pfx}self_attn.q_norm.weight"))?,
1300 k_norm: if shared {
1301 None
1302 } else {
1303 Some(f(&format!("{pfx}self_attn.k_norm.weight"))?)
1304 },
1305 kv_share_src: share_src,
1306 sliding: sliding_of(li),
1307 gate: t(&format!("{pfx}mlp.gate_proj.weight"))?,
1308 up: t(&format!("{pfx}mlp.up_proj.weight"))?,
1309 down: t(&format!("{pfx}mlp.down_proj.weight"))?,
1310 sparsity: gc.activation_sparsity.get(li).copied().unwrap_or(0.0),
1311 ple_gate: t(&format!("{pfx}per_layer_input_gate.weight"))?,
1312 ple_proj: t(&format!("{pfx}per_layer_projection.weight"))?,
1313 post_ple_norm: f(&format!("{pfx}post_per_layer_input_norm.weight"))?,
1314 });
1315 }
1316 let hd = arch.head_dim;
1317 let globals = G3nGlobals {
1318 altup_proj,
1319 altup_unembed,
1320 ple_embed: t("model.embed_tokens_per_layer.weight")?,
1321 ple_model_proj: t("model.per_layer_model_projection.weight")?,
1322 ple_norm: f("model.per_layer_projection_norm.weight")?,
1323 ple_vocab: gc.ple_vocab,
1324 ple_dim: gc.ple_dim,
1325 num_layers: arch.num_layers,
1326 hidden: arch.hidden_size,
1327 rms_eps: arch.rms_norm_eps,
1328 inv_freq_local: crate::attention::rope_inv_freq(
1329 hd,
1330 arch.rope_local_base_freq.unwrap_or(10_000.0) as f32,
1331 ),
1332 inv_freq_global: crate::attention::rope_inv_freq(hd, arch.rope_theta as f32),
1333 window: arch.sliding_window.unwrap_or(512),
1334 };
1335 pipeline.g3n = Some(Box::new((globals, g3n_layers)));
1336 }
1337 if arch.arch_name == "deepseek_v4" {
1342 let moe = arch
1343 .moe
1344 .as_ref()
1345 .ok_or_else(|| CmfError::Parse("deepseek_v4: no moe config".into()))?;
1346 let cfg = crate::dsv4::Dsv4Cfg {
1347 dim: arch.hidden_size,
1348 n_heads: arch.num_attention_heads,
1349 head_dim: arch.head_dim,
1350 rope_head_dim: if arch.partial_rotary_factor < 1.0 {
1357 (((arch.head_dim as f32 * arch.partial_rotary_factor) as usize) & !1)
1358 .clamp(2, arch.head_dim)
1359 } else {
1360 64.min(arch.head_dim)
1361 },
1362 q_lora_rank: 0,
1366 o_lora_rank: 0,
1367 o_groups: 8,
1374 hc_mult: 4,
1375 hc_sinkhorn_iters: 20,
1376 hc_eps: 1e-6,
1377 norm_eps: arch.rms_norm_eps as f32,
1378 n_routed_experts: moe.num_experts,
1379 top_k: moe.top_k,
1380 moe_inter: moe.moe_intermediate_size,
1381 route_scale: moe.routed_scaling_factor.unwrap_or(1.0) as f32,
1382 swiglu_limit: 10.0,
1388 window: arch.sliding_window.unwrap_or(128),
1389 index_topk: 512,
1390 vocab: arch.vocab_size,
1391 };
1392 let (g, dl) = crate::dsv4::load(model, &cfg, arch.num_layers)
1393 .map_err(|e| CmfError::Parse(format!("deepseek_v4: {e}")))?;
1394 let mut cfg = cfg;
1399 if let Some(l0) = dl.first() {
1400 cfg.q_lora_rank = l0.wq_a.rows();
1401 let attn_width = arch.num_attention_heads * arch.head_dim;
1402 if l0.wo_a.cols() > 0 && attn_width % l0.wo_a.cols() == 0 {
1403 cfg.o_groups = (attn_width / l0.wo_a.cols()).max(1);
1404 }
1405 cfg.o_lora_rank = l0.wo_b.cols() / cfg.o_groups.max(1);
1406 cfg.hc_mult = (l0.hc_attn_fn.len() / l0.hc_attn_base.len().max(1)) / cfg.dim.max(1);
1407 if cfg.hc_mult == 0 {
1408 cfg.hc_mult = 4;
1409 }
1410 }
1411 let (yf, yo, ybf, ybs) = match &arch.yarn {
1424 Some(y) => (
1425 y.factor,
1426 y.original_max_position_embeddings,
1427 y.beta_fast,
1428 y.beta_slow,
1429 ),
1430 None => {
1431 tracing::warn!(
1432 "deepseek_v4: the header carries no YaRN profile — \
1433 falling back to the release's (factor 16, original \
1434 65536, beta 32/1). Re-converting with a build that \
1435 reads rope_scaling.type would make this exact."
1436 );
1437 (16.0, 65536, 32.0, 1.0)
1438 }
1439 };
1440 pipeline.inv_freq = std::sync::Arc::new(crate::attention::yarn_inv_freq(
1441 cfg.rope_head_dim,
1442 arch.rope_theta as f32,
1443 yf,
1444 yo,
1445 ybf,
1446 ybs,
1447 ));
1448 if let Ok(stats) = std::env::var("CMF_MOE_PIN") {
1453 let cover = std::env::var("CMF_MOE_PIN_COVER")
1454 .ok()
1455 .and_then(|v| v.parse::<f64>().ok())
1456 .filter(|&c| c > 0.0 && c <= 1.0)
1457 .unwrap_or(0.95);
1458 let hot = crate::pin::hot_experts(&stats, cover);
1459 let mut names: Vec<String> = Vec::new();
1460 for e in &model.tensors {
1461 let is_expert = e.name.contains(".mlp.experts.");
1462 if !is_expert {
1463 names.push(e.name.clone()); }
1465 }
1466 let mut kept_experts = 0usize;
1467 if let Some(hot) = &hot {
1468 for (li, experts) in hot {
1469 for e in experts {
1470 for w in ["gate_proj", "up_proj", "down_proj"] {
1471 names.push(format!("model.layers.{li}.mlp.experts.{e}.{w}.weight"));
1472 }
1473 kept_experts += 1;
1474 }
1475 }
1476 }
1477 let r = crate::pin::pin_tensors(model, &names);
1478 tracing::info!(
1479 "закреплено {:.1} ГБ ({} тензоров, горячих экспертов {kept_experts}, покрытие {cover}); лимит {}",
1480 r.bytes as f64 / 1e9,
1481 r.tensors,
1482 r.limit
1483 .map(|l| format!("{:.1} ГБ", l as f64 / 1e9))
1484 .unwrap_or_else(|| "неизвестен".into())
1485 );
1486 if r.skipped > 0 {
1487 tracing::warn!("не закреплено тензоров: {}", r.skipped);
1488 }
1489 }
1490 let st = crate::dsv4::Dsv4State::new(arch.num_layers);
1491 let depth = std::env::var("CMF_DSV4_MTP_DEPTH")
1495 .ok()
1496 .and_then(|v| v.parse::<usize>().ok())
1497 .unwrap_or(3);
1498 pipeline.dsv4_mtp = crate::dsv4::load_mtp(model, &cfg, depth);
1499 crate::dsv4::dspark_reserve_note(&pipeline.dsv4_mtp, &cfg, &dl);
1501 pipeline.dsv4 = Some(Box::new((g, dl, cfg, st)));
1502 }
1503 pipeline.short_conv_cfg = short_conv_cfg;
1504 pipeline.mtp = mtp;
1505 pipeline.install_dynamic_routing(model, false);
1506 match ov {
1510 Overlay::One(sid) => {
1511 pipeline.dyn_active = model.header.skills.iter().position(|s| &s.id == sid);
1512 }
1513 Overlay::Blend(_) => pipeline.dyn_blend_loaded = true,
1514 Overlay::None => {}
1515 }
1516 if let Some(c) = &model.header.calibration {
1519 pipeline.set_calib_temp(c.temperature);
1520 }
1521 let o1 = match crate::nystrom::o1_from_env() {
1527 crate::nystrom::O1Env::Off => None,
1528 crate::nystrom::O1Env::On(cfg) => Some(cfg),
1529 crate::nystrom::O1Env::Unset => model
1530 .header
1531 .provenance
1532 .as_ref()
1533 .and_then(|p| p.get("o1_attn"))
1534 .and_then(crate::nystrom::O1Cfg::from_json),
1535 };
1536 if o1.is_some() {
1537 if pipeline.attn_softcap > 0.0 {
1538 return Err(CmfError::Parse(
1539 "--o1 with attention-logit soft-capping (Gemma-2) is not supported: \
1540 the streaming operator has no capped-score form"
1541 .into(),
1542 ));
1543 }
1544 pipeline.set_o1(o1);
1545 }
1546 Ok(pipeline)
1547 }
1548
1549 pub(crate) fn install_dynamic_routing(&mut self, model: &Arc<CmfModel>, force_f32: bool) {
1554 self.model = Some(model.clone());
1555 self.dyn_force_f32 = force_f32;
1556 let mut per_skill = Vec::with_capacity(model.header.skills.len());
1557 for sk in &model.header.skills {
1558 let mut ffn_layers = std::collections::BTreeSet::new();
1559 let mut non_ffn = false;
1560 let prefix = format!("skill.{}.", sk.id);
1561 for t in model.skill_tensors(&sk.id) {
1562 let rel = &t.name[prefix.len()..]; let toks: Vec<&str> = rel.split('.').collect();
1564 if toks.len() >= 5 && toks[0] == "model" && toks[1] == "layers" && toks[3] == "mlp"
1565 {
1566 if let Ok(li) = toks[2].parse::<usize>() {
1567 ffn_layers.insert(li);
1568 continue;
1569 }
1570 }
1571 non_ffn = true; }
1573 if non_ffn {
1574 tracing::warn!(
1575 "skill '{}' replaces non-FFN tensors — excluded from dynamic \
1576 routing (static overlay still works)",
1577 sk.id
1578 );
1579 per_skill.push(None);
1580 } else {
1581 per_skill.push(Some(ffn_layers.into_iter().collect::<Vec<_>>()));
1582 }
1583 }
1584 self.dyn_skill_layers = per_skill;
1585 }
1586
1587 pub fn set_active_skill(&mut self, idx: Option<usize>) -> Result<(), CmfError> {
1594 self.kv_cache.clear();
1596 self.kv_history.clear();
1597 if self.dyn_active == idx {
1598 return Ok(());
1599 }
1600 let model = self.model.clone().ok_or_else(|| {
1601 CmfError::Parse("dynamic routing needs a model-backed pipeline".into())
1602 })?;
1603 let mut union: std::collections::BTreeSet<usize> = std::collections::BTreeSet::new();
1604 if let Some(old) = self.dyn_active {
1605 if let Some(Some(ls)) = self.dyn_skill_layers.get(old) {
1606 union.extend(ls.iter().copied());
1607 }
1608 }
1609 let new_id: Option<String> = match idx {
1610 Some(n) => match self.dyn_skill_layers.get(n) {
1611 Some(Some(ls)) => {
1612 union.extend(ls.iter().copied());
1613 Some(model.header.skills[n].id.clone())
1614 }
1615 _ => {
1616 return Err(CmfError::Parse(format!(
1617 "skill index {n} not dynamic-eligible"
1618 )));
1619 }
1620 },
1621 None => None,
1622 };
1623 let ov = match &new_id {
1624 Some(s) => Overlay::One(s),
1625 None => Overlay::None,
1626 };
1627 let arch = model.arch();
1628 for li in union {
1629 self.weights.layers[li].ffn =
1630 build_layer_ffn(&model, arch, li, self.dyn_force_f32, &ov)?;
1631 }
1632 self.dyn_active = idx;
1633 Ok(())
1634 }
1635}