Skip to main content

cortiq_engine/
glm5_next.rs

1//! Text-only GLM-5.3-Flash (`glm5_next`) runtime.
2//!
3//! GLM is not a conventional one-residual Transformer: every block is
4//! wrapped by four-stream mHC, while the mixer alternates recurrent KDA and
5//! NoPE MLA/DSA.  Keeping the stack here avoids silently flattening mHC in
6//! the generic pipeline.  Large matrices remain mmap-backed `QTensor`s and
7//! routed experts may use the same VRAM-sized dynamic cache as Qwen/DSV4.
8
9use crate::dsv4::{Dsv4Cfg, HcScratch, hc_block};
10use crate::linear_core::{KdaCfg, KdaOutGate, KdaWeights, kda_forward};
11use crate::loader::{Overlay, build_ffn_at, load_f32, load_matrix};
12use crate::pipeline::{Act, DenseFfn, FfnKind, MlaWeights, MoeFfn, moe_route_with_eps};
13use crate::pool::Pool;
14use crate::qtensor::QTensor;
15use cortiq_core::{CmfError, CmfModel, Glm5NextConfig, LayerType, ModelArch, TensorDtype};
16use std::cell::RefCell;
17use std::sync::Arc;
18use std::sync::atomic::{AtomicU64, Ordering};
19
20const INDEX_NORM_EPS: f64 = 1e-6;
21
22/// Sequence ids are process-unique.  Model uid alone is not enough because a
23/// Pipeline can reset and reuse the same mmap-backed model for many prompts.
24static NEXT_GLM_SEQUENCE: AtomicU64 = AtomicU64::new(1);
25
26fn next_glm_sequence() -> u64 {
27    NEXT_GLM_SEQUENCE.fetch_add(1, Ordering::Relaxed)
28}
29
30// A decode token visits many MoE layers, but only one layer at a time.  Keep
31// the intermediate gate/up rows on the caller thread and resize in place so
32// every token does not allocate one Vec per selected expert per layer.  The
33// pool joins the caller before this scratch is touched again.
34thread_local! {
35    static GLM_MOE_ACTS: RefCell<Vec<Vec<f32>>> = const { RefCell::new(Vec::new()) };
36}
37
38struct HcWeights {
39    function: Vec<f32>,
40    base: Vec<f32>,
41    scale: [f32; 3],
42}
43
44enum Mixer {
45    Kda(KdaWeights),
46    Dsa(DsaWeights),
47}
48
49struct DsaWeights {
50    mla: MlaWeights,
51    index_q: QTensor,
52    index_k: QTensor,
53    index_k_norm: Vec<f32>,
54    index_k_bias: Vec<f32>,
55    index_weights: QTensor,
56    pool_gate: QTensor,
57    pool_ape: Vec<f32>,
58    /// kv_b in f32 `[nh·(nope + v), lora]`, made on first use for the
59    /// absorbed attention (`dsa_absorbed`).
60    kvb_f32: std::sync::OnceLock<Vec<f32>>,
61}
62
63pub struct Layer {
64    attn_hc: HcWeights,
65    ffn_hc: HcWeights,
66    input_norm: Vec<f32>,
67    post_norm: Vec<f32>,
68    mixer: Mixer,
69    ffn: FfnKind,
70    expert_ids: Vec<(usize, usize, usize)>,
71    shared_ids: Option<(usize, usize, usize)>,
72}
73
74pub struct Globals {
75    embed: QTensor,
76    norm: Vec<f32>,
77    lm_head: QTensor,
78}
79
80#[derive(Clone)]
81pub struct Cfg {
82    hc: Dsv4Cfg,
83    kda: KdaCfg,
84    eps: f64,
85    swiglu_limit: f32,
86    index_n_heads: usize,
87    index_head_dim: usize,
88    index_topk: usize,
89    index_kpool: usize,
90    index_tail: bool,
91}
92
93enum MixerState {
94    Kda(Vec<f32>),
95    Dsa(DsaState),
96}
97
98#[derive(Default)]
99struct DsaState {
100    /// Token-major normalized MLA latent `[position, kv_lora_rank]`.
101    /// Keeping the compressed cache (rather than expanding every token to
102    /// all heads) is what makes a 1M-token context viable on 16 GB devices.
103    latents: Vec<f32>,
104    /// One normalized index key and one pool-gate vector per position.
105    index_keys: Vec<f32>,
106    pool_gates: Vec<f32>,
107}
108
109pub struct State {
110    hyper: Vec<f32>,
111    mixers: Vec<MixerState>,
112    gpu_pool: Option<crate::qwen4_exp::QwenGpuPool>,
113    /// Device state key.  Both values are stable for the life of this host
114    /// state and are replaced on every fresh sequence reset.
115    model_uid: u64,
116    sequence_id: u64,
117    gpu_ready: bool,
118    pub pos: usize,
119    /// The sequence runs on the card's whole-token graph (`graph_token`):
120    /// None not tried yet, Some(false) declined at its start (the host runs
121    /// it), Some(true) the card holds its states.
122    graph: Option<bool>,
123    /// The sequence's tokens while the card runs it: a later refusal (past
124    /// `index_topk`, where DSA stops being full attention) replays them on
125    /// the host.
126    tokens: Vec<u32>,
127}
128
129impl State {
130    /// The card's graph state key of this sequence (apart from the
131    /// pipelines' own ids).
132    fn kv_id(&self) -> u64 {
133        (1u64 << 62) | self.sequence_id
134    }
135}
136
137impl State {
138    fn reset(&mut self, layers: &[Layer], _cfg: &Cfg) {
139        crate::gpu::glm_sequence_abort(self.model_uid, self.sequence_id);
140        if self.graph == Some(true) {
141            crate::gpu::graph_kv_reset(self.kv_id());
142        }
143        self.graph = None;
144        self.tokens.clear();
145        self.sequence_id = next_glm_sequence();
146        self.gpu_ready = false;
147        self.hyper.clear();
148        self.pos = 0;
149        self.mixers = layers
150            .iter()
151            .map(|l| match l.mixer {
152                Mixer::Kda(_) => MixerState::Kda(Vec::new()),
153                Mixer::Dsa(_) => MixerState::Dsa(DsaState::default()),
154            })
155            .collect();
156    }
157
158    fn ensure_gpu_sequence(&mut self, layers: &[Layer], cfg: &Cfg, position: usize) {
159        // The native state allocator and focused kernels are deliberately
160        // opt-in until the complete multi-layer chain encoder is present.
161        // Keeping this seam inactive by default guarantees that a partial
162        // bring-up cannot consume VRAM or perturb the authoritative CPU/Metal
163        // output path.
164        if std::env::var_os("CMF_GLM_NATIVE_STATE").is_none() {
165            return;
166        }
167        if self.gpu_ready {
168            if !crate::gpu::glm_sequence_reserve(
169                self.model_uid,
170                self.sequence_id,
171                position.saturating_add(1),
172            ) {
173                crate::gpu::glm_sequence_abort(self.model_uid, self.sequence_id);
174                self.gpu_ready = false;
175            }
176            return;
177        }
178        let (mut dsa_rank, mut dsa_index) = (0usize, 0usize);
179        for layer in layers {
180            if let Mixer::Dsa(w) = &layer.mixer {
181                dsa_rank = dsa_rank.max(w.mla.lora);
182                dsa_index = dsa_index.max(
183                    w.index_q
184                        .rows()
185                        .checked_div(cfg.index_n_heads.max(1))
186                        .unwrap_or(w.index_q.rows()),
187                );
188            }
189        }
190        self.gpu_ready = crate::gpu::glm_sequence_prepare(
191            self.model_uid,
192            self.sequence_id,
193            layers.len(),
194            cfg.hc.dim,
195            cfg.hc.hc_mult,
196            cfg.kda.num_heads,
197            cfg.kda.head_k_dim,
198            cfg.kda.head_v_dim,
199            cfg.kda.conv_kernel,
200            dsa_rank,
201            dsa_index,
202            cfg.index_topk,
203            cfg.index_kpool,
204        );
205        if self.gpu_ready
206            && !crate::gpu::glm_sequence_reserve(
207                self.model_uid,
208                self.sequence_id,
209                position.saturating_add(1),
210            )
211        {
212            crate::gpu::glm_sequence_abort(self.model_uid, self.sequence_id);
213            self.gpu_ready = false;
214        }
215    }
216}
217
218impl Drop for State {
219    fn drop(&mut self) {
220        crate::gpu::glm_sequence_abort(self.model_uid, self.sequence_id);
221        if self.graph == Some(true) {
222            crate::gpu::graph_kv_reset(self.kv_id());
223        }
224    }
225}
226
227fn err(s: impl Into<String>) -> CmfError {
228    CmfError::Parse(format!("glm5_next: {}", s.into()))
229}
230
231fn f(model: &CmfModel, name: &str) -> Result<Vec<f32>, CmfError> {
232    load_f32(model, name, &Overlay::None).map_err(err)
233}
234
235fn t(model: &Arc<CmfModel>, name: &str) -> Result<QTensor, CmfError> {
236    load_matrix(model, name, false, &Overlay::None)
237}
238
239fn load_hc(model: &CmfModel, prefix: &str, kind: &str) -> Result<HcWeights, CmfError> {
240    let scale = f(model, &format!("{prefix}hc_{kind}_scale"))?;
241    if scale.len() != 3 {
242        return Err(err(format!(
243            "{prefix}hc_{kind}_scale has {} values, expected 3",
244            scale.len()
245        )));
246    }
247    Ok(HcWeights {
248        function: f(model, &format!("{prefix}hc_{kind}_fn"))?,
249        base: f(model, &format!("{prefix}hc_{kind}_base"))?,
250        scale: [scale[0], scale[1], scale[2]],
251    })
252}
253
254fn load_kda(
255    model: &Arc<CmfModel>,
256    prefix: &str,
257    lower: Option<f32>,
258) -> Result<KdaWeights, CmfError> {
259    let p = format!("{prefix}kda_attn.");
260    Ok(KdaWeights {
261        q_proj: t(model, &format!("{p}q_proj.weight"))?,
262        k_proj: t(model, &format!("{p}k_proj.weight"))?,
263        v_proj: t(model, &format!("{p}v_proj.weight"))?,
264        conv_q: f(model, &format!("{p}q_conv1d.weight"))?,
265        conv_k: f(model, &format!("{p}k_conv1d.weight"))?,
266        conv_v: f(model, &format!("{p}v_conv1d.weight"))?,
267        f_a: t(model, &format!("{p}f_a_proj.weight"))?,
268        f_b: t(model, &format!("{p}f_b_proj.weight"))?,
269        dt_bias: f(model, &format!("{p}dt_bias"))?,
270        a_log: f(model, &format!("{p}A_log"))?,
271        b_proj: t(model, &format!("{p}b_proj.weight"))?,
272        gate: KdaOutGate::LowRank(
273            t(model, &format!("{p}g_a_proj.weight"))?,
274            t(model, &format!("{p}g_b_proj.weight"))?,
275        ),
276        o_norm: f(model, &format!("{p}o_norm.weight"))?,
277        o_proj: t(model, &format!("{p}o_proj.weight"))?,
278        gate_lower_bound: lower,
279    })
280}
281
282fn load_dsa(model: &Arc<CmfModel>, arch: &ModelArch, prefix: &str) -> Result<DsaWeights, CmfError> {
283    let m = arch
284        .mla
285        .as_ref()
286        .ok_or_else(|| err("missing MLA descriptor"))?;
287    let p = format!("{prefix}self_attn.");
288    let q_proj = t(model, &format!("{p}q_b_proj.weight"))?;
289    let hd = m.qk_rope_head_dim + m.qk_nope_head_dim;
290    let nh = q_proj.rows() / hd.max(1);
291    let mla = MlaWeights {
292        q_proj,
293        q_a: Some(t(model, &format!("{p}q_a_proj.weight"))?),
294        q_a_norm: Some(f(model, &format!("{p}q_a_layernorm.weight"))?),
295        kv_a: t(model, &format!("{p}kv_a_proj_with_mqa.weight"))?,
296        kv_a_norm: f(model, &format!("{p}kv_a_layernorm.weight"))?,
297        kv_b: t(model, &format!("{p}kv_b_proj.weight"))?,
298        o_proj: t(model, &format!("{p}o_proj.weight"))?,
299        nh,
300        qk_rope: m.qk_rope_head_dim,
301        qk_nope: m.qk_nope_head_dim,
302        v_dim: m.v_head_dim,
303        lora: m.kv_lora_rank,
304        scale: (hd as f32).sqrt().recip(),
305        nope: true,
306    };
307    let ix = format!("{p}indexer.");
308    Ok(DsaWeights {
309        mla,
310        index_q: t(model, &format!("{ix}wq_b.weight"))?,
311        index_k: t(model, &format!("{ix}wk.weight"))?,
312        index_k_norm: f(model, &format!("{ix}k_norm.weight"))?,
313        index_k_bias: f(model, &format!("{ix}k_norm.bias"))?,
314        index_weights: t(model, &format!("{ix}weights_proj.weight"))?,
315        pool_gate: t(model, &format!("{ix}index_kpool_compress_gate"))?,
316        pool_ape: f(model, &format!("{ix}index_kpool_compress_ape"))?,
317        kvb_f32: std::sync::OnceLock::new(),
318    })
319}
320
321fn expert_ids(m: &MoeFfn) -> Result<Vec<(usize, usize, usize)>, CmfError> {
322    m.experts
323        .iter()
324        .enumerate()
325        .map(|(e, d)| {
326            let gate = d
327                .gate_proj
328                .model_idx()
329                .ok_or_else(|| err(format!("expert {e} gate is not mmap-backed")))?;
330            let up = d
331                .up_proj
332                .model_idx()
333                .ok_or_else(|| err(format!("expert {e} up is not mmap-backed")))?;
334            let down = d
335                .down_proj
336                .model_idx()
337                .ok_or_else(|| err(format!("expert {e} down is not mmap-backed")))?;
338            Ok((gate, up, down))
339        })
340        .collect()
341}
342
343fn shared_ids(m: &MoeFfn) -> Option<(usize, usize, usize)> {
344    let (d, _) = m.shared.as_ref()?;
345    Some((
346        d.gate_proj.model_idx()?,
347        d.up_proj.model_idx()?,
348        d.down_proj.model_idx()?,
349    ))
350}
351
352fn layer_norm(x: &mut [f32], weight: &[f32], bias: &[f32], eps: f64) {
353    let mean = x.iter().map(|&v| v as f64).sum::<f64>() / x.len().max(1) as f64;
354    let var = x
355        .iter()
356        .map(|&v| {
357            let d = v as f64 - mean;
358            d * d
359        })
360        .sum::<f64>()
361        / x.len().max(1) as f64;
362    let inv = (var + eps).sqrt().recip() as f32;
363    for i in 0..x.len() {
364        x[i] = (x[i] - mean as f32) * inv * weight[i] + bias[i];
365    }
366}
367
368/// Deterministic DSA pool selection shared by the host fallback and the
369/// native selector oracle.  `torch.topk`'s score order is retained, with the
370/// pool index as a stable tie-break; the visible incomplete tail is appended
371/// after the selected complete pools.
372fn dsa_select_positions(
373    mut scored: Vec<(usize, f32)>,
374    npos: usize,
375    kpool: usize,
376    topk: usize,
377    include_tail: bool,
378) -> Vec<usize> {
379    let keep = (topk / kpool).min(scored.len());
380    // A total score/index order is required here.  `select_nth_unstable_by`
381    // is allowed to choose any member of an equal-score partition, which
382    // made a tied pool edge diverge from torch.topk and from the device
383    // selector even though the final sort had a tie-breaker.
384    scored.sort_unstable_by(|(pa, sa), (pb, sb)| {
385        sb.partial_cmp(sa)
386            .unwrap_or(std::cmp::Ordering::Equal)
387            .then(pa.cmp(pb))
388    });
389    scored.truncate(keep);
390    let mut selected = Vec::with_capacity(keep * kpool + kpool.saturating_sub(1));
391    for (pi, _) in scored {
392        selected.extend(pi * kpool..(pi + 1) * kpool);
393    }
394    if include_tail {
395        let tail = (npos / kpool) * kpool;
396        selected.extend(tail..npos);
397    }
398    selected
399}
400
401/// Exact single-token GLM DSA. The learned indexer compresses complete
402/// k-pools, selects `index_topk / kpool` pools and always carries the visible
403/// incomplete tail. At <= index_topk positions this reduces to full causal
404/// attention, while longer contexts stay bounded at the trained 2048 tokens.
405fn dsa_forward(
406    x: &[f32],
407    w: &DsaWeights,
408    cfg: &Cfg,
409    st: &mut DsaState,
410    pool: Option<&Pool>,
411) -> Vec<f32> {
412    let m = &w.mla;
413    let (nh, hd, dv, lora) = (m.nh, m.qk_rope + m.qk_nope, m.v_dim, m.lora);
414
415    let qa = m.q_a.as_ref().expect("GLM DSA always has q_a");
416    let mut q_resid = vec![0.0f32; qa.rows()];
417    qa.matvec(x, &mut q_resid, pool);
418    q_resid = crate::inference::rms_norm(
419        &q_resid,
420        m.q_a_norm.as_ref().expect("GLM DSA q_a norm"),
421        cfg.eps,
422        cortiq_core::NormStyle::Qwen,
423    );
424    let id = cfg.index_head_dim;
425    let ih = cfg.index_n_heads;
426    // These projections share their respective activations.  The Q4TP
427    // matvec-many kernel keeps each pair under one pool dispatch while
428    // retaining the same per-row arithmetic and output buffers.  Q2TP's
429    // mixed projection geometry is deliberately left on the established
430    // separate path: its specialized tiled kernels are faster than the
431    // generic batched fallback on the exact release checkpoint.
432    let mut q = vec![0.0f32; nh * hd];
433    let mut iq = vec![0.0f32; ih * id];
434    let q4_fused = |a: &QTensor, b: &QTensor| {
435        matches!(
436            (a, b),
437            (
438                QTensor::Mapped {
439                    dtype: TensorDtype::Q4TiledP,
440                    ..
441                },
442                QTensor::Mapped {
443                    dtype: TensorDtype::Q4TiledP,
444                    ..
445                }
446            )
447        )
448    };
449    if q4_fused(&m.q_proj, &w.index_q) {
450        QTensor::matvec_many([&m.q_proj, &w.index_q], &q_resid, [&mut q, &mut iq], pool);
451    } else {
452        m.q_proj.matvec(&q_resid, &mut q, pool);
453        w.index_q.matvec(&q_resid, &mut iq, pool);
454    }
455
456    let mut compressed = vec![0.0f32; lora + m.qk_rope];
457    let mut ik = vec![0.0f32; id];
458    let mut gate = vec![0.0f32; id];
459    let mut head_weights = vec![0.0f32; ih];
460    if q4_fused(&m.kv_a, &w.index_k)
461        && q4_fused(&m.kv_a, &w.pool_gate)
462        && q4_fused(&m.kv_a, &w.index_weights)
463    {
464        QTensor::matvec_many(
465            [&m.kv_a, &w.index_k, &w.pool_gate, &w.index_weights],
466            x,
467            [&mut compressed, &mut ik, &mut gate, &mut head_weights],
468            pool,
469        );
470    } else {
471        m.kv_a.matvec(x, &mut compressed, pool);
472        w.index_k.matvec(x, &mut ik, pool);
473        w.pool_gate.matvec(x, &mut gate, pool);
474        w.index_weights.matvec(x, &mut head_weights, pool);
475    }
476    let latent = crate::inference::rms_norm(
477        &compressed[..lora],
478        &m.kv_a_norm,
479        cfg.eps,
480        cortiq_core::NormStyle::Qwen,
481    );
482    st.latents.extend_from_slice(&latent);
483    // qk_rope is validated as zero for GLM-5.3; retain the generic geometry
484    // assertion so a future rotary checkpoint fails loudly.
485    debug_assert_eq!(m.qk_rope, 0);
486
487    layer_norm(
488        &mut ik,
489        &w.index_k_norm,
490        &w.index_k_bias,
491        // The indexer's LayerNorm is deliberately fixed at 1e-6 in the
492        // reference, independent of the text RMSNorm epsilon (1e-5 in the
493        // release config).  Reusing cfg.eps subtly changes every pool score.
494        INDEX_NORM_EPS,
495    );
496    st.index_keys.extend_from_slice(&ik);
497    st.pool_gates.extend_from_slice(&gate);
498
499    let npos = st.index_keys.len() / id;
500    let kp = cfg.index_kpool;
501    let complete = npos / kp;
502    let hscale = (ih as f32).sqrt().recip();
503    for v in &mut head_weights {
504        *v *= hscale;
505    }
506    let iscale = (id as f32).sqrt().recip();
507    let mut scored = Vec::with_capacity(complete);
508    let mut pooled = vec![0.0f32; id];
509    for pi in 0..complete {
510        for d in 0..id {
511            let mut mx = f32::NEG_INFINITY;
512            for t0 in 0..kp {
513                let pos = pi * kp + t0;
514                mx = mx.max(st.pool_gates[pos * id + d] + w.pool_ape[t0 * id + d]);
515            }
516            let mut z = 0.0f32;
517            let mut v = 0.0f32;
518            for t0 in 0..kp {
519                let pos = pi * kp + t0;
520                let p = (st.pool_gates[pos * id + d] + w.pool_ape[t0 * id + d] - mx).exp();
521                z += p;
522                v += p * st.index_keys[pos * id + d];
523            }
524            pooled[d] = v / z.max(f32::MIN_POSITIVE);
525        }
526        let mut score = 0.0f32;
527        for h in 0..ih {
528            let dot = iq[h * id..(h + 1) * id]
529                .iter()
530                .zip(&pooled)
531                .map(|(&a, &b)| a * b)
532                .sum::<f32>()
533                * iscale;
534            score += head_weights[h] * dot.max(0.0);
535        }
536        scored.push((pi, score));
537    }
538    // `torch.topk` returns the selected pools in score order.  Keep that
539    // order (with a deterministic pool-index tie break) so the subsequent
540    // f32 softmax/reduction follows the reference accumulation order.
541    let selected = dsa_select_positions(scored, npos, kp, cfg.index_topk, cfg.index_tail);
542    if dsa_absorb_on() && !selected.is_empty() {
543        let merged = dsa_absorbed(&q, w, st, &selected, pool);
544        let mut out = vec![0.0f32; cfg.hc.dim];
545        m.o_proj.matvec(&merged, &mut out, pool);
546        return out;
547    }
548    // Expand only the selected latents.  The old implementation kept an
549    // `[position, head, qk+v]` cache, which is ~128 KiB/token and exhausted
550    // host memory long before GLM's trained 1M context.  A single matmat
551    // streams the same kv_b rows once for the bounded selection (≤2048).
552    let mut selected_latent = Vec::with_capacity(selected.len() * lora);
553    for &pos in &selected {
554        selected_latent.extend_from_slice(&st.latents[pos * lora..(pos + 1) * lora]);
555    }
556    let kv_width = nh * (m.qk_nope + dv);
557    let mut selected_kv = vec![0.0f32; selected.len() * kv_width];
558    if !selected.is_empty() {
559        m.kv_b
560            .matmat(&selected_latent, selected.len(), &mut selected_kv, pool);
561    }
562
563    let mut merged = vec![0.0f32; nh * dv];
564    for h in 0..nh {
565        let qh = &q[h * hd..(h + 1) * hd];
566        let mut scores = Vec::with_capacity(selected.len());
567        let mut mx = f32::NEG_INFINITY;
568        for (si, &_pos) in selected.iter().enumerate() {
569            let off = si * kv_width + h * (m.qk_nope + dv);
570            let s = qh
571                .iter()
572                .zip(&selected_kv[off..off + m.qk_nope])
573                .map(|(&a, &b)| a * b)
574                .sum::<f32>()
575                * m.scale;
576            mx = mx.max(s);
577            scores.push(s);
578        }
579        let z = scores.iter().map(|&s| (s - mx).exp()).sum::<f32>();
580        let out = &mut merged[h * dv..(h + 1) * dv];
581        for (si, &s) in scores.iter().enumerate() {
582            let p = (s - mx).exp() / z.max(f32::MIN_POSITIVE);
583            let off = si * kv_width + h * (m.qk_nope + dv) + m.qk_nope;
584            for d in 0..dv {
585                out[d] += p * selected_kv[off + d];
586            }
587        }
588    }
589    let mut out = vec![0.0f32; cfg.hc.dim];
590    m.o_proj.matvec(&merged, &mut out, pool);
591    out
592}
593
594/// `CMF_GLM_DSA_ABSORB=0`: the selected latents expanded through kv_b every
595/// token (the reference's order) instead of the absorbed form.
596fn dsa_absorb_on() -> bool {
597    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
598    *ON.get_or_init(|| std::env::var("CMF_GLM_DSA_ABSORB").as_deref() != Ok("0"))
599}
600
601/// DSA's attention with kv_b absorbed (MLA's inference form): per head the
602/// query goes through K's half of kv_b once (`q' = W_káµ€ q`, lora wide), the
603/// scores are `q' · latent` over the selected positions, the latents' softmax
604/// mix goes through V's half. Exactly the expanded product up to f32
605/// rounding, at ~nh·lora·(nope + v + 2·n) multiply-adds instead of
606/// n·nh·(nope + v)·lora — at 512 positions 50 M instead of 8.6 G a layer.
607fn dsa_absorbed(q: &[f32], w: &DsaWeights, st: &DsaState, selected: &[usize], pool: Option<&Pool>) -> Vec<f32> {
608    let m = &w.mla;
609    let (nh, hd, nope, dv, lora) = (m.nh, m.qk_rope + m.qk_nope, m.qk_nope, m.v_dim, m.lora);
610    let stride = nope + dv;
611    let wkv = w.kvb_f32.get_or_init(|| {
612        let rows = m.kv_b.rows();
613        let mut v = vec![0.0f32; rows * lora];
614        for (r, row) in v.chunks_exact_mut(lora).enumerate() {
615            m.kv_b.row_f32(r, row);
616        }
617        v
618    });
619    let mut merged = vec![0.0f32; nh * dv];
620    let ptr = crate::audiovae::SendPtr(merged.as_mut_ptr());
621    let head = |h: usize| {
622        let qh = &q[h * hd + m.qk_rope..h * hd + m.qk_rope + nope];
623        let wk = &wkv[h * stride * lora..(h * stride + nope) * lora];
624        let wv = &wkv[(h * stride + nope) * lora..(h + 1) * stride * lora];
625        let mut qp = vec![0.0f32; lora];
626        for (d, &qd) in qh.iter().enumerate() {
627            for (a, &b) in qp.iter_mut().zip(&wk[d * lora..(d + 1) * lora]) {
628                *a += qd * b;
629            }
630        }
631        let mut scores: Vec<f32> = selected
632            .iter()
633            .map(|&pos| qp.iter().zip(&st.latents[pos * lora..(pos + 1) * lora]).map(|(&a, &b)| a * b).sum::<f32>() * m.scale)
634            .collect();
635        let mx = scores.iter().copied().fold(f32::NEG_INFINITY, f32::max);
636        let mut z = 0.0f32;
637        for s in &mut scores {
638            *s = (*s - mx).exp();
639            z += *s;
640        }
641        let z = z.max(f32::MIN_POSITIVE);
642        let mut mix = vec![0.0f32; lora];
643        for (&p, &pos) in scores.iter().zip(selected) {
644            let p = p / z;
645            for (a, &b) in mix.iter_mut().zip(&st.latents[pos * lora..(pos + 1) * lora]) {
646                *a += p * b;
647            }
648        }
649        // SAFETY: each head writes its own dv-wide slice.
650        let out = unsafe { ptr.row(h * dv, dv) };
651        for (d, o) in out.iter_mut().enumerate() {
652            *o = wv[d * lora..(d + 1) * lora].iter().zip(&mix).map(|(&a, &b)| a * b).sum();
653        }
654    };
655    match pool {
656        Some(p) => p.run_rows(nh, &|lo, hi| (lo..hi).for_each(&head)),
657        None => (0..nh).for_each(head),
658    }
659    merged
660}
661
662/// Load the exact GLM text stack. The vision tower is intentionally omitted
663/// by the converter; image/video tokens are therefore not accepted by CMF.
664pub fn load(
665    model: &Arc<CmfModel>,
666    arch: &ModelArch,
667) -> Result<(Globals, Vec<Layer>, Cfg, State), CmfError> {
668    let gc: &Glm5NextConfig = arch
669        .glm5_next
670        .as_ref()
671        .ok_or_else(|| err("missing glm5_next descriptor"))?;
672    if arch.layer_types.len() != arch.num_layers {
673        return Err(err(format!(
674            "layer schedule has {} entries, expected {}",
675            arch.layer_types.len(),
676            arch.num_layers
677        )));
678    }
679    let mla = arch
680        .mla
681        .as_ref()
682        .ok_or_else(|| err("missing MLA geometry"))?;
683    if gc.hc_mult == 0
684        || gc.index_n_heads == 0
685        || gc.index_head_dim == 0
686        || gc.index_topk == 0
687        || gc.index_kpool == 0
688        || gc.index_topk % gc.index_kpool != 0
689    {
690        return Err(err("invalid mHC/DSA geometry"));
691    }
692    let kda = KdaCfg {
693        num_heads: arch
694            .linear_num_key_heads
695            .ok_or_else(|| err("missing KDA heads"))?,
696        head_k_dim: arch
697            .linear_key_head_dim
698            .ok_or_else(|| err("missing KDA key dim"))?,
699        head_v_dim: arch
700            .linear_value_head_dim
701            .ok_or_else(|| err("missing KDA value dim"))?,
702        conv_kernel: arch
703            .linear_conv_kernel_dim
704            .ok_or_else(|| err("missing KDA conv"))?,
705        hidden_size: arch.hidden_size,
706        rms_eps: arch.rms_norm_eps,
707    };
708    let qk = mla.qk_rope_head_dim + mla.qk_nope_head_dim;
709    let hc = Dsv4Cfg {
710        dim: arch.hidden_size,
711        n_heads: arch.num_attention_heads,
712        head_dim: qk,
713        rope_head_dim: mla.qk_rope_head_dim,
714        q_lora_rank: mla.q_lora_rank.unwrap_or(0),
715        o_lora_rank: 0,
716        o_groups: 1,
717        hc_mult: gc.hc_mult,
718        hc_sinkhorn_iters: gc.hc_sinkhorn_iters,
719        hc_eps: gc.hc_eps,
720        norm_eps: arch.rms_norm_eps as f32,
721        n_routed_experts: arch.moe.as_ref().map_or(0, |m| m.num_experts),
722        top_k: arch.moe.as_ref().map_or(0, |m| m.top_k),
723        moe_inter: arch.moe.as_ref().map_or(0, |m| m.moe_intermediate_size),
724        route_scale: arch
725            .moe
726            .as_ref()
727            .and_then(|m| m.routed_scaling_factor)
728            .unwrap_or(1.0),
729        swiglu_limit: gc.swiglu_limit,
730        window: 0,
731        index_topk: gc.index_topk,
732        vocab: arch.vocab_size,
733    };
734    // `CMF_GLM_DSA_TOPK=<n>` (a multiple of the pool): a smaller selection
735    // for both the host and the card, so a short text exercises DSA's
736    // selection (a check; the file's own value otherwise)
737    let index_topk = std::env::var("CMF_GLM_DSA_TOPK")
738        .ok()
739        .and_then(|v| v.trim().parse::<usize>().ok())
740        .filter(|&k| k > 0 && k % gc.index_kpool == 0)
741        .unwrap_or(gc.index_topk);
742    let cfg = Cfg {
743        hc,
744        kda,
745        eps: arch.rms_norm_eps,
746        swiglu_limit: gc.swiglu_limit,
747        index_n_heads: gc.index_n_heads,
748        index_head_dim: gc.index_head_dim,
749        index_topk,
750        index_kpool: gc.index_kpool,
751        index_tail: gc.index_kpool_always_select_tail,
752    };
753    let globals = Globals {
754        embed: t(model, "model.embed_tokens.weight")?,
755        norm: f(model, "model.norm.weight")?,
756        lm_head: t(model, "lm_head.weight")?,
757    };
758    let mut layers = Vec::with_capacity(arch.num_layers);
759    for li in 0..arch.num_layers {
760        let p = format!("model.layers.{li}.");
761        let mixer = match arch.layer_types.get(li) {
762            Some(LayerType::Kda) => Mixer::Kda(load_kda(
763                model,
764                &p,
765                arch.kda_gate_lower_bound.map(|v| v as f32),
766            )?),
767            _ => Mixer::Dsa(load_dsa(model, arch, &p)?),
768        };
769        let ffn = build_ffn_at(model, arch, &p, false, &Overlay::None)?;
770        let (ids, shared) = match &ffn {
771            FfnKind::Moe(m) => (expert_ids(m)?, shared_ids(m)),
772            _ => (Vec::new(), None),
773        };
774        layers.push(Layer {
775            attn_hc: load_hc(model, &p, "attn")?,
776            ffn_hc: load_hc(model, &p, "ffn")?,
777            input_norm: f(model, &format!("{p}input_layernorm.weight"))?,
778            post_norm: f(model, &format!("{p}post_attention_layernorm.weight"))?,
779            mixer,
780            ffn,
781            expert_ids: ids,
782            shared_ids: shared,
783        });
784    }
785    let mut state = State {
786        hyper: Vec::new(),
787        mixers: Vec::new(),
788        gpu_pool: None,
789        model_uid: model.uid(),
790        sequence_id: next_glm_sequence(),
791        gpu_ready: false,
792        pos: 0,
793        graph: None,
794        tokens: Vec::new(),
795    };
796    state.reset(&layers, &cfg);
797    Ok((globals, layers, cfg, state))
798}
799
800fn dense_clamped(d: &DenseFfn, x: &[f32], limit: f32, pool: Option<&Pool>) -> Vec<f32> {
801    let mut out = vec![0.0f32; d.down_proj.rows()];
802    expert_swiglu_qtensor(
803        x,
804        &d.gate_proj,
805        &d.up_proj,
806        &d.down_proj,
807        d.gate_proj.rows(),
808        1.0,
809        limit,
810        pool,
811        &mut out,
812    );
813    out
814}
815
816/// SwiGLU with the two projections sharing one input.  `QTensor::matvec_many`
817/// keeps their row kernels under one pool dispatch for the large Q4TP expert
818/// matrices; serial and mixed-dtype callers retain the exact legacy kernels.
819/// The down projection remains a separate pass because it consumes the gated
820/// product, so this helper changes synchronization only, never arithmetic.
821#[allow(clippy::too_many_arguments)]
822fn expert_swiglu_qtensor(
823    x: &[f32],
824    gate: &QTensor,
825    up: &QTensor,
826    down: &QTensor,
827    inter: usize,
828    weight: f32,
829    limit: f32,
830    pool: Option<&Pool>,
831    out: &mut [f32],
832) {
833    // Q2TP's established SwiGLU helper is the numerical oracle for GLM's
834    // real checkpoint.  The fused row kernel is useful for synthetic/Q4
835    // probes, but on Q2 the changed accumulation order can move the greedy
836    // vocabulary edge even when its per-row dot product is exact.  Keep the
837    // production Q2 path on the legacy temporary-and-accumulate helper until
838    // a full-logit parity proof exists; this still benefits from the shared
839    // Q2TP matvec kernel itself.
840    if gate.model_dtype() == Some(TensorDtype::Q2TiledP) {
841        crate::dsv4::expert_swiglu(
842            x,
843            &|x, y| gate.matvec(x, y, pool),
844            &|x, y| up.matvec(x, y, pool),
845            &|x, y| down.matvec(x, y, pool),
846            inter,
847            weight,
848            limit,
849            out,
850        );
851        return;
852    }
853    // Keep the accepted Q4TP serial path byte-for-byte on the established
854    // helper.  Its three ordinary row dispatches are faster on the large
855    // Q4 checkpoint than the generic pair dispatcher (and preserve the
856    // repair-5 throughput/behavior envelope).  Q2's release path below uses
857    // the dedicated batched gate/up + down kernels instead.
858    if gate.model_dtype() == Some(TensorDtype::Q4TiledP) {
859        crate::dsv4::expert_swiglu(
860            x,
861            &|x, y| gate.matvec(x, y, pool),
862            &|x, y| up.matvec(x, y, pool),
863            &|x, y| down.matvec(x, y, pool),
864            inter,
865            weight,
866            limit,
867            out,
868        );
869        return;
870    }
871    // A fused pair is still useful for synthetic/mixed-dtype probes, where
872    // the legacy helper cannot share the activation rows.
873    let mut gate_buf = vec![0.0f32; inter];
874    if QTensor::matvec_silu_mul_limited(gate, up, x, &mut gate_buf, limit, pool) {
875        if weight != 1.0 {
876            for v in gate_buf.iter_mut() {
877                *v *= weight;
878            }
879        }
880        down.matvec(&gate_buf, out, pool);
881        return;
882    }
883    let mut up_buf = vec![0.0f32; inter];
884    let fused_q4 = matches!(
885        (gate, up, down),
886        (
887            QTensor::Mapped {
888                dtype: TensorDtype::Q4TiledP,
889                ..
890            },
891            QTensor::Mapped {
892                dtype: TensorDtype::Q4TiledP,
893                ..
894            },
895            QTensor::Mapped {
896                dtype: TensorDtype::Q4TiledP,
897                ..
898            }
899        )
900    );
901    if fused_q4 {
902        QTensor::matvec_many([gate, up], x, [&mut gate_buf, &mut up_buf], pool);
903    } else {
904        // Q2TP and mixed-dtype experts stay on their established individual
905        // tiled kernels; the generic batched dispatcher is slower there.
906        gate.matvec(x, &mut gate_buf, pool);
907        up.matvec(x, &mut up_buf, pool);
908    }
909    if limit > 0.0 {
910        for u in up_buf.iter_mut() {
911            *u = u.clamp(-limit, limit);
912        }
913        for g in gate_buf.iter_mut() {
914            *g = g.min(limit);
915        }
916    }
917    for (g, u) in gate_buf.iter_mut().zip(&up_buf) {
918        *g = (*g / (1.0 + (-*g).exp())) * *u * weight;
919    }
920    down.matvec(&gate_buf, out, pool);
921}
922
923/// Decide whether GLM's dynamic expert path is eligible for automatic use.
924///
925/// Q2 gate/up payloads have a bounded explicit Vulkan path, but the measured
926/// RTX 3090 decode is slower than exact CPU after applying the physical-VRAM
927/// reserve.  Automatic mode therefore stays on CPU for both profiles; an
928/// operator can still force the bounded dynamic path with
929/// `CMF_GLM_DYNAMIC_MOE=1`.
930fn glm_dynamic_moe_enabled(mode: Option<&str>) -> bool {
931    match mode {
932        Some("1") => true,
933        Some("0") => false,
934        None | Some("auto") => false,
935        Some(_) => false,
936    }
937}
938
939/// Keep the host-side GLM trunk on the exact CPU kernels while the explicitly
940/// forced dynamic path exercises only the resident-expert frame on Vulkan.
941/// GLM's KDA/DSA and HyperConnection state are scalar, token-at-a-time
942/// operations: sending each projection over PCIe costs more than its kernel.
943/// Forced dynamic mode uses this split by default; the env switch is retained
944/// as a narrow A/B escape hatch for a backend that has a faster static arm.
945#[cfg(feature = "gpu")]
946fn glm_gpu_moe_only_enabled(dynamic_enabled: bool) -> bool {
947    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
948    *ON.get_or_init(
949        || match std::env::var("CMF_GLM_GPU_MOE_ONLY").ok().as_deref() {
950            Some("0") | Some("false") | Some("off") => false,
951            Some("1") | Some("true") | Some("on") => true,
952            _ => dynamic_enabled,
953        },
954    )
955}
956
957/// Allow a release run to disable the batched CPU MoE path for an A/B profile
958/// without changing the default policy.  The switch is intentionally opt-in
959/// and process-local: `CMF_GLM_MOE_BATCH=0` is evidence-only instrumentation,
960/// while every normal invocation keeps the exact batched implementation.
961fn glm_moe_batch_enabled() -> bool {
962    static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
963    *ENABLED.get_or_init(|| {
964        // Batch gate/up and down rows by default; `CMF_GLM_MOE_BATCH=0` keeps
965        // the old serial path available for an explicit parity A/B.  The
966        // implementation retains the release Q2/Q4 oracle after the Q2
967        // SIMD experiment was rejected for changing greedy output.
968        !matches!(
969            std::env::var("CMF_GLM_MOE_BATCH").ok().as_deref(),
970            Some("0") | Some("false") | Some("off")
971        )
972    })
973}
974
975/// Optional per-layer wall-clock profile for the bounded Q2 CPU path.  It is
976/// deliberately off by default so the release policy has no logging or
977/// timing overhead; `CMF_GLM_CPU_PROF=1` is used only for evidence runs.
978fn glm_cpu_profile_enabled() -> bool {
979    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
980    *ON.get_or_init(|| std::env::var("CMF_GLM_CPU_PROF").ok().as_deref() == Some("1"))
981}
982
983/// Exact CPU GLM MoE with one gate/up dispatch and one down dispatch for all
984/// selected experts.  Q2TP gate/up and Q4TP down are the release profile, so
985/// this reuses the shared batched kernels instead of creating a second
986/// GLM-only execution subsystem.  `None` means the dtypes/shape are outside
987/// the shared kernel contract and the caller must use the serial fallback.
988fn moe_cpu_batched(
989    m: &MoeFfn,
990    x: &[f32],
991    idx: &[usize],
992    p: &[f32],
993    wsum: f32,
994    limit: f32,
995    pool: Option<&Pool>,
996) -> Option<Vec<f32>> {
997    if idx.is_empty() {
998        return None;
999    }
1000    let n = idx.len() + usize::from(m.shared.is_some());
1001    let mut pairs = Vec::with_capacity(n);
1002    let mut downs = Vec::with_capacity(n);
1003    let mut weights = Vec::with_capacity(n);
1004    for &e in idx {
1005        let d = m.experts.get(e)?;
1006        if d.act != Act::Silu {
1007            return None;
1008        }
1009        pairs.push((&d.gate_proj, &d.up_proj));
1010        downs.push(&d.down_proj);
1011        weights.push(p[e] / wsum * m.per_expert_scale.as_ref().map_or(1.0, |v| v[e]));
1012    }
1013    // Preserve the serial order: routed experts first, always-on shared last.
1014    if let Some((shared, gate)) = &m.shared {
1015        if shared.act != Act::Silu {
1016            return None;
1017        }
1018        let shared_weight = gate.as_ref().map_or(1.0, |g| {
1019            let mut y = [0.0f32; 1];
1020            g.matvec(x, &mut y, pool);
1021            1.0 / (1.0 + (-y[0]).exp())
1022        });
1023        pairs.push((&shared.gate_proj, &shared.up_proj));
1024        downs.push(&shared.down_proj);
1025        weights.push(shared_weight);
1026    }
1027
1028    let inter = pairs.first()?.0.rows();
1029    GLM_MOE_ACTS.with(|scratch| {
1030        let mut activations = scratch.borrow_mut();
1031        activations.truncate(n);
1032        while activations.len() < n {
1033            activations.push(Vec::new());
1034        }
1035        for a in activations.iter_mut() {
1036            a.resize(inter, 0.0);
1037        }
1038        if !QTensor::moe_gate_up_many_limited(&pairs, x, &mut activations[..], limit, pool) {
1039            return None;
1040        }
1041        let mut out = vec![0.0f32; x.len()];
1042        if !QTensor::moe_down_many(&downs, &activations[..], &weights, &mut out, pool) {
1043            return None;
1044        }
1045        Some(out)
1046    })
1047}
1048
1049/// Exact CPU completion for the routed GLM experts that are not resident in
1050/// the device arena.  This mirrors `moe_cold_experts_cpu` from the shared
1051/// pipeline, but keeps GLM's positive SwiGLU clamp in the fused path; using
1052/// the unclamped helper here would silently change the model on a cache miss.
1053fn glm_cold_experts_cpu(
1054    experts: &[(&DenseFfn, f32)],
1055    x: &[f32],
1056    limit: f32,
1057    pool: Option<&Pool>,
1058) -> Vec<f32> {
1059    let mut out = vec![0.0f32; x.len()];
1060    if experts.is_empty() {
1061        return out;
1062    }
1063    let pairs: Vec<_> = experts
1064        .iter()
1065        .map(|(e, _)| (&e.gate_proj, &e.up_proj))
1066        .collect();
1067    let downs: Vec<_> = experts.iter().map(|(e, _)| &e.down_proj).collect();
1068    let weights: Vec<_> = experts.iter().map(|(_, w)| *w).collect();
1069    let inter = experts[0].0.gate_proj.rows();
1070    let mut activations: Vec<Vec<f32>> = (0..experts.len()).map(|_| vec![0.0; inter]).collect();
1071    if QTensor::moe_gate_up_many_limited(&pairs, x, &mut activations, limit, pool)
1072        && QTensor::moe_down_many(&downs, &activations, &weights, &mut out, pool)
1073    {
1074        return out;
1075    }
1076    out.fill(0.0);
1077    for &(expert, weight) in experts {
1078        let mut one = vec![0.0f32; x.len()];
1079        expert_swiglu_qtensor(
1080            x,
1081            &expert.gate_proj,
1082            &expert.up_proj,
1083            &expert.down_proj,
1084            expert.gate_proj.rows(),
1085            weight,
1086            limit,
1087            pool,
1088            &mut one,
1089        );
1090        for (o, v) in out.iter_mut().zip(one) {
1091            *o += v;
1092        }
1093    }
1094    out
1095}
1096
1097fn moe_cpu(m: &MoeFfn, x: &[f32], limit: f32, pool: Option<&Pool>) -> Vec<f32> {
1098    let mut logits = vec![0.0f32; m.experts.len()];
1099    m.router.matvec(x, &mut logits, pool);
1100    // GLM's noaux_tc router renormalizes selected sigmoid scores with a
1101    // 1e-20 floor (the generic Qwen/LFM2 helper intentionally keeps its
1102    // historical 1e-6 floor).
1103    let (idx, p, wsum) = moe_route_with_eps(&logits, m, None, 1e-20);
1104    // Keep the same trace format as the generic pipeline for cache/locality
1105    // profiling; with no `CMF_MOE_TRACE` the helper is a cheap no-op.
1106    crate::pipeline::moe_trace_at(crate::gpu::cur_layer() as i32, &idx);
1107    // The batched Q2TP path is the repair-7 target.  Keep Q4TP on the
1108    // accepted serial helper: its larger rows make one giant virtual dispatch
1109    // disproportionately expensive on this CPU/NFS-backed checkpoint, and
1110    // repair-5 already established its behavior and throughput.
1111    let q2_batch =
1112        m.experts.first().and_then(|d| d.gate_proj.model_dtype()) == Some(TensorDtype::Q2TiledP);
1113    if q2_batch && glm_moe_batch_enabled() {
1114        if let Some(out) = moe_cpu_batched(m, x, &idx, &p, wsum, limit, pool) {
1115            return out;
1116        }
1117    }
1118    let mut out = vec![0.0f32; x.len()];
1119    for &e in &idx {
1120        let d = &m.experts[e];
1121        let mut one = vec![0.0f32; x.len()];
1122        expert_swiglu_qtensor(
1123            x,
1124            &d.gate_proj,
1125            &d.up_proj,
1126            &d.down_proj,
1127            d.gate_proj.rows(),
1128            p[e] / wsum,
1129            limit,
1130            pool,
1131            &mut one,
1132        );
1133        for (o, v) in out.iter_mut().zip(one) {
1134            *o += v;
1135        }
1136    }
1137    if let Some((d, shared_gate)) = &m.shared {
1138        let weight = shared_gate.as_ref().map_or(1.0, |g| {
1139            let mut y = [0.0f32; 1];
1140            g.matvec(x, &mut y, pool);
1141            1.0 / (1.0 + (-y[0]).exp())
1142        });
1143        let mut one = vec![0.0f32; x.len()];
1144        expert_swiglu_qtensor(
1145            x,
1146            &d.gate_proj,
1147            &d.up_proj,
1148            &d.down_proj,
1149            d.gate_proj.rows(),
1150            weight,
1151            limit,
1152            pool,
1153            &mut one,
1154        );
1155        for (o, v) in out.iter_mut().zip(one) {
1156            *o += v;
1157        }
1158    }
1159    out
1160}
1161
1162/// The routed FFN on a CUDA card (`gpu::moe_row`): the host routes as
1163/// `moe_cpu` does, the card computes the picks (built into its slots from
1164/// the mapped file) and the shared expert. `CMF_GLM_CUDA_MOE=0` keeps them on
1165/// the host; a refusal does too.
1166fn cuda_moe(layer: &Layer, x: &[f32], limit: f32, pool: Option<&Pool>) -> Option<Vec<f32>> {
1167    if !crate::gpu::cuda_active() || std::env::var("CMF_GLM_CUDA_MOE").as_deref() == Ok("0") {
1168        return None;
1169    }
1170    let FfnKind::Moe(m) = &layer.ffn else {
1171        return None;
1172    };
1173    if m.route_tau.is_some() || m.mask.is_some() {
1174        return None;
1175    }
1176    let first = m.experts.first()?;
1177    let model = first.gate_proj.model_arc()?;
1178    let inter = first.gate_proj.rows();
1179    let mut logits = vec![0.0f32; m.experts.len()];
1180    m.router.matvec(x, &mut logits, pool);
1181    let (idx, p, wsum) = moe_route_with_eps(&logits, m, None, 1e-20);
1182    crate::pipeline::moe_trace_at(crate::gpu::cur_layer() as i32, &idx);
1183    let picks: Vec<(usize, f32)> = idx.iter().map(|&e| (e, p[e] / wsum)).collect();
1184    let shared = match (&m.shared, layer.shared_ids) {
1185        (Some((d, gate)), Some(ids)) => {
1186            let w = gate.as_ref().map_or(1.0, |g| {
1187                let mut y = [0.0f32; 1];
1188                g.matvec(x, &mut y, pool);
1189                1.0 / (1.0 + (-y[0]).exp())
1190            });
1191            Some((ids, d.gate_proj.rows(), w))
1192        }
1193        (None, _) => None,
1194        (Some(_), None) => return None,
1195    };
1196    let mut out = vec![0.0f32; x.len()];
1197    crate::gpu::moe_row(&model, &layer.expert_ids, shared, inter, limit, x, &picks, &mut out).then_some(out)
1198}
1199
1200fn ffn_cpu(ffn: &FfnKind, x: &[f32], limit: f32, pool: Option<&Pool>) -> Vec<f32> {
1201    match ffn {
1202        FfnKind::Dense(d) => dense_clamped(d, x, limit, pool),
1203        FfnKind::Moe(m) => moe_cpu(m, x, limit, pool),
1204        FfnKind::DenseMoe(_) => unreachable!("GLM has no DenseMoe layer"),
1205    }
1206}
1207
1208#[cfg(feature = "gpu")]
1209fn dynamic_moe_gpu(
1210    layer: &Layer,
1211    li: usize,
1212    x: &[f32],
1213    gpu_pool: &mut Option<crate::qwen4_exp::QwenGpuPool>,
1214    cfg: &Cfg,
1215    n_layers: usize,
1216    pool: Option<&Pool>,
1217) -> Option<Vec<f32>> {
1218    let FfnKind::Moe(m) = &layer.ffn else {
1219        return None;
1220    };
1221    if !crate::gpu::enabled_here() || m.route_tau.is_some() || m.mask.is_some() {
1222        return None;
1223    }
1224    let model = m.experts.first()?.gate_proj.model_arc()?;
1225    let gu_q2 = m.experts.first()?.gate_proj.model_dtype() == Some(TensorDtype::Q2TiledP);
1226    let enabled = glm_dynamic_moe_enabled(std::env::var("CMF_GLM_DYNAMIC_MOE").ok().as_deref());
1227    if !enabled {
1228        return None;
1229    }
1230    if gpu_pool.is_none() {
1231        *gpu_pool = crate::qwen4_exp::QwenGpuPool::create_for_glm(
1232            &model,
1233            m.experts.first()?.gate_proj.rows(),
1234            x.len(),
1235            n_layers,
1236            m.experts.len(),
1237            gu_q2,
1238        );
1239    }
1240    let mut logits = vec![0.0f32; m.experts.len()];
1241    m.router.matvec(x, &mut logits, pool);
1242    // Keep the GPU and CPU branches on the same GLM router denominator.
1243    let (picks, probabilities, wsum) = moe_route_with_eps(&logits, m, None, 1e-20);
1244    let (remap, shared_slot) =
1245        gpu_pool
1246            .as_mut()?
1247            .ensure(&model, li, &picks, &layer.expert_ids, layer.shared_ids)?;
1248    let mut mix = vec![0.0f32; m.experts.len()];
1249    for &e in &picks {
1250        mix[e] = probabilities[e] / wsum;
1251    }
1252    let cold_ids: Vec<usize> = picks
1253        .iter()
1254        .copied()
1255        .filter(|&e| remap[e] == u32::MAX)
1256        .collect();
1257    let shared_weight = m.shared.as_ref().map_or(1.0, |(_, gate)| {
1258        gate.as_ref().map_or(1.0, |g| {
1259            let mut y = [0.0f32; 1];
1260            g.matvec(x, &mut y, pool);
1261            1.0 / (1.0 + (-y[0]).exp())
1262        })
1263    });
1264    let weights = crate::gpu_wgpu::Dsv4MoeW {
1265        router: &[],
1266        experts: &layer.expert_ids,
1267        logits: &logits,
1268        bias: Some(&mix),
1269        mask: None,
1270        forced: Some(&picks),
1271        remap: Some(&remap),
1272        global: Some(crate::gpu_wgpu::Dsv4GlobalMoe {
1273            pool_uid: model.uid(),
1274            shared_slot,
1275            segment_slots: gpu_pool.as_ref()?.segment_slots as u32,
1276        }),
1277        has_shared: m.shared.is_some(),
1278        shared_weight,
1279        preweighted: true,
1280        qwen_softmax: true,
1281    };
1282    let geom = crate::gpu_wgpu::Dsv4MoeGeom {
1283        hidden: x.len(),
1284        inter: m.experts.first()?.gate_proj.rows(),
1285        top_k: m.top_k,
1286        route_scale: 1.0,
1287        swiglu_limit: cfg.swiglu_limit,
1288        gu_q2,
1289        bf16: false,
1290    };
1291    let mut out = vec![0.0f32; x.len()];
1292    let mut cold = Vec::new();
1293    let mut cold_x = Vec::new();
1294    // The GPU frame and cache-miss experts are independent: resident experts
1295    // consume the device's arena while cold experts read immutable model
1296    // pages on the host.  Run both arms in parallel, as Qwen's proven path
1297    // does, so a miss no longer serializes a full gate/up/down completion
1298    // behind every one of the 42 layer submissions.
1299    let cold_jobs: Vec<_> = cold_ids
1300        .iter()
1301        .copied()
1302        .map(|e| (&m.experts[e], mix[e]))
1303        .collect();
1304    let (frame_ok, cold_cpu) = std::thread::scope(|scope| {
1305        let cpu = (!cold_jobs.is_empty())
1306            .then(|| scope.spawn(|| glm_cold_experts_cpu(&cold_jobs, x, cfg.swiglu_limit, pool)));
1307        let ok = crate::gpu_wgpu::dsv4_moe_frame(
1308            &model,
1309            &weights,
1310            geom,
1311            x,
1312            &mut cold,
1313            &mut cold_x,
1314            None,
1315            None,
1316            &mut out,
1317        );
1318        let early = cpu
1319            .map(|job| job.join().ok())
1320            .flatten()
1321            .unwrap_or_else(|| vec![0.0; x.len()]);
1322        (ok, early)
1323    });
1324    if !frame_ok
1325        || cold.len() != cold_jobs.len()
1326        || cold.iter().map(|&(e, _)| e).ne(cold_ids.iter().copied())
1327    {
1328        return None;
1329    }
1330    // Complete cache misses exactly on the CPU. The resident subset has
1331    // already been mixed with its final pre-normalized weights on device.
1332    for (o, c) in out.iter_mut().zip(&cold_cpu) {
1333        *o += c;
1334    }
1335    Some(out)
1336}
1337
1338/// Decode one token. DSA is mathematically full attention until the 2048
1339/// token budget is exceeded; the standard MLA cache is therefore exact for
1340/// ordinary prompts and remains the portable CPU/Metal fallback.
1341/// GLM's stack on the card's whole-token graph (`CMF_GLM_GRAPH=0`: the
1342/// host): KDA and NoPE MLA mixers, the dense and routed FFNs with their
1343/// SwiGLU clamp and DeepSeek-V4's four-stream mHC around both halves. Within
1344/// `index_topk` positions DSA's selection is every position, so its MLA is
1345/// the plain attention there; past it the card's indexer selects the
1346/// positions and the attention reads their latents (`GraphDsa`).
1347/// The graph calls' context cap: GLM's native million positions (past
1348/// `index_topk` DSA reads the selected latents, and the caches grow on the
1349/// card as the context does).
1350const GRAPH_CAP: usize = 1 << 20;
1351
1352fn graph_on() -> bool {
1353    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1354    *ON.get_or_init(|| std::env::var("CMF_GLM_GRAPH").as_deref() != Ok("0"))
1355}
1356
1357fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
1358    if let Some((_, i, kind, rs)) = t.graph_weight_or_blr() {
1359        return Some(crate::gpu::GraphW { idx: i, kind, row_scale: rs, data: &[], prism: crate::gpu::GraphPrismOp::None, affine: false });
1360    }
1361    t.as_f32().map(|d| crate::gpu::GraphW { idx: 0, kind: 4, row_scale: &[], data: d, prism: crate::gpu::GraphPrismOp::None, affine: false })
1362}
1363
1364/// The stack as graph layers (None: a weight the graphs cannot address).
1365fn graph_layers<'a>(layers: &'a [Layer], cfg: &Cfg) -> Option<Vec<crate::gpu::GraphLayer<'a>>> {
1366    use crate::gpu::{GraphAct, GraphAttn, GraphFfn, GraphLayer, GraphMhc, GraphMhcDsv4};
1367    let last = layers.len().checked_sub(1)?;
1368    let mut out = Vec::with_capacity(layers.len());
1369    for (li, l) in layers.iter().enumerate() {
1370        let attn = match &l.mixer {
1371            Mixer::Kda(w) => {
1372                let (g_a, g_b) = match &w.gate {
1373                    KdaOutGate::Full(g) => (gw(g)?, None),
1374                    KdaOutGate::LowRank(a, b) => (gw(a)?, Some(gw(b)?)),
1375                };
1376                GraphAttn::Kda {
1377                    q: gw(&w.q_proj)?,
1378                    k: gw(&w.k_proj)?,
1379                    v: gw(&w.v_proj)?,
1380                    conv_q: &w.conv_q,
1381                    conv_k: &w.conv_k,
1382                    conv_v: &w.conv_v,
1383                    f_a: gw(&w.f_a)?,
1384                    f_b: gw(&w.f_b)?,
1385                    dt_bias: &w.dt_bias,
1386                    a_log: &w.a_log,
1387                    b: gw(&w.b_proj)?,
1388                    g_a,
1389                    g_b,
1390                    o_norm: &w.o_norm,
1391                    out: gw(&w.o_proj)?,
1392                    nh: cfg.kda.num_heads,
1393                    dk: cfg.kda.head_k_dim,
1394                    dv: cfg.kda.head_v_dim,
1395                    kk: cfg.kda.conv_kernel,
1396                    lower_bound: w.gate_lower_bound,
1397                    cpu_state: &[],
1398                }
1399            }
1400            Mixer::Dsa(w) => {
1401                let m = &w.mla;
1402                let q_a = match &m.q_a {
1403                    Some(t) => Some(gw(t)?),
1404                    None => None,
1405                };
1406                GraphAttn::Mla {
1407                    hy: None,
1408                    q_a,
1409                    q_a_norm: m.q_a_norm.as_deref(),
1410                    q: gw(&m.q_proj)?,
1411                    kv_a: gw(&m.kv_a)?,
1412                    kv_a_norm: &m.kv_a_norm,
1413                    kv_b: gw(&m.kv_b)?,
1414                    o: gw(&m.o_proj)?,
1415                    nh: m.nh,
1416                    rope: m.qk_rope,
1417                    nope: m.qk_nope,
1418                    v_dim: m.v_dim,
1419                    lora: m.lora,
1420                    scale: m.scale,
1421                    no_rope: m.nope,
1422                    cpu_k: &[],
1423                    cpu_v: &[],
1424                    cpu_base: 0,
1425                    dsa: if cfg.index_tail {
1426                        let kvb = w.kvb_f32.get_or_init(|| {
1427                            let (rows, lora) = (m.kv_b.rows(), m.lora);
1428                            let mut v = vec![0.0f32; rows * lora];
1429                            for (r, row) in v.chunks_exact_mut(lora).enumerate() {
1430                                m.kv_b.row_f32(r, row);
1431                            }
1432                            v
1433                        });
1434                        Some(crate::gpu::GraphDsa {
1435                            index_q: gw(&w.index_q)?,
1436                            index_k: gw(&w.index_k)?,
1437                            pool_gate: gw(&w.pool_gate)?,
1438                            index_weights: gw(&w.index_weights)?,
1439                            k_norm: &w.index_k_norm,
1440                            k_bias: &w.index_k_bias,
1441                            ape: &w.pool_ape,
1442                            kv_b: kvb,
1443                            ih: cfg.index_n_heads,
1444                            id: cfg.index_head_dim,
1445                            topk: cfg.index_topk,
1446                            kpool: cfg.index_kpool,
1447                        })
1448                    } else {
1449                        // the device selection always takes the tail
1450                        return None;
1451                    },
1452                }
1453            }
1454        };
1455        let ffn = match &l.ffn {
1456            FfnKind::Dense(d) => GraphFfn::Dense {
1457                gate: gw(&d.gate_proj)?,
1458                up: gw(&d.up_proj)?,
1459                down: gw(&d.down_proj)?,
1460                act: GraphAct::Silu,
1461                limit: cfg.swiglu_limit,
1462                hot: None,
1463            },
1464            FfnKind::Moe(m) => {
1465                let inter = m.experts.first()?.gate_proj.rows();
1466                let shared = m.shared.as_ref().map(|(d, _)| d);
1467                // the shared expert rides in the bank when it has the routed
1468                // experts' width and codec
1469                let in_bank = shared.is_some_and(|d| d.gate_proj.rows() == inter && d.up_proj.rows() == inter);
1470                let mut experts = l.expert_ids.clone();
1471                if in_bank {
1472                    experts.push(l.shared_ids?);
1473                }
1474                let detached_shared = match shared {
1475                    Some(d) if !in_bank => Some(crate::gpu::GraphMoeDetachedShared {
1476                        gate: gw(&d.gate_proj)?,
1477                        up: gw(&d.up_proj)?,
1478                        down: gw(&d.down_proj)?,
1479                        width: d.gate_proj.rows(),
1480                    }),
1481                    _ => None,
1482                };
1483                let e0 = m.experts.first()?;
1484                let gu_q2 = e0.gate_proj.mapped_q2tp().is_some();
1485                if !(gu_q2 || e0.gate_proj.mapped_q4tp().is_some()) || e0.down_proj.mapped_q4tp().is_none() {
1486                    return None;
1487                }
1488                GraphFfn::Moe {
1489                    latent: None,
1490                    shared_limit: None,
1491                    router: gw(&m.router)?,
1492                    shared_gate: gw(&m.router)?,
1493                    experts,
1494                    n_exp: m.experts.len(),
1495                    top_k: m.top_k,
1496                    inter,
1497                    act: GraphAct::Silu,
1498                    norm_topk: m.norm_topk_prob,
1499                    q4tp: true,
1500                    gu_q2,
1501                    q82: false,
1502                    sigmoid: m.router_sigmoid,
1503                    sigmoid_denom_eps: m.sigmoid_denom_eps,
1504                    bias: m.expert_bias.as_deref(),
1505                    has_shared: in_bank,
1506                    detached_shared,
1507                    shared_gated: false,
1508                    route_scale: m.routed_scaling,
1509                    limit: cfg.swiglu_limit,
1510                }
1511            }
1512            FfnKind::DenseMoe(_) => return None,
1513        };
1514        out.push(GraphLayer {
1515            engram: None,
1516            mhc: Some(GraphMhc {
1517                head: None,
1518                attn_w: &l.attn_hc.function,
1519                attn_b: &l.attn_hc.base,
1520                ffn_w: &l.ffn_hc.function,
1521                ffn_b: &l.ffn_hc.base,
1522                enter: li == 0,
1523                leave: li == last,
1524                iters: cfg.hc.hc_sinkhorn_iters,
1525                pre_scale: 1.0,
1526                dsv4: Some(GraphMhcDsv4 {
1527                    ihc: None,
1528                    attn_scale: l.attn_hc.scale,
1529                    ffn_scale: l.ffn_hc.scale,
1530                    eps: cfg.hc.hc_eps,
1531                    rms_eps: cfg.hc.norm_eps,
1532                }),
1533            }),
1534            input_norm: &l.input_norm,
1535            attn,
1536            post_norm: &l.post_norm,
1537            ffn,
1538            attn_out_norm: None,
1539            ffn_out_norm: None,
1540            layer_scale: None,
1541        });
1542    }
1543    Some(out)
1544}
1545
1546/// The graph calls' call-wide attention geometry (heads, head width, scale)
1547/// and the widest FFN.
1548fn graph_geom(layers: &[Layer]) -> (usize, usize, f32, usize) {
1549    let mla = layers.iter().find_map(|l| match &l.mixer {
1550        Mixer::Dsa(w) => Some(&w.mla),
1551        _ => None,
1552    });
1553    let (nh, hd, scale) = mla.map_or((1, 64, 0.125), |m| (m.nh, m.qk_rope + m.qk_nope, m.scale));
1554    let inter = layers
1555        .iter()
1556        .map(|l| match &l.ffn {
1557            FfnKind::Dense(d) => d.gate_proj.rows(),
1558            FfnKind::Moe(m) => m.experts.first().map_or(0, |e| e.gate_proj.rows()),
1559            FfnKind::DenseMoe(_) => 0,
1560        })
1561        .max()
1562        .unwrap_or(0);
1563    (nh, hd, scale, inter)
1564}
1565
1566/// The host takes the sequence over from the card: its tokens replayed
1567/// through the host stack (a refusal or failure after the card held it).
1568fn host_replay(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, pool: Option<&Pool>) {
1569    let toks = std::mem::take(&mut state.tokens);
1570    tracing::warn!("glm5_next: the host replays {} tokens the card held", toks.len());
1571    state.reset(layers, cfg);
1572    state.graph = Some(false);
1573    let mut scratch = Vec::new();
1574    for (p, &t) in toks.iter().enumerate() {
1575        forward_inner(globals, layers, cfg, state, t, p, pool, &mut scratch, false, false);
1576    }
1577}
1578
1579/// A prompt's positions `start..` through the card's batch graph (the rows
1580/// in chunks), its last one through the token graph with the logits.
1581/// Returns the positions taken (0: none, the caller goes a token at a time).
1582#[allow(clippy::too_many_arguments)]
1583pub fn forward_prompt(
1584    globals: &Globals,
1585    layers: &[Layer],
1586    cfg: &Cfg,
1587    state: &mut State,
1588    ids: &[u32],
1589    start: usize,
1590    pool: Option<&Pool>,
1591    logits: &mut Vec<f32>,
1592) -> usize {
1593    use crate::gpu::BatchGraphOutcome;
1594    if ids.len() < 2 || !graph_on() || !(crate::gpu::cuda_active() || crate::gpu::wgpu_active()) {
1595        return 0;
1596    }
1597    if start == 0 || state.pos != start {
1598        state.reset(layers, cfg);
1599    }
1600    if state.graph == Some(false) || (start > 0 && state.graph != Some(true)) {
1601        return 0;
1602    }
1603    let Some(model) = globals.embed.model_arc() else { return 0 };
1604    let Some(gl) = graph_layers(layers, cfg) else { return 0 };
1605    let (nh, hd, scale, inter) = graph_geom(layers);
1606    let dim = cfg.hc.dim;
1607    // wide: a chunk past the card reads every bank once (wgpu stages each
1608    // streamed layer's experts whole); CUDA's small path takes 16 rows at a
1609    // time inside it either way
1610    let chunk = std::env::var("CMF_GLM_PROMPT_CHUNK").ok().and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(512).max(1);
1611    let body = ids.len() - 1;
1612    let o1: Vec<Option<Vec<crate::nystrom::O1DeviceView<'_>>>> = (0..gl.len()).map(|_| None).collect();
1613    let mut done = 0usize;
1614    while done < body {
1615        let end = (done + chunk).min(body);
1616        let k = end - done;
1617        let mut h = vec![0.0f32; k * dim];
1618        for (j, &t) in ids[done..end].iter().enumerate() {
1619            if (t as usize) < globals.embed.rows() {
1620                globals.embed.row_f32(t as usize, &mut h[j * dim..(j + 1) * dim]);
1621            }
1622        }
1623        let positions: Vec<usize> = (start + done..start + end).collect();
1624        let outcome = crate::gpu::forward_batch_graph_at(
1625            &model,
1626            state.kv_id(),
1627            0,
1628            &gl,
1629            &[],
1630            &mut h,
1631            nh,
1632            nh,
1633            hd,
1634            0,
1635            dim,
1636            inter,
1637            &positions,
1638            GRAPH_CAP,
1639            false,
1640            cfg.eps as f32,
1641            scale,
1642            k,
1643            &o1,
1644            0,
1645            None,
1646            None,
1647        );
1648        match outcome {
1649            BatchGraphOutcome::Completed => {
1650                if state.graph.is_none() {
1651                    tracing::info!("glm5_next: the prompt runs on the card's batch graph");
1652                }
1653                state.graph = Some(true);
1654                state.tokens.extend_from_slice(&ids[done..end]);
1655                state.pos = start + end;
1656                done = end;
1657            }
1658            // nothing ran: the caller goes on a token at a time from here
1659            BatchGraphOutcome::Declined => return done,
1660            BatchGraphOutcome::Failed => {
1661                host_replay(globals, layers, cfg, state, pool);
1662                return done;
1663            }
1664        }
1665    }
1666    forward_token(globals, layers, cfg, state, ids[body], start + body, pool, logits, true);
1667    ids.len()
1668}
1669
1670/// One token through the card's graph: the embedding in, the logits (or
1671/// nothing) out. Declined: no command ran.
1672fn graph_token(
1673    globals: &Globals,
1674    layers: &[Layer],
1675    cfg: &Cfg,
1676    state: &State,
1677    token_id: u32,
1678    position: usize,
1679    logits: &mut Vec<f32>,
1680    want_logits: bool,
1681) -> crate::gpu::TokenGraphOutcome {
1682    use crate::gpu::TokenGraphOutcome;
1683    if !graph_on() || !(crate::gpu::cuda_active() || crate::gpu::wgpu_active()) {
1684        return TokenGraphOutcome::Declined;
1685    }
1686    let Some(model) = globals.embed.model_arc() else { return TokenGraphOutcome::Declined };
1687    let Some(gl) = graph_layers(layers, cfg) else { return TokenGraphOutcome::Declined };
1688    let Some(head) = gw(&globals.lm_head) else { return TokenGraphOutcome::Declined };
1689    let (nh, hd, scale, inter) = graph_geom(layers);
1690    let mut h = vec![0.0f32; cfg.hc.dim];
1691    if (token_id as usize) < globals.embed.rows() {
1692        globals.embed.row_f32(token_id as usize, &mut h);
1693    }
1694    let o1: Vec<Option<Vec<crate::nystrom::O1DeviceView<'_>>>> = (0..gl.len()).map(|_| None).collect();
1695    let vocab = globals.lm_head.rows();
1696    crate::gpu::forward_token_graph(
1697        &model,
1698        state.kv_id(),
1699        &gl,
1700        &o1,
1701        0,
1702        &[],
1703        &mut h,
1704        nh,
1705        nh,
1706        hd,
1707        scale,
1708        0,
1709        cfg.hc.dim,
1710        inter,
1711        position,
1712        GRAPH_CAP,
1713        false,
1714        cfg.eps as f32,
1715        want_logits.then_some((&head, vocab)),
1716        &globals.norm,
1717        logits,
1718        &[],
1719        1,
1720        None,
1721        None,
1722        None,
1723        0,
1724        false,
1725    )
1726}
1727
1728#[allow(clippy::too_many_arguments)]
1729pub fn forward_token(
1730    globals: &Globals,
1731    layers: &[Layer],
1732    cfg: &Cfg,
1733    state: &mut State,
1734    token_id: u32,
1735    position: usize,
1736    pool: Option<&Pool>,
1737    logits: &mut Vec<f32>,
1738    want_logits: bool,
1739) {
1740    forward_inner(globals, layers, cfg, state, token_id, position, pool, logits, want_logits, true);
1741}
1742
1743/// `forward_token`; `allow_graph` false keeps the host (a replay).
1744#[allow(clippy::too_many_arguments)]
1745fn forward_inner(
1746    globals: &Globals,
1747    layers: &[Layer],
1748    cfg: &Cfg,
1749    state: &mut State,
1750    token_id: u32,
1751    position: usize,
1752    pool: Option<&Pool>,
1753    logits: &mut Vec<f32>,
1754    want_logits: bool,
1755    allow_graph: bool,
1756) {
1757    let prof = std::env::var_os("CMF_GLM_PROF").is_some();
1758    #[cfg(feature = "gpu")]
1759    let gpu_before = if prof {
1760        use std::sync::atomic::Ordering;
1761        Some((
1762            crate::gpu_wgpu::MOE_ENC_NS.load(Ordering::Relaxed),
1763            crate::gpu_wgpu::MOE_WAIT_NS.load(Ordering::Relaxed),
1764            crate::gpu_wgpu::MOE_GPU_NS[0].load(Ordering::Relaxed),
1765            crate::gpu_wgpu::MOE_GPU_N.load(Ordering::Relaxed),
1766            crate::gpu_wgpu::DSV4_FILLS.load(Ordering::Relaxed),
1767            crate::gpu_wgpu::DSV4_FILL_BYTES.load(Ordering::Relaxed),
1768            crate::gpu_wgpu::SUBMITS.load(Ordering::Relaxed),
1769            crate::gpu_wgpu::PASSES.load(Ordering::Relaxed),
1770            crate::gpu_wgpu::residency_stats(),
1771        ))
1772    } else {
1773        None
1774    };
1775    let token_t0 = std::time::Instant::now();
1776    if position == 0 || state.pos != position {
1777        state.reset(layers, cfg);
1778    }
1779    if !allow_graph {
1780        state.graph = Some(false);
1781    }
1782    if state.graph != Some(false) {
1783        match graph_token(globals, layers, cfg, state, token_id, position, logits, want_logits) {
1784            crate::gpu::TokenGraphOutcome::Completed => {
1785                if state.graph.is_none() {
1786                    tracing::info!("glm5_next: the stack runs on the card's whole-token graph");
1787                }
1788                state.graph = Some(true);
1789                state.tokens.push(token_id);
1790                if !want_logits {
1791                    logits.clear();
1792                }
1793                state.pos = position + 1;
1794                if prof {
1795                    eprintln!("glm-prof pos={position} total={:.3}s (graph)", token_t0.elapsed().as_secs_f64());
1796                }
1797                return;
1798            }
1799            outcome => {
1800                if state.graph == Some(true) {
1801                    // the card held the sequence: the host replays it from
1802                    // its tokens (past `index_topk`, or a refusal on the way)
1803                    tracing::warn!("glm5_next: the card's graph stopped at position {position} ({outcome:?})");
1804                    host_replay(globals, layers, cfg, state, pool);
1805                } else {
1806                    state.graph = Some(false);
1807                }
1808            }
1809        }
1810    }
1811    // Bring up the native persistent state before any layer touches the
1812    // mixer.  This is a capability/allocation probe only: the exact host
1813    // implementation remains authoritative until a complete GLM chain is
1814    // enabled, and any later cache-growth refusal tears the state down.
1815    state.ensure_gpu_sequence(layers, cfg, position);
1816    let mut emb = vec![0.0f32; cfg.hc.dim];
1817    if (token_id as usize) < globals.embed.rows() {
1818        globals.embed.row_f32(token_id as usize, &mut emb);
1819    }
1820    state.hyper.clear();
1821    for _ in 0..cfg.hc.hc_mult {
1822        state.hyper.extend_from_slice(&emb);
1823    }
1824    let mut scratch = HcScratch::new(&cfg.hc);
1825    let (hyper, mixers, gpu_pool) = (&mut state.hyper, &mut state.mixers, &mut state.gpu_pool);
1826    let profile = glm_cpu_profile_enabled();
1827    for (li, layer) in layers.iter().enumerate() {
1828        crate::gpu::set_layer(li as i64);
1829        let mixer_state = &mut mixers[li];
1830        let attn_t0 = profile.then(std::time::Instant::now);
1831        #[cfg(feature = "gpu")]
1832        let gpu_moe_only = glm_gpu_moe_only_enabled(glm_dynamic_moe_enabled(
1833            std::env::var("CMF_GLM_DYNAMIC_MOE").ok().as_deref(),
1834        ));
1835        #[cfg(not(feature = "gpu"))]
1836        let gpu_moe_only = false;
1837        let mut run_attn = || {
1838            hc_block(
1839                hyper,
1840                &layer.attn_hc.function,
1841                &layer.attn_hc.scale,
1842                &layer.attn_hc.base,
1843                &layer.input_norm,
1844                &cfg.hc,
1845                &mut scratch,
1846                pool,
1847                |x, out| {
1848                    let y = match (&layer.mixer, &mut *mixer_state) {
1849                        (Mixer::Kda(w), MixerState::Kda(st)) => {
1850                            kda_forward(x, w, &cfg.kda, st, pool)
1851                        }
1852                        (Mixer::Dsa(w), MixerState::Dsa(st)) => dsa_forward(x, w, cfg, st, pool),
1853                        _ => unreachable!("GLM mixer state mismatch"),
1854                    };
1855                    out.copy_from_slice(&y);
1856                },
1857            )
1858        };
1859        if gpu_moe_only {
1860            crate::gpu::cpu_scope(run_attn);
1861        } else {
1862            run_attn();
1863        }
1864        let attn_ms = attn_t0.map(|t| t.elapsed().as_secs_f64() * 1e3);
1865        let ffn_t0 = profile.then(std::time::Instant::now);
1866        let mut run_ffn = || {
1867            hc_block(
1868                hyper,
1869                &layer.ffn_hc.function,
1870                &layer.ffn_hc.scale,
1871                &layer.ffn_hc.base,
1872                &layer.post_norm,
1873                &cfg.hc,
1874                &mut scratch,
1875                pool,
1876                |x, out| {
1877                    #[cfg(feature = "gpu")]
1878                    let gpu = dynamic_moe_gpu(layer, li, x, gpu_pool, cfg, layers.len(), pool);
1879                    #[cfg(not(feature = "gpu"))]
1880                    let gpu: Option<Vec<f32>> = None;
1881                    let gpu = gpu.or_else(|| cuda_moe(layer, x, cfg.swiglu_limit, pool));
1882                    let y = gpu.unwrap_or_else(|| ffn_cpu(&layer.ffn, x, cfg.swiglu_limit, pool));
1883                    out.copy_from_slice(&y);
1884                },
1885            )
1886        };
1887        // Keep the MoE frame outside a CPU scope: dynamic_moe_gpu must see
1888        // enabled_here() for its router/projection dispatches.  The HC math
1889        // itself is already scalar CPU work and remains in the closure.
1890        run_ffn();
1891        if let (Some(attn_ms), Some(ffn_ms)) =
1892            (attn_ms, ffn_t0.map(|t| t.elapsed().as_secs_f64() * 1e3))
1893        {
1894            let mixer = match layer.mixer {
1895                Mixer::Kda(_) => "kda",
1896                Mixer::Dsa(_) => "dsa",
1897            };
1898            eprintln!("glm-prof layer={li} mixer={mixer} attn_ms={attn_ms:.3} ffn_ms={ffn_ms:.3}");
1899        }
1900    }
1901    crate::gpu::set_layer(-1);
1902    if want_logits {
1903        let mut hidden = vec![0.0f32; cfg.hc.dim];
1904        for stream in hyper.chunks(cfg.hc.dim) {
1905            for (h, &v) in hidden.iter_mut().zip(stream) {
1906                *h += v / cfg.hc.hc_mult as f32;
1907            }
1908        }
1909        hidden = crate::inference::rms_norm(
1910            &hidden,
1911            &globals.norm,
1912            cfg.eps,
1913            cortiq_core::NormStyle::Qwen,
1914        );
1915        logits.resize(globals.lm_head.rows(), 0.0);
1916        globals.lm_head.matvec(&hidden, logits, pool);
1917    } else {
1918        logits.clear();
1919    }
1920    state.pos = position + 1;
1921    if prof {
1922        eprintln!(
1923            "glm-prof pos={position} total={:.3}s",
1924            token_t0.elapsed().as_secs_f64()
1925        );
1926        #[cfg(feature = "gpu")]
1927        if let Some((enc0, wait0, card0, calls0, fills0, fill_bytes0, submits0, passes0, res0)) =
1928            gpu_before
1929        {
1930            use std::sync::atomic::Ordering;
1931            let enc = crate::gpu_wgpu::MOE_ENC_NS.load(Ordering::Relaxed) - enc0;
1932            let wait = crate::gpu_wgpu::MOE_WAIT_NS.load(Ordering::Relaxed) - wait0;
1933            let card = crate::gpu_wgpu::MOE_GPU_NS[0].load(Ordering::Relaxed) - card0;
1934            let calls = crate::gpu_wgpu::MOE_GPU_N.load(Ordering::Relaxed) - calls0;
1935            let fills = crate::gpu_wgpu::DSV4_FILLS.load(Ordering::Relaxed) - fills0;
1936            let fill_bytes = crate::gpu_wgpu::DSV4_FILL_BYTES.load(Ordering::Relaxed) - fill_bytes0;
1937            let submits = crate::gpu_wgpu::SUBMITS.load(Ordering::Relaxed) - submits0;
1938            let passes = crate::gpu_wgpu::PASSES.load(Ordering::Relaxed) - passes0;
1939            let (hits0, misses0, bytes0, evicts0) = res0;
1940            let (hits, misses, bytes, evicts) = crate::gpu_wgpu::residency_stats();
1941            eprintln!(
1942                "glm-moe-gpu pos={position} calls={calls} fills={fills} fill={:.1}MB \
1943                 encode={:.1}ms wait={:.1}ms card={:.1}ms submits={submits} passes={passes} \
1944                 residency=+{}h/+{}m/{:.1}MB/+{}e",
1945                fill_bytes as f64 / 1e6,
1946                enc as f64 / 1e6,
1947                wait as f64 / 1e6,
1948                card as f64 / 1e6,
1949                hits.saturating_sub(hits0),
1950                misses.saturating_sub(misses0),
1951                bytes.saturating_sub(bytes0) as f64 / 1e6,
1952                evicts.saturating_sub(evicts0),
1953            );
1954        }
1955    }
1956}
1957
1958#[cfg(test)]
1959mod tests {
1960    use super::{dsa_select_positions, glm_dynamic_moe_enabled, moe_cpu};
1961    use crate::pipeline::{Act, DenseFfn, MoeFfn};
1962    use crate::qtensor::QTensor;
1963
1964    fn dense(gate: &[f32], up: &[f32], down: &[f32]) -> DenseFfn {
1965        DenseFfn {
1966            gate_proj: QTensor::from_f32(gate.to_vec(), 2, 2),
1967            up_proj: QTensor::from_f32(up.to_vec(), 2, 2),
1968            down_proj: QTensor::from_f32(down.to_vec(), 2, 2),
1969            act: Act::Silu,
1970            down_t: None,
1971            segs: Vec::new(),
1972        }
1973    }
1974
1975    /// Each selected expert must contribute to the routed sum.  Passing the
1976    /// shared output buffer directly to `expert_swiglu` lets `QTensor::matvec`
1977    /// overwrite the prior expert, so this catches the regression with two
1978    /// deliberately different experts.
1979    #[test]
1980    fn glm_moe_accumulates_all_selected_experts() {
1981        let id = [1.0, 0.0, 0.0, 1.0];
1982        let twice = [2.0, 0.0, 0.0, 2.0];
1983        let expert0 = dense(&id, &id, &id);
1984        let expert1 = dense(&twice, &id, &id);
1985        let model = MoeFfn {
1986            router: QTensor::from_f32(vec![0.0; 4], 2, 2),
1987            experts: vec![expert0, expert1],
1988            top_k: 2,
1989            norm_topk_prob: true,
1990            router_sigmoid: true,
1991            sigmoid_denom_eps: 1e-20,
1992            expert_bias: None,
1993            routed_scaling: 1.0,
1994            route_tau: None,
1995            shared: None,
1996            stats: std::cell::RefCell::new(Vec::new()),
1997            act_sq: std::cell::RefCell::new(Vec::new()),
1998            act_rows: std::cell::RefCell::new(Vec::new()),
1999            mask: None,
2000            per_expert_scale: None,
2001            router_input_norm: false,
2002            resonance: None,
2003            grown: Vec::new(),
2004        };
2005        let x = [1.0f32, 2.0];
2006        let actual = moe_cpu(&model, &x, 0.0, None);
2007
2008        let mut expected = vec![0.0f32; 2];
2009        for expert in &model.experts {
2010            let mut one = vec![0.0f32; 2];
2011            crate::dsv4::expert_swiglu(
2012                &x,
2013                &|x, y| expert.gate_proj.matvec(x, y, None),
2014                &|x, y| expert.up_proj.matvec(x, y, None),
2015                &|x, y| expert.down_proj.matvec(x, y, None),
2016                2,
2017                0.5,
2018                0.0,
2019                &mut one,
2020            );
2021            for (dst, src) in expected.iter_mut().zip(one) {
2022                *dst += src;
2023            }
2024        }
2025        for (got, want) in actual.iter().zip(expected) {
2026            assert!((got - want).abs() < 1e-6, "got {got}, want {want}");
2027        }
2028    }
2029
2030    #[test]
2031    fn glm_dynamic_policy_is_dtype_aware() {
2032        // Automatic mode follows the measured faster exact CPU path.  The
2033        // bounded dynamic implementation remains available by explicit
2034        // force, including for Q4 and unsupported/unknown budgets.
2035        assert!(!glm_dynamic_moe_enabled(None));
2036        assert!(!glm_dynamic_moe_enabled(Some("auto")));
2037        assert!(glm_dynamic_moe_enabled(Some("1")));
2038        assert!(!glm_dynamic_moe_enabled(Some("0")));
2039        assert!(!glm_dynamic_moe_enabled(Some("unexpected")));
2040    }
2041
2042    /// The absorbed DSA attention against the expanded one (kv_b over every
2043    /// selected latent, then the per-head softmax): the same heads' outputs.
2044    #[test]
2045    fn dsa_absorbed_matches_the_expanded_form() {
2046        use super::{DsaState, DsaWeights, dsa_absorbed};
2047        use crate::pipeline::MlaWeights;
2048        let (nh, nope, dv, lora, npos) = (3usize, 8usize, 4usize, 16usize, 7usize);
2049        let mut seed = 0x2545_f491u32;
2050        let mut rnd = || {
2051            seed ^= seed << 13;
2052            seed ^= seed >> 17;
2053            seed ^= seed << 5;
2054            (seed as f32 / u32::MAX as f32) - 0.5
2055        };
2056        let kvb: Vec<f32> = (0..nh * (nope + dv) * lora).map(|_| rnd()).collect();
2057        let q: Vec<f32> = (0..nh * nope).map(|_| rnd()).collect();
2058        let latents: Vec<f32> = (0..npos * lora).map(|_| rnd()).collect();
2059        let z = |r: usize, c: usize| QTensor::from_f32(vec![0.0; r * c], r, c);
2060        let w = DsaWeights {
2061            mla: MlaWeights {
2062                q_proj: z(nh * nope, 4),
2063                q_a: None,
2064                q_a_norm: None,
2065                kv_a: z(lora, 4),
2066                kv_a_norm: vec![1.0; lora],
2067                kv_b: QTensor::from_f32(kvb.clone(), nh * (nope + dv), lora),
2068                o_proj: z(4, nh * dv),
2069                nh,
2070                qk_rope: 0,
2071                qk_nope: nope,
2072                v_dim: dv,
2073                lora,
2074                scale: 0.3,
2075                nope: true,
2076            },
2077            index_q: z(1, 4),
2078            index_k: z(1, 4),
2079            index_k_norm: vec![1.0],
2080            index_k_bias: vec![0.0],
2081            index_weights: z(1, 4),
2082            pool_gate: z(1, 4),
2083            pool_ape: vec![0.0],
2084            kvb_f32: std::sync::OnceLock::new(),
2085        };
2086        let st = DsaState { latents: latents.clone(), index_keys: Vec::new(), pool_gates: Vec::new() };
2087        let selected = [5usize, 0, 3, 6];
2088        let got = dsa_absorbed(&q, &w, &st, &selected, None);
2089        let stride = nope + dv;
2090        for h in 0..nh {
2091            let kv: Vec<Vec<f32>> = selected
2092                .iter()
2093                .map(|&p| (0..stride).map(|r| (0..lora).map(|l| kvb[(h * stride + r) * lora + l] * latents[p * lora + l]).sum()).collect())
2094                .collect();
2095            let sc: Vec<f32> = kv.iter().map(|k| (0..nope).map(|d| q[h * nope + d] * k[d]).sum::<f32>() * 0.3).collect();
2096            let mx = sc.iter().copied().fold(f32::NEG_INFINITY, f32::max);
2097            let zs: f32 = sc.iter().map(|&s| (s - mx).exp()).sum();
2098            for d in 0..dv {
2099                let want: f32 = sc.iter().zip(&kv).map(|(&s, k)| (s - mx).exp() / zs * k[nope + d]).sum();
2100                assert!((got[h * dv + d] - want).abs() < 1e-5, "head {h} lane {d}: {} vs {want}", got[h * dv + d]);
2101            }
2102        }
2103    }
2104
2105    #[test]
2106    fn dsa_selector_preserves_topk_order_and_tail() {
2107        // Three complete pools of four plus a visible two-token tail.  The
2108        // first two scores tie; lower pool index must win, and the tail must
2109        // remain after the selected complete pools.
2110        let got = dsa_select_positions(vec![(0, 0.5), (1, 0.5), (2, 0.9)], 14, 4, 8, true);
2111        assert_eq!(got, vec![8, 9, 10, 11, 0, 1, 2, 3, 12, 13]);
2112    }
2113}