Skip to main content

cortiq_engine/
hy4.rs

1//! Hy4-flash (`hy_v4_flash`) text runtime.
2//!
3//! Transcribed from the reference `modeling_hy_v4_flash.py`
4//! (transformers PR #50903), not inferred from tensor names. The stack:
5//!
6//! * four residual streams with identity hyper-connections (iHC): each
7//!   sub-layer folds the streams with `pre = σ(·) + eps` and returns its
8//!   output to every stream with `post = 2·σ(·) + eps`; the streams are never
9//!   mixed (no Sinkhorn matrix);
10//! * gated MLA (q through a 1024 rank, a 512 latent, 192+64 wide heads, V 256)
11//!   with learned sinks and a sandwich norm on the O projection; 30 sliding
12//!   layers (64 heads, a 512-position window, RoPE base 1e4) and 12 sparse
13//!   ones (32 heads, base 1e7) that attend to everything up to 2048 positions
14//!   and past that to the 2048 their compressed indexer recalls (groups of 4);
15//! * a dense first FFN, then 41 latent MoE blocks: the router and the shared
16//!   expert read the 3072-wide token, the 16-of-512 routed experts a
17//!   1536-wide projection of it, their sum projected back; a norm closes the
18//!   block;
19//! * Engram memory before the attention of layers 1, 11, 21 and 31: bigram
20//!   and trigram hashes index a 165M-row table, the rows gate into every
21//!   stream.
22//!
23//! The converter (`cortiq-cli/src/hy4pack.rs`) stores the rotary rows
24//! half-split, MLA heads rope first, and the Engram rows already through the
25//! model's fp8 round trip.
26
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 = "hy_v4_flash";
34
35/// The nn.RMSNorm epsilon of the Engram block. `eps=None` there, and torch's
36/// fused RMSNorm then takes the epsilon of its accumulation type (f32) even
37/// for bf16 activations — not `finfo(bfloat16).eps`. It matters: the streams
38/// the gate's query norms have an RMS near 0.03, so 2^-7 would shrink every
39/// query (and with it the gate) about threefold.
40const ENGRAM_EPS: f64 = f32::EPSILON as f64;
41
42fn err(s: impl Into<String>) -> CmfError {
43    CmfError::Parse(format!("hy_v4_flash: {}", s.into()))
44}
45
46/// `CMF_HY4_KEEP=FILE`: the routed experts of a cut without cutting the
47/// file — `{"<layer>": [kept expert ids], ...}`; every other expert of a
48/// listed layer gets a selection bias of -1e30, so no row ever picks it and
49/// the picks' weights renormalize over the kept ones, as in a `moe-defrag`
50/// cut of that set. Layers not listed keep all their experts.
51fn keep_mask(li: usize, mut bias: Vec<f32>) -> Vec<f32> {
52    static KEEP: std::sync::OnceLock<Option<std::collections::HashMap<usize, Vec<usize>>>> = std::sync::OnceLock::new();
53    let keep = KEEP.get_or_init(|| {
54        let path = std::env::var("CMF_HY4_KEEP").ok()?;
55        let text = std::fs::read_to_string(&path).map_err(|e| tracing::warn!("CMF_HY4_KEEP {path}: {e}")).ok()?;
56        let v: std::collections::HashMap<String, Vec<usize>> = serde_json::from_str(&text).map_err(|e| tracing::warn!("CMF_HY4_KEEP {path}: {e}")).ok()?;
57        let m: std::collections::HashMap<usize, Vec<usize>> = v.into_iter().filter_map(|(k, ids)| Some((k.parse().ok()?, ids))).collect();
58        tracing::info!("hy_v4_flash: CMF_HY4_KEEP masks {} layers' routed experts ({path})", m.len());
59        Some(m)
60    });
61    if let Some(ids) = keep.as_ref().and_then(|m| m.get(&li)) {
62        let mut on = vec![false; bias.len()];
63        for &e in ids {
64            if e < on.len() {
65                on[e] = true;
66            }
67        }
68        for (b, &o) in bias.iter_mut().zip(&on) {
69            if !o {
70                *b = -1e30;
71            }
72        }
73    }
74    bias
75}
76
77/// `CMF_HY4_ALIAS=FILE`: resonance substitutes (`cortiq hy4-alias`) —
78/// `{"<layer>": [source id of every expert]}`; expert `e` of a listed layer
79/// is loaded from expert `alias[e]`'s tensors, so the router keeps choosing
80/// among all experts with its own weights and a dropped expert's pick is
81/// computed by its substitute (the cut with an alias table, without cutting).
82fn alias_of(li: usize, e: usize) -> usize {
83    static ALIAS: std::sync::OnceLock<Option<std::collections::HashMap<usize, Vec<usize>>>> = std::sync::OnceLock::new();
84    let a = ALIAS.get_or_init(|| {
85        let path = std::env::var("CMF_HY4_ALIAS").ok()?;
86        let text = std::fs::read_to_string(&path).map_err(|e| tracing::warn!("CMF_HY4_ALIAS {path}: {e}")).ok()?;
87        let v: std::collections::HashMap<String, Vec<usize>> = serde_json::from_str(&text).map_err(|e| tracing::warn!("CMF_HY4_ALIAS {path}: {e}")).ok()?;
88        let m: std::collections::HashMap<usize, Vec<usize>> = v.into_iter().filter_map(|(k, ids)| Some((k.parse().ok()?, ids))).collect();
89        tracing::info!("hy_v4_flash: CMF_HY4_ALIAS maps {} layers' routed experts ({path})", m.len());
90        Some(m)
91    });
92    a.as_ref().and_then(|m| m.get(&li)).and_then(|v| v.get(e)).copied().unwrap_or(e)
93}
94
95/// `CMF_HY4_ABSENT=FILE`: `{"<layer>": [present expert ids]}` — the other
96/// experts of a listed layer are absent: the router still chooses its top-k
97/// among all of them with the full model's weights, and an absent pick adds
98/// nothing (its weight 0, the rest not renormalized). 1/0 per expert.
99fn absent_mask(li: usize, ne: usize) -> Option<Vec<f32>> {
100    static PRESENT: std::sync::OnceLock<Option<std::collections::HashMap<usize, Vec<usize>>>> = std::sync::OnceLock::new();
101    let m = PRESENT.get_or_init(|| {
102        let path = std::env::var("CMF_HY4_ABSENT").ok()?;
103        let text = std::fs::read_to_string(&path).map_err(|e| tracing::warn!("CMF_HY4_ABSENT {path}: {e}")).ok()?;
104        let v: std::collections::HashMap<String, Vec<usize>> = serde_json::from_str(&text).map_err(|e| tracing::warn!("CMF_HY4_ABSENT {path}: {e}")).ok()?;
105        let m: std::collections::HashMap<usize, Vec<usize>> = v.into_iter().filter_map(|(k, ids)| Some((k.parse().ok()?, ids))).collect();
106        tracing::info!("hy_v4_flash: CMF_HY4_ABSENT: {} layers' routed experts outside the list add nothing ({path})", m.len());
107        Some(m)
108    });
109    let ids = m.as_ref()?.get(&li)?;
110    let mut p = vec![0f32; ne];
111    for &e in ids {
112        if e < ne {
113            p[e] = 1.0;
114        }
115    }
116    Some(p)
117}
118
119fn f(model: &CmfModel, name: &str) -> Result<Vec<f32>, CmfError> {
120    load_f32(model, name, &Overlay::None).map_err(err)
121}
122
123fn t(model: &Arc<CmfModel>, name: &str) -> Result<QTensor, CmfError> {
124    load_matrix(model, name, false, &Overlay::None)
125}
126
127#[inline]
128fn sigmoid(x: f32) -> f32 {
129    1.0 / (1.0 + (-x).exp())
130}
131
132fn rms_w(x: &[f32], w: &[f32], eps: f64) -> Vec<f32> {
133    crate::inference::rms_norm(x, w, eps, NormStyle::Qwen)
134}
135
136fn rms_plain(x: &mut [f32], eps: f64) {
137    let ms = x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len().max(1) as f64;
138    let r = 1.0 / (ms + eps).sqrt() as f32;
139    for v in x.iter_mut() {
140        *v *= r;
141    }
142}
143
144fn bf16_round(x: f32) -> f32 {
145    let b = x.to_bits();
146    if x.is_nan() {
147        return x;
148    }
149    f32::from_bits((b.wrapping_add(0x7fff + ((b >> 16) & 1)) >> 16) << 16)
150}
151
152fn e4m3(b: u8) -> f32 {
153    let sign = if b & 0x80 != 0 { -1.0f32 } else { 1.0 };
154    let exp = ((b >> 3) & 0x0F) as i32;
155    let man = (b & 0x07) as f32;
156    let mag = if exp == 0 { man * (2f32).powi(-9) } else { (1.0 + man / 8.0) * (2f32).powi(exp - 7) };
157    sign * mag
158}
159
160/// Half-split rotation of `v[..rd]` at `pos` (`rd / 2` frequencies).
161pub(crate) fn rope_half(v: &mut [f32], invf: &[f32], pos: usize) {
162    let half = invf.len();
163    for i in 0..half {
164        let a = pos as f64 * invf[i] as f64;
165        let (s, c) = (a.sin() as f32, a.cos() as f32);
166        let (x0, x1) = (v[i], v[i + half]);
167        v[i] = x0 * c - x1 * s;
168        v[i + half] = x1 * c + x0 * s;
169    }
170}
171
172/// One identity hyper-connection: `[2·hc, hc·dim]` mixes, their bases and
173/// the two group scales.
174pub struct Hc {
175    pub function: Vec<f32>,
176    pub base: Vec<f32>,
177    pub scale: [f32; 2],
178}
179
180impl Hc {
181    /// The mixes `function · flat · rsqrt(mean(flat²) + eps)`.
182    fn mixes(&self, flat: &[f32], rows: usize, eps: f64, pool: Option<&Pool>) -> Vec<f32> {
183        let n = flat.len();
184        let ms = flat.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / n as f64;
185        let r = 1.0 / (ms + eps).sqrt() as f32;
186        let mut out = vec![0f32; rows];
187        let f = &self.function;
188        let work = |i: usize| -> f32 { f[i * n..(i + 1) * n].iter().zip(flat).map(|(a, b)| a * b).sum::<f32>() * r };
189        match pool {
190            Some(p) => {
191                let cells: Vec<std::sync::atomic::AtomicU32> = (0..rows).map(|_| std::sync::atomic::AtomicU32::new(0)).collect();
192                p.run_rows(rows, &|a, b| {
193                    for i in a..b {
194                        cells[i].store(work(i).to_bits(), std::sync::atomic::Ordering::Relaxed);
195                    }
196                });
197                for (o, c) in out.iter_mut().zip(&cells) {
198                    *o = f32::from_bits(c.load(std::sync::atomic::Ordering::Relaxed));
199                }
200            }
201            None => {
202                for (i, o) in out.iter_mut().enumerate() {
203                    *o = work(i);
204                }
205            }
206        }
207        out
208    }
209
210    /// (pre, post) of the sub-layer: `σ(m·s₀ + b) + eps`, `mag·σ(m·s₁ + b) + eps`.
211    fn split(&self, flat: &[f32], hc: usize, eps: f64, hc_eps: f32, mag: f32, pool: Option<&Pool>) -> (Vec<f32>, Vec<f32>) {
212        let m = self.mixes(flat, 2 * hc, eps, pool);
213        let pre = (0..hc).map(|j| sigmoid(m[j] * self.scale[0] + self.base[j]) + hc_eps).collect();
214        let post = (0..hc).map(|j| mag * sigmoid(m[hc + j] * self.scale[1] + self.base[hc + j]) + hc_eps).collect();
215        (pre, post)
216    }
217}
218
219pub struct Indexer {
220    /// `[ih·id, q_rank]`, each head `[id - rope | rope]` (rope half-split).
221    pub q: QTensor,
222    /// `[ih, hidden]` head weights.
223    pub hw: Vec<f32>,
224    /// `[id, hidden]` token key, then its norm.
225    pub tk: Vec<f32>,
226    pub tk_norm: Vec<f32>,
227    /// `[id, id]` pooling value and gate projections (f32), the pooled key's
228    /// norm and the intra-group position embedding `[ratio, id]`.
229    pub kv: Vec<f32>,
230    pub kg: Vec<f32>,
231    pub k_norm: Vec<f32>,
232    pub ape: Vec<f32>,
233}
234
235pub struct Attn {
236    pub q_a: QTensor,
237    pub q_a_norm: Vec<f32>,
238    /// `[nh·(rope + nope), q_rank]`, every head rope first.
239    pub q_b: QTensor,
240    /// `[lora + rope, hidden]`.
241    pub kv_a: QTensor,
242    pub kv_a_norm: Vec<f32>,
243    /// `[nh·(nope + v), lora]`, per head `[k_nope | v]`.
244    pub kv_b: QTensor,
245    /// `[nh·v, hidden]` elementwise output gate.
246    pub gate: QTensor,
247    pub o: QTensor,
248    pub post_norm: Vec<f32>,
249    pub sinks: Vec<f32>,
250    pub nh: usize,
251    pub sliding: bool,
252    pub indexer: Option<Indexer>,
253    kvb_f32: std::sync::OnceLock<Vec<f32>>,
254}
255
256pub struct Moe {
257    /// `[E, hidden]` f32 router, the selection bias.
258    pub router: Vec<f32>,
259    pub bias: Vec<f32>,
260    /// `[latent, hidden]`, `[hidden, latent]`.
261    pub down: QTensor,
262    pub up: QTensor,
263    pub shared: [QTensor; 3],
264    pub out_norm: Vec<f32>,
265    /// (gate, up, down) of every routed expert.
266    pub experts: Vec<[QTensor; 3]>,
267    /// Per expert 1 present / 0 absent: an absent expert stays in the
268    /// router's choice and its pick's weight becomes 0 (no renormalization
269    /// over the rest). The graph reads the selection bias followed by it.
270    pub present: Option<Vec<f32>>,
271    pub bias_ext: Option<Vec<f32>>,
272    /// Experts the file lacks (absent, standing on another's tensors).
273    pub missing: Vec<bool>,
274}
275
276pub enum Ffn {
277    Dense { gate: QTensor, up: QTensor, down: QTensor, out_norm: Vec<f32> },
278    Moe(Moe),
279}
280
281pub struct Engram {
282    pub table: String,
283    pub table_scale: String,
284    pub hd: usize,
285    pub lookup: Vec<u32>,
286    pub mult: Vec<u64>,
287    /// Hash modulus and table row offset of every head (orders major).
288    pub moduli: Vec<u64>,
289    pub offsets: Vec<u64>,
290    pub head_norms: Vec<f32>,
291    pub key: Vec<QTensor>,
292    pub key_b: Vec<Vec<f32>>,
293    pub value: QTensor,
294    pub value_b: Vec<f32>,
295    pub norm_key: Vec<Vec<f32>>,
296    pub norm_query: Vec<Vec<f32>>,
297    pub gamma: Vec<f32>,
298    /// `[hc, hidden]`.
299    pub hc_scales: Vec<f32>,
300}
301
302pub struct Layer {
303    pub attn_hc: Hc,
304    pub ffn_hc: Hc,
305    pub input_norm: Vec<f32>,
306    pub post_norm: Vec<f32>,
307    pub attn: Attn,
308    pub ffn: Ffn,
309    pub engram: Option<Engram>,
310}
311
312pub struct Globals {
313    pub model: Arc<CmfModel>,
314    pub embed: QTensor,
315    pub lm_head: QTensor,
316    pub norm: Vec<f32>,
317    pub head_fn: Vec<f32>,
318    pub head_base: Vec<f32>,
319    pub head_scale: f32,
320}
321
322pub struct Cfg {
323    pub dim: usize,
324    pub hc: usize,
325    pub eps: f64,
326    pub hc_eps: f32,
327    pub mag: f32,
328    pub rope: usize,
329    pub nope: usize,
330    pub v: usize,
331    pub lora: usize,
332    pub scale: f32,
333    pub window: usize,
334    pub invf_swa: Vec<f32>,
335    pub invf_dsa: Vec<f32>,
336    pub ix_nh: usize,
337    pub ix_hd: usize,
338    pub ratio: usize,
339    pub group_topk: usize,
340    /// Positions past which a sparse layer selects (group_topk · ratio).
341    pub candidate: usize,
342    pub top_k: usize,
343    pub route_scale: f32,
344    pub limit: f32,
345    pub latent: usize,
346    pub pad_id: u32,
347    pub image_id: u32,
348    pub video_id: u32,
349    pub max_ngram: usize,
350    pub n_per_ngram: usize,
351}
352
353/// One layer's cache: the normalized latent and the rotated shared key per
354/// position (a sliding layer keeps its window from `base` on), and on the
355/// sparse layers the indexer's token keys and pooled group keys.
356#[derive(Default)]
357struct LayerState {
358    lat: Vec<f32>,
359    kr: Vec<f32>,
360    base: usize,
361    tkeys: Vec<f32>,
362    gkeys: Vec<f32>,
363}
364
365pub struct State {
366    pub pos: usize,
367    pub tokens: Vec<u32>,
368    layers: Vec<LayerState>,
369    /// The sequence's device key (process-unique: a pipeline reuses one model
370    /// for many prompts).
371    sequence_id: u64,
372    /// The sequence runs on the card's graphs: None not tried yet, Some(false)
373    /// the host runs it, Some(true) the card holds its states.
374    graph: Option<bool>,
375}
376
377static NEXT_SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
378
379impl State {
380    pub fn reset(&mut self, n_layers: usize) {
381        if self.graph == Some(true) {
382            crate::gpu::graph_kv_reset(self.kv_id());
383        }
384        self.graph = None;
385        self.sequence_id = NEXT_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
386        self.pos = 0;
387        self.tokens.clear();
388        self.layers = (0..n_layers).map(|_| LayerState::default()).collect();
389    }
390
391    fn kv_id(&self) -> u64 {
392        (1u64 << 61) | self.sequence_id
393    }
394}
395
396impl Drop for State {
397    fn drop(&mut self) {
398        if self.graph == Some(true) {
399            crate::gpu::graph_kv_reset(self.kv_id());
400        }
401    }
402}
403
404fn inv_freq(theta: f64, rope: usize) -> Vec<f32> {
405    (0..rope / 2).map(|i| (1.0 / theta.powf(2.0 * i as f64 / rope as f64)) as f32).collect()
406}
407
408pub fn load(model: &Arc<CmfModel>, arch: &ModelArch) -> Result<(Globals, Vec<Layer>, Cfg, State), CmfError> {
409    let prov = model.header.provenance.as_ref().and_then(|p| p.get("hy4_flash")).ok_or_else(|| err("header has no hy4_flash record"))?;
410    let tc = prov.get("text_config").ok_or_else(|| err("no text_config"))?;
411    let u = |k: &str| -> Result<usize, CmfError> {
412        tc.get(k).and_then(|v| v.as_u64()).map(|v| v as usize).ok_or_else(|| err(format!("text_config.{k}")))
413    };
414    let fl = |k: &str, d: f64| tc.get(k).and_then(|v| v.as_f64()).unwrap_or(d);
415    if prov.get("rope_layout").and_then(|v| v.as_str()) != Some("half_split") {
416        return Err(err("the file's rotary layout is not the converter's half-split one"));
417    }
418    let mla = arch.mla.as_ref().ok_or_else(|| err("missing MLA geometry"))?;
419    let (rope, nope, v, lora) = (mla.qk_rope_head_dim, mla.qk_nope_head_dim, mla.v_head_dim, mla.kv_lora_rank);
420    let theta = |lt: &str, d: f64| tc["rope_parameters"][lt]["rope_theta"].as_f64().unwrap_or(d);
421    let cfg = Cfg {
422        dim: arch.hidden_size,
423        hc: u("hc_mult")?,
424        eps: arch.rms_norm_eps,
425        hc_eps: fl("hc_eps", 1e-6) as f32,
426        mag: fl("hc_magnitude", 2.0) as f32,
427        rope,
428        nope,
429        v,
430        lora,
431        scale: ((rope + nope) as f32).sqrt().recip(),
432        // `CMF_HY4_WINDOW=<n>`: another sliding window for both paths (a check)
433        window: std::env::var("CMF_HY4_WINDOW").ok().and_then(|v| v.parse().ok()).unwrap_or(u("sliding_window")?),
434        invf_swa: inv_freq(theta("sliding_attention", 1e4), rope),
435        invf_dsa: inv_freq(theta("deepseek_sparse_attention", 1e7), rope),
436        ix_nh: u("compressed_indexer_num_attention_heads")?,
437        ix_hd: u("compressed_indexer_head_dim")?,
438        ratio: u("compressed_indexer_compress_ratio")?,
439        group_topk: u("compressed_indexer_group_topk")?,
440        candidate: u("compressed_indexer_group_topk")? * u("compressed_indexer_compress_ratio")?,
441        top_k: u("num_experts_per_tok")?,
442        route_scale: fl("routed_scaling_factor", 1.0) as f32,
443        limit: fl("swiglu_limit", 0.0) as f32,
444        latent: u("routed_expert_hidden_size")?,
445        pad_id: u("engram_pad_id")? as u32,
446        image_id: prov.get("image_token_id").and_then(|v| v.as_u64()).unwrap_or(120120) as u32,
447        video_id: prov.get("video_token_id").and_then(|v| v.as_u64()).unwrap_or(120124) as u32,
448        max_ngram: u("engram_max_ngram_size")?,
449        n_per_ngram: u("engram_n_head_per_ngram")?,
450    };
451    let layer_types: Vec<&str> = tc["layer_types"].as_array().ok_or_else(|| err("layer_types"))?.iter().map(|v| v.as_str().unwrap_or("")).collect();
452    let mlp_types: Vec<&str> = tc["mlp_layer_types"].as_array().ok_or_else(|| err("mlp_layer_types"))?.iter().map(|v| v.as_str().unwrap_or("")).collect();
453    let hs = f(model, "model.hc_head.scale")?;
454    let globals = Globals {
455        model: model.clone(),
456        embed: t(model, "model.embed_tokens.weight")?,
457        lm_head: t(model, "lm_head.weight")?,
458        norm: f(model, "model.norm.weight")?,
459        head_fn: f(model, "model.hc_head.fn")?,
460        head_base: f(model, "model.hc_head.base")?,
461        head_scale: *hs.first().ok_or_else(|| err("hc_head.scale"))?,
462    };
463    let n_exp = arch.moe.as_ref().map_or(0, |m| m.num_experts);
464    let hc = cfg.hc;
465    let mut layers = Vec::with_capacity(arch.num_layers);
466    for li in 0..arch.num_layers {
467        let p = format!("model.layers.{li}.");
468        let hc_of = |kind: &str| -> Result<Hc, CmfError> {
469            let s = f(model, &format!("{p}{kind}.scale"))?;
470            if s.len() != 2 {
471                return Err(err(format!("{p}{kind}.scale has {} values", s.len())));
472            }
473            Ok(Hc { function: f(model, &format!("{p}{kind}.fn"))?, base: f(model, &format!("{p}{kind}.base"))?, scale: [s[0], s[1]] })
474        };
475        let a = format!("{p}self_attn.");
476        let sliding = layer_types.get(li).copied() == Some("sliding_attention");
477        let q_b = t(model, &format!("{a}q_b_proj.weight"))?;
478        let nh = q_b.rows() / (rope + nope);
479        let indexer = if sliding {
480            None
481        } else {
482            let i = format!("{a}indexer.");
483            Some(Indexer {
484                q: t(model, &format!("{i}query_projection.weight"))?,
485                hw: f(model, &format!("{i}head_weight_projection.weight"))?,
486                tk: f(model, &format!("{i}token_key_projection.weight"))?,
487                tk_norm: f(model, &format!("{i}token_key_norm.weight"))?,
488                kv: f(model, &format!("{i}key_value_projection.weight"))?,
489                kg: f(model, &format!("{i}key_gate_projection.weight"))?,
490                k_norm: f(model, &format!("{i}key_norm.weight"))?,
491                ape: f(model, &format!("{i}intra_group_ape"))?,
492            })
493        };
494        let attn = Attn {
495            q_a: t(model, &format!("{a}q_a_proj.weight"))?,
496            q_a_norm: f(model, &format!("{a}q_a_layernorm.weight"))?,
497            q_b,
498            kv_a: t(model, &format!("{a}kv_a_proj_with_mqa.weight"))?,
499            kv_a_norm: f(model, &format!("{a}kv_a_layernorm.weight"))?,
500            kv_b: t(model, &format!("{a}kv_b_proj.weight"))?,
501            gate: t(model, &format!("{a}gate_proj.weight"))?,
502            o: t(model, &format!("{a}o_proj.weight"))?,
503            post_norm: f(model, &format!("{a}post_proj_norm.weight"))?,
504            sinks: f(model, &format!("{a}sinks"))?,
505            nh,
506            sliding,
507            indexer,
508            kvb_f32: std::sync::OnceLock::new(),
509        };
510        let m = format!("{p}mlp.");
511        let ffn = if mlp_types.get(li).copied() == Some("dense") {
512            Ffn::Dense {
513                gate: t(model, &format!("{m}gate_proj.weight"))?,
514                up: t(model, &format!("{m}up_proj.weight"))?,
515                down: t(model, &format!("{m}down_proj.weight"))?,
516                out_norm: f(model, &format!("{m}post_fc2_norm.weight"))?,
517            }
518        } else {
519            // a `moe-defrag` cut with absent experts (CMF_DEFRAG_ABSENT) lacks
520            // their tensors: they stay in the router's choice, add nothing, and
521            // stand on the first present expert's tensors (never computed)
522            let has = |e: usize| model.tensor(&format!("{m}experts.{e}.gate_proj.weight")).is_some();
523            let first = (0..n_exp).map(|e| alias_of(li, e)).find(|&e| has(e)).ok_or_else(|| err(format!("layer {li}: no routed expert in the file")))?;
524            let mut missing = vec![false; n_exp];
525            let mut experts = Vec::with_capacity(n_exp);
526            for e in 0..n_exp {
527                let mut src = alias_of(li, e);
528                if !has(src) {
529                    missing[e] = true;
530                    src = first;
531                }
532                let x = format!("{m}experts.{src}.");
533                experts.push([
534                    t(model, &format!("{x}gate_proj.weight"))?,
535                    t(model, &format!("{x}up_proj.weight"))?,
536                    t(model, &format!("{x}down_proj.weight"))?,
537                ]);
538            }
539            let bias = keep_mask(li, f(model, &format!("{m}gate.e_score_correction_bias"))?);
540            let mut present = absent_mask(li, bias.len());
541            if missing.iter().any(|&v| v) {
542                let p = present.get_or_insert_with(|| vec![1.0; bias.len()]);
543                for (pv, &mi) in p.iter_mut().zip(&missing) {
544                    if mi {
545                        *pv = 0.0;
546                    }
547                }
548            }
549            let bias_ext = present.as_ref().map(|p| bias.iter().chain(p).copied().collect());
550            Ffn::Moe(Moe {
551                router: f(model, &format!("{m}gate.weight"))?,
552                bias,
553                present,
554                bias_ext,
555                missing,
556                down: t(model, &format!("{m}latent_down.weight"))?,
557                up: t(model, &format!("{m}latent_up.weight"))?,
558                shared: [
559                    t(model, &format!("{m}shared_experts.gate_proj.weight"))?,
560                    t(model, &format!("{m}shared_experts.up_proj.weight"))?,
561                    t(model, &format!("{m}shared_experts.down_proj.weight"))?,
562                ],
563                out_norm: f(model, &format!("{m}combine_output_norm.weight"))?,
564                experts,
565            })
566        };
567        let engram = match tc.get("engram").and_then(|e| e.get(format!("{li}"))) {
568            None => None,
569            Some(meta) => {
570                let d = format!("{p}engram.");
571                let lid = meta["layer_id"].as_u64().ok_or_else(|| err("engram layer_id"))? as usize;
572                let mult: Vec<u64> = meta["multipliers"].as_array().ok_or_else(|| err("engram multipliers"))?.iter().filter_map(|v| v.as_u64()).collect();
573                let moduli: Vec<u64> = tc["engram_layer_head_vocab_sizes"][format!("{lid}")]
574                    .as_array()
575                    .ok_or_else(|| err("engram head vocab sizes"))?
576                    .iter()
577                    .flat_map(|o| o.as_array().into_iter().flatten().filter_map(|v| v.as_u64()))
578                    .collect();
579                let mut offsets = Vec::with_capacity(moduli.len());
580                let mut acc = 0u64;
581                for &mo in &moduli {
582                    offsets.push(acc);
583                    acc += mo;
584                }
585                let te = model.tensor(&format!("{d}table")).ok_or_else(|| err(format!("{d}table")))?;
586                if te.shape.len() != 2 || te.shape[0] as u64 != acc {
587                    return Err(err(format!("{d}table rows {:?} != {acc}", te.shape)));
588                }
589                let hd = te.shape[1];
590                let lb = model.tensor_bytes(&format!("{d}lookup"))?;
591                let lookup = lb.chunks_exact(4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).collect();
592                Some(Engram {
593                    table: format!("{d}table"),
594                    table_scale: format!("{d}table_scale"),
595                    hd,
596                    lookup,
597                    mult,
598                    moduli,
599                    offsets,
600                    head_norms: f(model, &format!("{d}head_norms"))?,
601                    key: (0..hc).map(|j| t(model, &format!("{d}key_projs.{j}.weight"))).collect::<Result<_, _>>()?,
602                    key_b: (0..hc).map(|j| f(model, &format!("{d}key_projs.{j}.bias"))).collect::<Result<_, _>>()?,
603                    value: t(model, &format!("{d}value_proj.weight"))?,
604                    value_b: f(model, &format!("{d}value_proj.bias"))?,
605                    norm_key: (0..hc).map(|j| f(model, &format!("{d}norm_key.{j}.weight"))).collect::<Result<_, _>>()?,
606                    norm_query: (0..hc).map(|j| f(model, &format!("{d}norm_query.{j}.weight"))).collect::<Result<_, _>>()?,
607                    gamma: f(model, &format!("{d}pre_gamma"))?,
608                    hc_scales: f(model, &format!("{d}hc_scales"))?,
609                })
610            }
611        };
612        layers.push(Layer {
613            attn_hc: hc_of("attn_hc")?,
614            ffn_hc: hc_of("ffn_hc")?,
615            input_norm: f(model, &format!("{p}input_layernorm.weight"))?,
616            post_norm: f(model, &format!("{p}post_attention_layernorm.weight"))?,
617            attn,
618            ffn,
619            engram,
620        });
621    }
622    let mut state = State { pos: 0, tokens: Vec::new(), layers: Vec::new(), sequence_id: 0, graph: None };
623    state.reset(layers.len());
624    Ok((globals, layers, cfg, state))
625}
626
627impl Engram {
628    /// The table rows (one per hash head) of the n-gram ending at `pos`.
629    pub fn rows(&self, tokens: &[u32], pos: usize, cfg: &Cfg) -> Vec<u64> {
630        let table = self.lookup.len();
631        let comp = |p: Option<usize>| -> u64 {
632            let t = p.map_or(cfg.pad_id, |p| tokens[p]) as usize;
633            let t = if t < table { t } else { cfg.pad_id as usize };
634            self.lookup[t] as u64
635        };
636        let mixed: Vec<u64> = (0..cfg.max_ngram).map(|k| comp(pos.checked_sub(k)).wrapping_mul(self.mult[k])).collect();
637        let mut out = Vec::with_capacity(self.moduli.len());
638        for n in 2..=cfg.max_ngram {
639            let mut mix = mixed[0];
640            for m in &mixed[1..n] {
641                mix ^= *m;
642            }
643            let o0 = (n - 2) * cfg.n_per_ngram;
644            for h in 0..cfg.n_per_ngram {
645                out.push(self.offsets[o0 + h] + mix % self.moduli[o0 + h]);
646            }
647        }
648        out
649    }
650
651    /// The looked-up memory `[heads · hd]`: every row decoded (bf16 of
652    /// e4m3 times its scale, the reference's round trip) and RMS-normed.
653    pub fn memory(&self, model: &CmfModel, rows: &[u64]) -> Result<Vec<f32>, CmfError> {
654        let tab = model.tensor_bytes(&self.table)?;
655        let sc = model.tensor_bytes(&self.table_scale)?;
656        let hd = self.hd;
657        let mut out = Vec::with_capacity(rows.len() * hd);
658        for (h, &r) in rows.iter().enumerate() {
659            let r = r as usize;
660            let s = f32::from_bits((u16::from_le_bytes([sc[2 * r], sc[2 * r + 1]]) as u32) << 16);
661            let row: Vec<f32> = tab[r * hd..(r + 1) * hd].iter().map(|&b| bf16_round(e4m3(b) * s)).collect();
662            out.extend(rms_w(&row, &self.head_norms[h * hd..(h + 1) * hd], ENGRAM_EPS));
663        }
664        Ok(out)
665    }
666
667    /// Add the Engram residual to the `hc` streams.
668    pub fn apply(&self, streams: &mut [f32], mem: &[f32], cfg: &Cfg, pool: Option<&Pool>) {
669        let dim = cfg.dim;
670        let mut value = vec![0f32; dim];
671        self.value.matvec(mem, &mut value, pool);
672        for (v, b) in value.iter_mut().zip(&self.value_b) {
673            *v += b;
674        }
675        rms_plain(&mut value, ENGRAM_EPS);
676        for (v, g) in value.iter_mut().zip(&self.gamma) {
677            *v *= g;
678        }
679        let inv = (dim as f32).sqrt().recip();
680        for j in 0..cfg.hc {
681            let mut k = vec![0f32; dim];
682            self.key[j].matvec(mem, &mut k, pool);
683            for (v, b) in k.iter_mut().zip(&self.key_b[j]) {
684                *v += b;
685            }
686            let k = rms_w(&k, &self.norm_key[j], ENGRAM_EPS);
687            let s = &mut streams[j * dim..(j + 1) * dim];
688            let q = rms_w(s, &self.norm_query[j], ENGRAM_EPS);
689            let g = k.iter().zip(&q).map(|(a, b)| a * b).sum::<f32>() * inv;
690            let g = g.abs().max(1e-6).sqrt() * g.signum() * (g != 0.0) as u8 as f32;
691            let gate = sigmoid(g);
692            let hs = &self.hc_scales[j * dim..(j + 1) * dim];
693            for ((x, &m), &c) in s.iter_mut().zip(&value).zip(hs) {
694                *x += gate * m + c * m;
695            }
696        }
697    }
698}
699
700/// The groups a sparse query recalls past `cfg.candidate` positions:
701/// the `group_topk − 1` best complete groups before its own, then its own.
702fn select_groups(ix: &Indexer, ls: &LayerState, x: &[f32], q_resid: &[f32], pos: usize, cfg: &Cfg, pool: Option<&Pool>) -> Vec<usize> {
703    let (ih, id) = (cfg.ix_nh, cfg.ix_hd);
704    let own = pos / cfg.ratio;
705    let mut iq = vec![0f32; ih * id];
706    ix.q.matvec(q_resid, &mut iq, pool);
707    for h in 0..ih {
708        rope_half(&mut iq[h * id + id - cfg.rope..(h + 1) * id], &cfg.invf_dsa, pos);
709    }
710    let hscale = (ih as f32).sqrt().recip() * (id as f32).sqrt().recip();
711    let hw: Vec<f32> = (0..ih).map(|h| ix.hw[h * cfg.dim..(h + 1) * cfg.dim].iter().zip(x).map(|(a, b)| a * b).sum::<f32>() * hscale).collect();
712    let n = own.min(ls.gkeys.len() / id);
713    let mut scored: Vec<(usize, f32)> = (0..n)
714        .map(|g| {
715            let k = &ls.gkeys[g * id..(g + 1) * id];
716            let s = (0..ih)
717                .map(|h| {
718                    let d = iq[h * id..(h + 1) * id].iter().zip(k).map(|(a, b)| a * b).sum::<f32>();
719                    hw[h] * d.max(0.0)
720                })
721                .sum::<f32>();
722            (g, s)
723        })
724        .collect();
725    let keep = (cfg.group_topk - 1).min(scored.len());
726    scored.sort_unstable_by(|(ga, sa), (gb, sb)| sb.partial_cmp(sa).unwrap_or(std::cmp::Ordering::Equal).then(ga.cmp(gb)));
727    scored.truncate(keep);
728    let mut out: Vec<usize> = scored.into_iter().map(|(g, _)| g).collect();
729    out.push(own);
730    out
731}
732
733/// Pool the just-completed group `g` of a sparse layer's token keys into its
734/// key: `Σ_slot softmax_slot(kg·k + ape) ⊙ (kv·k)`, normed, rotated at the
735/// group's first position.
736fn pool_group(ix: &Indexer, ls: &mut LayerState, g: usize, cfg: &Cfg) {
737    let id = cfg.ix_hd;
738    let r = cfg.ratio;
739    let mut vals = vec![0f32; r * id];
740    let mut gates = vec![0f32; r * id];
741    for s in 0..r {
742        let k = &ls.tkeys[(g * r + s) * id..(g * r + s + 1) * id];
743        for d in 0..id {
744            vals[s * id + d] = ix.kv[d * id..(d + 1) * id].iter().zip(k).map(|(a, b)| a * b).sum();
745            gates[s * id + d] = ix.kg[d * id..(d + 1) * id].iter().zip(k).map(|(a, b)| a * b).sum::<f32>() + ix.ape[s * id + d];
746        }
747    }
748    let mut pooled = vec![0f32; id];
749    for d in 0..id {
750        let mx = (0..r).map(|s| gates[s * id + d]).fold(f32::NEG_INFINITY, f32::max);
751        let z: f32 = (0..r).map(|s| (gates[s * id + d] - mx).exp()).sum();
752        pooled[d] = (0..r).map(|s| (gates[s * id + d] - mx).exp() / z * vals[s * id + d]).sum();
753    }
754    let mut key = rms_w(&pooled, &ix.k_norm, cfg.eps);
755    rope_half(&mut key[id - cfg.rope..], &cfg.invf_dsa, g * r);
756    ls.gkeys.extend_from_slice(&key);
757}
758
759impl Attn {
760    fn kvb(&self) -> &[f32] {
761        self.kvb_f32.get_or_init(|| {
762            let (rows, cols) = (self.kv_b.rows(), self.kv_b.cols());
763            let mut v = vec![0f32; rows * cols];
764            for (r, row) in v.chunks_exact_mut(cols).enumerate() {
765                self.kv_b.row_f32(r, row);
766            }
767            v
768        })
769    }
770
771    fn forward(&self, x: &[f32], ls: &mut LayerState, pos: usize, cfg: &Cfg, pool: Option<&Pool>) -> Vec<f32> {
772        let (nh, rope, nope, vd, lora) = (self.nh, cfg.rope, cfg.nope, cfg.v, cfg.lora);
773        let hd = rope + nope;
774        let invf = if self.sliding { &cfg.invf_swa } else { &cfg.invf_dsa };
775        let mut qa = vec![0f32; self.q_a.rows()];
776        self.q_a.matvec(x, &mut qa, pool);
777        let q_resid = rms_w(&qa, &self.q_a_norm, cfg.eps);
778        let mut q = vec![0f32; nh * hd];
779        self.q_b.matvec(&q_resid, &mut q, pool);
780        let mut kv = vec![0f32; lora + rope];
781        self.kv_a.matvec(x, &mut kv, pool);
782        let lat = rms_w(&kv[..lora], &self.kv_a_norm, cfg.eps);
783        let mut kr = kv[lora..].to_vec();
784        rope_half(&mut kr, invf, pos);
785        for h in 0..nh {
786            rope_half(&mut q[h * hd..h * hd + rope], invf, pos);
787        }
788        ls.lat.extend_from_slice(&lat);
789        ls.kr.extend_from_slice(&kr);
790        let mut gate = vec![0f32; nh * vd];
791        self.gate.matvec(x, &mut gate, pool);
792
793        // the positions this query attends to
794        let n_have = ls.lat.len() / lora;
795        let positions: Vec<usize> = if self.sliding {
796            let lo = (pos + 1).saturating_sub(cfg.window);
797            (lo..=pos).collect()
798        } else {
799            let ix = self.indexer.as_ref().expect("a sparse layer has its indexer");
800            let mut tk = vec![0f32; cfg.ix_hd];
801            for (d, o) in tk.iter_mut().enumerate() {
802                *o = ix.tk[d * cfg.dim..(d + 1) * cfg.dim].iter().zip(x).map(|(a, b)| a * b).sum();
803            }
804            let tk = rms_w(&tk, &ix.tk_norm, cfg.eps);
805            ls.tkeys.extend_from_slice(&tk);
806            if (pos + 1) % cfg.ratio == 0 {
807                pool_group(ix, ls, pos / cfg.ratio, cfg);
808            }
809            if pos < cfg.candidate {
810                (0..=pos).collect()
811            } else {
812                let mut p = Vec::with_capacity(cfg.candidate);
813                for g in select_groups(ix, ls, x, &q_resid, pos, cfg, pool) {
814                    for s in g * cfg.ratio..((g + 1) * cfg.ratio).min(pos + 1) {
815                        p.push(s);
816                    }
817                }
818                p
819            }
820        };
821        let kvb = self.kvb();
822        let mut merged = vec![0f32; nh * vd];
823        let base = ls.base;
824        debug_assert!(n_have + base > pos);
825        let head = |h: usize, out: &mut [f32]| {
826            let qh = &q[h * hd..(h + 1) * hd];
827            let wk = &kvb[h * (nope + vd) * lora..(h * (nope + vd) + nope) * lora];
828            let wv = &kvb[(h * (nope + vd) + nope) * lora..(h + 1) * (nope + vd) * lora];
829            // absorbed query over the latent
830            let mut ql = vec![0f32; lora];
831            for r in 0..nope {
832                let qv = qh[rope + r];
833                for (o, &w) in ql.iter_mut().zip(&wk[r * lora..(r + 1) * lora]) {
834                    *o += qv * w;
835                }
836            }
837            let scores: Vec<f32> = positions
838                .iter()
839                .map(|&p| {
840                    let i = p - base;
841                    let l = &ls.lat[i * lora..(i + 1) * lora];
842                    let k = &ls.kr[i * rope..(i + 1) * rope];
843                    (ql.iter().zip(l).map(|(a, b)| a * b).sum::<f32>() + qh[..rope].iter().zip(k).map(|(a, b)| a * b).sum::<f32>()) * cfg.scale
844                })
845                .collect();
846            let sink = self.sinks[h];
847            let mx = scores.iter().copied().fold(sink, f32::max);
848            let z = scores.iter().map(|&s| (s - mx).exp()).sum::<f32>() + (sink - mx).exp();
849            let mut ol = vec![0f32; lora];
850            for (&p, &s) in positions.iter().zip(&scores) {
851                let w = (s - mx).exp() / z;
852                let i = p - base;
853                for (o, &l) in ol.iter_mut().zip(&ls.lat[i * lora..(i + 1) * lora]) {
854                    *o += w * l;
855                }
856            }
857            for (d, o) in out.iter_mut().enumerate() {
858                *o = wv[d * lora..(d + 1) * lora].iter().zip(&ol).map(|(a, b)| a * b).sum();
859            }
860        };
861        match pool {
862            Some(p) => {
863                let ptr = merged.as_mut_ptr() as usize;
864                p.run_rows(nh, &|a, b| {
865                    for h in a..b {
866                        // SAFETY: each head writes its own disjoint vd-wide slice
867                        let out = unsafe { std::slice::from_raw_parts_mut((ptr as *mut f32).add(h * vd), vd) };
868                        head(h, out);
869                    }
870                });
871            }
872            None => {
873                for (h, out) in merged.chunks_mut(vd).enumerate() {
874                    head(h, out);
875                }
876            }
877        }
878        for (m, g) in merged.iter_mut().zip(&gate) {
879            *m *= sigmoid(*g);
880        }
881        let mut out = vec![0f32; cfg.dim];
882        self.o.matvec(&merged, &mut out, pool);
883        // a sliding layer forgets what left its window
884        if self.sliding && ls.lat.len() / lora > 2 * cfg.window {
885            let drop = ls.lat.len() / lora - cfg.window;
886            ls.lat.drain(..drop * lora);
887            ls.kr.drain(..drop * rope);
888            ls.base += drop;
889        }
890        rms_w(&out, &self.post_norm, cfg.eps)
891    }
892}
893
894fn swiglu(g: &mut [f32], u: &[f32], limit: f32) {
895    for (a, &b) in g.iter_mut().zip(u) {
896        let (ga, ub) = if limit > 0.0 { (a.min(limit), b.clamp(-limit, limit)) } else { (*a, b) };
897        *a = ga / (1.0 + (-ga).exp()) * ub;
898    }
899}
900
901fn dense(gate: &QTensor, up: &QTensor, down: &QTensor, x: &[f32], limit: f32, pool: Option<&Pool>) -> Vec<f32> {
902    let mut g = vec![0f32; gate.rows()];
903    let mut u = vec![0f32; up.rows()];
904    gate.matvec(x, &mut g, pool);
905    up.matvec(x, &mut u, pool);
906    swiglu(&mut g, &u, limit);
907    let mut out = vec![0f32; down.rows()];
908    down.matvec(&g, &mut out, pool);
909    out
910}
911
912impl Moe {
913    /// The selected experts and their mixing weights.
914    pub fn route(&self, x: &[f32], cfg: &Cfg) -> Vec<(usize, f32)> {
915        let dim = cfg.dim;
916        let ne = self.bias.len();
917        let scores: Vec<f32> = (0..ne).map(|e| sigmoid(self.router[e * dim..(e + 1) * dim].iter().zip(x).map(|(a, b)| a * b).sum())).collect();
918        let mut order: Vec<usize> = (0..ne).collect();
919        order.sort_unstable_by(|&a, &b| (scores[b] + self.bias[b]).partial_cmp(&(scores[a] + self.bias[a])).unwrap_or(std::cmp::Ordering::Equal).then(a.cmp(&b)));
920        order.truncate(cfg.top_k);
921        let sum: f32 = order.iter().map(|&e| scores[e]).sum::<f32>() + 1e-20;
922        order.into_iter().map(|e| (e, scores[e] / sum * cfg.route_scale * self.present.as_ref().map_or(1.0, |p| p[e]))).collect()
923    }
924
925    fn forward(&self, x: &[f32], cfg: &Cfg, pool: Option<&Pool>) -> Vec<f32> {
926        let picks = self.route(x, cfg);
927        let mut lat = vec![0f32; cfg.latent];
928        self.down.matvec(x, &mut lat, pool);
929        let mut acc = vec![0f32; cfg.latent];
930        for &(e, w) in &picks {
931            if w == 0.0 {
932                continue;
933            }
934            let [g, u, d] = &self.experts[e];
935            let y = dense(g, u, d, &lat, cfg.limit, pool);
936            for (a, v) in acc.iter_mut().zip(&y) {
937                *a += w * v;
938            }
939        }
940        let mut routed = vec![0f32; cfg.dim];
941        self.up.matvec(&acc, &mut routed, pool);
942        let sh = dense(&self.shared[0], &self.shared[1], &self.shared[2], x, 0.0, pool);
943        for (r, s) in routed.iter_mut().zip(&sh) {
944            *r += s;
945        }
946        rms_w(&routed, &self.out_norm, cfg.eps)
947    }
948}
949
950/// `CMF_HY4_DUMP=<dir>,<pos>,<pos>…`: the host stack writes every layer's
951/// attention output and streams at those positions (`<dir>/<kind>_l<li>_p<pos>.f32`),
952/// for a layer-by-layer diff against the reference.
953fn dump(li: usize, pos: usize, kind: &str, v: &[f32]) {
954    static CFG: std::sync::OnceLock<Option<(String, Vec<usize>)>> = std::sync::OnceLock::new();
955    let cfg = CFG.get_or_init(|| {
956        let s = std::env::var("CMF_HY4_DUMP").ok()?;
957        let mut it = s.split(',');
958        let dir = it.next()?.to_string();
959        Some((dir, it.filter_map(|p| p.parse().ok()).collect()))
960    });
961    if let Some((dir, ps)) = cfg {
962        if ps.contains(&pos) {
963            let b: Vec<u8> = v.iter().flat_map(|x| x.to_le_bytes()).collect();
964            let _ = std::fs::write(format!("{dir}/{kind}_l{li}_p{pos}.f32"), b);
965        }
966    }
967}
968
969/// One routed FFN's SFq calibration rows (`capture`): the latent input of
970/// every captured token (f16, `latent` wide), its `top_k` picks and their
971/// mixing weights, as the forward routes them.
972pub struct CapLayer {
973    pub li: usize,
974    pub x: Vec<u16>,
975    pub picks: Vec<u16>,
976    pub w: Vec<f32>,
977}
978
979impl Moe {
980    /// The picks and mixing weights from the router's logits (`route`'s rule).
981    fn route_logits(&self, logits: &[f32], cfg: &Cfg) -> Vec<(usize, f32)> {
982        let ne = self.bias.len();
983        let scores: Vec<f32> = logits[..ne].iter().map(|&l| sigmoid(l)).collect();
984        let mut order: Vec<usize> = (0..ne).collect();
985        order.sort_unstable_by(|&a, &b| (scores[b] + self.bias[b]).partial_cmp(&(scores[a] + self.bias[a])).unwrap_or(std::cmp::Ordering::Equal).then(a.cmp(&b)));
986        order.truncate(cfg.top_k);
987        let sum: f32 = order.iter().map(|&e| scores[e]).sum::<f32>() + 1e-20;
988        order.into_iter().map(|e| (e, scores[e] / sum * cfg.route_scale * self.present.as_ref().map_or(1.0, |p| p[e]))).collect()
989    }
990}
991
992/// SFq calibration: every window through the card's prompt graph (CUDA
993/// hybrid) with the capture armed; per routed FFN, the latent rows of the
994/// window's tokens and the router's picks. A window is followed by one more
995/// token so all of its own rows take the batch path. Each routed FFN's rows
996/// of a window go to `sink` as they come; returns the tokens captured.
997pub fn capture(
998    globals: &Globals,
999    layers: &[Layer],
1000    cfg: &Cfg,
1001    state: &mut State,
1002    windows: &[Vec<u32>],
1003    sink: &mut dyn FnMut(&CapLayer) -> Result<(), String>,
1004    mut nll: Option<&mut Vec<f32>>,
1005) -> Result<usize, String> {
1006    let moe: Vec<usize> = layers.iter().enumerate().filter(|(_, l)| matches!(l.ffn, Ffn::Moe(_))).map(|(i, _)| i).collect();
1007    let ne = layers.iter().find_map(|l| match &l.ffn {
1008        Ffn::Moe(m) => Some(m.bias.len()),
1009        _ => None,
1010    });
1011    let ne = ne.ok_or("no routed FFN")?;
1012    let dim = cfg.latent;
1013    let t0 = std::time::Instant::now();
1014    let mut done = 0usize;
1015    for (wi, w) in windows.iter().enumerate() {
1016        if w.is_empty() {
1017            continue;
1018        }
1019        if !crate::gpu::hy4_capture_begin(moe.len(), dim, ne) {
1020            return Err("the capture needs the CUDA backend (CMF_GPU=cuda)".into());
1021        }
1022        state.reset(layers.len());
1023        let mut ids = w.clone();
1024        ids.push(*w.last().unwrap());
1025        let mut lg = Vec::new();
1026        // with `nll`: the window's rows kept, every row's loss on its next token
1027        // (the last row of a window has none: NaN), in the order of the picks
1028        let taken = match nll.as_mut() {
1029            Some(out) => {
1030                let mut hrows = Vec::new();
1031                let t = prompt_rows(globals, layers, cfg, state, w, 0, None, Some(&mut hrows));
1032                if t == w.len() && hrows.len() == w.len() * cfg.dim {
1033                    out.extend(row_nll(globals, cfg, &hrows, w));
1034                    ids.len()
1035                } else {
1036                    t
1037                }
1038            }
1039            None => forward_prompt(globals, layers, cfg, state, &ids, 0, None, &mut lg),
1040        };
1041        let rows = crate::gpu::hy4_capture_take().ok_or("the capture lost its rows")?;
1042        if taken != ids.len() || rows.len() != moe.len() {
1043            return Err(format!("window {wi}: the card's prompt graph took {taken} of {} rows ({} routed FFNs captured)", ids.len(), rows.len()));
1044        }
1045        for (k, (lat, logits)) in rows.iter().enumerate() {
1046            let n = lat.len() / dim;
1047            if n < w.len() || logits.len() < n * ne {
1048                return Err(format!("window {wi}: layer {} captured {n} rows of {}", moe[k], w.len()));
1049            }
1050            let Ffn::Moe(m) = &layers[moe[k]].ffn else { unreachable!() };
1051            let mut o = CapLayer { li: moe[k], x: Vec::with_capacity(w.len() * dim), picks: Vec::with_capacity(w.len() * cfg.top_k), w: Vec::with_capacity(w.len() * cfg.top_k) };
1052            o.x.extend(lat[..w.len() * dim].iter().map(|&v| cortiq_core::quant::f32_to_f16(v)));
1053            for r in 0..w.len() {
1054                for (e, wt) in m.route_logits(&logits[r * ne..(r + 1) * ne], cfg) {
1055                    o.picks.push(e as u16);
1056                    o.w.push(wt);
1057                }
1058            }
1059            sink(&o)?;
1060        }
1061        done += w.len();
1062        tracing::info!("hy_v4_flash capture: window {}/{} ({done} tokens, {:.0} s)", wi + 1, windows.len(), t0.elapsed().as_secs_f64());
1063    }
1064    state.reset(layers.len());
1065    Ok(done)
1066}
1067
1068/// Every row's loss on the window's next token from the stack's rows
1069/// (`hrows`, before the final norm); the last row NaN.
1070fn row_nll(globals: &Globals, cfg: &Cfg, hrows: &[f32], w: &[u32]) -> Vec<f32> {
1071    let (n, dim) = (w.len(), cfg.dim);
1072    let vocab = globals.lm_head.rows();
1073    let mut res = vec![f32::NAN; n];
1074    const B: usize = 64;
1075    let mut out = vec![0f32; B * vocab];
1076    let mut xs = vec![0f32; B * dim];
1077    let mut r0 = 0;
1078    while r0 + 1 < n {
1079        let b = B.min(n - 1 - r0);
1080        for j in 0..b {
1081            let x = rms_w(&hrows[(r0 + j) * dim..(r0 + j + 1) * dim], &globals.norm, cfg.eps);
1082            xs[j * dim..(j + 1) * dim].copy_from_slice(&x);
1083        }
1084        globals.lm_head.matmat(&xs[..b * dim], b, &mut out[..b * vocab], None);
1085        for j in 0..b {
1086            let row = &out[j * vocab..(j + 1) * vocab];
1087            let target = (w[r0 + j + 1] as usize).min(vocab - 1);
1088            let best = row.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v)) as f64;
1089            let den: f64 = row.iter().map(|&v| ((v as f64) - best).exp()).sum();
1090            res[r0 + j] = (den.ln() - (row[target] as f64 - best)) as f32;
1091        }
1092        r0 += b;
1093    }
1094    res
1095}
1096
1097/// Fold the streams with `pre`.
1098fn fold(streams: &[f32], pre: &[f32], dim: usize) -> Vec<f32> {
1099    let mut out = vec![0f32; dim];
1100    for (j, &p) in pre.iter().enumerate() {
1101        for (o, &s) in out.iter_mut().zip(&streams[j * dim..(j + 1) * dim]) {
1102            *o += p * s;
1103        }
1104    }
1105    out
1106}
1107
1108/// Return `y` to every stream with its `post` weight.
1109fn expand(streams: &mut [f32], post: &[f32], y: &[f32], dim: usize) {
1110    for (j, &p) in post.iter().enumerate() {
1111        for (s, &v) in streams[j * dim..(j + 1) * dim].iter_mut().zip(y) {
1112            *s += p * v;
1113        }
1114    }
1115}
1116
1117const GRAPH_CAP: usize = 1 << 20;
1118
1119fn graph_on() -> bool {
1120    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1121    *ON.get_or_init(|| std::env::var("CMF_HY4_GRAPH").as_deref() != Ok("0"))
1122}
1123
1124fn gw(t: &QTensor) -> Option<crate::gpu::GraphW<'_>> {
1125    if let Some((_, i, kind, rs)) = t.graph_weight_or_blr() {
1126        return Some(crate::gpu::GraphW { idx: i, kind, row_scale: rs, data: &[], prism: crate::gpu::GraphPrismOp::None, affine: false });
1127    }
1128    t.as_f32().map(|d| crate::gpu::GraphW { idx: 0, kind: 4, row_scale: &[], data: d, prism: crate::gpu::GraphPrismOp::None, affine: false })
1129}
1130
1131fn gf(d: &[f32]) -> crate::gpu::GraphW<'_> {
1132    crate::gpu::GraphW { idx: 0, kind: 4, row_scale: &[], data: d, prism: crate::gpu::GraphPrismOp::None, affine: false }
1133}
1134
1135/// The call's Engram memory rows of every Engram layer (the host's hash and
1136/// table read), for the tokens at `positions` of `tokens`.
1137fn engram_rows(globals: &Globals, layers: &[Layer], cfg: &Cfg, tokens: &[u32], positions: std::ops::Range<usize>) -> Option<Vec<(Vec<f32>, Vec<bool>)>> {
1138    // the tables' rows are reads of a large mapping, a page each: they fault
1139    // in in parallel (`CMF_HY4_ENGRAM_THREADS`, 32; on a pod whose page cache
1140    // cannot hold the 63 GB of tables, one thread took 5-15 s a 512-row chunk)
1141    static THREADS: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1142    let threads = *THREADS.get_or_init(|| std::env::var("CMF_HY4_ENGRAM_THREADS").ok().and_then(|v| v.parse::<usize>().ok()).unwrap_or(32).max(1));
1143    let pos: Vec<usize> = positions.collect();
1144    let mut out = Vec::new();
1145    for l in layers {
1146        let Some(e) = &l.engram else { continue };
1147        let width = e.hd * e.moduli.len();
1148        let per = pos.len().div_ceil(threads).max(16);
1149        let parts: Vec<Option<Vec<f32>>> = std::thread::scope(|sc| {
1150            let hs: Vec<_> = pos
1151                .chunks(per)
1152                .map(|ch| {
1153                    sc.spawn(move || {
1154                        let mut mem = Vec::with_capacity(ch.len() * width);
1155                        for &p in ch {
1156                            let rows = e.rows(tokens, p, cfg);
1157                            mem.extend(e.memory(&globals.model, &rows).ok()?);
1158                        }
1159                        Some(mem)
1160                    })
1161                })
1162                .collect();
1163            hs.into_iter().map(|h| h.join().ok().flatten()).collect()
1164        });
1165        let mut mem = Vec::with_capacity(pos.len() * width);
1166        for p in parts {
1167            mem.extend(p?);
1168        }
1169        let on: Vec<bool> = pos
1170            .iter()
1171            .map(|&p| {
1172                let t = tokens[p];
1173                t != cfg.image_id && t != cfg.video_id && t != cfg.pad_id
1174            })
1175            .collect();
1176        out.push((mem, on));
1177    }
1178    Some(out)
1179}
1180
1181/// The stack as graph layers for a call ending at `end` positions (None: a
1182/// weight the graphs cannot address, or a sparse layer past its dense range,
1183/// whose indexer has no device arm yet).
1184fn graph_layers<'a>(globals: &'a Globals, layers: &'a [Layer], cfg: &'a Cfg, eng: &'a [(Vec<f32>, Vec<bool>)], end: usize) -> Option<Vec<crate::gpu::GraphLayer<'a>>> {
1185    use crate::gpu::{GraphAct, GraphAttn, GraphEngram, GraphFfn, GraphHyIndexer, GraphLayer, GraphMhc, GraphMhcDsv4, GraphMhcHead, GraphMlaHy, GraphMoeDetachedShared, GraphMoeLatent};
1186    // `CMF_HY4_DEVICE_INDEXER=0`: the card stops at the dense range of the sparse layers
1187    if end > cfg.candidate && std::env::var("CMF_HY4_DEVICE_INDEXER").as_deref() == Ok("0") {
1188        return None;
1189    }
1190    let last = layers.len().checked_sub(1)?;
1191    let mut ei = 0usize;
1192    let mut out = Vec::with_capacity(layers.len());
1193    for (li, l) in layers.iter().enumerate() {
1194        let a = &l.attn;
1195        let attn = GraphAttn::Mla {
1196            q_a: Some(gw(&a.q_a)?),
1197            q_a_norm: Some(&a.q_a_norm),
1198            q: gw(&a.q_b)?,
1199            kv_a: gw(&a.kv_a)?,
1200            kv_a_norm: &a.kv_a_norm,
1201            kv_b: gw(&a.kv_b)?,
1202            o: gw(&a.o)?,
1203            nh: a.nh,
1204            rope: cfg.rope,
1205            nope: cfg.nope,
1206            v_dim: cfg.v,
1207            lora: cfg.lora,
1208            scale: cfg.scale,
1209            no_rope: false,
1210            cpu_k: &[],
1211            cpu_v: &[],
1212            cpu_base: 0,
1213            dsa: None,
1214            hy: Some(GraphMlaHy {
1215                gate: gw(&a.gate)?,
1216                sinks: &a.sinks,
1217                window: a.sliding.then_some(cfg.window),
1218                invf: if a.sliding { &cfg.invf_swa } else { &cfg.invf_dsa },
1219                indexer: match &a.indexer {
1220                    Some(ix) => Some(GraphHyIndexer {
1221                        q: gw(&ix.q)?,
1222                        hw: &ix.hw,
1223                        tk: &ix.tk,
1224                        tk_norm: &ix.tk_norm,
1225                        kv: &ix.kv,
1226                        kg: &ix.kg,
1227                        k_norm: &ix.k_norm,
1228                        ape: &ix.ape,
1229                        ih: cfg.ix_nh,
1230                        id: cfg.ix_hd,
1231                        ratio: cfg.ratio,
1232                        group_topk: cfg.group_topk,
1233                        kv_b: a.kvb(),
1234                    }),
1235                    None => None,
1236                },
1237            }),
1238        };
1239        let (ffn, ffn_out) = match &l.ffn {
1240            Ffn::Dense { gate, up, down, out_norm } => (
1241                GraphFfn::Dense { gate: gw(gate)?, up: gw(up)?, down: gw(down)?, act: GraphAct::Silu, limit: 0.0, hot: None },
1242                &out_norm[..],
1243            ),
1244            Ffn::Moe(m) => {
1245                let e0 = m.experts.first()?;
1246                let gu_q2 = e0[0].mapped_q2tp().is_some();
1247                if !(gu_q2 || e0[0].mapped_q4tp().is_some()) || e0[2].mapped_q4tp().is_none() {
1248                    return None;
1249                }
1250                // absent experts: no tensors on the card (usize::MAX), which only
1251                // the CUDA hybrid knows; elsewhere the layer stays on the host
1252                if m.missing.iter().any(|&v| v) && !crate::gpu::cuda_active() {
1253                    return None;
1254                }
1255                let experts = m
1256                    .experts
1257                    .iter()
1258                    .zip(&m.missing)
1259                    .map(|([g, u, d], &mi)| if mi { Some((usize::MAX, usize::MAX, usize::MAX)) } else { Some((g.model_idx()?, u.model_idx()?, d.model_idx()?)) })
1260                    .collect::<Option<Vec<_>>>()?;
1261                (
1262                    GraphFfn::Moe {
1263                        router: gf(&m.router),
1264                        shared_gate: gf(&m.router),
1265                        experts,
1266                        n_exp: m.experts.len(),
1267                        top_k: cfg.top_k,
1268                        inter: e0[0].rows(),
1269                        act: GraphAct::Silu,
1270                        norm_topk: true,
1271                        q4tp: true,
1272                        gu_q2,
1273                        q82: false,
1274                        sigmoid: true,
1275                        sigmoid_denom_eps: 1e-20,
1276                        bias: Some(m.bias_ext.as_deref().unwrap_or(&m.bias)),
1277                        has_shared: false,
1278                        detached_shared: Some(GraphMoeDetachedShared {
1279                            gate: gw(&m.shared[0])?,
1280                            up: gw(&m.shared[1])?,
1281                            down: gw(&m.shared[2])?,
1282                            width: m.shared[0].rows(),
1283                        }),
1284                        shared_gated: false,
1285                        route_scale: cfg.route_scale,
1286                        limit: cfg.limit,
1287                        shared_limit: Some(0.0),
1288                        latent: Some(GraphMoeLatent { down: gw(&m.down)?, up: gw(&m.up)?, dim: cfg.latent }),
1289                    },
1290                    &m.out_norm[..],
1291                )
1292            }
1293        };
1294        let engram = match &l.engram {
1295            Some(e) => {
1296                let (mem, on) = eng.get(ei)?;
1297                ei += 1;
1298                Some(GraphEngram {
1299                    mem,
1300                    on,
1301                    mem_dim: e.hd * e.moduli.len(),
1302                    value: gw(&e.value)?,
1303                    value_b: &e.value_b,
1304                    keys: e.key.iter().map(gw).collect::<Option<Vec<_>>>()?,
1305                    key_b: e.key_b.iter().map(|v| &v[..]).collect(),
1306                    norm_key: e.norm_key.iter().map(|v| &v[..]).collect(),
1307                    norm_query: e.norm_query.iter().map(|v| &v[..]).collect(),
1308                    gamma: &e.gamma,
1309                    hc_scales: &e.hc_scales,
1310                    eps: ENGRAM_EPS as f32,
1311                })
1312            }
1313            None => None,
1314        };
1315        out.push(GraphLayer {
1316            mhc: Some(GraphMhc {
1317                attn_w: &l.attn_hc.function,
1318                attn_b: &l.attn_hc.base,
1319                ffn_w: &l.ffn_hc.function,
1320                ffn_b: &l.ffn_hc.base,
1321                enter: li == 0,
1322                leave: li == last,
1323                iters: 0,
1324                pre_scale: 1.0,
1325                dsv4: Some(GraphMhcDsv4 {
1326                    attn_scale: [l.attn_hc.scale[0], l.attn_hc.scale[1], 0.0],
1327                    ffn_scale: [l.ffn_hc.scale[0], l.ffn_hc.scale[1], 0.0],
1328                    eps: cfg.hc_eps,
1329                    rms_eps: cfg.eps as f32,
1330                    ihc: Some(cfg.mag),
1331                }),
1332                head: (li == last).then_some(GraphMhcHead { w: &globals.head_fn, base: &globals.head_base, scale: globals.head_scale }),
1333            }),
1334            input_norm: &l.input_norm,
1335            attn,
1336            post_norm: &l.post_norm,
1337            ffn,
1338            attn_out_norm: Some(&a.post_norm),
1339            ffn_out_norm: Some(ffn_out),
1340            layer_scale: None,
1341            engram,
1342        });
1343    }
1344    Some(out)
1345}
1346
1347/// The call-wide geometry: the widest query heads, head width, softmax
1348/// scale and the widest FFN.
1349fn graph_geom(layers: &[Layer], cfg: &Cfg) -> (usize, usize, f32, usize) {
1350    let nh = layers.iter().map(|l| l.attn.nh).max().unwrap_or(1);
1351    let inter = layers
1352        .iter()
1353        .map(|l| match &l.ffn {
1354            Ffn::Dense { gate, .. } => gate.rows(),
1355            Ffn::Moe(m) => m.experts.first().map_or(0, |e| e[0].rows()).max(m.shared[0].rows()),
1356        })
1357        .max()
1358        .unwrap_or(0);
1359    (nh, cfg.rope + cfg.nope, cfg.scale, inter)
1360}
1361
1362/// The host takes the sequence over from the card: its tokens replayed
1363/// through the host stack.
1364fn host_replay(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, pool: Option<&Pool>) {
1365    let toks = std::mem::take(&mut state.tokens);
1366    tracing::warn!("hy_v4_flash: the host replays {} tokens the card held", toks.len());
1367    state.reset(layers.len());
1368    state.graph = Some(false);
1369    let mut scratch = Vec::new();
1370    for (p, &t) in toks.iter().enumerate() {
1371        host_token(globals, layers, cfg, state, t, p, pool, &mut scratch, false);
1372    }
1373}
1374
1375/// A prompt's positions `start..` through the card's batch graph (the rows in
1376/// chunks), its last one through the token graph with the logits. Returns
1377/// the positions taken (0: none, the caller goes a token at a time).
1378#[allow(clippy::too_many_arguments)]
1379pub fn forward_prompt(
1380    globals: &Globals,
1381    layers: &[Layer],
1382    cfg: &Cfg,
1383    state: &mut State,
1384    ids: &[u32],
1385    start: usize,
1386    pool: Option<&Pool>,
1387    logits: &mut Vec<f32>,
1388) -> usize {
1389    if ids.len() < 2 {
1390        return 0;
1391    }
1392    let body = ids.len() - 1;
1393    let done = prompt_rows(globals, layers, cfg, state, &ids[..body], start, pool, None);
1394    if done < body {
1395        return done;
1396    }
1397    forward_token(globals, layers, cfg, state, ids[body], start + body, pool, logits, true);
1398    ids.len()
1399}
1400
1401/// `ids` from `start` on through the card's prompt graph, a chunk a call
1402/// (`CMF_HY4_PROMPT_CHUNK`, 512); with `keep`, every row's hidden state
1403/// after the stack (the head's fold, before the final norm) appended to it.
1404/// Returns the rows the card took.
1405#[allow(clippy::too_many_arguments)]
1406fn prompt_rows(
1407    globals: &Globals,
1408    layers: &[Layer],
1409    cfg: &Cfg,
1410    state: &mut State,
1411    ids: &[u32],
1412    start: usize,
1413    pool: Option<&Pool>,
1414    mut keep: Option<&mut Vec<f32>>,
1415) -> usize {
1416    use crate::gpu::BatchGraphOutcome;
1417    if ids.is_empty() || !graph_on() || !(crate::gpu::cuda_active() || crate::gpu::wgpu_active()) {
1418        return 0;
1419    }
1420    if start == 0 || state.pos != start {
1421        state.reset(layers.len());
1422    }
1423    if state.graph == Some(false) || (start > 0 && state.graph != Some(true)) {
1424        return 0;
1425    }
1426    let model = globals.model.clone();
1427    let (nh, hd, scale, inter) = graph_geom(layers, cfg);
1428    let dim = cfg.dim;
1429    // long calls: a streamed layer's experts cross the bus once a call (the
1430    // CUDA hybrid runs a long prompt a layer at a time), and the Engram rows
1431    // of a call fault in together — 2048 rows on a card of 32 GB and more
1432    // (wgpu: chunks of 16 rows, `gpu_wgpu::hy4_wgpu_rows`)
1433    let big = crate::gpu::vram_budget() >= 32 << 30;
1434    #[cfg(feature = "gpu")]
1435    let small = if crate::gpu::wgpu_active() { Some(crate::gpu_wgpu::hy4_wgpu_rows()) } else { None };
1436    #[cfg(not(feature = "gpu"))]
1437    let small: Option<usize> = None;
1438    let chunk = std::env::var("CMF_HY4_PROMPT_CHUNK")
1439        .ok()
1440        .and_then(|v| v.trim().parse::<usize>().ok())
1441        .unwrap_or(small.unwrap_or(if big { 2048 } else { 512 }))
1442        .max(1);
1443    let body = ids.len();
1444    let mut done = 0usize;
1445    let mut all: Vec<u32> = state.tokens.clone();
1446    all.extend_from_slice(ids);
1447    let timing = std::env::var_os("CMF_CUDA_PROF").is_some();
1448    while done < body {
1449        let end = (done + chunk).min(body);
1450        let k = end - done;
1451        let t0 = std::time::Instant::now();
1452        let Some(eng) = engram_rows(globals, layers, cfg, &all, start + done..start + end) else { return done };
1453        let t1 = std::time::Instant::now();
1454        let Some(gl) = graph_layers(globals, layers, cfg, &eng, start + end) else { return done };
1455        let t2 = std::time::Instant::now();
1456        let o1: Vec<Option<Vec<crate::nystrom::O1DeviceView<'_>>>> = (0..gl.len()).map(|_| None).collect();
1457        let mut h = vec![0.0f32; k * dim];
1458        for (j, &t) in ids[done..end].iter().enumerate() {
1459            if (t as usize) < globals.embed.rows() {
1460                globals.embed.row_f32(t as usize, &mut h[j * dim..(j + 1) * dim]);
1461            }
1462        }
1463        let positions: Vec<usize> = (start + done..start + end).collect();
1464        let outcome = crate::gpu::forward_batch_graph_at(
1465            &model, state.kv_id(), 0, &gl, &cfg.invf_swa, &mut h, nh, nh, hd, cfg.rope, dim, inter, &positions, GRAPH_CAP, false, cfg.eps as f32, scale, k, &o1, 0, None, None,
1466        );
1467        if timing {
1468            tracing::info!(
1469                "hy_v4_flash prompt chunk of {k} rows: engram rows {:.2} s, layer views {:.2} s, the card {:.2} s",
1470                (t1 - t0).as_secs_f64(),
1471                (t2 - t1).as_secs_f64(),
1472                t2.elapsed().as_secs_f64()
1473            );
1474        }
1475        match outcome {
1476            BatchGraphOutcome::Completed => {
1477                if state.graph.is_none() {
1478                    tracing::info!("hy_v4_flash: the prompt runs on the card's batch graph");
1479                }
1480                state.graph = Some(true);
1481                state.tokens.extend_from_slice(&ids[done..end]);
1482                state.pos = start + end;
1483                done = end;
1484                if let Some(kp) = keep.as_deref_mut() {
1485                    kp.extend_from_slice(&h);
1486                }
1487            }
1488            BatchGraphOutcome::Declined => return done,
1489            BatchGraphOutcome::Failed => {
1490                host_replay(globals, layers, cfg, state, pool);
1491                return done;
1492            }
1493        }
1494    }
1495    done
1496}
1497
1498/// Perplexity on the card's prompt graph (`CMF_HY4_NLL_BATCH=0`: the token
1499/// path): the rows of `ids[..n−1]` through the stack in long calls, the final
1500/// norm and the head on the host, `nll` of every next token from `from` on.
1501/// None when the card does not take the window (the caller scores it the
1502/// token way). The same function the token path computes, chunked the way a
1503/// prompt is.
1504pub fn nll(globals: &Globals, layers: &[Layer], cfg: &Cfg, state: &mut State, ids: &[u32], from: usize, pool: Option<&Pool>) -> Option<(f64, usize)> {
1505    if std::env::var("CMF_HY4_NLL_BATCH").as_deref() == Ok("0") || ids.len() < 2 {
1506        return None;
1507    }
1508    let n = ids.len() - 1;
1509    let dim = cfg.dim;
1510    let t0 = std::time::Instant::now();
1511    state.reset(layers.len());
1512    let mut rows = Vec::with_capacity(n * dim);
1513    if prompt_rows(globals, layers, cfg, state, &ids[..n], 0, pool, Some(&mut rows)) != n || rows.len() != n * dim {
1514        state.reset(layers.len());
1515        return None;
1516    }
1517    state.reset(layers.len());
1518    let t_rows = t0.elapsed().as_secs_f64();
1519    let vocab = globals.lm_head.rows();
1520    let (mut nll, mut cnt) = (0f64, 0usize);
1521    const B: usize = 64;
1522    let mut out = vec![0f32; B * vocab];
1523    let mut xs = vec![0f32; B * dim];
1524    let mut r0 = from.min(n);
1525    while r0 < n {
1526        let b = B.min(n - r0);
1527        for j in 0..b {
1528            let x = rms_w(&rows[(r0 + j) * dim..(r0 + j + 1) * dim], &globals.norm, cfg.eps);
1529            xs[j * dim..(j + 1) * dim].copy_from_slice(&x);
1530        }
1531        globals.lm_head.matmat(&xs[..b * dim], b, &mut out[..b * vocab], pool);
1532        for j in 0..b {
1533            let row = &out[j * vocab..(j + 1) * vocab];
1534            let target = ids[r0 + j + 1] as usize;
1535            let best = row.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v)) as f64;
1536            let den: f64 = row.iter().map(|&v| ((v as f64) - best).exp()).sum();
1537            nll += den.ln() - (row[target.min(vocab - 1)] as f64 - best);
1538            cnt += 1;
1539        }
1540        r0 += b;
1541    }
1542    tracing::info!("hy_v4_flash nll: {n} rows through the card in {t_rows:.1} s ({:.1} rows/s), the head on the host {:.1} s", n as f64 / t_rows.max(1e-9), t0.elapsed().as_secs_f64() - t_rows);
1543    #[cfg(feature = "cuda")]
1544    if std::env::var_os("CMF_CUDA_PROF").is_some() {
1545        crate::gpu_cuda::perf_report();
1546    }
1547    Some((nll, cnt))
1548}
1549
1550/// One token through the card's graph: the embedding in, the logits out.
1551#[allow(clippy::too_many_arguments)]
1552fn 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 {
1553    use crate::gpu::TokenGraphOutcome;
1554    if !graph_on() || !(crate::gpu::cuda_active() || crate::gpu::wgpu_active()) {
1555        return TokenGraphOutcome::Declined;
1556    }
1557    let Some(head) = gw(&globals.lm_head) else { return TokenGraphOutcome::Declined };
1558    let mut toks = state.tokens.clone();
1559    toks.push(token_id);
1560    let Some(eng) = engram_rows(globals, layers, cfg, &toks, position..position + 1) else { return TokenGraphOutcome::Declined };
1561    let Some(gl) = graph_layers(globals, layers, cfg, &eng, position + 1) else { return TokenGraphOutcome::Declined };
1562    let (nh, hd, scale, inter) = graph_geom(layers, cfg);
1563    let mut h = vec![0.0f32; cfg.dim];
1564    if (token_id as usize) < globals.embed.rows() {
1565        globals.embed.row_f32(token_id as usize, &mut h);
1566    }
1567    let o1: Vec<Option<Vec<crate::nystrom::O1DeviceView<'_>>>> = (0..gl.len()).map(|_| None).collect();
1568    let vocab = globals.lm_head.rows();
1569    crate::gpu::forward_token_graph(
1570        &globals.model, state.kv_id(), &gl, &o1, 0, &cfg.invf_swa, &mut h, nh, nh, hd, scale, cfg.rope, cfg.dim, inter, position, GRAPH_CAP, false, cfg.eps as f32,
1571        want_logits.then_some((&head, vocab)), &globals.norm, logits, &[], 1, None, None, None, 0, false,
1572    )
1573}
1574
1575/// One token: on the card's graph while the card holds the sequence (or it
1576/// takes it at position 0), else through the host stack.
1577#[allow(clippy::too_many_arguments)]
1578pub fn forward_token(
1579    globals: &Globals,
1580    layers: &[Layer],
1581    cfg: &Cfg,
1582    state: &mut State,
1583    token_id: u32,
1584    position: usize,
1585    pool: Option<&Pool>,
1586    logits: &mut Vec<f32>,
1587    want_logits: bool,
1588) {
1589    use crate::gpu::TokenGraphOutcome;
1590    if position == 0 || state.pos != position {
1591        if position != 0 && state.pos != position {
1592            tracing::warn!("hy_v4_flash: position {position} after {}; the sequence restarts", state.pos);
1593        }
1594        state.reset(layers.len());
1595    }
1596    let try_graph = match state.graph {
1597        Some(true) => true,
1598        None => position == 0,
1599        Some(false) => false,
1600    };
1601    if try_graph {
1602        match graph_token(globals, layers, cfg, state, token_id, position, logits, want_logits) {
1603            TokenGraphOutcome::Completed => {
1604                if state.graph.is_none() {
1605                    tracing::info!("hy_v4_flash: decode runs on the card's token graph");
1606                }
1607                state.graph = Some(true);
1608                state.tokens.push(token_id);
1609                state.pos = position + 1;
1610                return;
1611            }
1612            TokenGraphOutcome::Declined if state.graph == Some(true) => {
1613                // the card held the sequence and cannot go on: the host replays it
1614                host_replay(globals, layers, cfg, state, pool);
1615            }
1616            TokenGraphOutcome::Declined => state.graph = Some(false),
1617            TokenGraphOutcome::Failed => host_replay(globals, layers, cfg, state, pool),
1618        }
1619    }
1620    host_token(globals, layers, cfg, state, token_id, position, pool, logits, want_logits);
1621}
1622
1623/// One token through the host stack; the logits when asked.
1624#[allow(clippy::too_many_arguments)]
1625fn host_token(
1626    globals: &Globals,
1627    layers: &[Layer],
1628    cfg: &Cfg,
1629    state: &mut State,
1630    token_id: u32,
1631    position: usize,
1632    pool: Option<&Pool>,
1633    logits: &mut Vec<f32>,
1634    want_logits: bool,
1635) {
1636    if position == 0 {
1637        state.layers = (0..layers.len()).map(|_| LayerState::default()).collect();
1638        state.tokens.clear();
1639    }
1640    state.tokens.push(token_id);
1641    let dim = cfg.dim;
1642    let hc = cfg.hc;
1643    let mut h = vec![0f32; dim];
1644    if (token_id as usize) < globals.embed.rows() {
1645        globals.embed.row_f32(token_id as usize, &mut h);
1646    }
1647    let mut streams: Vec<f32> = (0..hc).flat_map(|_| h.iter().copied()).collect();
1648    let engram_on = token_id != cfg.image_id && token_id != cfg.video_id && token_id != cfg.pad_id;
1649    for (li, l) in layers.iter().enumerate() {
1650        if let (Some(e), true) = (&l.engram, engram_on) {
1651            let rows = e.rows(&state.tokens, position, cfg);
1652            match e.memory(&globals.model, &rows) {
1653                Ok(mem) => {
1654                    dump(li, position, "engmem", &mem);
1655                    let before = streams.clone();
1656                    e.apply(&mut streams, &mem, cfg, pool);
1657                    let d: Vec<f32> = streams.iter().zip(&before).map(|(a, b)| a - b).collect();
1658                    dump(li, position, "engout", &d);
1659                }
1660                Err(er) => tracing::error!("hy_v4_flash: layer {li} Engram: {er}"),
1661            }
1662        }
1663        let (pre, post) = l.attn_hc.split(&streams, hc, cfg.eps, cfg.hc_eps, cfg.mag, pool);
1664        let x = rms_w(&fold(&streams, &pre, dim), &l.input_norm, cfg.eps);
1665        let y = l.attn.forward(&x, &mut state.layers[li], position, cfg, pool);
1666        dump(li, position, "attn", &y);
1667        expand(&mut streams, &post, &y, dim);
1668        let (pre, post) = l.ffn_hc.split(&streams, hc, cfg.eps, cfg.hc_eps, cfg.mag, pool);
1669        let x = rms_w(&fold(&streams, &pre, dim), &l.post_norm, cfg.eps);
1670        let y = match &l.ffn {
1671            Ffn::Dense { gate, up, down, out_norm } => rms_w(&dense(gate, up, down, &x, 0.0, pool), out_norm, cfg.eps),
1672            Ffn::Moe(m) => m.forward(&x, cfg, pool),
1673        };
1674        expand(&mut streams, &post, &y, dim);
1675        dump(li, position, "streams", &streams);
1676    }
1677    state.pos = position + 1;
1678    if !want_logits {
1679        return;
1680    }
1681    // the head's fold: σ(mixes · scale + base) + eps
1682    let n = streams.len();
1683    let ms = streams.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / n as f64;
1684    let r = 1.0 / (ms + cfg.eps).sqrt() as f32;
1685    let pre: Vec<f32> = (0..hc)
1686        .map(|j| {
1687            let m = globals.head_fn[j * n..(j + 1) * n].iter().zip(&streams).map(|(a, b)| a * b).sum::<f32>() * r;
1688            sigmoid(m * globals.head_scale + globals.head_base[j]) + cfg.hc_eps
1689        })
1690        .collect();
1691    let x = rms_w(&fold(&streams, &pre, dim), &globals.norm, cfg.eps);
1692    logits.resize(globals.lm_head.rows(), 0.0);
1693    globals.lm_head.matvec(&x, logits, pool);
1694}
1695
1696#[cfg(test)]
1697mod tests {
1698    use super::*;
1699
1700    #[test]
1701    fn half_split_rotation_matches_the_interleaved_reference() {
1702        // interleaved pairs (x0, y0, x1, y1) rotate pair i by pos·f_i;
1703        // de-interleaved (x0, x1, y0, y1) must give the same numbers
1704        let invf = [0.5f32, 0.25];
1705        let pos = 3;
1706        let inter = [1.0f32, 2.0, 3.0, 4.0];
1707        let mut want = [0f32; 4];
1708        for i in 0..2 {
1709            let a = pos as f32 * invf[i];
1710            let (x, y) = (inter[2 * i], inter[2 * i + 1]);
1711            want[2 * i] = x * a.cos() - y * a.sin();
1712            want[2 * i + 1] = y * a.cos() + x * a.sin();
1713        }
1714        let mut half = [inter[0], inter[2], inter[1], inter[3]];
1715        rope_half(&mut half, &invf, pos);
1716        let got = [half[0], half[2], half[1], half[3]];
1717        for (a, b) in want.iter().zip(&got) {
1718            assert!((a - b).abs() < 1e-5, "{want:?} vs {got:?}");
1719        }
1720    }
1721
1722    #[test]
1723    fn e4m3_decodes_the_ocp_values() {
1724        assert_eq!(e4m3(0x38), 1.0);
1725        assert_eq!(e4m3(0x7e), 448.0);
1726        assert_eq!(e4m3(0x01), 2f32.powi(-9));
1727        assert_eq!(e4m3(0xb8), -1.0);
1728    }
1729}