Skip to main content

cortiq_engine/
qtensor.rs

1//! QTensor — weight tensor with pluggable storage.
2//!
3//! Two backings, one interface:
4//! - `F32`   — owned dense floats (small models, tests). Every operation
5//!   is bit-identical to the historical `&[f32]` code paths.
6//! - `Mapped` — quantized bytes zero-copy from the CMF mmap (`q8_row` /
7//!   `q8_2f`). The matvec is fused: int8 rows × f32 activations, the
8//!   q8_2f column field folds into a pre-scale of the input
9//!   (`x'[i] = col[i]·x[i]`), so the inner loop is the same i8 dot as
10//!   q8_row. This is what lets a 15B file run in a few GB of RSS.
11//!
12//! Extension point: new dtypes = new match arm here, nothing else moves.
13
14use crate::pool::{Pool, matvec_rows, matvec_rows2};
15use cortiq_core::quant::{
16    GROUP_SIZE, Q1_TILE, Q2TP_CHUNK, Q4_TILE, Q4TP_NIB, f16_to_f32, q2tp_ladder, q2tp_sections,
17    q4tp_code, q4tp_ladder, q4tp_sections,
18};
19use cortiq_core::{CmfModel, TensorDtype};
20use std::cell::UnsafeCell;
21use std::sync::Arc;
22use std::sync::atomic::{AtomicU64, Ordering};
23
24/// `mxfp4` (OCP MX FP4) CPU kernels.
25mod mxfp4;
26/// `nvfp4` (NVIDIA NVFP4) CPU kernels.
27mod nvfp4;
28
29/// Whole q4tp experts on the host's cores (AVX-512 VNNI): the misses of a
30/// card's expert arena.
31#[cfg(target_arch = "x86_64")]
32mod moe_fast;
33
34/// D5 GPU-matmat gate telemetry: large-GEMM calls that reached the gate
35/// vs those the q8_2f device kernel actually consumed (SAM3 profiling).
36pub static MATMAT_GATE: AtomicU64 = AtomicU64::new(0);
37pub static MATMAT_GPU_HIT: AtomicU64 = AtomicU64::new(0);
38
39pub enum QTensor {
40    F32 {
41        data: Vec<f32>,
42        rows: usize,
43        cols: usize,
44    },
45    Mapped {
46        model: Arc<CmfModel>,
47        /// Index into the model's tensor directory.
48        idx: usize,
49        dtype: TensorDtype,
50        rows: usize,
51        cols: usize,
52        /// Per-row scales, dequantized to f32 up front (tiny).
53        row_scale: Vec<f32>,
54        /// q8_2f column field (θ), dequantized up front; empty for q8_row.
55        col_field: Vec<f32>,
56        /// Vbit only: byte offset of each row's packed data within the
57        /// tensor blob (`[rows + 1]`, computed once at load — the per-
58        /// matvec prefix scan over row bit-widths was O(rows) each call).
59        vbit_offsets: Vec<usize>,
60        /// q8-family decode repack (load-time, optional): rows in groups
61        /// of 4, interleaved in 16-byte units — one 64-byte line per
62        /// iteration feeds all 4 sdot lanes, ONE sequential weight
63        /// stream per worker instead of four (this is where llama.cpp's
64        /// repacked Q8 kernels get their bandwidth). Empty = off
65        /// (CMF_REPACK=0, non-SDOT arch, or an ineligible shape). Trades
66        /// an anonymous copy of the quants for mmap pages that go cold.
67        repack: Vec<u8>,
68    },
69    /// Binary low-rank (`blr`): ±1 paths, signs from the mmap, scales as
70    /// f32 (docs/BLR_NVG.md §3). Every device-graph accessor answers `None`
71    /// for it (whole-token graphs decline to per-op/host paths); the CPU
72    /// kernels live in `crate::blr`, the per-op wgpu kernels in
73    /// `gpu_wgpu::blr`.
74    Blr(Box<crate::blr::BlrTensor>),
75}
76
77/// Load-time q8 repack gate (see `Mapped::repack`). OPT-IN
78/// (`CMF_REPACK=1`): the single-stream hypothesis LOST on Apple Silicon
79/// (M4, interleaved A/B: decode 101 vs 94 tok/s — four adjacent row
80/// streams per worker feed the prefetcher MORE memory-level parallelism
81/// than one); kept as an experiment flag for x86, where the tradeoff
82/// may land differently.
83fn repack_enabled() -> bool {
84    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
85    *ON.get_or_init(|| {
86        std::env::var("CMF_REPACK")
87            .map(|v| v == "1")
88            .unwrap_or(cfg!(target_os = "android"))
89    })
90}
91
92/// Interleave q8 rows for the decode kernel: group g holds rows
93/// 4g..4g+4 as [r0[c], r1[c], r2[c], r3[c]] per 16-byte chunk c. Only
94/// full groups are packed — tail rows keep reading the mmap layout.
95fn q8_repack(bytes: &[u8], rows: usize, cols: usize) -> Vec<u8> {
96    #[cfg(target_arch = "aarch64")]
97    let arch_ok = sdot_enabled();
98    #[cfg(not(target_arch = "aarch64"))]
99    let arch_ok = false;
100    if !arch_ok || !repack_enabled() || rows < 256 || cols % 16 != 0 {
101        return Vec::new();
102    }
103    q8_repack_layout(bytes, rows, cols)
104}
105
106/// The pure layout transform behind `q8_repack` (tested directly —
107/// the gate depends on arch and env).
108fn q8_repack_layout(bytes: &[u8], rows: usize, cols: usize) -> Vec<u8> {
109    let groups = rows / 4;
110    let mut rep = vec![0u8; groups * 4 * cols];
111    for g in 0..groups {
112        let dst = &mut rep[g * 4 * cols..(g + 1) * 4 * cols];
113        for c in 0..cols / 16 {
114            for lane in 0..4 {
115                let src = (g * 4 + lane) * cols + c * 16;
116                dst[c * 64 + lane * 16..c * 64 + lane * 16 + 16]
117                    .copy_from_slice(&bytes[src..src + 16]);
118            }
119        }
120    }
121    rep
122}
123
124/// Prefix-sum of vbit row payload offsets (absolute within the tensor
125/// bytes). `offsets[r]..offsets[r+1]` is row r's packed data.
126fn vbit_row_offsets(bytes: &[u8], rows: usize, cols: usize) -> Vec<usize> {
127    let ng = cols / GROUP_SIZE;
128    let bits = &bytes[..rows];
129    let mut offsets = Vec::with_capacity(rows + 1);
130    let mut off = rows + rows * ng * 2;
131    for r in 0..rows {
132        offsets.push(off);
133        off += (cols * bits[r] as usize).div_ceil(8);
134    }
135    offsets.push(off);
136    offsets
137}
138
139/// `CMF_X86_BLOCKED` / `CMF_GPU_LMHEAD` / `CMF_GPU_SPLIT`, read once. They
140/// used to be read from the environment on every large matvec and on every
141/// matmat in six places — microseconds each, but also a knob that could
142/// change under a running process, which is not a thing a kernel choice
143/// should be able to do mid-sequence.
144fn blocked_enabled() -> bool {
145    use std::sync::atomic::Ordering::Relaxed;
146    match BLOCKED_OVERRIDE.load(Relaxed) {
147        1 => false,
148        2 => true,
149        _ => {
150            static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
151            *ON.get_or_init(|| {
152                std::env::var("CMF_X86_BLOCKED")
153                    .map(|v| v != "0")
154                    .unwrap_or(true)
155            })
156        }
157    }
158}
159
160static BLOCKED_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
161
162/// Force the blocked GEMM on or off, ignoring the environment; `None`
163/// restores it. For tests that need to run BOTH paths and compare them:
164/// `blocked_enabled` caches its answer for the life of the process, which
165/// is right when the environment is the only input, but leaves a test that
166/// flips `CMF_X86_BLOCKED` between two calls comparing a path against
167/// itself — or against whatever a test running in parallel latched first.
168pub fn set_blocked_override(on: Option<bool>) {
169    let v = match on {
170        None => 0,
171        Some(false) => 1,
172        Some(true) => 2,
173    };
174    BLOCKED_OVERRIDE.store(v, std::sync::atomic::Ordering::Relaxed);
175}
176
177fn gpu_lmhead_enabled() -> bool {
178    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
179    *ON.get_or_init(|| {
180        std::env::var("CMF_GPU_LMHEAD")
181            .map(|v| v != "0")
182            .unwrap_or(true)
183    })
184}
185
186fn gpu_split_frac() -> f32 {
187    // MiMo's banked verification projects every row on the device. Plain
188    // decode must not quantize half of its O/head activation on the CPU.
189    if FULL_GPU_Q8.get() {
190        return 1.0;
191    }
192    static F: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
193    *F.get_or_init(|| {
194        std::env::var("CMF_GPU_SPLIT")
195            .ok()
196            .and_then(|v| v.parse::<f32>().ok())
197            .unwrap_or(0.5)
198            .clamp(0.0, 1.0)
199    })
200}
201
202impl QTensor {
203    pub fn from_f32(data: Vec<f32>, rows: usize, cols: usize) -> Self {
204        debug_assert_eq!(data.len(), rows * cols);
205        Self::F32 { data, rows, cols }
206    }
207
208    /// Wrap a directory tensor without dequantizing the payload.
209    /// Falls back to dequantized f32 for dtypes without a fused kernel.
210    pub fn from_model(model: &Arc<CmfModel>, name: &str) -> Result<Self, String> {
211        // Indexed lookup: the linear directory scan made pipeline build
212        // O(N²) on MoE/skills files with thousands of tensors.
213        let idx = model
214            .tensor_index(name)
215            .ok_or_else(|| format!("tensor '{name}' not found in CMF directory"))?;
216        let entry = &model.tensors[idx];
217        if entry.shape.len() != 2 {
218            return Err(format!("QTensor::from_model needs 2-D, got '{name}'"));
219        }
220        let (rows, cols) = (entry.shape[0], entry.shape[1]);
221        let bytes = model.entry_bytes(entry);
222
223        match entry.dtype {
224            TensorDtype::Q8Row | TensorDtype::Q8_2f => {
225                let n = rows * cols;
226                let scales_off = n;
227                let row_scale: Vec<f32> = (0..rows)
228                    .map(|o| {
229                        f16_to_f32(u16::from_le_bytes([
230                            bytes[scales_off + o * 2],
231                            bytes[scales_off + o * 2 + 1],
232                        ]))
233                    })
234                    .collect();
235                let col_field: Vec<f32> = if entry.dtype == TensorDtype::Q8_2f {
236                    let col_off = n + rows * 2;
237                    (0..cols)
238                        .map(|i| {
239                            f16_to_f32(u16::from_le_bytes([
240                                bytes[col_off + i * 2],
241                                bytes[col_off + i * 2 + 1],
242                            ]))
243                        })
244                        .collect()
245                } else {
246                    Vec::new()
247                };
248                Ok(Self::Mapped {
249                    model: model.clone(),
250                    idx,
251                    dtype: entry.dtype,
252                    rows,
253                    cols,
254                    row_scale,
255                    col_field,
256                    vbit_offsets: Vec::new(),
257                    repack: q8_repack(bytes, rows, cols),
258                })
259            }
260            // vbit: fused kernel unpacks variable-bit rows from mmap.
261            TensorDtype::Vbit if cols % GROUP_SIZE == 0 => Ok(Self::Mapped {
262                model: model.clone(),
263                idx,
264                dtype: entry.dtype,
265                rows,
266                cols,
267                row_scale: Vec::new(),
268                col_field: Vec::new(),
269                vbit_offsets: vbit_row_offsets(bytes, rows, cols),
270                repack: Vec::new(),
271            }),
272            // vbit_ro (§4.2): the offset table comes straight from the
273            // file — no load-time prefix scan; kernels are shared with
274            // legacy vbit (they consume absolute offsets either way).
275            TensorDtype::VbitRo if cols % GROUP_SIZE == 0 => {
276                let (_, off_off, packed_off) = cortiq_core::quant::vbit_ro_sections(rows, cols);
277                let offsets: Vec<usize> = (0..=rows)
278                    .map(|r| packed_off + cortiq_core::quant::vbit_ro_offset(bytes, off_off, r))
279                    .collect();
280                Ok(Self::Mapped {
281                    model: model.clone(),
282                    idx,
283                    dtype: entry.dtype,
284                    rows,
285                    cols,
286                    row_scale: Vec::new(),
287                    col_field: Vec::new(),
288                    vbit_offsets: offsets,
289                    repack: Vec::new(),
290                })
291            }
292            // q4_block: fused kernel reads nibbles straight from mmap —
293            // a 14B q4 file no longer explodes into ×8 f32 RAM.
294            // q4_tiled (§4.3): interleaved [scale][nibbles] tiles — one
295            // sequential memory stream (measured ×1.66 ARM / ×1.13 AVX2
296            // at kernel level over the split layout).
297            TensorDtype::Q4Tiled if cols % GROUP_SIZE == 0 => Ok(Self::Mapped {
298                model: model.clone(),
299                idx,
300                dtype: entry.dtype,
301                rows,
302                cols,
303                row_scale: Vec::new(),
304                col_field: Vec::new(),
305                vbit_offsets: Vec::new(),
306                repack: Vec::new(),
307            }),
308            // q4tp (§4.10): nibbles from mmap, scale from the row ladder —
309            // 7.3% less file than q4t at the same 4-bit grid.
310            TensorDtype::Q4TiledP if cols % GROUP_SIZE == 0 => Ok(Self::Mapped {
311                model: model.clone(),
312                idx,
313                dtype: entry.dtype,
314                rows,
315                cols,
316                row_scale: Vec::new(),
317                col_field: Vec::new(),
318                vbit_offsets: Vec::new(),
319                repack: Vec::new(),
320            }),
321            // q2tp: 2-bit chunks from mmap, scale from the same row ladder.
322            TensorDtype::Q2TiledP if cols % GROUP_SIZE == 0 => Ok(Self::Mapped {
323                model: model.clone(),
324                idx,
325                dtype: entry.dtype,
326                rows,
327                cols,
328                row_scale: Vec::new(),
329                col_field: Vec::new(),
330                vbit_offsets: Vec::new(),
331                repack: Vec::new(),
332            }),
333            TensorDtype::Q4Block if cols % GROUP_SIZE == 0 => Ok(Self::Mapped {
334                model: model.clone(),
335                idx,
336                dtype: entry.dtype,
337                rows,
338                cols,
339                row_scale: Vec::new(),
340                col_field: Vec::new(),
341                vbit_offsets: Vec::new(),
342                repack: Vec::new(),
343            }),
344            // q1: binary sign-bit tiles from mmap (1-bit-trained models).
345            // q1g: the same signs as planes with one scale per 128-group.
346            TensorDtype::Q1 if cols % GROUP_SIZE == 0 => Ok(Self::Mapped {
347                model: model.clone(),
348                idx,
349                dtype: entry.dtype,
350                rows,
351                cols,
352                row_scale: Vec::new(),
353                col_field: Vec::new(),
354                vbit_offsets: Vec::new(),
355                repack: Vec::new(),
356            }),
357            TensorDtype::Q1G if cols % cortiq_core::quant::Q1G_GROUP == 0 => Ok(Self::Mapped {
358                model: model.clone(),
359                idx,
360                dtype: entry.dtype,
361                rows,
362                cols,
363                row_scale: Vec::new(),
364                col_field: Vec::new(),
365                vbit_offsets: Vec::new(),
366                repack: Vec::new(),
367            }),
368            // mxfp4: E2M1 codes + E8M0 scales straight from the mmap (the
369            // native FP4 expert codec; `qtensor::mxfp4`).
370            TensorDtype::Mxfp4 if cols % cortiq_core::mxfp4::GROUP == 0 => Ok(Self::Mapped {
371                model: model.clone(),
372                idx,
373                dtype: entry.dtype,
374                rows,
375                cols,
376                row_scale: Vec::new(),
377                col_field: Vec::new(),
378                vbit_offsets: Vec::new(),
379                repack: Vec::new(),
380            }),
381            // nvfp4: E2M1 codes + UE4M3 scales + tensor factor straight from
382            // the mmap (`qtensor::nvfp4`).
383            TensorDtype::Nvfp4 if cols % cortiq_core::nvfp4::GROUP == 0 => Ok(Self::Mapped {
384                model: model.clone(),
385                idx,
386                dtype: entry.dtype,
387                rows,
388                cols,
389                row_scale: Vec::new(),
390                col_field: Vec::new(),
391                vbit_offsets: Vec::new(),
392                repack: Vec::new(),
393            }),
394            // q1t (ternary + outlier overlay): fused per-row dequant kernel
395            // reads straight from mmap — a 12B q1t stays ~its file size in
396            // RAM instead of dequantizing to ~48 GB of f32.
397            TensorDtype::Q1T if cols % GROUP_SIZE == 0 => Ok(Self::Mapped {
398                model: model.clone(),
399                idx,
400                dtype: entry.dtype,
401                rows,
402                cols,
403                row_scale: Vec::new(),
404                col_field: Vec::new(),
405                vbit_offsets: Vec::new(),
406                repack: Vec::new(),
407            }),
408            // blr: factored kernels over the packed signs. CMF_BLR_DENSE=1
409            // dequantizes to f32 instead (A/B parity runs).
410            TensorDtype::BinaryLowRank if std::env::var("CMF_BLR_DENSE").as_deref() != Ok("1") => {
411                Ok(Self::Blr(Box::new(crate::blr::BlrTensor::from_model(
412                    model, idx,
413                )?)))
414            }
415            // No fused kernel yet → dequantize once (correct, more RAM).
416            _ => {
417                let mut data = vec![0.0f32; rows * cols];
418                cortiq_core::quant::dequant_tensor(entry, bytes, &mut data)?;
419                Ok(Self::from_f32(data, rows, cols))
420            }
421        }
422    }
423
424    /// Binary low-rank tensor? Fused multi-tensor kernels refuse it and fall
425    /// back to per-tensor calls.
426    pub fn is_blr(&self) -> bool {
427        matches!(self, Self::Blr(_))
428    }
429
430    /// Memory-mapped `mxfp4` tensor? Like `blr`, it has no row-range kernel
431    /// in the fused multi-tensor jobs: those run it per tensor.
432    pub fn is_mxfp4(&self) -> bool {
433        matches!(
434            self,
435            Self::Mapped {
436                dtype: TensorDtype::Mxfp4,
437                ..
438            }
439        )
440    }
441
442    /// Memory-mapped `nvfp4` tensor? No row-range kernel in the fused
443    /// multi-tensor jobs either.
444    pub fn is_nvfp4(&self) -> bool {
445        matches!(
446            self,
447            Self::Mapped {
448                dtype: TensorDtype::Nvfp4,
449                ..
450            }
451        )
452    }
453
454    /// Codecs the fused multi-tensor jobs (`matvec_many`, the SwiGLU and
455    /// MoE row kernels) do not carry: they fall back to per-tensor calls.
456    fn per_tensor_only(&self) -> bool {
457        self.is_blr() || self.is_mxfp4() || self.is_nvfp4()
458    }
459
460    /// (model, idx) of a `blr` tensor, for the wgpu graphs only (their
461    /// `blr` stage kernels, kind [`crate::gpu::GRAPH_KIND_BLR`]). Kept apart
462    /// from [`graph_weight`](Self::graph_weight), which stays None for
463    /// `blr`: every other graph consumer keys its kernels on that answer.
464    /// A file with a Prism contract keeps the per-op path.
465    pub fn graph_blr(&self) -> Option<(&Arc<CmfModel>, usize)> {
466        match self {
467            Self::Blr(t) if !crate::prism::has_contract(&t.model) => Some((&t.model, t.idx)),
468            _ => None,
469        }
470    }
471
472    /// [`graph_weight`](Self::graph_weight), then the Prism descriptor
473    /// form, then a `blr` tensor as kind [`crate::gpu::GRAPH_KIND_BLR`] —
474    /// the wgpu token and batch graph builders' lookup.
475    pub(crate) fn graph_weight_or_blr(
476        &self,
477    ) -> Option<(&std::sync::Arc<CmfModel>, usize, u8, &[f32])> {
478        self.graph_weight()
479            .or_else(|| self.graph_weight_descriptor())
480            .or_else(|| {
481                self.graph_blr()
482                    .map(|(m, i)| (m, i, crate::gpu::GRAPH_KIND_BLR, &[][..]))
483            })
484    }
485
486    /// Binary-weight-mapped tensor, q1 or q1g? (GPU gates: the binary CPU
487    /// kernels are compute-bound, so offload pays at much smaller shapes
488    /// than q8.)
489    pub(crate) fn is_q1(&self) -> bool {
490        matches!(
491            self,
492            Self::Mapped {
493                dtype: TensorDtype::Q1 | TensorDtype::Q1G,
494                ..
495            }
496        )
497    }
498
499    /// The binary-weight view (q1 tiles or q1g planes) the shared CPU row
500    /// drivers take; None for every other storage.
501    fn bin_w(&self) -> Option<BinW<'_>> {
502        match self {
503            Self::Mapped {
504                dtype: TensorDtype::Q1,
505                ..
506            } => Some(BinW::Q1(self.quant_bytes())),
507            Self::Mapped {
508                dtype: TensorDtype::Q1G,
509                rows,
510                cols,
511                ..
512            } => Some(BinW::q1g(self.quant_bytes(), *rows, *cols)),
513            _ => None,
514        }
515    }
516
517    /// Owned-f32 view (data, rows, cols) — the GDN a/b gate projections
518    /// arrive dequantized (force-f16 in the converter → F32 in RAM).
519    pub(crate) fn f32_parts(&self) -> Option<(&[f32], usize, usize)> {
520        match self {
521            Self::F32 { data, rows, cols } => Some((data, *rows, *cols)),
522            _ => None,
523        }
524    }
525
526    /// (directory idx, rows, cols) of a q1-mapped tensor — the
527    /// whole-block GPU path resolves offsets itself.
528    /// (idx, rows, cols) of a mapped tensor the whole-token GPU graph can drive
529    /// — Q1, Q1T or Q4-block (it resolves the offset and picks the kernel by
530    /// dtype). Q4-block lets a precise down_proj/lm_head stay on-device.
531    /// Named `q1_parts` for historical reasons.
532    pub(crate) fn q1_parts(&self) -> Option<(usize, usize, usize)> {
533        if self.has_prism_contract() {
534            return None;
535        }
536        match self {
537            #[cfg(target_os = "macos")]
538            Self::Mapped {
539                dtype: TensorDtype::Q1T,
540                ..
541            } if !crate::gpu::metal_q1t_enabled() => None,
542            Self::Mapped {
543                idx,
544                dtype:
545                    TensorDtype::Q1
546                    | TensorDtype::Q1G
547                    | TensorDtype::Q1T
548                    | TensorDtype::Q4Block
549                    | TensorDtype::Q4Tiled
550                    // Q2TiledP deliberately absent: the Metal graph has no
551                    // q2tp kernel, and advertising it here made the block
552                    // plan truncate mid-run at the first q2tp layer.
553                    | TensorDtype::Q4TiledP
554                    | TensorDtype::Q8Row
555                    | TensorDtype::Q8_2f,
556                rows,
557                cols,
558                ..
559            } => Some((*idx, *rows, *cols)),
560            _ => None,
561        }
562    }
563
564    /// `(directory idx, rows, cols)` for the native Metal token graph.  The
565    /// historical q1 graph gate intentionally refuses every Prism tensor so
566    /// an untransformed q2 payload cannot slip into the resident path.  The
567    /// Metal2 graph is descriptor-aware and admits only the production
568    /// q2tp-affine forward targets; ordinary q1/q4 callers retain the old
569    /// `q1_parts` behaviour.
570    #[cfg(target_os = "macos")]
571    pub(crate) fn metal_graph_parts(&self) -> Option<(usize, usize, usize)> {
572        if let Some((model, idx, kind, _)) = self.graph_weight_descriptor() {
573            let name = &model.tensors[idx].name;
574            let forward = kind == 9 && crate::prism::is_forward_weight(model, name);
575            let affine = kind == 9 && crate::prism::is_affine_target(model, name);
576            if forward && affine {
577                let e = model.tensors.get(idx)?;
578                return Some((idx, *e.shape.first()?, *e.shape.get(1)?));
579            }
580        }
581        self.q1_parts()
582    }
583
584    /// (directory idx, rows, cols) of a q4_tiled mapped tensor. The
585    /// chunk-prefill graph takes it in the same 4-tuple slot as
586    /// `q8_row_parts` with an EMPTY row_scale — q4t carries its scales
587    /// inside the 18-byte tiles, and the empty slice is what tells the
588    /// encoder to reach for the q4t kernels.
589    pub(crate) fn q4t_parts(&self) -> Option<(usize, usize, usize)> {
590        if self.has_prism_contract() {
591            return None;
592        }
593        match self {
594            Self::Mapped {
595                idx,
596                dtype: TensorDtype::Q4Tiled,
597                rows,
598                cols,
599                ..
600            } => Some((*idx, *rows, *cols)),
601            _ => None,
602        }
603    }
604
605    /// (directory idx, rows, cols) of a q4tp mapped tensor. Same empty-scale
606    /// slot as `q4t_parts` in the chunk graph — the encoder tells the two
607    /// apart by the tensor's dtype, not by the slot.
608    pub(crate) fn q4tp_parts(&self) -> Option<(usize, usize, usize)> {
609        if self.has_prism_contract() {
610            return None;
611        }
612        match self {
613            Self::Mapped {
614                idx,
615                dtype: TensorDtype::Q4TiledP,
616                rows,
617                cols,
618                ..
619            } => Some((*idx, *rows, *cols)),
620            _ => None,
621        }
622    }
623
624    /// (directory idx, rows, cols, row_scale) of a plain q8_row mapped
625    /// tensor — the chunk-prefill GPU graph resolves offsets itself.
626    /// q8_2f is excluded on purpose: its column field would need a
627    /// prescale stage on the device.
628    pub(crate) fn q8_row_parts(&self) -> Option<(usize, usize, usize, &[f32])> {
629        if self.has_prism_contract() {
630            return None;
631        }
632        match self {
633            Self::Mapped {
634                idx,
635                dtype: TensorDtype::Q8Row,
636                rows,
637                cols,
638                row_scale,
639                col_field,
640                ..
641            } if col_field.is_empty() => Some((*idx, *rows, *cols, row_scale)),
642            _ => None,
643        }
644    }
645
646    /// (directory idx, rows, cols, row_scale, col_field) of a q8_2f mapped
647    /// tensor — the chunk-prefill graph stages x·col on the device first.
648    pub(crate) fn q8_2f_parts(&self) -> Option<(usize, usize, usize, &[f32], &[f32])> {
649        if self.has_prism_contract() {
650            return None;
651        }
652        match self {
653            Self::Mapped {
654                idx,
655                dtype: TensorDtype::Q8_2f,
656                rows,
657                cols,
658                row_scale,
659                col_field,
660                ..
661            } if col_field.len() == *cols => Some((*idx, *rows, *cols, row_scale, col_field)),
662            _ => None,
663        }
664    }
665
666    /// The layout this tensor is stored in, when it is mapped from a model.
667    /// The frames branch on it — a q2tp gate against a q4tp down is a real
668    /// combination in the 2-bit profile and needs a different kernel.
669    pub fn model_dtype(&self) -> Option<cortiq_core::TensorDtype> {
670        match self {
671            Self::Mapped { dtype, .. } => Some(*dtype),
672            _ => None,
673        }
674    }
675
676    /// The tensor's index in the model directory, when it is mapped from one.
677    /// The GPU frames bind by index rather than by name — a name lookup per
678    /// layer per token is not free, and the index is what the device cache is
679    /// keyed on anyway.
680    pub fn model_idx(&self) -> Option<usize> {
681        match self {
682            Self::Mapped { idx, .. } => Some(*idx),
683            _ => None,
684        }
685    }
686
687    /// The model this tensor is mapped from, when it is mapped at all. The
688    /// GPU frames need the container to reach the bytes; a QTensor already
689    /// holds it, and threading a second handle down every call site to say
690    /// the same thing invites the two to disagree.
691    pub fn model_arc(&self) -> Option<std::sync::Arc<cortiq_core::CmfModel>> {
692        match self {
693            Self::Mapped { model, .. } => Some(model.clone()),
694            _ => None,
695        }
696    }
697
698    /// The mapped byte ranges decoding row `r` reads, as (address, length),
699    /// appended to `out`: what a caller hands the kernel as read-ahead advice
700    /// before a batch of row lookups in a table the page cache does not
701    /// hold. `false`, and nothing appended, for a tensor that is not mapped
702    /// or a codec whose rows have no fixed address.
703    pub fn row_spans(&self, r: usize, out: &mut Vec<(usize, usize)>) -> bool {
704        let Self::Mapped { dtype, .. } = self else {
705            return false;
706        };
707        let Some(spans) = row_span_offsets(*dtype, self.rows(), self.cols(), r) else {
708            return false;
709        };
710        let base = self.quant_bytes().as_ptr() as usize;
711        out.extend(spans.iter().filter(|s| s.1 > 0).map(|&(o, n)| (base + o, n)));
712        true
713    }
714
715    /// Whether this mapped tensor belongs to the Prism/Bonsai transform
716    /// contract.  Device graphs do not carry the descriptor, so callers use
717    /// this conservative predicate to stay on the descriptor-aware CPU path
718    /// instead of silently executing an unrotated matrix.
719    pub(crate) fn has_prism_contract(&self) -> bool {
720        matches!(self, Self::Mapped { model, .. } if crate::prism::has_contract(model))
721    }
722
723    pub fn rows(&self) -> usize {
724        match self {
725            Self::F32 { rows, .. } | Self::Mapped { rows, .. } => *rows,
726            Self::Blr(t) => t.rows,
727        }
728    }
729
730    /// Mapped q4t handle (model + directory index) — the fused GPU FFN
731    /// needs the raw file coordinates of its three projections.
732    pub(crate) fn mapped_q4t(&self) -> Option<(&Arc<CmfModel>, usize)> {
733        if self.has_prism_contract() {
734            return None;
735        }
736        match self {
737            Self::Mapped {
738                model,
739                idx,
740                dtype: TensorDtype::Q4Tiled,
741                ..
742            } => Some((model, *idx)),
743            _ => None,
744        }
745    }
746
747    /// Same slot as `mapped_q4t` for a q4tp tensor — the fused DiT FFN picks
748    /// its kernels by which of the two answers.
749    pub fn mapped_q4tp(&self) -> Option<(&Arc<CmfModel>, usize)> {
750        if self.has_prism_contract() {
751            return None;
752        }
753        match self {
754            Self::Mapped {
755                model,
756                idx,
757                dtype: TensorDtype::Q4TiledP,
758                ..
759            } => Some((model, *idx)),
760            _ => None,
761        }
762    }
763
764    /// (model, tensor idx) for a mapped weight in ANY codec the fused device
765    /// paths can run — four-bit tiled or either int8 layout.
766    ///
767    /// The fused DiT chains asked for `mapped_q4tp` by name, so an eight-bit
768    /// container never reached them and rendered through per-op GEMMs even
769    /// after those kernels learned its codec. The gate is what the codec has
770    /// a device GEMM for, not which codec it is.
771    pub fn mapped_device_gemm(&self) -> Option<(&Arc<CmfModel>, usize)> {
772        if self.has_prism_contract() {
773            return None;
774        }
775        match self {
776            Self::Mapped {
777                model,
778                idx,
779                dtype: TensorDtype::Q4TiledP | TensorDtype::Q8Row | TensorDtype::Q8_2f,
780                ..
781            } => Some((model, *idx)),
782            _ => None,
783        }
784    }
785
786    /// (model, tensor idx) for a q8_2f mapped weight — the eight-bit slot of
787    /// the MoE graph ladder (int8 body, f16 row scales, f16 column field).
788    pub fn mapped_q8_2f(&self) -> Option<(&Arc<CmfModel>, usize)> {
789        if self.has_prism_contract() {
790            return None;
791        }
792        match self {
793            Self::Mapped {
794                model,
795                idx,
796                dtype: TensorDtype::Q8_2f,
797                ..
798            } => Some((model, *idx)),
799            _ => None,
800        }
801    }
802
803    /// (model, tensor idx) for a q2tp mapped weight — the 2-bit twin of
804    /// `mapped_q4tp`, used by the mixed MoE profile.
805    pub fn mapped_q2tp(&self) -> Option<(&Arc<CmfModel>, usize)> {
806        if self.has_prism_contract() {
807            return None;
808        }
809        match self {
810            Self::Mapped {
811                model,
812                idx,
813                dtype: TensorDtype::Q2TiledP,
814                ..
815            } => Some((model, *idx)),
816            _ => None,
817        }
818    }
819
820    pub fn cols(&self) -> usize {
821        match self {
822            Self::F32 { cols, .. } | Self::Mapped { cols, .. } => *cols,
823            Self::Blr(t) => t.cols,
824        }
825    }
826
827    /// (model, tensor idx) for a q1 mapped weight — the wgpu token graph
828    /// keys its resident VRAM cache by idx. None for any other dtype/kind.
829    pub fn mapped_q1(&self) -> Option<(&std::sync::Arc<CmfModel>, usize)> {
830        if self.has_prism_contract() {
831            return None;
832        }
833        match self {
834            Self::Mapped {
835                model,
836                idx,
837                dtype: TensorDtype::Q1,
838                ..
839            } => Some((model, *idx)),
840            _ => None,
841        }
842    }
843
844    /// (model, idx, kind, row_scale) for a graph-capable mapped weight.
845    /// kind: 0=q8_row (per-row scales), 1=q1, 2=q4_block, 3=q1t
846    /// (tile-embedded, no rs), 5=q4_tiled, 6=q4tp, 7=q8_2f (both scale
847    /// planes live inside the tensor), 9=q2tp, 10=q1g (sign + scale
848    /// planes). None only for `vbit`.
849    ///
850    /// The old comment here claimed q4_block was unhandled while the arm
851    /// right below mapped it, and it named q8_2f as unhandled after that
852    /// stopped being true — a stale comment on this function is how a
853    /// model silently loses the graph, so it is worth keeping honest.
854    pub fn graph_weight(&self) -> Option<(&std::sync::Arc<CmfModel>, usize, u8, &[f32])> {
855        if self.has_prism_contract() {
856            return None;
857        }
858        self.graph_weight_descriptor()
859    }
860
861    /// Descriptor-aware graph handle used only by the Prism token graph.
862    /// Ordinary graph callers continue to use [`graph_weight`] and therefore
863    /// remain fail-closed until they provide the same explicit transform
864    /// contract.
865    pub(crate) fn graph_weight_descriptor(
866        &self,
867    ) -> Option<(&std::sync::Arc<CmfModel>, usize, u8, &[f32])> {
868        match self {
869            Self::Mapped {
870                model,
871                idx,
872                dtype: TensorDtype::Q8Row,
873                row_scale,
874                ..
875            } => Some((model, *idx, 0, row_scale.as_slice())),
876            Self::Mapped {
877                model,
878                idx,
879                dtype: TensorDtype::Q1,
880                ..
881            } => Some((model, *idx, 1, &[])),
882            // Kind 10, never 1: q1g's sign and scale planes are a different
883            // walk from q1's 6-byte tiles (the kind-2/5 mixup taught that).
884            Self::Mapped {
885                model,
886                idx,
887                dtype: TensorDtype::Q1G,
888                ..
889            } => Some((model, *idx, 10, &[])),
890            // Q4Tiled is kind 5, NOT 2: both carried 2 historically, and
891            // the wgpu token graph fed 18B interleaved tiles to the
892            // split-layout q4b kernel — garbage output on q4t models
893            // (caught by an end-to-end answer check on real Vulkan).
894            Self::Mapped {
895                model,
896                idx,
897                dtype: TensorDtype::Q4Tiled,
898                ..
899            } => Some((model, *idx, 5, &[])),
900            // Kind 6, not 5: q4tp's nibble stride and scale planes differ,
901            // and feeding them to the q4t kernel is exactly the mistake that
902            // produced garbage when Q4Tiled shared kind 2 with Q4Block.
903            Self::Mapped {
904                model,
905                idx,
906                dtype: TensorDtype::Q4TiledP,
907                ..
908            } => Some((model, *idx, 6, &[])),
909            Self::Mapped {
910                model,
911                idx,
912                dtype: TensorDtype::Q4Block,
913                ..
914            } => Some((model, *idx, 2, &[])),
915            // q8_2f carries BOTH scale planes after the int8 body (rows
916            // f16, then cols f16), so the graph takes the whole tensor
917            // and the kernel reads them where they lie — no host-side
918            // prescale, which is what the per-op path does instead.
919            Self::Mapped {
920                model,
921                idx,
922                dtype: TensorDtype::Q8_2f,
923                ..
924            } => Some((model, *idx, 7, &[])),
925            Self::Mapped {
926                model,
927                idx,
928                dtype: TensorDtype::Q1T,
929                ..
930            } => Some((model, *idx, 3, &[])),
931            // Kind 9: the 2-bit plane on the q4tp ladder (dense FFN gate/up
932            // of the q2tp profile). Its own kernel — 8 bytes a group where
933            // q4tp has 16, and rung 0 is the exact zero.
934            Self::Mapped {
935                model,
936                idx,
937                dtype: TensorDtype::Q2TiledP,
938                ..
939            } => Some((model, *idx, 9, &[])),
940            _ => None,
941        }
942    }
943
944    /// Dense f32 view — only for owned tensors. Masked/sparse execution
945    /// paths require it; quantized weights don't support masks yet.
946    /// The parts of a `q8_2f` tensor: codes by row, row scales, column field.
947    pub fn q8_2f_codes(&self) -> Option<(&[u8], &[f32], &[f32])> {
948        match self {
949            Self::Mapped { dtype: TensorDtype::Q8_2f, row_scale, col_field, .. } => {
950                Some((self.quant_bytes(), row_scale, col_field))
951            }
952            _ => None,
953        }
954    }
955
956    pub fn as_f32(&self) -> Option<&[f32]> {
957        match self {
958            Self::F32 { data, .. } => Some(data),
959            Self::Mapped { .. } | Self::Blr(_) => None,
960        }
961    }
962
963    /// The tensor's bytes in the file, for a device that takes them as they are.
964    pub fn mapped_bytes(&self) -> Option<&[u8]> {
965        match self {
966            Self::Mapped { .. } => Some(self.quant_bytes()),
967            _ => None,
968        }
969    }
970
971    fn quant_bytes(&self) -> &[u8] {
972        match self {
973            Self::Mapped { model, idx, .. } => model.entry_bytes(&model.tensors[*idx]),
974            Self::Blr(t) => t.bytes(),
975            Self::F32 { .. } => unreachable!("quant_bytes on F32"),
976        }
977    }
978
979    /// Dequantize one row into `dst` (embedding lookup).
980    pub fn row_f32(&self, r: usize, dst: &mut [f32]) {
981        let cols = self.cols();
982        debug_assert_eq!(dst.len(), cols);
983        match self {
984            Self::F32 { data, .. } => dst.copy_from_slice(&data[r * cols..(r + 1) * cols]),
985            Self::Blr(t) => t.row_f32(r, dst),
986            Self::Mapped {
987                model,
988                idx,
989                dtype,
990                row_scale,
991                col_field,
992                vbit_offsets,
993                ..
994            } => {
995                if *dtype == TensorDtype::Q4Tiled {
996                    let bytes = self.quant_bytes();
997                    let gpr = cols / GROUP_SIZE;
998                    for gi in 0..gpr {
999                        let tile = &bytes[(r * gpr + gi) * Q4_TILE..(r * gpr + gi + 1) * Q4_TILE];
1000                        let s = f16_to_f32(u16::from_le_bytes([tile[0], tile[1]]));
1001                        for (k, &b) in tile[2..].iter().enumerate() {
1002                            dst[gi * GROUP_SIZE + k * 2] = ((b & 0x0F) as f32 - 8.0) * s;
1003                            dst[gi * GROUP_SIZE + k * 2 + 1] = (((b >> 4) & 0x0F) as f32 - 8.0) * s;
1004                        }
1005                    }
1006                    if crate::prism::is_inverse_embedding(model, &model.tensors[*idx].name) {
1007                        crate::prism::inverse_embedding(model, dst);
1008                    }
1009                    return;
1010                }
1011                if *dtype == TensorDtype::Q4TiledP {
1012                    let bytes = self.quant_bytes();
1013                    let gpr = cols / GROUP_SIZE;
1014                    let v = Q4tpView::new(bytes, self.rows(), cols);
1015                    let mut sc = vec![0f32; gpr];
1016                    v.scales_into(r, gpr, &mut sc);
1017                    for gi in 0..gpr {
1018                        let tile = &v.nib[(r * gpr + gi) * Q4TP_NIB..(r * gpr + gi + 1) * Q4TP_NIB];
1019                        let s = sc[gi];
1020                        for (k, &b) in tile.iter().enumerate() {
1021                            dst[gi * GROUP_SIZE + k * 2] = ((b & 0x0F) as f32 - 8.0) * s;
1022                            dst[gi * GROUP_SIZE + k * 2 + 1] = (((b >> 4) & 0x0F) as f32 - 8.0) * s;
1023                        }
1024                    }
1025                    if crate::prism::is_inverse_embedding(model, &model.tensors[*idx].name) {
1026                        crate::prism::inverse_embedding(model, dst);
1027                    }
1028                    return;
1029                }
1030                if *dtype == TensorDtype::Q2TiledP {
1031                    let bytes = self.quant_bytes();
1032                    let gpr = cols / GROUP_SIZE;
1033                    let v = Q4tpView::new_q2(bytes, self.rows(), cols);
1034                    let mut sc = vec![0f32; gpr];
1035                    v.scales_into(r, gpr, &mut sc);
1036                    for gi in 0..gpr {
1037                        let ch =
1038                            &v.nib[(r * gpr + gi) * Q2TP_CHUNK..(r * gpr + gi + 1) * Q2TP_CHUNK];
1039                        let s = sc[gi];
1040                        for (k, &b) in ch.iter().enumerate() {
1041                            for j in 0..4 {
1042                                let center = if crate::prism::is_affine_target(
1043                                    model,
1044                                    &model.tensors[*idx].name,
1045                                ) {
1046                                    1.0
1047                                } else {
1048                                    1.5
1049                                };
1050                                dst[gi * GROUP_SIZE + k * 4 + j] =
1051                                    (((b >> (2 * j)) & 3) as f32 - center) * s;
1052                            }
1053                        }
1054                    }
1055                    if crate::prism::is_inverse_embedding(model, &model.tensors[*idx].name) {
1056                        crate::prism::inverse_embedding(model, dst);
1057                    }
1058                    return;
1059                }
1060                if *dtype == TensorDtype::Q4Block {
1061                    let (packed, scales) = q4_split(self.quant_bytes(), self.rows(), cols);
1062                    let gpr = cols / GROUP_SIZE;
1063                    for gi in 0..gpr {
1064                        let g = r * gpr + gi;
1065                        let s = f16_to_f32(u16::from_le_bytes([scales[g * 2], scales[g * 2 + 1]]));
1066                        for (k, &b) in packed[g * 16..(g + 1) * 16].iter().enumerate() {
1067                            dst[gi * GROUP_SIZE + k * 2] = ((b & 0x0F) as f32 - 8.0) * s;
1068                            dst[gi * GROUP_SIZE + k * 2 + 1] = (((b >> 4) & 0x0F) as f32 - 8.0) * s;
1069                        }
1070                    }
1071                    if crate::prism::is_inverse_embedding(model, &model.tensors[*idx].name) {
1072                        crate::prism::inverse_embedding(model, dst);
1073                    }
1074                    return;
1075                }
1076                if *dtype == TensorDtype::Mxfp4 {
1077                    mxfp4::Mx::new(self.quant_bytes(), self.rows(), cols).row_f32(r, dst);
1078                    if crate::prism::is_inverse_embedding(model, &model.tensors[*idx].name) {
1079                        crate::prism::inverse_embedding(model, dst);
1080                    }
1081                    return;
1082                }
1083                if *dtype == TensorDtype::Nvfp4 {
1084                    nvfp4::Nv::new(self.quant_bytes(), self.rows(), cols).row_f32(r, dst);
1085                    return;
1086                }
1087                if *dtype == TensorDtype::Q1 {
1088                    let bytes = self.quant_bytes();
1089                    let gpr = cols / GROUP_SIZE;
1090                    for gi in 0..gpr {
1091                        let tile = &bytes[(r * gpr + gi) * Q1_TILE..(r * gpr + gi + 1) * Q1_TILE];
1092                        let s = f16_to_f32(u16::from_le_bytes([tile[0], tile[1]]));
1093                        for (j, &b) in tile[2..].iter().enumerate() {
1094                            for k in 0..8 {
1095                                dst[gi * GROUP_SIZE + j * 8 + k] =
1096                                    (((b >> k) & 1) as f32 * 2.0 - 1.0) * s;
1097                            }
1098                        }
1099                    }
1100                    if crate::prism::is_inverse_embedding(model, &model.tensors[*idx].name) {
1101                        crate::prism::inverse_embedding(model, dst);
1102                    }
1103                    return;
1104                }
1105                if *dtype == TensorDtype::Q1G {
1106                    // The tied Bonsai embedding is q1g too: one row = cols/8
1107                    // sign bytes + cols/128 scales, same ±s values as q1.
1108                    let bytes = self.quant_bytes();
1109                    let sc_off = cortiq_core::quant::q1g_scale_offset(self.rows(), cols);
1110                    let gpr = cols / GROUP_SIZE;
1111                    for gi in 0..gpr {
1112                        let t = r * gpr + gi;
1113                        let s = f16_to_f32(q1g_scale_bits(bytes, sc_off, t));
1114                        for (j, &b) in bytes[t * 4..t * 4 + 4].iter().enumerate() {
1115                            for k in 0..8 {
1116                                dst[gi * GROUP_SIZE + j * 8 + k] =
1117                                    (((b >> k) & 1) as f32 * 2.0 - 1.0) * s;
1118                            }
1119                        }
1120                    }
1121                    if crate::prism::is_inverse_embedding(model, &model.tensors[*idx].name) {
1122                        crate::prism::inverse_embedding(model, dst);
1123                    }
1124                    return;
1125                }
1126                if *dtype == TensorDtype::Q1T {
1127                    let bytes = self.quant_bytes();
1128                    let gpr = cols / GROUP_SIZE;
1129                    let base_len = self.rows() * gpr * cortiq_core::quant::Q1T_TILE;
1130                    for gi in 0..gpr {
1131                        let off = (r * gpr + gi) * cortiq_core::quant::Q1T_TILE;
1132                        let s = cortiq_core::quant::f16_to_f32(u16::from_le_bytes([
1133                            bytes[off],
1134                            bytes[off + 1],
1135                        ]));
1136                        let codes = &bytes[off + 2..off + cortiq_core::quant::Q1T_TILE];
1137                        for k in 0..GROUP_SIZE {
1138                            dst[gi * GROUP_SIZE + k] = match cortiq_core::quant::q1t_code(codes, k)
1139                            {
1140                                1 => s,
1141                                2 => -s,
1142                                _ => 0.0,
1143                            };
1144                        }
1145                    }
1146                    // Overlay
1147                    let rows = self.rows();
1148                    let entries = base_len + (rows + 1) * 4;
1149                    if entries <= bytes.len() {
1150                        let ptrs = &bytes[base_len..base_len + (rows + 1) * 4];
1151                        let r0 = u32::from_le_bytes([
1152                            ptrs[r * 4],
1153                            ptrs[r * 4 + 1],
1154                            ptrs[r * 4 + 2],
1155                            ptrs[r * 4 + 3],
1156                        ]) as usize;
1157                        let r1 = u32::from_le_bytes([
1158                            ptrs[(r + 1) * 4],
1159                            ptrs[(r + 1) * 4 + 1],
1160                            ptrs[(r + 1) * 4 + 2],
1161                            ptrs[(r + 1) * 4 + 3],
1162                        ]) as usize;
1163                        let off = entries + r0 * 4;
1164                        for i in 0..r1 - r0 {
1165                            let item = &bytes[off + i * 4..off + i * 4 + 4];
1166                            let c = u16::from_le_bytes([item[0], item[1]]) as usize;
1167                            let v = cortiq_core::quant::f16_to_f32(u16::from_le_bytes([
1168                                item[2], item[3],
1169                            ]));
1170                            if c < cols {
1171                                dst[c] = v;
1172                            }
1173                        }
1174                    }
1175                    if crate::prism::is_inverse_embedding(model, &model.tensors[*idx].name) {
1176                        crate::prism::inverse_embedding(model, dst);
1177                    }
1178                    return;
1179                }
1180                if matches!(dtype, TensorDtype::Vbit | TensorDtype::VbitRo) {
1181                    let bytes = self.quant_bytes();
1182                    let rows = self.rows();
1183                    let ng = cols / GROUP_SIZE;
1184                    let bits = &bytes[..rows];
1185                    let sc_off = rows;
1186                    // Precomputed at load — embedding lookup used to scan
1187                    // the bit-widths of every preceding row (O(token_id)).
1188                    let off = vbit_offsets[r];
1189                    let b = bits[r] as usize;
1190                    let l = ((1usize << (b - 1)) - 1) as f32;
1191                    let data = &bytes[off..];
1192                    let (mut acc, mut nbits, mut byte_idx) = (0u64, 0usize, 0usize);
1193                    for (i, d) in dst.iter_mut().enumerate() {
1194                        while nbits < b {
1195                            acc = (acc << 8) | data[byte_idx] as u64;
1196                            byte_idx += 1;
1197                            nbits += 8;
1198                        }
1199                        let u = ((acc >> (nbits - b)) & ((1u64 << b) - 1)) as f32;
1200                        nbits -= b;
1201                        let so = (r * ng + i / GROUP_SIZE) * 2;
1202                        let sv = f16_to_f32(u16::from_le_bytes([
1203                            bytes[sc_off + so],
1204                            bytes[sc_off + so + 1],
1205                        ]));
1206                        *d = (u - l) * sv;
1207                    }
1208                    if crate::prism::is_inverse_embedding(model, &model.tensors[*idx].name) {
1209                        crate::prism::inverse_embedding(model, dst);
1210                    }
1211                    return;
1212                }
1213                let q = &self.quant_bytes()[r * cols..(r + 1) * cols];
1214                let s = row_scale[r];
1215                match dtype {
1216                    TensorDtype::Q8Row => {
1217                        for (d, &b) in dst.iter_mut().zip(q) {
1218                            *d = (b as i8) as f32 * s;
1219                        }
1220                    }
1221                    TensorDtype::Q8_2f => {
1222                        for (i, (d, &b)) in dst.iter_mut().zip(q).enumerate() {
1223                            *d = (b as i8) as f32 * s * col_field[i];
1224                        }
1225                    }
1226                    _ => unreachable!(),
1227                }
1228                if crate::prism::is_inverse_embedding(model, &model.tensors[*idx].name) {
1229                    crate::prism::inverse_embedding(model, dst);
1230                }
1231            }
1232        }
1233    }
1234
1235    /// Can this tensor's columns be read cheaply (for sparse down_proj)?
1236    /// True for F32/Q8Row/Q8_2f (per-row scale, direct strided access);
1237    /// false for group-packed q4/vbit (column access would unpack whole
1238    /// groups — sparse execution falls back to f32 for those).
1239    pub fn sparse_col_ok(&self) -> bool {
1240        match self {
1241            Self::F32 { .. } => true,
1242            Self::Blr(_) => false,
1243            Self::Mapped { dtype, .. } => {
1244                matches!(dtype, TensorDtype::Q8Row | TensorDtype::Q8_2f)
1245            }
1246        }
1247    }
1248
1249    /// down_proj [hidden, inter]: accumulate `w · col(c)` into `out`
1250    /// [hidden] — reads ONLY column `c` (one neuron) from the mmap,
1251    /// no full-matrix dequant. `out[k] += w · down[k, c]`.
1252    pub fn add_col_scaled(&self, c: usize, w: f32, out: &mut [f32]) {
1253        let inter = self.cols();
1254        let hidden = self.rows();
1255        debug_assert_eq!(out.len(), hidden);
1256        match self {
1257            Self::F32 { data, .. } => {
1258                for (k, o) in out.iter_mut().enumerate() {
1259                    *o += w * data[k * inter + c];
1260                }
1261            }
1262            Self::Blr(t) => t.add_col_scaled(c, w, out),
1263            Self::Mapped {
1264                dtype,
1265                row_scale,
1266                col_field,
1267                ..
1268            } => {
1269                let q = self.quant_bytes();
1270                let colf = if *dtype == TensorDtype::Q8_2f {
1271                    col_field[c]
1272                } else {
1273                    1.0
1274                };
1275                let wc = w * colf;
1276                for (k, o) in out.iter_mut().enumerate() {
1277                    let b = q[k * inter + c] as i8 as f32;
1278                    *o += wc * b * row_scale[k];
1279                }
1280            }
1281        }
1282    }
1283
1284    /// Touch the head of row `r` so the DRAM latency of the next
1285    /// neuron's weights overlaps the current one's arithmetic.
1286    ///
1287    /// Scattered rows are what per-token sparsity reads, and a 2 KB
1288    /// stride is past what the hardware prefetcher follows: without this
1289    /// every row starts with a cold miss that nothing hides. One touch
1290    /// per 512 bytes is enough — the rest of the row is a sequential run
1291    /// the prefetcher does pick up.
1292    #[inline]
1293    pub fn prefetch_row(&self, r: usize) {
1294        let Self::Mapped { dtype, .. } = self else {
1295            return;
1296        };
1297        if !matches!(dtype, TensorDtype::Q8Row | TensorDtype::Q8_2f) {
1298            return;
1299        }
1300        let cols = self.cols();
1301        let q = self.quant_bytes();
1302        let (a, b) = (r * cols, (r + 1) * cols);
1303        if b > q.len() {
1304            return;
1305        }
1306        let mut j = a;
1307        while j < b {
1308            unsafe { std::ptr::read_volatile(q.as_ptr().add(j)) };
1309            j += 512;
1310        }
1311    }
1312
1313    /// `out += w · row(r)` — the transposed twin of `add_col_scaled`.
1314    ///
1315    /// A neuron's `down` weights are a COLUMN of `[hidden, inter]`, and a
1316    /// column is strided: reading one costs a cache line per element, so
1317    /// per-neuron dynamic sparsity saves arithmetic and no bytes. Stored
1318    /// transposed (`down_proj.t.weight`, `[inter, hidden]`) the same
1319    /// weights are a contiguous ROW, and this accumulate reads exactly
1320    /// the neurons the token asked for.
1321    pub fn add_row_scaled(&self, r: usize, w: f32, out: &mut [f32], scratch: &mut [f32]) {
1322        let cols = self.cols();
1323        debug_assert_eq!(out.len(), cols);
1324        match self {
1325            Self::F32 { data, .. } => {
1326                let row = &data[r * cols..(r + 1) * cols];
1327                for (o, v) in out.iter_mut().zip(row) {
1328                    *o += w * v;
1329                }
1330            }
1331            Self::Blr(t) => {
1332                let tmp = &mut scratch[..cols];
1333                t.row_f32(r, tmp);
1334                for (o, v) in out.iter_mut().zip(tmp.iter()) {
1335                    *o += w * v;
1336                }
1337            }
1338            Self::Mapped {
1339                dtype,
1340                row_scale,
1341                col_field,
1342                ..
1343            } => match dtype {
1344                TensorDtype::Q8Row => {
1345                    let q = &self.quant_bytes()[r * cols..(r + 1) * cols];
1346                    let ws = w * row_scale[r];
1347                    let row: &[i8] =
1348                        unsafe { std::slice::from_raw_parts(q.as_ptr() as *const i8, q.len()) };
1349                    axpy_i8_f32(out, row, ws);
1350                }
1351                TensorDtype::Q8_2f => {
1352                    let q = &self.quant_bytes()[r * cols..(r + 1) * cols];
1353                    let ws = w * row_scale[r];
1354                    for ((o, b), c) in out.iter_mut().zip(q).zip(col_field) {
1355                        *o += ws * c * (*b as i8 as f32);
1356                    }
1357                }
1358                _ => {
1359                    self.row_f32(r, scratch);
1360                    for (o, v) in out.iter_mut().zip(scratch.iter()) {
1361                        *o += w * v;
1362                    }
1363                }
1364            },
1365        }
1366    }
1367
1368    /// Dot of row `r` with `x` (gate/up active-neuron path). Reads only
1369    /// row `r` from the mmap — no full dequant. q4/vbit dequant the row
1370    /// into `scratch` first (rare for active-FFN weights).
1371    pub fn row_dot(&self, r: usize, x: &[f32], scratch: &mut [f32]) -> f32 {
1372        let cols = self.cols();
1373        match self {
1374            Self::F32 { data, .. } => {
1375                let row = &data[r * cols..(r + 1) * cols];
1376                row.iter().zip(x).map(|(w, v)| w * v).sum()
1377            }
1378            Self::Blr(t) => {
1379                let tmp = &mut scratch[..cols];
1380                t.row_f32(r, tmp);
1381                tmp.iter().zip(x).map(|(w, v)| w * v).sum()
1382            }
1383            Self::Mapped {
1384                model,
1385                idx,
1386                dtype,
1387                row_scale,
1388                col_field,
1389                ..
1390            } => {
1391                let prism_forward =
1392                    crate::prism::is_forward_weight(model, &model.tensors[*idx].name);
1393                if prism_forward {
1394                    let transformed = crate::prism::forward(model, &x[..cols]);
1395                    let gpr = cols / GROUP_SIZE;
1396                    match dtype {
1397                        TensorDtype::Q2TiledP => {
1398                            let v = Q4tpView::new_q2(self.quant_bytes(), self.rows(), cols);
1399                            let mut sc = vec![0f32; gpr];
1400                            v.scales_into(r, gpr, &mut sc);
1401                            if crate::prism::is_affine_target(model, &model.tensors[*idx].name) {
1402                                return q2tp_affine_row_exact(v.nib, r, gpr, &transformed, &sc);
1403                            }
1404                            return q2tp_row_exact(v.nib, r, gpr, &transformed, &sc);
1405                        }
1406                        _ => {
1407                            self.row_f32(r, scratch);
1408                            return scratch.iter().zip(&transformed).map(|(w, v)| w * v).sum();
1409                        }
1410                    }
1411                }
1412                match dtype {
1413                    TensorDtype::Q8Row => {
1414                        let q = &self.quant_bytes()[r * cols..(r + 1) * cols];
1415                        dot_i8_f32(q, x) * row_scale[r]
1416                    }
1417                    TensorDtype::Q8_2f => {
1418                        let q = &self.quant_bytes()[r * cols..(r + 1) * cols];
1419                        dot_i8_col_f32(q, x, col_field) * row_scale[r]
1420                    }
1421                    _ => {
1422                        self.row_f32(r, scratch);
1423                        scratch.iter().zip(x).map(|(w, v)| w * v).sum()
1424                    }
1425                }
1426            }
1427        }
1428    }
1429
1430    /// `out = W · x` (row-major). F32 delegates to the historical
1431    /// bit-exact path; Mapped runs the fused int8 kernel.
1432    pub fn matvec(&self, x: &[f32], out: &mut [f32], pool: Option<&Pool>) {
1433        if self.exact_cpu_default() {
1434            return float_activations_scope(|| self.matvec(x, out, pool));
1435        }
1436        match self {
1437            // NOTE: `out.len()` DRIVES this arm — it computes that many rows,
1438            // and `x.len()` is the stride. A short `out` is legitimate here,
1439            // which is why the check below lives in the Mapped arm only.
1440            Self::F32 { data, .. } => {
1441                if !crate::f32_backend::matvec(data, x, out) {
1442                    matvec_rows(pool, data, x, out);
1443                }
1444            }
1445            Self::Blr(t) => {
1446                if crate::gpu::enabled_here()
1447                    && crate::blr::gpu_wanted()
1448                    && crate::gpu::blr_matmat(t, &x[..t.cols], 1, &mut out[..t.rows])
1449                {
1450                    return;
1451                }
1452                t.matvec(x, out, pool)
1453            }
1454            Self::Mapped {
1455                model,
1456                idx,
1457                dtype,
1458                rows,
1459                cols,
1460                row_scale,
1461                col_field,
1462                vbit_offsets,
1463                repack,
1464            } => {
1465                let _ = (model, idx);
1466                // Every kernel below writes `rows` entries through a raw
1467                // pointer, so a short `out` is an out-of-bounds WRITE, not a
1468                // wrong answer: it scribbles on the allocator's metadata and
1469                // the process aborts much later, somewhere innocent
1470                // (`double free or corruption`, `corrupted double-linked
1471                // list`). The debug_assert two of the kernels carried is
1472                // compiled out of the release — exactly the build where it
1473                // matters. Fail here instead, while the caller is still on
1474                // the stack to be named.
1475                assert!(
1476                    out.len() >= *rows && x.len() >= *cols,
1477                    "matvec {rows}x{cols}: out {} (need {rows}), x {} (need {cols})",
1478                    out.len(),
1479                    x.len(),
1480                );
1481                let prism_forward =
1482                    crate::prism::is_forward_weight(model, &model.tensors[*idx].name);
1483                if *dtype == TensorDtype::Q2TiledP
1484                    && std::env::var("CMF_Q2TP_TRACE").as_deref() == Ok("1")
1485                {
1486                    use std::sync::atomic::{AtomicUsize, Ordering};
1487                    static N: AtomicUsize = AtomicUsize::new(0);
1488                    let n = N.fetch_add(1, Ordering::Relaxed);
1489                    if n < 128 {
1490                        eprintln!(
1491                            "q2tp-dispatch #{n} name={} prism={} rows={} cols={} gpu={} optin={} layer={}",
1492                            model.tensors[*idx].name,
1493                            prism_forward,
1494                            rows,
1495                            cols,
1496                            crate::gpu::enabled_here(),
1497                            crate::gpu::q2tp_gpu_opt_in(),
1498                            crate::gpu::cur_layer(),
1499                        );
1500                    }
1501                }
1502                // Prism stores every manifest-listed forward matrix in the
1503                // signed-Hadamard basis.  The q2tp WGSL path receives that
1504                // transformed vector and an explicit affine bit; codecs
1505                // without a descriptor-aware kernel remain on CPU below.
1506                if prism_forward {
1507                    let transformed = crate::prism::forward(model, &x[..*cols]);
1508                    match dtype {
1509                        TensorDtype::Q4Block => {
1510                            q4matvec(self.quant_bytes(), &transformed, *rows, *cols, out, pool)
1511                        }
1512                        TensorDtype::Q4Tiled => {
1513                            q4t_matvec(self.quant_bytes(), &transformed, *rows, *cols, out, pool)
1514                        }
1515                        TensorDtype::Q4TiledP => {
1516                            q4tp_matvec(self.quant_bytes(), &transformed, *rows, *cols, out, pool)
1517                        }
1518                        TensorDtype::Q2TiledP => {
1519                            let affine =
1520                                crate::prism::is_affine_target(model, &model.tensors[*idx].name);
1521                            if *rows * *cols >= 8_388_608
1522                                && crate::gpu::enabled_here()
1523                                && crate::gpu::q2tp_gpu_opt_in()
1524                            {
1525                                let gpu_ok = if affine {
1526                                    crate::gpu::q2tp_affine_matvec(
1527                                        model,
1528                                        *idx,
1529                                        &transformed,
1530                                        *rows,
1531                                        *cols,
1532                                        out,
1533                                    )
1534                                } else {
1535                                    crate::gpu::q2tp_matvec(
1536                                        model,
1537                                        *idx,
1538                                        &transformed,
1539                                        *rows,
1540                                        *cols,
1541                                        out,
1542                                    )
1543                                };
1544                                if gpu_ok {
1545                                    return;
1546                                }
1547                            }
1548                            if affine {
1549                                q2tp_affine_matvec(
1550                                    self.quant_bytes(),
1551                                    &transformed,
1552                                    *rows,
1553                                    *cols,
1554                                    out,
1555                                    pool,
1556                                )
1557                            } else {
1558                                q2tp_matvec(
1559                                    self.quant_bytes(),
1560                                    &transformed,
1561                                    *rows,
1562                                    *cols,
1563                                    out,
1564                                    pool,
1565                                )
1566                            }
1567                        }
1568                        TensorDtype::Q1 | TensorDtype::Q1G => bin_matvec(
1569                            self.bin_w().expect("binary dtype"),
1570                            &transformed,
1571                            *rows,
1572                            *cols,
1573                            out,
1574                            pool,
1575                        ),
1576                        TensorDtype::Q1T => {
1577                            q1t_matvec(self.quant_bytes(), &transformed, *rows, *cols, out, pool)
1578                        }
1579                        TensorDtype::Mxfp4 => {
1580                            mxfp4::matvec(self.quant_bytes(), &transformed, *rows, *cols, out, pool)
1581                        }
1582                        TensorDtype::Nvfp4 => {
1583                            nvfp4::matvec(self.quant_bytes(), &transformed, *rows, *cols, out, pool)
1584                        }
1585                        TensorDtype::Vbit | TensorDtype::VbitRo => vbitmatvec(
1586                            self.quant_bytes(),
1587                            vbit_offsets,
1588                            &transformed,
1589                            *rows,
1590                            *cols,
1591                            out,
1592                            pool,
1593                        ),
1594                        TensorDtype::Q8Row | TensorDtype::Q8_2f => qmatvec(
1595                            self.quant_bytes(),
1596                            repack,
1597                            row_scale,
1598                            &transformed,
1599                            col_field,
1600                            *dtype,
1601                            *rows,
1602                            *cols,
1603                            out,
1604                            pool,
1605                        ),
1606                        _ => unreachable!("unsupported mapped Prism dtype {dtype:?}"),
1607                    }
1608                    return;
1609                }
1610                if *dtype == TensorDtype::Q4Block {
1611                    // GPU route (wgpu q4b kernel) for large q4_block matvecs —
1612                    // gives NVIDIA/AMD/Intel q4 models a GPU path. Probe keeps
1613                    // the winner; Metal returns false → the CPU kernel below.
1614                    if *rows * *cols >= 8_388_608 && crate::gpu::enabled_here() {
1615                        let t0 = std::time::Instant::now();
1616                        match crate::gpu::probe_arm(crate::gpu::OpClass::Matvec) {
1617                            crate::gpu::ProbeArm::Gpu => {
1618                                if crate::gpu::q4b_matvec(model, *idx, x, *rows, *cols, out) {
1619                                    crate::gpu::probe_record(
1620                                        crate::gpu::OpClass::Matvec,
1621                                        true,
1622                                        t0.elapsed(),
1623                                    );
1624                                    return;
1625                                }
1626                            }
1627                            crate::gpu::ProbeArm::CpuTimed => {
1628                                q4matvec(self.quant_bytes(), x, *rows, *cols, out, pool);
1629                                crate::gpu::probe_record(
1630                                    crate::gpu::OpClass::Matvec,
1631                                    false,
1632                                    t0.elapsed(),
1633                                );
1634                                return;
1635                            }
1636                            crate::gpu::ProbeArm::Cpu => {}
1637                        }
1638                    }
1639                    q4matvec(self.quant_bytes(), x, *rows, *cols, out, pool);
1640                    return;
1641                }
1642                if *dtype == TensorDtype::Q4Tiled {
1643                    // GPU route for large q4t matvecs — the lm_head class,
1644                    // same shape as the q4tp arm below. The probe keeps the
1645                    // winner; a backend without the kernel refuses and the
1646                    // CPU path stays.
1647                    if *rows * *cols >= 8_388_608 && crate::gpu::enabled_here() {
1648                        let t0 = std::time::Instant::now();
1649                        let cls = crate::gpu::matvec_class(*rows, *cols);
1650                        match crate::gpu::probe_arm(cls) {
1651                            crate::gpu::ProbeArm::Gpu => {
1652                                if crate::gpu::q4t_matvec(model, *idx, x, *rows, *cols, out) {
1653                                    crate::gpu::probe_record(cls, true, t0.elapsed());
1654                                    return;
1655                                }
1656                            }
1657                            crate::gpu::ProbeArm::CpuTimed => {
1658                                q4t_matvec(self.quant_bytes(), x, *rows, *cols, out, pool);
1659                                crate::gpu::probe_record(cls, false, t0.elapsed());
1660                                return;
1661                            }
1662                            crate::gpu::ProbeArm::Cpu => {}
1663                        }
1664                    }
1665                    q4t_matvec(self.quant_bytes(), x, *rows, *cols, out, pool);
1666                    return;
1667                }
1668                if *dtype == TensorDtype::Q4TiledP {
1669                    // GPU route for large q4tp matvecs — the lm_head class.
1670                    // On a q4tp checkpoint the head is the biggest single
1671                    // host matvec left in the decode step, and the batched
1672                    // kernel at b=1 already exists on both backends. Probe
1673                    // keeps the winner, same as q4_block above.
1674                    if *rows * *cols >= 8_388_608 && crate::gpu::enabled_here() {
1675                        let t0 = std::time::Instant::now();
1676                        let cls = crate::gpu::matvec_class(*rows, *cols);
1677                        match crate::gpu::probe_arm(cls) {
1678                            crate::gpu::ProbeArm::Gpu => {
1679                                if crate::gpu::q4tp_matvec(model, *idx, x, *rows, *cols, out) {
1680                                    crate::gpu::probe_record(cls, true, t0.elapsed());
1681                                    return;
1682                                }
1683                            }
1684                            crate::gpu::ProbeArm::CpuTimed => {
1685                                q4tp_matvec(self.quant_bytes(), x, *rows, *cols, out, pool);
1686                                crate::gpu::probe_record(cls, false, t0.elapsed());
1687                                return;
1688                            }
1689                            crate::gpu::ProbeArm::Cpu => {}
1690                        }
1691                    }
1692                    q4tp_matvec(self.quant_bytes(), x, *rows, *cols, out, pool);
1693                    return;
1694                }
1695                if *dtype == TensorDtype::Q2TiledP {
1696                    q2tp_matvec(self.quant_bytes(), x, *rows, *cols, out, pool);
1697                    return;
1698                }
1699                if *dtype == TensorDtype::Mxfp4 {
1700                    self.mxfp4_matvec(x, out, pool);
1701                    return;
1702                }
1703                if *dtype == TensorDtype::Nvfp4 {
1704                    nvfp4::matvec(self.quant_bytes(), x, *rows, *cols, out, pool);
1705                    return;
1706                }
1707                if *dtype == TensorDtype::Q1 || *dtype == TensorDtype::Q1G {
1708                    // GPU route for large q1 matvecs (out_proj / lm_head
1709                    // class): the CPU q1 kernel is load-port-bound at
1710                    // ~4 GB/s/core, the GPU one is bandwidth-bound — the
1711                    // probe measures both arms and keeps the winner.
1712                    let w = self.bin_w().expect("binary dtype");
1713                    if *rows * *cols >= 8_388_608 && crate::gpu::enabled_here() {
1714                        let t0 = std::time::Instant::now();
1715                        let arm = if crate::gpu::q1_force() {
1716                            crate::gpu::ProbeArm::Gpu
1717                        } else {
1718                            crate::gpu::probe_arm(crate::gpu::OpClass::Matvec)
1719                        };
1720                        match arm {
1721                            crate::gpu::ProbeArm::Gpu => {
1722                                let ok = if *dtype == TensorDtype::Q1G {
1723                                    crate::gpu::q1g_matvec(model, *idx, x, *rows, *cols, out)
1724                                } else {
1725                                    crate::gpu::q1_matvec(model, *idx, x, *rows, *cols, out)
1726                                };
1727                                if ok {
1728                                    crate::gpu::probe_record(
1729                                        crate::gpu::OpClass::Matvec,
1730                                        true,
1731                                        t0.elapsed(),
1732                                    );
1733                                    return;
1734                                }
1735                            }
1736                            crate::gpu::ProbeArm::CpuTimed => {
1737                                bin_matvec(w, x, *rows, *cols, out, pool);
1738                                crate::gpu::probe_record(
1739                                    crate::gpu::OpClass::Matvec,
1740                                    false,
1741                                    t0.elapsed(),
1742                                );
1743                                return;
1744                            }
1745                            crate::gpu::ProbeArm::Cpu => {}
1746                        }
1747                    }
1748                    bin_matvec(w, x, *rows, *cols, out, pool);
1749                    return;
1750                }
1751                if *dtype == TensorDtype::Q1T {
1752                    // GPU route for large q1t matvecs: the ternary BASE dot runs
1753                    // on the GPU (load-port-bound on CPU, like q1), then the
1754                    // sparse overlay is added on the CPU. Probe keeps the winner.
1755                    if *rows * *cols >= 8_388_608 && crate::gpu::enabled_here() {
1756                        let t0 = std::time::Instant::now();
1757                        match crate::gpu::probe_arm(crate::gpu::OpClass::Matvec) {
1758                            crate::gpu::ProbeArm::Gpu => {
1759                                if crate::gpu::q1t_matvec(model, *idx, x, *rows, *cols, out) {
1760                                    q1t_add_overlay(self.quant_bytes(), x, *rows, *cols, out, pool);
1761                                    crate::gpu::probe_record(
1762                                        crate::gpu::OpClass::Matvec,
1763                                        true,
1764                                        t0.elapsed(),
1765                                    );
1766                                    return;
1767                                }
1768                            }
1769                            crate::gpu::ProbeArm::CpuTimed => {
1770                                q1t_matvec(self.quant_bytes(), x, *rows, *cols, out, pool);
1771                                crate::gpu::probe_record(
1772                                    crate::gpu::OpClass::Matvec,
1773                                    false,
1774                                    t0.elapsed(),
1775                                );
1776                                return;
1777                            }
1778                            crate::gpu::ProbeArm::Cpu => {}
1779                        }
1780                    }
1781                    q1t_matvec(self.quant_bytes(), x, *rows, *cols, out, pool);
1782                    return;
1783                }
1784                if matches!(dtype, TensorDtype::Vbit | TensorDtype::VbitRo) {
1785                    vbitmatvec(self.quant_bytes(), vbit_offsets, x, *rows, *cols, out, pool);
1786                    return;
1787                }
1788                let xs = prescale(x, col_field, *dtype);
1789                // D5: large q8 matrices (lm_head-class) — hybrid
1790                // CPU∥GPU: split the rows, both sides compute
1791                // SIMULTANEOUSLY (same math, shared prescale).
1792                // GPU share: CMF_GPU_SPLIT (0..1, default 0.5).
1793                if *rows >= crate::gpu::min_rows()
1794                    && matches!(dtype, TensorDtype::Q8Row | TensorDtype::Q8_2f)
1795                    && gpu_lmhead_enabled()
1796                    && crate::gpu::enabled_here()
1797                {
1798                    // Runtime probe: alternate the hybrid against the
1799                    // pure-CPU matvec, keep whichever is faster HERE.
1800                    let t0 = std::time::Instant::now();
1801                    match crate::gpu::probe_arm(crate::gpu::OpClass::Matvec) {
1802                        crate::gpu::ProbeArm::Gpu => {}
1803                        crate::gpu::ProbeArm::CpuTimed => {
1804                            qmatvec(
1805                                self.quant_bytes(),
1806                                repack,
1807                                row_scale,
1808                                x,
1809                                col_field,
1810                                *dtype,
1811                                *rows,
1812                                *cols,
1813                                out,
1814                                pool,
1815                            );
1816                            crate::gpu::probe_record(
1817                                crate::gpu::OpClass::Matvec,
1818                                false,
1819                                t0.elapsed(),
1820                            );
1821                            return;
1822                        }
1823                        crate::gpu::ProbeArm::Cpu => {
1824                            qmatvec(
1825                                self.quant_bytes(),
1826                                repack,
1827                                row_scale,
1828                                x,
1829                                col_field,
1830                                *dtype,
1831                                *rows,
1832                                *cols,
1833                                out,
1834                                pool,
1835                            );
1836                            return;
1837                        }
1838                    }
1839                    let frac = gpu_split_frac();
1840                    let cpu_rows = ((*rows as f32) * (1.0 - frac)) as usize;
1841                    let (out_cpu, out_gpu) = out.split_at_mut(cpu_rows);
1842                    let bytes = self.quant_bytes();
1843                    let ok = std::thread::scope(|sc| {
1844                        let g = sc.spawn(|| {
1845                            crate::gpu::q8_matvec_range(
1846                                model,
1847                                *idx,
1848                                cpu_rows,
1849                                &row_scale[cpu_rows..],
1850                                &xs,
1851                                *rows - cpu_rows,
1852                                *cols,
1853                                out_gpu,
1854                            )
1855                        });
1856                        if cpu_rows > 0 {
1857                            // Repack prefix covers the full groups of the
1858                            // CPU half (the split starts at row 0).
1859                            let rep_cpu = if repack.is_empty() {
1860                                &[][..]
1861                            } else {
1862                                &repack[..(cpu_rows / 4) * 4 * *cols]
1863                            };
1864                            qmatvec(
1865                                &bytes[..cpu_rows * *cols],
1866                                rep_cpu,
1867                                &row_scale[..cpu_rows],
1868                                x,
1869                                col_field,
1870                                *dtype,
1871                                cpu_rows,
1872                                *cols,
1873                                out_cpu,
1874                                pool,
1875                            );
1876                        }
1877                        g.join().unwrap_or(false)
1878                    });
1879                    if ok {
1880                        crate::gpu::probe_record(crate::gpu::OpClass::Matvec, true, t0.elapsed());
1881                        return;
1882                    }
1883                    // GPU failed — CPU finishes its half (rows rebased —
1884                    // group offsets don't line up, mmap layout only).
1885                    qmatvec(
1886                        &bytes[cpu_rows * *cols..(*rows) * *cols],
1887                        &[],
1888                        &row_scale[cpu_rows..],
1889                        x,
1890                        col_field,
1891                        *dtype,
1892                        *rows - cpu_rows,
1893                        *cols,
1894                        out_gpu,
1895                        pool,
1896                    );
1897                    return;
1898                }
1899                qmatvec(
1900                    self.quant_bytes(),
1901                    repack,
1902                    row_scale,
1903                    x,
1904                    col_field,
1905                    *dtype,
1906                    *rows,
1907                    *cols,
1908                    out,
1909                    pool,
1910                );
1911            }
1912        }
1913    }
1914
1915    /// Fused two-input matvec (MTP verify pair): weights streamed once.
1916    pub fn matvec2(
1917        &self,
1918        x1: &[f32],
1919        x2: &[f32],
1920        o1: &mut [f32],
1921        o2: &mut [f32],
1922        pool: Option<&Pool>,
1923    ) {
1924        if self.exact_cpu_default() {
1925            return float_activations_scope(|| self.matvec2(x1, x2, o1, o2, pool));
1926        }
1927        match self {
1928            Self::F32 { data, .. } => matvec_rows2(pool, data, x1, x2, o1, o2),
1929            Self::Blr(_) => {
1930                self.matvec(x1, o1, pool);
1931                self.matvec(x2, o2, pool);
1932            }
1933            Self::Mapped {
1934                model,
1935                idx,
1936                dtype,
1937                rows,
1938                cols,
1939                row_scale,
1940                col_field,
1941                vbit_offsets,
1942                ..
1943            } => {
1944                if crate::prism::is_forward_weight(model, &model.tensors[*idx].name) {
1945                    let tx1 = crate::prism::forward(model, &x1[..*cols]);
1946                    let tx2 = crate::prism::forward(model, &x2[..*cols]);
1947                    match dtype {
1948                        TensorDtype::Q4Block => {
1949                            q4matvec2(self.quant_bytes(), &tx1, &tx2, *rows, *cols, o1, o2, pool)
1950                        }
1951                        TensorDtype::Q4Tiled => {
1952                            q4t_matvec2(self.quant_bytes(), &tx1, &tx2, *rows, *cols, o1, o2, pool)
1953                        }
1954                        TensorDtype::Q4TiledP => {
1955                            q4tp_matvec2(self.quant_bytes(), &tx1, &tx2, *rows, *cols, o1, o2, pool)
1956                        }
1957                        TensorDtype::Q2TiledP => {
1958                            if crate::prism::is_affine_target(model, &model.tensors[*idx].name) {
1959                                q2tp_affine_matvec2(
1960                                    self.quant_bytes(),
1961                                    &tx1,
1962                                    &tx2,
1963                                    *rows,
1964                                    *cols,
1965                                    o1,
1966                                    o2,
1967                                    pool,
1968                                )
1969                            } else {
1970                                q2tp_matvec2(
1971                                    self.quant_bytes(),
1972                                    &tx1,
1973                                    &tx2,
1974                                    *rows,
1975                                    *cols,
1976                                    o1,
1977                                    o2,
1978                                    pool,
1979                                )
1980                            }
1981                        }
1982                        TensorDtype::Q1 | TensorDtype::Q1G => bin_matvec2(
1983                            self.bin_w().expect("binary dtype"),
1984                            &tx1,
1985                            &tx2,
1986                            *rows,
1987                            *cols,
1988                            o1,
1989                            o2,
1990                            pool,
1991                        ),
1992                        TensorDtype::Q1T => {
1993                            q1t_matvec2(self.quant_bytes(), &tx1, &tx2, *rows, *cols, o1, o2, pool)
1994                        }
1995                        TensorDtype::Nvfp4 => nvfp4::matvec2(
1996                            self.quant_bytes(),
1997                            &tx1,
1998                            &tx2,
1999                            *rows,
2000                            *cols,
2001                            o1,
2002                            o2,
2003                            pool,
2004                        ),
2005                        TensorDtype::Mxfp4 => mxfp4::matvec2(
2006                            self.quant_bytes(),
2007                            &tx1,
2008                            &tx2,
2009                            *rows,
2010                            *cols,
2011                            o1,
2012                            o2,
2013                            pool,
2014                        ),
2015                        TensorDtype::Vbit | TensorDtype::VbitRo => vbitmatvec2(
2016                            self.quant_bytes(),
2017                            vbit_offsets,
2018                            &tx1,
2019                            &tx2,
2020                            *rows,
2021                            *cols,
2022                            o1,
2023                            o2,
2024                            pool,
2025                        ),
2026                        TensorDtype::Q8Row | TensorDtype::Q8_2f => qmatvec2(
2027                            self.quant_bytes(),
2028                            row_scale,
2029                            &tx1,
2030                            &tx2,
2031                            col_field,
2032                            *dtype,
2033                            *rows,
2034                            *cols,
2035                            o1,
2036                            o2,
2037                            pool,
2038                        ),
2039                        _ => unreachable!("unsupported mapped Prism dtype {dtype:?}"),
2040                    }
2041                    return;
2042                }
2043                if *dtype == TensorDtype::Q4Block {
2044                    q4matvec2(self.quant_bytes(), x1, x2, *rows, *cols, o1, o2, pool);
2045                    return;
2046                }
2047                if *dtype == TensorDtype::Q4Tiled {
2048                    q4t_matvec2(self.quant_bytes(), x1, x2, *rows, *cols, o1, o2, pool);
2049                    return;
2050                }
2051                if *dtype == TensorDtype::Q4TiledP {
2052                    q4tp_matvec2(self.quant_bytes(), x1, x2, *rows, *cols, o1, o2, pool);
2053                    return;
2054                }
2055                if *dtype == TensorDtype::Q2TiledP {
2056                    q2tp_matvec2(self.quant_bytes(), x1, x2, *rows, *cols, o1, o2, pool);
2057                    return;
2058                }
2059                if *dtype == TensorDtype::Mxfp4 {
2060                    mxfp4::matvec2(self.quant_bytes(), x1, x2, *rows, *cols, o1, o2, pool);
2061                    return;
2062                }
2063                if *dtype == TensorDtype::Nvfp4 {
2064                    nvfp4::matvec2(self.quant_bytes(), x1, x2, *rows, *cols, o1, o2, pool);
2065                    return;
2066                }
2067                if let Some(w) = self.bin_w() {
2068                    bin_matvec2(w, x1, x2, *rows, *cols, o1, o2, pool);
2069                    return;
2070                }
2071                if *dtype == TensorDtype::Q1T {
2072                    // Fused ternary pair: one row pass, the register
2073                    // unpack shared across both streams on ARM. (Q1T
2074                    // lacks a row_scale array — scales live inline in
2075                    // the tiles — so it must not fall through to the
2076                    // q8 qmatvec2 below.)
2077                    q1t_matvec2(self.quant_bytes(), x1, x2, *rows, *cols, o1, o2, pool);
2078                    return;
2079                }
2080                if matches!(dtype, TensorDtype::Vbit | TensorDtype::VbitRo) {
2081                    vbitmatvec2(
2082                        self.quant_bytes(),
2083                        vbit_offsets,
2084                        x1,
2085                        x2,
2086                        *rows,
2087                        *cols,
2088                        o1,
2089                        o2,
2090                        pool,
2091                    );
2092                    return;
2093                }
2094                qmatvec2(
2095                    self.quant_bytes(),
2096                    row_scale,
2097                    x1,
2098                    x2,
2099                    col_field,
2100                    *dtype,
2101                    *rows,
2102                    *cols,
2103                    o1,
2104                    o2,
2105                    pool,
2106                );
2107            }
2108        }
2109    }
2110}
2111
2112impl QTensor {
2113    /// Batched matvec (prefill-GEMM): xs — row-major [b, cols],
2114    /// out — row-major [b, rows]. Element-wise semantics are IDENTICAL
2115    /// to b matvec calls (same dot kernels in the same order); the win —
2116    /// the weight row streams from DRAM once per batch, not b times.
2117    /// `(model, index)` when this is a memory-mapped q4tp tensor — the
2118    /// identity a device-resident chain needs to hand `tp_matmat` the
2119    /// weight without going through this struct's own dispatch.
2120    pub fn q4tp_mapped(&self) -> Option<(&std::sync::Arc<CmfModel>, usize)> {
2121        if self.has_prism_contract() {
2122            return None;
2123        }
2124        match self {
2125            Self::Mapped {
2126                model, idx, dtype, ..
2127            } if *dtype == TensorDtype::Q4TiledP => Some((model, *idx)),
2128            _ => None,
2129        }
2130    }
2131
2132    /// `matmat` with the device's dense-plane product tried first, past the
2133    /// probe (CUDA: `h3_matmat`, the codec's plane cached on the card): for a
2134    /// stack whose every weight is touched once a forward (a detector), where
2135    /// the probe never sees a warm weight and keeps the host.
2136    pub fn matmat_dev(&self, xs_all: &[f32], b: usize, out: &mut [f32], pool: Option<&Pool>) {
2137        if b >= 8
2138            && b * self.rows() * self.cols() >= 1 << 24
2139            && crate::gpu::enabled_here()
2140            && let Self::Mapped { model, idx, .. } = self
2141            && crate::gpu::plane_matmat(model, *idx, &xs_all[..b * self.cols()], b, self.rows(), self.cols(), &mut out[..b * self.rows()])
2142        {
2143            return;
2144        }
2145        self.matmat(xs_all, b, out, pool)
2146    }
2147
2148    /// `CMF_CUDA_MM_VERIFY=1`: a device product against f32 rows of the same
2149    /// weight (and the host's own q4tp product), the first three calls of a
2150    /// tensor and every 50th after — printed when the device is off by 1e-3.
2151    fn verify_product(&self, name: &str, xs: &[f32], b: usize, dev: &[f32], pool: Option<&Pool>) {
2152        use std::sync::atomic::{AtomicU64, Ordering};
2153        static CALLS: std::sync::Mutex<Option<std::collections::HashMap<String, u64>>> = std::sync::Mutex::new(None);
2154        static BAD: AtomicU64 = AtomicU64::new(0);
2155        let k = {
2156            let mut m = CALLS.lock().unwrap();
2157            let e = m.get_or_insert_with(Default::default).entry(name.to_string()).or_insert(0);
2158            *e += 1;
2159            *e
2160        };
2161        if k > 3 && k % 50 != 0 {
2162            return;
2163        }
2164        let (rows, cols) = (self.rows(), self.cols());
2165        let mut exact = vec![0f32; b * rows];
2166        let mut w = vec![0f32; cols];
2167        for r in 0..rows {
2168            self.row_f32(r, &mut w);
2169            for bi in 0..b {
2170                let x = &xs[bi * cols..(bi + 1) * cols];
2171                exact[bi * rows + r] = w.iter().zip(x).map(|(a, c)| (*a as f64) * (*c as f64)).sum::<f64>() as f32;
2172            }
2173        }
2174        let mut host = vec![0f32; b * rows];
2175        q4tp_matmat(self.quant_bytes(), xs, b, rows, cols, &mut host, pool);
2176        let rel = |a: &[f32]| {
2177            let d: f64 = a.iter().zip(&exact).map(|(x, y)| ((x - y) as f64).powi(2)).sum();
2178            let n: f64 = exact.iter().map(|y| (*y as f64).powi(2)).sum();
2179            (d / n.max(1e-30)).sqrt()
2180        };
2181        let (rd, rh) = (rel(&dev[..b * rows]), rel(&host));
2182        if rd > 1e-3 {
2183            let bad = BAD.fetch_add(1, Ordering::Relaxed) + 1;
2184            eprintln!("cuda mm verify #{bad}: {name} b={b} {rows}x{cols} call {k}: device rel {rd:.3e}, host q4tp rel {rh:.3e}");
2185        } else if k <= 1 {
2186            eprintln!("cuda mm verify ok: {name} b={b} {rows}x{cols}: device rel {rd:.3e}, host q4tp rel {rh:.3e}");
2187        }
2188    }
2189
2190    pub fn matmat(&self, xs_all: &[f32], b: usize, out: &mut [f32], pool: Option<&Pool>) {
2191        if self.exact_cpu_default() {
2192            return float_activations_scope(|| self.matmat(xs_all, b, out, pool));
2193        }
2194        let cols = self.cols();
2195        let rows = self.rows();
2196        debug_assert_eq!(xs_all.len(), b * cols);
2197        debug_assert_eq!(out.len(), b * rows);
2198        let _prof = crate::cpuprof::time(crate::cpuprof::Slot::Matmat);
2199        // GPTQ calibration: fold this layer's inputs into its Hessian. Only
2200        // Mapped tensors carry a directory name; the check is a relaxed
2201        // atomic load, free when not calibrating.
2202        if crate::gptq_capture::capturing() {
2203            if let Self::Mapped { model, idx, .. } = self {
2204                crate::gptq_capture::accumulate(&model.tensors[*idx].name, xs_all, b, cols);
2205            }
2206            if let Self::Blr(t) = self {
2207                crate::gptq_capture::accumulate(t.name(), xs_all, b, cols);
2208            }
2209        }
2210        match self {
2211            Self::Blr(t) => {
2212                if crate::gpu::enabled_here()
2213                    && crate::blr::gpu_wanted()
2214                    && crate::gpu::blr_matmat(t, &xs_all[..b * cols], b, &mut out[..b * rows])
2215                {
2216                    return;
2217                }
2218                t.matmat(xs_all, b, out, pool)
2219            }
2220            Self::F32 { data, .. } => {
2221                if crate::f32_backend::matmat(data, xs_all, b, rows, cols, out) {
2222                    return;
2223                }
2224                let out_addr = SendMut(out.as_mut_ptr());
2225                // Over the batch, four positions a row at a time: four
2226                // independent chains, each still summing j = 0..cols in the
2227                // scalar order (bit-identical to the one-at-a-time loop and
2228                // to `matvec_rows`). The batch is the wide axis of a prefill;
2229                // the rows may be few (Spark-X2.5's 16-row g_proj spent
2230                // 17 ms a layer here split over its rows).
2231                let kernel = |start: usize, end: usize, r0: usize, r1: usize| {
2232                    let mut bi = start;
2233                    while bi < end {
2234                        let n = (end - bi).min(4);
2235                        for o in r0..r1 {
2236                            let row = &data[o * cols..(o + 1) * cols];
2237                            if n == 4 {
2238                                let x = |k: usize| &xs_all[(bi + k) * cols..(bi + k + 1) * cols];
2239                                let (x0, x1, x2, x3) = (x(0), x(1), x(2), x(3));
2240                                let (mut a0, mut a1, mut a2, mut a3) = (0f32, 0f32, 0f32, 0f32);
2241                                for j in 0..cols {
2242                                    let w = row[j];
2243                                    a0 += w * x0[j];
2244                                    a1 += w * x1[j];
2245                                    a2 += w * x2[j];
2246                                    a3 += w * x3[j];
2247                                }
2248                                for (k, acc) in [a0, a1, a2, a3].into_iter().enumerate() {
2249                                    unsafe { *out_addr.at((bi + k) * rows + o) = acc };
2250                                }
2251                            } else {
2252                                for k in 0..n {
2253                                    let x = &xs_all[(bi + k) * cols..(bi + k + 1) * cols];
2254                                    let mut acc = 0f32;
2255                                    for j in 0..cols {
2256                                        acc += row[j] * x[j];
2257                                    }
2258                                    unsafe { *out_addr.at((bi + k) * rows + o) = acc };
2259                                }
2260                            }
2261                        }
2262                        bi += n;
2263                    }
2264                };
2265                match pool {
2266                    // A chunk shorter than 256 positions (every prefill
2267                    // chunk on a Mac) left the whole GEMM on one core: an
2268                    // f16 CherryPit-1.2-2B scored 512 tokens in minutes.
2269                    // Split the output rows instead; every element keeps
2270                    // its own chain, so the result is bit-identical.
2271                    Some(pool) if b < 256 && rows >= 256 => {
2272                        pool.run_rows(rows, &|r0, r1| kernel(0, b, r0, r1))
2273                    }
2274                    _ => dispatch_rows(pool, b, &|s, e| kernel(s, e, 0, rows)),
2275                }
2276            }
2277            Self::Mapped {
2278                model,
2279                idx,
2280                dtype,
2281                row_scale,
2282                col_field,
2283                vbit_offsets,
2284                ..
2285            } => {
2286                if crate::prism::is_forward_weight(model, &model.tensors[*idx].name) {
2287                    let mut transformed = Vec::with_capacity(xs_all.len());
2288                    for bi in 0..b {
2289                        transformed.extend_from_slice(&crate::prism::forward(
2290                            model,
2291                            &xs_all[bi * cols..(bi + 1) * cols],
2292                        ));
2293                    }
2294                    match dtype {
2295                        TensorDtype::Q4Block => {
2296                            q4matmat(self.quant_bytes(), &transformed, b, rows, cols, out, pool)
2297                        }
2298                        TensorDtype::Q4Tiled => {
2299                            q4t_matmat(self.quant_bytes(), &transformed, b, rows, cols, out, pool)
2300                        }
2301                        TensorDtype::Q4TiledP => {
2302                            q4tp_matmat(self.quant_bytes(), &transformed, b, rows, cols, out, pool)
2303                        }
2304                        TensorDtype::Q2TiledP => {
2305                            let affine =
2306                                crate::prism::is_affine_target(model, &model.tensors[*idx].name);
2307                            // Affine Prism Q2TP has a descriptor-aware GPU
2308                            // kernel for short/tail batches too.  Unlike the
2309                            // ordinary Q2TP path, don't force b<32 back to a
2310                            // scalar CPU matmat: prefill chunks and the final
2311                            // tail both need to stay on the tested GPU arm.
2312                            let gpu_batch_ok = if affine {
2313                                b >= 2
2314                            } else {
2315                                b >= 32 && b * rows * cols >= 128_000_000
2316                            };
2317                            if gpu_batch_ok
2318                                && cols % 32 == 0
2319                                && crate::gpu::enabled_here()
2320                                && crate::gpu::q2tp_gpu_opt_in()
2321                            {
2322                                let gpu_ok = if affine {
2323                                    crate::gpu::q2tp_affine_matmat(
2324                                        model,
2325                                        *idx,
2326                                        &transformed,
2327                                        b,
2328                                        rows,
2329                                        cols,
2330                                        out,
2331                                    )
2332                                } else {
2333                                    crate::gpu::q2tp_matmat(
2334                                        model,
2335                                        *idx,
2336                                        &transformed,
2337                                        b,
2338                                        rows,
2339                                        cols,
2340                                        out,
2341                                    )
2342                                };
2343                                if gpu_ok {
2344                                    return;
2345                                }
2346                            }
2347                            // A one-token Prism decode is the other short
2348                            // case.  Use the descriptor-aware matvec kernel
2349                            // before falling back to the exact CPU path.
2350                            if affine
2351                                && b == 1
2352                                && cols % 32 == 0
2353                                && crate::gpu::enabled_here()
2354                                && crate::gpu::q2tp_gpu_opt_in()
2355                                && crate::gpu::q2tp_affine_matvec(
2356                                    model,
2357                                    *idx,
2358                                    &transformed[..cols],
2359                                    rows,
2360                                    cols,
2361                                    &mut out[..rows],
2362                                )
2363                            {
2364                                return;
2365                            }
2366                            if affine {
2367                                q2tp_affine_matmat(
2368                                    self.quant_bytes(),
2369                                    &transformed,
2370                                    b,
2371                                    rows,
2372                                    cols,
2373                                    out,
2374                                    pool,
2375                                )
2376                            } else {
2377                                q2tp_matmat(
2378                                    self.quant_bytes(),
2379                                    &transformed,
2380                                    b,
2381                                    rows,
2382                                    cols,
2383                                    out,
2384                                    pool,
2385                                )
2386                            }
2387                        }
2388                        TensorDtype::Q1 | TensorDtype::Q1G => bin_matmat(
2389                            self.bin_w().expect("binary dtype"),
2390                            &transformed,
2391                            b,
2392                            rows,
2393                            cols,
2394                            out,
2395                            pool,
2396                        ),
2397                        TensorDtype::Q1T => {
2398                            q1t_matmat(self.quant_bytes(), &transformed, b, rows, cols, out, pool)
2399                        }
2400                        TensorDtype::Mxfp4 => {
2401                            mxfp4::matmat(self.quant_bytes(), &transformed, b, rows, cols, out, pool)
2402                        }
2403                        TensorDtype::Nvfp4 => {
2404                            nvfp4::matmat(self.quant_bytes(), &transformed, b, rows, cols, out, pool)
2405                        }
2406                        TensorDtype::Vbit | TensorDtype::VbitRo => vbitmatmat(
2407                            self.quant_bytes(),
2408                            vbit_offsets,
2409                            &transformed,
2410                            b,
2411                            rows,
2412                            cols,
2413                            out,
2414                            pool,
2415                        ),
2416                        TensorDtype::Q8Row | TensorDtype::Q8_2f => {
2417                            let pre: Vec<std::borrow::Cow<'_, [f32]>> = (0..b)
2418                                .map(|bi| {
2419                                    prescale(
2420                                        &transformed[bi * cols..(bi + 1) * cols],
2421                                        col_field,
2422                                        *dtype,
2423                                    )
2424                                })
2425                                .collect();
2426                            qmatmat(self.quant_bytes(), row_scale, &pre, rows, cols, out, pool)
2427                        }
2428                        _ => unreachable!("unsupported mapped Prism dtype {dtype:?}"),
2429                    }
2430                    return;
2431                }
2432                if *dtype == TensorDtype::Q4Block {
2433                    q4matmat(self.quant_bytes(), xs_all, b, rows, cols, out, pool);
2434                    return;
2435                }
2436                if *dtype == TensorDtype::Mxfp4 {
2437                    self.mxfp4_matmat(xs_all, b, out, pool);
2438                    return;
2439                }
2440                if *dtype == TensorDtype::Nvfp4 {
2441                    nvfp4::matmat(self.quant_bytes(), xs_all, b, rows, cols, out, pool);
2442                    return;
2443                }
2444                if *dtype == TensorDtype::Q4TiledP {
2445                    // GPU batched q4tp GEMM (dequant + f32nt mul_mm on the
2446                    // device); the probe keeps whichever beats the CPU arm.
2447                    // Narrow (prompt-encode) and wide (DiT) batches probe
2448                    // as separate classes — the regimes have opposite
2449                    // winners and one shared verdict locked the wrong arm.
2450                    // Kill switch (gpu::mm_kill): one grossly slow GPU op
2451                    // (a fair-condition op is ≤~100 ms even at 1024px)
2452                    // means the device is contended by another process
2453                    // (e.g. a simulator) — verdicts are per-process, so
2454                    // without the bail the whole render crawls behind
2455                    // someone else's queue.
2456                    // Row-exact batches stay on the host: the device GEMM
2457                    // is an f32 dequant-sgemm, not the host matvec's sum.
2458                    //
2459                    // The native CUDA backend takes every batch of a large
2460                    // matrix, however narrow, and is not arbitrated against
2461                    // the host: its plane is built on the card from the
2462                    // codec's bytes in tens of milliseconds, where a wgpu
2463                    // weight has an upload to amortise and a narrow batch
2464                    // tiles badly. A decode-narrow batch (under 8 rows)
2465                    // takes it only while the plane is cached or fits
2466                    // without evicting another: a stack larger than the
2467                    // cache would otherwise rebuild every plane every token
2468                    // (MiniMax-Music-3's AR at batch 2: 6.4 s a frame).
2469                    if crate::gpu::cuda_active()
2470                        && b >= 2
2471                        && rows * cols >= (1 << 20)
2472                        && cols % 32 == 0
2473                        && !row_exact()
2474                        && crate::gpu::enabled_here()
2475                    {
2476                        if let Self::Mapped { model, idx, .. } = self {
2477                            if (b >= 8 || crate::gpu::cuda_plane_fits(model, *idx))
2478                                && crate::gpu::q4tp_matmat(model, *idx, xs_all, b, rows, cols, out)
2479                            {
2480                                if cuda_mm_verify() {
2481                                    self.verify_product(&model.tensors[*idx].name, xs_all, b, out, pool);
2482                                }
2483                                return;
2484                            }
2485                        }
2486                    }
2487                    if b >= 32
2488                        && b * rows * cols >= 128_000_000
2489                        && cols % 32 == 0
2490                        && !row_exact()
2491                        && !crate::gpu::mm_killed()
2492                        && crate::gpu::enabled_here()
2493                    {
2494                        let class = if b >= 128 {
2495                            crate::gpu::OpClass::MatmatWide
2496                        } else {
2497                            crate::gpu::OpClass::Matmat
2498                        };
2499                        if let Self::Mapped { model, idx, .. } = self {
2500                            // In-process A/B (`CMF_MM_AB=1`). Three
2501                            // wall-clock A/Bs on a shared stand disagreed
2502                            // with each other by 25% on the same change,
2503                            // because the machine drifts between processes
2504                            // and interleaving whole renders does not fix
2505                            // that. Here both arms run back to back on the
2506                            // SAME data inside one call, so whatever the
2507                            // machine is doing, it does to both — and the
2508                            // disagreement between their outputs falls out
2509                            // for free. Doubles the work; a diagnostic,
2510                            // not a mode.
2511                            if crate::mm_ab::on() {
2512                                let mut g = vec![0f32; b * rows];
2513                                let t = std::time::Instant::now();
2514                                let took = crate::gpu::q4tp_matmat(
2515                                    model, *idx, xs_all, b, rows, cols, &mut g,
2516                                );
2517                                let dg = t.elapsed();
2518                                let t = std::time::Instant::now();
2519                                q4tp_matmat(self.quant_bytes(), xs_all, b, rows, cols, out, pool);
2520                                let dc = t.elapsed();
2521                                crate::mm_ab::record(b, rows, cols, took, dg, dc, &g, out);
2522                                return;
2523                            }
2524                            let t0 = std::time::Instant::now();
2525                            // A cold call takes the device arm: its sample
2526                            // is discarded either way, and the upload is
2527                            // what the next step needs.
2528                            let resident = crate::gpu::weight_is_resident(model, *idx);
2529                            match crate::gpu::probe_arm_cold_prefers_gpu(class, resident) {
2530                                crate::gpu::ProbeArm::Gpu => {
2531                                    if crate::gpu::q4tp_matmat(
2532                                        model, *idx, xs_all, b, rows, cols, out,
2533                                    ) {
2534                                        let el = t0.elapsed();
2535                                        // Work-proportional budget: ~8× the
2536                                        // fair-device estimate (+20 ms slack).
2537                                        // An absolute cap missed the worst
2538                                        // case — contended ops sit at
2539                                        // 100–240 ms each and still bury a
2540                                        // render whose fair op is 3–9 ms.
2541                                        // Cold ops (first PSO build, buffer
2542                                        // alloc) are exempt: a one-off
2543                                        // ~50 ms compile is not contention.
2544                                        let flops = 2.0 * b as f64 * rows as f64 * cols as f64;
2545                                        let budget = std::time::Duration::from_secs_f64(
2546                                            flops / 1.5e12 * 8.0 + 0.020,
2547                                        );
2548                                        crate::gpu::mm_budget_check(
2549                                            "q4tp matmat",
2550                                            el,
2551                                            budget,
2552                                            crate::gpu::probe_was_cold() || !resident,
2553                                        );
2554                                        crate::gpu::probe_record(class, true, el);
2555                                        return;
2556                                    }
2557                                }
2558                                crate::gpu::ProbeArm::CpuTimed => {
2559                                    q4tp_matmat(
2560                                        self.quant_bytes(),
2561                                        xs_all,
2562                                        b,
2563                                        rows,
2564                                        cols,
2565                                        out,
2566                                        pool,
2567                                    );
2568                                    crate::gpu::probe_record(class, false, t0.elapsed());
2569                                    return;
2570                                }
2571                                crate::gpu::ProbeArm::Cpu => {}
2572                            }
2573                        }
2574                    }
2575                    q4tp_matmat(self.quant_bytes(), xs_all, b, rows, cols, out, pool);
2576                    return;
2577                }
2578                if *dtype == TensorDtype::Q2TiledP {
2579                    // Same device arm as q4tp, behind the same probe:
2580                    // the planes differ, the dispatch does not. Without
2581                    // this a q2tp file ran its widest projections on the
2582                    // host while the 4-bit one had the card, which is a
2583                    // codec paying for its size twice.
2584                    if b >= 32
2585                        && b * rows * cols >= 128_000_000
2586                        && cols % 32 == 0
2587                        && !crate::gpu::mm_killed()
2588                        && crate::gpu::enabled_here()
2589                    {
2590                        let class = if b >= 128 {
2591                            crate::gpu::OpClass::MatmatWide
2592                        } else {
2593                            crate::gpu::OpClass::Matmat
2594                        };
2595                        if let Self::Mapped { model, idx, .. } = self {
2596                            let t0 = std::time::Instant::now();
2597                            match crate::gpu::probe_arm(class) {
2598                                crate::gpu::ProbeArm::Gpu => {
2599                                    if crate::gpu::q2tp_matmat(
2600                                        model, *idx, xs_all, b, rows, cols, out,
2601                                    ) {
2602                                        crate::gpu::probe_record(class, true, t0.elapsed());
2603                                        return;
2604                                    }
2605                                }
2606                                crate::gpu::ProbeArm::CpuTimed => {
2607                                    q2tp_matmat(
2608                                        self.quant_bytes(),
2609                                        xs_all,
2610                                        b,
2611                                        rows,
2612                                        cols,
2613                                        out,
2614                                        pool,
2615                                    );
2616                                    crate::gpu::probe_record(class, false, t0.elapsed());
2617                                    return;
2618                                }
2619                                crate::gpu::ProbeArm::Cpu => {}
2620                            }
2621                        }
2622                    }
2623                    // Without a host arm a q2tp tensor falls through to
2624                    // the q8 fallback, which reads it at one BYTE per
2625                    // weight — a 2x overrun that killed pool workers
2626                    // mid-prefill while the dispatcher waited forever.
2627                    q2tp_matmat(self.quant_bytes(), xs_all, b, rows, cols, out, pool);
2628                    return;
2629                }
2630                if *dtype == TensorDtype::Q4Tiled {
2631                    // GPU batched q4t GEMM (dequant + f32nt mul_mm on the
2632                    // device); the probe keeps whichever beats the CPU arm.
2633                    // Narrow (prompt-encode) and wide (DiT) batches probe
2634                    // as separate classes — the regimes have opposite
2635                    // winners and one shared verdict locked the wrong arm.
2636                    // Kill switch (gpu::mm_kill): one grossly slow GPU op
2637                    // (a fair-condition op is ≤~100 ms even at 1024px)
2638                    // means the device is contended by another process
2639                    // (e.g. a simulator) — verdicts are per-process, so
2640                    // without the bail the whole render crawls behind
2641                    // someone else's queue.
2642                    if b >= 32
2643                        && b * rows * cols >= 128_000_000
2644                        && cols % 32 == 0
2645                        && !crate::gpu::mm_killed()
2646                        && crate::gpu::enabled_here()
2647                    {
2648                        let class = if b >= 128 {
2649                            crate::gpu::OpClass::MatmatWide
2650                        } else {
2651                            crate::gpu::OpClass::Matmat
2652                        };
2653                        if let Self::Mapped { model, idx, .. } = self {
2654                            let t0 = std::time::Instant::now();
2655                            match crate::gpu::probe_arm(class) {
2656                                crate::gpu::ProbeArm::Gpu => {
2657                                    if crate::gpu::q4t_matmat(
2658                                        model, *idx, xs_all, b, rows, cols, out,
2659                                    ) {
2660                                        let el = t0.elapsed();
2661                                        // Work-proportional budget: ~8× the
2662                                        // fair-device estimate (+20 ms slack).
2663                                        // An absolute cap missed the worst
2664                                        // case — contended ops sit at
2665                                        // 100–240 ms each and still bury a
2666                                        // render whose fair op is 3–9 ms.
2667                                        // Cold ops (first PSO build, buffer
2668                                        // alloc) are exempt: a one-off
2669                                        // ~50 ms compile is not contention.
2670                                        let flops = 2.0 * b as f64 * rows as f64 * cols as f64;
2671                                        let budget = std::time::Duration::from_secs_f64(
2672                                            flops / 1.5e12 * 8.0 + 0.020,
2673                                        );
2674                                        crate::gpu::mm_budget_check(
2675                                            "q4t matmat",
2676                                            el,
2677                                            budget,
2678                                            crate::gpu::probe_was_cold(),
2679                                        );
2680                                        crate::gpu::probe_record(class, true, el);
2681                                        return;
2682                                    }
2683                                }
2684                                crate::gpu::ProbeArm::CpuTimed => {
2685                                    q4t_matmat(
2686                                        self.quant_bytes(),
2687                                        xs_all,
2688                                        b,
2689                                        rows,
2690                                        cols,
2691                                        out,
2692                                        pool,
2693                                    );
2694                                    crate::gpu::probe_record(class, false, t0.elapsed());
2695                                    return;
2696                                }
2697                                crate::gpu::ProbeArm::Cpu => {}
2698                            }
2699                        }
2700                    }
2701                    q4t_matmat(self.quant_bytes(), xs_all, b, rows, cols, out, pool);
2702                    return;
2703                }
2704                if *dtype == TensorDtype::Q1 || *dtype == TensorDtype::Q1G {
2705                    // GPU batched q1 GEMM for wide prefill (q1_mul_mm on the
2706                    // device); the probe keeps whichever beats the CPU matmat.
2707                    // q1g has the twin `q1g_mul_mm` (cols % 128 by format).
2708                    let w = self.bin_w().expect("binary dtype");
2709                    if b >= 32
2710                        && b * rows * cols >= 128_000_000
2711                        && cols % 64 == 0
2712                        && crate::gpu::enabled_here()
2713                    {
2714                        if let Self::Mapped { model, idx, .. } = self {
2715                            let t0 = std::time::Instant::now();
2716                            match crate::gpu::probe_arm(crate::gpu::OpClass::Matmat) {
2717                                crate::gpu::ProbeArm::Gpu => {
2718                                    let ok = if *dtype == TensorDtype::Q1G {
2719                                        crate::gpu::q1g_matmat(
2720                                            model, *idx, xs_all, b, rows, cols, out,
2721                                        )
2722                                    } else {
2723                                        crate::gpu::q1_matmat(
2724                                            model, *idx, xs_all, b, rows, cols, out,
2725                                        )
2726                                    };
2727                                    if ok {
2728                                        crate::gpu::probe_record(
2729                                            crate::gpu::OpClass::Matmat,
2730                                            true,
2731                                            t0.elapsed(),
2732                                        );
2733                                        return;
2734                                    }
2735                                }
2736                                crate::gpu::ProbeArm::CpuTimed => {
2737                                    bin_matmat(w, xs_all, b, rows, cols, out, pool);
2738                                    crate::gpu::probe_record(
2739                                        crate::gpu::OpClass::Matmat,
2740                                        false,
2741                                        t0.elapsed(),
2742                                    );
2743                                    return;
2744                                }
2745                                crate::gpu::ProbeArm::Cpu => {}
2746                            }
2747                        }
2748                    }
2749                    bin_matmat(w, xs_all, b, rows, cols, out, pool);
2750                    return;
2751                }
2752                if *dtype == TensorDtype::Q1T {
2753                    // GPU batched GEMM for wide prefill (base + overlay on the
2754                    // device); probe keeps the winner vs the CPU matmat.
2755                    if b >= 32 && b * rows * cols >= 128_000_000 && crate::gpu::enabled_here() {
2756                        if let Self::Mapped { model, idx, .. } = self {
2757                            let t0 = std::time::Instant::now();
2758                            match crate::gpu::probe_arm(crate::gpu::OpClass::Matmat) {
2759                                crate::gpu::ProbeArm::Gpu => {
2760                                    if crate::gpu::q1t_matmat(
2761                                        model, *idx, xs_all, b, rows, cols, out,
2762                                    ) {
2763                                        crate::gpu::probe_record(
2764                                            crate::gpu::OpClass::Matmat,
2765                                            true,
2766                                            t0.elapsed(),
2767                                        );
2768                                        return;
2769                                    }
2770                                }
2771                                crate::gpu::ProbeArm::CpuTimed => {
2772                                    q1t_matmat(
2773                                        self.quant_bytes(),
2774                                        xs_all,
2775                                        b,
2776                                        rows,
2777                                        cols,
2778                                        out,
2779                                        pool,
2780                                    );
2781                                    crate::gpu::probe_record(
2782                                        crate::gpu::OpClass::Matmat,
2783                                        false,
2784                                        t0.elapsed(),
2785                                    );
2786                                    return;
2787                                }
2788                                crate::gpu::ProbeArm::Cpu => {}
2789                            }
2790                        }
2791                    }
2792                    q1t_matmat(self.quant_bytes(), xs_all, b, rows, cols, out, pool);
2793                    return;
2794                }
2795                if matches!(dtype, TensorDtype::Vbit | TensorDtype::VbitRo) {
2796                    vbitmatmat(
2797                        self.quant_bytes(),
2798                        vbit_offsets,
2799                        xs_all,
2800                        b,
2801                        rows,
2802                        cols,
2803                        out,
2804                        pool,
2805                    );
2806                    return;
2807                }
2808                let _pmp = crate::cpuprof::spans::span("mm.prescale");
2809                let pre: Vec<std::borrow::Cow<'_, [f32]>> = (0..b)
2810                    .map(|bi| prescale(&xs_all[bi * cols..(bi + 1) * cols], col_field, *dtype))
2811                    .collect();
2812                drop(_pmp);
2813                // MiMo verification is a 2–4 row decode panel, not a wide
2814                // prompt GEMM. Keep q8 projections on the same device as
2815                // decode; the generic b>=8 gate otherwise silently moves
2816                // every projection back to CPU. The short wgpu matmat uses
2817                // the same 64-lane reduction as its single-token matvec.
2818                if row_exact()
2819                    && (1..=4).contains(&b)
2820                    && matches!(dtype, TensorDtype::Q8Row | TensorDtype::Q8_2f)
2821                    && crate::gpu::enabled_here()
2822                    && crate::gpu::wgpu_active()
2823                {
2824                    let flat: Vec<f32> = pre.iter().flat_map(|v| v.iter().copied()).collect();
2825                    if crate::gpu::q8_matmat(model, *idx, row_scale, &flat, b, rows, cols, out) {
2826                        return;
2827                    }
2828                }
2829                // D5: large prefill-batch GEMMs — on the GPU (threshold by
2830                // work volume: submission carries b×rows×cols MACs).
2831                // Runtime probe: the naive GEMM shader + sync readback
2832                // lose to the CPU GEMM on slow driver stacks — alternate
2833                // both arms and keep the winner.
2834                // CMF_MATMAT_GPU=0: diagnostic off-switch for this D5
2835                // device arm only (default unchanged). The GPU int8 kernel
2836                // and the CPU int8 kernel are not bit-comparable and differ
2837                // ~1e-2/layer (measured on SAM3), which compounds through
2838                // deep stacks — validation harnesses that need a single
2839                // changed block per run turn the others off with this.
2840                if b >= 8
2841                    && b * rows * cols >= 128_000_000
2842                    && crate::gpu::enabled_here()
2843                    && std::env::var("CMF_MATMAT_GPU").as_deref() != Ok("0")
2844                {
2845                    if let Self::Mapped { model, idx, .. } = self {
2846                        MATMAT_GATE.fetch_add(1, Ordering::Relaxed);
2847                        let t0 = std::time::Instant::now();
2848                        match crate::gpu::probe_arm(crate::gpu::OpClass::Matmat) {
2849                            crate::gpu::ProbeArm::Gpu
2850                                if crate::gpu::probe_deciding(crate::gpu::OpClass::Matmat)
2851                                    && !crate::gpu::q8_resident_or_upload(model, *idx) =>
2852                            {
2853                                // Cold weights during probing: the upload
2854                                // has started, the count runs on the CPU —
2855                                // the GPU arm samples on the next touch.
2856                                let q = self.quant_bytes();
2857                                qmatmat(q, row_scale, &pre, rows, cols, out, pool);
2858                                return;
2859                            }
2860                            crate::gpu::ProbeArm::Gpu => {
2861                                // The two-field codec's own entry first, as
2862                                // `device_matmat` takes it: the column field
2863                                // folds into the weight plane and the GEMM
2864                                // runs on the matrix units. The plain int8
2865                                // entry below is the scalar f32 GEMM — on a
2866                                // Spark-X2.5 4B prefill it ran q|k|v|o at
2867                                // host speed.
2868                                if *dtype == TensorDtype::Q8_2f
2869                                    && std::env::var("CMF_Q8_2F_DEV").as_deref() != Ok("0")
2870                                    && crate::gpu::q8_matmat_2f(
2871                                        model, *idx, row_scale, col_field, xs_all, b, rows,
2872                                        cols, out,
2873                                    )
2874                                {
2875                                    MATMAT_GPU_HIT.fetch_add(1, Ordering::Relaxed);
2876                                    crate::gpu::probe_record(
2877                                        crate::gpu::OpClass::Matmat,
2878                                        true,
2879                                        t0.elapsed(),
2880                                    );
2881                                    return;
2882                                }
2883                                let flat: Vec<f32> =
2884                                    pre.iter().flat_map(|v| v.iter().copied()).collect();
2885                                if crate::gpu::q8_matmat(
2886                                    model, *idx, row_scale, &flat, b, rows, cols, out,
2887                                ) {
2888                                    crate::gpu::probe_record(
2889                                        crate::gpu::OpClass::Matmat,
2890                                        true,
2891                                        t0.elapsed(),
2892                                    );
2893                                    return;
2894                                }
2895                            }
2896                            crate::gpu::ProbeArm::CpuTimed => {
2897                                let q = self.quant_bytes();
2898                                qmatmat(q, row_scale, &pre, rows, cols, out, pool);
2899                                crate::gpu::probe_record(
2900                                    crate::gpu::OpClass::Matmat,
2901                                    false,
2902                                    t0.elapsed(),
2903                                );
2904                                return;
2905                            }
2906                            crate::gpu::ProbeArm::Cpu => {}
2907                        }
2908                    }
2909                }
2910                let q = self.quant_bytes();
2911                qmatmat(q, row_scale, &pre, rows, cols, out, pool);
2912            }
2913        }
2914    }
2915}
2916
2917impl QTensor {
2918    /// `mxfp4` matvec: the wgpu kernel for lm_head/expert-class shapes when
2919    /// the probe prefers the device, else the CPU kernels of
2920    /// `qtensor::mxfp4` (always on native Metal, which has no mxfp4 kernel).
2921    fn mxfp4_matvec(&self, x: &[f32], out: &mut [f32], pool: Option<&Pool>) {
2922        let (rows, cols) = (self.rows(), self.cols());
2923        if let Self::Mapped { model, idx, .. } = self {
2924            if rows * cols >= 8_388_608 && crate::gpu::enabled_here() {
2925                let t0 = std::time::Instant::now();
2926                let cls = crate::gpu::matvec_class(rows, cols);
2927                match crate::gpu::probe_arm(cls) {
2928                    crate::gpu::ProbeArm::Gpu => {
2929                        if crate::gpu::mxfp4_matvec(model, *idx, x, rows, cols, out) {
2930                            crate::gpu::probe_record(cls, true, t0.elapsed());
2931                            return;
2932                        }
2933                    }
2934                    crate::gpu::ProbeArm::CpuTimed => {
2935                        mxfp4::matvec(self.quant_bytes(), x, rows, cols, out, pool);
2936                        crate::gpu::probe_record(cls, false, t0.elapsed());
2937                        return;
2938                    }
2939                    crate::gpu::ProbeArm::Cpu => {}
2940                }
2941            }
2942        }
2943        mxfp4::matvec(self.quant_bytes(), x, rows, cols, out, pool);
2944    }
2945
2946    /// `mxfp4` batched matvec (`xs` `[b, cols]` → `out` `[b, rows]`): the
2947    /// device's batched kernel behind the same probe as the other codecs'
2948    /// GEMMs (never for row-exact batches — the device sums in another
2949    /// order than the host matvec), else the CPU kernels.
2950    fn mxfp4_matmat(&self, xs: &[f32], b: usize, out: &mut [f32], pool: Option<&Pool>) {
2951        let (rows, cols) = (self.rows(), self.cols());
2952        if let Self::Mapped { model, idx, .. } = self {
2953            if b >= 2
2954                && b * rows * cols >= 33_554_432
2955                && !row_exact()
2956                && !crate::gpu::mm_killed()
2957                && crate::gpu::enabled_here()
2958            {
2959                let class = if b >= 128 {
2960                    crate::gpu::OpClass::MatmatWide
2961                } else {
2962                    crate::gpu::OpClass::Matmat
2963                };
2964                let t0 = std::time::Instant::now();
2965                match crate::gpu::probe_arm(class) {
2966                    crate::gpu::ProbeArm::Gpu => {
2967                        if crate::gpu::mxfp4_matmat(model, *idx, xs, b, rows, cols, out) {
2968                            crate::gpu::probe_record(class, true, t0.elapsed());
2969                            return;
2970                        }
2971                    }
2972                    crate::gpu::ProbeArm::CpuTimed => {
2973                        mxfp4::matmat(self.quant_bytes(), xs, b, rows, cols, out, pool);
2974                        crate::gpu::probe_record(class, false, t0.elapsed());
2975                        return;
2976                    }
2977                    crate::gpu::ProbeArm::Cpu => {}
2978                }
2979            }
2980        }
2981        mxfp4::matmat(self.quant_bytes(), xs, b, rows, cols, out, pool);
2982    }
2983}
2984
2985impl QTensor {
2986    /// The device GEMM this tensor would take, run once on the caller's
2987    /// data — the startup parity probe's arm, and the one place that knows
2988    /// which entry point each codec has.
2989    ///
2990    /// It exists because the probe used to look for a `q4tp` weight by
2991    /// name AND dtype, and a container packed any other way was declared
2992    /// "host path" for the whole render even though its codec had a device
2993    /// GEMM of its own. A gate that only recognizes one codec is a gate
2994    /// that silently downgrades every other one.
2995    pub fn device_matmat(&self, xs: &[f32], b: usize, out: &mut [f32]) -> bool {
2996        let (rows, cols) = (self.rows(), self.cols());
2997        let Self::Mapped {
2998            model,
2999            idx,
3000            dtype,
3001            row_scale,
3002            col_field,
3003            ..
3004        } = self
3005        else {
3006            return false;
3007        };
3008        if crate::prism::has_contract(model) {
3009            return false;
3010        }
3011        match *dtype {
3012            TensorDtype::Q4TiledP => crate::gpu::q4tp_matmat(model, *idx, xs, b, rows, cols, out),
3013            // The two-field codec folds its column field into the
3014            // activation, which leaves a plain per-row int8 GEMM — the
3015            // same kernel `q8_row` uses, on both backends.
3016            TensorDtype::Q8Row | TensorDtype::Q8_2f => {
3017                // The field belongs to the weight; only a backend that cannot
3018                // apply it there makes a scaled copy of the activation.
3019                if *dtype == TensorDtype::Q8_2f
3020                    && std::env::var("CMF_Q8_2F_DEV").as_deref() != Ok("0")
3021                    && crate::gpu::q8_matmat_2f(
3022                        model, *idx, row_scale, col_field, xs, b, rows, cols, out,
3023                    )
3024                {
3025                    return true;
3026                }
3027                let flat: Vec<f32> = (0..b)
3028                    .flat_map(|bi| {
3029                        prescale(&xs[bi * cols..(bi + 1) * cols], col_field, *dtype).into_owned()
3030                    })
3031                    .collect();
3032                crate::gpu::q8_matmat(model, *idx, row_scale, &flat, b, rows, cols, out)
3033            }
3034            _ => false,
3035        }
3036    }
3037
3038    /// Multi-matrix job (roadmap §3 P0): N tensors sharing one input
3039    /// run under a SINGLE pool dispatch — QKV or gate+up cost one
3040    /// barrier instead of N. Per-row math is the exact same kernel as
3041    /// `matvec` (bit-identical outputs); only the dispatch is fused.
3042    /// Falls back to N sequential matvecs when the set is not a uniform
3043    /// q8-family/F32 group or there is no pool.
3044    pub fn matvec_many<const N: usize>(
3045        ts: [&QTensor; N],
3046        x: &[f32],
3047        mut outs: [&mut [f32]; N],
3048        pool: Option<&Pool>,
3049    ) {
3050        if Self::any_exact_cpu_default(&ts) {
3051            return float_activations_scope(|| Self::matvec_many(ts, x, outs, pool));
3052        }
3053        let total_rows: usize = ts.iter().map(|t| t.rows()).sum();
3054        if ts.iter().any(|t| t.has_prism_contract() || t.per_tensor_only()) {
3055            // The fused range kernels have no transform descriptor.  Let
3056            // each tensor's ordinary matvec dispatch perform the explicit
3057            // signed FWHT (and retain CPU fallback for mixed q2tp/q4tp).
3058            // blr has no row-range kernel either: per-tensor calls.
3059            for (t, o) in ts.iter().zip(outs.iter_mut()) {
3060                t.matvec(x, o, pool);
3061            }
3062            return;
3063        }
3064        let uniform_q8 = ts.iter().all(|t| {
3065            matches!(
3066                t,
3067                Self::Mapped {
3068                    dtype: TensorDtype::Q8Row | TensorDtype::Q8_2f,
3069                    ..
3070                }
3071            )
3072        });
3073        let uniform_f32 = ts.iter().all(|t| matches!(t, Self::F32 { .. }));
3074        if uniform_f32 && crate::f32_backend::active() {
3075            for (t, o) in ts.iter().zip(outs.iter_mut()) {
3076                t.matvec(x, o, pool);
3077            }
3078            return;
3079        }
3080        let uniform_q4 = ts.iter().all(|t| {
3081            matches!(
3082                t,
3083                Self::Mapped {
3084                    dtype: TensorDtype::Q4Block,
3085                    ..
3086                }
3087            )
3088        });
3089        let uniform_vbit = ts.iter().all(|t| {
3090            matches!(
3091                t,
3092                Self::Mapped {
3093                    dtype: TensorDtype::Vbit | TensorDtype::VbitRo,
3094                    ..
3095                }
3096            )
3097        });
3098        // q1 and q1g may mix freely: the shared activation split and group
3099        // sums are layout-independent, only the row kernel differs.
3100        let uniform_q1 =
3101            ts.iter().all(|t| t.bin_w().is_some()) && ts.iter().all(|t| t.cols() == ts[0].cols());
3102        let uniform_q1t = ts.iter().all(|t| {
3103            matches!(
3104                t,
3105                Self::Mapped {
3106                    dtype: TensorDtype::Q1T,
3107                    ..
3108                }
3109            )
3110        });
3111        // q4tp is the skeleton dtype of the big MoE files, and without an arm
3112        // here every projection that shares an input paid its own pool
3113        // barrier: DeepSeek-V4's attention step alone hands this function
3114        // wq_a, wkv and both compressors' pairs off the same hidden state.
3115        let uniform_q4tp = ts.iter().all(|t| {
3116            matches!(
3117                t,
3118                Self::Mapped {
3119                    dtype: TensorDtype::Q4TiledP,
3120                    ..
3121                }
3122            )
3123        }) && ts
3124            .iter()
3125            .all(|t| t.cols() == ts[0].cols() && t.cols() % GROUP_SIZE == 0);
3126        let Some(pool) = pool else {
3127            for (t, o) in ts.iter().zip(outs.iter_mut()) {
3128                t.matvec(x, o, None);
3129            }
3130            return;
3131        };
3132        if total_rows < 256
3133            || !(uniform_q8
3134                || uniform_f32
3135                || uniform_q4
3136                || uniform_vbit
3137                || uniform_q1
3138                || uniform_q1t
3139                || uniform_q4tp)
3140        {
3141            for (t, o) in ts.iter().zip(outs.iter_mut()) {
3142                t.matvec(x, o, Some(pool));
3143            }
3144            return;
3145        }
3146
3147        if uniform_q4tp {
3148            // Every tensor's rows laid end to end in one virtual row space,
3149            // so the whole set is ONE dispatch. The per-row body is the
3150            // `q4tp_matvec` arm verbatim — same activation split, same
3151            // accumulation order — so the outputs are bit-identical to the
3152            // sequential calls this replaces.
3153            let cols = ts[0].cols();
3154            let gpr = cols / GROUP_SIZE;
3155            let views: [Q4tpView; N] =
3156                std::array::from_fn(|i| Q4tpView::new(ts[i].quant_bytes(), ts[i].rows(), cols));
3157            let rows_of: [usize; N] = std::array::from_fn(|i| ts[i].rows());
3158            let outs_addr: [SendMut; N] = std::array::from_fn(|i| SendMut(outs[i].as_mut_ptr()));
3159            // flat index -> (which tensor, which of its rows)
3160            let locate = |flat: usize| -> (usize, usize) {
3161                let mut acc = 0;
3162                for (i, &r) in rows_of.iter().enumerate() {
3163                    if flat < acc + r {
3164                        return (i, flat - acc);
3165                    }
3166                    acc += r;
3167                }
3168                (rows_of.len() - 1, 0)
3169            };
3170            let (views, outs_addr) = (&views, &outs_addr);
3171            if a8w8_enabled() {
3172                let act = split_act(x);
3173                let act = &act;
3174                #[cfg(target_arch = "x86_64")]
3175                let lanes = q4tp_lanes();
3176                let run = |start: usize, end: usize| {
3177                    #[cfg(target_arch = "x86_64")]
3178                    if lanes > 1 && act.xg8.len() == gpr {
3179                        // L independent accumulator chains per worker —
3180                        // the plain body's math, lane-interleaved.
3181                        with_krow(gpr * lanes, |sc| {
3182                            // SAFETY: a8w8 implies AVX2; each (tensor, row)
3183                            // pair still belongs to exactly one worker.
3184                            unsafe {
3185                                match lanes {
3186                                    2 => q4tp_many_lanes::<2>(
3187                                        &views[..],
3188                                        &locate,
3189                                        start,
3190                                        end,
3191                                        gpr,
3192                                        &act.xq,
3193                                        &act.xg8,
3194                                        act.sx,
3195                                        &act.outliers,
3196                                        sc,
3197                                        &outs_addr[..],
3198                                    ),
3199                                    8 => q4tp_many_lanes::<8>(
3200                                        &views[..],
3201                                        &locate,
3202                                        start,
3203                                        end,
3204                                        gpr,
3205                                        &act.xq,
3206                                        &act.xg8,
3207                                        act.sx,
3208                                        &act.outliers,
3209                                        sc,
3210                                        &outs_addr[..],
3211                                    ),
3212                                    _ => q4tp_many_lanes::<4>(
3213                                        &views[..],
3214                                        &locate,
3215                                        start,
3216                                        end,
3217                                        gpr,
3218                                        &act.xq,
3219                                        &act.xg8,
3220                                        act.sx,
3221                                        &act.outliers,
3222                                        sc,
3223                                        &outs_addr[..],
3224                                    ),
3225                                }
3226                            }
3227                        });
3228                        return;
3229                    }
3230                    crate::cpuprof::count_plain_rows((end - start) as u64);
3231                    with_krow(gpr, |sc| {
3232                        for flat in start..end {
3233                            let (t, r) = locate(flat);
3234                            let v = &views[t];
3235                            v.scales_into(r, gpr, sc);
3236                            let mut acc = dot_q4tp_row_i8(v.nib, r, gpr, &act.xq, sc) * act.sx;
3237                            for &(j, xv) in &act.outliers {
3238                                let (w, s) = q4tp_outlier(v.nib, r, gpr, j, sc);
3239                                acc += w * s * xv;
3240                            }
3241                            // SAFETY: one worker owns each (tensor, row) pair.
3242                            unsafe { *outs_addr[t].at(r) = acc };
3243                        }
3244                    });
3245                };
3246                pool.run_rows(total_rows, &run);
3247            } else {
3248                let run = |start: usize, end: usize| {
3249                    with_krow(gpr, |sc| {
3250                        for flat in start..end {
3251                            let (t, r) = locate(flat);
3252                            let v = &views[t];
3253                            v.scales_into(r, gpr, sc);
3254                            // SAFETY: one worker owns each (tensor, row) pair.
3255                            unsafe { *outs_addr[t].at(r) = q4tp_row_exact(v.nib, r, gpr, x, sc) };
3256                        }
3257                    });
3258                };
3259                pool.run_rows(total_rows, &run);
3260            }
3261            return;
3262        }
3263
3264        if uniform_q1 {
3265            // One shared activation split + group sums (q1 has no col
3266            // field; the same input feeds every tensor).
3267            let outs_addr: [SendMut; N] = std::array::from_fn(|i| SendMut(outs[i].as_mut_ptr()));
3268            if a8w8_enabled() {
3269                let act = split_act(x);
3270                let gsum = q1_group_sums(&act.xq, ts[0].cols() / GROUP_SIZE);
3271                let (act, gsum) = (&act, &gsum);
3272                let closures: [_; N] = std::array::from_fn(|i| {
3273                    let (w, gpr, out) = (
3274                        ts[i].bin_w().expect("uniform_q1 checked"),
3275                        ts[i].cols() / GROUP_SIZE,
3276                        outs_addr[i],
3277                    );
3278                    move |s: usize, e: usize| bin_range_a8w8(w, gpr, act, gsum, out, s, e)
3279                });
3280                let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3281                    std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3282                pool.run_many(&parts);
3283            } else {
3284                let closures: [_; N] = std::array::from_fn(|i| {
3285                    let (w, gpr, out) = (
3286                        ts[i].bin_w().expect("uniform_q1 checked"),
3287                        ts[i].cols() / GROUP_SIZE,
3288                        outs_addr[i],
3289                    );
3290                    move |s: usize, e: usize| bin_range_f32(w, gpr, x, out, s, e)
3291                });
3292                let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3293                    std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3294                pool.run_many(&parts);
3295            }
3296            return;
3297        }
3298
3299        if uniform_q1t {
3300            // Q1T batched: one shared activation split + overlay decode,
3301            // all tensors' rows in ONE pool dispatch (saves N−1 dispatches
3302            // and N−1 redundant split_act calls per layer).
3303            let outs_addr: [SendMut; N] = std::array::from_fn(|i| SendMut(outs[i].as_mut_ptr()));
3304            const TILE: usize = cortiq_core::quant::Q1T_TILE;
3305            if a8w8_enabled() {
3306                let act = split_act(x);
3307                let act = &act;
3308                let x_ref = x;
3309                let closures: [_; N] = std::array::from_fn(|i| {
3310                    let bytes = ts[i].quant_bytes();
3311                    let (rows, cols) = (ts[i].rows(), ts[i].cols());
3312                    let gpr = cols / GROUP_SIZE;
3313                    let (rp_off, ent_off, has_ov) = q1t_overlay(bytes, rows * gpr * TILE, rows);
3314                    let out = outs_addr[i];
3315                    move |s: usize, e: usize| {
3316                        q1t_range_a8w8(bytes, gpr, rp_off, ent_off, has_ov, act, x_ref, out, s, e)
3317                    }
3318                });
3319                let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3320                    std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3321                pool.run_many(&parts);
3322            } else {
3323                let x_ref = x;
3324                let closures: [_; N] = std::array::from_fn(|i| {
3325                    let bytes = ts[i].quant_bytes();
3326                    let (rows, cols) = (ts[i].rows(), ts[i].cols());
3327                    let gpr = cols / GROUP_SIZE;
3328                    let (rp_off, ent_off, has_ov) = q1t_overlay(bytes, rows * gpr * TILE, rows);
3329                    let out = outs_addr[i];
3330                    move |s: usize, e: usize| {
3331                        q1t_range_f32_batch(bytes, gpr, rp_off, ent_off, has_ov, x_ref, out, s, e)
3332                    }
3333                });
3334                let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3335                    std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3336                pool.run_many(&parts);
3337            }
3338            return;
3339        }
3340
3341        if uniform_q4 || uniform_vbit {
3342            let outs_addr: [SendMut; N] = std::array::from_fn(|i| SendMut(outs[i].as_mut_ptr()));
3343            // q4/vbit share one activation split — no per-tensor col field.
3344            if a8w8_enabled() {
3345                let act = split_act(x);
3346                let act = &act;
3347                if uniform_q4 {
3348                    let closures: [_; N] = std::array::from_fn(|i| {
3349                        let (packed, scales) =
3350                            q4_split(ts[i].quant_bytes(), ts[i].rows(), ts[i].cols());
3351                        let (gpr, cols, out) =
3352                            (ts[i].cols() / GROUP_SIZE, ts[i].cols(), outs_addr[i]);
3353                        move |s: usize, e: usize| {
3354                            q4_range_a8w8(packed, scales, gpr, cols, act, out, s, e)
3355                        }
3356                    });
3357                    let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3358                        std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3359                    pool.run_many(&parts);
3360                } else {
3361                    let closures: [_; N] = std::array::from_fn(|i| {
3362                        let Self::Mapped { vbit_offsets, .. } = ts[i] else {
3363                            unreachable!()
3364                        };
3365                        let (bytes, rows, cols, out) = (
3366                            ts[i].quant_bytes(),
3367                            ts[i].rows(),
3368                            ts[i].cols(),
3369                            outs_addr[i],
3370                        );
3371                        move |s: usize, e: usize| {
3372                            vbit_range_a8w8(bytes, vbit_offsets, x, act, rows, cols, out, s, e)
3373                        }
3374                    });
3375                    let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3376                        std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3377                    pool.run_many(&parts);
3378                }
3379                return;
3380            }
3381            if uniform_q4 {
3382                let closures: [_; N] = std::array::from_fn(|i| {
3383                    let (packed, scales) =
3384                        q4_split(ts[i].quant_bytes(), ts[i].rows(), ts[i].cols());
3385                    let (gpr, out) = (ts[i].cols() / GROUP_SIZE, outs_addr[i]);
3386                    move |s: usize, e: usize| q4_range_f32(packed, scales, gpr, x, out, s, e)
3387                });
3388                let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3389                    std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3390                pool.run_many(&parts);
3391            } else {
3392                let closures: [_; N] = std::array::from_fn(|i| {
3393                    let Self::Mapped { vbit_offsets, .. } = ts[i] else {
3394                        unreachable!()
3395                    };
3396                    let (bytes, rows, cols, out) = (
3397                        ts[i].quant_bytes(),
3398                        ts[i].rows(),
3399                        ts[i].cols(),
3400                        outs_addr[i],
3401                    );
3402                    move |s: usize, e: usize| {
3403                        vbit_range_f32(bytes, vbit_offsets, x, rows, cols, out, s, e)
3404                    }
3405                });
3406                let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3407                    std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3408                pool.run_many(&parts);
3409            }
3410            return;
3411        }
3412
3413        if uniform_f32 {
3414            let outs_addr: [SendMut; N] = std::array::from_fn(|i| SendMut(outs[i].as_mut_ptr()));
3415            let closures: [_; N] = std::array::from_fn(|i| {
3416                let Self::F32 { data, cols, .. } = ts[i] else {
3417                    unreachable!()
3418                };
3419                let out = outs_addr[i];
3420                move |start: usize, end: usize| {
3421                    for o in start..end {
3422                        let row = &data[o * cols..(o + 1) * cols];
3423                        let mut sum = 0.0f32;
3424                        for j in 0..*cols {
3425                            sum += row[j] * x[j];
3426                        }
3427                        // SAFETY: disjoint (tensor, row) cells per worker.
3428                        unsafe { *out.at(o) = sum };
3429                    }
3430                }
3431            });
3432            let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3433                std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3434            pool.run_many(&parts);
3435            return;
3436        }
3437
3438        // Uniform q8-family: per-tensor prescale (q8_2f col fields
3439        // differ per tensor) + the shared range kernels.
3440        struct Ctx<'a> {
3441            bytes: &'a [u8],
3442            #[cfg_attr(not(target_arch = "aarch64"), allow(dead_code))]
3443            rep: &'a [u8],
3444            row_scale: &'a [f32],
3445            cols: usize,
3446            xs: std::borrow::Cow<'a, [f32]>,
3447        }
3448        let ctxs: [Ctx<'_>; N] = std::array::from_fn(|i| {
3449            let Self::Mapped {
3450                dtype,
3451                cols,
3452                row_scale,
3453                col_field,
3454                repack,
3455                ..
3456            } = ts[i]
3457            else {
3458                unreachable!()
3459            };
3460            Ctx {
3461                bytes: ts[i].quant_bytes(),
3462                rep: repack,
3463                row_scale,
3464                cols: *cols,
3465                xs: prescale(x, col_field, *dtype),
3466            }
3467        });
3468        let outs_addr: [SendMut; N] = std::array::from_fn(|i| SendMut(outs[i].as_mut_ptr()));
3469        #[cfg(target_arch = "aarch64")]
3470        if sdot_enabled() {
3471            let acts: [SplitAct; N] = std::array::from_fn(|i| split_act(&ctxs[i].xs));
3472            let closures: [_; N] = std::array::from_fn(|i| {
3473                let (c, act, out) = (&ctxs[i], &acts[i], outs_addr[i]);
3474                move |start: usize, end: usize| {
3475                    q8_range_sdot(c.bytes, c.rep, c.row_scale, act, c.cols, out, start, end)
3476                }
3477            });
3478            let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3479                std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3480            pool.run_many(&parts);
3481            return;
3482        }
3483        #[cfg(target_arch = "x86_64")]
3484        if avx2_a8w8_enabled() {
3485            let acts: [SplitAct; N] = std::array::from_fn(|i| split_act(&ctxs[i].xs));
3486            let closures: [_; N] = std::array::from_fn(|i| {
3487                let (c, act, out) = (&ctxs[i], &acts[i], outs_addr[i]);
3488                move |start: usize, end: usize| {
3489                    q8_range_avx2(c.bytes, c.row_scale, act, c.cols, out, start, end)
3490                }
3491            });
3492            let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3493                std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3494            pool.run_many(&parts);
3495            return;
3496        }
3497        let closures: [_; N] = std::array::from_fn(|i| {
3498            let (c, out) = (&ctxs[i], outs_addr[i]);
3499            move |start: usize, end: usize| {
3500                q8_range_f32(c.bytes, c.row_scale, &c.xs, c.cols, out, start, end)
3501            }
3502        });
3503        let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3504            std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3505        pool.run_many(&parts);
3506    }
3507}
3508
3509impl QTensor {
3510    /// Pair-input multi-matrix job: N tensors × 2 shared inputs under a
3511    /// single pool dispatch — the MTP/pair decode path publishes one job
3512    /// for Q/K/V (and one for gate+up) instead of one per tensor.
3513    /// Per-row math is exactly `matvec2`'s kernels; bit-identical.
3514    #[allow(clippy::needless_range_loop)]
3515    pub fn matvec2_many<const N: usize>(
3516        ts: [&QTensor; N],
3517        x1: &[f32],
3518        x2: &[f32],
3519        mut o1s: [&mut [f32]; N],
3520        mut o2s: [&mut [f32]; N],
3521        pool: Option<&Pool>,
3522    ) {
3523        if Self::any_exact_cpu_default(&ts) {
3524            return float_activations_scope(|| {
3525                Self::matvec2_many(ts, x1, x2, o1s, o2s, pool)
3526            });
3527        }
3528        let total_rows: usize = ts.iter().map(|t| t.rows()).sum();
3529        if ts.iter().any(|t| t.has_prism_contract() || t.per_tensor_only()) {
3530            for i in 0..N {
3531                ts[i].matvec2(x1, x2, o1s[i], o2s[i], pool);
3532            }
3533            return;
3534        }
3535        let uniform_q8 = ts.iter().all(|t| {
3536            matches!(
3537                t,
3538                Self::Mapped {
3539                    dtype: TensorDtype::Q8Row | TensorDtype::Q8_2f,
3540                    ..
3541                }
3542            )
3543        });
3544        let uniform_f32 = ts.iter().all(|t| matches!(t, Self::F32 { .. }));
3545        let uniform_q4 = ts.iter().all(|t| {
3546            matches!(
3547                t,
3548                Self::Mapped {
3549                    dtype: TensorDtype::Q4Block,
3550                    ..
3551                }
3552            )
3553        });
3554        let uniform_vbit = ts.iter().all(|t| {
3555            matches!(
3556                t,
3557                Self::Mapped {
3558                    dtype: TensorDtype::Vbit | TensorDtype::VbitRo,
3559                    ..
3560                }
3561            )
3562        });
3563        let fusable = pool.is_some()
3564            && total_rows >= 256
3565            && (uniform_q8 || uniform_f32 || uniform_q4 || uniform_vbit);
3566        if !fusable {
3567            for i in 0..N {
3568                ts[i].matvec2(x1, x2, o1s[i], o2s[i], pool);
3569            }
3570            return;
3571        }
3572        let pool = pool.unwrap();
3573
3574        if uniform_q4 || uniform_vbit {
3575            let p1: [SendMut; N] = std::array::from_fn(|i| SendMut(o1s[i].as_mut_ptr()));
3576            let p2: [SendMut; N] = std::array::from_fn(|i| SendMut(o2s[i].as_mut_ptr()));
3577            // q4/vbit share activation splits — no per-tensor col field.
3578            if a8w8_enabled() {
3579                let a1 = split_act(x1);
3580                let a2 = split_act(x2);
3581                let (a1, a2) = (&a1, &a2);
3582                if uniform_q4 {
3583                    let closures: [_; N] = std::array::from_fn(|i| {
3584                        let (packed, scales) =
3585                            q4_split(ts[i].quant_bytes(), ts[i].rows(), ts[i].cols());
3586                        let (gpr, cols, o1, o2) =
3587                            (ts[i].cols() / GROUP_SIZE, ts[i].cols(), p1[i], p2[i]);
3588                        move |s: usize, e: usize| {
3589                            q4_range2_a8w8(packed, scales, gpr, cols, a1, a2, o1, o2, s, e)
3590                        }
3591                    });
3592                    let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3593                        std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3594                    pool.run_many(&parts);
3595                } else {
3596                    let closures: [_; N] = std::array::from_fn(|i| {
3597                        let Self::Mapped { vbit_offsets, .. } = ts[i] else {
3598                            unreachable!()
3599                        };
3600                        let (bytes, rows, cols, o1, o2) = (
3601                            ts[i].quant_bytes(),
3602                            ts[i].rows(),
3603                            ts[i].cols(),
3604                            p1[i],
3605                            p2[i],
3606                        );
3607                        move |s: usize, e: usize| {
3608                            vbit_range2_a8w8(
3609                                bytes,
3610                                vbit_offsets,
3611                                x1,
3612                                x2,
3613                                a1,
3614                                a2,
3615                                rows,
3616                                cols,
3617                                o1,
3618                                o2,
3619                                s,
3620                                e,
3621                            )
3622                        }
3623                    });
3624                    let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3625                        std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3626                    pool.run_many(&parts);
3627                }
3628                return;
3629            }
3630            if uniform_q4 {
3631                let closures: [_; N] = std::array::from_fn(|i| {
3632                    let (packed, scales) =
3633                        q4_split(ts[i].quant_bytes(), ts[i].rows(), ts[i].cols());
3634                    let (gpr, o1, o2) = (ts[i].cols() / GROUP_SIZE, p1[i], p2[i]);
3635                    move |s: usize, e: usize| {
3636                        q4_range2_f32(packed, scales, gpr, x1, x2, o1, o2, s, e)
3637                    }
3638                });
3639                let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3640                    std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3641                pool.run_many(&parts);
3642            } else {
3643                let closures: [_; N] = std::array::from_fn(|i| {
3644                    let Self::Mapped { vbit_offsets, .. } = ts[i] else {
3645                        unreachable!()
3646                    };
3647                    let (bytes, rows, cols, o1, o2) = (
3648                        ts[i].quant_bytes(),
3649                        ts[i].rows(),
3650                        ts[i].cols(),
3651                        p1[i],
3652                        p2[i],
3653                    );
3654                    move |s: usize, e: usize| {
3655                        vbit_range2_f32(bytes, vbit_offsets, x1, x2, rows, cols, o1, o2, s, e)
3656                    }
3657                });
3658                let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3659                    std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3660                pool.run_many(&parts);
3661            }
3662            return;
3663        }
3664
3665        if uniform_f32 {
3666            let p1: [SendMut; N] = std::array::from_fn(|i| SendMut(o1s[i].as_mut_ptr()));
3667            let p2: [SendMut; N] = std::array::from_fn(|i| SendMut(o2s[i].as_mut_ptr()));
3668            let closures: [_; N] = std::array::from_fn(|i| {
3669                let Self::F32 { data, cols, .. } = ts[i] else {
3670                    unreachable!()
3671                };
3672                let (o1, o2) = (p1[i], p2[i]);
3673                move |start: usize, end: usize| {
3674                    for o in start..end {
3675                        let row = &data[o * cols..(o + 1) * cols];
3676                        let (mut s1, mut s2) = (0.0f32, 0.0f32);
3677                        for j in 0..*cols {
3678                            s1 += row[j] * x1[j];
3679                            s2 += row[j] * x2[j];
3680                        }
3681                        // SAFETY: disjoint (tensor, row) cells per worker.
3682                        unsafe {
3683                            *o1.at(o) = s1;
3684                            *o2.at(o) = s2;
3685                        }
3686                    }
3687                }
3688            });
3689            let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3690                std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3691            pool.run_many(&parts);
3692            return;
3693        }
3694
3695        struct Ctx<'a> {
3696            bytes: &'a [u8],
3697            row_scale: &'a [f32],
3698            cols: usize,
3699            xs1: std::borrow::Cow<'a, [f32]>,
3700            xs2: std::borrow::Cow<'a, [f32]>,
3701        }
3702        let ctxs: [Ctx<'_>; N] = std::array::from_fn(|i| {
3703            let Self::Mapped {
3704                dtype,
3705                cols,
3706                row_scale,
3707                col_field,
3708                ..
3709            } = ts[i]
3710            else {
3711                unreachable!()
3712            };
3713            Ctx {
3714                bytes: ts[i].quant_bytes(),
3715                row_scale,
3716                cols: *cols,
3717                xs1: prescale(x1, col_field, *dtype),
3718                xs2: prescale(x2, col_field, *dtype),
3719            }
3720        });
3721        let p1: [SendMut; N] = std::array::from_fn(|i| SendMut(o1s[i].as_mut_ptr()));
3722        let p2: [SendMut; N] = std::array::from_fn(|i| SendMut(o2s[i].as_mut_ptr()));
3723        #[cfg(target_arch = "aarch64")]
3724        if sdot_enabled() {
3725            let acts: [(SplitAct, SplitAct); N] =
3726                std::array::from_fn(|i| (split_act(&ctxs[i].xs1), split_act(&ctxs[i].xs2)));
3727            let closures: [_; N] = std::array::from_fn(|i| {
3728                let (c, a, o1, o2) = (&ctxs[i], &acts[i], p1[i], p2[i]);
3729                move |start: usize, end: usize| {
3730                    q8_range2_sdot(c.bytes, c.row_scale, &a.0, &a.1, c.cols, o1, o2, start, end)
3731                }
3732            });
3733            let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3734                std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3735            pool.run_many(&parts);
3736            return;
3737        }
3738        #[cfg(target_arch = "x86_64")]
3739        if avx2_a8w8_enabled() {
3740            let acts: [(SplitAct, SplitAct); N] =
3741                std::array::from_fn(|i| (split_act(&ctxs[i].xs1), split_act(&ctxs[i].xs2)));
3742            let closures: [_; N] = std::array::from_fn(|i| {
3743                let (c, a, o1, o2) = (&ctxs[i], &acts[i], p1[i], p2[i]);
3744                move |start: usize, end: usize| {
3745                    q8_range2_avx2(c.bytes, c.row_scale, &a.0, &a.1, c.cols, o1, o2, start, end)
3746                }
3747            });
3748            let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3749                std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3750            pool.run_many(&parts);
3751            return;
3752        }
3753        let closures: [_; N] = std::array::from_fn(|i| {
3754            let (c, o1, o2) = (&ctxs[i], p1[i], p2[i]);
3755            move |start: usize, end: usize| {
3756                q8_range2_f32(
3757                    c.bytes,
3758                    c.row_scale,
3759                    &c.xs1,
3760                    &c.xs2,
3761                    c.cols,
3762                    o1,
3763                    o2,
3764                    start,
3765                    end,
3766                )
3767            }
3768        });
3769        let parts: [(usize, &(dyn Fn(usize, usize) + Sync)); N] =
3770            std::array::from_fn(|i| (ts[i].rows(), &closures[i] as _));
3771        pool.run_many(&parts);
3772    }
3773
3774    /// Fused gate+up matvec with SiLU·mul: for each row r, computes
3775    /// `silu(gate·x) * (up·x)` and writes to `out[r]`. ONE pool dispatch,
3776    /// no intermediate g/u buffers, no separate silu pass. Falls back
3777    /// (returns false) for unsupported dtype combos.
3778    pub fn matvec_silu_mul(
3779        gate: &QTensor,
3780        up: &QTensor,
3781        x: &[f32],
3782        out: &mut [f32],
3783        pool: Option<&Pool>,
3784    ) -> bool {
3785        Self::matvec_silu_mul_limited(gate, up, x, out, 0.0, pool)
3786    }
3787
3788    /// Fused gate+up+SiLU with the GLM asymmetrical clamp.  `limit == 0`
3789    /// preserves the historical unclamped helper; a positive limit clamps
3790    /// `up` to both sides and `gate` only from above, matching the GLM
3791    /// SwiGLU reference.  Keeping the limit in the row kernel avoids the two
3792    /// intermediate vectors and the extra combine pass on the Q2TP experts.
3793    pub fn matvec_silu_mul_limited(
3794        gate: &QTensor,
3795        up: &QTensor,
3796        x: &[f32],
3797        out: &mut [f32],
3798        limit: f32,
3799        pool: Option<&Pool>,
3800    ) -> bool {
3801        #[cfg(target_os = "android")]
3802        if let Some(done) = Self::npu_silu_mul(gate, up, x, out, limit, pool) {
3803            return done;
3804        }
3805        Self::matvec_silu_mul_cpu(gate, up, x, out, limit, pool)
3806    }
3807
3808    /// The q4tp bytes of a matrix the NPU lane can take (not a Prism
3809    /// matrix: its rotation lives outside the bytes).
3810    #[cfg(target_os = "android")]
3811    fn npu_q4tp(&self) -> Option<(&[u8], usize, usize)> {
3812        match self {
3813            Self::Mapped { dtype: TensorDtype::Q4TiledP, rows, cols, .. } if !self.has_prism_contract() => {
3814                Some((self.quant_bytes(), *rows, *cols))
3815            }
3816            _ => None,
3817        }
3818    }
3819
3820    /// The NPU lane of the fused gate+up (`npu.rs`): `up` on the Hexagon DSP
3821    /// while this thread's pool computes `gate`. `None`: no lane for this
3822    /// pair, the caller takes the CPU kernel. While the lane's trial is open
3823    /// the calls alternate between the two paths and both are timed.
3824    #[cfg(target_os = "android")]
3825    fn npu_silu_mul(
3826        gate: &QTensor,
3827        up: &QTensor,
3828        x: &[f32],
3829        out: &mut [f32],
3830        limit: f32,
3831        pool: Option<&Pool>,
3832    ) -> Option<bool> {
3833        // Off unless asked for: a token is bound by DDR, which the CPU and the
3834        // DSP share, so on the phones measured so far the split does not pay
3835        // (`CMF_NPU_DECODE=1` turns it on; the trial then still decides).
3836        if !a8w8_enabled() || !crate::npu::decode_wanted() {
3837            return None;
3838        }
3839        let (gb, rows, cols) = gate.npu_q4tp()?;
3840        let (ub, urows, ucols) = up.npu_q4tp()?;
3841        if (urows, ucols) != (rows, cols) {
3842            return None;
3843        }
3844        let lg = npu_lane_q4tp(crate::npu::Mode::Decode, gb, rows, cols)?;
3845        let lu = npu_lane_q4tp(crate::npu::Mode::Decode, ub, rows, cols)?;
3846        let inter = rows;
3847        let t0 = std::time::Instant::now();
3848        let full_cpu = |out: &mut [f32]| {
3849            // The CPU's own best for this pair: the fused kernel, or two
3850            // ordinary matvecs where it declines.
3851            if !Self::matvec_silu_mul_cpu(gate, up, x, out, limit, pool) {
3852                let mut g = vec![0f32; inter];
3853                let mut u = vec![0f32; inter];
3854                gate.matvec(x, &mut g, pool);
3855                up.matvec(x, &mut u, pool);
3856                for r in 0..inter {
3857                    out[r] = silu_mul_limited(g[r], u[r], limit);
3858                }
3859            }
3860        };
3861        let timed = match crate::npu::arm(crate::npu::Mode::Decode) {
3862            crate::npu::Arm::Cpu => {
3863                full_cpu(out);
3864                crate::npu::trial_sample(crate::npu::Mode::Decode, false, t0.elapsed().as_micros() as u64);
3865                return Some(true);
3866            }
3867            crate::npu::Arm::Npu { timed } => timed,
3868        };
3869        // Rows `row0..` of both matrices go to the DSP as one call; the CPU's
3870        // fused kernel computes rows `..row0` meanwhile. The activation is the
3871        // same int8 split the CPU kernel makes (it makes it again inside), so
3872        // the two halves of `out` are the same arithmetic up to the Q15
3873        // rounding of the scales; the few outliers are added here in float.
3874        let row0 = lg.row0;
3875        let act = split_act(x);
3876        let mut pending = crate::npu::start(&lg, Some(&lu), &act.xq);
3877        if crate::npu::sync_mode() {
3878            // no overlap: for measuring the two costs apart
3879            if let Some(p) = pending.as_mut() {
3880                p.wait();
3881            }
3882        }
3883        let tg = std::time::Instant::now();
3884        ROW_LIMIT.with(|c| c.set(row0));
3885        let cpu_ok = Self::matvec_silu_mul_cpu(gate, up, x, out, limit, pool);
3886        ROW_LIMIT.with(|c| c.set(usize::MAX));
3887        let gate_us = tg.elapsed().as_micros() as u64;
3888        let pre_us = (tg - t0).as_micros() as u64;
3889        let tw = std::time::Instant::now();
3890        let y = pending.take().and_then(|p| p.finish());
3891        let wait_us = tw.elapsed().as_micros() as u64;
3892        let ok = match (cpu_ok, y) {
3893            (true, Some(y)) => {
3894                let k = act.sx * lg.unit();
3895                let (yg, yu) = y.split_at(lg.tiles * 32);
3896                for r in row0..inter {
3897                    let i = r - row0;
3898                    let mut gv = yg[i] as f32 * lg.row_max[i] * k;
3899                    let mut uv = yu[i] as f32 * lu.row_max[i] * k;
3900                    for &(j, xv) in &act.outliers {
3901                        let (w, s) = lg.weight(i, j);
3902                        gv += w * s * xv;
3903                        let (w, s) = lu.weight(i, j);
3904                        uv += w * s * xv;
3905                    }
3906                    out[r] = silu_mul_limited(gv, uv, limit);
3907                }
3908                true
3909            }
3910            (cpu_ok, y) => {
3911                static SAID: std::sync::Once = std::sync::Once::new();
3912                SAID.call_once(|| {
3913                    eprintln!("[cortiq] npu: fell back to the CPU (fused kernel took the rows: {cpu_ok}, DSP answered: {})", y.is_some())
3914                });
3915                full_cpu(out);
3916                false
3917            }
3918        };
3919        crate::npu::prof(pre_us, gate_us, wait_us, t0.elapsed().as_micros() as u64);
3920        if timed && ok {
3921            crate::npu::trial_sample(crate::npu::Mode::Decode, true, t0.elapsed().as_micros() as u64);
3922        }
3923        Some(true)
3924    }
3925
3926    fn matvec_silu_mul_cpu(
3927        gate: &QTensor,
3928        up: &QTensor,
3929        x: &[f32],
3930        out: &mut [f32],
3931        limit: f32,
3932        pool: Option<&Pool>,
3933    ) -> bool {
3934        if gate.exact_cpu_default() || up.exact_cpu_default() {
3935            return float_activations_scope(|| {
3936                Self::matvec_silu_mul_cpu(gate, up, x, out, limit, pool)
3937            });
3938        }
3939        if gate.has_prism_contract()
3940            || up.has_prism_contract()
3941            || gate.per_tensor_only()
3942            || up.per_tensor_only()
3943        {
3944            // The fused gate/up kernels consume x directly.  Prism requires
3945            // a per-matrix signed FWHT, so the caller must use two ordinary
3946            // descriptor-aware matvecs instead of an unrotated fast path.
3947            return false;
3948        }
3949        let inter = gate.rows();
3950        debug_assert_eq!(up.rows(), inter);
3951        debug_assert_eq!(out.len(), inter);
3952        debug_assert_eq!(gate.cols(), up.cols());
3953        if !a8w8_enabled() {
3954            return false;
3955        }
3956        let act = split_act(x);
3957        let act = &act;
3958        let x_ref = x;
3959        let out_addr = SendMut(out.as_mut_ptr());
3960
3961        match (gate, up) {
3962            // Q4Block gate + Q4Block up (most common mobile q4 models)
3963            (
3964                Self::Mapped {
3965                    dtype: TensorDtype::Q4Block,
3966                    ..
3967                },
3968                Self::Mapped {
3969                    dtype: TensorDtype::Q4Block,
3970                    ..
3971                },
3972            ) => {
3973                let (gp, gs) = q4_split(gate.quant_bytes(), gate.rows(), gate.cols());
3974                let (up_p, up_s) = q4_split(up.quant_bytes(), up.rows(), up.cols());
3975                let gpr = gate.cols() / GROUP_SIZE;
3976                let cols = gate.cols();
3977                let run = move |start: usize, end: usize| {
3978                    for r in start..end {
3979                        let mut gv = dot_q4_row_i8(gp, gs, r * gpr, gpr, &act.xq) * act.sx;
3980                        let mut uv = dot_q4_row_i8(up_p, up_s, r * gpr, gpr, &act.xq) * act.sx;
3981                        for &(j, xv) in &act.outliers {
3982                            let flat = r * cols + j;
3983                            let gb = gp[flat / 2];
3984                            let gn = if flat & 1 == 0 { gb & 0x0F } else { gb >> 4 };
3985                            let gsc = f16_to_f32(u16::from_le_bytes([
3986                                gs[(flat / GROUP_SIZE) * 2],
3987                                gs[(flat / GROUP_SIZE) * 2 + 1],
3988                            ]));
3989                            gv += ((gn as i32 - 8) as f32) * gsc * xv;
3990                            let ub = up_p[flat / 2];
3991                            let un = if flat & 1 == 0 { ub & 0x0F } else { ub >> 4 };
3992                            let usc = f16_to_f32(u16::from_le_bytes([
3993                                up_s[(flat / GROUP_SIZE) * 2],
3994                                up_s[(flat / GROUP_SIZE) * 2 + 1],
3995                            ]));
3996                            uv += ((un as i32 - 8) as f32) * usc * xv;
3997                        }
3998                        // SAFETY: disjoint row ranges per worker.
3999                        unsafe { *out_addr.at(r) = silu_mul_limited(gv, uv, limit) };
4000                    }
4001                };
4002                dispatch_rows(pool, inter, &run);
4003                true
4004            }
4005            // Q4Tiled gate + Q4Tiled up — one row pass, both tile
4006            // streams sequential, silu·mul fused (same per-row math as
4007            // `q4t_matvec`).
4008            (
4009                Self::Mapped {
4010                    dtype: TensorDtype::Q4Tiled,
4011                    ..
4012                },
4013                Self::Mapped {
4014                    dtype: TensorDtype::Q4Tiled,
4015                    ..
4016                },
4017            ) => {
4018                let g_bytes = gate.quant_bytes();
4019                let u_bytes = up.quant_bytes();
4020                let gpr = gate.cols() / GROUP_SIZE;
4021                let run = move |start: usize, end: usize| {
4022                    for r in start..end {
4023                        let mut gv = dot_q4t_row_i8(g_bytes, r, gpr, &act.xq) * act.sx;
4024                        let mut uv = dot_q4t_row_i8(u_bytes, r, gpr, &act.xq) * act.sx;
4025                        for &(j, xv) in &act.outliers {
4026                            let (w, s) = q4t_outlier(g_bytes, r, gpr, j);
4027                            gv += w * s * xv;
4028                            let (w, s) = q4t_outlier(u_bytes, r, gpr, j);
4029                            uv += w * s * xv;
4030                        }
4031                        // SAFETY: disjoint row ranges per worker.
4032                        unsafe { *out_addr.at(r) = silu_mul_limited(gv, uv, limit) };
4033                    }
4034                };
4035                dispatch_rows(pool, inter, &run);
4036                true
4037            }
4038            // Q4TiledP gate + Q4TiledP up — the same fused row pass, with
4039            // each row's two ladders built once and spent on both streams.
4040            (
4041                Self::Mapped {
4042                    dtype: TensorDtype::Q4TiledP,
4043                    ..
4044                },
4045                Self::Mapped {
4046                    dtype: TensorDtype::Q4TiledP,
4047                    ..
4048                },
4049            ) => {
4050                let cols = gate.cols();
4051                let gpr = cols / GROUP_SIZE;
4052                let gv_view = Q4tpView::new(gate.quant_bytes(), inter, cols);
4053                let uv_view = Q4tpView::new(up.quant_bytes(), inter, cols);
4054                #[cfg(target_arch = "x86_64")]
4055                let lanes = q4tp_lanes();
4056                let run = |start: usize, end: usize| {
4057                    #[cfg(target_arch = "x86_64")]
4058                    if lanes > 1 && act.xg8.len() == gpr {
4059                        // L independent accumulator chains per worker —
4060                        // the plain arm's math, lane-interleaved.
4061                        with_krows(gpr * lanes, |gsc, usc| {
4062                            // SAFETY: a8w8 implies AVX2; disjoint row ranges.
4063                            unsafe {
4064                                match lanes {
4065                                    2 => q4tp_gateup_lanes::<2>(
4066                                        &gv_view, &uv_view, start, end, gpr, &act.xq,
4067                                        &act.xg8, act.sx, limit, &act.outliers, gsc, usc,
4068                                        out_addr,
4069                                    ),
4070                                    8 => q4tp_gateup_lanes::<8>(
4071                                        &gv_view, &uv_view, start, end, gpr, &act.xq,
4072                                        &act.xg8, act.sx, limit, &act.outliers, gsc, usc,
4073                                        out_addr,
4074                                    ),
4075                                    _ => q4tp_gateup_lanes::<4>(
4076                                        &gv_view, &uv_view, start, end, gpr, &act.xq,
4077                                        &act.xg8, act.sx, limit, &act.outliers, gsc, usc,
4078                                        out_addr,
4079                                    ),
4080                                }
4081                            }
4082                        });
4083                        return;
4084                    }
4085                    crate::cpuprof::count_plain_rows((end - start) as u64);
4086                    with_krows(gpr, |gsc, usc| {
4087                        for r in start..end {
4088                            gv_view.scales_into(r, gpr, gsc);
4089                            uv_view.scales_into(r, gpr, usc);
4090                            let mut gv =
4091                                dot_q4tp_row_i8(gv_view.nib, r, gpr, &act.xq, gsc) * act.sx;
4092                            let mut uv =
4093                                dot_q4tp_row_i8(uv_view.nib, r, gpr, &act.xq, usc) * act.sx;
4094                            for &(j, xv) in &act.outliers {
4095                                let (w, s) = q4tp_outlier(gv_view.nib, r, gpr, j, gsc);
4096                                gv += w * s * xv;
4097                                let (w, s) = q4tp_outlier(uv_view.nib, r, gpr, j, usc);
4098                                uv += w * s * xv;
4099                            }
4100                            // SAFETY: disjoint row ranges per worker.
4101                            unsafe { *out_addr.at(r) = silu_mul_limited(gv, uv, limit) };
4102                        }
4103                    });
4104                };
4105                dispatch_rows(pool, inter, &run);
4106                true
4107            }
4108            // Q1 gate + Q1 up — one row pass over both sign streams,
4109            // silu·mul fused (the per-row math of `q1_range_a8w8`); the
4110            // activation group sums are shared by both streams. Without
4111            // this arm a q1 dense FFN paid two dispatches + a combine
4112            // loop — the exact barrier this function exists to remove.
4113            // q1g (and a q1/q1g mix) rides the same arm through `BinW`.
4114            (
4115                Self::Mapped {
4116                    dtype: TensorDtype::Q1 | TensorDtype::Q1G,
4117                    ..
4118                },
4119                Self::Mapped {
4120                    dtype: TensorDtype::Q1 | TensorDtype::Q1G,
4121                    ..
4122                },
4123            ) => {
4124                let gw = gate.bin_w().expect("binary dtype matched");
4125                let uw = up.bin_w().expect("binary dtype matched");
4126                let gpr = gate.cols() / GROUP_SIZE;
4127                let gsum = q1_group_sums(&act.xq, gpr);
4128                let gsum = &gsum;
4129                let run = move |start: usize, end: usize| {
4130                    for r in start..end {
4131                        let mut gv = gw.dot_i8(r, gpr, &act.xq, gsum) * act.sx;
4132                        let mut uv = uw.dot_i8(r, gpr, &act.xq, gsum) * act.sx;
4133                        for &(j, xv) in &act.outliers {
4134                            let (w, s) = gw.outlier(r, gpr, j);
4135                            gv += w * s * xv;
4136                            let (w, s) = uw.outlier(r, gpr, j);
4137                            uv += w * s * xv;
4138                        }
4139                        // SAFETY: disjoint row ranges per worker.
4140                        unsafe { *out_addr.at(r) = silu_mul_limited(gv, uv, limit) };
4141                    }
4142                };
4143                dispatch_rows(pool, inter, &run);
4144                true
4145            }
4146            // Q2TiledP gate + Q2TiledP up — the 2-bit expert pair (MoE
4147            // FFNs of the W2 class): one row pass, both ladders built
4148            // once, integer code dots with shared group sums.
4149            (
4150                Self::Mapped {
4151                    dtype: TensorDtype::Q2TiledP,
4152                    ..
4153                },
4154                Self::Mapped {
4155                    dtype: TensorDtype::Q2TiledP,
4156                    ..
4157                },
4158            ) => {
4159                let cols = gate.cols();
4160                let gpr = cols / GROUP_SIZE;
4161                let gv_view = Q4tpView::new_q2(gate.quant_bytes(), inter, cols);
4162                let uv_view = Q4tpView::new_q2(up.quant_bytes(), inter, cols);
4163                let gsum = q1_group_sums(&act.xq, gpr);
4164                let gsum = &gsum;
4165                let run = move |start: usize, end: usize| {
4166                    with_krows(gpr, |gsc, usc| {
4167                        for r in start..end {
4168                            gv_view.scales_into(r, gpr, gsc);
4169                            uv_view.scales_into(r, gpr, usc);
4170                            let mut gv =
4171                                dot_q2tp_row_i8(gv_view.nib, r, gpr, &act.xq, gsum, gsc) * act.sx;
4172                            let mut uv =
4173                                dot_q2tp_row_i8(uv_view.nib, r, gpr, &act.xq, gsum, usc) * act.sx;
4174                            for &(j, xv) in &act.outliers {
4175                                let (w, s) = q2tp_outlier(gv_view.nib, r, gpr, j, gsc);
4176                                gv += w * s * xv;
4177                                let (w, s) = q2tp_outlier(uv_view.nib, r, gpr, j, usc);
4178                                uv += w * s * xv;
4179                            }
4180                            // SAFETY: disjoint row ranges per worker.
4181                            unsafe { *out_addr.at(r) = silu_mul_limited(gv, uv, limit) };
4182                        }
4183                    });
4184                };
4185                dispatch_rows(pool, inter, &run);
4186                true
4187            }
4188            // Q8Row gate + Q8Row up — one row pass over both i8 streams.
4189            // Q8_2f stays out on purpose: its column field prescales the
4190            // activations PER TENSOR, which breaks this fn's shared
4191            // split_act contract — it keeps the two-dispatch path.
4192            (
4193                Self::Mapped {
4194                    dtype: TensorDtype::Q8Row,
4195                    row_scale: g_rs,
4196                    ..
4197                },
4198                Self::Mapped {
4199                    dtype: TensorDtype::Q8Row,
4200                    row_scale: u_rs,
4201                    ..
4202                },
4203            ) => {
4204                let g_bytes = gate.quant_bytes();
4205                let u_bytes = up.quant_bytes();
4206                let cols = gate.cols();
4207                let run = move |start: usize, end: usize| {
4208                    for r in start..end {
4209                        let gv = q8_row_dot(&g_bytes[r * cols..(r + 1) * cols], act) * g_rs[r];
4210                        let uv = q8_row_dot(&u_bytes[r * cols..(r + 1) * cols], act) * u_rs[r];
4211                        // SAFETY: disjoint row ranges per worker.
4212                        unsafe { *out_addr.at(r) = silu_mul_limited(gv, uv, limit) };
4213                    }
4214                };
4215                dispatch_rows(pool, inter, &run);
4216                true
4217            }
4218            // Q1T gate + Q1T up
4219            (
4220                Self::Mapped {
4221                    dtype: TensorDtype::Q1T,
4222                    ..
4223                },
4224                Self::Mapped {
4225                    dtype: TensorDtype::Q1T,
4226                    ..
4227                },
4228            ) => {
4229                const TILE: usize = cortiq_core::quant::Q1T_TILE;
4230                let g_bytes = gate.quant_bytes();
4231                let u_bytes = up.quant_bytes();
4232                let gpr = gate.cols() / GROUP_SIZE;
4233                let (g_rp, g_ent, g_ov) = q1t_overlay(g_bytes, inter * gpr * TILE, inter);
4234                let (u_rp, u_ent, u_ov) = q1t_overlay(u_bytes, inter * gpr * TILE, inter);
4235                let run = move |start: usize, end: usize| {
4236                    for r in start..end {
4237                        let mut gv = q1t_dot_row_i8(g_bytes, r, gpr, &act.xq) * act.sx;
4238                        let mut uv = q1t_dot_row_i8(u_bytes, r, gpr, &act.xq) * act.sx;
4239                        for &(j, xv) in &act.outliers {
4240                            gv += q1t_base_weight(g_bytes, r, gpr, j) * xv;
4241                            uv += q1t_base_weight(u_bytes, r, gpr, j) * xv;
4242                        }
4243                        gv += q1t_row_outlier_correction(g_bytes, r, g_rp, g_ent, g_ov, x_ref);
4244                        uv += q1t_row_outlier_correction(u_bytes, r, u_rp, u_ent, u_ov, x_ref);
4245                        // SAFETY: disjoint row ranges per worker.
4246                        unsafe { *out_addr.at(r) = silu_mul_limited(gv, uv, limit) };
4247                    }
4248                };
4249                dispatch_rows(pool, inter, &run);
4250                true
4251            }
4252            _ => false,
4253        }
4254    }
4255
4256    /// Every routed expert's fused gate/up/SiLU under ONE pool dispatch.
4257    ///
4258    /// The per-expert path pays a pool barrier per expert per stage: at 9
4259    /// experts over 40 layers that is ~720 barriers a token, and a decode
4260    /// profile of Qwen3.6-35B-A3B showed the pool parked in
4261    /// `psynch_cvwait` about twice as long as it spent computing. Laying
4262    /// every expert's rows end-to-end in one virtual row space collapses
4263    /// the stage to a single dispatch. The per-row body is the
4264    /// single-expert q4tp arm verbatim, so outputs are bit-identical.
4265    ///
4266    /// `false` = something is outside the fused q4tp kernel (dtype, shape,
4267    /// or a transformed tensor); the caller walks the ordinary per-expert
4268    /// path. Float activations use the same exact scalar rows, still fused
4269    /// under one pool dispatch.
4270    pub fn moe_gate_up_many(
4271        pairs: &[(&QTensor, &QTensor)],
4272        x: &[f32],
4273        outs: &mut [Vec<f32>],
4274        pool: Option<&Pool>,
4275    ) -> bool {
4276        Self::moe_gate_up_many_limited(pairs, x, outs, 0.0, pool)
4277    }
4278
4279    /// Batched gate/up/SiLU with the optional GLM clamp.  The public legacy
4280    /// helper above keeps its historical unclamped semantics; callers that
4281    /// implement a reference with a positive SwiGLU limit use this variant.
4282    pub fn moe_gate_up_many_limited(
4283        pairs: &[(&QTensor, &QTensor)],
4284        x: &[f32],
4285        outs: &mut [Vec<f32>],
4286        limit: f32,
4287        pool: Option<&Pool>,
4288    ) -> bool {
4289        if Self::any_exact_cpu_default_pairs(pairs) {
4290            return float_activations_scope(|| {
4291                Self::moe_gate_up_many_limited(pairs, x, outs, limit, pool)
4292            });
4293        }
4294        if pairs.is_empty() || pairs.len() != outs.len() {
4295            return false;
4296        }
4297        if pairs.iter().any(|(g, u)| g.per_tensor_only() || u.per_tensor_only()) {
4298            return false;
4299        }
4300        if !a8w8_enabled() {
4301            if limit > 0.0 {
4302                // The exact-row fallback applies no SwiGLU clamp; the
4303                // caller's per-expert path carries it instead.
4304                return false;
4305            }
4306            let groups = vec![vec![0]; pairs.len()];
4307            return Self::moe_gate_up_rows(pairs, &groups, x, outs, pool);
4308        }
4309        let inter = pairs[0].0.rows();
4310        let cols = pairs[0].0.cols();
4311        if cols % GROUP_SIZE != 0 {
4312            return false;
4313        }
4314        let gpr = cols / GROUP_SIZE;
4315        // Uniform layout across every routed pair: q4tp, or the 2-bit
4316        // profile's q2tp gate/up (the W2 class). Mixed sets refuse.
4317        let q2 = matches!(
4318            pairs[0].0,
4319            Self::Mapped {
4320                dtype: TensorDtype::Q2TiledP,
4321                ..
4322            }
4323        );
4324        let want = if q2 {
4325            TensorDtype::Q2TiledP
4326        } else {
4327            TensorDtype::Q4TiledP
4328        };
4329        let mut views = Vec::with_capacity(pairs.len() * 2);
4330        for ((g, u), o) in pairs.iter().zip(outs.iter()) {
4331            let both = matches!(g, Self::Mapped { dtype, .. } if *dtype == want)
4332                && matches!(u, Self::Mapped { dtype, .. } if *dtype == want);
4333            if !both
4334                || g.rows() != inter
4335                || u.rows() != inter
4336                || g.cols() != cols
4337                || u.cols() != cols
4338                || o.len() != inter
4339            {
4340                return false;
4341            }
4342            let mk = if q2 { Q4tpView::new_q2 } else { Q4tpView::new };
4343            views.push(mk(g.quant_bytes(), inter, cols));
4344            views.push(mk(u.quant_bytes(), inter, cols));
4345        }
4346        let act = split_act(x);
4347        let gsum = if q2 {
4348            q1_group_sums(&act.xq, gpr)
4349        } else {
4350            Vec::new()
4351        };
4352        let (act, gsum) = (&act, &gsum);
4353        let ptrs: Vec<SendMut> = outs.iter_mut().map(|o| SendMut(o.as_mut_ptr())).collect();
4354        let (views, ptrs) = (&views, &ptrs);
4355        let run = |start: usize, end: usize| {
4356            with_krows(gpr, |gsc, usc| {
4357                for flat in start..end {
4358                    let (e, r) = (flat / inter, flat % inter);
4359                    let gv_view = &views[e * 2];
4360                    let uv_view = &views[e * 2 + 1];
4361                    gv_view.scales_into(r, gpr, gsc);
4362                    uv_view.scales_into(r, gpr, usc);
4363                    let (mut gv, mut uv) = if q2 {
4364                        (
4365                            dot_q2tp_row_i8(gv_view.nib, r, gpr, &act.xq, gsum, gsc) * act.sx,
4366                            dot_q2tp_row_i8(uv_view.nib, r, gpr, &act.xq, gsum, usc) * act.sx,
4367                        )
4368                    } else {
4369                        (
4370                            dot_q4tp_row_i8(gv_view.nib, r, gpr, &act.xq, gsc) * act.sx,
4371                            dot_q4tp_row_i8(uv_view.nib, r, gpr, &act.xq, usc) * act.sx,
4372                        )
4373                    };
4374                    for &(j, xv) in &act.outliers {
4375                        let (og, ou) = if q2 {
4376                            (
4377                                q2tp_outlier(gv_view.nib, r, gpr, j, gsc),
4378                                q2tp_outlier(uv_view.nib, r, gpr, j, usc),
4379                            )
4380                        } else {
4381                            (
4382                                q4tp_outlier(gv_view.nib, r, gpr, j, gsc),
4383                                q4tp_outlier(uv_view.nib, r, gpr, j, usc),
4384                            )
4385                        };
4386                        gv += og.0 * og.1 * xv;
4387                        uv += ou.0 * ou.1 * xv;
4388                    }
4389                    // SAFETY: one worker owns each (expert, row) pair.
4390                    unsafe { *ptrs[e].at(r) = silu_mul_limited(gv, uv, limit) };
4391                }
4392            });
4393        };
4394        dispatch_rows(pool, pairs.len() * inter, &run);
4395        true
4396    }
4397
4398    /// Every routed expert's down projection, weighted and summed into
4399    /// `out`, under ONE pool dispatch.
4400    ///
4401    /// Partitioned by OUTPUT row rather than by expert: each row is owned
4402    /// by a single worker, so the experts are summed in the caller's order
4403    /// — the same sequence of f32 adds the serial `out[i] += w·eo[i]` loop
4404    /// performs, hence bit-identical. Partitioning by expert instead would
4405    /// race on the shared accumulator.
4406    pub fn moe_down_many(
4407        downs: &[&QTensor],
4408        gs: &[Vec<f32>],
4409        weights: &[f32],
4410        out: &mut [f32],
4411        pool: Option<&Pool>,
4412    ) -> bool {
4413        if Self::any_exact_cpu_default(downs) {
4414            return float_activations_scope(|| {
4415                Self::moe_down_many(downs, gs, weights, out, pool)
4416            });
4417        }
4418        if downs.is_empty() || downs.len() != gs.len() || downs.len() != weights.len() {
4419            return false;
4420        }
4421        if downs.iter().any(|d| d.per_tensor_only()) {
4422            return false;
4423        }
4424        if !a8w8_enabled() {
4425            let mut terms = vec![vec![0.0; out.len()]; downs.len()];
4426            if !Self::moe_down_rows(downs, &vec![1; downs.len()], gs, &mut terms, pool) {
4427                return false;
4428            }
4429            out.fill(0.0);
4430            for (row, &w) in terms.iter().zip(weights) {
4431                for (o, &v) in out.iter_mut().zip(row) {
4432                    *o += w * v;
4433                }
4434            }
4435            return true;
4436        }
4437        let rows = out.len();
4438        let cols = downs[0].cols();
4439        if cols % GROUP_SIZE != 0 {
4440            return false;
4441        }
4442        let gpr = cols / GROUP_SIZE;
4443        let mut views = Vec::with_capacity(downs.len());
4444        for (d, g) in downs.iter().zip(gs.iter()) {
4445            if !matches!(
4446                d,
4447                Self::Mapped {
4448                    dtype: TensorDtype::Q4TiledP,
4449                    ..
4450                }
4451            ) || d.rows() != rows
4452                || d.cols() != cols
4453                || g.len() != cols
4454            {
4455                return false;
4456            }
4457            views.push(Q4tpView::new(d.quant_bytes(), rows, cols));
4458        }
4459        // One int8 split per expert — the activation vectors differ.
4460        let acts: Vec<SplitAct> = gs.iter().map(|g| split_act(g)).collect();
4461        // Partitioned by OUTPUT row, with the experts folded inside: each
4462        // row is owned by one worker, so they are summed in the caller's
4463        // order — the same f32 sequence the serial `out[i] += w·eo[i]`
4464        // loop produces. Partitioning by expert instead would either race
4465        // on the accumulator or need a scratch plane and a second pass;
4466        // measured, that variant was a wash, so this keeps the simpler
4467        // shape.
4468        let out_addr = SendMut(out.as_mut_ptr());
4469        let (views, acts, weights) = (&views, &acts, &weights);
4470        let run = |start: usize, end: usize| {
4471            with_krow(gpr, |sc| {
4472                for r in start..end {
4473                    let mut acc = 0f32;
4474                    for (e, v) in views.iter().enumerate() {
4475                        v.scales_into(r, gpr, sc);
4476                        let a = &acts[e];
4477                        let mut d = dot_q4tp_row_i8(v.nib, r, gpr, &a.xq, sc) * a.sx;
4478                        for &(j, xv) in &a.outliers {
4479                            let (w, s) = q4tp_outlier(v.nib, r, gpr, j, sc);
4480                            d += w * s * xv;
4481                        }
4482                        acc += weights[e] * d;
4483                    }
4484                    // SAFETY: disjoint row ranges per worker.
4485                    unsafe { *out_addr.at(r) = acc };
4486                }
4487            });
4488        };
4489        dispatch_rows(pool, rows, &run);
4490        true
4491    }
4492
4493    /// `moe_gate_up_many` for SEVERAL tokens at once, decode-exact: expert
4494    /// `e` (`pairs[e]`, q4tp) serves the tokens `groups[e]` (row indices
4495    /// into `xs`, each `cols` wide). Every (expert, token) output is
4496    /// bit-identical to `moe_gate_up_many` run on that token alone — the
4497    /// same int8 activation split, VNNI dots, outlier terms and inline
4498    /// SiLU — while each weight row is read once for all the tokens routed
4499    /// to its expert (the speculative verify's expert sharing). `outs` is
4500    /// flat in (expert, token-of-group) order. False = not covered (not
4501    /// q4tp): the caller takes the per-token path. With float activations,
4502    /// the exact scalar row kernel replaces the int8 dot without changing
4503    /// the shared dispatch or route-order reduction.
4504    pub fn moe_gate_up_rows(
4505        pairs: &[(&QTensor, &QTensor)],
4506        groups: &[Vec<usize>],
4507        xs: &[f32],
4508        outs: &mut [Vec<f32>],
4509        pool: Option<&Pool>,
4510    ) -> bool {
4511        if Self::any_exact_cpu_default_pairs(pairs) {
4512            return float_activations_scope(|| {
4513                Self::moe_gate_up_rows(pairs, groups, xs, outs, pool)
4514            });
4515        }
4516        if pairs.is_empty() || pairs.len() != groups.len() {
4517            return false;
4518        }
4519        if pairs.iter().any(|(g, u)| g.per_tensor_only() || u.per_tensor_only()) {
4520            return false;
4521        }
4522        let inter = pairs[0].0.rows();
4523        let cols = pairs[0].0.cols();
4524        let n_pairs: usize = groups.iter().map(|g| g.len()).sum();
4525        if cols == 0 || cols % GROUP_SIZE != 0 || outs.len() != n_pairs || xs.len() % cols != 0 {
4526            return false;
4527        }
4528        let b = xs.len() / cols;
4529        let gpr = cols / GROUP_SIZE;
4530        let mut views = Vec::with_capacity(pairs.len() * 2);
4531        for (g, u) in pairs {
4532            let q4tp = |t: &QTensor| {
4533                matches!(
4534                    t,
4535                    Self::Mapped {
4536                        dtype: TensorDtype::Q4TiledP,
4537                        ..
4538                    }
4539                )
4540            };
4541            if g.has_prism_contract()
4542                || u.has_prism_contract()
4543                || !q4tp(g)
4544                || !q4tp(u)
4545                || g.rows() != inter
4546                || u.rows() != inter
4547                || g.cols() != cols
4548                || u.cols() != cols
4549            {
4550                return false;
4551            }
4552            views.push(Q4tpView::new(g.quant_bytes(), inter, cols));
4553            views.push(Q4tpView::new(u.quant_bytes(), inter, cols));
4554        }
4555        if outs.iter().any(|o| o.len() != inter) || groups.iter().flatten().any(|&t| t >= b) {
4556            return false;
4557        }
4558        let quantized = a8w8_enabled();
4559        let acts: Vec<SplitAct> = if quantized {
4560            (0..b)
4561                .map(|t| split_act(&xs[t * cols..(t + 1) * cols]))
4562                .collect()
4563        } else {
4564            Vec::new()
4565        };
4566        let mut offs = Vec::with_capacity(groups.len());
4567        let mut o = 0usize;
4568        for g in groups {
4569            offs.push(o);
4570            o += g.len();
4571        }
4572        let ptrs: Vec<SendMut> = outs.iter_mut().map(|o| SendMut(o.as_mut_ptr())).collect();
4573        let (views, ptrs, acts, offs) = (&views, &ptrs, &acts, &offs);
4574        let run = |start: usize, end: usize| {
4575            let (mut gsc, mut usc) = (vec![0f32; gpr], vec![0f32; gpr]);
4576            for flat in start..end {
4577                let (e, r) = (flat / inter, flat % inter);
4578                let (gv_view, uv_view) = (&views[e * 2], &views[e * 2 + 1]);
4579                gv_view.scales_into(r, gpr, &mut gsc);
4580                uv_view.scales_into(r, gpr, &mut usc);
4581                for (k, &t) in groups[e].iter().enumerate() {
4582                    if !quantized {
4583                        let x = &xs[t * cols..(t + 1) * cols];
4584                        let gv = q4tp_row_exact(gv_view.nib, r, gpr, x, &gsc);
4585                        let uv = q4tp_row_exact(uv_view.nib, r, gpr, x, &usc);
4586                        unsafe { *ptrs[offs[e] + k].at(r) = (gv / (1.0 + (-gv).exp())) * uv };
4587                        continue;
4588                    }
4589                    let act = &acts[t];
4590                    let mut gv = dot_q4tp_row_i8(gv_view.nib, r, gpr, &act.xq, &gsc) * act.sx;
4591                    let mut uv = dot_q4tp_row_i8(uv_view.nib, r, gpr, &act.xq, &usc) * act.sx;
4592                    for &(j, xv) in &act.outliers {
4593                        let og = q4tp_outlier(gv_view.nib, r, gpr, j, &gsc);
4594                        let ou = q4tp_outlier(uv_view.nib, r, gpr, j, &usc);
4595                        gv += og.0 * og.1 * xv;
4596                        uv += ou.0 * ou.1 * xv;
4597                    }
4598                    let silu_g = gv / (1.0 + (-gv).exp());
4599                    // SAFETY: one worker owns each (expert, row) cell of
4600                    // every output of the expert's group.
4601                    unsafe { *ptrs[offs[e] + k].at(r) = silu_g * uv };
4602                }
4603            }
4604        };
4605        dispatch_rows(pool, pairs.len() * inter, &run);
4606        true
4607    }
4608
4609    /// The per-(expert, token) down terms `moe_down_many` weights and sums,
4610    /// for SEVERAL tokens: `outs[p][o] = down_e[o] · gs[p]` (int8 split of
4611    /// `gs[p]`, VNNI dot, outlier terms — bit-identical to that kernel's
4612    /// `d`), each down row read once for its expert's whole group. The
4613    /// caller sums `w·d` per token in its route order, which reproduces
4614    /// `moe_down_many`'s f32 sequence exactly. Layout as `moe_gate_up_rows`.
4615    pub fn moe_down_rows(
4616        downs: &[&QTensor],
4617        group_lens: &[usize],
4618        gs: &[Vec<f32>],
4619        outs: &mut [Vec<f32>],
4620        pool: Option<&Pool>,
4621    ) -> bool {
4622        if Self::any_exact_cpu_default(downs) {
4623            return float_activations_scope(|| {
4624                Self::moe_down_rows(downs, group_lens, gs, outs, pool)
4625            });
4626        }
4627        if downs.is_empty() || downs.len() != group_lens.len() {
4628            return false;
4629        }
4630        if downs.iter().any(|d| d.per_tensor_only()) {
4631            return false;
4632        }
4633        let rows = downs[0].rows();
4634        let cols = downs[0].cols();
4635        let n_pairs: usize = group_lens.iter().sum();
4636        if cols == 0 || cols % GROUP_SIZE != 0 || gs.len() != n_pairs || outs.len() != n_pairs {
4637            return false;
4638        }
4639        let gpr = cols / GROUP_SIZE;
4640        let mut views = Vec::with_capacity(downs.len());
4641        for d in downs {
4642            if d.has_prism_contract()
4643                || !matches!(
4644                    d,
4645                    Self::Mapped {
4646                        dtype: TensorDtype::Q4TiledP,
4647                        ..
4648                    }
4649                )
4650                || d.rows() != rows
4651                || d.cols() != cols
4652            {
4653                return false;
4654            }
4655            views.push(Q4tpView::new(d.quant_bytes(), rows, cols));
4656        }
4657        if gs.iter().any(|g| g.len() != cols) || outs.iter().any(|o| o.len() != rows) {
4658            return false;
4659        }
4660        let quantized = a8w8_enabled();
4661        let acts: Vec<SplitAct> = if quantized {
4662            gs.iter().map(|g| split_act(g)).collect()
4663        } else {
4664            Vec::new()
4665        };
4666        let mut offs = Vec::with_capacity(group_lens.len());
4667        let mut o = 0usize;
4668        for &l in group_lens {
4669            offs.push(o);
4670            o += l;
4671        }
4672        let ptrs: Vec<SendMut> = outs.iter_mut().map(|o| SendMut(o.as_mut_ptr())).collect();
4673        let (views, ptrs, acts, offs) = (&views, &ptrs, &acts, &offs);
4674        let run = |start: usize, end: usize| {
4675            let mut sc = vec![0f32; gpr];
4676            for flat in start..end {
4677                let (e, r) = (flat / rows, flat % rows);
4678                let v = &views[e];
4679                v.scales_into(r, gpr, &mut sc);
4680                for k in 0..group_lens[e] {
4681                    if !quantized {
4682                        let d = q4tp_row_exact(v.nib, r, gpr, &gs[offs[e] + k], &sc);
4683                        unsafe { *ptrs[offs[e] + k].at(r) = d };
4684                        continue;
4685                    }
4686                    let a = &acts[offs[e] + k];
4687                    let mut d = dot_q4tp_row_i8(v.nib, r, gpr, &a.xq, &sc) * a.sx;
4688                    for &(j, xv) in &a.outliers {
4689                        let (w, s) = q4tp_outlier(v.nib, r, gpr, j, &sc);
4690                        d += w * s * xv;
4691                    }
4692                    // SAFETY: one worker owns each (expert, row) cell.
4693                    unsafe { *ptrs[offs[e] + k].at(r) = d };
4694                }
4695            }
4696        };
4697        dispatch_rows(pool, downs.len() * rows, &run);
4698        true
4699    }
4700
4701    /// Whole experts for SEVERAL tokens in one dispatch: expert `e`
4702    /// (`experts[e]` = its gate, up and down, q4tp) serves the tokens
4703    /// `groups[e]` (row indices into `xs`, each `hidden` wide), and
4704    /// `out[p]` (`hidden` wide, flat in (expert, token-of-group) order) is
4705    /// the term `down_e · (silu(gate_e · x) ⊙ (up_e · x))` the caller weights
4706    /// and sums. The math of `moe_gate_up_rows` followed by `moe_down_rows`
4707    /// (the same int8 activation split, outlier terms and SiLU) with every
4708    /// row's sum taken in sixteen float lanes and the SiLU's exponent a
4709    /// sixteen-lane polynomial, so a value differs from theirs by rounding
4710    /// only; the work is one dispatch and one pass over the weights at the
4711    /// speed of the memory bus (see `qtensor/moe_fast.rs`). False =
4712    /// not covered (no AVX-512 VNNI, not q4tp, float activations, a shape
4713    /// outside 64-wide steps): the caller takes the two row kernels.
4714    pub fn moe_expert_rows_fast(
4715        experts: &[(&QTensor, &QTensor, &QTensor)],
4716        groups: &[Vec<usize>],
4717        xs: &[f32],
4718        out: &mut [f32],
4719        pool: Option<&Pool>,
4720    ) -> bool {
4721        #[cfg(target_arch = "x86_64")]
4722        {
4723            moe_fast::run(experts, groups, xs, out, pool)
4724        }
4725        #[cfg(not(target_arch = "x86_64"))]
4726        {
4727            let _ = (experts, groups, xs, out, pool);
4728            false
4729        }
4730    }
4731
4732    /// Turn the clock of [`QTensor::moe_expert_rows_fast`] on or off; returns what it was.
4733    pub fn moe_expert_rows_fast_prof(on: bool) -> bool {
4734        #[cfg(target_arch = "x86_64")]
4735        {
4736            moe_fast::PROF_ON.swap(on, Ordering::Relaxed)
4737        }
4738        #[cfg(not(target_arch = "x86_64"))]
4739        {
4740            let _ = on;
4741            false
4742        }
4743    }
4744
4745    /// What the clock of [`QTensor::moe_expert_rows_fast`] summed since the last call, as one line; `None`
4746    /// when the kernel did not run.
4747    pub fn moe_expert_rows_fast_prof_take() -> Option<String> {
4748        #[cfg(target_arch = "x86_64")]
4749        {
4750            let p = moe_fast::prof_take();
4751            let (calls, parts, experts) = (p[0], p[1], p[2]);
4752            if calls == 0 || parts == 0 || experts == 0 {
4753                return None;
4754            }
4755            // thread time a phase took of an expert, microseconds
4756            let us = |ns: u64| ns as f64 / 1e3 / experts as f64;
4757            let call = |ns: u64| ns as f64 / 1e3 / calls as f64;
4758            Some(format!(
4759                "{calls} calls of {:.1} threads, {experts} experts, {} pairs, outliers {:.1} a token row and {:.1} a gate row; \
4760                 a call {:.0} us of setup ({:.0} the tokens' split) and {:.0} us of wall; thread time an expert, us: \
4761                 entry {:.0}, gate/up {:.0}, gate rows {:.0}, down {:.0}, waiting {:.0}",
4762                parts as f64 / calls as f64,
4763                p[3],
4764                p[5] as f64 / p[4].max(1) as f64,
4765                p[6] as f64 / p[3].max(1) as f64,
4766                call(p[7]),
4767                call(p[8]),
4768                call(p[9]),
4769                us(p[10]),
4770                us(p[11]),
4771                us(p[12]),
4772                us(p[13]),
4773                us(p[14]),
4774            ))
4775        }
4776        #[cfg(not(target_arch = "x86_64"))]
4777        None
4778    }
4779
4780    /// Set a knob of [`QTensor::moe_expert_rows_fast`] for the calls to come: 0 = the bytes of weights a
4781    /// row prefetches ahead of itself, 1 and 2 = the blocks of rows a core takes at a time of gate/up
4782    /// and of down. For a measurement that compares them in one process; the defaults come from
4783    /// `CMF_QWEN_CPU_PF` and `CMF_QWEN_CPU_CLAIM`. Returns the knob's value before the call.
4784    pub fn moe_expert_rows_fast_tune(knob: usize, value: usize) -> usize {
4785        #[cfg(target_arch = "x86_64")]
4786        {
4787            moe_fast::set_tune(knob, value)
4788        }
4789        #[cfg(not(target_arch = "x86_64"))]
4790        {
4791            let _ = (knob, value);
4792            0
4793        }
4794    }
4795
4796    /// Latent (Edge0) experts on the host: expert `i` = `experts[i]` (gate, up `[ff, cols]`, down
4797    /// `[cols, ff]`, all `nvfp4` file tensors) takes the input rows `groups[i]` of `xs` (`[row][cols]`);
4798    /// `out` gets one `[cols]` row per pair, expert after expert. False: a tensor is not `nvfp4` of
4799    /// those shapes.
4800    pub fn nvfp4_latent_rows(
4801        experts: &[(&QTensor, &QTensor, &QTensor)],
4802        groups: &[Vec<usize>],
4803        xs: &[f32],
4804        out: &mut [f32],
4805        pool: Option<&Pool>,
4806    ) -> bool {
4807        let Some(&(g0, _, _)) = experts.first() else { return true };
4808        let (ff, cols) = (g0.rows(), g0.cols());
4809        let mut views = Vec::with_capacity(experts.len());
4810        for &(g, u, d) in experts {
4811            let ok = [g, u, d].iter().all(|t| t.is_nvfp4())
4812                && g.rows() == ff
4813                && u.rows() == ff
4814                && g.cols() == cols
4815                && u.cols() == cols
4816                && d.rows() == cols
4817                && d.cols() == ff;
4818            if !ok {
4819                return false;
4820            }
4821            views.push((g.quant_bytes(), u.quant_bytes(), d.quant_bytes()));
4822        }
4823        let pairs: usize = groups.iter().map(|g| g.len()).sum();
4824        if out.len() < pairs * cols || groups.len() != experts.len() {
4825            return false;
4826        }
4827        nvfp4::latent_rows(&views, ff, cols, groups, xs, out, pool);
4828        true
4829    }
4830
4831    /// Whether this host has the cores for [`QTensor::moe_expert_rows_fast`] (AVX-512 VNNI with the int8
4832    /// activation path on).
4833    pub fn moe_expert_rows_fast_available() -> bool {
4834        #[cfg(target_arch = "x86_64")]
4835        {
4836            avx512vnni_enabled() && a8w8_enabled()
4837        }
4838        #[cfg(not(target_arch = "x86_64"))]
4839        {
4840            false
4841        }
4842    }
4843}
4844
4845/// Batched q8 kernel: same math as qmatvec, the row makes a single
4846/// pass from memory for the whole batch.
4847/// Accelerate CBLAS — the Apple AMX matrix units, the same engine
4848/// llama.cpp's `-ngl 0` prefill rides via ggml-blas.
4849#[cfg(target_os = "macos")]
4850mod accel_blas {
4851    #[link(name = "Accelerate", kind = "framework")]
4852    unsafe extern "C" {
4853        pub fn cblas_sgemm(
4854            order: i32,
4855            trans_a: i32,
4856            trans_b: i32,
4857            m: i32,
4858            n: i32,
4859            k: i32,
4860            alpha: f32,
4861            a: *const f32,
4862            lda: i32,
4863            b: *const f32,
4864            ldb: i32,
4865            beta: f32,
4866            c: *mut f32,
4867            ldc: i32,
4868        );
4869    }
4870}
4871
4872#[cfg(target_os = "macos")]
4873pub(crate) fn accel_gemm_enabled() -> bool {
4874    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4875    *ON.get_or_init(|| std::env::var("CMF_ACCEL").map(|v| v != "0").unwrap_or(true))
4876}
4877
4878/// Off macOS the "accel" GEMM is the portable NEON micro-kernel below —
4879/// same entry point, so the batched-attention path opens on mobile.
4880#[cfg(all(target_arch = "aarch64", not(target_os = "macos")))]
4881pub(crate) fn accel_gemm_enabled() -> bool {
4882    true
4883}
4884
4885/// On x86-64 the "accel" GEMM is the AVX2 micro-kernel below, so the
4886/// batched attention opens there too; `CMF_CPU_ATTEND=0` keeps the
4887/// per-position attend, and a CPU without AVX2/FMA never leaves it.
4888#[cfg(all(target_arch = "x86_64", not(target_os = "macos")))]
4889pub(crate) fn accel_gemm_enabled() -> bool {
4890    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4891    *ON.get_or_init(|| {
4892        std::is_x86_feature_detected!("avx2")
4893            && std::is_x86_feature_detected!("fma")
4894            && std::env::var("CMF_CPU_ATTEND").map(|v| v != "0").unwrap_or(true)
4895    })
4896}
4897
4898/// Any other architecture has no CPU micro-GEMM: the per-position attend.
4899#[cfg(not(any(target_os = "macos", target_arch = "aarch64", target_arch = "x86_64")))]
4900#[allow(dead_code)]
4901pub(crate) fn accel_gemm_enabled() -> bool {
4902    false
4903}
4904
4905/// Portable NEON f32 GEMM (row-major, optional Bᵀ): a 4×8 fmla
4906/// micro-kernel with A broadcast against B panels — the mobile stand-in
4907/// for Accelerate in the batched causal attention (QKᵀ and P·V). Not a
4908/// BLAS: shapes here are the attention panels (m ≤ heads·chunk,
4909/// k = head_dim or context), and the goal is removing the per-position
4910/// quadratic wall, not peak GEMM.
4911#[cfg(target_arch = "aarch64")]
4912#[allow(clippy::too_many_arguments)]
4913pub(crate) fn neon_gemm_rm(
4914    m: usize,
4915    n: usize,
4916    k: usize,
4917    alpha: f32,
4918    a: &[f32],
4919    lda: usize,
4920    b_mat: &[f32],
4921    ldb: usize,
4922    b_rows_are_n: bool,
4923    c: &mut [f32],
4924    ldc: usize,
4925) {
4926    debug_assert!(a.len() >= (m - 1) * lda + k);
4927    debug_assert!(c.len() >= (m - 1) * ldc + n);
4928    // SAFETY: bounds asserted above; NEON is baseline on aarch64.
4929    unsafe {
4930        use core::arch::aarch64::*;
4931        let mut i = 0usize;
4932        while i < m {
4933            let mi = (m - i).min(4);
4934            let mut j = 0usize;
4935            while j < n {
4936                let nj = (n - j).min(8);
4937                if mi == 4 && nj == 8 {
4938                    let (mut c0a, mut c0b) = (vdupq_n_f32(0.0), vdupq_n_f32(0.0));
4939                    let (mut c1a, mut c1b) = (vdupq_n_f32(0.0), vdupq_n_f32(0.0));
4940                    let (mut c2a, mut c2b) = (vdupq_n_f32(0.0), vdupq_n_f32(0.0));
4941                    let (mut c3a, mut c3b) = (vdupq_n_f32(0.0), vdupq_n_f32(0.0));
4942                    for p in 0..k {
4943                        let (b0, b1) = if b_rows_are_n {
4944                            // B is [n, k]: column p of Bᵀ = element p of
4945                            // eight consecutive B rows — gathered.
4946                            let base = b_mat.as_ptr().add(j * ldb + p);
4947                            let g = |o: usize| *base.add(o * ldb);
4948                            ([g(0), g(1), g(2), g(3)], [g(4), g(5), g(6), g(7)])
4949                        } else {
4950                            let base = b_mat.as_ptr().add(p * ldb + j);
4951                            (
4952                                [*base, *base.add(1), *base.add(2), *base.add(3)],
4953                                [*base.add(4), *base.add(5), *base.add(6), *base.add(7)],
4954                            )
4955                        };
4956                        let bv0 = vld1q_f32(b0.as_ptr());
4957                        let bv1 = vld1q_f32(b1.as_ptr());
4958                        let a0 = vdupq_n_f32(*a.as_ptr().add(i * lda + p));
4959                        let a1 = vdupq_n_f32(*a.as_ptr().add((i + 1) * lda + p));
4960                        let a2 = vdupq_n_f32(*a.as_ptr().add((i + 2) * lda + p));
4961                        let a3 = vdupq_n_f32(*a.as_ptr().add((i + 3) * lda + p));
4962                        c0a = vfmaq_f32(c0a, a0, bv0);
4963                        c0b = vfmaq_f32(c0b, a0, bv1);
4964                        c1a = vfmaq_f32(c1a, a1, bv0);
4965                        c1b = vfmaq_f32(c1b, a1, bv1);
4966                        c2a = vfmaq_f32(c2a, a2, bv0);
4967                        c2b = vfmaq_f32(c2b, a2, bv1);
4968                        c3a = vfmaq_f32(c3a, a3, bv0);
4969                        c3b = vfmaq_f32(c3b, a3, bv1);
4970                    }
4971                    let al = vdupq_n_f32(alpha);
4972                    for (r, (ca, cb)) in [(c0a, c0b), (c1a, c1b), (c2a, c2b), (c3a, c3b)]
4973                        .iter()
4974                        .enumerate()
4975                    {
4976                        let dst = c.as_mut_ptr().add((i + r) * ldc + j);
4977                        vst1q_f32(dst, vmulq_f32(*ca, al));
4978                        vst1q_f32(dst.add(4), vmulq_f32(*cb, al));
4979                    }
4980                } else {
4981                    for r in 0..mi {
4982                        for q in 0..nj {
4983                            let mut acc = 0f32;
4984                            for p in 0..k {
4985                                let bv = if b_rows_are_n {
4986                                    b_mat[(j + q) * ldb + p]
4987                                } else {
4988                                    b_mat[p * ldb + j + q]
4989                                };
4990                                acc += a[(i + r) * lda + p] * bv;
4991                            }
4992                            c[(i + r) * ldc + j + q] = acc * alpha;
4993                        }
4994                    }
4995                }
4996                j += nj;
4997            }
4998            i += mi;
4999        }
5000    }
5001}
5002
5003/// Off-macOS aarch64: the batched attention rides the NEON micro-GEMM.
5004#[cfg(all(target_arch = "aarch64", not(target_os = "macos")))]
5005#[allow(clippy::too_many_arguments)]
5006pub(crate) fn sgemm_rm(
5007    m: usize,
5008    n: usize,
5009    k: usize,
5010    alpha: f32,
5011    a: &[f32],
5012    lda: usize,
5013    b_mat: &[f32],
5014    ldb: usize,
5015    b_rows_are_n: bool,
5016    c: &mut [f32],
5017    ldc: usize,
5018) {
5019    neon_gemm_rm(m, n, k, alpha, a, lda, b_mat, ldb, b_rows_are_n, c, ldc);
5020}
5021
5022/// The portable micro-GEMM of the batched causal attention: NEON on
5023/// aarch64, AVX2 on x86-64. Same contract as `neon_gemm_rm`.
5024#[cfg(target_arch = "aarch64")]
5025#[allow(clippy::too_many_arguments)]
5026pub(crate) fn micro_gemm_rm(
5027    m: usize,
5028    n: usize,
5029    k: usize,
5030    alpha: f32,
5031    a: &[f32],
5032    lda: usize,
5033    b_mat: &[f32],
5034    ldb: usize,
5035    b_rows_are_n: bool,
5036    c: &mut [f32],
5037    ldc: usize,
5038) {
5039    neon_gemm_rm(m, n, k, alpha, a, lda, b_mat, ldb, b_rows_are_n, c, ldc);
5040}
5041
5042/// The portable micro-GEMM of the batched causal attention (x86-64 arm).
5043#[cfg(target_arch = "x86_64")]
5044#[allow(clippy::too_many_arguments)]
5045pub(crate) fn micro_gemm_rm(
5046    m: usize,
5047    n: usize,
5048    k: usize,
5049    alpha: f32,
5050    a: &[f32],
5051    lda: usize,
5052    b_mat: &[f32],
5053    ldb: usize,
5054    b_rows_are_n: bool,
5055    c: &mut [f32],
5056    ldc: usize,
5057) {
5058    x86_gemm_rm(m, n, k, alpha, a, lda, b_mat, ldb, b_rows_are_n, c, ldc);
5059}
5060
5061/// Off-macOS x86-64: the batched attention rides the AVX2 micro-GEMM.
5062#[cfg(all(target_arch = "x86_64", not(target_os = "macos")))]
5063#[allow(clippy::too_many_arguments)]
5064pub(crate) fn sgemm_rm(
5065    m: usize,
5066    n: usize,
5067    k: usize,
5068    alpha: f32,
5069    a: &[f32],
5070    lda: usize,
5071    b_mat: &[f32],
5072    ldb: usize,
5073    b_rows_are_n: bool,
5074    c: &mut [f32],
5075    ldc: usize,
5076) {
5077    x86_gemm_rm(m, n, k, alpha, a, lda, b_mat, ldb, b_rows_are_n, c, ldc);
5078}
5079
5080/// Portable x86-64 f32 GEMM (row-major, optional Bᵀ): the x86 twin of
5081/// `neon_gemm_rm` for the batched causal attention (Q·Kᵀ and P·V). An
5082/// AVX2+FMA 4×16 micro-kernel with A broadcast against B panels, blocked
5083/// so a 128-column × 256-row slab of B stays in L2 while the rows of A
5084/// stream past it (the P·V multiply has k = context, so without the k
5085/// blocking V would be re-read once per four rows). Same contract:
5086/// C[m,n] = alpha·A[m,k] × B, B stored [k,n] — or [n,k] with
5087/// `b_rows_are_n`, which packs Bᵀ first (the attention callers never
5088/// take that arm: they pack Kᵀ themselves). Not a BLAS: the shapes are
5089/// attention panels, and the goal is the end of the per-position
5090/// quadratic wall on x86, not peak GEMM. Scalar on a CPU without
5091/// AVX2/FMA.
5092#[cfg(target_arch = "x86_64")]
5093#[allow(clippy::too_many_arguments)]
5094pub(crate) fn x86_gemm_rm(
5095    m: usize,
5096    n: usize,
5097    k: usize,
5098    alpha: f32,
5099    a: &[f32],
5100    lda: usize,
5101    b_mat: &[f32],
5102    ldb: usize,
5103    b_rows_are_n: bool,
5104    c: &mut [f32],
5105    ldc: usize,
5106) {
5107    if m == 0 || n == 0 {
5108        return;
5109    }
5110    debug_assert!(a.len() >= (m - 1) * lda + k);
5111    debug_assert!(c.len() >= (m - 1) * ldc + n);
5112    if b_rows_are_n {
5113        debug_assert!(k == 0 || b_mat.len() >= (n - 1) * ldb + k);
5114        let mut bt = vec![0f32; k * n];
5115        for j in 0..n {
5116            for (p, &v) in b_mat[j * ldb..j * ldb + k].iter().enumerate() {
5117                bt[p * n + j] = v;
5118            }
5119        }
5120        return x86_gemm_rm(m, n, k, alpha, a, lda, &bt, n, false, c, ldc);
5121    }
5122    if k == 0 {
5123        for r in 0..m {
5124            c[r * ldc..r * ldc + n].fill(0.0);
5125        }
5126        return;
5127    }
5128    debug_assert!(b_mat.len() >= (k - 1) * ldb + n);
5129    if std::is_x86_feature_detected!("avx2") && std::is_x86_feature_detected!("fma") {
5130        // SAFETY: the bounds hold (asserted above), and both features were
5131        // just detected on this CPU.
5132        unsafe { x86_gemm_avx2(m, n, k, alpha, a, lda, b_mat, ldb, c, ldc) }
5133    } else {
5134        for r in 0..m {
5135            for j in 0..n {
5136                let mut acc = 0f32;
5137                for p in 0..k {
5138                    acc += a[r * lda + p] * b_mat[p * ldb + j];
5139                }
5140                c[r * ldc + j] = acc * alpha;
5141            }
5142        }
5143    }
5144}
5145
5146/// The AVX2+FMA body of `x86_gemm_rm` (B stored [k,n]). Loop nest:
5147/// column block (128) → k block (256) → four rows of A → 16-column
5148/// panel; the first k block starts the accumulators at zero, later ones
5149/// resume from C, the last one applies `alpha`.
5150///
5151/// # Safety
5152/// The caller has checked `avx2` and `fma` and the slice bounds
5153/// (`a` ≥ (m−1)·lda + k, `b` ≥ (k−1)·ldb + n, `c` ≥ (m−1)·ldc + n).
5154#[cfg(target_arch = "x86_64")]
5155#[target_feature(enable = "avx2,fma")]
5156#[allow(clippy::too_many_arguments)]
5157unsafe fn x86_gemm_avx2(
5158    m: usize,
5159    n: usize,
5160    k: usize,
5161    alpha: f32,
5162    a: &[f32],
5163    lda: usize,
5164    b: &[f32],
5165    ldb: usize,
5166    c: &mut [f32],
5167    ldc: usize,
5168) {
5169    use core::arch::x86_64::*;
5170    const NC: usize = 128;
5171    const KC: usize = 256;
5172    unsafe {
5173        let ap = a.as_ptr();
5174        let bp = b.as_ptr();
5175        let cp = c.as_mut_ptr();
5176        let al = _mm256_set1_ps(alpha);
5177        let mut jc = 0usize;
5178        while jc < n {
5179            let jend = (jc + NC).min(n);
5180            let mut pc = 0usize;
5181            while pc < k {
5182                let pend = (pc + KC).min(k);
5183                let (first, last) = (pc == 0, pend == k);
5184                let mut i = 0usize;
5185                while i < m {
5186                    let mi = (m - i).min(4);
5187                    let mut j = jc;
5188                    while j < jend {
5189                        let nj = (jend - j).min(16);
5190                        if mi == 4 && nj == 16 {
5191                            let a0 = ap.add(i * lda);
5192                            let a1 = ap.add((i + 1) * lda);
5193                            let a2 = ap.add((i + 2) * lda);
5194                            let a3 = ap.add((i + 3) * lda);
5195                            let c0 = cp.add(i * ldc + j);
5196                            let c1 = cp.add((i + 1) * ldc + j);
5197                            let c2 = cp.add((i + 2) * ldc + j);
5198                            let c3 = cp.add((i + 3) * ldc + j);
5199                            let (mut c00, mut c01, mut c10, mut c11, mut c20, mut c21, mut c30, mut c31) =
5200                                if first {
5201                                    let z = _mm256_setzero_ps();
5202                                    (z, z, z, z, z, z, z, z)
5203                                } else {
5204                                    (
5205                                        _mm256_loadu_ps(c0),
5206                                        _mm256_loadu_ps(c0.add(8)),
5207                                        _mm256_loadu_ps(c1),
5208                                        _mm256_loadu_ps(c1.add(8)),
5209                                        _mm256_loadu_ps(c2),
5210                                        _mm256_loadu_ps(c2.add(8)),
5211                                        _mm256_loadu_ps(c3),
5212                                        _mm256_loadu_ps(c3.add(8)),
5213                                    )
5214                                };
5215                            for p in pc..pend {
5216                                let bb = bp.add(p * ldb + j);
5217                                let b0 = _mm256_loadu_ps(bb);
5218                                let b1 = _mm256_loadu_ps(bb.add(8));
5219                                let x0 = _mm256_broadcast_ss(&*a0.add(p));
5220                                c00 = _mm256_fmadd_ps(x0, b0, c00);
5221                                c01 = _mm256_fmadd_ps(x0, b1, c01);
5222                                let x1 = _mm256_broadcast_ss(&*a1.add(p));
5223                                c10 = _mm256_fmadd_ps(x1, b0, c10);
5224                                c11 = _mm256_fmadd_ps(x1, b1, c11);
5225                                let x2 = _mm256_broadcast_ss(&*a2.add(p));
5226                                c20 = _mm256_fmadd_ps(x2, b0, c20);
5227                                c21 = _mm256_fmadd_ps(x2, b1, c21);
5228                                let x3 = _mm256_broadcast_ss(&*a3.add(p));
5229                                c30 = _mm256_fmadd_ps(x3, b0, c30);
5230                                c31 = _mm256_fmadd_ps(x3, b1, c31);
5231                            }
5232                            if last {
5233                                c00 = _mm256_mul_ps(c00, al);
5234                                c01 = _mm256_mul_ps(c01, al);
5235                                c10 = _mm256_mul_ps(c10, al);
5236                                c11 = _mm256_mul_ps(c11, al);
5237                                c20 = _mm256_mul_ps(c20, al);
5238                                c21 = _mm256_mul_ps(c21, al);
5239                                c30 = _mm256_mul_ps(c30, al);
5240                                c31 = _mm256_mul_ps(c31, al);
5241                            }
5242                            _mm256_storeu_ps(c0, c00);
5243                            _mm256_storeu_ps(c0.add(8), c01);
5244                            _mm256_storeu_ps(c1, c10);
5245                            _mm256_storeu_ps(c1.add(8), c11);
5246                            _mm256_storeu_ps(c2, c20);
5247                            _mm256_storeu_ps(c2.add(8), c21);
5248                            _mm256_storeu_ps(c3, c30);
5249                            _mm256_storeu_ps(c3.add(8), c31);
5250                        } else {
5251                            // Row-at-a-time tail: fewer than four rows left,
5252                            // or a panel narrower than 16 columns.
5253                            for r in 0..mi {
5254                                let ar = ap.add((i + r) * lda);
5255                                let cr = cp.add((i + r) * ldc + j);
5256                                let mut q = 0usize;
5257                                while q + 8 <= nj {
5258                                    let mut acc = if first {
5259                                        _mm256_setzero_ps()
5260                                    } else {
5261                                        _mm256_loadu_ps(cr.add(q))
5262                                    };
5263                                    for p in pc..pend {
5264                                        acc = _mm256_fmadd_ps(
5265                                            _mm256_broadcast_ss(&*ar.add(p)),
5266                                            _mm256_loadu_ps(bp.add(p * ldb + j + q)),
5267                                            acc,
5268                                        );
5269                                    }
5270                                    if last {
5271                                        acc = _mm256_mul_ps(acc, al);
5272                                    }
5273                                    _mm256_storeu_ps(cr.add(q), acc);
5274                                    q += 8;
5275                                }
5276                                while q < nj {
5277                                    let mut acc = if first { 0.0 } else { *cr.add(q) };
5278                                    for p in pc..pend {
5279                                        acc += *ar.add(p) * *bp.add(p * ldb + j + q);
5280                                    }
5281                                    if last {
5282                                        acc *= alpha;
5283                                    }
5284                                    *cr.add(q) = acc;
5285                                    q += 1;
5286                                }
5287                            }
5288                        }
5289                        j += nj;
5290                    }
5291                    i += mi;
5292                }
5293                pc = pend;
5294            }
5295            jc = jend;
5296        }
5297    }
5298}
5299
5300/// Row-major f32 GEMM, exposed for offline tools (the AWNP pass builds a
5301/// per-layer projection and applies it to every expert; a naive triple loop
5302/// would turn a two-minute job into half an hour).
5303#[allow(clippy::too_many_arguments)]
5304pub fn sgemm_public(
5305    m: usize,
5306    n: usize,
5307    k: usize,
5308    alpha: f32,
5309    a: &[f32],
5310    lda: usize,
5311    b_mat: &[f32],
5312    ldb: usize,
5313    b_rows_are_n: bool,
5314    c: &mut [f32],
5315    ldc: usize,
5316) {
5317    #[cfg(any(target_os = "macos", target_arch = "aarch64"))]
5318    {
5319        sgemm_rm(m, n, k, alpha, a, lda, b_mat, ldb, b_rows_are_n, c, ldc);
5320    }
5321    // x86 without Accelerate has no sgemm_rm (the specialized paths there are
5322    // quantized kernels): the packed AVX/FMA/AVX-512 kernels of
5323    // matrixmultiply, single-threaded — offline callers split rows across
5324    // their own threads.
5325    #[cfg(not(any(target_os = "macos", target_arch = "aarch64")))]
5326    {
5327        if m == 0 || n == 0 {
5328            return;
5329        }
5330        assert!(a.len() >= (m - 1) * lda + k && c.len() >= (m - 1) * ldc + n);
5331        let (rsb, csb) = if b_rows_are_n { (1, ldb as isize) } else { (ldb as isize, 1) };
5332        assert!(k == 0 || b_mat.len() > if b_rows_are_n { (n - 1) * ldb + k - 1 } else { (k - 1) * ldb + n - 1 });
5333        // SAFETY: the asserts above bound every element the strides reach.
5334        unsafe {
5335            matrixmultiply::sgemm(
5336                m,
5337                k,
5338                n,
5339                alpha,
5340                a.as_ptr(),
5341                lda as isize,
5342                1,
5343                b_mat.as_ptr(),
5344                rsb,
5345                csb,
5346                0.0,
5347                c.as_mut_ptr(),
5348                ldc as isize,
5349                1,
5350            );
5351        }
5352    }
5353}
5354
5355/// Row-major f32 GEMM on Accelerate: C[m,n] = alpha·A[m,k] × B(ᵀ).
5356/// `b_rows_are_n` = true multiplies by Bᵀ where B is stored [n, k].
5357#[cfg(target_os = "macos")]
5358#[allow(clippy::too_many_arguments)]
5359pub(crate) fn sgemm_rm(
5360    m: usize,
5361    n: usize,
5362    k: usize,
5363    alpha: f32,
5364    a: &[f32],
5365    lda: usize,
5366    b_mat: &[f32],
5367    ldb: usize,
5368    b_rows_are_n: bool,
5369    c: &mut [f32],
5370    ldc: usize,
5371) {
5372    debug_assert!(a.len() >= (m - 1) * lda + k);
5373    debug_assert!(c.len() >= (m - 1) * ldc + n);
5374    // Test hook: route the attention GEMMs through the portable NEON
5375    // micro-kernel ON APPLE SILICON — how the mobile batched attend is
5376    // measured without a phone in the loop. (Intel macOS has no NEON —
5377    // the hook is a no-op there, Accelerate continues below.)
5378    #[cfg(target_arch = "aarch64")]
5379    if std::env::var("CMF_FORCE_NEON_GEMM")
5380        .map(|v| v == "1")
5381        .unwrap_or(false)
5382    {
5383        return neon_gemm_rm(m, n, k, alpha, a, lda, b_mat, ldb, b_rows_are_n, c, ldc);
5384    }
5385    unsafe {
5386        accel_blas::cblas_sgemm(
5387            101, // RowMajor
5388            111, // NoTrans A
5389            if b_rows_are_n { 112 } else { 111 },
5390            m as i32,
5391            n as i32,
5392            k as i32,
5393            alpha,
5394            a.as_ptr(),
5395            lda as i32,
5396            b_mat.as_ptr(),
5397            ldb as i32,
5398            0.0,
5399            c.as_mut_ptr(),
5400            ldc as i32,
5401        );
5402    }
5403}
5404
5405/// Prefill GEMM through Accelerate (macOS): dequantize q8 rows into
5406/// f32 tiles (scale folded in, pool-parallel) and multiply each tile
5407/// on the AMX with one row-major sgemm. Tiles live in cache, weights
5408/// stream once. Numerics are f32-GEMM (not the int8 dot): prefill
5409/// logits shift within f32 rounding — tolerance-class, like every
5410/// reduction-order change; decode (M=1) never takes this path.
5411#[cfg(target_os = "macos")]
5412fn qmatmat_accel(
5413    q: &[u8],
5414    row_scale: &[f32],
5415    pre: &[std::borrow::Cow<'_, [f32]>],
5416    rows: usize,
5417    cols: usize,
5418    out: &mut [f32],
5419    pool: Option<&Pool>,
5420) {
5421    // NOTE: double-buffering the dequant against the sgemm (a scoped
5422    // thread driving the pool on tile k+1 while the caller multiplies
5423    // tile k) was tried and LOST ~6%: Accelerate's sgemm is itself
5424    // multithreaded, and the dequant workers just steal its cores.
5425    const TR: usize = 2048;
5426    let b = pre.len();
5427    thread_local! {
5428        static XPANEL: std::cell::RefCell<Vec<f32>> = const { std::cell::RefCell::new(Vec::new()) };
5429        static WTILE: std::cell::RefCell<Vec<f32>> = const { std::cell::RefCell::new(Vec::new()) };
5430    }
5431    XPANEL.with(|xp| {
5432        WTILE.with(|wt| {
5433            let mut xpanel = xp.borrow_mut();
5434            xpanel.clear();
5435            for x in pre {
5436                xpanel.extend_from_slice(x);
5437            }
5438            let mut wtile = wt.borrow_mut();
5439            wtile.resize(TR * cols, 0.0);
5440            let mut r0 = 0usize;
5441            while r0 < rows {
5442                let tr = TR.min(rows - r0);
5443                // Dequant the tile (scale folded) — pool-parallel.
5444                let wt_addr = SendMut(wtile.as_mut_ptr());
5445                let run = |start: usize, end: usize| {
5446                    for r in start..end {
5447                        let row = &q[(r0 + r) * cols..(r0 + r + 1) * cols];
5448                        let s = row_scale[r0 + r];
5449                        // SAFETY: workers cover disjoint r ranges.
5450                        let dst =
5451                            unsafe { std::slice::from_raw_parts_mut(wt_addr.at(r * cols), cols) };
5452                        for (d, &v) in dst.iter_mut().zip(row) {
5453                            *d = (v as i8) as f32 * s;
5454                        }
5455                    }
5456                };
5457                dispatch_rows(pool, tr, &run);
5458                // C[b, tr] (at column r0 of out[b, rows]) = X · Wtileᵀ
5459                unsafe {
5460                    accel_blas::cblas_sgemm(
5461                        101, // RowMajor
5462                        111, // NoTrans A
5463                        112, // Trans B
5464                        b as i32,
5465                        tr as i32,
5466                        cols as i32,
5467                        1.0,
5468                        xpanel.as_ptr(),
5469                        cols as i32,
5470                        wtile.as_ptr(),
5471                        cols as i32,
5472                        0.0,
5473                        out.as_mut_ptr().add(r0),
5474                        rows as i32,
5475                    );
5476                }
5477                r0 += tr;
5478            }
5479        })
5480    });
5481}
5482
5483fn qmatmat(
5484    q: &[u8],
5485    row_scale: &[f32],
5486    pre: &[std::borrow::Cow<'_, [f32]>],
5487    rows: usize,
5488    cols: usize,
5489    out: &mut [f32],
5490    pool: Option<&Pool>,
5491) {
5492    let b = pre.len();
5493    debug_assert_eq!(out.len(), b * rows);
5494    let _p = crate::cpuprof::spans::span("mm.qmatmat");
5495    // Big prefill batches ride the AMX (roadmap PR3): the row×batch
5496    // SDOT loop below peaks near the CPU's dot throughput, an order
5497    // below the matrix units. Small tensors and tiny test models stay
5498    // on the exact integer path.
5499    #[cfg(target_os = "macos")]
5500    if b >= 8 && rows * cols >= 500_000 && accel_gemm_enabled() {
5501        qmatmat_accel(q, row_scale, pre, rows, cols, out, pool);
5502        return;
5503    }
5504    #[cfg(target_arch = "aarch64")]
5505    if sdot_enabled() {
5506        let acts: Vec<SplitAct> = pre.iter().map(|x| split_act(x)).collect();
5507        let out_addr = SendMut(out.as_mut_ptr());
5508        // Blocked 2×4 (mobile prefill: no AMX to fall back on — this
5509        // path IS the ARM prefill GEMM off Apple silicon).
5510        let blocked_ok = blocked_enabled();
5511        let use_i8mm = i8mm_enabled();
5512        if blocked_ok {
5513            let run = |start: usize, end: usize| {
5514                let mut o = start;
5515                while o < end {
5516                    if o + 2 <= end {
5517                        let r0 = &q[o * cols..(o + 1) * cols];
5518                        let r1 = &q[(o + 1) * cols..(o + 2) * cols];
5519                        let mut bi = 0usize;
5520                        while bi + 4 <= acts.len() {
5521                            let xs = [
5522                                acts[bi].xq.as_slice(),
5523                                acts[bi + 1].xq.as_slice(),
5524                                acts[bi + 2].xq.as_slice(),
5525                                acts[bi + 3].xq.as_slice(),
5526                            ];
5527                            let d = if use_i8mm {
5528                                unsafe { dot_i8_smmla_2x4(r0, r1, xs) }
5529                            } else {
5530                                unsafe { dot_i8_sdot_2x4(r0, r1, xs) }
5531                            };
5532                            for (r, row) in [r0, r1].into_iter().enumerate() {
5533                                for k in 0..4 {
5534                                    let act = &acts[bi + k];
5535                                    let mut v = d[r][k] as f32 * act.sx;
5536                                    for &(j, xv) in &act.outliers {
5537                                        v += (row[j] as i8) as f32 * xv;
5538                                    }
5539                                    unsafe {
5540                                        *out_addr.at((bi + k) * rows + o + r) = v * row_scale[o + r]
5541                                    };
5542                                }
5543                            }
5544                            bi += 4;
5545                        }
5546                        while bi < acts.len() {
5547                            for (r, row) in [r0, r1].into_iter().enumerate() {
5548                                let v = row_dot_sdot(row, &acts[bi]) * row_scale[o + r];
5549                                unsafe { *out_addr.at(bi * rows + o + r) = v };
5550                            }
5551                            bi += 1;
5552                        }
5553                        o += 2;
5554                    } else {
5555                        let row = &q[o * cols..(o + 1) * cols];
5556                        for (bi, act) in acts.iter().enumerate() {
5557                            let v = row_dot_sdot(row, act) * row_scale[o];
5558                            unsafe { *out_addr.at(bi * rows + o) = v };
5559                        }
5560                        o += 1;
5561                    }
5562                }
5563            };
5564            dispatch_rows(pool, rows, &run);
5565            return;
5566        }
5567        let run = |start: usize, end: usize| {
5568            for o in start..end {
5569                let row = &q[o * cols..(o + 1) * cols];
5570                for (bi, act) in acts.iter().enumerate() {
5571                    let v = row_dot_sdot(row, act) * row_scale[o];
5572                    unsafe { *out_addr.at(bi * rows + o) = v };
5573                }
5574            }
5575        };
5576        dispatch_rows(pool, rows, &run);
5577        return;
5578    }
5579    // x86 A8W8 batch. Non-VNNI parts take the BLOCKED 2×4 kernel
5580    // (roadmap P0: two weight rows' abs() stay in registers across four
5581    // activation streams); VNNI machines keep the per-row bias-trick
5582    // dot, which is already throughput-bound there.
5583    #[cfg(target_arch = "x86_64")]
5584    if avx2_a8w8_enabled() {
5585        let acts = {
5586            let _psa = crate::cpuprof::spans::span("mm.split_act");
5587            let a: Vec<SplitAct> = pre.iter().map(|x| split_act(x)).collect();
5588            drop(_psa);
5589            a
5590        };
5591        let out_addr = SendMut(out.as_mut_ptr());
5592        // CMF_X86_BLOCKED=0 forces the per-row path (paired in-process
5593        // A/B on noisy shared-vCPU hosts).
5594        let blocked_ok = blocked_enabled();
5595        if !avx512vnni_enabled() && blocked_ok && !row_exact() {
5596            let run = |start: usize, end: usize| {
5597                let mut o = start;
5598                while o < end {
5599                    if o + 2 <= end {
5600                        let r0 = &q[o * cols..(o + 1) * cols];
5601                        let r1 = &q[(o + 1) * cols..(o + 2) * cols];
5602                        let mut bi = 0usize;
5603                        while bi + 4 <= acts.len() {
5604                            let xs = [
5605                                acts[bi].xq.as_slice(),
5606                                acts[bi + 1].xq.as_slice(),
5607                                acts[bi + 2].xq.as_slice(),
5608                                acts[bi + 3].xq.as_slice(),
5609                            ];
5610                            let d = unsafe { dot_i8_i8_avx2_2x4(r0, r1, xs) };
5611                            for (r, row) in [r0, r1].into_iter().enumerate() {
5612                                for k in 0..4 {
5613                                    let act = &acts[bi + k];
5614                                    let mut v = d[r][k] as f32 * act.sx;
5615                                    for &(j, xv) in &act.outliers {
5616                                        v += (row[j] as i8) as f32 * xv;
5617                                    }
5618                                    unsafe {
5619                                        *out_addr.at((bi + k) * rows + o + r) = v * row_scale[o + r]
5620                                    };
5621                                }
5622                            }
5623                            bi += 4;
5624                        }
5625                        while bi < acts.len() {
5626                            for (r, row) in [r0, r1].into_iter().enumerate() {
5627                                let v = row_dot_avx2(row, &acts[bi]) * row_scale[o + r];
5628                                unsafe { *out_addr.at(bi * rows + o + r) = v };
5629                            }
5630                            bi += 1;
5631                        }
5632                        o += 2;
5633                    } else {
5634                        let row = &q[o * cols..(o + 1) * cols];
5635                        for (bi, act) in acts.iter().enumerate() {
5636                            let v = row_dot_avx2(row, act) * row_scale[o];
5637                            unsafe { *out_addr.at(bi * rows + o) = v };
5638                        }
5639                        o += 1;
5640                    }
5641                }
5642            };
5643            dispatch_rows(pool, rows, &run);
5644            return;
5645        }
5646        let run = |start: usize, end: usize| {
5647            for o in start..end {
5648                let row = &q[o * cols..(o + 1) * cols];
5649                for (bi, act) in acts.iter().enumerate() {
5650                    let v = row_dot_avx2(row, act) * row_scale[o];
5651                    unsafe { *out_addr.at(bi * rows + o) = v };
5652                }
5653            }
5654        };
5655        dispatch_rows(pool, rows, &run);
5656        return;
5657    }
5658    let out_addr = SendMut(out.as_mut_ptr());
5659    let run = |start: usize, end: usize| {
5660        for o in start..end {
5661            let row = &q[o * cols..(o + 1) * cols];
5662            for (bi, x) in pre.iter().enumerate() {
5663                let mut acc = 0f32;
5664                for j in 0..cols {
5665                    acc += (row[j] as i8) as f32 * x[j];
5666                }
5667                unsafe { *out_addr.at(bi * rows + o) = acc * row_scale[o] };
5668            }
5669        }
5670    };
5671    dispatch_rows(pool, rows, &run);
5672}
5673
5674/// Split rows across pool workers (shared qmatvec pattern). Self-balancing
5675/// — see `Pool::run_rows` for why a static 1/n split is wrong here.
5676thread_local! {
5677    /// Rows a fused kernel dispatched from this thread may compute (`npu_silu_mul`:
5678    /// the rest of the rows are on the NPU). `usize::MAX`: all of them.
5679    static ROW_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
5680}
5681
5682fn dispatch_rows(pool: Option<&Pool>, rows: usize, run: &(dyn Fn(usize, usize) + Sync)) {
5683    let rows = rows.min(ROW_LIMIT.with(|c| c.get()));
5684    match pool {
5685        Some(pool) if rows >= 256 => pool.run_rows(rows, run),
5686        _ => run(0, rows),
5687    }
5688}
5689
5690/// Split a q4_block blob into (packed nibbles, f16 group scales).
5691fn q4_split(bytes: &[u8], rows: usize, cols: usize) -> (&[u8], &[u8]) {
5692    let groups = rows * cols / GROUP_SIZE;
5693    bytes.split_at(groups * 16)
5694}
5695
5696/// SIMD unpack for the dominant vbit width B=4 (94% of rows on the
5697/// log2-shape calibration): 16 packed bytes -> 32 centered i8 values.
5698/// vbit packs MSB-first, so the HIGH nibble is the even element
5699/// (opposite of q4_block's lo-first interleave). Centering is u-7.
5700#[inline]
5701fn vbit_fill4(data: &[u8], buf: &mut [u8]) {
5702    #[cfg(target_arch = "aarch64")]
5703    unsafe {
5704        return vbit_fill4_neon(data, buf);
5705    }
5706    #[cfg(target_arch = "x86_64")]
5707    if avx2_enabled() {
5708        return unsafe { vbit_fill4_avx2(data, buf) };
5709    }
5710    #[allow(unreachable_code)]
5711    for (blk, chunk) in buf.chunks_exact_mut(8).enumerate() {
5712        let u = unpack8::<4>(&data[blk * 4..]);
5713        for k in 0..8 {
5714            chunk[k] = (u[k] - 7) as i8 as u8;
5715        }
5716    }
5717}
5718
5719#[cfg(target_arch = "aarch64")]
5720#[target_feature(enable = "neon")]
5721unsafe fn vbit_fill4_neon(data: &[u8], buf: &mut [u8]) {
5722    // SAFETY: buf.len() is a multiple of GROUP_SIZE=32; data holds
5723    // buf.len()/2 packed bytes (validated at load).
5724    unsafe {
5725        use core::arch::aarch64::*;
5726        let n = buf.len();
5727        let mask = vdupq_n_u8(0x0F);
5728        let seven = vdupq_n_s8(7);
5729        let mut g = 0usize;
5730        while g * 32 + 32 <= n {
5731            let b = vld1q_u8(data.as_ptr().add(g * 16));
5732            let hi = vshrq_n_u8::<4>(b);
5733            let lo = vandq_u8(b, mask);
5734            let z0 = vsubq_s8(vreinterpretq_s8_u8(vzip1q_u8(hi, lo)), seven);
5735            let z1 = vsubq_s8(vreinterpretq_s8_u8(vzip2q_u8(hi, lo)), seven);
5736            vst1q_u8(buf.as_mut_ptr().add(g * 32), vreinterpretq_u8_s8(z0));
5737            vst1q_u8(buf.as_mut_ptr().add(g * 32 + 16), vreinterpretq_u8_s8(z1));
5738            g += 1;
5739        }
5740    }
5741}
5742
5743#[cfg(target_arch = "x86_64")]
5744#[target_feature(enable = "avx2")]
5745unsafe fn vbit_fill4_avx2(data: &[u8], buf: &mut [u8]) {
5746    // SAFETY: see vbit_fill4_neon.
5747    unsafe {
5748        use core::arch::x86_64::*;
5749        let n = buf.len();
5750        let mask = _mm_set1_epi8(0x0F);
5751        let seven = _mm256_set1_epi8(7);
5752        let mut g = 0usize;
5753        while g * 32 + 32 <= n {
5754            let b = _mm_loadu_si128(data.as_ptr().add(g * 16) as *const __m128i);
5755            let hi = _mm_and_si128(_mm_srli_epi16::<4>(b), mask);
5756            let lo = _mm_and_si128(b, mask);
5757            let z = _mm256_sub_epi8(
5758                _mm256_set_m128i(_mm_unpackhi_epi8(hi, lo), _mm_unpacklo_epi8(hi, lo)),
5759                seven,
5760            );
5761            _mm256_storeu_si256(buf.as_mut_ptr().add(g * 32) as *mut __m256i, z);
5762            g += 1;
5763        }
5764    }
5765}
5766
5767/// Unpack 8 MSB-first B-bit values from exactly B bytes (fixed shifts —
5768/// no serial bit-buffer, auto-vectorizable). Every 32-value group starts
5769/// byte-aligned (32·B/8 is integral for B∈3..8), so groups decompose
5770/// into 4 such blocks.
5771#[inline(always)]
5772fn unpack8<const B: usize>(data: &[u8]) -> [i32; 8] {
5773    let mut acc = 0u64;
5774    for i in 0..B {
5775        acc = (acc << 8) | data[i] as u64;
5776    }
5777    let mask = (1u64 << B) - 1;
5778    let mut out = [0i32; 8];
5779    for (k, o) in out.iter_mut().enumerate() {
5780        *o = ((acc >> ((7 - k) * B)) & mask) as i32;
5781    }
5782    out
5783}
5784
5785/// Fused vbit matvec straight from the mapped bytes (spec §3, P13
5786/// FIG.3): [u8 bits: rows][f16 scales: rows·cols/32][bit-packed rows,
5787/// MSB-first, byte-padded]. Row data offsets are precomputed at load
5788/// (`vbit_row_offsets`) — the per-call prefix scan was O(rows) pure
5789/// overhead on every matvec.
5790#[allow(clippy::too_many_arguments)]
5791fn vbitmatvec(
5792    bytes: &[u8],
5793    offsets: &[usize],
5794    x: &[f32],
5795    rows: usize,
5796    cols: usize,
5797    out: &mut [f32],
5798    pool: Option<&Pool>,
5799) {
5800    debug_assert_eq!(out.len(), rows);
5801    debug_assert_eq!(offsets.len(), rows + 1);
5802
5803    // SDOT path: unpack the row to centered i8 once, then per-group
5804    // int8 dot against the quantized activations — same A8W8 contract
5805    // as q8 (bounded noise; CMF_SDOT=0 keeps the exact scalar path).
5806    if a8w8_enabled() {
5807        let act = split_act(x);
5808        let out_addr = SendMut(out.as_mut_ptr());
5809        let run = move |start: usize, end: usize| {
5810            vbit_range_a8w8(bytes, offsets, x, &act, rows, cols, out_addr, start, end)
5811        };
5812        dispatch_rows(pool, rows, &run);
5813        return;
5814    }
5815
5816    let out_addr = SendMut(out.as_mut_ptr());
5817    let run = move |start: usize, end: usize| {
5818        vbit_range_f32(bytes, offsets, x, rows, cols, out_addr, start, end)
5819    };
5820    dispatch_rows(pool, rows, &run);
5821}
5822
5823/// One vbit row range via the A8W8 int8 path — kernel body of
5824/// `vbitmatvec`, extracted so multi-matrix jobs can drive it for
5825/// several tensors in one dispatch (b=8 rows go exact f32).
5826#[allow(clippy::too_many_arguments)]
5827fn vbit_range_a8w8(
5828    bytes: &[u8],
5829    offsets: &[usize],
5830    x: &[f32],
5831    act: &SplitAct,
5832    rows: usize,
5833    cols: usize,
5834    out: SendMut,
5835    start: usize,
5836    end: usize,
5837) {
5838    let ng = cols / GROUP_SIZE;
5839    let bits = &bytes[..rows];
5840    let sc_off = rows;
5841    let row_dot = |r: usize| -> f32 {
5842        let b = bits[r] as usize;
5843        let l = (1i32 << (b - 1)) - 1;
5844        let mask = (1u64 << b) - 1;
5845        let data = &bytes[offsets[r]..offsets[r + 1]];
5846        if b == 8 {
5847            // u−L reaches 128 → does not fit i8; exact f32 path.
5848            let (mut acc, mut nbits, mut idx) = (0u64, 0usize, 0usize);
5849            let mut dot = 0f32;
5850            for g in 0..ng {
5851                let so = (r * ng + g) * 2;
5852                let sgf = f16_to_f32(u16::from_le_bytes([
5853                    bytes[sc_off + so],
5854                    bytes[sc_off + so + 1],
5855                ]));
5856                let xg = &x[g * GROUP_SIZE..(g + 1) * GROUP_SIZE];
5857                let mut gd = 0f32;
5858                for &xv in xg.iter() {
5859                    if nbits < 8 {
5860                        acc = (acc << 8) | data[idx] as u64;
5861                        idx += 1;
5862                        nbits += 8;
5863                    }
5864                    let u = ((acc >> (nbits - 8)) & 0xFF) as i32;
5865                    nbits -= 8;
5866                    gd += (u - l) as f32 * xv;
5867                }
5868                dot += gd * sgf;
5869            }
5870            return dot;
5871        }
5872        // Per-worker scratch: this closure runs for every row of the
5873        // tensor (lm_head ≈ 150k rows/token) — a heap allocation per
5874        // row was measurable pure overhead.
5875        thread_local! {
5876            static VBIT_SCRATCH: std::cell::RefCell<Vec<u8>> =
5877                const { std::cell::RefCell::new(Vec::new()) };
5878        }
5879        #[inline(always)]
5880        fn fill<const B: usize>(data: &[u8], l: i32, buf: &mut [u8]) {
5881            for (blk, chunk) in buf.chunks_exact_mut(8).enumerate() {
5882                let u = unpack8::<B>(&data[blk * B..]);
5883                for k in 0..8 {
5884                    chunk[k] = (u[k] - l) as i8 as u8;
5885                }
5886            }
5887        }
5888        let _ = mask;
5889        VBIT_SCRATCH.with(|scratch| {
5890            let mut buf = scratch.borrow_mut();
5891            buf.resize(cols, 0);
5892            match b {
5893                3 => fill::<3>(data, l, &mut buf),
5894                4 => vbit_fill4(data, &mut buf),
5895                5 => fill::<5>(data, l, &mut buf),
5896                6 => fill::<6>(data, l, &mut buf),
5897                _ => unreachable!(),
5898            }
5899            let mut dot = 0f32;
5900            for g in 0..ng {
5901                let so = (r * ng + g) * 2;
5902                let s = f16_to_f32(u16::from_le_bytes([
5903                    bytes[sc_off + so],
5904                    bytes[sc_off + so + 1],
5905                ]));
5906                let d = dot_i8_i8(
5907                    &buf[g * GROUP_SIZE..(g + 1) * GROUP_SIZE],
5908                    &act.xq[g * GROUP_SIZE..(g + 1) * GROUP_SIZE],
5909                ) as f32
5910                    * act.sx;
5911                dot += d * s;
5912            }
5913            for &(j, xv) in &act.outliers {
5914                let so = (r * ng + j / GROUP_SIZE) * 2;
5915                let s = f16_to_f32(u16::from_le_bytes([
5916                    bytes[sc_off + so],
5917                    bytes[sc_off + so + 1],
5918                ]));
5919                // xq is zeroed at outlier slots — add the exact term.
5920                dot += (buf[j] as i8) as f32 * s * xv;
5921            }
5922            dot
5923        })
5924    };
5925    for r in start..end {
5926        // SAFETY: disjoint row ranges per worker.
5927        unsafe { *out.at(r) = row_dot(r) };
5928    }
5929}
5930
5931/// Exact scalar vbit row range (same extraction, non-SDOT path).
5932#[allow(clippy::too_many_arguments)]
5933fn vbit_range_f32(
5934    bytes: &[u8],
5935    offsets: &[usize],
5936    x: &[f32],
5937    rows: usize,
5938    cols: usize,
5939    out: SendMut,
5940    start: usize,
5941    end: usize,
5942) {
5943    let ng = cols / GROUP_SIZE;
5944    let bits = &bytes[..rows];
5945    let sc_off = rows;
5946    // Per-bit-width specialized inner loops: the compiler unrolls the
5947    // constant shifts (the generic bit-buffer loop was branch-bound —
5948    // 5.6 vs 13.2 tok/s q4 on the 0.8B).
5949    #[inline(always)]
5950    fn dot_row<const B: usize>(
5951        data: &[u8],
5952        bytes: &[u8],
5953        sc_off: usize,
5954        r: usize,
5955        ng: usize,
5956        x: &[f32],
5957    ) -> f32 {
5958        let l = ((1i32 << (B - 1)) - 1) as f32;
5959        let gbytes = GROUP_SIZE * B / 8;
5960        let mut dot = 0f32;
5961        for g in 0..ng {
5962            let so = (r * ng + g) * 2;
5963            let s = f16_to_f32(u16::from_le_bytes([
5964                bytes[sc_off + so],
5965                bytes[sc_off + so + 1],
5966            ]));
5967            let xg = &x[g * GROUP_SIZE..(g + 1) * GROUP_SIZE];
5968            let gd0 = &data[g * gbytes..(g + 1) * gbytes];
5969            let mut gd = 0f32;
5970            for blk in 0..GROUP_SIZE / 8 {
5971                let u = unpack8::<B>(&gd0[blk * B..]);
5972                let xb = &xg[blk * 8..blk * 8 + 8];
5973                for k in 0..8 {
5974                    gd += (u[k] as f32 - l) * xb[k];
5975                }
5976            }
5977            dot += gd * s;
5978        }
5979        dot
5980    }
5981    for r in start..end {
5982        let data = &bytes[offsets[r]..offsets[r + 1]];
5983        let v = match bits[r] {
5984            3 => dot_row::<3>(data, bytes, sc_off, r, ng, x),
5985            4 => dot_row::<4>(data, bytes, sc_off, r, ng, x),
5986            5 => dot_row::<5>(data, bytes, sc_off, r, ng, x),
5987            6 => dot_row::<6>(data, bytes, sc_off, r, ng, x),
5988            8 => dot_row::<8>(data, bytes, sc_off, r, ng, x),
5989            b => unreachable!("vbit bit-width {b} (validated at load)"),
5990        };
5991        // SAFETY: disjoint row ranges per worker.
5992        unsafe { *out.at(r) = v };
5993    }
5994}
5995
5996/// Fused two-input vbit matvec: each row is unpacked from the mmap ONCE
5997/// and dotted against BOTH activations (MTP verify / pair prefill used
5998/// to run two full matvecs — double weight traffic and double unpack).
5999/// Per-input math is identical to `vbitmatvec` → same accuracy contract.
6000#[allow(clippy::too_many_arguments)]
6001fn vbitmatvec2(
6002    bytes: &[u8],
6003    offsets: &[usize],
6004    x1: &[f32],
6005    x2: &[f32],
6006    rows: usize,
6007    cols: usize,
6008    o1: &mut [f32],
6009    o2: &mut [f32],
6010    pool: Option<&Pool>,
6011) {
6012    debug_assert_eq!(o1.len(), rows);
6013    debug_assert_eq!(o2.len(), rows);
6014
6015    if a8w8_enabled() {
6016        let a1 = split_act(x1);
6017        let a2 = split_act(x2);
6018        let p1 = SendMut(o1.as_mut_ptr());
6019        let p2 = SendMut(o2.as_mut_ptr());
6020        let run = move |start: usize, end: usize| {
6021            vbit_range2_a8w8(
6022                bytes, offsets, x1, x2, &a1, &a2, rows, cols, p1, p2, start, end,
6023            )
6024        };
6025        dispatch_rows(pool, rows, &run);
6026        return;
6027    }
6028
6029    let p1 = SendMut(o1.as_mut_ptr());
6030    let p2 = SendMut(o2.as_mut_ptr());
6031    let run = move |start: usize, end: usize| {
6032        vbit_range2_f32(bytes, offsets, x1, x2, rows, cols, p1, p2, start, end)
6033    };
6034    dispatch_rows(pool, rows, &run);
6035}
6036
6037/// Two-input vbit row range via the A8W8 int8 path — kernel body of
6038/// `vbitmatvec2`, extracted for pair multi-matrix jobs (b=8 rows go
6039/// exact f32 for both lanes, bits streamed once).
6040#[allow(clippy::too_many_arguments)]
6041fn vbit_range2_a8w8(
6042    bytes: &[u8],
6043    offsets: &[usize],
6044    x1: &[f32],
6045    x2: &[f32],
6046    a1: &SplitAct,
6047    a2: &SplitAct,
6048    rows: usize,
6049    cols: usize,
6050    p1: SendMut,
6051    p2: SendMut,
6052    start: usize,
6053    end: usize,
6054) {
6055    let ng = cols / GROUP_SIZE;
6056    let bits = &bytes[..rows];
6057    let sc_off = rows;
6058    let row_dots = |r: usize| -> (f32, f32) {
6059        let b = bits[r] as usize;
6060        let l = (1i32 << (b - 1)) - 1;
6061        let data = &bytes[offsets[r]..offsets[r + 1]];
6062        if b == 8 {
6063            // u−L reaches 128 → does not fit i8; exact f32 path,
6064            // bits still streamed once for both lanes.
6065            let (mut acc, mut nbits, mut idx) = (0u64, 0usize, 0usize);
6066            let (mut d1, mut d2) = (0f32, 0f32);
6067            for g in 0..ng {
6068                let so = (r * ng + g) * 2;
6069                let sgf = f16_to_f32(u16::from_le_bytes([
6070                    bytes[sc_off + so],
6071                    bytes[sc_off + so + 1],
6072                ]));
6073                let (mut g1, mut g2) = (0f32, 0f32);
6074                for k in 0..GROUP_SIZE {
6075                    if nbits < 8 {
6076                        acc = (acc << 8) | data[idx] as u64;
6077                        idx += 1;
6078                        nbits += 8;
6079                    }
6080                    let u = ((acc >> (nbits - 8)) & 0xFF) as i32;
6081                    nbits -= 8;
6082                    let w = (u - l) as f32;
6083                    g1 += w * x1[g * GROUP_SIZE + k];
6084                    g2 += w * x2[g * GROUP_SIZE + k];
6085                }
6086                d1 += g1 * sgf;
6087                d2 += g2 * sgf;
6088            }
6089            return (d1, d2);
6090        }
6091        thread_local! {
6092            static VBIT_SCRATCH2: std::cell::RefCell<Vec<u8>> =
6093                const { std::cell::RefCell::new(Vec::new()) };
6094        }
6095        #[inline(always)]
6096        fn fill<const B: usize>(data: &[u8], l: i32, buf: &mut [u8]) {
6097            for (blk, chunk) in buf.chunks_exact_mut(8).enumerate() {
6098                let u = unpack8::<B>(&data[blk * B..]);
6099                for k in 0..8 {
6100                    chunk[k] = (u[k] - l) as i8 as u8;
6101                }
6102            }
6103        }
6104        VBIT_SCRATCH2.with(|scratch| {
6105            let mut buf = scratch.borrow_mut();
6106            buf.resize(cols, 0);
6107            match b {
6108                3 => fill::<3>(data, l, &mut buf),
6109                4 => vbit_fill4(data, &mut buf),
6110                5 => fill::<5>(data, l, &mut buf),
6111                6 => fill::<6>(data, l, &mut buf),
6112                _ => unreachable!(),
6113            }
6114            let (mut d1, mut d2) = (0f32, 0f32);
6115            for g in 0..ng {
6116                let so = (r * ng + g) * 2;
6117                let s = f16_to_f32(u16::from_le_bytes([
6118                    bytes[sc_off + so],
6119                    bytes[sc_off + so + 1],
6120                ]));
6121                let wg = &buf[g * GROUP_SIZE..(g + 1) * GROUP_SIZE];
6122                let v1 = dot_i8_i8(wg, &a1.xq[g * GROUP_SIZE..(g + 1) * GROUP_SIZE]) as f32 * a1.sx;
6123                let v2 = dot_i8_i8(wg, &a2.xq[g * GROUP_SIZE..(g + 1) * GROUP_SIZE]) as f32 * a2.sx;
6124                d1 += v1 * s;
6125                d2 += v2 * s;
6126            }
6127            for &(j, xv) in &a1.outliers {
6128                let so = (r * ng + j / GROUP_SIZE) * 2;
6129                let s = f16_to_f32(u16::from_le_bytes([
6130                    bytes[sc_off + so],
6131                    bytes[sc_off + so + 1],
6132                ]));
6133                d1 += (buf[j] as i8) as f32 * s * xv;
6134            }
6135            for &(j, xv) in &a2.outliers {
6136                let so = (r * ng + j / GROUP_SIZE) * 2;
6137                let s = f16_to_f32(u16::from_le_bytes([
6138                    bytes[sc_off + so],
6139                    bytes[sc_off + so + 1],
6140                ]));
6141                d2 += (buf[j] as i8) as f32 * s * xv;
6142            }
6143            (d1, d2)
6144        })
6145    };
6146    for r in start..end {
6147        let (v1, v2) = row_dots(r);
6148        // SAFETY: disjoint row ranges per worker.
6149        unsafe {
6150            *p1.at(r) = v1;
6151            *p2.at(r) = v2;
6152        }
6153    }
6154}
6155
6156/// Two-input exact scalar vbit row range (same extraction) —
6157/// per-bit-width specialized, two accumulators per row; per-lane
6158/// accumulation order matches `vbitmatvec` exactly.
6159#[allow(clippy::too_many_arguments)]
6160fn vbit_range2_f32(
6161    bytes: &[u8],
6162    offsets: &[usize],
6163    x1: &[f32],
6164    x2: &[f32],
6165    rows: usize,
6166    cols: usize,
6167    p1: SendMut,
6168    p2: SendMut,
6169    start: usize,
6170    end: usize,
6171) {
6172    let ng = cols / GROUP_SIZE;
6173    let bits = &bytes[..rows];
6174    let sc_off = rows;
6175    #[inline(always)]
6176    #[allow(clippy::too_many_arguments)]
6177    fn dot_row2<const B: usize>(
6178        data: &[u8],
6179        bytes: &[u8],
6180        sc_off: usize,
6181        r: usize,
6182        ng: usize,
6183        x1: &[f32],
6184        x2: &[f32],
6185    ) -> (f32, f32) {
6186        let l = ((1i32 << (B - 1)) - 1) as f32;
6187        let gbytes = GROUP_SIZE * B / 8;
6188        let (mut d1, mut d2) = (0f32, 0f32);
6189        for g in 0..ng {
6190            let so = (r * ng + g) * 2;
6191            let s = f16_to_f32(u16::from_le_bytes([
6192                bytes[sc_off + so],
6193                bytes[sc_off + so + 1],
6194            ]));
6195            let x1g = &x1[g * GROUP_SIZE..(g + 1) * GROUP_SIZE];
6196            let x2g = &x2[g * GROUP_SIZE..(g + 1) * GROUP_SIZE];
6197            let gd0 = &data[g * gbytes..(g + 1) * gbytes];
6198            let (mut g1, mut g2) = (0f32, 0f32);
6199            for blk in 0..GROUP_SIZE / 8 {
6200                let u = unpack8::<B>(&gd0[blk * B..]);
6201                for k in 0..8 {
6202                    let w = u[k] as f32 - l;
6203                    g1 += w * x1g[blk * 8 + k];
6204                    g2 += w * x2g[blk * 8 + k];
6205                }
6206            }
6207            d1 += g1 * s;
6208            d2 += g2 * s;
6209        }
6210        (d1, d2)
6211    }
6212    for r in start..end {
6213        let data = &bytes[offsets[r]..offsets[r + 1]];
6214        let (v1, v2) = match bits[r] {
6215            3 => dot_row2::<3>(data, bytes, sc_off, r, ng, x1, x2),
6216            4 => dot_row2::<4>(data, bytes, sc_off, r, ng, x1, x2),
6217            5 => dot_row2::<5>(data, bytes, sc_off, r, ng, x1, x2),
6218            6 => dot_row2::<6>(data, bytes, sc_off, r, ng, x1, x2),
6219            8 => dot_row2::<8>(data, bytes, sc_off, r, ng, x1, x2),
6220            b => unreachable!("vbit bit-width {b} (validated at load)"),
6221        };
6222        // SAFETY: disjoint row ranges per worker.
6223        unsafe {
6224            *p1.at(r) = v1;
6225            *p2.at(r) = v2;
6226        }
6227    }
6228}
6229
6230// ───────────────────── q4_tiled kernels (§4.3) ─────────────────────
6231
6232/// One q4_tiled row dot on the A8W8 int8 path: per 32-group the tile
6233/// is ONE sequential read — [f16 scale][16B nibbles] — versus the two
6234/// distant streams of the split layout. Values/order identical to the
6235/// split kernels.
6236#[inline]
6237#[allow(unreachable_code)]
6238fn dot_q4t_row_i8(bytes: &[u8], r: usize, gpr: usize, xq: &[i8]) -> f32 {
6239    #[cfg(target_arch = "aarch64")]
6240    unsafe {
6241        return dot_q4t_row_sdot(bytes, r, gpr, xq);
6242    }
6243    #[cfg(target_arch = "x86_64")]
6244    unsafe {
6245        if vnni_tiles_enabled() {
6246            return dot_q4t_row_vnni(bytes, r, gpr, xq);
6247        }
6248        return dot_q4t_row_avx2(bytes, r, gpr, xq);
6249    }
6250    let mut acc = 0f32;
6251    for gi in 0..gpr {
6252        let tile = &bytes[(r * gpr + gi) * Q4_TILE..(r * gpr + gi + 1) * Q4_TILE];
6253        let s = f16_to_f32(u16::from_le_bytes([tile[0], tile[1]]));
6254        let mut d = 0i32;
6255        for (k, &b) in tile[2..].iter().enumerate() {
6256            d += ((b & 0x0F) as i32 - 8) * xq[gi * GROUP_SIZE + k * 2] as i32
6257                + (((b >> 4) & 0x0F) as i32 - 8) * xq[gi * GROUP_SIZE + k * 2 + 1] as i32;
6258        }
6259        acc += d as f32 * s;
6260    }
6261    acc
6262}
6263
6264#[cfg(target_arch = "aarch64")]
6265#[target_feature(enable = "neon,dotprod")]
6266unsafe fn dot_q4t_row_sdot(bytes: &[u8], r: usize, gpr: usize, xq: &[i8]) -> f32 {
6267    // SAFETY: callers uphold slice-length contracts (18B tile per group,
6268    // xq.len() == gpr·GROUP_SIZE).
6269    unsafe {
6270        use core::arch::aarch64::*;
6271        use core::arch::asm;
6272        let lomask = vdupq_n_u8(0x0F);
6273        let eight = vdupq_n_s8(8);
6274        let mut acc = 0f32;
6275        for gi in 0..gpr {
6276            let t = bytes.as_ptr().add((r * gpr + gi) * Q4_TILE);
6277            let s = f16_to_f32(u16::from_le_bytes([*t, *t.add(1)]));
6278            let b = vld1q_u8(t.add(2));
6279            let lo = vandq_u8(b, lomask);
6280            let hi = vshrq_n_u8::<4>(b);
6281            let e0 = vsubq_s8(vreinterpretq_s8_u8(vzip1q_u8(lo, hi)), eight);
6282            let e1 = vsubq_s8(vreinterpretq_s8_u8(vzip2q_u8(lo, hi)), eight);
6283            let x0 = vld1q_s8(xq.as_ptr().add(gi * GROUP_SIZE));
6284            let x1 = vld1q_s8(xq.as_ptr().add(gi * GROUP_SIZE + 16));
6285            let (mut a0, mut a1) = (vdupq_n_s32(0), vdupq_n_s32(0));
6286            asm!(
6287                "sdot {a0:v}.4s, {e0:v}.16b, {x0:v}.16b",
6288                "sdot {a1:v}.4s, {e1:v}.16b, {x1:v}.16b",
6289                a0 = inout(vreg) a0, a1 = inout(vreg) a1,
6290                e0 = in(vreg) e0, x0 = in(vreg) x0, e1 = in(vreg) e1, x1 = in(vreg) x1,
6291                options(pure, nomem, nostack),
6292            );
6293            acc += vaddvq_s32(vaddq_s32(a0, a1)) as f32 * s;
6294        }
6295        acc
6296    }
6297}
6298
6299#[cfg(target_arch = "x86_64")]
6300#[target_feature(enable = "avx2")]
6301unsafe fn dot_q4t_row_avx2(bytes: &[u8], r: usize, gpr: usize, xq: &[i8]) -> f32 {
6302    // SAFETY: see dot_q4t_row_sdot.
6303    unsafe {
6304        use core::arch::x86_64::*;
6305        let lomask = _mm_set1_epi8(0x0F);
6306        let eight = _mm256_set1_epi8(8);
6307        let ones = _mm256_set1_epi16(1);
6308        let mut acc = 0f32;
6309        for gi in 0..gpr {
6310            let t = bytes.as_ptr().add((r * gpr + gi) * Q4_TILE);
6311            let s = f16_to_f32(u16::from_le_bytes([*t, *t.add(1)]));
6312            let b = _mm_loadu_si128(t.add(2) as *const __m128i);
6313            let lo = _mm_and_si128(b, lomask);
6314            let hi = _mm_and_si128(_mm_srli_epi16::<4>(b), lomask);
6315            let w = _mm256_sub_epi8(
6316                _mm256_set_m128i(_mm_unpackhi_epi8(lo, hi), _mm_unpacklo_epi8(lo, hi)),
6317                eight,
6318            );
6319            let x = _mm256_loadu_si256(xq.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
6320            let p16 = _mm256_maddubs_epi16(_mm256_abs_epi8(w), _mm256_sign_epi8(x, w));
6321            let d = _mm256_madd_epi16(p16, ones);
6322            let hi128 = _mm256_extracti128_si256::<1>(d);
6323            let s128 = _mm_add_epi32(_mm256_castsi256_si128(d), hi128);
6324            let s64 = _mm_add_epi32(s128, _mm_srli_si128::<8>(s128));
6325            let s32 = _mm_add_epi32(s64, _mm_srli_si128::<4>(s64));
6326            acc += _mm_cvtsi128_si32(s32) as f32 * s;
6327        }
6328        acc
6329    }
6330}
6331
6332/// VNNI twin of `dot_q4t_row_avx2`: same unpack, `vpdpbusd` replaces
6333/// the maddubs+madd pair (see `dpbusd_hsum` — sums are bit-identical).
6334/// 256-bit VL encoding, so the VEX `vpsignb` stays usable.
6335#[cfg(target_arch = "x86_64")]
6336#[target_feature(enable = "avx2,avx512f,avx512bw,avx512vl,avx512vnni")]
6337unsafe fn dot_q4t_row_vnni(bytes: &[u8], r: usize, gpr: usize, xq: &[i8]) -> f32 {
6338    // SAFETY: see dot_q4t_row_sdot.
6339    unsafe {
6340        use core::arch::x86_64::*;
6341        let lomask = _mm_set1_epi8(0x0F);
6342        let eight = _mm256_set1_epi8(8);
6343        let mut acc = 0f32;
6344        for gi in 0..gpr {
6345            let t = bytes.as_ptr().add((r * gpr + gi) * Q4_TILE);
6346            let s = f16_to_f32(u16::from_le_bytes([*t, *t.add(1)]));
6347            let b = _mm_loadu_si128(t.add(2) as *const __m128i);
6348            let lo = _mm_and_si128(b, lomask);
6349            let hi = _mm_and_si128(_mm_srli_epi16::<4>(b), lomask);
6350            let w = _mm256_sub_epi8(
6351                _mm256_set_m128i(_mm_unpackhi_epi8(lo, hi), _mm_unpacklo_epi8(lo, hi)),
6352                eight,
6353            );
6354            let x = _mm256_loadu_si256(xq.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
6355            let d = dpbusd_hsum(_mm256_abs_epi8(w), _mm256_sign_epi8(x, w));
6356            acc += d as f32 * s;
6357        }
6358        acc
6359    }
6360}
6361
6362/// One q4_tiled row against FOUR activation streams: the nibble unpack
6363/// and abs() happen once per group instead of once per (group,
6364/// activation) — the unpack is the dominant per-element cost of the
6365/// tiled format (roadmap P0 portable blocking, q4t leg).
6366#[cfg(target_arch = "x86_64")]
6367// `fma` is NOT implied by `avx2`: without it LLVM lowers _mm256_fmadd_ps
6368// to a libm call per lane — measured 2x slower than the reduction this
6369// kernel replaces. The runtime gate (`avx2_enabled`) already requires
6370// both features, so declaring it here is safe.
6371#[target_feature(enable = "avx2,fma")]
6372unsafe fn dot_q4t_row_1x4_avx2(bytes: &[u8], r: usize, gpr: usize, xs: [&[i8]; 4]) -> [f32; 4] {
6373    // SAFETY: callers uphold the 18B-tile and xq-length contracts.
6374    unsafe {
6375        use core::arch::x86_64::*;
6376        let lomask = _mm_set1_epi8(0x0F);
6377        let eight = _mm256_set1_epi8(8);
6378        let ones = _mm256_set1_epi16(1);
6379        // One f32 accumulator VECTOR per activation, reduced once at the
6380        // end. Folding each group's i32 lanes to a scalar inside the loop
6381        // costs an extracti128 + three shift/add + a movd — a cross-lane
6382        // dependency chain per (group, activation), 288 of them per row at
6383        // cols=2304. The per-group scale is what forces a float
6384        // accumulator; it does not force a horizontal sum.
6385        //
6386        // The four accumulators are NAMED, not an array: as `[__m256; 4]`
6387        // indexed by a loop variable LLVM keeps them in memory and every
6388        // group pays four 32-byte loads and stores. That alone made this
6389        // kernel 2x SLOWER than the per-group reduction it replaces
6390        // (measured on the EPYC box: 150 s vs 71 s for two 256² steps).
6391        let mut f0 = _mm256_setzero_ps();
6392        let mut f1 = _mm256_setzero_ps();
6393        let mut f2 = _mm256_setzero_ps();
6394        let mut f3 = _mm256_setzero_ps();
6395        for gi in 0..gpr {
6396            let t = bytes.as_ptr().add((r * gpr + gi) * Q4_TILE);
6397            let s = f16_to_f32(u16::from_le_bytes([*t, *t.add(1)]));
6398            let sv = _mm256_set1_ps(s);
6399            let bb = _mm_loadu_si128(t.add(2) as *const __m128i);
6400            let lo = _mm_and_si128(bb, lomask);
6401            let hi = _mm_and_si128(_mm_srli_epi16::<4>(bb), lomask);
6402            let w = _mm256_sub_epi8(
6403                _mm256_set_m128i(_mm_unpackhi_epi8(lo, hi), _mm_unpacklo_epi8(lo, hi)),
6404                eight,
6405            );
6406            let aw = _mm256_abs_epi8(w);
6407            let off = gi * GROUP_SIZE;
6408            let dot = |xq: &[i8]| {
6409                let x = _mm256_loadu_si256(xq.as_ptr().add(off) as *const __m256i);
6410                let p16 = _mm256_maddubs_epi16(aw, _mm256_sign_epi8(x, w));
6411                _mm256_cvtepi32_ps(_mm256_madd_epi16(p16, ones))
6412            };
6413            f0 = _mm256_fmadd_ps(dot(xs[0]), sv, f0);
6414            f1 = _mm256_fmadd_ps(dot(xs[1]), sv, f1);
6415            f2 = _mm256_fmadd_ps(dot(xs[2]), sv, f2);
6416            f3 = _mm256_fmadd_ps(dot(xs[3]), sv, f3);
6417        }
6418        [
6419            hsum256_ps(f0),
6420            hsum256_ps(f1),
6421            hsum256_ps(f2),
6422            hsum256_ps(f3),
6423        ]
6424    }
6425}
6426
6427/// Horizontal sum of eight f32 lanes — the one cross-lane reduction the
6428/// blocked kernels pay, once per row instead of once per group.
6429#[cfg(target_arch = "x86_64")]
6430#[target_feature(enable = "avx2")]
6431#[inline]
6432unsafe fn hsum256_ps(v: core::arch::x86_64::__m256) -> f32 {
6433    // SAFETY: pure register arithmetic on the caller's vector.
6434    unsafe {
6435        use core::arch::x86_64::*;
6436        let hi = _mm256_extractf128_ps::<1>(v);
6437        let s = _mm_add_ps(_mm256_castps256_ps128(v), hi);
6438        let s = _mm_add_ps(s, _mm_movehl_ps(s, s));
6439        let s = _mm_add_ss(s, _mm_shuffle_ps::<0x55>(s, s));
6440        _mm_cvtss_f32(s)
6441    }
6442}
6443
6444/// VNNI twin of `dot_q4t_row_1x4_avx2` (see `dpbusd_hsum`).
6445#[cfg(target_arch = "x86_64")]
6446#[target_feature(enable = "avx2,fma,avx512f,avx512bw,avx512vl,avx512vnni")]
6447unsafe fn dot_q4t_row_1x4_vnni(bytes: &[u8], r: usize, gpr: usize, xs: [&[i8]; 4]) -> [f32; 4] {
6448    // SAFETY: callers uphold the 18B-tile and xq-length contracts.
6449    unsafe {
6450        use core::arch::x86_64::*;
6451        let lomask = _mm_set1_epi8(0x0F);
6452        let eight = _mm256_set1_epi8(8);
6453        // Same shape as the AVX2 twin: accumulate in f32 vectors and pay
6454        // one cross-lane reduction per row, not per (group, activation).
6455        let mut f0 = _mm256_setzero_ps();
6456        let mut f1 = _mm256_setzero_ps();
6457        let mut f2 = _mm256_setzero_ps();
6458        let mut f3 = _mm256_setzero_ps();
6459        for gi in 0..gpr {
6460            let t = bytes.as_ptr().add((r * gpr + gi) * Q4_TILE);
6461            let s = f16_to_f32(u16::from_le_bytes([*t, *t.add(1)]));
6462            let sv = _mm256_set1_ps(s);
6463            let bb = _mm_loadu_si128(t.add(2) as *const __m128i);
6464            let lo = _mm_and_si128(bb, lomask);
6465            let hi = _mm_and_si128(_mm_srli_epi16::<4>(bb), lomask);
6466            let w = _mm256_sub_epi8(
6467                _mm256_set_m128i(_mm_unpackhi_epi8(lo, hi), _mm_unpacklo_epi8(lo, hi)),
6468                eight,
6469            );
6470            let aw = _mm256_abs_epi8(w);
6471            let off = gi * GROUP_SIZE;
6472            let dot = |xq: &[i8]| {
6473                let x = _mm256_loadu_si256(xq.as_ptr().add(off) as *const __m256i);
6474                _mm256_cvtepi32_ps(_mm256_dpbusd_epi32(
6475                    _mm256_setzero_si256(),
6476                    aw,
6477                    _mm256_sign_epi8(x, w),
6478                ))
6479            };
6480            f0 = _mm256_fmadd_ps(dot(xs[0]), sv, f0);
6481            f1 = _mm256_fmadd_ps(dot(xs[1]), sv, f1);
6482            f2 = _mm256_fmadd_ps(dot(xs[2]), sv, f2);
6483            f3 = _mm256_fmadd_ps(dot(xs[3]), sv, f3);
6484        }
6485        let acc = [
6486            hsum256_ps(f0),
6487            hsum256_ps(f1),
6488            hsum256_ps(f2),
6489            hsum256_ps(f3),
6490        ];
6491        acc
6492    }
6493}
6494
6495/// ARM twin of `dot_q4t_row_1x4_avx2`: one nibble unpack per group
6496/// serves FOUR activation streams. Per stream the group order and f32
6497/// accumulation match `dot_q4t_row_sdot` exactly — batch == matvec
6498/// bit-for-bit.
6499#[cfg(target_arch = "aarch64")]
6500#[target_feature(enable = "neon,dotprod")]
6501unsafe fn dot_q4t_row_1x4_sdot(bytes: &[u8], r: usize, gpr: usize, xs: [&[i8]; 4]) -> [f32; 4] {
6502    // SAFETY: callers uphold the 18B-tile and xq-length contracts.
6503    unsafe {
6504        use core::arch::aarch64::*;
6505        use core::arch::asm;
6506        let lomask = vdupq_n_u8(0x0F);
6507        let eight = vdupq_n_s8(8);
6508        let mut acc = [0f32; 4];
6509        for gi in 0..gpr {
6510            let t = bytes.as_ptr().add((r * gpr + gi) * Q4_TILE);
6511            let s = f16_to_f32(u16::from_le_bytes([*t, *t.add(1)]));
6512            let b = vld1q_u8(t.add(2));
6513            let lo = vandq_u8(b, lomask);
6514            let hi = vshrq_n_u8::<4>(b);
6515            let e0 = vsubq_s8(vreinterpretq_s8_u8(vzip1q_u8(lo, hi)), eight);
6516            let e1 = vsubq_s8(vreinterpretq_s8_u8(vzip2q_u8(lo, hi)), eight);
6517            for (k, xq) in xs.iter().enumerate() {
6518                let x0 = vld1q_s8(xq.as_ptr().add(gi * GROUP_SIZE));
6519                let x1 = vld1q_s8(xq.as_ptr().add(gi * GROUP_SIZE + 16));
6520                let (mut a0, mut a1) = (vdupq_n_s32(0), vdupq_n_s32(0));
6521                asm!(
6522                    "sdot {a0:v}.4s, {e0:v}.16b, {x0:v}.16b",
6523                    "sdot {a1:v}.4s, {e1:v}.16b, {x1:v}.16b",
6524                    a0 = inout(vreg) a0, a1 = inout(vreg) a1,
6525                    e0 = in(vreg) e0, x0 = in(vreg) x0, e1 = in(vreg) e1, x1 = in(vreg) x1,
6526                    options(pure, nomem, nostack),
6527                );
6528                acc[k] += vaddvq_s32(vaddq_s32(a0, a1)) as f32 * s;
6529            }
6530        }
6531        acc
6532    }
6533}
6534
6535/// Exact-term correction for A8W8 outliers on a tiled row.
6536#[inline]
6537fn q4t_outlier(bytes: &[u8], r: usize, gpr: usize, j: usize) -> (f32, f32) {
6538    let gi = j / GROUP_SIZE;
6539    let k = j % GROUP_SIZE;
6540    let tile = &bytes[(r * gpr + gi) * Q4_TILE..(r * gpr + gi + 1) * Q4_TILE];
6541    let s = f16_to_f32(u16::from_le_bytes([tile[0], tile[1]]));
6542    let byte = tile[2 + k / 2];
6543    let nib = if k & 1 == 0 { byte & 0x0F } else { byte >> 4 };
6544    ((nib as i32 - 8) as f32, s)
6545}
6546
6547/// Exact scalar q4_tiled row (CMF_SDOT=0 contract) — same pairwise
6548/// accumulation shape as `q4_range_f32`.
6549#[inline]
6550fn q4t_row_exact(bytes: &[u8], r: usize, gpr: usize, x: &[f32]) -> f32 {
6551    let mut acc = 0f32;
6552    for gi in 0..gpr {
6553        let tile = &bytes[(r * gpr + gi) * Q4_TILE..(r * gpr + gi + 1) * Q4_TILE];
6554        let s = f16_to_f32(u16::from_le_bytes([tile[0], tile[1]]));
6555        let xg = &x[gi * GROUP_SIZE..(gi + 1) * GROUP_SIZE];
6556        let mut ga = 0f32;
6557        for (k, &b) in tile[2..].iter().enumerate() {
6558            ga += ((b & 0x0F) as f32 - 8.0) * xg[k * 2]
6559                + (((b >> 4) & 0x0F) as f32 - 8.0) * xg[k * 2 + 1];
6560        }
6561        acc += ga * s;
6562    }
6563    acc
6564}
6565
6566/// Split view of a `q4tp` payload. The three planes are resolved once per
6567/// matvec instead of per row — `q4tp_sections` is cheap, but doing it inside
6568/// the row loop would put a division on the hot path for nothing.
6569/// Where row `r` of a coded matrix lives inside its bytes, as up to three
6570/// (offset, length) ranges (a zero length marks an unused one). A q4t row is
6571/// one run of tiles; a q4tp row is its nibbles, its two ladder parameters
6572/// and its scale codes, in three sections of the tensor.
6573fn row_span_offsets(
6574    dtype: TensorDtype,
6575    rows: usize,
6576    cols: usize,
6577    r: usize,
6578) -> Option<[(usize, usize); 3]> {
6579    if r >= rows || cols % GROUP_SIZE != 0 {
6580        return None;
6581    }
6582    let gpr = cols / GROUP_SIZE;
6583    match dtype {
6584        TensorDtype::Q4Tiled => Some([(r * gpr * Q4_TILE, gpr * Q4_TILE), (0, 0), (0, 0)]),
6585        TensorDtype::Q4TiledP => {
6586            let (params, codes, stride) = q4tp_sections(rows, cols);
6587            Some([
6588                (r * gpr * Q4TP_NIB, gpr * Q4TP_NIB),
6589                (params + r * 4, 4),
6590                (codes + r * stride, stride),
6591            ])
6592        }
6593        _ => None,
6594    }
6595}
6596
6597struct Q4tpView<'a> {
6598    nib: &'a [u8],
6599    params: &'a [u8],
6600    codes: &'a [u8],
6601    stride: usize,
6602    /// q2tp reads the ladder with rung 0 = exact zero.
6603    zero_rung: bool,
6604}
6605
6606impl<'a> Q4tpView<'a> {
6607    fn new(bytes: &'a [u8], rows: usize, cols: usize) -> Self {
6608        let (params_off, codes_off, stride) = q4tp_sections(rows, cols);
6609        Self {
6610            nib: &bytes[..params_off],
6611            params: &bytes[params_off..codes_off],
6612            codes: &bytes[codes_off..],
6613            stride,
6614            zero_rung: false,
6615        }
6616    }
6617
6618    /// The q2tp view: identical params/codes planes, 8 B weight chunks.
6619    fn new_q2(bytes: &'a [u8], rows: usize, cols: usize) -> Self {
6620        let (params_off, codes_off, stride) = q2tp_sections(rows, cols);
6621        Self {
6622            nib: &bytes[..params_off],
6623            params: &bytes[params_off..codes_off],
6624            codes: &bytes[codes_off..],
6625            stride,
6626            zero_rung: true,
6627        }
6628    }
6629
6630    /// Expand row `r`'s per-tile scales into `out` (length `gpr`).
6631    ///
6632    /// Doing this once per row — rather than decoding a 5-bit code inside the
6633    /// tile loop — is what makes the format free at runtime. Random access to
6634    /// a packed 5-bit field costs a division, two bounds checks and a branch;
6635    /// the tile's actual work is two `sdot`s, so per-tile decoding dominated
6636    /// the kernel and cost 5x (measured: 1.4 vs 6.9 tok/s on Nanbeige-3B).
6637    /// Walking the plane sequentially with a bit accumulator is ~3 ops.
6638    /// Eight 5-bit codes are exactly five bytes, so a whole group of
6639    /// eight decodes from one little-endian word at fixed shifts. The
6640    /// bit-accumulator this replaces carried a data-dependent `while
6641    /// have < 5` refill whose branch sat in the innermost loop of every
6642    /// q4tp row; a decode profile put this function above the dot
6643    /// products it feeds. Same bitstream, same codes — just no branch
6644    /// and eight independent extractions.
6645    /// `avx2_enabled()` and `ladder_4` are compiled only for x86-64, so a
6646    /// plain `cfg!(target_arch = ...)` guard is NOT enough: `cfg!` is a
6647    /// runtime `false` on other targets, yet both arms still get compiled
6648    /// and the x86-only symbols do not exist there at all (aarch64 build:
6649    /// E0425). This associated fn IS a compile-time `cfg` — the whole
6650    /// branch, symbol references included, is dropped on non-x86 targets,
6651    /// and the non-x86 arm falls straight through to the scalar ladder.
6652    #[cfg(target_arch = "x86_64")]
6653    #[inline]
6654    fn ladder_via_avx2(&self) -> bool {
6655        avx2_enabled()
6656    }
6657    #[cfg(not(target_arch = "x86_64"))]
6658    #[inline]
6659    fn ladder_via_avx2(&self) -> bool {
6660        false
6661    }
6662
6663    #[inline]
6664    fn scales_into(&self, r: usize, gpr: usize, out: &mut [f32]) {
6665        let tab = if self.zero_rung {
6666            q2tp_ladder(self.params, r)
6667        } else if self.ladder_via_avx2() {
6668            // One lane of the 4-wide vector ladder (the other three are
6669            // duplicates) — every q4tp scale in the process then comes
6670            // from the SAME ladder bits, whichever call site decoded it.
6671            // `ladder_via_avx2()` is cfg-gated, so on non-x86 targets
6672            // this arm is never taken and never even compiled with the
6673            // x86-only symbols in scope.
6674            #[cfg(target_arch = "x86_64")]
6675            let tab = {
6676                let p = &self.params[r * 4..r * 4 + 4];
6677                let lo = f16_to_f32(u16::from_le_bytes([p[0], p[1]]));
6678                let st = f16_to_f32(u16::from_le_bytes([p[2], p[3]]));
6679                let mut tabc = [0f32; 128];
6680                unsafe { ladder_4(&[lo; 4], &[st; 4], &mut tabc) };
6681                let mut t = [0f32; 32];
6682                for (g, o) in t.iter_mut().enumerate() {
6683                    *o = tabc[g * 4];
6684                }
6685                t
6686            };
6687            // On a non-x86 target the arm is unreachable (the `cfg!`
6688            // above is false), so it decodes through the scalar ladder —
6689            // the very path this branch would have fallen back to.
6690            #[cfg(not(target_arch = "x86_64"))]
6691            let tab = q4tp_ladder(self.params, r);
6692            tab
6693        } else {
6694            q4tp_ladder(self.params, r)
6695        };
6696        let codes = &self.codes[r * self.stride..(r + 1) * self.stride];
6697        let out = &mut out[..gpr];
6698        let mut chunks = out.chunks_exact_mut(8);
6699        let mut ci = 0usize;
6700        for c in &mut chunks {
6701            let w = u64::from(codes[ci])
6702                | u64::from(codes[ci + 1]) << 8
6703                | u64::from(codes[ci + 2]) << 16
6704                | u64::from(codes[ci + 3]) << 24
6705                | u64::from(codes[ci + 4]) << 32;
6706            for (k, o) in c.iter_mut().enumerate() {
6707                *o = tab[((w >> (5 * k)) & 31) as usize];
6708            }
6709            ci += 5;
6710        }
6711        // Fewer than eight codes left: the shared total accessor, which
6712        // tolerates a 5-bit field whose spill byte is past the stride.
6713        let tail = &codes[ci..];
6714        for (k, o) in chunks.into_remainder().iter_mut().enumerate() {
6715            *o = tab[q4tp_code(tail, k)];
6716        }
6717    }
6718}
6719
6720#[inline]
6721fn dot_q4tp_row_i8(nib: &[u8], r: usize, gpr: usize, xq: &[i8], scales: &[f32]) -> f32 {
6722    #[cfg(target_arch = "aarch64")]
6723    unsafe {
6724        return dot_q4tp_row_sdot(nib, r, gpr, xq, scales);
6725    }
6726    #[cfg(target_arch = "x86_64")]
6727    unsafe {
6728        if vnni_tiles_enabled() {
6729            return dot_q4tp_row_vnni(nib, r, gpr, xq, scales);
6730        }
6731        return dot_q4tp_row_avx2(nib, r, gpr, xq, scales);
6732    }
6733    #[allow(unreachable_code)]
6734    {
6735        let mut acc = 0f32;
6736        for gi in 0..gpr {
6737            let tile = &nib[(r * gpr + gi) * Q4TP_NIB..(r * gpr + gi + 1) * Q4TP_NIB];
6738            let s = scales[gi];
6739            let mut d = 0i32;
6740            for (k, &b) in tile.iter().enumerate() {
6741                d += ((b & 0x0F) as i32 - 8) * xq[gi * GROUP_SIZE + k * 2] as i32
6742                    + (((b >> 4) & 0x0F) as i32 - 8) * xq[gi * GROUP_SIZE + k * 2 + 1] as i32;
6743            }
6744            acc += d as f32 * s;
6745        }
6746        acc
6747    }
6748}
6749
6750/// q4tp twin of `dot_q4t_row_sdot`: identical nibble math, but the tile
6751/// stride is 16 B (no inline scale) and the scale is a ladder lookup.
6752#[cfg(target_arch = "aarch64")]
6753#[target_feature(enable = "neon,dotprod")]
6754unsafe fn dot_q4tp_row_sdot(nib: &[u8], r: usize, gpr: usize, xq: &[i8], scales: &[f32]) -> f32 {
6755    // SAFETY: callers uphold slice-length contracts (16B tile per group,
6756    // xq.len() == gpr·GROUP_SIZE, codes covering gpr 5-bit fields).
6757    unsafe {
6758        use core::arch::aarch64::*;
6759        use core::arch::asm;
6760        let lomask = vdupq_n_u8(0x0F);
6761        let eight = vdupq_n_s8(8);
6762        let mut acc = 0f32;
6763        for gi in 0..gpr {
6764            let t = nib.as_ptr().add((r * gpr + gi) * Q4TP_NIB);
6765            let s = *scales.get_unchecked(gi);
6766            let b = vld1q_u8(t);
6767            let lo = vandq_u8(b, lomask);
6768            let hi = vshrq_n_u8::<4>(b);
6769            let e0 = vsubq_s8(vreinterpretq_s8_u8(vzip1q_u8(lo, hi)), eight);
6770            let e1 = vsubq_s8(vreinterpretq_s8_u8(vzip2q_u8(lo, hi)), eight);
6771            let x0 = vld1q_s8(xq.as_ptr().add(gi * GROUP_SIZE));
6772            let x1 = vld1q_s8(xq.as_ptr().add(gi * GROUP_SIZE + 16));
6773            let (mut a0, mut a1) = (vdupq_n_s32(0), vdupq_n_s32(0));
6774            asm!(
6775                "sdot {a0:v}.4s, {e0:v}.16b, {x0:v}.16b",
6776                "sdot {a1:v}.4s, {e1:v}.16b, {x1:v}.16b",
6777                a0 = inout(vreg) a0, a1 = inout(vreg) a1,
6778                e0 = in(vreg) e0, x0 = in(vreg) x0, e1 = in(vreg) e1, x1 = in(vreg) x1,
6779                options(pure, nomem, nostack),
6780            );
6781            acc += vaddvq_s32(vaddq_s32(a0, a1)) as f32 * s;
6782        }
6783        acc
6784    }
6785}
6786
6787#[cfg(target_arch = "x86_64")]
6788#[target_feature(enable = "avx2")]
6789unsafe fn dot_q4tp_row_avx2(nib: &[u8], r: usize, gpr: usize, xq: &[i8], scales: &[f32]) -> f32 {
6790    // SAFETY: see dot_q4tp_row_sdot.
6791    unsafe {
6792        use core::arch::x86_64::*;
6793        let lomask = _mm_set1_epi8(0x0F);
6794        let eight = _mm256_set1_epi8(8);
6795        let ones = _mm256_set1_epi16(1);
6796        let mut acc = 0f32;
6797        for gi in 0..gpr {
6798            let t = nib.as_ptr().add((r * gpr + gi) * Q4TP_NIB);
6799            let s = *scales.get_unchecked(gi);
6800            let b = _mm_loadu_si128(t as *const __m128i);
6801            let lo = _mm_and_si128(b, lomask);
6802            let hi = _mm_and_si128(_mm_srli_epi16::<4>(b), lomask);
6803            let w = _mm256_sub_epi8(
6804                _mm256_set_m128i(_mm_unpackhi_epi8(lo, hi), _mm_unpacklo_epi8(lo, hi)),
6805                eight,
6806            );
6807            let x = _mm256_loadu_si256(xq.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
6808            let p16 = _mm256_maddubs_epi16(_mm256_abs_epi8(w), _mm256_sign_epi8(x, w));
6809            let d = _mm256_madd_epi16(p16, ones);
6810            let hi128 = _mm256_extracti128_si256::<1>(d);
6811            let s128 = _mm_add_epi32(_mm256_castsi256_si128(d), hi128);
6812            let s64 = _mm_add_epi32(s128, _mm_srli_si128::<8>(s128));
6813            let s32 = _mm_add_epi32(s64, _mm_srli_si128::<4>(s64));
6814            acc += _mm_cvtsi128_si32(s32) as f32 * s;
6815        }
6816        acc
6817    }
6818}
6819
6820/// VNNI twin of `dot_q4tp_row_avx2` (see `dot_q4t_row_vnni` for why the
6821/// 256-bit VL encoding is the one to use here).
6822#[cfg(target_arch = "x86_64")]
6823#[target_feature(enable = "avx2,avx512f,avx512bw,avx512vl,avx512vnni")]
6824unsafe fn dot_q4tp_row_vnni(nib: &[u8], r: usize, gpr: usize, xq: &[i8], scales: &[f32]) -> f32 {
6825    // SAFETY: see dot_q4tp_row_sdot.
6826    unsafe {
6827        use core::arch::x86_64::*;
6828        let lomask = _mm_set1_epi8(0x0F);
6829        let eight = _mm256_set1_epi8(8);
6830        let mut acc = 0f32;
6831        for gi in 0..gpr {
6832            let t = nib.as_ptr().add((r * gpr + gi) * Q4TP_NIB);
6833            let s = *scales.get_unchecked(gi);
6834            let b = _mm_loadu_si128(t as *const __m128i);
6835            let lo = _mm_and_si128(b, lomask);
6836            let hi = _mm_and_si128(_mm_srli_epi16::<4>(b), lomask);
6837            let w = _mm256_sub_epi8(
6838                _mm256_set_m128i(_mm_unpackhi_epi8(lo, hi), _mm_unpacklo_epi8(lo, hi)),
6839                eight,
6840            );
6841            let x = _mm256_loadu_si256(xq.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
6842            acc += dpbusd_hsum(_mm256_abs_epi8(w), _mm256_sign_epi8(x, w)) as f32 * s;
6843        }
6844        acc
6845    }
6846}
6847
6848/// `2^x` for a 4-lane vector (range-reduced degree-6 polynomial).
6849/// ≤1 ulp vs libm `exp2f` — f32's own precision rounds the polynomial
6850/// home. Used only by [`q4tp_scales_lanes`]; see the ladder note there.
6851///
6852/// # Safety
6853/// AVX2.
6854#[cfg(target_arch = "x86_64")]
6855#[target_feature(enable = "avx2")]
6856#[inline]
6857unsafe fn exp2_128(x: core::arch::x86_64::__m128) -> core::arch::x86_64::__m128 {
6858    unsafe {
6859        use core::arch::x86_64::*;
6860        // floor via trunc with a below-integer correction.
6861        let tr = _mm_cvttps_epi32(x);
6862        // Compare against cvt(tr), NOT a bit-cast: the bit pattern of a
6863        // negative i32 is a NaN and cmplt against it is always false.
6864        let below = _mm_and_si128(
6865            _mm_castps_si128(_mm_cmplt_ps(x, _mm_cvtepi32_ps(tr))),
6866            _mm_set1_epi32(1),
6867        );
6868        let n = _mm_sub_epi32(tr, below); // floor(x)
6869        let r = _mm_sub_ps(x, _mm_cvtepi32_ps(n)); // x - floor(x) ∈ [0,1)
6870        // 2^r = exp(r·ln2) ≈ Σ aₖrᵏ, aₖ = ln2ᵏ/k!, k = 1..9 (Horner).
6871        // At r ∈ [0,1) the a₁₀ term is 7.1e-9 — below f32's own ulp.
6872        // The coefficients are carried at full decimal precision on
6873        // purpose: truncating them to an f32 spelling (what
6874        // `excessive_precision` suggests) would round the constants before
6875        // they reach the AVX registers. `approx_constant` fires on a₁ =
6876        // LN_2, but the table must stay internally consistent, so both
6877        // lints are allowed for this table only.
6878        #[allow(clippy::excessive_precision, clippy::approx_constant)]
6879        let a = [
6880            6.931_471_805_599_453e-1,
6881            2.402_265_069_591_007e-1,
6882            5.550_410_866_482_158e-2,
6883            9.618_129_107_628_477e-3,
6884            1.333_355_814_642_844e-3,
6885            1.540_353_039_338_161e-4,
6886            1.525_273_380_405_984e-5,
6887            1.321_548_679_014_431e-6,
6888            1.017_808_600_923_969_6e-7,
6889        ];
6890        let mut p = _mm_set1_ps(a[8]);
6891        for &c in a[..8].iter().rev() {
6892            p = _mm_add_ps(_mm_mul_ps(p, r), _mm_set1_ps(c));
6893        }
6894        p = _mm_add_ps(_mm_mul_ps(p, r), _mm_set1_ps(1.0));
6895        // Combine: p ∈ [1,2) carries the mantissa; n the exponent.
6896        // Underflow (n < −126) → 0; our args are f16-derived, so this
6897        // only matters for pathological rows.
6898        // bits(p) already carries exponent 127; adding n<<23 (mod 2^32,
6899        // correct for negative n too) retargets it to 127+n.
6900        let ncl = _mm_min_epi32(
6901            _mm_max_epi32(n, _mm_set1_epi32(-126)),
6902            _mm_set1_epi32(127),
6903        );
6904        let mut bits = _mm_add_epi32(_mm_castps_si128(p), _mm_slli_epi32(ncl, 23));
6905        let over = _mm_cmpgt_epi32(n, _mm_set1_epi32(127));
6906        bits = _mm_or_si128(
6907            _mm_andnot_si128(over, bits),
6908            _mm_and_si128(over, _mm_set1_epi32(0x007F_8000)),
6909        );
6910        let zero = _mm_cmplt_ps(x, _mm_set1_ps(-149.0));
6911        _mm_andnot_ps(zero, _mm_castsi128_ps(bits))
6912    }
6913}
6914
6915/// Horizontal helper: the four lanes of `v` as `[f32; 4]`.
6916#[cfg(target_arch = "x86_64")]
6917#[inline]
6918unsafe fn lanes4(v: core::arch::x86_64::__m128) -> [f32; 4] {
6919    use core::arch::x86_64::*;
6920    unsafe {
6921        [
6922            _mm_cvtss_f32(v),
6923            _mm_cvtss_f32(_mm_shuffle_ps(v, v, 0x55)),
6924            _mm_cvtss_f32(_mm_shuffle_ps(v, v, 0xAA)),
6925            _mm_cvtss_f32(_mm_shuffle_ps(v, v, 0xFF)),
6926        ]
6927    }
6928}
6929
6930/// FOUR rows' 32-run q4tp ladders at once into `[group * 4 + lane]`.
6931/// The chain is `t = exp2(lo); t *= exp2(st)` — per lane this is the
6932/// scalar `q4tp_ladder` recurrence run as `vmulps`, bit-identical; only
6933/// `exp2` is replaced (≤1 ulp, see [`exp2_128`]).
6934///
6935/// # Safety
6936/// AVX2.
6937#[cfg(target_arch = "x86_64")]
6938#[target_feature(enable = "avx2")]
6939#[inline]
6940unsafe fn ladder_4(lo4: &[f32; 4], st4: &[f32; 4], tabc: &mut [f32; 128]) {
6941    unsafe {
6942        use core::arch::x86_64::*;
6943        let ratio = exp2_128(_mm_loadu_ps(st4.as_ptr()));
6944        let mut t = exp2_128(_mm_loadu_ps(lo4.as_ptr()));
6945        tabc[0..4].copy_from_slice(&lanes4(t));
6946        for c in 1..32 {
6947            t = _mm_mul_ps(t, ratio);
6948            tabc[c * 4..c * 4 + 4].copy_from_slice(&lanes4(t));
6949        }
6950    }
6951}
6952
6953/// Decode FOUR rows' q4tp group scales at once. The scalar
6954/// [`Q4tpView::scales_into`] costs ~364 cycles a row — two libm `exp2`
6955/// calls plus the 31-step serial `t *= ratio` ladder chain — and the
6956/// ladder is 17 % of every decode token. Here the chains run as one
6957/// 4-lane vector: `t[c] = t[c-1] * ratio` is `vmulps`, bit-identical to
6958/// the scalar f32 chain (and to `q4tp_ladder`'s definition), so the only
6959/// bit change is `exp2` (≤1 ulp, see [`exp2_128`]); the dequant reference
6960/// shares this function. Output layout is `[row][group]`.
6961///
6962/// Only for `Q4TiledP` views (`!zero_rung`); rows need not be
6963/// contiguous. Falls back per incomplete tail chunk.
6964///
6965/// # Safety
6966/// AVX2; `out` must hold `rows.len() * gpr` floats.
6967#[cfg(target_arch = "x86_64")]
6968#[target_feature(enable = "avx2")]
6969unsafe fn q4tp_scales_lanes(
6970    vs: &[&Q4tpView<'_>],
6971    rows: &[usize],
6972    gpr: usize,
6973    out: &mut [f32],
6974) {
6975    use core::arch::x86_64::*;
6976    debug_assert_eq!(vs.len(), rows.len());
6977    debug_assert!(out.len() >= rows.len() * gpr);
6978    let mut done = 0usize;
6979    for (ci, chunk) in rows.chunks(4).enumerate() {
6980        let vchunk = &vs[ci * 4..ci * 4 + chunk.len()];
6981        if chunk.len() < 4 || vchunk.iter().any(|v| v.zero_rung) {
6982            for (l, &r) in chunk.iter().enumerate() {
6983                vchunk[l].scales_into(r, gpr, &mut out[(done + l) * gpr..(done + l + 1) * gpr]);
6984            }
6985            done += chunk.len();
6986            continue;
6987        }
6988        let (r0, r1, r2, r3) = (chunk[0], chunk[1], chunk[2], chunk[3]);
6989        let v0 = vchunk[0];
6990        let v1 = vchunk[1];
6991        let v2 = vchunk[2];
6992        let v3 = vchunk[3];
6993        // Gather the four (lo, st) f16 pairs — 4 B per row.
6994        let mut lo = [0f32; 4];
6995        let mut st = [0f32; 4];
6996        for (l, r) in [r0, r1, r2, r3].iter().enumerate() {
6997            let o = *r * 4;
6998            let vv = vchunk[l];
6999            lo[l] = cortiq_core::quant::f16_to_f32(u16::from_le_bytes([
7000                vv.params[o],
7001                vv.params[o + 1],
7002            ]));
7003            st[l] = cortiq_core::quant::f16_to_f32(u16::from_le_bytes([
7004                vv.params[o + 2],
7005                vv.params[o + 3],
7006            ]));
7007        }
7008        let lo_v = _mm_loadu_ps(lo.as_ptr());
7009        let st_v = _mm_loadu_ps(st.as_ptr());
7010        let ratio = exp2_128(st_v);
7011        let mut t = exp2_128(lo_v);
7012        // tab layout [group * 4 + lane] — contiguous stores per step.
7013        let mut tabc = [0f32; 32 * 4];
7014        tabc[0..4].copy_from_slice(&[
7015            _mm_cvtss_f32(t),
7016            _mm_cvtss_f32(_mm_shuffle_ps(t, t, 0x55)),
7017            _mm_cvtss_f32(_mm_shuffle_ps(t, t, 0xAA)),
7018            _mm_cvtss_f32(_mm_shuffle_ps(t, t, 0xFF)),
7019        ]);
7020        for c in 1..32 {
7021            t = _mm_mul_ps(t, ratio);
7022            tabc[c * 4..c * 4 + 4].copy_from_slice(&[
7023                _mm_cvtss_f32(t),
7024                _mm_cvtss_f32(_mm_shuffle_ps(t, t, 0x55)),
7025                _mm_cvtss_f32(_mm_shuffle_ps(t, t, 0xAA)),
7026                _mm_cvtss_f32(_mm_shuffle_ps(t, t, 0xFF)),
7027            ]);
7028        }
7029        // Scalar code walks (per row), reading tabc[group * 4 + lane].
7030        let vs4 = [v0, v1, v2, v3];
7031        for (l, &r) in [r0, r1, r2, r3].iter().enumerate() {
7032            let v = vs4[l];
7033            let codes = &v.codes[r * v.stride..(r + 1) * v.stride];
7034            let dst = &mut out[(done + l) * gpr..(done + l + 1) * gpr];
7035            let mut chunks = dst.chunks_exact_mut(8);
7036            let mut ci = 0usize;
7037            for c in &mut chunks {
7038                let w = u64::from(codes[ci])
7039                    | u64::from(codes[ci + 1]) << 8
7040                    | u64::from(codes[ci + 2]) << 16
7041                    | u64::from(codes[ci + 3]) << 24
7042                    | u64::from(codes[ci + 4]) << 32;
7043                for (k, o) in c.iter_mut().enumerate() {
7044                    *o = tabc[(((w >> (5 * k)) & 31) as usize) * 4 + l];
7045                }
7046                ci += 5;
7047            }
7048            let tail = &codes[ci..];
7049            for (k, o) in chunks.into_remainder().iter_mut().enumerate() {
7050                *o = tabc[q4tp_code(tail, k) * 4 + l];
7051            }
7052        }
7053        done += 4;
7054    }
7055}
7056
7057/// Decode-lane count for the q4tp row loops: how many rows one worker
7058/// steps through with independent `acc += d * scale` chains in ONE body.
7059/// The per-group AVX2 dot is a ~17-cycle dependent chain per 32 weights;
7060/// a single row serializes on it, overlapping rows reaches the uop-issue
7061/// bound instead. Each row keeps its own group order, so every output is
7062/// bit-identical to the plain row loop. `CMF_Q4TP_LANES=1` restores it;
7063/// 2/4/8 are the supported lane counts (default 4).
7064fn q4tp_lanes() -> usize {
7065    #[cfg(not(target_arch = "x86_64"))]
7066    {
7067        1
7068    }
7069    #[cfg(target_arch = "x86_64")]
7070    {
7071        static ON: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
7072        *ON.get_or_init(|| {
7073            let n: usize = std::env::var("CMF_Q4TP_LANES")
7074                .ok()
7075                .and_then(|v| v.parse().ok())
7076                .unwrap_or(4);
7077            match n {
7078                1 => 1,
7079                2 => 2,
7080                8 => 8,
7081                _ => 4,
7082            }
7083        })
7084    }
7085}
7086
7087/// One q4tp group tile unpacked to interleaved weights in 0..=16 — the
7088/// raw nibbles, WITHOUT the −8 shift. The correction travels in
7089/// `SplitAct::xg8` instead (each vertical lane subtracts `Σx`, and the
7090/// 8-lane reduction makes that `8·Σx` overall), which lets `vpmaddubsw`
7091/// consume the unsigned codes directly and deletes the per-byte `vpaddb`
7092/// + `vpabsb`/`vpsignb` — two of them port-5 ops in the old row
7093/// kernel's innermost loop.
7094///
7095/// # Safety
7096/// AVX2; `tile` must point at 16 valid weight bytes.
7097#[cfg(target_arch = "x86_64")]
7098#[target_feature(enable = "avx2")]
7099#[inline]
7100unsafe fn q4tp_unpack_w(tile: *const u8) -> core::arch::x86_64::__m256i {
7101    unsafe {
7102        use core::arch::x86_64::*;
7103        let lomask = _mm_set1_epi8(0x0F);
7104        let b = _mm_loadu_si128(tile as *const __m128i);
7105        let lo = _mm_and_si128(b, lomask);
7106        let hi = _mm_and_si128(_mm_srli_epi16::<4>(b), lomask);
7107        _mm256_set_m128i(_mm_unpackhi_epi8(lo, hi), _mm_unpacklo_epi8(lo, hi))
7108    }
7109}
7110
7111/// Σ over 32 columns of `w·x` as i32x8 lane partials: `vpmaddubsw`
7112/// (|w| ≤ 15, |x| ≤ 127 — pair sums ≤ 3810, no saturation) then `vpmaddwd`.
7113/// Exact in any association.
7114///
7115/// # Safety
7116/// AVX2; `xp` must point at 32 valid i8 activation bytes.
7117#[cfg(target_arch = "x86_64")]
7118#[target_feature(enable = "avx2")]
7119#[inline]
7120unsafe fn q4tp_madd_wx(
7121    w: core::arch::x86_64::__m256i,
7122    xp: *const i8,
7123) -> core::arch::x86_64::__m256i {
7124    unsafe {
7125        use core::arch::x86_64::*;
7126        let ones = _mm256_set1_epi16(1);
7127        let x = _mm256_loadu_si256(xp as *const __m256i);
7128        _mm256_madd_epi16(_mm256_maddubs_epi16(w, x), ones)
7129    }
7130}
7131
7132/// THE shared end-of-row reduction of the vertical f32 accumulator.
7133/// Every a8w8 q4tp path — the decode lane drivers and the row-exact
7134/// matmat cells — must reduce through this one function, or the
7135/// matvec↔matmat bitwise parity test breaks.
7136#[cfg(target_arch = "x86_64")]
7137#[target_feature(enable = "avx2")]
7138#[inline]
7139unsafe fn q4tp_hsum256(acc: core::arch::x86_64::__m256) -> f32 {
7140    unsafe {
7141        use core::arch::x86_64::*;
7142        let a = _mm_add_ps(_mm256_castps256_ps128(acc), _mm256_extractf128_ps::<1>(acc));
7143        let b = _mm_add_ps(a, _mm_movehl_ps(a, a));
7144        let c = _mm_add_ss(b, _mm_shuffle_ps(b, b, 0x55));
7145        _mm_cvtss_f32(c)
7146    }
7147}
7148
7149/// The `− 8·Σx` term of a q4tp a8w8 row: `8 · Σ_g Σx_g · scale_g`, an f32
7150/// dot over the groups. Every vertical-cell path subtracts it after its
7151/// horizontal sum through this one function, so their bits agree.
7152#[cfg(target_arch = "x86_64")]
7153#[inline]
7154fn q4tp_xg8_corr(xg8: &[f32], sc: &[f32]) -> f32 {
7155    let n = sc.len().min(xg8.len());
7156    8.0 * crate::attention::dot_f32(&xg8[..n], &sc[..n])
7157}
7158
7159/// One (row, activation) cell computed the vertical way: per group,
7160/// `Σ(w+8)·x as f32 · scale` fused into lane-wise f32x8 accumulators, one
7161/// horizontal reduction, then the `8·Σx` term (`q4tp_xg8_corr`). Used by the lane drivers' tails
7162/// and by the row-exact matmat column loop so both land on identical bits.
7163///
7164/// # Safety
7165/// AVX2; `gpr` groups must be covered by `xq`/`sc`/`xg8`.
7166#[cfg(target_arch = "x86_64")]
7167#[target_feature(enable = "avx2,fma")]
7168#[inline]
7169unsafe fn q4tp_cell_dot_v(
7170    nib: *const u8,
7171    r: usize,
7172    gpr: usize,
7173    xp: *const i8,
7174    sc: *const f32,
7175    xg8: *const f32,
7176) -> f32 {
7177    unsafe {
7178        use core::arch::x86_64::*;
7179        let mut acc = _mm256_setzero_ps();
7180        for gi in 0..gpr {
7181            let w = q4tp_unpack_w(nib.add((r * gpr + gi) * Q4TP_NIB));
7182            let d = q4tp_madd_wx(w, xp.add(gi * GROUP_SIZE));
7183            acc = _mm256_fmadd_ps(_mm256_cvtepi32_ps(d), _mm256_set1_ps(*sc.add(gi)), acc);
7184        }
7185        q4tp_hsum256(acc)
7186            - q4tp_xg8_corr(
7187                std::slice::from_raw_parts(xg8, gpr),
7188                std::slice::from_raw_parts(sc, gpr),
7189            )
7190    }
7191}
7192
7193/// Row `r` of a row-exact q4tp matmat against one activation panel (up to
7194/// four columns at a time): each weight group is unpacked ONCE and fed to
7195/// four independent column accumulators — the cell math of
7196/// [`q4tp_cell_dot_v`], gi-ascending, so every cell equals the decode
7197/// matvec's bits while the columns overlap their latency chains and the
7198/// unpack is shared. This is the AVX2 twin of the avx512-only blocked
7199/// kernel: without it, Broadwell prefill re-decodes every row once per
7200/// column (7 tok/s measured against q8_2f's 24).
7201///
7202/// # Safety
7203/// AVX2 (caller gates on `a8w8_enabled()` + `xg8.len() == gpr`);
7204/// `out` cells for this row are this worker's alone.
7205#[cfg(target_arch = "x86_64")]
7206#[target_feature(enable = "avx2,fma")]
7207unsafe fn q4tp_matmat_row_cols_v(
7208    v: &Q4tpView<'_>,
7209    r: usize,
7210    gpr: usize,
7211    acts: &[SplitAct],
7212    sc: &[f32],
7213    abase: usize,
7214    rows: usize,
7215    out: SendMut,
7216) {
7217    use core::arch::x86_64::*;
7218    debug_assert_eq!(sc.len(), gpr);
7219    let n = acts.len();
7220    let mut bi = 0usize;
7221    while bi + 4 <= n {
7222        let a: [&SplitAct; 4] = [&acts[bi], &acts[bi + 1], &acts[bi + 2], &acts[bi + 3]];
7223        let mut accs = [_mm256_setzero_ps(); 4];
7224        for gi in 0..gpr {
7225            let w = q4tp_unpack_w(v.nib.as_ptr().add((r * gpr + gi) * Q4TP_NIB));
7226            let sb = _mm256_set1_ps(*sc.get_unchecked(gi));
7227            for (k, act) in a.iter().enumerate() {
7228                let xp = act.xq.as_ptr().add(gi * GROUP_SIZE);
7229                let d = q4tp_madd_wx(w, xp);
7230                accs[k] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(d), sb, accs[k]);
7231            }
7232        }
7233        for k in 0..4 {
7234            let act = a[k];
7235            let mut acc = (q4tp_hsum256(accs[k]) - q4tp_xg8_corr(&act.xg8, sc)) * act.sx;
7236            for &(j, xv) in &act.outliers {
7237                let (w, s) = q4tp_outlier(v.nib, r, gpr, j, sc);
7238                acc += w * s * xv;
7239            }
7240            // SAFETY: disjoint (bi, r) cells per worker.
7241            unsafe { *out.at((abase + bi + k) * rows + r) = acc };
7242        }
7243        bi += 4;
7244    }
7245    // Remainder columns (1..=3): one vertical cell each.
7246    while bi < n {
7247        let act = &acts[bi];
7248        let mut acc = q4tp_cell_dot_v(
7249            v.nib.as_ptr(),
7250            r,
7251            gpr,
7252            act.xq.as_ptr(),
7253            sc.as_ptr(),
7254            act.xg8.as_ptr(),
7255        ) * act.sx;
7256        for &(j, xv) in &act.outliers {
7257            let (w, s) = q4tp_outlier(v.nib, r, gpr, j, sc);
7258            acc += w * s * xv;
7259        }
7260        // SAFETY: disjoint (bi, r) cells per worker.
7261        unsafe { *out.at((abase + bi) * rows + r) = acc };
7262        bi += 1;
7263    }
7264}
7265
7266/// Columns per activation panel of the q4tp batch: `CMF_Q4TP_PANEL`, else
7267/// 256 — and on x86-64 as many as fill half the core's L2 (`cols` int8
7268/// bytes a column), a multiple of four from 8 to 256. A panel of 256
7269/// columns of a 2560-wide row is 655 KB: on a 512 KB L2 (Zen 1/2) every
7270/// weight row streamed the whole panel from L3 again.
7271fn q4tp_panel_cols(cols: usize) -> usize {
7272    static ENV: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
7273    if let Some(v) = *ENV.get_or_init(|| {
7274        std::env::var("CMF_Q4TP_PANEL")
7275            .ok()
7276            .and_then(|v| v.parse().ok())
7277            .filter(|v: &usize| *v > 0)
7278    }) {
7279        return v;
7280    }
7281    #[cfg(target_arch = "x86_64")]
7282    {
7283        ((l2_bytes() / 2) / cols.max(1)).clamp(8, 256) & !3
7284    }
7285    #[cfg(not(target_arch = "x86_64"))]
7286    {
7287        let _ = cols;
7288        256
7289    }
7290}
7291
7292/// The per-core L2 size (Linux sysfs; 1 MB when unknown).
7293#[cfg(target_arch = "x86_64")]
7294fn l2_bytes() -> usize {
7295    static L2: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
7296    *L2.get_or_init(|| {
7297        let s = std::fs::read_to_string("/sys/devices/system/cpu/cpu0/cache/index2/size").unwrap_or_default();
7298        let s = s.trim();
7299        let (num, mul) = match s.strip_suffix('K') {
7300            Some(n) => (n, 1024),
7301            None => match s.strip_suffix('M') {
7302                Some(n) => (n, 1024 * 1024),
7303                None => (s, 1),
7304            },
7305        };
7306        num.parse::<usize>().ok().map(|n| n * mul).filter(|&b| b >= 64 * 1024).unwrap_or(1 << 20)
7307    })
7308}
7309
7310/// `CMF_Q4TP_FMA=0` keeps the row-exact vertical cell
7311/// (`q4tp_matmat_row_cols_v`) for a batch on an AVX2 CPU (A/B only).
7312#[cfg(target_arch = "x86_64")]
7313fn q4tp_fma_x86() -> bool {
7314    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
7315    *ON.get_or_init(|| {
7316        std::is_x86_feature_detected!("avx2")
7317            && std::is_x86_feature_detected!("fma")
7318            && std::env::var("CMF_Q4TP_FMA").map(|v| v != "0").unwrap_or(true)
7319    })
7320}
7321
7322/// Two weight rows (`r`, `r + 1`) against a panel of activation columns,
7323/// the tuned AVX2 shape for a batch that need not be row-exact: four
7324/// columns at a time, so each group's tile is unpacked once for four
7325/// columns and each column's 32 bytes are loaded once for two rows (eight
7326/// lane accumulators, the register file's worth). Per group and cell the
7327/// loop is `vpmaddubsw`, `vpmaddwd`, a convert and one FMA by the group
7328/// scale — the vertical cell's `− 8·Σx` correction leaves the loop and is
7329/// taken once per cell as `8 · Σ_g Σx_g · scale_g` (an f32 dot over the
7330/// groups). The same products as the vertical cell, summed in another
7331/// order: tolerance-class against the matvec, like the ARM tuned shape.
7332/// Columns past the last group of four take the vertical cell, row by row.
7333///
7334/// # Safety
7335/// AVX2 and FMA (`q4tp_fma_x86`); every column carries `xg8` of `gpr`
7336/// groups; `out` cells (`(abase + k)·rows + r`, `r + 1`) disjoint per worker.
7337#[cfg(target_arch = "x86_64")]
7338#[target_feature(enable = "avx2,fma")]
7339#[allow(clippy::too_many_arguments)]
7340unsafe fn q4tp_matmat_2rows_fma(
7341    v: &Q4tpView<'_>,
7342    r: usize,
7343    gpr: usize,
7344    acts: &[SplitAct],
7345    sc0: &[f32],
7346    sc1: &[f32],
7347    abase: usize,
7348    rows: usize,
7349    out: SendMut,
7350) {
7351    use core::arch::x86_64::*;
7352    debug_assert!(sc0.len() == gpr && sc1.len() == gpr);
7353    let n = acts.len();
7354    let nib = v.nib.as_ptr();
7355    let ones = _mm256_set1_epi16(1);
7356    let mut bi = 0usize;
7357    unsafe {
7358        while bi + 4 <= n {
7359            let a: [&SplitAct; 4] = [&acts[bi], &acts[bi + 1], &acts[bi + 2], &acts[bi + 3]];
7360            let xp: [*const i8; 4] = [
7361                a[0].xq.as_ptr(),
7362                a[1].xq.as_ptr(),
7363                a[2].xq.as_ptr(),
7364                a[3].xq.as_ptr(),
7365            ];
7366            let mut c0 = [_mm256_setzero_ps(); 4];
7367            let mut c1 = [_mm256_setzero_ps(); 4];
7368            for gi in 0..gpr {
7369                let w0 = q4tp_unpack_w(nib.add((r * gpr + gi) * Q4TP_NIB));
7370                let w1 = q4tp_unpack_w(nib.add(((r + 1) * gpr + gi) * Q4TP_NIB));
7371                let s0 = _mm256_set1_ps(*sc0.get_unchecked(gi));
7372                let s1 = _mm256_set1_ps(*sc1.get_unchecked(gi));
7373                for k in 0..4 {
7374                    let x = _mm256_loadu_si256(xp[k].add(gi * GROUP_SIZE) as *const __m256i);
7375                    let d0 = _mm256_madd_epi16(_mm256_maddubs_epi16(w0, x), ones);
7376                    let d1 = _mm256_madd_epi16(_mm256_maddubs_epi16(w1, x), ones);
7377                    c0[k] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(d0), s0, c0[k]);
7378                    c1[k] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(d1), s1, c1[k]);
7379                }
7380            }
7381            for (row, cr, scr) in [(r, &c0, sc0), (r + 1, &c1, sc1)] {
7382                for k in 0..4 {
7383                    let act = a[k];
7384                    let mut acc = (q4tp_hsum256(cr[k]) - q4tp_xg8_corr(&act.xg8, scr)) * act.sx;
7385                    for &(j, xv) in &act.outliers {
7386                        let (w, s) = q4tp_outlier(v.nib, row, gpr, j, scr);
7387                        acc += w * s * xv;
7388                    }
7389                    // SAFETY: disjoint (bi, r) cells per worker.
7390                    *out.at((abase + bi + k) * rows + row) = acc;
7391                }
7392            }
7393            bi += 4;
7394        }
7395        if bi < n {
7396            q4tp_matmat_row_cols_v(v, r, gpr, &acts[bi..], sc0, abase + bi, rows, out);
7397            q4tp_matmat_row_cols_v(v, r + 1, gpr, &acts[bi..], sc1, abase + bi, rows, out);
7398        }
7399    }
7400}
7401
7402/// Rows `start..end` of a single-output q4tp a8w8 matvec, `L` independent
7403/// accumulator chains wide. Per row: scales decoded once, groups stepped
7404/// in ascending `gi` with `acc += d as f32 * scale` (the exact plain-row
7405/// order), then the `* sx` scale and the outlier corrections in list
7406/// order — the plain row loop's arithmetic, line for line.
7407///
7408/// # Safety
7409/// AVX2 (callers gate on `a8w8_enabled()`); `out` disjoint per row.
7410#[cfg(target_arch = "x86_64")]
7411#[target_feature(enable = "avx2,fma")]
7412unsafe fn q4tp_matvec_lanes<const L: usize>(
7413    v: &Q4tpView<'_>,
7414    start: usize,
7415    end: usize,
7416    gpr: usize,
7417    xq: &[i8],
7418    xg8: &[f32],
7419    sx: f32,
7420    outliers: &[(usize, f32)],
7421    sc: &mut [f32],
7422    out: SendMut,
7423) {
7424    use core::arch::x86_64::*;
7425    debug_assert!(L >= 2 && sc.len() >= L * gpr && xg8.len() == gpr);
7426    crate::cpuprof::count_lane_rows((end - start) as u64);
7427    let mut base = start;
7428    while base + L <= end {
7429        let _t0 = crate::cpuprof::time(crate::cpuprof::Slot::GuScales);
7430        let mut rows = [0usize; L];
7431        for l in 0..L {
7432            rows[l] = base + l;
7433        }
7434        let v4: [&Q4tpView; L] = [v; L];
7435        q4tp_scales_lanes(&v4, &rows, gpr, sc);
7436        drop(_t0);
7437        let _t1 = crate::cpuprof::time(crate::cpuprof::Slot::GuDots);
7438        let mut accs = [_mm256_setzero_ps(); L];
7439        for gi in 0..gpr {
7440            let xp = xq.as_ptr().add(gi * GROUP_SIZE);
7441            for l in 0..L {
7442                let w = q4tp_unpack_w(v.nib.as_ptr().add((rows[l] * gpr + gi) * Q4TP_NIB));
7443                let d = q4tp_madd_wx(w, xp);
7444                let sb = _mm256_set1_ps(*sc.get_unchecked(l * gpr + gi));
7445                accs[l] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(d), sb, accs[l]);
7446            }
7447        }
7448        drop(_t1);
7449        let _t2 = crate::cpuprof::time(crate::cpuprof::Slot::GuPost);
7450        for l in 0..L {
7451            let r = rows[l];
7452            let scl = &sc[l * gpr..(l + 1) * gpr];
7453            let mut acc = (q4tp_hsum256(accs[l]) - q4tp_xg8_corr(xg8, scl)) * sx;
7454            for &(j, xv) in outliers {
7455                let (w, s) = q4tp_outlier(v.nib, r, gpr, j, scl);
7456                acc += w * s * xv;
7457            }
7458            // SAFETY: one lane owns each row.
7459            unsafe { *out.at(r) = acc };
7460        }
7461        drop(_t2);
7462        base += L;
7463    }
7464    // Partial lane batch (and any tail): one vertical cell per row —
7465    // the same reduction shape as the lanes above and as the row-exact
7466    // matmat, so bits agree across every path.
7467    for r in base..end {
7468        let scl = &mut sc[..gpr];
7469        v.scales_into(r, gpr, scl);
7470        let scl: &[f32] = scl;
7471        let mut acc = q4tp_cell_dot_v(v.nib.as_ptr(), r, gpr, xq.as_ptr(), scl.as_ptr(), xg8.as_ptr())
7472            * sx;
7473        for &(j, xv) in outliers {
7474            let (w, s) = q4tp_outlier(v.nib, r, gpr, j, scl);
7475            acc += w * s * xv;
7476        }
7477        // SAFETY: disjoint row ranges per worker.
7478        unsafe { *out.at(r) = acc };
7479    }
7480}
7481
7482/// Rows `start..end` of the fused SwiGLU gate+up q4tp arm, `L` chains
7483/// wide: both projections' scales decoded per lane, both group loops
7484/// stepped in the plain arm's per-row order, then `silu_mul_limited`
7485/// over the outlier-corrected pair — bit-identical to the plain arm.
7486///
7487/// # Safety
7488/// AVX2 (callers gate on `a8w8_enabled()`); `out` disjoint per row.
7489#[cfg(target_arch = "x86_64")]
7490#[target_feature(enable = "avx2,fma")]
7491unsafe fn q4tp_gateup_lanes<const L: usize>(
7492    gv: &Q4tpView<'_>,
7493    uv: &Q4tpView<'_>,
7494    start: usize,
7495    end: usize,
7496    gpr: usize,
7497    xq: &[i8],
7498    xg8: &[f32],
7499    sx: f32,
7500    limit: f32,
7501    outliers: &[(usize, f32)],
7502    gsc: &mut [f32],
7503    usc: &mut [f32],
7504    out: SendMut,
7505) {
7506    use core::arch::x86_64::*;
7507    debug_assert!(
7508        L >= 2 && gsc.len() >= L * gpr && usc.len() >= L * gpr && xg8.len() == gpr
7509    );
7510    crate::cpuprof::count_lane_rows((end - start) as u64);
7511    let mut base = start;
7512    while base + L <= end {
7513        let _t0 = crate::cpuprof::time(crate::cpuprof::Slot::GuScales);
7514        let mut rows = [0usize; L];
7515        for l in 0..L {
7516            rows[l] = base + l;
7517        }
7518        let gv4: [&Q4tpView; L] = [gv; L];
7519        let uv4: [&Q4tpView; L] = [uv; L];
7520        q4tp_scales_lanes(&gv4, &rows, gpr, gsc);
7521        q4tp_scales_lanes(&uv4, &rows, gpr, usc);
7522        drop(_t0);
7523        let _t1 = crate::cpuprof::time(crate::cpuprof::Slot::GuDots);
7524        let mut ag = [_mm256_setzero_ps(); L];
7525        let mut au = [_mm256_setzero_ps(); L];
7526        for gi in 0..gpr {
7527            let xp = xq.as_ptr().add(gi * GROUP_SIZE);
7528            for l in 0..L {
7529                let w = q4tp_unpack_w(gv.nib.as_ptr().add((rows[l] * gpr + gi) * Q4TP_NIB));
7530                let d = q4tp_madd_wx(w, xp);
7531                let sb = _mm256_set1_ps(*gsc.get_unchecked(l * gpr + gi));
7532                ag[l] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(d), sb, ag[l]);
7533            }
7534            for l in 0..L {
7535                let w = q4tp_unpack_w(uv.nib.as_ptr().add((rows[l] * gpr + gi) * Q4TP_NIB));
7536                let d = q4tp_madd_wx(w, xp);
7537                let sb = _mm256_set1_ps(*usc.get_unchecked(l * gpr + gi));
7538                au[l] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(d), sb, au[l]);
7539            }
7540        }
7541        drop(_t1);
7542        let _t2 = crate::cpuprof::time(crate::cpuprof::Slot::GuPost);
7543        for l in 0..L {
7544            let r = rows[l];
7545            let gs = &gsc[l * gpr..(l + 1) * gpr];
7546            let us = &usc[l * gpr..(l + 1) * gpr];
7547            let mut g = (q4tp_hsum256(ag[l]) - q4tp_xg8_corr(xg8, gs)) * sx;
7548            let mut u = (q4tp_hsum256(au[l]) - q4tp_xg8_corr(xg8, us)) * sx;
7549            for &(j, xv) in outliers {
7550                let (w, s) = q4tp_outlier(gv.nib, r, gpr, j, gs);
7551                g += w * s * xv;
7552                let (w, s) = q4tp_outlier(uv.nib, r, gpr, j, us);
7553                u += w * s * xv;
7554            }
7555            // SAFETY: one lane owns each row.
7556            unsafe { *out.at(r) = silu_mul_limited(g, u, limit) };
7557        }
7558        drop(_t2);
7559        base += L;
7560    }
7561    // Partial lane batch (and any tail): one vertical cell per stream.
7562    for r in base..end {
7563        let g = &mut gsc[..gpr];
7564        let u = &mut usc[..gpr];
7565        gv.scales_into(r, gpr, g);
7566        uv.scales_into(r, gpr, u);
7567        let (g, u): (&[f32], &[f32]) = (g, u);
7568        let mut gv_ =
7569            q4tp_cell_dot_v(gv.nib.as_ptr(), r, gpr, xq.as_ptr(), g.as_ptr(), xg8.as_ptr()) * sx;
7570        let mut uv_ =
7571            q4tp_cell_dot_v(uv.nib.as_ptr(), r, gpr, xq.as_ptr(), u.as_ptr(), xg8.as_ptr()) * sx;
7572        for &(j, xv) in outliers {
7573            let (w, s) = q4tp_outlier(gv.nib, r, gpr, j, g);
7574            gv_ += w * s * xv;
7575            let (w, s) = q4tp_outlier(uv.nib, r, gpr, j, u);
7576            uv_ += w * s * xv;
7577        }
7578        // SAFETY: disjoint row ranges per worker.
7579        unsafe { *out.at(r) = silu_mul_limited(gv_, uv_, limit) };
7580    }
7581}
7582
7583/// Flat-space sibling of [`q4tp_matvec_lanes`] for `matvec_many`: the
7584/// virtual row space spans several tensors, so each lane resolves its
7585/// (tensor, row) pair through the caller's `locate`, then runs the plain
7586/// per-row math of the fused q4tp arm.
7587///
7588/// # Safety
7589/// AVX2 (callers gate on `a8w8_enabled()`); `outs` disjoint per row.
7590#[cfg(target_arch = "x86_64")]
7591#[target_feature(enable = "avx2,fma")]
7592unsafe fn q4tp_many_lanes<const L: usize>(
7593    views: &[Q4tpView<'_>],
7594    locate: &(dyn Fn(usize) -> (usize, usize)),
7595    start: usize,
7596    end: usize,
7597    gpr: usize,
7598    xq: &[i8],
7599    xg8: &[f32],
7600    sx: f32,
7601    outliers: &[(usize, f32)],
7602    sc: &mut [f32],
7603    outs: &[SendMut],
7604) {
7605    use core::arch::x86_64::*;
7606    debug_assert!(L >= 2 && sc.len() >= L * gpr && xg8.len() == gpr);
7607    crate::cpuprof::count_lane_rows((end - start) as u64);
7608    let mut base = start;
7609    while base + L <= end {
7610        let _t0 = crate::cpuprof::time(crate::cpuprof::Slot::GuScales);
7611        let mut tk = [0usize; L];
7612        let mut rows = [0usize; L];
7613        for l in 0..L {
7614            let (t, r) = locate(base + l);
7615            tk[l] = t;
7616            rows[l] = r;
7617        }
7618        let v4: [&Q4tpView; L] = std::array::from_fn(|l| &views[tk[l]]);
7619        q4tp_scales_lanes(&v4, &rows, gpr, sc);
7620        drop(_t0);
7621        let _t1 = crate::cpuprof::time(crate::cpuprof::Slot::GuDots);
7622        let mut accs = [_mm256_setzero_ps(); L];
7623        for gi in 0..gpr {
7624            let xp = xq.as_ptr().add(gi * GROUP_SIZE);
7625            for l in 0..L {
7626                let w = q4tp_unpack_w(
7627                    views[tk[l]].nib.as_ptr().add((rows[l] * gpr + gi) * Q4TP_NIB),
7628                );
7629                let d = q4tp_madd_wx(w, xp);
7630                let sb = _mm256_set1_ps(*sc.get_unchecked(l * gpr + gi));
7631                accs[l] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(d), sb, accs[l]);
7632            }
7633        }
7634        drop(_t1);
7635        let _t2 = crate::cpuprof::time(crate::cpuprof::Slot::GuPost);
7636        for l in 0..L {
7637            let (t, r) = (tk[l], rows[l]);
7638            let scl = &sc[l * gpr..(l + 1) * gpr];
7639            let mut acc = (q4tp_hsum256(accs[l]) - q4tp_xg8_corr(xg8, scl)) * sx;
7640            for &(j, xv) in outliers {
7641                let (w, s) = q4tp_outlier(views[t].nib, r, gpr, j, scl);
7642                acc += w * s * xv;
7643            }
7644            // SAFETY: one lane owns each (tensor, row) pair.
7645            unsafe { *outs[t].at(r) = acc };
7646        }
7647        drop(_t2);
7648        base += L;
7649    }
7650    // Partial lane batch (and any tail): one vertical cell per row.
7651    for flat in base..end {
7652        let (t, r) = locate(flat);
7653        let v = &views[t];
7654        let scl = &mut sc[..gpr];
7655        v.scales_into(r, gpr, scl);
7656        let scl: &[f32] = scl;
7657        let mut acc =
7658            q4tp_cell_dot_v(v.nib.as_ptr(), r, gpr, xq.as_ptr(), scl.as_ptr(), xg8.as_ptr()) * sx;
7659        for &(j, xv) in outliers {
7660            let (w, s) = q4tp_outlier(v.nib, r, gpr, j, scl);
7661            acc += w * s * xv;
7662        }
7663        // SAFETY: one worker owns each (tensor, row) pair.
7664        unsafe { *outs[t].at(r) = acc };
7665    }
7666}
7667
7668/// Exact scalar q4tp row — the `CMF_SDOT=0` contract, same pairwise
7669/// accumulation shape as `q4t_row_exact`.
7670#[inline]
7671fn q4tp_row_exact(nib: &[u8], r: usize, gpr: usize, x: &[f32], scales: &[f32]) -> f32 {
7672    #[cfg(target_arch = "x86_64")]
7673    if avx2_enabled() {
7674        // Keep the scalar pair/group reduction order, not a vector sum.
7675        return unsafe { q4tp_row_float_avx2(nib, r, gpr, x, scales) };
7676    }
7677    q4tp_row_float_scalar(nib, r, gpr, x, scales)
7678}
7679
7680#[inline]
7681fn q4tp_row_float_scalar(nib: &[u8], r: usize, gpr: usize, x: &[f32], scales: &[f32]) -> f32 {
7682    let mut acc = 0f32;
7683    for gi in 0..gpr {
7684        let tile = &nib[(r * gpr + gi) * Q4TP_NIB..(r * gpr + gi + 1) * Q4TP_NIB];
7685        let s = scales[gi];
7686        let xg = &x[gi * GROUP_SIZE..(gi + 1) * GROUP_SIZE];
7687        let mut ga = 0f32;
7688        for (k, &b) in tile.iter().enumerate() {
7689            ga += ((b & 0x0F) as f32 - 8.0) * xg[k * 2]
7690                + (((b >> 4) & 0x0F) as f32 - 8.0) * xg[k * 2 + 1];
7691        }
7692        acc += ga * s;
7693    }
7694    acc
7695}
7696
7697/// Vectorize unpack, conversion and multiplication, but preserve every
7698/// pair addition and the scalar accumulation order. No activation rounding
7699/// or FMA: bit-identical to the float scalar row, including its group scale.
7700#[cfg(target_arch = "x86_64")]
7701#[target_feature(enable = "avx2")]
7702unsafe fn q4tp_row_float_avx2(nib: &[u8], r: usize, gpr: usize, x: &[f32], scales: &[f32]) -> f32 {
7703    // SAFETY: caller checks AVX2 and provides the same complete 32-element
7704    // groups as the scalar row. Loads/stores are explicitly unaligned.
7705    unsafe {
7706        use core::arch::x86_64::*;
7707        let mask = _mm_set1_epi8(15);
7708        let eight = _mm_set1_epi8(8);
7709        let order = _mm256_setr_epi32(0, 1, 4, 5, 2, 3, 6, 7);
7710        let mut acc = 0.0f32;
7711        for gi in 0..gpr {
7712            let packed = _mm_loadu_si128(nib.as_ptr().add((r * gpr + gi) * Q4TP_NIB).cast());
7713            let lo = _mm_and_si128(packed, mask);
7714            let hi = _mm_and_si128(_mm_srli_epi16::<4>(packed), mask);
7715            let w0 = _mm_sub_epi8(_mm_unpacklo_epi8(lo, hi), eight);
7716            let w1 = _mm_sub_epi8(_mm_unpackhi_epi8(lo, hi), eight);
7717            let xp = x.as_ptr().add(gi * GROUP_SIZE);
7718            let a = _mm256_mul_ps(
7719                _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(w0)),
7720                _mm256_loadu_ps(xp),
7721            );
7722            let b = _mm256_mul_ps(
7723                _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128::<8>(w0))),
7724                _mm256_loadu_ps(xp.add(8)),
7725            );
7726            let c = _mm256_mul_ps(
7727                _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(w1)),
7728                _mm256_loadu_ps(xp.add(16)),
7729            );
7730            let d = _mm256_mul_ps(
7731                _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128::<8>(w1))),
7732                _mm256_loadu_ps(xp.add(24)),
7733            );
7734            let mut pairs = [0.0f32; 16];
7735            _mm256_storeu_ps(
7736                pairs.as_mut_ptr(),
7737                _mm256_permutevar8x32_ps(_mm256_hadd_ps(a, b), order),
7738            );
7739            _mm256_storeu_ps(
7740                pairs.as_mut_ptr().add(8),
7741                _mm256_permutevar8x32_ps(_mm256_hadd_ps(c, d), order),
7742            );
7743            let mut ga = 0.0f32;
7744            for v in pairs {
7745                ga += v;
7746            }
7747            acc += ga * scales[gi];
7748        }
7749        acc
7750    }
7751}
7752
7753/// Single weight of a q4tp tensor — the a8w8 outlier path, which restores
7754/// activation outliers at full precision after the int8 pass.
7755#[inline]
7756fn q4tp_outlier(nib: &[u8], r: usize, gpr: usize, j: usize, scales: &[f32]) -> (f32, f32) {
7757    let (gi, k) = (j / GROUP_SIZE, j % GROUP_SIZE);
7758    let byte = nib[(r * gpr + gi) * Q4TP_NIB + k / 2];
7759    let n = if k & 1 == 0 { byte & 0x0F } else { byte >> 4 };
7760    ((n as i32 - 8) as f32, scales[gi])
7761}
7762
7763/// Fused q4tp matvec (dispatch mirrors `q4t_matvec`).
7764fn q4tp_matvec(
7765    bytes: &[u8],
7766    x: &[f32],
7767    rows: usize,
7768    cols: usize,
7769    out: &mut [f32],
7770    pool: Option<&Pool>,
7771) {
7772    debug_assert_eq!(out.len(), rows);
7773    let gpr = cols / GROUP_SIZE;
7774    let v = Q4tpView::new(bytes, rows, cols);
7775    let out_addr = SendMut(out.as_mut_ptr());
7776    if a8w8_enabled() {
7777        let act = split_act(x);
7778        #[cfg(target_arch = "x86_64")]
7779        let lanes = q4tp_lanes();
7780        let run = |start: usize, end: usize| {
7781            #[cfg(target_arch = "x86_64")]
7782            if lanes > 1 && act.xg8.len() == gpr {
7783                // L independent accumulator chains per worker — the plain
7784                // row body's math, lane-interleaved.
7785                with_krow(gpr * lanes, |sc| {
7786                    // SAFETY: a8w8 implies AVX2; disjoint row ranges.
7787                    unsafe {
7788                        match lanes {
7789                            2 => q4tp_matvec_lanes::<2>(
7790                                &v, start, end, gpr, &act.xq, &act.xg8, act.sx,
7791                                &act.outliers, sc, out_addr,
7792                            ),
7793                            8 => q4tp_matvec_lanes::<8>(
7794                                &v, start, end, gpr, &act.xq, &act.xg8, act.sx,
7795                                &act.outliers, sc, out_addr,
7796                            ),
7797                            _ => q4tp_matvec_lanes::<4>(
7798                                &v, start, end, gpr, &act.xq, &act.xg8, act.sx,
7799                                &act.outliers, sc, out_addr,
7800                            ),
7801                        }
7802                    }
7803                });
7804                return;
7805            }
7806            crate::cpuprof::count_plain_rows((end - start) as u64);
7807            // One scratch row of scales per worker — borrowed, not minted.
7808            with_krow(gpr, |sc| {
7809                for r in start..end {
7810                    v.scales_into(r, gpr, sc);
7811                    let mut acc = dot_q4tp_row_i8(v.nib, r, gpr, &act.xq, sc) * act.sx;
7812                    for &(j, xv) in &act.outliers {
7813                        let (w, s) = q4tp_outlier(v.nib, r, gpr, j, sc);
7814                        acc += w * s * xv;
7815                    }
7816                    // SAFETY: disjoint row ranges per worker.
7817                    unsafe { *out_addr.at(r) = acc }
7818                }
7819            })
7820        };
7821        dispatch_rows(pool, rows, &run);
7822        return;
7823    }
7824    let run = |start: usize, end: usize| {
7825        with_krow(gpr, |sc| {
7826            for r in start..end {
7827                v.scales_into(r, gpr, sc);
7828                // SAFETY: disjoint row ranges per worker.
7829                unsafe { *out_addr.at(r) = q4tp_row_exact(v.nib, r, gpr, x, sc) };
7830            }
7831        })
7832    };
7833    dispatch_rows(pool, rows, &run);
7834}
7835
7836/// Fused two-input q4tp matvec — the SwiGLU gate/up pair. Weights and the
7837/// row ladder are read once and spent on both activation streams.
7838#[allow(clippy::too_many_arguments)]
7839fn q4tp_matvec2(
7840    bytes: &[u8],
7841    x1: &[f32],
7842    x2: &[f32],
7843    rows: usize,
7844    cols: usize,
7845    o1: &mut [f32],
7846    o2: &mut [f32],
7847    pool: Option<&Pool>,
7848) {
7849    let gpr = cols / GROUP_SIZE;
7850    let v = Q4tpView::new(bytes, rows, cols);
7851    let (p1, p2) = (SendMut(o1.as_mut_ptr()), SendMut(o2.as_mut_ptr()));
7852    let run = |start: usize, end: usize| {
7853        let mut sc = vec![0f32; gpr];
7854        for r in start..end {
7855            v.scales_into(r, gpr, &mut sc);
7856            // SAFETY: disjoint row ranges per worker.
7857            unsafe {
7858                *p1.at(r) = q4tp_row_exact(v.nib, r, gpr, x1, &sc);
7859                *p2.at(r) = q4tp_row_exact(v.nib, r, gpr, x2, &sc);
7860            }
7861        }
7862    };
7863    dispatch_rows(pool, rows, &run);
7864}
7865
7866/// One q2tp outlier weight at column `j` of row `r`: the 2-bit code and
7867/// its group scale, mirrored on `q4tp_outlier`.
7868#[inline]
7869fn q2tp_outlier(chunks: &[u8], r: usize, gpr: usize, j: usize, scales: &[f32]) -> (f32, f32) {
7870    let (gi, k) = (j / GROUP_SIZE, j % GROUP_SIZE);
7871    let byte = chunks[(r * gpr + gi) * Q2TP_CHUNK + k / 4];
7872    let c = (byte >> (2 * (k % 4))) & 3;
7873    (c as f32 - 1.5, scales[gi])
7874}
7875
7876#[cfg(target_arch = "x86_64")]
7877const Q2TP_DECODE_U32: [u32; 256] = {
7878    let mut tab = [0u32; 256];
7879    let mut b = 0usize;
7880    while b < 256 {
7881        tab[b] = ((b as u32) & 3)
7882            | ((((b as u32) >> 2) & 3) << 8)
7883            | ((((b as u32) >> 4) & 3) << 16)
7884            | ((((b as u32) >> 6) & 3) << 24);
7885        b += 1;
7886    }
7887    tab
7888};
7889
7890/// Eight packed q2tp bytes against 32 signed activation bytes. `maddubs`
7891/// exactly computes unsigned 2-bit code × signed i8; its pair sums cannot
7892/// saturate (2 × 3 × 127 < i16::MAX), and the second madd widens to i32.
7893#[cfg(target_arch = "x86_64")]
7894#[target_feature(enable = "avx2")]
7895unsafe fn q2tp_code_dot_avx2(ch: &[u8], x: &[i8]) -> i32 {
7896    use core::arch::x86_64::*;
7897    debug_assert!(ch.len() >= Q2TP_CHUNK && x.len() >= GROUP_SIZE);
7898    let codes = _mm256_setr_epi32(
7899        Q2TP_DECODE_U32[ch[0] as usize] as i32,
7900        Q2TP_DECODE_U32[ch[1] as usize] as i32,
7901        Q2TP_DECODE_U32[ch[2] as usize] as i32,
7902        Q2TP_DECODE_U32[ch[3] as usize] as i32,
7903        Q2TP_DECODE_U32[ch[4] as usize] as i32,
7904        Q2TP_DECODE_U32[ch[5] as usize] as i32,
7905        Q2TP_DECODE_U32[ch[6] as usize] as i32,
7906        Q2TP_DECODE_U32[ch[7] as usize] as i32,
7907    );
7908    let xv = unsafe { _mm256_loadu_si256(x.as_ptr().cast()) };
7909    let pair = _mm256_maddubs_epi16(codes, xv);
7910    let quad = _mm256_madd_epi16(pair, _mm256_set1_epi16(1));
7911    let sum128 = _mm_add_epi32(
7912        _mm256_castsi256_si128(quad),
7913        _mm256_extracti128_si256(quad, 1),
7914    );
7915    let sum64 = _mm_hadd_epi32(sum128, sum128);
7916    _mm_cvtsi128_si32(_mm_hadd_epi32(sum64, sum64))
7917}
7918
7919#[cfg(target_arch = "x86_64")]
7920#[inline]
7921fn q2tp_avx2_enabled() -> bool {
7922    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
7923    *ON.get_or_init(|| std::arch::is_x86_feature_detected!("avx2"))
7924}
7925
7926/// Integer dot of one q2tp row against pre-quantized activations:
7927/// Σ_g s_g · (Σ c·xq − 1.5·Σ xq). The half-integer grid (c − 1.5)
7928/// becomes exact integer math through the group sums — the same trick
7929/// every a8w8 kernel in this file rides. The codes decode into a
7930/// 32-byte scratch in natural order and the dot itself is the shared
7931/// SDOT primitive; elsewhere a scalar integer loop.
7932#[inline]
7933fn dot_q2tp_row_i8(
7934    chunks: &[u8],
7935    r: usize,
7936    gpr: usize,
7937    xq: &[i8],
7938    gsum: &[i32],
7939    scales: &[f32],
7940) -> f32 {
7941    let mut acc = 0f32;
7942    let base = r * gpr * Q2TP_CHUNK;
7943    #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
7944    let mut codes = [0i8; GROUP_SIZE];
7945    #[cfg(target_arch = "x86_64")]
7946    // Cache the process-wide AVX2 decision; probing it for every 32-weight
7947    // group adds a branch to the hottest Q2TP row loop while retaining the
7948    // established table-load AVX2 arithmetic (and without coupling this path
7949    // to the separate FMA-gated A8W8 switch).
7950    let avx2 = q2tp_avx2_enabled();
7951    for gi in 0..gpr {
7952        let ch = &chunks[base + gi * Q2TP_CHUNK..base + (gi + 1) * Q2TP_CHUNK];
7953        let xg = &xq[gi * GROUP_SIZE..(gi + 1) * GROUP_SIZE];
7954        #[cfg(target_arch = "aarch64")]
7955        // NEON: the byte's four 2-bit fields land in four lane vectors
7956        // (shift+mask), vld4 de-interleaves xq to match (xj[k] =
7957        // xq[4k+j]), widening MACs accumulate exactly in i32. A scalar
7958        // decode here cost as much as the dot it fed — the profile put
7959        // it at the top of the whole W2 decode.
7960        let dot = unsafe {
7961            use core::arch::aarch64::*;
7962            let b = vld1_u8(ch.as_ptr());
7963            let three = vdup_n_u8(3);
7964            let c0 = vreinterpret_s8_u8(vand_u8(b, three));
7965            let c1 = vreinterpret_s8_u8(vand_u8(vshr_n_u8(b, 2), three));
7966            let c2 = vreinterpret_s8_u8(vand_u8(vshr_n_u8(b, 4), three));
7967            let c3 = vreinterpret_s8_u8(vand_u8(vshr_n_u8(b, 6), three));
7968            let x4 = vld4_s8(xg.as_ptr());
7969            let mut acc4 = vdupq_n_s32(0);
7970            acc4 = vpadalq_s16(acc4, vmull_s8(c0, x4.0));
7971            acc4 = vpadalq_s16(acc4, vmull_s8(c1, x4.1));
7972            acc4 = vpadalq_s16(acc4, vmull_s8(c2, x4.2));
7973            acc4 = vpadalq_s16(acc4, vmull_s8(c3, x4.3));
7974            vaddvq_s32(acc4)
7975        };
7976        #[cfg(target_arch = "x86_64")]
7977        let dot: i32 = if avx2 {
7978            // SAFETY: the runtime feature check gates the target-feature body;
7979            // the group slices above are exactly 8 and 32 bytes long.
7980            unsafe { q2tp_code_dot_avx2(ch, xg) }
7981        } else {
7982            ch.iter()
7983                .enumerate()
7984                .map(|(k, &b)| {
7985                    ((b & 3) as i32) * xg[k * 4] as i32
7986                        + (((b >> 2) & 3) as i32) * xg[k * 4 + 1] as i32
7987                        + (((b >> 4) & 3) as i32) * xg[k * 4 + 2] as i32
7988                        + (((b >> 6) & 3) as i32) * xg[k * 4 + 3] as i32
7989                })
7990                .sum()
7991        };
7992        #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
7993        let dot: i32 = {
7994            for (k, &b) in ch.iter().enumerate() {
7995                codes[k * 4] = (b & 3) as i8;
7996                codes[k * 4 + 1] = ((b >> 2) & 3) as i8;
7997                codes[k * 4 + 2] = ((b >> 4) & 3) as i8;
7998                codes[k * 4 + 3] = ((b >> 6) & 3) as i8;
7999            }
8000            codes
8001                .iter()
8002                .zip(xg)
8003                .map(|(&c, &x)| c as i32 * x as i32)
8004                .sum()
8005        };
8006        acc += scales[gi] * (dot as f32 - 1.5 * gsum[gi] as f32);
8007    }
8008    acc
8009}
8010
8011/// Exact f32 dot of one q2tp row: 2-bit fields LSB-first, (c − 1.5)·s.
8012/// Scalar on purpose — the 2-bit class targets the GPU graph; the CPU
8013/// path exists for parity gates and small-machine fallback.
8014fn q2tp_row_exact(chunks: &[u8], r: usize, gpr: usize, x: &[f32], scales: &[f32]) -> f32 {
8015    q2tp_row_exact_center(chunks, r, gpr, x, scales, 1.5)
8016}
8017
8018/// Fused Prism affine row: the derived correction is applied inside the
8019/// decoded code, avoiding a second accumulated dot and avoiding cancellation
8020/// between `B=(c-1.5)s` and `+.5s` for long 5120/17408 rows.
8021#[inline]
8022fn q2tp_affine_row_exact(chunks: &[u8], r: usize, gpr: usize, x: &[f32], scales: &[f32]) -> f32 {
8023    q2tp_row_exact_center(chunks, r, gpr, x, scales, 1.0)
8024}
8025
8026#[inline]
8027fn q2tp_row_exact_center(
8028    chunks: &[u8],
8029    r: usize,
8030    gpr: usize,
8031    x: &[f32],
8032    scales: &[f32],
8033    center: f32,
8034) -> f32 {
8035    let mut acc = 0f32;
8036    for gi in 0..gpr {
8037        let ch = &chunks[(r * gpr + gi) * Q2TP_CHUNK..(r * gpr + gi + 1) * Q2TP_CHUNK];
8038        let s = scales[gi];
8039        let xb = &x[gi * GROUP_SIZE..(gi + 1) * GROUP_SIZE];
8040        let mut g = 0f32;
8041        for (k, &b) in ch.iter().enumerate() {
8042            g += ((b & 3) as f32 - center) * xb[k * 4]
8043                + (((b >> 2) & 3) as f32 - center) * xb[k * 4 + 1]
8044                + (((b >> 4) & 3) as f32 - center) * xb[k * 4 + 2]
8045                + (((b >> 6) & 3) as f32 - center) * xb[k * 4 + 3];
8046        }
8047        acc += s * g;
8048    }
8049    acc
8050}
8051
8052fn q2tp_matvec(
8053    bytes: &[u8],
8054    x: &[f32],
8055    rows: usize,
8056    cols: usize,
8057    out: &mut [f32],
8058    pool: Option<&Pool>,
8059) {
8060    q2tp_matvec_mode(bytes, x, rows, cols, out, pool, false);
8061}
8062
8063fn q2tp_affine_matvec(
8064    bytes: &[u8],
8065    x: &[f32],
8066    rows: usize,
8067    cols: usize,
8068    out: &mut [f32],
8069    pool: Option<&Pool>,
8070) {
8071    q2tp_matvec_mode(bytes, x, rows, cols, out, pool, true);
8072}
8073
8074fn q2tp_matvec_mode(
8075    bytes: &[u8],
8076    x: &[f32],
8077    rows: usize,
8078    cols: usize,
8079    out: &mut [f32],
8080    pool: Option<&Pool>,
8081    affine: bool,
8082) {
8083    debug_assert_eq!(out.len(), rows);
8084    let gpr = cols / GROUP_SIZE;
8085    let v = Q4tpView::new_q2(bytes, rows, cols);
8086    let out_addr = SendMut(out.as_mut_ptr());
8087    // a8w8 fast path (CMF_SDOT=0 keeps the exact scalar walk): integer
8088    // code dots + group sums, exact outlier correction — the same
8089    // contract as every sibling kernel; measured 2-bit rows were the
8090    // only scalar holdout in the family.
8091    if !affine && a8w8_enabled() {
8092        let act = split_act(x);
8093        let gsum = q1_group_sums(&act.xq, gpr);
8094        let (act, gsum) = (&act, &gsum);
8095        let run = move |start: usize, end: usize| {
8096            with_krow(gpr, |sc| {
8097                for r in start..end {
8098                    v.scales_into(r, gpr, sc);
8099                    let mut acc = dot_q2tp_row_i8(v.nib, r, gpr, &act.xq, gsum, sc) * act.sx;
8100                    for &(j, xv) in &act.outliers {
8101                        let (w, s) = q2tp_outlier(v.nib, r, gpr, j, sc);
8102                        acc += w * s * xv;
8103                    }
8104                    // SAFETY: disjoint row ranges per worker.
8105                    unsafe { *out_addr.at(r) = acc };
8106                }
8107            })
8108        };
8109        dispatch_rows(pool, rows, &run);
8110        return;
8111    }
8112    let run = |start: usize, end: usize| {
8113        with_krow(gpr, |sc| {
8114            for r in start..end {
8115                v.scales_into(r, gpr, sc);
8116                // SAFETY: disjoint row ranges per worker.
8117                unsafe {
8118                    *out_addr.at(r) = if affine {
8119                        q2tp_affine_row_exact(v.nib, r, gpr, x, sc)
8120                    } else {
8121                        q2tp_row_exact(v.nib, r, gpr, x, sc)
8122                    }
8123                };
8124            }
8125        })
8126    };
8127    dispatch_rows(pool, rows, &run);
8128}
8129
8130/// Fused two-input q2tp matvec — the SwiGLU gate/up pair.
8131#[allow(clippy::too_many_arguments)]
8132fn q2tp_matvec2(
8133    bytes: &[u8],
8134    x1: &[f32],
8135    x2: &[f32],
8136    rows: usize,
8137    cols: usize,
8138    o1: &mut [f32],
8139    o2: &mut [f32],
8140    pool: Option<&Pool>,
8141) {
8142    q2tp_matvec2_mode(bytes, x1, x2, rows, cols, o1, o2, pool, false);
8143}
8144
8145#[allow(clippy::too_many_arguments)]
8146fn q2tp_affine_matvec2(
8147    bytes: &[u8],
8148    x1: &[f32],
8149    x2: &[f32],
8150    rows: usize,
8151    cols: usize,
8152    o1: &mut [f32],
8153    o2: &mut [f32],
8154    pool: Option<&Pool>,
8155) {
8156    q2tp_matvec2_mode(bytes, x1, x2, rows, cols, o1, o2, pool, true);
8157}
8158
8159#[allow(clippy::too_many_arguments)]
8160fn q2tp_matvec2_mode(
8161    bytes: &[u8],
8162    x1: &[f32],
8163    x2: &[f32],
8164    rows: usize,
8165    cols: usize,
8166    o1: &mut [f32],
8167    o2: &mut [f32],
8168    pool: Option<&Pool>,
8169    affine: bool,
8170) {
8171    let gpr = cols / GROUP_SIZE;
8172    let v = Q4tpView::new_q2(bytes, rows, cols);
8173    let (p1, p2) = (SendMut(o1.as_mut_ptr()), SendMut(o2.as_mut_ptr()));
8174    let run = |start: usize, end: usize| {
8175        let mut sc = vec![0f32; gpr];
8176        for r in start..end {
8177            v.scales_into(r, gpr, &mut sc);
8178            // SAFETY: disjoint row ranges per worker.
8179            unsafe {
8180                *p1.at(r) = if affine {
8181                    q2tp_affine_row_exact(v.nib, r, gpr, x1, &sc)
8182                } else {
8183                    q2tp_row_exact(v.nib, r, gpr, x1, &sc)
8184                };
8185                *p2.at(r) = if affine {
8186                    q2tp_affine_row_exact(v.nib, r, gpr, x2, &sc)
8187                } else {
8188                    q2tp_row_exact(v.nib, r, gpr, x2, &sc)
8189                };
8190            }
8191        }
8192    };
8193    dispatch_rows(pool, rows, &run);
8194}
8195
8196/// Batched q2tp matmat: scalar row kernel over every batch column. CPU
8197/// prefill only — decode rides the graph, so plain and correct beats
8198/// clever here.
8199/// Test doors into the host 2-bit kernels: the stand's heap corruption
8200/// pointed at down-shaped tensors, and the private fns need a way to be
8201/// held to a reference without a model file around them.
8202pub fn q2tp_matvec_for_test(bytes: &[u8], x: &[f32], rows: usize, cols: usize, out: &mut [f32]) {
8203    // The facade IS the reference: encoder oracles hold requant output
8204    // to the exact scalar walk. The production dispatch may take the i8
8205    // fast path, whose error scale is the ACTIVATIONS' — a different
8206    // claim than the encoder correctness these tests pin.
8207    let gpr = cols / GROUP_SIZE;
8208    let v = Q4tpView::new_q2(bytes, rows, cols);
8209    with_krow(gpr, |sc| {
8210        for r in 0..rows {
8211            v.scales_into(r, gpr, sc);
8212            out[r] = q2tp_row_exact(v.nib, r, gpr, x, sc);
8213        }
8214    });
8215}
8216
8217/// Test door for the descriptor-specific fused affine decode.  Production
8218/// callers select this through a validated Prism header, never by dtype alone.
8219pub fn q2tp_affine_matvec_for_test(
8220    bytes: &[u8],
8221    x: &[f32],
8222    rows: usize,
8223    cols: usize,
8224    out: &mut [f32],
8225) {
8226    q2tp_affine_matvec(bytes, x, rows, cols, out, None);
8227}
8228
8229pub fn q2tp_matmat_for_test(
8230    bytes: &[u8],
8231    xs_all: &[f32],
8232    b: usize,
8233    rows: usize,
8234    cols: usize,
8235    out: &mut [f32],
8236) {
8237    q2tp_matmat(bytes, xs_all, b, rows, cols, out, None);
8238}
8239
8240fn q2tp_matmat(
8241    bytes: &[u8],
8242    xs_all: &[f32],
8243    b: usize,
8244    rows: usize,
8245    cols: usize,
8246    out: &mut [f32],
8247    pool: Option<&Pool>,
8248) {
8249    q2tp_matmat_mode(bytes, xs_all, b, rows, cols, out, pool, false);
8250}
8251
8252fn q2tp_affine_matmat(
8253    bytes: &[u8],
8254    xs_all: &[f32],
8255    b: usize,
8256    rows: usize,
8257    cols: usize,
8258    out: &mut [f32],
8259    pool: Option<&Pool>,
8260) {
8261    q2tp_matmat_mode(bytes, xs_all, b, rows, cols, out, pool, true);
8262}
8263
8264fn q2tp_matmat_mode(
8265    bytes: &[u8],
8266    xs_all: &[f32],
8267    b: usize,
8268    rows: usize,
8269    cols: usize,
8270    out: &mut [f32],
8271    pool: Option<&Pool>,
8272    affine: bool,
8273) {
8274    debug_assert_eq!(out.len(), b * rows);
8275    let gpr = cols / GROUP_SIZE;
8276    let v = Q4tpView::new_q2(bytes, rows, cols);
8277    let out_addr = SendMut(out.as_mut_ptr());
8278    let run = |start: usize, end: usize| {
8279        let mut sc = vec![0f32; gpr];
8280        for r in start..end {
8281            v.scales_into(r, gpr, &mut sc);
8282            for bi in 0..b {
8283                let x = &xs_all[bi * cols..(bi + 1) * cols];
8284                // SAFETY: disjoint row ranges per worker.
8285                unsafe {
8286                    *out_addr.at(bi * rows + r) = if affine {
8287                        q2tp_affine_row_exact(v.nib, r, gpr, x, &sc)
8288                    } else {
8289                        q2tp_row_exact(v.nib, r, gpr, x, &sc)
8290                    }
8291                };
8292            }
8293        }
8294    };
8295    dispatch_rows(pool, rows, &run);
8296}
8297
8298/// The pre-vectorised shape, kept for A/B (`CMF_Q4TP_V1=1`): the
8299/// horizontal add lands once per group per column instead of once per
8300/// row. Same weights, same activations — only the reduction differs.
8301/// It is also the row-exact batch kernel: per group and column it forms
8302/// `int dot as f32 * scale` and adds it to a scalar running sum, which is
8303/// `dot_q4tp_row_sdot` step for step (Rust never contracts to an fma),
8304/// so each column is bit-identical to that column's matvec.
8305#[cfg(target_arch = "aarch64")]
8306#[target_feature(enable = "neon,dotprod")]
8307unsafe fn dot_q4tp_row_1x4_sdot_v1(
8308    nib: &[u8],
8309    r: usize,
8310    gpr: usize,
8311    xs: [&[i8]; 4],
8312    scales: &[f32],
8313) -> [f32; 4] {
8314    unsafe {
8315        use core::arch::aarch64::*;
8316        use core::arch::asm;
8317        let lomask = vdupq_n_u8(0x0F);
8318        let eight = vdupq_n_s8(8);
8319        let (mut f0, mut f1, mut f2, mut f3) = (0f32, 0f32, 0f32, 0f32);
8320        for gi in 0..gpr {
8321            let t = nib.as_ptr().add((r * gpr + gi) * Q4TP_NIB);
8322            let s = *scales.get_unchecked(gi);
8323            let bb = vld1q_u8(t);
8324            let lo = vandq_u8(bb, lomask);
8325            let hi = vshrq_n_u8::<4>(bb);
8326            let e0 = vsubq_s8(vreinterpretq_s8_u8(vzip1q_u8(lo, hi)), eight);
8327            let e1 = vsubq_s8(vreinterpretq_s8_u8(vzip2q_u8(lo, hi)), eight);
8328            let mut d = [0f32; 4];
8329            for (k, dk) in d.iter_mut().enumerate() {
8330                let x0 = vld1q_s8(xs[k].as_ptr().add(gi * GROUP_SIZE));
8331                let x1 = vld1q_s8(xs[k].as_ptr().add(gi * GROUP_SIZE + 16));
8332                let (mut a0, mut a1) = (vdupq_n_s32(0), vdupq_n_s32(0));
8333                asm!(
8334                    "sdot {a0:v}.4s, {e0:v}.16b, {x0:v}.16b",
8335                    "sdot {a1:v}.4s, {e1:v}.16b, {x1:v}.16b",
8336                    a0 = inout(vreg) a0, a1 = inout(vreg) a1,
8337                    e0 = in(vreg) e0, x0 = in(vreg) x0, e1 = in(vreg) e1, x1 = in(vreg) x1,
8338                    options(pure, nomem, nostack),
8339                );
8340                *dk = vaddvq_s32(vaddq_s32(a0, a1)) as f32 * s;
8341            }
8342            f0 += d[0];
8343            f1 += d[1];
8344            f2 += d[2];
8345            f3 += d[3];
8346        }
8347        [f0, f1, f2, f3]
8348    }
8349}
8350
8351/// Which q4tp batch kernel to run: 1 = the previous one, 2 = the tuned
8352/// one, 0 = decide from the CPU. An atomic rather than a `OnceLock` so a
8353/// benchmark can alternate the two inside one process, where the machine's
8354/// mood — a shared box drifts ±25% between runs — is the same for both.
8355/// What the two mean is per-architecture: on x86 the blocked AVX-512 path
8356/// against the per-column one, on ARM the two reduction shapes.
8357#[allow(dead_code)]
8358static Q4TP_ALT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
8359
8360/// Tests that store `Q4TP_ALT` hold this, so one test's kernel pick does
8361/// not leak into another's bit-exact comparison running in parallel.
8362#[cfg(test)]
8363static Q4TP_ALT_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
8364
8365/// Blocking pays on x86 only with 512-bit VNNI. With AVX2 alone, four
8366/// columns sharing an unpack still measured slower than the per-column
8367/// path (23.2 ms against 19.4 on a 48-thread EPYC), because that path
8368/// already dequantizes the row once — so the blocked kernel bought a
8369/// second unpack-free pass at the price of half the vector width.
8370#[cfg(target_arch = "x86_64")]
8371fn q4tp_blocked_x86() -> bool {
8372    match Q4TP_ALT.load(std::sync::atomic::Ordering::Relaxed) {
8373        1 => false,
8374        // A forced ON still asks the CPU. The switch exists so a bench can
8375        // pick a kernel, not so it can promise instructions the machine
8376        // does not have — CI caught that as a SIGILL on a runner without
8377        // AVX-512, where the parity test had turned the path on by hand.
8378        2 => avx512vnni_enabled(),
8379        // Deliberately not cached back into the switch: both gates below
8380        // hold their own `OnceLock`, and latching their answer here would
8381        // make a test's override outlive the test that set it.
8382        _ => blocked_enabled() && avx512vnni_enabled(),
8383    }
8384}
8385
8386/// `CMF_Q4TP_V1=1` picks the old reduction shape (A/B only).
8387#[cfg(target_arch = "aarch64")]
8388#[allow(dead_code)]
8389fn q4tp_v1() -> bool {
8390    match Q4TP_ALT.load(std::sync::atomic::Ordering::Relaxed) {
8391        1 => true,
8392        2 => false,
8393        _ => {
8394            static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
8395            *ON.get_or_init(|| std::env::var("CMF_Q4TP_V1").is_ok_and(|v| v != "0"))
8396        }
8397    }
8398}
8399
8400/// Two weight rows against eight columns. The activation load is the
8401/// same for both rows, so it is paid once for twice the arithmetic, and
8402/// sixteen accumulator chains run where eight did — which is what a kernel
8403/// retiring 0.29 instructions a cycle is short of. Register pressure is
8404/// the limit: sixteen `zmm` accumulators, two weight tiles, one
8405/// activation, of thirty-two.
8406///
8407/// Four rows by four columns spends the same sixteen accumulators the
8408/// other way and measured worse — 1488 GFLOP/s against 1644 — so the
8409/// unpack, which four rows pay twice as often, costs more than the extra
8410/// sharing of one activation load buys.
8411#[cfg(target_arch = "x86_64")]
8412#[target_feature(enable = "avx512f,avx512bw,avx512vnni")]
8413unsafe fn dot_q4tp_2x8_avx512(
8414    nib: &[u8],
8415    r0: usize,
8416    gpr: usize,
8417    xs: [&[i8]; 8],
8418    sc0: &[f32],
8419    sc1: &[f32],
8420) -> [[f32; 8]; 2] {
8421    // SAFETY: as dot_q4tp_row_1x8_avx512, two adjacent rows at once; the
8422    // caller guarantees r0 + 1 < rows and the ISA.
8423    unsafe {
8424        use core::arch::x86_64::*;
8425        let lomask = _mm256_set1_epi8(0x0F);
8426        let eight = _mm256_set1_epi8(8);
8427        let zero = _mm512_setzero_si512();
8428        let mut v0 = [_mm512_setzero_ps(); 8];
8429        let mut v1 = [_mm512_setzero_ps(); 8];
8430        let pairs = gpr / 2;
8431        let unpack = |r: usize, gi: usize| -> (__m512i, __mmask64) {
8432            let t = nib.as_ptr().add((r * gpr + gi) * Q4TP_NIB);
8433            let bb = _mm256_loadu_si256(t as *const __m256i);
8434            let lo = _mm256_and_si256(bb, lomask);
8435            let hi = _mm256_and_si256(_mm256_srli_epi16::<4>(bb), lomask);
8436            let ul = _mm256_sub_epi8(_mm256_unpacklo_epi8(lo, hi), eight);
8437            let uh = _mm256_sub_epi8(_mm256_unpackhi_epi8(lo, hi), eight);
8438            let cat = _mm512_inserti64x4::<1>(_mm512_castsi256_si512(ul), uh);
8439            let w = _mm512_shuffle_i64x2::<0b11_01_10_00>(cat, cat);
8440            (_mm512_abs_epi8(w), _mm512_movepi8_mask(w))
8441        };
8442        for gp in 0..pairs {
8443            let gi = gp * 2;
8444            let (wa0, neg0) = unpack(r0, gi);
8445            let (wa1, neg1) = unpack(r0 + 1, gi);
8446            let off = gi * GROUP_SIZE;
8447            let sv = |sc: &[f32]| {
8448                _mm512_insertf32x8::<1>(
8449                    _mm512_castps256_ps512(_mm256_set1_ps(*sc.get_unchecked(gi))),
8450                    _mm256_set1_ps(*sc.get_unchecked(gi + 1)),
8451                )
8452            };
8453            let s0 = sv(sc0);
8454            let s1 = sv(sc1);
8455            for k in 0..8 {
8456                let xv = _mm512_loadu_si512(xs[k].as_ptr().add(off) as *const __m512i);
8457                let d0 = _mm512_cvtepi32_ps(_mm512_dpbusd_epi32(
8458                    zero,
8459                    wa0,
8460                    _mm512_mask_sub_epi8(xv, neg0, zero, xv),
8461                ));
8462                let d1 = _mm512_cvtepi32_ps(_mm512_dpbusd_epi32(
8463                    zero,
8464                    wa1,
8465                    _mm512_mask_sub_epi8(xv, neg1, zero, xv),
8466                ));
8467                v0[k] = _mm512_fmadd_ps(d0, s0, v0[k]);
8468                v1[k] = _mm512_fmadd_ps(d1, s1, v1[k]);
8469            }
8470        }
8471        let mut acc = [[0f32; 8]; 2];
8472        for k in 0..8 {
8473            acc[0][k] = _mm512_reduce_add_ps(v0[k]);
8474            acc[1][k] = _mm512_reduce_add_ps(v1[k]);
8475        }
8476        if gpr % 2 == 1 {
8477            let off = (gpr - 1) * GROUP_SIZE;
8478            for j in off..off + GROUP_SIZE {
8479                let (w0, sa) = q4tp_outlier(nib, r0, gpr, j, sc0);
8480                let (w1, sb) = q4tp_outlier(nib, r0 + 1, gpr, j, sc1);
8481                for k in 0..8 {
8482                    let x = *xs[k].get_unchecked(j) as f32;
8483                    acc[0][k] += w0 * sa * x;
8484                    acc[1][k] += w1 * sb * x;
8485                }
8486            }
8487        }
8488        acc
8489    }
8490}
8491
8492/// The same, eight columns at a time. One unpack then feeds twice as many
8493/// activation streams, so a wide batch reads the weight tile half as
8494/// often; the price is eight accumulators live at once. Measured 9.0 ->
8495/// 8.3 ms at 9216x2304, b=296 on a 48-thread EPYC 9B45.
8496#[cfg(target_arch = "x86_64")]
8497#[target_feature(enable = "avx512f,avx512bw,avx512vnni")]
8498unsafe fn dot_q4tp_row_1x8_avx512(
8499    nib: &[u8],
8500    r: usize,
8501    gpr: usize,
8502    xs: [&[i8]; 8],
8503    scales: &[f32],
8504) -> [f32; 8] {
8505    // SAFETY: as dot_q4tp_row_1x4_avx2; caller guarantees the ISA.
8506    unsafe {
8507        use core::arch::x86_64::*;
8508        let lomask = _mm256_set1_epi8(0x0F);
8509        let eight = _mm256_set1_epi8(8);
8510        let zero = _mm512_setzero_si512();
8511        let (mut v0, mut v1, mut v2, mut v3) = (
8512            _mm512_setzero_ps(),
8513            _mm512_setzero_ps(),
8514            _mm512_setzero_ps(),
8515            _mm512_setzero_ps(),
8516        );
8517        let (mut v4, mut v5, mut v6, mut v7) = (
8518            _mm512_setzero_ps(),
8519            _mm512_setzero_ps(),
8520            _mm512_setzero_ps(),
8521            _mm512_setzero_ps(),
8522        );
8523        let pairs = gpr / 2;
8524        for gp in 0..pairs {
8525            let gi = gp * 2;
8526            let t = nib.as_ptr().add((r * gpr + gi) * Q4TP_NIB);
8527            let bb = _mm256_loadu_si256(t as *const __m256i);
8528            let lo = _mm256_and_si256(bb, lomask);
8529            let hi = _mm256_and_si256(_mm256_srli_epi16::<4>(bb), lomask);
8530            // `unpack` works per 128-bit lane, so the halves come out as
8531            // [A.lo, B.lo] and [A.hi, B.hi]; the shuffle reorders the four
8532            // 128-bit lanes into the weights' natural order, which is what
8533            // the straight activation load expects.
8534            let ul = _mm256_sub_epi8(_mm256_unpacklo_epi8(lo, hi), eight);
8535            let uh = _mm256_sub_epi8(_mm256_unpackhi_epi8(lo, hi), eight);
8536            let cat = _mm512_inserti64x4::<1>(_mm512_castsi256_si512(ul), uh);
8537            let w = _mm512_shuffle_i64x2::<0b11_01_10_00>(cat, cat);
8538            let wabs = _mm512_abs_epi8(w);
8539            let neg = _mm512_movepi8_mask(w);
8540            let off = gi * GROUP_SIZE;
8541            let sv = _mm512_insertf32x8::<1>(
8542                _mm512_castps256_ps512(_mm256_set1_ps(*scales.get_unchecked(gi))),
8543                _mm256_set1_ps(*scales.get_unchecked(gi + 1)),
8544            );
8545            let dot = |x: &[i8]| -> __m512 {
8546                let xv = _mm512_loadu_si512(x.as_ptr().add(off) as *const __m512i);
8547                let sx = _mm512_mask_sub_epi8(xv, neg, zero, xv);
8548                _mm512_cvtepi32_ps(_mm512_dpbusd_epi32(zero, wabs, sx))
8549            };
8550            v0 = _mm512_fmadd_ps(dot(xs[0]), sv, v0);
8551            v1 = _mm512_fmadd_ps(dot(xs[1]), sv, v1);
8552            v2 = _mm512_fmadd_ps(dot(xs[2]), sv, v2);
8553            v3 = _mm512_fmadd_ps(dot(xs[3]), sv, v3);
8554            v4 = _mm512_fmadd_ps(dot(xs[4]), sv, v4);
8555            v5 = _mm512_fmadd_ps(dot(xs[5]), sv, v5);
8556            v6 = _mm512_fmadd_ps(dot(xs[6]), sv, v6);
8557            v7 = _mm512_fmadd_ps(dot(xs[7]), sv, v7);
8558        }
8559        let mut acc = [
8560            _mm512_reduce_add_ps(v0),
8561            _mm512_reduce_add_ps(v1),
8562            _mm512_reduce_add_ps(v2),
8563            _mm512_reduce_add_ps(v3),
8564            _mm512_reduce_add_ps(v4),
8565            _mm512_reduce_add_ps(v5),
8566            _mm512_reduce_add_ps(v6),
8567            _mm512_reduce_add_ps(v7),
8568        ];
8569        // An odd group count leaves one group over; the narrow kernel
8570        // finishes it rather than the tail being a special case here.
8571        if gpr % 2 == 1 {
8572            let off = (gpr - 1) * GROUP_SIZE;
8573            for j in off..off + GROUP_SIZE {
8574                let (w, s) = q4tp_outlier(nib, r, gpr, j, scales);
8575                let ws = w * s;
8576                for k in 0..8 {
8577                    acc[k] += ws * *xs[k].get_unchecked(j) as f32;
8578                }
8579            }
8580        }
8581        acc
8582    }
8583}
8584
8585/// The same four columns, 512 bits wide. Two groups (64 weights) ride one
8586/// unpack and one `vpdpbusd`, where AVX2 needs two unpacks and four
8587/// `maddubs`/`madd` pairs — about 2.3x fewer instructions for the same
8588/// arithmetic. The two groups carry different scales, so the fma takes a
8589/// vector whose halves hold each group's scale rather than a broadcast.
8590///
8591/// There is no 512-bit `vpsignb`, so the activation's sign is applied by
8592/// negating under a mask taken from the weight's sign bits. That mask is
8593/// per-tile, so it is hoisted out of the column loop and the per-column
8594/// cost stays exactly one instruction, as with `sign_epi8`. Weights of
8595/// zero are not zeroed by the mask trick and do not need to be: their
8596/// magnitude is zero, so the product is.
8597#[cfg(target_arch = "x86_64")]
8598#[target_feature(enable = "avx512f,avx512bw,avx512vnni")]
8599unsafe fn dot_q4tp_row_1x4_avx512(
8600    nib: &[u8],
8601    r: usize,
8602    gpr: usize,
8603    xs: [&[i8]; 4],
8604    scales: &[f32],
8605) -> [f32; 4] {
8606    // SAFETY: as dot_q4tp_row_1x4_avx2; caller guarantees the ISA.
8607    unsafe {
8608        use core::arch::x86_64::*;
8609        let lomask = _mm256_set1_epi8(0x0F);
8610        let eight = _mm256_set1_epi8(8);
8611        let zero = _mm512_setzero_si512();
8612        let (mut v0, mut v1, mut v2, mut v3) = (
8613            _mm512_setzero_ps(),
8614            _mm512_setzero_ps(),
8615            _mm512_setzero_ps(),
8616            _mm512_setzero_ps(),
8617        );
8618        let pairs = gpr / 2;
8619        for gp in 0..pairs {
8620            let gi = gp * 2;
8621            let t = nib.as_ptr().add((r * gpr + gi) * Q4TP_NIB);
8622            let bb = _mm256_loadu_si256(t as *const __m256i);
8623            let lo = _mm256_and_si256(bb, lomask);
8624            let hi = _mm256_and_si256(_mm256_srli_epi16::<4>(bb), lomask);
8625            // `unpack` works per 128-bit lane, so the halves come out as
8626            // [A.lo, B.lo] and [A.hi, B.hi]; the shuffle reorders the four
8627            // 128-bit lanes into the weights' natural order, which is what
8628            // the straight activation load expects.
8629            let ul = _mm256_sub_epi8(_mm256_unpacklo_epi8(lo, hi), eight);
8630            let uh = _mm256_sub_epi8(_mm256_unpackhi_epi8(lo, hi), eight);
8631            let cat = _mm512_inserti64x4::<1>(_mm512_castsi256_si512(ul), uh);
8632            let w = _mm512_shuffle_i64x2::<0b11_01_10_00>(cat, cat);
8633            let wabs = _mm512_abs_epi8(w);
8634            let neg = _mm512_movepi8_mask(w);
8635            let off = gi * GROUP_SIZE;
8636            let sv = _mm512_insertf32x8::<1>(
8637                _mm512_castps256_ps512(_mm256_set1_ps(*scales.get_unchecked(gi))),
8638                _mm256_set1_ps(*scales.get_unchecked(gi + 1)),
8639            );
8640            let dot = |x: &[i8]| -> __m512 {
8641                let xv = _mm512_loadu_si512(x.as_ptr().add(off) as *const __m512i);
8642                let sx = _mm512_mask_sub_epi8(xv, neg, zero, xv);
8643                _mm512_cvtepi32_ps(_mm512_dpbusd_epi32(zero, wabs, sx))
8644            };
8645            v0 = _mm512_fmadd_ps(dot(xs[0]), sv, v0);
8646            v1 = _mm512_fmadd_ps(dot(xs[1]), sv, v1);
8647            v2 = _mm512_fmadd_ps(dot(xs[2]), sv, v2);
8648            v3 = _mm512_fmadd_ps(dot(xs[3]), sv, v3);
8649        }
8650        let mut acc = [
8651            _mm512_reduce_add_ps(v0),
8652            _mm512_reduce_add_ps(v1),
8653            _mm512_reduce_add_ps(v2),
8654            _mm512_reduce_add_ps(v3),
8655        ];
8656        // An odd group count leaves one group over; the narrow kernel
8657        // finishes it rather than the tail being a special case here.
8658        if gpr % 2 == 1 {
8659            let off = (gpr - 1) * GROUP_SIZE;
8660            for j in off..off + GROUP_SIZE {
8661                let (w, s) = q4tp_outlier(nib, r, gpr, j, scales);
8662                let ws = w * s;
8663                for k in 0..4 {
8664                    acc[k] += ws * *xs[k].get_unchecked(j) as f32;
8665                }
8666            }
8667        }
8668        acc
8669    }
8670}
8671
8672/// Four batch columns against one q4tp row: the tile is unpacked ONCE and
8673/// spent on four activation streams, which is where a prefill batch stops
8674/// being weight-bandwidth-bound. Twin of `dot_q4t_row_1x4_sdot`.
8675#[cfg(target_arch = "aarch64")]
8676#[target_feature(enable = "neon,dotprod")]
8677unsafe fn dot_q4tp_row_1x4_sdot(
8678    nib: &[u8],
8679    r: usize,
8680    gpr: usize,
8681    xs: [&[i8]; 4],
8682    scales: &[f32],
8683) -> [f32; 4] {
8684    // SAFETY: see dot_q4tp_row_sdot; every xs[k] is gpr·GROUP_SIZE long.
8685    unsafe {
8686        use core::arch::aarch64::*;
8687        use core::arch::asm;
8688        let lomask = vdupq_n_u8(0x0F);
8689        let eight = vdupq_n_s8(8);
8690        // Named accumulators, NOT an array indexed by a loop variable: the
8691        // latter does not stay in registers (the same defect cost 2x in the
8692        // AVX2 q4t kernel and again in WGSL).
8693        //
8694        // They are VECTORS, and the horizontal add happens once at the end
8695        // instead of once per group per column. `vaddvq` is a cross-lane
8696        // reduction — with 72 groups and four columns the old shape paid
8697        // 288 of them per row, each one a dependency stall the pipeline
8698        // cannot hide, to save four float adds. The group's scale now
8699        // rides an fma into the lane accumulators, so the arithmetic per
8700        // group is one convert and one fma. Summation order changes (the
8701        // lanes carry independent partial sums), which is the same
8702        // round-off class the SDOT path already lives in — the strict
8703        // kernel (`CMF_SDOT=0`, what `cortiq ppl` runs) is unchanged and
8704        // stays the reference.
8705        let (mut v0, mut v1, mut v2, mut v3) = (
8706            vdupq_n_f32(0.0),
8707            vdupq_n_f32(0.0),
8708            vdupq_n_f32(0.0),
8709            vdupq_n_f32(0.0),
8710        );
8711        for gi in 0..gpr {
8712            let t = nib.as_ptr().add((r * gpr + gi) * Q4TP_NIB);
8713            let s = *scales.get_unchecked(gi);
8714            let bb = vld1q_u8(t);
8715            let lo = vandq_u8(bb, lomask);
8716            let hi = vshrq_n_u8::<4>(bb);
8717            let e0 = vsubq_s8(vreinterpretq_s8_u8(vzip1q_u8(lo, hi)), eight);
8718            let e1 = vsubq_s8(vreinterpretq_s8_u8(vzip2q_u8(lo, hi)), eight);
8719            let off = gi * GROUP_SIZE;
8720            let dot4 = |x: &[i8]| -> int32x4_t {
8721                let x0 = vld1q_s8(x.as_ptr().add(off));
8722                let x1 = vld1q_s8(x.as_ptr().add(off + 16));
8723                let (mut a0, mut a1) = (vdupq_n_s32(0), vdupq_n_s32(0));
8724                asm!(
8725                    "sdot {a0:v}.4s, {e0:v}.16b, {x0:v}.16b",
8726                    "sdot {a1:v}.4s, {e1:v}.16b, {x1:v}.16b",
8727                    a0 = inout(vreg) a0, a1 = inout(vreg) a1,
8728                    e0 = in(vreg) e0, x0 = in(vreg) x0, e1 = in(vreg) e1, x1 = in(vreg) x1,
8729                    options(pure, nomem, nostack),
8730                );
8731                vaddq_s32(a0, a1)
8732            };
8733            v0 = vfmaq_n_f32(v0, vcvtq_f32_s32(dot4(xs[0])), s);
8734            v1 = vfmaq_n_f32(v1, vcvtq_f32_s32(dot4(xs[1])), s);
8735            v2 = vfmaq_n_f32(v2, vcvtq_f32_s32(dot4(xs[2])), s);
8736            v3 = vfmaq_n_f32(v3, vcvtq_f32_s32(dot4(xs[3])), s);
8737        }
8738        [
8739            vaddvq_f32(v0),
8740            vaddvq_f32(v1),
8741            vaddvq_f32(v2),
8742            vaddvq_f32(v3),
8743        ]
8744    }
8745}
8746
8747fn cuda_mm_verify() -> bool {
8748    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
8749    *ON.get_or_init(|| std::env::var("CMF_CUDA_MM_VERIFY").as_deref() == Ok("1"))
8750}
8751
8752/// Fused q4tp matmat — the same three arms `q4t_matmat` has. Shipping only
8753/// the scalar one made Nanbeige-3B decode at 1.2 tok/s against q4t's 5.9:
8754/// the format was fine, the missing arms were the whole regression.
8755///
8756/// Under `row_exact()` every cell is summed in `q4tp_matvec`'s order on
8757/// every architecture; the mode is read once, so one call never mixes
8758/// the two contracts when a concurrent scope opens or closes mid-call.
8759/// Copy rows `row0..` of a q4tp matrix into the NPU module's tiled layout
8760/// (`npu.rs`): the codes byte for byte, each group's scale as a Q15 ratio of
8761/// the row's largest. `buf` is `ceil((rows - row0)/32) * gpr * npu::REC` bytes.
8762#[cfg(target_os = "android")]
8763fn npu_fill_q4tp(bytes: &[u8], rows: usize, cols: usize, buf: &mut [u8], row0: usize) -> Option<crate::npu::Tiled> {
8764    const REC: usize = crate::npu::REC;
8765    let gpr = cols / GROUP_SIZE;
8766    let tiles = (rows - row0).div_ceil(32);
8767    if buf.len() != tiles * gpr * REC {
8768        return None;
8769    }
8770    buf.fill(0);
8771    let v = Q4tpView::new(bytes, rows, cols);
8772    let mut scales = vec![0f32; gpr];
8773    let mut row_max = vec![0f32; rows - row0];
8774    for r in row0..rows {
8775        v.scales_into(r, gpr, &mut scales);
8776        let mx = scales.iter().fold(0f32, |a, &s| a.max(s.abs()));
8777        row_max[r - row0] = mx;
8778        let inv = if mx > 0.0 { 32767.0 / mx } else { 0.0 };
8779        let (t, lane) = ((r - row0) / 32, (r - row0) % 32);
8780        for g in 0..gpr {
8781            let rec = &mut buf[(t * gpr + g) * REC..(t * gpr + g + 1) * REC];
8782            let src = &v.nib[(r * gpr + g) * Q4TP_NIB..(r * gpr + g + 1) * Q4TP_NIB];
8783            for j in 0..4 {
8784                rec[j * 128 + lane * 4..j * 128 + lane * 4 + 4].copy_from_slice(&src[4 * j..4 * j + 4]);
8785            }
8786            let q = ((scales[g] * inv).round() as i32).clamp(-32767, 32767);
8787            rec[512 + lane * 4..512 + lane * 4 + 4].copy_from_slice(&(q << 16).to_le_bytes());
8788        }
8789    }
8790    // A group's integer sum is below 2^15; `gpr` of them, shifted, must stay inside an i32.
8791    let shift = (15u32.saturating_sub(gpr.next_power_of_two().trailing_zeros())).min(8);
8792    Some(crate::npu::Tiled { tiles, gpr, shift, row_max })
8793}
8794
8795#[cfg(target_os = "android")]
8796fn npu_lane_q4tp(mode: crate::npu::Mode, bytes: &[u8], rows: usize, cols: usize) -> Option<std::sync::Arc<crate::npu::Lane>> {
8797    crate::npu::lane_for(mode, bytes.as_ptr() as usize, rows, cols, &|buf, row0| {
8798        npu_fill_q4tp(bytes, rows, cols, buf, row0)
8799    })
8800}
8801
8802/// The NPU split of a prompt chunk's q4tp `matmat`: rows `row0..` for all
8803/// `b` vectors on the DSP while the CPU kernel computes rows `..row0`.
8804/// `false`: no lane for this matrix — the caller runs the CPU kernel.
8805#[cfg(target_os = "android")]
8806#[allow(clippy::too_many_arguments)]
8807fn npu_q4tp_matmat(bytes: &[u8], xs_all: &[f32], b: usize, rows: usize, cols: usize, out: &mut [f32], pool: Option<&Pool>) -> bool {
8808    use crate::npu::Mode::Batch;
8809    if b < 4 || !a8w8_enabled() || row_exact() {
8810        return false;
8811    }
8812    let Some(lane) = npu_lane_q4tp(Batch, bytes, rows, cols) else {
8813        return false;
8814    };
8815    let t0 = std::time::Instant::now();
8816    // Nanoseconds per vector per million weights: the trial's matrices differ in shape.
8817    let per_vec = |t0: std::time::Instant| (t0.elapsed().as_nanos() as u64) * 1_000_000 / (b * rows * cols) as u64;
8818    let timed = match crate::npu::arm(Batch) {
8819        crate::npu::Arm::Cpu => {
8820            q4tp_matmat_with(bytes, xs_all, b, rows, cols, out, pool, false);
8821            crate::npu::trial_sample(Batch, false, per_vec(t0));
8822            return true;
8823        }
8824        crate::npu::Arm::Npu { timed } => timed,
8825    };
8826    // The same per-vector int8 split the CPU kernel makes (it makes it
8827    // again inside): integers to the DSP, outliers added here in float.
8828    let acts = split_acts_pooled(xs_all, b, cols, pool);
8829    let mut xq = vec![0i8; b * cols];
8830    for (dst, a) in xq.chunks_exact_mut(cols).zip(&acts) {
8831        dst.copy_from_slice(&a.xq);
8832    }
8833    let pending = crate::npu::start_batch(&lane, b, &xq);
8834    let row0 = lane.row0;
8835    ROW_LIMIT.with(|c| c.set(row0));
8836    q4tp_matmat_with(bytes, xs_all, b, rows, cols, out, pool, false);
8837    ROW_LIMIT.with(|c| c.set(usize::MAX));
8838    match pending.and_then(|p| p.finish()) {
8839        Some(y) => {
8840            let n = lane.tiles * 32;
8841            for (bi, a) in acts.iter().enumerate() {
8842                let k = a.sx * lane.unit();
8843                let yb = &y[bi * n..(bi + 1) * n];
8844                let ob = &mut out[bi * rows..(bi + 1) * rows];
8845                for r in row0..rows {
8846                    let i = r - row0;
8847                    let mut v = yb[i] as f32 * lane.row_max[i] * k;
8848                    for &(j, xv) in &a.outliers {
8849                        let (w, s) = lane.weight(i, j);
8850                        v += w * s * xv;
8851                    }
8852                    ob[r] = v;
8853                }
8854            }
8855            if timed {
8856                crate::npu::trial_sample(Batch, true, per_vec(t0));
8857            }
8858        }
8859        None => q4tp_matmat_with(bytes, xs_all, b, rows, cols, out, pool, false),
8860    }
8861    true
8862}
8863
8864fn q4tp_matmat(
8865    bytes: &[u8],
8866    xs_all: &[f32],
8867    b: usize,
8868    rows: usize,
8869    cols: usize,
8870    out: &mut [f32],
8871    pool: Option<&Pool>,
8872) {
8873    #[cfg(target_os = "android")]
8874    if npu_q4tp_matmat(bytes, xs_all, b, rows, cols, out, pool) {
8875        return;
8876    }
8877    q4tp_matmat_with(bytes, xs_all, b, rows, cols, out, pool, row_exact())
8878}
8879
8880/// `q4tp_matmat` with the row-exact mode passed in rather than read from
8881/// the shared counter: `exact` = each cell equals its token's matvec bit
8882/// for bit, otherwise the fast blocked / AMX arms are free to reorder.
8883#[allow(clippy::too_many_arguments)]
8884fn q4tp_matmat_with(
8885    bytes: &[u8],
8886    xs_all: &[f32],
8887    b: usize,
8888    rows: usize,
8889    cols: usize,
8890    out: &mut [f32],
8891    pool: Option<&Pool>,
8892    exact: bool,
8893) {
8894    debug_assert_eq!(out.len(), b * rows);
8895    let gpr = cols / GROUP_SIZE;
8896    let v = Q4tpView::new(bytes, rows, cols);
8897
8898    // Wide batches ride the AMX through a dequant-tile sgemm, as in q4t.
8899    // An f32 GEMM over dequantized weights is not the matvec's int8 sum,
8900    // so a row-exact batch never takes it.
8901    #[cfg(target_os = "macos")]
8902    if !exact && b >= 8 && rows * cols >= 500_000 && accel_gemm_enabled() {
8903        dequant_matmat_accel(
8904            &|r, dst| {
8905                let mut sc = [0f32; 32];
8906                let mut scv;
8907                let s: &[f32] = if gpr <= 32 {
8908                    v.scales_into(r, gpr, &mut sc);
8909                    &sc[..gpr]
8910                } else {
8911                    scv = vec![0f32; gpr];
8912                    v.scales_into(r, gpr, &mut scv);
8913                    &scv
8914                };
8915                for gi in 0..gpr {
8916                    let tile = &v.nib[(r * gpr + gi) * Q4TP_NIB..(r * gpr + gi + 1) * Q4TP_NIB];
8917                    for (k, &bb) in tile.iter().enumerate() {
8918                        dst[gi * GROUP_SIZE + k * 2] = ((bb & 0x0F) as f32 - 8.0) * s[gi];
8919                        dst[gi * GROUP_SIZE + k * 2 + 1] =
8920                            (((bb >> 4) & 0x0F) as f32 - 8.0) * s[gi];
8921                    }
8922                }
8923            },
8924            xs_all,
8925            b,
8926            rows,
8927            cols,
8928            out,
8929            pool,
8930        );
8931        return;
8932    }
8933
8934    let out_addr = SendMut(out.as_mut_ptr());
8935    if a8w8_enabled() {
8936        let acts = split_acts_pooled(xs_all, b, cols, pool);
8937        let acts = &acts;
8938        // ARM stays blocked under `exact` too: the 1x4 kernel then runs in
8939        // its v1 shape, whose per-group `int dot as f32 * scale` and scalar
8940        // running sum are exactly `dot_q4tp_row_sdot`'s, so the tile is
8941        // still unpacked once for four columns and each column equals its
8942        // matvec. The tuned shape (fma into lane partials, one horizontal
8943        // add per row) is 1-16 ulp off the matvec and is kept for `!exact`.
8944        #[cfg(target_arch = "aarch64")]
8945        let blocked_ok = sdot_enabled() && blocked_enabled();
8946        // x86 gets the same blocking: one tile unpack spent on four
8947        // columns. Without it every column re-decoded the row, which is
8948        // why a 48-core EPYC measured a sixth of an M4's per-core rate.
8949        // The gate is `avx2_enabled`, as in q4t — `sdot_enabled` answers
8950        // for ARM's dotprod and is hard-wired false everywhere else, so
8951        // asking it here left the whole blocked path unreachable on x86.
8952        #[cfg(target_arch = "x86_64")]
8953        let blocked_ok = q4tp_blocked_x86() && !exact;
8954        #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
8955        let blocked_ok = {
8956            let _ = exact;
8957            false
8958        };
8959        // Columns are swept in panels that fit L2. Without this a
8960        // row-pair walks every activation in the batch — 4.8 MB at
8961        // 512x512 — and does it again for the next pair, so the whole
8962        // batch streams out of the shared cache once per row. Measured
8963        // 800 GB/s of it, flat across batch sizes, which is the signature
8964        // of a loop bound by traffic rather than by arithmetic. A panel of
8965        // 256 columns is 590 KB beside 221 KB of this worker's weights:
8966        // both stay resident and the batch crosses L3 once instead of
8967        // once per row.
8968        let panel_cols = q4tp_panel_cols(cols);
8969        let run = |start: usize, end: usize| {
8970            for abase in (0..acts.len()).step_by(panel_cols) {
8971                let alen = (acts.len() - abase).min(panel_cols);
8972                let mut sc = vec![0f32; gpr];
8973                #[cfg(target_arch = "x86_64")]
8974                let mut r_lo = start;
8975                #[cfg(target_arch = "x86_64")]
8976                if blocked_ok && alen >= 8 {
8977                    let mut sc1 = vec![0f32; gpr];
8978                    while r_lo + 2 <= end {
8979                        v.scales_into(r_lo, gpr, &mut sc);
8980                        v.scales_into(r_lo + 1, gpr, &mut sc1);
8981                        let mut bi = 0usize;
8982                        while bi + 8 <= alen {
8983                            let xs = [
8984                                acts[abase + bi].xq.as_slice(),
8985                                acts[abase + bi + 1].xq.as_slice(),
8986                                acts[abase + bi + 2].xq.as_slice(),
8987                                acts[abase + bi + 3].xq.as_slice(),
8988                                acts[abase + bi + 4].xq.as_slice(),
8989                                acts[abase + bi + 5].xq.as_slice(),
8990                                acts[abase + bi + 6].xq.as_slice(),
8991                                acts[abase + bi + 7].xq.as_slice(),
8992                            ];
8993                            let d = unsafe { dot_q4tp_2x8_avx512(v.nib, r_lo, gpr, xs, &sc, &sc1) };
8994                            for (row, dr, scr) in [(r_lo, &d[0], &sc), (r_lo + 1, &d[1], &sc1)] {
8995                                for k in 0..8 {
8996                                    let act = &acts[abase + bi + k];
8997                                    let mut acc = dr[k] * act.sx;
8998                                    for &(j, xv) in &act.outliers {
8999                                        let (w, s) = q4tp_outlier(v.nib, row, gpr, j, scr);
9000                                        acc += w * s * xv;
9001                                    }
9002                                    // SAFETY: disjoint (bi, r) cells per worker.
9003                                    unsafe { *out_addr.at((abase + bi + k) * rows + row) = acc };
9004                                }
9005                            }
9006                            bi += 8;
9007                        }
9008                        // Columns past the last group of eight, both rows —
9009                        // the same single-row kernel the tail below uses.
9010                        for row in [r_lo, r_lo + 1] {
9011                            let scr: &[f32] = if row == r_lo { &sc } else { &sc1 };
9012                            for b2 in bi..alen {
9013                                let act = &acts[abase + b2];
9014                                let xs4 = [
9015                                    act.xq.as_slice(),
9016                                    act.xq.as_slice(),
9017                                    act.xq.as_slice(),
9018                                    act.xq.as_slice(),
9019                                ];
9020                                let d =
9021                                    unsafe { dot_q4tp_row_1x4_avx512(v.nib, row, gpr, xs4, scr) };
9022                                let mut acc = d[0] * act.sx;
9023                                for &(j, xv) in &act.outliers {
9024                                    let (w, s) = q4tp_outlier(v.nib, row, gpr, j, scr);
9025                                    acc += w * s * xv;
9026                                }
9027                                // SAFETY: disjoint (bi, r) cells per worker.
9028                                unsafe { *out_addr.at((abase + b2) * rows + row) = acc };
9029                            }
9030                        }
9031                        r_lo += 2;
9032                    }
9033                }
9034                // AVX2 without VNNI, a batch that need not be row-exact:
9035                // two rows against four columns with FMA
9036                // (`q4tp_matmat_2rows_fma`); an odd last row falls to the
9037                // vertical cell below.
9038                #[cfg(target_arch = "x86_64")]
9039                if !blocked_ok
9040                    && !exact
9041                    && alen >= 4
9042                    && q4tp_fma_x86()
9043                    && acts[abase..abase + alen].iter().all(|a| a.xg8.len() == gpr)
9044                {
9045                    let mut sc1 = vec![0f32; gpr];
9046                    while r_lo + 2 <= end {
9047                        v.scales_into(r_lo, gpr, &mut sc);
9048                        v.scales_into(r_lo + 1, gpr, &mut sc1);
9049                        // SAFETY: AVX2+FMA checked; cells disjoint per
9050                        // (worker, bi, r).
9051                        unsafe {
9052                            q4tp_matmat_2rows_fma(
9053                                &v,
9054                                r_lo,
9055                                gpr,
9056                                &acts[abase..abase + alen],
9057                                &sc,
9058                                &sc1,
9059                                abase,
9060                                rows,
9061                                out_addr,
9062                            )
9063                        };
9064                        r_lo += 2;
9065                    }
9066                }
9067                #[cfg(target_arch = "x86_64")]
9068                let row_start = r_lo;
9069                #[cfg(not(target_arch = "x86_64"))]
9070                let row_start = start;
9071                for r in row_start..end {
9072                    v.scales_into(r, gpr, &mut sc);
9073                    let mut bi = 0usize;
9074                    #[cfg(target_arch = "x86_64")]
9075                    if blocked_ok {
9076                        while bi + 8 <= alen {
9077                            let xs = [
9078                                acts[abase + bi].xq.as_slice(),
9079                                acts[abase + bi + 1].xq.as_slice(),
9080                                acts[abase + bi + 2].xq.as_slice(),
9081                                acts[abase + bi + 3].xq.as_slice(),
9082                                acts[abase + bi + 4].xq.as_slice(),
9083                                acts[abase + bi + 5].xq.as_slice(),
9084                                acts[abase + bi + 6].xq.as_slice(),
9085                                acts[abase + bi + 7].xq.as_slice(),
9086                            ];
9087                            let d = unsafe { dot_q4tp_row_1x8_avx512(v.nib, r, gpr, xs, &sc) };
9088                            for k in 0..8 {
9089                                let act = &acts[abase + bi + k];
9090                                let mut acc = d[k] * act.sx;
9091                                for &(j, xv) in &act.outliers {
9092                                    let (w, s) = q4tp_outlier(v.nib, r, gpr, j, &sc);
9093                                    acc += w * s * xv;
9094                                }
9095                                // SAFETY: disjoint (bi, r) cells per worker.
9096                                unsafe { *out_addr.at((abase + bi + k) * rows + r) = acc };
9097                            }
9098                            bi += 8;
9099                        }
9100                        while bi + 4 <= alen {
9101                            let xs = [
9102                                acts[abase + bi].xq.as_slice(),
9103                                acts[abase + bi + 1].xq.as_slice(),
9104                                acts[abase + bi + 2].xq.as_slice(),
9105                                acts[abase + bi + 3].xq.as_slice(),
9106                            ];
9107                            let d = unsafe { dot_q4tp_row_1x4_avx512(v.nib, r, gpr, xs, &sc) };
9108                            for k in 0..4 {
9109                                let act = &acts[abase + bi + k];
9110                                let mut acc = d[k] * act.sx;
9111                                for &(j, xv) in &act.outliers {
9112                                    let (w, s) = q4tp_outlier(v.nib, r, gpr, j, &sc);
9113                                    acc += w * s * xv;
9114                                }
9115                                // SAFETY: disjoint (bi, r) cells per worker.
9116                                unsafe { *out_addr.at((abase + bi + k) * rows + r) = acc };
9117                            }
9118                            bi += 4;
9119                        }
9120                    }
9121                    #[cfg(target_arch = "aarch64")]
9122                    if blocked_ok {
9123                        while bi + 4 <= alen {
9124                            let xs = [
9125                                acts[abase + bi].xq.as_slice(),
9126                                acts[abase + bi + 1].xq.as_slice(),
9127                                acts[abase + bi + 2].xq.as_slice(),
9128                                acts[abase + bi + 3].xq.as_slice(),
9129                            ];
9130                            let d = unsafe {
9131                                if exact || q4tp_v1() {
9132                                    dot_q4tp_row_1x4_sdot_v1(v.nib, r, gpr, xs, &sc)
9133                                } else {
9134                                    dot_q4tp_row_1x4_sdot(v.nib, r, gpr, xs, &sc)
9135                                }
9136                            };
9137                            for k in 0..4 {
9138                                let act = &acts[abase + bi + k];
9139                                let mut acc = d[k] * act.sx;
9140                                for &(j, xv) in &act.outliers {
9141                                    let (w, s) = q4tp_outlier(v.nib, r, gpr, j, &sc);
9142                                    acc += w * s * xv;
9143                                }
9144                                // SAFETY: disjoint (bi, r) cells per worker.
9145                                unsafe { *out_addr.at((abase + bi + k) * rows + r) = acc };
9146                            }
9147                            bi += 4;
9148                        }
9149                    }
9150                    let _ = blocked_ok;
9151                    // AVX2: the vertical column panel shares each group's
9152                    // unpack across four columns and keeps the row-exact
9153                    // cell bits (see `q4tp_matmat_row_cols_v`). Falls
9154                    // through to the single-column loop only when a column
9155                    // lacks its per-group correction.
9156                    #[cfg(target_arch = "x86_64")]
9157                    if acts[abase..abase + alen]
9158                        .iter()
9159                        .all(|a| a.xg8.len() == gpr)
9160                    {
9161                        // SAFETY: a8w8 implies AVX2; cells stay disjoint
9162                        // per (worker, bi, r).
9163                        unsafe {
9164                            q4tp_matmat_row_cols_v(
9165                                &v,
9166                                r,
9167                                gpr,
9168                                &acts[abase + bi..abase + alen],
9169                                &sc,
9170                                abase + bi,
9171                                rows,
9172                                out_addr,
9173                            )
9174                        };
9175                        bi = alen;
9176                    }
9177                    while bi < alen {
9178                        let act = &acts[abase + bi];
9179                        let mut acc = dot_q4tp_row_i8(v.nib, r, gpr, &act.xq, &sc) * act.sx;
9180                        for &(j, xv) in &act.outliers {
9181                            let (w, s) = q4tp_outlier(v.nib, r, gpr, j, &sc);
9182                            acc += w * s * xv;
9183                        }
9184                        // SAFETY: disjoint (bi, r) cells per worker range.
9185                        unsafe { *out_addr.at((abase + bi) * rows + r) = acc };
9186                        bi += 1;
9187                    }
9188                }
9189            }
9190        };
9191        dispatch_rows(pool, rows, &run);
9192        return;
9193    }
9194
9195    let run = |start: usize, end: usize| {
9196        let mut sc = vec![0f32; gpr];
9197        for r in start..end {
9198            v.scales_into(r, gpr, &mut sc);
9199            for bi in 0..b {
9200                let x = &xs_all[bi * cols..(bi + 1) * cols];
9201                // SAFETY: disjoint (bi, r) cells per worker range.
9202                unsafe { *out_addr.at(bi * rows + r) = q4tp_row_exact(v.nib, r, gpr, x, &sc) };
9203            }
9204        }
9205    };
9206    dispatch_rows(pool, rows, &run);
9207}
9208
9209/// Fused q4_tiled matvec (dispatch mirrors `q4matvec`).
9210fn q4t_matvec(
9211    bytes: &[u8],
9212    x: &[f32],
9213    rows: usize,
9214    cols: usize,
9215    out: &mut [f32],
9216    pool: Option<&Pool>,
9217) {
9218    debug_assert_eq!(out.len(), rows);
9219    let gpr = cols / GROUP_SIZE;
9220    let out_addr = SendMut(out.as_mut_ptr());
9221    if a8w8_enabled() {
9222        let act = split_act(x);
9223        let run = move |start: usize, end: usize| {
9224            for r in start..end {
9225                let mut acc = dot_q4t_row_i8(bytes, r, gpr, &act.xq) * act.sx;
9226                for &(j, xv) in &act.outliers {
9227                    let (w, s) = q4t_outlier(bytes, r, gpr, j);
9228                    acc += w * s * xv;
9229                }
9230                // SAFETY: disjoint row ranges per worker.
9231                unsafe { *out_addr.at(r) = acc };
9232            }
9233        };
9234        dispatch_rows(pool, rows, &run);
9235        return;
9236    }
9237    let run = move |start: usize, end: usize| {
9238        for r in start..end {
9239            // SAFETY: disjoint row ranges per worker.
9240            unsafe { *out_addr.at(r) = q4t_row_exact(bytes, r, gpr, x) };
9241        }
9242    };
9243    dispatch_rows(pool, rows, &run);
9244}
9245
9246/// Fused two-input q4_tiled matvec (weights read once per pair).
9247#[allow(clippy::too_many_arguments)]
9248fn q4t_matvec2(
9249    bytes: &[u8],
9250    x1: &[f32],
9251    x2: &[f32],
9252    rows: usize,
9253    cols: usize,
9254    o1: &mut [f32],
9255    o2: &mut [f32],
9256    pool: Option<&Pool>,
9257) {
9258    let gpr = cols / GROUP_SIZE;
9259    let p1 = SendMut(o1.as_mut_ptr());
9260    let p2 = SendMut(o2.as_mut_ptr());
9261    if a8w8_enabled() {
9262        let a1 = split_act(x1);
9263        let a2 = split_act(x2);
9264        let run = move |start: usize, end: usize| {
9265            for r in start..end {
9266                let mut v1 = dot_q4t_row_i8(bytes, r, gpr, &a1.xq) * a1.sx;
9267                let mut v2 = dot_q4t_row_i8(bytes, r, gpr, &a2.xq) * a2.sx;
9268                for &(j, xv) in &a1.outliers {
9269                    let (w, s) = q4t_outlier(bytes, r, gpr, j);
9270                    v1 += w * s * xv;
9271                }
9272                for &(j, xv) in &a2.outliers {
9273                    let (w, s) = q4t_outlier(bytes, r, gpr, j);
9274                    v2 += w * s * xv;
9275                }
9276                // SAFETY: disjoint row ranges per worker.
9277                unsafe {
9278                    *p1.at(r) = v1;
9279                    *p2.at(r) = v2;
9280                }
9281            }
9282        };
9283        dispatch_rows(pool, rows, &run);
9284        return;
9285    }
9286    let run = move |start: usize, end: usize| {
9287        for r in start..end {
9288            // SAFETY: disjoint row ranges per worker.
9289            unsafe {
9290                *p1.at(r) = q4t_row_exact(bytes, r, gpr, x1);
9291                *p2.at(r) = q4t_row_exact(bytes, r, gpr, x2);
9292            }
9293        }
9294    };
9295    dispatch_rows(pool, rows, &run);
9296}
9297
9298/// Batched q4_tiled matmat: each row's tiles stream once per microbatch.
9299#[allow(clippy::too_many_arguments)]
9300/// Prefill GEMM through Accelerate for group-quantized codecs: a
9301/// caller-supplied row dequantizer fills f32 tiles (pool-parallel) and
9302/// each tile rides the AMX with one sgemm — the generic sibling of
9303/// `qmatmat_accel` (q8). Numerics are f32-GEMM (tolerance class);
9304/// decode (b=1) never takes this path.
9305#[cfg(target_os = "macos")]
9306fn dequant_matmat_accel(
9307    dequant_row: &(dyn Fn(usize, &mut [f32]) + Sync),
9308    xs_all: &[f32],
9309    b: usize,
9310    rows: usize,
9311    cols: usize,
9312    out: &mut [f32],
9313    pool: Option<&Pool>,
9314) {
9315    const TR: usize = 2048;
9316    thread_local! {
9317        static WTILE: std::cell::RefCell<Vec<f32>> = const { std::cell::RefCell::new(Vec::new()) };
9318    }
9319    WTILE.with(|wt| {
9320        let mut wtile = wt.borrow_mut();
9321        wtile.resize(TR * cols, 0.0);
9322        let mut r0 = 0usize;
9323        while r0 < rows {
9324            let tr = TR.min(rows - r0);
9325            let wt_addr = SendMut(wtile.as_mut_ptr());
9326            let run = |start: usize, end: usize| {
9327                for r in start..end {
9328                    // SAFETY: workers cover disjoint r ranges.
9329                    let dst = unsafe { std::slice::from_raw_parts_mut(wt_addr.at(r * cols), cols) };
9330                    dequant_row(r0 + r, dst);
9331                }
9332            };
9333            dispatch_rows(pool, tr, &run);
9334            unsafe {
9335                accel_blas::cblas_sgemm(
9336                    101, // RowMajor
9337                    111, // NoTrans A
9338                    112, // Trans B
9339                    b as i32,
9340                    tr as i32,
9341                    cols as i32,
9342                    1.0,
9343                    xs_all.as_ptr(),
9344                    cols as i32,
9345                    wtile.as_ptr(),
9346                    cols as i32,
9347                    0.0,
9348                    out.as_mut_ptr().add(r0),
9349                    rows as i32,
9350                );
9351            }
9352            r0 += tr;
9353        }
9354    });
9355}
9356
9357fn q4t_matmat(
9358    bytes: &[u8],
9359    xs_all: &[f32],
9360    b: usize,
9361    rows: usize,
9362    cols: usize,
9363    out: &mut [f32],
9364    pool: Option<&Pool>,
9365) {
9366    debug_assert_eq!(out.len(), b * rows);
9367    let gpr = cols / GROUP_SIZE;
9368    // Wide batches ride the AMX like q8's qmatmat: on Apple silicon
9369    // the dequant-tile sgemm is an order above the SDOT row loop for
9370    // prefill shapes (imagegen DiT forwards are exactly this).
9371    #[cfg(target_os = "macos")]
9372    if b >= 8 && rows * cols >= 500_000 && accel_gemm_enabled() {
9373        dequant_matmat_accel(
9374            &|r, dst| {
9375                for gi in 0..gpr {
9376                    let tile = &bytes[(r * gpr + gi) * Q4_TILE..(r * gpr + gi + 1) * Q4_TILE];
9377                    let s = f16_to_f32(u16::from_le_bytes([tile[0], tile[1]]));
9378                    for (k, &bb) in tile[2..].iter().enumerate() {
9379                        dst[gi * GROUP_SIZE + k * 2] = ((bb & 0x0F) as f32 - 8.0) * s;
9380                        dst[gi * GROUP_SIZE + k * 2 + 1] = (((bb >> 4) & 0x0F) as f32 - 8.0) * s;
9381                    }
9382                }
9383            },
9384            xs_all,
9385            b,
9386            rows,
9387            cols,
9388            out,
9389            pool,
9390        );
9391        return;
9392    }
9393    let out_addr = SendMut(out.as_mut_ptr());
9394    if a8w8_enabled() {
9395        let acts: Vec<SplitAct> = (0..b)
9396            .map(|bi| split_act(&xs_all[bi * cols..(bi + 1) * cols]))
9397            .collect();
9398        let acts = &acts;
9399        #[cfg(target_arch = "x86_64")]
9400        let blocked_ok = avx2_enabled() && blocked_enabled();
9401        #[cfg(target_arch = "aarch64")]
9402        let blocked_ok = sdot_enabled() && blocked_enabled();
9403        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
9404        let blocked_ok = false;
9405        let run = move |start: usize, end: usize| {
9406            for r in start..end {
9407                let mut bi = 0usize;
9408                #[cfg(target_arch = "aarch64")]
9409                if blocked_ok {
9410                    while bi + 4 <= acts.len() {
9411                        let xs = [
9412                            acts[bi].xq.as_slice(),
9413                            acts[bi + 1].xq.as_slice(),
9414                            acts[bi + 2].xq.as_slice(),
9415                            acts[bi + 3].xq.as_slice(),
9416                        ];
9417                        let d = unsafe { dot_q4t_row_1x4_sdot(bytes, r, gpr, xs) };
9418                        for k in 0..4 {
9419                            let act = &acts[bi + k];
9420                            let mut acc = d[k] * act.sx;
9421                            for &(j, xv) in &act.outliers {
9422                                let (w, sc) = q4t_outlier(bytes, r, gpr, j);
9423                                acc += w * sc * xv;
9424                            }
9425                            // SAFETY: disjoint (bi, r) cells per worker.
9426                            unsafe { *out_addr.at((bi + k) * rows + r) = acc };
9427                        }
9428                        bi += 4;
9429                    }
9430                }
9431                #[cfg(target_arch = "x86_64")]
9432                if blocked_ok {
9433                    while bi + 4 <= acts.len() {
9434                        let xs = [
9435                            acts[bi].xq.as_slice(),
9436                            acts[bi + 1].xq.as_slice(),
9437                            acts[bi + 2].xq.as_slice(),
9438                            acts[bi + 3].xq.as_slice(),
9439                        ];
9440                        let d = unsafe {
9441                            if vnni_tiles_enabled() {
9442                                dot_q4t_row_1x4_vnni(bytes, r, gpr, xs)
9443                            } else {
9444                                dot_q4t_row_1x4_avx2(bytes, r, gpr, xs)
9445                            }
9446                        };
9447                        for k in 0..4 {
9448                            let act = &acts[bi + k];
9449                            let mut acc = d[k] * act.sx;
9450                            for &(j, xv) in &act.outliers {
9451                                let (w, sc) = q4t_outlier(bytes, r, gpr, j);
9452                                acc += w * sc * xv;
9453                            }
9454                            // SAFETY: disjoint (bi, r) cells per worker.
9455                            unsafe { *out_addr.at((bi + k) * rows + r) = acc };
9456                        }
9457                        bi += 4;
9458                    }
9459                }
9460                let _ = blocked_ok;
9461                while bi < acts.len() {
9462                    let act = &acts[bi];
9463                    let mut acc = dot_q4t_row_i8(bytes, r, gpr, &act.xq) * act.sx;
9464                    for &(j, xv) in &act.outliers {
9465                        let (w, s) = q4t_outlier(bytes, r, gpr, j);
9466                        acc += w * s * xv;
9467                    }
9468                    // SAFETY: disjoint (bi, r) cells per worker range.
9469                    unsafe { *out_addr.at(bi * rows + r) = acc };
9470                    bi += 1;
9471                }
9472            }
9473        };
9474        dispatch_rows(pool, rows, &run);
9475        return;
9476    }
9477    let run = move |start: usize, end: usize| {
9478        for r in start..end {
9479            for bi in 0..b {
9480                let x = &xs_all[bi * cols..(bi + 1) * cols];
9481                // SAFETY: disjoint (bi, r) cells per worker range.
9482                unsafe { *out_addr.at(bi * rows + r) = q4t_row_exact(bytes, r, gpr, x) };
9483            }
9484        }
9485    };
9486    dispatch_rows(pool, rows, &run);
9487}
9488
9489// ── q1 (dtype 12): binary weights, [f16 scale][4B sign bits] per
9490// 32-group tile. The kernel family mirrors q4_tiled: one sequential
9491// stream of 6-byte tiles, per-tile integer dot × scale, exact outlier
9492// correction (A8W8 contract), exact scalar path under CMF_SDOT=0. ──
9493
9494/// Per-32-group sums of the quantized activation — the ±1 identity's
9495/// shared half: `dot = −2·sdot(mask, x) − gsum[g]`, computed ONCE per
9496/// matvec and reused by every row.
9497fn q1_group_sums(xq: &[i8], gpr: usize) -> Vec<i32> {
9498    (0..gpr)
9499        .map(|gi| {
9500            xq[gi * GROUP_SIZE..(gi + 1) * GROUP_SIZE]
9501                .iter()
9502                .map(|&v| v as i32)
9503                .sum()
9504        })
9505        .collect()
9506}
9507
9508/// One q1 row via the A8W8 int8 path — mask-SDOT on ARM (no ±1
9509/// expansion at all), scalar bit loop elsewhere (AVX2 queued with the
9510/// x86 pass).
9511#[inline]
9512#[allow(unreachable_code)]
9513/// AVX2 q1 row via the same ±1 identity as the ARM sdot kernel: the
9514/// sign bits expand to a {0, −1} byte mask through shuffle+cmpeq, the
9515/// masked activation sums through maddubs(1, x&mask), and
9516/// `dot = −(2·masked_sum + Σx_group)` — bit-identical integer math.
9517#[cfg(target_arch = "x86_64")]
9518#[target_feature(enable = "avx2")]
9519unsafe fn dot_q1_row_avx2(bytes: &[u8], r: usize, gpr: usize, xq: &[i8], gsum: &[i32]) -> f32 {
9520    // SAFETY: callers uphold the 6B-tile and xq/gsum length contracts.
9521    unsafe {
9522        use core::arch::x86_64::*;
9523        // Byte j of the mask must replicate bits-byte j/8.
9524        let expand = _mm256_setr_epi8(
9525            0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3,
9526            3, 3, 3,
9527        );
9528        let bitsel = _mm256_setr_epi8(
9529            1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64,
9530            -128, 1, 2, 4, 8, 16, 32, 64, -128,
9531        );
9532        let ones8 = _mm256_set1_epi8(1);
9533        let ones16 = _mm256_set1_epi16(1);
9534        let mut acc = 0f32;
9535        for gi in 0..gpr {
9536            let t = bytes.as_ptr().add((r * gpr + gi) * Q1_TILE);
9537            let s = f16_to_f32(u16::from_le_bytes([*t, *t.add(1)]));
9538            let bits = u32::from_le_bytes([*t.add(2), *t.add(3), *t.add(4), *t.add(5)]);
9539            let bc = _mm256_shuffle_epi8(_mm256_set1_epi32(bits as i32), expand);
9540            let mask = _mm256_cmpeq_epi8(_mm256_and_si256(bc, bitsel), bitsel);
9541            let x = _mm256_loadu_si256(xq.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
9542            let sel = _mm256_and_si256(x, mask);
9543            // Σ of selected i8 lanes: maddubs(1u8, sel_i8) pairs → madd.
9544            let p16 = _mm256_maddubs_epi16(ones8, sel);
9545            let d32 = _mm256_madd_epi16(p16, ones16);
9546            let hi128 = _mm256_extracti128_si256::<1>(d32);
9547            let s128 = _mm_add_epi32(_mm256_castsi256_si128(d32), hi128);
9548            let s64 = _mm_add_epi32(s128, _mm_srli_si128::<8>(s128));
9549            let s32 = _mm_add_epi32(s64, _mm_srli_si128::<4>(s64));
9550            let msum = _mm_cvtsi128_si32(s32);
9551            // The and-select keeps x UN-negated (unlike ARM's −1-mask
9552            // sdot): d = Σ_set − Σ_unset = 2·Σ_set − Σ_all.
9553            let d = 2 * msum - gsum[gi];
9554            acc += d as f32 * s;
9555        }
9556        acc
9557    }
9558}
9559
9560/// VNNI twin of `dot_q1_row_avx2`: the masked-select sum goes through
9561/// one `vpdpbusd(1u8, sel)` (see `dpbusd_hsum` — bit-identical).
9562#[cfg(target_arch = "x86_64")]
9563#[target_feature(enable = "avx2,avx512f,avx512bw,avx512vl,avx512vnni")]
9564unsafe fn dot_q1_row_vnni(bytes: &[u8], r: usize, gpr: usize, xq: &[i8], gsum: &[i32]) -> f32 {
9565    // SAFETY: callers uphold the 6B-tile and xq/gsum length contracts.
9566    unsafe {
9567        use core::arch::x86_64::*;
9568        let expand = _mm256_setr_epi8(
9569            0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3,
9570            3, 3, 3,
9571        );
9572        let bitsel = _mm256_setr_epi8(
9573            1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64,
9574            -128, 1, 2, 4, 8, 16, 32, 64, -128,
9575        );
9576        let ones8 = _mm256_set1_epi8(1);
9577        let mut acc = 0f32;
9578        for gi in 0..gpr {
9579            let t = bytes.as_ptr().add((r * gpr + gi) * Q1_TILE);
9580            let s = f16_to_f32(u16::from_le_bytes([*t, *t.add(1)]));
9581            let bits = u32::from_le_bytes([*t.add(2), *t.add(3), *t.add(4), *t.add(5)]);
9582            let bc = _mm256_shuffle_epi8(_mm256_set1_epi32(bits as i32), expand);
9583            let mask = _mm256_cmpeq_epi8(_mm256_and_si256(bc, bitsel), bitsel);
9584            let x = _mm256_loadu_si256(xq.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
9585            let msum = dpbusd_hsum(ones8, _mm256_and_si256(x, mask));
9586            let d = 2 * msum - gsum[gi];
9587            acc += d as f32 * s;
9588        }
9589        acc
9590    }
9591}
9592
9593/// VNNI twin of `dot_q1_row_1x4_avx2` (see `dpbusd_hsum`).
9594#[cfg(target_arch = "x86_64")]
9595#[target_feature(enable = "avx2,avx512f,avx512bw,avx512vl,avx512vnni")]
9596unsafe fn dot_q1_row_1x4_vnni(
9597    bytes: &[u8],
9598    r: usize,
9599    gpr: usize,
9600    xs: [&[i8]; 4],
9601    gsums: [&[i32]; 4],
9602) -> [f32; 4] {
9603    // SAFETY: callers uphold the 6B-tile and xq/gsum length contracts.
9604    unsafe {
9605        use core::arch::x86_64::*;
9606        let expand = _mm256_setr_epi8(
9607            0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3,
9608            3, 3, 3,
9609        );
9610        let bitsel = _mm256_setr_epi8(
9611            1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64,
9612            -128, 1, 2, 4, 8, 16, 32, 64, -128,
9613        );
9614        let ones8 = _mm256_set1_epi8(1);
9615        let mut acc = [0f32; 4];
9616        for gi in 0..gpr {
9617            let t = bytes.as_ptr().add((r * gpr + gi) * Q1_TILE);
9618            let s = f16_to_f32(u16::from_le_bytes([*t, *t.add(1)]));
9619            let bits = u32::from_le_bytes([*t.add(2), *t.add(3), *t.add(4), *t.add(5)]);
9620            let bc = _mm256_shuffle_epi8(_mm256_set1_epi32(bits as i32), expand);
9621            let mask = _mm256_cmpeq_epi8(_mm256_and_si256(bc, bitsel), bitsel);
9622            for (k, xq) in xs.iter().enumerate() {
9623                let x = _mm256_loadu_si256(xq.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
9624                let msum = dpbusd_hsum(ones8, _mm256_and_si256(x, mask));
9625                let d = 2 * msum - gsums[k][gi];
9626                acc[k] += d as f32 * s;
9627            }
9628        }
9629        acc
9630    }
9631}
9632
9633/// The blocked 1×4 flavor: the expanded bit mask serves four activation
9634/// streams per group (mask build once, four select+reduce chains).
9635#[cfg(target_arch = "x86_64")]
9636#[target_feature(enable = "avx2")]
9637unsafe fn dot_q1_row_1x4_avx2(
9638    bytes: &[u8],
9639    r: usize,
9640    gpr: usize,
9641    xs: [&[i8]; 4],
9642    gsums: [&[i32]; 4],
9643) -> [f32; 4] {
9644    // SAFETY: callers uphold the 6B-tile and xq/gsum length contracts.
9645    unsafe {
9646        use core::arch::x86_64::*;
9647        let expand = _mm256_setr_epi8(
9648            0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3,
9649            3, 3, 3,
9650        );
9651        let bitsel = _mm256_setr_epi8(
9652            1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64,
9653            -128, 1, 2, 4, 8, 16, 32, 64, -128,
9654        );
9655        let ones8 = _mm256_set1_epi8(1);
9656        let ones16 = _mm256_set1_epi16(1);
9657        let mut acc = [0f32; 4];
9658        for gi in 0..gpr {
9659            let t = bytes.as_ptr().add((r * gpr + gi) * Q1_TILE);
9660            let s = f16_to_f32(u16::from_le_bytes([*t, *t.add(1)]));
9661            let bits = u32::from_le_bytes([*t.add(2), *t.add(3), *t.add(4), *t.add(5)]);
9662            let bc = _mm256_shuffle_epi8(_mm256_set1_epi32(bits as i32), expand);
9663            let mask = _mm256_cmpeq_epi8(_mm256_and_si256(bc, bitsel), bitsel);
9664            for (k, xq) in xs.iter().enumerate() {
9665                let x = _mm256_loadu_si256(xq.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
9666                let sel = _mm256_and_si256(x, mask);
9667                let p16 = _mm256_maddubs_epi16(ones8, sel);
9668                let d32 = _mm256_madd_epi16(p16, ones16);
9669                let hi128 = _mm256_extracti128_si256::<1>(d32);
9670                let s128 = _mm_add_epi32(_mm256_castsi256_si128(d32), hi128);
9671                let s64 = _mm_add_epi32(s128, _mm_srli_si128::<8>(s128));
9672                let s32 = _mm_add_epi32(s64, _mm_srli_si128::<4>(s64));
9673                let msum = _mm_cvtsi128_si32(s32);
9674                let d = 2 * msum - gsums[k][gi];
9675                acc[k] += d as f32 * s;
9676            }
9677        }
9678        acc
9679    }
9680}
9681
9682#[allow(unreachable_code)]
9683fn dot_q1_row_i8(bytes: &[u8], r: usize, gpr: usize, xq: &[i8], gsum: &[i32]) -> f32 {
9684    #[cfg(target_arch = "aarch64")]
9685    unsafe {
9686        return dot_q1_row_sdot(bytes, r, gpr, xq, gsum);
9687    }
9688    #[cfg(target_arch = "x86_64")]
9689    if avx2_enabled() {
9690        unsafe {
9691            if vnni_tiles_enabled() {
9692                return dot_q1_row_vnni(bytes, r, gpr, xq, gsum);
9693            }
9694            return dot_q1_row_avx2(bytes, r, gpr, xq, gsum);
9695        }
9696    }
9697    let _ = gsum;
9698    let mut acc = 0f32;
9699    for gi in 0..gpr {
9700        let tile = &bytes[(r * gpr + gi) * Q1_TILE..(r * gpr + gi + 1) * Q1_TILE];
9701        let s = f16_to_f32(u16::from_le_bytes([tile[0], tile[1]]));
9702        let mut d = 0i32;
9703        for (j, &b) in tile[2..].iter().enumerate() {
9704            for k in 0..8 {
9705                let w = ((b >> k) & 1) as i32 * 2 - 1;
9706                d += w * xq[gi * GROUP_SIZE + j * 8 + k] as i32;
9707            }
9708        }
9709        acc += d as f32 * s;
9710    }
9711    acc
9712}
9713
9714/// SDOT q1 row via the ±1 identity: the vtst mask (0xFF where the bit
9715/// is set, i.e. −1 as i8) feeds `sdot` DIRECTLY — no expansion to ±1
9716/// lanes at all — and `dot = −(2·sdot(mask, x) + Σx_group)`, with the
9717/// per-group activation sums shared across every row of the matvec.
9718/// Four tiles (128 weights) per iteration: integer dots reduce through
9719/// a vpaddq tree into ONE i32x4 that meets its four scales in a single
9720/// fused f32 multiply-add. Integer math throughout — bit-identical to
9721/// the scalar ±1 reference.
9722#[cfg(target_arch = "aarch64")]
9723#[target_feature(enable = "neon,dotprod")]
9724unsafe fn dot_q1_row_sdot(bytes: &[u8], r: usize, gpr: usize, xq: &[i8], gsum: &[i32]) -> f32 {
9725    // SAFETY: callers uphold slice-length contracts (6B tile per group,
9726    // xq.len() == gpr·GROUP_SIZE, gsum.len() == gpr).
9727    unsafe {
9728        use core::arch::aarch64::*;
9729        use core::arch::asm;
9730        const MASKS: [u8; 16] = [1, 2, 4, 8, 16, 32, 64, 128, 1, 2, 4, 8, 16, 32, 64, 128];
9731        let m = vld1q_u8(MASKS.as_ptr());
9732        // One tile's −Σ_set(x) as an UNREDUCED i32x4 (two mask-sdots).
9733        macro_rules! tile_dot {
9734            ($t:expr, $x:expr) => {{
9735                let v0 = vcombine_u8(vdup_n_u8(*$t.add(2)), vdup_n_u8(*$t.add(3)));
9736                let v1 = vcombine_u8(vdup_n_u8(*$t.add(4)), vdup_n_u8(*$t.add(5)));
9737                let w0 = vreinterpretq_s8_u8(vtstq_u8(v0, m));
9738                let w1 = vreinterpretq_s8_u8(vtstq_u8(v1, m));
9739                let x0 = vld1q_s8($x);
9740                let x1 = vld1q_s8($x.add(16));
9741                let (mut a0, mut a1) = (vdupq_n_s32(0), vdupq_n_s32(0));
9742                asm!(
9743                    "sdot {a0:v}.4s, {w0:v}.16b, {x0:v}.16b",
9744                    "sdot {a1:v}.4s, {w1:v}.16b, {x1:v}.16b",
9745                    a0 = inout(vreg) a0, a1 = inout(vreg) a1,
9746                    w0 = in(vreg) w0, x0 = in(vreg) x0, w1 = in(vreg) w1, x1 = in(vreg) x1,
9747                    options(pure, nomem, nostack),
9748                );
9749                vaddq_s32(a0, a1)
9750            }};
9751        }
9752        // TBL unpack over PAIR loads: one vld1q covers two 6B tiles
9753        // ([s s b b b b][s s b b b b] + 4B slack), TBL replicates each
9754        // bit-byte across 8 lanes for vtst, and the four scales gather
9755        // through tbl2 into one fcvtl — the 16 ld1r broadcast loads and
9756        // 4 branchy software f16 conversions per 128 weights (the
9757        // measured load-port wall of this kernel) become 2 vector
9758        // loads + 9 table lookups. Integer math order is unchanged —
9759        // bit-identical results (FCVTL is exact on every f16).
9760        const IW00: [u8; 16] = [2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3];
9761        const IW01: [u8; 16] = [4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5];
9762        const IW10: [u8; 16] = [8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9];
9763        const IW11: [u8; 16] = [
9764            10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11,
9765        ];
9766        const ISC: [u8; 8] = [0, 1, 6, 7, 16, 17, 22, 23];
9767        let (iw00, iw01) = (vld1q_u8(IW00.as_ptr()), vld1q_u8(IW01.as_ptr()));
9768        let (iw10, iw11) = (vld1q_u8(IW10.as_ptr()), vld1q_u8(IW11.as_ptr()));
9769        let isc = vld1_u8(ISC.as_ptr());
9770        // One tile's −Σ_set(x) from a TBL-unpacked pair load.
9771        macro_rules! tile_dot_tbl {
9772            ($ld:expr, $i0:expr, $i1:expr, $x:expr) => {{
9773                let w0 = vreinterpretq_s8_u8(vtstq_u8(vqtbl1q_u8($ld, $i0), m));
9774                let w1 = vreinterpretq_s8_u8(vtstq_u8(vqtbl1q_u8($ld, $i1), m));
9775                let x0 = vld1q_s8($x);
9776                let x1 = vld1q_s8($x.add(16));
9777                let (mut a0, mut a1) = (vdupq_n_s32(0), vdupq_n_s32(0));
9778                asm!(
9779                    "sdot {a0:v}.4s, {w0:v}.16b, {x0:v}.16b",
9780                    "sdot {a1:v}.4s, {w1:v}.16b, {x1:v}.16b",
9781                    a0 = inout(vreg) a0, a1 = inout(vreg) a1,
9782                    w0 = in(vreg) w0, x0 = in(vreg) x0, w1 = in(vreg) w1, x1 = in(vreg) x1,
9783                    options(pure, nomem, nostack),
9784                );
9785                vaddq_s32(a0, a1)
9786            }};
9787        }
9788        let base = bytes.as_ptr().add(r * gpr * Q1_TILE);
9789        let row_base = r * gpr * Q1_TILE;
9790        let abs_end = bytes.len();
9791        let xp = xq.as_ptr();
9792        let gp = gsum.as_ptr();
9793        let mut accv = vdupq_n_f32(0.0);
9794        let mut gi = 0;
9795        // The second pair load reads 4B past tile gi+3 — stay inside
9796        // the payload slice (only the file's final tiles fall back).
9797        while gi + 4 <= gpr && row_base + (gi + 4) * Q1_TILE + 4 <= abs_end {
9798            let t0 = base.add(gi * Q1_TILE);
9799            let ld_a = vld1q_u8(t0);
9800            let ld_b = vld1q_u8(t0.add(2 * Q1_TILE));
9801            let d0 = tile_dot_tbl!(ld_a, iw00, iw01, xp.add(gi * GROUP_SIZE));
9802            let d1 = tile_dot_tbl!(ld_a, iw10, iw11, xp.add((gi + 1) * GROUP_SIZE));
9803            let d2 = tile_dot_tbl!(ld_b, iw00, iw01, xp.add((gi + 2) * GROUP_SIZE));
9804            let d3 = tile_dot_tbl!(ld_b, iw10, iw11, xp.add((gi + 3) * GROUP_SIZE));
9805            // [−Σ0, −Σ1, −Σ2, −Σ3] → dots = −(2·Σset_neg + gsum)
9806            let neg = vpaddq_s32(vpaddq_s32(d0, d1), vpaddq_s32(d2, d3));
9807            let g = vld1q_s32(gp.add(gi));
9808            let dots = vnegq_s32(vaddq_s32(vshlq_n_s32::<1>(neg), g));
9809            let sc16 = vqtbl2_u8(uint8x16x2_t(ld_a, ld_b), isc);
9810            let scf: float32x4_t;
9811            asm!(
9812                "fcvtl {o:v}.4s, {i:v}.4h",
9813                o = out(vreg) scf, i = in(vreg) sc16,
9814                options(pure, nomem, nostack),
9815            );
9816            accv = vfmaq_f32(accv, vcvtq_f32_s32(dots), scf);
9817            gi += 4;
9818        }
9819        let mut acc = vaddvq_f32(accv);
9820        while gi < gpr {
9821            let t = base.add(gi * Q1_TILE);
9822            let s = f16_to_f32(u16::from_le_bytes([*t, *t.add(1)]));
9823            let d = vaddvq_s32(tile_dot!(t, xp.add(gi * GROUP_SIZE)));
9824            acc += (-(2 * d + *gp.add(gi))) as f32 * s;
9825            gi += 1;
9826        }
9827        acc
9828    }
9829}
9830
9831/// Blocked q1 1×4: one TBL unpack of the tile pair serves FOUR
9832/// activation streams (prefill amortization — the same idea as the
9833/// AVX2 twin; per stream the group order, fma order and tail match the
9834/// single-row kernel exactly, so batch == matvec bit-for-bit).
9835#[cfg(target_arch = "aarch64")]
9836#[target_feature(enable = "neon,dotprod")]
9837unsafe fn dot_q1_row_1x4_sdot(
9838    bytes: &[u8],
9839    r: usize,
9840    gpr: usize,
9841    xs: [&[i8]; 4],
9842    gs: [&[i32]; 4],
9843) -> [f32; 4] {
9844    // SAFETY: same slice-length contracts as `dot_q1_row_sdot`, ×4.
9845    unsafe {
9846        use core::arch::aarch64::*;
9847        use core::arch::asm;
9848        const MASKS: [u8; 16] = [1, 2, 4, 8, 16, 32, 64, 128, 1, 2, 4, 8, 16, 32, 64, 128];
9849        const IW00: [u8; 16] = [2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3];
9850        const IW01: [u8; 16] = [4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5];
9851        const IW10: [u8; 16] = [8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9];
9852        const IW11: [u8; 16] = [
9853            10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11,
9854        ];
9855        const ISC: [u8; 8] = [0, 1, 6, 7, 16, 17, 22, 23];
9856        let m = vld1q_u8(MASKS.as_ptr());
9857        let (iw00, iw01) = (vld1q_u8(IW00.as_ptr()), vld1q_u8(IW01.as_ptr()));
9858        let (iw10, iw11) = (vld1q_u8(IW10.as_ptr()), vld1q_u8(IW11.as_ptr()));
9859        let isc = vld1_u8(ISC.as_ptr());
9860        macro_rules! sdot2 {
9861            ($w0:expr, $w1:expr, $x:expr) => {{
9862                let x0 = vld1q_s8($x);
9863                let x1 = vld1q_s8($x.add(16));
9864                let (mut a0, mut a1) = (vdupq_n_s32(0), vdupq_n_s32(0));
9865                asm!(
9866                    "sdot {a0:v}.4s, {w0:v}.16b, {x0:v}.16b",
9867                    "sdot {a1:v}.4s, {w1:v}.16b, {x1:v}.16b",
9868                    a0 = inout(vreg) a0, a1 = inout(vreg) a1,
9869                    w0 = in(vreg) $w0, x0 = in(vreg) x0, w1 = in(vreg) $w1, x1 = in(vreg) x1,
9870                    options(pure, nomem, nostack),
9871                );
9872                vaddq_s32(a0, a1)
9873            }};
9874        }
9875        let base = bytes.as_ptr().add(r * gpr * Q1_TILE);
9876        let row_base = r * gpr * Q1_TILE;
9877        let abs_end = bytes.len();
9878        let mut accv = [vdupq_n_f32(0.0); 4];
9879        let mut gi = 0;
9880        while gi + 4 <= gpr && row_base + (gi + 4) * Q1_TILE + 4 <= abs_end {
9881            let t0 = base.add(gi * Q1_TILE);
9882            let ld_a = vld1q_u8(t0);
9883            let ld_b = vld1q_u8(t0.add(2 * Q1_TILE));
9884            // Unpack ONCE — eight ±mask vectors serve all four streams.
9885            let w00 = vreinterpretq_s8_u8(vtstq_u8(vqtbl1q_u8(ld_a, iw00), m));
9886            let w01 = vreinterpretq_s8_u8(vtstq_u8(vqtbl1q_u8(ld_a, iw01), m));
9887            let w10 = vreinterpretq_s8_u8(vtstq_u8(vqtbl1q_u8(ld_a, iw10), m));
9888            let w11 = vreinterpretq_s8_u8(vtstq_u8(vqtbl1q_u8(ld_a, iw11), m));
9889            let w20 = vreinterpretq_s8_u8(vtstq_u8(vqtbl1q_u8(ld_b, iw00), m));
9890            let w21 = vreinterpretq_s8_u8(vtstq_u8(vqtbl1q_u8(ld_b, iw01), m));
9891            let w30 = vreinterpretq_s8_u8(vtstq_u8(vqtbl1q_u8(ld_b, iw10), m));
9892            let w31 = vreinterpretq_s8_u8(vtstq_u8(vqtbl1q_u8(ld_b, iw11), m));
9893            let sc16 = vqtbl2_u8(uint8x16x2_t(ld_a, ld_b), isc);
9894            let scf: float32x4_t;
9895            asm!(
9896                "fcvtl {o:v}.4s, {i:v}.4h",
9897                o = out(vreg) scf, i = in(vreg) sc16,
9898                options(pure, nomem, nostack),
9899            );
9900            for k in 0..4 {
9901                let xp = xs[k].as_ptr();
9902                let d0 = sdot2!(w00, w01, xp.add(gi * GROUP_SIZE));
9903                let d1 = sdot2!(w10, w11, xp.add((gi + 1) * GROUP_SIZE));
9904                let d2 = sdot2!(w20, w21, xp.add((gi + 2) * GROUP_SIZE));
9905                let d3 = sdot2!(w30, w31, xp.add((gi + 3) * GROUP_SIZE));
9906                let neg = vpaddq_s32(vpaddq_s32(d0, d1), vpaddq_s32(d2, d3));
9907                let g = vld1q_s32(gs[k].as_ptr().add(gi));
9908                let dots = vnegq_s32(vaddq_s32(vshlq_n_s32::<1>(neg), g));
9909                accv[k] = vfmaq_f32(accv[k], vcvtq_f32_s32(dots), scf);
9910            }
9911            gi += 4;
9912        }
9913        let mut acc = [
9914            vaddvq_f32(accv[0]),
9915            vaddvq_f32(accv[1]),
9916            vaddvq_f32(accv[2]),
9917            vaddvq_f32(accv[3]),
9918        ];
9919        while gi < gpr {
9920            let t = base.add(gi * Q1_TILE);
9921            let sc = f16_to_f32(u16::from_le_bytes([*t, *t.add(1)]));
9922            let v0 = vcombine_u8(vdup_n_u8(*t.add(2)), vdup_n_u8(*t.add(3)));
9923            let v1 = vcombine_u8(vdup_n_u8(*t.add(4)), vdup_n_u8(*t.add(5)));
9924            let w0 = vreinterpretq_s8_u8(vtstq_u8(v0, m));
9925            let w1 = vreinterpretq_s8_u8(vtstq_u8(v1, m));
9926            for k in 0..4 {
9927                let d = vaddvq_s32(sdot2!(w0, w1, xs[k].as_ptr().add(gi * GROUP_SIZE)));
9928                acc[k] += (-(2 * d + *gs[k].as_ptr().add(gi))) as f32 * sc;
9929            }
9930            gi += 1;
9931        }
9932        acc
9933    }
9934}
9935
9936/// (weight ±1, scale) of one q1 element — the exact outlier term.
9937#[inline]
9938fn q1_outlier(bytes: &[u8], r: usize, gpr: usize, j: usize) -> (f32, f32) {
9939    let gi = j / GROUP_SIZE;
9940    let k = j % GROUP_SIZE;
9941    let tile = &bytes[(r * gpr + gi) * Q1_TILE..(r * gpr + gi + 1) * Q1_TILE];
9942    let s = f16_to_f32(u16::from_le_bytes([tile[0], tile[1]]));
9943    let bit = (tile[2 + k / 8] >> (k % 8)) & 1;
9944    ((bit as i32 * 2 - 1) as f32, s)
9945}
9946
9947/// Exact scalar q1 row (CMF_SDOT=0 contract).
9948#[inline]
9949fn q1_row_exact(bytes: &[u8], r: usize, gpr: usize, x: &[f32]) -> f32 {
9950    let mut acc = 0f32;
9951    for gi in 0..gpr {
9952        let tile = &bytes[(r * gpr + gi) * Q1_TILE..(r * gpr + gi + 1) * Q1_TILE];
9953        let s = f16_to_f32(u16::from_le_bytes([tile[0], tile[1]]));
9954        let xg = &x[gi * GROUP_SIZE..(gi + 1) * GROUP_SIZE];
9955        let mut ga = 0f32;
9956        for (j, &b) in tile[2..].iter().enumerate() {
9957            for k in 0..8 {
9958                ga += (((b >> k) & 1) as f32 * 2.0 - 1.0) * xg[j * 8 + k];
9959            }
9960        }
9961        acc += ga * s;
9962    }
9963    acc
9964}
9965
9966/// One binary-weight row range via A8W8 (the body of `bin_matvec`'s hot
9967/// loop, extracted so multi-matrix jobs drive the same kernel).
9968#[allow(clippy::too_many_arguments)]
9969fn bin_range_a8w8(
9970    w: BinW,
9971    gpr: usize,
9972    act: &SplitAct,
9973    gsum: &[i32],
9974    out: SendMut,
9975    start: usize,
9976    end: usize,
9977) {
9978    for r in start..end {
9979        let mut acc = w.dot_i8(r, gpr, &act.xq, gsum) * act.sx;
9980        for &(j, xv) in &act.outliers {
9981            let (wv, s) = w.outlier(r, gpr, j);
9982            acc += wv * s * xv;
9983        }
9984        // SAFETY: disjoint row ranges per worker.
9985        unsafe { *out.at(r) = acc };
9986    }
9987}
9988
9989/// Exact-scalar binary-weight row range (CMF_SDOT=0 contract).
9990fn bin_range_f32(w: BinW, gpr: usize, x: &[f32], out: SendMut, start: usize, end: usize) {
9991    for r in start..end {
9992        // SAFETY: disjoint row ranges per worker.
9993        unsafe { *out.at(r) = w.row_exact(r, gpr, x) };
9994    }
9995}
9996
9997/// A binary (±s) weight in either of its layouts: `q1` 6-byte tiles, or
9998/// `q1g` planes with one scale per 128-group. The row drivers — matvec,
9999/// matvec2, matmat, the multi-projection job and the fused gate/up pair —
10000/// are written once against this; only the per-row kernels differ, and
10001/// the match costs one predictable branch per row. `gpr` is always the
10002/// row's count of 32-tiles (cols / 32): the activation group sums and the
10003/// tile walk are shared by both layouts.
10004#[derive(Clone, Copy)]
10005pub(crate) enum BinW<'a> {
10006    Q1(&'a [u8]),
10007    Q1g {
10008        bytes: &'a [u8],
10009        /// Byte offset of the f16 scale plane (= rows · cols/8).
10010        sc_off: usize,
10011        /// Row count: the q1 kernels treat the payload's final row
10012        /// specially (see `dot_q1g_row_sdot`), and q1g mirrors that.
10013        rows: usize,
10014    },
10015}
10016
10017impl<'a> BinW<'a> {
10018    fn q1g(bytes: &'a [u8], rows: usize, cols: usize) -> Self {
10019        Self::Q1g {
10020            bytes,
10021            sc_off: cortiq_core::quant::q1g_scale_offset(rows, cols),
10022            rows,
10023        }
10024    }
10025
10026    #[inline]
10027    fn dot_i8(self, r: usize, gpr: usize, xq: &[i8], gsum: &[i32]) -> f32 {
10028        match self {
10029            Self::Q1(b) => dot_q1_row_i8(b, r, gpr, xq, gsum),
10030            Self::Q1g {
10031                bytes,
10032                sc_off,
10033                rows,
10034            } => dot_q1g_row_i8(bytes, sc_off, rows, r, gpr, xq, gsum),
10035        }
10036    }
10037
10038    #[inline]
10039    fn row_exact(self, r: usize, gpr: usize, x: &[f32]) -> f32 {
10040        match self {
10041            Self::Q1(b) => q1_row_exact(b, r, gpr, x),
10042            Self::Q1g { bytes, sc_off, .. } => q1g_row_exact(bytes, sc_off, r, gpr, x),
10043        }
10044    }
10045
10046    #[inline]
10047    fn outlier(self, r: usize, gpr: usize, j: usize) -> (f32, f32) {
10048        match self {
10049            Self::Q1(b) => q1_outlier(b, r, gpr, j),
10050            Self::Q1g { bytes, sc_off, .. } => q1g_outlier(bytes, sc_off, r, gpr, j),
10051        }
10052    }
10053
10054    /// Blocked 1×4 row (one unpack, four activation streams).
10055    ///
10056    /// # Safety
10057    /// The SDOT/dotprod target feature must be present (`sdot_enabled`).
10058    #[cfg(target_arch = "aarch64")]
10059    #[inline]
10060    unsafe fn dot_1x4_sdot(
10061        self,
10062        r: usize,
10063        gpr: usize,
10064        xs: [&[i8]; 4],
10065        gs: [&[i32]; 4],
10066    ) -> [f32; 4] {
10067        // SAFETY: forwarded caller contract.
10068        unsafe {
10069            match self {
10070                Self::Q1(b) => dot_q1_row_1x4_sdot(b, r, gpr, xs, gs),
10071                Self::Q1g {
10072                    bytes,
10073                    sc_off,
10074                    rows,
10075                } => dot_q1g_row_1x4_sdot(bytes, sc_off, rows, r, gpr, xs, gs),
10076            }
10077        }
10078    }
10079
10080    /// Blocked 1×4 row on x86 (VNNI when the tile switch is on).
10081    ///
10082    /// # Safety
10083    /// AVX2 must be present (`avx2_enabled`).
10084    #[cfg(target_arch = "x86_64")]
10085    #[inline]
10086    unsafe fn dot_1x4_x86(self, r: usize, gpr: usize, xs: [&[i8]; 4], gs: [&[i32]; 4]) -> [f32; 4] {
10087        // SAFETY: forwarded caller contract.
10088        unsafe {
10089            match (self, vnni_tiles_enabled()) {
10090                (Self::Q1(b), true) => dot_q1_row_1x4_vnni(b, r, gpr, xs, gs),
10091                (Self::Q1(b), false) => dot_q1_row_1x4_avx2(b, r, gpr, xs, gs),
10092                (Self::Q1g { bytes, sc_off, .. }, true) => {
10093                    dot_q1g_row_1x4_vnni(bytes, sc_off, r, gpr, xs, gs)
10094                }
10095                (Self::Q1g { bytes, sc_off, .. }, false) => {
10096                    dot_q1g_row_1x4_avx2(bytes, sc_off, r, gpr, xs, gs)
10097                }
10098            }
10099        }
10100    }
10101}
10102
10103// ── q1g (dtype 20): binary weights, ONE f16 scale per 128-group, in sign
10104// and scale PLANES (`[bits: rows·cols/8][f16: rows·cols/128]`). Same
10105// kernel family as q1 and — deliberately — the same float accumulation
10106// order (one `acc += d·s` per 32-tile, the group's scale reused four
10107// times), so a q1g repack of a q1 tensor whose tile scales agree gives
10108// the same f32 outputs bit for bit on every path. The win is the stream:
10109// 18 bytes per 128 weights instead of 24, the bits 16-byte aligned. ──
10110
10111/// Sign bits of q1g tile `t` (flat 32-tile index `r·gpr + gi`).
10112#[inline]
10113fn q1g_bits(bytes: &[u8], t: usize) -> u32 {
10114    u32::from_le_bytes([
10115        bytes[t * 4],
10116        bytes[t * 4 + 1],
10117        bytes[t * 4 + 2],
10118        bytes[t * 4 + 3],
10119    ])
10120}
10121
10122/// Raw f16 bits of the scale of the 128-group holding q1g tile `t`.
10123#[inline]
10124fn q1g_scale_bits(bytes: &[u8], sc_off: usize, t: usize) -> u16 {
10125    let o = sc_off + (t / 4) * 2;
10126    u16::from_le_bytes([bytes[o], bytes[o + 1]])
10127}
10128
10129/// One q1g row via the A8W8 int8 path (dispatch twin of `dot_q1_row_i8`).
10130#[allow(unreachable_code)]
10131#[allow(clippy::too_many_arguments)]
10132fn dot_q1g_row_i8(
10133    bytes: &[u8],
10134    sc_off: usize,
10135    rows: usize,
10136    r: usize,
10137    gpr: usize,
10138    xq: &[i8],
10139    gsum: &[i32],
10140) -> f32 {
10141    #[cfg(target_arch = "aarch64")]
10142    unsafe {
10143        return dot_q1g_row_sdot(bytes, sc_off, rows, r, gpr, xq, gsum);
10144    }
10145    #[cfg(target_arch = "x86_64")]
10146    if avx2_enabled() {
10147        unsafe {
10148            if vnni_tiles_enabled() {
10149                return dot_q1g_row_vnni(bytes, sc_off, r, gpr, xq, gsum);
10150            }
10151            return dot_q1g_row_avx2(bytes, sc_off, r, gpr, xq, gsum);
10152        }
10153    }
10154    let _ = (gsum, rows);
10155    let mut acc = 0f32;
10156    for gi in 0..gpr {
10157        let t = r * gpr + gi;
10158        let s = f16_to_f32(q1g_scale_bits(bytes, sc_off, t));
10159        let bits = q1g_bits(bytes, t);
10160        let mut d = 0i32;
10161        for k in 0..GROUP_SIZE {
10162            let w = ((bits >> k) & 1) as i32 * 2 - 1;
10163            d += w * xq[gi * GROUP_SIZE + k] as i32;
10164        }
10165        acc += d as f32 * s;
10166    }
10167    acc
10168}
10169
10170/// Four tiles' unreduced `i32×8` partial sums → `[Σ0, Σ1, Σ2, Σ3]` in one
10171/// hadd tree: 3 hadds + 1 add for four tiles where the per-tile reduce of
10172/// the q1 kernels costs 7 ops each. Integer math, so any order gives the
10173/// q1 kernel's per-tile sums exactly.
10174#[cfg(target_arch = "x86_64")]
10175#[target_feature(enable = "avx2")]
10176#[inline]
10177unsafe fn q1g_hsum4(
10178    d0: core::arch::x86_64::__m256i,
10179    d1: core::arch::x86_64::__m256i,
10180    d2: core::arch::x86_64::__m256i,
10181    d3: core::arch::x86_64::__m256i,
10182) -> core::arch::x86_64::__m128i {
10183    // SAFETY: pure register math.
10184    unsafe {
10185        use core::arch::x86_64::*;
10186        let h = _mm256_hadd_epi32(_mm256_hadd_epi32(d0, d1), _mm256_hadd_epi32(d2, d3));
10187        _mm_add_epi32(_mm256_castsi256_si128(h), _mm256_extracti128_si256::<1>(h))
10188    }
10189}
10190
10191/// One 128-group's epilogue, in q1's float order: `d = 2·Σset − Σx` per
10192/// tile (exact i32 → exact f32), then `acc += d·s` tile by tile — four
10193/// separately rounded multiply/add pairs, the q1 kernels' sequence.
10194#[cfg(target_arch = "x86_64")]
10195#[target_feature(enable = "avx2")]
10196#[inline]
10197unsafe fn q1g_group_acc(
10198    acc: f32,
10199    msum4: core::arch::x86_64::__m128i,
10200    gsum4: &[i32],
10201    s: f32,
10202) -> f32 {
10203    // SAFETY: gsum4 holds the group's four tile sums (callers slice it).
10204    unsafe {
10205        use core::arch::x86_64::*;
10206        let g = _mm_loadu_si128(gsum4.as_ptr() as *const __m128i);
10207        let d = _mm_cvtepi32_ps(_mm_sub_epi32(_mm_slli_epi32::<1>(msum4), g));
10208        let mut f = [0f32; 4];
10209        _mm_storeu_ps(f.as_mut_ptr(), d);
10210        let mut acc = acc;
10211        for v in f {
10212            acc += v * s;
10213        }
10214        acc
10215    }
10216}
10217
10218/// AVX2 q1g row: `dot_q1_row_avx2`'s mask/select/maddubs per tile, but the
10219/// four tiles of a 128-group reduce together (`q1g_hsum4`) and the scale
10220/// converts once per group — bit-identical results (integer sums, then
10221/// q1's per-tile float sequence), fewer horizontal ops and f16 decodes.
10222#[cfg(target_arch = "x86_64")]
10223#[target_feature(enable = "avx2")]
10224unsafe fn dot_q1g_row_avx2(
10225    bytes: &[u8],
10226    sc_off: usize,
10227    r: usize,
10228    gpr: usize,
10229    xq: &[i8],
10230    gsum: &[i32],
10231) -> f32 {
10232    // SAFETY: callers uphold the plane-length and xq/gsum contracts
10233    // (gpr % 4 == 0, xq.len() == gpr·32, gsum.len() == gpr).
10234    unsafe {
10235        use core::arch::x86_64::*;
10236        let expand = _mm256_setr_epi8(
10237            0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3,
10238            3, 3, 3,
10239        );
10240        let bitsel = _mm256_setr_epi8(
10241            1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64,
10242            -128, 1, 2, 4, 8, 16, 32, 64, -128,
10243        );
10244        let ones8 = _mm256_set1_epi8(1);
10245        let ones16 = _mm256_set1_epi16(1);
10246        let bp = bytes.as_ptr().add(r * gpr * 4);
10247        let mut acc = 0f32;
10248        let mut gi = 0;
10249        while gi < gpr {
10250            let s = f16_to_f32(q1g_scale_bits(bytes, sc_off, r * gpr + gi));
10251            let mut d = [_mm256_setzero_si256(); 4];
10252            for (k, dk) in d.iter_mut().enumerate() {
10253                let t = gi + k;
10254                let bits = (bp.add(t * 4) as *const u32).read_unaligned();
10255                let bc = _mm256_shuffle_epi8(_mm256_set1_epi32(bits as i32), expand);
10256                let mask = _mm256_cmpeq_epi8(_mm256_and_si256(bc, bitsel), bitsel);
10257                let x = _mm256_loadu_si256(xq.as_ptr().add(t * GROUP_SIZE) as *const __m256i);
10258                let sel = _mm256_and_si256(x, mask);
10259                *dk = _mm256_madd_epi16(_mm256_maddubs_epi16(ones8, sel), ones16);
10260            }
10261            let m4 = q1g_hsum4(d[0], d[1], d[2], d[3]);
10262            acc = q1g_group_acc(acc, m4, &gsum[gi..gi + 4], s);
10263            gi += 4;
10264        }
10265        acc
10266    }
10267}
10268
10269/// VNNI twin of `dot_q1g_row_avx2`: `vpdpbusd(1u8, sel)` per tile (the
10270/// same i32 lanes as maddubs+madd — bounded products), same group reduce.
10271#[cfg(target_arch = "x86_64")]
10272#[target_feature(enable = "avx2,avx512f,avx512bw,avx512vl,avx512vnni")]
10273unsafe fn dot_q1g_row_vnni(
10274    bytes: &[u8],
10275    sc_off: usize,
10276    r: usize,
10277    gpr: usize,
10278    xq: &[i8],
10279    gsum: &[i32],
10280) -> f32 {
10281    // SAFETY: callers uphold the plane-length and xq/gsum contracts.
10282    unsafe {
10283        use core::arch::x86_64::*;
10284        let expand = _mm256_setr_epi8(
10285            0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3,
10286            3, 3, 3,
10287        );
10288        let bitsel = _mm256_setr_epi8(
10289            1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64,
10290            -128, 1, 2, 4, 8, 16, 32, 64, -128,
10291        );
10292        let ones8 = _mm256_set1_epi8(1);
10293        let bp = bytes.as_ptr().add(r * gpr * 4);
10294        let mut acc = 0f32;
10295        let mut gi = 0;
10296        while gi < gpr {
10297            let s = f16_to_f32(q1g_scale_bits(bytes, sc_off, r * gpr + gi));
10298            let mut d = [_mm256_setzero_si256(); 4];
10299            for (k, dk) in d.iter_mut().enumerate() {
10300                let t = gi + k;
10301                let bits = (bp.add(t * 4) as *const u32).read_unaligned();
10302                let bc = _mm256_shuffle_epi8(_mm256_set1_epi32(bits as i32), expand);
10303                let mask = _mm256_cmpeq_epi8(_mm256_and_si256(bc, bitsel), bitsel);
10304                let x = _mm256_loadu_si256(xq.as_ptr().add(t * GROUP_SIZE) as *const __m256i);
10305                *dk = _mm256_dpbusd_epi32(_mm256_setzero_si256(), ones8, _mm256_and_si256(x, mask));
10306            }
10307            let m4 = q1g_hsum4(d[0], d[1], d[2], d[3]);
10308            acc = q1g_group_acc(acc, m4, &gsum[gi..gi + 4], s);
10309            gi += 4;
10310        }
10311        acc
10312    }
10313}
10314
10315/// Blocked 1×4 AVX2 q1g row: each tile's mask is built once and serves
10316/// four activation streams; per stream, the group reduce and float order
10317/// of `dot_q1g_row_avx2` (so batch == matvec bit for bit).
10318#[cfg(target_arch = "x86_64")]
10319#[target_feature(enable = "avx2")]
10320unsafe fn dot_q1g_row_1x4_avx2(
10321    bytes: &[u8],
10322    sc_off: usize,
10323    r: usize,
10324    gpr: usize,
10325    xs: [&[i8]; 4],
10326    gsums: [&[i32]; 4],
10327) -> [f32; 4] {
10328    // SAFETY: callers uphold the plane-length and xq/gsum contracts.
10329    unsafe {
10330        use core::arch::x86_64::*;
10331        let expand = _mm256_setr_epi8(
10332            0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3,
10333            3, 3, 3,
10334        );
10335        let bitsel = _mm256_setr_epi8(
10336            1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64,
10337            -128, 1, 2, 4, 8, 16, 32, 64, -128,
10338        );
10339        let ones8 = _mm256_set1_epi8(1);
10340        let ones16 = _mm256_set1_epi16(1);
10341        let bp = bytes.as_ptr().add(r * gpr * 4);
10342        let mut acc = [0f32; 4];
10343        let mut gi = 0;
10344        while gi < gpr {
10345            let s = f16_to_f32(q1g_scale_bits(bytes, sc_off, r * gpr + gi));
10346            // d[stream][tile]
10347            let mut d = [[_mm256_setzero_si256(); 4]; 4];
10348            for t in 0..4 {
10349                let bits = (bp.add((gi + t) * 4) as *const u32).read_unaligned();
10350                let bc = _mm256_shuffle_epi8(_mm256_set1_epi32(bits as i32), expand);
10351                let mask = _mm256_cmpeq_epi8(_mm256_and_si256(bc, bitsel), bitsel);
10352                for (k, xq) in xs.iter().enumerate() {
10353                    let x = _mm256_loadu_si256(
10354                        xq.as_ptr().add((gi + t) * GROUP_SIZE) as *const __m256i
10355                    );
10356                    let sel = _mm256_and_si256(x, mask);
10357                    d[k][t] = _mm256_madd_epi16(_mm256_maddubs_epi16(ones8, sel), ones16);
10358                }
10359            }
10360            for k in 0..4 {
10361                let m4 = q1g_hsum4(d[k][0], d[k][1], d[k][2], d[k][3]);
10362                acc[k] = q1g_group_acc(acc[k], m4, &gsums[k][gi..gi + 4], s);
10363            }
10364            gi += 4;
10365        }
10366        acc
10367    }
10368}
10369
10370/// VNNI twin of `dot_q1g_row_1x4_avx2`.
10371#[cfg(target_arch = "x86_64")]
10372#[target_feature(enable = "avx2,avx512f,avx512bw,avx512vl,avx512vnni")]
10373unsafe fn dot_q1g_row_1x4_vnni(
10374    bytes: &[u8],
10375    sc_off: usize,
10376    r: usize,
10377    gpr: usize,
10378    xs: [&[i8]; 4],
10379    gsums: [&[i32]; 4],
10380) -> [f32; 4] {
10381    // SAFETY: callers uphold the plane-length and xq/gsum contracts.
10382    unsafe {
10383        use core::arch::x86_64::*;
10384        let expand = _mm256_setr_epi8(
10385            0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3,
10386            3, 3, 3,
10387        );
10388        let bitsel = _mm256_setr_epi8(
10389            1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64,
10390            -128, 1, 2, 4, 8, 16, 32, 64, -128,
10391        );
10392        let ones8 = _mm256_set1_epi8(1);
10393        let bp = bytes.as_ptr().add(r * gpr * 4);
10394        let mut acc = [0f32; 4];
10395        let mut gi = 0;
10396        while gi < gpr {
10397            let s = f16_to_f32(q1g_scale_bits(bytes, sc_off, r * gpr + gi));
10398            let mut d = [[_mm256_setzero_si256(); 4]; 4];
10399            for t in 0..4 {
10400                let bits = (bp.add((gi + t) * 4) as *const u32).read_unaligned();
10401                let bc = _mm256_shuffle_epi8(_mm256_set1_epi32(bits as i32), expand);
10402                let mask = _mm256_cmpeq_epi8(_mm256_and_si256(bc, bitsel), bitsel);
10403                for (k, xq) in xs.iter().enumerate() {
10404                    let x = _mm256_loadu_si256(
10405                        xq.as_ptr().add((gi + t) * GROUP_SIZE) as *const __m256i
10406                    );
10407                    d[k][t] = _mm256_dpbusd_epi32(
10408                        _mm256_setzero_si256(),
10409                        ones8,
10410                        _mm256_and_si256(x, mask),
10411                    );
10412                }
10413            }
10414            for k in 0..4 {
10415                let m4 = q1g_hsum4(d[k][0], d[k][1], d[k][2], d[k][3]);
10416                acc[k] = q1g_group_acc(acc[k], m4, &gsums[k][gi..gi + 4], s);
10417            }
10418            gi += 4;
10419        }
10420        acc
10421    }
10422}
10423
10424/// SDOT q1g row: the `dot_q1_row_sdot` math on the plane layout. One
10425/// aligned 16-byte load carries a whole 128-group's signs (q1 needs two
10426/// pair loads and a TBL gather of four scales for the same weights), TBL
10427/// replicates each sign byte across 8 lanes for vtst, and the group's ONE
10428/// scale converts once (FCVTL, exact) and broadcasts. Lane order, the
10429/// vpaddq tree, the fma into the four lane accumulators and the tail are
10430/// the q1 kernel's — including its quirk: q1's pair load reads 4 bytes
10431/// past the 4th tile, so the payload's final four tiles (last row) take
10432/// the scalar tail there. q1g has no overread, but takes the same tail on
10433/// the last row to stay bit-identical to q1.
10434#[cfg(target_arch = "aarch64")]
10435#[target_feature(enable = "neon,dotprod")]
10436#[allow(clippy::too_many_arguments)]
10437unsafe fn dot_q1g_row_sdot(
10438    bytes: &[u8],
10439    sc_off: usize,
10440    rows: usize,
10441    r: usize,
10442    gpr: usize,
10443    xq: &[i8],
10444    gsum: &[i32],
10445) -> f32 {
10446    // SAFETY: callers uphold the plane-length and xq/gsum contracts
10447    // (gpr % 4 == 0, xq.len() == gpr·32, gsum.len() == gpr).
10448    unsafe {
10449        use core::arch::aarch64::*;
10450        use core::arch::asm;
10451        const MASKS: [u8; 16] = [1, 2, 4, 8, 16, 32, 64, 128, 1, 2, 4, 8, 16, 32, 64, 128];
10452        // Tile t of the group = sign bytes 4t..4t+4 of the 16-byte load.
10453        const IW: [[u8; 16]; 8] = [
10454            [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1],
10455            [2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3],
10456            [4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5],
10457            [6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7],
10458            [8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9],
10459            [
10460                10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11,
10461            ],
10462            [
10463                12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13,
10464            ],
10465            [
10466                14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
10467            ],
10468        ];
10469        let m = vld1q_u8(MASKS.as_ptr());
10470        let iw: [uint8x16_t; 8] = core::array::from_fn(|i| vld1q_u8(IW[i].as_ptr()));
10471        macro_rules! tile_dot {
10472            ($w0:expr, $w1:expr, $x:expr) => {{
10473                let x0 = vld1q_s8($x);
10474                let x1 = vld1q_s8($x.add(16));
10475                let (mut a0, mut a1) = (vdupq_n_s32(0), vdupq_n_s32(0));
10476                asm!(
10477                    "sdot {a0:v}.4s, {w0:v}.16b, {x0:v}.16b",
10478                    "sdot {a1:v}.4s, {w1:v}.16b, {x1:v}.16b",
10479                    a0 = inout(vreg) a0, a1 = inout(vreg) a1,
10480                    w0 = in(vreg) $w0, x0 = in(vreg) x0, w1 = in(vreg) $w1, x1 = in(vreg) x1,
10481                    options(pure, nomem, nostack),
10482                );
10483                vaddq_s32(a0, a1)
10484            }};
10485        }
10486        macro_rules! tbl_mask {
10487            ($ld:expr, $i:expr) => {
10488                vreinterpretq_s8_u8(vtstq_u8(vqtbl1q_u8($ld, iw[$i]), m))
10489            };
10490        }
10491        let bp = bytes.as_ptr().add(r * gpr * 4);
10492        let xp = xq.as_ptr();
10493        let gp = gsum.as_ptr();
10494        let vec_end = if r + 1 == rows { gpr - 4 } else { gpr };
10495        let mut accv = vdupq_n_f32(0.0);
10496        let mut gi = 0;
10497        while gi + 4 <= vec_end {
10498            let ld = vld1q_u8(bp.add(gi * 4));
10499            let d0 = tile_dot!(tbl_mask!(ld, 0), tbl_mask!(ld, 1), xp.add(gi * GROUP_SIZE));
10500            let d1 = tile_dot!(
10501                tbl_mask!(ld, 2),
10502                tbl_mask!(ld, 3),
10503                xp.add((gi + 1) * GROUP_SIZE)
10504            );
10505            let d2 = tile_dot!(
10506                tbl_mask!(ld, 4),
10507                tbl_mask!(ld, 5),
10508                xp.add((gi + 2) * GROUP_SIZE)
10509            );
10510            let d3 = tile_dot!(
10511                tbl_mask!(ld, 6),
10512                tbl_mask!(ld, 7),
10513                xp.add((gi + 3) * GROUP_SIZE)
10514            );
10515            let neg = vpaddq_s32(vpaddq_s32(d0, d1), vpaddq_s32(d2, d3));
10516            let g = vld1q_s32(gp.add(gi));
10517            let dots = vnegq_s32(vaddq_s32(vshlq_n_s32::<1>(neg), g));
10518            let h = vdup_n_u16(q1g_scale_bits(bytes, sc_off, r * gpr + gi));
10519            let scf: float32x4_t;
10520            asm!(
10521                "fcvtl {o:v}.4s, {i:v}.4h",
10522                o = out(vreg) scf, i = in(vreg) h,
10523                options(pure, nomem, nostack),
10524            );
10525            accv = vfmaq_f32(accv, vcvtq_f32_s32(dots), scf);
10526            gi += 4;
10527        }
10528        let mut acc = vaddvq_f32(accv);
10529        while gi < gpr {
10530            let t = bp.add(gi * 4);
10531            let s = f16_to_f32(q1g_scale_bits(bytes, sc_off, r * gpr + gi));
10532            let v0 = vcombine_u8(vdup_n_u8(*t), vdup_n_u8(*t.add(1)));
10533            let v1 = vcombine_u8(vdup_n_u8(*t.add(2)), vdup_n_u8(*t.add(3)));
10534            let w0 = vreinterpretq_s8_u8(vtstq_u8(v0, m));
10535            let w1 = vreinterpretq_s8_u8(vtstq_u8(v1, m));
10536            let d = vaddvq_s32(tile_dot!(w0, w1, xp.add(gi * GROUP_SIZE)));
10537            acc += (-(2 * d + *gp.add(gi))) as f32 * s;
10538            gi += 1;
10539        }
10540        acc
10541    }
10542}
10543
10544/// Blocked q1g 1×4: one unpack of the group serves four activation
10545/// streams; per stream bit-identical to `dot_q1g_row_sdot` (and so to the
10546/// q1 1×4 kernel, same last-row tail).
10547#[cfg(target_arch = "aarch64")]
10548#[target_feature(enable = "neon,dotprod")]
10549#[allow(clippy::too_many_arguments)]
10550unsafe fn dot_q1g_row_1x4_sdot(
10551    bytes: &[u8],
10552    sc_off: usize,
10553    rows: usize,
10554    r: usize,
10555    gpr: usize,
10556    xs: [&[i8]; 4],
10557    gs: [&[i32]; 4],
10558) -> [f32; 4] {
10559    // SAFETY: same contracts as `dot_q1g_row_sdot`, ×4.
10560    unsafe {
10561        use core::arch::aarch64::*;
10562        use core::arch::asm;
10563        const MASKS: [u8; 16] = [1, 2, 4, 8, 16, 32, 64, 128, 1, 2, 4, 8, 16, 32, 64, 128];
10564        const IW: [[u8; 16]; 8] = [
10565            [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1],
10566            [2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3],
10567            [4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5],
10568            [6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7],
10569            [8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9],
10570            [
10571                10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11,
10572            ],
10573            [
10574                12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13,
10575            ],
10576            [
10577                14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
10578            ],
10579        ];
10580        let m = vld1q_u8(MASKS.as_ptr());
10581        let iw: [uint8x16_t; 8] = core::array::from_fn(|i| vld1q_u8(IW[i].as_ptr()));
10582        macro_rules! sdot2 {
10583            ($w0:expr, $w1:expr, $x:expr) => {{
10584                let x0 = vld1q_s8($x);
10585                let x1 = vld1q_s8($x.add(16));
10586                let (mut a0, mut a1) = (vdupq_n_s32(0), vdupq_n_s32(0));
10587                asm!(
10588                    "sdot {a0:v}.4s, {w0:v}.16b, {x0:v}.16b",
10589                    "sdot {a1:v}.4s, {w1:v}.16b, {x1:v}.16b",
10590                    a0 = inout(vreg) a0, a1 = inout(vreg) a1,
10591                    w0 = in(vreg) $w0, x0 = in(vreg) x0, w1 = in(vreg) $w1, x1 = in(vreg) x1,
10592                    options(pure, nomem, nostack),
10593                );
10594                vaddq_s32(a0, a1)
10595            }};
10596        }
10597        let bp = bytes.as_ptr().add(r * gpr * 4);
10598        let vec_end = if r + 1 == rows { gpr - 4 } else { gpr };
10599        let mut accv = [vdupq_n_f32(0.0); 4];
10600        let mut gi = 0;
10601        while gi + 4 <= vec_end {
10602            let ld = vld1q_u8(bp.add(gi * 4));
10603            // Unpack ONCE — eight ±mask vectors serve all four streams.
10604            let w: [int8x16_t; 8] =
10605                core::array::from_fn(|i| vreinterpretq_s8_u8(vtstq_u8(vqtbl1q_u8(ld, iw[i]), m)));
10606            let h = vdup_n_u16(q1g_scale_bits(bytes, sc_off, r * gpr + gi));
10607            let scf: float32x4_t;
10608            asm!(
10609                "fcvtl {o:v}.4s, {i:v}.4h",
10610                o = out(vreg) scf, i = in(vreg) h,
10611                options(pure, nomem, nostack),
10612            );
10613            for k in 0..4 {
10614                let xp = xs[k].as_ptr();
10615                let d0 = sdot2!(w[0], w[1], xp.add(gi * GROUP_SIZE));
10616                let d1 = sdot2!(w[2], w[3], xp.add((gi + 1) * GROUP_SIZE));
10617                let d2 = sdot2!(w[4], w[5], xp.add((gi + 2) * GROUP_SIZE));
10618                let d3 = sdot2!(w[6], w[7], xp.add((gi + 3) * GROUP_SIZE));
10619                let neg = vpaddq_s32(vpaddq_s32(d0, d1), vpaddq_s32(d2, d3));
10620                let g = vld1q_s32(gs[k].as_ptr().add(gi));
10621                let dots = vnegq_s32(vaddq_s32(vshlq_n_s32::<1>(neg), g));
10622                accv[k] = vfmaq_f32(accv[k], vcvtq_f32_s32(dots), scf);
10623            }
10624            gi += 4;
10625        }
10626        let mut acc = [
10627            vaddvq_f32(accv[0]),
10628            vaddvq_f32(accv[1]),
10629            vaddvq_f32(accv[2]),
10630            vaddvq_f32(accv[3]),
10631        ];
10632        while gi < gpr {
10633            let t = bp.add(gi * 4);
10634            let sc = f16_to_f32(q1g_scale_bits(bytes, sc_off, r * gpr + gi));
10635            let v0 = vcombine_u8(vdup_n_u8(*t), vdup_n_u8(*t.add(1)));
10636            let v1 = vcombine_u8(vdup_n_u8(*t.add(2)), vdup_n_u8(*t.add(3)));
10637            let w0 = vreinterpretq_s8_u8(vtstq_u8(v0, m));
10638            let w1 = vreinterpretq_s8_u8(vtstq_u8(v1, m));
10639            for k in 0..4 {
10640                let d = vaddvq_s32(sdot2!(w0, w1, xs[k].as_ptr().add(gi * GROUP_SIZE)));
10641                acc[k] += (-(2 * d + *gs[k].as_ptr().add(gi))) as f32 * sc;
10642            }
10643            gi += 1;
10644        }
10645        acc
10646    }
10647}
10648
10649/// (weight ±1, scale) of one q1g element — the exact outlier term.
10650#[inline]
10651fn q1g_outlier(bytes: &[u8], sc_off: usize, r: usize, gpr: usize, j: usize) -> (f32, f32) {
10652    let t = r * gpr + j / GROUP_SIZE;
10653    let k = j % GROUP_SIZE;
10654    let s = f16_to_f32(q1g_scale_bits(bytes, sc_off, t));
10655    let bit = (bytes[t * 4 + k / 8] >> (k % 8)) & 1;
10656    ((bit as i32 * 2 - 1) as f32, s)
10657}
10658
10659/// Exact scalar q1g row (CMF_SDOT=0 contract) — `q1_row_exact`'s order.
10660#[inline]
10661fn q1g_row_exact(bytes: &[u8], sc_off: usize, r: usize, gpr: usize, x: &[f32]) -> f32 {
10662    let mut acc = 0f32;
10663    for gi in 0..gpr {
10664        let t = r * gpr + gi;
10665        let s = f16_to_f32(q1g_scale_bits(bytes, sc_off, t));
10666        let xg = &x[gi * GROUP_SIZE..(gi + 1) * GROUP_SIZE];
10667        let mut ga = 0f32;
10668        for (j, &b) in bytes[t * 4..t * 4 + 4].iter().enumerate() {
10669            for k in 0..8 {
10670                ga += (((b >> k) & 1) as f32 * 2.0 - 1.0) * xg[j * 8 + k];
10671            }
10672        }
10673        acc += ga * s;
10674    }
10675    acc
10676}
10677
10678/// q1t per-row overlay locator. After the base (`base_len`) come
10679/// `[u32 row_ptr[rows+1]]` then `[(u16 col, f16 val)]` grouped by row (row
10680/// `r`'s entries are `[row_ptr[r], row_ptr[r+1])`). Returns
10681/// `(row_ptr offset, entries offset, present)`.
10682fn q1t_overlay(bytes: &[u8], base_len: usize, rows: usize) -> (usize, usize, bool) {
10683    let entries = base_len + (rows + 1) * 4;
10684    (base_len, entries, entries <= bytes.len())
10685}
10686
10687/// Read `row_ptr[r]` from the overlay's prefix-sum table.
10688#[inline]
10689fn q1t_rowptr(bytes: &[u8], rp_off: usize, r: usize) -> usize {
10690    let o = rp_off + r * 4;
10691    u32::from_le_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]]) as usize
10692}
10693
10694/// Byte → the 5 ternary signs it packs `{−1,0,+1}` as f32, precomputed so
10695/// decoding a q1t code is a table load, not the base-3 divide/modulo per
10696/// weight (division is ~20–40× the cost of a load). Built at compile time.
10697const SIGN5: [[f32; 5]; 256] = {
10698    let mut lut = [[0.0f32; 5]; 256];
10699    let pow3 = [1u16, 3, 9, 27, 81];
10700    let mut byte = 0usize;
10701    while byte < 256 {
10702        let mut i = 0usize;
10703        while i < 5 {
10704            let code = (byte as u16 / pow3[i]) % 3;
10705            lut[byte][i] = if code == 1 {
10706                1.0
10707            } else if code == 2 {
10708                -1.0
10709            } else {
10710                0.0
10711            };
10712            i += 1;
10713        }
10714        byte += 1;
10715    }
10716    lut
10717};
10718
10719/// Same table, as i8 signs — the operand for the int8 SDOT base kernel.
10720const SIGN5_I8: [[i8; 5]; 256] = {
10721    let mut lut = [[0i8; 5]; 256];
10722    let pow3 = [1u16, 3, 9, 27, 81];
10723    let mut byte = 0usize;
10724    while byte < 256 {
10725        let mut i = 0usize;
10726        while i < 5 {
10727            let code = (byte as u16 / pow3[i]) % 3;
10728            lut[byte][i] = if code == 1 {
10729                1
10730            } else if code == 2 {
10731                -1
10732            } else {
10733                0
10734            };
10735            i += 1;
10736        }
10737        byte += 1;
10738    }
10739    lut
10740};
10741
10742/// The same 5 i8 signs packed into a u64 (`[s0 s1 s2 s3 s4 0 0 0]`, LE) so the
10743/// group unpack is 7 unaligned u64 stores at offsets 0,5,10,…,30 instead of
10744/// six 5-byte copies + LUT indexing — each store's trailing zeros are fixed by
10745/// the next store, and the last one runs 6 B past the 32nd weight (the unpack
10746/// buffer is padded to 40). This is the decode/prefill hot inner op.
10747const SIGN5_U64: [u64; 256] = {
10748    let mut lut = [0u64; 256];
10749    let pow3 = [1u16, 3, 9, 27, 81];
10750    let mut byte = 0usize;
10751    while byte < 256 {
10752        let mut v = 0u64;
10753        let mut i = 0usize;
10754        while i < 5 {
10755            let code = (byte as u16 / pow3[i]) % 3;
10756            let s: u8 = if code == 1 {
10757                1
10758            } else if code == 2 {
10759                0xFF
10760            } else {
10761                0
10762            };
10763            v |= (s as u64) << (i * 8);
10764            i += 1;
10765        }
10766        lut[byte] = v;
10767        byte += 1;
10768    }
10769    lut
10770};
10771
10772/// Ternary base weight at `(row r, col j)` = `sign(code)·s_group`. Used to add
10773/// back activation-outlier columns, whose `x` was zeroed for the int8 bulk dot
10774/// (`split_act`). At a weight-outlier position the code is 0, so this is 0 and
10775/// the overlay correction owns that column — no double counting.
10776#[inline]
10777fn q1t_base_weight(bytes: &[u8], r: usize, gpr: usize, j: usize) -> f32 {
10778    const TILE: usize = cortiq_core::quant::Q1T_TILE;
10779    let off = (r * gpr + j / GROUP_SIZE) * TILE;
10780    let s = f16_to_f32(u16::from_le_bytes([bytes[off], bytes[off + 1]]));
10781    let within = j % GROUP_SIZE;
10782    SIGN5[bytes[off + 2 + within / 5] as usize][within % 5] * s
10783}
10784
10785/// One 32-group int8 dot via two SDOTs. Bit-exact vs the scalar i8 sum
10786/// (integer accumulation is order-independent).
10787#[cfg(target_arch = "aarch64")]
10788#[target_feature(enable = "neon,dotprod")]
10789#[inline]
10790unsafe fn sdot32_i8(w: *const i8, x: *const i8) -> i32 {
10791    // SAFETY: caller guarantees 32 readable i8 at each pointer.
10792    unsafe {
10793        use core::arch::aarch64::*;
10794        use core::arch::asm;
10795        let w0 = vld1q_s8(w);
10796        let w1 = vld1q_s8(w.add(16));
10797        let x0 = vld1q_s8(x);
10798        let x1 = vld1q_s8(x.add(16));
10799        let (mut a0, mut a1) = (vdupq_n_s32(0), vdupq_n_s32(0));
10800        asm!(
10801            "sdot {a0:v}.4s, {w0:v}.16b, {x0:v}.16b",
10802            "sdot {a1:v}.4s, {w1:v}.16b, {x1:v}.16b",
10803            a0 = inout(vreg) a0, a1 = inout(vreg) a1,
10804            w0 = in(vreg) w0, x0 = in(vreg) x0, w1 = in(vreg) w1, x1 = in(vreg) x1,
10805            options(pure, nomem, nostack),
10806        );
10807        vaddvq_s32(vaddq_s32(a0, a1))
10808    }
10809}
10810
10811/// One 32-group int8 dot via AVX2: signed·signed as `maddubs(|w|, sign(x,w))`
10812/// then `madd` and a horizontal reduce (the same idiom as `dot_q4t_row_avx2`).
10813#[cfg(target_arch = "x86_64")]
10814#[target_feature(enable = "avx2")]
10815#[inline]
10816unsafe fn i8dot32_avx2(w: *const i8, x: *const i8) -> i32 {
10817    // SAFETY: caller guarantees 32 readable i8 at each pointer.
10818    unsafe {
10819        use core::arch::x86_64::*;
10820        let wv = _mm256_loadu_si256(w as *const __m256i);
10821        let xv = _mm256_loadu_si256(x as *const __m256i);
10822        let p16 = _mm256_maddubs_epi16(_mm256_abs_epi8(wv), _mm256_sign_epi8(xv, wv));
10823        let d = _mm256_madd_epi16(p16, _mm256_set1_epi16(1));
10824        let hi128 = _mm256_extracti128_si256::<1>(d);
10825        let s128 = _mm_add_epi32(_mm256_castsi256_si128(d), hi128);
10826        let s64 = _mm_add_epi32(s128, _mm_srli_si128::<8>(s128));
10827        let s32 = _mm_add_epi32(s64, _mm_srli_si128::<4>(s64));
10828        _mm_cvtsi128_si32(s32)
10829    }
10830}
10831
10832/// Unpack one q1t group's base-3 codes into 32 i8 signs via 7 unaligned u64
10833/// stores (see `SIGN5_U64`). `dst` MUST have ≥ 40 bytes: the 7th store writes
10834/// `dst[30..38]`. Stores go in order so each one's trailing zeros are
10835/// overwritten by the next; the final 6 padding bytes are unused by the dot.
10836#[inline]
10837fn q1t_unpack_group_i8(codes: *const u8, dst: &mut [i8]) {
10838    debug_assert!(dst.len() >= 40);
10839    // SAFETY: codes points at 7 readable bytes; dst has ≥ 40 bytes so every
10840    // 8-byte store at offset bi*5 (bi ≤ 6 → ≤ 30) stays in bounds.
10841    unsafe {
10842        let p = dst.as_mut_ptr();
10843        for bi in 0..7 {
10844            core::ptr::write_unaligned(
10845                p.add(bi * 5) as *mut u64,
10846                SIGN5_U64[*codes.add(bi) as usize],
10847            );
10848        }
10849    }
10850}
10851
10852/// One 32-group int8 dot, arch-dispatched (the matmat inner loop, where the
10853/// row's signs are unpacked once and dotted against every batch input).
10854/// Callers are gated by `a8w8_enabled()`, so the target-feature arms are
10855/// reachable; the scalar arm is a non-SIMD-arch fallback.
10856#[inline]
10857fn q1t_i8dot32(w: *const i8, x: *const i8) -> i32 {
10858    #[cfg(target_arch = "aarch64")]
10859    unsafe {
10860        return sdot32_i8(w, x);
10861    }
10862    #[cfg(target_arch = "x86_64")]
10863    unsafe {
10864        return i8dot32_avx2(w, x);
10865    }
10866    #[allow(unreachable_code)]
10867    unsafe {
10868        let mut s = 0i32;
10869        for k in 0..GROUP_SIZE {
10870            s += *w.add(k) as i32 * *x.add(k) as i32;
10871        }
10872        s
10873    }
10874}
10875
10876#[inline]
10877unsafe fn q1t_unpack_reg_u64s(codes: *const u8) -> (u64, u64, u64, u64) {
10878    let (s0, s1, s2, s3, s4, s5, s6) = unsafe {
10879        (
10880            SIGN5_U64[*codes as usize],
10881            SIGN5_U64[*codes.add(1) as usize],
10882            SIGN5_U64[*codes.add(2) as usize],
10883            SIGN5_U64[*codes.add(3) as usize],
10884            SIGN5_U64[*codes.add(4) as usize],
10885            SIGN5_U64[*codes.add(5) as usize],
10886            SIGN5_U64[*codes.add(6) as usize],
10887        )
10888    };
10889
10890    let u0 = s0 | (s1 << 40);
10891    let u1 = (s1 >> 24) | (s2 << 16) | (s3 << 56);
10892    let u2 = (s3 >> 8) | (s4 << 32);
10893    let u3 = (s4 >> 32) | (s5 << 8) | (s6 << 48);
10894
10895    (u0, u1, u2, u3)
10896}
10897
10898/// One q1t row's int8 base dot: `Σ_group s·dot(signs, xq)` (before the shared
10899/// `sx`). Direct register unpacking (zero stack stores/loads, no STLF stalls).
10900/// ARM SDOT.
10901#[cfg(target_arch = "aarch64")]
10902#[target_feature(enable = "neon,dotprod")]
10903unsafe fn q1t_dot_row_sdot(bytes: &[u8], r: usize, gpr: usize, xq: &[i8]) -> f32 {
10904    use core::arch::aarch64::*;
10905    use core::arch::asm;
10906    unsafe {
10907        const TILE: usize = cortiq_core::quant::Q1T_TILE;
10908        let mut acc = 0f32;
10909        let bytes_ptr = bytes.as_ptr();
10910        let xq_ptr = xq.as_ptr();
10911        let row_off = r * gpr * TILE;
10912
10913        let gpr2 = gpr & !1;
10914        let mut gi = 0;
10915        while gi < gpr2 {
10916            let off0 = row_off + gi * TILE;
10917            let off1 = off0 + TILE;
10918            let s0 = f16_to_f32(u16::from_le_bytes([
10919                *bytes_ptr.add(off0),
10920                *bytes_ptr.add(off0 + 1),
10921            ]));
10922            let s1 = f16_to_f32(u16::from_le_bytes([
10923                *bytes_ptr.add(off1),
10924                *bytes_ptr.add(off1 + 1),
10925            ]));
10926
10927            let (u0_0, u1_0, u2_0, u3_0) = q1t_unpack_reg_u64s(bytes_ptr.add(off0 + 2));
10928            let (u0_1, u1_1, u2_1, u3_1) = q1t_unpack_reg_u64s(bytes_ptr.add(off1 + 2));
10929
10930            let w0_0 = vreinterpretq_s8_u64(vcombine_u64(vcreate_u64(u0_0), vcreate_u64(u1_0)));
10931            let w1_0 = vreinterpretq_s8_u64(vcombine_u64(vcreate_u64(u2_0), vcreate_u64(u3_0)));
10932            let w0_1 = vreinterpretq_s8_u64(vcombine_u64(vcreate_u64(u0_1), vcreate_u64(u1_1)));
10933            let w1_1 = vreinterpretq_s8_u64(vcombine_u64(vcreate_u64(u2_1), vcreate_u64(u3_1)));
10934
10935            let x0_0 = vld1q_s8(xq_ptr.add(gi * GROUP_SIZE));
10936            let x1_0 = vld1q_s8(xq_ptr.add(gi * GROUP_SIZE + 16));
10937            let x0_1 = vld1q_s8(xq_ptr.add((gi + 1) * GROUP_SIZE));
10938            let x1_1 = vld1q_s8(xq_ptr.add((gi + 1) * GROUP_SIZE + 16));
10939
10940            let (mut a0_0, mut a1_0) = (vdupq_n_s32(0), vdupq_n_s32(0));
10941            let (mut a0_1, mut a1_1) = (vdupq_n_s32(0), vdupq_n_s32(0));
10942            asm!(
10943                "sdot {a0_0:v}.4s, {w0_0:v}.16b, {x0_0:v}.16b",
10944                "sdot {a1_0:v}.4s, {w1_0:v}.16b, {x1_0:v}.16b",
10945                "sdot {a0_1:v}.4s, {w0_1:v}.16b, {x0_1:v}.16b",
10946                "sdot {a1_1:v}.4s, {w1_1:v}.16b, {x1_1:v}.16b",
10947                a0_0 = inout(vreg) a0_0, a1_0 = inout(vreg) a1_0,
10948                a0_1 = inout(vreg) a0_1, a1_1 = inout(vreg) a1_1,
10949                w0_0 = in(vreg) w0_0, x0_0 = in(vreg) x0_0, w1_0 = in(vreg) w1_0, x1_0 = in(vreg) x1_0,
10950                w0_1 = in(vreg) w0_1, x0_1 = in(vreg) x0_1, w1_1 = in(vreg) w1_1, x1_1 = in(vreg) x1_1,
10951                options(pure, nomem, nostack),
10952            );
10953            let d0 = vaddvq_s32(vaddq_s32(a0_0, a1_0));
10954            let d1 = vaddvq_s32(vaddq_s32(a0_1, a1_1));
10955            acc += d0 as f32 * s0 + d1 as f32 * s1;
10956            gi += 2;
10957        }
10958
10959        if gi < gpr {
10960            let off = row_off + gi * TILE;
10961            let s = f16_to_f32(u16::from_le_bytes([
10962                *bytes_ptr.add(off),
10963                *bytes_ptr.add(off + 1),
10964            ]));
10965            let (u0, u1, u2, u3) = q1t_unpack_reg_u64s(bytes_ptr.add(off + 2));
10966            let w0 = vreinterpretq_s8_u64(vcombine_u64(vcreate_u64(u0), vcreate_u64(u1)));
10967            let w1 = vreinterpretq_s8_u64(vcombine_u64(vcreate_u64(u2), vcreate_u64(u3)));
10968            let x0 = vld1q_s8(xq_ptr.add(gi * GROUP_SIZE));
10969            let x1 = vld1q_s8(xq_ptr.add(gi * GROUP_SIZE + 16));
10970            let (mut a0, mut a1) = (vdupq_n_s32(0), vdupq_n_s32(0));
10971            asm!(
10972                "sdot {a0:v}.4s, {w0:v}.16b, {x0:v}.16b",
10973                "sdot {a1:v}.4s, {w1:v}.16b, {x1:v}.16b",
10974                a0 = inout(vreg) a0, a1 = inout(vreg) a1,
10975                w0 = in(vreg) w0, x0 = in(vreg) x0, w1 = in(vreg) w1, x1 = in(vreg) x1,
10976                options(pure, nomem, nostack),
10977            );
10978            let d = vaddvq_s32(vaddq_s32(a0, a1));
10979            acc += d as f32 * s;
10980        }
10981        acc
10982    }
10983}
10984
10985/// x86 AVX2 mirror of `q1t_dot_row_sdot` (maddubs int8 dot per group).
10986#[cfg(target_arch = "x86_64")]
10987#[target_feature(enable = "avx2")]
10988unsafe fn q1t_dot_row_avx2(bytes: &[u8], r: usize, gpr: usize, xq: &[i8]) -> f32 {
10989    use core::arch::x86_64::*;
10990    unsafe {
10991        const TILE: usize = cortiq_core::quant::Q1T_TILE;
10992        let mut acc = 0f32;
10993        let bytes_ptr = bytes.as_ptr();
10994        let xq_ptr = xq.as_ptr();
10995        let row_off = r * gpr * TILE;
10996
10997        let ones = _mm256_set1_epi16(1);
10998        for gi in 0..gpr {
10999            let off = row_off + gi * TILE;
11000            let s = f16_to_f32(u16::from_le_bytes([
11001                *bytes_ptr.add(off),
11002                *bytes_ptr.add(off + 1),
11003            ]));
11004            let (u0, u1, u2, u3) = q1t_unpack_reg_u64s(bytes_ptr.add(off + 2));
11005            let wv = _mm256_set_epi64x(u3 as i64, u2 as i64, u1 as i64, u0 as i64);
11006            let xv = _mm256_loadu_si256(xq_ptr.add(gi * GROUP_SIZE) as *const __m256i);
11007            let p16 = _mm256_maddubs_epi16(_mm256_abs_epi8(wv), _mm256_sign_epi8(xv, wv));
11008            let d256 = _mm256_madd_epi16(p16, ones);
11009            let d128 = _mm_add_epi32(
11010                _mm256_castsi256_si128(d256),
11011                _mm256_extracti128_si256(d256, 1),
11012            );
11013            let d64 = _mm_add_epi32(d128, _mm_shuffle_epi32(d128, 0xee));
11014            let d32 = _mm_cvtsi128_si32(_mm_add_epi32(d64, _mm_shuffle_epi32(d64, 0x55)));
11015            acc += d32 as f32 * s;
11016        }
11017        acc
11018    }
11019}
11020
11021/// VNNI twin of `q1t_dot_row_avx2` (see `dpbusd_hsum`).
11022#[cfg(target_arch = "x86_64")]
11023#[target_feature(enable = "avx2,avx512f,avx512bw,avx512vl,avx512vnni")]
11024unsafe fn q1t_dot_row_vnni(bytes: &[u8], r: usize, gpr: usize, xq: &[i8]) -> f32 {
11025    use core::arch::x86_64::*;
11026    // SAFETY: same tile/xq contracts as `q1t_dot_row_avx2`.
11027    unsafe {
11028        const TILE: usize = cortiq_core::quant::Q1T_TILE;
11029        let mut acc = 0f32;
11030        let bytes_ptr = bytes.as_ptr();
11031        let xq_ptr = xq.as_ptr();
11032        let row_off = r * gpr * TILE;
11033        for gi in 0..gpr {
11034            let off = row_off + gi * TILE;
11035            let s = f16_to_f32(u16::from_le_bytes([
11036                *bytes_ptr.add(off),
11037                *bytes_ptr.add(off + 1),
11038            ]));
11039            let (u0, u1, u2, u3) = q1t_unpack_reg_u64s(bytes_ptr.add(off + 2));
11040            let wv = _mm256_set_epi64x(u3 as i64, u2 as i64, u1 as i64, u0 as i64);
11041            let xv = _mm256_loadu_si256(xq_ptr.add(gi * GROUP_SIZE) as *const __m256i);
11042            let d = dpbusd_hsum(_mm256_abs_epi8(wv), _mm256_sign_epi8(xv, wv));
11043            acc += d as f32 * s;
11044        }
11045        acc
11046    }
11047}
11048
11049/// Per-row int8 base dot, dispatched once per row (matvec decode hot path).
11050/// Callers are gated by `a8w8_enabled()`, so the target-feature kernels are
11051/// reachable.
11052#[inline]
11053fn q1t_dot_row_i8(bytes: &[u8], r: usize, gpr: usize, xq: &[i8]) -> f32 {
11054    #[cfg(target_arch = "aarch64")]
11055    unsafe {
11056        return q1t_dot_row_sdot(bytes, r, gpr, xq);
11057    }
11058    #[cfg(target_arch = "x86_64")]
11059    unsafe {
11060        if vnni_tiles_enabled() {
11061            return q1t_dot_row_vnni(bytes, r, gpr, xq);
11062        }
11063        return q1t_dot_row_avx2(bytes, r, gpr, xq);
11064    }
11065    #[allow(unreachable_code)]
11066    {
11067        const TILE: usize = cortiq_core::quant::Q1T_TILE;
11068        let mut acc = 0f32;
11069        let mut sg = [0i8; GROUP_SIZE + 8]; // +8 slack for the u64-store unpack
11070        for gi in 0..gpr {
11071            let off = (r * gpr + gi) * TILE;
11072            let s = f16_to_f32(u16::from_le_bytes([bytes[off], bytes[off + 1]]));
11073            q1t_unpack_group_i8(bytes.as_ptr().wrapping_add(off + 2), &mut sg);
11074            let mut d = 0i32;
11075            for k in 0..GROUP_SIZE {
11076                d += sg[k] as i32 * xq[gi * GROUP_SIZE + k] as i32;
11077            }
11078            acc += d as f32 * s;
11079        }
11080        acc
11081    }
11082}
11083
11084/// Σ over a row's outliers of `value·x[col]` — the correction that adds the
11085/// overlay's exact weights on top of the base dot. INVARIANT: the encoder
11086/// writes ternary code 0 at every outlier position (`quantize_q1t`), so the
11087/// base contributes nothing there and this is a plain `value·x`, not
11088/// `(value − base)·x` — no scattered per-outlier scale read. Row `r`'s entries
11089/// are the contiguous slice `[row_ptr[r], row_ptr[r+1])`, so no binary search.
11090fn q1t_row_outlier_correction(
11091    bytes: &[u8],
11092    r: usize,
11093    rp_off: usize,
11094    entries_off: usize,
11095    has_ov: bool,
11096    x: &[f32],
11097) -> f32 {
11098    if !has_ov {
11099        return 0.0;
11100    }
11101    let (c0, c1) = (
11102        q1t_rowptr(bytes, rp_off, r),
11103        q1t_rowptr(bytes, rp_off, r + 1),
11104    );
11105    let mut corr = 0f32;
11106    for p in c0..c1 {
11107        let e = entries_off + p * 4;
11108        let col = u16::from_le_bytes([bytes[e], bytes[e + 1]]) as usize;
11109        let val = f16_to_f32(u16::from_le_bytes([bytes[e + 2], bytes[e + 3]]));
11110        corr += val * x[col];
11111    }
11112    corr
11113}
11114
11115/// Dequantize one q1t row into `buf[..cols]` via the sign LUT (no division),
11116/// then apply the row's outliers (its `[row_ptr[r], row_ptr[r+1])` slice).
11117/// Used by the batched (prefill) path where the decode amortizes over the batch.
11118fn q1t_dequant_row(
11119    bytes: &[u8],
11120    r: usize,
11121    gpr: usize,
11122    rp_off: usize,
11123    entries_off: usize,
11124    has_ov: bool,
11125    buf: &mut [f32],
11126) {
11127    const TILE: usize = cortiq_core::quant::Q1T_TILE;
11128    for g in 0..gpr {
11129        let off = (r * gpr + g) * TILE;
11130        let s = f16_to_f32(u16::from_le_bytes([bytes[off], bytes[off + 1]]));
11131        let codes = &bytes[off + 2..off + TILE];
11132        let bc = g * GROUP_SIZE;
11133        // 6 full bytes (30 codes) + a 7th byte holding the last 2.
11134        for bi in 0..6 {
11135            let lut = &SIGN5[codes[bi] as usize];
11136            let d = &mut buf[bc + bi * 5..bc + bi * 5 + 5];
11137            for i in 0..5 {
11138                d[i] = lut[i] * s;
11139            }
11140        }
11141        let lut = &SIGN5[codes[6] as usize];
11142        buf[bc + 30] = lut[0] * s;
11143        buf[bc + 31] = lut[1] * s;
11144    }
11145    if !has_ov {
11146        return;
11147    }
11148    let (c0, c1) = (
11149        q1t_rowptr(bytes, rp_off, r),
11150        q1t_rowptr(bytes, rp_off, r + 1),
11151    );
11152    for p in c0..c1 {
11153        let e = entries_off + p * 4;
11154        let col = u16::from_le_bytes([bytes[e], bytes[e + 1]]) as usize;
11155        buf[col] = f16_to_f32(u16::from_le_bytes([bytes[e + 2], bytes[e + 3]]));
11156    }
11157}
11158
11159/// Add the sparse outlier overlay onto a base dot already in `out` (the GPU
11160/// computes the ternary base; the overlay stays on the CPU — its entries are
11161/// few and its per-row gather doesn't vectorize on the GPU). Row-parallel.
11162fn q1t_add_overlay(
11163    bytes: &[u8],
11164    x: &[f32],
11165    rows: usize,
11166    cols: usize,
11167    out: &mut [f32],
11168    pool: Option<&Pool>,
11169) {
11170    const TILE: usize = cortiq_core::quant::Q1T_TILE;
11171    let gpr = cols / GROUP_SIZE;
11172    let (rp_off, ent_off, has_ov) = q1t_overlay(bytes, rows * gpr * TILE, rows);
11173    if !has_ov {
11174        return;
11175    }
11176    let out_addr = SendMut(out.as_mut_ptr());
11177    let run = move |start: usize, end: usize| {
11178        for r in start..end {
11179            let corr = q1t_row_outlier_correction(bytes, r, rp_off, ent_off, has_ov, x);
11180            // SAFETY: disjoint rows; add onto the base the GPU already wrote.
11181            unsafe { *out_addr.at(r) += corr };
11182        }
11183    };
11184    dispatch_rows(pool, rows, &run);
11185}
11186
11187/// Q1T row range via the A8W8 int8 path — shared activation split,
11188/// per-row: base SDOT dot + outlier correction + overlay.
11189#[allow(clippy::too_many_arguments)]
11190fn q1t_range_a8w8(
11191    bytes: &[u8],
11192    gpr: usize,
11193    rp_off: usize,
11194    ent_off: usize,
11195    has_ov: bool,
11196    act: &SplitAct,
11197    x: &[f32],
11198    out: SendMut,
11199    start: usize,
11200    end: usize,
11201) {
11202    for r in start..end {
11203        let mut acc = q1t_dot_row_i8(bytes, r, gpr, &act.xq) * act.sx;
11204        for &(j, xv) in &act.outliers {
11205            acc += q1t_base_weight(bytes, r, gpr, j) * xv;
11206        }
11207        acc += q1t_row_outlier_correction(bytes, r, rp_off, ent_off, has_ov, x);
11208        // SAFETY: disjoint row ranges per worker.
11209        unsafe { *out.at(r) = acc };
11210    }
11211}
11212
11213/// Q1T row range via the f32 path (no SDOT) — for matvec_many batched
11214/// dispatch when a8w8 is unavailable.
11215#[allow(clippy::too_many_arguments)]
11216fn q1t_range_f32_batch(
11217    bytes: &[u8],
11218    gpr: usize,
11219    rp_off: usize,
11220    ent_off: usize,
11221    has_ov: bool,
11222    x: &[f32],
11223    out: SendMut,
11224    start: usize,
11225    end: usize,
11226) {
11227    const TILE: usize = cortiq_core::quant::Q1T_TILE;
11228    let mut sg = [0f32; GROUP_SIZE];
11229    for r in start..end {
11230        let mut acc = 0f32;
11231        for g in 0..gpr {
11232            let off = (r * gpr + g) * TILE;
11233            let s = f16_to_f32(u16::from_le_bytes([bytes[off], bytes[off + 1]]));
11234            let codes = &bytes[off + 2..off + TILE];
11235            let xg = &x[g * GROUP_SIZE..g * GROUP_SIZE + GROUP_SIZE];
11236            for bi in 0..6 {
11237                sg[bi * 5..bi * 5 + 5].copy_from_slice(&SIGN5[codes[bi] as usize]);
11238            }
11239            let lut = &SIGN5[codes[6] as usize];
11240            sg[30] = lut[0];
11241            sg[31] = lut[1];
11242            let mut gsum = 0f32;
11243            for k in 0..GROUP_SIZE {
11244                gsum += sg[k] * xg[k];
11245            }
11246            acc += s * gsum;
11247        }
11248        acc += q1t_row_outlier_correction(bytes, r, rp_off, ent_off, has_ov, x);
11249        // SAFETY: disjoint row ranges per worker.
11250        unsafe { *out.at(r) = acc };
11251    }
11252}
11253
11254/// Ternary (q1t) matvec — decode+dot straight from mmap, one group at a time:
11255/// no per-ROW buffer, no division (the sign LUT), and a tiny per-group sign
11256/// buffer so the 32-wide dot vectorizes. This is the decode hot path.
11257fn q1t_matvec(
11258    bytes: &[u8],
11259    x: &[f32],
11260    rows: usize,
11261    cols: usize,
11262    out: &mut [f32],
11263    pool: Option<&Pool>,
11264) {
11265    debug_assert_eq!(out.len(), rows);
11266    const TILE: usize = cortiq_core::quant::Q1T_TILE;
11267    let gpr = cols / GROUP_SIZE;
11268    let (rp_off, ent_off, has_ov) = q1t_overlay(bytes, rows * gpr * TILE, rows);
11269    let out_addr = SendMut(out.as_mut_ptr());
11270    // int8 SDOT base dot (ARM dotprod): ~4× the f32 arithmetic. x → i8 once
11271    // (`split_act`), activation outliers added back exactly in f32, weight
11272    // overlay on top. ARM SDOT / x86 AVX2; CMF_SDOT=0 keeps the exact f32 path.
11273    if a8w8_enabled() {
11274        let act = split_act(x);
11275        let act = &act;
11276        let run = move |start: usize, end: usize| {
11277            for r in start..end {
11278                let mut acc = q1t_dot_row_i8(bytes, r, gpr, &act.xq) * act.sx;
11279                for &(j, xv) in &act.outliers {
11280                    acc += q1t_base_weight(bytes, r, gpr, j) * xv;
11281                }
11282                acc += q1t_row_outlier_correction(bytes, r, rp_off, ent_off, has_ov, x);
11283                // SAFETY: disjoint row ranges per worker.
11284                unsafe { *out_addr.at(r) = acc };
11285            }
11286        };
11287        dispatch_rows(pool, rows, &run);
11288        return;
11289    }
11290    let run = move |start: usize, end: usize| {
11291        // Per-group signs, unpacked contiguously so the dot below is a clean
11292        // 32-wide reduction the autovectorizer turns into f32x4 FMAs — the
11293        // 5-values-per-byte base-3 layout won't SIMD in place.
11294        let mut sg = [0f32; GROUP_SIZE];
11295        for r in start..end {
11296            let mut acc = 0f32;
11297            for g in 0..gpr {
11298                let off = (r * gpr + g) * TILE;
11299                let s = f16_to_f32(u16::from_le_bytes([bytes[off], bytes[off + 1]]));
11300                let codes = &bytes[off + 2..off + TILE];
11301                let xg = &x[g * GROUP_SIZE..g * GROUP_SIZE + GROUP_SIZE];
11302                for bi in 0..6 {
11303                    sg[bi * 5..bi * 5 + 5].copy_from_slice(&SIGN5[codes[bi] as usize]);
11304                }
11305                let lut = &SIGN5[codes[6] as usize];
11306                sg[30] = lut[0];
11307                sg[31] = lut[1];
11308                let mut gsum = 0f32;
11309                for k in 0..GROUP_SIZE {
11310                    gsum += sg[k] * xg[k];
11311                }
11312                acc += s * gsum;
11313            }
11314            acc += q1t_row_outlier_correction(bytes, r, rp_off, ent_off, has_ov, x);
11315            unsafe { *out_addr.at(r) = acc };
11316        }
11317    };
11318    dispatch_rows(pool, rows, &run);
11319}
11320
11321/// Fused-pair twin of `q1t_dot_row_sdot`: ONE register unpack of the
11322/// ternary codes serves BOTH activation streams (the unpack chain is
11323/// the dominant per-row cost — MTP verify pairs paid it twice). Per
11324/// stream the group order and f32 accumulation match the single-row
11325/// kernel exactly, so pair == 2×matvec bit-for-bit.
11326#[cfg(target_arch = "aarch64")]
11327#[target_feature(enable = "neon,dotprod")]
11328unsafe fn q1t_dot_row_sdot2(bytes: &[u8], r: usize, gpr: usize, xa: &[i8], xb: &[i8]) -> [f32; 2] {
11329    use core::arch::aarch64::*;
11330    use core::arch::asm;
11331    // SAFETY: same slice-length contracts as `q1t_dot_row_sdot`, ×2.
11332    unsafe {
11333        const TILE: usize = cortiq_core::quant::Q1T_TILE;
11334        let bytes_ptr = bytes.as_ptr();
11335        let row_off = r * gpr * TILE;
11336        let xp = [xa.as_ptr(), xb.as_ptr()];
11337        let mut acc = [0f32; 2];
11338        macro_rules! sdot2 {
11339            ($w0:expr, $w1:expr, $x:expr) => {{
11340                let x0 = vld1q_s8($x);
11341                let x1 = vld1q_s8($x.add(16));
11342                let (mut a0, mut a1) = (vdupq_n_s32(0), vdupq_n_s32(0));
11343                asm!(
11344                    "sdot {a0:v}.4s, {w0:v}.16b, {x0:v}.16b",
11345                    "sdot {a1:v}.4s, {w1:v}.16b, {x1:v}.16b",
11346                    a0 = inout(vreg) a0, a1 = inout(vreg) a1,
11347                    w0 = in(vreg) $w0, x0 = in(vreg) x0, w1 = in(vreg) $w1, x1 = in(vreg) x1,
11348                    options(pure, nomem, nostack),
11349                );
11350                vaddvq_s32(vaddq_s32(a0, a1))
11351            }};
11352        }
11353        let gpr2 = gpr & !1;
11354        let mut gi = 0;
11355        while gi < gpr2 {
11356            let off0 = row_off + gi * TILE;
11357            let off1 = off0 + TILE;
11358            let s0 = f16_to_f32(u16::from_le_bytes([
11359                *bytes_ptr.add(off0),
11360                *bytes_ptr.add(off0 + 1),
11361            ]));
11362            let s1 = f16_to_f32(u16::from_le_bytes([
11363                *bytes_ptr.add(off1),
11364                *bytes_ptr.add(off1 + 1),
11365            ]));
11366            let (u0_0, u1_0, u2_0, u3_0) = q1t_unpack_reg_u64s(bytes_ptr.add(off0 + 2));
11367            let (u0_1, u1_1, u2_1, u3_1) = q1t_unpack_reg_u64s(bytes_ptr.add(off1 + 2));
11368            let w0_0 = vreinterpretq_s8_u64(vcombine_u64(vcreate_u64(u0_0), vcreate_u64(u1_0)));
11369            let w1_0 = vreinterpretq_s8_u64(vcombine_u64(vcreate_u64(u2_0), vcreate_u64(u3_0)));
11370            let w0_1 = vreinterpretq_s8_u64(vcombine_u64(vcreate_u64(u0_1), vcreate_u64(u1_1)));
11371            let w1_1 = vreinterpretq_s8_u64(vcombine_u64(vcreate_u64(u2_1), vcreate_u64(u3_1)));
11372            for k in 0..2 {
11373                let d0 = sdot2!(w0_0, w1_0, xp[k].add(gi * GROUP_SIZE));
11374                let d1 = sdot2!(w0_1, w1_1, xp[k].add((gi + 1) * GROUP_SIZE));
11375                acc[k] += d0 as f32 * s0 + d1 as f32 * s1;
11376            }
11377            gi += 2;
11378        }
11379        if gi < gpr {
11380            let off = row_off + gi * TILE;
11381            let s = f16_to_f32(u16::from_le_bytes([
11382                *bytes_ptr.add(off),
11383                *bytes_ptr.add(off + 1),
11384            ]));
11385            let (u0, u1, u2, u3) = q1t_unpack_reg_u64s(bytes_ptr.add(off + 2));
11386            let w0 = vreinterpretq_s8_u64(vcombine_u64(vcreate_u64(u0), vcreate_u64(u1)));
11387            let w1 = vreinterpretq_s8_u64(vcombine_u64(vcreate_u64(u2), vcreate_u64(u3)));
11388            for k in 0..2 {
11389                let d = sdot2!(w0, w1, xp[k].add(gi * GROUP_SIZE));
11390                acc[k] += d as f32 * s;
11391            }
11392        }
11393        acc
11394    }
11395}
11396
11397/// Fused Q1T pair matvec: ONE pass over the rows serves both
11398/// activation streams — on ARM the ternary register unpack happens
11399/// once per tile pair (`q1t_dot_row_sdot2`); elsewhere the second dot
11400/// rides the row's L1-warm tile bytes. Per stream the math matches
11401/// `q1t_matvec` exactly.
11402fn q1t_matvec2(
11403    bytes: &[u8],
11404    x1: &[f32],
11405    x2: &[f32],
11406    rows: usize,
11407    cols: usize,
11408    o1: &mut [f32],
11409    o2: &mut [f32],
11410    pool: Option<&Pool>,
11411) {
11412    debug_assert_eq!(o1.len(), rows);
11413    debug_assert_eq!(o2.len(), rows);
11414    const TILE: usize = cortiq_core::quant::Q1T_TILE;
11415    let gpr = cols / GROUP_SIZE;
11416    let (rp_off, ent_off, has_ov) = q1t_overlay(bytes, rows * gpr * TILE, rows);
11417    let out1 = SendMut(o1.as_mut_ptr());
11418    let out2 = SendMut(o2.as_mut_ptr());
11419    if a8w8_enabled() {
11420        let a1 = split_act(x1);
11421        let a2 = split_act(x2);
11422        let (a1, a2) = (&a1, &a2);
11423        let run = move |start: usize, end: usize| {
11424            for r in start..end {
11425                #[cfg(target_arch = "aarch64")]
11426                // a8w8 on aarch64 ⇔ sdot_enabled(), so the kernel's
11427                // target features are present.
11428                let ds = unsafe { q1t_dot_row_sdot2(bytes, r, gpr, &a1.xq, &a2.xq) };
11429                #[cfg(not(target_arch = "aarch64"))]
11430                let ds = [
11431                    q1t_dot_row_i8(bytes, r, gpr, &a1.xq),
11432                    q1t_dot_row_i8(bytes, r, gpr, &a2.xq),
11433                ];
11434                let mut acc1 = ds[0] * a1.sx;
11435                for &(j, xv) in &a1.outliers {
11436                    acc1 += q1t_base_weight(bytes, r, gpr, j) * xv;
11437                }
11438                acc1 += q1t_row_outlier_correction(bytes, r, rp_off, ent_off, has_ov, x1);
11439                let mut acc2 = ds[1] * a2.sx;
11440                for &(j, xv) in &a2.outliers {
11441                    acc2 += q1t_base_weight(bytes, r, gpr, j) * xv;
11442                }
11443                acc2 += q1t_row_outlier_correction(bytes, r, rp_off, ent_off, has_ov, x2);
11444                // SAFETY: disjoint row ranges per worker.
11445                unsafe {
11446                    *out1.at(r) = acc1;
11447                    *out2.at(r) = acc2;
11448                }
11449            }
11450        };
11451        dispatch_rows(pool, rows, &run);
11452        return;
11453    }
11454    let run = move |start: usize, end: usize| {
11455        // Exact path (CMF_SDOT=0): unpack the sign LUT once per group,
11456        // dot both streams — same op order per stream as `q1t_matvec`.
11457        let mut sg = [0f32; GROUP_SIZE];
11458        for r in start..end {
11459            let mut acc1 = 0f32;
11460            let mut acc2 = 0f32;
11461            for g in 0..gpr {
11462                let off = (r * gpr + g) * TILE;
11463                let s = f16_to_f32(u16::from_le_bytes([bytes[off], bytes[off + 1]]));
11464                let codes = &bytes[off + 2..off + TILE];
11465                for bi in 0..6 {
11466                    sg[bi * 5..bi * 5 + 5].copy_from_slice(&SIGN5[codes[bi] as usize]);
11467                }
11468                let lut = &SIGN5[codes[6] as usize];
11469                sg[30] = lut[0];
11470                sg[31] = lut[1];
11471                let xg1 = &x1[g * GROUP_SIZE..g * GROUP_SIZE + GROUP_SIZE];
11472                let xg2 = &x2[g * GROUP_SIZE..g * GROUP_SIZE + GROUP_SIZE];
11473                let mut gsum1 = 0f32;
11474                for k in 0..GROUP_SIZE {
11475                    gsum1 += sg[k] * xg1[k];
11476                }
11477                acc1 += s * gsum1;
11478                let mut gsum2 = 0f32;
11479                for k in 0..GROUP_SIZE {
11480                    gsum2 += sg[k] * xg2[k];
11481                }
11482                acc2 += s * gsum2;
11483            }
11484            acc1 += q1t_row_outlier_correction(bytes, r, rp_off, ent_off, has_ov, x1);
11485            acc2 += q1t_row_outlier_correction(bytes, r, rp_off, ent_off, has_ov, x2);
11486            // SAFETY: disjoint row ranges per worker.
11487            unsafe {
11488                *out1.at(r) = acc1;
11489                *out2.at(r) = acc2;
11490            }
11491        }
11492    };
11493    dispatch_rows(pool, rows, &run);
11494}
11495
11496/// Ternary (q1t) matmat (prefill) — dequant each row once, dot the whole
11497/// batch against it (amortizes the per-row decode).
11498fn q1t_matmat(
11499    bytes: &[u8],
11500    xs: &[f32],
11501    b: usize,
11502    rows: usize,
11503    cols: usize,
11504    out: &mut [f32],
11505    pool: Option<&Pool>,
11506) {
11507    debug_assert_eq!(out.len(), b * rows);
11508    const TILE: usize = cortiq_core::quant::Q1T_TILE;
11509    let gpr = cols / GROUP_SIZE;
11510    let (rp_off, ent_off, has_ov) = q1t_overlay(bytes, rows * gpr * TILE, rows);
11511    let out_addr = SendMut(out.as_mut_ptr());
11512    // int8 prefill (ARM SDOT / x86 AVX2): quantize the B inputs once, unpack
11513    // each weight row's signs to i8 ONCE, then int8-dot against every input —
11514    // the row sign-decode amortizes over the whole batch. CMF_SDOT=0 → f32.
11515    if a8w8_enabled() {
11516        let acts: Vec<SplitAct> = (0..b)
11517            .map(|bi| split_act(&xs[bi * cols..(bi + 1) * cols]))
11518            .collect();
11519        let acts = &acts;
11520        let run = move |start: usize, end: usize| {
11521            let mut sg = vec![0i8; cols + 8]; // row signs, i8 (+8 unpack slack)
11522            let mut sc = vec![0f32; gpr]; // per-group scales
11523            let mut accs = vec![0f32; b]; // per-batch accumulators, reused per row
11524            for r in start..end {
11525                for g in 0..gpr {
11526                    let off = (r * gpr + g) * TILE;
11527                    sc[g] = f16_to_f32(u16::from_le_bytes([bytes[off], bytes[off + 1]]));
11528                    q1t_unpack_group_i8(
11529                        bytes.as_ptr().wrapping_add(off + 2),
11530                        &mut sg[g * GROUP_SIZE..],
11531                    );
11532                }
11533                for bi in 0..b {
11534                    let act = &acts[bi];
11535                    let mut isum = 0f32;
11536                    for g in 0..gpr {
11537                        let d = q1t_i8dot32(
11538                            sg.as_ptr().wrapping_add(g * GROUP_SIZE),
11539                            act.xq.as_ptr().wrapping_add(g * GROUP_SIZE),
11540                        );
11541                        isum += d as f32 * sc[g];
11542                    }
11543                    let mut acc = isum * act.sx;
11544                    for &(j, xv) in &act.outliers {
11545                        acc += q1t_base_weight(bytes, r, gpr, j) * xv;
11546                    }
11547                    accs[bi] = acc;
11548                }
11549                // Overlay ONCE per row for the whole batch: read each (col, val)
11550                // from mmap a single time (was b× — the re-read dominated prefill)
11551                // and fan it out over the batch via the cached inputs.
11552                if has_ov {
11553                    let (c0, c1) = (
11554                        q1t_rowptr(bytes, rp_off, r),
11555                        q1t_rowptr(bytes, rp_off, r + 1),
11556                    );
11557                    for p in c0..c1 {
11558                        let e = ent_off + p * 4;
11559                        let col = u16::from_le_bytes([bytes[e], bytes[e + 1]]) as usize;
11560                        let val = f16_to_f32(u16::from_le_bytes([bytes[e + 2], bytes[e + 3]]));
11561                        for bi in 0..b {
11562                            accs[bi] += val * xs[bi * cols + col];
11563                        }
11564                    }
11565                }
11566                for bi in 0..b {
11567                    unsafe { *out_addr.at(bi * rows + r) = accs[bi] };
11568                }
11569            }
11570        };
11571        dispatch_rows(pool, rows, &run);
11572        return;
11573    }
11574    let run = move |start: usize, end: usize| {
11575        let mut buf = vec![0f32; cols];
11576        for r in start..end {
11577            q1t_dequant_row(bytes, r, gpr, rp_off, ent_off, has_ov, &mut buf);
11578            for bi in 0..b {
11579                let xr = &xs[bi * cols..(bi + 1) * cols];
11580                let mut acc = 0f32;
11581                for j in 0..cols {
11582                    acc += buf[j] * xr[j];
11583                }
11584                unsafe { *out_addr.at(bi * rows + r) = acc };
11585            }
11586        }
11587    };
11588    dispatch_rows(pool, rows, &run);
11589}
11590
11591/// q1-tile entry points of the binary drivers (the tests' handles; the
11592/// runtime goes through `QTensor::bin_w`).
11593#[cfg(test)]
11594fn q1_matvec(
11595    bytes: &[u8],
11596    x: &[f32],
11597    rows: usize,
11598    cols: usize,
11599    out: &mut [f32],
11600    pool: Option<&Pool>,
11601) {
11602    bin_matvec(BinW::Q1(bytes), x, rows, cols, out, pool)
11603}
11604
11605/// Binary-weight matvec (q1 or q1g): A8W8 rows with the shared group
11606/// sums, or the exact scalar walk under CMF_SDOT=0.
11607fn bin_matvec(w: BinW, x: &[f32], rows: usize, cols: usize, out: &mut [f32], pool: Option<&Pool>) {
11608    debug_assert_eq!(out.len(), rows);
11609    let gpr = cols / GROUP_SIZE;
11610    let out_addr = SendMut(out.as_mut_ptr());
11611    if a8w8_enabled() {
11612        let act = split_act(x);
11613        let gsum = q1_group_sums(&act.xq, gpr);
11614        let (act, gsum) = (&act, &gsum);
11615        let run =
11616            move |start: usize, end: usize| bin_range_a8w8(w, gpr, act, gsum, out_addr, start, end);
11617        dispatch_rows(pool, rows, &run);
11618        return;
11619    }
11620    let run = move |start: usize, end: usize| bin_range_f32(w, gpr, x, out_addr, start, end);
11621    dispatch_rows(pool, rows, &run);
11622}
11623
11624/// Fused two-input q1 matvec (weights read once per pair).
11625#[cfg(test)]
11626#[allow(clippy::too_many_arguments)]
11627fn q1_matvec2(
11628    bytes: &[u8],
11629    x1: &[f32],
11630    x2: &[f32],
11631    rows: usize,
11632    cols: usize,
11633    o1: &mut [f32],
11634    o2: &mut [f32],
11635    pool: Option<&Pool>,
11636) {
11637    bin_matvec2(BinW::Q1(bytes), x1, x2, rows, cols, o1, o2, pool)
11638}
11639
11640/// Fused two-input binary-weight matvec (q1 or q1g).
11641#[allow(clippy::too_many_arguments)]
11642fn bin_matvec2(
11643    w: BinW,
11644    x1: &[f32],
11645    x2: &[f32],
11646    rows: usize,
11647    cols: usize,
11648    o1: &mut [f32],
11649    o2: &mut [f32],
11650    pool: Option<&Pool>,
11651) {
11652    let gpr = cols / GROUP_SIZE;
11653    let p1 = SendMut(o1.as_mut_ptr());
11654    let p2 = SendMut(o2.as_mut_ptr());
11655    if a8w8_enabled() {
11656        let a1 = split_act(x1);
11657        let a2 = split_act(x2);
11658        let g1 = q1_group_sums(&a1.xq, gpr);
11659        let g2 = q1_group_sums(&a2.xq, gpr);
11660        let (a1, a2, g1, g2) = (&a1, &a2, &g1, &g2);
11661        let run = move |start: usize, end: usize| {
11662            for r in start..end {
11663                let mut v1 = w.dot_i8(r, gpr, &a1.xq, g1) * a1.sx;
11664                let mut v2 = w.dot_i8(r, gpr, &a2.xq, g2) * a2.sx;
11665                for &(j, xv) in &a1.outliers {
11666                    let (wv, s) = w.outlier(r, gpr, j);
11667                    v1 += wv * s * xv;
11668                }
11669                for &(j, xv) in &a2.outliers {
11670                    let (wv, s) = w.outlier(r, gpr, j);
11671                    v2 += wv * s * xv;
11672                }
11673                // SAFETY: disjoint row ranges per worker.
11674                unsafe {
11675                    *p1.at(r) = v1;
11676                    *p2.at(r) = v2;
11677                }
11678            }
11679        };
11680        dispatch_rows(pool, rows, &run);
11681        return;
11682    }
11683    let run = move |start: usize, end: usize| {
11684        for r in start..end {
11685            // SAFETY: disjoint row ranges per worker.
11686            unsafe {
11687                *p1.at(r) = w.row_exact(r, gpr, x1);
11688                *p2.at(r) = w.row_exact(r, gpr, x2);
11689            }
11690        }
11691    };
11692    dispatch_rows(pool, rows, &run);
11693}
11694
11695/// Batched q1 matmat: each row's tiles stream once per microbatch.
11696#[cfg(test)]
11697#[allow(clippy::too_many_arguments)]
11698fn q1_matmat(
11699    bytes: &[u8],
11700    xs_all: &[f32],
11701    b: usize,
11702    rows: usize,
11703    cols: usize,
11704    out: &mut [f32],
11705    pool: Option<&Pool>,
11706) {
11707    bin_matmat(BinW::Q1(bytes), xs_all, b, rows, cols, out, pool)
11708}
11709
11710/// Batched binary-weight matmat (q1 or q1g).
11711#[allow(clippy::too_many_arguments)]
11712fn bin_matmat(
11713    w: BinW,
11714    xs_all: &[f32],
11715    b: usize,
11716    rows: usize,
11717    cols: usize,
11718    out: &mut [f32],
11719    pool: Option<&Pool>,
11720) {
11721    debug_assert_eq!(out.len(), b * rows);
11722    let gpr = cols / GROUP_SIZE;
11723    let out_addr = SendMut(out.as_mut_ptr());
11724    if a8w8_enabled() {
11725        let acts: Vec<(SplitAct, Vec<i32>)> = (0..b)
11726            .map(|bi| {
11727                let act = split_act(&xs_all[bi * cols..(bi + 1) * cols]);
11728                let gsum = q1_group_sums(&act.xq, gpr);
11729                (act, gsum)
11730            })
11731            .collect();
11732        let acts = &acts;
11733        #[cfg(target_arch = "x86_64")]
11734        let blocked_ok = avx2_enabled() && blocked_enabled();
11735        #[cfg(target_arch = "aarch64")]
11736        let blocked_ok = sdot_enabled() && blocked_enabled();
11737        let run = move |start: usize, end: usize| {
11738            for r in start..end {
11739                let mut bi = 0usize;
11740                // Blocked 1×4: the unpacked bit mask serves four
11741                // activation streams per group.
11742                #[cfg(target_arch = "aarch64")]
11743                if blocked_ok {
11744                    while bi + 4 <= acts.len() {
11745                        let xs = [
11746                            acts[bi].0.xq.as_slice(),
11747                            acts[bi + 1].0.xq.as_slice(),
11748                            acts[bi + 2].0.xq.as_slice(),
11749                            acts[bi + 3].0.xq.as_slice(),
11750                        ];
11751                        let gs = [
11752                            acts[bi].1.as_slice(),
11753                            acts[bi + 1].1.as_slice(),
11754                            acts[bi + 2].1.as_slice(),
11755                            acts[bi + 3].1.as_slice(),
11756                        ];
11757                        // SAFETY: blocked_ok checked SDOT.
11758                        let d = unsafe { w.dot_1x4_sdot(r, gpr, xs, gs) };
11759                        for k in 0..4 {
11760                            let (act, _) = &acts[bi + k];
11761                            let mut acc = d[k] * act.sx;
11762                            for &(j, xv) in &act.outliers {
11763                                let (wv, sc) = w.outlier(r, gpr, j);
11764                                acc += wv * sc * xv;
11765                            }
11766                            // SAFETY: disjoint (bi, r) cells per worker.
11767                            unsafe { *out_addr.at((bi + k) * rows + r) = acc };
11768                        }
11769                        bi += 4;
11770                    }
11771                }
11772                #[cfg(target_arch = "x86_64")]
11773                if blocked_ok {
11774                    while bi + 4 <= acts.len() {
11775                        let xs = [
11776                            acts[bi].0.xq.as_slice(),
11777                            acts[bi + 1].0.xq.as_slice(),
11778                            acts[bi + 2].0.xq.as_slice(),
11779                            acts[bi + 3].0.xq.as_slice(),
11780                        ];
11781                        let gs = [
11782                            acts[bi].1.as_slice(),
11783                            acts[bi + 1].1.as_slice(),
11784                            acts[bi + 2].1.as_slice(),
11785                            acts[bi + 3].1.as_slice(),
11786                        ];
11787                        // SAFETY: blocked_ok checked AVX2.
11788                        let d = unsafe { w.dot_1x4_x86(r, gpr, xs, gs) };
11789                        for k in 0..4 {
11790                            let (act, _) = &acts[bi + k];
11791                            let mut acc = d[k] * act.sx;
11792                            for &(j, xv) in &act.outliers {
11793                                let (wv, sc) = w.outlier(r, gpr, j);
11794                                acc += wv * sc * xv;
11795                            }
11796                            // SAFETY: disjoint (bi, r) cells per worker.
11797                            unsafe { *out_addr.at((bi + k) * rows + r) = acc };
11798                        }
11799                        bi += 4;
11800                    }
11801                }
11802                while bi < acts.len() {
11803                    let (act, gsum) = &acts[bi];
11804                    let mut acc = w.dot_i8(r, gpr, &act.xq, gsum) * act.sx;
11805                    for &(j, xv) in &act.outliers {
11806                        let (wv, s) = w.outlier(r, gpr, j);
11807                        acc += wv * s * xv;
11808                    }
11809                    // SAFETY: disjoint (bi, r) cells per worker range.
11810                    unsafe { *out_addr.at(bi * rows + r) = acc };
11811                    bi += 1;
11812                }
11813            }
11814        };
11815        dispatch_rows(pool, rows, &run);
11816        return;
11817    }
11818    let run = move |start: usize, end: usize| {
11819        for r in start..end {
11820            for bi in 0..b {
11821                let x = &xs_all[bi * cols..(bi + 1) * cols];
11822                // SAFETY: disjoint (bi, r) cells per worker range.
11823                unsafe { *out_addr.at(bi * rows + r) = w.row_exact(r, gpr, x) };
11824            }
11825        }
11826    };
11827    dispatch_rows(pool, rows, &run);
11828}
11829
11830/// Fused q4_block matvec straight from the mapped bytes. SDOT path when
11831/// dotprod is available (port of vmfcore `dot_q4_block_sdot`, measured
11832/// +23% on q4 decode): nibbles → centered i8, int8×int8 `sdot` per
11833/// 32-group, exact outlier correction — the same A8W8 contract as q8.
11834/// `CMF_SDOT=0` keeps the exact scalar path.
11835fn q4matvec(
11836    bytes: &[u8],
11837    x: &[f32],
11838    rows: usize,
11839    cols: usize,
11840    out: &mut [f32],
11841    pool: Option<&Pool>,
11842) {
11843    debug_assert_eq!(out.len(), rows);
11844    let (packed, scales) = q4_split(bytes, rows, cols);
11845    let gpr = cols / GROUP_SIZE;
11846    let out_addr = SendMut(out.as_mut_ptr());
11847
11848    if a8w8_enabled() {
11849        let act = split_act(x);
11850        let run = move |start: usize, end: usize| {
11851            q4_range_a8w8(packed, scales, gpr, cols, &act, out_addr, start, end)
11852        };
11853        dispatch_rows(pool, rows, &run);
11854        return;
11855    }
11856
11857    let run =
11858        move |start: usize, end: usize| q4_range_f32(packed, scales, gpr, x, out_addr, start, end);
11859    dispatch_rows(pool, rows, &run);
11860}
11861
11862/// One q4 row via the A8W8 int8 path — SDOT on ARM, AVX2 maddubs on
11863/// x86 (scalar fallback is unreachable: callers gate on a8w8_enabled).
11864#[inline]
11865#[allow(unreachable_code)]
11866/// One UNPACKED q4 row (centered i8 in `buf`) against four activation
11867/// streams: the 32-byte weight chunk and its abs() load once per group,
11868/// the per-group f16 scale decodes once — four maddubs+reduce chains
11869/// instead of four full (load, abs, dot) rounds.
11870#[cfg(target_arch = "x86_64")]
11871#[target_feature(enable = "avx2")]
11872unsafe fn dot_q4b_row_1x4_avx2(
11873    buf: &[u8],
11874    scales: &[u8],
11875    g0: usize,
11876    gpr: usize,
11877    xs: [&[i8]; 4],
11878) -> [f32; 4] {
11879    // SAFETY: callers uphold buffer contracts (buf.len() == gpr·32).
11880    unsafe {
11881        use core::arch::x86_64::*;
11882        let ones = _mm256_set1_epi16(1);
11883        let mut acc = [0f32; 4];
11884        for gi in 0..gpr {
11885            let s = f16_to_f32(u16::from_le_bytes([
11886                scales[(g0 + gi) * 2],
11887                scales[(g0 + gi) * 2 + 1],
11888            ]));
11889            let w = _mm256_loadu_si256(buf.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
11890            let aw = _mm256_abs_epi8(w);
11891            for (k, xq) in xs.iter().enumerate() {
11892                let x = _mm256_loadu_si256(xq.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
11893                let p16 = _mm256_maddubs_epi16(aw, _mm256_sign_epi8(x, w));
11894                let d = _mm256_madd_epi16(p16, ones);
11895                let hi128 = _mm256_extracti128_si256::<1>(d);
11896                let s128 = _mm_add_epi32(_mm256_castsi256_si128(d), hi128);
11897                let s64 = _mm_add_epi32(s128, _mm_srli_si128::<8>(s128));
11898                let s32 = _mm_add_epi32(s64, _mm_srli_si128::<4>(s64));
11899                acc[k] += _mm_cvtsi128_si32(s32) as f32 * s;
11900            }
11901        }
11902        acc
11903    }
11904}
11905
11906/// VNNI twin of `dot_q4b_row_1x4_avx2` (see `dpbusd_hsum`).
11907#[cfg(target_arch = "x86_64")]
11908#[target_feature(enable = "avx2,avx512f,avx512bw,avx512vl,avx512vnni")]
11909unsafe fn dot_q4b_row_1x4_vnni(
11910    buf: &[u8],
11911    scales: &[u8],
11912    g0: usize,
11913    gpr: usize,
11914    xs: [&[i8]; 4],
11915) -> [f32; 4] {
11916    // SAFETY: callers uphold buffer contracts (buf.len() == gpr·32).
11917    unsafe {
11918        use core::arch::x86_64::*;
11919        let mut acc = [0f32; 4];
11920        for gi in 0..gpr {
11921            let s = f16_to_f32(u16::from_le_bytes([
11922                scales[(g0 + gi) * 2],
11923                scales[(g0 + gi) * 2 + 1],
11924            ]));
11925            let w = _mm256_loadu_si256(buf.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
11926            let aw = _mm256_abs_epi8(w);
11927            for (k, xq) in xs.iter().enumerate() {
11928                let x = _mm256_loadu_si256(xq.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
11929                let d = dpbusd_hsum(aw, _mm256_sign_epi8(x, w));
11930                acc[k] += d as f32 * s;
11931            }
11932        }
11933        acc
11934    }
11935}
11936
11937/// The vbit flavor of the blocked 1×4: the per-activation A8W8 scale
11938/// folds in PER GROUP as `(d·sx)·s` — bit-matching the single-matvec
11939/// accumulation order (the q4_block flavor applies sx once at the end,
11940/// matching ITS single path; the two conventions are historical and
11941/// each blocked leg must mirror its own).
11942#[cfg(target_arch = "x86_64")]
11943#[target_feature(enable = "avx2")]
11944unsafe fn dot_q4b_row_1x4_sx_avx2(
11945    buf: &[u8],
11946    scales: &[u8],
11947    g0: usize,
11948    gpr: usize,
11949    xs: [&[i8]; 4],
11950    sxs: [f32; 4],
11951) -> [f32; 4] {
11952    // SAFETY: callers uphold buffer contracts (buf.len() == gpr·32).
11953    unsafe {
11954        use core::arch::x86_64::*;
11955        let ones = _mm256_set1_epi16(1);
11956        let mut acc = [0f32; 4];
11957        for gi in 0..gpr {
11958            let s = f16_to_f32(u16::from_le_bytes([
11959                scales[(g0 + gi) * 2],
11960                scales[(g0 + gi) * 2 + 1],
11961            ]));
11962            let w = _mm256_loadu_si256(buf.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
11963            let aw = _mm256_abs_epi8(w);
11964            for (k, xq) in xs.iter().enumerate() {
11965                let x = _mm256_loadu_si256(xq.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
11966                let p16 = _mm256_maddubs_epi16(aw, _mm256_sign_epi8(x, w));
11967                let d = _mm256_madd_epi16(p16, ones);
11968                let hi128 = _mm256_extracti128_si256::<1>(d);
11969                let s128 = _mm_add_epi32(_mm256_castsi256_si128(d), hi128);
11970                let s64 = _mm_add_epi32(s128, _mm_srli_si128::<8>(s128));
11971                let s32 = _mm_add_epi32(s64, _mm_srli_si128::<4>(s64));
11972                acc[k] += (_mm_cvtsi128_si32(s32) as f32 * sxs[k]) * s;
11973            }
11974        }
11975        acc
11976    }
11977}
11978
11979/// VNNI twin of `dot_q4b_row_1x4_sx_avx2` (see `dpbusd_hsum`; the
11980/// per-group `(d·sx)·s` fold mirrors the vbit single path).
11981#[cfg(target_arch = "x86_64")]
11982#[target_feature(enable = "avx2,avx512f,avx512bw,avx512vl,avx512vnni")]
11983unsafe fn dot_q4b_row_1x4_sx_vnni(
11984    buf: &[u8],
11985    scales: &[u8],
11986    g0: usize,
11987    gpr: usize,
11988    xs: [&[i8]; 4],
11989    sxs: [f32; 4],
11990) -> [f32; 4] {
11991    // SAFETY: callers uphold buffer contracts (buf.len() == gpr·32).
11992    unsafe {
11993        use core::arch::x86_64::*;
11994        let mut acc = [0f32; 4];
11995        for gi in 0..gpr {
11996            let s = f16_to_f32(u16::from_le_bytes([
11997                scales[(g0 + gi) * 2],
11998                scales[(g0 + gi) * 2 + 1],
11999            ]));
12000            let w = _mm256_loadu_si256(buf.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
12001            let aw = _mm256_abs_epi8(w);
12002            for (k, xq) in xs.iter().enumerate() {
12003                let x = _mm256_loadu_si256(xq.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
12004                let d = dpbusd_hsum(aw, _mm256_sign_epi8(x, w));
12005                acc[k] += (d as f32 * sxs[k]) * s;
12006            }
12007        }
12008        acc
12009    }
12010}
12011
12012#[allow(unreachable_code)]
12013fn dot_q4_row_i8(packed: &[u8], scales: &[u8], g0: usize, gpr: usize, xq: &[i8]) -> f32 {
12014    #[cfg(target_arch = "aarch64")]
12015    unsafe {
12016        return dot_q4_row_sdot(packed, scales, g0, gpr, xq);
12017    }
12018    #[cfg(target_arch = "x86_64")]
12019    unsafe {
12020        return dot_q4_row_avx2(packed, scales, g0, gpr, xq);
12021    }
12022    let mut acc = 0f32;
12023    for gi in 0..gpr {
12024        let g = g0 + gi;
12025        let s = f16_to_f32(u16::from_le_bytes([scales[g * 2], scales[g * 2 + 1]]));
12026        let mut d = 0i32;
12027        for (k, &b) in packed[g * 16..(g + 1) * 16].iter().enumerate() {
12028            d += ((b & 0x0F) as i32 - 8) * xq[gi * GROUP_SIZE + k * 2] as i32
12029                + (((b >> 4) & 0x0F) as i32 - 8) * xq[gi * GROUP_SIZE + k * 2 + 1] as i32;
12030        }
12031        acc += d as f32 * s;
12032    }
12033    acc
12034}
12035
12036/// Two-activation q4 row via the A8W8 int8 path (see `dot_q4_row_i8`).
12037#[inline]
12038#[allow(unreachable_code)]
12039fn dot_q4_row_i8_2(
12040    packed: &[u8],
12041    scales: &[u8],
12042    g0: usize,
12043    gpr: usize,
12044    xq1: &[i8],
12045    xq2: &[i8],
12046) -> (f32, f32) {
12047    #[cfg(target_arch = "aarch64")]
12048    unsafe {
12049        return dot_q4_row_sdot2(packed, scales, g0, gpr, xq1, xq2);
12050    }
12051    #[cfg(target_arch = "x86_64")]
12052    unsafe {
12053        return dot_q4_row_avx2_2(packed, scales, g0, gpr, xq1, xq2);
12054    }
12055    (
12056        dot_q4_row_i8(packed, scales, g0, gpr, xq1),
12057        dot_q4_row_i8(packed, scales, g0, gpr, xq2),
12058    )
12059}
12060
12061/// One q4 row range via SDOT (kernel body of `q4matvec`, extracted so
12062/// multi-matrix jobs can drive it for several tensors in one dispatch).
12063#[allow(clippy::too_many_arguments)]
12064fn q4_range_a8w8(
12065    packed: &[u8],
12066    scales: &[u8],
12067    gpr: usize,
12068    cols: usize,
12069    act: &SplitAct,
12070    out: SendMut,
12071    start: usize,
12072    end: usize,
12073) {
12074    for r in start..end {
12075        let mut acc = dot_q4_row_i8(packed, scales, r * gpr, gpr, &act.xq) * act.sx;
12076        // xq is zeroed at outlier slots — add the exact terms.
12077        for &(j, xv) in &act.outliers {
12078            let flat = r * cols + j;
12079            let byte = packed[flat / 2];
12080            let nib = if flat & 1 == 0 {
12081                byte & 0x0F
12082            } else {
12083                byte >> 4
12084            };
12085            let s = f16_to_f32(u16::from_le_bytes([
12086                scales[(flat / GROUP_SIZE) * 2],
12087                scales[(flat / GROUP_SIZE) * 2 + 1],
12088            ]));
12089            acc += ((nib as i32 - 8) as f32) * s * xv;
12090        }
12091        // SAFETY: disjoint row ranges per worker.
12092        unsafe { *out.at(r) = acc };
12093    }
12094}
12095
12096/// Two-input q4 row range via the A8W8 int8 path — kernel body of
12097/// `q4matvec2`, extracted for pair multi-matrix jobs.
12098#[allow(clippy::too_many_arguments)]
12099fn q4_range2_a8w8(
12100    packed: &[u8],
12101    scales: &[u8],
12102    gpr: usize,
12103    cols: usize,
12104    a1: &SplitAct,
12105    a2: &SplitAct,
12106    p1: SendMut,
12107    p2: SendMut,
12108    start: usize,
12109    end: usize,
12110) {
12111    for r in start..end {
12112        let (s1, s2) = dot_q4_row_i8_2(packed, scales, r * gpr, gpr, &a1.xq, &a2.xq);
12113        let mut acc1 = s1 * a1.sx;
12114        let mut acc2 = s2 * a2.sx;
12115        // xq is zeroed at outlier slots — add the exact terms.
12116        let fix = |outliers: &[(usize, f32)], acc: &mut f32| {
12117            for &(j, xv) in outliers {
12118                let flat = r * cols + j;
12119                let byte = packed[flat / 2];
12120                let nib = if flat & 1 == 0 {
12121                    byte & 0x0F
12122                } else {
12123                    byte >> 4
12124                };
12125                let s = f16_to_f32(u16::from_le_bytes([
12126                    scales[(flat / GROUP_SIZE) * 2],
12127                    scales[(flat / GROUP_SIZE) * 2 + 1],
12128                ]));
12129                *acc += ((nib as i32 - 8) as f32) * s * xv;
12130            }
12131        };
12132        fix(&a1.outliers, &mut acc1);
12133        fix(&a2.outliers, &mut acc2);
12134        // SAFETY: disjoint row ranges per worker.
12135        unsafe {
12136            *p1.at(r) = acc1;
12137            *p2.at(r) = acc2;
12138        }
12139    }
12140}
12141
12142/// Exact scalar q4 row range (same extraction, non-SDOT path).
12143fn q4_range_f32(
12144    packed: &[u8],
12145    scales: &[u8],
12146    gpr: usize,
12147    x: &[f32],
12148    out: SendMut,
12149    start: usize,
12150    end: usize,
12151) {
12152    for r in start..end {
12153        let mut acc = 0f32;
12154        for gi in 0..gpr {
12155            let g = r * gpr + gi;
12156            let s = f16_to_f32(u16::from_le_bytes([scales[g * 2], scales[g * 2 + 1]]));
12157            let pk = &packed[g * 16..(g + 1) * 16];
12158            let xg = &x[gi * GROUP_SIZE..(gi + 1) * GROUP_SIZE];
12159            let mut ga = 0f32;
12160            for (k, &b) in pk.iter().enumerate() {
12161                ga += ((b & 0x0F) as f32 - 8.0) * xg[k * 2]
12162                    + (((b >> 4) & 0x0F) as f32 - 8.0) * xg[k * 2 + 1];
12163            }
12164            acc += ga * s;
12165        }
12166        // SAFETY: disjoint row ranges per worker.
12167        unsafe { *out.at(r) = acc };
12168    }
12169}
12170
12171/// Fused two-input q4 matvec: nibbles are unpacked ONCE per group and
12172/// dotted against both activations (was: two full matvecs — double
12173/// weight traffic). Per-lane math matches `q4matvec` exactly.
12174#[allow(clippy::too_many_arguments)]
12175fn q4matvec2(
12176    bytes: &[u8],
12177    x1: &[f32],
12178    x2: &[f32],
12179    rows: usize,
12180    cols: usize,
12181    o1: &mut [f32],
12182    o2: &mut [f32],
12183    pool: Option<&Pool>,
12184) {
12185    debug_assert_eq!(o1.len(), rows);
12186    debug_assert_eq!(o2.len(), rows);
12187    let (packed, scales) = q4_split(bytes, rows, cols);
12188    let gpr = cols / GROUP_SIZE;
12189
12190    if a8w8_enabled() {
12191        let a1 = split_act(x1);
12192        let a2 = split_act(x2);
12193        let p1 = SendMut(o1.as_mut_ptr());
12194        let p2 = SendMut(o2.as_mut_ptr());
12195        let run = move |start: usize, end: usize| {
12196            q4_range2_a8w8(packed, scales, gpr, cols, &a1, &a2, p1, p2, start, end)
12197        };
12198        dispatch_rows(pool, rows, &run);
12199        return;
12200    }
12201
12202    let p1 = SendMut(o1.as_mut_ptr());
12203    let p2 = SendMut(o2.as_mut_ptr());
12204    let run = move |start: usize, end: usize| {
12205        q4_range2_f32(packed, scales, gpr, x1, x2, p1, p2, start, end)
12206    };
12207    dispatch_rows(pool, rows, &run);
12208}
12209
12210/// Two-input exact scalar q4 row range (same extraction).
12211#[allow(clippy::too_many_arguments)]
12212fn q4_range2_f32(
12213    packed: &[u8],
12214    scales: &[u8],
12215    gpr: usize,
12216    x1: &[f32],
12217    x2: &[f32],
12218    p1: SendMut,
12219    p2: SendMut,
12220    start: usize,
12221    end: usize,
12222) {
12223    for r in start..end {
12224        let (mut acc1, mut acc2) = (0f32, 0f32);
12225        for gi in 0..gpr {
12226            let g = r * gpr + gi;
12227            let s = f16_to_f32(u16::from_le_bytes([scales[g * 2], scales[g * 2 + 1]]));
12228            let pk = &packed[g * 16..(g + 1) * 16];
12229            let x1g = &x1[gi * GROUP_SIZE..(gi + 1) * GROUP_SIZE];
12230            let x2g = &x2[gi * GROUP_SIZE..(gi + 1) * GROUP_SIZE];
12231            let (mut g1, mut g2) = (0f32, 0f32);
12232            for (k, &b) in pk.iter().enumerate() {
12233                let wl = (b & 0x0F) as f32 - 8.0;
12234                let wh = ((b >> 4) & 0x0F) as f32 - 8.0;
12235                g1 += wl * x1g[k * 2] + wh * x1g[k * 2 + 1];
12236                g2 += wl * x2g[k * 2] + wh * x2g[k * 2 + 1];
12237            }
12238            acc1 += g1 * s;
12239            acc2 += g2 * s;
12240        }
12241        // SAFETY: disjoint row ranges per worker.
12242        unsafe {
12243            *p1.at(r) = acc1;
12244            *p2.at(r) = acc2;
12245        }
12246    }
12247}
12248
12249thread_local! {
12250    /// Per-worker decoded-row scratch for the batched q4/vbit kernels
12251    /// (centered i8 for SDOT, f32 for the exact/scalar paths).
12252    static ROW_I8: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
12253    static ROW_F32: std::cell::RefCell<Vec<f32>> = const { std::cell::RefCell::new(Vec::new()) };
12254}
12255
12256/// Batched q4 matmat: each weight row is unpacked from the mmap ONCE
12257/// and dotted against ALL b activations (prefill used to fall back to b
12258/// full matvecs — b× weight traffic and b× nibble decode). Per-position
12259/// math matches `q4matvec` exactly: same group order, same accumulation.
12260/// `out` is row-major [b, rows] like `qmatmat`.
12261#[allow(clippy::too_many_arguments)]
12262fn q4matmat(
12263    bytes: &[u8],
12264    xs_all: &[f32],
12265    b: usize,
12266    rows: usize,
12267    cols: usize,
12268    out: &mut [f32],
12269    pool: Option<&Pool>,
12270) {
12271    debug_assert_eq!(xs_all.len(), b * cols);
12272    debug_assert_eq!(out.len(), b * rows);
12273    let (packed, scales) = q4_split(bytes, rows, cols);
12274    let gpr = cols / GROUP_SIZE;
12275    let gscale = |g: usize| f16_to_f32(u16::from_le_bytes([scales[g * 2], scales[g * 2 + 1]]));
12276
12277    if a8w8_enabled() {
12278        let acts: Vec<SplitAct> = (0..b)
12279            .map(|bi| split_act(&xs_all[bi * cols..(bi + 1) * cols]))
12280            .collect();
12281        let acts = &acts;
12282        let out_addr = SendMut(out.as_mut_ptr());
12283        let run = move |start: usize, end: usize| {
12284            ROW_I8.with(|rb| {
12285                let mut buf = rb.borrow_mut();
12286                buf.resize(cols, 0);
12287                for r in start..end {
12288                    // Unpack the row's nibbles to centered i8 once
12289                    // (element 2k = low nibble, 2k+1 = high — flat order,
12290                    // same as dot_q4_row_sdot's zip).
12291                    for gi in 0..gpr {
12292                        let g = r * gpr + gi;
12293                        for (k, &bt) in packed[g * 16..(g + 1) * 16].iter().enumerate() {
12294                            buf[gi * GROUP_SIZE + k * 2] = ((bt & 0x0F) as i32 - 8) as i8 as u8;
12295                            buf[gi * GROUP_SIZE + k * 2 + 1] =
12296                                (((bt >> 4) & 0x0F) as i32 - 8) as i8 as u8;
12297                        }
12298                    }
12299                    let mut bi = 0usize;
12300                    #[cfg(target_arch = "x86_64")]
12301                    if avx2_enabled() && blocked_enabled() {
12302                        while bi + 4 <= acts.len() {
12303                            let xs = [
12304                                acts[bi].xq.as_slice(),
12305                                acts[bi + 1].xq.as_slice(),
12306                                acts[bi + 2].xq.as_slice(),
12307                                acts[bi + 3].xq.as_slice(),
12308                            ];
12309                            let d = unsafe {
12310                                if vnni_tiles_enabled() {
12311                                    dot_q4b_row_1x4_vnni(&buf, scales, r * gpr, gpr, xs)
12312                                } else {
12313                                    dot_q4b_row_1x4_avx2(&buf, scales, r * gpr, gpr, xs)
12314                                }
12315                            };
12316                            for k in 0..4 {
12317                                let act = &acts[bi + k];
12318                                let mut acc = d[k] * act.sx;
12319                                for &(j, xv) in &act.outliers {
12320                                    acc += (buf[j] as i8) as f32
12321                                        * gscale((r * cols + j) / GROUP_SIZE)
12322                                        * xv;
12323                                }
12324                                // SAFETY: disjoint (bi, r) cells per worker.
12325                                unsafe { *out_addr.at((bi + k) * rows + r) = acc };
12326                            }
12327                            bi += 4;
12328                        }
12329                    }
12330                    while bi < acts.len() {
12331                        let act = &acts[bi];
12332                        let mut acc = 0f32;
12333                        for gi in 0..gpr {
12334                            let d = dot_i8_i8(
12335                                &buf[gi * GROUP_SIZE..(gi + 1) * GROUP_SIZE],
12336                                &act.xq[gi * GROUP_SIZE..(gi + 1) * GROUP_SIZE],
12337                            );
12338                            acc += d as f32 * gscale(r * gpr + gi);
12339                        }
12340                        acc *= act.sx;
12341                        // xq is zeroed at outlier slots — exact terms.
12342                        for &(j, xv) in &act.outliers {
12343                            acc += (buf[j] as i8) as f32 * gscale((r * cols + j) / GROUP_SIZE) * xv;
12344                        }
12345                        // SAFETY: disjoint (bi, r) cells per worker row range.
12346                        unsafe { *out_addr.at(bi * rows + r) = acc };
12347                        bi += 1;
12348                    }
12349                }
12350            })
12351        };
12352        dispatch_rows(pool, rows, &run);
12353        return;
12354    }
12355
12356    let out_addr = SendMut(out.as_mut_ptr());
12357    let run = move |start: usize, end: usize| {
12358        ROW_F32.with(|rb| {
12359            let mut buf = rb.borrow_mut();
12360            buf.resize(cols, 0.0);
12361            for r in start..end {
12362                // Decode raw (nib − 8) values once; scales stay per-group
12363                // so the accumulation order matches q4matvec bit-for-bit.
12364                for gi in 0..gpr {
12365                    let g = r * gpr + gi;
12366                    for (k, &bt) in packed[g * 16..(g + 1) * 16].iter().enumerate() {
12367                        buf[gi * GROUP_SIZE + k * 2] = (bt & 0x0F) as f32 - 8.0;
12368                        buf[gi * GROUP_SIZE + k * 2 + 1] = ((bt >> 4) & 0x0F) as f32 - 8.0;
12369                    }
12370                }
12371                for bi in 0..b {
12372                    let x = &xs_all[bi * cols..(bi + 1) * cols];
12373                    let mut acc = 0f32;
12374                    for gi in 0..gpr {
12375                        let mut ga = 0f32;
12376                        // Pairwise (lo + hi) addition, matching
12377                        // q4matvec's `ga += lo·x + hi·x` shape exactly —
12378                        // a flat one-per-element loop rounds differently
12379                        // and broke bit-parity on the scalar (x86) path.
12380                        for k in 0..GROUP_SIZE / 2 {
12381                            let e = gi * GROUP_SIZE + k * 2;
12382                            ga += buf[e] * x[e] + buf[e + 1] * x[e + 1];
12383                        }
12384                        acc += ga * gscale(r * gpr + gi);
12385                    }
12386                    // SAFETY: disjoint (bi, r) cells per worker row range.
12387                    unsafe { *out_addr.at(bi * rows + r) = acc };
12388                }
12389            }
12390        })
12391    };
12392    dispatch_rows(pool, rows, &run);
12393}
12394
12395/// Batched vbit matmat: each variable-bit row is decoded from the mmap
12396/// ONCE for the whole microbatch. Same per-position math as
12397/// `vbitmatvec` (SDOT A8W8 with exact outliers / exact f32 for b=8 rows
12398/// and the scalar path).
12399#[allow(clippy::too_many_arguments)]
12400fn vbitmatmat(
12401    bytes: &[u8],
12402    offsets: &[usize],
12403    xs_all: &[f32],
12404    b: usize,
12405    rows: usize,
12406    cols: usize,
12407    out: &mut [f32],
12408    pool: Option<&Pool>,
12409) {
12410    debug_assert_eq!(xs_all.len(), b * cols);
12411    debug_assert_eq!(out.len(), b * rows);
12412    debug_assert_eq!(offsets.len(), rows + 1);
12413    let ng = cols / GROUP_SIZE;
12414    let bits = &bytes[..rows];
12415    let sc_off = rows;
12416    let gscale = |r: usize, g: usize| {
12417        let so = (r * ng + g) * 2;
12418        f16_to_f32(u16::from_le_bytes([
12419            bytes[sc_off + so],
12420            bytes[sc_off + so + 1],
12421        ]))
12422    };
12423
12424    // Decode row r's raw (u − L) values into `dst` (f32, unscaled).
12425    let decode_f32 = |r: usize, dst: &mut [f32]| {
12426        let bw = bits[r] as usize;
12427        let l = ((1i32 << (bw - 1)) - 1) as f32;
12428        let data = &bytes[offsets[r]..offsets[r + 1]];
12429        let (mut acc, mut nbits, mut idx) = (0u64, 0usize, 0usize);
12430        for d in dst.iter_mut() {
12431            while nbits < bw {
12432                acc = (acc << 8) | data[idx] as u64;
12433                idx += 1;
12434                nbits += 8;
12435            }
12436            let u = ((acc >> (nbits - bw)) & ((1u64 << bw) - 1)) as f32;
12437            nbits -= bw;
12438            *d = u - l;
12439        }
12440    };
12441
12442    if a8w8_enabled() {
12443        let acts: Vec<SplitAct> = (0..b)
12444            .map(|bi| split_act(&xs_all[bi * cols..(bi + 1) * cols]))
12445            .collect();
12446        let acts = &acts;
12447        let out_addr = SendMut(out.as_mut_ptr());
12448        let run = move |start: usize, end: usize| {
12449            for r in start..end {
12450                let bw = bits[r] as usize;
12451                if bw == 8 {
12452                    // u−L reaches 128 → no i8 path; decode once, exact
12453                    // f32 dots for every position (same as vbitmatvec).
12454                    ROW_F32.with(|rb| {
12455                        let mut buf = rb.borrow_mut();
12456                        buf.resize(cols, 0.0);
12457                        decode_f32(r, &mut buf);
12458                        for bi in 0..b {
12459                            let x = &xs_all[bi * cols..(bi + 1) * cols];
12460                            let mut dot = 0f32;
12461                            for g in 0..ng {
12462                                let mut gd = 0f32;
12463                                for k in 0..GROUP_SIZE {
12464                                    gd += buf[g * GROUP_SIZE + k] * x[g * GROUP_SIZE + k];
12465                                }
12466                                dot += gd * gscale(r, g);
12467                            }
12468                            // SAFETY: disjoint (bi, r) cells per worker range.
12469                            unsafe { *out_addr.at(bi * rows + r) = dot };
12470                        }
12471                    });
12472                    continue;
12473                }
12474                let l = (1i32 << (bw - 1)) - 1;
12475                let data = &bytes[offsets[r]..offsets[r + 1]];
12476                ROW_I8.with(|rb| {
12477                    let mut buf = rb.borrow_mut();
12478                    buf.resize(cols, 0);
12479                    #[inline(always)]
12480                    fn fill<const B: usize>(data: &[u8], l: i32, buf: &mut [u8]) {
12481                        for (blk, chunk) in buf.chunks_exact_mut(8).enumerate() {
12482                            let u = unpack8::<B>(&data[blk * B..]);
12483                            for k in 0..8 {
12484                                chunk[k] = (u[k] - l) as i8 as u8;
12485                            }
12486                        }
12487                    }
12488                    match bw {
12489                        3 => fill::<3>(data, l, &mut buf),
12490                        4 => vbit_fill4(data, &mut buf),
12491                        5 => fill::<5>(data, l, &mut buf),
12492                        6 => fill::<6>(data, l, &mut buf),
12493                        _ => unreachable!("vbit bit-width {bw} (validated at load)"),
12494                    }
12495                    let mut bi = 0usize;
12496                    // The vbit scale table shares q4_block's layout
12497                    // (contiguous f16 per (row·ng + g)), so the same
12498                    // blocked 1×4 kernel serves the decoded row.
12499                    #[cfg(target_arch = "x86_64")]
12500                    if avx2_enabled() && blocked_enabled() {
12501                        while bi + 4 <= acts.len() {
12502                            let xs = [
12503                                acts[bi].xq.as_slice(),
12504                                acts[bi + 1].xq.as_slice(),
12505                                acts[bi + 2].xq.as_slice(),
12506                                acts[bi + 3].xq.as_slice(),
12507                            ];
12508                            let sxs = [
12509                                acts[bi].sx,
12510                                acts[bi + 1].sx,
12511                                acts[bi + 2].sx,
12512                                acts[bi + 3].sx,
12513                            ];
12514                            let d = unsafe {
12515                                if vnni_tiles_enabled() {
12516                                    dot_q4b_row_1x4_sx_vnni(
12517                                        &buf,
12518                                        &bytes[sc_off..],
12519                                        r * ng,
12520                                        ng,
12521                                        xs,
12522                                        sxs,
12523                                    )
12524                                } else {
12525                                    dot_q4b_row_1x4_sx_avx2(
12526                                        &buf,
12527                                        &bytes[sc_off..],
12528                                        r * ng,
12529                                        ng,
12530                                        xs,
12531                                        sxs,
12532                                    )
12533                                }
12534                            };
12535                            for k in 0..4 {
12536                                let act = &acts[bi + k];
12537                                let mut dot = d[k];
12538                                for &(j, xv) in &act.outliers {
12539                                    dot += (buf[j] as i8) as f32 * gscale(r, j / GROUP_SIZE) * xv;
12540                                }
12541                                // SAFETY: disjoint (bi, r) cells per worker.
12542                                unsafe { *out_addr.at((bi + k) * rows + r) = dot };
12543                            }
12544                            bi += 4;
12545                        }
12546                    }
12547                    while bi < acts.len() {
12548                        let act = &acts[bi];
12549                        let mut dot = 0f32;
12550                        for g in 0..ng {
12551                            let d = dot_i8_i8(
12552                                &buf[g * GROUP_SIZE..(g + 1) * GROUP_SIZE],
12553                                &act.xq[g * GROUP_SIZE..(g + 1) * GROUP_SIZE],
12554                            ) as f32
12555                                * act.sx;
12556                            dot += d * gscale(r, g);
12557                        }
12558                        for &(j, xv) in &act.outliers {
12559                            dot += (buf[j] as i8) as f32 * gscale(r, j / GROUP_SIZE) * xv;
12560                        }
12561                        // SAFETY: disjoint (bi, r) cells per worker range.
12562                        unsafe { *out_addr.at(bi * rows + r) = dot };
12563                        bi += 1;
12564                    }
12565                });
12566            }
12567        };
12568        dispatch_rows(pool, rows, &run);
12569        return;
12570    }
12571
12572    let out_addr = SendMut(out.as_mut_ptr());
12573    let run = move |start: usize, end: usize| {
12574        ROW_F32.with(|rb| {
12575            let mut buf = rb.borrow_mut();
12576            buf.resize(cols, 0.0);
12577            for r in start..end {
12578                decode_f32(r, &mut buf);
12579                for bi in 0..b {
12580                    let x = &xs_all[bi * cols..(bi + 1) * cols];
12581                    let mut dot = 0f32;
12582                    for g in 0..ng {
12583                        let mut gd = 0f32;
12584                        for k in 0..GROUP_SIZE {
12585                            gd += buf[g * GROUP_SIZE + k] * x[g * GROUP_SIZE + k];
12586                        }
12587                        dot += gd * gscale(r, g);
12588                    }
12589                    // SAFETY: disjoint (bi, r) cells per worker range.
12590                    unsafe { *out_addr.at(bi * rows + r) = dot };
12591                }
12592            }
12593        })
12594    };
12595    dispatch_rows(pool, rows, &run);
12596}
12597
12598/// Build a GPU batch job for a q8-family mapped tensor (primary
12599/// shard): prescaled input + directory coordinates. None → not
12600/// GPU-eligible, caller stays on the CPU.
12601pub(crate) fn gpu_batch_job<'a>(
12602    t: &'a QTensor,
12603    x: &[f32],
12604) -> Option<(std::sync::Arc<CmfModel>, crate::gpu::BatchJob<'a>)> {
12605    match t {
12606        QTensor::Mapped {
12607            model,
12608            idx,
12609            dtype: dt @ (TensorDtype::Q8Row | TensorDtype::Q8_2f),
12610            rows,
12611            cols,
12612            row_scale,
12613            col_field,
12614            ..
12615        } => Some((
12616            model.clone(),
12617            crate::gpu::BatchJob {
12618                idx: *idx,
12619                rows: *rows,
12620                cols: *cols,
12621                row_scale,
12622                xs: prescale(x, col_field, *dt).into_owned(),
12623                layout: crate::gpu::BatchLayout::Q8,
12624            },
12625        )),
12626        // q1: raw f32 activations, tile-embedded scales.
12627        QTensor::Mapped {
12628            model,
12629            idx,
12630            dtype: TensorDtype::Q1,
12631            rows,
12632            cols,
12633            ..
12634        } => Some((
12635            model.clone(),
12636            crate::gpu::BatchJob {
12637                idx: *idx,
12638                rows: *rows,
12639                cols: *cols,
12640                row_scale: &[],
12641                xs: x.to_vec(),
12642                layout: crate::gpu::BatchLayout::Q1,
12643            },
12644        )),
12645        // q1g: same raw-f32 contract, sign + scale planes.
12646        QTensor::Mapped {
12647            model,
12648            idx,
12649            dtype: TensorDtype::Q1G,
12650            rows,
12651            cols,
12652            ..
12653        } => Some((
12654            model.clone(),
12655            crate::gpu::BatchJob {
12656                idx: *idx,
12657                rows: *rows,
12658                cols: *cols,
12659                row_scale: &[],
12660                xs: x.to_vec(),
12661                layout: crate::gpu::BatchLayout::Q1g,
12662            },
12663        )),
12664        // q4_tiled / q4tp: raw f32 activations; the scales live in the
12665        // payload (inline tiles / row ladder), so row_scale stays empty.
12666        // The GDN projection batch already runs these layouts on Metal —
12667        // this arm lets the attention QKV batch reach the same kernels.
12668        QTensor::Mapped {
12669            model,
12670            idx,
12671            dtype: dt @ (TensorDtype::Q4Tiled | TensorDtype::Q4TiledP),
12672            rows,
12673            cols,
12674            ..
12675        } => Some((
12676            model.clone(),
12677            crate::gpu::BatchJob {
12678                idx: *idx,
12679                rows: *rows,
12680                cols: *cols,
12681                row_scale: &[],
12682                xs: x.to_vec(),
12683                layout: if *dt == TensorDtype::Q4Tiled {
12684                    crate::gpu::BatchLayout::Q4t
12685                } else {
12686                    crate::gpu::BatchLayout::Q4tp
12687                },
12688            },
12689        )),
12690        _ => None,
12691    }
12692}
12693
12694thread_local! {
12695    static PRESCALE_BUF1: std::cell::RefCell<Vec<f32>> = const { std::cell::RefCell::new(Vec::new()) };
12696    static PRESCALE_BUF2: std::cell::RefCell<Vec<f32>> = const { std::cell::RefCell::new(Vec::new()) };
12697}
12698
12699pub(crate) fn prescale<'a>(
12700    x: &'a [f32],
12701    col_field: &[f32],
12702    dtype: TensorDtype,
12703) -> std::borrow::Cow<'a, [f32]> {
12704    if dtype == TensorDtype::Q8_2f {
12705        x.iter().zip(col_field).map(|(a, c)| a * c).collect()
12706    } else {
12707        std::borrow::Cow::Borrowed(x)
12708    }
12709}
12710
12711/// θ col-field fold for q8_2f activations. Borrowed pass-through for
12712/// every other dtype, using thread-local buffers to eliminate per-matvec allocations.
12713pub(crate) fn prescale_with<R, F: FnOnce(&[f32]) -> R>(
12714    x: &[f32],
12715    col_field: &[f32],
12716    dtype: TensorDtype,
12717    buf_id: u8,
12718    f: F,
12719) -> R {
12720    if dtype == TensorDtype::Q8_2f {
12721        if buf_id == 1 {
12722            PRESCALE_BUF1.with(|b| {
12723                let mut buf = b.borrow_mut();
12724                buf.clear();
12725                buf.extend(x.iter().zip(col_field).map(|(a, c)| a * c));
12726                f(&buf)
12727            })
12728        } else {
12729            PRESCALE_BUF2.with(|b| {
12730                let mut buf = b.borrow_mut();
12731                buf.clear();
12732                buf.extend(x.iter().zip(col_field).map(|(a, c)| a * c));
12733                f(&buf)
12734            })
12735        }
12736    } else {
12737        f(x)
12738    }
12739}
12740
12741// ───────────────────── x86-64 AVX2 kernels (roadmap этап 2) ─────────────────────
12742
12743/// AVX2+FMA available? Default ON when the CPU supports both;
12744/// `CMF_AVX2=0` disables (falls back to the autovectorized loops).
12745#[cfg(target_arch = "x86_64")]
12746pub(crate) fn avx2_enabled() -> bool {
12747    use std::sync::OnceLock;
12748    static ON: OnceLock<bool> = OnceLock::new();
12749    *ON.get_or_init(|| {
12750        std::env::var("CMF_AVX2").map(|v| v != "0").unwrap_or(true)
12751            && std::arch::is_x86_feature_detected!("avx2")
12752            && std::arch::is_x86_feature_detected!("fma")
12753    })
12754}
12755
12756/// AVX2 A8W8 allowed? The quantized-activation contract is switched by
12757/// the SAME env as the ARM SDOT path: `CMF_SDOT=0` keeps exact kernels
12758/// (the golden-parity exact gate relies on it) — AVX2 f32 kernels stay
12759/// active either way, they are exact (regrouped sums only).
12760#[cfg(target_arch = "x86_64")]
12761fn avx2_a8w8_enabled() -> bool {
12762    if FLOAT_ACTIVATIONS.get() {
12763        return false;
12764    }
12765    use std::sync::OnceLock;
12766    static ON: OnceLock<bool> = OnceLock::new();
12767    *ON.get_or_init(|| {
12768        avx2_enabled() && std::env::var("CMF_SDOT").map(|v| v != "0").unwrap_or(true)
12769    })
12770}
12771
12772thread_local! {
12773    static FULL_GPU_Q8: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
12774}
12775
12776/// Match the graph's full-device q8 projection precision on MiMo's host
12777/// tail. Does not enable the GPU or bypass a CPU-only/device-refusal gate.
12778pub(crate) fn enter_full_gpu_q8_scope() -> impl Drop {
12779    struct Restore(bool, std::marker::PhantomData<std::rc::Rc<()>>);
12780    impl Drop for Restore {
12781        fn drop(&mut self) {
12782            FULL_GPU_Q8.set(self.0);
12783        }
12784    }
12785    Restore(FULL_GPU_Q8.replace(true), std::marker::PhantomData)
12786}
12787
12788// Dynamic MiMo experts must not change activation precision when a cache
12789// fill moves them from CPU to GPU. Thread-local: only the cold-expert
12790// dispatch selects float kernels; concurrent pipelines keep their policy.
12791thread_local! {
12792    static FLOAT_ACTIVATIONS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
12793}
12794
12795/// Flint's released Q2/Q4 profiles are unusually sensitive to activation
12796/// quantization in the host-side attention path. With the normal A8W8
12797/// default, a short greedy decode can diverge after the first token even
12798/// though the selected-expert Metal path itself is unchanged. An Embryo file
12799/// carries a router fitted on the exact φ, which A8W8 moves by 4e-3, and its
12800/// CPU decode costs the same without it. Keep the reference float-activation
12801/// contract for both unless the operator has explicitly selected an
12802/// `CMF_SDOT` policy.
12803fn exact_cpu_default_enabled() -> bool {
12804    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
12805    *ON.get_or_init(|| std::env::var_os("CMF_SDOT").is_none())
12806}
12807
12808impl QTensor {
12809    #[inline]
12810    fn exact_cpu_default(&self) -> bool {
12811        !FLOAT_ACTIVATIONS.get()
12812            && exact_cpu_default_enabled()
12813            && matches!(
12814                self,
12815                Self::Mapped { model, dtype, .. } if matches!(model.header.arch.arch_name.as_str(), "flint" | "cortiq_embryo")
12816                    // Dory on q8 runs as fast on float activations and exact; on
12817                    // q4tp int8 is 4.7× on an M4 for 0.1 % of perplexity.
12818                    || (model.header.arch.arch_name == "dory" && *dtype == TensorDtype::Q8_2f)
12819            )
12820    }
12821
12822    #[inline]
12823    fn any_exact_cpu_default(ts: &[&QTensor]) -> bool {
12824        ts.iter().any(|t| t.exact_cpu_default())
12825    }
12826
12827    #[inline]
12828    fn any_exact_cpu_default_pairs(pairs: &[(&QTensor, &QTensor)]) -> bool {
12829        pairs
12830            .iter()
12831            .any(|(gate, up)| gate.exact_cpu_default() || up.exact_cpu_default())
12832    }
12833}
12834
12835/// Run `f` with the exact float-activation contract on this thread: the
12836/// 4-bit and 8-bit kernels skip the int8 activation split (`CMF_SDOT=0`
12837/// semantics, scoped). For parity tests and diagnostics — e.g. an `mxfp4`
12838/// model then computes bit for bit what its dequantized f32 twin computes.
12839pub fn with_float_activations<R>(f: impl FnOnce() -> R) -> R {
12840    float_activations_scope(f)
12841}
12842
12843/// Active on the current thread. `Pool` snapshots this with its job
12844/// descriptor and installs it on persistent workers, so a scoped quantized
12845/// matvec cannot accidentally choose a different kernel on a worker.
12846#[inline]
12847pub(crate) fn float_activations_active() -> bool {
12848    FLOAT_ACTIVATIONS.get()
12849}
12850
12851/// Restores the current thread's float-activation state on drop. The `Rc`
12852/// marker deliberately keeps the guard on the thread that created it: this
12853/// policy is thread-local, not a portable capability.
12854pub(crate) struct FloatActivationsScope {
12855    previous: bool,
12856    _not_send: std::marker::PhantomData<std::rc::Rc<()>>,
12857}
12858
12859impl Drop for FloatActivationsScope {
12860    fn drop(&mut self) {
12861        FLOAT_ACTIVATIONS.set(self.previous);
12862    }
12863}
12864
12865#[inline]
12866pub(crate) fn enter_float_activations_scope() -> FloatActivationsScope {
12867    FloatActivationsScope {
12868        previous: FLOAT_ACTIVATIONS.replace(true),
12869        _not_send: std::marker::PhantomData,
12870    }
12871}
12872
12873/// Run `f` with exact float activations (no A8W8 int8 activation
12874/// quantization in the quantized matvecs). The persistent row pool carries
12875/// this scope into a dispatched job and restores each worker afterwards.
12876/// Public for parity tests that compare the default kernels with the strict
12877/// ones in one process; `CMF_SDOT=0` is the process-wide equivalent.
12878#[doc(hidden)]
12879pub fn float_activations_scope<R>(f: impl FnOnce() -> R) -> R {
12880    let _scope = enter_float_activations_scope();
12881    f()
12882}
12883
12884/// Row-exact batching: while set, the x86 batched kernels (`qmatmat`,
12885/// `q4tp_matmat`) compute every (weight row, token) cell with the
12886/// single-token kernel instead of the blocked 2×4 / 1×4 / 1×8 tiles, so a
12887/// token's result does not depend on the batch it rides in and equals its
12888/// matvec. On ARM `q4tp_matmat` keeps its 1×4 tile but in the matvec's
12889/// reduction order, and no q4tp batch takes the AMX or device GEMM. The
12890/// MiMo speculative verify holds it (`row_exact_scope`) — its accepted
12891/// rows must be the rows plain decode would have produced.
12892// Shared with pool workers, so overlapping requests must keep the mode
12893// enabled until the LAST scope leaves. Saving/restoring a global bool is
12894// incorrect when two threads enter and leave in a non-LIFO order.
12895static ROW_EXACT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12896
12897pub(crate) fn row_exact() -> bool {
12898    ROW_EXACT.load(std::sync::atomic::Ordering::Acquire) != 0
12899}
12900
12901fn counted_row_exact_scope<R>(active: &std::sync::atomic::AtomicUsize, f: impl FnOnce() -> R) -> R {
12902    struct Restore<'a>(&'a std::sync::atomic::AtomicUsize);
12903    impl Drop for Restore<'_> {
12904        fn drop(&mut self) {
12905            self.0.fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
12906        }
12907    }
12908    active.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
12909    let _restore = Restore(active);
12910    f()
12911}
12912
12913/// Run `f` with row-exact batching on (also released on unwind).
12914pub(crate) fn row_exact_scope<R>(f: impl FnOnce() -> R) -> R {
12915    counted_row_exact_scope(&ROW_EXACT, f)
12916}
12917
12918/// A8W8 quantized-activation path available on THIS machine? One
12919/// switch across architectures: ARM dotprod (CMF_SDOT) or x86 AVX2
12920/// (CMF_AVX2 + the same CMF_SDOT exact-contract override).
12921#[inline]
12922pub(crate) fn a8w8_enabled() -> bool {
12923    #[cfg(target_arch = "aarch64")]
12924    {
12925        sdot_enabled()
12926    }
12927    #[cfg(target_arch = "x86_64")]
12928    {
12929        avx2_a8w8_enabled()
12930    }
12931    #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
12932    {
12933        false
12934    }
12935}
12936
12937/// int8·int8 dot dispatch: SDOT on ARM; AVX-512 VNNI (vpdpbusd) or AVX2
12938/// maddubs on x86. Callers are gated by `a8w8_enabled()`.
12939#[inline]
12940#[allow(unreachable_code)]
12941fn dot_i8_i8(w: &[u8], xq: &[i8]) -> i32 {
12942    #[cfg(target_arch = "aarch64")]
12943    unsafe {
12944        return dot_i8_sdot(w, xq);
12945    }
12946    #[cfg(target_arch = "x86_64")]
12947    unsafe {
12948        if avx512vnni_enabled() {
12949            return dot_i8_i8_vnni(w, xq);
12950        }
12951        return dot_i8_i8_avx2(w, xq);
12952    }
12953    w.iter()
12954        .zip(xq)
12955        .map(|(&a, &b)| (a as i8) as i32 * b as i32)
12956        .sum()
12957}
12958
12959/// AVX-512 VNNI available? (F+BW+VL+VNNI; `CMF_AVX512=0` falls back to
12960/// AVX2.) VL matters: short 32-byte groups (q4/vbit) ride the 256-bit
12961/// `vpdpbusd` encoding.
12962#[cfg(target_arch = "x86_64")]
12963fn avx512vnni_enabled() -> bool {
12964    use std::sync::OnceLock;
12965    static ON: OnceLock<bool> = OnceLock::new();
12966    *ON.get_or_init(|| {
12967        std::env::var("CMF_AVX512")
12968            .map(|v| v != "0")
12969            .unwrap_or(true)
12970            && std::arch::is_x86_feature_detected!("avx512f")
12971            && std::arch::is_x86_feature_detected!("avx512bw")
12972            && std::arch::is_x86_feature_detected!("avx512vl")
12973            && std::arch::is_x86_feature_detected!("avx512vnni")
12974    })
12975}
12976
12977/// Grouped-codec VNNI arms (the q4t/q4b/q1/q1t tile kernels): default
12978/// ON where AVX-512 VNNI exists (`CMF_VNNI_TILES=0` opt-out). Measured
12979/// on Ryzen 7950X (Zen4, 3 alternating process pairs, blocked GEMM
12980/// 4864×896 b=256): q4t 63→68 GF/s (+8%), q1 53→56 (+6%), q4b 72→75
12981/// (+4%) — consistent, no leg regressed. The tile kernels keep a
12982/// horizontal reduce per 32-weight group, so the `vpdpbusd` saving is
12983/// smaller than the long-dot q8 win (+13%), but it is real and free.
12984#[cfg(target_arch = "x86_64")]
12985fn vnni_tiles_enabled() -> bool {
12986    use std::sync::OnceLock;
12987    static ON: OnceLock<bool> = OnceLock::new();
12988    *ON.get_or_init(|| {
12989        std::env::var("CMF_VNNI_TILES")
12990            .map(|v| v != "0")
12991            .unwrap_or(true)
12992            && avx512vnni_enabled()
12993    })
12994}
12995
12996/// One 256-bit u8×i8 dot → i32 via `vpdpbusd` into a fresh accumulator
12997/// plus the same horizontal reduce the AVX2 kernels use. Products are
12998/// bounded (|w| ≤ 8 or ≤ 1), so maddubs never saturated — the i32 sum
12999/// is bit-identical to the maddubs+madd pair it replaces.
13000#[cfg(target_arch = "x86_64")]
13001#[target_feature(enable = "avx2,avx512f,avx512bw,avx512vl,avx512vnni")]
13002#[inline]
13003unsafe fn dpbusd_hsum(aw: core::arch::x86_64::__m256i, xs: core::arch::x86_64::__m256i) -> i32 {
13004    // SAFETY: pure register math.
13005    unsafe {
13006        use core::arch::x86_64::*;
13007        let d = _mm256_dpbusd_epi32(_mm256_setzero_si256(), aw, xs);
13008        let hi128 = _mm256_extracti128_si256::<1>(d);
13009        let s128 = _mm_add_epi32(_mm256_castsi256_si128(d), hi128);
13010        let s64 = _mm_add_epi32(s128, _mm_srli_si128::<8>(s128));
13011        let s32 = _mm_add_epi32(s64, _mm_srli_si128::<4>(s64));
13012        _mm_cvtsi128_si32(s32)
13013    }
13014}
13015
13016/// int8·int8 via AVX-512 VNNI: `vpdpbusd` fuses the maddubs+madd+add
13017/// triple into one u8×i8 dot-accumulate. AVX-512 has no vpsignb, so the
13018/// |w|·sign(x,w) trick becomes |w| × (x negated where w<0) via a mask
13019/// subtract — w==0 lanes contribute 0 through |w|=0 either way.
13020#[cfg(target_arch = "x86_64")]
13021#[target_feature(enable = "avx2,avx512f,avx512bw,avx512vl,avx512vnni")]
13022unsafe fn dot_i8_i8_vnni(w: &[u8], xq: &[i8]) -> i32 {
13023    // SAFETY: callers uphold slice-length contracts (see call sites).
13024    unsafe {
13025        use core::arch::x86_64::*;
13026        let n = w.len();
13027        let mut j = 0usize;
13028        let mut total: i32;
13029        // 4 independent accumulators: vpdpbusd is its own loop-carried
13030        // dependency (~5-cycle latency) — a single-acc loop runs
13031        // latency-bound and LOSES to the AVX2 maddubs kernel, measured
13032        // on Granite Rapids.
13033        {
13034            #[inline(always)]
13035            unsafe fn step(
13036                w: *const u8,
13037                x: *const i8,
13038                acc: core::arch::x86_64::__m512i,
13039            ) -> core::arch::x86_64::__m512i {
13040                unsafe {
13041                    use core::arch::x86_64::*;
13042                    let wv = _mm512_loadu_si512(w as *const _);
13043                    let xv = _mm512_loadu_si512(x as *const _);
13044                    let aw = _mm512_abs_epi8(wv);
13045                    let neg = _mm512_movepi8_mask(wv);
13046                    let sx = _mm512_mask_sub_epi8(xv, neg, _mm512_setzero_si512(), xv);
13047                    _mm512_dpbusd_epi32(acc, aw, sx)
13048                }
13049            }
13050            let (mut a0, mut a1, mut a2, mut a3) = (
13051                _mm512_setzero_si512(),
13052                _mm512_setzero_si512(),
13053                _mm512_setzero_si512(),
13054                _mm512_setzero_si512(),
13055            );
13056            while j + 256 <= n {
13057                a0 = step(w.as_ptr().add(j), xq.as_ptr().add(j), a0);
13058                a1 = step(w.as_ptr().add(j + 64), xq.as_ptr().add(j + 64), a1);
13059                a2 = step(w.as_ptr().add(j + 128), xq.as_ptr().add(j + 128), a2);
13060                a3 = step(w.as_ptr().add(j + 192), xq.as_ptr().add(j + 192), a3);
13061                j += 256;
13062            }
13063            while j + 64 <= n {
13064                a0 = step(w.as_ptr().add(j), xq.as_ptr().add(j), a0);
13065                j += 64;
13066            }
13067            let s01 = _mm512_add_epi32(a0, a1);
13068            let s23 = _mm512_add_epi32(a2, a3);
13069            total = _mm512_reduce_add_epi32(_mm512_add_epi32(s01, s23));
13070        }
13071        // 32-wide (q4/vbit groups are exactly 32 bytes).
13072        if j + 32 <= n {
13073            let wv = _mm256_loadu_si256(w.as_ptr().add(j) as *const __m256i);
13074            let xv = _mm256_loadu_si256(xq.as_ptr().add(j) as *const __m256i);
13075            let d = _mm256_dpbusd_epi32(
13076                _mm256_setzero_si256(),
13077                _mm256_abs_epi8(wv),
13078                _mm256_sign_epi8(xv, wv),
13079            );
13080            let hi128 = _mm256_extracti128_si256::<1>(d);
13081            let s128 = _mm_add_epi32(_mm256_castsi256_si128(d), hi128);
13082            let s64 = _mm_add_epi32(s128, _mm_srli_si128::<8>(s128));
13083            let s32 = _mm_add_epi32(s64, _mm_srli_si128::<4>(s64));
13084            total += _mm_cvtsi128_si32(s32);
13085            j += 32;
13086        }
13087        while j < n {
13088            total += (w[j] as i8) as i32 * xq[j] as i32;
13089            j += 1;
13090        }
13091        total
13092    }
13093}
13094
13095/// i8 row · f32 x via AVX2/FMA (x86 mirror of `dot_i8_f32_neon`).
13096#[cfg(target_arch = "x86_64")]
13097#[target_feature(enable = "avx2,fma")]
13098unsafe fn dot_i8_f32_avx2(w: &[u8], x: &[f32]) -> f32 {
13099    // SAFETY: callers uphold slice-length contracts (see call sites).
13100    unsafe {
13101        use core::arch::x86_64::*;
13102        let n = x.len();
13103        let wp = w.as_ptr();
13104        let xp = x.as_ptr();
13105        let (mut a0, mut a1) = (_mm256_setzero_ps(), _mm256_setzero_ps());
13106        let mut j = 0usize;
13107        while j + 16 <= n {
13108            let wb = _mm_loadu_si128(wp.add(j) as *const __m128i);
13109            let lo = _mm256_cvtepi8_epi32(wb);
13110            let hi = _mm256_cvtepi8_epi32(_mm_srli_si128::<8>(wb));
13111            a0 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(lo), _mm256_loadu_ps(xp.add(j)), a0);
13112            a1 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(hi), _mm256_loadu_ps(xp.add(j + 8)), a1);
13113            j += 16;
13114        }
13115        let acc = _mm256_add_ps(a0, a1);
13116        let hi128 = _mm256_extractf128_ps::<1>(acc);
13117        let s128 = _mm_add_ps(_mm256_castps256_ps128(acc), hi128);
13118        let s64 = _mm_add_ps(s128, _mm_movehl_ps(s128, s128));
13119        let s32 = _mm_add_ss(s64, _mm_shuffle_ps::<1>(s64, s64));
13120        let mut sum = _mm_cvtss_f32(s32);
13121        while j < n {
13122            sum += (*wp.add(j) as i8) as f32 * *xp.add(j);
13123            j += 1;
13124        }
13125        sum
13126    }
13127}
13128
13129/// int8(weight)·int8(activation) → i32 via AVX2 maddubs — the x86
13130/// analogue of the SDOT A8W8 path. `maddubs` takes u8×i8, so the
13131/// standard sign trick applies: |w| × sign(x, w) ≡ w × x per lane.
13132/// Pair saturation is safe: |w|≤128, |x|≤127 → 2·128·127 < 32767.
13133#[cfg(target_arch = "x86_64")]
13134#[target_feature(enable = "avx2")]
13135unsafe fn dot_i8_i8_avx2(w: &[u8], xq: &[i8]) -> i32 {
13136    // SAFETY: callers uphold slice-length contracts (see call sites).
13137    unsafe {
13138        use core::arch::x86_64::*;
13139        let n = w.len();
13140        let ones = _mm256_set1_epi16(1);
13141        let mut acc = _mm256_setzero_si256();
13142        let mut j = 0usize;
13143        while j + 32 <= n {
13144            let wv = _mm256_loadu_si256(w.as_ptr().add(j) as *const __m256i);
13145            let xv = _mm256_loadu_si256(xq.as_ptr().add(j) as *const __m256i);
13146            let p16 = _mm256_maddubs_epi16(_mm256_abs_epi8(wv), _mm256_sign_epi8(xv, wv));
13147            acc = _mm256_add_epi32(acc, _mm256_madd_epi16(p16, ones));
13148            j += 32;
13149        }
13150        let hi128 = _mm256_extracti128_si256::<1>(acc);
13151        let s128 = _mm_add_epi32(_mm256_castsi256_si128(acc), hi128);
13152        let s64 = _mm_add_epi32(s128, _mm_srli_si128::<8>(s128));
13153        let s32 = _mm_add_epi32(s64, _mm_srli_si128::<4>(s64));
13154        let mut s = _mm_cvtsi128_si32(s32);
13155        while j < n {
13156            s += (w[j] as i8) as i32 * xq[j] as i32;
13157            j += 1;
13158        }
13159        s
13160    }
13161}
13162
13163/// smmla 2×4: one instruction covers a 2-row × 2-activation × 8-deep
13164/// tile (32 MACs vs sdot's 16) — the weight pair loads once per 8-k
13165/// slice as a combined 2×8 register and meets two activation pairs.
13166#[cfg(target_arch = "aarch64")]
13167#[target_feature(enable = "neon,i8mm")]
13168unsafe fn dot_i8_smmla_2x4(w0: &[u8], w1: &[u8], xs: [&[i8]; 4]) -> [[i32; 4]; 2] {
13169    // SAFETY: callers uphold slice-length contracts.
13170    unsafe {
13171        use core::arch::aarch64::*;
13172        use core::arch::asm;
13173        let n = w0.len();
13174        let w0p = w0.as_ptr() as *const i8;
13175        let w1p = w1.as_ptr() as *const i8;
13176        // acc01 holds [c(r0,x0) c(r0,x1) c(r1,x0) c(r1,x1)]; acc23 the
13177        // same for x2/x3.
13178        let mut acc01 = vdupq_n_s32(0);
13179        let mut acc23 = vdupq_n_s32(0);
13180        let mut i = 0usize;
13181        while i + 8 <= n {
13182            let wa = vcombine_s8(vld1_s8(w0p.add(i)), vld1_s8(w1p.add(i)));
13183            let xb01 = vcombine_s8(
13184                vld1_s8(xs[0].as_ptr().add(i)),
13185                vld1_s8(xs[1].as_ptr().add(i)),
13186            );
13187            let xb23 = vcombine_s8(
13188                vld1_s8(xs[2].as_ptr().add(i)),
13189                vld1_s8(xs[3].as_ptr().add(i)),
13190            );
13191            asm!(
13192                "smmla {a01:v}.4s, {w:v}.16b, {x01:v}.16b",
13193                "smmla {a23:v}.4s, {w:v}.16b, {x23:v}.16b",
13194                a01 = inout(vreg) acc01, a23 = inout(vreg) acc23,
13195                w = in(vreg) wa, x01 = in(vreg) xb01, x23 = in(vreg) xb23,
13196                options(pure, nomem, nostack),
13197            );
13198            i += 8;
13199        }
13200        let mut out = [[0i32; 4]; 2];
13201        let a01: [i32; 4] = core::mem::transmute(acc01);
13202        let a23: [i32; 4] = core::mem::transmute(acc23);
13203        out[0][0] = a01[0];
13204        out[0][1] = a01[1];
13205        out[1][0] = a01[2];
13206        out[1][1] = a01[3];
13207        out[0][2] = a23[0];
13208        out[0][3] = a23[1];
13209        out[1][2] = a23[2];
13210        out[1][3] = a23[3];
13211        if i < n {
13212            for (k, x) in xs.iter().enumerate() {
13213                for j in i..n {
13214                    out[0][k] += (w0[j] as i8) as i32 * x[j] as i32;
13215                    out[1][k] += (w1[j] as i8) as i32 * x[j] as i32;
13216                }
13217            }
13218        }
13219        out
13220    }
13221}
13222
13223/// ARM twin of the x86 blocked prefill GEMM: two weight rows stay in
13224/// registers across four activation streams, eight sdot accumulators.
13225/// (The per-row form re-read each W row once per activation.)
13226#[cfg(target_arch = "aarch64")]
13227#[target_feature(enable = "neon,dotprod")]
13228unsafe fn dot_i8_sdot_2x4(w0: &[u8], w1: &[u8], xs: [&[i8]; 4]) -> [[i32; 4]; 2] {
13229    // SAFETY: callers uphold slice-length contracts.
13230    unsafe {
13231        use core::arch::aarch64::*;
13232        use core::arch::asm;
13233        let n = w0.len();
13234        let w0p = w0.as_ptr() as *const i8;
13235        let w1p = w1.as_ptr() as *const i8;
13236        let mut acc = [[vdupq_n_s32(0); 4]; 2];
13237        let mut i = 0usize;
13238        while i + 16 <= n {
13239            let wv0 = vld1q_s8(w0p.add(i));
13240            let wv1 = vld1q_s8(w1p.add(i));
13241            for (k, x) in xs.iter().enumerate() {
13242                let xv = vld1q_s8(x.as_ptr().add(i));
13243                let (mut a0, mut a1) = (acc[0][k], acc[1][k]);
13244                asm!(
13245                    "sdot {a0:v}.4s, {w0:v}.16b, {x:v}.16b",
13246                    "sdot {a1:v}.4s, {w1:v}.16b, {x:v}.16b",
13247                    a0 = inout(vreg) a0, a1 = inout(vreg) a1,
13248                    w0 = in(vreg) wv0, w1 = in(vreg) wv1, x = in(vreg) xv,
13249                    options(pure, nomem, nostack),
13250                );
13251                acc[0][k] = a0;
13252                acc[1][k] = a1;
13253            }
13254            i += 16;
13255        }
13256        let mut out = [[0i32; 4]; 2];
13257        for r in 0..2 {
13258            for k in 0..4 {
13259                out[r][k] = vaddvq_s32(acc[r][k]);
13260            }
13261        }
13262        if i < n {
13263            for (k, x) in xs.iter().enumerate() {
13264                for j in i..n {
13265                    out[0][k] += (w0[j] as i8) as i32 * x[j] as i32;
13266                    out[1][k] += (w1[j] as i8) as i32 * x[j] as i32;
13267                }
13268            }
13269        }
13270        out
13271    }
13272}
13273
13274/// Blocked 2 weight rows × 4 activations for the prefill GEMM
13275/// (roadmap P0: packed panels + multi-row accumulators). The two rows'
13276/// abs() live in registers across all four activation streams; the
13277/// sign-fixup is recomputed per pair (the price of the maddubs trick).
13278/// Returns raw i8·i8 dots; the caller applies scales and outliers.
13279#[cfg(target_arch = "x86_64")]
13280#[target_feature(enable = "avx2")]
13281unsafe fn dot_i8_i8_avx2_2x4(w0: &[u8], w1: &[u8], xs: [&[i8]; 4]) -> [[i32; 4]; 2] {
13282    // SAFETY: callers uphold slice-length contracts.
13283    unsafe {
13284        use core::arch::x86_64::*;
13285        let n = w0.len();
13286        let ones = _mm256_set1_epi16(1);
13287        let mut acc = [[_mm256_setzero_si256(); 4]; 2];
13288        let mut j = 0usize;
13289        while j + 32 <= n {
13290            let wv0 = _mm256_loadu_si256(w0.as_ptr().add(j) as *const __m256i);
13291            let wv1 = _mm256_loadu_si256(w1.as_ptr().add(j) as *const __m256i);
13292            let aw0 = _mm256_abs_epi8(wv0);
13293            let aw1 = _mm256_abs_epi8(wv1);
13294            for (k, x) in xs.iter().enumerate() {
13295                let xv = _mm256_loadu_si256(x.as_ptr().add(j) as *const __m256i);
13296                let p0 = _mm256_maddubs_epi16(aw0, _mm256_sign_epi8(xv, wv0));
13297                acc[0][k] = _mm256_add_epi32(acc[0][k], _mm256_madd_epi16(p0, ones));
13298                let p1 = _mm256_maddubs_epi16(aw1, _mm256_sign_epi8(xv, wv1));
13299                acc[1][k] = _mm256_add_epi32(acc[1][k], _mm256_madd_epi16(p1, ones));
13300            }
13301            j += 32;
13302        }
13303        let mut out = [[0i32; 4]; 2];
13304        for r in 0..2 {
13305            for k in 0..4 {
13306                let a = acc[r][k];
13307                let hi128 = _mm256_extracti128_si256::<1>(a);
13308                let s128 = _mm_add_epi32(_mm256_castsi256_si128(a), hi128);
13309                let s64 = _mm_add_epi32(s128, _mm_srli_si128::<8>(s128));
13310                let s32 = _mm_add_epi32(s64, _mm_srli_si128::<4>(s64));
13311                out[r][k] = _mm_cvtsi128_si32(s32);
13312            }
13313        }
13314        if j < n {
13315            for (k, x) in xs.iter().enumerate() {
13316                for i in j..n {
13317                    out[0][k] += (w0[i] as i8) as i32 * x[i] as i32;
13318                    out[1][k] += (w1[i] as i8) as i32 * x[i] as i32;
13319                }
13320            }
13321        }
13322        out
13323    }
13324}
13325
13326/// AVX2/VNNI q8 row dot with exact outlier correction (x86 mirror of
13327/// `row_dot_sdot` — same A8W8 contract). With AVX-512 VNNI the row goes
13328/// through the bias trick: Σ(w+128)·x via pure `vpdpbusd` (no per-lane
13329/// sign fixups), corrected by −128·Σx with Σx precomputed per split.
13330#[cfg(target_arch = "x86_64")]
13331#[inline]
13332fn row_dot_avx2(row: &[u8], act: &SplitAct) -> f32 {
13333    let dot = if avx512vnni_enabled() && row.len() >= 64 {
13334        (unsafe { dot_u8p128_i8_vnni(row, &act.xq) }) - 128 * act.xsum
13335    } else {
13336        unsafe { dot_i8_i8_avx2(row, &act.xq) }
13337    };
13338    let mut acc = dot as f32 * act.sx;
13339    for &(j, xv) in &act.outliers {
13340        acc += (row[j] as i8) as f32 * xv;
13341    }
13342    acc
13343}
13344
13345/// Σ (w[i]+128)·x[i] via pure `vpdpbusd` — the caller subtracts
13346/// 128·Σx. Four independent accumulators (dpbusd is ~5-cycle latency;
13347/// a single-acc loop runs latency-bound, measured on Granite Rapids).
13348#[cfg(target_arch = "x86_64")]
13349#[target_feature(enable = "avx2,avx512f,avx512bw,avx512vl,avx512vnni")]
13350unsafe fn dot_u8p128_i8_vnni(w: &[u8], xq: &[i8]) -> i32 {
13351    // SAFETY: callers uphold slice-length contracts (see call sites).
13352    unsafe {
13353        use core::arch::x86_64::*;
13354        let n = w.len();
13355        let flip = _mm512_set1_epi8(-128); // XOR 0x80: i8 w → u8 (w+128)
13356        #[inline(always)]
13357        unsafe fn step(
13358            w: *const u8,
13359            x: *const i8,
13360            flip: core::arch::x86_64::__m512i,
13361            acc: core::arch::x86_64::__m512i,
13362        ) -> core::arch::x86_64::__m512i {
13363            unsafe {
13364                use core::arch::x86_64::*;
13365                let wv = _mm512_xor_si512(_mm512_loadu_si512(w as *const _), flip);
13366                _mm512_dpbusd_epi32(acc, wv, _mm512_loadu_si512(x as *const _))
13367            }
13368        }
13369        let (mut a0, mut a1, mut a2, mut a3) = (
13370            _mm512_setzero_si512(),
13371            _mm512_setzero_si512(),
13372            _mm512_setzero_si512(),
13373            _mm512_setzero_si512(),
13374        );
13375        let mut j = 0usize;
13376        while j + 256 <= n {
13377            a0 = step(w.as_ptr().add(j), xq.as_ptr().add(j), flip, a0);
13378            a1 = step(w.as_ptr().add(j + 64), xq.as_ptr().add(j + 64), flip, a1);
13379            a2 = step(w.as_ptr().add(j + 128), xq.as_ptr().add(j + 128), flip, a2);
13380            a3 = step(w.as_ptr().add(j + 192), xq.as_ptr().add(j + 192), flip, a3);
13381            j += 256;
13382        }
13383        while j + 64 <= n {
13384            a0 = step(w.as_ptr().add(j), xq.as_ptr().add(j), flip, a0);
13385            j += 64;
13386        }
13387        let mut total = _mm512_reduce_add_epi32(_mm512_add_epi32(
13388            _mm512_add_epi32(a0, a1),
13389            _mm512_add_epi32(a2, a3),
13390        ));
13391        // Scalar tail: (w as i8) + 128 ≡ (w as u8) ^ 0x80.
13392        while j < n {
13393            total += ((w[j] ^ 0x80) as i32) * xq[j] as i32;
13394            j += 1;
13395        }
13396        total
13397    }
13398}
13399
13400/// One q4 row via AVX2: nibbles → centered i8 (unpacklo/hi restores the
13401/// writer's flat order, same as the NEON vzip pair), maddubs against
13402/// the pre-quantized activation group, × the group's f16 scale. Pair
13403/// saturation safe: |w|≤8, |x|≤127 → 2·8·127 ≪ 32767. Mirror of
13404/// `dot_q4_row_sdot`.
13405#[cfg(target_arch = "x86_64")]
13406#[target_feature(enable = "avx2")]
13407unsafe fn dot_q4_row_avx2(packed: &[u8], scales: &[u8], g0: usize, gpr: usize, xq: &[i8]) -> f32 {
13408    // SAFETY: callers uphold slice-length contracts (16 packed bytes and
13409    // 2 scale bytes per group; xq.len() == gpr·GROUP_SIZE).
13410    unsafe {
13411        use core::arch::x86_64::*;
13412        let lomask = _mm_set1_epi8(0x0F);
13413        let eight = _mm256_set1_epi8(8);
13414        let ones = _mm256_set1_epi16(1);
13415        let mut acc = 0f32;
13416        for gi in 0..gpr {
13417            let g = g0 + gi;
13418            let s = f16_to_f32(u16::from_le_bytes([scales[g * 2], scales[g * 2 + 1]]));
13419            let b = _mm_loadu_si128(packed.as_ptr().add(g * 16) as *const __m128i);
13420            let lo = _mm_and_si128(b, lomask);
13421            let hi = _mm_and_si128(_mm_srli_epi16::<4>(b), lomask);
13422            let w = _mm256_sub_epi8(
13423                _mm256_set_m128i(_mm_unpackhi_epi8(lo, hi), _mm_unpacklo_epi8(lo, hi)),
13424                eight,
13425            );
13426            let x = _mm256_loadu_si256(xq.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
13427            let p16 = _mm256_maddubs_epi16(_mm256_abs_epi8(w), _mm256_sign_epi8(x, w));
13428            let d = _mm256_madd_epi16(p16, ones);
13429            let hi128 = _mm256_extracti128_si256::<1>(d);
13430            let s128 = _mm_add_epi32(_mm256_castsi256_si128(d), hi128);
13431            let s64 = _mm_add_epi32(s128, _mm_srli_si128::<8>(s128));
13432            let s32 = _mm_add_epi32(s64, _mm_srli_si128::<4>(s64));
13433            acc += _mm_cvtsi128_si32(s32) as f32 * s;
13434        }
13435        acc
13436    }
13437}
13438
13439/// Two-activation q4 row via AVX2: nibbles unpacked ONCE per group,
13440/// both activations dotted against the same centered i8 register.
13441#[cfg(target_arch = "x86_64")]
13442#[target_feature(enable = "avx2")]
13443unsafe fn dot_q4_row_avx2_2(
13444    packed: &[u8],
13445    scales: &[u8],
13446    g0: usize,
13447    gpr: usize,
13448    xq1: &[i8],
13449    xq2: &[i8],
13450) -> (f32, f32) {
13451    // SAFETY: callers uphold slice-length contracts (see dot_q4_row_avx2).
13452    unsafe {
13453        use core::arch::x86_64::*;
13454        let lomask = _mm_set1_epi8(0x0F);
13455        let eight = _mm256_set1_epi8(8);
13456        let ones = _mm256_set1_epi16(1);
13457        let (mut acc1, mut acc2) = (0f32, 0f32);
13458        #[inline(always)]
13459        unsafe fn hsum(d: core::arch::x86_64::__m256i) -> i32 {
13460            unsafe {
13461                use core::arch::x86_64::*;
13462                let hi128 = _mm256_extracti128_si256::<1>(d);
13463                let s128 = _mm_add_epi32(_mm256_castsi256_si128(d), hi128);
13464                let s64 = _mm_add_epi32(s128, _mm_srli_si128::<8>(s128));
13465                let s32 = _mm_add_epi32(s64, _mm_srli_si128::<4>(s64));
13466                _mm_cvtsi128_si32(s32)
13467            }
13468        }
13469        for gi in 0..gpr {
13470            let g = g0 + gi;
13471            let s = f16_to_f32(u16::from_le_bytes([scales[g * 2], scales[g * 2 + 1]]));
13472            let b = _mm_loadu_si128(packed.as_ptr().add(g * 16) as *const __m128i);
13473            let lo = _mm_and_si128(b, lomask);
13474            let hi = _mm_and_si128(_mm_srli_epi16::<4>(b), lomask);
13475            let w = _mm256_sub_epi8(
13476                _mm256_set_m128i(_mm_unpackhi_epi8(lo, hi), _mm_unpacklo_epi8(lo, hi)),
13477                eight,
13478            );
13479            let aw = _mm256_abs_epi8(w);
13480            let x1 = _mm256_loadu_si256(xq1.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
13481            let x2 = _mm256_loadu_si256(xq2.as_ptr().add(gi * GROUP_SIZE) as *const __m256i);
13482            let d1 = _mm256_madd_epi16(_mm256_maddubs_epi16(aw, _mm256_sign_epi8(x1, w)), ones);
13483            let d2 = _mm256_madd_epi16(_mm256_maddubs_epi16(aw, _mm256_sign_epi8(x2, w)), ones);
13484            acc1 += hsum(d1) as f32 * s;
13485            acc2 += hsum(d2) as f32 * s;
13486        }
13487        (acc1, acc2)
13488    }
13489}
13490
13491/// One q8 row range via AVX2 (x86 mirror of `q8_range_sdot`).
13492#[cfg(target_arch = "x86_64")]
13493fn q8_range_avx2(
13494    q: &[u8],
13495    row_scale: &[f32],
13496    act: &SplitAct,
13497    cols: usize,
13498    out_addr: SendMut,
13499    start: usize,
13500    end: usize,
13501) {
13502    for o in start..end {
13503        let v = row_dot_avx2(&q[o * cols..(o + 1) * cols], act) * row_scale[o];
13504        // SAFETY: disjoint row ranges per worker.
13505        unsafe { *out_addr.at(o) = v };
13506    }
13507}
13508
13509/// Two-input q8 row range via AVX2 (x86 mirror of `q8_range2_sdot`).
13510#[cfg(target_arch = "x86_64")]
13511#[allow(clippy::too_many_arguments)]
13512fn q8_range2_avx2(
13513    q: &[u8],
13514    row_scale: &[f32],
13515    a1: &SplitAct,
13516    a2: &SplitAct,
13517    cols: usize,
13518    p1: SendMut,
13519    p2: SendMut,
13520    start: usize,
13521    end: usize,
13522) {
13523    for o in start..end {
13524        let row = &q[o * cols..(o + 1) * cols];
13525        // SAFETY: disjoint row ranges per worker.
13526        unsafe {
13527            *p1.at(o) = row_dot_avx2(row, a1) * row_scale[o];
13528            *p2.at(o) = row_dot_avx2(row, a2) * row_scale[o];
13529        }
13530    }
13531}
13532
13533// ───────────────────── A8W8 SDOT path (port of vmfcore, ×1.78 decode) ─────────────────────
13534
13535/// ARMv8.6 i8mm (smmla): 32 int8 MACs per instruction vs sdot's 16 —
13536/// yet MEASURED 2.4× SLOWER than the blocked sdot on Apple silicon
13537/// (108 vs 264 GF/s): the on-the-fly vcombine packing and the two-
13538/// accumulator dependency chain swamp the MAC advantage, and Apple's
13539/// four SIMD pipes already keep sdot fed. OPT-IN (CMF_I8MM=1) for
13540/// field trials on Cortex-A710/X-class parts with two pipes, where the
13541/// balance may differ; a pre-interleaved weight layout (repack infra)
13542/// is the known path if it ever earns its keep.
13543#[cfg(target_arch = "aarch64")]
13544fn i8mm_enabled() -> bool {
13545    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
13546    *ON.get_or_init(|| {
13547        std::env::var("CMF_I8MM").map(|v| v == "1").unwrap_or(false)
13548            && std::arch::is_aarch64_feature_detected!("i8mm")
13549    })
13550}
13551
13552/// SDOT enabled? Default ON when the CPU has ARMv8.2 dotprod;
13553/// `CMF_SDOT=0` disables (falls back to i8×f32 NEON).
13554/// (On non-ARM release builds only the test tolerance switch calls it.)
13555#[cfg_attr(not(target_arch = "aarch64"), allow(dead_code))]
13556fn sdot_enabled() -> bool {
13557    if FLOAT_ACTIVATIONS.get() {
13558        return false;
13559    }
13560    use std::sync::OnceLock;
13561    static ON: OnceLock<bool> = OnceLock::new();
13562    *ON.get_or_init(|| {
13563        let want = std::env::var("CMF_SDOT").map(|v| v != "0").unwrap_or(true);
13564        if !want {
13565            return false;
13566        }
13567
13568        #[cfg(target_arch = "aarch64")]
13569        {
13570            if std::arch::is_aarch64_feature_detected!("dotprod") {
13571                return true;
13572            }
13573            #[cfg(target_os = "android")]
13574            {
13575                if let Ok(cpuinfo) = std::fs::read_to_string("/proc/cpuinfo") {
13576                    if cpuinfo.lines().any(|l| {
13577                        (l.starts_with("Features") || l.starts_with("features"))
13578                            && l.contains("asimddp")
13579                    }) {
13580                        return true;
13581                    }
13582                }
13583            }
13584            false
13585        }
13586        #[cfg(not(target_arch = "aarch64"))]
13587        {
13588            false
13589        }
13590    })
13591}
13592
13593/// Two-field activation split (≡ vmfcore `q8_split_prep`): outlier
13594/// channels (>8·rms) are computed exactly in f32; the bulk (outliers
13595/// zeroed → clean absmax) goes through int8 SDOT. Computed ONCE per
13596/// matvec, shared by all rows/workers.
13597struct SplitAct {
13598    xq: Vec<i8>,
13599    sx: f32,
13600    outliers: Vec<(usize, f32)>,
13601    /// Σ xq — the VNNI bias-trick correction (`(w+128)·x` sums need
13602    /// `−128·Σx`); one i32 per split, computed once per matvec.
13603    #[cfg_attr(not(target_arch = "x86_64"), allow(dead_code))]
13604    xsum: i32,
13605    /// `Σ xq` per 32-element group, already f32 — the q4tp `(w+8)·x − 8·Σx`
13606    /// correction for the VERTICAL accumulator: the f32x8 partials reduce
13607    /// through an 8-lane horizontal sum, and each lane subtracts this once,
13608    /// so the row total carries exactly `8·Σx`. Precomputing it lets the
13609    /// AVX2 kernels drop the per-byte `vpaddb`/`vpabsb`/`vpsignb` (two of
13610    /// the three sat on port 5) and feed the raw unsigned nibbles straight
13611    /// to `vpmaddubsw`. Every value is an integer ≤ 32·127, so both the
13612    /// f32 conversion and each lane's subtraction are exact and the cell
13613    /// equals the old `(nib − 8)` dot bit for bit.
13614    #[cfg_attr(not(target_arch = "x86_64"), allow(dead_code))]
13615    xg8: Vec<f32>,
13616}
13617
13618thread_local! {
13619    /// Recycled xq buffers: split_act runs for every matvec (~200/token)
13620    /// and its hidden-size allocation was steady-state heap churn.
13621    static XQ_FREE: std::cell::RefCell<Vec<Vec<i8>>> =
13622        const { std::cell::RefCell::new(Vec::new()) };
13623    /// Recycled per-group correction buffers (see `SplitAct::xg8`).
13624    static XG8_FREE: std::cell::RefCell<Vec<Vec<f32>>> =
13625        const { std::cell::RefCell::new(Vec::new()) };
13626}
13627
13628/// Pop a recycled `xg8` buffer, or mint one; filled by [`xg8_of`].
13629fn xg8_take() -> Vec<f32> {
13630    let mut v = XG8_FREE.with(|f| f.borrow_mut().pop()).unwrap_or_default();
13631    v.clear();
13632    v
13633}
13634
13635impl Drop for SplitAct {
13636    fn drop(&mut self) {
13637        let buf = std::mem::take(&mut self.xq);
13638        if buf.capacity() > 0 {
13639            XQ_FREE.with(|f| {
13640                let mut f = f.borrow_mut();
13641                if f.len() < 16 {
13642                    f.push(buf);
13643                }
13644            });
13645        }
13646        let buf = std::mem::take(&mut self.xg8);
13647        if buf.capacity() > 0 {
13648            XG8_FREE.with(|f| {
13649                let mut f = f.borrow_mut();
13650                if f.len() < 16 {
13651                    f.push(buf);
13652                }
13653            });
13654        }
13655    }
13656}
13657
13658/// Fill `out` with `Σ xq` per group — see [`SplitAct::xg8`]. A tail
13659/// shorter than one group is dropped (`chunks_exact`); kernels guard on
13660/// `xg8.len() == gpr`.
13661fn xg8_fill(xq: &[i8], out: &mut Vec<f32>) {
13662    out.clear();
13663    out.extend(xq.chunks_exact(GROUP_SIZE).map(|c| {
13664        let mut s = 0i32;
13665        for &v in c {
13666            s += v as i32;
13667        }
13668        s as f32
13669    }));
13670}
13671
13672thread_local! {
13673    /// One scratch row per WORKER, kept for the life of the thread.
13674    ///
13675    /// The kernels take a row of group scales per dispatch, and a fresh
13676    /// `vec![0f32; gpr]` inside the closure is one allocation per worker per
13677    /// dispatch — on the release checkpoint about six thousand a token, a
13678    /// quarter of everything the benchmark counts.
13679    static KROW: UnsafeCell<Vec<f32>> = const { UnsafeCell::new(Vec::new()) };
13680    /// Two scratch rows for a gate/up pair.  Q2TP and Q4TP fused SwiGLU
13681    /// decode each projection's ladder independently, but both ladders have
13682    /// the same lifetime; retaining them per worker removes two heap trips
13683    /// from every dispatched expert pair.
13684    static KROWS: UnsafeCell<[Vec<f32>; 2]> =
13685        const { UnsafeCell::new([Vec::new(), Vec::new()]) };
13686}
13687
13688/// Borrow `n` floats of the calling worker's scratch. Nothing inside a
13689/// kernel body borrows it again, which is what keeps the RefCell honest.
13690#[inline]
13691fn with_krow<R>(n: usize, f: impl FnOnce(&mut [f32]) -> R) -> R {
13692    KROW.with(|s| {
13693        // SAFETY: `KROW` is thread-local and this function does not recurse;
13694        // each worker has exclusive access to its own scratch row.
13695        let b = unsafe { &mut *s.get() };
13696        if b.len() < n {
13697            b.resize(n, 0.0);
13698        }
13699        f(&mut b[..n])
13700    })
13701}
13702
13703/// `t.round().clamp(-127.0, 127.0) as i8`, bit for bit, without the libm
13704/// call. On baseline x86-64 (no SSE4.1 `roundps`) `f32::round` is a
13705/// function call per element, and split_act runs it over every hidden
13706/// state before every matvec: measured 27 us a call on a 2048-wide
13707/// activation on an EPYC 7763 — 5.4 ms of a 55 ms decode token, all of
13708/// it on the caller's thread while thirty workers wait. Clamping first is
13709/// equivalent (round is monotonic and ±127 are integers), and after the
13710/// clamp `t - trunc(t)` is exact, so the half-away-from-zero decision is
13711/// the one `round` makes. NaN clamps to NaN and converts to 0, as before.
13712/// The loop vectorizes (cvttps2dq + compare/select).
13713#[inline(always)]
13714fn q8_round(t: f32) -> i8 {
13715    let t = t.clamp(-127.0, 127.0);
13716    let i = t as i32;
13717    let f = t - i as f32;
13718    let r = if f >= 0.5 {
13719        i + 1
13720    } else if f <= -0.5 {
13721        i - 1
13722    } else {
13723        i
13724    };
13725    r as i8
13726}
13727
13728#[inline]
13729fn with_krows<R>(n: usize, f: impl FnOnce(&mut [f32], &mut [f32]) -> R) -> R {
13730    KROWS.with(|s| {
13731        // SAFETY: KROWS is thread-local and no kernel body recursively calls
13732        // this helper; each participant owns its two vectors exclusively.
13733        let b = unsafe { &mut *s.get() };
13734        for row in b.iter_mut() {
13735            if row.len() < n {
13736                row.resize(n, 0.0);
13737            }
13738        }
13739        let (a, b) = b.split_at_mut(1);
13740        f(&mut a[0][..n], &mut b[0][..n])
13741    })
13742}
13743
13744#[inline]
13745fn silu_mul_limited(mut gate: f32, mut up: f32, limit: f32) -> f32 {
13746    if limit > 0.0 {
13747        up = up.clamp(-limit, limit);
13748        gate = gate.min(limit);
13749    }
13750    gate / (1.0 + (-gate).exp()) * up
13751}
13752
13753/// `split_act` of every column of a batch, the columns spread over the
13754/// pool from 16 on. Each column's split is its own (the same bits as the
13755/// serial loop); serially it was 25 µs a column, 6 ms of a Spark-4B
13756/// prefill token on an 8-thread EPYC while the workers idled.
13757fn split_acts_pooled(xs_all: &[f32], b: usize, cols: usize, pool: Option<&Pool>) -> Vec<SplitAct> {
13758    match pool {
13759        Some(p) if b >= 16 => {
13760            let slots: Vec<std::sync::Mutex<Option<SplitAct>>> =
13761                (0..b).map(|_| std::sync::Mutex::new(None)).collect();
13762            p.run_rows(b, &|start, end| {
13763                for bi in start..end {
13764                    let a = split_act(&xs_all[bi * cols..(bi + 1) * cols]);
13765                    *slots[bi].lock().unwrap_or_else(|e| e.into_inner()) = Some(a);
13766                }
13767            });
13768            slots
13769                .into_iter()
13770                .map(|m| {
13771                    m.into_inner()
13772                        .unwrap_or_else(|e| e.into_inner())
13773                        .expect("every column split")
13774                })
13775                .collect()
13776        }
13777        _ => (0..b)
13778            .map(|bi| split_act(&xs_all[bi * cols..(bi + 1) * cols]))
13779            .collect(),
13780    }
13781}
13782
13783fn split_act(x: &[f32]) -> SplitAct {
13784    let _prof = crate::cpuprof::time(crate::cpuprof::Slot::SplitAct);
13785    let n = x.len();
13786    let rms = (x.iter().map(|&v| (v * v) as f64).sum::<f64>() / n.max(1) as f64).sqrt() as f32;
13787    let thr = 8.0 * rms;
13788    // One pass: collect outliers and the bulk absmax (outliers excluded —
13789    // identical to the old zero-then-fold over a copied buffer, minus the
13790    // full-vector copy).
13791    let mut outliers: Vec<(usize, f32)> = Vec::new();
13792    let mut amax = 0f32;
13793    for (j, &v) in x.iter().enumerate() {
13794        let a = v.abs();
13795        if a > thr {
13796            outliers.push((j, v));
13797        } else if a > amax {
13798            amax = a;
13799        }
13800    }
13801    let sx = if amax > 0.0 { amax / 127.0 } else { 1.0 };
13802    let inv = 1.0 / sx;
13803    crate::cpuprof::count_outliers(outliers.len() as u64);
13804    let mut xq = XQ_FREE.with(|f| f.borrow_mut().pop()).unwrap_or_default();
13805    xq.clear();
13806    xq.reserve(n);
13807    if outliers.is_empty() {
13808        xq.extend(
13809            x.iter()
13810                .map(|&v| q8_round(v * inv)),
13811        );
13812    } else {
13813        // Outlier slots quantize to 0 (their exact term is added later).
13814        xq.extend(x.iter().map(|&v| {
13815            if v.abs() > thr {
13816                0
13817            } else {
13818                q8_round(v * inv)
13819            }
13820        }));
13821    }
13822    let xsum = xq.iter().map(|&v| v as i32).sum();
13823    let mut xg8 = xg8_take();
13824    xg8_fill(&xq, &mut xg8);
13825    SplitAct {
13826        xq,
13827        sx,
13828        outliers,
13829        xsum,
13830        xg8,
13831    }
13832}
13833
13834fn split_act_q8_2f(x: &[f32], col: &[f32]) -> SplitAct {
13835    let _prof = crate::cpuprof::time(crate::cpuprof::Slot::SplitAct);
13836    let n = x.len();
13837    let rms = (x
13838        .iter()
13839        .zip(col)
13840        .map(|(&a, &c)| {
13841            let v = a * c;
13842            (v * v) as f64
13843        })
13844        .sum::<f64>()
13845        / n.max(1) as f64)
13846        .sqrt() as f32;
13847    let thr = 8.0 * rms;
13848
13849    let mut outliers = Vec::new();
13850    let mut amax = 0f32;
13851    for (j, (&a, &c)) in x.iter().zip(col).enumerate() {
13852        let v = a * c;
13853        let s = v.abs();
13854        if s > thr {
13855            outliers.push((j, v));
13856        } else if s > amax {
13857            amax = s;
13858        }
13859    }
13860
13861    let sx = if amax > 0.0 { amax / 127.0 } else { 1.0 };
13862    let inv = 1.0 / sx;
13863    let mut xq = XQ_FREE.with(|f| f.borrow_mut().pop()).unwrap_or_default();
13864    xq.clear();
13865    xq.reserve(n);
13866    if outliers.is_empty() {
13867        xq.extend(
13868            x.iter()
13869                .zip(col)
13870                .map(|(&a, &c)| q8_round((a * c) * inv)),
13871        );
13872    } else {
13873        xq.extend(x.iter().zip(col).map(|(&a, &c)| {
13874            let v = a * c;
13875            if v.abs() > thr {
13876                0
13877            } else {
13878                q8_round(v * inv)
13879            }
13880        }));
13881    }
13882    let xsum = xq.iter().map(|&v| v as i32).sum();
13883    let mut xg8 = xg8_take();
13884    xg8_fill(&xq, &mut xg8);
13885    SplitAct {
13886        xq,
13887        sx,
13888        outliers,
13889        xsum,
13890        xg8,
13891    }
13892}
13893
13894/// int8(weight)·int8(activation) → i32 via `sdot` (inline asm — the
13895/// vdotq intrinsic is unstable; port of vmfcore `dot_i8_sdot`).
13896#[cfg(target_arch = "aarch64")]
13897#[target_feature(enable = "neon,dotprod")]
13898unsafe fn dot_i8_sdot(w: &[u8], xq: &[i8]) -> i32 {
13899    // SAFETY: callers uphold slice-length contracts (see call sites).
13900    unsafe {
13901        use core::arch::aarch64::*;
13902        use core::arch::asm;
13903        let wp = w.as_ptr() as *const i8;
13904        let n = w.len();
13905        let (mut a0, mut a1, mut a2, mut a3) = (
13906            vdupq_n_s32(0),
13907            vdupq_n_s32(0),
13908            vdupq_n_s32(0),
13909            vdupq_n_s32(0),
13910        );
13911        let mut i = 0;
13912        while i + 64 <= n {
13913            let (w0, x0) = (vld1q_s8(wp.add(i)), vld1q_s8(xq.as_ptr().add(i)));
13914            let (w1, x1) = (vld1q_s8(wp.add(i + 16)), vld1q_s8(xq.as_ptr().add(i + 16)));
13915            let (w2, x2) = (vld1q_s8(wp.add(i + 32)), vld1q_s8(xq.as_ptr().add(i + 32)));
13916            let (w3, x3) = (vld1q_s8(wp.add(i + 48)), vld1q_s8(xq.as_ptr().add(i + 48)));
13917            asm!(
13918                "sdot {a0:v}.4s, {w0:v}.16b, {x0:v}.16b",
13919                "sdot {a1:v}.4s, {w1:v}.16b, {x1:v}.16b",
13920                "sdot {a2:v}.4s, {w2:v}.16b, {x2:v}.16b",
13921                "sdot {a3:v}.4s, {w3:v}.16b, {x3:v}.16b",
13922                a0 = inout(vreg) a0, a1 = inout(vreg) a1, a2 = inout(vreg) a2, a3 = inout(vreg) a3,
13923                w0 = in(vreg) w0, x0 = in(vreg) x0, w1 = in(vreg) w1, x1 = in(vreg) x1,
13924                w2 = in(vreg) w2, x2 = in(vreg) x2, w3 = in(vreg) w3, x3 = in(vreg) x3,
13925                options(pure, nomem, nostack),
13926            );
13927            i += 64;
13928        }
13929        while i + 16 <= n {
13930            let (wv, xv) = (vld1q_s8(wp.add(i)), vld1q_s8(xq.as_ptr().add(i)));
13931            asm!("sdot {a:v}.4s, {w:v}.16b, {x:v}.16b",
13932                 a = inout(vreg) a0, w = in(vreg) wv, x = in(vreg) xv, options(pure, nomem, nostack));
13933            i += 16;
13934        }
13935        let mut s = vaddvq_s32(vaddq_s32(vaddq_s32(a0, a1), vaddq_s32(a2, a3)));
13936        while i < n {
13937            s += (*wp.add(i)) as i32 * xq[i] as i32;
13938            i += 1;
13939        }
13940        s
13941    }
13942}
13943
13944/// Row-blocked SDOT: 4 output rows per pass — the activation chunk is
13945/// loaded once and reused, 4 independent accumulators hide sdot latency
13946/// (port of vmfcore `dot_i8_sdot_4rows`).
13947#[cfg(target_arch = "aarch64")]
13948#[target_feature(enable = "neon,dotprod")]
13949unsafe fn dot_i8_sdot_4rows(w0: &[u8], w1: &[u8], w2: &[u8], w3: &[u8], xq: &[i8]) -> [i32; 4] {
13950    // SAFETY: callers uphold slice-length contracts (see call sites).
13951    unsafe {
13952        use core::arch::aarch64::*;
13953        use core::arch::asm;
13954        let n = xq.len();
13955        let px = xq.as_ptr();
13956        let (p0, p1, p2, p3) = (
13957            w0.as_ptr() as *const i8,
13958            w1.as_ptr() as *const i8,
13959            w2.as_ptr() as *const i8,
13960            w3.as_ptr() as *const i8,
13961        );
13962        let (mut a0, mut a1, mut a2, mut a3) = (
13963            vdupq_n_s32(0),
13964            vdupq_n_s32(0),
13965            vdupq_n_s32(0),
13966            vdupq_n_s32(0),
13967        );
13968        let mut i = 0;
13969        while i + 16 <= n {
13970            let x = vld1q_s8(px.add(i));
13971            let v0 = vld1q_s8(p0.add(i));
13972            let v1 = vld1q_s8(p1.add(i));
13973            let v2 = vld1q_s8(p2.add(i));
13974            let v3 = vld1q_s8(p3.add(i));
13975            asm!(
13976                "sdot {a0:v}.4s, {v0:v}.16b, {x:v}.16b",
13977                "sdot {a1:v}.4s, {v1:v}.16b, {x:v}.16b",
13978                "sdot {a2:v}.4s, {v2:v}.16b, {x:v}.16b",
13979                "sdot {a3:v}.4s, {v3:v}.16b, {x:v}.16b",
13980                a0 = inout(vreg) a0, a1 = inout(vreg) a1, a2 = inout(vreg) a2, a3 = inout(vreg) a3,
13981                v0 = in(vreg) v0, v1 = in(vreg) v1, v2 = in(vreg) v2, v3 = in(vreg) v3, x = in(vreg) x,
13982                options(pure, nomem, nostack),
13983            );
13984            i += 16;
13985        }
13986        let mut r = [
13987            vaddvq_s32(a0),
13988            vaddvq_s32(a1),
13989            vaddvq_s32(a2),
13990            vaddvq_s32(a3),
13991        ];
13992        while i < n {
13993            let xi = *px.add(i) as i32;
13994            r[0] += (*p0.add(i)) as i32 * xi;
13995            r[1] += (*p1.add(i)) as i32 * xi;
13996            r[2] += (*p2.add(i)) as i32 * xi;
13997            r[3] += (*p3.add(i)) as i32 * xi;
13998            i += 1;
13999        }
14000        r
14001    }
14002}
14003
14004/// 4 interleaved rows in one pass: the repacked group is [r0[c], r1[c],
14005/// r2[c], r3[c]] per 16-byte chunk, so each iteration reads ONE 64-byte
14006/// line plus the shared activation chunk — a single sequential weight
14007/// stream per worker. Per-row accumulation is the same one-accumulator
14008/// scheme as `dot_i8_sdot_4rows`; integer sums are exact, so outputs
14009/// are bit-identical to the mmap-layout kernel.
14010#[cfg(target_arch = "aarch64")]
14011#[target_feature(enable = "neon,dotprod")]
14012unsafe fn dot_i8_sdot_4rows_il(g: &[u8], xq: &[i8]) -> [i32; 4] {
14013    // SAFETY: callers uphold slice-length contracts (g.len() == 4·n,
14014    // n % 16 == 0 — guaranteed by the repack gate).
14015    unsafe {
14016        use core::arch::aarch64::*;
14017        use core::arch::asm;
14018        let n = xq.len();
14019        let px = xq.as_ptr();
14020        let pg = g.as_ptr() as *const i8;
14021        let (mut a0, mut a1, mut a2, mut a3) = (
14022            vdupq_n_s32(0),
14023            vdupq_n_s32(0),
14024            vdupq_n_s32(0),
14025            vdupq_n_s32(0),
14026        );
14027        let mut i = 0;
14028        while i + 16 <= n {
14029            let x = vld1q_s8(px.add(i));
14030            let base = pg.add(4 * i);
14031            let v0 = vld1q_s8(base);
14032            let v1 = vld1q_s8(base.add(16));
14033            let v2 = vld1q_s8(base.add(32));
14034            let v3 = vld1q_s8(base.add(48));
14035            asm!(
14036                "sdot {a0:v}.4s, {v0:v}.16b, {x:v}.16b",
14037                "sdot {a1:v}.4s, {v1:v}.16b, {x:v}.16b",
14038                "sdot {a2:v}.4s, {v2:v}.16b, {x:v}.16b",
14039                "sdot {a3:v}.4s, {v3:v}.16b, {x:v}.16b",
14040                a0 = inout(vreg) a0, a1 = inout(vreg) a1, a2 = inout(vreg) a2, a3 = inout(vreg) a3,
14041                v0 = in(vreg) v0, v1 = in(vreg) v1, v2 = in(vreg) v2, v3 = in(vreg) v3, x = in(vreg) x,
14042                options(pure, nomem, nostack),
14043            );
14044            i += 16;
14045        }
14046        [
14047            vaddvq_s32(a0),
14048            vaddvq_s32(a1),
14049            vaddvq_s32(a2),
14050            vaddvq_s32(a3),
14051        ]
14052    }
14053}
14054
14055/// One q8 row range via SDOT (4-row blocks + tail) — the body of
14056/// `qmatvec`'s hot loop, extracted so multi-matrix jobs can drive the
14057/// SAME kernel for several tensors under one pool dispatch. `rep` — the
14058/// load-time interleaved repack (empty = mmap layout only); rows outside
14059/// full 4-row groups always come from the mmap layout.
14060#[cfg(target_arch = "aarch64")]
14061fn q8_range_sdot(
14062    q: &[u8],
14063    rep: &[u8],
14064    row_scale: &[f32],
14065    act: &SplitAct,
14066    cols: usize,
14067    out_addr: SendMut,
14068    start: usize,
14069    end: usize,
14070) {
14071    let mut o = start;
14072    // Leading rows to the group boundary (repack path only): the pool
14073    // splits row ranges arbitrarily, groups are absolute.
14074    if !rep.is_empty() {
14075        while o < end && o % 4 != 0 {
14076            let v = row_dot_sdot(&q[o * cols..(o + 1) * cols], act) * row_scale[o];
14077            unsafe { *out_addr.at(o) = v };
14078            o += 1;
14079        }
14080    }
14081    while o + 4 <= end {
14082        let r = if rep.is_empty() {
14083            unsafe {
14084                dot_i8_sdot_4rows(
14085                    &q[o * cols..(o + 1) * cols],
14086                    &q[(o + 1) * cols..(o + 2) * cols],
14087                    &q[(o + 2) * cols..(o + 3) * cols],
14088                    &q[(o + 3) * cols..(o + 4) * cols],
14089                    &act.xq,
14090                )
14091            }
14092        } else {
14093            unsafe { dot_i8_sdot_4rows_il(&rep[o * cols..(o + 4) * cols], &act.xq) }
14094        };
14095        for k in 0..4 {
14096            let mut acc = r[k] as f32 * act.sx;
14097            for &(j, xv) in &act.outliers {
14098                acc += (q[(o + k) * cols + j] as i8) as f32 * xv;
14099            }
14100            // SAFETY: disjoint row ranges per worker.
14101            unsafe { *out_addr.at(o + k) = acc * row_scale[o + k] };
14102        }
14103        o += 4;
14104    }
14105    while o < end {
14106        let v = row_dot_sdot(&q[o * cols..(o + 1) * cols], act) * row_scale[o];
14107        unsafe { *out_addr.at(o) = v };
14108        o += 1;
14109    }
14110}
14111
14112/// Two-input q8 row range via SDOT — `qmatvec2`'s hot loop, extracted
14113/// for the fused pair multi-matrix job (`matvec2_many`).
14114#[cfg(target_arch = "aarch64")]
14115#[allow(clippy::too_many_arguments)]
14116fn q8_range2_sdot(
14117    q: &[u8],
14118    row_scale: &[f32],
14119    a1: &SplitAct,
14120    a2: &SplitAct,
14121    cols: usize,
14122    p1: SendMut,
14123    p2: SendMut,
14124    start: usize,
14125    end: usize,
14126) {
14127    for o in start..end {
14128        let row = &q[o * cols..(o + 1) * cols];
14129        // SAFETY: disjoint row ranges per worker.
14130        unsafe {
14131            *p1.at(o) = row_dot_sdot(row, a1) * row_scale[o];
14132            *p2.at(o) = row_dot_sdot(row, a2) * row_scale[o];
14133        }
14134    }
14135}
14136
14137/// Two-input q8 row range, f32 kernel (non-SDOT) — same extraction.
14138#[allow(clippy::too_many_arguments)]
14139fn q8_range2_f32(
14140    q: &[u8],
14141    row_scale: &[f32],
14142    x1: &[f32],
14143    x2: &[f32],
14144    cols: usize,
14145    p1: SendMut,
14146    p2: SendMut,
14147    start: usize,
14148    end: usize,
14149) {
14150    for o in start..end {
14151        let row = &q[o * cols..(o + 1) * cols];
14152        // SAFETY: disjoint row ranges per worker.
14153        unsafe {
14154            *p1.at(o) = dot_i8_f32(row, x1) * row_scale[o];
14155            *p2.at(o) = dot_i8_f32(row, x2) * row_scale[o];
14156        }
14157    }
14158}
14159
14160/// Scalar/NEON-f32 q8 row range (non-SDOT platforms) — same extraction.
14161fn q8_range_f32(
14162    q: &[u8],
14163    row_scale: &[f32],
14164    xs: &[f32],
14165    cols: usize,
14166    out_addr: SendMut,
14167    start: usize,
14168    end: usize,
14169) {
14170    for o in start..end {
14171        let v = dot_i8_f32(&q[o * cols..(o + 1) * cols], xs) * row_scale[o];
14172        // SAFETY: disjoint row ranges per worker.
14173        unsafe { *out_addr.at(o) = v };
14174    }
14175}
14176
14177/// One q8 row against a split activation, portable: the per-arch fast
14178/// dots where they exist, the exact scalar loop elsewhere. The scalar
14179/// arm is also the test oracle for both fast arms.
14180#[inline]
14181fn q8_row_dot(row: &[u8], act: &SplitAct) -> f32 {
14182    #[cfg(target_arch = "aarch64")]
14183    return row_dot_sdot(row, act);
14184    #[cfg(target_arch = "x86_64")]
14185    return row_dot_avx2(row, act);
14186    #[allow(unreachable_code)]
14187    q8_row_dot_scalar(row, act)
14188}
14189
14190#[allow(dead_code)]
14191fn q8_row_dot_scalar(row: &[u8], act: &SplitAct) -> f32 {
14192    let mut acc = 0i32;
14193    for (k, &b) in row.iter().enumerate() {
14194        acc += (b as i8) as i32 * act.xq[k] as i32;
14195    }
14196    let mut acc = acc as f32 * act.sx;
14197    for &(j, xv) in &act.outliers {
14198        acc += (row[j] as i8) as f32 * xv;
14199    }
14200    acc
14201}
14202
14203/// SDOT row dot with exact outlier correction:
14204/// `dot = sdot(w, xq)·sx + Σ_outl w[j]·x[j]` (then × row_scale by caller).
14205#[cfg(target_arch = "aarch64")]
14206#[inline]
14207fn row_dot_sdot(row: &[u8], act: &SplitAct) -> f32 {
14208    let mut acc = unsafe { dot_i8_sdot(row, &act.xq) } as f32 * act.sx;
14209    for &(j, xv) in &act.outliers {
14210        acc += (row[j] as i8) as f32 * xv;
14211    }
14212    acc
14213}
14214
14215/// One q4 row via SDOT: each 32-group's nibbles unpack to centered i8
14216/// (nib−8 ∈ [−8,7]), int8×int8 `sdot` against the pre-quantized
14217/// activation group, × the group's f16 scale. Returns Σ_g dot_g·s_g;
14218/// the caller multiplies by the activation scale and adds the exact
14219/// outlier terms (port of vmfcore `dot_q4_block_sdot`, +23% measured).
14220/// Nibble order matches the writer: element 2k = low nibble, 2k+1 = high
14221/// → zip(lo,hi) restores flat order.
14222#[cfg(target_arch = "aarch64")]
14223#[target_feature(enable = "neon,dotprod")]
14224unsafe fn dot_q4_row_sdot(packed: &[u8], scales: &[u8], g0: usize, gpr: usize, xq: &[i8]) -> f32 {
14225    // SAFETY: callers uphold slice-length contracts (16 packed bytes and
14226    // 2 scale bytes per group; xq.len() == gpr·GROUP_SIZE).
14227    unsafe {
14228        use core::arch::aarch64::*;
14229        use core::arch::asm;
14230        let lomask = vdupq_n_u8(0x0F);
14231        let eight = vdupq_n_s8(8);
14232        let mut acc = 0f32;
14233        for gi in 0..gpr {
14234            let g = g0 + gi;
14235            let s = f16_to_f32(u16::from_le_bytes([scales[g * 2], scales[g * 2 + 1]]));
14236            let b = vld1q_u8(packed.as_ptr().add(g * 16));
14237            let lo = vandq_u8(b, lomask);
14238            let hi = vshrq_n_u8::<4>(b);
14239            let e0 = vsubq_s8(vreinterpretq_s8_u8(vzip1q_u8(lo, hi)), eight);
14240            let e1 = vsubq_s8(vreinterpretq_s8_u8(vzip2q_u8(lo, hi)), eight);
14241            let x0 = vld1q_s8(xq.as_ptr().add(gi * GROUP_SIZE));
14242            let x1 = vld1q_s8(xq.as_ptr().add(gi * GROUP_SIZE + 16));
14243            let (mut a0, mut a1) = (vdupq_n_s32(0), vdupq_n_s32(0));
14244            asm!(
14245                "sdot {a0:v}.4s, {e0:v}.16b, {x0:v}.16b",
14246                "sdot {a1:v}.4s, {e1:v}.16b, {x1:v}.16b",
14247                a0 = inout(vreg) a0, a1 = inout(vreg) a1,
14248                e0 = in(vreg) e0, x0 = in(vreg) x0, e1 = in(vreg) e1, x1 = in(vreg) x1,
14249                options(pure, nomem, nostack),
14250            );
14251            acc += vaddvq_s32(vaddq_s32(a0, a1)) as f32 * s;
14252        }
14253        acc
14254    }
14255}
14256
14257/// Two-activation q4 row via SDOT: the nibble unpack (the expensive
14258/// part) happens ONCE per group; both pre-quantized activations are
14259/// dotted against the same centered i8 registers. Per-lane math matches
14260/// `dot_q4_row_sdot` exactly.
14261#[cfg(target_arch = "aarch64")]
14262#[target_feature(enable = "neon,dotprod")]
14263unsafe fn dot_q4_row_sdot2(
14264    packed: &[u8],
14265    scales: &[u8],
14266    g0: usize,
14267    gpr: usize,
14268    xq1: &[i8],
14269    xq2: &[i8],
14270) -> (f32, f32) {
14271    // SAFETY: callers uphold slice-length contracts (16 packed bytes and
14272    // 2 scale bytes per group; xq*.len() == gpr·GROUP_SIZE).
14273    unsafe {
14274        use core::arch::aarch64::*;
14275        use core::arch::asm;
14276        let lomask = vdupq_n_u8(0x0F);
14277        let eight = vdupq_n_s8(8);
14278        let (mut acc1, mut acc2) = (0f32, 0f32);
14279        for gi in 0..gpr {
14280            let g = g0 + gi;
14281            let s = f16_to_f32(u16::from_le_bytes([scales[g * 2], scales[g * 2 + 1]]));
14282            let b = vld1q_u8(packed.as_ptr().add(g * 16));
14283            let lo = vandq_u8(b, lomask);
14284            let hi = vshrq_n_u8::<4>(b);
14285            let e0 = vsubq_s8(vreinterpretq_s8_u8(vzip1q_u8(lo, hi)), eight);
14286            let e1 = vsubq_s8(vreinterpretq_s8_u8(vzip2q_u8(lo, hi)), eight);
14287            let x10 = vld1q_s8(xq1.as_ptr().add(gi * GROUP_SIZE));
14288            let x11 = vld1q_s8(xq1.as_ptr().add(gi * GROUP_SIZE + 16));
14289            let x20 = vld1q_s8(xq2.as_ptr().add(gi * GROUP_SIZE));
14290            let x21 = vld1q_s8(xq2.as_ptr().add(gi * GROUP_SIZE + 16));
14291            let (mut a0, mut a1, mut b0, mut b1) = (
14292                vdupq_n_s32(0),
14293                vdupq_n_s32(0),
14294                vdupq_n_s32(0),
14295                vdupq_n_s32(0),
14296            );
14297            asm!(
14298                "sdot {a0:v}.4s, {e0:v}.16b, {x10:v}.16b",
14299                "sdot {a1:v}.4s, {e1:v}.16b, {x11:v}.16b",
14300                "sdot {b0:v}.4s, {e0:v}.16b, {x20:v}.16b",
14301                "sdot {b1:v}.4s, {e1:v}.16b, {x21:v}.16b",
14302                a0 = inout(vreg) a0, a1 = inout(vreg) a1,
14303                b0 = inout(vreg) b0, b1 = inout(vreg) b1,
14304                e0 = in(vreg) e0, e1 = in(vreg) e1,
14305                x10 = in(vreg) x10, x11 = in(vreg) x11,
14306                x20 = in(vreg) x20, x21 = in(vreg) x21,
14307                options(pure, nomem, nostack),
14308            );
14309            acc1 += vaddvq_s32(vaddq_s32(a0, a1)) as f32 * s;
14310            acc2 += vaddvq_s32(vaddq_s32(b0, b1)) as f32 * s;
14311        }
14312        (acc1, acc2)
14313    }
14314}
14315
14316// ───────────────────── fused int8 kernels ─────────────────────
14317
14318/// `acc += w · row` where the row is centered i8 — NEON widen+fma on
14319/// aarch64, scalar elsewhere. The KV-cache q8 value path rides on this.
14320#[inline]
14321pub(crate) fn axpy_i8_f32(acc: &mut [f32], row: &[i8], w: f32) {
14322    #[cfg(target_arch = "aarch64")]
14323    unsafe {
14324        return axpy_i8_f32_neon(acc, row, w);
14325    }
14326    #[cfg(target_arch = "x86_64")]
14327    if avx2_enabled() {
14328        return unsafe { axpy_i8_f32_avx2(acc, row, w) };
14329    }
14330    #[allow(unreachable_code)]
14331    {
14332        for (a, &b) in acc.iter_mut().zip(row) {
14333            *a += w * b as f32;
14334        }
14335    }
14336}
14337
14338/// i8→f32 axpy via AVX2/FMA (x86 mirror of `axpy_i8_f32_neon`).
14339#[cfg(target_arch = "x86_64")]
14340#[target_feature(enable = "avx2,fma")]
14341unsafe fn axpy_i8_f32_avx2(acc: &mut [f32], row: &[i8], w: f32) {
14342    // SAFETY: callers uphold slice-length contracts (see call sites).
14343    unsafe {
14344        use core::arch::x86_64::*;
14345        let n = acc.len().min(row.len());
14346        let ap = acc.as_mut_ptr();
14347        let rp = row.as_ptr();
14348        let wv = _mm256_set1_ps(w);
14349        let mut j = 0usize;
14350        while j + 16 <= n {
14351            let rb = _mm_loadu_si128(rp.add(j) as *const __m128i);
14352            let lo = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(rb));
14353            let hi = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128::<8>(rb)));
14354            let v0 = _mm256_fmadd_ps(wv, lo, _mm256_loadu_ps(ap.add(j)));
14355            let v1 = _mm256_fmadd_ps(wv, hi, _mm256_loadu_ps(ap.add(j + 8)));
14356            _mm256_storeu_ps(ap.add(j), v0);
14357            _mm256_storeu_ps(ap.add(j + 8), v1);
14358            j += 16;
14359        }
14360        while j < n {
14361            *ap.add(j) += w * (*rp.add(j)) as f32;
14362            j += 1;
14363        }
14364    }
14365}
14366
14367#[cfg(target_arch = "aarch64")]
14368#[target_feature(enable = "neon")]
14369unsafe fn axpy_i8_f32_neon(acc: &mut [f32], row: &[i8], w: f32) {
14370    // SAFETY: callers uphold slice-length contracts (see call sites).
14371    unsafe {
14372        use core::arch::aarch64::*;
14373        let n = acc.len().min(row.len());
14374        let ap = acc.as_mut_ptr();
14375        let rp = row.as_ptr();
14376        let wv = vdupq_n_f32(w);
14377        let mut j = 0usize;
14378        while j + 16 <= n {
14379            let rb = vld1q_s8(rp.add(j));
14380            let lo = vmovl_s8(vget_low_s8(rb));
14381            let hi = vmovl_s8(vget_high_s8(rb));
14382            for (off, half) in [(0, lo), (8, hi)] {
14383                let f0 = vcvtq_f32_s32(vmovl_s16(vget_low_s16(half)));
14384                let f1 = vcvtq_f32_s32(vmovl_s16(vget_high_s16(half)));
14385                let o = j + off;
14386                vst1q_f32(ap.add(o), vfmaq_f32(vld1q_f32(ap.add(o)), wv, f0));
14387                vst1q_f32(ap.add(o + 4), vfmaq_f32(vld1q_f32(ap.add(o + 4)), wv, f1));
14388            }
14389            j += 16;
14390        }
14391        while j < n {
14392            *ap.add(j) += w * (*rp.add(j)) as f32;
14393            j += 1;
14394        }
14395    }
14396}
14397
14398/// i8 row · f32 x. NEON on aarch64 (ported from vmfcore `dot_i8_f32_neon`,
14399/// ≈9× scalar), scalar elsewhere.
14400#[inline]
14401pub(crate) fn dot_i8_f32(w: &[u8], x: &[f32]) -> f32 {
14402    #[cfg(target_arch = "aarch64")]
14403    unsafe {
14404        return dot_i8_f32_neon(w, x);
14405    }
14406    #[cfg(target_arch = "x86_64")]
14407    if avx2_enabled() {
14408        return unsafe { dot_i8_f32_avx2(w, x) };
14409    }
14410    #[allow(unreachable_code)]
14411    {
14412        let mut sum = 0.0f32;
14413        for (j, &b) in w.iter().enumerate() {
14414            sum += (b as i8) as f32 * x[j];
14415        }
14416        sum
14417    }
14418}
14419
14420/// i8 row · (x ⊙ col_field) — the q8_2f row dot with the θ col-field
14421/// folded into the product (no prescaled copy of x). NEON on aarch64,
14422/// scalar elsewhere. Used by the active-neuron path `row_dot`.
14423#[inline]
14424fn dot_i8_col_f32(w: &[u8], x: &[f32], col: &[f32]) -> f32 {
14425    #[cfg(target_arch = "aarch64")]
14426    unsafe {
14427        return dot_i8_col_f32_neon(w, x, col);
14428    }
14429    #[allow(unreachable_code)]
14430    {
14431        let mut sum = 0.0f32;
14432        for (j, &b) in w.iter().enumerate() {
14433            sum += (b as i8) as f32 * x[j] * col[j];
14434        }
14435        sum
14436    }
14437}
14438
14439#[cfg(target_arch = "aarch64")]
14440#[target_feature(enable = "neon")]
14441unsafe fn dot_i8_col_f32_neon(w: &[u8], x: &[f32], col: &[f32]) -> f32 {
14442    // SAFETY: callers uphold slice-length contracts (see call sites).
14443    unsafe {
14444        use core::arch::aarch64::*;
14445        let n = x.len();
14446        let wp = w.as_ptr() as *const i8;
14447        let xp = x.as_ptr();
14448        let cp = col.as_ptr();
14449        let (mut a0, mut a1, mut a2, mut a3) = (
14450            vdupq_n_f32(0.0),
14451            vdupq_n_f32(0.0),
14452            vdupq_n_f32(0.0),
14453            vdupq_n_f32(0.0),
14454        );
14455        let mut j = 0usize;
14456        while j + 16 <= n {
14457            let wb = vld1q_s8(wp.add(j));
14458            let lo = vmovl_s8(vget_low_s8(wb));
14459            let hi = vmovl_s8(vget_high_s8(wb));
14460            let w0 = vcvtq_f32_s32(vmovl_s16(vget_low_s16(lo)));
14461            let w1 = vcvtq_f32_s32(vmovl_s16(vget_high_s16(lo)));
14462            let w2 = vcvtq_f32_s32(vmovl_s16(vget_low_s16(hi)));
14463            let w3 = vcvtq_f32_s32(vmovl_s16(vget_high_s16(hi)));
14464            a0 = vfmaq_f32(
14465                a0,
14466                w0,
14467                vmulq_f32(vld1q_f32(xp.add(j)), vld1q_f32(cp.add(j))),
14468            );
14469            a1 = vfmaq_f32(
14470                a1,
14471                w1,
14472                vmulq_f32(vld1q_f32(xp.add(j + 4)), vld1q_f32(cp.add(j + 4))),
14473            );
14474            a2 = vfmaq_f32(
14475                a2,
14476                w2,
14477                vmulq_f32(vld1q_f32(xp.add(j + 8)), vld1q_f32(cp.add(j + 8))),
14478            );
14479            a3 = vfmaq_f32(
14480                a3,
14481                w3,
14482                vmulq_f32(vld1q_f32(xp.add(j + 12)), vld1q_f32(cp.add(j + 12))),
14483            );
14484            j += 16;
14485        }
14486        let mut sum = vaddvq_f32(vaddq_f32(vaddq_f32(a0, a1), vaddq_f32(a2, a3)));
14487        while j < n {
14488            sum += (*wp.add(j)) as f32 * *xp.add(j) * *cp.add(j);
14489            j += 1;
14490        }
14491        sum
14492    }
14493}
14494
14495#[cfg(target_arch = "aarch64")]
14496#[target_feature(enable = "neon")]
14497unsafe fn dot_i8_f32_neon(w: &[u8], x: &[f32]) -> f32 {
14498    // SAFETY: callers uphold slice-length contracts (see call sites).
14499    unsafe {
14500        use core::arch::aarch64::*;
14501        let n = x.len();
14502        let wp = w.as_ptr() as *const i8;
14503        let xp = x.as_ptr();
14504        let (mut a0, mut a1, mut a2, mut a3) = (
14505            vdupq_n_f32(0.0),
14506            vdupq_n_f32(0.0),
14507            vdupq_n_f32(0.0),
14508            vdupq_n_f32(0.0),
14509        );
14510        let mut j = 0usize;
14511        while j + 16 <= n {
14512            let wb = vld1q_s8(wp.add(j));
14513            let lo = vmovl_s8(vget_low_s8(wb));
14514            let hi = vmovl_s8(vget_high_s8(wb));
14515            let w0 = vcvtq_f32_s32(vmovl_s16(vget_low_s16(lo)));
14516            let w1 = vcvtq_f32_s32(vmovl_s16(vget_high_s16(lo)));
14517            let w2 = vcvtq_f32_s32(vmovl_s16(vget_low_s16(hi)));
14518            let w3 = vcvtq_f32_s32(vmovl_s16(vget_high_s16(hi)));
14519            a0 = vfmaq_f32(a0, w0, vld1q_f32(xp.add(j)));
14520            a1 = vfmaq_f32(a1, w1, vld1q_f32(xp.add(j + 4)));
14521            a2 = vfmaq_f32(a2, w2, vld1q_f32(xp.add(j + 8)));
14522            a3 = vfmaq_f32(a3, w3, vld1q_f32(xp.add(j + 12)));
14523            j += 16;
14524        }
14525        let mut sum = vaddvq_f32(vaddq_f32(vaddq_f32(a0, a1), vaddq_f32(a2, a3)));
14526        while j < n {
14527            sum += (*wp.add(j)) as f32 * *xp.add(j);
14528            j += 1;
14529        }
14530        sum
14531    }
14532}
14533
14534#[allow(clippy::too_many_arguments)]
14535fn qmatvec(
14536    q: &[u8],
14537    rep: &[u8],
14538    row_scale: &[f32],
14539    x: &[f32],
14540    col_field: &[f32],
14541    dtype: TensorDtype,
14542    rows: usize,
14543    cols: usize,
14544    out: &mut [f32],
14545    pool: Option<&Pool>,
14546) {
14547    debug_assert_eq!(out.len(), rows);
14548    #[cfg(not(target_arch = "aarch64"))]
14549    let _ = rep;
14550
14551    #[cfg(target_arch = "aarch64")]
14552    if sdot_enabled() {
14553        let act = if dtype == TensorDtype::Q8_2f {
14554            split_act_q8_2f(x, col_field)
14555        } else {
14556            split_act(x)
14557        };
14558        let out_addr = SendMut(out.as_mut_ptr());
14559        let run_range = |start: usize, end: usize| {
14560            q8_range_sdot(q, rep, row_scale, &act, cols, out_addr, start, end)
14561        };
14562        match pool {
14563            Some(pool) if rows >= 256 => pool.run_rows(rows, &run_range),
14564            _ => run_range(0, rows),
14565        }
14566        return;
14567    }
14568    // x86 A8W8 via AVX2 maddubs — same quantized-activation contract as
14569    // the SDOT path (CMF_AVX2=0 keeps the exact i8×f32 loop).
14570    #[cfg(target_arch = "x86_64")]
14571    if avx2_a8w8_enabled() {
14572        let act = if dtype == TensorDtype::Q8_2f {
14573            split_act_q8_2f(x, col_field)
14574        } else {
14575            split_act(x)
14576        };
14577        let out_addr = SendMut(out.as_mut_ptr());
14578        let run_range = |start: usize, end: usize| {
14579            q8_range_avx2(q, row_scale, &act, cols, out_addr, start, end)
14580        };
14581        match pool {
14582            Some(pool) if rows >= 256 => pool.run_rows(rows, &run_range),
14583            _ => run_range(0, rows),
14584        }
14585        return;
14586    }
14587
14588    prescale_with(x, col_field, dtype, 1, |xs| {
14589        let out_addr = SendMut(out.as_mut_ptr());
14590        let run_range = move |start: usize, end: usize| {
14591            for o in start..end {
14592                let v = dot_i8_f32(&q[o * cols..(o + 1) * cols], xs) * row_scale[o];
14593                // SAFETY: disjoint row ranges per worker.
14594                unsafe { *out_addr.at(o) = v };
14595            }
14596        };
14597        match pool {
14598            Some(pool) if rows >= 256 => pool.run_rows(rows, &run_range),
14599            _ => run_range(0, rows),
14600        }
14601    });
14602}
14603
14604#[allow(clippy::too_many_arguments)]
14605fn qmatvec2(
14606    q: &[u8],
14607    row_scale: &[f32],
14608    x1: &[f32],
14609    x2: &[f32],
14610    col_field: &[f32],
14611    dtype: TensorDtype,
14612    rows: usize,
14613    cols: usize,
14614    o1: &mut [f32],
14615    o2: &mut [f32],
14616    pool: Option<&Pool>,
14617) {
14618    #[cfg(target_arch = "aarch64")]
14619    if sdot_enabled() {
14620        let a1s = if dtype == TensorDtype::Q8_2f {
14621            split_act_q8_2f(x1, col_field)
14622        } else {
14623            split_act(x1)
14624        };
14625        let a2s = if dtype == TensorDtype::Q8_2f {
14626            split_act_q8_2f(x2, col_field)
14627        } else {
14628            split_act(x2)
14629        };
14630        let p1 = SendMut(o1.as_mut_ptr());
14631        let p2 = SendMut(o2.as_mut_ptr());
14632        let run_range = |start: usize, end: usize| {
14633            q8_range2_sdot(q, row_scale, &a1s, &a2s, cols, p1, p2, start, end)
14634        };
14635        match pool {
14636            Some(pool) if rows >= 256 => pool.run_rows(rows, &run_range),
14637            _ => run_range(0, rows),
14638        }
14639        return;
14640    }
14641    #[cfg(target_arch = "x86_64")]
14642    if avx2_a8w8_enabled() {
14643        let a1s = if dtype == TensorDtype::Q8_2f {
14644            split_act_q8_2f(x1, col_field)
14645        } else {
14646            split_act(x1)
14647        };
14648        let a2s = if dtype == TensorDtype::Q8_2f {
14649            split_act_q8_2f(x2, col_field)
14650        } else {
14651            split_act(x2)
14652        };
14653        let p1 = SendMut(o1.as_mut_ptr());
14654        let p2 = SendMut(o2.as_mut_ptr());
14655        let run_range = |start: usize, end: usize| {
14656            q8_range2_avx2(q, row_scale, &a1s, &a2s, cols, p1, p2, start, end)
14657        };
14658        match pool {
14659            Some(pool) if rows >= 256 => pool.run_rows(rows, &run_range),
14660            _ => run_range(0, rows),
14661        }
14662        return;
14663    }
14664
14665    prescale_with(x1, col_field, dtype, 1, |x1s| {
14666        prescale_with(x2, col_field, dtype, 2, |x2s| {
14667            let p1 = SendMut(o1.as_mut_ptr());
14668            let p2 = SendMut(o2.as_mut_ptr());
14669            let run_range = move |start: usize, end: usize| {
14670                for o in start..end {
14671                    let row = &q[o * cols..(o + 1) * cols];
14672                    let s1 = dot_i8_f32(row, x1s) * row_scale[o];
14673                    let s2 = dot_i8_f32(row, x2s) * row_scale[o];
14674                    // SAFETY: disjoint row ranges per worker.
14675                    unsafe {
14676                        *p1.at(o) = s1;
14677                        *p2.at(o) = s2;
14678                    }
14679                }
14680            };
14681            match pool {
14682                Some(pool) if rows >= 256 => pool.run_rows(rows, &run_range),
14683                _ => run_range(0, rows),
14684            }
14685        });
14686    });
14687}
14688
14689#[derive(Clone, Copy)]
14690struct SendMut(*mut f32);
14691unsafe impl Send for SendMut {}
14692unsafe impl Sync for SendMut {}
14693
14694impl SendMut {
14695    #[inline]
14696    fn at(self, i: usize) -> *mut f32 {
14697        unsafe { self.0.add(i) }
14698    }
14699}
14700
14701#[cfg(test)]
14702mod tests {
14703
14704    /// `q8_round` must be `round().clamp(±127) as i8` bit for bit: every
14705    /// half-integer, their neighbours one ulp either side, the clamp
14706    /// boundary, huge values, infinities and NaN, plus a dense sweep.
14707    #[test]
14708    fn q8_round_is_round_clamp() {
14709        let reference = |t: f32| t.round().clamp(-127.0, 127.0) as i8;
14710        let mut probe = vec![
14711            0.0f32,
14712            -0.0,
14713            f32::NAN,
14714            f32::INFINITY,
14715            f32::NEG_INFINITY,
14716            f32::MAX,
14717            f32::MIN,
14718            1e30,
14719            -1e30,
14720            f32::MIN_POSITIVE,
14721            -f32::MIN_POSITIVE,
14722        ];
14723        for k in -300i32..=300 {
14724            let h = k as f32 * 0.5;
14725            let up = f32::from_bits(h.to_bits() + 1);
14726            let down = f32::from_bits(h.to_bits().wrapping_sub(1));
14727            for t in [h, up, down] {
14728                probe.push(t);
14729                probe.push(-t);
14730            }
14731        }
14732        let mut t = -140.0f32;
14733        while t < 140.0 {
14734            probe.push(t);
14735            t += 0.000_731;
14736        }
14737        for t in probe {
14738            assert_eq!(q8_round(t), reference(t), "t = {t:e} ({:#x})", t.to_bits());
14739        }
14740    }
14741
14742    use super::*;
14743
14744    /// The f32 `matmat` walks the batch four positions a row at a time; every
14745    /// output must still be the scalar-order sum `matvec` gives, bit for bit
14746    /// (a 7-row batch covers the four-wide block and the remainder).
14747    #[test]
14748    fn f32_matmat_equals_matvec_bitwise() {
14749        let (rows, cols, b) = (5usize, 37usize, 7usize);
14750        let w: Vec<f32> = (0..rows * cols).map(|i| ((i * 7919 % 113) as f32 - 56.0) / 37.0).collect();
14751        let xs: Vec<f32> = (0..b * cols).map(|i| ((i * 104_729 % 97) as f32 - 48.0) / 29.0).collect();
14752        let t = QTensor::from_f32(w, rows, cols);
14753        let mut out = vec![0f32; b * rows];
14754        t.matmat(&xs, b, &mut out, None);
14755        for bi in 0..b {
14756            let mut one = vec![0f32; rows];
14757            t.matvec(&xs[bi * cols..(bi + 1) * cols], &mut one, None);
14758            for o in 0..rows {
14759                assert_eq!(out[bi * rows + o].to_bits(), one[o].to_bits(), "bi {bi} row {o}");
14760            }
14761        }
14762    }
14763
14764    /// A short batch on a pool splits the f32 GEMM over its output rows
14765    /// (it used to run on one core); the sums must not change by a bit.
14766    #[test]
14767    fn f32_matmat_row_split_on_pool_is_bitwise() {
14768        let (rows, cols, b) = (300usize, 37usize, 7usize);
14769        let w: Vec<f32> = (0..rows * cols).map(|i| ((i * 7919 % 113) as f32 - 56.0) / 37.0).collect();
14770        let xs: Vec<f32> = (0..b * cols).map(|i| ((i * 104_729 % 97) as f32 - 48.0) / 29.0).collect();
14771        let t = QTensor::from_f32(w, rows, cols);
14772        let mut alone = vec![0f32; b * rows];
14773        t.matmat(&xs, b, &mut alone, None);
14774        let pool = Pool::new(3);
14775        let mut split = vec![0f32; b * rows];
14776        t.matmat(&xs, b, &mut split, Some(&pool));
14777        let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
14778        assert_eq!(bits(&alone), bits(&split));
14779    }
14780
14781    #[test]
14782    fn q2tp_i8_dot_matches_exact_on_grid() {
14783        // On-grid activations (±1 → sx=1/127, xq=±127 dequantizes
14784        // exactly, no outliers) must make the integer path agree with
14785        // the exact scalar walk to f32 rounding.
14786        let (rows, cols) = (5, 64);
14787        let gpr = cols / GROUP_SIZE;
14788        // Synthetic codes plane + a flat ladder: scales_into is not under
14789        // test here, so drive dot_q2tp_row_i8 / q2tp_row_exact directly
14790        // with hand-made scales.
14791        let chunks: Vec<u8> = (0..rows * gpr * Q2TP_CHUNK)
14792            .map(|i| (i as u32).wrapping_mul(2654435761) as u8)
14793            .collect();
14794        let scales: Vec<f32> = (0..gpr).map(|g| 0.5 + g as f32 * 0.25).collect();
14795        let x: Vec<f32> = (0..cols)
14796            .map(|i| if i % 3 == 0 { -1.0 } else { 1.0 })
14797            .collect();
14798        let act = split_act(&x);
14799        assert!(
14800            act.outliers.is_empty(),
14801            "on-grid input must have no outliers"
14802        );
14803        let gsum = q1_group_sums(&act.xq, gpr);
14804        for r in 0..rows {
14805            let exact = q2tp_row_exact(&chunks, r, gpr, &x, &scales);
14806            let fast = dot_q2tp_row_i8(&chunks, r, gpr, &act.xq, &gsum, &scales) * act.sx;
14807            assert!(
14808                (exact - fast).abs() <= exact.abs() * 1e-5 + 1e-5,
14809                "row {r}: exact {exact} vs i8 {fast}"
14810            );
14811        }
14812    }
14813
14814    #[cfg(target_arch = "x86_64")]
14815    #[test]
14816    fn q2tp_avx2_dot_matches_scalar_for_random_patterns() {
14817        // Compare the release AVX2 integer dot against the scalar oracle over
14818        // arbitrary packed bytes/activation signs.  This guards the exact
14819        // table-load path used after rejecting a faster-looking decoder whose
14820        // full-checkpoint greedy output drifted.
14821        if !std::arch::is_x86_feature_detected!("avx2") {
14822            return;
14823        }
14824        let mut seed = 0x9e3779b9u32;
14825        let mut next = || {
14826            seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
14827            seed
14828        };
14829        for _ in 0..20_000 {
14830            let mut ch = [0u8; Q2TP_CHUNK];
14831            let mut x = [0i8; GROUP_SIZE];
14832            for b in &mut ch {
14833                *b = next() as u8;
14834            }
14835            for v in &mut x {
14836                *v = (next() >> 24) as i8;
14837            }
14838            let mut reference = 0i32;
14839            for (k, &b) in ch.iter().enumerate() {
14840                reference += (b & 3) as i32 * x[k * 4] as i32;
14841                reference += ((b >> 2) & 3) as i32 * x[k * 4 + 1] as i32;
14842                reference += ((b >> 4) & 3) as i32 * x[k * 4 + 2] as i32;
14843                reference += ((b >> 6) & 3) as i32 * x[k * 4 + 3] as i32;
14844            }
14845            // SAFETY: guarded by the runtime AVX2 feature check and fixed
14846            // 8-byte/32-byte slice lengths above.
14847            let got = unsafe { q2tp_code_dot_avx2(&ch, &x) };
14848            assert_eq!(got, reference, "packed q2 lane mismatch");
14849        }
14850    }
14851
14852    #[test]
14853    fn q2tp_affine_fuses_half_scale_correction_without_changing_raw_decode() {
14854        let (rows, cols) = (1usize, GROUP_SIZE);
14855        let mut bytes = vec![0u8; Q2TP_CHUNK + 4 + 1];
14856        // Repeating symbols 0,1,2,0 at unit scale.  q2tp's raw B is
14857        // (c-1.5), while the affine Prism operator is (c-1.0).
14858        bytes[..Q2TP_CHUNK].fill(0x24); // codes 0,1,2,0 in LSB-first order
14859        bytes[Q2TP_CHUNK..Q2TP_CHUNK + 2].copy_from_slice(&0u16.to_le_bytes());
14860        bytes[Q2TP_CHUNK + 2..Q2TP_CHUNK + 4].copy_from_slice(&0u16.to_le_bytes());
14861        bytes[Q2TP_CHUNK + 4] = 1; // dtype16 rung 1 = 1.0
14862        let x = vec![1.0f32; cols];
14863        let mut raw = vec![0.0f32; rows];
14864        let mut affine = vec![0.0f32; rows];
14865        q2tp_matvec_for_test(&bytes, &x, rows, cols, &mut raw);
14866        q2tp_affine_matvec_for_test(&bytes, &x, rows, cols, &mut affine);
14867        assert_eq!(raw, vec![-24.0]);
14868        assert_eq!(affine, vec![-8.0]);
14869        assert!((affine[0] - (raw[0] + 0.5 * cols as f32)).abs() < 1e-6);
14870    }
14871
14872    #[test]
14873    fn q8_row_dot_fast_matches_scalar() {
14874        // The per-arch fast dot must agree with the exact scalar oracle
14875        // (same contract the fused q8 FFN arm rides on).
14876        let cols = 96;
14877        let row: Vec<u8> = (0..cols)
14878            .map(|i| ((i * 37 % 251) - 125) as i8 as u8)
14879            .collect();
14880        let x: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.13).sin()).collect();
14881        let act = split_act(&x);
14882        let fast = q8_row_dot(&row, &act);
14883        let scalar = q8_row_dot_scalar(&row, &act);
14884        assert!(
14885            (fast - scalar).abs() <= scalar.abs() * 1e-5 + 1e-5,
14886            "fast {fast} vs scalar {scalar}"
14887        );
14888    }
14889
14890    #[test]
14891    fn f32_matvec_matches_matvec_rows_bitexact() {
14892        let (rows, cols) = (300, 40);
14893        let w: Vec<f32> = (0..rows * cols).map(|i| (i as f32 * 0.017).sin()).collect();
14894        let x: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.05).cos()).collect();
14895        let qt = QTensor::from_f32(w.clone(), rows, cols);
14896
14897        let mut a = vec![0.0f32; rows];
14898        matvec_rows(None, &w, &x, &mut a);
14899        let mut b = vec![0.0f32; rows];
14900        qt.matvec(&x, &mut b, None);
14901        assert_eq!(a, b);
14902    }
14903
14904    #[test]
14905    fn sdot_kernel_exact_on_grid() {
14906        // Activations already on the i8 grid (±1 with amax=1 → sx=1/127,
14907        // xq=±127 dequantizes EXACTLY) → the SDOT path must match the
14908        // exact f32 dot to float rounding. This isolates kernel
14909        // correctness from quantization noise.
14910        eprintln!("sdot_enabled = {}", sdot_enabled());
14911        let (rows, cols) = (9, 80); // odd rows → exercises 4-row + tail
14912        let w: Vec<u8> = (0..rows * cols)
14913            .map(|i| (((i * 37) % 251) as i32 - 125) as i8 as u8)
14914            .collect();
14915        let scales: Vec<f32> = (0..rows).map(|o| 0.005 + o as f32 * 0.001).collect();
14916        let x: Vec<f32> = (0..cols)
14917            .map(|i| match i % 3 {
14918                0 => 1.0,
14919                1 => -1.0,
14920                _ => 0.0,
14921            })
14922            .collect();
14923        let mut a = vec![0.0f32; rows];
14924        qmatvec(
14925            &w,
14926            &[],
14927            &scales,
14928            &x,
14929            &[],
14930            TensorDtype::Q8Row,
14931            rows,
14932            cols,
14933            &mut a,
14934            None,
14935        );
14936        for o in 0..rows {
14937            let mut acc = 0.0f32;
14938            for j in 0..cols {
14939                acc += (w[o * cols + j] as i8) as f32 * x[j];
14940            }
14941            let expect = acc * scales[o];
14942            assert!(
14943                (a[o] - expect).abs() < 1e-3 * expect.abs().max(1e-3),
14944                "row {o}: {} vs {expect}",
14945                a[o]
14946            );
14947        }
14948    }
14949
14950    #[test]
14951    fn q1_tbl_fast_path_matches_reference() {
14952        // gpr = 8 exercises the TBL pair-load fast loop, and the LAST
14953        // row's final 4-tile window trips the 4B-overread guard (the
14954        // payload ends exactly at the last tile) — both paths must
14955        // agree with the dequant reference.
14956        let (rows, cols) = (5, 256);
14957        let gpr = cols / GROUP_SIZE;
14958        let mut bytes = Vec::new();
14959        for t in 0..rows * gpr {
14960            let s = 0.007 + (t % 11) as f32 * 0.004;
14961            bytes.extend_from_slice(&cortiq_core::quant::f32_to_f16(s).to_le_bytes());
14962            for j in 0..4 {
14963                bytes.push(((t * 53 + j * 89 + 7) % 249) as u8);
14964            }
14965        }
14966        let x: Vec<f32> = (0..cols)
14967            .map(|i| if (i * 5) % 7 < 3 { 1.0 } else { -1.0 })
14968            .collect();
14969        let mut w = vec![0.0f32; rows * cols];
14970        cortiq_core::quant::dequant_q1(&bytes, &mut w);
14971        let mut got = vec![0.0f32; rows];
14972        q1_matvec(&bytes, &x, rows, cols, &mut got, None);
14973        for o in 0..rows {
14974            let expect: f32 = (0..cols).map(|j| w[o * cols + j] * x[j]).sum();
14975            assert!(
14976                (got[o] - expect).abs() < 1e-3 * expect.abs().max(1e-3),
14977                "row {o}: {} vs {expect}",
14978                got[o]
14979            );
14980        }
14981        // Blocked 1×4 batch (b=5: one quad + remainder) must equal the
14982        // single-matvec path bit-for-bit.
14983        let b = 5usize;
14984        let mut xs_all = Vec::new();
14985        for bi in 0..b {
14986            xs_all.extend(x.iter().map(|v| if bi % 2 == 0 { *v } else { -*v }));
14987        }
14988        let mut mm = vec![0.0f32; b * rows];
14989        q1_matmat(&bytes, &xs_all, b, rows, cols, &mut mm, None);
14990        for bi in 0..b {
14991            let mut single = vec![0.0f32; rows];
14992            q1_matvec(
14993                &bytes,
14994                &xs_all[bi * cols..(bi + 1) * cols],
14995                rows,
14996                cols,
14997                &mut single,
14998                None,
14999            );
15000            assert_eq!(&mm[bi * rows..(bi + 1) * rows], &single[..], "stream {bi}");
15001        }
15002    }
15003
15004    #[test]
15005    fn q1_kernels_match_exact_reference() {
15006        // Synthetic q1 payload: 6-byte tiles [f16 scale][4B bits].
15007        let (rows, cols) = (7, 96);
15008        let gpr = cols / GROUP_SIZE;
15009        let mut bytes = Vec::new();
15010        for t in 0..rows * gpr {
15011            let s = 0.01 + (t % 13) as f32 * 0.003;
15012            bytes.extend_from_slice(&cortiq_core::quant::f32_to_f16(s).to_le_bytes());
15013            for j in 0..4 {
15014                bytes.push(((t * 31 + j * 97) % 251) as u8);
15015            }
15016        }
15017        // On-grid activations (±1, amax 1) → the SDOT path is exact.
15018        let x: Vec<f32> = (0..cols)
15019            .map(|i| if i % 3 == 0 { 1.0 } else { -1.0 })
15020            .collect();
15021        // Reference through the core dequant.
15022        let mut w = vec![0.0f32; rows * cols];
15023        cortiq_core::quant::dequant_q1(&bytes, &mut w);
15024        let mut expect = vec![0.0f32; rows];
15025        for o in 0..rows {
15026            expect[o] = (0..cols).map(|j| w[o * cols + j] * x[j]).sum();
15027        }
15028        let mut got = vec![0.0f32; rows];
15029        q1_matvec(&bytes, &x, rows, cols, &mut got, None);
15030        for o in 0..rows {
15031            assert!(
15032                (got[o] - expect[o]).abs() < 1e-3 * expect[o].abs().max(1e-3),
15033                "row {o}: {} vs {}",
15034                got[o],
15035                expect[o]
15036            );
15037        }
15038        // Pair and batch paths agree with the single path.
15039        let x2: Vec<f32> = x.iter().map(|v| -v).collect();
15040        let (mut a1, mut a2) = (vec![0.0f32; rows], vec![0.0f32; rows]);
15041        q1_matvec2(&bytes, &x, &x2, rows, cols, &mut a1, &mut a2, None);
15042        assert_eq!(a1, got);
15043        let mut xs = x.clone();
15044        xs.extend_from_slice(&x2);
15045        let mut mm = vec![0.0f32; 2 * rows];
15046        q1_matmat(&bytes, &xs, 2, rows, cols, &mut mm, None);
15047        assert_eq!(&mm[..rows], got.as_slice());
15048        assert_eq!(&mm[rows..], a2.as_slice());
15049    }
15050
15051    /// A Bonsai-shaped q1 payload (one f16 scale per 128-group, stored in
15052    /// all four tiles; pseudo-random signs) and its q1g repack.
15053    fn q1_q1g_pair(rows: usize, cols: usize, salt: usize) -> (Vec<u8>, Vec<u8>) {
15054        let tiles = rows * cols / GROUP_SIZE;
15055        let mut q1 = Vec::with_capacity(tiles * Q1_TILE);
15056        for t in 0..tiles {
15057            let s = 0.004 + ((t / 4 * 37 + salt) % 29) as f32 * 0.0011;
15058            q1.extend_from_slice(&cortiq_core::quant::f32_to_f16(s).to_le_bytes());
15059            let bits = ((t * 2_654_435_761 + salt * 40_503) as u32).rotate_left((t % 31) as u32);
15060            q1.extend_from_slice(&bits.to_le_bytes());
15061        }
15062        let rp = cortiq_core::quant::repack_q1_to_q1g(&q1, rows, cols, 0.0);
15063        assert_eq!(rp.differing, 0, "uniform scales repack exactly");
15064        (q1, rp.data)
15065    }
15066
15067    /// Activations off the int8 grid with two outlier channels, so the
15068    /// A8W8 path quantizes AND takes the exact outlier correction.
15069    fn q1g_test_x(cols: usize, salt: usize) -> Vec<f32> {
15070        let mut x: Vec<f32> = (0..cols)
15071            .map(|i| ((i * 13 + salt * 7) as f32 * 0.071).sin() * 0.9)
15072            .collect();
15073        x[3 % cols] = 41.0;
15074        x[(cols / 2 + 5) % cols] = -37.5;
15075        x
15076    }
15077
15078    /// Every CPU row kernel of q1g returns the q1 kernel's f32 BIT FOR BIT
15079    /// on a uniform-scale repack: A8W8 rows (SIMD of this machine, and the
15080    /// x86 AVX2/VNNI twins directly), the exact scalar rows (CMF_SDOT=0
15081    /// contract), the outlier term, the drivers (matvec, matvec2, matmat
15082    /// with the blocked 1×4 quad + remainder) — including gpr = 4 and the
15083    /// last row, where q1's pair load falls back to its scalar tail.
15084    #[test]
15085    fn q1g_cpu_kernels_equal_q1_bit_for_bit() {
15086        for &(rows, cols) in &[(3usize, 128usize), (5, 256), (9, 2048), (2, 6144)] {
15087            let gpr = cols / GROUP_SIZE;
15088            let (q1, q1g) = q1_q1g_pair(rows, cols, rows + cols);
15089            let (wa, wb) = (BinW::Q1(&q1), BinW::q1g(&q1g, rows, cols));
15090            let x = q1g_test_x(cols, rows);
15091            let act = split_act(&x);
15092            assert!(!act.outliers.is_empty(), "test wants the outlier path");
15093            let gsum = q1_group_sums(&act.xq, gpr);
15094            for r in 0..rows {
15095                let (a, b) = (wa.row_exact(r, gpr, &x), wb.row_exact(r, gpr, &x));
15096                assert_eq!(a.to_bits(), b.to_bits(), "{rows}x{cols} exact row {r}");
15097                let (a, b) = (
15098                    wa.dot_i8(r, gpr, &act.xq, &gsum),
15099                    wb.dot_i8(r, gpr, &act.xq, &gsum),
15100                );
15101                assert_eq!(a.to_bits(), b.to_bits(), "{rows}x{cols} i8 row {r}");
15102                for j in [0, 31, 32, 127, cols - 1] {
15103                    let (a, b) = (wa.outlier(r, gpr, j), wb.outlier(r, gpr, j));
15104                    assert_eq!(
15105                        (a.0.to_bits(), a.1.to_bits()),
15106                        (b.0.to_bits(), b.1.to_bits())
15107                    );
15108                }
15109                #[cfg(target_arch = "x86_64")]
15110                if avx2_enabled() {
15111                    let sc = cortiq_core::quant::q1g_scale_offset(rows, cols);
15112                    // SAFETY: AVX2 checked; payloads sized for (rows, cols).
15113                    unsafe {
15114                        let a = dot_q1_row_avx2(&q1, r, gpr, &act.xq, &gsum);
15115                        let b = dot_q1g_row_avx2(&q1g, sc, r, gpr, &act.xq, &gsum);
15116                        assert_eq!(a.to_bits(), b.to_bits(), "avx2 row {r}");
15117                    }
15118                    if std::is_x86_feature_detected!("avx512vnni")
15119                        && std::is_x86_feature_detected!("avx512bw")
15120                        && std::is_x86_feature_detected!("avx512vl")
15121                    {
15122                        // SAFETY: VNNI family detected just above.
15123                        unsafe {
15124                            let a = dot_q1_row_vnni(&q1, r, gpr, &act.xq, &gsum);
15125                            let b = dot_q1g_row_vnni(&q1g, sc, r, gpr, &act.xq, &gsum);
15126                            assert_eq!(a.to_bits(), b.to_bits(), "vnni row {r}");
15127                        }
15128                    }
15129                }
15130            }
15131            // Drivers: single, pair, batch (b = 5: one blocked quad + one).
15132            let (mut ga, mut gb) = (vec![0f32; rows], vec![0f32; rows]);
15133            bin_matvec(wa, &x, rows, cols, &mut ga, None);
15134            bin_matvec(wb, &x, rows, cols, &mut gb, None);
15135            assert_eq!(ga, gb, "{rows}x{cols} matvec");
15136            let x2 = q1g_test_x(cols, rows + 1);
15137            let (mut a1, mut a2, mut b1, mut b2) = (
15138                vec![0f32; rows],
15139                vec![0f32; rows],
15140                vec![0f32; rows],
15141                vec![0f32; rows],
15142            );
15143            bin_matvec2(wa, &x, &x2, rows, cols, &mut a1, &mut a2, None);
15144            bin_matvec2(wb, &x, &x2, rows, cols, &mut b1, &mut b2, None);
15145            assert_eq!((&a1, &a2), (&b1, &b2), "{rows}x{cols} matvec2");
15146            let b = 5usize;
15147            let xs: Vec<f32> = (0..b).flat_map(|k| q1g_test_x(cols, k * 3 + 2)).collect();
15148            let (mut ma, mut mb) = (vec![0f32; b * rows], vec![0f32; b * rows]);
15149            bin_matmat(wa, &xs, b, rows, cols, &mut ma, None);
15150            bin_matmat(wb, &xs, b, rows, cols, &mut mb, None);
15151            assert_eq!(ma, mb, "{rows}x{cols} matmat");
15152            // The blocked 1×4 kernels directly (the driver only takes them
15153            // under CMF_X86_BLOCKED / SDOT, a process-wide switch).
15154            let acts: Vec<(SplitAct, Vec<i32>)> = (0..4)
15155                .map(|k| {
15156                    let a = split_act(&xs[k * cols..(k + 1) * cols]);
15157                    let g = q1_group_sums(&a.xq, gpr);
15158                    (a, g)
15159                })
15160                .collect();
15161            let xq4: [&[i8]; 4] = std::array::from_fn(|k| acts[k].0.xq.as_slice());
15162            let gs4: [&[i32]; 4] = std::array::from_fn(|k| acts[k].1.as_slice());
15163            for r in 0..rows {
15164                #[cfg(target_arch = "x86_64")]
15165                if avx2_enabled() {
15166                    // SAFETY: AVX2 checked; payloads sized for (rows, cols).
15167                    let (a, b) = unsafe {
15168                        (
15169                            wa.dot_1x4_x86(r, gpr, xq4, gs4),
15170                            wb.dot_1x4_x86(r, gpr, xq4, gs4),
15171                        )
15172                    };
15173                    assert_eq!(a.map(f32::to_bits), b.map(f32::to_bits), "1x4 row {r}");
15174                }
15175                #[cfg(target_arch = "aarch64")]
15176                if sdot_enabled() {
15177                    // SAFETY: SDOT checked; payloads sized for (rows, cols).
15178                    let (a, b) = unsafe {
15179                        (
15180                            wa.dot_1x4_sdot(r, gpr, xq4, gs4),
15181                            wb.dot_1x4_sdot(r, gpr, xq4, gs4),
15182                        )
15183                    };
15184                    assert_eq!(a.map(f32::to_bits), b.map(f32::to_bits), "1x4 row {r}");
15185                }
15186                let _ = (r, &xq4, &gs4);
15187            }
15188        }
15189    }
15190
15191    /// CPU kernel A/B, q1 vs q1g matvec (A8W8 path of this machine, the
15192    /// exact path too), Bonsai-1.7B decode shapes, arms alternated every
15193    /// round, medians printed. `CMF_THREADS` sets the pool (default 8).
15194    /// `cargo test -p cortiq-engine --release --lib q1g_cpu_matvec_speed --
15195    /// --ignored --nocapture`
15196    #[test]
15197    #[ignore]
15198    fn q1g_cpu_matvec_speed() {
15199        use crate::pool::Pool;
15200        let threads = std::env::var("CMF_THREADS")
15201            .ok()
15202            .and_then(|v| v.parse().ok())
15203            .unwrap_or(8usize);
15204        let pool = Pool::new(threads);
15205        for &(name, rows, cols, reps) in &[
15206            ("gate/up_proj", 6144usize, 2048usize, 41usize),
15207            ("down_proj", 2048, 6144, 41),
15208            ("lm_head", 151_669, 2048, 9),
15209        ] {
15210            let (q1, q1g) = q1_q1g_pair(rows, cols, 3);
15211            let (wa, wb) = (BinW::Q1(&q1), BinW::q1g(&q1g, rows, cols));
15212            let x = q1g_test_x(cols, 1);
15213            let mut out = vec![0f32; rows];
15214            let mut time = |w: BinW| {
15215                let t0 = std::time::Instant::now();
15216                bin_matvec(w, &x, rows, cols, &mut out, Some(&pool));
15217                t0.elapsed().as_secs_f64()
15218            };
15219            let _ = (time(wa), time(wb));
15220            let (mut ta, mut tb) = (Vec::new(), Vec::new());
15221            for r in 0..reps {
15222                if r % 2 == 0 {
15223                    ta.push(time(wa));
15224                    tb.push(time(wb));
15225                } else {
15226                    tb.push(time(wb));
15227                    ta.push(time(wa));
15228                }
15229            }
15230            ta.sort_by(|a, b| a.partial_cmp(b).unwrap());
15231            tb.sort_by(|a, b| a.partial_cmp(b).unwrap());
15232            let (ma, mb) = (ta[reps / 2], tb[reps / 2]);
15233            eprintln!(
15234                "cpu x{threads} a8w8={} {name:>12} {rows}x{cols}: q1 {:8.1} us | q1g {:8.1} us | q1g/q1 time {:.3}",
15235                a8w8_enabled(),
15236                ma * 1e6,
15237                mb * 1e6,
15238                mb / ma
15239            );
15240        }
15241    }
15242
15243    /// The mapped QTensor paths a real Bonsai q1g file takes — matvec, the
15244    /// multi-projection job (all-q1g and q1/q1g mixed), the fused gate/up
15245    /// with SiLU, matmat, matvec2 and the embedding row — equal the q1
15246    /// tensor they were repacked from, bit for bit.
15247    #[test]
15248    fn q1g_mapped_tensor_paths_equal_q1() {
15249        use crate::pool::Pool;
15250        use cortiq_core::{CmfHeader, CmfModel, TensorSpec};
15251        let (rows, cols) = (300usize, 256usize);
15252        let (gq1, gq1g) = q1_q1g_pair(rows, cols, 1);
15253        let (uq1, uq1g) = q1_q1g_pair(rows, cols, 2);
15254        let header: CmfHeader = serde_json::from_value(serde_json::json!({
15255            "format": "cmf", "version": cortiq_core::CMF_VERSION,
15256            "arch": {"arch_name": "tiny-q1g", "hidden_size": cols,
15257                "intermediate_size": rows, "num_layers": 1, "num_attention_heads": 2,
15258                "num_kv_heads": 1, "head_dim": 128, "vocab_size": rows,
15259                "layer_types": ["FullAttention"], "rms_norm_eps": 1e-6,
15260                "max_position_embeddings": 8},
15261            "quant_type": "VBIT"
15262        }))
15263        .unwrap();
15264        let spec = |name: &str, dtype, data: &Vec<u8>| TensorSpec {
15265            name: name.into(),
15266            dtype,
15267            shape: vec![rows, cols],
15268            data: data.clone(),
15269        };
15270        let specs = [
15271            spec("g1", TensorDtype::Q1, &gq1),
15272            spec("u1", TensorDtype::Q1, &uq1),
15273            spec("gg", TensorDtype::Q1G, &gq1g),
15274            spec("ug", TensorDtype::Q1G, &uq1g),
15275        ];
15276        let dir = std::env::temp_dir().join(format!("cmf-q1g-mapped-{}", std::process::id()));
15277        std::fs::create_dir_all(&dir).unwrap();
15278        let path = dir.join("m.cmf");
15279        CmfModel::write(&path, &header, &specs, None, None).unwrap();
15280        let model = Arc::new(CmfModel::open(&path).unwrap());
15281        assert!(model.verify().is_empty(), "{:?}", model.verify());
15282        let t = |n: &str| QTensor::from_model(&model, n).unwrap();
15283        let (g1, u1, gg, ug) = (t("g1"), t("u1"), t("gg"), t("ug"));
15284        assert_eq!(gg.model_dtype(), Some(TensorDtype::Q1G));
15285        assert!(gg.is_q1() && gg.graph_weight().map(|w| w.2) == Some(10));
15286        let pool = Pool::new(3);
15287        let x = q1g_test_x(cols, 4);
15288        let run = |a: &QTensor| {
15289            let mut o = vec![0f32; rows];
15290            a.matvec(&x, &mut o, Some(&pool));
15291            o
15292        };
15293        assert_eq!(run(&g1), run(&gg), "matvec");
15294        let many = |a: &QTensor, b: &QTensor| {
15295            let (mut oa, mut ob) = (vec![0f32; rows], vec![0f32; rows]);
15296            QTensor::matvec_many([a, b], &x, [&mut oa, &mut ob], Some(&pool));
15297            (oa, ob)
15298        };
15299        let want = many(&g1, &u1);
15300        assert_eq!(want, many(&gg, &ug), "matvec_many q1g");
15301        assert_eq!(want, many(&g1, &ug), "matvec_many mixed");
15302        assert_eq!(want, (run(&g1), run(&u1)), "matvec_many == singles");
15303        let fused = |g: &QTensor, u: &QTensor| {
15304            let mut o = vec![0f32; rows];
15305            let ok = QTensor::matvec_silu_mul(g, u, &x, &mut o, Some(&pool));
15306            (ok, o)
15307        };
15308        let (ok_a, fa) = fused(&g1, &u1);
15309        let (ok_b, fb) = fused(&gg, &ug);
15310        assert_eq!(ok_a, ok_b, "q1g takes the fused arm whenever q1 does");
15311        assert_eq!(fa, fb, "fused gate/up");
15312        let b = 6usize;
15313        let xs: Vec<f32> = (0..b).flat_map(|k| q1g_test_x(cols, k + 9)).collect();
15314        let mm = |a: &QTensor| {
15315            let mut o = vec![0f32; b * rows];
15316            a.matmat(&xs, b, &mut o, Some(&pool));
15317            o
15318        };
15319        assert_eq!(mm(&g1), mm(&gg), "matmat");
15320        let x2 = q1g_test_x(cols, 77);
15321        let pair = |a: &QTensor| {
15322            let (mut o1, mut o2) = (vec![0f32; rows], vec![0f32; rows]);
15323            a.matvec2(&x, &x2, &mut o1, &mut o2, Some(&pool));
15324            (o1, o2)
15325        };
15326        assert_eq!(pair(&g1), pair(&gg), "matvec2");
15327        for r in [0, 1, rows / 2, rows - 1] {
15328            let (mut ra, mut rb) = (vec![0f32; cols], vec![0f32; cols]);
15329            g1.row_f32(r, &mut ra);
15330            gg.row_f32(r, &mut rb);
15331            assert_eq!(ra, rb, "embedding row {r}");
15332        }
15333        drop((g1, u1, gg, ug, model));
15334        let _ = std::fs::remove_dir_all(&dir);
15335    }
15336
15337    /// A `blr` tensor read from a real CMF file: it maps to the factored
15338    /// arm (not a dense copy), declines every device-graph accessor, and
15339    /// every QTensor entry point a layer may take — matvec, matvec2,
15340    /// matmat (table loop and GEMM sizes), the multi-tensor job mixed with
15341    /// a q8_row sibling, the fused gate/up refusal, rows and columns — equals
15342    /// the dense reference built by the core dequant.
15343    #[test]
15344    fn blr_mapped_tensor_paths_equal_dense() {
15345        use crate::pool::Pool;
15346        use cortiq_core::{CmfHeader, CmfModel, TensorSpec};
15347        let (rows, cols, r) = (96usize, 128usize, 16usize);
15348        let mut rng = crate::blr::tests::Rng(41);
15349        let gate = crate::blr::tests::make(&mut rng, rows, cols, r, 2);
15350        let up = crate::blr::tests::make(&mut rng, rows, cols, r, 1);
15351        // q8_row sibling: [int8 rows·cols][f16 row scale · rows].
15352        let mut q8: Vec<u8> = (0..rows * cols)
15353            .map(|i| (((i * 89) % 253) as i32 - 126) as i8 as u8)
15354            .collect();
15355        for o in 0..rows {
15356            q8.extend_from_slice(&cortiq_core::quant::f32_to_f16(0.002 + o as f32 * 1e-4).to_le_bytes());
15357        }
15358        let header: CmfHeader = serde_json::from_value(serde_json::json!({
15359            "format": "cmf", "version": cortiq_core::CMF_VERSION,
15360            "arch": {"arch_name": "tiny-blr", "hidden_size": cols,
15361                "intermediate_size": rows, "num_layers": 1, "num_attention_heads": 2,
15362                "num_kv_heads": 1, "head_dim": 64, "vocab_size": rows,
15363                "layer_types": ["FullAttention"], "rms_norm_eps": 1e-6,
15364                "max_position_embeddings": 8},
15365            "quant_type": "Q8_2F"
15366        }))
15367        .unwrap();
15368        let specs = [
15369            TensorSpec {
15370                name: "g".into(),
15371                dtype: TensorDtype::BinaryLowRank,
15372                shape: vec![rows, cols],
15373                data: gate.clone(),
15374            },
15375            TensorSpec {
15376                name: "u".into(),
15377                dtype: TensorDtype::BinaryLowRank,
15378                shape: vec![rows, cols],
15379                data: up.clone(),
15380            },
15381            TensorSpec {
15382                name: "q".into(),
15383                dtype: TensorDtype::Q8Row,
15384                shape: vec![rows, cols],
15385                data: q8,
15386            },
15387        ];
15388        let dir = std::env::temp_dir().join(format!("cmf-blr-mapped-{}", std::process::id()));
15389        std::fs::create_dir_all(&dir).unwrap();
15390        let path = dir.join("m.cmf");
15391        CmfModel::write(&path, &header, &specs, None, None).unwrap();
15392        let model = Arc::new(CmfModel::open(&path).unwrap());
15393        assert!(model.verify().is_empty(), "{:?}", model.verify());
15394        let t = |n: &str| QTensor::from_model(&model, n).unwrap();
15395        let (g, u, q) = (t("g"), t("u"), t("q"));
15396        assert!(g.is_blr() && u.is_blr() && !q.is_blr());
15397        assert!(g.graph_weight().is_none() && g.graph_weight_descriptor().is_none());
15398        assert!(g.as_f32().is_none() && g.model_idx().is_none());
15399        assert!(g.mapped_device_gemm().is_none() && g.q1_parts().is_none());
15400        assert!(!g.sparse_col_ok());
15401        assert_eq!((g.rows(), g.cols()), (rows, cols));
15402        let deq = |bytes: &[u8]| {
15403            let mut w = vec![0f32; rows * cols];
15404            cortiq_core::blr::dequant_blr(bytes, rows, cols, &mut w).unwrap();
15405            w
15406        };
15407        let (wg, wu) = (deq(&gate), deq(&up));
15408        let mv = |w: &[f32], x: &[f32]| -> Vec<f32> {
15409            (0..rows)
15410                .map(|i| (0..cols).map(|j| w[i * cols + j] * x[j]).sum())
15411                .collect()
15412        };
15413        let close = |a: &[f32], b: &[f32], what: &str| {
15414            let s = b.iter().map(|v| v * v).sum::<f32>().sqrt().max(1e-30);
15415            let e = a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum::<f32>().sqrt();
15416            assert!(e / s < 1e-5, "{what}: rel {}", e / s);
15417        };
15418        let pool = Pool::new(3);
15419        let x: Vec<f32> = (0..cols).map(|_| rng.f()).collect();
15420        let x2: Vec<f32> = (0..cols).map(|_| rng.f()).collect();
15421        let mut o = vec![0f32; rows];
15422        g.matvec(&x, &mut o, Some(&pool));
15423        close(&o, &mv(&wg, &x), "matvec");
15424        let (mut o1, mut o2) = (vec![0f32; rows], vec![0f32; rows]);
15425        g.matvec2(&x, &x2, &mut o1, &mut o2, Some(&pool));
15426        close(&o1, &mv(&wg, &x), "matvec2 a");
15427        close(&o2, &mv(&wg, &x2), "matvec2 b");
15428        for b in [2usize, 5] {
15429            let xs: Vec<f32> = (0..b * cols).map(|_| rng.f()).collect();
15430            let mut om = vec![0f32; b * rows];
15431            g.matmat(&xs, b, &mut om, Some(&pool));
15432            for t in 0..b {
15433                close(
15434                    &om[t * rows..(t + 1) * rows],
15435                    &mv(&wg, &xs[t * cols..(t + 1) * cols]),
15436                    "matmat",
15437                );
15438            }
15439        }
15440        // Multi-tensor job mixed with a q8_row sibling: per-tensor fallback,
15441        // the q8_row output identical to its own matvec.
15442        let (mut a, mut bq, mut c) = (vec![0f32; rows], vec![0f32; rows], vec![0f32; rows]);
15443        QTensor::matvec_many([&g, &q, &u], &x, [&mut a, &mut bq, &mut c], Some(&pool));
15444        close(&a, &mv(&wg, &x), "matvec_many blr gate");
15445        close(&c, &mv(&wu, &x), "matvec_many blr up");
15446        let mut qo = vec![0f32; rows];
15447        q.matvec(&x, &mut qo, Some(&pool));
15448        assert_eq!(bq, qo, "matvec_many q8_row sibling");
15449        let mut f = vec![0f32; rows];
15450        assert!(!QTensor::matvec_silu_mul(&g, &u, &x, &mut f, Some(&pool)));
15451        let mut row = vec![0f32; cols];
15452        g.row_f32(rows / 3, &mut row);
15453        close(&row, &wg[(rows / 3) * cols..(rows / 3 + 1) * cols], "row_f32");
15454        let mut scratch = vec![0f32; cols];
15455        let d = g.row_dot(7, &x, &mut scratch);
15456        let want: f32 = (0..cols).map(|j| wg[7 * cols + j] * x[j]).sum();
15457        assert!((d - want).abs() < 1e-4 * (1.0 + want.abs()), "row_dot");
15458        let mut col = vec![0f32; rows];
15459        g.add_col_scaled(cols / 2, 1.5, &mut col);
15460        let want: Vec<f32> = (0..rows).map(|i| 1.5 * wg[i * cols + cols / 2]).collect();
15461        close(&col, &want, "add_col_scaled");
15462        drop((g, u, q, model));
15463        let _ = std::fs::remove_dir_all(&dir);
15464    }
15465
15466    #[test]
15467    fn repack_is_bit_identical() {
15468        // The interleaved-repack kernel must produce EXACTLY the same
15469        // bits as the mmap-layout kernel: integer accumulation is order-
15470        // exact, the f32 epilogue is identical. Odd rows exercise the
15471        // tail; direct range calls exercise unaligned pool splits.
15472        let (rows, cols) = (267, 96); // 66 groups + 3 tail rows, cols % 16 == 0
15473        let w: Vec<u8> = (0..rows * cols)
15474            .map(|i| (((i * 89) % 253) as i32 - 126) as i8 as u8)
15475            .collect();
15476        let scales: Vec<f32> = (0..rows).map(|o| 0.003 + o as f32 * 0.0007).collect();
15477        let x: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.37).sin() * 2.0).collect();
15478        let rep = q8_repack_layout(&w, rows, cols);
15479        // Group interleave round-trips.
15480        for g in 0..rows / 4 {
15481            for c in 0..cols / 16 {
15482                for lane in 0..4 {
15483                    assert_eq!(
15484                        &rep[g * 4 * cols + c * 64 + lane * 16
15485                            ..g * 4 * cols + c * 64 + lane * 16 + 16],
15486                        &w[(g * 4 + lane) * cols + c * 16..(g * 4 + lane) * cols + c * 16 + 16],
15487                    );
15488                }
15489            }
15490        }
15491        let mut a = vec![0.0f32; rows];
15492        qmatvec(
15493            &w,
15494            &[],
15495            &scales,
15496            &x,
15497            &[],
15498            TensorDtype::Q8Row,
15499            rows,
15500            cols,
15501            &mut a,
15502            None,
15503        );
15504        let mut b = vec![0.0f32; rows];
15505        qmatvec(
15506            &w,
15507            &rep,
15508            &scales,
15509            &x,
15510            &[],
15511            TensorDtype::Q8Row,
15512            rows,
15513            cols,
15514            &mut b,
15515            None,
15516        );
15517        assert_eq!(a, b, "full-range repack output diverged");
15518
15519        #[cfg(target_arch = "aarch64")]
15520        if sdot_enabled() {
15521            // Unaligned range split (pool workers get arbitrary bounds).
15522            let act = split_act(&x);
15523            let mut c1 = vec![0.0f32; rows];
15524            let mut c2 = vec![0.0f32; rows];
15525            q8_range_sdot(
15526                &w,
15527                &[],
15528                &scales,
15529                &act,
15530                cols,
15531                SendMut(c1.as_mut_ptr()),
15532                3,
15533                rows - 2,
15534            );
15535            q8_range_sdot(
15536                &w,
15537                &rep,
15538                &scales,
15539                &act,
15540                cols,
15541                SendMut(c2.as_mut_ptr()),
15542                3,
15543                rows - 2,
15544            );
15545            assert_eq!(c1, c2, "unaligned-range repack output diverged");
15546        }
15547    }
15548
15549    #[test]
15550    fn sdot_a8w8_noise_is_bounded() {
15551        // Off-grid activations: A8 quantization noise must stay small in
15552        // relative L2 over the whole output (realistic accuracy contract;
15553        // vmfcore measured argmax-identical decode on real models).
15554        let (rows, cols) = (16, 512);
15555        let w: Vec<u8> = (0..rows * cols)
15556            .map(|i| (((i * 37) % 251) as i32 - 125) as i8 as u8)
15557            .collect();
15558        let scales = vec![0.01f32; rows];
15559        let x: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.21).sin()).collect();
15560        let mut a = vec![0.0f32; rows];
15561        qmatvec(
15562            &w,
15563            &[],
15564            &scales,
15565            &x,
15566            &[],
15567            TensorDtype::Q8Row,
15568            rows,
15569            cols,
15570            &mut a,
15571            None,
15572        );
15573        let (mut num, mut den) = (0f64, 0f64);
15574        for o in 0..rows {
15575            let mut acc = 0.0f32;
15576            for j in 0..cols {
15577                acc += (w[o * cols + j] as i8) as f32 * x[j];
15578            }
15579            let expect = acc * scales[o];
15580            num += ((a[o] - expect) as f64).powi(2);
15581            den += (expect as f64).powi(2);
15582        }
15583        let rel = (num / den.max(1e-12)).sqrt();
15584        assert!(rel < 0.05, "A8W8 relative L2 error too high: {rel}");
15585    }
15586
15587    #[test]
15588    fn i8_dot_neon_matches_scalar() {
15589        let n = 100;
15590        let w: Vec<u8> = (0..n).map(|i| ((i * 37 + 11) % 251) as u8).collect();
15591        let x: Vec<f32> = (0..n).map(|i| (i as f32 * 0.13).sin()).collect();
15592        let mut scalar = 0.0f32;
15593        for j in 0..n {
15594            scalar += (w[j] as i8) as f32 * x[j];
15595        }
15596        let fast = dot_i8_f32(&w, &x);
15597        assert!((scalar - fast).abs() < 1e-3 * scalar.abs().max(1.0));
15598    }
15599
15600    /// Fused vbit matvec must match full dequant_vbit + dense matvec.
15601    #[test]
15602    fn vbitmatvec_matches_full_dequant() {
15603        let (rows, cols) = (6, 64);
15604        let ng = cols / GROUP_SIZE;
15605        // Hand-craft: bits per row, f16 scales, packed rows.
15606        let bits: Vec<u8> = vec![3, 4, 5, 6, 8, 4];
15607        let mut bytes = bits.clone();
15608        for g in 0..rows * ng {
15609            let s = 0.02 + 0.001 * g as f32;
15610            bytes.extend_from_slice(&cortiq_core::quant::f32_to_f16(s).to_le_bytes());
15611        }
15612        for r in 0..rows {
15613            let b = bits[r] as usize;
15614            let (mut acc, mut nb) = (0u64, 0usize);
15615            let mut rowbytes = Vec::new();
15616            for i in 0..cols {
15617                let v = ((i * 7 + r * 13) % (1 << b)) as u64;
15618                acc = (acc << b) | v;
15619                nb += b;
15620                while nb >= 8 {
15621                    nb -= 8;
15622                    rowbytes.push(((acc >> nb) & 0xFF) as u8);
15623                }
15624            }
15625            if nb > 0 {
15626                rowbytes.push(((acc << (8 - nb)) & 0xFF) as u8);
15627            }
15628            bytes.extend_from_slice(&rowbytes);
15629        }
15630        let x: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.19).sin()).collect();
15631
15632        let mut reference = vec![0f32; rows * cols];
15633        cortiq_core::quant::dequant_vbit(&bytes, rows, cols, &mut reference).unwrap();
15634        let mut expect = vec![0f32; rows];
15635        for r in 0..rows {
15636            expect[r] = reference[r * cols..(r + 1) * cols]
15637                .iter()
15638                .zip(&x)
15639                .map(|(w, xv)| w * xv)
15640                .sum();
15641        }
15642        let mut got = vec![0f32; rows];
15643        let offsets = vbit_row_offsets(&bytes, rows, cols);
15644        vbitmatvec(&bytes, &offsets, &x, rows, cols, &mut got, None);
15645        // SDOT path quantizes activations to i8 (A8W8): bounded noise,
15646        // same contract as q8 (exact path is pinned by CMF_SDOT=0 in
15647        // the golden-parity gate).
15648        let tol = if a8w8_enabled() { 6e-2 } else { 1e-4 };
15649        let scale = expect.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6);
15650        for r in 0..rows {
15651            assert!(
15652                (got[r] - expect[r]).abs() < tol * scale,
15653                "row {r}: {} vs {}",
15654                got[r],
15655                expect[r]
15656            );
15657        }
15658    }
15659
15660    /// Fused q4 matvec must match the reference full-dequant + dense
15661    /// matvec bit-for-bit in structure (same f32 math, group order).
15662    /// vbit matmat: the blocked 1×4 leg must match the per-row path
15663    /// (paired env toggle; larger shape so both code paths engage).
15664    #[test]
15665    #[cfg(target_arch = "x86_64")]
15666    fn vbit_matmat_blocked_matches_per_row() {
15667        let (rows, cols, b) = (64usize, 128usize, 9usize);
15668        let ng = cols / GROUP_SIZE;
15669        let bits: Vec<u8> = (0..rows).map(|r| [3u8, 4, 5, 6][r % 4]).collect();
15670        let mut bytes = bits.clone();
15671        for g in 0..rows * ng {
15672            let sc = 0.02 + 0.0005 * g as f32;
15673            bytes.extend_from_slice(&cortiq_core::quant::f32_to_f16(sc).to_le_bytes());
15674        }
15675        for r in 0..rows {
15676            let bw = bits[r] as usize;
15677            let (mut acc, mut nb) = (0u64, 0usize);
15678            let mut rowbytes = Vec::new();
15679            for i in 0..cols {
15680                let v = ((i * 7 + r * 13) % (1 << bw)) as u64;
15681                acc = (acc << bw) | v;
15682                nb += bw;
15683                while nb >= 8 {
15684                    nb -= 8;
15685                    rowbytes.push(((acc >> nb) & 0xFF) as u8);
15686                }
15687            }
15688            if nb > 0 {
15689                rowbytes.push(((acc << (8 - nb)) & 0xFF) as u8);
15690            }
15691            bytes.extend_from_slice(&rowbytes);
15692        }
15693        let x: Vec<f32> = (0..b * cols)
15694            .map(|i| ((i * 13 + 7) % 97) as f32 / 97.0 - 0.5)
15695            .collect();
15696        let offsets = vbit_row_offsets(&bytes, rows, cols);
15697        let mut y_a = vec![0f32; b * rows];
15698        let mut y_b = vec![0f32; b * rows];
15699        unsafe { std::env::set_var("CMF_X86_BLOCKED", "1") };
15700        vbitmatmat(&bytes, &offsets, &x, b, rows, cols, &mut y_a, None);
15701        unsafe { std::env::set_var("CMF_X86_BLOCKED", "0") };
15702        vbitmatmat(&bytes, &offsets, &x, b, rows, cols, &mut y_b, None);
15703        unsafe { std::env::remove_var("CMF_X86_BLOCKED") };
15704        let max_d = y_a
15705            .iter()
15706            .zip(&y_b)
15707            .map(|(p, q)| (p - q).abs())
15708            .fold(0.0f32, f32::max);
15709        assert!(max_d < 1e-4, "vbit blocked ≠ per-row: max|Δ| = {max_d}");
15710    }
15711
15712    /// q4t blocked 1×4 (SDOT on ARM, AVX2 on x86) must equal the
15713    /// per-row path exactly: same nibble unpack, same group order,
15714    /// same f32 accumulation — batch == matvec bit-for-bit. b=9 covers
15715    /// two full 1×4 blocks plus a remainder through the single-row
15716    /// kernel. (Both paths produce identical output, so the shared
15717    /// CMF_X86_BLOCKED env var racing with other tests cannot flip
15718    /// the verdict — worst case both sides take the same path.)
15719    #[test]
15720    fn q4t_matmat_blocked_matches_per_row() {
15721        let (rows, cols, b) = (16usize, 64usize, 9usize);
15722        let gpr = cols / GROUP_SIZE;
15723        let mut bytes = vec![0u8; rows * gpr * Q4_TILE];
15724        for r in 0..rows {
15725            for g in 0..gpr {
15726                let t = (r * gpr + g) * Q4_TILE;
15727                let sc = 0.02 + 0.001 * (r * gpr + g) as f32;
15728                bytes[t..t + 2].copy_from_slice(&cortiq_core::quant::f32_to_f16(sc).to_le_bytes());
15729                for k in 0..16 {
15730                    bytes[t + 2 + k] = ((r * 31 + g * 7 + k * 13) % 251) as u8;
15731                }
15732            }
15733        }
15734        let x: Vec<f32> = (0..b * cols)
15735            .map(|i| ((i * 13 + 7) % 97) as f32 / 97.0 - 0.5)
15736            .collect();
15737        let mut y_blk = vec![0f32; b * rows];
15738        let mut y_row = vec![0f32; b * rows];
15739        unsafe { std::env::set_var("CMF_X86_BLOCKED", "1") };
15740        q4t_matmat(&bytes, &x, b, rows, cols, &mut y_blk, None);
15741        unsafe { std::env::set_var("CMF_X86_BLOCKED", "0") };
15742        q4t_matmat(&bytes, &x, b, rows, cols, &mut y_row, None);
15743        unsafe { std::env::remove_var("CMF_X86_BLOCKED") };
15744        assert_eq!(y_blk, y_row, "q4t blocked 1x4 ≠ per-row");
15745    }
15746
15747    /// The wide-batch Accelerate arm of q4t_matmat vs a brute-force
15748    /// f32 dequant matmul: both are f32 GEMMs, so only reduction
15749    /// order differs — tight tolerance.
15750    /// A synthetic q4tp payload: random nibbles plus a per-row ladder whose
15751    /// span varies row to row, so the codes actually exercise the full 0..31
15752    /// range rather than clustering on one rung.
15753    fn synth_q4tp(rows: usize, cols: usize) -> Vec<u8> {
15754        use cortiq_core::quant::{f32_to_f16, q4tp_code_stride, q4tp_put_code};
15755        let gpr = cols / GROUP_SIZE;
15756        let stride = q4tp_code_stride(gpr);
15757        let (params_off, codes_off, _) = q4tp_sections(rows, cols);
15758        let mut b = vec![0u8; codes_off + rows * stride];
15759        for r in 0..rows {
15760            for g in 0..gpr {
15761                let t = (r * gpr + g) * Q4TP_NIB;
15762                for k in 0..16 {
15763                    b[t + k] = ((r * 31 + g * 7 + k * 13) % 251) as u8;
15764                }
15765            }
15766            let lo = -6.0 - 0.03 * (r % 17) as f32;
15767            let step = 0.01 + 0.004 * (r % 11) as f32;
15768            let p = params_off + r * 4;
15769            b[p..p + 2].copy_from_slice(&f32_to_f16(lo).to_le_bytes());
15770            b[p + 2..p + 4].copy_from_slice(&f32_to_f16(step).to_le_bytes());
15771            let crow = &mut b[codes_off + r * stride..codes_off + (r + 1) * stride];
15772            for g in 0..gpr {
15773                q4tp_put_code(crow, g, (r * 5 + g * 3) % 32);
15774            }
15775        }
15776        b
15777    }
15778
15779    /// The same weights re-expressed as q4_tiled, so the proven kernel can
15780    /// be the reference: each tile stores the ladder scale its code selects.
15781    /// Only the f16 rounding of that scale separates the two payloads.
15782    fn q4tp_as_q4t(bytes: &[u8], rows: usize, cols: usize) -> Vec<u8> {
15783        let gpr = cols / GROUP_SIZE;
15784        let v = Q4tpView::new(bytes, rows, cols);
15785        let mut out = vec![0u8; rows * gpr * Q4_TILE];
15786        let mut sc = vec![0f32; gpr];
15787        for r in 0..rows {
15788            v.scales_into(r, gpr, &mut sc);
15789            for g in 0..gpr {
15790                let t = (r * gpr + g) * Q4_TILE;
15791                let s = sc[g];
15792                out[t..t + 2].copy_from_slice(&cortiq_core::quant::f32_to_f16(s).to_le_bytes());
15793                let src = (r * gpr + g) * Q4TP_NIB;
15794                out[t + 2..t + Q4_TILE].copy_from_slice(&v.nib[src..src + Q4TP_NIB]);
15795            }
15796        }
15797        out
15798    }
15799
15800    /// The exact (`CMF_SDOT=0`) path must reproduce `dequant_q4tp` to f32
15801    /// rounding — that scalar routine is the format's definition, and the
15802    /// kernels re-derive the scale from the ladder independently. Call the
15803    /// row kernel directly: `matmat` picks the int8 arm when a8w8 is on,
15804    /// so routing through it would test the other path by accident.
15805    #[test]
15806    fn q4tp_exact_path_matches_dequant_reference() {
15807        let (rows, cols) = (256usize, 512usize);
15808        let gpr = cols / GROUP_SIZE;
15809        let bytes = synth_q4tp(rows, cols);
15810        let mut w = vec![0f32; rows * cols];
15811        cortiq_core::quant::dequant_q4tp(&bytes, rows, cols, &mut w);
15812
15813        let x: Vec<f32> = (0..cols)
15814            .map(|i| ((i * 13 + 7) % 97) as f32 / 97.0 - 0.5)
15815            .collect();
15816        let v = Q4tpView::new(&bytes, rows, cols);
15817        let mut sc = vec![0f32; gpr];
15818        for r in 0..rows {
15819            v.scales_into(r, gpr, &mut sc);
15820            let got = q4tp_row_exact(v.nib, r, gpr, &x, &sc);
15821            let want: f32 = (0..cols).map(|c| w[r * cols + c] * x[c]).sum();
15822            // These dot products cancel down to ~1e-3 from terms of ~5e-2, so
15823            // the meaningful yardstick is the summed magnitude, not the result:
15824            // against the result any reordering of a 512-term f32 sum "fails".
15825            let mag: f32 = (0..cols).map(|c| (w[r * cols + c] * x[c]).abs()).sum();
15826            assert!(
15827                (got - want).abs() <= 1e-5 * mag,
15828                "row {r}: kernel {got} vs dequant {want}"
15829            );
15830        }
15831    }
15832
15833    /// The int8 (a8w8) path can't be checked against an f32 reference — the
15834    /// activation quantization dominates. Check it against the q4t kernel it
15835    /// was ported from instead, on payloads holding the same weights: that
15836    /// isolates exactly what the port could break (16 B stride, ladder
15837    /// lookup, nibble unpack) from what it deliberately shares.
15838    #[test]
15839    fn q4tp_matvec_matches_the_q4t_kernel_it_was_ported_from() {
15840        let (rows, cols) = (256usize, 512usize);
15841        let bytes = synth_q4tp(rows, cols);
15842        let twin = q4tp_as_q4t(&bytes, rows, cols);
15843        let x: Vec<f32> = (0..cols)
15844            .map(|i| ((i * 13 + 7) % 97) as f32 / 97.0 - 0.5)
15845            .collect();
15846
15847        let mut got = vec![0f32; rows];
15848        q4tp_matvec(&bytes, &x, rows, cols, &mut got, None);
15849        let mut want = vec![0f32; rows];
15850        q4t_matvec(&twin, &x, rows, cols, &mut want, None);
15851
15852        // Scale is f16 in the twin and f32 here, so allow that rounding on
15853        // top of the summed magnitude (same cancellation argument as above).
15854        let mut w = vec![0f32; rows * cols];
15855        cortiq_core::quant::dequant_q4tp(&bytes, rows, cols, &mut w);
15856        for r in 0..rows {
15857            let mag: f32 = (0..cols).map(|c| (w[r * cols + c] * x[c]).abs()).sum();
15858            assert!(
15859                (got[r] - want[r]).abs() <= 1e-3 * mag,
15860                "row {r}: q4tp {} vs q4t {}",
15861                got[r],
15862                want[r]
15863            );
15864        }
15865    }
15866
15867    /// `matmat` carries three arms (Accelerate, blocked int8 1x4, scalar).
15868    /// Batch 5 crosses the blocked kernel's stride, so this exercises the
15869    /// 1x4 path AND its scalar tail in one run — the blocked kernel is new
15870    /// code and its four accumulators are exactly what tends to go wrong.
15871    #[test]
15872    fn q4tp_matmat_matches_the_q4t_kernel_it_was_ported_from() {
15873        let (rows, cols, b) = (256usize, 512usize, 5usize);
15874        let bytes = synth_q4tp(rows, cols);
15875        let twin = q4tp_as_q4t(&bytes, rows, cols);
15876        let xs: Vec<f32> = (0..b * cols)
15877            .map(|i| ((i * 29 + 11) % 89) as f32 / 89.0 - 0.5)
15878            .collect();
15879
15880        let mut got = vec![0f32; b * rows];
15881        q4tp_matmat(&bytes, &xs, b, rows, cols, &mut got, None);
15882        let mut want = vec![0f32; b * rows];
15883        q4t_matmat(&twin, &xs, b, rows, cols, &mut want, None);
15884
15885        let mut w = vec![0f32; rows * cols];
15886        cortiq_core::quant::dequant_q4tp(&bytes, rows, cols, &mut w);
15887        for t in 0..b {
15888            for r in 0..rows {
15889                let mag: f32 = (0..cols)
15890                    .map(|c| (w[r * cols + c] * xs[t * cols + c]).abs())
15891                    .sum();
15892                let (g, wa) = (got[t * rows + r], want[t * rows + r]);
15893                assert!(
15894                    (g - wa).abs() <= 1e-3 * mag,
15895                    "batch {t} row {r}: q4tp {g} vs q4t {wa}"
15896                );
15897            }
15898        }
15899    }
15900
15901    #[test]
15902    fn q4tp_matvec2_matches_the_single_stream_kernel() {
15903        let (rows, cols) = (128usize, 256usize);
15904        let gpr = cols / GROUP_SIZE;
15905        let bytes = synth_q4tp(rows, cols);
15906        let xs: Vec<f32> = (0..2 * cols)
15907            .map(|i| ((i * 29 + 11) % 89) as f32 / 89.0 - 0.5)
15908            .collect();
15909
15910        let (mut o1, mut o2) = (vec![0f32; rows], vec![0f32; rows]);
15911        q4tp_matvec2(
15912            &bytes,
15913            &xs[..cols],
15914            &xs[cols..],
15915            rows,
15916            cols,
15917            &mut o1,
15918            &mut o2,
15919            None,
15920        );
15921
15922        // matvec2 takes the exact path for both streams, so the single-row
15923        // kernel is an exact reference — no tolerance for path differences.
15924        let v = Q4tpView::new(&bytes, rows, cols);
15925        let mut sc = vec![0f32; gpr];
15926        for r in 0..rows {
15927            v.scales_into(r, gpr, &mut sc);
15928            assert_eq!(o1[r], q4tp_row_exact(v.nib, r, gpr, &xs[..cols], &sc));
15929            assert_eq!(o2[r], q4tp_row_exact(v.nib, r, gpr, &xs[cols..], &sc));
15930        }
15931    }
15932
15933    /// q4tp must not COST speed — it exists to save bytes, and a format that
15934    /// trades 7% of a file for a slower model is a bad trade. This guard is
15935    /// here because correctness tests happily passed while `q4tp_matmat` was
15936    /// missing its int8 and Accelerate arms and the model ran 5x slower.
15937    /// Measured on M-series: 0.97-1.04x, i.e. parity (16 B tiles are better
15938    /// aligned than q4t's 18 B, which pays for the scale indirection).
15939    #[test]
15940    fn q4tp_matvec_keeps_pace_with_q4t() {
15941        let (rows, cols) = (4096usize, 3072usize);
15942        let bytes = synth_q4tp(rows, cols);
15943        let twin = q4tp_as_q4t(&bytes, rows, cols);
15944        let x: Vec<f32> = (0..cols).map(|i| (i % 97) as f32 / 97.0 - 0.5).collect();
15945        let mut o = vec![0f32; rows];
15946        let n = 12;
15947        let mut best = (f64::MAX, f64::MAX);
15948        // Interleaved A/B, minimum statistic: this machine throttles, and a
15949        // mean over a thermal ramp reliably indicts whichever ran second.
15950        for _ in 0..3 {
15951            let t0 = std::time::Instant::now();
15952            for _ in 0..n {
15953                q4t_matvec(&twin, &x, rows, cols, &mut o, None);
15954            }
15955            best.0 = best.0.min(t0.elapsed().as_secs_f64());
15956            let t0 = std::time::Instant::now();
15957            for _ in 0..n {
15958                q4tp_matvec(&bytes, &x, rows, cols, &mut o, None);
15959            }
15960            best.1 = best.1.min(t0.elapsed().as_secs_f64());
15961        }
15962        let ratio = best.1 / best.0;
15963        println!(
15964            "q4t {:.3} ms | q4tp {:.3} ms | {ratio:.2}x",
15965            best.0 * 1e3 / n as f64,
15966            best.1 * 1e3 / n as f64
15967        );
15968        assert!(ratio < 2.0, "q4tp matvec {ratio:.2}x slower than q4t");
15969    }
15970
15971    #[cfg(target_os = "macos")]
15972    #[test]
15973    fn q4t_matmat_accel_matches_dequant_reference() {
15974        if !accel_gemm_enabled() {
15975            return; // CMF_ACCEL=0
15976        }
15977        let (rows, cols, b) = (512usize, 1024usize, 8usize); // ≥500K → accel arm
15978        let gpr = cols / GROUP_SIZE;
15979        let mut bytes = vec![0u8; rows * gpr * Q4_TILE];
15980        for r in 0..rows {
15981            for g in 0..gpr {
15982                let t = (r * gpr + g) * Q4_TILE;
15983                let sc = 0.02 + 0.0005 * ((r * gpr + g) % 64) as f32;
15984                bytes[t..t + 2].copy_from_slice(&cortiq_core::quant::f32_to_f16(sc).to_le_bytes());
15985                for k in 0..16 {
15986                    bytes[t + 2 + k] = ((r * 31 + g * 7 + k * 13) % 251) as u8;
15987                }
15988            }
15989        }
15990        let x: Vec<f32> = (0..b * cols)
15991            .map(|i| ((i * 13 + 7) % 97) as f32 / 97.0 - 0.5)
15992            .collect();
15993        let mut got = vec![0f32; b * rows];
15994        q4t_matmat(&bytes, &x, b, rows, cols, &mut got, None);
15995        // Brute-force reference off the same tiles.
15996        let mut w = vec![0f32; rows * cols];
15997        for r in 0..rows {
15998            for g in 0..gpr {
15999                let t = (r * gpr + g) * Q4_TILE;
16000                let s = f16_to_f32(u16::from_le_bytes([bytes[t], bytes[t + 1]]));
16001                for (k, &bb) in bytes[t + 2..t + Q4_TILE].iter().enumerate() {
16002                    w[r * cols + g * GROUP_SIZE + k * 2] = ((bb & 0x0F) as f32 - 8.0) * s;
16003                    w[r * cols + g * GROUP_SIZE + k * 2 + 1] =
16004                        (((bb >> 4) & 0x0F) as f32 - 8.0) * s;
16005                }
16006            }
16007        }
16008        for bi in 0..b {
16009            for r in 0..rows {
16010                let want: f32 = (0..cols).map(|j| x[bi * cols + j] * w[r * cols + j]).sum();
16011                let d = (got[bi * rows + r] - want).abs();
16012                assert!(
16013                    d <= want.abs().max(1.0) * 1e-4,
16014                    "accel q4t GEMM diverged at ({bi},{r}): {} vs {want}",
16015                    got[bi * rows + r]
16016                );
16017            }
16018        }
16019    }
16020
16021    #[test]
16022    fn q4matvec_matches_full_dequant() {
16023        let (rows, cols) = (8, 64);
16024        let groups = rows * cols / GROUP_SIZE;
16025        // Hand-craft a q4_block blob: nibbles then f16 scales.
16026        let mut bytes = Vec::with_capacity(groups * 16 + groups * 2);
16027        for i in 0..groups * 16 {
16028            bytes.push((((i * 7 + 3) % 256) & 0xFF) as u8);
16029        }
16030        for g in 0..groups {
16031            let s = 0.01 + 0.003 * g as f32;
16032            bytes.extend_from_slice(&cortiq_core::quant::f32_to_f16(s).to_le_bytes());
16033        }
16034        let x: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.17).sin()).collect();
16035
16036        let mut reference = vec![0.0f32; rows * cols];
16037        cortiq_core::quant::dequant_q4_block(&bytes, &mut reference);
16038        let mut expect = vec![0.0f32; rows];
16039        for r in 0..rows {
16040            expect[r] = reference[r * cols..(r + 1) * cols]
16041                .iter()
16042                .zip(&x)
16043                .map(|(w, xv)| w * xv)
16044                .sum();
16045        }
16046
16047        let mut got = vec![0.0f32; rows];
16048        q4matvec(&bytes, &x, rows, cols, &mut got, None);
16049        // SDOT path quantizes activations to i8 (A8W8): bounded noise,
16050        // same contract as q8/vbit (exact path is pinned by CMF_SDOT=0
16051        // in the golden-parity gate).
16052        let tol = if a8w8_enabled() { 6e-2 } else { 1e-4 };
16053        let scale = expect.iter().fold(0f32, |m, v| m.max(v.abs())).max(1.0);
16054        for r in 0..rows {
16055            assert!(
16056                (got[r] - expect[r]).abs() < tol * scale,
16057                "row {r}: {} vs {}",
16058                got[r],
16059                expect[r]
16060            );
16061        }
16062    }
16063
16064    /// Fused two-input vbit matvec must equal two single matvecs exactly
16065    /// (same per-lane accumulation order on both scalar and SDOT paths).
16066    #[test]
16067    fn vbitmatvec2_equals_two_singles() {
16068        let (rows, cols) = (6, 64);
16069        let ng = cols / GROUP_SIZE;
16070        let bits: Vec<u8> = vec![3, 4, 5, 6, 8, 4];
16071        let mut bytes = bits.clone();
16072        for g in 0..rows * ng {
16073            let s = 0.02 + 0.001 * g as f32;
16074            bytes.extend_from_slice(&cortiq_core::quant::f32_to_f16(s).to_le_bytes());
16075        }
16076        for r in 0..rows {
16077            let b = bits[r] as usize;
16078            let (mut acc, mut nb) = (0u64, 0usize);
16079            let mut rowbytes = Vec::new();
16080            for i in 0..cols {
16081                let v = ((i * 7 + r * 13) % (1 << b)) as u64;
16082                acc = (acc << b) | v;
16083                nb += b;
16084                while nb >= 8 {
16085                    nb -= 8;
16086                    rowbytes.push(((acc >> nb) & 0xFF) as u8);
16087                }
16088            }
16089            if nb > 0 {
16090                rowbytes.push(((acc << (8 - nb)) & 0xFF) as u8);
16091            }
16092            bytes.extend_from_slice(&rowbytes);
16093        }
16094        let x1: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.19).sin()).collect();
16095        let x2: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.11).cos()).collect();
16096        let offsets = vbit_row_offsets(&bytes, rows, cols);
16097
16098        let (mut a1, mut a2) = (vec![0f32; rows], vec![0f32; rows]);
16099        vbitmatvec(&bytes, &offsets, &x1, rows, cols, &mut a1, None);
16100        vbitmatvec(&bytes, &offsets, &x2, rows, cols, &mut a2, None);
16101        let (mut b1, mut b2) = (vec![0f32; rows], vec![0f32; rows]);
16102        vbitmatvec2(
16103            &bytes, &offsets, &x1, &x2, rows, cols, &mut b1, &mut b2, None,
16104        );
16105        assert_eq!(a1, b1, "fused vbit lane 1 must be bit-identical");
16106        assert_eq!(a2, b2, "fused vbit lane 2 must be bit-identical");
16107    }
16108
16109    /// Fused two-input q4 matvec must equal two single matvecs exactly.
16110    #[test]
16111    fn q4matvec2_equals_two_singles() {
16112        let (rows, cols) = (8, 128);
16113        let groups = rows * cols / GROUP_SIZE;
16114        let mut bytes = Vec::with_capacity(groups * 16 + groups * 2);
16115        for i in 0..groups * 16 {
16116            bytes.push((((i * 7 + 3) % 256) & 0xFF) as u8);
16117        }
16118        for g in 0..groups {
16119            let s = 0.01 + 0.003 * g as f32;
16120            bytes.extend_from_slice(&cortiq_core::quant::f32_to_f16(s).to_le_bytes());
16121        }
16122        // Include an outlier channel so the SDOT correction path is
16123        // exercised in the pair kernel too.
16124        let mut x1: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.17).sin()).collect();
16125        x1[9] = 250.0;
16126        let x2: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.23).cos()).collect();
16127
16128        let (mut a1, mut a2) = (vec![0f32; rows], vec![0f32; rows]);
16129        q4matvec(&bytes, &x1, rows, cols, &mut a1, None);
16130        q4matvec(&bytes, &x2, rows, cols, &mut a2, None);
16131        let (mut b1, mut b2) = (vec![0f32; rows], vec![0f32; rows]);
16132        q4matvec2(&bytes, &x1, &x2, rows, cols, &mut b1, &mut b2, None);
16133        assert_eq!(a1, b1, "fused q4 lane 1 must be bit-identical");
16134        assert_eq!(a2, b2, "fused q4 lane 2 must be bit-identical");
16135    }
16136
16137    /// Multi-matrix job must equal separate matvecs exactly — same
16138    /// kernels, only the dispatch is fused.
16139    #[test]
16140    fn matvec_many_equals_separate_matvecs() {
16141        use crate::pool::Pool;
16142        let (r1, r2, cols) = (300, 200, 64);
16143        let mk = |salt: usize, rows: usize| {
16144            QTensor::from_f32(
16145                (0..rows * cols)
16146                    .map(|i| ((i * 7 + salt) % 97) as f32 / 97.0 - 0.5)
16147                    .collect(),
16148                rows,
16149                cols,
16150            )
16151        };
16152        let (a, b) = (mk(1, r1), mk(5, r2));
16153        let x: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.11).sin()).collect();
16154        let pool = Pool::new(3);
16155
16156        let (mut ea, mut eb) = (vec![0f32; r1], vec![0f32; r2]);
16157        a.matvec(&x, &mut ea, Some(&pool));
16158        b.matvec(&x, &mut eb, Some(&pool));
16159        let (mut ga, mut gb) = (vec![0f32; r1], vec![0f32; r2]);
16160        QTensor::matvec_many([&a, &b], &x, [&mut ga, &mut gb], Some(&pool));
16161        assert_eq!(ea, ga, "fused multi-matrix lane 1 must be bit-identical");
16162        assert_eq!(eb, gb, "fused multi-matrix lane 2 must be bit-identical");
16163    }
16164
16165    /// The public Q4TP operator must take the real mapped matvec_many arm,
16166    /// rather than the F32 fallback above.  Build a tiny valid CMF so both
16167    /// handles retain their mmap payloads, then compare the fused dispatch
16168    /// with two ordinary mapped matvec calls bit-for-bit.
16169    #[test]
16170    fn q4tp_matvec_many_equals_separate_matvecs() {
16171        use crate::pool::Pool;
16172        use cortiq_core::{CMF_VERSION, CmfHeader, CmfModel, QuantType, TensorSpec};
16173
16174        let (r1, r2, cols) = (300usize, 200usize, 64usize);
16175        let arch: cortiq_core::ModelArch = serde_json::from_value(serde_json::json!({
16176            "arch_name": "tiny-q4tp",
16177            "hidden_size": cols,
16178            "intermediate_size": cols * 2,
16179            "num_layers": 1,
16180            "num_attention_heads": 2,
16181            "num_kv_heads": 1,
16182            "head_dim": 32,
16183            "vocab_size": r1,
16184            "layer_types": ["FullAttention"],
16185            "rms_norm_eps": 1e-6,
16186            "max_position_embeddings": 8,
16187            "linear_conv_kernel_dim": 0,
16188            "linear_num_key_heads": 0,
16189            "linear_num_value_heads": 0
16190        }))
16191        .unwrap();
16192        let header = CmfHeader {
16193            format: "cmf".into(),
16194            version: CMF_VERSION,
16195            arch,
16196            quant_type: QuantType::Q4Block,
16197            provenance: None,
16198            tokenizer_config: None,
16199            section_hashes: None,
16200            skills: Vec::new(),
16201            shard: None,
16202            calibration: None,
16203            routing: None,
16204            genome: None,
16205            lineage: Vec::new(),
16206            router: None,
16207            segments: Vec::new(),
16208        };
16209        let specs = [
16210            TensorSpec {
16211                name: "q".into(),
16212                dtype: TensorDtype::Q4TiledP,
16213                shape: vec![r1, cols],
16214                data: synth_q4tp(r1, cols),
16215            },
16216            TensorSpec {
16217                name: "kv".into(),
16218                dtype: TensorDtype::Q4TiledP,
16219                shape: vec![r2, cols],
16220                data: synth_q4tp(r2, cols),
16221            },
16222        ];
16223        let dir = std::env::temp_dir().join(format!("cmf-q4tp-many-{}", std::process::id()));
16224        std::fs::create_dir_all(&dir).unwrap();
16225        let path = dir.join("m.cmf");
16226        CmfModel::write(&path, &header, &specs, None, None).unwrap();
16227        let model = Arc::new(CmfModel::open(&path).unwrap());
16228        let (a, b) = (
16229            QTensor::from_model(&model, "q").unwrap(),
16230            QTensor::from_model(&model, "kv").unwrap(),
16231        );
16232        assert_eq!(a.model_dtype(), Some(TensorDtype::Q4TiledP));
16233        assert_eq!(b.model_dtype(), Some(TensorDtype::Q4TiledP));
16234        let x: Vec<f32> = (0..cols)
16235            .map(|i| ((i * 17 + 3) % 97) as f32 / 97.0 - 0.5)
16236            .collect();
16237        let pool = Pool::new(3);
16238        let (mut ea, mut eb) = (vec![0.0f32; r1], vec![0.0f32; r2]);
16239        a.matvec(&x, &mut ea, Some(&pool));
16240        b.matvec(&x, &mut eb, Some(&pool));
16241        let (mut ga, mut gb) = (vec![0.0f32; r1], vec![0.0f32; r2]);
16242        QTensor::matvec_many([&a, &b], &x, [&mut ga, &mut gb], Some(&pool));
16243        assert_eq!(ea, ga, "Q4TP fused lane 1 must be bit-identical");
16244        assert_eq!(eb, gb, "Q4TP fused lane 2 must be bit-identical");
16245        let _ = std::fs::remove_dir_all(&dir);
16246    }
16247
16248    /// The fast expert kernel (`moe_fast`): its scales are bit for bit
16249    /// those of `scales_into`, whole experts equal `moe_gate_up_rows` +
16250    /// `moe_down_rows` up to the rounding of a sixteen-lane sum, with
16251    /// activation outliers on both stages, empty groups, groups past four
16252    /// tokens, and the same bits with and without a pool.
16253    #[cfg(target_arch = "x86_64")]
16254    #[test]
16255    fn fast_expert_rows_match_the_row_kernels() {
16256        use crate::pool::Pool;
16257        use cortiq_core::{CMF_VERSION, CmfHeader, CmfModel, QuantType, TensorSpec};
16258
16259        // The scales, every row width the code decode has a path for.
16260        for (rows, cols) in [(32usize, 2560usize), (16, 640), (48, 192), (16, 64)] {
16261            let bytes = synth_q4tp(rows, cols);
16262            let v = Q4tpView::new(&bytes, rows, cols);
16263            let gpr = cols / GROUP_SIZE;
16264            for r0 in (0..rows).step_by(16) {
16265                let Some(got) = moe_fast::block_scales(&v, r0, gpr) else {
16266                    eprintln!("fast_expert_rows: no AVX-512 VNNI here, skipped");
16267                    return;
16268                };
16269                for i in 0..16 {
16270                    let mut want = vec![0f32; gpr];
16271                    v.scales_into(r0 + i, gpr, &mut want);
16272                    assert_eq!(
16273                        want.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
16274                        got[i * gpr..(i + 1) * gpr].iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
16275                        "scales of row {} ({rows}x{cols})",
16276                        r0 + i
16277                    );
16278                }
16279            }
16280        }
16281
16282        let (h, inter, ne) = (256usize, 640usize, 5usize);
16283        let arch: cortiq_core::ModelArch = serde_json::from_value(serde_json::json!({
16284            "arch_name": "tiny-q4tp-moe",
16285            "hidden_size": h,
16286            "intermediate_size": inter,
16287            "num_layers": 1,
16288            "num_attention_heads": h / 32,
16289            "num_kv_heads": 1,
16290            "head_dim": 32,
16291            "vocab_size": 8,
16292            "layer_types": ["FullAttention"],
16293            "rms_norm_eps": 1e-6,
16294            "max_position_embeddings": 8,
16295            "linear_conv_kernel_dim": 0,
16296            "linear_num_key_heads": 0,
16297            "linear_num_value_heads": 0
16298        }))
16299        .unwrap();
16300        let header = CmfHeader {
16301            format: "cmf".into(),
16302            version: CMF_VERSION,
16303            arch,
16304            quant_type: QuantType::Q4Block,
16305            provenance: None,
16306            tokenizer_config: None,
16307            section_hashes: None,
16308            skills: Vec::new(),
16309            shard: None,
16310            calibration: None,
16311            routing: None,
16312            genome: None,
16313            lineage: Vec::new(),
16314            router: None,
16315            segments: Vec::new(),
16316        };
16317        let mut specs = Vec::new();
16318        for e in 0..ne {
16319            for (k, (n, r, c)) in [("g", inter, h), ("u", inter, h), ("d", h, inter)]
16320                .into_iter()
16321                .enumerate()
16322            {
16323                let mut data = synth_q4tp(r, c);
16324                for (i, byte) in data[..r * (c / GROUP_SIZE) * Q4TP_NIB]
16325                    .iter_mut()
16326                    .enumerate()
16327                {
16328                    *byte ^= ((i * (e * 3 + k + 1)) % 251) as u8;
16329                }
16330                specs.push(TensorSpec {
16331                    name: format!("{n}{e}"),
16332                    dtype: TensorDtype::Q4TiledP,
16333                    shape: vec![r, c],
16334                    data,
16335                });
16336            }
16337        }
16338        let dir = std::env::temp_dir().join(format!("cmf-moe-fast-{}", std::process::id()));
16339        std::fs::create_dir_all(&dir).unwrap();
16340        let path = dir.join("m.cmf");
16341        CmfModel::write(&path, &header, &specs, None, None).unwrap();
16342        let model = Arc::new(CmfModel::open(&path).unwrap());
16343        let t = |n: String| QTensor::from_model(&model, &n).unwrap();
16344        let g: Vec<QTensor> = (0..ne).map(|e| t(format!("g{e}"))).collect();
16345        let u: Vec<QTensor> = (0..ne).map(|e| t(format!("u{e}"))).collect();
16346        let d: Vec<QTensor> = (0..ne).map(|e| t(format!("d{e}"))).collect();
16347        let b = 6usize;
16348        let mut xs: Vec<f32> = (0..b * h)
16349            .map(|i| ((i * 31 + 7) % 89) as f32 / 89.0 - 0.5)
16350            .collect();
16351        xs[5] = 9.0; // an activation outlier on token 0
16352        // Expert -> its tokens: five (a full chunk and one more), one, none, three, two.
16353        let groups: Vec<Vec<usize>> = vec![vec![0, 1, 2, 3, 4], vec![5], vec![], vec![2, 0, 5], vec![1, 3]];
16354        let lens: Vec<usize> = groups.iter().map(|v| v.len()).collect();
16355        let n_pairs: usize = lens.iter().sum();
16356        let pool = Pool::new(3);
16357        let close = |want: &[f32], got: &[f32], rel: f32, what: &str| {
16358            assert_eq!(want.len(), got.len(), "{what}: length");
16359            let top = want.iter().fold(0f32, |m, v| m.max(v.abs()));
16360            assert!(top > 0.0, "{what}: an all-zero reference proves nothing");
16361            for (i, (w, v)) in want.iter().zip(got).enumerate() {
16362                assert!((w - v).abs() <= rel * top, "{what}: [{i}] {w} vs {v} (scale {top})");
16363            }
16364        };
16365
16366        // The reference: the two row kernels.
16367        let pairs: Vec<(&QTensor, &QTensor)> = (0..ne).map(|e| (&g[e], &u[e])).collect();
16368        let mut gs: Vec<Vec<f32>> = (0..n_pairs).map(|_| vec![0f32; inter]).collect();
16369        assert!(QTensor::moe_gate_up_rows(&pairs, &groups, &xs, &mut gs, Some(&pool)));
16370        let downs: Vec<&QTensor> = d.iter().collect();
16371        let mut ds: Vec<Vec<f32>> = (0..n_pairs).map(|_| vec![0f32; h]).collect();
16372        assert!(QTensor::moe_down_rows(&downs, &lens, &gs, &mut ds, Some(&pool)));
16373
16374        let triples: Vec<(&QTensor, &QTensor, &QTensor)> = (0..ne).map(|e| (&g[e], &u[e], &d[e])).collect();
16375        let mut out = vec![0f32; n_pairs * h];
16376        let mut gs_fast = Vec::new();
16377        if !moe_fast::run_stages(&triples, &groups, &xs, &mut out, Some(&pool), None, Some(&mut gs_fast)) {
16378            eprintln!("fast_expert_rows: the int8 activation kernels are off here, skipped");
16379            let _ = std::fs::remove_dir_all(&dir);
16380            return;
16381        }
16382        close(&gs.concat(), &gs_fast, 1e-4, "gate and up");
16383        close(&ds.concat(), &out, 1e-2, "whole experts");
16384
16385        // The down stage alone on the reference's gate rows, one of them
16386        // with an outlier (the gate rows of a real expert have them).
16387        let mut gs_out = gs.clone();
16388        let top = gs.iter().flatten().fold(0f32, |m, v| m.max(v.abs()));
16389        gs_out[0][3] = 40.0 * top;
16390        let mut ds_out: Vec<Vec<f32>> = (0..n_pairs).map(|_| vec![0f32; h]).collect();
16391        assert!(QTensor::moe_down_rows(&downs, &lens, &gs_out, &mut ds_out, Some(&pool)));
16392        let mut out2 = vec![0f32; n_pairs * h];
16393        assert!(moe_fast::run_stages(&triples, &groups, &xs, &mut out2, Some(&pool), Some(&gs_out.concat()), None));
16394        close(&ds_out.concat(), &out2, 1e-4, "down");
16395
16396        // The same bits on the calling thread alone, and a refusal the caller can fall back from.
16397        let mut out3 = vec![0f32; n_pairs * h];
16398        assert!(QTensor::moe_expert_rows_fast(&triples, &groups, &xs, &mut out3, None));
16399        assert_eq!(
16400            out.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
16401            out3.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
16402            "pooled and serial runs must agree bit for bit"
16403        );
16404        // A pool on two NUMA nodes gives each side half of every matrix's rows: the same bits again.
16405        pool.mark_two_nodes(true);
16406        let mut out4 = vec![0f32; n_pairs * h];
16407        assert!(QTensor::moe_expert_rows_fast(&triples, &groups, &xs, &mut out4, Some(&pool)));
16408        let mut out5 = vec![0f32; n_pairs * h];
16409        assert!(moe_fast::run_stages(&triples, &groups, &xs, &mut out5, Some(&pool), Some(&gs_out.concat()), None));
16410        pool.mark_two_nodes(false);
16411        assert_eq!(
16412            out.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
16413            out4.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
16414            "the rows split over two sides must agree bit for bit"
16415        );
16416        assert_eq!(
16417            out2.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
16418            out5.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
16419            "the down rows split over two sides must agree bit for bit"
16420        );
16421        let mut short = vec![0f32; n_pairs * h - 1];
16422        assert!(!QTensor::moe_expert_rows_fast(&triples, &groups, &xs, &mut short, Some(&pool)));
16423        let _ = std::fs::remove_dir_all(&dir);
16424    }
16425
16426    /// The MiMo speculative verify's kernels: several tokens' MoE through
16427    /// `moe_gate_up_rows` / `moe_down_rows` (+ the caller's route-order sum)
16428    /// is bit-identical to each token alone through `moe_gate_up_many` /
16429    /// `moe_down_many` (decode), and a row-exact `q4tp_matmat` of five
16430    /// tokens (wide enough for the blocked tiles) equals five matvecs.
16431    #[test]
16432    fn multi_token_moe_rows_equal_single_token_decode() {
16433        use crate::pool::Pool;
16434        use cortiq_core::{CMF_VERSION, CmfHeader, CmfModel, QuantType, TensorSpec};
16435
16436        let (h, inter, ne) = (64usize, 128usize, 3usize);
16437        let arch: cortiq_core::ModelArch = serde_json::from_value(serde_json::json!({
16438            "arch_name": "tiny-q4tp-moe",
16439            "hidden_size": h,
16440            "intermediate_size": inter,
16441            "num_layers": 1,
16442            "num_attention_heads": 2,
16443            "num_kv_heads": 1,
16444            "head_dim": 32,
16445            "vocab_size": 8,
16446            "layer_types": ["FullAttention"],
16447            "rms_norm_eps": 1e-6,
16448            "max_position_embeddings": 8,
16449            "linear_conv_kernel_dim": 0,
16450            "linear_num_key_heads": 0,
16451            "linear_num_value_heads": 0
16452        }))
16453        .unwrap();
16454        let header = CmfHeader {
16455            format: "cmf".into(),
16456            version: CMF_VERSION,
16457            arch,
16458            quant_type: QuantType::Q4Block,
16459            provenance: None,
16460            tokenizer_config: None,
16461            section_hashes: None,
16462            skills: Vec::new(),
16463            shard: None,
16464            calibration: None,
16465            routing: None,
16466            genome: None,
16467            lineage: Vec::new(),
16468            router: None,
16469            segments: Vec::new(),
16470        };
16471        let mut specs = Vec::new();
16472        for e in 0..ne {
16473            for (k, (n, r, c)) in [("g", inter, h), ("u", inter, h), ("d", h, inter)]
16474                .into_iter()
16475                .enumerate()
16476            {
16477                // Distinct experts: perturb only the nibble plane (any byte
16478                // is a valid pair of codes; the ladder stays intact).
16479                let mut data = synth_q4tp(r, c);
16480                for (i, byte) in data[..r * (c / GROUP_SIZE) * Q4TP_NIB]
16481                    .iter_mut()
16482                    .enumerate()
16483                {
16484                    *byte ^= ((i * (e * 3 + k + 1)) % 251) as u8;
16485                }
16486                specs.push(TensorSpec {
16487                    name: format!("{n}{e}"),
16488                    dtype: TensorDtype::Q4TiledP,
16489                    shape: vec![r, c],
16490                    data,
16491                });
16492            }
16493        }
16494        let dir = std::env::temp_dir().join(format!(
16495            "cmf-moe-rows-{}-{}",
16496            std::process::id(),
16497            FLOAT_ACTIVATIONS.get()
16498        ));
16499        std::fs::create_dir_all(&dir).unwrap();
16500        let path = dir.join("m.cmf");
16501        CmfModel::write(&path, &header, &specs, None, None).unwrap();
16502        let model = Arc::new(CmfModel::open(&path).unwrap());
16503        let t = |n: String| QTensor::from_model(&model, &n).unwrap();
16504        let g: Vec<QTensor> = (0..ne).map(|e| t(format!("g{e}"))).collect();
16505        let u: Vec<QTensor> = (0..ne).map(|e| t(format!("u{e}"))).collect();
16506        let d: Vec<QTensor> = (0..ne).map(|e| t(format!("d{e}"))).collect();
16507        let b = 4usize;
16508        let mut xs: Vec<f32> = (0..b * h)
16509            .map(|i| ((i * 31 + 7) % 89) as f32 / 89.0 - 0.5)
16510            .collect();
16511        xs[5] = 9.0; // an activation outlier on token 0
16512        // Token -> (experts in route order, weights).
16513        let routes: Vec<(Vec<usize>, Vec<f32>)> = vec![
16514            (vec![2, 0], vec![0.6, 0.4]),
16515            (vec![0, 1, 2], vec![0.2, 0.5, 0.3]),
16516            (vec![1], vec![1.0]),
16517            (vec![2, 1, 0], vec![0.25, 0.25, 0.5]),
16518        ];
16519        let pool = Pool::new(3);
16520        // Decode reference, token by token.
16521        let mut want = vec![0f32; b * h];
16522        for (tk, (idx, w)) in routes.iter().enumerate() {
16523            let x = &xs[tk * h..(tk + 1) * h];
16524            let pairs: Vec<(&QTensor, &QTensor)> = idx.iter().map(|&e| (&g[e], &u[e])).collect();
16525            let mut gs: Vec<Vec<f32>> = idx.iter().map(|_| vec![0f32; inter]).collect();
16526            assert!(QTensor::moe_gate_up_many(&pairs, x, &mut gs, Some(&pool)));
16527            if FLOAT_ACTIVATIONS.get() {
16528                for (slot, &e) in idx.iter().enumerate() {
16529                    let (mut gate, mut up) = (vec![0.0; inter], vec![0.0; inter]);
16530                    g[e].matvec(x, &mut gate, Some(&pool));
16531                    u[e].matvec(x, &mut up, Some(&pool));
16532                    for (v, u) in gate.iter_mut().zip(up) {
16533                        *v = (*v / (1.0 + (-*v).exp())) * u;
16534                    }
16535                    assert_eq!(gs[slot], gate, "float gate/up must equal ordinary matvecs");
16536                }
16537            }
16538            let downs: Vec<&QTensor> = idx.iter().map(|&e| &d[e]).collect();
16539            assert!(QTensor::moe_down_many(
16540                &downs,
16541                &gs,
16542                w,
16543                &mut want[tk * h..(tk + 1) * h],
16544                Some(&pool)
16545            ));
16546        }
16547        if FLOAT_ACTIVATIONS.get() {
16548            for (tk, (idx, w)) in routes.iter().enumerate() {
16549                let mut scalar = vec![0.0; h];
16550                for (&e, &weight) in idx.iter().zip(w) {
16551                    let (mut gate, mut up, mut down) =
16552                        (vec![0.0; inter], vec![0.0; inter], vec![0.0; h]);
16553                    g[e].matvec(&xs[tk * h..(tk + 1) * h], &mut gate, Some(&pool));
16554                    u[e].matvec(&xs[tk * h..(tk + 1) * h], &mut up, Some(&pool));
16555                    for (v, u) in gate.iter_mut().zip(up) {
16556                        *v = (*v / (1.0 + (-*v).exp())) * u;
16557                    }
16558                    d[e].matvec(&gate, &mut down, Some(&pool));
16559                    for (v, d) in scalar.iter_mut().zip(down) {
16560                        *v += weight * d;
16561                    }
16562                }
16563                assert_eq!(
16564                    &want[tk * h..(tk + 1) * h],
16565                    scalar,
16566                    "float many equals scalar experts"
16567                );
16568            }
16569        }
16570        // All four tokens at once, grouped by expert.
16571        let mut experts: Vec<usize> = Vec::new();
16572        let mut groups: Vec<Vec<usize>> = Vec::new();
16573        for (tk, (idx, _)) in routes.iter().enumerate() {
16574            for &e in idx {
16575                match experts.iter().position(|&x| x == e) {
16576                    Some(k) => groups[k].push(tk),
16577                    None => {
16578                        experts.push(e);
16579                        groups.push(vec![tk]);
16580                    }
16581                }
16582            }
16583        }
16584        let n_pairs: usize = groups.iter().map(|g| g.len()).sum();
16585        let pairs: Vec<(&QTensor, &QTensor)> = experts.iter().map(|&e| (&g[e], &u[e])).collect();
16586        let mut gs: Vec<Vec<f32>> = (0..n_pairs).map(|_| vec![0f32; inter]).collect();
16587        assert!(QTensor::moe_gate_up_rows(
16588            &pairs,
16589            &groups,
16590            &xs,
16591            &mut gs,
16592            Some(&pool)
16593        ));
16594        let downs: Vec<&QTensor> = experts.iter().map(|&e| &d[e]).collect();
16595        let lens: Vec<usize> = groups.iter().map(|g| g.len()).collect();
16596        let mut ds: Vec<Vec<f32>> = (0..n_pairs).map(|_| vec![0f32; h]).collect();
16597        assert!(QTensor::moe_down_rows(
16598            &downs,
16599            &lens,
16600            &gs,
16601            &mut ds,
16602            Some(&pool)
16603        ));
16604        let slot = |tk: usize, e: usize| {
16605            let k = experts.iter().position(|&x| x == e).unwrap();
16606            groups[..k].iter().map(|g| g.len()).sum::<usize>()
16607                + groups[k].iter().position(|&x| x == tk).unwrap()
16608        };
16609        let mut got = vec![0f32; b * h];
16610        for (tk, (idx, w)) in routes.iter().enumerate() {
16611            for i in 0..h {
16612                let mut acc = 0f32;
16613                for (&e, &we) in idx.iter().zip(w) {
16614                    acc += we * ds[slot(tk, e)][i];
16615                }
16616                got[tk * h + i] = acc;
16617            }
16618        }
16619        assert!(want.iter().any(|v| *v != 0.0));
16620        assert_eq!(
16621            want.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
16622            got.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
16623            "multi-token MoE must equal decode bit for bit"
16624        );
16625
16626        // Row-exact q4tp_matmat: five tokens (a blocked 1x4 tile + tail
16627        // otherwise) equal five matvecs.
16628        let b5 = 5usize;
16629        let x5: Vec<f32> = (0..b5 * h)
16630            .map(|i| ((i * 13 + 5) % 71) as f32 / 71.0 - 0.5)
16631            .collect();
16632        let mut mm = vec![0f32; b5 * inter];
16633        row_exact_scope(|| g[1].matmat(&x5, b5, &mut mm, Some(&pool)));
16634        for tk in 0..b5 {
16635            let mut mv = vec![0f32; inter];
16636            g[1].matvec(&x5[tk * h..(tk + 1) * h], &mut mv, Some(&pool));
16637            assert_eq!(
16638                mv.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
16639                mm[tk * inter..(tk + 1) * inter]
16640                    .iter()
16641                    .map(|v| v.to_bits())
16642                    .collect::<Vec<_>>(),
16643                "row-exact matmat token {tk}"
16644            );
16645        }
16646        // Other concurrent tests/requests may still hold the shared mode.
16647        // Nested, overlapping and unwind restoration is checked separately.
16648        let _ = std::fs::remove_dir_all(&dir);
16649    }
16650
16651    /// The row-exact fix must not touch the fast path. Outside the scope
16652    /// `q4tp_matmat` has to produce exactly what it did before, and on ARM
16653    /// "before" is spelled out below: the tuned 1x4 SDOT tile for every
16654    /// four columns and the single-row kernel for the tail. Inside the
16655    /// scope every column equals its token's matvec. `q4tp_matmat_with`
16656    /// takes the mode as an argument, so a concurrent test holding the
16657    /// shared scope cannot flip it under this one.
16658    #[test]
16659    fn q4tp_matmat_fast_path_unchanged_outside_row_exact() {
16660        use crate::pool::Pool;
16661        use std::sync::atomic::Ordering::Relaxed;
16662        let _alt = Q4TP_ALT_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
16663        // The tuned ARM shape, which is also what an unset switch picks
16664        // unless CMF_Q4TP_V1 is exported.
16665        Q4TP_ALT.store(2, Relaxed);
16666        let pool = Pool::new(3);
16667        // Under 500k cells, so macOS keeps the matmat off the AMX; the
16668        // second shape runs across pool workers (rows >= 256) with 32
16669        // groups of accumulation and a tail after two 1x4 tiles.
16670        for &(rows, cols, b) in &[(64usize, 256usize, 7usize), (320, 1024, 9)] {
16671            let bytes = synth_q4tp(rows, cols);
16672            let mut xs: Vec<f32> = (0..b * cols)
16673                .map(|i| ((i * 29 + 11) % 83) as f32 / 83.0 - 0.5)
16674                .collect();
16675            xs[3] = 7.5; // an activation outlier on token 0
16676            let run = |exact: bool| {
16677                let mut out = vec![0f32; b * rows];
16678                q4tp_matmat_with(&bytes, &xs, b, rows, cols, &mut out, Some(&pool), exact);
16679                out
16680            };
16681            let (fast, exact) = (run(false), run(true));
16682            #[cfg(not(target_arch = "aarch64"))]
16683            let _ = fast;
16684            let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
16685            let mut matvecs = vec![0f32; b * rows];
16686            for (bi, o) in matvecs.chunks_mut(rows).enumerate() {
16687                q4tp_matvec(
16688                    &bytes,
16689                    &xs[bi * cols..(bi + 1) * cols],
16690                    rows,
16691                    cols,
16692                    o,
16693                    Some(&pool),
16694                );
16695            }
16696            assert!(matvecs.iter().any(|v| *v != 0.0));
16697            assert_eq!(
16698                bits(&exact),
16699                bits(&matvecs),
16700                "{rows}x{cols} b={b}: row-exact matmat must equal per-token matvecs"
16701            );
16702            #[cfg(target_arch = "aarch64")]
16703            {
16704                // The pre-fix ARM loop, cell for cell.
16705                let gpr = cols / GROUP_SIZE;
16706                let v = Q4tpView::new(&bytes, rows, cols);
16707                let mut old = vec![0f32; b * rows];
16708                let mut sc = vec![0f32; gpr];
16709                let a8w8 = a8w8_enabled();
16710                let blocked = sdot_enabled() && blocked_enabled();
16711                let acts: Vec<SplitAct> = (0..b)
16712                    .map(|bi| split_act(&xs[bi * cols..(bi + 1) * cols]))
16713                    .collect();
16714                for r in 0..rows {
16715                    v.scales_into(r, gpr, &mut sc);
16716                    if !a8w8 {
16717                        for bi in 0..b {
16718                            let x = &xs[bi * cols..(bi + 1) * cols];
16719                            old[bi * rows + r] = q4tp_row_exact(v.nib, r, gpr, x, &sc);
16720                        }
16721                        continue;
16722                    }
16723                    let finish = |d: f32, act: &SplitAct| {
16724                        let mut acc = d * act.sx;
16725                        for &(j, xv) in &act.outliers {
16726                            let (w, s) = q4tp_outlier(v.nib, r, gpr, j, &sc);
16727                            acc += w * s * xv;
16728                        }
16729                        acc
16730                    };
16731                    let mut bi = 0usize;
16732                    while blocked && bi + 4 <= b {
16733                        let xs4 = [
16734                            acts[bi].xq.as_slice(),
16735                            acts[bi + 1].xq.as_slice(),
16736                            acts[bi + 2].xq.as_slice(),
16737                            acts[bi + 3].xq.as_slice(),
16738                        ];
16739                        let d = unsafe { dot_q4tp_row_1x4_sdot(v.nib, r, gpr, xs4, &sc) };
16740                        for k in 0..4 {
16741                            old[(bi + k) * rows + r] = finish(d[k], &acts[bi + k]);
16742                        }
16743                        bi += 4;
16744                    }
16745                    for (bi, act) in acts.iter().enumerate().skip(bi) {
16746                        let d = dot_q4tp_row_i8(v.nib, r, gpr, &act.xq, &sc);
16747                        old[bi * rows + r] = finish(d, act);
16748                    }
16749                }
16750                assert_eq!(
16751                    bits(&fast),
16752                    bits(&old),
16753                    "{rows}x{cols} b={b}: the fast path changed outside row_exact"
16754                );
16755                // And it is still the fast tile that runs: its lane-parallel
16756                // fma sum rounds differently from the matvec somewhere.
16757                if blocked {
16758                    assert_ne!(
16759                        bits(&fast),
16760                        bits(&matvecs),
16761                        "{rows}x{cols} b={b}: the tuned tile no longer runs outside row_exact"
16762                    );
16763                }
16764            }
16765        }
16766        Q4TP_ALT.store(0, Relaxed);
16767    }
16768
16769    #[test]
16770    fn row_exact_scopes_survive_overlap_nesting_and_unwind() {
16771        use std::sync::{Barrier, atomic::{AtomicUsize, Ordering}};
16772        // A private counter makes this restoration test independent of
16773        // numerical tests concurrently using the production counter.
16774        let active = AtomicUsize::new(0);
16775        counted_row_exact_scope(&active, || {
16776            assert_eq!(active.load(Ordering::Acquire), 1);
16777            counted_row_exact_scope(&active, || {
16778                assert_eq!(active.load(Ordering::Acquire), 2);
16779            });
16780            assert_eq!(active.load(Ordering::Acquire), 1);
16781        });
16782        assert_eq!(active.load(Ordering::Acquire), 0);
16783
16784        let both_entered = Barrier::new(2);
16785        let release_last = Barrier::new(2);
16786        std::thread::scope(|s| {
16787            let first = s.spawn(|| counted_row_exact_scope(&active, || {
16788                both_entered.wait();
16789            }));
16790            let last = s.spawn(|| counted_row_exact_scope(&active, || {
16791                both_entered.wait();
16792                release_last.wait();
16793            }));
16794            first.join().unwrap();
16795            let after_first = active.load(Ordering::Acquire);
16796            release_last.wait();
16797            last.join().unwrap();
16798            assert_eq!(after_first, 1, "second request must remain exact");
16799        });
16800        assert_eq!(active.load(Ordering::Acquire), 0);
16801        let panic = std::panic::catch_unwind(|| {
16802            counted_row_exact_scope(&active, || panic!("scope unwind"));
16803        });
16804        assert!(panic.is_err());
16805        assert_eq!(active.load(Ordering::Acquire), 0);
16806    }
16807
16808    #[test]
16809    #[cfg(target_arch = "x86_64")]
16810    fn q4tp_float_avx2_is_bitwise_scalar() {
16811        if !avx2_enabled() {
16812            return;
16813        }
16814        for cols in [32, 64, 96, 2048, 4096] {
16815            let rows = 9;
16816            let bytes = synth_q4tp(rows, cols);
16817            let v = Q4tpView::new(&bytes, rows, cols);
16818            let gpr = cols / GROUP_SIZE;
16819            let mut sc = vec![0.0; gpr];
16820            for seed in 1..=5 {
16821                let xs: Vec<f32> = (0..cols)
16822                    .map(|i| (((i * 104729 + seed * 8191) % 100003) as f32 - 50001.0) / 7919.0)
16823                    .collect();
16824                for r in 0..rows {
16825                    v.scales_into(r, gpr, &mut sc);
16826                    let scalar = q4tp_row_float_scalar(v.nib, r, gpr, &xs, &sc);
16827                    let vector = unsafe { q4tp_row_float_avx2(v.nib, r, gpr, &xs, &sc) };
16828                    assert_eq!(
16829                        scalar.to_bits(),
16830                        vector.to_bits(),
16831                        "cols={cols} row={r} seed={seed}"
16832                    );
16833                }
16834            }
16835        }
16836    }
16837
16838    #[test]
16839    fn multi_token_moe_rows_float_equal_single_token_decode() {
16840        float_activations_scope(multi_token_moe_rows_equal_single_token_decode);
16841    }
16842
16843    #[test]
16844    fn full_gpu_q8_scope_is_nested_and_thread_local() {
16845        assert!(!FULL_GPU_Q8.get());
16846        let before = gpu_split_frac();
16847        {
16848            let _guard = enter_full_gpu_q8_scope();
16849            assert_eq!(gpu_split_frac(), 1.0);
16850            {
16851                let _nested = enter_full_gpu_q8_scope();
16852            }
16853            assert_eq!(gpu_split_frac(), 1.0);
16854            std::thread::spawn(|| assert!(!FULL_GPU_Q8.get())).join().unwrap();
16855        }
16856        assert!(!FULL_GPU_Q8.get());
16857        assert_eq!(gpu_split_frac(), before);
16858    }
16859
16860    #[test]
16861    fn float_activation_scope_is_nested_thread_local_and_unwind_safe() {
16862        assert!(!FLOAT_ACTIVATIONS.get());
16863        let before = a8w8_enabled();
16864        float_activations_scope(|| {
16865            assert!(!a8w8_enabled());
16866            float_activations_scope(|| assert!(!a8w8_enabled()));
16867            assert!(FLOAT_ACTIVATIONS.get());
16868            std::thread::spawn(|| assert!(!FLOAT_ACTIVATIONS.get()))
16869                .join()
16870                .unwrap();
16871        });
16872        assert!(!FLOAT_ACTIVATIONS.get());
16873        assert_eq!(a8w8_enabled(), before);
16874        let _ = std::panic::catch_unwind(|| float_activations_scope(|| panic!("test unwind")));
16875        assert!(!FLOAT_ACTIVATIONS.get());
16876    }
16877
16878    /// Batched q4/vbit matmat must equal per-position matvec calls
16879    /// exactly (the fallback it replaced) — same kernels, same order.
16880    #[test]
16881    fn batched_matmat_equals_per_position_matvec() {
16882        let (rows, cols, b) = (8, 64, 5);
16883        // q4 blob.
16884        let groups = rows * cols / GROUP_SIZE;
16885        let mut q4 = Vec::new();
16886        for i in 0..groups * 16 {
16887            q4.push((((i * 7 + 3) % 256) & 0xFF) as u8);
16888        }
16889        for g in 0..groups {
16890            q4.extend_from_slice(
16891                &cortiq_core::quant::f32_to_f16(0.01 + 0.003 * g as f32).to_le_bytes(),
16892            );
16893        }
16894        // vbit blob (mixed widths incl. 8).
16895        let ng = cols / GROUP_SIZE;
16896        let bits: Vec<u8> = vec![3, 4, 5, 6, 8, 4, 5, 3];
16897        let mut vb = bits.clone();
16898        for g in 0..rows * ng {
16899            vb.extend_from_slice(
16900                &cortiq_core::quant::f32_to_f16(0.02 + 0.001 * g as f32).to_le_bytes(),
16901            );
16902        }
16903        for r in 0..rows {
16904            let bw = bits[r] as usize;
16905            let (mut acc, mut nb) = (0u64, 0usize);
16906            let mut rowbytes = Vec::new();
16907            for i in 0..cols {
16908                let v = ((i * 7 + r * 13) % (1 << bw)) as u64;
16909                acc = (acc << bw) | v;
16910                nb += bw;
16911                while nb >= 8 {
16912                    nb -= 8;
16913                    rowbytes.push(((acc >> nb) & 0xFF) as u8);
16914                }
16915            }
16916            if nb > 0 {
16917                rowbytes.push(((acc << (8 - nb)) & 0xFF) as u8);
16918            }
16919            vb.extend_from_slice(&rowbytes);
16920        }
16921        let offsets = vbit_row_offsets(&vb, rows, cols);
16922
16923        let xs: Vec<f32> = (0..b * cols).map(|i| (i as f32 * 0.13).sin()).collect();
16924
16925        // q4: batch vs singles.
16926        let mut got = vec![0f32; b * rows];
16927        q4matmat(&q4, &xs, b, rows, cols, &mut got, None);
16928        for bi in 0..b {
16929            let mut expect = vec![0f32; rows];
16930            q4matvec(
16931                &q4,
16932                &xs[bi * cols..(bi + 1) * cols],
16933                rows,
16934                cols,
16935                &mut expect,
16936                None,
16937            );
16938            assert_eq!(
16939                &got[bi * rows..(bi + 1) * rows],
16940                &expect[..],
16941                "q4 batch pos {bi}"
16942            );
16943        }
16944
16945        // vbit: batch vs singles.
16946        let mut got = vec![0f32; b * rows];
16947        vbitmatmat(&vb, &offsets, &xs, b, rows, cols, &mut got, None);
16948        for bi in 0..b {
16949            let mut expect = vec![0f32; rows];
16950            vbitmatvec(
16951                &vb,
16952                &offsets,
16953                &xs[bi * cols..(bi + 1) * cols],
16954                rows,
16955                cols,
16956                &mut expect,
16957                None,
16958            );
16959            assert_eq!(
16960                &got[bi * rows..(bi + 1) * rows],
16961                &expect[..],
16962                "vbit batch pos {bi}"
16963            );
16964        }
16965    }
16966
16967    /// q4_tiled kernels must produce BIT-identical outputs to the q4
16968    /// split kernels on the same values (same ints, same order — only
16969    /// the byte placement differs).
16970    #[test]
16971    fn q4_tiled_matches_q4_block_bitexact() {
16972        let (rows, cols, b) = (8usize, 128usize, 3usize);
16973        let groups = rows * cols / GROUP_SIZE;
16974        let mut split = Vec::with_capacity(groups * 18);
16975        for i in 0..groups * 16 {
16976            split.push((((i * 7 + 3) % 256) & 0xFF) as u8);
16977        }
16978        for g in 0..groups {
16979            split.extend_from_slice(
16980                &cortiq_core::quant::f32_to_f16(0.01 + 0.003 * g as f32).to_le_bytes(),
16981            );
16982        }
16983        // Re-tile: [scale][nibbles] per group.
16984        let (packed, scales) = split.split_at(groups * 16);
16985        let mut tiled = Vec::with_capacity(groups * Q4_TILE);
16986        for g in 0..groups {
16987            tiled.extend_from_slice(&scales[g * 2..g * 2 + 2]);
16988            tiled.extend_from_slice(&packed[g * 16..(g + 1) * 16]);
16989        }
16990
16991        let mut x1: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.17).sin()).collect();
16992        x1[9] = 250.0; // exercise the outlier path
16993        let x2: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.23).cos()).collect();
16994
16995        let (mut a, mut t) = (vec![0f32; rows], vec![0f32; rows]);
16996        q4matvec(&split, &x1, rows, cols, &mut a, None);
16997        q4t_matvec(&tiled, &x1, rows, cols, &mut t, None);
16998        assert_eq!(a, t, "q4t matvec must match q4 bit-for-bit");
16999
17000        let (mut a1, mut a2) = (vec![0f32; rows], vec![0f32; rows]);
17001        let (mut t1, mut t2) = (vec![0f32; rows], vec![0f32; rows]);
17002        q4matvec2(&split, &x1, &x2, rows, cols, &mut a1, &mut a2, None);
17003        q4t_matvec2(&tiled, &x1, &x2, rows, cols, &mut t1, &mut t2, None);
17004        assert_eq!(a1, t1);
17005        assert_eq!(a2, t2);
17006
17007        let xs: Vec<f32> = (0..b * cols).map(|i| (i as f32 * 0.13).sin()).collect();
17008        let (mut am, mut tm) = (vec![0f32; b * rows], vec![0f32; b * rows]);
17009        q4matmat(&split, &xs, b, rows, cols, &mut am, None);
17010        q4t_matmat(&tiled, &xs, b, rows, cols, &mut tm, None);
17011        assert_eq!(am, tm, "q4t matmat must match q4 bit-for-bit");
17012    }
17013
17014    /// q4 SDOT outlier correction: a single huge activation channel
17015    /// (>8·rms → outlier, zeroed in xq) must still contribute its EXACT
17016    /// term. On-grid bulk (±1/0 → xq dequantizes exactly) isolates the
17017    /// correction from A8W8 noise. cols must exceed 64: at n=64 the
17018    /// 8·rms threshold equals sqrt(v²+rest) ≥ v, so a single outlier
17019    /// can never qualify (8² = n).
17020    #[test]
17021    fn q4matvec_sdot_outlier_exact() {
17022        let (rows, cols) = (4, 128);
17023        let groups = rows * cols / GROUP_SIZE;
17024        let mut bytes = Vec::with_capacity(groups * 16 + groups * 2);
17025        for i in 0..groups * 16 {
17026            bytes.push(((i * 11 + 5) % 256) as u8);
17027        }
17028        for g in 0..groups {
17029            let s = 0.02 + 0.002 * g as f32;
17030            bytes.extend_from_slice(&cortiq_core::quant::f32_to_f16(s).to_le_bytes());
17031        }
17032        let mut x: Vec<f32> = (0..cols)
17033            .map(|i| match i % 3 {
17034                0 => 1.0,
17035                1 => -1.0,
17036                _ => 0.0,
17037            })
17038            .collect();
17039        x[17] = 300.0; // ≫ 8·rms → outlier channel
17040
17041        let mut reference = vec![0.0f32; rows * cols];
17042        cortiq_core::quant::dequant_q4_block(&bytes, &mut reference);
17043        let mut expect = vec![0.0f32; rows];
17044        for r in 0..rows {
17045            expect[r] = reference[r * cols..(r + 1) * cols]
17046                .iter()
17047                .zip(&x)
17048                .map(|(w, xv)| w * xv)
17049                .sum();
17050        }
17051        let mut got = vec![0.0f32; rows];
17052        q4matvec(&bytes, &x, rows, cols, &mut got, None);
17053        let scale = expect.iter().fold(0f32, |m, v| m.max(v.abs())).max(1.0);
17054        for r in 0..rows {
17055            assert!(
17056                (got[r] - expect[r]).abs() < 2e-3 * scale,
17057                "row {r}: {} vs {} (outlier term must be exact)",
17058                got[r],
17059                expect[r]
17060            );
17061        }
17062    }
17063
17064    /// The fused q1t matvec must equal the reference (dequant_q1t → dot),
17065    /// including the ternary zero level and the binary-searched outlier
17066    /// overlay. Guards the mmap kernel that makes a 12B q1t runnable.
17067    #[test]
17068    fn q1t_matvec_matches_reference() {
17069        use cortiq_core::quant::{dequant_q1t, f32_to_f16};
17070        let (rows, cols) = (3usize, 64usize); // gpr = 2
17071        let gpr = cols / GROUP_SIZE;
17072        let scales = [0.5f32, 0.3, 0.7, 0.2, 0.6, 0.15];
17073        // Overlay (must be sorted by flat index): a few spikes across rows.
17074        let outliers: [(u32, f32); 3] = [(5, 9.0), (70, -4.5), (150, 3.25)];
17075        let is_out = |flat: usize| outliers.iter().any(|&(i, _)| i as usize == flat);
17076        let mut bytes = Vec::new();
17077        for r in 0..rows {
17078            for g in 0..gpr {
17079                bytes.extend_from_slice(&f32_to_f16(scales[r * gpr + g]).to_le_bytes());
17080                let mut c = [0u8; 7];
17081                for k in 0..GROUP_SIZE {
17082                    // Encoder invariant: code 0 at outlier positions.
17083                    let code = if is_out(r * cols + g * GROUP_SIZE + k) {
17084                        0
17085                    } else {
17086                        ((k + r * 3 + g) % 3) as u8 // 0,1,2
17087                    };
17088                    cortiq_core::quant::q1t_pack(&mut c, k, code);
17089                }
17090                bytes.extend_from_slice(&c);
17091            }
17092        }
17093        // Per-row overlay: [u32 row_ptr[rows+1]] then [(u16 col, f16 val)] by
17094        // row (outliers are sorted by flat index → already grouped by row).
17095        let mut row_ptr = vec![0u32; rows + 1];
17096        for &(idx, _) in &outliers {
17097            row_ptr[idx as usize / cols + 1] += 1;
17098        }
17099        for r in 0..rows {
17100            row_ptr[r + 1] += row_ptr[r];
17101        }
17102        for &p in &row_ptr {
17103            bytes.extend_from_slice(&p.to_le_bytes());
17104        }
17105        for &(idx, v) in &outliers {
17106            bytes.extend_from_slice(&((idx as usize % cols) as u16).to_le_bytes());
17107            bytes.extend_from_slice(&f32_to_f16(v).to_le_bytes());
17108        }
17109
17110        let mut refw = vec![0f32; rows * cols];
17111        dequant_q1t(&bytes, rows, cols, &mut refw);
17112        // On-grid activations (±1, amax 1) so the int8 SDOT path reconstructs
17113        // x exactly and matches the f32 reference (same trick as the q1 test).
17114        let x: Vec<f32> = (0..cols)
17115            .map(|j| if j % 3 == 0 { 1.0 } else { -1.0 })
17116            .collect();
17117        let mut expect = vec![0f32; rows];
17118        for r in 0..rows {
17119            let mut a = 0.0f32;
17120            for j in 0..cols {
17121                a += refw[r * cols + j] * x[j];
17122            }
17123            expect[r] = a;
17124        }
17125        let tol = |e: f32| 1e-3 * e.abs().max(1e-3);
17126        let mut got = vec![0f32; rows];
17127        q1t_matvec(&bytes, &x, rows, cols, &mut got, None);
17128        for r in 0..rows {
17129            assert!(
17130                (got[r] - expect[r]).abs() < tol(expect[r]),
17131                "row {r}: {} vs {}",
17132                got[r],
17133                expect[r]
17134            );
17135        }
17136        // matmat (b=2, f32 decode path) must agree too.
17137        let x2: Vec<f32> = x.iter().chain(x.iter()).copied().collect();
17138        let mut gm = vec![0f32; 2 * rows];
17139        q1t_matmat(&bytes, &x2, 2, rows, cols, &mut gm, None);
17140        for r in 0..rows {
17141            assert!((gm[r] - expect[r]).abs() < tol(expect[r]));
17142            assert!((gm[rows + r] - expect[r]).abs() < tol(expect[r]));
17143        }
17144        // Fused pair (q1t_matvec2) must equal two single matvecs
17145        // bit-for-bit: same unpack, same group order, same f32
17146        // accumulation per stream. Distinct x2 exercises both lanes.
17147        let xb: Vec<f32> = (0..cols)
17148            .map(|j| if j % 5 == 0 { -1.0 } else { 1.0 })
17149            .collect();
17150        let (mut s1, mut s2) = (vec![0f32; rows], vec![0f32; rows]);
17151        q1t_matvec(&bytes, &x, rows, cols, &mut s1, None);
17152        q1t_matvec(&bytes, &xb, rows, cols, &mut s2, None);
17153        let (mut p1, mut p2) = (vec![0f32; rows], vec![0f32; rows]);
17154        q1t_matvec2(&bytes, &x, &xb, rows, cols, &mut p1, &mut p2, None);
17155        assert_eq!(p1, s1, "q1t pair lane 1 ≠ single matvec");
17156        assert_eq!(p2, s2, "q1t pair lane 2 ≠ single matvec");
17157    }
17158
17159    /// Pair == 2×matvec with an ODD group count (the kernel's tail
17160    /// group) and no overlay section.
17161    #[test]
17162    fn q1t_matvec2_odd_gpr_matches_singles() {
17163        use cortiq_core::quant::{Q1T_TILE, f32_to_f16, q1t_pack};
17164        let (rows, cols) = (5usize, 96usize); // gpr = 3 → paired + tail
17165        let gpr = cols / GROUP_SIZE;
17166        let mut bytes = Vec::with_capacity(rows * gpr * Q1T_TILE);
17167        for r in 0..rows {
17168            for g in 0..gpr {
17169                bytes.extend_from_slice(&f32_to_f16(0.1 + 0.05 * (r + g) as f32).to_le_bytes());
17170                let mut c = [0u8; 7];
17171                for k in 0..GROUP_SIZE {
17172                    q1t_pack(&mut c, k, ((k * 7 + r * 5 + g * 3) % 3) as u8);
17173                }
17174                bytes.extend_from_slice(&c);
17175            }
17176        }
17177        let x1: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.31).sin()).collect();
17178        let x2: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.17).cos()).collect();
17179        let (mut s1, mut s2) = (vec![0f32; rows], vec![0f32; rows]);
17180        q1t_matvec(&bytes, &x1, rows, cols, &mut s1, None);
17181        q1t_matvec(&bytes, &x2, rows, cols, &mut s2, None);
17182        let (mut p1, mut p2) = (vec![0f32; rows], vec![0f32; rows]);
17183        q1t_matvec2(&bytes, &x1, &x2, rows, cols, &mut p1, &mut p2, None);
17184        assert_eq!(p1, s1, "odd-gpr pair lane 1 ≠ single");
17185        assert_eq!(p2, s2, "odd-gpr pair lane 2 ≠ single");
17186    }
17187
17188    // Speed A/B: fused pair (one unpack, two streams) vs two single
17189    // matvecs. Single-threaded, FFN-sized, min-of paired in-process.
17190    //   cargo test -p cortiq-engine --release q1t_matvec2_speed -- --ignored --nocapture
17191    #[test]
17192    #[ignore]
17193    fn q1t_matvec2_speed() {
17194        use cortiq_core::quant::{Q1T_TILE, f32_to_f16, q1t_pack};
17195        use std::time::Instant;
17196        let (rows, cols) = (8192usize, 4096usize);
17197        let gpr = cols / GROUP_SIZE;
17198        let mut bytes = Vec::with_capacity(rows * gpr * Q1T_TILE);
17199        for r in 0..rows {
17200            for g in 0..gpr {
17201                let s = 0.1 + ((r + g) % 7) as f32 * 0.01;
17202                bytes.extend_from_slice(&f32_to_f16(s).to_le_bytes());
17203                let mut c = [0u8; 7];
17204                for k in 0..GROUP_SIZE {
17205                    q1t_pack(&mut c, k, ((k * 7 + r + g) % 3) as u8);
17206                }
17207                bytes.extend_from_slice(&c);
17208            }
17209        }
17210        let x1: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.31).sin()).collect();
17211        let x2: Vec<f32> = (0..cols).map(|i| (i as f32 * 0.17).cos()).collect();
17212        let (mut s1, mut s2) = (vec![0f32; rows], vec![0f32; rows]);
17213        let (mut p1, mut p2) = (vec![0f32; rows], vec![0f32; rows]);
17214        // Warm both paths once.
17215        q1t_matvec(&bytes, &x1, rows, cols, &mut s1, None);
17216        q1t_matvec2(&bytes, &x1, &x2, rows, cols, &mut p1, &mut p2, None);
17217        let (mut t_pair, mut t_two) = (f64::MAX, f64::MAX);
17218        for _ in 0..8 {
17219            let t0 = Instant::now();
17220            q1t_matvec2(&bytes, &x1, &x2, rows, cols, &mut p1, &mut p2, None);
17221            t_pair = t_pair.min(t0.elapsed().as_secs_f64() * 1000.0);
17222            let t1 = Instant::now();
17223            q1t_matvec(&bytes, &x1, rows, cols, &mut s1, None);
17224            q1t_matvec(&bytes, &x2, rows, cols, &mut s2, None);
17225            t_two = t_two.min(t1.elapsed().as_secs_f64() * 1000.0);
17226        }
17227        assert_eq!(p1, s1);
17228        assert_eq!(p2, s2);
17229        println!("q1t pair {rows}x{cols}: fused {t_pair:.2} ms | two singles {t_two:.2} ms");
17230    }
17231
17232    // Speed A/B: the base-3-division decode (what the packing commit left in
17233    // place) vs the fused sign-LUT matvec. Both single-threaded, same bytes.
17234    //   cargo test -p cortiq-engine q1t_matvec_speed -- --ignored --nocapture
17235    #[test]
17236    #[ignore]
17237    fn q1t_matvec_speed() {
17238        use cortiq_core::quant::{Q1T_TILE, f32_to_f16, q1t_code, q1t_pack};
17239        use std::time::Instant;
17240        let (rows, cols) = (8192usize, 4096usize); // FFN-sized
17241        let gpr = cols / GROUP_SIZE;
17242        let mut bytes = Vec::with_capacity(rows * gpr * Q1T_TILE + 16);
17243        for r in 0..rows {
17244            for g in 0..gpr {
17245                let s = 0.1 + ((r + g) % 7) as f32 * 0.01;
17246                bytes.extend_from_slice(&f32_to_f16(s).to_le_bytes());
17247                let mut c = [0u8; 7];
17248                for k in 0..GROUP_SIZE {
17249                    q1t_pack(&mut c, k, ((k * 7 + r + g) % 3) as u8);
17250                }
17251                bytes.extend_from_slice(&c);
17252            }
17253        }
17254        let (n, stride) = (rows * cols, 40usize); // ~2.5% outliers, per-row overlay
17255        let mut row_ptr = vec![0u32; rows + 1];
17256        let mut idx = 0usize;
17257        while idx < n {
17258            row_ptr[idx / cols + 1] += 1;
17259            idx += stride;
17260        }
17261        for r in 0..rows {
17262            row_ptr[r + 1] += row_ptr[r];
17263        }
17264        for &p in &row_ptr {
17265            bytes.extend_from_slice(&p.to_le_bytes());
17266        }
17267        let mut idx = 0usize;
17268        while idx < n {
17269            bytes.extend_from_slice(&((idx % cols) as u16).to_le_bytes());
17270            bytes.extend_from_slice(&f32_to_f16((idx % 13) as f32 * 0.1 - 0.6).to_le_bytes());
17271            idx += stride;
17272        }
17273        // On-grid ±1 so the fast path's int8 SDOT is exact vs the f32 "slow"
17274        // reference (the A/B is a timing check; values must still agree).
17275        let x: Vec<f32> = (0..cols)
17276            .map(|j| if j % 3 == 0 { 1.0 } else { -1.0 })
17277            .collect();
17278        let (rp_off, ent_off, has_ov) = q1t_overlay(&bytes, rows * gpr * Q1T_TILE, rows);
17279
17280        // "before": base-3 division decode into a buffer, then dot.
17281        let slow = |out: &mut [f32]| {
17282            let mut buf = vec![0f32; cols];
17283            for r in 0..rows {
17284                for g in 0..gpr {
17285                    let off = (r * gpr + g) * Q1T_TILE;
17286                    let s = f16_to_f32(u16::from_le_bytes([bytes[off], bytes[off + 1]]));
17287                    let codes = &bytes[off + 2..off + Q1T_TILE];
17288                    for k in 0..GROUP_SIZE {
17289                        buf[g * GROUP_SIZE + k] = match q1t_code(codes, k) {
17290                            1 => s,
17291                            2 => -s,
17292                            _ => 0.0,
17293                        };
17294                    }
17295                }
17296                out[r] = q1t_row_outlier_correction(&bytes, r, rp_off, ent_off, has_ov, &x)
17297                    + (0..cols).map(|j| buf[j] * x[j]).sum::<f32>();
17298            }
17299        };
17300        let iters = 5;
17301        let mut a = vec![0f32; rows];
17302        slow(&mut a); // warm
17303        let t = Instant::now();
17304        for _ in 0..iters {
17305            slow(&mut a);
17306        }
17307        let slow_ms = t.elapsed().as_secs_f64() * 1e3 / iters as f64;
17308
17309        let mut b = vec![0f32; rows];
17310        q1t_matvec(&bytes, &x, rows, cols, &mut b, None); // warm
17311        let t = Instant::now();
17312        for _ in 0..iters {
17313            q1t_matvec(&bytes, &x, rows, cols, &mut b, None);
17314        }
17315        let fast_ms = t.elapsed().as_secs_f64() * 1e3 / iters as f64;
17316
17317        for r in 0..rows {
17318            assert!((a[r] - b[r]).abs() < 1e-2, "mismatch row {r}");
17319        }
17320        println!(
17321            "q1t matvec {rows}x{cols} (1 thread): div-decode {slow_ms:.2} ms  fused-LUT {fast_ms:.2} ms  => {:.2}x",
17322            slow_ms / fast_ms
17323        );
17324    }
17325}
17326
17327#[cfg(test)]
17328mod row_span_tests {
17329    use cortiq_core::TensorDtype;
17330
17331    /// The three ranges `row_span_offsets` names are exactly what decoding a
17332    /// q4tp row reads: with every other byte of the tensor overwritten the
17333    /// row's nibbles and scales come back unchanged.
17334    #[test]
17335    fn q4tp_row_spans_cover_the_row() {
17336        let (rows, cols) = (37usize, 160usize);
17337        let gpr = cols / 32;
17338        let total = cortiq_core::quant::expected_nbytes(TensorDtype::Q4TiledP, &[rows, cols]).unwrap();
17339        let (params_off, _, _) = cortiq_core::quant::q4tp_sections(rows, cols);
17340        let mut bytes: Vec<u8> = (0..total).map(|i| (i * 61 % 251) as u8).collect();
17341        let lo = cortiq_core::quant::f32_to_f16(-4.0);
17342        let step = cortiq_core::quant::f32_to_f16(0.1);
17343        for r in 0..rows {
17344            let o = params_off + r * 4;
17345            bytes[o..o + 2].copy_from_slice(&lo.to_le_bytes());
17346            bytes[o + 2..o + 4].copy_from_slice(&step.to_le_bytes());
17347        }
17348        for r in [0usize, 1, 17, rows - 1] {
17349            let spans = super::row_span_offsets(TensorDtype::Q4TiledP, rows, cols, r).unwrap();
17350            assert_eq!(spans.iter().map(|s| s.1).sum::<usize>(), total / rows);
17351            let mut keep = vec![false; total];
17352            for &(o, n) in &spans {
17353                keep[o..o + n].fill(true);
17354            }
17355            let other: Vec<u8> =
17356                bytes.iter().zip(&keep).map(|(&b, &k)| if k { b } else { 0x5A }).collect();
17357            let (a, b) = (super::Q4tpView::new(&bytes, rows, cols), super::Q4tpView::new(&other, rows, cols));
17358            let (mut sa, mut sb) = (vec![0f32; gpr], vec![0f32; gpr]);
17359            a.scales_into(r, gpr, &mut sa);
17360            b.scales_into(r, gpr, &mut sb);
17361            assert_eq!(sa, sb, "row {r} scales");
17362            let nib = r * gpr * super::Q4TP_NIB..(r + 1) * gpr * super::Q4TP_NIB;
17363            assert_eq!(a.nib[nib.clone()], b.nib[nib], "row {r} nibbles");
17364        }
17365        assert!(super::row_span_offsets(TensorDtype::Q4TiledP, rows, cols, rows).is_none());
17366        assert!(super::row_span_offsets(TensorDtype::Q8_2f, rows, cols, 0).is_none());
17367        let t = super::row_span_offsets(TensorDtype::Q4Tiled, rows, cols, 3).unwrap();
17368        assert_eq!(t[0], (3 * gpr * super::Q4_TILE, gpr * super::Q4_TILE));
17369    }
17370}
17371
17372#[cfg(test)]
17373mod gemm_bench {
17374    /// `cargo test -p cortiq-engine --release q4tp_matmat_throughput -- --ignored --nocapture`
17375    /// Times the batched q4tp GEMM at the shapes the image DiT runs
17376    /// (b=296 tokens, 2304 -> 9216), on synthetic bytes: no model, no
17377    /// mmap, no thermal drift over minutes — a kernel change shows up
17378    /// here in seconds where a full render hides it in noise.
17379    ///
17380    /// On macOS add `CMF_ACCEL=0`: this shape is over the 500k-cell mark
17381    /// where the matmat hands off to Accelerate's dequant sgemm, and
17382    /// without the opt-out both rows below measure the AMX, not the
17383    /// kernel under test.
17384    #[test]
17385    #[ignore]
17386    fn q4tp_matmat_throughput() {
17387        let _alt = super::Q4TP_ALT_TEST_LOCK
17388            .lock()
17389            .unwrap_or_else(|e| e.into_inner());
17390        // 296 is a prompt-encode batch; the image DiT runs 2085 at
17391        // 512x512, where the activation panel stops fitting L2 and the
17392        // loop's shape starts to matter more than its instructions.
17393        let b: usize = std::env::var("CMF_BENCH_B")
17394            .ok()
17395            .and_then(|v| v.parse().ok())
17396            .unwrap_or(296);
17397        let (rows, cols) = (9216usize, 2304usize);
17398        let (_, _, _) = (rows, cols, b);
17399        let total =
17400            cortiq_core::quant::expected_nbytes(cortiq_core::TensorDtype::Q4TiledP, &[rows, cols])
17401                .unwrap();
17402        // Random nibbles are fine, but the row params are f16 (lo, step)
17403        // of a geometric ladder: garbage there gives exp2 of a huge
17404        // exponent, the scales come back inf, and the whole bench times
17405        // NaN arithmetic instead of the kernel.
17406        let (params_off, codes_off, _) = cortiq_core::quant::q4tp_sections(rows, cols);
17407        let mut bytes: Vec<u8> = (0..total).map(|i| (i * 37 % 251) as u8).collect();
17408        let lo = cortiq_core::quant::f32_to_f16(-4.0);
17409        let step = cortiq_core::quant::f32_to_f16(0.1);
17410        for r in 0..rows {
17411            let o = params_off + r * 4;
17412            bytes[o..o + 2].copy_from_slice(&lo.to_le_bytes());
17413            bytes[o + 2..o + 4].copy_from_slice(&step.to_le_bytes());
17414        }
17415        let _ = codes_off;
17416        let xs: Vec<f32> = (0..b * cols)
17417            .map(|i| ((i % 97) as f32 - 48.0) / 48.0)
17418            .collect();
17419        let mut out = vec![0f32; b * rows];
17420        let pool = crate::pool::Pool::from_env();
17421        // A shared 48-core stand drifts ±25% run to run, which is wider
17422        // than any kernel change worth making. So: alternate the two
17423        // kernels inside one process and keep the BEST time for
17424        // each. Interleaving makes both see the same interference, and a
17425        // minimum is the one statistic another tenant cannot inflate.
17426        super::q4tp_matmat(&bytes, &xs, b, rows, cols, &mut out, pool.as_deref());
17427        let reps: usize = std::env::var("CMF_BENCH_REPS")
17428            .ok()
17429            .and_then(|v| v.parse().ok())
17430            .unwrap_or(10);
17431        let mut best = [f64::MAX; 2];
17432        let mut sums = [0f32; 2];
17433        for _ in 0..reps {
17434            for (k, w) in [(0usize, 1u8), (1usize, 2u8)] {
17435                super::Q4TP_ALT.store(w, std::sync::atomic::Ordering::Relaxed);
17436                let t = std::time::Instant::now();
17437                super::q4tp_matmat(&bytes, &xs, b, rows, cols, &mut out, pool.as_deref());
17438                best[k] = best[k].min(t.elapsed().as_secs_f64());
17439                sums[k] = out.iter().take(64).sum::<f32>();
17440            }
17441        }
17442        let flops = 2.0 * b as f64 * rows as f64 * cols as f64;
17443        for (k, name) in ["previous", "tuned   "].iter().enumerate() {
17444            println!(
17445                "q4tp matmat {rows}x{cols} b={b} {name}: {:.1} ms  {:.1} GFLOP/s  (checksum {:.3})",
17446                best[k] * 1e3,
17447                flops / best[k] / 1e9,
17448                sums[k]
17449            );
17450        }
17451        assert!(
17452            (sums[0] - sums[1]).abs() < 1e-2,
17453            "the tuned kernel changed the result: {} vs {}",
17454            sums[0],
17455            sums[1]
17456        );
17457    }
17458
17459    /// The blocked kernel must agree with the per-column path exactly —
17460    /// same weights, same activation split, only a different instruction
17461    /// mix. Shapes are chosen to hit the awkward cases: a column count
17462    /// that leaves an odd group (the 512-bit kernel does two at a time),
17463    /// and a batch that does not divide by four.
17464    #[test]
17465    fn q4tp_matmat_blocked_matches_scalar() {
17466        use std::sync::atomic::Ordering::Relaxed;
17467        let _alt = super::Q4TP_ALT_TEST_LOCK
17468            .lock()
17469            .unwrap_or_else(|e| e.into_inner());
17470        // The last shape carries the image DiT's column count — 2304, so
17471        // 72 groups of accumulation, which is where a reordered sum can
17472        // actually drift — and runs through the thread pool, since the
17473        // blocked path splits rows across workers. Its row count stays
17474        // under 500k cells on purpose: above that, macOS diverts the whole
17475        // matmat to the Accelerate/AMX dequant sgemm and neither kernel
17476        // here would run.
17477        for &(rows, cols, b) in &[
17478            (64usize, 128usize, 7usize),
17479            (33, 96, 4),
17480            (16, 256, 9),
17481            (192, 2304, 37),
17482        ] {
17483            let total = cortiq_core::quant::expected_nbytes(
17484                cortiq_core::TensorDtype::Q4TiledP,
17485                &[rows, cols],
17486            )
17487            .unwrap();
17488            let (params_off, _, _) = cortiq_core::quant::q4tp_sections(rows, cols);
17489            let mut bytes: Vec<u8> = (0..total).map(|i| (i * 61 % 251) as u8).collect();
17490            let lo = cortiq_core::quant::f32_to_f16(-4.0);
17491            let step = cortiq_core::quant::f32_to_f16(0.1);
17492            for r in 0..rows {
17493                let o = params_off + r * 4;
17494                bytes[o..o + 2].copy_from_slice(&lo.to_le_bytes());
17495                bytes[o + 2..o + 4].copy_from_slice(&step.to_le_bytes());
17496            }
17497            let xs: Vec<f32> = (0..b * cols)
17498                .map(|i| ((i % 89) as f32 - 44.0) / 44.0)
17499                .collect();
17500            let mut got = vec![0f32; b * rows];
17501            let mut want = vec![0f32; b * rows];
17502            let gpr = cols / 32;
17503            let view = super::Q4tpView::new(&bytes, rows, cols);
17504            let pool = crate::pool::Pool::from_env();
17505            super::Q4TP_ALT.store(2, Relaxed);
17506            super::q4tp_matmat(&bytes, &xs, b, rows, cols, &mut got, pool.as_deref());
17507            super::Q4TP_ALT.store(1, Relaxed);
17508            super::q4tp_matmat(&bytes, &xs, b, rows, cols, &mut want, pool.as_deref());
17509            super::Q4TP_ALT.store(0, Relaxed);
17510            // Measured against the output's scale, not cell by cell: a
17511            // dot product of 2304 terms lands near zero wherever the row
17512            // and the activation nearly cancel, and there a per-cell
17513            // ratio reports 1e-3 for an absolute error of 5e-6 — f32's
17514            // own rounding, reordered. What must stay small is the error
17515            // relative to what the layer actually outputs.
17516            let scale = want.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6);
17517            let (mut worst, mut at) = (0f32, 0usize);
17518            for (i, (g, w)) in got.iter().zip(&want).enumerate() {
17519                if (g - w).abs() > worst {
17520                    worst = (g - w).abs();
17521                    at = i;
17522                }
17523            }
17524            assert!(
17525                worst <= 1e-4 * scale,
17526                "{rows}x{cols} b={b}: blocked and scalar disagree by {worst:.3e} \
17527                 (scale {scale:.3e}) at cell {at}: {} vs {}",
17528                got[at],
17529                want[at]
17530            );
17531
17532            // "Same speed, no quality loss" is a claim about which answer
17533            // is RIGHT, not about which two agree. Both paths sum the same
17534            // 2304 products in different orders, so f64 decides: the
17535            // blocked kernel keeps sixteen partial sums and folds them at
17536            // the end, which is a shallower addition tree than the
17537            // per-column path's running scalar, and it must not be worse.
17538            let (mut e_blocked, mut e_scalar) = (0f64, 0f64);
17539            for bi in 0..b {
17540                let act = super::split_act(&xs[bi * cols..(bi + 1) * cols]);
17541                for r in 0..rows {
17542                    let mut sc = vec![0f32; gpr];
17543                    view.scales_into(r, gpr, &mut sc);
17544                    let mut exact = 0f64;
17545                    for j in 0..cols {
17546                        let (w, sq) = super::q4tp_outlier(view.nib, r, gpr, j, &sc);
17547                        exact += w as f64 * sq as f64 * act.xq[j] as f64;
17548                    }
17549                    exact *= act.sx as f64;
17550                    for &(j, xv) in &act.outliers {
17551                        let (w, sq) = super::q4tp_outlier(view.nib, r, gpr, j, &sc);
17552                        exact += w as f64 * sq as f64 * xv as f64;
17553                    }
17554                    let i = bi * rows + r;
17555                    e_blocked = e_blocked.max((got[i] as f64 - exact).abs());
17556                    e_scalar = e_scalar.max((want[i] as f64 - exact).abs());
17557                }
17558            }
17559            println!(
17560                "{rows}x{cols} b={b}: worst error vs f64 — blocked {e_blocked:.3e}, \
17561                 per-column {e_scalar:.3e}"
17562            );
17563            // An absolute bar, not a race between the two: at these
17564            // magnitudes both sit in f32's last bits, and on a small shape
17565            // whichever one happens to round the unluckiest cell "wins" by
17566            // a factor the next seed reverses.
17567            assert!(
17568                e_blocked <= 1e-5 * scale as f64 && e_scalar <= 1e-5 * scale as f64,
17569                "{rows}x{cols} b={b}: error against f64 too large — blocked \
17570                 {e_blocked:.3e}, per-column {e_scalar:.3e}, scale {scale:.3e}"
17571            );
17572        }
17573    }
17574
17575    /// What the row-exact contract costs a speculative-verify panel on the
17576    /// host: the same batch through the fast arms, through the row-exact
17577    /// arms, and as one matvec per token (the other way to be exact).
17578    /// Arms alternate inside one process and keep their best time.
17579    /// `CMF_GPU=0 cargo test -p cortiq-engine --release q4tp_matmat_row_exact_cost -- --ignored --nocapture`
17580    #[test]
17581    #[ignore]
17582    fn q4tp_matmat_row_exact_cost() {
17583        let _alt = super::Q4TP_ALT_TEST_LOCK
17584            .lock()
17585            .unwrap_or_else(|e| e.into_inner());
17586        let pool = crate::pool::Pool::from_env();
17587        let reps: usize = std::env::var("CMF_BENCH_REPS")
17588            .ok()
17589            .and_then(|v| v.parse().ok())
17590            .unwrap_or(30);
17591        for &(rows, cols) in &[(2048usize, 4096usize), (4096, 2048), (4096, 4096)] {
17592            let total = cortiq_core::quant::expected_nbytes(
17593                cortiq_core::TensorDtype::Q4TiledP,
17594                &[rows, cols],
17595            )
17596            .unwrap();
17597            let (params_off, _, _) = cortiq_core::quant::q4tp_sections(rows, cols);
17598            let mut bytes: Vec<u8> = (0..total).map(|i| (i * 37 % 251) as u8).collect();
17599            let lo = cortiq_core::quant::f32_to_f16(-4.0);
17600            let step = cortiq_core::quant::f32_to_f16(0.1);
17601            for r in 0..rows {
17602                let o = params_off + r * 4;
17603                bytes[o..o + 2].copy_from_slice(&lo.to_le_bytes());
17604                bytes[o + 2..o + 4].copy_from_slice(&step.to_le_bytes());
17605            }
17606            for &b in &[2usize, 4, 5, 8] {
17607                let xs: Vec<f32> = (0..b * cols)
17608                    .map(|i| ((i % 97) as f32 - 48.0) / 48.0)
17609                    .collect();
17610                let mut out = vec![0f32; b * rows];
17611                let mut best = [f64::MAX; 3];
17612                for _ in 0..reps {
17613                    for (k, best_k) in best.iter_mut().enumerate() {
17614                        let t = std::time::Instant::now();
17615                        match k {
17616                            0 | 1 => super::q4tp_matmat_with(
17617                                &bytes,
17618                                &xs,
17619                                b,
17620                                rows,
17621                                cols,
17622                                &mut out,
17623                                pool.as_deref(),
17624                                k == 1,
17625                            ),
17626                            _ => {
17627                                for (bi, o) in out.chunks_mut(rows).enumerate() {
17628                                    super::q4tp_matvec(
17629                                        &bytes,
17630                                        &xs[bi * cols..(bi + 1) * cols],
17631                                        rows,
17632                                        cols,
17633                                        o,
17634                                        pool.as_deref(),
17635                                    );
17636                                }
17637                            }
17638                        }
17639                        *best_k = best_k.min(t.elapsed().as_secs_f64());
17640                    }
17641                }
17642                println!(
17643                    "q4tp {rows}x{cols} b={b}: fast {:.3} ms, row-exact {:.3} ms, \
17644                     {b} matvecs {:.3} ms",
17645                    best[0] * 1e3,
17646                    best[1] * 1e3,
17647                    best[2] * 1e3
17648                );
17649            }
17650        }
17651    }
17652
17653    /// The q4t twin of the throughput bench, same shape and rules, so the
17654    /// two quantisations' batch kernels can be read against each other.
17655    /// `cargo test -p cortiq-engine --release q4t_matmat_throughput -- --ignored --nocapture`
17656    #[test]
17657    #[ignore]
17658    fn q4t_matmat_throughput() {
17659        let (rows, cols, b) = (9216usize, 2304usize, 296usize);
17660        let total =
17661            cortiq_core::quant::expected_nbytes(cortiq_core::TensorDtype::Q4Tiled, &[rows, cols])
17662                .unwrap();
17663        // q4t carries a per-group f16 scale in the tile's first two bytes;
17664        // random bytes there decode to inf and the bench would time NaNs.
17665        let mut bytes: Vec<u8> = (0..total).map(|i| (i * 37 % 251) as u8).collect();
17666        let sc = cortiq_core::quant::f32_to_f16(0.02);
17667        for t in bytes.chunks_mut(super::Q4_TILE) {
17668            t[..2].copy_from_slice(&sc.to_le_bytes());
17669        }
17670        let xs: Vec<f32> = (0..b * cols)
17671            .map(|i| ((i % 97) as f32 - 48.0) / 48.0)
17672            .collect();
17673        let mut out = vec![0f32; b * rows];
17674        let pool = crate::pool::Pool::from_env();
17675        super::q4t_matmat(&bytes, &xs, b, rows, cols, &mut out, pool.as_deref());
17676        let reps: usize = std::env::var("CMF_BENCH_REPS")
17677            .ok()
17678            .and_then(|v| v.parse().ok())
17679            .unwrap_or(10);
17680        let mut best = f64::MAX;
17681        for _ in 0..reps {
17682            let t = std::time::Instant::now();
17683            super::q4t_matmat(&bytes, &xs, b, rows, cols, &mut out, pool.as_deref());
17684            best = best.min(t.elapsed().as_secs_f64());
17685        }
17686        let flops = 2.0 * b as f64 * rows as f64 * cols as f64;
17687        println!(
17688            "q4t matmat {rows}x{cols} b={b}: {:.1} ms  {:.1} GFLOP/s  (checksum {:.3})",
17689            best * 1e3,
17690            flops / best / 1e9,
17691            out.iter().take(64).sum::<f32>()
17692        );
17693    }
17694}
17695
17696#[cfg(all(test, target_arch = "x86_64"))]
17697mod x86_gemm_tests {
17698    use super::x86_gemm_rm;
17699
17700    /// The AVX2 two-row FMA q4tp batch kernel against the row-exact
17701    /// vertical cell (the matvec's bits): odd row counts (the last row
17702    /// takes the vertical cell), columns past a group of four, a wide
17703    /// row of 2560 columns (80 groups), outliers in the activations, and
17704    /// the pool. Measured against the output's scale, as the blocked
17705    /// kernel's test does.
17706    #[test]
17707    fn q4tp_fma_batch_matches_the_row_exact_cell() {
17708        if !super::q4tp_fma_x86() || !super::a8w8_enabled() {
17709            return;
17710        }
17711        let pool = crate::pool::Pool::from_env();
17712        for &(rows, cols, b) in &[(33usize, 96usize, 7usize), (64, 256, 13), (257, 2560, 37)] {
17713            let total = cortiq_core::quant::expected_nbytes(
17714                cortiq_core::TensorDtype::Q4TiledP,
17715                &[rows, cols],
17716            )
17717            .unwrap();
17718            let (params_off, _, _) = cortiq_core::quant::q4tp_sections(rows, cols);
17719            let mut bytes: Vec<u8> = (0..total).map(|i| (i * 61 % 251) as u8).collect();
17720            let lo = cortiq_core::quant::f32_to_f16(-4.0);
17721            let step = cortiq_core::quant::f32_to_f16(0.1);
17722            for r in 0..rows {
17723                let o = params_off + r * 4;
17724                bytes[o..o + 2].copy_from_slice(&lo.to_le_bytes());
17725                bytes[o + 2..o + 4].copy_from_slice(&step.to_le_bytes());
17726            }
17727            let mut xs: Vec<f32> = (0..b * cols)
17728                .map(|i| ((i * 37 % 89) as f32 - 44.0) / 44.0)
17729                .collect();
17730            for bi in (0..b).step_by(3) {
17731                xs[bi * cols + (bi * 7) % cols] = 40.0; // an outlier column
17732            }
17733            let mut got = vec![0f32; b * rows];
17734            let mut want = vec![0f32; b * rows];
17735            super::q4tp_matmat_with(&bytes, &xs, b, rows, cols, &mut got, pool.as_deref(), false);
17736            super::q4tp_matmat_with(&bytes, &xs, b, rows, cols, &mut want, pool.as_deref(), true);
17737            let scale = want.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6);
17738            let worst = got.iter().zip(&want).map(|(g, w)| (g - w).abs()).fold(0f32, f32::max);
17739            assert!(
17740                worst <= 1e-5 * scale,
17741                "{rows}x{cols} b={b}: FMA batch and row-exact cell disagree by {worst:.3e} (scale {scale:.3e})"
17742            );
17743        }
17744    }
17745
17746    #[allow(clippy::too_many_arguments)]
17747    fn naive(
17748        m: usize,
17749        n: usize,
17750        k: usize,
17751        alpha: f32,
17752        a: &[f32],
17753        lda: usize,
17754        b: &[f32],
17755        ldb: usize,
17756        b_rows_are_n: bool,
17757    ) -> Vec<f64> {
17758        let mut c = vec![0f64; m * n];
17759        for i in 0..m {
17760            for j in 0..n {
17761                let mut acc = 0f64;
17762                for p in 0..k {
17763                    let bv = if b_rows_are_n { b[j * ldb + p] } else { b[p * ldb + j] };
17764                    acc += a[i * lda + p] as f64 * bv as f64;
17765                }
17766                c[i * n + j] = acc * alpha as f64;
17767            }
17768        }
17769        c
17770    }
17771
17772    /// The AVX2 micro-GEMM against a double-precision triple loop: both
17773    /// B layouts, padded leading dimensions, shapes that exercise the
17774    /// 4×16 kernel, the row and column tails, and the k blocking (k >
17775    /// 256 resumes the accumulators from C).
17776    #[test]
17777    fn x86_gemm_matches_naive_on_odd_shapes() {
17778        for &(m, n, k) in &[
17779            (1usize, 1usize, 1usize),
17780            (4, 16, 256),
17781            (7, 37, 19),
17782            (9, 300, 257),
17783            (64, 1000, 256),
17784            (5, 256, 1001),
17785            (13, 129, 512),
17786            (8, 16, 0),
17787        ] {
17788            for &bt in &[false, true] {
17789                let (lda, ldb, ldc) = (k + 3, if bt { k + 2 } else { n + 5 }, n + 1);
17790                let a: Vec<f32> = (0..m * lda)
17791                    .map(|i| ((i * 7919) % 1000) as f32 / 500.0 - 1.0)
17792                    .collect();
17793                let brows = if bt { n } else { k.max(1) };
17794                let b: Vec<f32> = (0..brows * ldb)
17795                    .map(|i| ((i * 104_729) % 997) as f32 / 498.5 - 1.0)
17796                    .collect();
17797                let mut c = vec![f32::NAN; m * ldc];
17798                x86_gemm_rm(m, n, k, 0.37, &a, lda, &b, ldb, bt, &mut c, ldc);
17799                let r = naive(m, n, k, 0.37, &a, lda, &b, ldb, bt);
17800                for i in 0..m {
17801                    for j in 0..n {
17802                        let (x, y) = (c[i * ldc + j] as f64, r[i * n + j]);
17803                        assert!(
17804                            (x - y).abs() <= 1e-3 * (1.0 + y.abs()),
17805                            "m{m} n{n} k{k} bt{bt} [{i},{j}]: {x} vs {y}"
17806                        );
17807                    }
17808                    assert!(c[i * ldc + n].is_nan(), "m{m} n{n} k{k}: padding column written");
17809                }
17810            }
17811        }
17812    }
17813}