Elffuss BraidHub

kikocis/coco public

main · 60.0 KiBRawPermalink
1// coco config-driven decoder: the fixed primitive set + Model/SequenceMixer traits
2// + build_model dispatcher.
3//
4// STEP 0 (pure refactor, no behavior change): the inlined qwen2 forward from
5// qwen2_q.rs is lifted VERBATIM into named primitives that WRAP the existing
6// qlinear.rs machinery:
7// RmsNorm → wraps RmsNormFused
8// Rope → wraps RotaryEmbedding + rope_apply
9// GqaAttention → the flash-decode block (incl. COCO_FUSED_ATTN candle fallback +
10// persistent KvCache); the first (and only) SequenceMixer impl
11// SwiGlu → the fused MLP
12// A DecoderLayer holds input_norm, mixer: Box<dyn SequenceMixer>, pre_ffn_norm, and
13// ffn: Ffn::Dense(SwiGlu). Optional post-attn / post-ffn norms are None for qwen2.
14//
15// The trait-object dispatch is once per layer per token — proven negligible by the
16// Step-0 tok/s gate (design §5 risk 4).
17
18use anyhow::Result;
19use candle_core::{DType, Device, Module, Tensor, D};
20use candle_nn::{Activation, VarBuilder};
21use std::sync::Arc;
22
23use crate::config::{yarn_get_mscale, Arch, CocoConfig, RopeScaling};
24use crate::qlinear::{fuse_resid_enabled, rope_apply, KvCache, QGroup, RmsNormFused};
25use crate::qwen2_q::{Proj, WeightSource, WeightStats};
26
27// ── env-flag helpers (identical semantics to the originals in qwen2_q.rs) ──────────
28
29fn fused_max_ctx() -> usize {
30 std::env::var("COCO_MAX_CTX")
31 .ok()
32 .and_then(|s| s.parse().ok())
33 .unwrap_or(8192)
34}
35
36fn fused_attn_enabled() -> bool {
37 !matches!(std::env::var("COCO_FUSED_ATTN").as_deref(), Ok("0"))
38}
39
40fn fused_min_ctx() -> usize {
41 std::env::var("COCO_FUSED_MIN_CTX")
42 .ok()
43 .and_then(|s| s.parse().ok())
44 .unwrap_or(0)
45}
46
47/// Debug switch: when COCO_NO_QK_NORM is set, SKIP the qwen3 q_norm/k_norm even
48/// though they were loaded. Lets the Prove phase show that turning qk_norm off
49/// garbles a qwen3 model — proving the primitive is real and on the live path.
50/// Default OFF (unset) → qk_norm applies normally.
51fn qk_norm_disabled() -> bool {
52 std::env::var("COCO_NO_QK_NORM").is_ok()
53}
54
55/// Gate for the (future) fused MLA Metal kernel. Default = the candle fallback (always
56/// correct). Mirrors `COCO_FUSED_ATTN`. A fused latent-cache flash-decode kernel would
57/// switch on when `COCO_FUSED_MLA=1`; today only the fallback exists, so this is read
58/// but the fused branch is not yet wired (the fallback is unconditionally taken).
59fn fused_mla_enabled() -> bool {
60 matches!(std::env::var("COCO_FUSED_MLA").as_deref(), Ok("1"))
61}
62
63// ─────────────────────────── the shared model contract ───────────────────────────
64
65/// The model contract every arch wiring implements (candle has NO such trait).
66pub trait Model {
67 fn forward(&mut self, ids: &Tensor, offset: usize) -> Result<Tensor>;
68 fn clear_kv_cache(&mut self);
69}
70
71/// The ONE pluggable per-layer seam. GqaAttention is the first/only impl in Step 0;
72/// Mla / SparseSelect / GatedDeltaNet / ShortConv land in later steps.
73pub trait SequenceMixer {
74 /// `xs` is already input-normed upstream. `resid` (COCO_FUSE_RESID) is the layer
75 /// input folded into the o_proj store epilogue. Returns the mixed hidden state.
76 fn forward(
77 &mut self,
78 xs: &Tensor,
79 attention_mask: Option<&Tensor>,
80 seqlen_offset: usize,
81 resid: Option<&Tensor>,
82 ) -> Result<Tensor>;
83 fn clear_cache(&mut self);
84}
85
86// ─────────────────────────── primitive: RmsNorm ───────────────────────────
87
88/// Fused RMSNorm primitive — thin wrapper over the existing `RmsNormFused` kernel.
89pub struct RmsNorm(RmsNormFused);
90
91impl RmsNorm {
92 pub fn new(weight: Tensor, eps: f64) -> Result<Self> {
93 Ok(Self(RmsNormFused::new(weight, eps)?))
94 }
95 pub fn forward(&self, x: &Tensor) -> Result<Tensor> {
96 self.0.forward(x)
97 }
98 /// Fused residual-add + RMSNorm in one dispatch → (h = a+b, normed = norm(h)).
99 pub fn forward_add(&self, a: &Tensor, b: &Tensor) -> Result<(Tensor, Tensor)> {
100 self.0.forward_add(a, b)
101 }
102}
103
104// ─────────────────────────── primitive: Rope ───────────────────────────
105
106/// RoPE primitive — wraps the fused `rope_apply` kernel + the cos/sin tables, with
107/// the per-token thread-local slice cache. Verbatim behavior from qwen2_q.rs.
108pub struct Rope {
109 sin: Tensor,
110 cos: Tensor,
111}
112
113thread_local! {
114 /// Per-token cached RoPE cos/sin slice: (seqlen_offset, seq_len, cos, sin).
115 static ROPE_SLICE_CACHE: std::cell::RefCell<Option<(usize, usize, Tensor, Tensor)>> =
116 const { std::cell::RefCell::new(None) };
117
118 /// (layers_secs, head_secs, count) accumulated across profiled decode steps.
119 static PROFILE_ACC: std::cell::RefCell<(f64, f64, usize)> =
120 const { std::cell::RefCell::new((0.0, 0.0, 0)) };
121}
122
123/// Print + reset the COCO_PROFILE accumulator (called from the bench harness).
124pub fn profile_report() {
125 PROFILE_ACC.with(|a| {
126 let (l, h, n) = *a.borrow();
127 if n > 0 {
128 eprintln!(
129 "PROFILE n={} | layers {:.3} ms/tok | norm+lm_head {:.3} ms/tok | total {:.3} ms/tok",
130 n,
131 l / n as f64 * 1e3,
132 h / n as f64 * 1e3,
133 (l + h) / n as f64 * 1e3,
134 );
135 }
136 });
137}
138
139impl Rope {
140 pub fn new(dtype: DType, cfg: &CocoConfig, dev: &Device) -> Result<Self> {
141 let dim = cfg.head_dim();
142 let max_seq_len = cfg.max_position_embeddings;
143 let inv_freq: Vec<_> = (0..dim)
144 .step_by(2)
145 .map(|i| 1f32 / cfg.rope_theta.powf(i as f64 / dim as f64) as f32)
146 .collect();
147 let inv_freq_len = inv_freq.len();
148 let inv_freq = Tensor::from_vec(inv_freq, (1, inv_freq_len), dev)?.to_dtype(dtype)?;
149 let t = Tensor::arange(0u32, max_seq_len as u32, dev)?
150 .to_dtype(dtype)?
151 .reshape((max_seq_len, 1))?;
152 let freqs = t.matmul(&inv_freq)?;
153 Ok(Self {
154 sin: freqs.sin()?,
155 cos: freqs.cos()?,
156 })
157 }
158
159 pub fn apply(&self, q: &Tensor, k: &Tensor, seqlen_offset: usize) -> Result<(Tensor, Tensor)> {
160 let (_b_sz, _h, seq_len, _n_embd) = q.dims4()?;
161 let (cos, sin) = ROPE_SLICE_CACHE.with(|c| -> Result<(Tensor, Tensor)> {
162 let mut c = c.borrow_mut();
163 if let Some((off, len, cos, sin)) = c.as_ref() {
164 if *off == seqlen_offset && *len == seq_len {
165 return Ok((cos.clone(), sin.clone()));
166 }
167 }
168 let cos = self.cos.narrow(0, seqlen_offset, seq_len)?;
169 let sin = self.sin.narrow(0, seqlen_offset, seq_len)?;
170 *c = Some((seqlen_offset, seq_len, cos.clone(), sin.clone()));
171 Ok((cos, sin))
172 })?;
173 if std::env::var("COCO_NO_FUSE_ROPE").is_err()
174 && matches!(q.device(), Device::Metal(_))
175 && q.dtype() == DType::BF16
176 {
177 let q_embed = rope_apply(q, &cos, &sin)?;
178 let k_embed = rope_apply(k, &cos, &sin)?;
179 return Ok((q_embed, k_embed));
180 }
181 let q_embed = candle_nn::rotary_emb::rope(&q.contiguous()?, &cos, &sin)?;
182 let k_embed = candle_nn::rotary_emb::rope(&k.contiguous()?, &cos, &sin)?;
183 Ok((q_embed, k_embed))
184 }
185}
186
187// ─────────────────────────── primitive: SwiGlu (dense FFN) ───────────────────────────
188
189/// SwiGLU dense FFN primitive — gate/up fused as one QGroup, down as one Proj. The
190/// fused-swiglu / ffn-mega / fallback paths are byte-identical to qwen2_q.rs's MLP.
191pub struct SwiGlu {
192 gate_up: QGroup,
193 down_proj: Proj,
194 act_fn: Activation,
195}
196
197impl SwiGlu {
198 pub fn new(src: &mut WeightSource, prefix: &str, cfg: &CocoConfig) -> Result<Self> {
199 Ok(Self {
200 gate_up: src.quant_group(&[
201 (&format!("{prefix}.gate_proj"), false),
202 (&format!("{prefix}.up_proj"), false),
203 ])?,
204 down_proj: src.proj(&format!("{prefix}.down_proj"), false)?,
205 act_fn: cfg.hidden_act,
206 })
207 }
208
209 pub fn forward(&self, xs: &Tensor, resid: Option<&Tensor>) -> Result<Tensor> {
210 if let Proj::Quant(down) = &self.down_proj {
211 if let Some(out) = self.gate_up.forward_ffn_mega(xs, down)? {
212 return match resid {
213 Some(r) => Ok((out + r)?),
214 None => Ok(out),
215 };
216 }
217 }
218 let fuse = std::env::var("COCO_FUSE_SWIGLU").as_deref() != Ok("0");
219 if fuse {
220 if let Some(act) = self.gate_up.forward_swiglu(xs)? {
221 return match resid {
222 Some(r) => self.down_proj.forward_resid(&act, r),
223 None => self.down_proj.forward(&act),
224 };
225 }
226 }
227 let mut gu = self.gate_up.forward(xs)?;
228 let rhs = gu.pop().unwrap();
229 let lhs = gu.pop().unwrap().apply(&self.act_fn)?;
230 let act = (lhs * rhs)?;
231 match resid {
232 Some(r) => self.down_proj.forward_resid(&act, r),
233 None => self.down_proj.forward(&act),
234 }
235 }
236}
237
238// ─────────────────────────── primitive: MoeFfn (top-k MoE FFN) ───────────────────────────
239
240/// Top-k Mixture-of-Experts FFN (qwen3_moe / mixtral / glm4_moe). A DENSE fp16 router
241/// `gate` [hidden, num_experts] (tiny — kept dense, not turboquant'd) selects the
242/// top-`k` experts per token; each expert is a `SwiGlu` (per-expert gate/up = a QGroup,
243/// down = a Proj, turboquant-compressed exactly like the dense FFN).
244///
245/// Forward matches candle `qwen3_moe.rs::Qwen3SparseMoeBlock` exactly:
246/// logits = gate(x) [T, num_experts]
247/// probs = softmax(logits, dim=experts)
248/// idx = argsort(probs, desc)[..k] top-k expert ids [T, k]
249/// weights = gather(probs, idx) [T, k]
250/// if norm_topk_prob: weights /= sum_k(weights) renormalize the k
251/// out[t] = Σ_{e in idx[t]} weights[t,e] · expert_e(x[t])
252/// implemented via the same per-expert gather/scatter (index_select rows for each
253/// expert, forward once, broadcast_mul the weight, index_add back).
254pub struct MoeFfn {
255 gate: candle_nn::Linear, // router — DENSE fp16, [hidden, num_experts], no bias
256 experts: Vec<SwiGlu>,
257 num_experts_per_tok: usize,
258 norm_topk_prob: bool,
259 /// DeepSeek-MoE: always-on shared experts summed (ungated) with the routed output.
260 /// Empty for qwen3_moe (n_shared_experts absent) → behavior unchanged.
261 shared_experts: Vec<SwiGlu>,
262 /// DeepSeek-MoE: scalar applied to the routed-expert sum. 1.0 for qwen3_moe (and,
263 /// per the oracle, only applied when `!norm_topk_prob`).
264 routed_scaling_factor: f64,
265}
266
267impl MoeFfn {
268 pub fn new(
269 src: &mut WeightSource,
270 prefix: &str,
271 cfg: &CocoConfig,
272 norm_vb: &VarBuilder,
273 ) -> Result<Self> {
274 // Routed-expert count: qwen3_moe uses `num_experts`; DeepSeek-MoE uses
275 // `n_routed_experts`. Exactly one is nonzero for a given arch.
276 let n_routed = if cfg.arch == Arch::DeepSeekV2 {
277 cfg.n_routed_experts
278 } else {
279 cfg.num_experts
280 };
281 // Router stays a dense fp16 linear read straight from the mmap'd VarBuilder.
282 // Tensor name: model.layers.{L}.mlp.gate.weight (no bias).
283 let gate = candle_nn::linear_no_bias(
284 cfg.hidden_size,
285 n_routed,
286 norm_vb.pp(format!("{prefix}.gate")),
287 )?;
288 // Per-expert SwiGLU. gate_proj/up_proj = a QGroup, down_proj = a Proj — the
289 // expert intermediate width is moe_intermediate_size (768 for Qwen3-30B-A3B,
290 // 1408 for DeepSeek-V2-Lite), read from config by SwiGlu::new via the weight
291 // shapes. Turboquant divisibility (inn % 128 == 0) is checked at encode time.
292 let mut experts = Vec::with_capacity(n_routed);
293 for i in 0..n_routed {
294 experts.push(SwiGlu::new(src, &format!("{prefix}.experts.{i}"), cfg)?);
295 }
296
297 // DeepSeek-MoE shared experts: a SINGLE always-on SwiGLU of intermediate width
298 // `moe_intermediate_size * n_shared_experts` (per deepseek2.rs `Moe::new`),
299 // summed ungated with the routed output. `SwiGlu::new` derives the (wide)
300 // intermediate from the `{prefix}.shared_experts` weight shapes. Absent for
301 // qwen3_moe → empty vec, behavior unchanged.
302 let mut shared_experts = Vec::new();
303 if cfg.arch == Arch::DeepSeekV2 && cfg.n_shared_experts.unwrap_or(0) > 0 {
304 shared_experts.push(SwiGlu::new(src, &format!("{prefix}.shared_experts"), cfg)?);
305 }
306
307 // routed_scaling_factor is a DeepSeek concept; qwen3_moe keeps 1.0.
308 let routed_scaling_factor = if cfg.arch == Arch::DeepSeekV2 {
309 cfg.routed_scaling_factor
310 } else {
311 1.0
312 };
313
314 Ok(Self {
315 gate,
316 experts,
317 num_experts_per_tok: cfg.num_experts_per_tok,
318 norm_topk_prob: cfg.norm_topk_prob,
319 shared_experts,
320 routed_scaling_factor,
321 })
322 }
323
324 fn forward(&self, xs: &Tensor, resid: Option<&Tensor>) -> Result<Tensor> {
325 let (b_size, seq_len, hidden_dim) = xs.dims3()?;
326 let xs2d = xs.reshape(((), hidden_dim))?;
327
328 // Router: logits → softmax over experts. The router Linear weight is the model
329 // dtype (BF16 on Metal); matmul it in that dtype, then cast to f32 for a stable
330 // softmax/argsort/gather (candle's reference softmaxes then works in f32).
331 let router_logits = self.gate.forward(&xs2d)?.to_dtype(DType::F32)?;
332 let routing_weights = candle_nn::ops::softmax_last_dim(&router_logits)?;
333
334 // top-k: argsort descending, take the first k expert ids, gather their probs.
335 let experts_per_tok = routing_weights
336 .arg_sort_last_dim(false)?
337 .narrow(D::Minus1, 0, self.num_experts_per_tok)?
338 .contiguous()?;
339 let topk_weights = routing_weights.gather(&experts_per_tok, D::Minus1)?;
340
341 let topk_weights = topk_weights.to_dtype(DType::F32)?.to_vec2::<f32>()?;
342 let experts_per_tok = experts_per_tok.to_vec2::<u32>()?;
343
344 // Invert token→experts into expert→(rows, weights) for a single batched
345 // forward per expert (matches candle's scatter loop exactly).
346 let mut top_x = vec![vec![]; self.experts.len()];
347 let mut selected_weights = vec![vec![]; self.experts.len()];
348 for (row_idx, (rw, expert_idxs)) in
349 topk_weights.iter().zip(experts_per_tok.iter()).enumerate()
350 {
351 let sum_rw = rw.iter().sum::<f32>();
352 for (&w, &expert_idx) in rw.iter().zip(expert_idxs.iter()) {
353 top_x[expert_idx as usize].push(row_idx as u32);
354 // Oracle (deepseek2.rs MoeGate): renormalize when norm_topk_prob (and
355 // top_k>1), else scale by routed_scaling_factor. Mutually exclusive.
356 let w = if self.norm_topk_prob && self.num_experts_per_tok > 1 {
357 w / sum_rw
358 } else {
359 w * self.routed_scaling_factor as f32
360 };
361 selected_weights[expert_idx as usize].push(w);
362 }
363 }
364
365 let mut ys = xs2d.zeros_like()?;
366 for (expert_idx, expert) in self.experts.iter().enumerate() {
367 let rows = &top_x[expert_idx];
368 if rows.is_empty() {
369 continue;
370 }
371 let rows_t = Tensor::new(rows.as_slice(), xs2d.device())?;
372 let w_t = Tensor::new(selected_weights[expert_idx].as_slice(), xs2d.device())?
373 .reshape(((), 1))?
374 .to_dtype(xs2d.dtype())?;
375 let cur = xs2d.index_select(&rows_t, 0)?;
376 // Expert SwiGLU (no residual — the MoE weighted sum is accumulated below).
377 let cur = expert.forward(&cur, None)?;
378 let cur = cur.broadcast_mul(&w_t)?;
379 ys = ys.index_add(&rows_t, &cur, 0)?;
380 }
381
382 // DeepSeek-MoE: add the always-on shared experts (ungated) to the routed sum.
383 // Runs on the ORIGINAL activation xs2d (the routed weighting is already folded
384 // into `ys`). No-op for qwen3_moe (shared_experts empty).
385 for shared in &self.shared_experts {
386 ys = (ys + shared.forward(&xs2d, None)?)?;
387 }
388
389 let out = ys.reshape((b_size, seq_len, hidden_dim))?;
390 match resid {
391 Some(r) => Ok((out + r)?),
392 None => Ok(out),
393 }
394 }
395}
396
397/// Feed-forward: dense SwiGLU or top-k MoE. Config-selected fixed primitive.
398pub enum Ffn {
399 Dense(SwiGlu),
400 Moe(MoeFfn),
401}
402
403impl Ffn {
404 fn forward(&self, xs: &Tensor, resid: Option<&Tensor>) -> Result<Tensor> {
405 match self {
406 Ffn::Dense(m) => m.forward(xs, resid),
407 Ffn::Moe(m) => m.forward(xs, resid),
408 }
409 }
410}
411
412// ─────────────────────────── mixer: GqaAttention ───────────────────────────
413
414/// GQA causal flash-decode attention (the first/only SequenceMixer). Contains the
415/// persistent KvCache + the candle fallback, byte-identical to qwen2_q.rs's Attention.
416pub struct GqaAttention {
417 qkv: QGroup,
418 o_proj: Proj,
419 num_heads: usize,
420 num_kv_heads: usize,
421 num_kv_groups: usize,
422 head_dim: usize,
423 hidden_size: usize,
424 rotary_emb: Arc<Rope>,
425 /// qwen3 QK-norm: RmsNorm over head_dim applied to reshaped per-head q/k BEFORE
426 /// rope. `None` for qwen2 (cfg.qk_norm == false) so that path is byte-identical.
427 q_norm: Option<RmsNorm>,
428 k_norm: Option<RmsNorm>,
429 kv_cache: Option<(Tensor, Tensor)>,
430 kv_fast: Option<KvCache>,
431 fused: bool,
432}
433
434impl GqaAttention {
435 pub fn new(
436 src: &mut WeightSource,
437 prefix: &str,
438 rotary_emb: Arc<Rope>,
439 cfg: &CocoConfig,
440 norm_vb: &VarBuilder,
441 ) -> Result<Self> {
442 let hidden_sz = cfg.hidden_size;
443 let num_heads = cfg.num_attention_heads;
444 let num_kv_heads = cfg.num_key_value_heads;
445 let num_kv_groups = num_heads / num_kv_heads;
446 let head_dim = cfg.head_dim();
447 let bias = cfg.attn_bias;
448
449 // qwen3 QK-norm: an RmsNorm over head_dim on the reshaped per-head q & k,
450 // applied BEFORE rope. Gated by cfg.qk_norm (false for qwen2 → None). Weights
451 // are small fp16 norm vectors read from the mmap'd VarBuilder, not quantized.
452 let (q_norm, k_norm) = if cfg.qk_norm {
453 let q_w = norm_vb.pp(format!("{prefix}.q_norm")).get(head_dim, "weight")?;
454 let k_w = norm_vb.pp(format!("{prefix}.k_norm")).get(head_dim, "weight")?;
455 (
456 Some(RmsNorm::new(q_w, cfg.rms_norm_eps)?),
457 Some(RmsNorm::new(k_w, cfg.rms_norm_eps)?),
458 )
459 } else {
460 (None, None)
461 };
462
463 Ok(Self {
464 qkv: src.quant_group(&[
465 (&format!("{prefix}.q_proj"), bias),
466 (&format!("{prefix}.k_proj"), bias),
467 (&format!("{prefix}.v_proj"), bias),
468 ])?,
469 o_proj: src.proj(&format!("{prefix}.o_proj"), false)?,
470 num_heads,
471 num_kv_heads,
472 num_kv_groups,
473 head_dim,
474 hidden_size: hidden_sz,
475 rotary_emb,
476 q_norm,
477 k_norm,
478 kv_cache: None,
479 kv_fast: None,
480 fused: fused_attn_enabled(),
481 })
482 }
483
484 #[allow(clippy::too_many_arguments)]
485 fn candle_attention(
486 &mut self,
487 query_states: &Tensor,
488 key_states: &Tensor,
489 value_states: &Tensor,
490 attention_mask: Option<&Tensor>,
491 b_sz: usize,
492 q_len: usize,
493 resid: Option<&Tensor>,
494 ) -> Result<Tensor> {
495 let (key_states, value_states) = match &self.kv_cache {
496 None => (key_states.clone(), value_states.clone()),
497 Some((prev_k, prev_v)) => {
498 let key_states = Tensor::cat(&[prev_k, key_states], 2)?;
499 let value_states = Tensor::cat(&[prev_v, value_states], 2)?;
500 (key_states, value_states)
501 }
502 };
503 self.kv_cache = Some((key_states.clone(), value_states.clone()));
504
505 let key_states =
506 candle_transformers::utils::repeat_kv(key_states, self.num_kv_groups)?.contiguous()?;
507 let value_states =
508 candle_transformers::utils::repeat_kv(value_states, self.num_kv_groups)?.contiguous()?;
509
510 let attn_output = {
511 let scale = 1f64 / f64::sqrt(self.head_dim as f64);
512 let attn_weights = (query_states.matmul(&key_states.transpose(2, 3)?)? * scale)?;
513
514 let attn_weights = match attention_mask {
515 None => attn_weights,
516 Some(mask) => attn_weights.broadcast_add(mask)?,
517 };
518 let attn_weights = candle_nn::ops::softmax_last_dim(&attn_weights)?;
519 attn_weights.matmul(&value_states)?
520 };
521 // o_proj input width is n_heads*head_dim, which for qwen3 (16*128=2048) is NOT
522 // hidden_size (1024) — reshape to the attention output width, not hidden_size.
523 let attn_output = attn_output
524 .transpose(1, 2)?
525 .reshape((b_sz, q_len, self.num_heads * self.head_dim))?;
526 match resid {
527 Some(r) => self.o_proj.forward_resid(&attn_output, r),
528 None => self.o_proj.forward(&attn_output),
529 }
530 }
531}
532
533impl SequenceMixer for GqaAttention {
534 fn forward(
535 &mut self,
536 xs: &Tensor,
537 attention_mask: Option<&Tensor>,
538 seqlen_offset: usize,
539 resid: Option<&Tensor>,
540 ) -> Result<Tensor> {
541 let (b_sz, q_len, _) = xs.dims3()?;
542
543 let mut qkv = self.qkv.forward(xs)?;
544 let value_states = qkv.pop().unwrap();
545 let key_states = qkv.pop().unwrap();
546 let query_states = qkv.pop().unwrap();
547
548 let query_states = query_states
549 .reshape((b_sz, q_len, self.num_heads, self.head_dim))?
550 .transpose(1, 2)?;
551 let key_states = key_states
552 .reshape((b_sz, q_len, self.num_kv_heads, self.head_dim))?
553 .transpose(1, 2)?;
554 let value_states = value_states
555 .reshape((b_sz, q_len, self.num_kv_heads, self.head_dim))?
556 .transpose(1, 2)?;
557
558 // qwen3 QK-norm: RmsNorm over head_dim on the per-head q & k, BEFORE rope.
559 // No-op for qwen2 (q_norm/k_norm are None). COCO_NO_QK_NORM skips it (debug:
560 // proves the primitive is live — a qwen3 model garbles without it).
561 let (query_states, key_states) = if qk_norm_disabled() {
562 (query_states, key_states)
563 } else {
564 // The reshaped q/k are non-contiguous (post-transpose); the RmsNorm reshape
565 // needs contiguous input, so contiguify only when a norm actually applies.
566 let query_states = match &self.q_norm {
567 Some(qn) => qn.forward(&query_states.contiguous()?)?,
568 None => query_states,
569 };
570 let key_states = match &self.k_norm {
571 Some(kn) => kn.forward(&key_states.contiguous()?)?,
572 None => key_states,
573 };
574 (query_states, key_states)
575 };
576
577 let (query_states, key_states) =
578 self.rotary_emb.apply(&query_states, &key_states, seqlen_offset)?;
579
580 if self.fused && b_sz == 1 {
581 if self.kv_fast.is_none() {
582 self.kv_fast = Some(KvCache::new(
583 self.num_heads,
584 self.num_kv_heads,
585 self.head_dim,
586 fused_max_ctx(),
587 query_states.device(),
588 )?);
589 }
590 let k_f = key_states.squeeze(0)?.contiguous()?;
591 let v_f = value_states.squeeze(0)?.contiguous()?;
592
593 if q_len == 1 {
594 let ctx_now = self.kv_fast.as_ref().unwrap().len();
595 let k1 = k_f.squeeze(1)?;
596 let v1 = v_f.squeeze(1)?;
597 if ctx_now >= fused_min_ctx() {
598 let kc = self.kv_fast.as_mut().unwrap();
599 let q_f = query_states.squeeze(0)?.squeeze(1)?.contiguous()?;
600 let attn = kc.decode(&q_f, &k1, &v1)?;
601 let attn = attn.to_dtype(xs.dtype())?;
602 return match resid {
603 Some(r) => self.o_proj.forward_resid(&attn, r),
604 None => self.o_proj.forward(&attn),
605 };
606 } else {
607 self.kv_fast
608 .as_mut()
609 .unwrap()
610 .append_prefill(&k1.unsqueeze(1)?, &v1.unsqueeze(1)?)?;
611 return self.candle_attention(
612 &query_states,
613 &key_states,
614 &value_states,
615 attention_mask,
616 b_sz,
617 q_len,
618 resid,
619 );
620 }
621 } else {
622 self.kv_fast.as_mut().unwrap().append_prefill(&k_f, &v_f)?;
623 return self.candle_attention(
624 &query_states,
625 &key_states,
626 &value_states,
627 attention_mask,
628 b_sz,
629 q_len,
630 resid,
631 );
632 }
633 }
634
635 self.candle_attention(
636 &query_states,
637 &key_states,
638 &value_states,
639 attention_mask,
640 b_sz,
641 q_len,
642 resid,
643 )
644 }
645
646 fn clear_cache(&mut self) {
647 self.kv_cache = None;
648 if let Some(kc) = self.kv_fast.as_mut() {
649 kc.clear();
650 }
651 }
652}
653
654// ─────────────────────────── mixer: MlaAttention (DeepSeek V2/V3) ───────────────────────────
655
656/// Decoupled-RoPE tables for MLA. Sized `qk_rope_head_dim` (64 on V2-Lite), applied
657/// ONLY to the rope slices q_pe/k_pe. Ported verbatim from deepseek2.rs
658/// `DeepSeekV2RotaryEmbedding`: plain freqs when no scaling, YaRN interpolation +
659/// mscale sin/cos magnitude when `rope_scaling: yarn`. Uses candle `rope_i`
660/// (interleaved) exactly like the oracle — NOT coco's NeoX `rope`.
661pub struct MlaRope {
662 sin: Tensor,
663 cos: Tensor,
664}
665
666impl MlaRope {
667 pub fn new(dtype: DType, cfg: &CocoConfig, dev: &Device) -> Result<Self> {
668 let dim = cfg.qk_rope_head_dim;
669 let theta = cfg.rope_theta as f32;
670 match &cfg.rope_scaling {
671 Some(RopeScaling::Yarn {
672 original_max_position_embeddings,
673 beta_fast,
674 beta_slow,
675 mscale,
676 mscale_all_dim,
677 factor,
678 ..
679 }) => Self::new_yarn(
680 dtype,
681 dev,
682 dim,
683 theta,
684 cfg.max_position_embeddings,
685 *original_max_position_embeddings,
686 *beta_fast,
687 *beta_slow,
688 *factor,
689 *mscale,
690 *mscale_all_dim,
691 ),
692 Some(RopeScaling::LinearOrDynamic { .. }) => {
693 anyhow::bail!("MLA linear/dynamic rope scaling not implemented (only yarn)")
694 }
695 None => Self::new_unscaled(dtype, dev, dim, theta, cfg.max_position_embeddings),
696 }
697 }
698
699 fn new_unscaled(
700 dtype: DType,
701 dev: &Device,
702 dim: usize,
703 theta: f32,
704 max_seq_len: usize,
705 ) -> Result<Self> {
706 let inv_freq: Vec<f32> = (0..dim)
707 .step_by(2)
708 .map(|i| 1f32 / theta.powf(i as f32 / dim as f32))
709 .collect();
710 let inv_freq_len = inv_freq.len();
711 let inv_freq = Tensor::from_vec(inv_freq, (1, inv_freq_len), dev)?;
712 let t = Tensor::arange(0u32, max_seq_len as u32, dev)?
713 .to_dtype(DType::F32)?
714 .reshape((max_seq_len, 1))?;
715 let freqs = t.matmul(&inv_freq)?;
716 Ok(Self {
717 sin: freqs.sin()?.to_dtype(dtype)?,
718 cos: freqs.cos()?.to_dtype(dtype)?,
719 })
720 }
721
722 #[allow(clippy::too_many_arguments)]
723 fn new_yarn(
724 dtype: DType,
725 dev: &Device,
726 dim: usize,
727 theta: f32,
728 max_position_embeddings: usize,
729 original_max_position_embeddings: usize,
730 beta_fast: f32,
731 beta_slow: f32,
732 factor: f32,
733 mscale: f32,
734 mscale_all_dim: f32,
735 ) -> Result<Self> {
736 // freq_extra = un-interpolated (extrapolation) freqs; freq_inter = /factor.
737 let freq_extra: Vec<f32> = (0..dim)
738 .step_by(2)
739 .map(|i| 1f32 / theta.powf(i as f32 / dim as f32))
740 .collect();
741 let freq_extra_len = freq_extra.len();
742 let freq_extra = Tensor::from_vec(freq_extra, freq_extra_len, dev)?;
743 let freq_inter: Vec<f32> = (0..dim)
744 .step_by(2)
745 .map(|i| 1f32 / (factor * theta.powf(i as f32 / dim as f32)))
746 .collect();
747 let freq_inter_len = freq_inter.len();
748 let freq_inter = Tensor::from_vec(freq_inter, (1, freq_inter_len), dev)?;
749
750 let (low, high) = yarn_find_correction_range(
751 beta_fast,
752 beta_slow,
753 dim,
754 theta,
755 original_max_position_embeddings,
756 );
757 let inv_freq_mask = (1.0 - yarn_linear_ramp_mask(low, high, dim / 2, dev)?)?;
758 let inv_freq = freq_inter
759 .broadcast_mul(&(1.0 - &inv_freq_mask)?)?
760 .broadcast_add(&freq_extra.broadcast_mul(&inv_freq_mask)?)?;
761
762 let t = Tensor::arange(0u32, max_position_embeddings as u32, dev)?
763 .to_dtype(DType::F32)?
764 .reshape((max_position_embeddings, 1))?;
765 let freqs = t.matmul(&inv_freq)?;
766
767 // sin/cos magnitude correction. On V2-Lite mscale==mscale_all_dim → 1.0.
768 let mscale =
769 yarn_get_mscale(factor, mscale) / yarn_get_mscale(factor, mscale_all_dim);
770 let sin = (freqs.sin()? * mscale as f64)?.to_dtype(dtype)?;
771 let cos = (freqs.cos()? * mscale as f64)?.to_dtype(dtype)?;
772 Ok(Self { sin, cos })
773 }
774
775 /// Apply interleaved rope to q_pe and k_pe (each `[b, heads_or_1, seq, rope_dim]`).
776 /// Uses candle `rope_i` to match the oracle byte-for-byte.
777 fn apply(&self, q: &Tensor, k: &Tensor, seqlen_offset: usize) -> Result<(Tensor, Tensor)> {
778 let (_b, _h, seq_len, _d) = q.dims4()?;
779 let cos = self.cos.narrow(0, seqlen_offset, seq_len)?;
780 let sin = self.sin.narrow(0, seqlen_offset, seq_len)?;
781 let q_embed = candle_nn::rotary_emb::rope_i(&q.contiguous()?, &cos, &sin)?;
782 let k_embed = candle_nn::rotary_emb::rope_i(&k.contiguous()?, &cos, &sin)?;
783 Ok((q_embed, k_embed))
784 }
785}
786
787// YaRN helpers — ported verbatim from deepseek2.rs.
788fn yarn_find_correction_dim(num_rot: f32, dim: usize, base: f32, max_pos: usize) -> f32 {
789 (dim as f32 * (max_pos as f32 / (num_rot * 2.0 * std::f32::consts::PI)).ln())
790 / (2.0 * base.ln())
791}
792
793fn yarn_find_correction_range(
794 low_rot: f32,
795 high_rot: f32,
796 dim: usize,
797 base: f32,
798 max_pos: usize,
799) -> (f32, f32) {
800 let low = yarn_find_correction_dim(low_rot, dim, base, max_pos).floor();
801 let high = yarn_find_correction_dim(high_rot, dim, base, max_pos).ceil();
802 (low.max(0.0), high.min(dim as f32 - 1.0))
803}
804
805fn yarn_linear_ramp_mask(min: f32, mut max: f32, dim: usize, dev: &Device) -> Result<Tensor> {
806 if min == max {
807 max += 0.001;
808 }
809 let linear_func =
810 ((Tensor::arange(0f32, dim as f32, dev)? - min as f64)? / (max as f64 - min as f64))?;
811 Ok(linear_func.clamp(0.0, 1.0)?)
812}
813
814/// The optional compressed-Q latent path. `Plain` = direct q_proj (V2-Lite,
815/// q_lora_rank=null); `Lora` = q_a_proj → q_a_layernorm → q_b_proj (full V2/V3).
816/// Mirrors deepseek2.rs `QProj`.
817enum QProj {
818 Plain(Proj),
819 Lora {
820 a: Proj,
821 norm: RmsNorm,
822 b: Proj,
823 },
824}
825
826impl QProj {
827 fn forward(&self, xs: &Tensor) -> Result<Tensor> {
828 match self {
829 QProj::Plain(lin) => lin.forward(xs),
830 QProj::Lora { a, norm, b } => b.forward(&norm.forward(&a.forward(xs)?)?),
831 }
832 }
833}
834
835/// Multi-head Latent Attention (DeepSeek V2/V3). Candle-fallback-first: ports
836/// deepseek2.rs `Attention::forward` line-for-line onto coco's QLinear primitives.
837///
838/// Genuinely-new vs GqaAttention: asymmetric K(192)/V(128); a nope+rope head split
839/// with rope on only a 64-dim slice; a single shared k_pe broadcast across all query
840/// heads (MQA-style latent). The cache is a PEER `LatentKvCache` (candle
841/// `Option<(Tensor,Tensor)>` cat-cache of the reconstructed per-head k[192]/v[128]);
842/// the fused GQA `KvCache` is NOT allocated for this arch.
843pub struct MlaAttention {
844 q: QProj,
845 kv_a_proj_with_mqa: Proj,
846 kv_a_layernorm: RmsNorm,
847 kv_b_proj: Proj,
848 o_proj: Proj,
849 rotary_emb: Arc<MlaRope>,
850 num_heads: usize,
851 q_head_dim: usize, // qk_nope + qk_rope (192)
852 qk_nope_head_dim: usize, // 128
853 qk_rope_head_dim: usize, // 64
854 v_head_dim: usize, // 128
855 kv_lora_rank: usize, // 512 (c_kv width == kv_a_layernorm length)
856 softmax_scale: f64,
857 /// Peer LatentKvCache (fallback form): reconstructed per-head k[192]/v[128], grown
858 /// by Tensor::cat along seq — exactly GqaAttention::candle_attention's path. This
859 /// is intentionally NOT the fused KvCache (asymmetric K/V, latent layout).
860 kv_cache: Option<(Tensor, Tensor)>,
861}
862
863impl MlaAttention {
864 pub fn new(
865 src: &mut WeightSource,
866 prefix: &str,
867 rotary_emb: Arc<MlaRope>,
868 cfg: &CocoConfig,
869 norm_vb: &VarBuilder,
870 ) -> Result<Self> {
871 let num_heads = cfg.num_attention_heads;
872 let q_head_dim = cfg.mla_q_head_dim();
873 let bias = cfg.attention_bias;
874
875 // Q path: Plain (q_proj) or Lora (q_a_proj → q_a_layernorm → q_b_proj).
876 let q = match cfg.q_lora_rank {
877 None => QProj::Plain(src.proj(&format!("{prefix}.q_proj"), bias)?),
878 Some(lora_rank) => {
879 let a = src.proj(&format!("{prefix}.q_a_proj"), bias)?;
880 let norm_w = norm_vb
881 .pp(format!("{prefix}.q_a_layernorm"))
882 .get(lora_rank, "weight")?;
883 let norm = RmsNorm::new(norm_w, cfg.rms_norm_eps)?;
884 let b = src.proj(&format!("{prefix}.q_b_proj"), false)?;
885 QProj::Lora { a, norm, b }
886 }
887 };
888
889 // kv_a_proj_with_mqa: hidden → kv_lora_rank + qk_rope_head_dim (576 on V2-Lite).
890 let kv_a_proj_with_mqa = src.proj(&format!("{prefix}.kv_a_proj_with_mqa"), bias)?;
891 let kv_a_norm_w = norm_vb
892 .pp(format!("{prefix}.kv_a_layernorm"))
893 .get(cfg.kv_lora_rank, "weight")?;
894 let kv_a_layernorm = RmsNorm::new(kv_a_norm_w, cfg.rms_norm_eps)?;
895 // kv_b_proj: kv_lora_rank → heads * (qk_nope + v_head_dim). No bias (oracle).
896 let kv_b_proj = src.proj(&format!("{prefix}.kv_b_proj"), false)?;
897 let o_proj = src.proj(&format!("{prefix}.o_proj"), bias)?;
898
899 Ok(Self {
900 q,
901 kv_a_proj_with_mqa,
902 kv_a_layernorm,
903 kv_b_proj,
904 o_proj,
905 rotary_emb,
906 num_heads,
907 q_head_dim,
908 qk_nope_head_dim: cfg.qk_nope_head_dim,
909 qk_rope_head_dim: cfg.qk_rope_head_dim,
910 v_head_dim: cfg.v_head_dim,
911 kv_lora_rank: cfg.kv_lora_rank,
912 softmax_scale: cfg.mla_softmax_scale(),
913 kv_cache: None,
914 })
915 }
916}
917
918impl SequenceMixer for MlaAttention {
919 fn forward(
920 &mut self,
921 xs: &Tensor,
922 attention_mask: Option<&Tensor>,
923 seqlen_offset: usize,
924 resid: Option<&Tensor>,
925 ) -> Result<Tensor> {
926 let _ = fused_mla_enabled(); // fused Metal MLA is a later step; fallback always.
927 let (bs, seq_len, _) = xs.dims3()?;
928
929 // 1. Q path → [bs, heads, seq, q_head_dim]; split nope[128] + pe[64].
930 let q = self.q.forward(xs)?;
931 let q = q
932 .reshape((bs, seq_len, self.num_heads, self.q_head_dim))?
933 .transpose(1, 2)?;
934 let q_nope = q.narrow(D::Minus1, 0, self.qk_nope_head_dim)?;
935 let q_pe = q.narrow(D::Minus1, self.qk_nope_head_dim, self.qk_rope_head_dim)?;
936
937 // 2. KV compression: compressed = kv_a_proj_with_mqa(x) → c_kv[512] + k_pe[64].
938 let compressed_kv = self.kv_a_proj_with_mqa.forward(xs)?;
939 let c_kv = compressed_kv.narrow(D::Minus1, 0, self.kv_lora_rank)?;
940 let k_pe = compressed_kv.narrow(D::Minus1, self.kv_lora_rank, self.qk_rope_head_dim)?;
941 // k_pe: one shared rope key → [bs, 1, seq, rope_dim].
942 let k_pe = k_pe
943 .reshape((bs, seq_len, 1, self.qk_rope_head_dim))?
944 .transpose(1, 2)?;
945
946 // 3. Reconstruct: kv = kv_b_proj(kv_a_layernorm(c_kv)) → [bs, heads, seq, 256];
947 // split k_nope[128] + v[128].
948 let kv = self.kv_b_proj.forward(&self.kv_a_layernorm.forward(&c_kv)?)?;
949 let kv = kv
950 .reshape((
951 bs,
952 seq_len,
953 self.num_heads,
954 self.qk_nope_head_dim + self.v_head_dim,
955 ))?
956 .transpose(1, 2)?;
957 let k_nope = kv.narrow(D::Minus1, 0, self.qk_nope_head_dim)?;
958 let v = kv.narrow(D::Minus1, self.qk_nope_head_dim, self.v_head_dim)?;
959
960 // 4. Decoupled RoPE on q_pe and k_pe (64-dim slices only).
961 let (q_pe, k_pe) = self.rotary_emb.apply(&q_pe, &k_pe, seqlen_offset)?;
962
963 // 5. Assemble q=cat(q_nope,q_pe)→192; k=cat(k_nope, broadcast(k_pe over heads))→192.
964 let q = Tensor::cat(&[&q_nope.contiguous()?, &q_pe.contiguous()?], D::Minus1)?;
965 let k_pe_b = k_pe.broadcast_as((bs, self.num_heads, seq_len, self.qk_rope_head_dim))?;
966 let k = Tensor::cat(&[&k_nope.contiguous()?, &k_pe_b.contiguous()?], D::Minus1)?;
967
968 // 6. Grow the peer latent cache (reconstructed k[192]/v[128]) along seq.
969 let (k, v) = match &self.kv_cache {
970 None => (k, v),
971 Some((prev_k, prev_v)) => {
972 let k = Tensor::cat(&[prev_k, &k], 2)?;
973 let v = Tensor::cat(&[prev_v, &v], 2)?;
974 (k, v)
975 }
976 };
977 self.kv_cache = Some((k.clone(), v.clone()));
978
979 // 7. Attend: softmax(q·kᵀ·scale + mask)·v → v_head_dim wide → o_proj.
980 let att = (q.contiguous()?.matmul(&k.t()?.contiguous()?)? * self.softmax_scale)?;
981 let att = match attention_mask {
982 Some(mask) => att.broadcast_add(mask)?,
983 None => att,
984 };
985 let att = candle_nn::ops::softmax_last_dim(&att)?;
986 let ctx = att.matmul(&v.contiguous()?)?; // [bs, heads, seq, v_head_dim]
987 let ctx = ctx
988 .transpose(1, 2)?
989 .reshape((bs, seq_len, self.num_heads * self.v_head_dim))?;
990
991 match resid {
992 Some(r) => self.o_proj.forward_resid(&ctx, r),
993 None => self.o_proj.forward(&ctx),
994 }
995 }
996
997 fn clear_cache(&mut self) {
998 self.kv_cache = None;
999 }
1000}
1001
1002// ─────────────────────────── mixer: GatedDeltaNet (qwen3_5 linear-attn) ───────────────────────────
1003
1004/// GatedDeltaNet linear-attention mixer (qwen3_next / qwen3_5). Matrix-valued recurrent
1005/// state (NOT masked softmax), validated bit-exact against the HF oracle in `bin/gdn_ref.rs`
1006/// (max_abs_err 1.8e-7). Incremental: the per-layer `state` (S[nv,hk,hv] f32) + `conv_state`
1007/// [conv_dim, k-1] carry across forward calls → constant memory regardless of context.
1008pub struct GatedDeltaNet {
1009 in_proj_qkvz: Proj,
1010 in_proj_ba: Proj,
1011 out_proj: Proj,
1012 conv1d_w: Tensor, // [conv_dim, 1, k]
1013 a_log: Tensor, // [nv]
1014 dt_bias: Tensor, // [nv]
1015 norm_w: Tensor, // [hv] (RMSNormGated)
1016 hidden: usize,
1017 nk: usize,
1018 nv: usize,
1019 hk: usize,
1020 hv: usize,
1021 ck: usize,
1022 eps: f64,
1023 state: Option<Tensor>, // S[nv,hk,hv] f32
1024 conv_state: Option<Tensor>, // [conv_dim, ck-1] f32
1025}
1026
1027impl GatedDeltaNet {
1028 pub fn new(
1029 src: &mut WeightSource,
1030 prefix: &str,
1031 cfg: &CocoConfig,
1032 norm_vb: &VarBuilder,
1033 ) -> Result<Self> {
1034 let nk = cfg.linear_num_key_heads;
1035 let nv = cfg.linear_num_value_heads;
1036 let hk = cfg.linear_key_head_dim;
1037 let hv = cfg.linear_value_head_dim;
1038 let ck = cfg.linear_conv_kernel_dim;
1039 let conv_dim = nk * hk * 2 + nv * hv; // key_dim*2 + value_dim
1040 Ok(Self {
1041 in_proj_qkvz: src.proj(&format!("{prefix}.in_proj_qkvz"), false)?,
1042 in_proj_ba: src.proj(&format!("{prefix}.in_proj_ba"), false)?,
1043 out_proj: src.proj(&format!("{prefix}.out_proj"), false)?,
1044 conv1d_w: norm_vb.pp(format!("{prefix}.conv1d")).get((conv_dim, 1, ck), "weight")?,
1045 a_log: norm_vb.pp(prefix).get(nv, "A_log")?,
1046 dt_bias: norm_vb.pp(prefix).get(nv, "dt_bias")?,
1047 norm_w: norm_vb.pp(format!("{prefix}.norm")).get(hv, "weight")?,
1048 hidden: cfg.hidden_size,
1049 nk,
1050 nv,
1051 hk,
1052 hv,
1053 ck,
1054 eps: cfg.rms_norm_eps,
1055 state: None,
1056 conv_state: None,
1057 })
1058 }
1059}
1060
1061fn gdn_silu(x: &Tensor) -> Result<Tensor> {
1062 Ok((x * candle_nn::ops::sigmoid(x)?)?)
1063}
1064fn gdn_l2norm(x: &Tensor, eps: f64) -> Result<Tensor> {
1065 let denom = (x.sqr()?.sum_keepdim(candle_core::D::Minus1)? + eps)?.sqrt()?;
1066 Ok(x.broadcast_div(&denom)?)
1067}
1068
1069impl SequenceMixer for GatedDeltaNet {
1070 fn forward(
1071 &mut self,
1072 xs: &Tensor,
1073 _attention_mask: Option<&Tensor>,
1074 _seqlen_offset: usize,
1075 resid: Option<&Tensor>,
1076 ) -> Result<Tensor> {
1077 use candle_core::{DType, IndexOp, D};
1078 let (b_sz, q_len, _) = xs.dims3()?;
1079 let dev = xs.device().clone();
1080 let (nk, nv, hk, hv, ck) = (self.nk, self.nv, self.hk, self.hv, self.ck);
1081 let (kd, vd, rep) = (nk * hk, nv * hv, nv / nk);
1082 let conv_dim = kd + kd + vd;
1083 let s = b_sz * q_len;
1084
1085 // 1. projections (f32 for the recurrence numerics)
1086 let x = xs.reshape((s, self.hidden))?.to_dtype(DType::F32)?;
1087 let qkvz = self.in_proj_qkvz.forward(&x)?.to_dtype(DType::F32)?;
1088 let ba = self.in_proj_ba.forward(&x)?.to_dtype(DType::F32)?;
1089
1090 // 2. fix ordering
1091 let qkvz = qkvz.reshape((s, nk, 2 * hk + 2 * hv * rep))?;
1092 let q = qkvz.narrow(2, 0, hk)?.contiguous()?.reshape((s, kd))?;
1093 let k = qkvz.narrow(2, hk, hk)?.contiguous()?.reshape((s, kd))?;
1094 let v3 = qkvz.narrow(2, 2 * hk, rep * hv)?.reshape((s, vd))?;
1095 let z = qkvz.narrow(2, 2 * hk + rep * hv, rep * hv)?.reshape((s, nv, hv))?;
1096 let ba = ba.reshape((s, nk, 2 * rep))?;
1097 let b = ba.narrow(2, 0, rep)?.reshape((s, nv))?;
1098 let a = ba.narrow(2, rep, rep)?.reshape((s, nv))?;
1099
1100 // 3+4. conv (causal depthwise, k=4) continuing from cached conv_state, + silu
1101 let mixed_t = Tensor::cat(&[&q, &k, &v3], 1)?.t()?.contiguous()?; // [conv_dim, s]
1102 let prev = match &self.conv_state {
1103 Some(cs) => cs.clone(),
1104 None => Tensor::zeros((conv_dim, ck - 1), DType::F32, &dev)?,
1105 };
1106 let padded = Tensor::cat(&[&prev, &mixed_t], 1)?; // [conv_dim, ck-1+s]
1107 let convd = padded
1108 .unsqueeze(0)?
1109 .conv1d(&self.conv1d_w, 0, 1, 1, conv_dim)?
1110 .squeeze(0)?; // [conv_dim, s]
1111 self.conv_state = Some(padded.narrow(1, padded.dim(1)? - (ck - 1), ck - 1)?.contiguous()?);
1112 let mixed = gdn_silu(&convd)?.t()?.contiguous()?; // [s, conv_dim]
1113
1114 // 5. split; 6. beta,g; 7. repeat_interleave q,k
1115 let q = mixed.narrow(1, 0, kd)?.reshape((s, nk, hk))?;
1116 let k = mixed.narrow(1, kd, kd)?.reshape((s, nk, hk))?;
1117 let v = mixed.narrow(1, 2 * kd, vd)?.reshape((s, nv, hv))?;
1118 let beta = candle_nn::ops::sigmoid(&b)?;
1119 let gate = softplus_pos(&a.broadcast_add(&self.dt_bias)?)?;
1120 let gdecay = gate.broadcast_mul(&self.a_log.exp()?.neg()?)?; // [s,nv]
1121 let ri = |t: &Tensor| -> Result<Tensor> {
1122 Ok(t.reshape((s, nk, 1, hk))?
1123 .broadcast_as((s, nk, rep, hk))?
1124 .reshape((s, nv, hk))?)
1125 };
1126 let q = (gdn_l2norm(&ri(&q)?, 1e-6)? * (1.0 / (hk as f64).sqrt()))?;
1127 let k = gdn_l2norm(&ri(&k)?, 1e-6)?;
1128
1129 // 8. recurrence continuing from cached S
1130 let mut sstate = match &self.state {
1131 Some(st) => st.clone(),
1132 None => Tensor::zeros((nv, hk, hv), DType::F32, &dev)?,
1133 };
1134 let mut outs: Vec<Tensor> = Vec::with_capacity(s);
1135 for i in 0..s {
1136 let q_t = q.i(i)?;
1137 let k_t = k.i(i)?;
1138 let v_t = v.i(i)?;
1139 let g_t = gdecay.i(i)?.exp()?.reshape((nv, 1, 1))?;
1140 let beta_t = beta.i(i)?.reshape((nv, 1))?;
1141 sstate = sstate.broadcast_mul(&g_t)?;
1142 let k_col = k_t.reshape((nv, hk, 1))?;
1143 let kv = sstate.broadcast_mul(&k_col)?.sum(1)?;
1144 let delta = (v_t - kv)?.broadcast_mul(&beta_t)?;
1145 sstate = (sstate + k_col.broadcast_mul(&delta.reshape((nv, 1, hv))?)?)?;
1146 outs.push(sstate.broadcast_mul(&q_t.reshape((nv, hk, 1))?)?.sum(1)?.unsqueeze(0)?);
1147 }
1148 self.state = Some(sstate);
1149 let out = Tensor::cat(&outs, 0)?; // [s,nv,hv]
1150
1151 // 9. RMSNormGated; 10. out_proj (+ resid)
1152 let oc = out.reshape((s * nv, hv))?;
1153 let zc = z.reshape((s * nv, hv))?;
1154 let var = oc.sqr()?.mean_keepdim(D::Minus1)?;
1155 let oc = oc.broadcast_div(&(var + self.eps)?.sqrt()?)?;
1156 let oc = oc.broadcast_mul(&self.norm_w)?;
1157 let oc = (oc * gdn_silu(&zc)?)?.reshape((b_sz, q_len, vd))?;
1158 let oc = oc.to_dtype(xs.dtype())?;
1159 match resid {
1160 Some(r) => self.out_proj.forward_resid(&oc, r),
1161 None => self.out_proj.forward(&oc),
1162 }
1163 }
1164
1165 fn clear_cache(&mut self) {
1166 self.state = None;
1167 self.conv_state = None;
1168 }
1169}
1170
1171fn softplus_pos(x: &Tensor) -> Result<Tensor> {
1172 Ok(((x.exp()? + 1.0)?).log()?)
1173}
1174
1175// ─────────────────────────── DecoderLayer (config-driven op-list) ───────────────────────────
1176
1177/// One decoder layer = the ordered op-list, driven by config not hard-coded. For
1178/// qwen2 the optional sandwich norms are None and the ffn is Ffn::Dense(SwiGlu).
1179pub struct DecoderLayer {
1180 input_norm: RmsNorm,
1181 mixer: Box<dyn SequenceMixer>,
1182 post_attn_norm: Option<RmsNorm>,
1183 pre_ffn_norm: RmsNorm,
1184 ffn: Ffn,
1185 post_ffn_norm: Option<RmsNorm>,
1186}
1187
1188impl DecoderLayer {
1189 fn new(
1190 src: &mut WeightSource,
1191 idx: usize,
1192 rotary_emb: Arc<Rope>,
1193 mla_rotary_emb: Option<&Arc<MlaRope>>,
1194 cfg: &CocoConfig,
1195 norm_vb: &VarBuilder,
1196 ) -> Result<Self> {
1197 let prefix = format!("model.layers.{idx}");
1198 // Mixer: MLA for DeepSeek V2/V3, GQA (qwen2/qwen3/qwen3_moe) otherwise. Both
1199 // implement the SAME SequenceMixer trait → no op-list change, cache stays
1200 // hidden inside the mixer (MLA owns a peer LatentKvCache, not the fused KvCache).
1201 let mixer: Box<dyn SequenceMixer> = if cfg.arch == Arch::DeepSeekV2 {
1202 let mla_rope = mla_rotary_emb
1203 .expect("MlaRope must be built for Arch::DeepSeekV2")
1204 .clone();
1205 Box::new(MlaAttention::new(
1206 src,
1207 &format!("{prefix}.self_attn"),
1208 mla_rope,
1209 cfg,
1210 norm_vb,
1211 )?)
1212 } else {
1213 Box::new(GqaAttention::new(
1214 src,
1215 &format!("{prefix}.self_attn"),
1216 rotary_emb,
1217 cfg,
1218 norm_vb,
1219 )?)
1220 };
1221 // Per-layer dense-vs-MoE. qwen3_moe: layers not in mlp_only_layers / not skipped
1222 // by decoder_sparse_step. DeepSeek-MoE: first_k_dense_replace layers are dense,
1223 // the rest MoE (deepseek_layer_is_moe). Dense archs always take SwiGLU. Same
1224 // op-list, only the Ffn variant differs — the registry moat (design §1.2).
1225 let is_moe = if cfg.arch == Arch::DeepSeekV2 {
1226 cfg.deepseek_layer_is_moe(idx)
1227 } else {
1228 cfg.layer_is_moe(idx)
1229 };
1230 let ffn = if is_moe {
1231 Ffn::Moe(MoeFfn::new(src, &format!("{prefix}.mlp"), cfg, norm_vb)?)
1232 } else {
1233 Ffn::Dense(SwiGlu::new(src, &format!("{prefix}.mlp"), cfg)?)
1234 };
1235 let input_norm = RmsNorm::new(
1236 norm_vb
1237 .pp(format!("model.layers.{idx}.input_layernorm"))
1238 .get(cfg.hidden_size, "weight")?,
1239 cfg.rms_norm_eps,
1240 )?;
1241 let pre_ffn_norm = RmsNorm::new(
1242 norm_vb
1243 .pp(format!("model.layers.{idx}.post_attention_layernorm"))
1244 .get(cfg.hidden_size, "weight")?,
1245 cfg.rms_norm_eps,
1246 )?;
1247 Ok(Self {
1248 input_norm,
1249 mixer,
1250 post_attn_norm: None, // gemma3 sandwich norms land later
1251 pre_ffn_norm,
1252 ffn,
1253 post_ffn_norm: None,
1254 })
1255 }
1256
1257 fn forward(
1258 &mut self,
1259 xs: &Tensor,
1260 attention_mask: Option<&Tensor>,
1261 seqlen_offset: usize,
1262 ) -> Result<Tensor> {
1263 let residual = xs;
1264 let xs = self.input_norm.forward(xs)?;
1265 if fuse_resid_enabled() {
1266 let h = self
1267 .mixer
1268 .forward(&xs, attention_mask, seqlen_offset, Some(residual))?;
1269 // post_attn_norm (sandwich) would go here for gemma3; None for qwen2.
1270 let normed = self.pre_ffn_norm.forward(&h)?;
1271 let out = self.ffn.forward(&normed, Some(&h))?;
1272 // post_ffn_norm (sandwich) would go here for gemma3; None for qwen2.
1273 return Ok(out);
1274 }
1275 let attn_out = self
1276 .mixer
1277 .forward(&xs, attention_mask, seqlen_offset, None)?;
1278 let (h, normed) = self.pre_ffn_norm.forward_add(residual, &attn_out)?;
1279 let xs2 = self.ffn.forward(&normed, None)?;
1280 Ok((&h + xs2)?)
1281 }
1282
1283 fn clear_kv_cache(&mut self) {
1284 self.mixer.clear_cache();
1285 let _ = &self.post_attn_norm;
1286 let _ = &self.post_ffn_norm;
1287 }
1288}
1289
1290// ─────────────────────────── DenseDecoder (the qwen2/qwen3/llama/… wiring) ───────────────────────────
1291
1292/// The generic dense-FFN decoder wiring. qwen2/qwen3/llama/mistral/gemma3 all use
1293/// this same op-list; only config flags differ. Step 0 registers qwen2 only.
1294pub struct DenseDecoder {
1295 embed_tokens: candle_nn::Embedding,
1296 layers: Vec<DecoderLayer>,
1297 norm: RmsNorm,
1298 lm_head: Proj,
1299 sliding_window: usize,
1300 device: Device,
1301 dtype: DType,
1302}
1303
1304impl DenseDecoder {
1305 pub fn new(cfg: &CocoConfig, mut src: WeightSource, vb: VarBuilder) -> Result<(Self, WeightStats)> {
1306 let device = src.device.clone();
1307 let dtype = src.dtype;
1308 let vb_m = vb.pp("model");
1309 let embed_tokens =
1310 candle_nn::embedding(cfg.vocab_size, cfg.hidden_size, vb_m.pp("embed_tokens"))?;
1311 let rotary_emb = Arc::new(Rope::new(dtype, cfg, &device)?);
1312 // MLA decoupled-rope table (sized qk_rope_head_dim, YaRN-scaled) — built only
1313 // for DeepSeek so other archs pay nothing. Shared Arc across all layers.
1314 let mla_rotary_emb = if cfg.arch == Arch::DeepSeekV2 {
1315 Some(Arc::new(MlaRope::new(dtype, cfg, &device)?))
1316 } else {
1317 None
1318 };
1319 let mut layers = Vec::with_capacity(cfg.num_hidden_layers);
1320 for idx in 0..cfg.num_hidden_layers {
1321 layers.push(DecoderLayer::new(
1322 &mut src,
1323 idx,
1324 rotary_emb.clone(),
1325 mla_rotary_emb.as_ref(),
1326 cfg,
1327 &vb,
1328 )?);
1329 }
1330 let norm = RmsNorm::new(vb_m.pp("norm").get(cfg.hidden_size, "weight")?, cfg.rms_norm_eps)?;
1331
1332 // lm_head — identical logic to qwen2_q.rs::Model::new. Tied embeddings stay
1333 // fp16; a separate head is optionally turboquant'd via COCO_QUANT_HEAD.
1334 let head_separate = vb.contains_tensor("lm_head.weight");
1335 let quant_head = matches!(std::env::var("COCO_QUANT_HEAD").as_deref(), Ok(v) if v != "0");
1336 let lm_head = if !head_separate {
1337 if quant_head {
1338 eprintln!(
1339 "COCO_QUANT_HEAD set but this model TIES lm_head to the embeddings \
1340 (no separate lm_head.weight) — keeping the head fp16 to avoid \
1341 double-quantizing the shared embedding matrix."
1342 );
1343 }
1344 Proj::Dense(candle_nn::Linear::new(embed_tokens.embeddings().clone(), None))
1345 } else if quant_head {
1346 if matches!(std::env::var("COCO_QUANT_HEAD").as_deref(), Ok("8")) {
1347 eprintln!(
1348 "COCO_QUANT_HEAD=8 requested but the qmatvec kernel is 3-bit (8-level) \
1349 only — a Q8 head is not wired; using the standard turboquant 3-bit head."
1350 );
1351 }
1352 let (qw, comp, fp16) = src.quant_lm_head(&vb, cfg.vocab_size, cfg.hidden_size)?;
1353 eprintln!(
1354 "COCO_QUANT_HEAD: lm_head compressed {:.1} MB fp16 -> {:.1} MB (3-bit)",
1355 fp16 as f64 / (1024.0 * 1024.0),
1356 comp as f64 / (1024.0 * 1024.0),
1357 );
1358 Proj::Quant(qw)
1359 } else {
1360 Proj::Dense(candle_nn::linear_no_bias(
1361 cfg.hidden_size,
1362 cfg.vocab_size,
1363 vb.pp("lm_head"),
1364 )?)
1365 };
1366
1367 let stats = src.stats();
1368 Ok((
1369 Self {
1370 embed_tokens,
1371 layers,
1372 norm,
1373 lm_head,
1374 sliding_window: cfg.sliding_window,
1375 device,
1376 dtype,
1377 },
1378 stats,
1379 ))
1380 }
1381
1382 fn prepare_causal_attention_mask(
1383 &self,
1384 b_size: usize,
1385 tgt_len: usize,
1386 seqlen_offset: usize,
1387 ) -> Result<Tensor> {
1388 let mask: Vec<_> = (0..tgt_len)
1389 .flat_map(|i| {
1390 (0..tgt_len).map(move |j| {
1391 if i < j || j + self.sliding_window < i {
1392 f32::NEG_INFINITY
1393 } else {
1394 0.
1395 }
1396 })
1397 })
1398 .collect();
1399 let mask = Tensor::from_slice(&mask, (tgt_len, tgt_len), &self.device)?;
1400 let mask = if seqlen_offset > 0 {
1401 let mask0 = Tensor::zeros((tgt_len, seqlen_offset), DType::F32, &self.device)?;
1402 Tensor::cat(&[&mask0, &mask], D::Minus1)?
1403 } else {
1404 mask
1405 };
1406 Ok(mask
1407 .expand((b_size, 1, tgt_len, tgt_len + seqlen_offset))?
1408 .to_dtype(self.dtype)?)
1409 }
1410}
1411
1412impl Model for DenseDecoder {
1413 fn forward(&mut self, input_ids: &Tensor, seqlen_offset: usize) -> Result<Tensor> {
1414 let (b_size, seq_len) = input_ids.dims2()?;
1415 let attention_mask: Option<Tensor> = if seq_len <= 1 {
1416 None
1417 } else {
1418 Some(self.prepare_causal_attention_mask(b_size, seq_len, seqlen_offset)?)
1419 };
1420 // COCO_PROFILE: sync-and-time the layers vs norm+lm_head phases of a single-
1421 // token decode. Off by default (the syncs serialize the pipeline; profiling
1422 // only) — so the gate path (COCO_PROFILE unset) is byte-identical to below.
1423 let profile = seq_len == 1 && std::env::var("COCO_PROFILE").is_ok();
1424 let mut xs = self.embed_tokens.forward(input_ids)?;
1425 if profile {
1426 self.device.synchronize()?;
1427 let t = std::time::Instant::now();
1428 for layer in self.layers.iter_mut() {
1429 xs = layer.forward(&xs, attention_mask.as_ref(), seqlen_offset)?;
1430 }
1431 self.device.synchronize()?;
1432 let t_layers = t.elapsed().as_secs_f64();
1433 let t = std::time::Instant::now();
1434 let xn = xs.narrow(1, seq_len - 1, 1)?;
1435 let xn = self.norm.forward(&xn)?;
1436 let out = self.lm_head.forward(&xn)?;
1437 self.device.synchronize()?;
1438 let t_head = t.elapsed().as_secs_f64();
1439 PROFILE_ACC.with(|a| {
1440 let mut a = a.borrow_mut();
1441 a.0 += t_layers;
1442 a.1 += t_head;
1443 a.2 += 1;
1444 });
1445 return Ok(out);
1446 }
1447 for layer in self.layers.iter_mut() {
1448 xs = layer.forward(&xs, attention_mask.as_ref(), seqlen_offset)?;
1449 }
1450 let xs = xs.narrow(1, seq_len - 1, 1)?;
1451 let xs = self.norm.forward(&xs)?;
1452 self.lm_head.forward(&xs)
1453 }
1454
1455 fn clear_kv_cache(&mut self) {
1456 for layer in self.layers.iter_mut() {
1457 layer.clear_kv_cache()
1458 }
1459 }
1460}
1461
1462// ─────────────────────────── the dispatcher ───────────────────────────
1463
1464/// config.json → Arch → assembled forward. The `match cfg.arch` IS the registry.
1465/// Returns the boxed model + load-time weight stats (for the storage report).
1466pub fn build_model(
1467 cfg: &CocoConfig,
1468 src: WeightSource,
1469 vb: VarBuilder,
1470) -> Result<(Box<dyn Model>, WeightStats)> {
1471 match cfg.arch {
1472 // qwen2 and qwen3 dense share the SAME DenseDecoder wiring — only config flags
1473 // differ (qwen3: qk_norm=true, attn_bias=false, explicit head_dim). This IS the
1474 // registry moat: a second architecture through one op-list, no new forward.
1475 Arch::Qwen2 | Arch::Qwen3 => {
1476 let (m, stats) = DenseDecoder::new(cfg, src, vb)?;
1477 Ok((Box::new(m), stats))
1478 }
1479 // qwen3_moe = qwen3 attention (qk_norm GqaAttention, reused unchanged) with an
1480 // Ffn::Moe per sparse layer. The SAME DenseDecoder/DecoderLayer op-list — the
1481 // ONLY delta is the FFN variant, selected per layer inside DecoderLayer::new via
1482 // cfg.layer_is_moe. No forked attention, no new kernel (design §3 Step 2).
1483 Arch::Qwen3Moe => {
1484 let (m, stats) = DenseDecoder::new(cfg, src, vb)?;
1485 Ok((Box::new(m), stats))
1486 }
1487 // DeepSeek V2/V3: the SAME DenseDecoder/DecoderLayer op-list, but each layer's
1488 // SequenceMixer is MlaAttention (built when cfg.arch == DeepSeekV2 inside
1489 // DecoderLayer::new) and the FFN is DeepSeek-MoE (shared experts + dense prefix
1490 // + routed scaling). No forked decoder; the fused Metal MLA kernel is gated
1491 // behind COCO_FUSED_MLA (default = the candle fallback, always correct).
1492 Arch::DeepSeekV2 => {
1493 let (m, stats) = DenseDecoder::new(cfg, src, vb)?;
1494 Ok((Box::new(m), stats))
1495 }
1496 // Qwen3.5: config parses + arch resolves (registry moat done), but the
1497 // GatedDeltaNet linear-attn SequenceMixer + recurrent-state cache are not yet
1498 // implemented. Report the parsed layer plan so the config path is provably wired.
1499 Arch::Qwen35 => {
1500 let n = cfg.num_hidden_layers;
1501 let lin = (0..n).filter(|&i| cfg.layer_is_linear_attn(i)).count();
1502 anyhow::bail!(
1503 "Qwen3.5 recognized + config parsed: {n} layers = {lin} GatedDeltaNet (linear-attn) \
1504 + {} full-attn GQA; head_dim={}, linear_k_heads={} linear_v_heads={} conv_k={}, \
1505 partial_rope={}. GatedDeltaNet SequenceMixer not yet implemented (TRENDING_ARCH_DESIGN.md §1.3).",
1506 n - lin, cfg.head_dim(), cfg.linear_num_key_heads, cfg.linear_num_value_heads,
1507 cfg.linear_conv_kernel_dim, cfg.partial_rotary_factor,
1508 )
1509 }
1510 }
1511}