Skip to main content

cortiq_engine/
maxwell.rs

1//! Maxwell-V1-Flash (`maxwell_moe`) text runtime.
2//!
3//! Transcribed from the reference `modeling_maxwell_moe.py`, not inferred
4//! from tensor names. The stack:
5//!
6//! * four residual streams with manifold-constrained hyper-connections: each
7//!   sub-layer folds the streams with `pre = σ(·) + eps`, returns its output
8//!   to every stream with `post = 2·σ(·)` and mixes the streams with a
9//!   doubly stochastic matrix (a row softmax and 20 Sinkhorn rounds) — the
10//!   DeepSeek-V4 form (`dsv4::hc_split_sinkhorn`), its router's input scaled
11//!   by `1 / (rms + eps)`; a learned sigmoid fold closes the stack;
12//! * GQA (32 heads over 4 KV groups, 128 wide) with a per-head RMSNorm on q
13//!   and k before the rotation (base 2e7), and block-sparse support: a query
14//!   attends to the first 8 blocks of 128 positions, to its own block and
15//!   the 7 before it, and to at most 16 blocks in between that the layer's
16//!   indexer picks for each KV group by the best token score of the block.
17//!   Below 4096 positions that is every position: plain causal attention;
18//! * a dense SwiGLU FFN in the first three layers, then 42 MoE blocks: a
19//!   sigmoid router, 12 of 256 experts chosen with a selection bias, their
20//!   weights the unbiased scores renormalized, plus an ungated shared expert
21//!   twice as wide.
22//!
23//! The converter is `cortiq-cli/src/maxwellpack.rs`; the MTP layer of the
24//! checkpoint is not converted.
25
26use crate::dsv4::{hc_expand, hc_fold, hc_split_sinkhorn};
27use crate::loader::{Overlay, load_f32, load_matrix};
28use crate::pool::Pool;
29use crate::qtensor::QTensor;
30use cortiq_core::{CmfError, CmfModel, ModelArch, NormStyle};
31use std::sync::Arc;
32
33pub const ARCH_NAME: &str = "maxwell_moe";
34
35fn err(s: impl Into<String>) -> CmfError {
36    CmfError::Parse(format!("maxwell_moe: {}", s.into()))
37}
38
39fn f(model: &CmfModel, name: &str) -> Result<Vec<f32>, CmfError> {
40    load_f32(model, name, &Overlay::None).map_err(err)
41}
42
43fn t(model: &Arc<CmfModel>, name: &str) -> Result<QTensor, CmfError> {
44    load_matrix(model, name, false, &Overlay::None)
45}
46
47#[inline]
48fn sigmoid(x: f32) -> f32 {
49    1.0 / (1.0 + (-x).exp())
50}
51
52fn rms_w(x: &[f32], w: &[f32], eps: f64) -> Vec<f32> {
53    crate::inference::rms_norm(x, w, eps, NormStyle::Qwen)
54}
55
56/// One hyper-connection: `[2·hc + hc², hc·dim]` mapping, its bias and the
57/// three gating factors (pre, post, mix).
58pub struct Hc {
59    pub function: Vec<f32>,
60    pub base: Vec<f32>,
61    pub scale: [f32; 3],
62}
63
64impl Hc {
65    /// The mapping's rows over the flattened streams, scaled by
66    /// `1 / (‖x‖ / √n + eps)` — the reference adds its epsilon to the RMS,
67    /// not under the root.
68    fn mixes(&self, flat: &[f32], eps: f32, pool: Option<&Pool>) -> Vec<f32> {
69        let n = flat.len();
70        let rows = self.base.len();
71        let ms = flat.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / n as f64;
72        let r = (1.0 / (ms.sqrt() + eps as f64)) as f32;
73        let mut out = vec![0f32; rows];
74        let w = &self.function;
75        let work = |i: usize| -> f32 { w[i * n..(i + 1) * n].iter().zip(flat).map(|(a, b)| a * b).sum::<f32>() * r };
76        match pool {
77            Some(p) => {
78                let addr = crate::pool::SendMut::new(out.as_mut_ptr());
79                p.run_rows(rows, &|a, b| {
80                    for i in a..b {
81                        unsafe { *addr.at(i) = work(i) };
82                    }
83                });
84            }
85            None => {
86                for (i, o) in out.iter_mut().enumerate() {
87                    *o = work(i);
88                }
89            }
90        }
91        out
92    }
93
94    /// (pre, post, mix) of the sub-layer.
95    fn split(&self, flat: &[f32], cfg: &Cfg, pool: Option<&Pool>) -> (Vec<f32>, Vec<f32>, Vec<f32>) {
96        let hc = cfg.hc;
97        let m = self.mixes(flat, cfg.hc_eps, pool);
98        let (mut pre, mut post, mut comb) = (vec![0f32; hc], vec![0f32; hc], vec![0f32; hc * hc]);
99        hc_split_sinkhorn(&m, &self.scale, &self.base, hc, cfg.sinkhorn_iters, cfg.hc_eps, &mut pre, &mut post, &mut comb);
100        (pre, post, comb)
101    }
102}
103
104/// The block router: `[groups·id, hidden]` index queries, one `[id, hidden]`
105/// index key shared by the groups, their per-head norms (f32).
106pub struct Indexer {
107    pub q: Vec<f32>,
108    pub k: Vec<f32>,
109    pub q_norm: Vec<f32>,
110    pub k_norm: Vec<f32>,
111}
112
113pub struct Attn {
114    pub q: QTensor,
115    pub k: QTensor,
116    pub v: QTensor,
117    pub o: QTensor,
118    pub q_norm: Vec<f32>,
119    pub k_norm: Vec<f32>,
120    pub indexer: Indexer,
121}
122
123pub struct Moe {
124    /// `[E, hidden]` f32 router and the selection bias.
125    pub router: Vec<f32>,
126    pub bias: Vec<f32>,
127    /// (gate, up, down) of every routed expert and of the shared one.
128    pub experts: Vec<[QTensor; 3]>,
129    pub shared: [QTensor; 3],
130}
131
132pub enum Ffn {
133    Dense { gate: QTensor, up: QTensor, down: QTensor },
134    Moe(Moe),
135}
136
137pub struct Layer {
138    pub attn_hc: Hc,
139    pub ffn_hc: Hc,
140    pub input_norm: Vec<f32>,
141    pub post_norm: Vec<f32>,
142    pub attn: Attn,
143    pub ffn: Ffn,
144}
145
146/// The embedding table, a row a token. The converter stores it f16; read as
147/// a matrix it would be dequantized whole (1.6 GB of f32 in every pipeline
148/// of a server), so its rows are taken straight from the file's mapping.
149pub enum Embed {
150    Half { idx: usize, rows: usize, bf16: bool },
151    Matrix(QTensor),
152}
153
154impl Embed {
155    fn load(model: &Arc<CmfModel>, name: &str) -> Result<Self, CmfError> {
156        let idx = model.tensor_index(name).ok_or_else(|| err(format!("{name} missing")))?;
157        let e = &model.tensors[idx];
158        match e.dtype {
159            cortiq_core::TensorDtype::F16 | cortiq_core::TensorDtype::Bf16 if e.shape.len() == 2 => Ok(Embed::Half { idx, rows: e.shape[0], bf16: e.dtype == cortiq_core::TensorDtype::Bf16 }),
160            _ => Ok(Embed::Matrix(t(model, name)?)),
161        }
162    }
163
164    pub fn rows(&self) -> usize {
165        match self {
166            Embed::Half { rows, .. } => *rows,
167            Embed::Matrix(m) => m.rows(),
168        }
169    }
170
171    /// Row `r` into `out` (`out.len()` wide).
172    pub fn row_f32(&self, model: &CmfModel, r: usize, out: &mut [f32]) {
173        match self {
174            Embed::Half { idx, bf16, .. } => {
175                let bytes = model.entry_bytes(&model.tensors[*idx]);
176                let dim = out.len();
177                for (o, b) in out.iter_mut().zip(bytes[r * dim * 2..(r + 1) * dim * 2].chunks_exact(2)) {
178                    let h = u16::from_le_bytes([b[0], b[1]]);
179                    *o = if *bf16 { cortiq_core::quant::bf16_to_f32(h) } else { cortiq_core::quant::f16_to_f32(h) };
180                }
181            }
182            Embed::Matrix(m) => m.row_f32(r, out),
183        }
184    }
185}
186
187pub struct Globals {
188    /// The checkpoint's multi-token-prediction layer, when the file carries it.
189    pub mtp: Option<Mtp>,
190    pub model: Arc<CmfModel>,
191    pub embed: Embed,
192    pub lm_head: QTensor,
193    pub norm: Vec<f32>,
194    pub head_fn: Vec<f32>,
195    pub head_base: Vec<f32>,
196    pub head_scale: f32,
197}
198
199pub struct Cfg {
200    pub dim: usize,
201    pub hc: usize,
202    pub eps: f64,
203    pub hc_eps: f32,
204    pub sinkhorn_iters: usize,
205    pub nh: usize,
206    pub nkv: usize,
207    pub hd: usize,
208    pub scale: f32,
209    pub invf: Vec<f32>,
210    /// Positions a block holds, the blocks every query sees at the start of
211    /// the context and before itself (its own included), and the blocks the
212    /// indexer adds a KV group.
213    pub block: usize,
214    pub prefix_blocks: usize,
215    pub local_blocks: usize,
216    pub remote_blocks: usize,
217    pub top_k: usize,
218    /// The context cap (`CMF_MAX_SEQ`, 32 768): the positions the card's
219    /// reserve is sized for.
220    pub max_seq: usize,
221}
222
223impl Cfg {
224    /// Positions below which every query attends to its whole past.
225    pub fn dense_range(&self) -> usize {
226        (self.prefix_blocks + self.local_blocks + self.remote_blocks) * self.block
227    }
228}
229
230/// One layer's cache: the rotated keys and the values of every position
231/// (`nkv·hd` each) and the indexer's rotated key (`hd`).
232#[derive(Default)]
233struct LayerState {
234    k: Vec<f32>,
235    v: Vec<f32>,
236    ik: Vec<f32>,
237}
238
239pub struct State {
240    pub pos: usize,
241    pub tokens: Vec<u32>,
242    layers: Vec<LayerState>,
243    /// The sequence's device key (process-unique: a pipeline reuses one model
244    /// for many prompts).
245    sequence_id: u64,
246    /// The sequence runs on the card's graphs: None not tried yet, Some(false)
247    /// the host runs it, Some(true) the card holds its states.
248    graph: Option<bool>,
249    /// Drafting with the MTP layer (`spec_token`).
250    spec: Spec,
251}
252
253/// The speculation's state: the card may hold one row past the confirmed
254/// ones — the draft's, kept until the next token is known.
255#[derive(Default)]
256struct Spec {
257    /// The stack's closing streams of the last confirmed position (`hc·dim`;
258    /// empty: not known, nothing to draft from).
259    streams: Vec<f32>,
260    /// The row after it, already on the card: its token (the draft), its
261    /// folded hidden row (the head runs when the row is taken) and its
262    /// streams.
263    kept: Option<(u32, Vec<f32>, Vec<f32>)>,
264    /// The MTP layer's rows on the card: one contiguous run of positions
265    /// from `mtp_base` (its attention counts positions from there).
266    mtp_base: usize,
267    mtp_rows: usize,
268    /// MTP rows not on the card yet: a position's streams and the token
269    /// after it, in order (a taken draft's position waits for the next pass).
270    pending: Vec<(Vec<f32>, u32)>,
271    /// Verify passes and the drafts they kept.
272    passes: u64,
273    hits: u64,
274    /// Seconds in the MTP layer's host projections, its card call, the
275    /// verify call and the heads.
276    t: [f64; 4],
277}
278
279static NEXT_SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
280
281impl State {
282    pub fn reset(&mut self, n_layers: usize) {
283        if self.graph == Some(true) {
284            crate::gpu::graph_kv_reset(self.kv_id());
285        }
286        if self.spec.mtp_rows > 0 {
287            crate::gpu::graph_kv_reset(self.mtp_kv_id());
288        }
289        self.spec.report();
290        self.spec = Spec::default();
291        self.graph = None;
292        self.sequence_id = NEXT_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
293        self.pos = 0;
294        self.tokens.clear();
295        self.layers = (0..n_layers).map(|_| LayerState::default()).collect();
296    }
297
298    fn kv_id(&self) -> u64 {
299        (1u64 << 60) | self.sequence_id
300    }
301
302    /// The MTP layer's own rows.
303    fn mtp_kv_id(&self) -> u64 {
304        (1u64 << 59) | self.sequence_id
305    }
306}
307
308impl Spec {
309    /// The share of drafts a sequence took, once (`RUST_LOG=info`).
310    fn report(&self) {
311        if self.passes >= 16 {
312            let p = self.passes as f64;
313            tracing::info!(
314                "maxwell_moe: {} of {} drafts taken ({:.0} %); a pass: MTP projections {:.2} ms, MTP layer {:.2} ms, verify {:.2} ms, heads {:.2} ms",
315                self.hits,
316                self.passes,
317                100.0 * self.hits as f64 / p,
318                self.t[0] * 1e3 / p,
319                self.t[1] * 1e3 / p,
320                self.t[2] * 1e3 / p,
321                self.t[3] * 1e3 / p
322            );
323        }
324    }
325}
326
327impl Drop for State {
328    fn drop(&mut self) {
329        self.spec.report();
330        if self.graph == Some(true) {
331            crate::gpu::graph_kv_reset(self.kv_id());
332        }
333        if self.spec.mtp_rows > 0 {
334            crate::gpu::graph_kv_reset(self.mtp_kv_id());
335        }
336    }
337}
338
339pub fn load(model: &Arc<CmfModel>, arch: &ModelArch) -> Result<(Globals, Vec<Layer>, Cfg, State), CmfError> {
340    let prov = model.header.provenance.as_ref().and_then(|p| p.get("maxwell_moe")).ok_or_else(|| err("header has no maxwell_moe record"))?;
341    let c = prov.get("config").ok_or_else(|| err("no config"))?;
342    let u = |k: &str| -> Result<usize, CmfError> { c.get(k).and_then(|v| v.as_u64()).map(|v| v as usize).ok_or_else(|| err(format!("config.{k}"))) };
343    let (nh, nkv, hd) = (arch.num_attention_heads, arch.num_kv_heads, arch.head_dim);
344    if nkv == 0 || nh % nkv != 0 || hd % 2 != 0 {
345        return Err(err(format!("attention geometry {nh}/{nkv} x {hd}")));
346    }
347    let block = u("block_sparse_gqa_block_size")?;
348    let moe = arch.moe.as_ref().ok_or_else(|| err("missing MoE geometry"))?;
349    let cfg = Cfg {
350        dim: arch.hidden_size,
351        hc: u("num_residual_streams")?,
352        eps: arch.rms_norm_eps,
353        hc_eps: 1e-6,
354        sinkhorn_iters: u("mhc_sinkhorn_iterations")?,
355        nh,
356        nkv,
357        hd,
358        scale: (hd as f32).sqrt().recip(),
359        invf: (0..hd / 2).map(|i| (1.0 / arch.rope_theta.powf(2.0 * i as f64 / hd as f64)) as f32).collect(),
360        block,
361        prefix_blocks: u("block_sparse_gqa_prefix_window_size")? / block.max(1),
362        local_blocks: u("block_sparse_gqa_local_window_size")? / block.max(1),
363        remote_blocks: u("block_sparse_gqa_num_remote_blocks")?,
364        top_k: moe.top_k,
365        max_seq: crate::gpu::context_cap(model),
366    };
367    if block == 0 || cfg.prefix_blocks == 0 || cfg.local_blocks == 0 || !(1..=4).contains(&cfg.hc) {
368        return Err(err("block-sparse geometry"));
369    }
370    let hs = f(model, "model.hc_head.scale")?;
371    let mut globals = Globals {
372        mtp: None,
373        model: model.clone(),
374        embed: Embed::load(model, "model.embed_tokens.weight")?,
375        lm_head: t(model, "lm_head.weight")?,
376        norm: f(model, "model.norm.weight")?,
377        head_fn: f(model, "model.hc_head.fn")?,
378        head_base: f(model, "model.hc_head.base")?,
379        head_scale: *hs.first().ok_or_else(|| err("hc_head.scale"))?,
380    };
381    let mut layers = Vec::with_capacity(arch.num_layers);
382    for li in 0..arch.num_layers {
383        layers.push(load_layer(model, &format!("model.layers.{li}."), &cfg, moe.num_experts, true)?);
384    }
385    globals.mtp = load_mtp(model, &cfg, moe.num_experts)?;
386    if let (Some(m), true) = (&globals.mtp, spec_mode() != 0) {
387        // the MTP layer's weights go on the card after the stack's: the stack's plan leaves them room
388        crate::gpu::plan_extra_reserve(model.uid(), m.bytes + m.bytes / 8 + (64 << 20));
389    }
390    // wgpu: the rows every position keeps while the attention is dense (f32 keys and values of
391    // the KV groups, a row a layer) and the prompt chunk's rows, beside the weights. At the
392    // backend's plain reserve a 24 GB card holding the 4-bit file ran out of memory on a
393    // 2048-token prompt.
394    let rows = cfg.dense_range() + cfg.dense_range() / 8;
395    let mirrors = (rows * layers.len() * 2 * cfg.nkv * cfg.hd * 4) as u64;
396    crate::gpu::wgpu_reserve_at_least(mirrors + (2u64 << 30));
397    // — but not below the weights themselves: the stack takes no device prefix, so a card
398    // that could hold them and is told to keep less runs every token on the host (a 24 GB
399    // card under the 4-bit file: 19.3 GB resident, prompts of 3 000 tokens beside them).
400    // The embedding stays on the host, and the MTP layer drafts on CUDA only.
401    let emb = model.tensor("model.embed_tokens.weight").map_or(0, |e| e.nbytes as u64);
402    let on_card: u64 = model.tensors.iter().filter(|e| !e.name.starts_with("mtp.")).map(|e| e.nbytes as u64).sum::<u64>().saturating_sub(emb);
403    crate::gpu::wgpu_keep_at_least(on_card + on_card / 40 + (64 << 20));
404    // its mirrors (f32 keys and values of the KV groups and the index key, 207 KB a position)
405    // grow a block of 1024 positions at a time, not to the next power of two
406    crate::gpu::wgpu_kv_step(1024);
407    let mut state = State { pos: 0, tokens: Vec::new(), layers: Vec::new(), sequence_id: 0, graph: None, spec: Spec::default() };
408    state.reset(layers.len());
409    Ok((globals, layers, cfg, state))
410}
411
412/// One decoder layer by its name prefix; `indexed`: with the attention's block
413/// indexer (the MTP layer's attention is plain GQA and has none).
414fn load_layer(model: &Arc<CmfModel>, p: &str, cfg: &Cfg, n_exp: usize, indexed: bool) -> Result<Layer, CmfError> {
415    let (nh, nkv, hd) = (cfg.nh, cfg.nkv, cfg.hd);
416    let mix = 2 * cfg.hc + cfg.hc * cfg.hc;
417    let hc_of = |kind: &str| -> Result<Hc, CmfError> {
418        let s = f(model, &format!("{p}{kind}.scale"))?;
419        let h = Hc { function: f(model, &format!("{p}{kind}.fn"))?, base: f(model, &format!("{p}{kind}.base"))?, scale: [s.first().copied().unwrap_or(0.0), s.get(1).copied().unwrap_or(0.0), s.get(2).copied().unwrap_or(0.0)] };
420        if s.len() != 3 || h.base.len() != mix || h.function.len() != mix * cfg.hc * cfg.dim {
421            return Err(err(format!("{p}{kind}: shape")));
422        }
423        Ok(h)
424    };
425    let a = format!("{p}self_attn.");
426    let ix = |n: &str| -> Result<Vec<f32>, CmfError> { if indexed { f(model, &format!("{a}indexer.{n}")) } else { Ok(Vec::new()) } };
427    let attn = Attn {
428        q: t(model, &format!("{a}q_proj.weight"))?,
429        k: t(model, &format!("{a}k_proj.weight"))?,
430        v: t(model, &format!("{a}v_proj.weight"))?,
431        o: t(model, &format!("{a}o_proj.weight"))?,
432        q_norm: f(model, &format!("{a}q_norm.weight"))?,
433        k_norm: f(model, &format!("{a}k_norm.weight"))?,
434        indexer: Indexer { q: ix("q_proj.weight")?, k: ix("k_proj.weight")?, q_norm: ix("q_norm.weight")?, k_norm: ix("k_norm.weight")? },
435    };
436    if attn.q.rows() != nh * hd || attn.k.rows() != nkv * hd || attn.v.rows() != nkv * hd || (indexed && (attn.indexer.q.len() != nkv * hd * cfg.dim || attn.indexer.k.len() != hd * cfg.dim)) {
437        return Err(err(format!("{p}: attention shapes")));
438    }
439    let m = format!("{p}mlp.");
440    let ffn = if model.tensor(&format!("{m}gate.weight")).is_none() {
441        Ffn::Dense { gate: t(model, &format!("{m}gate_proj.weight"))?, up: t(model, &format!("{m}up_proj.weight"))?, down: t(model, &format!("{m}down_proj.weight"))? }
442    } else {
443        let mut experts = Vec::with_capacity(n_exp);
444        for e in 0..n_exp {
445            let x = format!("{m}experts.{e}.");
446            experts.push([t(model, &format!("{x}gate_proj.weight"))?, t(model, &format!("{x}up_proj.weight"))?, t(model, &format!("{x}down_proj.weight"))?]);
447        }
448        let mo = Moe {
449            router: f(model, &format!("{m}gate.weight"))?,
450            bias: f(model, &format!("{m}gate.e_score_correction_bias"))?,
451            experts,
452            shared: [
453                t(model, &format!("{m}shared_experts.gate_proj.weight"))?,
454                t(model, &format!("{m}shared_experts.up_proj.weight"))?,
455                t(model, &format!("{m}shared_experts.down_proj.weight"))?,
456            ],
457        };
458        if mo.bias.len() != n_exp || mo.router.len() != n_exp * cfg.dim {
459            return Err(err(format!("{p}: router shapes")));
460        }
461        Ffn::Moe(mo)
462    };
463    Ok(Layer {
464        attn_hc: hc_of("attn_hc")?,
465        ffn_hc: hc_of("ffn_hc")?,
466        input_norm: f(model, &format!("{p}input_layernorm.weight"))?,
467        post_norm: f(model, &format!("{p}post_attention_layernorm.weight"))?,
468        attn,
469        ffn,
470    })
471}
472
473/// The checkpoint's multi-token-prediction layer (`mtp.0.*`): at position `i`
474/// it takes the stack's streams and the embedding of token `i + 1` —
475/// `stream_s = e_proj(enorm(emb)) + h_proj(hnorm(stream_s))` — through one
476/// decoder layer (plain GQA over its own rows, a routed FFN), its own closing
477/// fold and final norm, and the model's head: token `i + 2`. The card drafts
478/// with it (`spec_token`).
479pub struct Mtp {
480    pub enorm: Vec<f32>,
481    pub hnorm: Vec<f32>,
482    pub e_proj: QTensor,
483    pub h_proj: QTensor,
484    pub layer: Layer,
485    pub head_fn: Vec<f32>,
486    pub head_base: Vec<f32>,
487    pub head_scale: f32,
488    pub final_norm: Vec<f32>,
489    /// Bytes of its tensors (the room the card keeps for them).
490    pub bytes: u64,
491}
492
493fn load_mtp(model: &Arc<CmfModel>, cfg: &Cfg, n_exp: usize) -> Result<Option<Mtp>, CmfError> {
494    if model.tensor("mtp.0.e_proj.weight").is_none() {
495        return Ok(None);
496    }
497    let hs = f(model, "mtp.0.hc_head.scale")?;
498    let m = Mtp {
499        enorm: f(model, "mtp.0.enorm.weight")?,
500        hnorm: f(model, "mtp.0.hnorm.weight")?,
501        e_proj: t(model, "mtp.0.e_proj.weight")?,
502        h_proj: t(model, "mtp.0.h_proj.weight")?,
503        layer: load_layer(model, "mtp.0.layer.", cfg, n_exp, false)?,
504        head_fn: f(model, "mtp.0.hc_head.fn")?,
505        head_base: f(model, "mtp.0.hc_head.base")?,
506        head_scale: *hs.first().ok_or_else(|| err("mtp.0.hc_head.scale"))?,
507        final_norm: f(model, "mtp.0.final_norm.weight")?,
508        bytes: model.tensors.iter().filter(|e| e.name.starts_with("mtp.")).map(|e| e.nbytes).sum(),
509    };
510    if m.enorm.len() != cfg.dim || m.hnorm.len() != cfg.dim || m.final_norm.len() != cfg.dim || m.e_proj.rows() != cfg.dim || m.h_proj.rows() != cfg.dim || m.head_fn.len() != cfg.hc * cfg.hc * cfg.dim || matches!(m.layer.ffn, Ffn::Dense { .. }) {
511        return Err(err("mtp.0: shapes"));
512    }
513    Ok(Some(m))
514}
515
516/// Per-head RMS norm with one weight vector shared by the heads.
517fn norm_heads(x: &mut [f32], w: &[f32], hd: usize, eps: f64) {
518    for h in x.chunks_mut(hd) {
519        let ms = h.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / hd as f64;
520        let r = (1.0 / (ms + eps).sqrt()) as f32;
521        for (v, &g) in h.iter_mut().zip(w) {
522            *v = *v * r * g;
523        }
524    }
525}
526
527fn rope_heads(x: &mut [f32], invf: &[f32], hd: usize, pos: usize) {
528    for h in x.chunks_mut(hd) {
529        crate::hy4::rope_half(h, invf, pos);
530    }
531}
532
533/// The blocks position `pos` attends to in every KV group, ascending: the
534/// prefix, its own block and the ones before it, and — once the blocks in
535/// between outnumber `remote_blocks` — the best of those by `score(group,
536/// block)`, the block's largest token score (ties to the lower block).
537pub fn route_blocks(pos: usize, cfg: &Cfg, groups: usize, mut score: impl FnMut(usize, usize) -> f32) -> Vec<Vec<usize>> {
538    let cur = pos / cfg.block;
539    let local0 = (cur + 1).saturating_sub(cfg.local_blocks);
540    let mut fixed: Vec<usize> = (0..cfg.prefix_blocks.min(cur + 1)).collect();
541    fixed.extend((local0.max(cfg.prefix_blocks)..=cur).filter(|b| *b >= cfg.prefix_blocks));
542    // the blocks in between: wholly past the prefix and wholly before the local window
543    let between: Vec<usize> = (cfg.prefix_blocks..local0).collect();
544    (0..groups)
545        .map(|g| {
546            let mut sel = fixed.clone();
547            if between.len() <= cfg.remote_blocks {
548                sel.extend(&between);
549            } else {
550                let mut scored: Vec<(usize, f32)> = between.iter().map(|&b| (b, score(g, b))).collect();
551                scored.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal).then(a.0.cmp(&b.0)));
552                sel.extend(scored[..cfg.remote_blocks].iter().map(|s| s.0));
553            }
554            sel.sort_unstable();
555            sel
556        })
557        .collect()
558}
559
560impl Attn {
561    /// One position: its rows into the cache, the block route, the attention
562    /// over the routed positions, the O projection.
563    fn forward(&self, x: &[f32], ls: &mut LayerState, pos: usize, cfg: &Cfg, pool: Option<&Pool>) -> Vec<f32> {
564        let (nh, nkv, hd, dim) = (cfg.nh, cfg.nkv, cfg.hd, cfg.dim);
565        let per = nh / nkv;
566        let mut q = vec![0f32; nh * hd];
567        let mut k = vec![0f32; nkv * hd];
568        let mut v = vec![0f32; nkv * hd];
569        cap(0, x, |li| ["q", "k", "v"].iter().map(|m| format!("model.layers.{li}.self_attn.{m}_proj.weight")).collect());
570        self.q.matvec(x, &mut q, pool);
571        self.k.matvec(x, &mut k, pool);
572        self.v.matvec(x, &mut v, pool);
573        norm_heads(&mut q, &self.q_norm, hd, cfg.eps);
574        norm_heads(&mut k, &self.k_norm, hd, cfg.eps);
575        rope_heads(&mut q, &cfg.invf, hd, pos);
576        rope_heads(&mut k, &cfg.invf, hd, pos);
577        ls.k.extend_from_slice(&k);
578        ls.v.extend_from_slice(&v);
579        // the indexer's key of this position (every position keeps one: a later query may need it)
580        let ix = &self.indexer;
581        let mut ik = vec![0f32; hd];
582        crate::pool::matvec_rows(pool, &ix.k, x, &mut ik);
583        norm_heads(&mut ik, &ix.k_norm, hd, cfg.eps);
584        rope_heads(&mut ik, &cfg.invf, hd, pos);
585        ls.ik.extend_from_slice(&ik);
586        debug_assert_eq!(ls.k.len(), (pos + 1) * nkv * hd);
587
588        let sparse = pos >= cfg.dense_range();
589        let routes: Vec<Vec<usize>> = if sparse {
590            let mut iq = vec![0f32; nkv * hd];
591            crate::pool::matvec_rows(pool, &ix.q, x, &mut iq);
592            norm_heads(&mut iq, &ix.q_norm, hd, cfg.eps);
593            rope_heads(&mut iq, &cfg.invf, hd, pos);
594            // the best token score of every candidate block, a group at a time
595            let cur = pos / cfg.block;
596            let local0 = (cur + 1).saturating_sub(cfg.local_blocks);
597            let (b0, b1) = (cfg.prefix_blocks, local0);
598            let nb = b1 - b0;
599            let mut best = vec![f32::NEG_INFINITY; nkv * nb];
600            let keys = &ls.ik;
601            let block = cfg.block;
602            let work = |i: usize, out: &mut f32| {
603                let (g, b) = (i / nb, b0 + i % nb);
604                let qg = &iq[g * hd..(g + 1) * hd];
605                let mut mx = f32::NEG_INFINITY;
606                for tpos in b * block..(b + 1) * block {
607                    let s: f32 = keys[tpos * hd..(tpos + 1) * hd].iter().zip(qg).map(|(a, b)| a * b).sum();
608                    mx = mx.max(s);
609                }
610                *out = mx;
611            };
612            match pool {
613                Some(p) => {
614                    let addr = crate::pool::SendMut::new(best.as_mut_ptr());
615                    p.run_rows(nkv * nb, &|a, b| {
616                        for i in a..b {
617                            work(i, unsafe { &mut *addr.at(i) });
618                        }
619                    });
620                }
621                None => {
622                    for (i, o) in best.iter_mut().enumerate() {
623                        work(i, o);
624                    }
625                }
626            }
627            route_blocks(pos, cfg, nkv, |g, b| best[g * nb + (b - b0)])
628        } else {
629            Vec::new()
630        };
631
632        let mut out = vec![0f32; nh * hd];
633        let (kc, vc) = (&ls.k, &ls.v);
634        let scale = cfg.scale;
635        let block = cfg.block;
636        let head = |h: usize, o: &mut [f32]| {
637            let g = h / per;
638            let qh = &q[h * hd..(h + 1) * hd];
639            let mut scores: Vec<(usize, f32)> = Vec::new();
640            let mut push = |tpos: usize| {
641                let kr = &kc[(tpos * nkv + g) * hd..(tpos * nkv + g + 1) * hd];
642                scores.push((tpos, kr.iter().zip(qh).map(|(a, b)| a * b).sum::<f32>() * scale));
643            };
644            if sparse {
645                for &b in &routes[g] {
646                    for tpos in b * block..((b + 1) * block).min(pos + 1) {
647                        push(tpos);
648                    }
649                }
650            } else {
651                for tpos in 0..=pos {
652                    push(tpos);
653                }
654            }
655            let mx = scores.iter().fold(f32::NEG_INFINITY, |a, s| a.max(s.1));
656            let mut den = 0f64;
657            for s in scores.iter_mut() {
658                s.1 = (s.1 - mx).exp();
659                den += s.1 as f64;
660            }
661            let inv = (1.0 / den) as f32;
662            for &(tpos, w) in &scores {
663                let vr = &vc[(tpos * nkv + g) * hd..(tpos * nkv + g + 1) * hd];
664                let w = w * inv;
665                for (a, b) in o.iter_mut().zip(vr) {
666                    *a += w * b;
667                }
668            }
669        };
670        match pool {
671            Some(p) => {
672                let addr = crate::pool::SendMut::new(out.as_mut_ptr());
673                p.run_rows(nh, &|a, b| {
674                    for h in a..b {
675                        head(h, unsafe { std::slice::from_raw_parts_mut(addr.at(h * hd), hd) });
676                    }
677                });
678            }
679            None => {
680                for (h, o) in out.chunks_mut(hd).enumerate() {
681                    head(h, o);
682                }
683            }
684        }
685        cap(1, &out, |li| vec![format!("model.layers.{li}.self_attn.o_proj.weight")]);
686        let mut y = vec![0f32; dim];
687        self.o.matvec(&out, &mut y, pool);
688        y
689    }
690}
691
692// ---------------------------------------------------------------- calibration capture
693//
694// A GPTQ pass over the dense trunk (`cortiq requant --quant q4tp-dense --calib`): while
695// `gptq_capture` is on, the host stack folds the inputs of the attention projections, the
696// dense FFNs and the shared experts into their Hessians. The stack runs a row a token, and a
697// rank-1 update a token streams a whole Hessian (16.8 M entries for the O projection's 4096
698// inputs), so the rows wait in a panel and fold `CAP_ROWS` at a time, one blocked XᵀX.
699
700const CAP_ROWS: usize = 64;
701
702struct CapPanel {
703    /// The matrices that read this panel; the first owns the Hessian, the others alias it.
704    names: Vec<String>,
705    cols: usize,
706    rows: Vec<f32>,
707}
708
709thread_local! {
710    static CAP_LAYER: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
711}
712static CAP: std::sync::Mutex<Vec<((usize, u8), CapPanel)>> = std::sync::Mutex::new(Vec::new());
713
714fn cap_fold(p: &mut CapPanel) {
715    let b = p.rows.len() / p.cols.max(1);
716    if b > 0 {
717        for n in &p.names {
718            crate::gptq_capture::accumulate(n, &p.rows, b, p.cols);
719        }
720    }
721    p.rows.clear();
722}
723
724/// A row of the current layer's panel `kind` (0 the attention's input, 1 the O projection's,
725/// 2 the FFN's, 3 its down projection's); `names` the matrices that read it.
726fn cap(kind: u8, x: &[f32], names: impl FnOnce(usize) -> Vec<String>) {
727    if !crate::gptq_capture::capturing() {
728        return;
729    }
730    let li = CAP_LAYER.with(|c| c.get());
731    let mut g = CAP.lock().unwrap();
732    let at = match g.iter().position(|(k, _)| *k == (li, kind)) {
733        Some(i) => i,
734        None => {
735            g.push(((li, kind), CapPanel { names: names(li), cols: x.len(), rows: Vec::new() }));
736            g.len() - 1
737        }
738    };
739    let p = &mut g[at].1;
740    if p.cols != x.len() {
741        return;
742    }
743    p.rows.extend_from_slice(x);
744    if p.rows.len() >= CAP_ROWS * p.cols {
745        cap_fold(p);
746    }
747}
748
749/// The rows still waiting in the panels into their Hessians: the end of a calibration pass,
750/// before `gptq_capture::end`.
751pub fn capture_flush() {
752    let mut g = CAP.lock().unwrap();
753    for (_, p) in g.iter_mut() {
754        cap_fold(p);
755    }
756    g.clear();
757}
758
759fn swiglu(g: &mut [f32], u: &[f32]) {
760    for (a, &b) in g.iter_mut().zip(u) {
761        *a = *a / (1.0 + (-*a).exp()) * b;
762    }
763}
764
765/// `tag`: the block's name under its layer for a calibration capture (`mlp.` a dense FFN,
766/// `mlp.shared_experts.` a shared expert); None for a routed expert, which no pass captures.
767fn dense(gate: &QTensor, up: &QTensor, down: &QTensor, x: &[f32], pool: Option<&Pool>, tag: Option<&str>) -> Vec<f32> {
768    let mut g = vec![0f32; gate.rows()];
769    let mut u = vec![0f32; up.rows()];
770    if let Some(t) = tag {
771        cap(2, x, |li| vec![format!("model.layers.{li}.{t}gate_proj.weight"), format!("model.layers.{li}.{t}up_proj.weight")]);
772    }
773    gate.matvec(x, &mut g, pool);
774    up.matvec(x, &mut u, pool);
775    swiglu(&mut g, &u);
776    if let Some(t) = tag {
777        cap(3, &g, |li| vec![format!("model.layers.{li}.{t}down_proj.weight")]);
778    }
779    let mut out = vec![0f32; down.rows()];
780    down.matvec(&g, &mut out, pool);
781    out
782}
783
784impl Moe {
785    /// The selected experts and their mixing weights: the choice by
786    /// `σ(logit) + bias`, the weights the chosen scores over their sum.
787    pub fn route(&self, x: &[f32], cfg: &Cfg, pool: Option<&Pool>) -> Vec<(usize, f32)> {
788        let ne = self.bias.len();
789        let mut logits = vec![0f32; ne];
790        crate::pool::matvec_rows(pool, &self.router, x, &mut logits);
791        route_logits(&logits, &self.bias, cfg.top_k)
792    }
793
794    fn forward(&self, x: &[f32], cfg: &Cfg, pool: Option<&Pool>) -> Vec<f32> {
795        let mut y = dense(&self.shared[0], &self.shared[1], &self.shared[2], x, pool, Some("mlp.shared_experts."));
796        for (e, w) in self.route(x, cfg, pool) {
797            let [g, u, d] = &self.experts[e];
798            let ye = dense(g, u, d, x, pool, None);
799            for (a, v) in y.iter_mut().zip(&ye) {
800                *a += w * v;
801            }
802        }
803        y
804    }
805}
806
807/// Top-k by `σ(logit) + bias` (ties to the lower expert), weights
808/// `σ / (Σσ + 1e-20)` over the chosen ones.
809pub fn route_logits(logits: &[f32], bias: &[f32], top_k: usize) -> Vec<(usize, f32)> {
810    let scores: Vec<f32> = logits.iter().map(|&l| sigmoid(l)).collect();
811    let mut order: Vec<usize> = (0..scores.len()).collect();
812    order.sort_unstable_by(|&a, &b| (scores[b] + bias[b]).partial_cmp(&(scores[a] + bias[a])).unwrap_or(std::cmp::Ordering::Equal).then(a.cmp(&b)));
813    order.truncate(top_k);
814    let sum: f32 = order.iter().map(|&e| scores[e]).sum::<f32>() + 1e-20;
815    order.into_iter().map(|e| (e, scores[e] / sum)).collect()
816}
817
818/// `CMF_MAXWELL_DUMP=<dir>,<pos>,<pos>…`: the host stack writes every layer's
819/// attention output and streams at those positions
820/// (`<dir>/<kind>_l<li>_p<pos>.f32`), for a layer-by-layer diff against the
821/// reference.
822fn dump(li: usize, pos: usize, kind: &str, v: &[f32]) {
823    static CFG: std::sync::OnceLock<Option<(String, Vec<usize>)>> = std::sync::OnceLock::new();
824    let cfg = CFG.get_or_init(|| {
825        let s = std::env::var("CMF_MAXWELL_DUMP").ok()?;
826        let mut it = s.split(',');
827        let dir = it.next()?.to_string();
828        Some((dir, it.filter_map(|p| p.parse().ok()).collect()))
829    });
830    if let Some((dir, ps)) = cfg {
831        if ps.contains(&pos) {
832            let b: Vec<u8> = v.iter().flat_map(|x| x.to_le_bytes()).collect();
833            let _ = std::fs::write(format!("{dir}/{kind}_l{li}_p{pos}.f32"), b);
834        }
835    }
836}
837
838const GRAPH_CAP: usize = 1 << 20;
839
840fn graph_on() -> bool {
841    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
842    *ON.get_or_init(|| std::env::var("CMF_MAXWELL_GRAPH").as_deref() != Ok("0"))
843}
844
845fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
846    if let Some((_, i, kind, rs)) = t.graph_weight_or_blr() {
847        return Some(crate::gpu::GraphW { idx: i, kind, row_scale: rs, data: &[], prism: crate::gpu::GraphPrismOp::None, affine: false });
848    }
849    t.as_f32().map(|d| crate::gpu::GraphW { idx: 0, kind: 4, row_scale: &[], data: d, prism: crate::gpu::GraphPrismOp::None, affine: false })
850}
851
852fn gf(d: &[f32]) -> crate::gpu::GraphW<'_> {
853    crate::gpu::GraphW { idx: 0, kind: 4, row_scale: &[], data: d, prism: crate::gpu::GraphPrismOp::None, affine: false }
854}
855
856/// The stack as graph layers for a call ending at `end` positions (None: a
857/// weight the graphs cannot address, or a call past the dense range on a
858/// backend whose attention has no block router).
859/// Positions a discrete card holds over wgpu beside the weights: the block route keeps f16 keys
860/// and values of the KV groups and the index key of every position, a layer (104 KB a
861/// position over 45 layers, as the CUDA arm), beside a prompt
862/// chunk's scratch and the driver's share (`SCRATCH`). An allocation past the card is a panic
863/// in wgpu.
864/// Rows of a prompt chunk over wgpu: the batch graph keeps every layer's scratch of a call for
865/// the prompt (2 MB a row over 45 layers on an L4), beside the weights and the route's mirrors
866/// of `positions`. A chunk costs about a second whatever its rows (the experts' weights), so
867/// the rows are as many as fit, 512 at most.
868fn wgpu_chunk_rows(cfg: &Cfg, layers: usize, positions: usize) -> usize {
869    let total = crate::gpu::wgpu_card_total();
870    if total == 0 {
871        return 512;
872    }
873    // the driver's share of the card, the call's other buffers, the staging (measured: 45 KB a
874    // row a layer)
875    const KEEP: u64 = 2560 << 20;
876    let mirrors = (positions + 2048) as u64 * crate::gpu::wgpu_route_position_bytes(layers, cfg.nkv, cfg.hd);
877    let room = total.saturating_sub(crate::gpu::resident_bytes()).saturating_sub(mirrors).saturating_sub(KEEP);
878    let per_row = (layers as u64) * 50 * 1024;
879    ((room / per_row.max(1)) as usize / 32 * 32).clamp(32, 512)
880}
881
882fn wgpu_rows(cfg: &Cfg, layers: usize) -> usize {
883    // `CMF_MAXWELL_WGPU_ROWS=<n>`: the positions to allow (measuring what a position costs)
884    if let Some(n) = std::env::var("CMF_MAXWELL_WGPU_ROWS").ok().and_then(|v| v.parse::<usize>().ok()) {
885        return n;
886    }
887    let total = crate::gpu::wgpu_card_total();
888    if total == 0 {
889        return usize::MAX;
890    }
891    const SCRATCH: u64 = 2560 << 20;
892    let per = crate::gpu::wgpu_route_position_bytes(layers, cfg.nkv, cfg.hd).max(1);
893    let room = total.saturating_sub(crate::gpu::vram_budget()).saturating_sub(SCRATCH);
894    (room / per) as usize
895}
896
897fn graph_layers<'a>(globals: &'a Globals, layers: &'a [Layer], cfg: &'a Cfg, end: usize) -> Option<Vec<crate::gpu::GraphLayer<'a>>> {
898    // the rows the card keeps room for: the cap, or on CUDA with no cap named the rows that fit
899    // beside weights that stay on the card whole
900    let kept = match crate::gpu::route_rows() {
901        0 => cfg.max_seq,
902        r => r.min(cfg.max_seq),
903    };
904    if end > kept {
905        static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
906        if !SAID.swap(true, std::sync::atomic::Ordering::Relaxed) {
907            tracing::warn!(
908                "maxwell_moe: {end} positions, past the {kept} the card keeps room for: later rows may leave it for the \
909                 host. Set CMF_MAX_SEQ to the context you need (the routed experts stream to make room)."
910            );
911        }
912    }
913    let routed = end > cfg.dense_range();
914    if routed && !crate::gpu::block_route_on() {
915        static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
916        if !SAID.swap(true, std::sync::atomic::Ordering::Relaxed) {
917            tracing::warn!(
918                "maxwell_moe: past {} positions the attention picks its blocks, which this backend's graphs do not do; \
919                 the sequence continues on the host (the CUDA backend, CMF_GPU=cuda, keeps it on the card)",
920                cfg.dense_range()
921            );
922        }
923        return None;
924    }
925    if crate::gpu::wgpu_active() {
926        let rows = wgpu_rows(cfg, layers.len());
927        static TOLD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
928        if !TOLD.swap(true, std::sync::atomic::Ordering::Relaxed) {
929            tracing::info!("maxwell_moe: beside the weights this card holds {rows} positions over wgpu");
930        }
931        if end > rows {
932            static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
933            if !SAID.swap(true, std::sync::atomic::Ordering::Relaxed) {
934                tracing::warn!(
935                    "maxwell_moe: beside the weights this card holds {rows} positions over wgpu; the sequence continues on the \
936                     host (the CUDA backend, CMF_GPU=cuda, streams the experts and keeps a longer context on the card)"
937                );
938            }
939            return None;
940        }
941    }
942    let last = layers.len().checked_sub(1)?;
943    // The block route rides the layer's own geometry, on the CUDA hybrid and on the wgpu
944    // graphs (their per-layer-geometry arm, `gpu_wgpu::broute`). `CMF_MAXWELL_GEOM=0` puts the
945    // wgpu graphs back on the call-wide geometry (the dense range only).
946    let own_geom = crate::gpu::cuda_active() || std::env::var("CMF_MAXWELL_GEOM").as_deref() != Ok("0");
947    let mut out = Vec::with_capacity(layers.len());
948    for (li, l) in layers.iter().enumerate() {
949        let head = (li == last).then_some((&globals.head_fn[..], &globals.head_base[..], globals.head_scale));
950        out.push(graph_layer(l, cfg, own_geom, li == 0, li == last, head)?);
951    }
952    Some(out)
953}
954
955/// One layer for the card's graphs. `route`: its attention carries the block
956/// route on the layer's own geometry (the main stack on CUDA); `enter` /
957/// `leave`: it opens / closes the hyper-connection range, `head` the closing
958/// fold's weights.
959fn graph_layer<'a>(l: &'a Layer, cfg: &'a Cfg, route: bool, enter: bool, leave: bool, head: Option<(&'a [f32], &'a [f32], f32)>) -> Option<crate::gpu::GraphLayer<'a>> {
960    use crate::gpu::{GraphAct, GraphAttn, GraphAttnGeom, GraphBlockRoute, GraphFfn, GraphLayer, GraphMhc, GraphMhcDsv4, GraphMhcHead, GraphMoeDetachedShared};
961    let a = &l.attn;
962    let ix = &a.indexer;
963    let attn = GraphAttn::Full {
964        wq: gw(&a.q)?,
965        wk: gw(&a.k)?,
966        wv: gw(&a.v)?,
967        wo: gw(&a.o)?,
968        q_norm: Some(&a.q_norm),
969        k_norm: Some(&a.k_norm),
970        late_qk_norm: false,
971        bias: None,
972        output_gate: false,
973        cpu_k: &[],
974        cpu_v: &[],
975        cpu_base: 0,
976        geom: route.then_some(GraphAttnGeom {
977            nkv: cfg.nkv,
978            hd: cfg.hd,
979            dv: cfg.hd,
980            rd: cfg.hd,
981            invf: &cfg.invf,
982            rope_scale: 1.0,
983            window: None,
984            sink: None,
985            v_norm: false,
986            dash: None,
987            vres: None,
988            route: Some(GraphBlockRoute {
989                q: &ix.q,
990                k: &ix.k,
991                q_norm: &ix.q_norm,
992                k_norm: &ix.k_norm,
993                block: cfg.block,
994                prefix: cfg.prefix_blocks,
995                local: cfg.local_blocks,
996                remote: cfg.remote_blocks,
997            }),
998        }),
999        head_gate: None,
1000    };
1001    let ffn = match &l.ffn {
1002        Ffn::Dense { gate, up, down } => GraphFfn::Dense { gate: gw(gate)?, up: gw(up)?, down: gw(down)?, act: GraphAct::Silu, limit: 0.0, hot: None },
1003        Ffn::Moe(m) => {
1004            let e0 = m.experts.first()?;
1005            let q82 = e0[0].mapped_q8_2f().is_some();
1006            let gu_q2 = e0[0].mapped_q2tp().is_some();
1007            let uniform = m.experts.iter().all(|[g, u, d]| {
1008                if q82 {
1009                    g.mapped_q8_2f().is_some() && u.mapped_q8_2f().is_some() && d.mapped_q8_2f().is_some()
1010                } else if gu_q2 {
1011                    g.mapped_q2tp().is_some() && u.mapped_q2tp().is_some() && d.mapped_q4tp().is_some()
1012                } else {
1013                    g.mapped_q4tp().is_some() && u.mapped_q4tp().is_some() && d.mapped_q4tp().is_some()
1014                }
1015            });
1016            if !uniform {
1017                return None;
1018            }
1019            let experts = m.experts.iter().map(|[g, u, d]| Some((g.model_idx()?, u.model_idx()?, d.model_idx()?))).collect::<Option<Vec<_>>>()?;
1020            GraphFfn::Moe {
1021                router: gf(&m.router),
1022                shared_gate: gf(&m.router),
1023                experts,
1024                n_exp: m.experts.len(),
1025                top_k: cfg.top_k,
1026                inter: e0[0].rows(),
1027                act: GraphAct::Silu,
1028                norm_topk: true,
1029                q4tp: !q82,
1030                gu_q2,
1031                q82,
1032                sigmoid: true,
1033                sigmoid_denom_eps: 1e-20,
1034                bias: Some(&m.bias),
1035                has_shared: false,
1036                detached_shared: Some(GraphMoeDetachedShared { gate: gw(&m.shared[0])?, up: gw(&m.shared[1])?, down: gw(&m.shared[2])?, width: m.shared[0].rows() }),
1037                shared_gated: false,
1038                route_scale: 1.0,
1039                limit: 0.0,
1040                shared_limit: None,
1041                latent: None,
1042            }
1043        }
1044    };
1045    Some(GraphLayer {
1046        mhc: Some(GraphMhc {
1047            attn_w: &l.attn_hc.function,
1048            attn_b: &l.attn_hc.base,
1049            ffn_w: &l.ffn_hc.function,
1050            ffn_b: &l.ffn_hc.base,
1051            enter,
1052            leave,
1053            iters: cfg.sinkhorn_iters,
1054            pre_scale: 1.0,
1055            // a negative RMS epsilon: added to the RMS itself (`Hc::mixes`)
1056            dsv4: Some(GraphMhcDsv4 { attn_scale: l.attn_hc.scale, ffn_scale: l.ffn_hc.scale, eps: cfg.hc_eps, rms_eps: -cfg.hc_eps, ihc: None }),
1057            head: head.map(|(w, base, scale)| GraphMhcHead { w, base, scale }),
1058        }),
1059        input_norm: &l.input_norm,
1060        attn,
1061        post_norm: &l.post_norm,
1062        ffn,
1063        attn_out_norm: None,
1064        ffn_out_norm: None,
1065        layer_scale: None,
1066        engram: None,
1067    })
1068}
1069
1070/// The widest FFN of the stack (the graphs' scratch width).
1071fn graph_inter(layers: &[Layer]) -> usize {
1072    layers
1073        .iter()
1074        .map(|l| match &l.ffn {
1075            Ffn::Dense { gate, .. } => gate.rows(),
1076            Ffn::Moe(m) => m.experts.first().map_or(0, |e| e[0].rows()).max(m.shared[0].rows()),
1077        })
1078        .max()
1079        .unwrap_or(0)
1080}
1081
1082/// The host takes the sequence over from the card: its tokens replayed
1083/// through the host stack.
1084fn host_replay(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, pool: Option<&Pool>) {
1085    let toks = std::mem::take(&mut state.tokens);
1086    tracing::warn!("maxwell_moe: the host replays {} tokens the card held", toks.len());
1087    state.reset(layers.len());
1088    state.graph = Some(false);
1089    let mut scratch = Vec::new();
1090    for (p, &tk) in toks.iter().enumerate() {
1091        host_token(globals, layers, cfg, state, tk, p, pool, &mut scratch, false);
1092    }
1093}
1094
1095/// A prompt's positions `start..` through the card's batch graph (the rows in
1096/// chunks), its last one through the token graph with the logits. Returns
1097/// the positions taken (0: none, the caller goes a token at a time).
1098#[allow(clippy::too_many_arguments)]
1099pub fn forward_prompt(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, ids: &[u32], start: usize, pool: Option<&Pool>, logits: &mut Vec<f32>) -> usize {
1100    if ids.len() < 2 {
1101        return 0;
1102    }
1103    let body = ids.len() - 1;
1104    let done = prompt_rows(globals, layers, cfg, state, &ids[..body], start, pool, None);
1105    if done < body {
1106        return done;
1107    }
1108    forward_token(globals, layers, cfg, state, ids[body], start + body, pool, logits, true);
1109    ids.len()
1110}
1111
1112/// `ids` from `start` on through the card's prompt graph, a chunk a call
1113/// (`CMF_MAXWELL_PROMPT_CHUNK`, 512; halved down to 16 when the card
1114/// declines a chunk); with `keep`, every row's hidden state after the stack (the head's fold,
1115/// before the final norm) appended to it. Returns the rows the card took.
1116#[allow(clippy::too_many_arguments)]
1117fn prompt_rows(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, ids: &[u32], start: usize, pool: Option<&Pool>, mut keep: Option<&mut Vec<f32>>) -> usize {
1118    if ids.is_empty() || !graph_on() || !(crate::gpu::cuda_active() || crate::gpu::wgpu_active()) {
1119        return 0;
1120    }
1121    if start == 0 || state.pos != start {
1122        state.reset(layers.len());
1123    }
1124    if state.graph == Some(false) || (start > 0 && state.graph != Some(true)) {
1125        return 0;
1126    }
1127    // a draft's row kept past the confirmed ones leaves the card before the prompt's rows
1128    spec_drop(state, layers.len(), start);
1129    // wgpu: every mirror sized for the whole prompt at its first chunk (no growth midway, when
1130    // the old and the new buffers would sit on the card together)
1131    let hinted = crate::gpu::wgpu_active();
1132    if hinted {
1133        crate::gpu::set_batch_kv_hint(start + ids.len() + 1);
1134    }
1135    let done = prompt_rows_inner(globals, layers, cfg, state, ids, start, pool, keep.as_deref_mut());
1136    if hinted {
1137        crate::gpu::set_batch_kv_hint(0);
1138    }
1139    done
1140}
1141
1142#[allow(clippy::too_many_arguments)]
1143fn prompt_rows_inner(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, ids: &[u32], start: usize, pool: Option<&Pool>, mut keep: Option<&mut Vec<f32>>) -> usize {
1144    use crate::gpu::BatchGraphOutcome;
1145    let model = globals.model.clone();
1146    let inter = graph_inter(layers);
1147    let dim = cfg.dim;
1148    let named = std::env::var("CMF_MAXWELL_PROMPT_CHUNK").ok().and_then(|v| v.trim().parse::<usize>().ok());
1149    let mut chunk = named.unwrap_or(512).max(1);
1150    let body = ids.len();
1151    let mut done = 0usize;
1152    let timing = std::env::var_os("CMF_CUDA_PROF").is_some();
1153    while done < body {
1154        // over wgpu a chunk's rows take what the card has left beside the weights and the
1155        // mirrors (sized for the whole prompt at its first chunk)
1156        if named.is_none() && crate::gpu::wgpu_active() {
1157            chunk = chunk.min(wgpu_chunk_rows(cfg, layers.len(), start + body + 1));
1158        }
1159        let end = (done + chunk).min(body);
1160        let k = end - done;
1161        let t0 = std::time::Instant::now();
1162        let Some(gl) = graph_layers(globals, layers, cfg, start + end) else { return done };
1163        let o1: Vec<Option<Vec<crate::nystrom::O1DeviceView<'_>>>> = (0..gl.len()).map(|_| None).collect();
1164        let mut h = vec![0.0f32; k * dim];
1165        for (j, &tk) in ids[done..end].iter().enumerate() {
1166            if (tk as usize) < globals.embed.rows() {
1167                globals.embed.row_f32(&globals.model, tk as usize, &mut h[j * dim..(j + 1) * dim]);
1168            }
1169        }
1170        let positions: Vec<usize> = (start + done..start + end).collect();
1171        let outcome = crate::gpu::forward_batch_graph_at(
1172            &model, state.kv_id(), 0, &gl, &cfg.invf, &mut h, cfg.nh, cfg.nkv, cfg.hd, cfg.hd, dim, inter, &positions, GRAPH_CAP, false, cfg.eps as f32, cfg.scale, k, &o1, 0, None, None,
1173        );
1174        if timing {
1175            tracing::info!("maxwell_moe prompt chunk of {k} rows: the card {:.2} s", t0.elapsed().as_secs_f64());
1176        }
1177        // `CMF_MAXWELL_MEMLOG=1`: the device allocator's bytes after every prompt chunk (and the
1178        // card's free memory as the driver reports it, when it does)
1179        if std::env::var("CMF_MAXWELL_MEMLOG").as_deref() == Ok("1") {
1180            tracing::info!(
1181                "maxwell_moe memlog: {} positions, {:.0} MiB in use on the device ({:.0} MiB resident weights)",
1182                start + end,
1183                crate::gpu::device_bytes_in_use().unwrap_or(0) as f64 / 1048576.0,
1184                crate::gpu::resident_bytes() as f64 / 1048576.0
1185            );
1186        }
1187        match outcome {
1188            BatchGraphOutcome::Completed => {
1189                if state.graph.is_none() {
1190                    tracing::info!("maxwell_moe: the prompt runs on the card's batch graph");
1191                }
1192                state.graph = Some(true);
1193                state.tokens.extend_from_slice(&ids[done..end]);
1194                state.pos = start + end;
1195                done = end;
1196                if let Some(kp) = keep.as_deref_mut() {
1197                    kp.extend_from_slice(&h);
1198                }
1199            }
1200            BatchGraphOutcome::Declined => {
1201                // a chunk's rows may not fit beside the weights (a card whose budget the
1202                // experts fill): fewer rows a call before the rows go a token at a time
1203                if chunk > 16 {
1204                    chunk = (chunk / 2).max(16);
1205                    continue;
1206                }
1207                if done > 0 || state.graph == Some(true) {
1208                    // the card holds the rows before this chunk: the host takes them over
1209                    host_replay(globals, layers, cfg, state, pool);
1210                }
1211                return done;
1212            }
1213            BatchGraphOutcome::Failed => {
1214                host_replay(globals, layers, cfg, state, pool);
1215                return done;
1216            }
1217        }
1218    }
1219    done
1220}
1221
1222/// Perplexity on the card's prompt graph (`CMF_MAXWELL_NLL_BATCH=0`: the
1223/// token path): the rows of `ids[..n−1]` through the stack in long calls, the
1224/// final norm and the head on the host, `nll` of every next token from
1225/// `from` on. None when the card does not take the window.
1226pub fn nll(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, ids: &[u32], from: usize, pool: Option<&Pool>) -> Option<(f64, usize)> {
1227    if std::env::var("CMF_MAXWELL_NLL_BATCH").as_deref() == Ok("0") || ids.len() < 2 || !graph_on() || !(crate::gpu::cuda_active() || crate::gpu::wgpu_active()) {
1228        return None;
1229    }
1230    let n = ids.len() - 1;
1231    let dim = cfg.dim;
1232    let t0 = std::time::Instant::now();
1233    state.reset(layers.len());
1234    // a window the card cannot take whole is scored the token way: no host replay here
1235    graph_layers(globals, layers, cfg, n)?;
1236    let mut rows = Vec::with_capacity(n * dim);
1237    if prompt_rows(globals, layers, cfg, state, &ids[..n], 0, pool, Some(&mut rows)) != n || rows.len() != n * dim {
1238        state.reset(layers.len());
1239        return None;
1240    }
1241    state.reset(layers.len());
1242    let t_rows = t0.elapsed().as_secs_f64();
1243    let vocab = globals.lm_head.rows();
1244    let (mut nll, mut cnt) = (0f64, 0usize);
1245    let score = |row: &[f32], target: usize| -> f64 {
1246        let best = row.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v)) as f64;
1247        let den: f64 = row.iter().map(|&v| ((v as f64) - best).exp()).sum();
1248        den.ln() - (row[target.min(vocab - 1)] as f64 - best)
1249    };
1250    let mut r0 = from.min(n);
1251    // over wgpu a row at a time through the graph's own head (a call without layers): a matmat
1252    // of the head would upload a second copy of it beside the graph's and run a 24 GB card out
1253    // of memory at the next window, and on the host it takes a minute a window
1254    if crate::gpu::wgpu_active() {
1255        let mut lg = Vec::with_capacity(vocab);
1256        while r0 < n {
1257            if !head_logits(globals, cfg, state, &globals.norm, &rows[r0 * dim..(r0 + 1) * dim], &mut lg) {
1258                break;
1259            }
1260            nll += score(&lg, ids[r0 + 1] as usize);
1261            cnt += 1;
1262            r0 += 1;
1263        }
1264    }
1265    const B: usize = 64;
1266    let mut out = vec![0f32; B * vocab];
1267    let mut xs = vec![0f32; B * dim];
1268    while r0 < n {
1269        let b = B.min(n - r0);
1270        for j in 0..b {
1271            let x = rms_w(&rows[(r0 + j) * dim..(r0 + j + 1) * dim], &globals.norm, cfg.eps);
1272            xs[j * dim..(j + 1) * dim].copy_from_slice(&x);
1273        }
1274        globals.lm_head.matmat(&xs[..b * dim], b, &mut out[..b * vocab], pool);
1275        for j in 0..b {
1276            nll += score(&out[j * vocab..(j + 1) * vocab], ids[r0 + j + 1] as usize);
1277            cnt += 1;
1278        }
1279        r0 += b;
1280    }
1281    tracing::info!("maxwell_moe nll: {n} rows through the card in {t_rows:.1} s ({:.1} rows/s), the head {:.1} s", n as f64 / t_rows.max(1e-9), t0.elapsed().as_secs_f64() - t_rows);
1282    Some((nll, cnt))
1283}
1284
1285/// One token through the card's graph: the embedding in, the logits out.
1286#[allow(clippy::too_many_arguments)]
1287fn graph_token(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &State, token_id: u32, position: usize, logits: &mut Vec<f32>, want_logits: bool) -> crate::gpu::TokenGraphOutcome {
1288    use crate::gpu::TokenGraphOutcome;
1289    if !graph_on() || !(crate::gpu::cuda_active() || crate::gpu::wgpu_active()) {
1290        return TokenGraphOutcome::Declined;
1291    }
1292    let Some(head) = gw(&globals.lm_head) else { return TokenGraphOutcome::Declined };
1293    let Some(gl) = graph_layers(globals, layers, cfg, position + 1) else { return TokenGraphOutcome::Declined };
1294    let mut h = vec![0.0f32; cfg.dim];
1295    if (token_id as usize) < globals.embed.rows() {
1296        globals.embed.row_f32(&globals.model, token_id as usize, &mut h);
1297    }
1298    let o1: Vec<Option<Vec<crate::nystrom::O1DeviceView<'_>>>> = (0..gl.len()).map(|_| None).collect();
1299    let vocab = globals.lm_head.rows();
1300    crate::gpu::forward_token_graph(
1301        &globals.model, state.kv_id(), &gl, &o1, 0, &cfg.invf, &mut h, cfg.nh, cfg.nkv, cfg.hd, cfg.scale, cfg.hd, cfg.dim, graph_inter(layers), position, GRAPH_CAP, false, cfg.eps as f32,
1302        want_logits.then_some((&head, vocab)), &globals.norm, logits, &[], 1, None, None, None, 0, false,
1303    )
1304}
1305
1306/// One token: on the card's graph while the card holds the sequence (or it
1307/// takes it at position 0), else through the host stack.
1308#[allow(clippy::too_many_arguments)]
1309pub fn forward_token(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, token_id: u32, position: usize, pool: Option<&Pool>, logits: &mut Vec<f32>, want_logits: bool) {
1310    use crate::gpu::TokenGraphOutcome;
1311    if position == 0 || state.pos != position {
1312        if position != 0 && state.pos != position {
1313            tracing::warn!("maxwell_moe: position {position} after {}; the sequence restarts", state.pos);
1314        }
1315        state.reset(layers.len());
1316    }
1317    let try_graph = match state.graph {
1318        Some(true) => true,
1319        None => position == 0,
1320        Some(false) => false,
1321    };
1322    if try_graph {
1323        let spec = spec_on(globals);
1324        if spec && want_logits && state.graph == Some(true) && spec_token(globals, layers, cfg, state, token_id, position, pool, logits) {
1325            return;
1326        }
1327        // a plain call: a kept row leaves the card first, and the streams it
1328        // would have continued from are not this row's
1329        spec_drop(state, layers.len(), position);
1330        if spec {
1331            crate::gpu::graph_streams_want();
1332        }
1333        let outcome = graph_token(globals, layers, cfg, state, token_id, position, logits, want_logits);
1334        let streams = if spec { crate::gpu::graph_streams_take() } else { Vec::new() };
1335        match outcome {
1336            TokenGraphOutcome::Completed => {
1337                if state.graph.is_none() {
1338                    tracing::info!("maxwell_moe: decode runs on the card's token graph");
1339                }
1340                state.graph = Some(true);
1341                state.tokens.push(token_id);
1342                state.pos = position + 1;
1343                state.spec.streams = if streams.len() == cfg.hc * cfg.dim { streams } else { Vec::new() };
1344                return;
1345            }
1346            TokenGraphOutcome::Declined if state.graph == Some(true) => {
1347                // the card held the sequence and cannot go on: the host replays it
1348                host_replay(globals, layers, cfg, state, pool);
1349            }
1350            TokenGraphOutcome::Declined => state.graph = Some(false),
1351            TokenGraphOutcome::Failed => host_replay(globals, layers, cfg, state, pool),
1352        }
1353    }
1354    host_token(globals, layers, cfg, state, token_id, position, pool, logits, want_logits);
1355}
1356
1357// ---------------------------------------------------------------- calibration of the routed experts
1358
1359/// What `cortiq quantize-moe` calibrates the routed experts on: per captured
1360/// layer the routed FFN's normed input rows (`dim` f16 values a token), each
1361/// token's `top_k` expert ids in route order (`u16::MAX`: none) and their
1362/// route weights.
1363#[derive(Default)]
1364pub struct MoeCapture {
1365    pub x: Vec<Vec<u16>>,
1366    pub picks: Vec<Vec<u16>>,
1367    pub w: Vec<Vec<f32>>,
1368}
1369
1370/// The capture of layers `lo..hi` over `ids`, a sequence of its own: the
1371/// prompt path on the CUDA card with the routed FFNs tapped
1372/// (`gpu::moe_tap_begin`) — the host stack runs a few tokens a second, and
1373/// an expert sees one token in twenty.
1374#[allow(clippy::too_many_arguments)]
1375pub fn capture_window(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, ids: &[u32], lo: usize, hi: usize, pool: Option<&Pool>) -> Result<MoeCapture, String> {
1376    if !crate::gpu::cuda_active() {
1377        return Err("the routed experts' calibration runs on the CUDA backend (CMF_GPU=cuda)".into());
1378    }
1379    if lo >= hi || hi > layers.len() || (lo..hi).any(|li| matches!(layers[li].ffn, Ffn::Dense { .. })) {
1380        return Err(format!("layers {lo}..{hi}: not a range of routed layers"));
1381    }
1382    state.reset(layers.len());
1383    crate::gpu::moe_tap_begin(lo, hi);
1384    let done = prompt_rows(globals, layers, cfg, state, ids, 0, pool, None);
1385    let taps = crate::gpu::moe_tap_end();
1386    state.reset(layers.len());
1387    if done != ids.len() {
1388        return Err(format!("the card took {done} of {} rows", ids.len()));
1389    }
1390    let mut cap = MoeCapture { x: vec![Vec::new(); hi - lo], picks: vec![Vec::new(); hi - lo], w: vec![Vec::new(); hi - lo] };
1391    for (li, x, pk, pw) in taps {
1392        let k = li - lo;
1393        cap.x[k].extend(x.iter().map(|&v| cortiq_core::quant::f32_to_f16(v)));
1394        cap.picks[k].extend(pk.iter().map(|&e| if (0..u16::MAX as i32).contains(&e) { e as u16 } else { u16::MAX }));
1395        cap.w[k].extend(pw);
1396    }
1397    for k in 0..hi - lo {
1398        if cap.x[k].len() != ids.len() * cfg.dim || cap.picks[k].len() != ids.len() * cfg.top_k {
1399            return Err(format!("layer {}: {} rows and {} routes captured for {} tokens (the prompt left the grouped path?)", lo + k, cap.x[k].len() / cfg.dim, cap.picks[k].len() / cfg.top_k.max(1), ids.len()));
1400        }
1401    }
1402    Ok(cap)
1403}
1404
1405// ---------------------------------------------------------------- drafting with the MTP layer
1406//
1407// The checkpoint's MTP layer predicts token i + 2 from the stack's streams at position i and
1408// the embedding of token i + 1. On CUDA every main call past the first is two rows: the token
1409// just chosen and the MTP layer's draft of the one after it. When the next token is the draft,
1410// its row is already on the card and its logits are returned without a call; when it is not,
1411// the row leaves the mirrors (`graph_kv_set_stored`). A two-row call costs 1.29x a one-row call
1412// on an L4 (17.3 against 13.4 ms), and the heads' calls take back what that saves there.
1413// `CMF_MAXWELL_SPEC=1` turns it on (`spec_mode`: off by default). The MTP layer's own context starts at the first position
1414// it sees (its rows count positions from there: RoPE is relative).
1415
1416/// The MTP layer could not go on the card (no room, a weight the graphs do not address): the
1417/// drafting stays off instead of asking again every token.
1418static SPEC_BROKEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1419
1420/// `CMF_MAXWELL_SPEC`: 1 drafts while every weight is on the card, 2 also when the experts
1421/// stream (a streamed plan's calls wait for the host between their layers, twice for two
1422/// rows). Off without it: on an L4 three quarters of the drafts are taken and a token still
1423/// costs what it did (67.2 against 65.5 tok/s) — a pass reads the head 2.75 times.
1424fn spec_mode() -> u8 {
1425    static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
1426    *MODE.get_or_init(|| match std::env::var("CMF_MAXWELL_SPEC").as_deref() {
1427        Ok("1") => 1,
1428        Ok("2") => 2,
1429        _ => 0,
1430    })
1431}
1432
1433fn spec_on(globals: &Globals) -> bool {
1434    let mode = spec_mode();
1435    globals.mtp.is_some()
1436        && mode != 0
1437        && crate::gpu::cuda_active()
1438        && !SPEC_BROKEN.load(std::sync::atomic::Ordering::Relaxed)
1439        && (mode == 2 || !crate::gpu::plan_streamed(globals.model.uid()))
1440}
1441
1442/// A kept row (the draft's) off the card: the mirrors back to `position` rows. The MTP
1443/// layer's run ends here too (the plain call that follows leaves it a gap).
1444fn spec_drop(state: &mut State, n_layers: usize, position: usize) {
1445    if state.spec.kept.take().is_some() {
1446        for li in 0..n_layers {
1447            crate::gpu::graph_kv_set_stored(state.kv_id(), li, position);
1448        }
1449    }
1450    state.spec.streams.clear();
1451    state.spec.pending.clear();
1452}
1453
1454/// The vocabulary's logits of one folded hidden row: the final norm and the head on the card,
1455/// a call without layers.
1456fn head_logits(globals: &Globals, cfg: &Cfg, state: &State, norm: &[f32], hidden: &[f32], logits: &mut Vec<f32>) -> bool {
1457    let Some(head) = gw(&globals.lm_head) else { return false };
1458    let vocab = globals.lm_head.rows();
1459    let mut h = hidden.to_vec();
1460    let mut run = 0usize;
1461    let outcome = crate::gpu::forward_token_graph(
1462        &globals.model, state.kv_id(), &[], &[], 0, &cfg.invf, &mut h, cfg.nh, cfg.nkv, cfg.hd, cfg.scale, cfg.hd, cfg.dim, cfg.dim, 0, GRAPH_CAP, false, cfg.eps as f32,
1463        Some((&head, vocab)), norm, logits, &[], 1, None, None, Some(&mut run), 0, false,
1464    );
1465    outcome == crate::gpu::TokenGraphOutcome::Completed && logits.len() == vocab
1466}
1467
1468/// The MTP layer over its pending rows, one call: their rows onto the card, and the last
1469/// row's prediction — the draft of the token two positions after it.
1470fn mtp_rows(globals: &Globals, cfg: &Cfg, state: &mut State, last_pos: usize, pool: Option<&Pool>) -> Option<u32> {
1471    use crate::gpu::BatchGraphOutcome;
1472    let mtp = globals.mtp.as_ref()?;
1473    let (dim, hc) = (cfg.dim, cfg.hc);
1474    let k = state.spec.pending.len();
1475    if k == 0 || k > 8 || last_pos + 1 < k {
1476        return None;
1477    }
1478    let first = last_pos + 1 - k;
1479    // its rows are one contiguous run: a gap starts a new one
1480    if state.spec.mtp_rows > 0 && state.spec.mtp_base + state.spec.mtp_rows != first {
1481        crate::gpu::graph_kv_reset(state.mtp_kv_id());
1482        state.spec.mtp_rows = 0;
1483    }
1484    if state.spec.mtp_rows == 0 {
1485        state.spec.mtp_base = first;
1486    }
1487    let t0 = std::time::Instant::now();
1488    // stream_s = e_proj(enorm(emb(next))) + h_proj(hnorm(stream_s)), a GEMM over the rows each
1489    let (mut en, mut hn) = (Vec::with_capacity(k * dim), Vec::with_capacity(k * hc * dim));
1490    let mut e = vec![0f32; dim];
1491    for (streams, next) in &state.spec.pending {
1492        if streams.len() != hc * dim || *next as usize >= globals.embed.rows() {
1493            return None;
1494        }
1495        globals.embed.row_f32(&globals.model, *next as usize, &mut e);
1496        en.extend(rms_w(&e, &mtp.enorm, cfg.eps));
1497        for s in streams.chunks(dim) {
1498            hn.extend(rms_w(s, &mtp.hnorm, cfg.eps));
1499        }
1500    }
1501    let (mut eo, mut ho) = (vec![0f32; k * dim], vec![0f32; k * hc * dim]);
1502    mtp.e_proj.matmat(&en, k, &mut eo, pool);
1503    mtp.h_proj.matmat(&hn, k * hc, &mut ho, pool);
1504    for (r, row) in ho.chunks_mut(hc * dim).enumerate() {
1505        for s in row.chunks_mut(dim) {
1506            for (a, b) in s.iter_mut().zip(&eo[r * dim..(r + 1) * dim]) {
1507                *a += b;
1508            }
1509        }
1510    }
1511    state.spec.t[0] += t0.elapsed().as_secs_f64();
1512    let t1 = std::time::Instant::now();
1513    let gl = [graph_layer(&mtp.layer, cfg, false, false, true, Some((&mtp.head_fn, &mtp.head_base, mtp.head_scale)))?];
1514    let inter = match &mtp.layer.ffn {
1515        Ffn::Moe(m) => m.experts.first().map_or(0, |x| x[0].rows()).max(m.shared[0].rows()),
1516        Ffn::Dense { gate, .. } => gate.rows(),
1517    };
1518    let o1: [Option<Vec<crate::nystrom::O1DeviceView<'_>>>; 1] = [None];
1519    let rel = first - state.spec.mtp_base;
1520    let positions: Vec<usize> = (rel..rel + k).collect();
1521    let mut h = vec![0f32; k * dim];
1522    crate::gpu::graph_streams_in(ho);
1523    let outcome = crate::gpu::forward_batch_graph_at(
1524        &globals.model, state.mtp_kv_id(), 0, &gl, &cfg.invf, &mut h, cfg.nh, cfg.nkv, cfg.hd, cfg.hd, dim, inter, &positions, GRAPH_CAP, false, cfg.eps as f32, cfg.scale, k, &o1, 0, None, None,
1525    );
1526    state.spec.t[1] += t1.elapsed().as_secs_f64();
1527    let mut lg = Vec::new();
1528    let t2 = std::time::Instant::now();
1529    let ok = outcome == BatchGraphOutcome::Completed && head_logits(globals, cfg, state, &mtp.final_norm, &h[(k - 1) * dim..], &mut lg);
1530    state.spec.t[3] += t2.elapsed().as_secs_f64();
1531    if !ok {
1532        if !SPEC_BROKEN.swap(true, std::sync::atomic::Ordering::Relaxed) {
1533            tracing::warn!("maxwell_moe: the MTP layer did not run on the card ({outcome:?}); decoding goes on without drafts");
1534        }
1535        return None;
1536    }
1537    state.spec.mtp_rows += k;
1538    state.spec.pending.clear();
1539    Some(lg.iter().enumerate().fold((0usize, f32::NEG_INFINITY), |b, (i, &v)| if v > b.1 { (i, v) } else { b }).0 as u32)
1540}
1541
1542/// One token with a draft beside it: true when the token's logits are in `logits` and the
1543/// state stepped; false leaves the token to the plain call (no row of it is on the card).
1544#[allow(clippy::too_many_arguments)]
1545fn spec_token(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, token: u32, position: usize, pool: Option<&Pool>, logits: &mut Vec<f32>) -> bool {
1546    use crate::gpu::BatchGraphOutcome;
1547    let (dim, hc) = (cfg.dim, cfg.hc);
1548    if position == 0 {
1549        return false;
1550    }
1551    // the row kept from the last call: this token's, when it was the draft
1552    if let Some((tok, hidden, st)) = state.spec.kept.take() {
1553        if tok == token {
1554            let t0 = std::time::Instant::now();
1555            let ok = head_logits(globals, cfg, state, &globals.norm, &hidden, logits);
1556            state.spec.t[3] += t0.elapsed().as_secs_f64();
1557            if ok {
1558                // the MTP layer's row of the position before waits for the next pass
1559                let before = std::mem::replace(&mut state.spec.streams, st);
1560                state.spec.pending.push((before, token));
1561                state.spec.hits += 1;
1562                state.tokens.push(token);
1563                state.pos = position + 1;
1564                return true;
1565            }
1566        }
1567        for li in 0..layers.len() {
1568            crate::gpu::graph_kv_set_stored(state.kv_id(), li, position);
1569        }
1570    }
1571    if state.spec.streams.len() != hc * dim {
1572        return false;
1573    }
1574    // the draft of the token after this one: the MTP layer up to the position before
1575    state.spec.pending.push((state.spec.streams.clone(), token));
1576    let Some(draft) = mtp_rows(globals, cfg, state, position - 1, pool) else {
1577        state.spec.pending.clear();
1578        state.spec.mtp_rows = 0;
1579        return false;
1580    };
1581    // this token and the draft, one call
1582    let Some(gl) = graph_layers(globals, layers, cfg, position + 2) else { return false };
1583    let mut h = vec![0f32; 2 * dim];
1584    for (r, &t) in [token, draft].iter().enumerate() {
1585        if (t as usize) < globals.embed.rows() {
1586            globals.embed.row_f32(&globals.model, t as usize, &mut h[r * dim..(r + 1) * dim]);
1587        }
1588    }
1589    let positions = [position, position + 1];
1590    let o1: Vec<Option<Vec<crate::nystrom::O1DeviceView<'_>>>> = (0..gl.len()).map(|_| None).collect();
1591    let t0 = std::time::Instant::now();
1592    crate::gpu::graph_streams_want();
1593    let outcome = crate::gpu::forward_batch_graph_at(
1594        &globals.model, state.kv_id(), 0, &gl, &cfg.invf, &mut h, cfg.nh, cfg.nkv, cfg.hd, cfg.hd, dim, graph_inter(layers), &positions, GRAPH_CAP, false, cfg.eps as f32, cfg.scale, 2, &o1, 0, None, None,
1595    );
1596    let streams = crate::gpu::graph_streams_take();
1597    state.spec.t[2] += t0.elapsed().as_secs_f64();
1598    if outcome == BatchGraphOutcome::Completed && streams.len() == 2 * hc * dim {
1599        let t1 = std::time::Instant::now();
1600        let ok = head_logits(globals, cfg, state, &globals.norm, &h[..dim], logits);
1601        state.spec.t[3] += t1.elapsed().as_secs_f64();
1602        if ok {
1603            state.spec.streams = streams[..hc * dim].to_vec();
1604            state.spec.kept = Some((draft, h[dim..].to_vec(), streams[hc * dim..].to_vec()));
1605            state.spec.passes += 1;
1606            state.tokens.push(token);
1607            state.pos = position + 1;
1608            return true;
1609        }
1610    }
1611    // the call left rows the plain path cannot continue from: back to this position
1612    if outcome != BatchGraphOutcome::Declined {
1613        for li in 0..layers.len() {
1614            crate::gpu::graph_kv_set_stored(state.kv_id(), li, position);
1615        }
1616    }
1617    state.spec.streams.clear();
1618    false
1619}
1620
1621/// The streams of one position after the whole stack (host).
1622fn host_streams(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, token_id: u32, position: usize, pool: Option<&Pool>) -> Vec<f32> {
1623    let (dim, hc) = (cfg.dim, cfg.hc);
1624    let mut h = vec![0f32; dim];
1625    if (token_id as usize) < globals.embed.rows() {
1626        globals.embed.row_f32(&globals.model, token_id as usize, &mut h);
1627    }
1628    let mut streams: Vec<f32> = (0..hc).flat_map(|_| h.iter().copied()).collect();
1629    let mut folded = vec![0f32; dim];
1630    let mut next = vec![0f32; hc * dim];
1631    for (li, l) in layers.iter().enumerate() {
1632        CAP_LAYER.with(|c| c.set(li));
1633        let (pre, post, comb) = l.attn_hc.split(&streams, cfg, pool);
1634        hc_fold(&streams, &pre, hc, dim, &mut folded);
1635        let x = rms_w(&folded, &l.input_norm, cfg.eps);
1636        let y = l.attn.forward(&x, &mut state.layers[li], position, cfg, pool);
1637        dump(li, position, "attn", &y);
1638        hc_expand(&y, &streams, &post, &comb, hc, dim, &mut next);
1639        std::mem::swap(&mut streams, &mut next);
1640        let (pre, post, comb) = l.ffn_hc.split(&streams, cfg, pool);
1641        hc_fold(&streams, &pre, hc, dim, &mut folded);
1642        let x = rms_w(&folded, &l.post_norm, cfg.eps);
1643        let y = match &l.ffn {
1644            Ffn::Dense { gate, up, down } => dense(gate, up, down, &x, pool, Some("mlp.")),
1645            Ffn::Moe(m) => m.forward(&x, cfg, pool),
1646        };
1647        dump(li, position, "ffn", &y);
1648        hc_expand(&y, &streams, &post, &comb, hc, dim, &mut next);
1649        std::mem::swap(&mut streams, &mut next);
1650        dump(li, position, "streams", &streams);
1651    }
1652    streams
1653}
1654
1655/// The closing fold of the streams: `σ(mixes · scale + base) + eps` weights.
1656fn head_fold(globals: &Globals, cfg: &Cfg, streams: &[f32]) -> Vec<f32> {
1657    let (dim, hc) = (cfg.dim, cfg.hc);
1658    let n = streams.len();
1659    let ms = streams.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / n as f64;
1660    let r = (1.0 / (ms + cfg.hc_eps as f64).sqrt()) as f32;
1661    let pre: Vec<f32> = (0..hc)
1662        .map(|j| {
1663            let m = globals.head_fn[j * n..(j + 1) * n].iter().zip(streams).map(|(a, b)| a * b).sum::<f32>() * r;
1664            sigmoid(m * globals.head_scale + globals.head_base[j]) + cfg.hc_eps
1665        })
1666        .collect();
1667    let mut out = vec![0f32; dim];
1668    hc_fold(streams, &pre, hc, dim, &mut out);
1669    out
1670}
1671
1672/// One token through the host stack; the logits when asked.
1673#[allow(clippy::too_many_arguments)]
1674fn host_token(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, token_id: u32, position: usize, pool: Option<&Pool>, logits: &mut Vec<f32>, want_logits: bool) {
1675    if position == 0 {
1676        state.layers = (0..layers.len()).map(|_| LayerState::default()).collect();
1677        state.tokens.clear();
1678    }
1679    state.tokens.push(token_id);
1680    let streams = host_streams(globals, layers, cfg, state, token_id, position, pool);
1681    state.pos = position + 1;
1682    if !want_logits {
1683        return;
1684    }
1685    let x = rms_w(&head_fold(globals, cfg, &streams), &globals.norm, cfg.eps);
1686    dump(layers.len(), position, "final", &x);
1687    logits.resize(globals.lm_head.rows(), 0.0);
1688    if crate::gptq_capture::capturing() {
1689        CAP_LAYER.with(|c| c.set(usize::MAX));
1690        cap(4, &x, |_| vec!["lm_head.weight".to_string()]);
1691    }
1692    globals.lm_head.matvec(&x, logits, pool);
1693}
1694
1695#[cfg(test)]
1696mod tests {
1697    use super::*;
1698
1699    fn cfg() -> Cfg {
1700        Cfg { dim: 8, hc: 4, eps: 1e-6, hc_eps: 1e-6, sinkhorn_iters: 20, nh: 4, nkv: 2, hd: 4, scale: 0.5, invf: vec![1.0, 0.1], block: 128, prefix_blocks: 8, local_blocks: 8, remote_blocks: 16, top_k: 2, max_seq: 32768 }
1701    }
1702
1703    #[test]
1704    fn below_the_dense_range_every_block_is_routed() {
1705        let c = cfg();
1706        assert_eq!(c.dense_range(), 4096);
1707        for pos in [0usize, 127, 128, 1023, 1024, 2047, 2048, 4095] {
1708            let r = route_blocks(pos, &c, 2, |_, _| panic!("no scoring below the dense range"));
1709            let want: Vec<usize> = (0..=pos / 128).collect();
1710            assert_eq!(r[0], want, "position {pos}");
1711            assert_eq!(r[1], want);
1712        }
1713    }
1714
1715    #[test]
1716    fn past_the_dense_range_the_best_blocks_join_the_fixed_ones() {
1717        let c = cfg();
1718        // position 5000: block 39; local 32..=39, prefix 0..8, candidates 8..32 (24 blocks), 16 picked
1719        let r = route_blocks(5000, &c, 2, |g, b| if g == 0 { b as f32 } else { -(b as f32) });
1720        let mut want0: Vec<usize> = (0..8).collect();
1721        want0.extend(16..32);
1722        want0.extend(32..=39);
1723        assert_eq!(r[0], want0);
1724        let mut want1: Vec<usize> = (0..8).collect();
1725        want1.extend(8..24);
1726        want1.extend(32..=39);
1727        assert_eq!(r[1], want1);
1728        // a tie keeps the lower block
1729        let r = route_blocks(5000, &c, 1, |_, _| 1.0);
1730        let mut want: Vec<usize> = (0..24).collect();
1731        want.extend(32..=39);
1732        assert_eq!(r[0], want);
1733        // position 4096: block 32, local 25..=32, 17 candidates 8..25 of which the tie drops the last
1734        let r = route_blocks(4096, &c, 1, |_, _| 1.0);
1735        let mut want: Vec<usize> = (0..24).collect();
1736        want.extend(25..=32);
1737        assert_eq!(r[0], want);
1738    }
1739
1740    #[test]
1741    fn the_router_picks_by_the_biased_score_and_weighs_by_the_plain_one() {
1742        // scores σ(0)=0.5, σ(2)≈0.881, σ(-2)≈0.119; the bias lifts expert 2 over expert 0
1743        let picks = route_logits(&[0.0, 2.0, -2.0], &[0.0, 0.0, 0.5], 2);
1744        assert_eq!(picks.iter().map(|p| p.0).collect::<Vec<_>>(), vec![1, 2]);
1745        let (s1, s2) = (sigmoid(2.0), sigmoid(-2.0));
1746        assert!((picks[0].1 - s1 / (s1 + s2)).abs() < 1e-6);
1747        assert!((picks[1].1 - s2 / (s1 + s2)).abs() < 1e-6);
1748        assert!((picks.iter().map(|p| p.1).sum::<f32>() - 1.0).abs() < 1e-6);
1749    }
1750
1751    #[test]
1752    fn the_mapping_is_scaled_by_the_rms_plus_epsilon() {
1753        // 2 streams of 2: rms of [3, 4, 0, 0] is 2.5; one mapping row of ones → 7 / (2.5 + eps)
1754        let hc = Hc { function: vec![1.0; 4], base: vec![0.0], scale: [1.0; 3] };
1755        let m = hc.mixes(&[3.0, 4.0, 0.0, 0.0], 1e-6, None);
1756        assert!((m[0] - 7.0 / (2.5 + 1e-6)).abs() < 1e-5, "{m:?}");
1757    }
1758}