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                (
103                    (thk_h[f] as f64 * mscale).cos(),
104                    (thq_h[f] as f64 * mscale).cos(),
105                )
106            } else {
107                (
108                    (thk_h[f - nph] as f64 * mscale).sin(),
109                    (thq_h[f - nph] as f64 * mscale).sin(),
110                )
111            };
112            let fkw = fk * kh;
113            let row = &mut s[f * dv..(f + 1) * dv];
114            let dcf = dec[f];
115            for d in 0..dv {
116                // S = decay·S + κ·φk⊗v (f64 math, f32 cell)
117                let cell = dcf * row[d] as f64 + fkw * vt[d] as f64;
118                row[d] = cell as f32;
119                ot[d] += (fq * cell) as f32; // o = Σ φq·S
120            }
121        }
122    }
123}
124
125/// κ_h = σ(W_k·x + b)_h — the per-head write gate (None when the layer
126/// has no k_gate tensors: classic phase core).
127fn kappa_of(x: &[f32], w: &VmfPhaseWeights, nh: usize, pool: Option<&Pool>) -> Option<Vec<f32>> {
128    let (kw, kb) = w.k_gate.as_ref()?;
129    let mut k = vec![0.0f32; nh];
130    kw.matvec(x, &mut k, pool);
131    for (v, b) in k.iter_mut().zip(kb) {
132        *v = 1.0 / (1.0 + (-(*v + b)).exp());
133    }
134    Some(k)
135}
136
137/// Forward one position through a vmf_phase layer, advancing `state`.
138pub fn vmf_phase_forward(
139    x: &[f32],
140    w: &VmfPhaseWeights,
141    cfg: &VmfPhaseCfg,
142    state: &mut Vec<f32>,
143    pool: Option<&Pool>,
144) -> Vec<f32> {
145    if state.len() != cfg.state_len() {
146        *state = vec![0f32; cfg.state_len()];
147    }
148    let (nh, nph, dv) = (cfg.num_heads, cfg.nphase, cfg.value_head_dim);
149
150    let mut thq = vec![0.0f32; nh * nph];
151    w.thq.matvec(x, &mut thq, pool);
152    let mut thk = vec![0.0f32; nh * nph];
153    w.thk.matvec(x, &mut thk, pool);
154    let mut v = vec![0.0f32; nh * dv];
155    w.v_proj.matvec(x, &mut v, pool);
156
157    let kap = kappa_of(x, w, nh, pool);
158    let mut o = vec![0.0f32; nh * dv];
159    phase_step(&thq, &thk, &v, &w.decay, kap.as_deref(), cfg, state, &mut o);
160
161    let mut out = vec![0.0f32; cfg.hidden_size];
162    w.out_proj.matvec(&o, &mut out, pool);
163    out
164}
165
166/// Fused two-position forward (speculative verify). Lane 1 commits into
167/// `state` (its token is always committed); lane 2's tentative state
168/// goes into `scratch` — the caller swaps it in on draft acceptance and
169/// simply drops it on rejection.
170#[allow(clippy::too_many_arguments)]
171pub fn vmf_phase_pair(
172    x1: &[f32],
173    x2: &[f32],
174    w: &VmfPhaseWeights,
175    cfg: &VmfPhaseCfg,
176    state: &mut Vec<f32>,
177    scratch: &mut Vec<f32>,
178    pool: Option<&Pool>,
179) -> (Vec<f32>, Vec<f32>) {
180    if state.len() != cfg.state_len() {
181        *state = vec![0f32; cfg.state_len()];
182    }
183    let (nh, nph, dv) = (cfg.num_heads, cfg.nphase, cfg.value_head_dim);
184
185    let mut thq1 = vec![0.0f32; nh * nph];
186    let mut thq2 = vec![0.0f32; nh * nph];
187    w.thq.matvec2(x1, x2, &mut thq1, &mut thq2, pool);
188    let mut thk1 = vec![0.0f32; nh * nph];
189    let mut thk2 = vec![0.0f32; nh * nph];
190    w.thk.matvec2(x1, x2, &mut thk1, &mut thk2, pool);
191    let mut v1 = vec![0.0f32; nh * dv];
192    let mut v2 = vec![0.0f32; nh * dv];
193    w.v_proj.matvec2(x1, x2, &mut v1, &mut v2, pool);
194
195    // Lane 1 commits into the real state.
196    let kap1 = kappa_of(x1, w, nh, pool);
197    let mut o1 = vec![0.0f32; nh * dv];
198    phase_step(
199        &thq1,
200        &thk1,
201        &v1,
202        &w.decay,
203        kap1.as_deref(),
204        cfg,
205        state,
206        &mut o1,
207    );
208
209    // Lane 2 runs on a copy — tentative until the draft is verified.
210    let kap2 = kappa_of(x2, w, nh, pool);
211    scratch.clear();
212    scratch.extend_from_slice(state);
213    let mut o2 = vec![0.0f32; nh * dv];
214    phase_step(
215        &thq2,
216        &thk2,
217        &v2,
218        &w.decay,
219        kap2.as_deref(),
220        cfg,
221        scratch,
222        &mut o2,
223    );
224
225    let mut out1 = vec![0.0f32; cfg.hidden_size];
226    let mut out2 = vec![0.0f32; cfg.hidden_size];
227    w.out_proj.matvec2(&o1, &o2, &mut out1, &mut out2, pool);
228    (out1, out2)
229}
230
231// ───────────────────────── GatedDeltaNet (faithful vendor operator) ─────────────────────────
232
233/// Weights of one GatedDeltaNet layer (`model.layers.{i}.linear_attn.*`,
234/// names 1:1 with the source model — no fold, no training).
235pub struct GdnWeights {
236    /// [2·nk·dk + nv·dv, hidden] — fused q/k/v projection
237    pub in_proj_qkv: QTensor,
238    /// [nv·dv, hidden] — output-gate projection z
239    pub in_proj_z: QTensor,
240    /// [nv, hidden] — decay modulation a
241    pub in_proj_a: QTensor,
242    /// [nv, hidden] — write-strength b (β = σ(b))
243    pub in_proj_b: QTensor,
244    /// [c_dim · kk] — depthwise causal conv taps, flattened [c][tap]
245    pub conv1d: Vec<f32>,
246    /// [nv]
247    pub a_log: Vec<f32>,
248    /// [nv]
249    pub dt_bias: Vec<f32>,
250    /// [dv] — gated RMSNorm weight (plain x̂·w, validated by the oracle)
251    pub norm: Vec<f32>,
252    /// [hidden, nv·dv]
253    pub out_proj: QTensor,
254}
255
256#[derive(Clone, Copy)]
257pub struct GdnCfg {
258    pub num_v_heads: usize,
259    pub num_k_heads: usize,
260    pub key_head_dim: usize,
261    pub value_head_dim: usize,
262    pub conv_kernel: usize,
263    pub hidden_size: usize,
264    pub rms_eps: f64,
265}
266
267impl GdnCfg {
268    pub fn conv_dim(&self) -> usize {
269        2 * self.num_k_heads * self.key_head_dim + self.num_v_heads * self.value_head_dim
270    }
271
272    /// Packed state: [conv ring (kk−1)·c_dim | S nv·dk·dv], one Vec<f64>
273    /// so the speculative scratch-swap moves ring and condensate together.
274    pub fn state_len(&self) -> usize {
275        (self.conv_kernel - 1) * self.conv_dim()
276            + self.num_v_heads * self.key_head_dim * self.value_head_dim
277    }
278}
279
280fn softplus(x: f64) -> f64 {
281    if x > 20.0 { x } else { x.exp().ln_1p() }
282}
283
284fn sigmoid(x: f64) -> f64 {
285    1.0 / (1.0 + (-x).exp())
286}
287
288fn silu(x: f64) -> f64 {
289    x / (1.0 + (-x).exp())
290}
291
292/// `*mut f32` that may cross worker threads; safety comes from the
293/// disjoint (head, element) ranges each worker writes.
294#[derive(Clone, Copy)]
295struct SendMutF32(*mut f32);
296unsafe impl Send for SendMutF32 {}
297unsafe impl Sync for SendMutF32 {}
298
299/// One recurrent step given the raw (pre-conv) projections of this
300/// position. Advances the packed state (conv ring + S) and writes the
301/// gated per-head output into `of` [nv·dv].
302///
303/// The condensate math runs in f32 (the vendor operator's own dtype —
304/// `mamba_ssm_dtype: float32` in the source configs; the old f64 was
305/// over-precision at 4× the traffic and no SIMD). The two S passes are
306/// element-wise in `dj` with no cross-lane reduction, so LLVM
307/// auto-vectorizes them (fmla on NEON, FMA on AVX2). Heads are
308/// independent given the conv output and run across the pool — on a
309/// Qwen3.5-27B this loop is 48 heads × 128×128 × 48 layers per token,
310/// the single biggest serial block in the hybrid's decode.
311#[allow(clippy::too_many_arguments)]
312fn gdn_step(
313    qkv: &[f32],
314    z: &[f32],
315    a: &[f32],
316    b: &[f32],
317    w: &GdnWeights,
318    cfg: &GdnCfg,
319    state: &mut [f32],
320    of: &mut [f32],
321    pool: Option<&Pool>,
322) {
323    let (nv, nk, dk, dv, kk) = (
324        cfg.num_v_heads,
325        cfg.num_k_heads,
326        cfg.key_head_dim,
327        cfg.value_head_dim,
328        cfg.conv_kernel,
329    );
330    let c_dim = cfg.conv_dim();
331    let (kd, rep) = (nk * dk, nv / nk);
332    let (ring, s_all) = state.split_at_mut((kk - 1) * c_dim);
333
334    // Depthwise causal conv over [ring…, current] + SiLU. Taps are
335    // ordered oldest→newest; tap kk−1 multiplies the current position.
336    // (Tiny: c_dim × kk — f64 accumulation kept.)
337    let mut cq = vec![0f32; c_dim];
338    for c in 0..c_dim {
339        let taps = &w.conv1d[c * kk..(c + 1) * kk];
340        let mut acc = qkv[c] as f64 * taps[kk - 1] as f64;
341        for j in 0..kk - 1 {
342            acc += ring[j * c_dim + c] as f64 * taps[j] as f64;
343        }
344        cq[c] = silu(acc) as f32;
345    }
346    // Ring shift: drop the oldest position, append the raw current one.
347    if kk > 1 {
348        ring.copy_within(c_dim.., 0);
349        let tail = (kk - 2) * c_dim;
350        ring[tail..tail + c_dim].copy_from_slice(&qkv[..c_dim]);
351    }
352
353    let cq = &cq;
354    let s_ptr = SendMutF32(s_all.as_mut_ptr());
355    let of_ptr = SendMutF32(of.as_mut_ptr());
356    let head_range = |h0: usize, h1: usize| {
357        // Rebind the Sync wrappers whole — edition-2021 disjoint capture
358        // would otherwise grab the raw `.0` fields and lose Send/Sync.
359        let (s_ptr, of_ptr) = (s_ptr, of_ptr);
360        // Per-worker scratch, recycled across calls (thread-local freelists).
361        let mut kv = crate::attention::take_buf(dv);
362        let mut delta = crate::attention::take_buf(dv);
363        let mut o = crate::attention::take_buf(dv);
364        let mut kf = crate::attention::take_buf(dk);
365        let mut qf = crate::attention::take_buf(dk);
366        for h in h0..h1 {
367            let ko = h / rep; // source q/k head (GQA)
368            let (qs, ks) = (ko * dk, kd + ko * dk);
369            // l2-normalize q and k; q additionally scaled by 1/√dk.
370            let (mut nq, mut nkn) = (0f64, 0f64);
371            for d in 0..dk {
372                nq += (cq[qs + d] as f64) * (cq[qs + d] as f64);
373                nkn += (cq[ks + d] as f64) * (cq[ks + d] as f64);
374            }
375            let invq = (1.0 / ((nq + 1e-6).sqrt() * (dk as f64).sqrt())) as f32;
376            let invk = (1.0 / (nkn + 1e-6).sqrt()) as f32;
377            for d in 0..dk {
378                qf[d] = cq[qs + d] * invq;
379                kf[d] = cq[ks + d] * invk;
380            }
381
382            let g = (-(w.a_log[h] as f64).exp() * softplus(a[h] as f64 + w.dt_bias[h] as f64)).exp()
383                as f32;
384            let beta = sigmoid(b[h] as f64) as f32;
385
386            // SAFETY: disjoint per-head S and output slices per worker.
387            let s = unsafe { std::slice::from_raw_parts_mut(s_ptr.0.add(h * dk * dv), dk * dv) };
388            let oh = unsafe { std::slice::from_raw_parts_mut(of_ptr.0.add(h * dv), dv) };
389            let vt = &cq[2 * kd + h * dv..2 * kd + (h + 1) * dv];
390
391            // S ← g·S;  kv = kᵀS;  S += k ⊗ β(v − kv);  o = qᵀS —
392            // algebraically regrouped so S is READ twice and WRITTEN
393            // once: kv over S_old (then ×g), one fused update+query pass.
394            kv[..dv].fill(0.0);
395            for di in 0..dk {
396                let kfd = kf[di];
397                let row = &s[di * dv..(di + 1) * dv];
398                for dj in 0..dv {
399                    kv[dj] += row[dj] * kfd; // elementwise in dj → SIMD
400                }
401            }
402            for dj in 0..dv {
403                delta[dj] = (vt[dj] - g * kv[dj]) * beta;
404            }
405            o[..dv].fill(0.0);
406            for di in 0..dk {
407                let kfd = kf[di];
408                let qfd = qf[di];
409                let row = &mut s[di * dv..(di + 1) * dv];
410                for dj in 0..dv {
411                    let cell = g * row[dj] + kfd * delta[dj];
412                    row[dj] = cell;
413                    o[dj] += qfd * cell; // elementwise in dj → SIMD
414                }
415            }
416            // Gated RMSNorm per head: x̂·w·silu(z) (oracle-validated form).
417            let ss: f64 = o[..dv].iter().map(|&v| (v as f64) * (v as f64)).sum();
418            let inv = 1.0 / (ss / dv as f64 + cfg.rms_eps).sqrt();
419            for dj in 0..dv {
420                oh[dj] =
421                    ((o[dj] as f64 * inv) * w.norm[dj] as f64 * silu(z[h * dv + dj] as f64)) as f32;
422            }
423        }
424        crate::attention::recycle_buf(&mut kv);
425        crate::attention::recycle_buf(&mut delta);
426        crate::attention::recycle_buf(&mut o);
427        crate::attention::recycle_buf(&mut kf);
428        crate::attention::recycle_buf(&mut qf);
429    };
430    match pool {
431        Some(pool) if nv >= 4 => pool.run(&|widx, n| {
432            let chunk = nv.div_ceil(n);
433            let h0 = (widx * chunk).min(nv);
434            let h1 = (h0 + chunk).min(nv);
435            if h0 < h1 {
436                head_range(h0, h1);
437            }
438        }),
439        _ => head_range(0, nv),
440    }
441}
442
443/// Forward one position through a GatedDeltaNet layer, advancing `state`.
444pub fn gdn_forward(
445    x: &[f32],
446    w: &GdnWeights,
447    cfg: &GdnCfg,
448    state: &mut Vec<f32>,
449    pool: Option<&Pool>,
450) -> Vec<f32> {
451    if state.len() != cfg.state_len() {
452        *state = vec![0f32; cfg.state_len()];
453    }
454    let (c_dim, vd) = (cfg.conv_dim(), cfg.num_v_heads * cfg.value_head_dim);
455
456    let mut qkv = vec![0.0f32; c_dim];
457    let mut z = vec![0.0f32; vd];
458    let mut a = vec![0.0f32; cfg.num_v_heads];
459    let mut b = vec![0.0f32; cfg.num_v_heads];
460    // D5: two heavy projections (the GDN mixer is ~half a hybrid layer's
461    // bytes) — one GPU submission; a/b are tiny and stay on CPU. The
462    // Batch probe arbitrates GPU vs the fused-CPU dispatch per machine.
463    let cpu_projs = |qkv: &mut Vec<f32>, z: &mut Vec<f32>, a: &mut Vec<f32>, b: &mut Vec<f32>| {
464        QTensor::matvec_many(
465            [&w.in_proj_qkv, &w.in_proj_z, &w.in_proj_a, &w.in_proj_b],
466            x,
467            [
468                qkv.as_mut_slice(),
469                z.as_mut_slice(),
470                a.as_mut_slice(),
471                b.as_mut_slice(),
472            ],
473            pool,
474        );
475    };
476    let mut done = false;
477    if crate::gpu::enabled_here() && gdn_projs_eligible(w) {
478        match crate::gpu::probe_arm(crate::gpu::OpClass::Batch) {
479            crate::gpu::ProbeArm::Gpu => {
480                let t0 = std::time::Instant::now();
481                if gdn_projs_gpu(w, x, &mut qkv, &mut z) {
482                    crate::gpu::probe_record(crate::gpu::OpClass::Batch, true, t0.elapsed());
483                    w.in_proj_a.matvec(x, &mut a, pool);
484                    w.in_proj_b.matvec(x, &mut b, pool);
485                    done = true;
486                }
487            }
488            crate::gpu::ProbeArm::CpuTimed => {
489                let t0 = std::time::Instant::now();
490                crate::gpu::cpu_scope(|| cpu_projs(&mut qkv, &mut z, &mut a, &mut b));
491                crate::gpu::probe_record(crate::gpu::OpClass::Batch, false, t0.elapsed());
492                done = true;
493            }
494            crate::gpu::ProbeArm::Cpu => {
495                crate::gpu::cpu_scope(|| cpu_projs(&mut qkv, &mut z, &mut a, &mut b));
496                done = true;
497            }
498        }
499    }
500    if !done {
501        cpu_projs(&mut qkv, &mut z, &mut a, &mut b);
502    }
503
504    let mut of = vec![0.0f32; vd];
505    gdn_step(&qkv, &z, &a, &b, w, cfg, state, &mut of, pool);
506
507    let mut out = vec![0.0f32; cfg.hidden_size];
508    w.out_proj.matvec(&of, &mut out, pool);
509    out
510}
511
512/// Batched GDN forward (prefill-GEMM): the qkv/z/a/b and out_proj
513/// projections are matmat over the batch (a weight row once per chunk),
514/// the gdn_step recurrence runs sequentially over positions (state is the
515/// same as the sequential path; the math is elementwise identical).
516pub fn gdn_forward_batch(
517    xs: &[f32],
518    b: usize,
519    w: &GdnWeights,
520    cfg: &GdnCfg,
521    state: &mut Vec<f32>,
522    pool: Option<&Pool>,
523) -> Vec<f32> {
524    if state.len() != cfg.state_len() {
525        *state = vec![0f32; cfg.state_len()];
526    }
527    let (c_dim, vd) = (cfg.conv_dim(), cfg.num_v_heads * cfg.value_head_dim);
528    let nv = cfg.num_v_heads;
529
530    let mut qkv = vec![0.0f32; b * c_dim];
531    w.in_proj_qkv.matmat(xs, b, &mut qkv, pool);
532    let mut z = vec![0.0f32; b * vd];
533    w.in_proj_z.matmat(xs, b, &mut z, pool);
534    let mut a = vec![0.0f32; b * nv];
535    w.in_proj_a.matmat(xs, b, &mut a, pool);
536    let mut bb = vec![0.0f32; b * nv];
537    w.in_proj_b.matmat(xs, b, &mut bb, pool);
538
539    let mut of = vec![0.0f32; b * vd];
540    for bi in 0..b {
541        gdn_step(
542            &qkv[bi * c_dim..(bi + 1) * c_dim],
543            &z[bi * vd..(bi + 1) * vd],
544            &a[bi * nv..(bi + 1) * nv],
545            &bb[bi * nv..(bi + 1) * nv],
546            w,
547            cfg,
548            state,
549            &mut of[bi * vd..(bi + 1) * vd],
550            pool,
551        );
552    }
553    let mut out = vec![0.0f32; b * cfg.hidden_size];
554    w.out_proj.matmat(&of, b, &mut out, pool);
555    out
556}
557
558/// GDN qkv+z GPU eligibility: q1 mixers offload by default (the CPU q1
559/// kernel is compute-bound); q8 stays opt-in via CMF_GPU_GDN=1 (measured
560/// neutral). The probe in `gdn_forward` still arbitrates either way.
561fn gdn_projs_eligible(w: &GdnWeights) -> bool {
562    // Any tile-embedded-scale layout, not just q1: the batched matvec now has
563    // kernels for all of them, and the probe arbitrates whether it pays.
564    // `CMF_GPU_GDN=0` forces the CPU projections back — the switch exists so
565    // the two arms can be compared inside ONE run: this machine throttles far
566    // enough that measurements minutes apart are not comparable.
567    if std::env::var("CMF_GPU_GDN")
568        .map(|v| v == "0")
569        .unwrap_or(false)
570    {
571        return false;
572    }
573    w.in_proj_qkv.is_q1()
574        || w.in_proj_qkv.q4t_parts().is_some()
575        || w.in_proj_qkv.q4tp_parts().is_some()
576        || std::env::var("CMF_GPU_GDN")
577            .map(|v| v == "1")
578            .unwrap_or(false)
579}
580
581/// GDN qkv+z on GPU in a single submission (independent matvecs of one input).
582fn gdn_projs_gpu(w: &GdnWeights, x: &[f32], qkv: &mut [f32], z: &mut [f32]) -> bool {
583    use crate::gpu::matvec_batch;
584    use crate::qtensor::QTensor;
585    if !crate::gpu::enabled_here() {
586        return false;
587    }
588    fn part<'a>(
589        t: &'a QTensor,
590        x: &[f32],
591    ) -> Option<(
592        std::sync::Arc<cortiq_core::CmfModel>,
593        crate::gpu::BatchJob<'a>,
594    )> {
595        use crate::gpu::BatchJob;
596        use crate::qtensor::prescale;
597        use cortiq_core::TensorDtype;
598        match t {
599            QTensor::Mapped {
600                model,
601                idx,
602                dtype: dt @ (TensorDtype::Q8Row | TensorDtype::Q8_2f),
603                rows,
604                cols,
605                row_scale,
606                col_field,
607                ..
608            } => Some((
609                model.clone(),
610                BatchJob {
611                    idx: *idx,
612                    rows: *rows,
613                    cols: *cols,
614                    row_scale,
615                    xs: prescale(x, col_field, *dt).into_owned(),
616                    layout: crate::gpu::BatchLayout::Q8,
617                },
618            )),
619            QTensor::Mapped {
620                model,
621                idx,
622                dtype: TensorDtype::Q1,
623                rows,
624                cols,
625                ..
626            } => Some((
627                model.clone(),
628                BatchJob {
629                    idx: *idx,
630                    rows: *rows,
631                    cols: *cols,
632                    row_scale: &[],
633                    xs: x.to_vec(),
634                    layout: crate::gpu::BatchLayout::Q1,
635                },
636            )),
637            // q4t/q4tp: same tile-embedded-scale contract as q1, different
638            // stride. Missing here, a hybrid model's GDN projections fell to
639            // the CPU on every layer while its experts rode the device.
640            QTensor::Mapped {
641                model,
642                idx,
643                dtype: dt @ (TensorDtype::Q4Tiled | TensorDtype::Q4TiledP),
644                rows,
645                cols,
646                ..
647            } => Some((
648                model.clone(),
649                BatchJob {
650                    idx: *idx,
651                    rows: *rows,
652                    cols: *cols,
653                    row_scale: &[],
654                    xs: x.to_vec(),
655                    layout: if *dt == TensorDtype::Q4TiledP {
656                        crate::gpu::BatchLayout::Q4tp
657                    } else {
658                        crate::gpu::BatchLayout::Q4t
659                    },
660                },
661            )),
662            _ => None,
663        }
664    }
665    let Some((model, jq)) = part(&w.in_proj_qkv, x) else {
666        return false;
667    };
668    let Some((_, jz)) = part(&w.in_proj_z, x) else {
669        return false;
670    };
671    matvec_batch(&model, &[jq, jz], &mut [qkv, z])
672}
673
674/// Fused two-position forward (speculative verify): lane 1 commits into
675/// `state`, lane 2 is tentative in `scratch` (ring + S move together).
676#[allow(clippy::too_many_arguments)]
677pub fn gdn_pair(
678    x1: &[f32],
679    x2: &[f32],
680    w: &GdnWeights,
681    cfg: &GdnCfg,
682    state: &mut Vec<f32>,
683    scratch: &mut Vec<f32>,
684    pool: Option<&Pool>,
685) -> (Vec<f32>, Vec<f32>) {
686    if state.len() != cfg.state_len() {
687        *state = vec![0f32; cfg.state_len()];
688    }
689    let (c_dim, vd, nv) = (
690        cfg.conv_dim(),
691        cfg.num_v_heads * cfg.value_head_dim,
692        cfg.num_v_heads,
693    );
694
695    let mut qkv1 = vec![0.0f32; c_dim];
696    let mut qkv2 = vec![0.0f32; c_dim];
697    w.in_proj_qkv.matvec2(x1, x2, &mut qkv1, &mut qkv2, pool);
698    let mut z1 = vec![0.0f32; vd];
699    let mut z2 = vec![0.0f32; vd];
700    w.in_proj_z.matvec2(x1, x2, &mut z1, &mut z2, pool);
701    let mut a1 = vec![0.0f32; nv];
702    let mut a2 = vec![0.0f32; nv];
703    w.in_proj_a.matvec2(x1, x2, &mut a1, &mut a2, pool);
704    let mut b1 = vec![0.0f32; nv];
705    let mut b2 = vec![0.0f32; nv];
706    w.in_proj_b.matvec2(x1, x2, &mut b1, &mut b2, pool);
707
708    let mut of1 = vec![0.0f32; vd];
709    gdn_step(&qkv1, &z1, &a1, &b1, w, cfg, state, &mut of1, pool);
710
711    scratch.clear();
712    scratch.extend_from_slice(state);
713    let mut of2 = vec![0.0f32; vd];
714    gdn_step(&qkv2, &z2, &a2, &b2, w, cfg, scratch, &mut of2, pool);
715
716    let mut out1 = vec![0.0f32; cfg.hidden_size];
717    let mut out2 = vec![0.0f32; cfg.hidden_size];
718    w.out_proj.matvec2(&of1, &of2, &mut out1, &mut out2, pool);
719    (out1, out2)
720}
721
722// ───────────────────────── ShortConv (LFM2 gated short convolution) ─────────────────────────
723
724/// Weights of one LFM2 short-convolution mixer
725/// (`model.layers.{i}.short_conv.*`, renamed from the vendor `conv.*` at
726/// convert time). No recurrent condensate — the only state is the causal
727/// conv ring (the last `kernel−1` gated inputs per channel).
728pub struct ShortConvWeights {
729    /// [3·hidden, hidden] — fused (B, C, x) projection.
730    pub in_proj: QTensor,
731    /// [hidden · kernel] depthwise conv taps, flattened `[channel][tap]`
732    /// (the source `[hidden, 1, kernel]` with the singleton group axis
733    /// dropped). Tap `kernel−1` multiplies the current position.
734    pub conv: Vec<f32>,
735    /// [hidden, hidden] — output projection.
736    pub out_proj: QTensor,
737}
738
739#[derive(Clone, Copy)]
740pub struct ShortConvCfg {
741    pub hidden_size: usize,
742    /// Conv kernel width `L` (`conv_L_cache`; LFM2 uses 3).
743    pub kernel: usize,
744}
745
746impl ShortConvCfg {
747    /// Conv ring: the last `kernel−1` gated inputs per channel.
748    pub fn state_len(&self) -> usize {
749        (self.kernel - 1) * self.hidden_size
750    }
751}
752
753/// One position through the gated conv, given the fused projection
754/// `bcx = in_proj·x` [3·hidden] = [B | C | x]. Advances the conv ring and
755/// writes the gated conv output `y = C ⊙ conv(B ⊙ x)` [hidden] into `y`.
756///
757/// The conv is PyTorch's causal depthwise `Conv1d(padding=kernel−1)`
758/// truncated to the current length: for tap `k`, weight `w[c][k]` pairs
759/// with the input `kernel−1−k` steps in the past, so `w[c][kernel−1]` is
760/// the current position. The ring holds `in[t−1] … in[t−(kernel−1)]` at
761/// slots `0 … kernel−2`.
762fn short_conv_step(
763    bcx: &[f32],
764    conv: &[f32],
765    cfg: &ShortConvCfg,
766    ring_state: &mut [f32],
767    y: &mut [f32],
768) {
769    let (h, k) = (cfg.hidden_size, cfg.kernel);
770    let ring = k - 1;
771    let (bg, cg, xg) = (&bcx[0..h], &bcx[h..2 * h], &bcx[2 * h..3 * h]);
772    for c in 0..h {
773        let bx = bg[c] * xg[c];
774        let wc = &conv[c * k..(c + 1) * k];
775        // Current tap, then the past taps read from the channel's ring.
776        let mut acc = wc[k - 1] * bx;
777        let rc = &mut ring_state[c * ring..c * ring + ring];
778        for s in 0..ring {
779            acc += wc[k - 2 - s] * rc[s];
780        }
781        y[c] = cg[c] * acc;
782        // Shift newest-in-front: slot 0 becomes the just-seen input.
783        for s in (1..ring).rev() {
784            rc[s] = rc[s - 1];
785        }
786        if ring > 0 {
787            rc[0] = bx;
788        }
789    }
790}
791
792/// Forward one position through a short-conv layer, advancing `state`.
793pub fn short_conv_forward(
794    x: &[f32],
795    w: &ShortConvWeights,
796    cfg: &ShortConvCfg,
797    state: &mut Vec<f32>,
798    pool: Option<&Pool>,
799) -> Vec<f32> {
800    if state.len() != cfg.state_len() {
801        *state = vec![0f32; cfg.state_len()];
802    }
803    let h = cfg.hidden_size;
804    let mut bcx = vec![0.0f32; 3 * h];
805    w.in_proj.matvec(x, &mut bcx, pool);
806    let mut y = vec![0.0f32; h];
807    short_conv_step(&bcx, &w.conv, cfg, state, &mut y);
808    let mut out = vec![0.0f32; h];
809    w.out_proj.matvec(&y, &mut out, pool);
810    out
811}
812
813/// Batched short-conv forward (prefill-GEMM): in_proj/out_proj are matmat
814/// over the chunk (a weight row streamed once), the conv walks the
815/// positions in order — the chunk is contiguous, so the ring state is
816/// exactly the sequential path's and the math is elementwise identical.
817pub fn short_conv_forward_batch(
818    xs: &[f32],
819    b: usize,
820    w: &ShortConvWeights,
821    cfg: &ShortConvCfg,
822    state: &mut Vec<f32>,
823    pool: Option<&Pool>,
824) -> Vec<f32> {
825    if state.len() != cfg.state_len() {
826        *state = vec![0f32; cfg.state_len()];
827    }
828    let h = cfg.hidden_size;
829    let mut bcx = vec![0.0f32; b * 3 * h];
830    w.in_proj.matmat(xs, b, &mut bcx, pool);
831    let mut y = vec![0.0f32; b * h];
832    for bi in 0..b {
833        short_conv_step(
834            &bcx[bi * 3 * h..(bi + 1) * 3 * h],
835            &w.conv,
836            cfg,
837            state,
838            &mut y[bi * h..(bi + 1) * h],
839        );
840    }
841    let mut out = vec![0.0f32; b * h];
842    w.out_proj.matmat(&y, b, &mut out, pool);
843    out
844}
845
846/// Fused two-position forward (speculative verify). Lane 1 commits into
847/// `state`; lane 2's tentative ring goes into `scratch` — swapped in on
848/// draft acceptance, dropped on rejection. LFM2 ships no MTP head, so this
849/// is exercised only by the pair-fusion micro-benchmark; kept correct.
850#[allow(clippy::too_many_arguments)]
851pub fn short_conv_pair(
852    x1: &[f32],
853    x2: &[f32],
854    w: &ShortConvWeights,
855    cfg: &ShortConvCfg,
856    state: &mut Vec<f32>,
857    scratch: &mut Vec<f32>,
858    pool: Option<&Pool>,
859) -> (Vec<f32>, Vec<f32>) {
860    if state.len() != cfg.state_len() {
861        *state = vec![0f32; cfg.state_len()];
862    }
863    let h = cfg.hidden_size;
864    let mut bcx1 = vec![0.0f32; 3 * h];
865    let mut bcx2 = vec![0.0f32; 3 * h];
866    w.in_proj.matvec2(x1, x2, &mut bcx1, &mut bcx2, pool);
867
868    let mut y1 = vec![0.0f32; h];
869    short_conv_step(&bcx1, &w.conv, cfg, state, &mut y1);
870    scratch.clear();
871    scratch.extend_from_slice(state);
872    let mut y2 = vec![0.0f32; h];
873    short_conv_step(&bcx2, &w.conv, cfg, scratch, &mut y2);
874
875    let mut out1 = vec![0.0f32; h];
876    let mut out2 = vec![0.0f32; h];
877    w.out_proj.matvec2(&y1, &y2, &mut out1, &mut out2, pool);
878    (out1, out2)
879}
880
881// ─── Kimi Delta Attention (KDA) ─────────────────────────────────────────
882//
883// Kimi Linear / Kimi-K3 linear mixer (reference: FLA naive_recurrent_kda
884// + moonshotai modeling_kimi.py). Differences from GatedDeltaNet above:
885// separate q/k/v projections each behind its OWN causal depthwise short
886// convolution; the delta-rule decay is a PER-CHANNEL vector (diagonal)
887// instead of a per-head scalar; the decay pre-activation comes from a
888// low-rank projection f_b(f_a(x)); and the output gate norm uses
889// sigmoid, not SiLU.
890
891pub struct KdaWeights {
892    /// [nh·dk, hidden]
893    pub q_proj: QTensor,
894    /// [nh·dk, hidden]
895    pub k_proj: QTensor,
896    /// [nh·dv, hidden]
897    pub v_proj: QTensor,
898    /// [nh·dk × kk] — depthwise taps, oldest→newest (see GdnWeights.conv1d)
899    pub conv_q: Vec<f32>,
900    pub conv_k: Vec<f32>,
901    /// [nh·dv × kk]
902    pub conv_v: Vec<f32>,
903    /// [rank, hidden] — low-rank decay projection, stage 1
904    pub f_a: QTensor,
905    /// [nh·dk, rank] — stage 2
906    pub f_b: QTensor,
907    /// [nh·dk]
908    pub dt_bias: Vec<f32>,
909    /// [nh] per-head (Kimi-Linear-48B) | [dk] per-dim (Kimi-K3) |
910    /// [nh·dk] full — broadcast resolved by length.
911    pub a_log: Vec<f32>,
912    /// [nh, hidden] — β = σ(b_proj·x) per head
913    pub b_proj: QTensor,
914    /// Output gate: full-rank g_proj (K3) or low-rank g_b(g_a(x)) (48B).
915    pub gate: KdaOutGate,
916    /// [dv] — gated RMSNorm weight (per head over head_v_dim)
917    pub o_norm: Vec<f32>,
918    /// [hidden, nh·dv]
919    pub o_proj: QTensor,
920    /// Some(lb): log-decay = lb·σ(exp(A)·(f+bias)) (K3, lb=−5);
921    /// None: −exp(A)·softplus(f+bias) (Kimi-Linear-48B).
922    pub gate_lower_bound: Option<f32>,
923}
924
925pub enum KdaOutGate {
926    /// [nh·dv, hidden]
927    Full(QTensor),
928    /// g_a [rank, hidden], g_b [nh·dv, rank]
929    LowRank(QTensor, QTensor),
930}
931
932#[derive(Clone, Copy)]
933pub struct KdaCfg {
934    pub num_heads: usize,
935    pub head_k_dim: usize,
936    pub head_v_dim: usize,
937    pub conv_kernel: usize,
938    pub hidden_size: usize,
939    pub rms_eps: f64,
940}
941
942impl KdaCfg {
943    /// Packed state: [q ring | k ring | v ring | S nh·dk·dv], one Vec —
944    /// same single-buffer convention as GdnCfg::state_len.
945    pub fn state_len(&self) -> usize {
946        let (nh, dk, dv, kk) = (
947            self.num_heads,
948            self.head_k_dim,
949            self.head_v_dim,
950            self.conv_kernel,
951        );
952        (kk - 1) * (2 * nh * dk + nh * dv) + nh * dk * dv
953    }
954}
955
956/// Depthwise causal conv over [ring…, current] + SiLU, then ring shift.
957/// Taps oldest→newest, tap kk−1 multiplies the current position.
958fn kda_conv(raw: &[f32], taps: &[f32], ring: &mut [f32], kk: usize, out: &mut [f32]) {
959    let c_dim = raw.len();
960    for c in 0..c_dim {
961        let t = &taps[c * kk..(c + 1) * kk];
962        let mut acc = raw[c] as f64 * t[kk - 1] as f64;
963        for j in 0..kk - 1 {
964            acc += ring[j * c_dim + c] as f64 * t[j] as f64;
965        }
966        out[c] = silu(acc) as f32;
967    }
968    if kk > 1 {
969        ring.copy_within(c_dim.., 0);
970        let tail = (kk - 2) * c_dim;
971        ring[tail..tail + c_dim].copy_from_slice(raw);
972    }
973}
974
975/// Per-channel log-decay for head-channel (h, d): resolves the A_log
976/// broadcast by length and applies the configured gate formula.
977#[inline]
978fn kda_log_decay(w: &KdaWeights, cfg: &KdaCfg, h: usize, d: usize, f: f32) -> f64 {
979    let (nh, dk) = (cfg.num_heads, cfg.head_k_dim);
980    let a = if w.a_log.len() == nh {
981        w.a_log[h] as f64
982    } else if w.a_log.len() == dk {
983        w.a_log[d] as f64
984    } else {
985        w.a_log[h * dk + d] as f64
986    };
987    let raw = f as f64 + w.dt_bias[h * dk + d] as f64;
988    match w.gate_lower_bound {
989        Some(lb) => lb as f64 * sigmoid(a.exp() * raw),
990        None => -a.exp() * softplus(raw),
991    }
992}
993
994/// One recurrent step given this position's raw (pre-conv) projections.
995/// Advances the packed state and writes the gated per-head output into
996/// `of` [nh·dv]. Recurrence (FLA naive_recurrent_kda):
997///   S ← Diag(exp(g))·S;  S += β·k ⊗ (v − kᵀS);  o = qᵀS
998/// with q,k L2-normalized per head and q additionally scaled by 1/√dk —
999/// regrouped into two S passes like gdn_step (per-channel decay folds
1000/// into the k readout of the first pass).
1001#[allow(clippy::too_many_arguments)]
1002fn kda_step(
1003    xq: &[f32],
1004    xk: &[f32],
1005    xv: &[f32],
1006    f: &[f32],
1007    b: &[f32],
1008    gate_out: &[f32],
1009    w: &KdaWeights,
1010    cfg: &KdaCfg,
1011    state: &mut [f32],
1012    of: &mut [f32],
1013    pool: Option<&Pool>,
1014) {
1015    let (nh, dk, dv, kk) = (
1016        cfg.num_heads,
1017        cfg.head_k_dim,
1018        cfg.head_v_dim,
1019        cfg.conv_kernel,
1020    );
1021    let (kd, vd) = (nh * dk, nh * dv);
1022    let ring_q_len = (kk - 1) * kd;
1023    let ring_v_len = (kk - 1) * vd;
1024    let (ring_q, rest) = state.split_at_mut(ring_q_len);
1025    let (ring_k, rest) = rest.split_at_mut(ring_q_len);
1026    let (ring_v, s_all) = rest.split_at_mut(ring_v_len);
1027
1028    let mut cq = vec![0f32; kd];
1029    let mut ck = vec![0f32; kd];
1030    let mut cv = vec![0f32; vd];
1031    kda_conv(xq, &w.conv_q, ring_q, kk, &mut cq);
1032    kda_conv(xk, &w.conv_k, ring_k, kk, &mut ck);
1033    kda_conv(xv, &w.conv_v, ring_v, kk, &mut cv);
1034
1035    let (cq, ck, cv) = (&cq, &ck, &cv);
1036    let s_ptr = SendMutF32(s_all.as_mut_ptr());
1037    let of_ptr = SendMutF32(of.as_mut_ptr());
1038    let head_range = |h0: usize, h1: usize| {
1039        let (s_ptr, of_ptr) = (s_ptr, of_ptr);
1040        let mut kv = crate::attention::take_buf(dv);
1041        let mut delta = crate::attention::take_buf(dv);
1042        let mut o = crate::attention::take_buf(dv);
1043        let mut kf = crate::attention::take_buf(dk);
1044        let mut qf = crate::attention::take_buf(dk);
1045        let mut gd = crate::attention::take_buf(dk);
1046        for h in h0..h1 {
1047            let qs = h * dk;
1048            // l2-normalize q and k; q additionally scaled by 1/√dk.
1049            let (mut nq, mut nkn) = (0f64, 0f64);
1050            for d in 0..dk {
1051                nq += (cq[qs + d] as f64) * (cq[qs + d] as f64);
1052                nkn += (ck[qs + d] as f64) * (ck[qs + d] as f64);
1053            }
1054            let invq = (1.0 / ((nq + 1e-6).sqrt() * (dk as f64).sqrt())) as f32;
1055            let invk = (1.0 / (nkn + 1e-6).sqrt()) as f32;
1056            for d in 0..dk {
1057                qf[d] = cq[qs + d] * invq;
1058                kf[d] = ck[qs + d] * invk;
1059                gd[d] = kda_log_decay(w, cfg, h, d, f[qs + d]).exp() as f32;
1060            }
1061            let beta = sigmoid(b[h] as f64) as f32;
1062
1063            // SAFETY: disjoint per-head S and output slices per worker.
1064            let s = unsafe { std::slice::from_raw_parts_mut(s_ptr.0.add(h * dk * dv), dk * dv) };
1065            let oh = unsafe { std::slice::from_raw_parts_mut(of_ptr.0.add(h * dv), dv) };
1066            let vt = &cv[h * dv..(h + 1) * dv];
1067
1068            // Pass 1: kv = kᵀ(Diag(gd)·S_old) — decay folded into k.
1069            kv[..dv].fill(0.0);
1070            for di in 0..dk {
1071                let kg = kf[di] * gd[di];
1072                let row = &s[di * dv..(di + 1) * dv];
1073                for dj in 0..dv {
1074                    kv[dj] += row[dj] * kg;
1075                }
1076            }
1077            for dj in 0..dv {
1078                delta[dj] = (vt[dj] - kv[dj]) * beta;
1079            }
1080            // Pass 2: S[di,:] = gd[di]·row + k[di]·delta;  o += q[di]·row.
1081            o[..dv].fill(0.0);
1082            for di in 0..dk {
1083                let (kfd, qfd, gdd) = (kf[di], qf[di], gd[di]);
1084                let row = &mut s[di * dv..(di + 1) * dv];
1085                for dj in 0..dv {
1086                    let cell = gdd * row[dj] + kfd * delta[dj];
1087                    row[dj] = cell;
1088                    o[dj] += qfd * cell;
1089                }
1090            }
1091            // Gated RMSNorm per head: x̂·w·σ(gate) — sigmoid, not SiLU.
1092            let ss: f64 = o[..dv].iter().map(|&v| (v as f64) * (v as f64)).sum();
1093            let inv = 1.0 / (ss / dv as f64 + cfg.rms_eps).sqrt();
1094            for dj in 0..dv {
1095                oh[dj] = ((o[dj] as f64 * inv)
1096                    * w.o_norm[dj] as f64
1097                    * sigmoid(gate_out[h * dv + dj] as f64)) as f32;
1098            }
1099        }
1100        crate::attention::recycle_buf(&mut kv);
1101        crate::attention::recycle_buf(&mut delta);
1102        crate::attention::recycle_buf(&mut o);
1103        crate::attention::recycle_buf(&mut kf);
1104        crate::attention::recycle_buf(&mut qf);
1105        crate::attention::recycle_buf(&mut gd);
1106    };
1107    match pool {
1108        Some(pool) if nh >= 4 => pool.run(&|widx, n| {
1109            let chunk = nh.div_ceil(n);
1110            let h0 = (widx * chunk).min(nh);
1111            let h1 = (h0 + chunk).min(nh);
1112            if h0 < h1 {
1113                head_range(h0, h1);
1114            }
1115        }),
1116        _ => head_range(0, nh),
1117    }
1118}
1119
1120/// Project one position's raw q/k/v/f/β/gate inputs (shared by the
1121/// single and batched forwards; `bi` selects the row when batched).
1122fn kda_gate_out(w: &KdaWeights, x: &[f32], vd: usize, pool: Option<&Pool>) -> Vec<f32> {
1123    let mut g = vec![0.0f32; vd];
1124    match &w.gate {
1125        KdaOutGate::Full(gp) => gp.matvec(x, &mut g, pool),
1126        KdaOutGate::LowRank(ga, gb) => {
1127            let mut low = vec![0.0f32; ga.rows()];
1128            ga.matvec(x, &mut low, pool);
1129            gb.matvec(&low, &mut g, pool);
1130        }
1131    }
1132    g
1133}
1134
1135/// Forward one position through a KDA layer, advancing `state`.
1136pub fn kda_forward(
1137    x: &[f32],
1138    w: &KdaWeights,
1139    cfg: &KdaCfg,
1140    state: &mut Vec<f32>,
1141    pool: Option<&Pool>,
1142) -> Vec<f32> {
1143    if state.len() != cfg.state_len() {
1144        *state = vec![0f32; cfg.state_len()];
1145    }
1146    let (nh, dk, dv) = (cfg.num_heads, cfg.head_k_dim, cfg.head_v_dim);
1147    let (kd, vd) = (nh * dk, nh * dv);
1148
1149    let mut xq = vec![0.0f32; kd];
1150    let mut xk = vec![0.0f32; kd];
1151    let mut xv = vec![0.0f32; vd];
1152    let mut fl = vec![0.0f32; w.f_a.rows()];
1153    let mut b = vec![0.0f32; nh];
1154    QTensor::matvec_many(
1155        [&w.q_proj, &w.k_proj, &w.v_proj, &w.f_a],
1156        x,
1157        [
1158            xq.as_mut_slice(),
1159            xk.as_mut_slice(),
1160            xv.as_mut_slice(),
1161            fl.as_mut_slice(),
1162        ],
1163        pool,
1164    );
1165    w.b_proj.matvec(x, &mut b, pool);
1166    let mut f = vec![0.0f32; kd];
1167    w.f_b.matvec(&fl, &mut f, pool);
1168    let gate_out = kda_gate_out(w, x, vd, pool);
1169
1170    let mut of = vec![0.0f32; vd];
1171    kda_step(
1172        &xq, &xk, &xv, &f, &b, &gate_out, w, cfg, state, &mut of, pool,
1173    );
1174
1175    let mut out = vec![0.0f32; cfg.hidden_size];
1176    w.o_proj.matvec(&of, &mut out, pool);
1177    out
1178}
1179
1180/// Batched KDA forward (prefill-GEMM): projections as matmat over the
1181/// chunk, the recurrence sequential per position — elementwise identical
1182/// to the single-position path.
1183pub fn kda_forward_batch(
1184    xs: &[f32],
1185    bsz: usize,
1186    w: &KdaWeights,
1187    cfg: &KdaCfg,
1188    state: &mut Vec<f32>,
1189    pool: Option<&Pool>,
1190) -> Vec<f32> {
1191    if state.len() != cfg.state_len() {
1192        *state = vec![0f32; cfg.state_len()];
1193    }
1194    let (nh, dk, dv, hs) = (
1195        cfg.num_heads,
1196        cfg.head_k_dim,
1197        cfg.head_v_dim,
1198        cfg.hidden_size,
1199    );
1200    let (kd, vd) = (nh * dk, nh * dv);
1201
1202    let mut xq = vec![0.0f32; bsz * kd];
1203    w.q_proj.matmat(xs, bsz, &mut xq, pool);
1204    let mut xk = vec![0.0f32; bsz * kd];
1205    w.k_proj.matmat(xs, bsz, &mut xk, pool);
1206    let mut xv = vec![0.0f32; bsz * vd];
1207    w.v_proj.matmat(xs, bsz, &mut xv, pool);
1208    let rank = w.f_a.rows();
1209    let mut fl = vec![0.0f32; bsz * rank];
1210    w.f_a.matmat(xs, bsz, &mut fl, pool);
1211    let mut f = vec![0.0f32; bsz * kd];
1212    w.f_b.matmat(&fl, bsz, &mut f, pool);
1213    let mut b = vec![0.0f32; bsz * nh];
1214    w.b_proj.matmat(xs, bsz, &mut b, pool);
1215    let mut gate_out = vec![0.0f32; bsz * vd];
1216    match &w.gate {
1217        KdaOutGate::Full(gp) => gp.matmat(xs, bsz, &mut gate_out, pool),
1218        KdaOutGate::LowRank(ga, gb) => {
1219            let mut low = vec![0.0f32; bsz * ga.rows()];
1220            ga.matmat(xs, bsz, &mut low, pool);
1221            gb.matmat(&low, bsz, &mut gate_out, pool);
1222        }
1223    }
1224
1225    let mut of = vec![0.0f32; bsz * vd];
1226    for bi in 0..bsz {
1227        let mut oh = vec![0.0f32; vd];
1228        kda_step(
1229            &xq[bi * kd..(bi + 1) * kd],
1230            &xk[bi * kd..(bi + 1) * kd],
1231            &xv[bi * vd..(bi + 1) * vd],
1232            &f[bi * kd..(bi + 1) * kd],
1233            &b[bi * nh..(bi + 1) * nh],
1234            &gate_out[bi * vd..(bi + 1) * vd],
1235            w,
1236            cfg,
1237            state,
1238            &mut oh,
1239            pool,
1240        );
1241        of[bi * vd..(bi + 1) * vd].copy_from_slice(&oh);
1242    }
1243
1244    let mut out = vec![0.0f32; bsz * hs];
1245    w.o_proj.matmat(&of, bsz, &mut out, pool);
1246    out
1247}
1248
1249#[cfg(test)]
1250mod tests {
1251    #[test]
1252    fn kda_forward_matches_naive_reference() {
1253        // Small deterministic KDA layer; the oracle is a literal port of
1254        // FLA naive_recurrent_kda + naive_kda_gate + the modeling glue
1255        // (conv→silu, low-rank decay, sigmoid-gated output norm), coded
1256        // straight from the reference — a different shape from the fused
1257        // two-pass production kernel.
1258        let (nh, dk, dv, kk, hs, rank) = (2usize, 4usize, 4usize, 3usize, 6usize, 3usize);
1259        let synth = |rows: usize, cols: usize, salt: usize| -> QTensor {
1260            QTensor::from_f32(
1261                (0..rows * cols)
1262                    .map(|i| (((i * 31 + salt * 17) % 101) as f32 / 101.0 - 0.5) * 0.6)
1263                    .collect(),
1264                rows,
1265                cols,
1266            )
1267        };
1268        let vecf = |n: usize, salt: usize| -> Vec<f32> {
1269            (0..n)
1270                .map(|i| (((i * 13 + salt * 7) % 89) as f32 / 89.0 - 0.5) * 0.8)
1271                .collect()
1272        };
1273        for (label, a_log, lb) in [
1274            ("per-head standard", vecf(nh, 40), None),
1275            ("per-dim lower-bound", vecf(dk, 41), Some(-5.0f32)),
1276        ] {
1277            let w = KdaWeights {
1278                q_proj: synth(nh * dk, hs, 1),
1279                k_proj: synth(nh * dk, hs, 2),
1280                v_proj: synth(nh * dv, hs, 3),
1281                conv_q: vecf(nh * dk * kk, 4),
1282                conv_k: vecf(nh * dk * kk, 5),
1283                conv_v: vecf(nh * dv * kk, 6),
1284                f_a: synth(rank, hs, 7),
1285                f_b: synth(nh * dk, rank, 8),
1286                dt_bias: vecf(nh * dk, 9),
1287                a_log: a_log.clone(),
1288                b_proj: synth(nh, hs, 10),
1289                gate: KdaOutGate::LowRank(synth(rank, hs, 11), synth(nh * dv, rank, 12)),
1290                o_norm: (0..dv).map(|i| 1.0 + 0.1 * i as f32).collect(),
1291                o_proj: synth(hs, nh * dv, 13),
1292                gate_lower_bound: lb,
1293            };
1294            let cfg = KdaCfg {
1295                num_heads: nh,
1296                head_k_dim: dk,
1297                head_v_dim: dv,
1298                conv_kernel: kk,
1299                hidden_size: hs,
1300                rms_eps: 1e-6,
1301            };
1302            let xs: Vec<Vec<f32>> = (0..6)
1303                .map(|t| {
1304                    (0..hs)
1305                        .map(|i| ((t * hs + i) as f32 * 0.37).sin() * 0.5)
1306                        .collect()
1307                })
1308                .collect();
1309
1310            // Production path.
1311            let mut state = Vec::new();
1312            let got: Vec<Vec<f32>> = xs
1313                .iter()
1314                .map(|x| kda_forward(x, &w, &cfg, &mut state, None))
1315                .collect();
1316
1317            // Oracle.
1318            let mv = |t: &QTensor, x: &[f32]| -> Vec<f32> {
1319                let mut o = vec![0.0f32; t.rows()];
1320                t.matvec(x, &mut o, None);
1321                o
1322            };
1323            let mut hist: Vec<(Vec<f32>, Vec<f32>, Vec<f32>)> = Vec::new(); // raw xq/xk/xv
1324            let mut s_state = vec![0f64; nh * dk * dv];
1325            let mut want: Vec<Vec<f32>> = Vec::new();
1326            for x in &xs {
1327                let (xq, xk, xv) = (mv(&w.q_proj, x), mv(&w.k_proj, x), mv(&w.v_proj, x));
1328                hist.push((xq, xk, xv));
1329                // conv over the raw history, taps oldest→newest.
1330                let conv = |sel: fn(&(Vec<f32>, Vec<f32>, Vec<f32>)) -> &Vec<f32>,
1331                            taps: &[f32],
1332                            n: usize|
1333                 -> Vec<f32> {
1334                    (0..n)
1335                        .map(|c| {
1336                            let t = &taps[c * kk..(c + 1) * kk];
1337                            let mut acc = 0f64;
1338                            for j in 0..kk {
1339                                let idx = hist.len() as i64 - (kk as i64 - j as i64);
1340                                if idx >= 0 {
1341                                    acc += sel(&hist[idx as usize])[c] as f64 * t[j] as f64;
1342                                }
1343                            }
1344                            silu(acc)
1345                        })
1346                        .map(|v| v as f32)
1347                        .collect()
1348                };
1349                let cq = conv(|h| &h.0, &w.conv_q, nh * dk);
1350                let ck = conv(|h| &h.1, &w.conv_k, nh * dk);
1351                let cv = conv(|h| &h.2, &w.conv_v, nh * dv);
1352                let f = mv(&w.f_b, &mv(&w.f_a, x));
1353                let bb = mv(&w.b_proj, x);
1354                let gate_out = match &w.gate {
1355                    KdaOutGate::LowRank(ga, gb) => mv(gb, &mv(ga, x)),
1356                    KdaOutGate::Full(g) => mv(g, x),
1357                };
1358                let mut of = vec![0f32; nh * dv];
1359                for h in 0..nh {
1360                    // l2norm + scale.
1361                    let q: Vec<f64> = {
1362                        let sl = &cq[h * dk..(h + 1) * dk];
1363                        let n: f64 = sl.iter().map(|&v| (v as f64) * (v as f64)).sum();
1364                        let inv = 1.0 / ((n + 1e-6).sqrt() * (dk as f64).sqrt());
1365                        sl.iter().map(|&v| v as f64 * inv).collect()
1366                    };
1367                    let k: Vec<f64> = {
1368                        let sl = &ck[h * dk..(h + 1) * dk];
1369                        let n: f64 = sl.iter().map(|&v| (v as f64) * (v as f64)).sum();
1370                        let inv = 1.0 / (n + 1e-6).sqrt();
1371                        sl.iter().map(|&v| v as f64 * inv).collect()
1372                    };
1373                    let v: Vec<f64> = cv[h * dv..(h + 1) * dv].iter().map(|&v| v as f64).collect();
1374                    // gate: g = −exp(A)·softplus(f+bias) | lb·σ(exp(A)·(f+bias))
1375                    let g: Vec<f64> = (0..dk)
1376                        .map(|d| {
1377                            let a = if w.a_log.len() == nh {
1378                                w.a_log[h] as f64
1379                            } else {
1380                                w.a_log[d] as f64
1381                            };
1382                            let raw = f[h * dk + d] as f64 + w.dt_bias[h * dk + d] as f64;
1383                            match w.gate_lower_bound {
1384                                Some(lb) => lb as f64 * sigmoid(a.exp() * raw),
1385                                None => -a.exp() * softplus(raw),
1386                            }
1387                        })
1388                        .collect();
1389                    let beta = sigmoid(bb[h] as f64);
1390                    let s = &mut s_state[h * dk * dv..(h + 1) * dk * dv];
1391                    // S = Diag(exp(g))·S
1392                    for di in 0..dk {
1393                        for dj in 0..dv {
1394                            s[di * dv + dj] *= g[di].exp();
1395                        }
1396                    }
1397                    // kv = kᵀS; S += β·k⊗(v−kv); o = qᵀS
1398                    let mut kv = vec![0f64; dv];
1399                    for di in 0..dk {
1400                        for dj in 0..dv {
1401                            kv[dj] += k[di] * s[di * dv + dj];
1402                        }
1403                    }
1404                    for di in 0..dk {
1405                        for dj in 0..dv {
1406                            s[di * dv + dj] += beta * k[di] * (v[dj] - kv[dj]);
1407                        }
1408                    }
1409                    let mut o = vec![0f64; dv];
1410                    for di in 0..dk {
1411                        for dj in 0..dv {
1412                            o[dj] += q[di] * s[di * dv + dj];
1413                        }
1414                    }
1415                    // sigmoid-gated RMSNorm
1416                    let ss: f64 = o.iter().map(|&v| v * v).sum();
1417                    let inv = 1.0 / (ss / dv as f64 + cfg.rms_eps).sqrt();
1418                    for dj in 0..dv {
1419                        of[h * dv + dj] = (o[dj]
1420                            * inv
1421                            * w.o_norm[dj] as f64
1422                            * sigmoid(gate_out[h * dv + dj] as f64))
1423                            as f32;
1424                    }
1425                }
1426                want.push(mv(&w.o_proj, &of));
1427            }
1428
1429            for (t, (g, e)) in got.iter().zip(&want).enumerate() {
1430                for (i, (a, b)) in g.iter().zip(e.iter()).enumerate() {
1431                    assert!((a - b).abs() < 2e-4, "{label}: t={t} i={i}: {a} vs {b}");
1432                }
1433            }
1434        }
1435
1436        // Batched prefill must equal the sequential singles bit-close.
1437        let w = KdaWeights {
1438            q_proj: synth(nh * dk, hs, 1),
1439            k_proj: synth(nh * dk, hs, 2),
1440            v_proj: synth(nh * dv, hs, 3),
1441            conv_q: vecf(nh * dk * kk, 4),
1442            conv_k: vecf(nh * dk * kk, 5),
1443            conv_v: vecf(nh * dv * kk, 6),
1444            f_a: synth(rank, hs, 7),
1445            f_b: synth(nh * dk, rank, 8),
1446            dt_bias: vecf(nh * dk, 9),
1447            a_log: vecf(nh, 40),
1448            b_proj: synth(nh, hs, 10),
1449            gate: KdaOutGate::LowRank(synth(rank, hs, 11), synth(nh * dv, rank, 12)),
1450            o_norm: (0..dv).map(|i| 1.0 + 0.1 * i as f32).collect(),
1451            o_proj: synth(hs, nh * dv, 13),
1452            gate_lower_bound: None,
1453        };
1454        let cfg = KdaCfg {
1455            num_heads: nh,
1456            head_k_dim: dk,
1457            head_v_dim: dv,
1458            conv_kernel: kk,
1459            hidden_size: hs,
1460            rms_eps: 1e-6,
1461        };
1462        let xs: Vec<f32> = (0..5 * hs).map(|i| (i as f32 * 0.29).cos() * 0.4).collect();
1463        let mut st1 = Vec::new();
1464        let seq: Vec<f32> = (0..5)
1465            .flat_map(|t| kda_forward(&xs[t * hs..(t + 1) * hs], &w, &cfg, &mut st1, None))
1466            .collect();
1467        let mut st2 = Vec::new();
1468        let bat = kda_forward_batch(&xs, 5, &w, &cfg, &mut st2, None);
1469        for (i, (a, b)) in seq.iter().zip(&bat).enumerate() {
1470            assert!((a - b).abs() < 1e-5, "batch i={i}: {a} vs {b}");
1471        }
1472        assert_eq!(st1, st2, "state must match after the chunk");
1473    }
1474
1475    use super::*;
1476
1477    fn tiny() -> (VmfPhaseWeights, VmfPhaseCfg) {
1478        let cfg = VmfPhaseCfg {
1479            num_heads: 2,
1480            nphase: 3,
1481            value_head_dim: 4,
1482            hidden_size: 8,
1483            phase_mass: 0.0,
1484        };
1485        let synth = |rows: usize, cols: usize, salt: usize| {
1486            QTensor::from_f32(
1487                (0..rows * cols)
1488                    .map(|i| (((i * 13 + salt * 7) % 97) as f32 / 97.0 - 0.5) * 0.4)
1489                    .collect(),
1490                rows,
1491                cols,
1492            )
1493        };
1494        let w = VmfPhaseWeights {
1495            thq: synth(cfg.num_heads * cfg.nphase, cfg.hidden_size, 1),
1496            thk: synth(cfg.num_heads * cfg.nphase, cfg.hidden_size, 2),
1497            v_proj: synth(cfg.num_heads * cfg.value_head_dim, cfg.hidden_size, 3),
1498            out_proj: synth(cfg.hidden_size, cfg.num_heads * cfg.value_head_dim, 4),
1499            decay: (0..cfg.num_heads * 2 * cfg.nphase)
1500                .map(|i| 0.9 + 0.005 * (i % 10) as f64)
1501                .collect(),
1502            k_gate: None,
1503        };
1504        (w, cfg)
1505    }
1506
1507    #[test]
1508    fn state_persists_and_changes_output() {
1509        let (w, cfg) = tiny();
1510        let x: Vec<f32> = (0..8).map(|i| (i as f32 * 0.3).sin()).collect();
1511        let mut state = Vec::new();
1512        let o1 = vmf_phase_forward(&x, &w, &cfg, &mut state, None);
1513        let o2 = vmf_phase_forward(&x, &w, &cfg, &mut state, None);
1514        // Same input, evolved condensate → different output.
1515        assert!(o1.iter().zip(&o2).any(|(a, b)| (a - b).abs() > 1e-6));
1516        assert_eq!(state.len(), cfg.state_len());
1517    }
1518
1519    /// θ-mass (η′): mass=0 is bit-identical to the massless kernel; mass>0
1520    /// changes the output (phase narrowed → kernel widened). Guards the
1521    /// no-op default and that the knob is actually wired.
1522    #[test]
1523    fn phase_mass_zero_is_noop_and_positive_shifts() {
1524        let (w, cfg0) = tiny();
1525        let mut cfg_m = cfg0.clone();
1526        cfg_m.phase_mass = 1.0;
1527        let x: Vec<f32> = (0..8).map(|i| (i as f32 * 0.4).sin()).collect();
1528
1529        let mut s0 = Vec::new();
1530        let base = vmf_phase_forward(&x, &w, &cfg0, &mut s0, None);
1531        // Re-run with mass=0 → must be bit-identical.
1532        let mut s0b = Vec::new();
1533        let base2 = vmf_phase_forward(&x, &w, &cfg0, &mut s0b, None);
1534        assert_eq!(base, base2, "mass=0 must be deterministic/no-op");
1535        // mass=1 → output differs (θ halved before cos/sin).
1536        let mut sm = Vec::new();
1537        let massed = vmf_phase_forward(&x, &w, &cfg_m, &mut sm, None);
1538        assert!(
1539            base.iter().zip(&massed).any(|(a, b)| (a - b).abs() > 1e-5),
1540            "mass>0 must change the output"
1541        );
1542        assert!(massed.iter().all(|v| v.is_finite()));
1543    }
1544
1545    /// κ write gate (hybrid_k): saturated-open gate (bias ≫ 0 → κ→1)
1546    /// matches the gateless kernel within fp tolerance; a closed gate
1547    /// (bias ≪ 0 → κ→0) writes nothing — the state stays zero and the
1548    /// output collapses to the empty-condensate readout.
1549    #[test]
1550    fn kappa_gate_open_matches_none_and_closed_writes_nothing() {
1551        let (mut w, cfg) = tiny();
1552        let x: Vec<f32> = (0..8).map(|i| (i as f32 * 0.3).sin()).collect();
1553
1554        let mut s_none = Vec::new();
1555        let base1 = vmf_phase_forward(&x, &w, &cfg, &mut s_none, None);
1556        let base2 = vmf_phase_forward(&x, &w, &cfg, &mut s_none, None);
1557
1558        // Open gate: W=0, bias=+20 → κ = σ(20) ≈ 1 − 2e−9.
1559        w.k_gate = Some((
1560            QTensor::from_f32(
1561                vec![0.0; cfg.num_heads * cfg.hidden_size],
1562                cfg.num_heads,
1563                cfg.hidden_size,
1564            ),
1565            vec![20.0; cfg.num_heads],
1566        ));
1567        let mut s_open = Vec::new();
1568        let o1 = vmf_phase_forward(&x, &w, &cfg, &mut s_open, None);
1569        let o2 = vmf_phase_forward(&x, &w, &cfg, &mut s_open, None);
1570        for (a, b) in base1.iter().zip(&o1).chain(base2.iter().zip(&o2)) {
1571            assert!(
1572                (a - b).abs() < 1e-5,
1573                "open κ must match gateless: {a} vs {b}"
1574            );
1575        }
1576
1577        // Closed gate: bias=−20 → κ ≈ 0 → nothing is written.
1578        w.k_gate = Some((
1579            QTensor::from_f32(
1580                vec![0.0; cfg.num_heads * cfg.hidden_size],
1581                cfg.num_heads,
1582                cfg.hidden_size,
1583            ),
1584            vec![-20.0; cfg.num_heads],
1585        ));
1586        let mut s_closed = Vec::new();
1587        let oc = vmf_phase_forward(&x, &w, &cfg, &mut s_closed, None);
1588        assert!(
1589            s_closed.iter().all(|&v| v.abs() < 1e-7),
1590            "closed κ: state must stay empty"
1591        );
1592        assert!(
1593            oc.iter().all(|&v| v.abs() < 1e-6),
1594            "closed κ: empty-condensate readout"
1595        );
1596    }
1597
1598    #[test]
1599    fn pair_matches_two_singles_bitexact() {
1600        let (w, cfg) = tiny();
1601        let x1: Vec<f32> = (0..8).map(|i| (i as f32 * 0.2).cos()).collect();
1602        let x2: Vec<f32> = (0..8).map(|i| (i as f32 * 0.5).sin()).collect();
1603
1604        // Reference: two sequential singles.
1605        let mut s_ref = Vec::new();
1606        let r1 = vmf_phase_forward(&x1, &w, &cfg, &mut s_ref, None);
1607        let r2 = vmf_phase_forward(&x2, &w, &cfg, &mut s_ref, None);
1608
1609        // Pair: lane1 commits, lane2 tentative in scratch.
1610        let mut s = Vec::new();
1611        let mut scratch = Vec::new();
1612        let (p1, p2) = vmf_phase_pair(&x1, &x2, &w, &cfg, &mut s, &mut scratch, None);
1613        assert_eq!(r1, p1, "lane 1 must be bit-identical");
1614        assert_eq!(r2, p2, "lane 2 must be bit-identical");
1615        // Accepting the draft = swapping scratch in → equals s_ref.
1616        std::mem::swap(&mut s, &mut scratch);
1617        assert_eq!(s, s_ref, "accepted state must equal sequential state");
1618    }
1619
1620    #[test]
1621    fn rejected_draft_leaves_state_at_lane1() {
1622        let (w, cfg) = tiny();
1623        let x1: Vec<f32> = (0..8).map(|i| (i as f32 * 0.7).sin()).collect();
1624        let x2 = vec![0.5f32; 8];
1625
1626        let mut s_ref = Vec::new();
1627        let _ = vmf_phase_forward(&x1, &w, &cfg, &mut s_ref, None);
1628
1629        let mut s = Vec::new();
1630        let mut scratch = Vec::new();
1631        let _ = vmf_phase_pair(&x1, &x2, &w, &cfg, &mut s, &mut scratch, None);
1632        // Reject: state must be exactly the post-lane1 state.
1633        assert_eq!(s, s_ref);
1634    }
1635
1636    // ───────────── GatedDeltaNet ─────────────
1637
1638    fn tiny_gdn() -> (GdnWeights, GdnCfg) {
1639        let cfg = GdnCfg {
1640            num_v_heads: 4,
1641            num_k_heads: 2,
1642            key_head_dim: 3,
1643            value_head_dim: 5,
1644            conv_kernel: 4,
1645            hidden_size: 8,
1646            rms_eps: 1e-6,
1647        };
1648        let c_dim = cfg.conv_dim();
1649        let vd = cfg.num_v_heads * cfg.value_head_dim;
1650        let synth = |rows: usize, cols: usize, salt: usize| {
1651            QTensor::from_f32(
1652                (0..rows * cols)
1653                    .map(|i| (((i * 13 + salt * 7) % 97) as f32 / 97.0 - 0.5) * 0.4)
1654                    .collect(),
1655                rows,
1656                cols,
1657            )
1658        };
1659        let vecf = |n: usize, salt: usize| -> Vec<f32> {
1660            (0..n)
1661                .map(|i| (((i * 11 + salt * 5) % 89) as f32 / 89.0 - 0.5) * 0.6)
1662                .collect()
1663        };
1664        let w = GdnWeights {
1665            in_proj_qkv: synth(c_dim, cfg.hidden_size, 1),
1666            in_proj_z: synth(vd, cfg.hidden_size, 2),
1667            in_proj_a: synth(cfg.num_v_heads, cfg.hidden_size, 3),
1668            in_proj_b: synth(cfg.num_v_heads, cfg.hidden_size, 4),
1669            conv1d: vecf(c_dim * cfg.conv_kernel, 5),
1670            a_log: (0..cfg.num_v_heads).map(|i| 0.2 + 0.3 * i as f32).collect(),
1671            dt_bias: vecf(cfg.num_v_heads, 6),
1672            norm: vec![1.0; cfg.value_head_dim],
1673            out_proj: synth(cfg.hidden_size, vd, 7),
1674        };
1675        (w, cfg)
1676    }
1677
1678    #[test]
1679    fn gdn_state_persists_and_changes_output() {
1680        let (w, cfg) = tiny_gdn();
1681        let x: Vec<f32> = (0..8).map(|i| (i as f32 * 0.3).sin()).collect();
1682        let mut state = Vec::new();
1683        let o1 = gdn_forward(&x, &w, &cfg, &mut state, None);
1684        let o2 = gdn_forward(&x, &w, &cfg, &mut state, None);
1685        assert!(o1.iter().zip(&o2).any(|(a, b)| (a - b).abs() > 1e-6));
1686        assert_eq!(state.len(), cfg.state_len());
1687    }
1688
1689    #[test]
1690    fn gdn_pair_matches_two_singles_bitexact() {
1691        let (w, cfg) = tiny_gdn();
1692        let x1: Vec<f32> = (0..8).map(|i| (i as f32 * 0.2).cos()).collect();
1693        let x2: Vec<f32> = (0..8).map(|i| (i as f32 * 0.5).sin()).collect();
1694
1695        let mut s_ref = Vec::new();
1696        let r1 = gdn_forward(&x1, &w, &cfg, &mut s_ref, None);
1697        let r2 = gdn_forward(&x2, &w, &cfg, &mut s_ref, None);
1698
1699        let mut s = Vec::new();
1700        let mut scratch = Vec::new();
1701        let (p1, p2) = gdn_pair(&x1, &x2, &w, &cfg, &mut s, &mut scratch, None);
1702        assert_eq!(r1, p1, "lane 1 must be bit-identical");
1703        assert_eq!(r2, p2, "lane 2 must be bit-identical");
1704        std::mem::swap(&mut s, &mut scratch);
1705        assert_eq!(s, s_ref, "accepted state must equal sequential state");
1706    }
1707
1708    #[test]
1709    fn gdn_rejected_draft_leaves_state_at_lane1() {
1710        let (w, cfg) = tiny_gdn();
1711        let x1: Vec<f32> = (0..8).map(|i| (i as f32 * 0.7).sin()).collect();
1712        let x2 = vec![0.5f32; 8];
1713
1714        let mut s_ref = Vec::new();
1715        let _ = gdn_forward(&x1, &w, &cfg, &mut s_ref, None);
1716
1717        let mut s = Vec::new();
1718        let mut scratch = Vec::new();
1719        let _ = gdn_pair(&x1, &x2, &w, &cfg, &mut s, &mut scratch, None);
1720        assert_eq!(s, s_ref);
1721    }
1722
1723    /// The conv ring must give the same result as an explicit causal
1724    /// conv over the whole sequence (oracle semantics: zero left-pad,
1725    /// tap kk−1 on the current position).
1726    #[test]
1727    fn gdn_conv_ring_matches_explicit_causal_conv() {
1728        let (w, cfg) = tiny_gdn();
1729        let seq: Vec<Vec<f32>> = (0..6)
1730            .map(|t| (0..8).map(|i| ((t * 8 + i) as f32 * 0.17).sin()).collect())
1731            .collect();
1732
1733        // Reference: recompute position t from scratch each time with a
1734        // fresh state built by replaying the prefix.
1735        let mut s_inc = Vec::new();
1736        for (t, x) in seq.iter().enumerate() {
1737            let inc = gdn_forward(x, &w, &cfg, &mut s_inc, None);
1738            let mut s_replay = Vec::new();
1739            let mut replay = Vec::new();
1740            for xr in &seq[..=t] {
1741                replay = gdn_forward(xr, &w, &cfg, &mut s_replay, None);
1742            }
1743            assert_eq!(inc, replay, "position {t}: ring must equal replay");
1744        }
1745    }
1746
1747    fn tiny_short_conv() -> (ShortConvWeights, ShortConvCfg) {
1748        let cfg = ShortConvCfg {
1749            hidden_size: 8,
1750            kernel: 3,
1751        };
1752        let synth = |rows: usize, cols: usize, salt: usize| {
1753            QTensor::from_f32(
1754                (0..rows * cols)
1755                    .map(|i| (((i * 11 + salt * 5) % 89) as f32 / 89.0 - 0.5) * 0.5)
1756                    .collect(),
1757                rows,
1758                cols,
1759            )
1760        };
1761        let w = ShortConvWeights {
1762            in_proj: synth(3 * cfg.hidden_size, cfg.hidden_size, 1),
1763            conv: (0..cfg.hidden_size * cfg.kernel)
1764                .map(|i| ((i * 7 % 13) as f32 / 13.0 - 0.5) * 0.8)
1765                .collect(),
1766            out_proj: synth(cfg.hidden_size, cfg.hidden_size, 2),
1767        };
1768        (w, cfg)
1769    }
1770
1771    /// The incremental conv ring must equal a from-scratch causal replay
1772    /// of the prefix at every position — the decode/prefill contract.
1773    #[test]
1774    fn short_conv_ring_matches_explicit_causal_conv() {
1775        let (w, cfg) = tiny_short_conv();
1776        let seq: Vec<Vec<f32>> = (0..6)
1777            .map(|t| (0..8).map(|i| ((t * 8 + i) as f32 * 0.19).cos()).collect())
1778            .collect();
1779        let mut s_inc = Vec::new();
1780        for (t, x) in seq.iter().enumerate() {
1781            let inc = short_conv_forward(x, &w, &cfg, &mut s_inc, None);
1782            let mut s_replay = Vec::new();
1783            let mut replay = Vec::new();
1784            for xr in &seq[..=t] {
1785                replay = short_conv_forward(xr, &w, &cfg, &mut s_replay, None);
1786            }
1787            assert_eq!(inc, replay, "position {t}: ring must equal replay");
1788            assert_eq!(s_inc.len(), cfg.state_len());
1789        }
1790    }
1791
1792    /// The batched prefill path (matmat + sequential conv over the chunk)
1793    /// must reproduce the position-by-position decode path exactly.
1794    #[test]
1795    fn short_conv_batch_matches_sequential() {
1796        let (w, cfg) = tiny_short_conv();
1797        let b = 5;
1798        let xs: Vec<f32> = (0..b * cfg.hidden_size)
1799            .map(|i| (i as f32 * 0.13).sin() * 0.6)
1800            .collect();
1801
1802        let mut s_seq = Vec::new();
1803        let mut seq_out = vec![0.0f32; b * cfg.hidden_size];
1804        for bi in 0..b {
1805            let o = short_conv_forward(
1806                &xs[bi * cfg.hidden_size..(bi + 1) * cfg.hidden_size],
1807                &w,
1808                &cfg,
1809                &mut s_seq,
1810                None,
1811            );
1812            seq_out[bi * cfg.hidden_size..(bi + 1) * cfg.hidden_size].copy_from_slice(&o);
1813        }
1814
1815        let mut s_batch = Vec::new();
1816        let batch_out = short_conv_forward_batch(&xs, b, &w, &cfg, &mut s_batch, None);
1817        assert_eq!(
1818            seq_out, batch_out,
1819            "batch conv must match sequential decode"
1820        );
1821        assert_eq!(s_seq, s_batch, "ring state must match after the chunk");
1822    }
1823}