Elffuss BraidHub

kikocis/coco public

main · 21.0 KiBRawPermalink
1// LEGACY inlined qwen2 forward — the ORIGINAL hard-forked qwen2 model (pre-Step-0).
2//
3// This is the pristine hand-forked qwen2 forward that shipped before the config-
4// driven registry refactor. It stays the DEFAULT path (COCO_REGISTRY unset) so the
5// Step-0 gate can A/B the OLD inlined path against the NEW registry path
6// (`model.rs` / `config.rs`, COCO_REGISTRY=1) inside ONE binary.
7//
8// It reuses the shared load-time machinery (`Proj`, `WeightSource`, `WeightStats`)
9// from `qwen2_q.rs` verbatim — only the forward (RoPE/GQA-flash-decode/SwiGLU/Model)
10// lives here. Behavior is byte-identical to the original qwen2_q.rs::Model.
11
12use anyhow::Result;
13use candle_core::{DType, Device, Module, Tensor, D};
14use candle_nn::{Activation, VarBuilder};
15use candle_transformers::models::qwen2::Config;
16use std::sync::Arc;
17
18use crate::qlinear::{fuse_resid_enabled, rope_apply, KvCache, QGroup, QWeight, RmsNormFused};
19use crate::qwen2_q::{Proj, WeightSource, WeightStats};
20use crate::turboquant::{encode, LLOYD_MAX_3BIT};
21
22thread_local! {
23 /// (layers_secs, head_secs, count) accumulated across profiled decode steps.
24 static PROFILE_ACC: std::cell::RefCell<(f64, f64, usize)> =
25 const { std::cell::RefCell::new((0.0, 0.0, 0)) };
26
27 /// Per-token cached RoPE cos/sin slice: (seqlen_offset, seq_len, cos, sin).
28 static ROPE_SLICE_CACHE: std::cell::RefCell<Option<(usize, usize, Tensor, Tensor)>> =
29 const { std::cell::RefCell::new(None) };
30}
31
32/// Print + reset the COCO_PROFILE accumulator (called from the bench harness).
33pub fn profile_report() {
34 PROFILE_ACC.with(|a| {
35 let (l, h, n) = *a.borrow();
36 if n > 0 {
37 eprintln!(
38 "PROFILE n={} | layers {:.3} ms/tok | norm+lm_head {:.3} ms/tok | total {:.3} ms/tok",
39 n,
40 l / n as f64 * 1e3,
41 h / n as f64 * 1e3,
42 (l + h) / n as f64 * 1e3,
43 );
44 }
45 });
46}
47
48fn fused_max_ctx() -> usize {
49 std::env::var("COCO_MAX_CTX")
50 .ok()
51 .and_then(|s| s.parse().ok())
52 .unwrap_or(8192)
53}
54
55fn fused_attn_enabled() -> bool {
56 !matches!(std::env::var("COCO_FUSED_ATTN").as_deref(), Ok("0"))
57}
58
59fn fused_min_ctx() -> usize {
60 std::env::var("COCO_FUSED_MIN_CTX")
61 .ok()
62 .and_then(|s| s.parse().ok())
63 .unwrap_or(0)
64}
65
66// ─────────────────────────── model (forked) ───────────────────────────
67
68struct RotaryEmbedding {
69 sin: Tensor,
70 cos: Tensor,
71}
72
73impl RotaryEmbedding {
74 fn new(dtype: DType, cfg: &Config, dev: &Device) -> Result<Self> {
75 let dim = cfg.hidden_size / cfg.num_attention_heads;
76 let max_seq_len = cfg.max_position_embeddings;
77 let inv_freq: Vec<_> = (0..dim)
78 .step_by(2)
79 .map(|i| 1f32 / cfg.rope_theta.powf(i as f64 / dim as f64) as f32)
80 .collect();
81 let inv_freq_len = inv_freq.len();
82 let inv_freq = Tensor::from_vec(inv_freq, (1, inv_freq_len), dev)?.to_dtype(dtype)?;
83 let t = Tensor::arange(0u32, max_seq_len as u32, dev)?
84 .to_dtype(dtype)?
85 .reshape((max_seq_len, 1))?;
86 let freqs = t.matmul(&inv_freq)?;
87 Ok(Self {
88 sin: freqs.sin()?,
89 cos: freqs.cos()?,
90 })
91 }
92
93 fn apply_rotary_emb_qkv(
94 &self,
95 q: &Tensor,
96 k: &Tensor,
97 seqlen_offset: usize,
98 ) -> Result<(Tensor, Tensor)> {
99 let (_b_sz, _h, seq_len, _n_embd) = q.dims4()?;
100 let (cos, sin) = ROPE_SLICE_CACHE.with(|c| -> Result<(Tensor, Tensor)> {
101 let mut c = c.borrow_mut();
102 if let Some((off, len, cos, sin)) = c.as_ref() {
103 if *off == seqlen_offset && *len == seq_len {
104 return Ok((cos.clone(), sin.clone()));
105 }
106 }
107 let cos = self.cos.narrow(0, seqlen_offset, seq_len)?;
108 let sin = self.sin.narrow(0, seqlen_offset, seq_len)?;
109 *c = Some((seqlen_offset, seq_len, cos.clone(), sin.clone()));
110 Ok((cos, sin))
111 })?;
112 if std::env::var("COCO_NO_FUSE_ROPE").is_err()
113 && matches!(q.device(), Device::Metal(_))
114 && q.dtype() == DType::BF16
115 {
116 let q_embed = rope_apply(q, &cos, &sin)?;
117 let k_embed = rope_apply(k, &cos, &sin)?;
118 return Ok((q_embed, k_embed));
119 }
120 let q_embed = candle_nn::rotary_emb::rope(&q.contiguous()?, &cos, &sin)?;
121 let k_embed = candle_nn::rotary_emb::rope(&k.contiguous()?, &cos, &sin)?;
122 Ok((q_embed, k_embed))
123 }
124}
125
126struct MLP {
127 gate_up: QGroup,
128 down_proj: Proj,
129 act_fn: Activation,
130}
131
132impl MLP {
133 fn new(src: &mut WeightSource, prefix: &str, cfg: &Config) -> Result<Self> {
134 Ok(Self {
135 gate_up: src.quant_group(&[
136 (&format!("{prefix}.gate_proj"), false),
137 (&format!("{prefix}.up_proj"), false),
138 ])?,
139 down_proj: src.proj(&format!("{prefix}.down_proj"), false)?,
140 act_fn: cfg.hidden_act,
141 })
142 }
143
144 fn forward(&self, xs: &Tensor, resid: Option<&Tensor>) -> Result<Tensor> {
145 if let Proj::Quant(down) = &self.down_proj {
146 if let Some(out) = self.gate_up.forward_ffn_mega(xs, down)? {
147 return match resid {
148 Some(r) => Ok((out + r)?),
149 None => Ok(out),
150 };
151 }
152 }
153 let fuse = std::env::var("COCO_FUSE_SWIGLU").as_deref() != Ok("0");
154 if fuse {
155 if let Some(act) = self.gate_up.forward_swiglu(xs)? {
156 return match resid {
157 Some(r) => self.down_proj.forward_resid(&act, r),
158 None => self.down_proj.forward(&act),
159 };
160 }
161 }
162 let mut gu = self.gate_up.forward(xs)?;
163 let rhs = gu.pop().unwrap();
164 let lhs = gu.pop().unwrap().apply(&self.act_fn)?;
165 let act = (lhs * rhs)?;
166 match resid {
167 Some(r) => self.down_proj.forward_resid(&act, r),
168 None => self.down_proj.forward(&act),
169 }
170 }
171}
172
173struct Attention {
174 qkv: QGroup,
175 o_proj: Proj,
176 num_heads: usize,
177 num_kv_heads: usize,
178 num_kv_groups: usize,
179 head_dim: usize,
180 hidden_size: usize,
181 rotary_emb: Arc<RotaryEmbedding>,
182 kv_cache: Option<(Tensor, Tensor)>,
183 kv_fast: Option<KvCache>,
184 fused: bool,
185}
186
187impl Attention {
188 fn new(
189 src: &mut WeightSource,
190 prefix: &str,
191 rotary_emb: Arc<RotaryEmbedding>,
192 cfg: &Config,
193 ) -> Result<Self> {
194 let hidden_sz = cfg.hidden_size;
195 let num_heads = cfg.num_attention_heads;
196 let num_kv_heads = cfg.num_key_value_heads;
197 let num_kv_groups = num_heads / num_kv_heads;
198 let head_dim = hidden_sz / num_heads;
199 Ok(Self {
200 qkv: src.quant_group(&[
201 (&format!("{prefix}.q_proj"), true),
202 (&format!("{prefix}.k_proj"), true),
203 (&format!("{prefix}.v_proj"), true),
204 ])?,
205 o_proj: src.proj(&format!("{prefix}.o_proj"), false)?,
206 num_heads,
207 num_kv_heads,
208 num_kv_groups,
209 head_dim,
210 hidden_size: hidden_sz,
211 rotary_emb,
212 kv_cache: None,
213 kv_fast: None,
214 fused: fused_attn_enabled(),
215 })
216 }
217
218 fn forward(
219 &mut self,
220 xs: &Tensor,
221 attention_mask: Option<&Tensor>,
222 seqlen_offset: usize,
223 resid: Option<&Tensor>,
224 ) -> Result<Tensor> {
225 let (b_sz, q_len, _) = xs.dims3()?;
226
227 let mut qkv = self.qkv.forward(xs)?;
228 let value_states = qkv.pop().unwrap();
229 let key_states = qkv.pop().unwrap();
230 let query_states = qkv.pop().unwrap();
231
232 let query_states = query_states
233 .reshape((b_sz, q_len, self.num_heads, self.head_dim))?
234 .transpose(1, 2)?;
235 let key_states = key_states
236 .reshape((b_sz, q_len, self.num_kv_heads, self.head_dim))?
237 .transpose(1, 2)?;
238 let value_states = value_states
239 .reshape((b_sz, q_len, self.num_kv_heads, self.head_dim))?
240 .transpose(1, 2)?;
241
242 let (query_states, key_states) =
243 self.rotary_emb
244 .apply_rotary_emb_qkv(&query_states, &key_states, seqlen_offset)?;
245
246 if self.fused && b_sz == 1 {
247 if self.kv_fast.is_none() {
248 self.kv_fast = Some(KvCache::new(
249 self.num_heads,
250 self.num_kv_heads,
251 self.head_dim,
252 fused_max_ctx(),
253 query_states.device(),
254 )?);
255 }
256 let k_f = key_states.squeeze(0)?.contiguous()?;
257 let v_f = value_states.squeeze(0)?.contiguous()?;
258
259 if q_len == 1 {
260 let ctx_now = self.kv_fast.as_ref().unwrap().len();
261 let k1 = k_f.squeeze(1)?;
262 let v1 = v_f.squeeze(1)?;
263 if ctx_now >= fused_min_ctx() {
264 let kc = self.kv_fast.as_mut().unwrap();
265 let q_f = query_states.squeeze(0)?.squeeze(1)?.contiguous()?;
266 let attn = kc.decode(&q_f, &k1, &v1)?;
267 let attn = attn.to_dtype(xs.dtype())?;
268 return match resid {
269 Some(r) => self.o_proj.forward_resid(&attn, r),
270 None => self.o_proj.forward(&attn),
271 };
272 } else {
273 self.kv_fast
274 .as_mut()
275 .unwrap()
276 .append_prefill(&k1.unsqueeze(1)?, &v1.unsqueeze(1)?)?;
277 return self.candle_attention(
278 &query_states,
279 &key_states,
280 &value_states,
281 attention_mask,
282 b_sz,
283 q_len,
284 resid,
285 );
286 }
287 } else {
288 self.kv_fast.as_mut().unwrap().append_prefill(&k_f, &v_f)?;
289 return self.candle_attention(
290 &query_states,
291 &key_states,
292 &value_states,
293 attention_mask,
294 b_sz,
295 q_len,
296 resid,
297 );
298 }
299 }
300
301 self.candle_attention(
302 &query_states,
303 &key_states,
304 &value_states,
305 attention_mask,
306 b_sz,
307 q_len,
308 resid,
309 )
310 }
311
312 #[allow(clippy::too_many_arguments)]
313 fn candle_attention(
314 &mut self,
315 query_states: &Tensor,
316 key_states: &Tensor,
317 value_states: &Tensor,
318 attention_mask: Option<&Tensor>,
319 b_sz: usize,
320 q_len: usize,
321 resid: Option<&Tensor>,
322 ) -> Result<Tensor> {
323 let (key_states, value_states) = match &self.kv_cache {
324 None => (key_states.clone(), value_states.clone()),
325 Some((prev_k, prev_v)) => {
326 let key_states = Tensor::cat(&[prev_k, key_states], 2)?;
327 let value_states = Tensor::cat(&[prev_v, value_states], 2)?;
328 (key_states, value_states)
329 }
330 };
331 self.kv_cache = Some((key_states.clone(), value_states.clone()));
332
333 let key_states =
334 candle_transformers::utils::repeat_kv(key_states, self.num_kv_groups)?.contiguous()?;
335 let value_states =
336 candle_transformers::utils::repeat_kv(value_states, self.num_kv_groups)?.contiguous()?;
337
338 let attn_output = {
339 let scale = 1f64 / f64::sqrt(self.head_dim as f64);
340 let attn_weights = (query_states.matmul(&key_states.transpose(2, 3)?)? * scale)?;
341
342 let attn_weights = match attention_mask {
343 None => attn_weights,
344 Some(mask) => attn_weights.broadcast_add(mask)?,
345 };
346 let attn_weights = candle_nn::ops::softmax_last_dim(&attn_weights)?;
347 attn_weights.matmul(&value_states)?
348 };
349 let attn_output = attn_output
350 .transpose(1, 2)?
351 .reshape((b_sz, q_len, self.hidden_size))?;
352 match resid {
353 Some(r) => self.o_proj.forward_resid(&attn_output, r),
354 None => self.o_proj.forward(&attn_output),
355 }
356 }
357
358 fn clear_kv_cache(&mut self) {
359 self.kv_cache = None;
360 if let Some(kc) = self.kv_fast.as_mut() {
361 kc.clear();
362 }
363 }
364}
365
366struct DecoderLayer {
367 self_attn: Attention,
368 mlp: MLP,
369 input_layernorm: RmsNormFused,
370 post_attention_layernorm: RmsNormFused,
371}
372
373impl DecoderLayer {
374 fn new(
375 src: &mut WeightSource,
376 idx: usize,
377 rotary_emb: Arc<RotaryEmbedding>,
378 cfg: &Config,
379 norm_vb: &VarBuilder,
380 ) -> Result<Self> {
381 let prefix = format!("model.layers.{idx}");
382 let self_attn = Attention::new(src, &format!("{prefix}.self_attn"), rotary_emb, cfg)?;
383 let mlp = MLP::new(src, &format!("{prefix}.mlp"), cfg)?;
384 let input_layernorm = RmsNormFused::new(
385 norm_vb
386 .pp(format!("model.layers.{idx}.input_layernorm"))
387 .get(cfg.hidden_size, "weight")?,
388 cfg.rms_norm_eps,
389 )?;
390 let post_attention_layernorm = RmsNormFused::new(
391 norm_vb
392 .pp(format!("model.layers.{idx}.post_attention_layernorm"))
393 .get(cfg.hidden_size, "weight")?,
394 cfg.rms_norm_eps,
395 )?;
396 Ok(Self {
397 self_attn,
398 mlp,
399 input_layernorm,
400 post_attention_layernorm,
401 })
402 }
403
404 fn forward(
405 &mut self,
406 xs: &Tensor,
407 attention_mask: Option<&Tensor>,
408 seqlen_offset: usize,
409 ) -> Result<Tensor> {
410 let residual = xs;
411 let xs = self.input_layernorm.forward(xs)?;
412 if fuse_resid_enabled() {
413 let h = self
414 .self_attn
415 .forward(&xs, attention_mask, seqlen_offset, Some(residual))?;
416 let normed = self.post_attention_layernorm.forward(&h)?;
417 return self.mlp.forward(&normed, Some(&h));
418 }
419 let attn_out = self
420 .self_attn
421 .forward(&xs, attention_mask, seqlen_offset, None)?;
422 let (h, normed) = self.post_attention_layernorm.forward_add(residual, &attn_out)?;
423 let xs2 = self.mlp.forward(&normed, None)?;
424 Ok((&h + xs2)?)
425 }
426
427 fn clear_kv_cache(&mut self) {
428 self.self_attn.clear_kv_cache()
429 }
430}
431
432pub struct Model {
433 embed_tokens: candle_nn::Embedding,
434 layers: Vec<DecoderLayer>,
435 norm: RmsNormFused,
436 lm_head: Proj,
437 sliding_window: usize,
438 device: Device,
439 dtype: DType,
440}
441
442impl Model {
443 pub fn new(cfg: &Config, mut src: WeightSource, vb: VarBuilder) -> Result<(Self, WeightStats)> {
444 let device = src.device.clone();
445 let dtype = src.dtype;
446 let vb_m = vb.pp("model");
447 let embed_tokens =
448 candle_nn::embedding(cfg.vocab_size, cfg.hidden_size, vb_m.pp("embed_tokens"))?;
449 let rotary_emb = Arc::new(RotaryEmbedding::new(dtype, cfg, &device)?);
450 let mut layers = Vec::with_capacity(cfg.num_hidden_layers);
451 for idx in 0..cfg.num_hidden_layers {
452 layers.push(DecoderLayer::new(&mut src, idx, rotary_emb.clone(), cfg, &vb)?);
453 }
454 let norm = RmsNormFused::new(
455 vb_m.pp("norm").get(cfg.hidden_size, "weight")?,
456 cfg.rms_norm_eps,
457 )?;
458
459 let head_separate = vb.contains_tensor("lm_head.weight");
460 let quant_head = matches!(std::env::var("COCO_QUANT_HEAD").as_deref(), Ok(v) if v != "0");
461 let lm_head = if !head_separate {
462 if quant_head {
463 eprintln!(
464 "COCO_QUANT_HEAD set but this model TIES lm_head to the embeddings \
465 (no separate lm_head.weight) — keeping the head fp16 to avoid \
466 double-quantizing the shared embedding matrix."
467 );
468 }
469 Proj::Dense(candle_nn::Linear::new(embed_tokens.embeddings().clone(), None))
470 } else if quant_head {
471 if matches!(std::env::var("COCO_QUANT_HEAD").as_deref(), Ok("8")) {
472 eprintln!(
473 "COCO_QUANT_HEAD=8 requested but the qmatvec kernel is 3-bit (8-level) \
474 only — a Q8 head is not wired; using the standard turboquant 3-bit head."
475 );
476 }
477 let w = vb
478 .get((cfg.vocab_size, cfg.hidden_size), "lm_head.weight")?
479 .to_dtype(DType::F32)?
480 .flatten_all()?
481 .to_vec1::<f32>()?;
482 let q = encode(&w, cfg.vocab_size, cfg.hidden_size, &src.cfg, &LLOYD_MAX_3BIT);
483 drop(w);
484 let qw = QWeight::from_tq(&q, None, &device)?;
485 src.total_compressed_bytes += qw.compressed_bytes;
486 src.total_fp16_bytes += cfg.vocab_size * cfg.hidden_size * 2;
487 src.n_quant += 1;
488 eprintln!(
489 "COCO_QUANT_HEAD: lm_head compressed {:.1} MB fp16 -> {:.1} MB (3-bit)",
490 (cfg.vocab_size * cfg.hidden_size * 2) as f64 / (1024.0 * 1024.0),
491 qw.compressed_bytes as f64 / (1024.0 * 1024.0),
492 );
493 Proj::Quant(qw)
494 } else {
495 Proj::Dense(candle_nn::linear_no_bias(
496 cfg.hidden_size,
497 cfg.vocab_size,
498 vb.pp("lm_head"),
499 )?)
500 };
501
502 let stats = src.stats();
503 Ok((
504 Self {
505 embed_tokens,
506 layers,
507 norm,
508 lm_head,
509 sliding_window: cfg.sliding_window,
510 device,
511 dtype,
512 },
513 stats,
514 ))
515 }
516
517 fn prepare_causal_attention_mask(
518 &self,
519 b_size: usize,
520 tgt_len: usize,
521 seqlen_offset: usize,
522 ) -> Result<Tensor> {
523 let mask: Vec<_> = (0..tgt_len)
524 .flat_map(|i| {
525 (0..tgt_len).map(move |j| {
526 if i < j || j + self.sliding_window < i {
527 f32::NEG_INFINITY
528 } else {
529 0.
530 }
531 })
532 })
533 .collect();
534 let mask = Tensor::from_slice(&mask, (tgt_len, tgt_len), &self.device)?;
535 let mask = if seqlen_offset > 0 {
536 let mask0 = Tensor::zeros((tgt_len, seqlen_offset), DType::F32, &self.device)?;
537 Tensor::cat(&[&mask0, &mask], D::Minus1)?
538 } else {
539 mask
540 };
541 Ok(mask
542 .expand((b_size, 1, tgt_len, tgt_len + seqlen_offset))?
543 .to_dtype(self.dtype)?)
544 }
545
546 pub fn forward(&mut self, input_ids: &Tensor, seqlen_offset: usize) -> Result<Tensor> {
547 let (b_size, seq_len) = input_ids.dims2()?;
548 let attention_mask: Option<Tensor> = if seq_len <= 1 {
549 None
550 } else {
551 Some(self.prepare_causal_attention_mask(b_size, seq_len, seqlen_offset)?)
552 };
553 let profile = seq_len == 1 && std::env::var("COCO_PROFILE").is_ok();
554 let mut xs = self.embed_tokens.forward(input_ids)?;
555 if profile {
556 self.device.synchronize()?;
557 let t = std::time::Instant::now();
558 for layer in self.layers.iter_mut() {
559 xs = layer.forward(&xs, attention_mask.as_ref(), seqlen_offset)?;
560 }
561 self.device.synchronize()?;
562 let t_layers = t.elapsed().as_secs_f64();
563 let t = std::time::Instant::now();
564 let xn = xs.narrow(1, seq_len - 1, 1)?;
565 let xn = self.norm.forward(&xn)?;
566 let out = self.lm_head.forward(&xn)?;
567 self.device.synchronize()?;
568 let t_head = t.elapsed().as_secs_f64();
569 PROFILE_ACC.with(|a| {
570 let mut a = a.borrow_mut();
571 a.0 += t_layers;
572 a.1 += t_head;
573 a.2 += 1;
574 });
575 return Ok(out);
576 }
577 for layer in self.layers.iter_mut() {
578 xs = layer.forward(&xs, attention_mask.as_ref(), seqlen_offset)?;
579 }
580 let xs = xs.narrow(1, seq_len - 1, 1)?;
581 let xs = self.norm.forward(&xs)?;
582 self.lm_head.forward(&xs)
583 }
584
585 pub fn clear_kv_cache(&mut self) {
586 for layer in self.layers.iter_mut() {
587 layer.clear_kv_cache()
588 }
589 }
590}
591
592// The legacy inlined model also satisfies the shared `Model` contract so main.rs can
593// hold it in the SAME `Box<dyn Model>` as the registry path — the ONLY difference
594// between the two paths is which builder ran, gated by COCO_REGISTRY. The methods
595// forward verbatim to the inherent ones above (byte-identical behavior).
596impl crate::model::Model for Model {
597 fn forward(&mut self, ids: &Tensor, offset: usize) -> Result<Tensor> {
598 Model::forward(self, ids, offset)
599 }
600 fn clear_kv_cache(&mut self) {
601 Model::clear_kv_cache(self)
602 }
603}