Elffuss BraidHub

kikocis/coco public

main · 17.7 KiBRawPermalink
1// coco-owned config: the config.json → architectures[0] → Arch registry.
2//
3// This replaces the hard dependency on candle's `qwen2::Config` type. `CocoConfig`
4// is a serde superset of the fields every mainstream decoder-only LM exposes; flag
5// fields are defaulted so future archs (qwen3, llama, mistral, gemma3, …) drop in
6// as field-mapping + a registry arm, with no kernel changes. Step 0 registers ONLY
7// qwen2 — the flags below are the qwen2 wiring.
8
9use anyhow::{anyhow, Context, Result};
10use candle_nn::Activation;
11use serde::Deserialize;
12use std::path::Path;
13
14/// The architecture tag resolved from config.json's `architectures[0]`. Step 0 has
15/// exactly one entry; every later step adds an arm here + a registry-table row.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Arch {
18 Qwen2,
19 Qwen3,
20 Qwen3Moe,
21 DeepSeekV2,
22 /// Qwen3.5 hybrid: 3:1 interleave of GatedDeltaNet (linear-attn recurrent) +
23 /// periodic full GQA attention. Config lives under a multimodal `text_config`.
24 Qwen35,
25}
26
27/// The registry: HF `architectures[0]` string → coco `Arch`. This table IS the moat
28/// candle lacks (candle's `models/mod.rs` is a flat `pub mod` list with no dispatch).
29/// Adding an arch = adding a row here + a `build_model` match arm.
30pub const ARCH_REGISTRY: &[(&str, Arch)] = &[
31 ("Qwen2ForCausalLM", Arch::Qwen2),
32 ("Qwen3ForCausalLM", Arch::Qwen3),
33 ("Qwen3MoeForCausalLM", Arch::Qwen3Moe),
34 ("DeepseekV2ForCausalLM", Arch::DeepSeekV2),
35 ("Qwen3_5ForConditionalGeneration", Arch::Qwen35),
36 ("Qwen3_5ForCausalLM", Arch::Qwen35),
37];
38
39fn default_true() -> bool {
40 true
41}
42fn default_false() -> bool {
43 false
44}
45fn default_rope_theta() -> f64 {
46 10000.0
47}
48fn default_hidden_act() -> Activation {
49 Activation::Silu
50}
51fn default_max_pos() -> usize {
52 32768
53}
54fn default_decoder_sparse_step() -> usize {
55 1
56}
57fn default_moe_layer_freq() -> usize {
58 1
59}
60fn default_routed_scaling_factor() -> f64 {
61 1.0
62}
63fn default_partial_rotary() -> f32 {
64 1.0
65}
66fn default_sliding_window() -> usize {
67 // qwen2 config.json carries a huge sliding_window; the mask code treats it as
68 // effectively "no window" for these models. Default matches that when absent.
69 4096
70}
71
72/// Deserialize `sliding_window`, tolerating an explicit JSON `null` (qwen3) as well
73/// as an absent key — both collapse to `default_sliding_window()`.
74fn de_opt_sliding_window<'de, D>(de: D) -> std::result::Result<usize, D::Error>
75where
76 D: serde::Deserializer<'de>,
77{
78 let v: Option<usize> = Option::deserialize(de)?;
79 Ok(v.unwrap_or_else(default_sliding_window))
80}
81
82/// coco-owned union config. A `#[derive(Deserialize)]` superset of qwen2's
83/// config.json fields, plus flag fields defaulted for future archs. The quant/fast
84/// path reads ONLY this — never candle's `qwen2::Config`. Several fields
85/// (intermediate_size, qk_norm, attn_bias, tie_word_embeddings, …) are part of the
86/// union for future arch wirings and are not all read in Step 0's qwen2 path.
87#[derive(Debug, Clone, Deserialize)]
88#[allow(dead_code)]
89pub struct CocoConfig {
90 pub hidden_size: usize,
91 pub num_hidden_layers: usize,
92 pub num_attention_heads: usize,
93 pub num_key_value_heads: usize,
94 pub intermediate_size: usize,
95 pub vocab_size: usize,
96 pub rms_norm_eps: f64,
97
98 #[serde(default = "default_rope_theta")]
99 pub rope_theta: f64,
100
101 #[serde(default = "default_max_pos")]
102 pub max_position_embeddings: usize,
103
104 /// qwen2 carries a huge sliding_window (mask treats it as "no window"); qwen3
105 /// sets it to `null`. serde's `default` only fires on an ABSENT key — an explicit
106 /// `null` would error into `usize` — so deserialize via `Option` then unwrap to
107 /// the default. Either way the mask code sees a large "no window" value.
108 #[serde(default, deserialize_with = "de_opt_sliding_window")]
109 pub sliding_window: usize,
110
111 #[serde(default = "default_hidden_act")]
112 pub hidden_act: Activation,
113
114 /// Explicit head_dim (qwen3/gemma3 set it; qwen2 derives hidden/n_heads). When
115 /// absent, `head_dim()` derives it. Kept `Option` so the derive path is faithful.
116 #[serde(default)]
117 pub head_dim: Option<usize>,
118
119 // ── flag fields, defaulted for the qwen2 wiring (future archs override) ──────
120 /// QK-norm on head_dim q&k pre-rope (qwen3). qwen2 = false.
121 #[serde(default = "default_false")]
122 pub qk_norm: bool,
123
124 /// q/k/v projection biases. qwen2 = true; qwen3/llama/mistral = false.
125 #[serde(default = "default_true")]
126 pub attn_bias: bool,
127
128 /// Tie lm_head to the embedding matrix (Qwen2.5-1.5B = true).
129 #[serde(default = "default_false")]
130 pub tie_word_embeddings: bool,
131
132 // ── MoE fields (qwen3_moe / mixtral / glm4_moe). Defaulted to a dense wiring
133 // (num_experts=0) so non-MoE config.json blobs parse unchanged. ──────────
134 /// Number of experts in each MoE FFN (0 = dense arch, no MoE).
135 #[serde(default)]
136 pub num_experts: usize,
137 /// top-k experts activated per token.
138 #[serde(default)]
139 pub num_experts_per_tok: usize,
140 /// Per-expert SwiGLU intermediate width (distinct from the dense
141 /// intermediate_size; qwen3_moe = 768).
142 #[serde(default)]
143 pub moe_intermediate_size: usize,
144 /// Renormalize the top-k router weights to sum to 1 (qwen3_moe = true).
145 #[serde(default = "default_true")]
146 pub norm_topk_prob: bool,
147 /// Layer indices that stay DENSE even in a MoE arch (qwen3_moe = []).
148 #[serde(default)]
149 pub mlp_only_layers: Vec<usize>,
150 /// Sparse-layer stride: a MoE layer only every `decoder_sparse_step` layers
151 /// (qwen3_moe = 1 → every layer is MoE).
152 #[serde(default = "default_decoder_sparse_step")]
153 pub decoder_sparse_step: usize,
154
155 // ── DeepSeek-V2/V3 MLA fields (Arch::DeepSeekV2). All serde-defaulted so every
156 // other arch's config.json still parses unchanged. On V2-Lite: kv_lora_rank=512,
157 // q_lora_rank=null, qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128. ──
158 /// Rank of the compressed KV latent `c_kv` (the MQA-shared cache row width).
159 #[serde(default)]
160 pub kv_lora_rank: usize,
161 /// Rank of the optional compressed Q latent (full V2/V3). `None` on V2-Lite →
162 /// direct `q_proj` (QProj::Plain fork).
163 #[serde(default)]
164 pub q_lora_rank: Option<usize>,
165 /// Content (no-rope) part of the per-head Q/K dim.
166 #[serde(default)]
167 pub qk_nope_head_dim: usize,
168 /// Decoupled-rope part of the per-head Q dim + the single shared K rope dim.
169 #[serde(default)]
170 pub qk_rope_head_dim: usize,
171 /// Per-head V width (asymmetric: K is qk_nope+qk_rope, V is v_head_dim).
172 #[serde(default)]
173 pub v_head_dim: usize,
174 /// q/k/v/o projection biases for MLA (attention_bias in HF config; V2-Lite = false).
175 #[serde(default = "default_false")]
176 pub attention_bias: bool,
177
178 // ── DeepSeek-MoE FFN fields. Distinct from the qwen3_moe MoE fields above:
179 // DeepSeek adds always-on shared experts + a dense-layer prefix + a routed
180 // scaling factor. All defaulted to a no-op so qwen3_moe behavior is unchanged. ──
181 /// Number of routed experts (DeepSeek names it `n_routed_experts`; 0 = not a
182 /// DeepSeek-MoE arch).
183 #[serde(default)]
184 pub n_routed_experts: usize,
185 /// Number of always-on shared experts whose output is ADDED (ungated) to the
186 /// routed sum. `None`/0 = no shared experts.
187 #[serde(default)]
188 pub n_shared_experts: Option<usize>,
189 /// The first K decoder layers use a plain dense SwiGLU (not MoE). V2-Lite = 1.
190 #[serde(default)]
191 pub first_k_dense_replace: usize,
192 /// A MoE layer only every `moe_layer_freq` layers past `first_k_dense_replace`
193 /// (V2-Lite = 1 → every layer past the dense prefix is MoE).
194 #[serde(default = "default_moe_layer_freq")]
195 pub moe_layer_freq: usize,
196 /// Scalar multiplied into the routed-expert sum (DeepSeek routed_scaling_factor).
197 #[serde(default = "default_routed_scaling_factor")]
198 pub routed_scaling_factor: f64,
199 /// Grouped-topk config (full V2/V3). V2-Lite = 1/1 → degenerates to plain top-k,
200 /// which the existing top-k path already covers.
201 #[serde(default)]
202 pub n_group: usize,
203 #[serde(default)]
204 pub topk_group: usize,
205
206 /// YaRN (or linear/dynamic) rope scaling. `None` = plain rope. When present with
207 /// `type: yarn`, MLA applies the mscale sin/cos correction + squared-mscale
208 /// softmax scale, exactly per candle deepseek2.rs.
209 #[serde(default)]
210 pub rope_scaling: Option<RopeScaling>,
211
212 // ── Qwen3.5 hybrid (Arch::Qwen35) fields. All serde-defaulted so every other arch's
213 // config.json parses unchanged. Per-layer mixer type comes from `layer_types` (a
214 // per-layer "linear_attention"/"full_attention" list) or `full_attention_interval`. ──
215 /// Per-layer mixer selector: "linear_attention" (GatedDeltaNet) or "full_attention" (GQA).
216 #[serde(default)]
217 pub layer_types: Vec<String>,
218 /// When `layer_types` is absent: every `full_attention_interval`-th layer is full-attn.
219 #[serde(default)]
220 pub full_attention_interval: usize,
221 /// GatedDeltaNet per-head key/value dims and head counts.
222 #[serde(default)]
223 pub linear_key_head_dim: usize,
224 #[serde(default)]
225 pub linear_value_head_dim: usize,
226 #[serde(default)]
227 pub linear_num_key_heads: usize,
228 #[serde(default)]
229 pub linear_num_value_heads: usize,
230 /// Depthwise causal conv kernel width on the GatedDeltaNet q/k/v stream.
231 #[serde(default)]
232 pub linear_conv_kernel_dim: usize,
233 /// Full-attn layers apply rope to only the first `partial_rotary_factor * head_dim`
234 /// dims (rest NoPE). Absent → 1.0 (full rope, the qwen3 behavior).
235 #[serde(default = "default_partial_rotary")]
236 pub partial_rotary_factor: f32,
237 /// Full-attn layers carry a post-attention sigmoid output gate (qwen3.5 = true).
238 #[serde(default = "default_false")]
239 pub attn_output_gate: bool,
240
241 /// Resolved at load from `architectures[0]`; not in config.json's fields itself.
242 #[serde(skip, default = "default_arch")]
243 pub arch: Arch,
244}
245
246/// DeepSeek rope scaling. `#[serde(untagged)]` matches candle's `DeepSeekV2RopeScaling`:
247/// the YaRN variant carries the correction params; the linear/dynamic variant only a
248/// factor. Fields not present default so V2-Lite's yarn blob parses.
249#[derive(Debug, Clone, Deserialize)]
250#[serde(untagged)]
251pub enum RopeScaling {
252 Yarn {
253 original_max_position_embeddings: usize,
254 beta_fast: f32,
255 beta_slow: f32,
256 mscale: f32,
257 mscale_all_dim: f32,
258 factor: f32,
259 #[serde(rename = "type")]
260 scaling_type: String,
261 },
262 LinearOrDynamic {
263 #[serde(rename = "type")]
264 scaling_type: String,
265 factor: f64,
266 },
267}
268
269impl CocoConfig {
270 /// Is decoder layer `idx` a MoE FFN (vs a dense SwiGLU)? A layer is DENSE if it
271 /// is listed in `mlp_only_layers` OR (decoder_sparse_step > 1 and it is not a
272 /// multiple-stride sparse layer). All other layers of a MoE arch are MoE. Dense
273 /// archs (num_experts == 0) are never MoE. Matches HF qwen3_moe layer selection.
274 pub fn layer_is_moe(&self, idx: usize) -> bool {
275 if self.arch != Arch::Qwen3Moe || self.num_experts == 0 {
276 return false;
277 }
278 if self.mlp_only_layers.contains(&idx) {
279 return false;
280 }
281 if self.decoder_sparse_step > 1 && (idx + 1) % self.decoder_sparse_step != 0 {
282 return false;
283 }
284 true
285 }
286}
287
288fn default_arch() -> Arch {
289 Arch::Qwen2
290}
291
292/// YaRN mscale, ported verbatim from deepseek2.rs `yarn_get_mscale`:
293/// `0.1 * mscale * ln(scale) + 1` for scale > 1, else 1. Used both for the sin/cos
294/// magnitude in MLA rope and (squared) in the softmax scale.
295pub fn yarn_get_mscale(scale: f32, mscale: f32) -> f32 {
296 if scale <= 1.0 {
297 return 1.0;
298 }
299 0.1 * mscale * scale.ln() + 1.0
300}
301
302impl CocoConfig {
303 /// head_dim: explicit if present, else hidden_size / num_attention_heads (qwen2).
304 pub fn head_dim(&self) -> usize {
305 self.head_dim
306 .unwrap_or(self.hidden_size / self.num_attention_heads)
307 }
308
309 /// MLA per-head Q/K dim = qk_nope_head_dim + qk_rope_head_dim (192 on V2-Lite).
310 pub fn mla_q_head_dim(&self) -> usize {
311 self.qk_nope_head_dim + self.qk_rope_head_dim
312 }
313
314 /// MLA softmax scale = 1/sqrt(q_head_dim), with the YaRN squared-mscale correction
315 /// when `rope_scaling` is a yarn variant — ported verbatim from deepseek2.rs
316 /// `softmax_scale()` (mismatched mscale silently degrades). `mscale_all_dim` here,
317 /// applied twice (squared).
318 pub fn mla_softmax_scale(&self) -> f64 {
319 let mut s = 1.0_f64 / (self.mla_q_head_dim() as f64).sqrt();
320 if let Some(RopeScaling::Yarn {
321 mscale_all_dim,
322 factor,
323 ..
324 }) = &self.rope_scaling
325 {
326 let m = yarn_get_mscale(*factor, *mscale_all_dim) as f64;
327 s = s * m * m;
328 }
329 s
330 }
331
332 /// DeepSeek-MoE per-layer dense-vs-MoE selection: the first `first_k_dense_replace`
333 /// layers are plain dense SwiGLU; the rest are MoE (subject to `moe_layer_freq`).
334 /// Matches deepseek2.rs `DecoderLayer::new`. Dense archs / non-DeepSeek return false.
335 pub fn deepseek_layer_is_moe(&self, idx: usize) -> bool {
336 if self.arch != Arch::DeepSeekV2 || self.n_routed_experts == 0 {
337 return false;
338 }
339 idx >= self.first_k_dense_replace && idx % self.moe_layer_freq == 0
340 }
341
342 /// Qwen3.5 per-layer mixer: true = GatedDeltaNet (linear attn), false = full GQA.
343 /// Prefers the explicit `layer_types` list; falls back to `full_attention_interval`
344 /// (every Nth layer full-attn, the rest linear). Non-qwen3.5 archs return false.
345 pub fn layer_is_linear_attn(&self, idx: usize) -> bool {
346 if self.arch != Arch::Qwen35 {
347 return false;
348 }
349 if let Some(t) = self.layer_types.get(idx) {
350 return t == "linear_attention";
351 }
352 let n = self.full_attention_interval.max(1);
353 (idx + 1) % n != 0
354 }
355
356 /// Load config.json, resolve `architectures[0]` (or `model_type`) against the
357 /// registry, and parse the union config. This is the config.json → Arch step.
358 pub fn from_dir(dir: &Path) -> Result<Self> {
359 let path = dir.join("config.json");
360 let bytes = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
361 Self::from_json_bytes(&bytes)
362 .with_context(|| format!("parsing {}", path.display()))
363 }
364
365 /// Parse a config.json byte blob and resolve its architecture tag.
366 pub fn from_json_bytes(bytes: &[u8]) -> Result<Self> {
367 // First pull architectures[0] / model_type to resolve the Arch.
368 // Parse the whole config as a Value. Resolve arch from the top-level
369 // architectures/model_type; take the LM fields from `text_config` when this is a
370 // multimodal wrapper (qwen3_5, with a `vision_config` sibling we ignore), else from
371 // the top-level object itself (qwen2/qwen3/deepseek).
372 let root: serde_json::Value = serde_json::from_slice(bytes)?;
373 let architectures: Vec<String> = root
374 .get("architectures")
375 .and_then(|v| serde_json::from_value(v.clone()).ok())
376 .unwrap_or_default();
377 let model_type = root
378 .get("model_type")
379 .and_then(|v| v.as_str())
380 .map(str::to_string);
381 let arch = resolve_arch(&architectures, model_type.as_deref())?;
382
383 let text_config = root.get("text_config").cloned();
384 let lm_val = text_config.unwrap_or(root);
385 let mut cfg: CocoConfig = serde_json::from_value(lm_val)?;
386 cfg.arch = arch;
387
388 // Arch-implied flags. qwen3's config.json has NO `qk_norm` field and NO
389 // q/k/v bias — those are architecture facts, not config values — so we force
390 // them here rather than trusting/expecting config keys. (qwen3 DOES carry
391 // `attention_bias: false`, but forcing keeps us robust to its absence.)
392 // qwen3_moe shares qwen3's attention: QK-norm on, no q/k/v bias. The ONLY
393 // delta vs qwen3 dense is the FFN (MoE vs SwiGLU) — read from the MoE fields.
394 if arch == Arch::Qwen3 || arch == Arch::Qwen3Moe {
395 cfg.qk_norm = true;
396 cfg.attn_bias = false;
397 }
398 // DeepSeek V2/V3 is full causal (no sliding window). Its config.json omits
399 // `sliding_window`, so the default (4096) would wrongly window contexts > 4096.
400 // Force it to the full range. MLA has its own head-dim split (not the GQA
401 // qk_norm), so leave qk_norm/attn_bias to the MLA-specific fields.
402 if arch == Arch::DeepSeekV2 {
403 cfg.sliding_window = cfg.max_position_embeddings;
404 }
405 Ok(cfg)
406 }
407}
408
409/// Resolve `architectures[0]` (preferred) or `model_type` against ARCH_REGISTRY.
410fn resolve_arch(architectures: &[String], model_type: Option<&str>) -> Result<Arch> {
411 if let Some(first) = architectures.first() {
412 if let Some((_, arch)) = ARCH_REGISTRY.iter().find(|(name, _)| name == first) {
413 return Ok(*arch);
414 }
415 }
416 // Fallback: model_type string (qwen2 → Qwen2, qwen3 → Qwen3).
417 if let Some(mt) = model_type {
418 match mt {
419 "qwen2" => return Ok(Arch::Qwen2),
420 "qwen3" => return Ok(Arch::Qwen3),
421 "qwen3_moe" => return Ok(Arch::Qwen3Moe),
422 "deepseek_v2" | "deepseek_v3" => return Ok(Arch::DeepSeekV2),
423 "qwen3_5" | "qwen3_5_text" | "qwen3_5_moe" => return Ok(Arch::Qwen35),
424 _ => {}
425 }
426 }
427 Err(anyhow!(
428 "unregistered architecture: architectures={:?} model_type={:?} (registered: {:?})",
429 architectures,
430 model_type,
431 ARCH_REGISTRY.iter().map(|(n, _)| *n).collect::<Vec<_>>()
432 ))
433}