Skip to main content

cortiq_engine/
linear_core.rs

1//! Linear-attention cores, selected by `arch.linear_core.kind`
2//! (descriptor-driven operators — Patent 15 claim 8).
3//!
4//! Two tracks (owner decision 2026-07-04):
5//!
6//! * `gated_delta_net` — the faithful vendor operator (Qwen3.5 /
7//!   Qwen3-Next). Default for models that ship GDN weights: conversion
8//!   carries the tensors 1:1 and needs no training. Port of the
9//!   validated `gated_delta_net` (vmfcore/rust/src/forward.rs) against
10//!   the numpy/torch oracle (vmfcore/gdn_layer.py).
11//!
12//! * `vmf_phase` — the canonical core: token carries a phase θ; kernel
13//!   φ(θ) = [cos θ; sin θ] gives a linear factorization; the condensate
14//!   is a recurrent state S[head][p2, dv] with decay exp(−exp(A_log)).
15//!   Noise-robust and simpler than vendor recurrences. Exotic operators
16//!   are folded onto it at CONVERT time (`--linear-core vmf_phase`) and
17//!   quality is restored by the offline heal — the research track and
18//!   the production mechanism for Patent-15 skills (mask→heal→compress).
19//!
20//! Both cores implement the same contract: `*_forward` (one position,
21//! advances the state) and `*_pair` (fused two positions; lane 1
22//! commits, lane 2 is tentative in `scratch` for speculative verify).
23//! State lives in the layer's `linear_state: Vec<f32>` and is resized
24//! lazily by the core itself.
25
26use crate::pool::Pool;
27use crate::qtensor::QTensor;
28
29/// Weights of one vmf_phase layer (`model.layers.{i}.vmf_attn.*`).
30pub struct VmfPhaseWeights {
31    /// [nh·nphase, hidden] — query phase projection
32    pub thq: QTensor,
33    /// [nh·nphase, hidden] — key phase projection
34    pub thk: QTensor,
35    /// [nh·dv, hidden]
36    pub v_proj: QTensor,
37    /// [hidden, nh·dv]
38    pub out_proj: QTensor,
39    /// Per-component decay exp(−exp(A_log)), len nh·2·nphase (precomputed).
40    pub decay: Vec<f64>,
41    /// Selective-write input gate κ (hybrid_k core, stage 71): weight
42    /// [nh, hidden] + bias [nh]; κ_h = σ(W_k·x + b)_h multiplies the
43    /// state WRITE (S = decay·S + κ·φk⊗v). None = classic phase core,
44    /// bit-identical to the pre-κ kernel. Measured at mechanism level:
45    /// knee ×2–6 earlier, restores correlated-noise robustness, LM
46    /// crossover vs softmax at SEQ 512 (experiments/lc_final_merged.json).
47    pub k_gate: Option<(QTensor, Vec<f32>)>,
48}
49
50#[derive(Clone, Copy)]
51pub struct VmfPhaseCfg {
52    pub num_heads: usize,
53    pub nphase: usize,
54    pub value_head_dim: usize,
55    pub hidden_size: usize,
56    /// θ-mass (η′ correction): a restoring potential pulling the phase
57    /// toward 0 — θ_eff = θ/(1+mass) — which WIDENS the phase kernel.
58    /// Measured (experiments/vmf_native_core*.py) to restore noise
59    /// robustness when the phase projection is FIXED (exactly CMF's
60    /// fold-before-heal regime: thq/thk are init, not trained) — recall
61    /// 3%→91% at moderate noise; redundant once the projection is
62    /// healed. 0.0 = massless Goldstone (bit-identical to prior kernel).
63    /// Set via CMF_PHASE_MASS. Validated at mechanism level, not yet LM.
64    pub phase_mass: f32,
65}
66
67impl VmfPhaseCfg {
68    pub fn state_len(&self) -> usize {
69        self.num_heads * 2 * self.nphase * self.value_head_dim
70    }
71}
72
73/// One recurrent step for one head-set given projected phases/values.
74/// `state` is S[nh][p2, dv] stored f32 (per-element math in f64 — the
75/// storage halves, each step's arithmetic keeps the old precision).
76fn phase_step(
77    thq: &[f32],
78    thk: &[f32],
79    v: &[f32],
80    decay: &[f64],
81    kap: Option<&[f32]>,
82    cfg: &VmfPhaseCfg,
83    state: &mut [f32],
84    out: &mut [f32],
85) {
86    let (nh, nph, dv) = (cfg.num_heads, cfg.nphase, cfg.value_head_dim);
87    // θ-mass (η′): θ_eff = θ/(1+mass). mass=0 → factor 1 → no-op.
88    let mscale = 1.0f64 / (1.0 + cfg.phase_mass as f64);
89    let p2 = 2 * nph;
90    for h in 0..nh {
91        let s = &mut state[h * p2 * dv..(h + 1) * p2 * dv];
92        let thk_h = &thk[h * nph..(h + 1) * nph];
93        let thq_h = &thq[h * nph..(h + 1) * nph];
94        let vt = &v[h * dv..(h + 1) * dv];
95        let ot = &mut out[h * dv..(h + 1) * dv];
96        let dec = &decay[h * p2..(h + 1) * p2];
97        // Selective write (hybrid_k): κ scales what enters the condensate.
98        let kh = kap.map_or(1.0f64, |k| k[h] as f64);
99        for f in 0..p2 {
100            // φ(θ) = [cos·nph, sin·nph], θ scaled by the mass factor.
101            let (fk, fq) = if f < nph {
102                ((thk_h[f] as f64 * mscale).cos(), (thq_h[f] as f64 * mscale).cos())
103            } else {
104                (
105                    (thk_h[f - nph] as f64 * mscale).sin(),
106                    (thq_h[f - nph] as f64 * mscale).sin(),
107                )
108            };
109            let fkw = fk * kh;
110            let row = &mut s[f * dv..(f + 1) * dv];
111            let dcf = dec[f];
112            for d in 0..dv {
113                // S = decay·S + κ·φk⊗v (f64 math, f32 cell)
114                let cell = dcf * row[d] as f64 + fkw * vt[d] as f64;
115                row[d] = cell as f32;
116                ot[d] += (fq * cell) as f32; // o = Σ φq·S
117            }
118        }
119    }
120}
121
122/// κ_h = σ(W_k·x + b)_h — the per-head write gate (None when the layer
123/// has no k_gate tensors: classic phase core).
124fn kappa_of(x: &[f32], w: &VmfPhaseWeights, nh: usize, pool: Option<&Pool>) -> Option<Vec<f32>> {
125    let (kw, kb) = w.k_gate.as_ref()?;
126    let mut k = vec![0.0f32; nh];
127    kw.matvec(x, &mut k, pool);
128    for (v, b) in k.iter_mut().zip(kb) {
129        *v = 1.0 / (1.0 + (-(*v + b)).exp());
130    }
131    Some(k)
132}
133
134/// Forward one position through a vmf_phase layer, advancing `state`.
135pub fn vmf_phase_forward(
136    x: &[f32],
137    w: &VmfPhaseWeights,
138    cfg: &VmfPhaseCfg,
139    state: &mut Vec<f32>,
140    pool: Option<&Pool>,
141) -> Vec<f32> {
142    if state.len() != cfg.state_len() {
143        *state = vec![0f32; cfg.state_len()];
144    }
145    let (nh, nph, dv) = (cfg.num_heads, cfg.nphase, cfg.value_head_dim);
146
147    let mut thq = vec![0.0f32; nh * nph];
148    w.thq.matvec(x, &mut thq, pool);
149    let mut thk = vec![0.0f32; nh * nph];
150    w.thk.matvec(x, &mut thk, pool);
151    let mut v = vec![0.0f32; nh * dv];
152    w.v_proj.matvec(x, &mut v, pool);
153
154    let kap = kappa_of(x, w, nh, pool);
155    let mut o = vec![0.0f32; nh * dv];
156    phase_step(&thq, &thk, &v, &w.decay, kap.as_deref(), cfg, state, &mut o);
157
158    let mut out = vec![0.0f32; cfg.hidden_size];
159    w.out_proj.matvec(&o, &mut out, pool);
160    out
161}
162
163/// Fused two-position forward (speculative verify). Lane 1 commits into
164/// `state` (its token is always committed); lane 2's tentative state
165/// goes into `scratch` — the caller swaps it in on draft acceptance and
166/// simply drops it on rejection.
167#[allow(clippy::too_many_arguments)]
168pub fn vmf_phase_pair(
169    x1: &[f32],
170    x2: &[f32],
171    w: &VmfPhaseWeights,
172    cfg: &VmfPhaseCfg,
173    state: &mut Vec<f32>,
174    scratch: &mut Vec<f32>,
175    pool: Option<&Pool>,
176) -> (Vec<f32>, Vec<f32>) {
177    if state.len() != cfg.state_len() {
178        *state = vec![0f32; cfg.state_len()];
179    }
180    let (nh, nph, dv) = (cfg.num_heads, cfg.nphase, cfg.value_head_dim);
181
182    let mut thq1 = vec![0.0f32; nh * nph];
183    let mut thq2 = vec![0.0f32; nh * nph];
184    w.thq.matvec2(x1, x2, &mut thq1, &mut thq2, pool);
185    let mut thk1 = vec![0.0f32; nh * nph];
186    let mut thk2 = vec![0.0f32; nh * nph];
187    w.thk.matvec2(x1, x2, &mut thk1, &mut thk2, pool);
188    let mut v1 = vec![0.0f32; nh * dv];
189    let mut v2 = vec![0.0f32; nh * dv];
190    w.v_proj.matvec2(x1, x2, &mut v1, &mut v2, pool);
191
192    // Lane 1 commits into the real state.
193    let kap1 = kappa_of(x1, w, nh, pool);
194    let mut o1 = vec![0.0f32; nh * dv];
195    phase_step(&thq1, &thk1, &v1, &w.decay, kap1.as_deref(), cfg, state, &mut o1);
196
197    // Lane 2 runs on a copy — tentative until the draft is verified.
198    let kap2 = kappa_of(x2, w, nh, pool);
199    scratch.clear();
200    scratch.extend_from_slice(state);
201    let mut o2 = vec![0.0f32; nh * dv];
202    phase_step(&thq2, &thk2, &v2, &w.decay, kap2.as_deref(), cfg, scratch, &mut o2);
203
204    let mut out1 = vec![0.0f32; cfg.hidden_size];
205    let mut out2 = vec![0.0f32; cfg.hidden_size];
206    w.out_proj.matvec2(&o1, &o2, &mut out1, &mut out2, pool);
207    (out1, out2)
208}
209
210// ───────────────────────── GatedDeltaNet (faithful vendor operator) ─────────────────────────
211
212/// Weights of one GatedDeltaNet layer (`model.layers.{i}.linear_attn.*`,
213/// names 1:1 with the source model — no fold, no training).
214pub struct GdnWeights {
215    /// [2·nk·dk + nv·dv, hidden] — fused q/k/v projection
216    pub in_proj_qkv: QTensor,
217    /// [nv·dv, hidden] — output-gate projection z
218    pub in_proj_z: QTensor,
219    /// [nv, hidden] — decay modulation a
220    pub in_proj_a: QTensor,
221    /// [nv, hidden] — write-strength b (β = σ(b))
222    pub in_proj_b: QTensor,
223    /// [c_dim · kk] — depthwise causal conv taps, flattened [c][tap]
224    pub conv1d: Vec<f32>,
225    /// [nv]
226    pub a_log: Vec<f32>,
227    /// [nv]
228    pub dt_bias: Vec<f32>,
229    /// [dv] — gated RMSNorm weight (plain x̂·w, validated by the oracle)
230    pub norm: Vec<f32>,
231    /// [hidden, nv·dv]
232    pub out_proj: QTensor,
233}
234
235#[derive(Clone, Copy)]
236pub struct GdnCfg {
237    pub num_v_heads: usize,
238    pub num_k_heads: usize,
239    pub key_head_dim: usize,
240    pub value_head_dim: usize,
241    pub conv_kernel: usize,
242    pub hidden_size: usize,
243    pub rms_eps: f64,
244}
245
246impl GdnCfg {
247    pub fn conv_dim(&self) -> usize {
248        2 * self.num_k_heads * self.key_head_dim + self.num_v_heads * self.value_head_dim
249    }
250
251    /// Packed state: [conv ring (kk−1)·c_dim | S nv·dk·dv], one Vec<f64>
252    /// so the speculative scratch-swap moves ring and condensate together.
253    pub fn state_len(&self) -> usize {
254        (self.conv_kernel - 1) * self.conv_dim()
255            + self.num_v_heads * self.key_head_dim * self.value_head_dim
256    }
257}
258
259fn softplus(x: f64) -> f64 {
260    if x > 20.0 {
261        x
262    } else {
263        x.exp().ln_1p()
264    }
265}
266
267fn sigmoid(x: f64) -> f64 {
268    1.0 / (1.0 + (-x).exp())
269}
270
271fn silu(x: f64) -> f64 {
272    x / (1.0 + (-x).exp())
273}
274
275/// `*mut f32` that may cross worker threads; safety comes from the
276/// disjoint (head, element) ranges each worker writes.
277#[derive(Clone, Copy)]
278struct SendMutF32(*mut f32);
279unsafe impl Send for SendMutF32 {}
280unsafe impl Sync for SendMutF32 {}
281
282/// One recurrent step given the raw (pre-conv) projections of this
283/// position. Advances the packed state (conv ring + S) and writes the
284/// gated per-head output into `of` [nv·dv].
285///
286/// The condensate math runs in f32 (the vendor operator's own dtype —
287/// `mamba_ssm_dtype: float32` in the source configs; the old f64 was
288/// over-precision at 4× the traffic and no SIMD). The two S passes are
289/// element-wise in `dj` with no cross-lane reduction, so LLVM
290/// auto-vectorizes them (fmla on NEON, FMA on AVX2). Heads are
291/// independent given the conv output and run across the pool — on a
292/// Qwen3.5-27B this loop is 48 heads × 128×128 × 48 layers per token,
293/// the single biggest serial block in the hybrid's decode.
294#[allow(clippy::too_many_arguments)]
295fn gdn_step(
296    qkv: &[f32],
297    z: &[f32],
298    a: &[f32],
299    b: &[f32],
300    w: &GdnWeights,
301    cfg: &GdnCfg,
302    state: &mut [f32],
303    of: &mut [f32],
304    pool: Option<&Pool>,
305) {
306    let (nv, nk, dk, dv, kk) = (
307        cfg.num_v_heads,
308        cfg.num_k_heads,
309        cfg.key_head_dim,
310        cfg.value_head_dim,
311        cfg.conv_kernel,
312    );
313    let c_dim = cfg.conv_dim();
314    let (kd, rep) = (nk * dk, nv / nk);
315    let (ring, s_all) = state.split_at_mut((kk - 1) * c_dim);
316
317    // Depthwise causal conv over [ring…, current] + SiLU. Taps are
318    // ordered oldest→newest; tap kk−1 multiplies the current position.
319    // (Tiny: c_dim × kk — f64 accumulation kept.)
320    let mut cq = vec![0f32; c_dim];
321    for c in 0..c_dim {
322        let taps = &w.conv1d[c * kk..(c + 1) * kk];
323        let mut acc = qkv[c] as f64 * taps[kk - 1] as f64;
324        for j in 0..kk - 1 {
325            acc += ring[j * c_dim + c] as f64 * taps[j] as f64;
326        }
327        cq[c] = silu(acc) as f32;
328    }
329    // Ring shift: drop the oldest position, append the raw current one.
330    if kk > 1 {
331        ring.copy_within(c_dim.., 0);
332        let tail = (kk - 2) * c_dim;
333        ring[tail..tail + c_dim].copy_from_slice(&qkv[..c_dim]);
334    }
335
336    let cq = &cq;
337    let s_ptr = SendMutF32(s_all.as_mut_ptr());
338    let of_ptr = SendMutF32(of.as_mut_ptr());
339    let head_range = |h0: usize, h1: usize| {
340        // Rebind the Sync wrappers whole — edition-2021 disjoint capture
341        // would otherwise grab the raw `.0` fields and lose Send/Sync.
342        let (s_ptr, of_ptr) = (s_ptr, of_ptr);
343        // Per-worker scratch, recycled across calls (thread-local freelists).
344        let mut kv = crate::attention::take_buf(dv);
345        let mut delta = crate::attention::take_buf(dv);
346        let mut o = crate::attention::take_buf(dv);
347        let mut kf = crate::attention::take_buf(dk);
348        let mut qf = crate::attention::take_buf(dk);
349        for h in h0..h1 {
350            let ko = h / rep; // source q/k head (GQA)
351            let (qs, ks) = (ko * dk, kd + ko * dk);
352            // l2-normalize q and k; q additionally scaled by 1/√dk.
353            let (mut nq, mut nkn) = (0f64, 0f64);
354            for d in 0..dk {
355                nq += (cq[qs + d] as f64) * (cq[qs + d] as f64);
356                nkn += (cq[ks + d] as f64) * (cq[ks + d] as f64);
357            }
358            let invq = (1.0 / ((nq + 1e-6).sqrt() * (dk as f64).sqrt())) as f32;
359            let invk = (1.0 / (nkn + 1e-6).sqrt()) as f32;
360            for d in 0..dk {
361                qf[d] = cq[qs + d] * invq;
362                kf[d] = cq[ks + d] * invk;
363            }
364
365            let g = (-(w.a_log[h] as f64).exp()
366                * softplus(a[h] as f64 + w.dt_bias[h] as f64))
367            .exp() as f32;
368            let beta = sigmoid(b[h] as f64) as f32;
369
370            // SAFETY: disjoint per-head S and output slices per worker.
371            let s = unsafe { std::slice::from_raw_parts_mut(s_ptr.0.add(h * dk * dv), dk * dv) };
372            let oh =
373                unsafe { std::slice::from_raw_parts_mut(of_ptr.0.add(h * dv), dv) };
374            let vt = &cq[2 * kd + h * dv..2 * kd + (h + 1) * dv];
375
376            // S ← g·S;  kv = kᵀS;  S += k ⊗ β(v − kv);  o = qᵀS —
377            // algebraically regrouped so S is READ twice and WRITTEN
378            // once: kv over S_old (then ×g), one fused update+query pass.
379            kv[..dv].fill(0.0);
380            for di in 0..dk {
381                let kfd = kf[di];
382                let row = &s[di * dv..(di + 1) * dv];
383                for dj in 0..dv {
384                    kv[dj] += row[dj] * kfd; // elementwise in dj → SIMD
385                }
386            }
387            for dj in 0..dv {
388                delta[dj] = (vt[dj] - g * kv[dj]) * beta;
389            }
390            o[..dv].fill(0.0);
391            for di in 0..dk {
392                let kfd = kf[di];
393                let qfd = qf[di];
394                let row = &mut s[di * dv..(di + 1) * dv];
395                for dj in 0..dv {
396                    let cell = g * row[dj] + kfd * delta[dj];
397                    row[dj] = cell;
398                    o[dj] += qfd * cell; // elementwise in dj → SIMD
399                }
400            }
401            // Gated RMSNorm per head: x̂·w·silu(z) (oracle-validated form).
402            let ss: f64 = o[..dv].iter().map(|&v| (v as f64) * (v as f64)).sum();
403            let inv = 1.0 / (ss / dv as f64 + cfg.rms_eps).sqrt();
404            for dj in 0..dv {
405                oh[dj] =
406                    ((o[dj] as f64 * inv) * w.norm[dj] as f64 * silu(z[h * dv + dj] as f64)) as f32;
407            }
408        }
409        crate::attention::recycle_buf(&mut kv);
410        crate::attention::recycle_buf(&mut delta);
411        crate::attention::recycle_buf(&mut o);
412        crate::attention::recycle_buf(&mut kf);
413        crate::attention::recycle_buf(&mut qf);
414    };
415    match pool {
416        Some(pool) if nv >= 4 => pool.run(&|widx, n| {
417            let chunk = nv.div_ceil(n);
418            let h0 = (widx * chunk).min(nv);
419            let h1 = (h0 + chunk).min(nv);
420            if h0 < h1 {
421                head_range(h0, h1);
422            }
423        }),
424        _ => head_range(0, nv),
425    }
426}
427
428/// Forward one position through a GatedDeltaNet layer, advancing `state`.
429pub fn gdn_forward(
430    x: &[f32],
431    w: &GdnWeights,
432    cfg: &GdnCfg,
433    state: &mut Vec<f32>,
434    pool: Option<&Pool>,
435) -> Vec<f32> {
436    if state.len() != cfg.state_len() {
437        *state = vec![0f32; cfg.state_len()];
438    }
439    let (c_dim, vd) = (cfg.conv_dim(), cfg.num_v_heads * cfg.value_head_dim);
440
441    let mut qkv = vec![0.0f32; c_dim];
442    let mut z = vec![0.0f32; vd];
443    let mut a = vec![0.0f32; cfg.num_v_heads];
444    let mut b = vec![0.0f32; cfg.num_v_heads];
445    // D5: two heavy projections (qkv+z ≈ 24MB q8 per 35B layer, ×30 layers
446    // = half the token's bytes) — in a single GPU submission; a/b are tiny
447    // and stay on CPU.
448    if gdn_projs_gpu(w, x, &mut qkv, &mut z) {
449        w.in_proj_a.matvec(x, &mut a, pool);
450        w.in_proj_b.matvec(x, &mut b, pool);
451    } else {
452        // All four projections under ONE pool dispatch (uniform-dtype
453        // multi-matrix job; falls back to per-tensor matvecs otherwise).
454        QTensor::matvec_many(
455            [&w.in_proj_qkv, &w.in_proj_z, &w.in_proj_a, &w.in_proj_b],
456            x,
457            [
458                qkv.as_mut_slice(),
459                z.as_mut_slice(),
460                a.as_mut_slice(),
461                b.as_mut_slice(),
462            ],
463            pool,
464        );
465    }
466
467    let mut of = vec![0.0f32; vd];
468    gdn_step(&qkv, &z, &a, &b, w, cfg, state, &mut of, pool);
469
470    let mut out = vec![0.0f32; cfg.hidden_size];
471    w.out_proj.matvec(&of, &mut out, pool);
472    out
473}
474
475/// Batched GDN forward (prefill-GEMM): the qkv/z/a/b and out_proj
476/// projections are matmat over the batch (a weight row once per chunk),
477/// the gdn_step recurrence runs sequentially over positions (state is the
478/// same as the sequential path; the math is elementwise identical).
479pub fn gdn_forward_batch(
480    xs: &[f32],
481    b: usize,
482    w: &GdnWeights,
483    cfg: &GdnCfg,
484    state: &mut Vec<f32>,
485    pool: Option<&Pool>,
486) -> Vec<f32> {
487    if state.len() != cfg.state_len() {
488        *state = vec![0f32; cfg.state_len()];
489    }
490    let (c_dim, vd) = (cfg.conv_dim(), cfg.num_v_heads * cfg.value_head_dim);
491    let nv = cfg.num_v_heads;
492
493    let mut qkv = vec![0.0f32; b * c_dim];
494    w.in_proj_qkv.matmat(xs, b, &mut qkv, pool);
495    let mut z = vec![0.0f32; b * vd];
496    w.in_proj_z.matmat(xs, b, &mut z, pool);
497    let mut a = vec![0.0f32; b * nv];
498    w.in_proj_a.matmat(xs, b, &mut a, pool);
499    let mut bb = vec![0.0f32; b * nv];
500    w.in_proj_b.matmat(xs, b, &mut bb, pool);
501
502    let mut of = vec![0.0f32; b * vd];
503    for bi in 0..b {
504        gdn_step(
505            &qkv[bi * c_dim..(bi + 1) * c_dim],
506            &z[bi * vd..(bi + 1) * vd],
507            &a[bi * nv..(bi + 1) * nv],
508            &bb[bi * nv..(bi + 1) * nv],
509            w,
510            cfg,
511            state,
512            &mut of[bi * vd..(bi + 1) * vd],
513            pool,
514        );
515    }
516    let mut out = vec![0.0f32; b * cfg.hidden_size];
517    w.out_proj.matmat(&of, b, &mut out, pool);
518    out
519}
520
521/// GDN qkv+z on GPU in a single submission (independent matvecs of one input).
522fn gdn_projs_gpu(w: &GdnWeights, x: &[f32], qkv: &mut [f32], z: &mut [f32]) -> bool {
523    use crate::gpu::matvec_batch;
524    use crate::qtensor::QTensor;
525    // Measured (35B, alternating A/B): 2 matvecs per submission do NOT
526    // amortize the sync cost — neutral within the noise. Opt-in until
527    // attention/norms move into this same submission.
528    if !crate::gpu::enabled_here()
529        || !std::env::var("CMF_GPU_GDN").map(|v| v == "1").unwrap_or(false)
530    {
531        return false;
532    }
533    fn part<'a>(
534        t: &'a QTensor,
535        x: &[f32],
536    ) -> Option<(std::sync::Arc<cortiq_core::CmfModel>, crate::gpu::BatchJob<'a>)> {
537        use crate::gpu::BatchJob;
538        use crate::qtensor::prescale;
539        use cortiq_core::TensorDtype;
540        match t {
541        QTensor::Mapped {
542            model,
543            idx,
544            dtype: dt @ (TensorDtype::Q8Row | TensorDtype::Q8_2f),
545            rows,
546            cols,
547            row_scale,
548            col_field,
549            ..
550        } => Some((
551            model.clone(),
552            BatchJob {
553                idx: *idx,
554                rows: *rows,
555                cols: *cols,
556                row_scale,
557                xs: prescale(x, col_field, *dt).into_owned(),
558            },
559        )),
560        _ => None,
561        }
562    }
563    let Some((model, jq)) = part(&w.in_proj_qkv, x) else { return false };
564    let Some((_, jz)) = part(&w.in_proj_z, x) else { return false };
565    matvec_batch(&model, &[jq, jz], &mut [qkv, z])
566}
567
568/// Fused two-position forward (speculative verify): lane 1 commits into
569/// `state`, lane 2 is tentative in `scratch` (ring + S move together).
570#[allow(clippy::too_many_arguments)]
571pub fn gdn_pair(
572    x1: &[f32],
573    x2: &[f32],
574    w: &GdnWeights,
575    cfg: &GdnCfg,
576    state: &mut Vec<f32>,
577    scratch: &mut Vec<f32>,
578    pool: Option<&Pool>,
579) -> (Vec<f32>, Vec<f32>) {
580    if state.len() != cfg.state_len() {
581        *state = vec![0f32; cfg.state_len()];
582    }
583    let (c_dim, vd, nv) = (
584        cfg.conv_dim(),
585        cfg.num_v_heads * cfg.value_head_dim,
586        cfg.num_v_heads,
587    );
588
589    let mut qkv1 = vec![0.0f32; c_dim];
590    let mut qkv2 = vec![0.0f32; c_dim];
591    w.in_proj_qkv.matvec2(x1, x2, &mut qkv1, &mut qkv2, pool);
592    let mut z1 = vec![0.0f32; vd];
593    let mut z2 = vec![0.0f32; vd];
594    w.in_proj_z.matvec2(x1, x2, &mut z1, &mut z2, pool);
595    let mut a1 = vec![0.0f32; nv];
596    let mut a2 = vec![0.0f32; nv];
597    w.in_proj_a.matvec2(x1, x2, &mut a1, &mut a2, pool);
598    let mut b1 = vec![0.0f32; nv];
599    let mut b2 = vec![0.0f32; nv];
600    w.in_proj_b.matvec2(x1, x2, &mut b1, &mut b2, pool);
601
602    let mut of1 = vec![0.0f32; vd];
603    gdn_step(&qkv1, &z1, &a1, &b1, w, cfg, state, &mut of1, pool);
604
605    scratch.clear();
606    scratch.extend_from_slice(state);
607    let mut of2 = vec![0.0f32; vd];
608    gdn_step(&qkv2, &z2, &a2, &b2, w, cfg, scratch, &mut of2, pool);
609
610    let mut out1 = vec![0.0f32; cfg.hidden_size];
611    let mut out2 = vec![0.0f32; cfg.hidden_size];
612    w.out_proj.matvec2(&of1, &of2, &mut out1, &mut out2, pool);
613    (out1, out2)
614}
615
616#[cfg(test)]
617mod tests {
618    use super::*;
619
620    fn tiny() -> (VmfPhaseWeights, VmfPhaseCfg) {
621        let cfg = VmfPhaseCfg {
622            num_heads: 2,
623            nphase: 3,
624            value_head_dim: 4,
625            hidden_size: 8,
626            phase_mass: 0.0,
627        };
628        let synth = |rows: usize, cols: usize, salt: usize| {
629            QTensor::from_f32(
630                (0..rows * cols)
631                    .map(|i| (((i * 13 + salt * 7) % 97) as f32 / 97.0 - 0.5) * 0.4)
632                    .collect(),
633                rows,
634                cols,
635            )
636        };
637        let w = VmfPhaseWeights {
638            thq: synth(cfg.num_heads * cfg.nphase, cfg.hidden_size, 1),
639            thk: synth(cfg.num_heads * cfg.nphase, cfg.hidden_size, 2),
640            v_proj: synth(cfg.num_heads * cfg.value_head_dim, cfg.hidden_size, 3),
641            out_proj: synth(cfg.hidden_size, cfg.num_heads * cfg.value_head_dim, 4),
642            decay: (0..cfg.num_heads * 2 * cfg.nphase)
643                .map(|i| 0.9 + 0.005 * (i % 10) as f64)
644                .collect(),
645            k_gate: None,
646        };
647        (w, cfg)
648    }
649
650    #[test]
651    fn state_persists_and_changes_output() {
652        let (w, cfg) = tiny();
653        let x: Vec<f32> = (0..8).map(|i| (i as f32 * 0.3).sin()).collect();
654        let mut state = Vec::new();
655        let o1 = vmf_phase_forward(&x, &w, &cfg, &mut state, None);
656        let o2 = vmf_phase_forward(&x, &w, &cfg, &mut state, None);
657        // Same input, evolved condensate → different output.
658        assert!(o1.iter().zip(&o2).any(|(a, b)| (a - b).abs() > 1e-6));
659        assert_eq!(state.len(), cfg.state_len());
660    }
661
662    /// θ-mass (η′): mass=0 is bit-identical to the massless kernel; mass>0
663    /// changes the output (phase narrowed → kernel widened). Guards the
664    /// no-op default and that the knob is actually wired.
665    #[test]
666    fn phase_mass_zero_is_noop_and_positive_shifts() {
667        let (w, cfg0) = tiny();
668        let mut cfg_m = cfg0.clone();
669        cfg_m.phase_mass = 1.0;
670        let x: Vec<f32> = (0..8).map(|i| (i as f32 * 0.4).sin()).collect();
671
672        let mut s0 = Vec::new();
673        let base = vmf_phase_forward(&x, &w, &cfg0, &mut s0, None);
674        // Re-run with mass=0 → must be bit-identical.
675        let mut s0b = Vec::new();
676        let base2 = vmf_phase_forward(&x, &w, &cfg0, &mut s0b, None);
677        assert_eq!(base, base2, "mass=0 must be deterministic/no-op");
678        // mass=1 → output differs (θ halved before cos/sin).
679        let mut sm = Vec::new();
680        let massed = vmf_phase_forward(&x, &w, &cfg_m, &mut sm, None);
681        assert!(
682            base.iter().zip(&massed).any(|(a, b)| (a - b).abs() > 1e-5),
683            "mass>0 must change the output"
684        );
685        assert!(massed.iter().all(|v| v.is_finite()));
686    }
687
688    /// κ write gate (hybrid_k): saturated-open gate (bias ≫ 0 → κ→1)
689    /// matches the gateless kernel within fp tolerance; a closed gate
690    /// (bias ≪ 0 → κ→0) writes nothing — the state stays zero and the
691    /// output collapses to the empty-condensate readout.
692    #[test]
693    fn kappa_gate_open_matches_none_and_closed_writes_nothing() {
694        let (mut w, cfg) = tiny();
695        let x: Vec<f32> = (0..8).map(|i| (i as f32 * 0.3).sin()).collect();
696
697        let mut s_none = Vec::new();
698        let base1 = vmf_phase_forward(&x, &w, &cfg, &mut s_none, None);
699        let base2 = vmf_phase_forward(&x, &w, &cfg, &mut s_none, None);
700
701        // Open gate: W=0, bias=+20 → κ = σ(20) ≈ 1 − 2e−9.
702        w.k_gate = Some((
703            QTensor::from_f32(vec![0.0; cfg.num_heads * cfg.hidden_size], cfg.num_heads, cfg.hidden_size),
704            vec![20.0; cfg.num_heads],
705        ));
706        let mut s_open = Vec::new();
707        let o1 = vmf_phase_forward(&x, &w, &cfg, &mut s_open, None);
708        let o2 = vmf_phase_forward(&x, &w, &cfg, &mut s_open, None);
709        for (a, b) in base1.iter().zip(&o1).chain(base2.iter().zip(&o2)) {
710            assert!((a - b).abs() < 1e-5, "open κ must match gateless: {a} vs {b}");
711        }
712
713        // Closed gate: bias=−20 → κ ≈ 0 → nothing is written.
714        w.k_gate = Some((
715            QTensor::from_f32(vec![0.0; cfg.num_heads * cfg.hidden_size], cfg.num_heads, cfg.hidden_size),
716            vec![-20.0; cfg.num_heads],
717        ));
718        let mut s_closed = Vec::new();
719        let oc = vmf_phase_forward(&x, &w, &cfg, &mut s_closed, None);
720        assert!(s_closed.iter().all(|&v| v.abs() < 1e-7), "closed κ: state must stay empty");
721        assert!(oc.iter().all(|&v| v.abs() < 1e-6), "closed κ: empty-condensate readout");
722    }
723
724    #[test]
725    fn pair_matches_two_singles_bitexact() {
726        let (w, cfg) = tiny();
727        let x1: Vec<f32> = (0..8).map(|i| (i as f32 * 0.2).cos()).collect();
728        let x2: Vec<f32> = (0..8).map(|i| (i as f32 * 0.5).sin()).collect();
729
730        // Reference: two sequential singles.
731        let mut s_ref = Vec::new();
732        let r1 = vmf_phase_forward(&x1, &w, &cfg, &mut s_ref, None);
733        let r2 = vmf_phase_forward(&x2, &w, &cfg, &mut s_ref, None);
734
735        // Pair: lane1 commits, lane2 tentative in scratch.
736        let mut s = Vec::new();
737        let mut scratch = Vec::new();
738        let (p1, p2) = vmf_phase_pair(&x1, &x2, &w, &cfg, &mut s, &mut scratch, None);
739        assert_eq!(r1, p1, "lane 1 must be bit-identical");
740        assert_eq!(r2, p2, "lane 2 must be bit-identical");
741        // Accepting the draft = swapping scratch in → equals s_ref.
742        std::mem::swap(&mut s, &mut scratch);
743        assert_eq!(s, s_ref, "accepted state must equal sequential state");
744    }
745
746    #[test]
747    fn rejected_draft_leaves_state_at_lane1() {
748        let (w, cfg) = tiny();
749        let x1: Vec<f32> = (0..8).map(|i| (i as f32 * 0.7).sin()).collect();
750        let x2 = vec![0.5f32; 8];
751
752        let mut s_ref = Vec::new();
753        let _ = vmf_phase_forward(&x1, &w, &cfg, &mut s_ref, None);
754
755        let mut s = Vec::new();
756        let mut scratch = Vec::new();
757        let _ = vmf_phase_pair(&x1, &x2, &w, &cfg, &mut s, &mut scratch, None);
758        // Reject: state must be exactly the post-lane1 state.
759        assert_eq!(s, s_ref);
760    }
761
762    // ───────────── GatedDeltaNet ─────────────
763
764    fn tiny_gdn() -> (GdnWeights, GdnCfg) {
765        let cfg = GdnCfg {
766            num_v_heads: 4,
767            num_k_heads: 2,
768            key_head_dim: 3,
769            value_head_dim: 5,
770            conv_kernel: 4,
771            hidden_size: 8,
772            rms_eps: 1e-6,
773        };
774        let c_dim = cfg.conv_dim();
775        let vd = cfg.num_v_heads * cfg.value_head_dim;
776        let synth = |rows: usize, cols: usize, salt: usize| {
777            QTensor::from_f32(
778                (0..rows * cols)
779                    .map(|i| (((i * 13 + salt * 7) % 97) as f32 / 97.0 - 0.5) * 0.4)
780                    .collect(),
781                rows,
782                cols,
783            )
784        };
785        let vecf = |n: usize, salt: usize| -> Vec<f32> {
786            (0..n)
787                .map(|i| (((i * 11 + salt * 5) % 89) as f32 / 89.0 - 0.5) * 0.6)
788                .collect()
789        };
790        let w = GdnWeights {
791            in_proj_qkv: synth(c_dim, cfg.hidden_size, 1),
792            in_proj_z: synth(vd, cfg.hidden_size, 2),
793            in_proj_a: synth(cfg.num_v_heads, cfg.hidden_size, 3),
794            in_proj_b: synth(cfg.num_v_heads, cfg.hidden_size, 4),
795            conv1d: vecf(c_dim * cfg.conv_kernel, 5),
796            a_log: (0..cfg.num_v_heads).map(|i| 0.2 + 0.3 * i as f32).collect(),
797            dt_bias: vecf(cfg.num_v_heads, 6),
798            norm: vec![1.0; cfg.value_head_dim],
799            out_proj: synth(cfg.hidden_size, vd, 7),
800        };
801        (w, cfg)
802    }
803
804    #[test]
805    fn gdn_state_persists_and_changes_output() {
806        let (w, cfg) = tiny_gdn();
807        let x: Vec<f32> = (0..8).map(|i| (i as f32 * 0.3).sin()).collect();
808        let mut state = Vec::new();
809        let o1 = gdn_forward(&x, &w, &cfg, &mut state, None);
810        let o2 = gdn_forward(&x, &w, &cfg, &mut state, None);
811        assert!(o1.iter().zip(&o2).any(|(a, b)| (a - b).abs() > 1e-6));
812        assert_eq!(state.len(), cfg.state_len());
813    }
814
815    #[test]
816    fn gdn_pair_matches_two_singles_bitexact() {
817        let (w, cfg) = tiny_gdn();
818        let x1: Vec<f32> = (0..8).map(|i| (i as f32 * 0.2).cos()).collect();
819        let x2: Vec<f32> = (0..8).map(|i| (i as f32 * 0.5).sin()).collect();
820
821        let mut s_ref = Vec::new();
822        let r1 = gdn_forward(&x1, &w, &cfg, &mut s_ref, None);
823        let r2 = gdn_forward(&x2, &w, &cfg, &mut s_ref, None);
824
825        let mut s = Vec::new();
826        let mut scratch = Vec::new();
827        let (p1, p2) = gdn_pair(&x1, &x2, &w, &cfg, &mut s, &mut scratch, None);
828        assert_eq!(r1, p1, "lane 1 must be bit-identical");
829        assert_eq!(r2, p2, "lane 2 must be bit-identical");
830        std::mem::swap(&mut s, &mut scratch);
831        assert_eq!(s, s_ref, "accepted state must equal sequential state");
832    }
833
834    #[test]
835    fn gdn_rejected_draft_leaves_state_at_lane1() {
836        let (w, cfg) = tiny_gdn();
837        let x1: Vec<f32> = (0..8).map(|i| (i as f32 * 0.7).sin()).collect();
838        let x2 = vec![0.5f32; 8];
839
840        let mut s_ref = Vec::new();
841        let _ = gdn_forward(&x1, &w, &cfg, &mut s_ref, None);
842
843        let mut s = Vec::new();
844        let mut scratch = Vec::new();
845        let _ = gdn_pair(&x1, &x2, &w, &cfg, &mut s, &mut scratch, None);
846        assert_eq!(s, s_ref);
847    }
848
849    /// The conv ring must give the same result as an explicit causal
850    /// conv over the whole sequence (oracle semantics: zero left-pad,
851    /// tap kk−1 on the current position).
852    #[test]
853    fn gdn_conv_ring_matches_explicit_causal_conv() {
854        let (w, cfg) = tiny_gdn();
855        let seq: Vec<Vec<f32>> = (0..6)
856            .map(|t| (0..8).map(|i| ((t * 8 + i) as f32 * 0.17).sin()).collect())
857            .collect();
858
859        // Reference: recompute position t from scratch each time with a
860        // fresh state built by replaying the prefix.
861        let mut s_inc = Vec::new();
862        for (t, x) in seq.iter().enumerate() {
863            let inc = gdn_forward(x, &w, &cfg, &mut s_inc, None);
864            let mut s_replay = Vec::new();
865            let mut replay = Vec::new();
866            for xr in &seq[..=t] {
867                replay = gdn_forward(xr, &w, &cfg, &mut s_replay, None);
868            }
869            assert_eq!(inc, replay, "position {t}: ring must equal replay");
870        }
871    }
872}