Skip to main content

cortiq_engine/
attention.rs

1//! Attention forward pass — GQA with RoPE, head masking, head-major KV.
2//!
3//! Two entry points:
4//! - `multi_head_attention` — the historical f32-slice path with per-head
5//!   masking (task masks); untouched, exercised by masked models.
6//! - `qwen_attention` / `qwen_attention_pair` — the dense QTensor path:
7//!   quantized-from-mmap weights, optional Qwen3.5 extras (per-head
8//!   qk-norm, output gate, partial rotary). With extras off and f32
9//!   weights the math is identical to the historical path.
10
11use crate::kv_cache::LayerKvCache;
12use crate::pool::Pool;
13use crate::qtensor::QTensor;
14
15/// Scale-less RMS normalization of one V head (Gemma-4):
16/// x ← x / sqrt(mean(x²) + eps). No weight, no +1 — pure normalization.
17fn vnorm_head(x: &mut [f32], eps: f64) {
18    let ms = x.iter().map(|&a| (a as f64) * (a as f64)).sum::<f64>() / x.len().max(1) as f64;
19    let inv = 1.0 / (ms + eps).sqrt() as f32;
20    for a in x.iter_mut() {
21        *a *= inv;
22    }
23}
24
25/// Precompute RoPE inverse frequencies for a head dimension — powf is
26/// paid once per model, not per (head × position × dim) in the hot loop.
27pub fn rope_inv_freq(head_dim: usize, base: f32) -> Vec<f32> {
28    (0..head_dim / 2)
29        .map(|i| 1.0 / base.powf(2.0 * i as f32 / head_dim as f32))
30        .collect()
31}
32
33/// Hugging Face-compatible YaRN inverse frequencies. `head_dim` is the
34/// rotary dimension (after partial_rotary_factor), not the full head width.
35pub fn yarn_inv_freq(
36    head_dim: usize,
37    base: f32,
38    factor: f32,
39    original_max_position_embeddings: usize,
40    beta_fast: f32,
41    beta_slow: f32,
42) -> Vec<f32> {
43    let correction_dim = |rotations: f32| {
44        (head_dim as f32
45            * (original_max_position_embeddings as f32 / (rotations * 2.0 * std::f32::consts::PI))
46                .ln())
47            / (2.0 * base.ln())
48    };
49    let low = correction_dim(beta_fast).floor().max(0.0) as usize;
50    let high = correction_dim(beta_slow)
51        .ceil()
52        .clamp(0.0, (head_dim / 2).saturating_sub(1) as f32) as usize;
53    let denom = (high.saturating_sub(low)).max(1) as f32;
54    (0..head_dim / 2)
55        .map(|i| {
56            let extrap = 1.0 / base.powf(2.0 * i as f32 / head_dim as f32);
57            let interp = extrap / factor;
58            let ramp = ((i.saturating_sub(low)) as f32 / denom).clamp(0.0, 1.0);
59            let extrapolation = 1.0 - ramp;
60            interp * (1.0 - extrapolation) + extrap * extrapolation
61        })
62        .collect()
63}
64
65/// Rotate one vector in place (RoPE, half-split pairing as in Llama/Qwen).
66pub fn rope_rotate(x: &mut [f32], position: usize, inv_freq: &[f32]) {
67    rope_rotate_scaled(x, position, inv_freq, 1.0);
68}
69
70/// RoPE with an optional post-processing scale on both cos and sin (YaRN).
71thread_local! {
72    /// (sin, cos) per rotary frequency for the position being rotated.
73    static ROPE_TAB: std::cell::RefCell<Vec<(f32, f32)>> =
74        const { std::cell::RefCell::new(Vec::new()) };
75}
76
77/// Fill `tab` with `(position·freq).sin_cos()` per frequency — exactly the
78/// values `rope_rotate_scaled` computes inline.
79fn rope_table(tab: &mut Vec<(f32, f32)>, position: usize, inv_freq: &[f32]) {
80    tab.clear();
81    tab.extend(inv_freq.iter().map(|&freq| (position as f32 * freq).sin_cos()));
82}
83
84/// `rope_table` of an MRoPE row: frequency `i` turns by the position of
85/// its interleaved axis.
86fn mrope_table(tab: &mut Vec<(f32, f32)>, pos: [i64; 3], sections: [usize; 3], inv_freq: &[f32]) {
87    tab.clear();
88    tab.extend(
89        inv_freq
90            .iter()
91            .enumerate()
92            .map(|(i, &freq)| (pos[crate::sensenova::mrope_axis(i, sections)] as f32 * freq).sin_cos()),
93    );
94}
95
96/// `rope_rotate_scaled` with the sin/cos precomputed (bit-identical).
97#[inline]
98fn rope_rotate_table(x: &mut [f32], tab: &[(f32, f32)], scale: f32) {
99    let half = tab.len();
100    for (i, &(sin, cos)) in tab.iter().enumerate() {
101        let x0 = x[i];
102        let x1 = x[i + half];
103        x[i] = (x0 * cos - x1 * sin) * scale;
104        x[i + half] = (x0 * sin + x1 * cos) * scale;
105    }
106}
107
108pub fn rope_rotate_scaled(x: &mut [f32], position: usize, inv_freq: &[f32], scale: f32) {
109    let half = inv_freq.len();
110    for (i, &freq) in inv_freq.iter().enumerate() {
111        let angle = position as f32 * freq;
112        let (sin, cos) = angle.sin_cos();
113        let x0 = x[i];
114        let x1 = x[i + half];
115        x[i] = (x0 * cos - x1 * sin) * scale;
116        x[i + half] = (x0 * sin + x1 * cos) * scale;
117    }
118}
119
120/// Single-head attention: softmax(Q·Kᵀ/√d)·V over a contiguous cache.
121/// `k_cache`/`v_cache`: `[seq_len × head_dim]`.
122/// Returns `([head_dim] output, [seq_len] attention probabilities)` —
123/// the probabilities feed attention-importance accumulation for eviction.
124pub fn attention_head(
125    q: &[f32],
126    k_cache: &[f32],
127    v_cache: &[f32],
128    head_dim: usize,
129    seq_len: usize,
130) -> (Vec<f32>, Vec<f32>) {
131    let scale = 1.0 / (head_dim as f32).sqrt();
132
133    // These two loops are the decode-attention hot path: cost grows
134    // linearly with the stored context, so they are NEON-vectorized
135    // (regrouped summation only — same products).
136    let mut scores = vec![0.0f32; seq_len];
137    for s in 0..seq_len {
138        let k = &k_cache[s * head_dim..(s + 1) * head_dim];
139        scores[s] = dot_f32(q, k) * scale;
140    }
141
142    // Numerically stable softmax.
143    let max_score = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
144    let mut sum = 0.0f32;
145    for s in scores.iter_mut() {
146        *s = (*s - max_score).exp();
147        sum += *s;
148    }
149    if sum > 0.0 {
150        for s in scores.iter_mut() {
151            *s /= sum;
152        }
153    }
154
155    let mut output = vec![0.0f32; head_dim];
156    for s in 0..seq_len {
157        let w = scores[s];
158        if w.abs() < 1e-12 {
159            continue;
160        }
161        let v = &v_cache[s * head_dim..(s + 1) * head_dim];
162        axpy_f32(&mut output, v, w);
163    }
164    (output, scores)
165}
166
167/// f32 dot with 4 independent accumulators — NEON on aarch64, scalar
168/// elsewhere. Same products as the sequential loop, regrouped sums.
169#[inline]
170pub(crate) fn dot_f32(a: &[f32], b: &[f32]) -> f32 {
171    #[cfg(target_arch = "aarch64")]
172    unsafe {
173        return dot_f32_neon(a, b);
174    }
175    #[cfg(target_arch = "x86_64")]
176    if crate::qtensor::avx2_enabled() {
177        return unsafe { dot_f32_avx2(a, b) };
178    }
179    #[allow(unreachable_code)]
180    {
181        a.iter().zip(b).map(|(x, y)| x * y).sum()
182    }
183}
184
185/// f32 dot via AVX2/FMA (x86 mirror of `dot_f32_neon`; regrouped sums).
186#[cfg(target_arch = "x86_64")]
187#[target_feature(enable = "avx2,fma")]
188unsafe fn dot_f32_avx2(a: &[f32], b: &[f32]) -> f32 {
189    // SAFETY: callers pass equal-length slices.
190    unsafe {
191        use core::arch::x86_64::*;
192        let n = a.len().min(b.len());
193        let (ap, bp) = (a.as_ptr(), b.as_ptr());
194        let (mut s0, mut s1) = (_mm256_setzero_ps(), _mm256_setzero_ps());
195        let mut j = 0usize;
196        while j + 16 <= n {
197            s0 = _mm256_fmadd_ps(_mm256_loadu_ps(ap.add(j)), _mm256_loadu_ps(bp.add(j)), s0);
198            s1 = _mm256_fmadd_ps(
199                _mm256_loadu_ps(ap.add(j + 8)),
200                _mm256_loadu_ps(bp.add(j + 8)),
201                s1,
202            );
203            j += 16;
204        }
205        let acc = _mm256_add_ps(s0, s1);
206        let hi = _mm256_extractf128_ps::<1>(acc);
207        let q = _mm_add_ps(_mm256_castps256_ps128(acc), hi);
208        let d = _mm_add_ps(q, _mm_movehl_ps(q, q));
209        let s = _mm_add_ss(d, _mm_shuffle_ps::<1>(d, d));
210        let mut sum = _mm_cvtss_f32(s);
211        while j < n {
212            sum += *ap.add(j) * *bp.add(j);
213            j += 1;
214        }
215        sum
216    }
217}
218
219#[cfg(target_arch = "aarch64")]
220#[target_feature(enable = "neon")]
221unsafe fn dot_f32_neon(a: &[f32], b: &[f32]) -> f32 {
222    // SAFETY: callers pass equal-length slices (head_dim rows).
223    unsafe {
224        use core::arch::aarch64::*;
225        let n = a.len().min(b.len());
226        let (ap, bp) = (a.as_ptr(), b.as_ptr());
227        let (mut a0, mut a1, mut a2, mut a3) = (
228            vdupq_n_f32(0.0),
229            vdupq_n_f32(0.0),
230            vdupq_n_f32(0.0),
231            vdupq_n_f32(0.0),
232        );
233        let mut j = 0usize;
234        while j + 16 <= n {
235            a0 = vfmaq_f32(a0, vld1q_f32(ap.add(j)), vld1q_f32(bp.add(j)));
236            a1 = vfmaq_f32(a1, vld1q_f32(ap.add(j + 4)), vld1q_f32(bp.add(j + 4)));
237            a2 = vfmaq_f32(a2, vld1q_f32(ap.add(j + 8)), vld1q_f32(bp.add(j + 8)));
238            a3 = vfmaq_f32(a3, vld1q_f32(ap.add(j + 12)), vld1q_f32(bp.add(j + 12)));
239            j += 16;
240        }
241        let mut sum = vaddvq_f32(vaddq_f32(vaddq_f32(a0, a1), vaddq_f32(a2, a3)));
242        while j < n {
243            sum += *ap.add(j) * *bp.add(j);
244            j += 1;
245        }
246        sum
247    }
248}
249
250/// exp(x) for one NEON vector — Cephes-style degree-6 polynomial,
251/// |rel err| < 2e-7 on the softmax range. The batched-attend softmax
252/// calls exp hundreds of millions of times per long prefill; libm's
253/// scalar expf there would eat the whole GEMM win.
254#[cfg(target_arch = "aarch64")]
255#[inline]
256pub(crate) unsafe fn vexpq_f32(x: core::arch::aarch64::float32x4_t) -> core::arch::aarch64::float32x4_t {
257    // SAFETY: pure register math.
258    unsafe {
259        use core::arch::aarch64::*;
260        let x = vmaxq_f32(x, vdupq_n_f32(-87.0));
261        let x = vminq_f32(x, vdupq_n_f32(88.0));
262        let n = vrndnq_f32(vmulq_f32(x, vdupq_n_f32(std::f32::consts::LOG2_E)));
263        // r = x − n·ln2, split hi/lo for accuracy (Cephes).
264        let r = vfmsq_f32(x, n, vdupq_n_f32(0.693_359_4));
265        let r = vfmsq_f32(r, n, vdupq_n_f32(-2.121_944_4e-4));
266        let mut p = vdupq_n_f32(1.987_569_1e-4);
267        p = vfmaq_f32(vdupq_n_f32(1.398_2e-3), p, r);
268        p = vfmaq_f32(vdupq_n_f32(8.333_452e-3), p, r);
269        p = vfmaq_f32(vdupq_n_f32(4.166_579_6e-2), p, r);
270        p = vfmaq_f32(vdupq_n_f32(1.666_666_5e-1), p, r);
271        p = vfmaq_f32(vdupq_n_f32(5.000_000_3e-1), p, r);
272        let r2 = vmulq_f32(r, r);
273        let e = vaddq_f32(vaddq_f32(vdupq_n_f32(1.0), r), vmulq_f32(p, r2));
274        let pow2 = vreinterpretq_f32_s32(vshlq_n_s32::<23>(vaddq_s32(
275            vcvtq_s32_f32(n),
276            vdupq_n_s32(127),
277        )));
278        vmulq_f32(e, pow2)
279    }
280}
281
282/// Numerically stable in-place softmax of one score row — vectorized
283/// max / exp / sum on aarch64 (scalar exp only on the tail).
284#[cfg(target_arch = "aarch64")]
285pub(crate) fn softmax_row(row: &mut [f32]) {
286    // SAFETY: slice reads/writes within bounds.
287    unsafe {
288        use core::arch::aarch64::*;
289        let nn = row.len();
290        let p = row.as_mut_ptr();
291        let mut j = 0usize;
292        let mut mv = vdupq_n_f32(f32::NEG_INFINITY);
293        while j + 4 <= nn {
294            mv = vmaxq_f32(mv, vld1q_f32(p.add(j)));
295            j += 4;
296        }
297        let mut maxs = vmaxvq_f32(mv);
298        while j < nn {
299            maxs = maxs.max(*p.add(j));
300            j += 1;
301        }
302        if maxs == f32::NEG_INFINITY {
303            return;
304        }
305        let mvv = vdupq_n_f32(maxs);
306        let mut sumv = vdupq_n_f32(0.0);
307        j = 0;
308        while j + 4 <= nn {
309            let e = vexpq_f32(vsubq_f32(vld1q_f32(p.add(j)), mvv));
310            vst1q_f32(p.add(j), e);
311            sumv = vaddq_f32(sumv, e);
312            j += 4;
313        }
314        let mut sum = vaddvq_f32(sumv);
315        while j < nn {
316            let e = (*p.add(j) - maxs).exp();
317            *p.add(j) = e;
318            sum += e;
319            j += 1;
320        }
321        if sum > 0.0 {
322            let inv = vdupq_n_f32(1.0 / sum);
323            j = 0;
324            while j + 4 <= nn {
325                vst1q_f32(p.add(j), vmulq_f32(vld1q_f32(p.add(j)), inv));
326                j += 4;
327            }
328            while j < nn {
329                *p.add(j) *= 1.0 / sum;
330                j += 1;
331            }
332        }
333    }
334}
335
336/// Numerically stable in-place softmax of one score row on x86-64:
337/// AVX2 max / exp / sum (the NEON twin's Cephes polynomial), scalar on a
338/// CPU without AVX2/FMA. The batched chunk attend's softmax.
339#[cfg(target_arch = "x86_64")]
340pub(crate) fn softmax_row(row: &mut [f32]) {
341    if std::arch::is_x86_feature_detected!("avx2") && std::arch::is_x86_feature_detected!("fma") {
342        // SAFETY: both features were just detected on this CPU.
343        return unsafe { softmax_row_avx2(row) };
344    }
345    let maxs = row.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
346    if maxs == f32::NEG_INFINITY {
347        return;
348    }
349    let mut sum = 0f32;
350    for v in row.iter_mut() {
351        *v = (*v - maxs).exp();
352        sum += *v;
353    }
354    if sum > 0.0 {
355        let inv = 1.0 / sum;
356        for v in row.iter_mut() {
357            *v *= inv;
358        }
359    }
360}
361
362/// exp(x) for one AVX2 vector — the Cephes degree-6 polynomial of
363/// `vexpq_f32`, |rel err| < 2e-7 on the softmax range.
364///
365/// # Safety
366/// The caller has checked `avx2` and `fma`.
367#[cfg(target_arch = "x86_64")]
368#[target_feature(enable = "avx2,fma")]
369#[inline]
370unsafe fn exp_avx2(x: core::arch::x86_64::__m256) -> core::arch::x86_64::__m256 {
371    use core::arch::x86_64::*;
372    let x = _mm256_max_ps(x, _mm256_set1_ps(-87.0));
373    let x = _mm256_min_ps(x, _mm256_set1_ps(88.0));
374    let n = _mm256_round_ps::<{ _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC }>(_mm256_mul_ps(
375        x,
376        _mm256_set1_ps(std::f32::consts::LOG2_E),
377    ));
378    // r = x − n·ln2, split hi/lo for accuracy (Cephes).
379    let r = _mm256_fnmadd_ps(n, _mm256_set1_ps(0.693_359_4), x);
380    let r = _mm256_fnmadd_ps(n, _mm256_set1_ps(-2.121_944_4e-4), r);
381    let mut p = _mm256_set1_ps(1.987_569_1e-4);
382    p = _mm256_fmadd_ps(p, r, _mm256_set1_ps(1.398_2e-3));
383    p = _mm256_fmadd_ps(p, r, _mm256_set1_ps(8.333_452e-3));
384    p = _mm256_fmadd_ps(p, r, _mm256_set1_ps(4.166_579_6e-2));
385    p = _mm256_fmadd_ps(p, r, _mm256_set1_ps(1.666_666_5e-1));
386    p = _mm256_fmadd_ps(p, r, _mm256_set1_ps(5.000_000_3e-1));
387    let r2 = _mm256_mul_ps(r, r);
388    let e = _mm256_fmadd_ps(p, r2, _mm256_add_ps(_mm256_set1_ps(1.0), r));
389    let pow2 = _mm256_castsi256_ps(_mm256_slli_epi32::<23>(_mm256_add_epi32(
390        _mm256_cvtps_epi32(n),
391        _mm256_set1_epi32(127),
392    )));
393    _mm256_mul_ps(e, pow2)
394}
395
396/// The AVX2 body of the x86 `softmax_row`.
397///
398/// # Safety
399/// The caller has checked `avx2` and `fma`.
400#[cfg(target_arch = "x86_64")]
401#[target_feature(enable = "avx2,fma")]
402unsafe fn softmax_row_avx2(row: &mut [f32]) {
403    use core::arch::x86_64::*;
404    // SAFETY: every access is within row[..nn].
405    unsafe {
406        let nn = row.len();
407        let p = row.as_mut_ptr();
408        let mut j = 0usize;
409        let mut mv = _mm256_set1_ps(f32::NEG_INFINITY);
410        while j + 8 <= nn {
411            mv = _mm256_max_ps(mv, _mm256_loadu_ps(p.add(j)));
412            j += 8;
413        }
414        let mut lanes = [0f32; 8];
415        _mm256_storeu_ps(lanes.as_mut_ptr(), mv);
416        let mut maxs = lanes.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
417        while j < nn {
418            maxs = maxs.max(*p.add(j));
419            j += 1;
420        }
421        if maxs == f32::NEG_INFINITY {
422            return;
423        }
424        let mvv = _mm256_set1_ps(maxs);
425        let mut sumv = _mm256_setzero_ps();
426        j = 0;
427        while j + 8 <= nn {
428            let e = exp_avx2(_mm256_sub_ps(_mm256_loadu_ps(p.add(j)), mvv));
429            _mm256_storeu_ps(p.add(j), e);
430            sumv = _mm256_add_ps(sumv, e);
431            j += 8;
432        }
433        _mm256_storeu_ps(lanes.as_mut_ptr(), sumv);
434        let mut sum: f32 = lanes.iter().sum();
435        while j < nn {
436            let e = (*p.add(j) - maxs).exp();
437            *p.add(j) = e;
438            sum += e;
439            j += 1;
440        }
441        if sum > 0.0 {
442            let inv = _mm256_set1_ps(1.0 / sum);
443            j = 0;
444            while j + 8 <= nn {
445                _mm256_storeu_ps(p.add(j), _mm256_mul_ps(_mm256_loadu_ps(p.add(j)), inv));
446                j += 8;
447            }
448            while j < nn {
449                *p.add(j) *= 1.0 / sum;
450                j += 1;
451            }
452        }
453    }
454}
455
456/// `acc += w · row` (f32 axpy) — NEON on aarch64, scalar elsewhere.
457#[inline]
458pub(crate) fn axpy_f32(acc: &mut [f32], row: &[f32], w: f32) {
459    #[cfg(target_arch = "aarch64")]
460    unsafe {
461        return axpy_f32_neon(acc, row, w);
462    }
463    #[cfg(target_arch = "x86_64")]
464    if crate::qtensor::avx2_enabled() {
465        return unsafe { axpy_f32_avx2(acc, row, w) };
466    }
467    #[allow(unreachable_code)]
468    {
469        for (a, &r) in acc.iter_mut().zip(row) {
470            *a += w * r;
471        }
472    }
473}
474
475/// f32 axpy via AVX2/FMA (x86 mirror of `axpy_f32_neon`).
476#[cfg(target_arch = "x86_64")]
477#[target_feature(enable = "avx2,fma")]
478unsafe fn axpy_f32_avx2(acc: &mut [f32], row: &[f32], w: f32) {
479    // SAFETY: callers pass equal-length slices (head_dim rows).
480    unsafe {
481        use core::arch::x86_64::*;
482        let n = acc.len().min(row.len());
483        let ap = acc.as_mut_ptr();
484        let rp = row.as_ptr();
485        let wv = _mm256_set1_ps(w);
486        let mut j = 0usize;
487        while j + 8 <= n {
488            let v = _mm256_fmadd_ps(wv, _mm256_loadu_ps(rp.add(j)), _mm256_loadu_ps(ap.add(j)));
489            _mm256_storeu_ps(ap.add(j), v);
490            j += 8;
491        }
492        while j < n {
493            *ap.add(j) += w * *rp.add(j);
494            j += 1;
495        }
496    }
497}
498
499#[cfg(target_arch = "aarch64")]
500#[target_feature(enable = "neon")]
501unsafe fn axpy_f32_neon(acc: &mut [f32], row: &[f32], w: f32) {
502    // SAFETY: callers pass equal-length slices (head_dim rows).
503    unsafe {
504        use core::arch::aarch64::*;
505        let n = acc.len().min(row.len());
506        let ap = acc.as_mut_ptr();
507        let rp = row.as_ptr();
508        let wv = vdupq_n_f32(w);
509        let mut j = 0usize;
510        while j + 4 <= n {
511            let v = vfmaq_f32(vld1q_f32(ap.add(j)), wv, vld1q_f32(rp.add(j)));
512            vst1q_f32(ap.add(j), v);
513            j += 4;
514        }
515        while j < n {
516            *ap.add(j) += w * *rp.add(j);
517            j += 1;
518        }
519    }
520}
521
522/// Multi-head GQA attention for one position.
523///
524/// - `active_heads[h]` — Q-head mask; a KV group whose Q heads are ALL
525///   dead is neither projected nor cached (GQA-skip: no FLOPs, no memory).
526/// - KV cache is head-major: per-head reads are contiguous slices,
527///   no per-head gather copies.
528///
529/// Weights: `wq [num_heads·head_dim, hidden]`, `wk/wv [num_kv·head_dim, hidden]`,
530/// `wo [hidden, num_heads·head_dim]`. Returns `[hidden_size]`.
531#[allow(clippy::too_many_arguments)]
532pub fn multi_head_attention(
533    hidden: &[f32],
534    wq: &[f32],
535    wk: &[f32],
536    wv: &[f32],
537    wo: &[f32],
538    cache: &mut LayerKvCache,
539    num_heads: usize,
540    num_kv_heads: usize,
541    head_dim: usize,
542    hidden_size: usize,
543    position: usize,
544    active_heads: &[bool],
545    inv_freq: &[f32],
546) -> Vec<f32> {
547    let heads_per_kv = num_heads / num_kv_heads;
548    let head_alive = |h: usize| -> bool { active_heads.get(h).copied().unwrap_or(true) };
549    // A KV group lives while at least one of its Q heads lives.
550    let group_alive: Vec<bool> = (0..num_kv_heads)
551        .map(|g| (0..heads_per_kv).any(|i| head_alive(g * heads_per_kv + i)))
552        .collect();
553
554    // ── Q projection (live heads only) ──
555    let mut q_all = vec![0.0f32; num_heads * head_dim];
556    for h in 0..num_heads {
557        if !head_alive(h) {
558            continue;
559        }
560        for d in 0..head_dim {
561            let row = (h * head_dim + d) * hidden_size;
562            let mut sum = 0.0f32;
563            for j in 0..hidden_size {
564                sum += wq[row + j] * hidden[j];
565            }
566            q_all[h * head_dim + d] = sum;
567        }
568        rope_rotate(
569            &mut q_all[h * head_dim..(h + 1) * head_dim],
570            position,
571            inv_freq,
572        );
573    }
574
575    // ── K/V projection (live groups only) ──
576    let mut k_new = vec![0.0f32; num_kv_heads * head_dim];
577    let mut v_new = vec![0.0f32; num_kv_heads * head_dim];
578    for g in 0..num_kv_heads {
579        if !group_alive[g] {
580            continue;
581        }
582        for d in 0..head_dim {
583            let row = (g * head_dim + d) * hidden_size;
584            let (mut ks, mut vs) = (0.0f32, 0.0f32);
585            for j in 0..hidden_size {
586                ks += wk[row + j] * hidden[j];
587                vs += wv[row + j] * hidden[j];
588            }
589            k_new[g * head_dim + d] = ks;
590            v_new[g * head_dim + d] = vs;
591        }
592        rope_rotate(
593            &mut k_new[g * head_dim..(g + 1) * head_dim],
594            position,
595            inv_freq,
596        );
597    }
598
599    cache.append(&k_new, &v_new, &group_alive);
600
601    // ── Per-head attention over contiguous head-major slices ──
602    let mut attn_out = vec![0.0f32; num_heads * head_dim];
603    let mut imp = vec![0.0f32; cache.seq_len];
604    for h in 0..num_heads {
605        if !head_alive(h) {
606            continue; // dead head contributes zeros
607        }
608        let g = h / heads_per_kv;
609        let stored = cache.head_len(g);
610        if stored == 0 {
611            continue;
612        }
613        let _ = stored;
614        let (out, probs) = cache.attend(&q_all[h * head_dim..(h + 1) * head_dim], g);
615        attn_out[h * head_dim..(h + 1) * head_dim].copy_from_slice(&out);
616        for (dst, &p) in imp.iter_mut().zip(&probs) {
617            *dst += p;
618        }
619    }
620    // A position's importance is the probability mass that reads it —
621    // accumulated for importance-aware eviction.
622    cache.accumulate_imp(&imp);
623
624    // ── Output projection ──
625    let mut output = vec![0.0f32; hidden_size];
626    for i in 0..hidden_size {
627        let mut sum = 0.0f32;
628        let row = i * num_heads * head_dim;
629        for j in 0..(num_heads * head_dim) {
630            sum += wo[row + j] * attn_out[j];
631        }
632        output[i] = sum;
633    }
634    output
635}
636
637/// Fused two-position GQA attention: Q/K/V/O weight rows are streamed
638/// from memory once for both positions; the attention itself runs
639/// sequentially (position p first — its K/V must be in the cache before
640/// position p+1 attends). Dense-only (no head mask): the speculative
641/// path uses it for draft verification. Bit-identical to two calls of
642/// `multi_head_attention`.
643#[allow(clippy::too_many_arguments)]
644pub fn multi_head_attention_pair(
645    hidden1: &[f32],
646    hidden2: &[f32],
647    wq: &[f32],
648    wk: &[f32],
649    wv: &[f32],
650    wo: &[f32],
651    cache: &mut LayerKvCache,
652    num_heads: usize,
653    num_kv_heads: usize,
654    head_dim: usize,
655    hidden_size: usize,
656    position: usize,
657    inv_freq: &[f32],
658) -> (Vec<f32>, Vec<f32>) {
659    let heads_per_kv = num_heads / num_kv_heads;
660
661    // ── Fused projections: each weight row read once, two dots ──
662    let qk_dim = num_heads * head_dim;
663    let kv_dim = num_kv_heads * head_dim;
664    let mut q1 = vec![0.0f32; qk_dim];
665    let mut q2 = vec![0.0f32; qk_dim];
666    let mut k1 = vec![0.0f32; kv_dim];
667    let mut k2 = vec![0.0f32; kv_dim];
668    let mut v1 = vec![0.0f32; kv_dim];
669    let mut v2 = vec![0.0f32; kv_dim];
670    let proj2 = |w: &[f32], o1: &mut [f32], o2: &mut [f32]| {
671        for (o, (d1, d2)) in o1.iter_mut().zip(o2.iter_mut()).enumerate() {
672            let row = &w[o * hidden_size..(o + 1) * hidden_size];
673            let (mut s1, mut s2) = (0.0f32, 0.0f32);
674            for j in 0..hidden_size {
675                s1 += row[j] * hidden1[j];
676                s2 += row[j] * hidden2[j];
677            }
678            *d1 = s1;
679            *d2 = s2;
680        }
681    };
682    proj2(wq, &mut q1, &mut q2);
683    proj2(wk, &mut k1, &mut k2);
684    proj2(wv, &mut v1, &mut v2);
685
686    for h in 0..num_heads {
687        rope_rotate(
688            &mut q1[h * head_dim..(h + 1) * head_dim],
689            position,
690            inv_freq,
691        );
692        rope_rotate(
693            &mut q2[h * head_dim..(h + 1) * head_dim],
694            position + 1,
695            inv_freq,
696        );
697    }
698    for g in 0..num_kv_heads {
699        rope_rotate(
700            &mut k1[g * head_dim..(g + 1) * head_dim],
701            position,
702            inv_freq,
703        );
704        rope_rotate(
705            &mut k2[g * head_dim..(g + 1) * head_dim],
706            position + 1,
707            inv_freq,
708        );
709    }
710
711    // ── Sequential attention: p, then p+1 (causal dependency) ──
712    let alive = vec![true; num_kv_heads];
713    let attend = |q_all: &[f32], cache: &LayerKvCache| -> Vec<f32> {
714        let mut attn_out = vec![0.0f32; qk_dim];
715        let mut imp = vec![0.0f32; cache.seq_len];
716        for h in 0..num_heads {
717            let g = h / heads_per_kv;
718            let stored = cache.head_len(g);
719            if stored == 0 {
720                continue;
721            }
722            let _ = stored;
723            let (out, probs) = cache.attend(&q_all[h * head_dim..(h + 1) * head_dim], g);
724            attn_out[h * head_dim..(h + 1) * head_dim].copy_from_slice(&out);
725            for (dst, &p) in imp.iter_mut().zip(&probs) {
726                *dst += p;
727            }
728        }
729        attn_out.extend_from_slice(&imp); // carry imp back to the caller
730        attn_out
731    };
732
733    cache.append(&k1, &v1, &alive);
734    let mut a1 = attend(&q1, cache);
735    let imp1 = a1.split_off(qk_dim);
736    cache.accumulate_imp(&imp1);
737
738    cache.append(&k2, &v2, &alive);
739    let mut a2 = attend(&q2, cache);
740    let imp2 = a2.split_off(qk_dim);
741    cache.accumulate_imp(&imp2);
742
743    // ── Fused output projection ──
744    let mut out1 = vec![0.0f32; hidden_size];
745    let mut out2 = vec![0.0f32; hidden_size];
746    for i in 0..hidden_size {
747        let row = &wo[i * qk_dim..(i + 1) * qk_dim];
748        let (mut s1, mut s2) = (0.0f32, 0.0f32);
749        for j in 0..qk_dim {
750            s1 += row[j] * a1[j];
751            s2 += row[j] * a2[j];
752        }
753        out1[i] = s1;
754        out2[i] = s2;
755    }
756    (out1, out2)
757}
758
759/// Per-head RMS norm with weight (qk-norm). Follows the model's norm
760/// style: Qwen3.5/Qwen3-Next are zero-centered `x̂·(1+w)` (gemma-style),
761/// classic Qwen/Llama are `x̂·w` — same authority as the layer norms.
762#[inline]
763pub(crate) fn rmsnorm_head(x: &mut [f32], w: &[f32], eps: f64, style: cortiq_core::NormStyle) {
764    let mut ss = 0f64;
765    for &v in x.iter() {
766        ss += (v as f64) * (v as f64);
767    }
768    let inv = (1.0 / (ss / x.len() as f64 + eps).sqrt()) as f32;
769    match style {
770        cortiq_core::NormStyle::Qwen => {
771            for (v, &wi) in x.iter_mut().zip(w) {
772                *v = *v * inv * wi;
773            }
774        }
775        cortiq_core::NormStyle::Gemma => {
776            for (v, &wi) in x.iter_mut().zip(w) {
777                *v = *v * inv * (1.0 + wi);
778            }
779        }
780    }
781}
782
783/// Interleaved-MRoPE positions of a prompt's rows (SenseNova-Loop image
784/// prompts): row `position - base` rotates frequency `i` by its
785/// `sensenova::mrope_axis` position instead of the plain one.
786#[derive(Clone, Copy)]
787pub struct MropeView<'a> {
788    pub base: usize,
789    pub pos: &'a [[i64; 3]],
790    pub sections: [usize; 3],
791}
792
793/// Dense attention configuration (no head masks — masked execution uses
794/// the historical path).
795#[derive(Clone, Copy)]
796pub struct QwenAttnCfg<'a> {
797    /// MRoPE rows of the prompt being prefilled (None: plain RoPE).
798    pub mrope: Option<MropeView<'a>>,
799    pub num_heads: usize,
800    pub num_kv_heads: usize,
801    pub head_dim: usize,
802    pub hidden_size: usize,
803    pub position: usize,
804    /// len = rotary_dim / 2
805    pub inv_freq: &'a [f32],
806    /// ≤ head_dim; RoPE rotates only the first `rotary_dim` dims.
807    pub rotary_dim: usize,
808    pub q_norm: Option<&'a [f32]>,
809    pub k_norm: Option<&'a [f32]>,
810    /// Qwen3.5: wq rows = 2·nh·hd, per-head [q(hd); gate(hd)];
811    /// attention output is multiplied by sigmoid(gate) before o_proj.
812    pub output_gate: bool,
813    /// Laguna: separate projection followed by softplus. Bool = per-head
814    /// projection (broadcast across head_dim), false = per-element.
815    pub softplus_gate: Option<(&'a QTensor, bool)>,
816    /// Multiplier applied to both RoPE cos and sin (YaRN attention factor).
817    pub rope_scale: f32,
818    pub rms_eps: f64,
819    /// Attention score scale (1/√head_dim unless the arch overrides).
820    pub scale: f32,
821    /// Gemma-2 attention-logit soft-capping: scores pass tanh(s/c)·c
822    /// before the softmax. 0.0 = off.
823    pub softcap: f32,
824    /// Sliding-window width: attend only the last N positions (Gemma-3
825    /// local layers). None = full context.
826    pub window: Option<usize>,
827    /// Scale-less RMS normalization of each V head before it enters
828    /// the cache (Gemma-4).
829    pub v_norm: bool,
830    /// HunYuan dense: the per-head q/k RMSNorm runs AFTER RoPE
831    /// (`ModelArch::qk_norm_after_rope`). False = norm, then rotate.
832    pub qk_norm_after_rope: bool,
833    /// `softplus_gate` applies sigmoid instead of softplus (Spark-X2.5's
834    /// head-wise output gate; Laguna's is softplus).
835    pub gate_sigmoid: bool,
836    /// Norm-weight semantics for qk-norm (same as the layer norms).
837    pub norm_style: cortiq_core::NormStyle,
838    /// Qwen2-family q/k/v projection biases (added after the matvecs).
839    pub bias: Option<(&'a [f32], &'a [f32], &'a [f32])>,
840    pub pool: Option<&'a Pool>,
841    /// Width of each V head, ≤ `head_dim` (MiMo-V2: 128 against 192-wide
842    /// Q/K heads; every other family: `head_dim`). V projects to
843    /// `num_kv_heads·v_head_dim`, is zero-padded to `head_dim` per head
844    /// inside the KV cache (the pad rows carry no value, so the attend's
845    /// pad dims come out exactly 0), and the attention output is
846    /// compacted back to `num_heads·v_head_dim` before o_proj.
847    pub v_head_dim: usize,
848    /// The rows V projects, when they are not the layer's normed input (Ripple's value
849    /// residual: `lerp(embedding, normed, blend)`), laid out as that input is: one position's
850    /// row, a pair's two, a chunk's `b`. None = V reads what Q and K read.
851    pub value_in: Option<&'a [f32]>,
852}
853
854/// `[n × vd]` heads → `[n × hd]`, each head zero-padded at its tail (a V
855/// row narrower than the cache's head width). A no-copy move when vd == hd.
856pub(crate) fn pad_heads(src: Vec<f32>, n: usize, vd: usize, hd: usize) -> Vec<f32> {
857    if vd == hd {
858        return src;
859    }
860    assert!(
861        vd < hd && src.len() == n * vd,
862        "pad_heads: {} values for {n} heads of {vd} (cache width {hd})",
863        src.len()
864    );
865    let mut out = take_buf(n * hd);
866    for h in 0..n {
867        out[h * hd..h * hd + vd].copy_from_slice(&src[h * vd..(h + 1) * vd]);
868    }
869    let mut src = src;
870    recycle_buf(&mut src);
871    out
872}
873
874/// `[rows × n × hd]` → `[rows × n × vd]`: drop each head's pad tail (the
875/// inverse of `pad_heads` on the attention output, before o_proj).
876pub(crate) fn compact_heads(src: Vec<f32>, n: usize, hd: usize, vd: usize) -> Vec<f32> {
877    if vd == hd {
878        return src;
879    }
880    let rows = src.len() / (n * hd);
881    assert!(
882        vd < hd && src.len() == rows * n * hd,
883        "compact_heads: {} values for {n} heads of {hd}",
884        src.len()
885    );
886    let mut out = take_buf(rows * n * vd);
887    for r in 0..rows * n {
888        out[r * vd..(r + 1) * vd].copy_from_slice(&src[r * hd..r * hd + vd]);
889    }
890    let mut src = src;
891    recycle_buf(&mut src);
892    out
893}
894
895/// V narrower than the head width is compacted out of the attention
896/// output before o_proj, which leaves no defined width for an output gate
897/// (Qwen3.5 / Laguna gates are head_dim wide). The loader refuses the
898/// combination; this keeps a hand-built cfg from running it silently.
899#[inline]
900fn check_v_width(cfg: &QwenAttnCfg) {
901    assert!(
902        cfg.v_head_dim > 0 && cfg.v_head_dim <= cfg.head_dim,
903        "v_head_dim {} must be in 1..={}",
904        cfg.v_head_dim,
905        cfg.head_dim
906    );
907    assert!(
908        cfg.v_head_dim == cfg.head_dim || (!cfg.output_gate && cfg.softplus_gate.is_none()),
909        "an attention output gate needs V heads as wide as Q/K heads"
910    );
911}
912
913/// A layer's sinks are one logit per Q head; anything else is a loader
914/// bug that would otherwise attend with some other head's sink.
915#[inline]
916fn check_sinks(cache: &LayerKvCache, nh: usize) {
917    if let Some(s) = cache.sinks.as_deref() {
918        assert_eq!(
919            s.len(),
920            nh,
921            "layer sinks: {} logits for {nh} Q heads",
922            s.len()
923        );
924    }
925}
926
927/// The learned sink logits of the Q heads `[h0, h1)` of `cache`'s layer
928/// (empty when the layer has none).
929#[inline]
930fn sink_slice(cache: &LayerKvCache, h0: usize, h1: usize) -> &[f32] {
931    match cache.sinks.as_deref() {
932        Some(s) => &s[h0..h1],
933        None => &[],
934    }
935}
936
937thread_local! {
938    /// Recycled projection/attention buffers: the dense attention path
939    /// consumed ~7 fresh Vecs per layer per token (roadmap §3 P0).
940    static PROJ_FREE: std::cell::RefCell<Vec<Vec<f32>>> =
941        const { std::cell::RefCell::new(Vec::new()) };
942}
943
944/// Take a zeroed buffer of length `n` from the freelist (or allocate).
945pub(crate) fn take_buf(n: usize) -> Vec<f32> {
946    let mut b = PROJ_FREE.with(|f| f.borrow_mut().pop()).unwrap_or_default();
947    b.clear();
948    b.resize(n, 0.0);
949    b
950}
951
952/// Return a buffer to the freelist (leaves an empty Vec behind).
953pub(crate) fn recycle_buf(b: &mut Vec<f32>) {
954    let b = std::mem::take(b);
955    if b.capacity() > 0 {
956        PROJ_FREE.with(|f| {
957            let mut f = f.borrow_mut();
958            if f.len() < 16 {
959                f.push(b);
960            }
961        });
962    }
963}
964
965struct Projected {
966    q: Vec<f32>,
967    gate: Vec<f32>,
968    k: Vec<f32>,
969    v: Vec<f32>,
970}
971
972impl Drop for Projected {
973    fn drop(&mut self) {
974        recycle_buf(&mut self.q);
975        recycle_buf(&mut self.gate);
976        recycle_buf(&mut self.k);
977        recycle_buf(&mut self.v);
978    }
979}
980
981/// Project + split gate + qk-norm + partial RoPE for one position.
982fn project_position(
983    hidden: &[f32],
984    wq: &QTensor,
985    wk: &QTensor,
986    wv: &QTensor,
987    cfg: &QwenAttnCfg,
988    position: usize,
989) -> Projected {
990    let (q_raw, k, v) = project_matvecs(hidden, wq, wk, wv, cfg);
991    finish_projection(q_raw, k, v, cfg, position)
992}
993
994/// The Q/K/V matvecs of one position (GPU batch or fused CPU dispatch).
995fn project_matvecs(
996    hidden: &[f32],
997    wq: &QTensor,
998    wk: &QTensor,
999    wv: &QTensor,
1000    cfg: &QwenAttnCfg,
1001) -> (Vec<f32>, Vec<f32>, Vec<f32>) {
1002    let (_, nkv, hd) = (cfg.num_heads, cfg.num_kv_heads, cfg.head_dim);
1003    let mut q_raw = take_buf(wq.rows());
1004    let mut k = take_buf(nkv * hd);
1005    // V heads may be narrower than Q/K (MiMo-V2); padded before the cache.
1006    let mut v = take_buf(nkv * cfg.v_head_dim);
1007    if let Some(vin) = cfg.value_in {
1008        // V has a row of its own: Q and K as one job, V as another.
1009        QTensor::matvec_many(
1010            [wq, wk],
1011            hidden,
1012            [q_raw.as_mut_slice(), k.as_mut_slice()],
1013            cfg.pool,
1014        );
1015        wv.matvec(&vin[..hidden.len()], &mut v, cfg.pool);
1016        return (q_raw, k, v);
1017    }
1018    // QKV in ONE device submission (этап 4): three matvecs, one poll —
1019    // gated by the same discrete-card threshold as every GPU op. Any
1020    // refusal (budget/dtype/shard) falls through to the CPU path.
1021    // Runtime probe (Batch class): the batch either amortizes its
1022    // submit+poll on this driver stack or the fused CPU dispatch wins.
1023    let mut done = false;
1024    // Prism matrices need one descriptor-aware FWHT per projection, while the
1025    // fused batch job has no transform metadata.  Bypassing that unsupported
1026    // probe is deliberate: matvec_many sees the Prism contract and routes
1027    // each matrix through the correct per-op GPU kernel instead of putting the
1028    // whole Q/K/V set in cpu_scope after a structural batch decline.
1029    let prism_projections =
1030        wq.has_prism_contract() || wk.has_prism_contract() || wv.has_prism_contract();
1031    if !prism_projections
1032        && crate::gpu::enabled_here()
1033        && (wq.rows() >= crate::gpu::min_rows() || wq.is_q1()) {
1034        let arm = if wq.is_q1() && crate::gpu::q1_force() {
1035            crate::gpu::ProbeArm::Gpu
1036        } else {
1037            crate::gpu::probe_arm(crate::gpu::OpClass::Batch)
1038        };
1039        match arm {
1040            crate::gpu::ProbeArm::Gpu => {
1041                if let (Some((m, jq)), Some((_, jk)), Some((_, jv))) = (
1042                    crate::qtensor::gpu_batch_job(wq, hidden),
1043                    crate::qtensor::gpu_batch_job(wk, hidden),
1044                    crate::qtensor::gpu_batch_job(wv, hidden),
1045                ) {
1046                    let t0 = std::time::Instant::now();
1047                    done = crate::gpu::matvec_batch(
1048                        &m,
1049                        &[jq, jk, jv],
1050                        &mut [q_raw.as_mut_slice(), k.as_mut_slice(), v.as_mut_slice()],
1051                    );
1052                    if done {
1053                        crate::gpu::probe_record(crate::gpu::OpClass::Batch, true, t0.elapsed());
1054                    } else {
1055                        crate::gpu::probe_note_decline(crate::gpu::OpClass::Batch);
1056                    }
1057                } else {
1058                    // No batch job could be built for these weights —
1059                    // structural, and silence would leave the class
1060                    // alternating for the life of the process.
1061                    crate::gpu::probe_note_decline(crate::gpu::OpClass::Batch);
1062                }
1063            }
1064            crate::gpu::ProbeArm::CpuTimed => {
1065                let t0 = std::time::Instant::now();
1066                crate::gpu::cpu_scope(|| {
1067                    QTensor::matvec_many(
1068                        [wq, wk, wv],
1069                        hidden,
1070                        [q_raw.as_mut_slice(), k.as_mut_slice(), v.as_mut_slice()],
1071                        cfg.pool,
1072                    )
1073                });
1074                crate::gpu::probe_record(crate::gpu::OpClass::Batch, false, t0.elapsed());
1075                done = true;
1076            }
1077            crate::gpu::ProbeArm::Cpu => {
1078                crate::gpu::cpu_scope(|| {
1079                    QTensor::matvec_many(
1080                        [wq, wk, wv],
1081                        hidden,
1082                        [q_raw.as_mut_slice(), k.as_mut_slice(), v.as_mut_slice()],
1083                        cfg.pool,
1084                    )
1085                });
1086                done = true;
1087            }
1088        }
1089    }
1090    if !done {
1091        // Multi-matrix job: Q, K and V projections under one pool dispatch.
1092        QTensor::matvec_many(
1093            [wq, wk, wv],
1094            hidden,
1095            [q_raw.as_mut_slice(), k.as_mut_slice(), v.as_mut_slice()],
1096            cfg.pool,
1097        );
1098    }
1099    (q_raw, k, v)
1100}
1101
1102/// Everything between the QKV matvecs and the attend: bias, gate
1103/// split, qk-norm, partial RoPE (the shared tail of `project_position`).
1104pub(crate) fn finish_projection_debug(
1105    q_raw: Vec<f32>,
1106    k: Vec<f32>,
1107    v: Vec<f32>,
1108    cfg: &QwenAttnCfg,
1109    position: usize,
1110) -> (Vec<f32>, Vec<f32>, Vec<f32>, Vec<f32>) {
1111    let p = finish_projection(q_raw, k, v, cfg, position);
1112    (p.q.clone(), p.gate.clone(), p.k.clone(), p.v.clone())
1113}
1114
1115/// Per-head qk-norm and partial RoPE in the architecture's order. Qwen3
1116/// (and every family before HunYuan) norms, then rotates; HunYuan dense
1117/// rotates, then norms — `cfg.qk_norm_after_rope`. The V norm (Gemma-4)
1118/// is independent of both and stays with the caller.
1119pub(crate) fn qk_norm_and_rope(
1120    cfg: &QwenAttnCfg,
1121    q: &mut [f32],
1122    k: &mut [f32],
1123    nh: usize,
1124    nkv: usize,
1125    hd: usize,
1126    position: usize,
1127) {
1128    let rd = cfg.rotary_dim.min(hd);
1129    let norm = |q: &mut [f32], k: &mut [f32]| {
1130        if let Some(qw) = cfg.q_norm {
1131            for h in 0..nh {
1132                rmsnorm_head(&mut q[h * hd..h * hd + hd], qw, cfg.rms_eps, cfg.norm_style);
1133            }
1134        }
1135        if let Some(kw) = cfg.k_norm {
1136            for g in 0..nkv {
1137                rmsnorm_head(&mut k[g * hd..g * hd + hd], kw, cfg.rms_eps, cfg.norm_style);
1138            }
1139        }
1140    };
1141    // A layer with no RoPE still may have a non-empty pipeline-wide
1142    // frequency table (Flint's full-attention layers are exactly that
1143    // profile).  There is no zero-width head slice to rotate: constructing
1144    // a table from the global frequencies and passing it to that slice used
1145    // to index `x[0]` and panic before its first token.
1146    if rd == 0 {
1147        norm(q, k);
1148        return;
1149    }
1150
1151    // One sin/cos table per position, shared by every head: the angle of
1152    // frequency i does not depend on the head, and `rope_rotate_scaled`
1153    // recomputed it for each of the nh + nkv heads — 1152 libm `sin_cos`
1154    // a layer on MiniCPM5-2B (16 + 2 heads × 64). Same angle expression,
1155    // same sin_cos, same rotation → bit-identical.
1156    let rope = |q: &mut [f32], k: &mut [f32]| {
1157        ROPE_TAB.with(|t| {
1158            let mut t = t.borrow_mut();
1159            match cfg.mrope.filter(|m| position >= m.base && position - m.base < m.pos.len()) {
1160                Some(m) => mrope_table(&mut t, m.pos[position - m.base], m.sections, &cfg.inv_freq[..rd / 2]),
1161                None => rope_table(&mut t, position, &cfg.inv_freq[..rd / 2]),
1162            }
1163            for h in 0..nh {
1164                rope_rotate_table(&mut q[h * hd..h * hd + rd], &t, cfg.rope_scale);
1165            }
1166            for g in 0..nkv {
1167                rope_rotate_table(&mut k[g * hd..g * hd + rd], &t, cfg.rope_scale);
1168            }
1169        })
1170    };
1171    if cfg.qk_norm_after_rope {
1172        rope(q, k);
1173        norm(q, k);
1174    } else {
1175        norm(q, k);
1176        rope(q, k);
1177    }
1178}
1179
1180fn finish_projection(
1181    mut q_raw: Vec<f32>,
1182    mut k: Vec<f32>,
1183    mut v: Vec<f32>,
1184    cfg: &QwenAttnCfg,
1185    position: usize,
1186) -> Projected {
1187    let (nh, nkv, hd) = (cfg.num_heads, cfg.num_kv_heads, cfg.head_dim);
1188    if let Some((bq, bk, bv)) = cfg.bias {
1189        for (x, b) in q_raw.iter_mut().zip(bq) {
1190            *x += b;
1191        }
1192        for (x, b) in k.iter_mut().zip(bk) {
1193            *x += b;
1194        }
1195        for (x, b) in v.iter_mut().zip(bv) {
1196            *x += b;
1197        }
1198    }
1199
1200    // Gate split: per-head [q(hd); gate(hd)] (vmfcore/HF convention).
1201    let (mut q, gate) = if cfg.output_gate {
1202        let mut qn = take_buf(nh * hd);
1203        let mut g = take_buf(nh * hd);
1204        for h in 0..nh {
1205            let src = h * hd * 2;
1206            let dst = h * hd;
1207            qn[dst..dst + hd].copy_from_slice(&q_raw[src..src + hd]);
1208            g[dst..dst + hd].copy_from_slice(&q_raw[src + hd..src + 2 * hd]);
1209        }
1210        recycle_buf(&mut q_raw);
1211        (qn, g)
1212    } else {
1213        (q_raw, Vec::new())
1214    };
1215
1216    if cfg.v_norm {
1217        let vd = cfg.v_head_dim;
1218        for g in 0..nkv {
1219            vnorm_head(&mut v[g * vd..g * vd + vd], cfg.rms_eps);
1220        }
1221    }
1222    // qk-norm and partial RoPE (first rotary_dim dims of each head), in
1223    // the architecture's order.
1224    qk_norm_and_rope(cfg, &mut q, &mut k, nh, nkv, hd, position);
1225    // V narrower than the cache's head width: zero-pad each head (the
1226    // output is compacted back before o_proj by the caller).
1227    let v = pad_heads(v, nkv, cfg.v_head_dim, hd);
1228    Projected { q, gate, k, v }
1229}
1230
1231pub(crate) fn attend_all_heads(
1232    q: &[f32],
1233    cache: &LayerKvCache,
1234    nh: usize,
1235    heads_per_kv: usize,
1236    hd: usize,
1237    scale: f32,
1238    window: Option<usize>,
1239    softcap: f32,
1240) -> (Vec<f32>, Vec<f32>) {
1241    attend_all_heads_pool(q, cache, nh, heads_per_kv, hd, scale, window, softcap, None)
1242}
1243
1244/// `attend_all_heads` as it ran when the cache held `upto` rows, into
1245/// zeroed caller buffers (`out` = nh·hd, `imp` = the importance row of
1246/// that moment). The serial group loop verbatim, with every group's rows
1247/// capped at `upto`.
1248#[allow(clippy::too_many_arguments)]
1249fn attend_all_heads_upto(
1250    q: &[f32],
1251    cache: &LayerKvCache,
1252    nh: usize,
1253    heads_per_kv: usize,
1254    hd: usize,
1255    scale: f32,
1256    window: Option<usize>,
1257    softcap: f32,
1258    upto: usize,
1259    out: &mut [f32],
1260    imp: &mut [f32],
1261) {
1262    check_sinks(cache, nh);
1263    let nkv = nh / heads_per_kv;
1264    for g in 0..nkv {
1265        let stored = cache.head_len(g).min(upto);
1266        if stored == 0 {
1267            continue;
1268        }
1269        let first = window.map(|w| stored.saturating_sub(w)).unwrap_or(0);
1270        let span = g * heads_per_kv * hd..(g + 1) * heads_per_kv * hd;
1271        cache.attend_group_upto(
1272            &q[span.clone()],
1273            g,
1274            &mut out[span],
1275            imp,
1276            scale,
1277            first,
1278            softcap,
1279            upto,
1280            sink_slice(cache, g * heads_per_kv, (g + 1) * heads_per_kv),
1281        );
1282    }
1283}
1284
1285/// Decode attend below this many (head × stored row) cells stays serial:
1286/// the pool's barrier costs more than the work.
1287const ATTEND_PAR_MIN_CELLS: usize = 16 * 96;
1288
1289/// `row[i] = exp(row[i] − m)` in place, returning Σ row: the softmax's
1290/// exponent pass without its normalization (the split-K decode attend
1291/// normalizes after merging its chunks). AVX2 on x86-64 (the softmax
1292/// row's Cephes polynomial), scalar libm elsewhere.
1293pub(crate) fn exp_shift_sum(row: &mut [f32], m: f32) -> f32 {
1294    #[cfg(target_arch = "x86_64")]
1295    if std::arch::is_x86_feature_detected!("avx2") && std::arch::is_x86_feature_detected!("fma") {
1296        // SAFETY: both features were just detected on this CPU.
1297        return unsafe { exp_shift_sum_avx2(row, m) };
1298    }
1299    let mut s = 0f32;
1300    for v in row.iter_mut() {
1301        *v = (*v - m).exp();
1302        s += *v;
1303    }
1304    s
1305}
1306
1307/// The AVX2 body of `exp_shift_sum`.
1308///
1309/// # Safety
1310/// The caller has checked `avx2` and `fma`.
1311#[cfg(target_arch = "x86_64")]
1312#[target_feature(enable = "avx2,fma")]
1313unsafe fn exp_shift_sum_avx2(row: &mut [f32], m: f32) -> f32 {
1314    use core::arch::x86_64::*;
1315    // SAFETY: every access is within row[..n].
1316    unsafe {
1317        let n = row.len();
1318        let p = row.as_mut_ptr();
1319        let mv = _mm256_set1_ps(m);
1320        let mut sv = _mm256_setzero_ps();
1321        let mut j = 0usize;
1322        while j + 8 <= n {
1323            let e = exp_avx2(_mm256_sub_ps(_mm256_loadu_ps(p.add(j)), mv));
1324            _mm256_storeu_ps(p.add(j), e);
1325            sv = _mm256_add_ps(sv, e);
1326            j += 8;
1327        }
1328        let mut lanes = [0f32; 8];
1329        _mm256_storeu_ps(lanes.as_mut_ptr(), sv);
1330        let mut s: f32 = lanes.iter().sum();
1331        while j < n {
1332            let e = (*p.add(j) - m).exp();
1333            *p.add(j) = e;
1334            s += e;
1335            j += 1;
1336        }
1337        s
1338    }
1339}
1340
1341/// `CMF_ATTEND_SPLITK=0` keeps the per-head pooled decode attend (A/B).
1342fn splitk_on() -> bool {
1343    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1344    *ON.get_or_init(|| std::env::var("CMF_ATTEND_SPLITK").as_deref() != Ok("0"))
1345}
1346
1347/// Keys per work unit of the split-K decode attend.
1348const SPLITK_CHUNK: usize = 256;
1349
1350/// Split-K decode attend over a long grouped-query context (flash-decoding
1351/// on the CPU pool). The per-head pooled attend gave each Q head its own
1352/// job, so every head streamed its group's whole K and V: at 16 000 rows a
1353/// full layer read 512 MB for 128 MB of cache, at ~4 GB/s on an 8-core
1354/// EPYC — the decode step's largest cost past 4 000 tokens. Here a job is
1355/// (KV group, a chunk of `SPLITK_CHUNK` keys): each K and V row is read
1356/// once for all the group's heads, the chunk keeps its own max and sum
1357/// (an online softmax), and the chunks merge per head afterwards. The
1358/// importance row adds each head's final probabilities in the serial
1359/// (group, head) order. The same scores and exponents as `attend_group`
1360/// up to the vector exp; the sums run in another order (tolerance-class).
1361/// F32 cache, no soft-cap, no learned sinks (the caller checks).
1362#[allow(clippy::too_many_arguments)]
1363fn attend_split_k(
1364    q: &[f32],
1365    cache: &LayerKvCache,
1366    nh: usize,
1367    heads_per_kv: usize,
1368    hd: usize,
1369    scale: f32,
1370    window: Option<usize>,
1371    pool: &crate::pool::Pool,
1372    longest: usize,
1373) -> (Vec<f32>, Vec<f32>) {
1374    let hpk = heads_per_kv;
1375    let nkv = nh / hpk;
1376    let (kh, vh) = (cache.k_heads(), cache.v_heads());
1377    // Per group: visible rows [first, stored), chunked.
1378    let spans: Vec<(usize, usize)> = (0..nkv)
1379        .map(|g| {
1380            let stored = kh[g].len() / hd;
1381            let first = window.map_or(0, |w| stored.saturating_sub(w)).min(stored);
1382            (first, stored)
1383        })
1384        .collect();
1385    let mut units: Vec<(usize, usize, usize)> = Vec::new(); // (group, r0, r1)
1386    for (g, &(first, stored)) in spans.iter().enumerate() {
1387        let mut r0 = first;
1388        while r0 < stored {
1389            let r1 = (r0 + SPLITK_CHUNK).min(stored);
1390            units.push((g, r0, r1));
1391            r0 = r1;
1392        }
1393    }
1394    let nu = units.len();
1395    // probs[h·longest + (p − first_g)]: the chunk's exponents, rescaled
1396    // to probabilities after the merge. ml[u·hpk + h] = (max, sum);
1397    // part[(u·hpk + h)·hd ..]: the chunk's un-normalized output.
1398    let mut probs = take_buf(nh * longest);
1399    let mut ml = vec![(f32::NEG_INFINITY, 0f32); nu * hpk];
1400    let mut part = take_buf(nu * hpk * hd);
1401    {
1402        let (probs_p, ml_p, part_p) = (
1403            crate::pool::SendMut::new(probs.as_mut_ptr()),
1404            SendPair(ml.as_mut_ptr()),
1405            crate::pool::SendMut::new(part.as_mut_ptr()),
1406        );
1407        let (units, spans) = (&units, &spans);
1408        let run = |u0: usize, u1: usize| {
1409            for u in u0..u1 {
1410                let (g, r0, r1) = units[u];
1411                let first = spans[g].0;
1412                let (k, v) = (&kh[g], &vh[g]);
1413                let len = r1 - r0;
1414                // SAFETY: unit u owns probs columns [r0, r1) of its group's
1415                // heads, ml[u·hpk..] and part[u·hpk·hd..].
1416                let rows = |h: usize| unsafe {
1417                    std::slice::from_raw_parts_mut(
1418                        probs_p.at((g * hpk + h) * longest + (r0 - first)),
1419                        len,
1420                    )
1421                };
1422                for p in r0..r1 {
1423                    let krow = &k[p * hd..(p + 1) * hd];
1424                    for h in 0..hpk {
1425                        let qh = &q[(g * hpk + h) * hd..(g * hpk + h + 1) * hd];
1426                        rows(h)[p - r0] = dot_f32(qh, krow) * scale;
1427                    }
1428                }
1429                let out = unsafe { std::slice::from_raw_parts_mut(part_p.at(u * hpk * hd), hpk * hd) };
1430                out.fill(0.0);
1431                for h in 0..hpk {
1432                    let s = rows(h);
1433                    let m = s.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
1434                    let l = exp_shift_sum(s, m);
1435                    unsafe { *ml_p.at(u * hpk + h) = (m, l) };
1436                }
1437                for p in r0..r1 {
1438                    let vrow = &v[p * hd..(p + 1) * hd];
1439                    for h in 0..hpk {
1440                        let w = rows(h)[p - r0];
1441                        axpy_f32(&mut out[h * hd..(h + 1) * hd], vrow, w);
1442                    }
1443                }
1444            }
1445        };
1446        pool.run_rows(nu, &run);
1447    }
1448    // Merge per head: M = max over chunks, Z = Σ l·e^(m − M).
1449    let mut attn_out = take_buf(nh * hd);
1450    let mut imp = take_buf(cache.seq_len);
1451    let mut fac = vec![0f32; nu * hpk];
1452    for g in 0..nkv {
1453        let us: Vec<usize> = (0..nu).filter(|&u| units[u].0 == g).collect();
1454        for h in 0..hpk {
1455            let mx = us.iter().map(|&u| ml[u * hpk + h].0).fold(f32::NEG_INFINITY, f32::max);
1456            let z: f32 = us
1457                .iter()
1458                .map(|&u| {
1459                    let (m, l) = ml[u * hpk + h];
1460                    l * (m - mx).exp()
1461                })
1462                .sum();
1463            let inv = if z > 0.0 { 1.0 / z } else { 0.0 };
1464            let o = &mut attn_out[(g * hpk + h) * hd..(g * hpk + h + 1) * hd];
1465            for &u in &us {
1466                let f = (ml[u * hpk + h].0 - mx).exp() * inv;
1467                fac[u * hpk + h] = f;
1468                axpy_f32(o, &part[(u * hpk + h) * hd..(u * hpk + h + 1) * hd], f);
1469            }
1470        }
1471        // Importance: each head's probabilities, (group, head) order.
1472        let (first, stored) = spans[g];
1473        let n = imp.len().min(stored);
1474        for h in 0..hpk {
1475            for &u in &us {
1476                let (_, r0, r1) = units[u];
1477                let r1 = r1.min(n);
1478                if r1 <= r0 {
1479                    continue;
1480                }
1481                let f = fac[u * hpk + h];
1482                let row = &probs[(g * hpk + h) * longest + (r0 - first)..][..r1 - r0];
1483                for (dst, &e) in imp[r0..r1].iter_mut().zip(row) {
1484                    *dst += e * f;
1485                }
1486            }
1487        }
1488    }
1489    recycle_buf(&mut probs);
1490    recycle_buf(&mut part);
1491    (attn_out, imp)
1492}
1493
1494/// A raw `(max, sum)` pointer the split-K jobs share (disjoint slots).
1495struct SendPair(*mut (f32, f32));
1496// SAFETY: each job writes only its own unit's slots.
1497unsafe impl Send for SendPair {}
1498unsafe impl Sync for SendPair {}
1499impl SendPair {
1500    // A method, so the closure captures &SendPair rather than the raw
1501    // field (2021 disjoint capture).
1502    fn at(&self, i: usize) -> *mut (f32, f32) {
1503        // SAFETY: callers index within the slot array.
1504        unsafe { self.0.add(i) }
1505    }
1506}
1507
1508/// `attend_all_heads`, one pool job over the heads once the context is
1509/// long enough. The serial kernel was the whole CPU attention of a decode
1510/// step on one core: 16 heads × `stored` rows of dot + libm `exp` + axpy,
1511/// ~70 us a layer at 100 tokens and linear in the context. Each head is
1512/// attended by the same `attend_group` arithmetic (a group of one head:
1513/// every per-head loop runs over the same rows in the same order), and
1514/// the importance sums are added afterwards in the serial path's (group,
1515/// head) order — output and importance are bit-identical.
1516#[allow(clippy::too_many_arguments)]
1517pub(crate) fn attend_all_heads_pool(
1518    q: &[f32],
1519    cache: &LayerKvCache,
1520    nh: usize,
1521    heads_per_kv: usize,
1522    hd: usize,
1523    scale: f32,
1524    window: Option<usize>,
1525    softcap: f32,
1526    pool: Option<&crate::pool::Pool>,
1527) -> (Vec<f32>, Vec<f32>) {
1528    check_sinks(cache, nh);
1529    let nkv = nh / heads_per_kv.max(1);
1530    let longest = (0..nkv).map(|g| cache.head_len(g)).max().unwrap_or(0);
1531    // x86-64 (the architecture it was measured on): the split-K attend
1532    // for a grouped context of 512 rows or more. `CMF_ATTEND_SPLITK=0`
1533    // keeps the per-head jobs (bit-identical to the serial attend).
1534    if let Some(pool) = pool
1535        && cfg!(target_arch = "x86_64")
1536        && heads_per_kv >= 2
1537        && nh % heads_per_kv == 0
1538        && longest >= 512
1539        && cache.mode == crate::kv_cache::KvMode::F32
1540        && softcap == 0.0
1541        && cache.sinks.is_none()
1542        && splitk_on()
1543    {
1544        return attend_split_k(q, cache, nh, heads_per_kv, hd, scale, window, pool, longest);
1545    }
1546    if let Some(pool) = pool
1547        && nh >= 2
1548        && nh * longest >= ATTEND_PAR_MIN_CELLS
1549    {
1550        let mut attn_out = take_buf(nh * hd);
1551        let mut imp = take_buf(cache.seq_len);
1552        // Per-head probabilities, each head's own row: [nh × longest].
1553        let mut probs = take_buf(nh * longest);
1554        let (out_p, probs_p) = (
1555            crate::pool::SendMut::new(attn_out.as_mut_ptr()),
1556            crate::pool::SendMut::new(probs.as_mut_ptr()),
1557        );
1558        let run = |h0: usize, h1: usize| {
1559            for h in h0..h1 {
1560                let g = h / heads_per_kv;
1561                let stored = cache.head_len(g);
1562                // SAFETY: head h owns out[h·hd..] and probs[h·longest..].
1563                let (out_h, probs_h) = unsafe {
1564                    (
1565                        std::slice::from_raw_parts_mut(out_p.at(h * hd), hd),
1566                        std::slice::from_raw_parts_mut(probs_p.at(h * longest), longest),
1567                    )
1568                };
1569                if stored == 0 {
1570                    continue;
1571                }
1572                let first = window.map(|w| stored.saturating_sub(w)).unwrap_or(0);
1573                cache.attend_group(
1574                    &q[h * hd..(h + 1) * hd],
1575                    g,
1576                    out_h,
1577                    probs_h,
1578                    scale,
1579                    first,
1580                    softcap,
1581                    sink_slice(cache, h, h + 1),
1582                );
1583            }
1584        };
1585        pool.run_rows(nh, &run);
1586        // Importance in the serial order: groups, then their heads. Each
1587        // probs row is 0 + p exactly, so the sums match attend_group's.
1588        for g in 0..nkv {
1589            let stored = cache.head_len(g);
1590            if stored == 0 {
1591                continue;
1592            }
1593            let n = imp.len().min(stored);
1594            for h in g * heads_per_kv..(g + 1) * heads_per_kv {
1595                let row = &probs[h * longest..h * longest + n];
1596                for (dst, &p) in imp[..n].iter_mut().zip(row) {
1597                    *dst += p;
1598                }
1599            }
1600        }
1601        recycle_buf(&mut probs);
1602        return (attn_out, imp);
1603    }
1604    let mut attn_out = take_buf(nh * hd);
1605    let mut imp = take_buf(cache.seq_len);
1606    // Grouped GQA kernel: the group's shared K/V storage is streamed
1607    // once for all its Q-heads (per-head attend re-read it
1608    // heads_per_kv times). Bit-identical per head — see attend_group.
1609    let nkv = nh / heads_per_kv;
1610    for g in 0..nkv {
1611        let stored = cache.head_len(g);
1612        if stored == 0 {
1613            continue;
1614        }
1615        let first = window.map(|w| stored.saturating_sub(w)).unwrap_or(0);
1616        let span = g * heads_per_kv * hd..(g + 1) * heads_per_kv * hd;
1617        cache.attend_group(
1618            &q[span.clone()],
1619            g,
1620            &mut attn_out[span],
1621            &mut imp,
1622            scale,
1623            first,
1624            softcap,
1625            sink_slice(cache, g * heads_per_kv, (g + 1) * heads_per_kv),
1626        );
1627    }
1628    (attn_out, imp)
1629}
1630
1631#[inline]
1632fn apply_gate(ao: &mut [f32], gate: &[f32]) {
1633    for (a, &g) in ao.iter_mut().zip(gate) {
1634        *a *= 1.0 / (1.0 + (-g).exp());
1635    }
1636}
1637
1638#[inline]
1639fn softplus(x: f32) -> f32 {
1640    x.max(0.0) + (-x.abs()).exp().ln_1p()
1641}
1642
1643/// The gain one projected-gate value gives (sigmoid, or softplus).
1644pub(crate) fn projected_gate_gain(g: f32, sigmoid: bool) -> f32 {
1645    if sigmoid {
1646        1.0 / (1.0 + (-g).exp())
1647    } else {
1648        softplus(g)
1649    }
1650}
1651
1652pub(crate) fn apply_projected_gate(
1653    ao: &mut [f32],
1654    raw: &[f32],
1655    per_head: bool,
1656    head_dim: usize,
1657    sigmoid: bool,
1658) {
1659    let act = |g: f32| projected_gate_gain(g, sigmoid);
1660    if per_head {
1661        for (h, &g) in raw.iter().enumerate() {
1662            let gain = act(g);
1663            for a in &mut ao[h * head_dim..(h + 1) * head_dim] {
1664                *a *= gain;
1665            }
1666        }
1667    } else {
1668        for (a, &g) in ao.iter_mut().zip(raw) {
1669            *a *= act(g);
1670        }
1671    }
1672}
1673
1674fn projected_gate(hidden: &[f32], cfg: &QwenAttnCfg) -> Option<Vec<f32>> {
1675    cfg.softplus_gate.map(|(proj, _)| {
1676        let mut gate = take_buf(proj.rows());
1677        proj.matvec(hidden, &mut gate, cfg.pool);
1678        gate
1679    })
1680}
1681
1682/// The CPU middle of an attention layer whose QKV matvecs already ran
1683/// (e.g. on the GPU token graph) and whose O projection runs after:
1684/// bias, gate split, qk-norm, RoPE, KV append, grouped attend, output
1685/// gate. Bit-identical to `qwen_attention` between its two matvecs.
1686pub fn qwen_attention_core(
1687    q_raw: Vec<f32>,
1688    k: Vec<f32>,
1689    v: Vec<f32>,
1690    cache: &mut LayerKvCache,
1691    cfg: &QwenAttnCfg,
1692) -> Vec<f32> {
1693    let (nh, nkv, hd) = (cfg.num_heads, cfg.num_kv_heads, cfg.head_dim);
1694    let heads_per_kv = nh / nkv;
1695    check_v_width(cfg);
1696    // A direct caller may have appended the completed boundary without
1697    // passing through the usual post-row hook. Seal before accepting another
1698    // exact row so the first row after B cannot re-open ordinary KV growth.
1699    if cache
1700        .o1_pending_boundary()
1701        .is_some_and(|target| cache.seq_len >= target)
1702    {
1703        if let Err(err) = cache.o1_seal_checked(nh) {
1704            cache.o1_abort(err);
1705        }
1706    }
1707    let p = finish_projection(q_raw, k, v, cfg, cfg.position);
1708    // The Metal sandwich path already ran Q/K/V projections on the device
1709    // and calls this middle function directly. If a sealed O(1) view refused
1710    // device admission, keep that path on the streaming state; appending to
1711    // the now-dropped exact KV here would silently resurrect unbounded cache.
1712    if cache.o1_sealed() {
1713        let mut ao = cache.o1_step(&p.q, &p.k, &p.v, nh);
1714        if cfg.output_gate {
1715            apply_gate(&mut ao, &p.gate);
1716        }
1717        return compact_heads(ao, nh, hd, cfg.v_head_dim);
1718    }
1719    // O(1) prefill trace: while a nystrom layer is collecting, the exact
1720    // prompt pass also records this position's queries for the seal
1721    // (no-op on plain layers).
1722    cache.o1_push_q(&p.q);
1723    // Empty alive slice = every head alive (append's get().unwrap_or(true))
1724    // — the vec![true; nkv] here was one allocation per layer per token.
1725    cache.append(&p.k, &p.v, &[]);
1726
1727    let (mut ao, mut imp) = attend_all_heads_pool(
1728        &p.q,
1729        cache,
1730        nh,
1731        heads_per_kv,
1732        hd,
1733        cfg.scale,
1734        cfg.window,
1735        cfg.softcap,
1736        cfg.pool,
1737    );
1738    cache.accumulate_imp(&imp);
1739    if cfg.output_gate {
1740        apply_gate(&mut ao, &p.gate);
1741    }
1742    // A deferred short-prompt seal is a completed-row barrier. The exact
1743    // row above is retained in the trace/KV, then conversion happens before
1744    // the next row can append. A malformed transition is terminal: clear
1745    // the layer and publish the error for Pipeline's existing failure path.
1746    // A layer awaiting its exact rows is sealed by the pipeline instead.
1747    if !cache.o1_await_keep
1748        && cache
1749            .o1_pending_boundary()
1750            .is_some_and(|target| cache.seq_len >= target)
1751    {
1752        if let Err(err) = cache.o1_seal_checked(nh) {
1753            cache.o1_abort(err);
1754        }
1755    }
1756    recycle_buf(&mut imp);
1757    // V narrower than the head width: the pad dims of every head are
1758    // exactly 0 (zero V rows), drop them so o_proj reads nh·v_head_dim.
1759    compact_heads(ao, nh, hd, cfg.v_head_dim)
1760}
1761
1762/// Dense GQA attention for one position (QTensor weights, Qwen3.5 extras).
1763#[allow(clippy::too_many_arguments)]
1764pub fn qwen_attention(
1765    hidden: &[f32],
1766    wq: &QTensor,
1767    wk: &QTensor,
1768    wv: &QTensor,
1769    wo: &QTensor,
1770    cache: &mut LayerKvCache,
1771    cfg: &QwenAttnCfg,
1772) -> Vec<f32> {
1773    // Once a deferred barrier seals, every following row must use the
1774    // streaming state. This dispatch also covers sequential fallback rows
1775    // after a pair/batch was split at the barrier.
1776    if cache.o1_sealed() {
1777        return qwen_attention_nystrom(hidden, wq, wk, wv, wo, cache, cfg);
1778    }
1779    let prof = crate::cpuprof::time(crate::cpuprof::Slot::Qkv);
1780    let (q_raw, k, v) = project_matvecs(hidden, wq, wk, wv, cfg);
1781    drop(prof);
1782    let mut projected = projected_gate(hidden, cfg);
1783    let prof = crate::cpuprof::time(crate::cpuprof::Slot::AttnCore);
1784    let mut ao = qwen_attention_core(q_raw, k, v, cache, cfg);
1785    drop(prof);
1786    if let (Some(raw), Some((_, per_head))) = (projected.as_deref(), cfg.softplus_gate) {
1787        // A gate is refused at load when V is narrower than the head
1788        // (the core output is compacted), so ao is nh·head_dim here.
1789        apply_projected_gate(&mut ao, raw, per_head, cfg.head_dim, cfg.gate_sigmoid);
1790    }
1791    let mut out = take_buf(cfg.hidden_size);
1792    let prof = crate::cpuprof::time(crate::cpuprof::Slot::AttnO);
1793    wo.matvec(&ao, &mut out, cfg.pool);
1794    drop(prof);
1795    recycle_buf(&mut ao);
1796    if let Some(mut gate) = projected.take() {
1797        recycle_buf(&mut gate);
1798    }
1799    out
1800}
1801
1802/// `CMF_PREFILL_PROF`: cumulative ns of `qwen_attention_batch`'s stages —
1803/// projections (q|k|v and a projected gate), the per-position host loop
1804/// (bias, norms, RoPE, host append), the attend (with its gate), the O
1805/// projection — and inside the attend, the device call's two host parts:
1806/// the head-major pack of Q and the call itself (upload, kernels, readback);
1807/// last, the share of the projections a host-side projected gate takes.
1808/// The pipeline prints them with its attention/FFN split.
1809pub(crate) static ATTN_SPLIT: [std::sync::atomic::AtomicU64; 7] =
1810    [const { std::sync::atomic::AtomicU64::new(0) }; 7];
1811
1812/// `CMF_PREFILL_PROF`: chunks whose layer named a device mirror but went up
1813/// by the host upload instead (the mirror attend refused them).
1814pub(crate) static MIRROR_UPLOADS: std::sync::atomic::AtomicU64 =
1815    std::sync::atomic::AtomicU64::new(0);
1816
1817pub(crate) fn attn_split_on() -> bool {
1818    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1819    *ON.get_or_init(|| std::env::var_os("CMF_PREFILL_PROF").is_some())
1820}
1821
1822/// Batched-chunk exact attention (roadmap §3 P0 «prefill»): Q/K/V and O
1823/// projections run as chunk-GEMMs — each weight row streams from memory
1824/// ONCE per chunk instead of once per position — while the attention
1825/// core stays per-position (causal append order). Per-position math is
1826/// identical to `qwen_attention` (matmat ≡ per-position matvec by the
1827/// existing parity tests), so the results match the sequential prefill.
1828/// `cfg.position` is the chunk's FIRST absolute position.
1829#[allow(clippy::too_many_arguments)]
1830pub fn qwen_attention_batch(
1831    normed_all: &[f32],
1832    b: usize,
1833    wq: &QTensor,
1834    wk: &QTensor,
1835    wv: &QTensor,
1836    wo: &QTensor,
1837    cache: &mut LayerKvCache,
1838    cfg: &QwenAttnCfg,
1839) -> Vec<f32> {
1840    let (nh, nkv, hd) = (cfg.num_heads, cfg.num_kv_heads, cfg.head_dim);
1841    let heads_per_kv = nh / nkv;
1842    let qrows = wq.rows();
1843    check_v_width(cfg);
1844    // V row width per position: nkv·v_head_dim (== nkv·hd unless V heads
1845    // are narrower, MiMo-V2); padded to hd per head before the append.
1846    let vd = cfg.v_head_dim;
1847    let vrow = nkv * vd;
1848    debug_assert_eq!(normed_all.len(), b * cfg.hidden_size);
1849
1850    // A chunk that reaches the deferred barrier is walked row by row so the
1851    // completed exact row can seal before the first compressed row. A
1852    // sealed state also cannot use this append-and-batched-attend path.
1853    if cache.o1_sealed() || cache.o1_boundary_crossed_by(b) {
1854        let mut out = take_buf(b * cfg.hidden_size);
1855        for bi in 0..b {
1856            let mut row_cfg = *cfg;
1857            row_cfg.position = cfg.position + bi;
1858            row_cfg.value_in = cfg
1859                .value_in
1860                .map(|v| &v[bi * cfg.hidden_size..(bi + 1) * cfg.hidden_size]);
1861            let row = qwen_attention(
1862                &normed_all[bi * cfg.hidden_size..(bi + 1) * cfg.hidden_size],
1863                wq,
1864                wk,
1865                wv,
1866                wo,
1867                cache,
1868                &row_cfg,
1869            );
1870            out[bi * cfg.hidden_size..(bi + 1) * cfg.hidden_size].copy_from_slice(&row);
1871        }
1872        return out;
1873    }
1874
1875    // ── chunk-GEMM projections ──
1876    let split_t0 = std::time::Instant::now();
1877    let mut q_all = take_buf(b * qrows);
1878    let mut k_all = take_buf(b * nkv * hd);
1879    let mut v_all = take_buf(b * vrow);
1880    // One fused submission when the device is in play: three `matmat`
1881    // calls upload the SAME normed chunk three times and pay three round
1882    // trips per layer. Falls through to the per-projection path on any
1883    // refusal (non-q4t weights, no device, contention kill).
1884    // GPTQ calibration needs every projection's input folded on the host
1885    // (`QTensor::matmat`); the fused device submissions below skip it.
1886    let capturing = crate::gptq_capture::capturing();
1887    let fused = crate::gpu::enabled_here()
1888        && !crate::gpu::mm_killed()
1889        && b >= 32
1890        && !capturing
1891        // The fused submissions project q|k|v from one chunk; V with rows of its own goes
1892        // by the per-projection path.
1893        && cfg.value_in.is_none()
1894        && match (wq.mapped_q4t(), wk.mapped_q4t(), wv.mapped_q4t()) {
1895            (Some((model, iq)), Some((_, ik)), Some((_, iv))) => {
1896                let (rk, rv) = (wk.rows(), wv.rows());
1897                let mut cat = take_buf(b * (qrows + rk + rv));
1898                let ok = crate::gpu::q4t_qkv(
1899                    model,
1900                    iq,
1901                    ik,
1902                    iv,
1903                    normed_all,
1904                    b,
1905                    cfg.hidden_size,
1906                    qrows,
1907                    rk,
1908                    rv,
1909                    &mut cat,
1910                );
1911                if ok {
1912                    q_all.copy_from_slice(&cat[..b * qrows]);
1913                    k_all.copy_from_slice(&cat[b * qrows..b * (qrows + rk)]);
1914                    v_all.copy_from_slice(&cat[b * (qrows + rk)..b * (qrows + rk + rv)]);
1915                }
1916                recycle_buf(&mut cat);
1917                ok
1918            }
1919            _ => false,
1920        };
1921    // Any other device codec: q|k|v (and the projected gate) as separate
1922    // GEMMs on the card, read back in one trip instead of one each.
1923    let mut projected_all: Option<Vec<f32>> = None;
1924    let fused = fused
1925        || (crate::gpu::enabled_here()
1926            && !crate::gpu::mm_killed()
1927            && b >= 32
1928            && !capturing
1929            && cfg.value_in.is_none()
1930            && std::env::var("CMF_QKV_KEEP").as_deref() != Ok("0")
1931            && match (
1932                wq.mapped_device_gemm(),
1933                wk.mapped_device_gemm(),
1934                wv.mapped_device_gemm(),
1935                cfg.softplus_gate.map(|(p, _)| p.mapped_device_gemm()),
1936            ) {
1937                // A projected gate in another codec (Spark keeps its 16-row
1938                // g_proj in f32) stays a host GEMM below; q|k|v still go.
1939                (Some((model, iq)), Some((mk, ik)), Some((mv, iv)), gate)
1940                    if std::sync::Arc::ptr_eq(model, mk) && std::sync::Arc::ptr_eq(model, mv) =>
1941                {
1942                    let gate = gate.flatten().filter(|(mg, _)| std::sync::Arc::ptr_eq(model, mg));
1943                    let (rk, rv) = (wk.rows(), wv.rows());
1944                    let mut idxs = vec![(iq, qrows), (ik, rk), (iv, rv)];
1945                    let rg = match (gate, cfg.softplus_gate) {
1946                        (Some((_, ig)), Some((p, _))) => {
1947                            idxs.push((ig, p.rows()));
1948                            p.rows()
1949                        }
1950                        _ => 0,
1951                    };
1952                    let mut cat = take_buf(b * (qrows + rk + rv + rg));
1953                    let ok = crate::gpu::gemm_many_keep(model, &idxs, normed_all, b, cfg.hidden_size, &mut cat);
1954                    if ok {
1955                        let (e1, e2, e3) = (b * qrows, b * (qrows + rk), b * (qrows + rk + rv));
1956                        q_all.copy_from_slice(&cat[..e1]);
1957                        k_all.copy_from_slice(&cat[e1..e2]);
1958                        v_all.copy_from_slice(&cat[e2..e3]);
1959                        if rg > 0 {
1960                            projected_all = Some(cat[e3..e3 + b * rg].to_vec());
1961                        }
1962                    }
1963                    recycle_buf(&mut cat);
1964                    ok
1965                }
1966                _ => false,
1967            });
1968    if !fused {
1969        wq.matmat(normed_all, b, &mut q_all, cfg.pool);
1970        wk.matmat(normed_all, b, &mut k_all, cfg.pool);
1971        wv.matmat(cfg.value_in.unwrap_or(normed_all), b, &mut v_all, cfg.pool);
1972    }
1973    let t_gate = std::time::Instant::now();
1974    if projected_all.is_none() {
1975        projected_all = cfg.softplus_gate.map(|(proj, _)| {
1976            let mut values = take_buf(b * proj.rows());
1977            proj.matmat(normed_all, b, &mut values, cfg.pool);
1978            values
1979        });
1980    }
1981    if attn_split_on() {
1982        ATTN_SPLIT[6].fetch_add(
1983            t_gate.elapsed().as_nanos() as u64,
1984            std::sync::atomic::Ordering::Relaxed,
1985        );
1986    }
1987
1988    // ── per-position: bias, gate split, qk-norm, partial RoPE, append;
1989    //    the attend either runs per position (exact historical order)
1990    //    or batched over the whole chunk after the appends ──
1991    // Batched causal attend: Accelerate on macOS, the portable NEON
1992    // micro-GEMM elsewhere on aarch64 (mobile prefill was per-position
1993    // — the quadratic wall).
1994    // The batched attends below (device chunk_attend, the aarch64
1995    // attend_chunk, the portable fallback) know neither a window nor a
1996    // learned sink: such layers keep the per-position grouped attend,
1997    // which carries both.
1998    // A window wider than every key this chunk can see (the cache's rows
1999    // plus the chunk) masks nothing: each query's window then starts at
2000    // row 0, which is exactly the full causal attend — so a short prompt
2001    // on a sliding layer (Spark-X2.5: 512) keeps the batched attend.
2002    // Taken only on Spark-X2.5 (`gate_sigmoid`, the one architecture whose
2003    // prefill parity was measured on it): every other windowed model
2004    // (Gemma-3, Phi-3, Laguna, ...) keeps its historical per-position
2005    // attend bit for bit. The identity holds for all of them — widen this
2006    // after measuring one.
2007    let window_masks = cfg
2008        .window
2009        .is_some_and(|w| !cfg.gate_sigmoid || cache.seq_len + b > w);
2010    // A window that does mask: the wgpu chunk softmax applies it itself
2011    // (`chunk_attend_win`), and the portable fallback below honours it too.
2012    // Spark-X2.5 only, as above.
2013    let device_window = window_masks && cfg.gate_sigmoid && crate::gpu::chunk_attend_windowed();
2014    let attend_core = b >= 32
2015        && cache.mode == crate::kv_cache::KvMode::F32
2016        && cfg.softcap == 0.0 // capped scores: per-position attend (correctness first)
2017        && cache.sinks.is_none();
2018    let attend_ok = attend_core && (!window_masks || device_window);
2019    // The device can batch it on any architecture. That matters because
2020    // the CPU twin needs Accelerate or the NEON micro-GEMM, so x86 had
2021    // no batched attend at all and prefill fell back to a per-position
2022    // scalar loop — 30% of a 512-token prefill and 46% of a 1024-token
2023    // one on a 256-core EPYC.
2024    // Every shape condition `chunk_attend` checks is mirrored here: on a
2025    // machine with no CPU twin (x86) a refusal after this point would
2026    // leave the output zeroed, so refusal must be impossible short of a
2027    // lost device.
2028    // A projected gate is applied to `ao_all` after the batched attend, so
2029    // it does not need the device to know it. Admitted for Spark-X2.5's
2030    // head-wise sigmoid only: Laguna's softplus gate keeps the CPU attend
2031    // it has always had (no Laguna parity was measured on this arm).
2032    let gpu_attend = attend_ok
2033        && crate::gpu::enabled_here()
2034        && !crate::gpu::mm_killed()
2035        && !cfg.output_gate
2036        && (cfg.softplus_gate.is_none() || cfg.gate_sigmoid)
2037        && nh > 0
2038        && nkv > 0
2039        && hd > 0
2040        && nh % nkv == 0
2041        && cache.o1.is_none();
2042    #[cfg(target_arch = "aarch64")]
2043    let cpu_attend = attend_ok
2044        && (crate::qtensor::accel_gemm_enabled()
2045            || std::env::var("CMF_FORCE_NEON_GEMM")
2046                .map(|v| v == "1")
2047                .unwrap_or(false));
2048    // x86-64: the AVX2 micro-GEMM twin (`qtensor::x86_gemm_rm`;
2049    // `CMF_CPU_ATTEND=0` keeps the per-position attend). `attend_chunk`
2050    // masks a sliding window itself and bounds its GEMM range to the
2051    // window, so a windowed layer takes it too, under the device arm's
2052    // Spark-only rule (the window's parity was measured on Spark). An O(1)
2053    // layer still collecting its exact prefix takes it as on aarch64: the
2054    // chunk that ends on the boundary must give the exact pipeline's rows
2055    // (`o1_prefix_chunk_ending_on_boundary_matches_exact_prefill`).
2056    #[cfg(target_arch = "x86_64")]
2057    let cpu_attend = attend_core
2058        && (!window_masks || cfg.gate_sigmoid)
2059        && crate::qtensor::accel_gemm_enabled();
2060    #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
2061    let cpu_attend = false;
2062    let batched_attend = cpu_attend || gpu_attend;
2063    // Without a batched attend (no device, a CPU without a micro-GEMM, or
2064    // a shape the chunk attends refuse)
2065    // every position used to attend right after its own append, serially
2066    // on the caller: a scalar-core loop of dot + libm exp + axpy that was
2067    // 30% of a 512-token and 46% of a 1024-token prefill on a 256-core
2068    // EPYC. Appending the whole chunk first and attending each position
2069    // over exactly the rows it would have seen (`upto = s0 + i + 1`) is
2070    // the same arithmetic per position — so the pool can take the
2071    // positions in parallel and the result stays bit-identical. The
2072    // importance rows are added back in position order afterwards.
2073    let par_positions = !batched_attend
2074        && cfg.pool.is_some()
2075        && b >= 2
2076        && cache.mode == crate::kv_cache::KvMode::F32
2077        && std::env::var("CMF_PAR_ATTEND").map_or(true, |v| v != "0");
2078    let stash_q = batched_attend || par_positions;
2079    let split_t1 = std::time::Instant::now();
2080    let prof_attend = crate::cpuprof::time(crate::cpuprof::Slot::PrefillAttend);
2081    let s0 = cache.seq_len;
2082    let mut ao_all = take_buf(b * nh * hd);
2083    let mut q_rope_all = if stash_q {
2084        take_buf(b * nh * hd)
2085    } else {
2086        Vec::new()
2087    };
2088    let mut gates_all = if stash_q && cfg.output_gate {
2089        take_buf(b * nh * hd)
2090    } else {
2091        Vec::new()
2092    };
2093    // Bias, V norm, qk-norm and RoPE are per position and touch nothing but
2094    // that position's rows: on a pooled host they run across the pool
2095    // first (in place in q_all / k_all / v_all), and the loop below keeps
2096    // only the ordered part — the o1 trace, the host append, the stash.
2097    // Same arithmetic per position, so bit-identical; the serial walk was
2098    // ~2.3 s of a Spark-4B 8k prefill (36 layers × 8000 positions).
2099    // Spark-X2.5 only (`gate_sigmoid`), the one architecture this was
2100    // measured on: every other model keeps the serial walk.
2101    // `CMF_PAR_ROPE=0` keeps it serial (A/B).
2102    let pre_rotated = stash_q
2103        && cfg.gate_sigmoid
2104        && !cfg.output_gate
2105        && cache.o1.is_none()
2106        && b >= 32
2107        && cfg.pool.is_some()
2108        && std::env::var("CMF_PAR_ROPE").as_deref() != Ok("0");
2109    // max |x| over the chunk's rotated queries, keys and values
2110    // (`gpu::abs_max_or_inf`), for the device attend's f16 operand guard:
2111    // taken in the pool pass below while the rows are hot, else scanned.
2112    let qkv_amax = [const { std::sync::atomic::AtomicU32::new(0) }; 3];
2113    if pre_rotated {
2114        let pool = cfg.pool.expect("pre_rotated requires a pool");
2115        let (qp, kp, vp) = (
2116            crate::pool::SendMut::new(q_all.as_mut_ptr()),
2117            crate::pool::SendMut::new(k_all.as_mut_ptr()),
2118            crate::pool::SendMut::new(v_all.as_mut_ptr()),
2119        );
2120        let run = |b0: usize, b1: usize| {
2121            for bi in b0..b1 {
2122                // SAFETY: position bi owns row bi of each panel.
2123                let (q, k, v) = unsafe {
2124                    (
2125                        std::slice::from_raw_parts_mut(qp.at(bi * qrows), nh * hd),
2126                        std::slice::from_raw_parts_mut(kp.at(bi * nkv * hd), nkv * hd),
2127                        std::slice::from_raw_parts_mut(vp.at(bi * vrow), vrow),
2128                    )
2129                };
2130                if let Some((bq, bk, bv)) = cfg.bias {
2131                    for (x, bb) in q.iter_mut().zip(bq) {
2132                        *x += bb;
2133                    }
2134                    for (x, bb) in k.iter_mut().zip(bk) {
2135                        *x += bb;
2136                    }
2137                    for (x, bb) in v.iter_mut().zip(bv) {
2138                        *x += bb;
2139                    }
2140                }
2141                if cfg.v_norm {
2142                    for g in 0..nkv {
2143                        vnorm_head(&mut v[g * vd..g * vd + vd], cfg.rms_eps);
2144                    }
2145                }
2146                qk_norm_and_rope(cfg, q, k, nh, nkv, hd, cfg.position + bi);
2147                if gpu_attend {
2148                    // Non-negative (or +inf): the bit order is the order.
2149                    for (a, x) in qkv_amax.iter().zip([&*q, &*k, &*v]) {
2150                        a.fetch_max(
2151                            crate::gpu::abs_max_or_inf(x).to_bits(),
2152                            std::sync::atomic::Ordering::Relaxed,
2153                        );
2154                    }
2155                }
2156            }
2157        };
2158        pool.run_rows(b, &run);
2159    }
2160    for bi in 0..b {
2161        let pos = cfg.position + bi;
2162        let q_raw = &mut q_all[bi * qrows..(bi + 1) * qrows];
2163        let k = &mut k_all[bi * nkv * hd..(bi + 1) * nkv * hd];
2164        let v = &mut v_all[bi * vrow..(bi + 1) * vrow];
2165        if pre_rotated {
2166            // Already biased, normed and rotated above.
2167            cache.o1_push_q(&q_raw[..nh * hd]);
2168            if vd == hd {
2169                cache.append(k, v, &[]);
2170            } else {
2171                let mut vp = pad_heads(v.to_vec(), nkv, vd, hd);
2172                cache.append(k, &vp, &[]);
2173                recycle_buf(&mut vp);
2174            }
2175            q_rope_all[bi * nh * hd..(bi + 1) * nh * hd].copy_from_slice(&q_raw[..nh * hd]);
2176            continue;
2177        }
2178        if let Some((bq, bk, bv)) = cfg.bias {
2179            for (x, bb) in q_raw.iter_mut().zip(bq) {
2180                *x += bb;
2181            }
2182            for (x, bb) in k.iter_mut().zip(bk) {
2183                *x += bb;
2184            }
2185            for (x, bb) in v.iter_mut().zip(bv) {
2186                *x += bb;
2187            }
2188        }
2189        // Gate split: per-head [q(hd); gate(hd)] (see project_position).
2190        let (mut q, mut gate) = if cfg.output_gate {
2191            let mut qn = take_buf(nh * hd);
2192            let mut g = take_buf(nh * hd);
2193            for hh in 0..nh {
2194                let src = hh * hd * 2;
2195                let dst = hh * hd;
2196                qn[dst..dst + hd].copy_from_slice(&q_raw[src..src + hd]);
2197                g[dst..dst + hd].copy_from_slice(&q_raw[src + hd..src + 2 * hd]);
2198            }
2199            (qn, g)
2200        } else {
2201            (take_buf(nh * hd), Vec::new())
2202        };
2203        if !cfg.output_gate {
2204            q.copy_from_slice(&q_raw[..nh * hd]);
2205        }
2206        if cfg.v_norm {
2207            for g in 0..nkv {
2208                vnorm_head(&mut v[g * vd..g * vd + vd], cfg.rms_eps);
2209            }
2210        }
2211        qk_norm_and_rope(cfg, &mut q, k, nh, nkv, hd, pos);
2212
2213        cache.o1_push_q(&q);
2214        if vd == hd {
2215            cache.append(k, v, &[]);
2216        } else {
2217            let mut vp = pad_heads(v.to_vec(), nkv, vd, hd);
2218            cache.append(k, &vp, &[]);
2219            recycle_buf(&mut vp);
2220        }
2221        if stash_q {
2222            q_rope_all[bi * nh * hd..(bi + 1) * nh * hd].copy_from_slice(&q);
2223            if cfg.output_gate {
2224                gates_all[bi * nh * hd..(bi + 1) * nh * hd].copy_from_slice(&gate);
2225            }
2226        } else {
2227            let (mut ao, mut imp) = attend_all_heads(
2228                &q,
2229                cache,
2230                nh,
2231                heads_per_kv,
2232                hd,
2233                cfg.scale,
2234                cfg.window,
2235                cfg.softcap,
2236            );
2237            cache.accumulate_imp(&imp);
2238            if cfg.output_gate {
2239                apply_gate(&mut ao, &gate);
2240            }
2241            if let (Some(all), Some((proj, per_head))) =
2242                (projected_all.as_deref(), cfg.softplus_gate)
2243            {
2244                let raw = &all[bi * proj.rows()..(bi + 1) * proj.rows()];
2245                apply_projected_gate(&mut ao, raw, per_head, hd, cfg.gate_sigmoid);
2246            }
2247            ao_all[bi * nh * hd..(bi + 1) * nh * hd].copy_from_slice(&ao);
2248            recycle_buf(&mut ao);
2249            recycle_buf(&mut imp);
2250        }
2251        recycle_buf(&mut q);
2252        recycle_buf(&mut gate);
2253    }
2254    let split_t2 = std::time::Instant::now();
2255    if par_positions {
2256        let pool = cfg.pool.expect("par_positions requires a pool");
2257        let s_end = cache.seq_len;
2258        let row = s0 + b;
2259        let mut imp_all = take_buf(b * row);
2260        let (ao_p, imp_p) = (
2261            crate::pool::SendMut::new(ao_all.as_mut_ptr()),
2262            crate::pool::SendMut::new(imp_all.as_mut_ptr()),
2263        );
2264        let (qr, gr) = (&q_rope_all, &gates_all);
2265        let proj = projected_all.as_deref();
2266        let cache_ref: &LayerKvCache = cache;
2267        let run = |b0: usize, b1: usize| {
2268            for bi in b0..b1 {
2269                let upto = s0 + bi + 1;
2270                let imp_len = upto.min(s_end);
2271                // SAFETY: position bi owns ao[bi·nh·hd..] and imp[bi·row..].
2272                let (ao, imp) = unsafe {
2273                    (
2274                        std::slice::from_raw_parts_mut(ao_p.at(bi * nh * hd), nh * hd),
2275                        std::slice::from_raw_parts_mut(imp_p.at(bi * row), imp_len),
2276                    )
2277                };
2278                attend_all_heads_upto(
2279                    &qr[bi * nh * hd..(bi + 1) * nh * hd],
2280                    cache_ref,
2281                    nh,
2282                    heads_per_kv,
2283                    hd,
2284                    cfg.scale,
2285                    cfg.window,
2286                    cfg.softcap,
2287                    upto,
2288                    ao,
2289                    imp,
2290                );
2291                if cfg.output_gate {
2292                    apply_gate(ao, &gr[bi * nh * hd..(bi + 1) * nh * hd]);
2293                }
2294                if let (Some(all), Some((pj, per_head))) = (proj, cfg.softplus_gate) {
2295                    let raw = &all[bi * pj.rows()..(bi + 1) * pj.rows()];
2296                    apply_projected_gate(ao, raw, per_head, hd, cfg.gate_sigmoid);
2297                }
2298            }
2299        };
2300        pool.run_rows(b, &run);
2301        for bi in 0..b {
2302            let imp_len = (s0 + bi + 1).min(s_end);
2303            cache.accumulate_imp(&imp_all[bi * row..bi * row + imp_len]);
2304        }
2305        recycle_buf(&mut imp_all);
2306    }
2307    // Set when the device ran the head gate and the O projection too.
2308    let mut projected_out: Option<Vec<f32>> = None;
2309    if batched_attend {
2310        // Head-major pack for the device kernel: [b][nh·hd] -> [nh][b][hd].
2311        let mut done = false;
2312        if gpu_attend {
2313            let t_pack = std::time::Instant::now();
2314            let mut qhm = take_buf(nh * b * hd);
2315            for bi in 0..b {
2316                for h in 0..nh {
2317                    let src = &q_rope_all[bi * nh * hd + h * hd..bi * nh * hd + (h + 1) * hd];
2318                    qhm[h * b * hd + bi * hd..h * b * hd + (bi + 1) * hd].copy_from_slice(src);
2319                }
2320            }
2321            let t_dev = std::time::Instant::now();
2322            let w = if device_window { cfg.window.unwrap_or(0) } else { 0 };
2323            // The pipeline named the decode graph's device mirror of this
2324            // layer: append the chunk's rows to it and attend in place
2325            // (`chunk_attend_mirror`; the host rows above are the same
2326            // bits). Rows are positions there, so the host rows must be
2327            // contiguous positions: unevicted, from `base` on (a sliding
2328            // tail, `trim_window`, starts past 0).
2329            let host_base = cache.base();
2330            let mirror = crate::gpu::prefill_mirror()
2331                .filter(|_| cfg.gate_sigmoid && vd == hd && cfg.position == host_base + s0);
2332            // The matrix-unit attend casts Q, K and V to f16: its guard
2333            // takes max |x| over the chunk's queries and over every K/V row
2334            // the cache holds (those the attend reads among them).
2335            let pass_max =
2336                |i: usize| f32::from_bits(qkv_amax[i].load(std::sync::atomic::Ordering::Relaxed));
2337            let (k_max, v_max) = match mirror {
2338                // The chunk's rows were measured in the pool pass.
2339                Some(_) if pre_rotated => {
2340                    cache.kv_abs_max_after((s0, s0 + b, pass_max(1), pass_max(2)))
2341                }
2342                Some(_) => cache.kv_abs_max(),
2343                None => (f32::INFINITY, f32::INFINITY),
2344            };
2345            let q_max = if pre_rotated {
2346                pass_max(0)
2347            } else if mirror.is_some() {
2348                crate::gpu::abs_max_or_inf(&qhm)
2349            } else {
2350                f32::INFINITY
2351            };
2352            let operand_max = q_max.max(k_max).max(v_max);
2353            // The whole tail on the card when the O weight has a device GEMM:
2354            // the head gate (its gains taken here exactly as
2355            // `apply_projected_gate` takes them) and the O projection read
2356            // the attention output where it is. `CMF_PREFILL_WO_KEEP=0`
2357            // brings it home as before (A/B).
2358            // The card's scan of the O operand gives the host's product bit
2359            // for bit only while max |gated output| <= 1000
2360            // (`gpu_wgpu::chunk_attend_mirror_wo`). A softmax average of V
2361            // rows times a sigmoid gain is at most max |v| (times 1 + ~2^-10
2362            // for the f16 operands), so max |v| <= 990 vouches for it; past
2363            // that the output comes home. Spark-X2.5 only, as the mirror.
2364            let gains = match (projected_all.as_deref(), cfg.softplus_gate) {
2365                (Some(all), Some((proj, true))) if proj.rows() == nh => Some(Some(
2366                    all[..b * nh]
2367                        .iter()
2368                        .map(|&g| projected_gate_gain(g, cfg.gate_sigmoid))
2369                        .collect::<Vec<f32>>(),
2370                )),
2371                (None, None) => Some(None),
2372                _ => None,
2373            };
2374            if let (Some(t), Some(gains), Some(wo_dev)) = (
2375                mirror,
2376                gains.filter(|_| {
2377                    !cfg.output_gate
2378                        && v_max <= 990.0
2379                        && std::env::var("CMF_PREFILL_WO_KEEP").as_deref() != Ok("0")
2380                }),
2381                wo.mapped_device_gemm(),
2382            ) {
2383                let mut o = vec![0.0f32; b * cfg.hidden_size];
2384                if crate::gpu::chunk_attend_mirror_wo(
2385                    t,
2386                    cache.k_heads(),
2387                    cache.v_heads(),
2388                    host_base,
2389                    &qhm,
2390                    b,
2391                    cfg.position,
2392                    nh,
2393                    nkv,
2394                    hd,
2395                    cfg.scale,
2396                    cfg.window,
2397                    w,
2398                    operand_max,
2399                    gains.as_deref(),
2400                    wo_dev,
2401                    cfg.hidden_size,
2402                    &mut o,
2403                ) {
2404                    projected_out = Some(o);
2405                    done = true;
2406                }
2407            }
2408            if let Some(t) = mirror.filter(|_| !done) {
2409                done = crate::gpu::chunk_attend_mirror(
2410                    t,
2411                    cache.k_heads(),
2412                    cache.v_heads(),
2413                    host_base,
2414                    &qhm,
2415                    b,
2416                    cfg.position,
2417                    nh,
2418                    nkv,
2419                    hd,
2420                    cfg.scale,
2421                    cfg.window,
2422                    w,
2423                    operand_max,
2424                    &mut ao_all,
2425                );
2426            }
2427            if !done {
2428                if mirror.is_some() {
2429                    MIRROR_UPLOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2430                }
2431                // Under a masking window only the rows the first query can
2432                // still see go up: `lo` is the oldest of them.
2433                let lo = if w > 0 { (s0 + 1).saturating_sub(w) } else { 0 };
2434                let ks: Vec<&[f32]> = (0..nkv).map(|g| &cache.head_keys(g)[lo * hd..]).collect();
2435                let vs: Vec<&[f32]> =
2436                    (0..nkv).map(|g| &cache.head_values(g)[lo * hd..]).collect();
2437                done = crate::gpu::chunk_attend_win(
2438                    &qhm,
2439                    &ks,
2440                    &vs,
2441                    b,
2442                    s0 - lo,
2443                    nh,
2444                    nkv,
2445                    hd,
2446                    cfg.scale,
2447                    w,
2448                    &mut ao_all,
2449                );
2450            }
2451            recycle_buf(&mut qhm);
2452            if attn_split_on() {
2453                let t_end = std::time::Instant::now();
2454                ATTN_SPLIT[4].fetch_add(
2455                    t_dev.duration_since(t_pack).as_nanos() as u64,
2456                    std::sync::atomic::Ordering::Relaxed,
2457                );
2458                ATTN_SPLIT[5].fetch_add(
2459                    t_end.duration_since(t_dev).as_nanos() as u64,
2460                    std::sync::atomic::Ordering::Relaxed,
2461                );
2462            }
2463        }
2464        #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
2465        if !done {
2466            cache.attend_chunk(
2467                &q_rope_all,
2468                b,
2469                s0,
2470                nh,
2471                heads_per_kv,
2472                hd,
2473                &mut ao_all,
2474                cfg.pool,
2475                cfg.scale,
2476                cfg.window,
2477            );
2478            done = true;
2479        }
2480        if !done {
2481            // Portable fallback. It exists so a device refusal can never
2482            // leave `ao_all` untouched: this path is chosen BEFORE the
2483            // per-position attend is skipped, and a CPU without a
2484            // micro-GEMM has no other batched attend to fall back to.
2485            let n = s0 + b;
2486            struct OutPtr(*mut f32);
2487            // SAFETY: workers own disjoint query ranges, so the writes
2488            // through this pointer never overlap.
2489            unsafe impl Send for OutPtr {}
2490            unsafe impl Sync for OutPtr {}
2491            impl OutPtr {
2492                fn at(&self, i: usize) -> *mut f32 {
2493                    unsafe { self.0.add(i) }
2494                }
2495            }
2496            let out_ptr = OutPtr(ao_all.as_mut_ptr());
2497            let (qr, sc) = (&q_rope_all, cfg.scale);
2498            let win = if device_window { cfg.window } else { None };
2499            let run = |start: usize, end: usize| {
2500                for bi in start..end {
2501                    let lim = s0 + bi + 1;
2502                    let lo = win.map_or(0, |w| lim.saturating_sub(w));
2503                    for h in 0..nh {
2504                        let kv = h / heads_per_kv;
2505                        let (ks, vs) = (cache.head_keys(kv), cache.head_values(kv));
2506                        if ks.len() < n * hd || vs.len() < n * hd {
2507                            continue;
2508                        }
2509                        let (ks, vs) = (&ks[lo * hd..], &vs[lo * hd..]);
2510                        let q = &qr[bi * nh * hd + h * hd..bi * nh * hd + (h + 1) * hd];
2511                        let mut probs = vec![0f32; lim - lo];
2512                        let mut mx = f32::NEG_INFINITY;
2513                        for (j, p) in probs.iter_mut().enumerate() {
2514                            let krow = &ks[j * hd..(j + 1) * hd];
2515                            let d: f32 = q.iter().zip(krow).map(|(&a, &b)| a * b).sum();
2516                            *p = d * sc;
2517                            mx = mx.max(*p);
2518                        }
2519                        let mut sum = 0f32;
2520                        for p in probs.iter_mut() {
2521                            *p = (*p - mx).exp();
2522                            sum += *p;
2523                        }
2524                        let inv = if sum > 0.0 { 1.0 / sum } else { 0.0 };
2525                        let base = bi * nh * hd + h * hd;
2526                        for d in 0..hd {
2527                            let mut acc = 0f32;
2528                            for (j, &p) in probs.iter().enumerate() {
2529                                acc += p * vs[j * hd + d];
2530                            }
2531                            // SAFETY: workers own disjoint query ranges.
2532                            unsafe { *out_ptr.at(base + d) = acc * inv };
2533                        }
2534                    }
2535                }
2536            };
2537            match cfg.pool {
2538                Some(p) => p.run_rows(b, &run),
2539                None => run(0, b),
2540            }
2541        }
2542        if cfg.output_gate && projected_out.is_none() {
2543            apply_gate(&mut ao_all, &gates_all);
2544        }
2545        if let (Some(all), Some((proj, per_head)), None) =
2546            (projected_all.as_deref(), cfg.softplus_gate, projected_out.as_ref())
2547        {
2548            for bi in 0..b {
2549                apply_projected_gate(
2550                    &mut ao_all[bi * nh * hd..(bi + 1) * nh * hd],
2551                    &all[bi * proj.rows()..(bi + 1) * proj.rows()],
2552                    per_head,
2553                    hd,
2554                    cfg.gate_sigmoid,
2555                );
2556            }
2557        }
2558    }
2559    recycle_buf(&mut q_rope_all);
2560    recycle_buf(&mut gates_all);
2561    drop(prof_attend);
2562    let split_t3 = std::time::Instant::now();
2563
2564    // ── chunk-GEMM output projection ──
2565    // V narrower than the head width: drop every head's (zero) pad dims so
2566    // o_proj reads b × nh·v_head_dim.
2567    let mut ao_all = compact_heads(ao_all, nh, hd, vd);
2568    let out = match projected_out {
2569        Some(o) => o,
2570        None => {
2571            let mut out = vec![0.0f32; b * cfg.hidden_size];
2572            wo.matmat(&ao_all, b, &mut out, cfg.pool);
2573            out
2574        }
2575    };
2576    if attn_split_on() {
2577        let t4 = std::time::Instant::now();
2578        for (i, (a, z)) in [(split_t0, split_t1), (split_t1, split_t2), (split_t2, split_t3), (split_t3, t4)]
2579            .into_iter()
2580            .enumerate()
2581        {
2582            ATTN_SPLIT[i].fetch_add(
2583                z.duration_since(a).as_nanos() as u64,
2584                std::sync::atomic::Ordering::Relaxed,
2585            );
2586        }
2587    }
2588    recycle_buf(&mut q_all);
2589    recycle_buf(&mut k_all);
2590    recycle_buf(&mut v_all);
2591    recycle_buf(&mut ao_all);
2592    if let Some(mut values) = projected_all.take() {
2593        recycle_buf(&mut values);
2594    }
2595    // A chunk that ends exactly on the deferred barrier holds only exact
2596    // rows: it ran batched, and the layer converts here, as the row path
2597    // does after its boundary row. A layer awaiting its exact rows is sealed
2598    // by the pipeline once every far-field layer holds them.
2599    if !cache.o1_await_keep
2600        && cache
2601            .o1_pending_boundary()
2602            .is_some_and(|target| cache.seq_len >= target)
2603    {
2604        if let Err(err) = cache.o1_seal_checked(nh) {
2605            cache.o1_abort(err);
2606        }
2607    }
2608    out
2609}
2610
2611/// Block-diffusion preview (Clover): every row of the block attends the
2612/// whole committed prefix AND every row of the block, itself and the
2613/// rows after it included — the denoiser is bidirectional inside the
2614/// block. The block's rows are appended for the attend and dropped again,
2615/// so the cache leaves exactly as it came: the preview never commits.
2616/// Projections, the output gate, qk-norm and RoPE are those of
2617/// `qwen_attention_batch`; only the visibility differs.
2618#[allow(clippy::too_many_arguments)]
2619pub(crate) fn qwen_attention_preview(
2620    normed_all: &[f32],
2621    b: usize,
2622    wq: &QTensor,
2623    wk: &QTensor,
2624    wv: &QTensor,
2625    wo: &QTensor,
2626    cache: &mut LayerKvCache,
2627    cfg: &QwenAttnCfg,
2628) -> Vec<f32> {
2629    let (nh, nkv, hd) = (cfg.num_heads, cfg.num_kv_heads, cfg.head_dim);
2630    let heads_per_kv = nh / nkv;
2631    let qrows = wq.rows();
2632    assert_eq!(cfg.v_head_dim, hd, "block preview: V heads narrower than Q/K");
2633    assert!(cfg.softplus_gate.is_none() && cache.o1.is_none() && cache.sinks.is_none());
2634    assert!(cfg.value_in.is_none(), "block preview: V with rows of its own");
2635    let mut q_all = take_buf(b * qrows);
2636    let mut k_all = take_buf(b * nkv * hd);
2637    let mut v_all = take_buf(b * nkv * hd);
2638    wq.matmat(normed_all, b, &mut q_all, cfg.pool);
2639    wk.matmat(normed_all, b, &mut k_all, cfg.pool);
2640    wv.matmat(normed_all, b, &mut v_all, cfg.pool);
2641    let mut q_rope = take_buf(b * nh * hd);
2642    let mut gates = if cfg.output_gate { take_buf(b * nh * hd) } else { Vec::new() };
2643    for bi in 0..b {
2644        let q_raw = &q_all[bi * qrows..(bi + 1) * qrows];
2645        let q = &mut q_rope[bi * nh * hd..(bi + 1) * nh * hd];
2646        if cfg.output_gate {
2647            // Per-head [q(hd); gate(hd)], as in `qwen_attention_batch`.
2648            for h in 0..nh {
2649                q[h * hd..(h + 1) * hd].copy_from_slice(&q_raw[2 * h * hd..(2 * h + 1) * hd]);
2650                gates[(bi * nh + h) * hd..(bi * nh + h + 1) * hd]
2651                    .copy_from_slice(&q_raw[(2 * h + 1) * hd..(2 * h + 2) * hd]);
2652            }
2653        } else {
2654            q.copy_from_slice(&q_raw[..nh * hd]);
2655        }
2656        let kv = bi * nkv * hd..(bi + 1) * nkv * hd;
2657        if let Some((bq, bk, bv)) = cfg.bias {
2658            for (x, bb) in q.iter_mut().zip(bq) {
2659                *x += bb;
2660            }
2661            for (x, bb) in k_all[kv.clone()].iter_mut().zip(bk) {
2662                *x += bb;
2663            }
2664            for (x, bb) in v_all[kv.clone()].iter_mut().zip(bv) {
2665                *x += bb;
2666            }
2667        }
2668        qk_norm_and_rope(cfg, q, &mut k_all[kv.clone()], nh, nkv, hd, cfg.position + bi);
2669        cache.append(&k_all[kv.clone()], &v_all[kv], &[]);
2670    }
2671    // Every row sees every stored row: the attend of a decode step taken
2672    // after the whole block was appended.
2673    let stored = cache.seq_len;
2674    let mut ao_all = take_buf(b * nh * hd);
2675    {
2676        let ao_p = crate::pool::SendMut::new(ao_all.as_mut_ptr());
2677        let (qr, cache_ref) = (&q_rope, &*cache);
2678        let run = |b0: usize, b1: usize| {
2679            let mut imp = take_buf(stored);
2680            for bi in b0..b1 {
2681                // SAFETY: row bi owns ao[bi·nh·hd..(bi+1)·nh·hd].
2682                let ao = unsafe { std::slice::from_raw_parts_mut(ao_p.at(bi * nh * hd), nh * hd) };
2683                attend_all_heads_upto(
2684                    &qr[bi * nh * hd..(bi + 1) * nh * hd],
2685                    cache_ref,
2686                    nh,
2687                    heads_per_kv,
2688                    hd,
2689                    cfg.scale,
2690                    None,
2691                    cfg.softcap,
2692                    usize::MAX,
2693                    ao,
2694                    &mut imp,
2695                );
2696            }
2697            recycle_buf(&mut imp);
2698        };
2699        match cfg.pool {
2700            Some(p) if b > 1 => p.run_rows(b, &run),
2701            _ => run(0, b),
2702        }
2703    }
2704    cache.truncate_last(b);
2705    if cfg.output_gate {
2706        apply_gate(&mut ao_all, &gates);
2707    }
2708    let mut out = take_buf(b * cfg.hidden_size);
2709    wo.matmat(&ao_all, b, &mut out, cfg.pool);
2710    for buf in [&mut q_all, &mut k_all, &mut v_all, &mut q_rope, &mut gates, &mut ao_all] {
2711        recycle_buf(buf);
2712    }
2713    out
2714}
2715
2716/// Dense GQA attention for one DECODE position on a SEALED O(1) layer:
2717/// projection / qk-norm / partial RoPE / output gate are identical to
2718/// `qwen_attention`, but the KV cache is replaced by per-KV-group
2719/// streaming Nyström states (exact window + permanent sinks + landmark
2720/// skeleton, shared across the group's Q heads). Head masks don't
2721/// apply — the o1 path is dense, like the masked-on-quantized fallback.
2722#[allow(clippy::too_many_arguments)]
2723pub fn qwen_attention_nystrom(
2724    hidden: &[f32],
2725    wq: &QTensor,
2726    wk: &QTensor,
2727    wv: &QTensor,
2728    wo: &QTensor,
2729    cache: &mut LayerKvCache,
2730    cfg: &QwenAttnCfg,
2731) -> Vec<f32> {
2732    check_v_width(cfg);
2733    let p = project_position(hidden, wq, wk, wv, cfg, cfg.position);
2734    let mut projected = projected_gate(hidden, cfg);
2735    let ao = cache.o1_step(&p.q, &p.k, &p.v, cfg.num_heads);
2736    // (p.v was padded to head_dim; drop the zero pad dims again.)
2737    let mut ao = compact_heads(ao, cfg.num_heads, cfg.head_dim, cfg.v_head_dim);
2738    if std::env::var("CMF_O1_TRACE").is_ok() {
2739        eprintln!(
2740            "o1-trace cpu attn[..8] = {:?} (q[..4]={:?} k[..4]={:?})",
2741            &ao[..8],
2742            &p.q[..4],
2743            &p.k[..4]
2744        );
2745    }
2746    if cfg.output_gate {
2747        apply_gate(&mut ao, &p.gate);
2748    }
2749    if let (Some(raw), Some((_, per_head))) = (projected.as_deref(), cfg.softplus_gate) {
2750        apply_projected_gate(&mut ao, raw, per_head, cfg.head_dim, cfg.gate_sigmoid);
2751    }
2752    let mut out = vec![0.0f32; cfg.hidden_size];
2753    wo.matvec(&ao, &mut out, cfg.pool);
2754    if let Some(mut gate) = projected.take() {
2755        recycle_buf(&mut gate);
2756    }
2757    out
2758}
2759
2760/// Fused two-position dense attention (speculative verify): projections
2761/// stream the weights once via `matvec2`; attention runs sequentially
2762/// (causal dependency through the cache).
2763#[allow(clippy::too_many_arguments)]
2764pub fn qwen_attention_pair(
2765    h1: &[f32],
2766    h2: &[f32],
2767    wq: &QTensor,
2768    wk: &QTensor,
2769    wv: &QTensor,
2770    wo: &QTensor,
2771    cache: &mut LayerKvCache,
2772    cfg: &QwenAttnCfg,
2773) -> (Vec<f32>, Vec<f32>) {
2774    let (nh, nkv, hd) = (cfg.num_heads, cfg.num_kv_heads, cfg.head_dim);
2775    let heads_per_kv = nh / nkv;
2776    check_v_width(cfg);
2777    let vd = cfg.v_head_dim;
2778
2779    // Preserve causal ordering across a deferred boundary. The ordinary
2780    // pair kernel is exact-only and would append both rows before a seal;
2781    // sequential dispatch lets row B convert and row B+1 use Nyström.
2782    if cache.o1_sealed()
2783        || cache.o1_boundary_crossed_by(2)
2784        || cache
2785            .o1_pending_boundary()
2786            .is_some_and(|target| cache.seq_len + 2 == target)
2787        // V with rows of its own: the fused pair job projects q|k|v from one row.
2788        || cfg.value_in.is_some()
2789    {
2790        let hs = cfg.hidden_size;
2791        let mut cfg1 = *cfg;
2792        cfg1.position = cfg.position;
2793        cfg1.value_in = cfg.value_in.map(|v| &v[..hs]);
2794        let mut cfg2 = *cfg;
2795        cfg2.position = cfg.position + 1;
2796        cfg2.value_in = cfg.value_in.map(|v| &v[hs..2 * hs]);
2797        return (
2798            qwen_attention(h1, wq, wk, wv, wo, cache, &cfg1),
2799            qwen_attention(h2, wq, wk, wv, wo, cache, &cfg2),
2800        );
2801    }
2802
2803    // Fused projections (one weight pass for both positions) — Q, K
2804    // and V under a single pool dispatch (multi-matrix pair job).
2805    let mut q1r = take_buf(wq.rows());
2806    let mut q2r = take_buf(wq.rows());
2807    let mut k1 = take_buf(nkv * hd);
2808    let mut k2 = take_buf(nkv * hd);
2809    let mut v1 = take_buf(nkv * vd);
2810    let mut v2 = take_buf(nkv * vd);
2811    QTensor::matvec2_many(
2812        [wq, wk, wv],
2813        h1,
2814        h2,
2815        [q1r.as_mut_slice(), k1.as_mut_slice(), v1.as_mut_slice()],
2816        [q2r.as_mut_slice(), k2.as_mut_slice(), v2.as_mut_slice()],
2817        cfg.pool,
2818    );
2819    if let Some((bq, bk, bv)) = cfg.bias {
2820        for lane in [(&mut q1r, &mut k1, &mut v1), (&mut q2r, &mut k2, &mut v2)] {
2821            for (x, b) in lane.0.iter_mut().zip(bq) {
2822                *x += b;
2823            }
2824            for (x, b) in lane.1.iter_mut().zip(bk) {
2825                *x += b;
2826            }
2827            for (x, b) in lane.2.iter_mut().zip(bv) {
2828                *x += b;
2829            }
2830        }
2831    }
2832
2833    let finish = |mut q_raw: Vec<f32>, k: &mut [f32], pos: usize| -> (Vec<f32>, Vec<f32>) {
2834        // split + norms + rope, reusing the single-position logic shape
2835        let (mut q, mut gate) = if cfg.output_gate {
2836            let mut qn = take_buf(nh * hd);
2837            let mut g = take_buf(nh * hd);
2838            for h in 0..nh {
2839                let src = h * hd * 2;
2840                let dst = h * hd;
2841                qn[dst..dst + hd].copy_from_slice(&q_raw[src..src + hd]);
2842                g[dst..dst + hd].copy_from_slice(&q_raw[src + hd..src + 2 * hd]);
2843            }
2844            recycle_buf(&mut q_raw);
2845            (qn, g)
2846        } else {
2847            (q_raw, Vec::new())
2848        };
2849        qk_norm_and_rope(cfg, &mut q, k, nh, nkv, hd, pos);
2850        let _ = &mut gate;
2851        (q, gate)
2852    };
2853
2854    let (mut qa, mut gate1) = finish(q1r, &mut k1, cfg.position);
2855    let (mut qb, mut gate2) = finish(q2r, &mut k2, cfg.position + 1);
2856    // V-norm (gemma-4): the closure covers q/k; V is normalized here or
2857    // the pair prefill caches raw V while singles cache normalized.
2858    if cfg.v_norm {
2859        for g in 0..nkv {
2860            vnorm_head(&mut v1[g * vd..g * vd + vd], cfg.rms_eps);
2861            vnorm_head(&mut v2[g * vd..g * vd + vd], cfg.rms_eps);
2862        }
2863    }
2864    // V narrower than the head width: zero-pad each head for the cache.
2865    let mut v1 = pad_heads(v1, nkv, vd, hd);
2866    let mut v2 = pad_heads(v2, nkv, vd, hd);
2867
2868    // O(1) prefill trace (see qwen_attention): lane order = position
2869    // order, so the collected buffer stays position-major.
2870    cache.o1_push_q(&qa);
2871    cache.o1_push_q(&qb);
2872    // Empty alive slice = every head alive (see qwen_attention).
2873    cache.append(&k1, &v1, &[]);
2874    let (mut a1, mut imp1) = attend_all_heads(
2875        &qa,
2876        cache,
2877        nh,
2878        heads_per_kv,
2879        hd,
2880        cfg.scale,
2881        cfg.window,
2882        cfg.softcap,
2883    );
2884    cache.accumulate_imp(&imp1);
2885
2886    cache.append(&k2, &v2, &[]);
2887    let (mut a2, mut imp2) = attend_all_heads(
2888        &qb,
2889        cache,
2890        nh,
2891        heads_per_kv,
2892        hd,
2893        cfg.scale,
2894        cfg.window,
2895        cfg.softcap,
2896    );
2897    cache.accumulate_imp(&imp2);
2898
2899    if cfg.output_gate {
2900        apply_gate(&mut a1, &gate1);
2901        apply_gate(&mut a2, &gate2);
2902    }
2903    if let Some((proj, per_head)) = cfg.softplus_gate {
2904        let mut g1 = take_buf(proj.rows());
2905        let mut g2 = take_buf(proj.rows());
2906        proj.matvec2(h1, h2, &mut g1, &mut g2, cfg.pool);
2907        apply_projected_gate(&mut a1, &g1, per_head, hd, cfg.gate_sigmoid);
2908        apply_projected_gate(&mut a2, &g2, per_head, hd, cfg.gate_sigmoid);
2909        recycle_buf(&mut g1);
2910        recycle_buf(&mut g2);
2911    }
2912
2913    // V narrower than the head width: o_proj reads nh·v_head_dim.
2914    let mut a1 = compact_heads(a1, nh, hd, vd);
2915    let mut a2 = compact_heads(a2, nh, hd, vd);
2916    let mut o1 = take_buf(cfg.hidden_size);
2917    let mut o2 = take_buf(cfg.hidden_size);
2918    wo.matvec2(&a1, &a2, &mut o1, &mut o2, cfg.pool);
2919    for b in [
2920        &mut qa, &mut qb, &mut gate1, &mut gate2, &mut k1, &mut k2, &mut v1, &mut v2, &mut a1,
2921        &mut a2, &mut imp1, &mut imp2,
2922    ] {
2923        recycle_buf(b);
2924    }
2925    (o1, o2)
2926}
2927
2928#[cfg(test)]
2929mod tests {
2930    use super::*;
2931    use crate::kv_cache::LayerKvCache;
2932
2933    fn gqa_cache(nkv: usize, hd: usize, rows: usize) -> LayerKvCache {
2934        let mut c = LayerKvCache::new(nkv, hd);
2935        c.mode = crate::kv_cache::KvMode::F32;
2936        for r in 0..rows {
2937            let k: Vec<f32> = (0..nkv * hd)
2938                .map(|i| (((r * 31 + i * 7) % 101) as f32 / 101.0 - 0.5) * 3.0)
2939                .collect();
2940            let v: Vec<f32> = (0..nkv * hd)
2941                .map(|i| (((r * 17 + i * 11) % 89) as f32 / 89.0 - 0.5) * 2.0)
2942                .collect();
2943            c.append(&k, &v, &[]);
2944        }
2945        c
2946    }
2947
2948    /// The pooled decode attend (one job over the heads) must equal the
2949    /// serial grouped kernel bit for bit — output AND importance — at the
2950    /// MiniCPM5 geometry (16 q-heads over 2 kv-heads, head_dim 128).
2951    #[test]
2952    fn pooled_attend_is_bit_identical_to_serial() {
2953        let (nh, nkv, hd) = (16usize, 2usize, 128usize);
2954        let pool = crate::pool::Pool::new(3);
2955        for rows in [7usize, 96, 300] {
2956            let mut cache = gqa_cache(nkv, hd, rows);
2957            let q: Vec<f32> = (0..nh * hd)
2958                .map(|i| (((i * 29) % 113) as f32 / 113.0 - 0.5) * 1.7)
2959                .collect();
2960            // Learned sinks (MiMo-V2 SWA layers) ride both kernels too.
2961            let sinks: Vec<f32> = (0..nh).map(|h| (h as f32 * 0.37).sin() * 3.0).collect();
2962            for sink in [None, Some(sinks)] {
2963                cache.sinks = sink.clone();
2964                for window in [None, Some(50usize)] {
2965                    let (a, ia) =
2966                        attend_all_heads(&q, &cache, nh, nh / nkv, hd, 0.088, window, 0.0);
2967                    let (b, ib) = attend_all_heads_pool(
2968                        &q,
2969                        &cache,
2970                        nh,
2971                        nh / nkv,
2972                        hd,
2973                        0.088,
2974                        window,
2975                        0.0,
2976                        Some(&pool),
2977                    );
2978                    let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
2979                    let s = sink.is_some();
2980                    assert_eq!(
2981                        bits(&a),
2982                        bits(&b),
2983                        "out rows={rows} window={window:?} sink={s}"
2984                    );
2985                    assert_eq!(
2986                        bits(&ia),
2987                        bits(&ib),
2988                        "imp rows={rows} window={window:?} sink={s}"
2989                    );
2990                }
2991            }
2992        }
2993    }
2994
2995    /// The capped (parallel-prefill) attend equals the incremental one for
2996    /// a sliding window with learned sinks as well.
2997    #[test]
2998    fn capped_attend_with_sinks_and_window_equals_incremental() {
2999        let (nh, nkv, hd) = (6usize, 2usize, 16usize);
3000        let total = 20usize;
3001        let sinks: Vec<f32> = (0..nh).map(|h| h as f32 * 0.6 - 1.5).collect();
3002        let mut full = gqa_cache(nkv, hd, total);
3003        full.sinks = Some(sinks.clone());
3004        for upto in [1usize, 2, 3, 4, 11, 20] {
3005            let mut partial = gqa_cache(nkv, hd, upto);
3006            partial.sinks = Some(sinks.clone());
3007            let q: Vec<f32> = (0..nh * hd)
3008                .map(|i| (((i * 41 + upto) % 89) as f32 / 89.0 - 0.5) * 2.3)
3009                .collect();
3010            let (a, ia) = attend_all_heads(&q, &partial, nh, nh / nkv, hd, 0.25, Some(3), 0.0);
3011            let mut b = vec![0f32; nh * hd];
3012            let mut ib = vec![0f32; upto];
3013            attend_all_heads_upto(
3014                &q,
3015                &full,
3016                nh,
3017                nh / nkv,
3018                hd,
3019                0.25,
3020                Some(3),
3021                0.0,
3022                upto,
3023                &mut b,
3024                &mut ib,
3025            );
3026            let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
3027            assert_eq!(bits(&a), bits(&b), "out upto={upto}");
3028            assert_eq!(bits(&ia), bits(&ib), "imp upto={upto}");
3029        }
3030    }
3031
3032    /// MiMo-V2-shaped layer config: 4 Q heads over `nkv` KV heads, head_dim
3033    /// 8, V heads 4 wide, partial rotary 4, optional window and sinks.
3034    #[allow(clippy::too_many_arguments)]
3035    fn narrow_cfg<'a>(
3036        nkv: usize,
3037        inv: &'a [f32],
3038        position: usize,
3039        window: Option<usize>,
3040        pool: Option<&'a crate::pool::Pool>,
3041    ) -> QwenAttnCfg<'a> {
3042        QwenAttnCfg {
3043            mrope: None,
3044            num_heads: 4,
3045            num_kv_heads: nkv,
3046            head_dim: 8,
3047            hidden_size: 16,
3048            position,
3049            inv_freq: inv,
3050            rotary_dim: 4,
3051            scale: 1.0 / (8f32).sqrt(),
3052            softcap: 0.0,
3053            window,
3054            v_norm: false,
3055            qk_norm_after_rope: false,
3056            gate_sigmoid: false,
3057            q_norm: None,
3058            k_norm: None,
3059            output_gate: false,
3060            softplus_gate: None,
3061            rope_scale: 1.0,
3062            bias: None,
3063            rms_eps: 1e-6,
3064            norm_style: cortiq_core::NormStyle::Qwen,
3065            pool,
3066            v_head_dim: 4,
3067            value_in: None,
3068        }
3069    }
3070
3071    #[test]
3072    fn no_rope_layer_skips_global_frequency_table() {
3073        // Recursive Flint keeps the normal global frequency table in the
3074        // pipeline, but its full-attention layers have rotary_dim=0.  A
3075        // no-RoPE layer must be an identity transform, not a zero-width
3076        // slice passed to every entry in that table.
3077        let (nh, nkv, hd) = (2usize, 1usize, 8usize);
3078        let inv = rope_inv_freq(hd, 10_000.0);
3079        let cfg = QwenAttnCfg {
3080            mrope: None,
3081            num_heads: nh,
3082            num_kv_heads: nkv,
3083            head_dim: hd,
3084            hidden_size: nh * hd,
3085            position: 17,
3086            inv_freq: &inv,
3087            rotary_dim: 0,
3088            scale: 1.0 / (hd as f32).sqrt(),
3089            softcap: 0.0,
3090            window: None,
3091            v_norm: false,
3092            qk_norm_after_rope: false,
3093            gate_sigmoid: false,
3094            q_norm: None,
3095            k_norm: None,
3096            output_gate: false,
3097            softplus_gate: None,
3098            rope_scale: 1.0,
3099            bias: None,
3100            rms_eps: 1e-6,
3101            norm_style: cortiq_core::NormStyle::Qwen,
3102            pool: None,
3103            v_head_dim: hd,
3104            value_in: None,
3105        };
3106        let mut q: Vec<f32> = (0..nh * hd).map(|i| i as f32 - 7.5).collect();
3107        let mut k: Vec<f32> = (0..nkv * hd).map(|i| i as f32 * 0.25 - 1.0).collect();
3108        let q_before = q.clone();
3109        let k_before = k.clone();
3110        qk_norm_and_rope(&cfg, &mut q, &mut k, nh, nkv, hd, cfg.position);
3111        assert_eq!(q, q_before);
3112        assert_eq!(k, k_before);
3113    }
3114
3115    /// V heads narrower than Q/K (MiMo-V2: 128 vs 192): the padded-cache /
3116    /// compacted-output path must equal a direct reference that never pads
3117    /// — native vd-wide V rows, per-head softmax (with the window and the
3118    /// learned sink), o_proj over nh·vd — to < 1e-6, position by position.
3119    #[test]
3120    fn narrow_v_attention_matches_direct_reference() {
3121        let (nh, hd, vd, hs, rd) = (4usize, 8usize, 4usize, 16usize, 4usize);
3122        let inv = rope_inv_freq(rd, 10_000.0);
3123        for (nkv, window, sinks) in [
3124            (1usize, None, None),
3125            (2, Some(3usize), Some(vec![0.4f32, -1.0, 2.0, 0.1])),
3126            (2, None, Some(vec![-0.3f32, 0.9, 0.0, 1.7])),
3127        ] {
3128            let hpk = nh / nkv;
3129            let wq = synth(nh * hd, hs, 11);
3130            let wk = synth(nkv * hd, hs, 12);
3131            let wv = synth(nkv * vd, hs, 13);
3132            let wo = synth(hs, nh * vd, 14);
3133            let (fq, fk, fv, fo) = (
3134                wq.as_f32().unwrap().to_vec(),
3135                wk.as_f32().unwrap().to_vec(),
3136                wv.as_f32().unwrap().to_vec(),
3137                wo.as_f32().unwrap().to_vec(),
3138            );
3139            let mut cache = LayerKvCache::new(nkv, hd);
3140            cache.mode = crate::kv_cache::KvMode::F32;
3141            cache.sinks = sinks.clone();
3142            // Reference state: rotated keys and NATIVE-width values.
3143            let mut ref_k: Vec<Vec<f32>> = Vec::new();
3144            let mut ref_v: Vec<Vec<f64>> = Vec::new();
3145            for pos in 0..7usize {
3146                let x: Vec<f32> = (0..hs)
3147                    .map(|i| ((i as f32 + 1.0) * (pos as f32 + 0.5) * 0.37).sin())
3148                    .collect();
3149                let got = qwen_attention(
3150                    &x,
3151                    &wq,
3152                    &wk,
3153                    &wv,
3154                    &wo,
3155                    &mut cache,
3156                    &narrow_cfg(nkv, &inv, pos, window, None),
3157                );
3158                // ── direct reference ──
3159                let mv = |w: &[f32], rows: usize| -> Vec<f32> {
3160                    (0..rows)
3161                        .map(|r| (0..hs).map(|j| w[r * hs + j] * x[j]).sum::<f32>())
3162                        .collect()
3163                };
3164                let mut q = mv(&fq, nh * hd);
3165                let mut k = mv(&fk, nkv * hd);
3166                let v = mv(&fv, nkv * vd);
3167                for h in 0..nh {
3168                    rope_rotate(&mut q[h * hd..h * hd + rd], pos, &inv);
3169                }
3170                for g in 0..nkv {
3171                    rope_rotate(&mut k[g * hd..g * hd + rd], pos, &inv);
3172                }
3173                ref_k.push(k);
3174                ref_v.push(v.iter().map(|&a| a as f64).collect());
3175                let stored = pos + 1;
3176                let first = window.map(|w| stored.saturating_sub(w)).unwrap_or(0);
3177                let mut ao = vec![0f64; nh * vd];
3178                for h in 0..nh {
3179                    let g = h / hpk;
3180                    let mut z: Vec<f64> = (first..stored)
3181                        .map(|p| {
3182                            (0..hd)
3183                                .map(|d| q[h * hd + d] as f64 * ref_k[p][g * hd + d] as f64)
3184                                .sum::<f64>()
3185                                / (hd as f64).sqrt()
3186                        })
3187                        .collect();
3188                    if let Some(s) = &sinks {
3189                        z.push(s[h] as f64);
3190                    }
3191                    let m = z.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
3192                    let e: Vec<f64> = z.iter().map(|&a| (a - m).exp()).collect();
3193                    let sum: f64 = e.iter().sum();
3194                    for (j, p) in (first..stored).enumerate() {
3195                        for d in 0..vd {
3196                            ao[h * vd + d] += e[j] / sum * ref_v[p][g * vd + d];
3197                        }
3198                    }
3199                }
3200                for i in 0..hs {
3201                    let want: f64 = (0..nh * vd)
3202                        .map(|j| fo[i * nh * vd + j] as f64 * ao[j])
3203                        .sum();
3204                    assert!(
3205                        (got[i] as f64 - want).abs() < 1e-6,
3206                        "nkv {nkv} window {window:?} sinks {} pos {pos} out[{i}]: {} vs {want}",
3207                        sinks.is_some(),
3208                        got[i]
3209                    );
3210                }
3211            }
3212            // The cache holds V padded to head_dim with exact zeros.
3213            for g in 0..nkv {
3214                let vals = cache.head_values(g);
3215                assert_eq!(vals.len(), 7 * hd);
3216                for p in 0..7 {
3217                    assert!(vals[p * hd + vd..(p + 1) * hd].iter().all(|&x| x == 0.0));
3218                    for d in 0..vd {
3219                        assert_eq!(vals[p * hd + d] as f64, ref_v[p][g * vd + d]);
3220                    }
3221                }
3222            }
3223        }
3224    }
3225
3226    /// The batched-chunk and the fused-pair attention paths reach the same
3227    /// narrow-V / sink / window layer: both must be bit-identical to the
3228    /// single-position path (same kernels, same order).
3229    #[test]
3230    fn narrow_v_batch_and_pair_equal_singles() {
3231        let (hd, vd, hs, rd) = (8usize, 4usize, 16usize, 4usize);
3232        let inv = rope_inv_freq(rd, 10_000.0);
3233        let nkv = 2usize;
3234        let wq = synth(4 * hd, hs, 21);
3235        let wk = synth(nkv * hd, hs, 22);
3236        let wv = synth(nkv * vd, hs, 23);
3237        let wo = synth(hs, 4 * vd, 24);
3238        let sinks = Some(vec![0.3f32, -0.8, 1.2, 0.0]);
3239        let xs: Vec<Vec<f32>> = (0..9)
3240            .map(|p| {
3241                (0..hs)
3242                    .map(|i| ((i * 3 + p * 5) as f32 * 0.21).cos())
3243                    .collect()
3244            })
3245            .collect();
3246        let fresh = || {
3247            let mut c = LayerKvCache::new(nkv, hd);
3248            c.mode = crate::kv_cache::KvMode::F32;
3249            c.sinks = sinks.clone();
3250            c
3251        };
3252        let pool = crate::pool::Pool::new(2);
3253        for pool in [None, Some(&pool)] {
3254            for window in [None, Some(3usize)] {
3255                let mut c1 = fresh();
3256                let singles: Vec<Vec<f32>> = (0..xs.len())
3257                    .map(|p| {
3258                        qwen_attention(
3259                            &xs[p],
3260                            &wq,
3261                            &wk,
3262                            &wv,
3263                            &wo,
3264                            &mut c1,
3265                            &narrow_cfg(nkv, &inv, p, window, pool),
3266                        )
3267                    })
3268                    .collect();
3269                // Batched chunks of 4 + 5 positions.
3270                let mut c2 = fresh();
3271                let mut batched = Vec::new();
3272                for (p0, n) in [(0usize, 4usize), (4, 5)] {
3273                    let flat: Vec<f32> = xs[p0..p0 + n].iter().flatten().copied().collect();
3274                    let out = qwen_attention_batch(
3275                        &flat,
3276                        n,
3277                        &wq,
3278                        &wk,
3279                        &wv,
3280                        &wo,
3281                        &mut c2,
3282                        &narrow_cfg(nkv, &inv, p0, window, pool),
3283                    );
3284                    for bi in 0..n {
3285                        batched.push(out[bi * hs..(bi + 1) * hs].to_vec());
3286                    }
3287                }
3288                // Pairs (the last position single).
3289                let mut c3 = fresh();
3290                let mut paired = Vec::new();
3291                for p in (0..8).step_by(2) {
3292                    let (a, b) = qwen_attention_pair(
3293                        &xs[p],
3294                        &xs[p + 1],
3295                        &wq,
3296                        &wk,
3297                        &wv,
3298                        &wo,
3299                        &mut c3,
3300                        &narrow_cfg(nkv, &inv, p, window, pool),
3301                    );
3302                    paired.push(a);
3303                    paired.push(b);
3304                }
3305                paired.push(qwen_attention(
3306                    &xs[8],
3307                    &wq,
3308                    &wk,
3309                    &wv,
3310                    &wo,
3311                    &mut c3,
3312                    &narrow_cfg(nkv, &inv, 8, window, pool),
3313                ));
3314                let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
3315                for p in 0..xs.len() {
3316                    let w = window;
3317                    let pl = pool.is_some();
3318                    assert_eq!(
3319                        bits(&singles[p]),
3320                        bits(&batched[p]),
3321                        "batch p{p} w{w:?} pool {pl}"
3322                    );
3323                    assert_eq!(
3324                        bits(&singles[p]),
3325                        bits(&paired[p]),
3326                        "pair p{p} w{w:?} pool {pl}"
3327                    );
3328                }
3329                assert_eq!(c1.head_values(0), c2.head_values(0));
3330                assert_eq!(c1.head_values(1), c3.head_values(1));
3331            }
3332        }
3333    }
3334
3335    /// A position attended after the whole chunk was appended, capped at
3336    /// the rows it could see (`upto`), equals attending right after its
3337    /// own append — the contract of the parallel prefill attend.
3338    #[test]
3339    fn capped_attend_equals_incremental_attend() {
3340        let (nh, nkv, hd) = (8usize, 2usize, 64usize);
3341        let total = 40usize;
3342        let full = gqa_cache(nkv, hd, total);
3343        for upto in [1usize, 5, 23, 40] {
3344            let partial = gqa_cache(nkv, hd, upto);
3345            let q: Vec<f32> = (0..nh * hd)
3346                .map(|i| (((i * 37 + upto) % 97) as f32 / 97.0 - 0.5) * 2.1)
3347                .collect();
3348            let (a, ia) = attend_all_heads(&q, &partial, nh, nh / nkv, hd, 0.125, None, 0.0);
3349            let mut b = vec![0f32; nh * hd];
3350            let mut ib = vec![0f32; upto];
3351            attend_all_heads_upto(
3352                &q,
3353                &full,
3354                nh,
3355                nh / nkv,
3356                hd,
3357                0.125,
3358                None,
3359                0.0,
3360                upto,
3361                &mut b,
3362                &mut ib,
3363            );
3364            let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
3365            assert_eq!(bits(&a), bits(&b), "out upto={upto}");
3366            assert_eq!(bits(&ia), bits(&ib), "imp upto={upto}");
3367        }
3368    }
3369
3370    fn synth(rows: usize, cols: usize, salt: usize) -> QTensor {
3371        QTensor::from_f32(
3372            (0..rows * cols)
3373                .map(|i| (((i * 13 + salt * 7) % 97) as f32 / 97.0 - 0.5) * 0.4)
3374                .collect(),
3375            rows,
3376            cols,
3377        )
3378    }
3379
3380    /// Every projection path must apply identical semantics: the pair
3381    /// path (prefill / speculative verify) once missed the q/k/v bias
3382    /// while singles had it — healthy PPL, garbage generation.
3383    #[test]
3384    fn pair_with_bias_matches_two_singles() {
3385        let (nh, nkv, hd, hs) = (2usize, 1usize, 4usize, 8usize);
3386        let wq = synth(nh * hd, hs, 1);
3387        let wk = synth(nkv * hd, hs, 2);
3388        let wv = synth(nkv * hd, hs, 3);
3389        let wo = synth(hs, nh * hd, 4);
3390        let bq: Vec<f32> = (0..nh * hd).map(|i| 0.1 + 0.01 * i as f32).collect();
3391        let bk: Vec<f32> = (0..nkv * hd).map(|i| -0.2 + 0.02 * i as f32).collect();
3392        let bv: Vec<f32> = (0..nkv * hd).map(|i| 0.05 * i as f32).collect();
3393        let inv = rope_inv_freq(hd, 10_000.0);
3394        let cfg = |position| QwenAttnCfg {
3395            mrope: None,
3396            num_heads: nh,
3397            num_kv_heads: nkv,
3398            head_dim: hd,
3399            hidden_size: hs,
3400            position,
3401            inv_freq: &inv,
3402            rotary_dim: hd,
3403            scale: 1.0 / (hd as f32).sqrt(),
3404            softcap: 0.0,
3405            window: None,
3406            v_norm: false,
3407            qk_norm_after_rope: false,
3408            gate_sigmoid: false,
3409            q_norm: None,
3410            k_norm: None,
3411            output_gate: false,
3412            softplus_gate: None,
3413            rope_scale: 1.0,
3414            bias: Some((&bq, &bk, &bv)),
3415            rms_eps: 1e-6,
3416            norm_style: cortiq_core::NormStyle::Qwen,
3417            pool: None,
3418            v_head_dim: hd,
3419            value_in: None,
3420        };
3421        let h1: Vec<f32> = (0..hs).map(|i| (i as f32 * 0.3).sin()).collect();
3422        let h2: Vec<f32> = (0..hs).map(|i| (i as f32 * 0.7).cos()).collect();
3423
3424        let mut c_ref = LayerKvCache::new(nkv, hd);
3425        let r1 = qwen_attention(&h1, &wq, &wk, &wv, &wo, &mut c_ref, &cfg(0));
3426        let r2 = qwen_attention(&h2, &wq, &wk, &wv, &wo, &mut c_ref, &cfg(1));
3427
3428        let mut c = LayerKvCache::new(nkv, hd);
3429        let (p1, p2) = qwen_attention_pair(&h1, &h2, &wq, &wk, &wv, &wo, &mut c, &cfg(0));
3430        for (a, b) in r1.iter().zip(&p1) {
3431            assert!((a - b).abs() < 1e-5, "lane1 {a} vs {b}");
3432        }
3433        for (a, b) in r2.iter().zip(&p2) {
3434            assert!((a - b).abs() < 1e-5, "lane2 {a} vs {b}");
3435        }
3436    }
3437
3438    /// gemma-4 V-norm: the pair path once normalized q/k but cached RAW
3439    /// V — healthy singles, diverging pair prefill.
3440    #[test]
3441    fn pair_with_v_norm_matches_two_singles() {
3442        let (nh, nkv, hd, hs) = (2usize, 1usize, 4usize, 8usize);
3443        let wq = synth(nh * hd, hs, 5);
3444        let wk = synth(nkv * hd, hs, 6);
3445        let wv = synth(nkv * hd, hs, 7);
3446        let wo = synth(hs, nh * hd, 8);
3447        let inv = rope_inv_freq(hd, 10_000.0);
3448        let cfg = |position| QwenAttnCfg {
3449            mrope: None,
3450            num_heads: nh,
3451            num_kv_heads: nkv,
3452            head_dim: hd,
3453            hidden_size: hs,
3454            position,
3455            inv_freq: &inv,
3456            rotary_dim: hd,
3457            scale: 1.0 / (hd as f32).sqrt(),
3458            softcap: 0.0,
3459            window: None,
3460            v_norm: true,
3461            qk_norm_after_rope: false,
3462            gate_sigmoid: false,
3463            q_norm: None,
3464            k_norm: None,
3465            output_gate: false,
3466            softplus_gate: None,
3467            rope_scale: 1.0,
3468            bias: None,
3469            rms_eps: 1e-6,
3470            norm_style: cortiq_core::NormStyle::Qwen,
3471            pool: None,
3472            v_head_dim: hd,
3473            value_in: None,
3474        };
3475        let h1: Vec<f32> = (0..hs).map(|i| (i as f32 * 0.4).sin()).collect();
3476        let h2: Vec<f32> = (0..hs).map(|i| (i as f32 * 0.9).cos()).collect();
3477
3478        let mut c_ref = LayerKvCache::new(nkv, hd);
3479        let r1 = qwen_attention(&h1, &wq, &wk, &wv, &wo, &mut c_ref, &cfg(0));
3480        let r2 = qwen_attention(&h2, &wq, &wk, &wv, &wo, &mut c_ref, &cfg(1));
3481
3482        let mut c = LayerKvCache::new(nkv, hd);
3483        let (p1, p2) = qwen_attention_pair(&h1, &h2, &wq, &wk, &wv, &wo, &mut c, &cfg(0));
3484        for (a, b) in r1.iter().zip(&p1) {
3485            assert!((a - b).abs() < 1e-5, "lane1 {a} vs {b}");
3486        }
3487        for (a, b) in r2.iter().zip(&p2) {
3488            assert!((a - b).abs() < 1e-5, "lane2 {a} vs {b}");
3489        }
3490    }
3491
3492    #[test]
3493    fn laguna_per_head_softplus_gate_matches_reference() {
3494        let (nh, nkv, hd, hs) = (2usize, 1usize, 2usize, 4usize);
3495        let zeros = |rows, cols| QTensor::from_f32(vec![0.0; rows * cols], rows, cols);
3496        let wq = zeros(nh * hd, hs);
3497        let wk = zeros(nkv * hd, hs);
3498        let wv = QTensor::from_f32(vec![1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0], nkv * hd, hs);
3499        let wo = QTensor::from_f32(
3500            vec![
3501                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
3502            ],
3503            hs,
3504            nh * hd,
3505        );
3506        let gate = QTensor::from_f32(vec![1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0], nh, hs);
3507        let inv = rope_inv_freq(hd, 10_000.0);
3508        let cfg = QwenAttnCfg {
3509            mrope: None,
3510            num_heads: nh,
3511            num_kv_heads: nkv,
3512            head_dim: hd,
3513            hidden_size: hs,
3514            position: 0,
3515            inv_freq: &inv,
3516            rotary_dim: hd,
3517            q_norm: None,
3518            k_norm: None,
3519            output_gate: false,
3520            softplus_gate: Some((&gate, true)),
3521            rope_scale: 1.0,
3522            rms_eps: 1e-6,
3523            scale: 1.0 / (hd as f32).sqrt(),
3524            softcap: 0.0,
3525            window: None,
3526            v_norm: false,
3527            qk_norm_after_rope: false,
3528            gate_sigmoid: false,
3529            norm_style: cortiq_core::NormStyle::Qwen,
3530            bias: None,
3531            pool: None,
3532            v_head_dim: hd,
3533            value_in: None,
3534        };
3535        let hidden = vec![0.0, 1.0, 2.0, 3.0];
3536        let mut cache = LayerKvCache::new(nkv, hd);
3537        let out = qwen_attention(&hidden, &wq, &wk, &wv, &wo, &mut cache, &cfg);
3538        let expected = [0.0, softplus(0.0), 0.0, softplus(1.0)];
3539        for (actual, expected) in out.iter().zip(expected) {
3540            assert!((actual - expected).abs() < 1e-6, "{actual} != {expected}");
3541        }
3542    }
3543
3544    #[test]
3545    fn yarn_frequency_endpoints_match_interpolation_contract() {
3546        let freq = yarn_inv_freq(64, 500_000.0, 128.0, 8192, 32.0, 1.0);
3547        let base = rope_inv_freq(64, 500_000.0);
3548        assert_eq!(freq.len(), 32);
3549        assert!((freq[0] - base[0]).abs() < 1e-7);
3550        assert!((freq[31] - base[31] / 128.0).abs() < 1e-9);
3551    }
3552
3553    #[test]
3554    fn rope_preserves_norm() {
3555        let mut q = vec![1.0, 0.0, 0.5, 0.5];
3556        let before: f32 = q.iter().map(|x| x * x).sum::<f32>().sqrt();
3557        rope_rotate(&mut q, 7, &rope_inv_freq(4, 10000.0));
3558        let after: f32 = q.iter().map(|x| x * x).sum::<f32>().sqrt();
3559        assert!((before - after).abs() < 1e-5);
3560    }
3561
3562    #[test]
3563    fn rope_identity_at_position_zero() {
3564        let mut q = vec![0.3, -0.7, 1.1, 0.2];
3565        let orig = q.clone();
3566        rope_rotate(&mut q, 0, &rope_inv_freq(4, 10000.0));
3567        for (a, b) in q.iter().zip(&orig) {
3568            assert!((a - b).abs() < 1e-6);
3569        }
3570    }
3571
3572    #[test]
3573    fn attention_head_uniform() {
3574        let head_dim = 4;
3575        let seq_len = 3;
3576        let q = vec![1.0; head_dim];
3577        let k = vec![1.0; seq_len * head_dim];
3578        let v = vec![
3579            1.0, 0.0, 0.0, 0.0, //
3580            0.0, 1.0, 0.0, 0.0, //
3581            0.0, 0.0, 1.0, 0.0,
3582        ];
3583        let (out, probs) = attention_head(&q, &k, &v, head_dim, seq_len);
3584        for d in 0..3 {
3585            assert!((out[d] - 1.0 / 3.0).abs() < 0.1);
3586        }
3587        let mass: f32 = probs.iter().sum();
3588        assert!((mass - 1.0).abs() < 1e-5, "probs must sum to 1");
3589    }
3590
3591    #[test]
3592    fn dead_group_skips_projection_and_cache() {
3593        let (heads, kv, hd, hidden) = (4usize, 2usize, 4usize, 8usize);
3594        let mut cache = LayerKvCache::new(kv, hd);
3595        let h_in = vec![0.5f32; hidden];
3596        let wq = vec![0.1f32; heads * hd * hidden];
3597        let wk = vec![0.1f32; kv * hd * hidden];
3598        let wv = vec![0.1f32; kv * hd * hidden];
3599        let wo = vec![0.1f32; hidden * heads * hd];
3600
3601        // Kill group 1 (Q heads 2 and 3).
3602        let active = vec![true, true, false, false];
3603        let inv_freq = rope_inv_freq(hd, 1e4);
3604        let out = multi_head_attention(
3605            &h_in, &wq, &wk, &wv, &wo, &mut cache, heads, kv, hd, hidden, 0, &active, &inv_freq,
3606        );
3607        assert_eq!(cache.head_len(0), 1, "live group cached");
3608        assert_eq!(cache.head_len(1), 0, "dead group must not be cached");
3609        assert!(
3610            out.iter().any(|&x| x.abs() > 1e-9),
3611            "live heads still produce output"
3612        );
3613    }
3614
3615    #[test]
3616    fn attention_pair_equals_two_sequential_calls() {
3617        let (heads, kv, hd, hidden) = (4usize, 2usize, 4usize, 8usize);
3618        let mk = |salt: usize, n: usize| -> Vec<f32> {
3619            (0..n)
3620                .map(|i| ((i * 7 + salt * 13) % 89) as f32 / 89.0 - 0.5)
3621                .collect()
3622        };
3623        let h1 = mk(1, hidden);
3624        let h2 = mk(2, hidden);
3625        let wq = mk(3, heads * hd * hidden);
3626        let wk = mk(4, kv * hd * hidden);
3627        let wv = mk(5, kv * hd * hidden);
3628        let wo = mk(6, hidden * heads * hd);
3629        let inv_freq = rope_inv_freq(hd, 1e4);
3630
3631        // Reference: two sequential single-position calls.
3632        let mut c_ref = LayerKvCache::new(kv, hd);
3633        let r1 = multi_head_attention(
3634            &h1, &wq, &wk, &wv, &wo, &mut c_ref, heads, kv, hd, hidden, 5, &[true; 4], &inv_freq,
3635        );
3636        let r2 = multi_head_attention(
3637            &h2, &wq, &wk, &wv, &wo, &mut c_ref, heads, kv, hd, hidden, 6, &[true; 4], &inv_freq,
3638        );
3639
3640        // Fused pair.
3641        let mut c_pair = LayerKvCache::new(kv, hd);
3642        let (p1, p2) = multi_head_attention_pair(
3643            &h1,
3644            &h2,
3645            &wq,
3646            &wk,
3647            &wv,
3648            &wo,
3649            &mut c_pair,
3650            heads,
3651            kv,
3652            hd,
3653            hidden,
3654            5,
3655            &inv_freq,
3656        );
3657
3658        assert_eq!(r1, p1, "pair lane 1 must be bit-identical");
3659        assert_eq!(r2, p2, "pair lane 2 must be bit-identical");
3660        assert_eq!(c_ref.seq_len, c_pair.seq_len);
3661        assert_eq!(c_ref.head_keys(0), c_pair.head_keys(0));
3662    }
3663
3664    #[test]
3665    fn masked_equals_dense_when_all_heads_alive() {
3666        let (heads, kv, hd, hidden) = (2usize, 1usize, 4usize, 8usize);
3667        let h_in: Vec<f32> = (0..hidden).map(|i| (i as f32 * 0.3).sin()).collect();
3668        let wq: Vec<f32> = (0..heads * hd * hidden)
3669            .map(|i| (i as f32 * 0.01).cos() * 0.1)
3670            .collect();
3671        let wk: Vec<f32> = (0..kv * hd * hidden)
3672            .map(|i| (i as f32 * 0.02).sin() * 0.1)
3673            .collect();
3674        let wv: Vec<f32> = (0..kv * hd * hidden)
3675            .map(|i| (i as f32 * 0.03).cos() * 0.1)
3676            .collect();
3677        let wo: Vec<f32> = (0..hidden * heads * hd)
3678            .map(|i| (i as f32 * 0.04).sin() * 0.1)
3679            .collect();
3680
3681        let mut c1 = LayerKvCache::new(kv, hd);
3682        let mut c2 = LayerKvCache::new(kv, hd);
3683        let inv_freq = rope_inv_freq(hd, 1e4);
3684        let dense = multi_head_attention(
3685            &h_in,
3686            &wq,
3687            &wk,
3688            &wv,
3689            &wo,
3690            &mut c1,
3691            heads,
3692            kv,
3693            hd,
3694            hidden,
3695            0,
3696            &[true, true],
3697            &inv_freq,
3698        );
3699        let masked = multi_head_attention(
3700            &h_in, &wq, &wk, &wv, &wo, &mut c2, heads, kv, hd, hidden, 0, &[true; 2], &inv_freq,
3701        );
3702        for (a, b) in dense.iter().zip(&masked) {
3703            assert_eq!(a, b, "full mask must be bit-identical to dense");
3704        }
3705    }
3706
3707    /// Spark-X2.5's sliding layer (head-wise sigmoid g_proj gate, window
3708    /// 6 here) with its tail trimmed after every call answers bit for bit
3709    /// what the untrimmed cache does — per position, in batched chunks of
3710    /// 5 and 13 (the per-position and pool-parallel `upto` attends), and in
3711    /// fused pairs with a 2-row rollback in between.
3712    #[test]
3713    fn swa_trim_batch_pair_single_equal() {
3714        let (nh, nkv, hd, hs) = (4usize, 2usize, 8usize, 16usize);
3715        let w = 6usize;
3716        let inv = rope_inv_freq(hd, 10_000.0);
3717        let wq = synth(nh * hd, hs, 31);
3718        let wk = synth(nkv * hd, hs, 32);
3719        let wv = synth(nkv * hd, hs, 33);
3720        let wo = synth(hs, nh * hd, 34);
3721        let gp = synth(nh, hs, 35);
3722        let n = 64usize;
3723        let xs: Vec<Vec<f32>> = (0..n)
3724            .map(|p| {
3725                (0..hs)
3726                    .map(|i| ((i * 5 + p * 3) as f32 * 0.17).sin())
3727                    .collect()
3728            })
3729            .collect();
3730        let cfg = |position: usize, pool: Option<&'static crate::pool::Pool>| QwenAttnCfg {
3731            mrope: None,
3732            num_heads: nh,
3733            num_kv_heads: nkv,
3734            head_dim: hd,
3735            hidden_size: hs,
3736            position,
3737            inv_freq: &inv,
3738            rotary_dim: hd,
3739            scale: 1.0 / (hd as f32).sqrt(),
3740            softcap: 0.0,
3741            window: Some(w),
3742            v_norm: false,
3743            qk_norm_after_rope: false,
3744            gate_sigmoid: true,
3745            q_norm: None,
3746            k_norm: None,
3747            output_gate: false,
3748            softplus_gate: Some((&gp, true)),
3749            rope_scale: 1.0,
3750            bias: None,
3751            rms_eps: 1e-6,
3752            norm_style: cortiq_core::NormStyle::Qwen,
3753            pool,
3754            v_head_dim: hd,
3755            value_in: None,
3756        };
3757        let fresh = || {
3758            let mut c = LayerKvCache::new(nkv, hd);
3759            c.mode = crate::kv_cache::KvMode::F32;
3760            c
3761        };
3762        let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
3763        static POOL: std::sync::OnceLock<crate::pool::Pool> = std::sync::OnceLock::new();
3764        let pool: &'static crate::pool::Pool = POOL.get_or_init(|| crate::pool::Pool::new(2));
3765        for pool in [None, Some(pool)] {
3766            // Two arms, identical calls; `trim` trims after each one.
3767            let run = |trim: bool| {
3768                let (mut cs, mut cb, mut cp) = (fresh(), fresh(), fresh());
3769                let mut out_s = Vec::new();
3770                for (p, x) in xs.iter().enumerate() {
3771                    out_s.push(qwen_attention(
3772                        x,
3773                        &wq,
3774                        &wk,
3775                        &wv,
3776                        &wo,
3777                        &mut cs,
3778                        &cfg(p, pool),
3779                    ));
3780                    if trim {
3781                        cs.trim_window(w, 2, 4);
3782                    }
3783                }
3784                let mut out_b = Vec::new();
3785                let mut p0 = 0usize;
3786                for &b in [5usize, 13].iter().cycle() {
3787                    if p0 >= n {
3788                        break;
3789                    }
3790                    let b = b.min(n - p0);
3791                    let flat: Vec<f32> = xs[p0..p0 + b].iter().flatten().copied().collect();
3792                    let o =
3793                        qwen_attention_batch(&flat, b, &wq, &wk, &wv, &wo, &mut cb, &cfg(p0, pool));
3794                    out_b.extend(o.chunks(hs).map(|r| r.to_vec()));
3795                    if trim {
3796                        cb.trim_window(w, 2, 4);
3797                    }
3798                    p0 += b;
3799                }
3800                let mut out_p = Vec::new();
3801                let mut p = 0usize;
3802                while p + 1 < n {
3803                    let (a, b) = qwen_attention_pair(
3804                        &xs[p],
3805                        &xs[p + 1],
3806                        &wq,
3807                        &wk,
3808                        &wv,
3809                        &wo,
3810                        &mut cp,
3811                        &cfg(p, pool),
3812                    );
3813                    if trim {
3814                        cp.trim_window(w, 2, 4);
3815                    }
3816                    // Every third pair is a rejected draft: roll it back
3817                    // and run the pair again on other inputs.
3818                    if (p / 2) % 3 == 1 {
3819                        cp.truncate_last(2);
3820                        let (a2, b2) = qwen_attention_pair(
3821                            &xs[p + 1],
3822                            &xs[p],
3823                            &wq,
3824                            &wk,
3825                            &wv,
3826                            &wo,
3827                            &mut cp,
3828                            &cfg(p, pool),
3829                        );
3830                        out_p.push(a2);
3831                        out_p.push(b2);
3832                        if trim {
3833                            cp.trim_window(w, 2, 4);
3834                        }
3835                    } else {
3836                        out_p.push(a);
3837                        out_p.push(b);
3838                    }
3839                    p += 2;
3840                }
3841                (out_s, out_b, out_p, cs.base(), cb.base(), cp.base())
3842            };
3843            let (s0, b0, p0, ..) = run(false);
3844            let (s1, b1, p1, bs, bb, bp) = run(true);
3845            assert!(bs > 0 && bb > 0 && bp > 0, "the trim fired: {bs} {bb} {bp}");
3846            let pl = pool.is_some();
3847            for p in 0..n {
3848                assert_eq!(bits(&s0[p]), bits(&s1[p]), "single p{p} pool {pl}");
3849                assert_eq!(bits(&b0[p]), bits(&b1[p]), "batch p{p} pool {pl}");
3850                // The batched walk is the per-position one, bit for bit.
3851                assert_eq!(bits(&s0[p]), bits(&b1[p]), "batch vs single p{p} pool {pl}");
3852            }
3853            for (p, (a, b)) in p0.iter().zip(&p1).enumerate() {
3854                assert_eq!(bits(a), bits(b), "pair row {p} pool {pl}");
3855            }
3856        }
3857    }
3858}
3859
3860/// HunYuan dense applies the per-head q/k RMSNorm AFTER RoPE. A rotation
3861/// keeps a head's RMS, so the two orders differ exactly by where the norm
3862/// WEIGHTS land — which is why the flag exists instead of a weight fold.
3863#[cfg(test)]
3864mod qk_norm_order_tests {
3865    use super::*;
3866
3867    fn cfg<'a>(
3868        inv: &'a [f32],
3869        qw: &'a [f32],
3870        kw: &'a [f32],
3871        late: bool,
3872        hd: usize,
3873    ) -> QwenAttnCfg<'a> {
3874        QwenAttnCfg {
3875            mrope: None,
3876            num_heads: 2,
3877            num_kv_heads: 1,
3878            head_dim: hd,
3879            hidden_size: 4 * hd,
3880            position: 7,
3881            inv_freq: inv,
3882            rotary_dim: hd,
3883            scale: 1.0 / (hd as f32).sqrt(),
3884            softcap: 0.0,
3885            window: None,
3886            v_norm: false,
3887            qk_norm_after_rope: late,
3888            gate_sigmoid: false,
3889            q_norm: Some(qw),
3890            k_norm: Some(kw),
3891            output_gate: false,
3892            softplus_gate: None,
3893            rope_scale: 1.0,
3894            bias: None,
3895            rms_eps: 1e-6,
3896            norm_style: cortiq_core::NormStyle::Qwen,
3897            pool: None,
3898            v_head_dim: hd,
3899            value_in: None,
3900        }
3901    }
3902
3903    /// Reference for the late order, written independently of the helper:
3904    /// rotate every head, then x̂·w with the RMS of the ROTATED head.
3905    fn late_reference(x: &[f32], w: &[f32], hd: usize, pos: usize, inv: &[f32]) -> Vec<f32> {
3906        let mut y = x.to_vec();
3907        for h in 0..x.len() / hd {
3908            let head = &mut y[h * hd..(h + 1) * hd];
3909            rope_rotate(head, pos, inv);
3910            let ss: f64 = head.iter().map(|&v| (v as f64) * (v as f64)).sum();
3911            let inv_rms = 1.0 / (ss / hd as f64 + 1e-6).sqrt();
3912            for (d, v) in head.iter_mut().enumerate() {
3913                *v = ((*v as f64) * inv_rms) as f32 * w[d];
3914            }
3915        }
3916        y
3917    }
3918
3919    #[test]
3920    fn late_order_matches_reference_and_differs_from_early() {
3921        let hd = 16;
3922        let inv = rope_inv_freq(hd, 10_000.0);
3923        // Non-pair-symmetric norm weights: the only case where the order matters.
3924        let qw: Vec<f32> = (0..hd).map(|d| 0.5 + 0.1 * d as f32).collect();
3925        let kw: Vec<f32> = (0..hd).map(|d| 1.5 - 0.05 * d as f32).collect();
3926        let q0: Vec<f32> = (0..2 * hd).map(|i| ((i * 7) % 11) as f32 * 0.3 - 1.0).collect();
3927        let k0: Vec<f32> = (0..hd).map(|i| ((i * 5) % 13) as f32 * 0.2 - 1.2).collect();
3928
3929        let (mut q_late, mut k_late) = (q0.clone(), k0.clone());
3930        let c_late = cfg(&inv, &qw, &kw, true, hd);
3931        qk_norm_and_rope(&c_late, &mut q_late, &mut k_late, 2, 1, hd, 7);
3932        let q_ref = late_reference(&q0, &qw, hd, 7, &inv);
3933        let k_ref = late_reference(&k0, &kw, hd, 7, &inv);
3934        for (a, b) in q_late.iter().zip(&q_ref) {
3935            assert!((a - b).abs() < 1e-5, "q late: {a} vs {b}");
3936        }
3937        for (a, b) in k_late.iter().zip(&k_ref) {
3938            assert!((a - b).abs() < 1e-5, "k late: {a} vs {b}");
3939        }
3940
3941        let (mut q_early, mut k_early) = (q0.clone(), k0.clone());
3942        let c_early = cfg(&inv, &qw, &kw, false, hd);
3943        qk_norm_and_rope(&c_early, &mut q_early, &mut k_early, 2, 1, hd, 7);
3944        let dq: f32 = q_early.iter().zip(&q_late).map(|(a, b)| (a - b).abs()).sum();
3945        assert!(dq > 1e-2, "orders must differ with non-symmetric weights ({dq})");
3946    }
3947
3948    #[test]
3949    fn orders_coincide_for_pair_symmetric_weights() {
3950        // w_i == w_{i+hd/2}: the rotation commutes with the diagonal scale,
3951        // so both orders must agree to float precision.
3952        let hd = 8;
3953        let inv = rope_inv_freq(hd, 10_000.0);
3954        let half: Vec<f32> = vec![0.7, 1.3, 0.9, 1.1];
3955        let w: Vec<f32> = half.iter().chain(&half).copied().collect();
3956        let q0: Vec<f32> = (0..2 * hd).map(|i| (i as f32 * 0.37).sin()).collect();
3957        let k0: Vec<f32> = (0..hd).map(|i| (i as f32 * 0.53).cos()).collect();
3958        let (mut qa, mut ka) = (q0.clone(), k0.clone());
3959        let (mut qb, mut kb) = (q0.clone(), k0.clone());
3960        qk_norm_and_rope(&cfg(&inv, &w, &w, true, hd), &mut qa, &mut ka, 2, 1, hd, 7);
3961        qk_norm_and_rope(&cfg(&inv, &w, &w, false, hd), &mut qb, &mut kb, 2, 1, hd, 7);
3962        for (a, b) in qa.iter().zip(&qb).chain(ka.iter().zip(&kb)) {
3963            assert!((a - b).abs() < 1e-5, "{a} vs {b}");
3964        }
3965    }
3966}
3967
3968#[cfg(test)]
3969mod splitk_tests {
3970    use super::*;
3971    use crate::kv_cache::{KvMode, LayerKvCache};
3972
3973    /// The pooled decode attend (split-K on x86-64, per-head jobs
3974    /// elsewhere) against the serial grouped attend: full context and a
3975    /// window, a context that is not a multiple of the chunk, output and
3976    /// importance.
3977    #[test]
3978    fn pooled_decode_attend_matches_serial() {
3979        let (nkv, hd, hpk) = (2usize, 64usize, 4usize);
3980        let nh = nkv * hpk;
3981        let pool = crate::pool::Pool::new(3);
3982        for (n, window) in [(700usize, None), (1300, Some(512usize)), (600, Some(4000))] {
3983            let mut c = LayerKvCache::new(nkv, hd);
3984            c.mode = KvMode::F32;
3985            for p in 0..n {
3986                let k: Vec<f32> = (0..nkv * hd)
3987                    .map(|i| ((i * 31 + p * 17 + 3) % 97) as f32 / 48.5 - 1.0)
3988                    .collect();
3989                let v: Vec<f32> = (0..nkv * hd)
3990                    .map(|i| ((i * 13 + p * 29 + 7) % 89) as f32 / 89.0 - 0.5)
3991                    .collect();
3992                c.append(&k, &v, &[]);
3993            }
3994            let q: Vec<f32> = (0..nh * hd).map(|i| ((i * 11 + 5) % 83) as f32 / 41.5 - 1.0).collect();
3995            let scale = 1.0 / (hd as f32).sqrt();
3996            let (o1, i1) = attend_all_heads(&q, &c, nh, hpk, hd, scale, window, 0.0);
3997            let (o2, i2) =
3998                attend_all_heads_pool(&q, &c, nh, hpk, hd, scale, window, 0.0, Some(&pool));
3999            for (i, (a, b)) in o1.iter().zip(&o2).enumerate() {
4000                assert!((a - b).abs() <= 1e-5, "n{n} {window:?} out[{i}]: {a} vs {b}");
4001            }
4002            assert_eq!(i1.len(), i2.len());
4003            for (i, (a, b)) in i1.iter().zip(&i2).enumerate() {
4004                assert!((a - b).abs() <= 1e-5 * (1.0 + a.abs()), "n{n} {window:?} imp[{i}]: {a} vs {b}");
4005            }
4006        }
4007    }
4008}