Skip to main content

kodamaembed_cpu/
gemm.rs

1//! C = A W^T + bias in FP32; all tiles reduce depth in one order, so bits ignore batch and workers.
2
3use crate::{math, workers::POOL};
4use rayon::prelude::*;
5
6/// A strip's rows and a panel's columns; a 6 x 16 tile holds twelve 8-lane accumulators.
7pub(crate) const MR: usize = 6;
8pub(crate) const NR: usize = 16;
9/// K block: a strip of A and a panel slice of W stay in L1 and L2 cache.
10pub(crate) const KC: usize = 256;
11/// Rows per task in long inputs, so a band of A stays in L2 across its panel tiles.
12const MC: usize = 16 * MR;
13/// Up to this many rows one band holds them all, so each panel tile is read once per K block.
14pub(crate) const SHORT_ROWS: usize = 256;
15/// Up to this many rows a band's K block of A fits a 32 KB L1 once gathered.
16const GATHER_ROWS: usize = 32 * 1024 / (KC * size_of::<f32>());
17/// Panels a band must feed before rereading gathered rows repays the copy.
18const GATHER_PANELS: usize = 12;
19/// AVX2 pair path: a depth block's two panel slices (16 KB) serve a chunk of strips from L1.
20#[cfg(target_arch = "x86_64")]
21const DEPTH: usize = 128;
22/// Strips whose sums wait on the stack between the AVX2 pair path's depth blocks.
23#[cfg(target_arch = "x86_64")]
24const CHUNK: usize = 8;
25/// Depth steps an AVX2 loop iteration: Gracemont mispredicts a 128-trip exit, not a 32-trip one.
26#[cfg(target_arch = "x86_64")]
27const STEPS: usize = 4;
28/// Depth steps ahead the AVX2 pair loop prefetches its panel lines, so their L2 hits do not stall.
29#[cfg(target_arch = "x86_64")]
30const AHEAD: usize = 8;
31
32/// Which microkernel runs the tiles.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum Kernel {
35    /// Eight-lane FMA (x86-64 with AVX2 and FMA).
36    #[cfg(target_arch = "x86_64")]
37    Avx2,
38    /// Avx2's operations in its order on four-lane vectors (64-bit ARM), so results keep its bits.
39    #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
40    Neon,
41    /// Plain Rust, for any processor.
42    Portable,
43}
44
45/// The instruction set as its maker spells it, for device names and messages.
46impl std::fmt::Display for Kernel {
47    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        formatter.write_str(match self {
49            #[cfg(target_arch = "x86_64")]
50            Self::Avx2 => "AVX2",
51            #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
52            Self::Neon => "NEON",
53            Self::Portable => "portable",
54        })
55    }
56}
57
58impl Kernel {
59    /// Whether this processor supports the explicitly selected kernel.
60    pub fn is_supported(self) -> bool {
61        match self {
62            #[cfg(target_arch = "x86_64")]
63            Self::Avx2 => is_x86_feature_detected!("avx2") && is_x86_feature_detected!("fma"),
64            #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
65            Self::Neon => true,
66            Self::Portable => true,
67        }
68    }
69
70    /// The fastest kernel this processor runs.
71    pub fn detect() -> Self {
72        #[cfg(target_arch = "x86_64")]
73        if is_x86_feature_detected!("avx2") && is_x86_feature_detected!("fma") {
74            return Self::Avx2;
75        }
76        #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
77        {
78            Self::Neon
79        }
80        #[cfg(not(all(target_arch = "aarch64", target_feature = "neon")))]
81        {
82            Self::Portable
83        }
84    }
85}
86
87/// A weight W [n, k] (output by input) packed for the microkernel.
88pub struct PackedWeight {
89    n: usize,
90    k: usize,
91    panels: Vec<f32>,
92}
93
94impl PackedWeight {
95    pub fn new(w: &[f32], n: usize, k: usize) -> Self {
96        assert!(n > 0 && k > 0, "positive dimensions");
97        let elements = n.checked_mul(k).expect("dimensions overflow");
98        assert_eq!(w.len(), elements);
99        let mut panels = vec![0.0; panels_len(n, k)];
100        pack_rows(w, k, n, k, &mut panels);
101        Self { n, k, panels }
102    }
103
104    pub fn n(&self) -> usize {
105        self.n
106    }
107
108    pub fn k(&self) -> usize {
109        self.k
110    }
111
112    #[cfg(target_arch = "x86_64")]
113    pub(crate) fn rows(&self) -> Vec<f32> {
114        let mut rows = vec![0.0; self.n * self.k];
115        for (j, row) in rows.chunks_exact_mut(self.k).enumerate() {
116            let panel = &self.panels[j / NR * self.k * NR..];
117            for (i, value) in row.iter_mut().enumerate() {
118                *value = panel[i * NR + j % NR];
119            }
120        }
121        rows
122    }
123
124    fn columns(&self, first: usize, end: usize) -> Panels<'_> {
125        Panels {
126            values: &self.panels[first * self.k * NR..end * self.k * NR],
127            n: (end * NR).min(self.n) - first * NR,
128            k: self.k,
129        }
130    }
131}
132
133/// Columns in NR-wide panels laid out [k][NR], zero past n.
134#[derive(Clone, Copy)]
135pub(crate) struct Panels<'a> {
136    pub(crate) values: &'a [f32],
137    pub(crate) n: usize,
138    pub(crate) k: usize,
139}
140
141impl<'a> Panels<'a> {
142    /// K block `k0..k0 + kc` of panels `p..p + width`.
143    fn slices(&self, p: usize, width: usize, k0: usize, kc: usize) -> Slices<'a> {
144        let k = self.k;
145        Slices {
146            values: &self.values[(p * k + k0) * NR..((p + width - 1) * k + k0 + kc) * NR],
147            next: k * NR,
148            width,
149        }
150    }
151}
152
153/// One K block of `width` adjacent panels, `next` floats apart.
154#[derive(Clone, Copy)]
155struct Slices<'a> {
156    values: &'a [f32],
157    next: usize,
158    width: usize,
159}
160
161/// Runs of `span` whole panels, then each panel left over, as (first, width).
162fn panel_groups(panels: usize, whole: usize, span: usize) -> impl Iterator<Item = (usize, usize)> {
163    let grouped = whole - whole % span;
164    (0..grouped)
165        .step_by(span)
166        .map(move |p| (p, span))
167        .chain((grouped..panels).map(|p| (p, 1)))
168}
169
170pub(crate) fn panels_len(n: usize, k: usize) -> usize {
171    let elements = n
172        .div_ceil(NR)
173        .checked_mul(k)
174        .and_then(|size| size.checked_mul(NR))
175        .expect("dimensions overflow");
176    assert!(
177        elements <= isize::MAX as usize / size_of::<f32>(),
178        "packed dimensions exceed addressable memory"
179    );
180    elements
181}
182
183pub(crate) fn pack_rows(source: &[f32], stride: usize, n: usize, k: usize, out: &mut [f32]) {
184    for (p, panel) in out[..panels_len(n, k)].chunks_exact_mut(k * NR).enumerate() {
185        let cols = NR.min(n - p * NR);
186        if cols < NR {
187            panel.fill(0.0);
188        }
189        for col in 0..cols {
190            let row = &source[(p * NR + col) * stride..][..k];
191            for (i, &value) in row.iter().enumerate() {
192                panel[i * NR + col] = value;
193            }
194        }
195    }
196}
197
198pub(crate) fn pack_columns(source: &[f32], stride: usize, n: usize, k: usize, out: &mut [f32]) {
199    for (p, panel) in out[..panels_len(n, k)].chunks_exact_mut(k * NR).enumerate() {
200        let cols = NR.min(n - p * NR);
201        for (i, row) in panel.as_chunks_mut::<NR>().0.iter_mut().enumerate() {
202            row[..cols].copy_from_slice(&source[i * stride + p * NR..][..cols]);
203            row[cols..].fill(0.0);
204        }
205    }
206}
207
208/// What is applied to A W^T before it is stored in C [m, n].
209#[derive(Clone, Copy)]
210pub enum Epilogue<'a> {
211    /// + bias (n values)
212    Bias(&'a [f32]),
213    /// gelu(. + bias)
214    BiasGelu(&'a [f32]),
215    /// . + bias + residual [m, n]
216    BiasResidual(&'a [f32], &'a [f32]),
217}
218
219impl<'a> Epilogue<'a> {
220    fn bias(&self) -> &[f32] {
221        match self {
222            Self::Bias(bias) | Self::BiasGelu(bias) | Self::BiasResidual(bias, _) => bias,
223        }
224    }
225
226    fn columns_from(self, col: usize) -> Epilogue<'a> {
227        match self {
228            Self::Bias(bias) => Self::Bias(&bias[col..]),
229            Self::BiasGelu(bias) => Self::BiasGelu(&bias[col..]),
230            Self::BiasResidual(bias, residual) => {
231                Self::BiasResidual(&bias[col..], &residual[col..])
232            }
233        }
234    }
235}
236
237/// c [m, n] = epilogue(a [m, k] W^T) on KodamaEmbed's worker threads.
238pub fn gemm(
239    kernel: Kernel,
240    a: &[f32],
241    m: usize,
242    w: &PackedWeight,
243    epilogue: Epilogue,
244    c: &mut [f32],
245) {
246    assert!(
247        kernel.is_supported(),
248        "kernel {kernel} is unavailable on this processor"
249    );
250    let (n, k) = (w.n, w.k);
251    let a_len = m.checked_mul(k).expect("dimensions overflow");
252    let c_len = m.checked_mul(n).expect("dimensions overflow");
253    assert!(
254        a.len() >= a_len && c.len() >= c_len,
255        "a is m x k and c m x n"
256    );
257    assert!(epilogue.bias().len() >= n, "bias per column");
258    if let Epilogue::BiasResidual(_, residual) = epilogue {
259        assert!(residual.len() >= c_len, "residual too short");
260    }
261    if m == 0 {
262        return;
263    }
264    POOL.install(|| gemm_current_pool(kernel, a, m, w, epilogue, c));
265}
266
267/// Executes in the caller-selected Rayon pool; encoder callers install it once.
268pub(crate) fn gemm_current_pool(
269    kernel: Kernel,
270    a: &[f32],
271    m: usize,
272    w: &PackedWeight,
273    epilogue: Epilogue,
274    c: &mut [f32],
275) {
276    assert!(
277        kernel.is_supported(),
278        "kernel {kernel} is unavailable on this processor"
279    );
280    let (n, k) = (w.n, w.k);
281    let a_len = m.checked_mul(k).expect("dimensions overflow");
282    let c_len = m.checked_mul(n).expect("dimensions overflow");
283    assert!(
284        a.len() >= a_len && c.len() >= c_len,
285        "a is m x k and c m x n"
286    );
287    assert!(epilogue.bias().len() >= n, "bias per column");
288    if let Epilogue::BiasResidual(_, residual) = epilogue {
289        assert!(residual.len() >= c_len, "residual too short");
290    }
291    if m == 0 {
292        return;
293    }
294    let panels = n.div_ceil(NR);
295    // Short inputs: one band, an equal run of panels per worker; long inputs: bands by runs of
296    // `span` panels. A job per task, so a worker that runs out takes any task left.
297    let (height, runs) = if m <= SHORT_ROWS {
298        (m, rayon::current_num_threads().min(panels))
299    } else {
300        (MC, panels.div_ceil(kernel.span()))
301    };
302    let out = SharedOut(c.as_mut_ptr());
303    (0..m.div_ceil(height) * runs)
304        .into_par_iter()
305        .with_max_len(1)
306        .for_each(|task| {
307            let (row0, run) = (task / runs * height, task % runs);
308            let (first, end) = (run * panels / runs, (run + 1) * panels / runs);
309            let band = Band {
310                kernel,
311                a: &a[row0 * k..],
312                lda: k,
313                rows: height.min(m - row0),
314                panels: w.columns(first, end),
315                ldc: n,
316                epilogue: Some(Placed {
317                    epilogue: epilogue.columns_from(first * NR),
318                    row0,
319                    stride: n,
320                }),
321            };
322            // SAFETY: C holds m rows of n values, and a task writes only its band of its panels.
323            unsafe { band.run(out.at(row0 * n + first * NR)) };
324        });
325}
326
327/// Tasks' tiles interleave in memory, which disjoint slices cannot express.
328#[derive(Clone, Copy)]
329struct SharedOut(*mut f32);
330
331// SAFETY: each task writes only its own cells.
332unsafe impl Send for SharedOut {}
333// SAFETY: as above.
334unsafe impl Sync for SharedOut {}
335
336impl SharedOut {
337    /// A method, so closures capture the Sync wrapper, not its raw pointer.
338    ///
339    /// # Safety
340    /// `offset` is inside C.
341    unsafe fn at(self, offset: usize) -> *mut f32 {
342        // SAFETY: the caller vouches for offset.
343        unsafe { self.0.add(offset) }
344    }
345}
346
347/// c [rows, ldc] = a [rows, lda] W^T on the calling thread, without an epilogue.
348pub(crate) fn product(
349    kernel: Kernel,
350    a: &[f32],
351    lda: usize,
352    rows: usize,
353    panels: Panels,
354    c: &mut [f32],
355    ldc: usize,
356) {
357    if rows == 0 {
358        return;
359    }
360    assert!(c.len() >= (rows - 1) * ldc + panels.n, "c holds the rows");
361    let band = Band {
362        kernel,
363        a,
364        lda,
365        rows,
366        panels,
367        ldc,
368        epilogue: None,
369    };
370    // SAFETY: c holds the rows (asserted) and is this call's alone.
371    unsafe { band.run(c.as_mut_ptr()) };
372}
373
374/// # Safety
375/// As for [`Kernel::tile`], on a processor with AVX2 and FMA.
376#[cfg(target_arch = "x86_64")]
377#[target_feature(enable = "avx2,fma")]
378#[inline]
379#[allow(clippy::too_many_arguments)]
380unsafe fn tile_rows_avx2<const R: usize>(
381    kc: usize,
382    a: *const f32,
383    lda: usize,
384    panel: *const f32,
385    c: *mut f32,
386    ldc: usize,
387    first: bool,
388    finish: Option<Finish>,
389) {
390    use std::arch::x86_64::*;
391    // SAFETY: the caller vouches for every address read and written.
392    unsafe {
393        let mut acc = [[_mm256_setzero_ps(); 2]; R];
394        steps(0..kc, |p| {
395            let b0 = _mm256_loadu_ps(panel.add(p * NR));
396            let b1 = _mm256_loadu_ps(panel.add(p * NR + 8));
397            for (r, row) in acc.iter_mut().enumerate() {
398                let value = _mm256_broadcast_ss(&*a.add(r * lda + p));
399                row[0] = _mm256_fmadd_ps(value, b0, row[0]);
400                row[1] = _mm256_fmadd_ps(value, b1, row[1]);
401            }
402        });
403        for (r, &row) in acc.iter().enumerate() {
404            store_avx2(row, c, ldc, r, first, finish);
405        }
406    }
407}
408
409/// tile_rows_avx2's multiply-adds in its order, four lanes at a time.
410///
411/// # Safety
412/// As for [`Kernel::tile`], on a processor with NEON.
413#[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
414#[target_feature(enable = "neon")]
415#[inline]
416#[allow(clippy::too_many_arguments)]
417unsafe fn tile_rows_neon<const R: usize>(
418    kc: usize,
419    a: *const f32,
420    lda: usize,
421    panel: *const f32,
422    c: *mut f32,
423    ldc: usize,
424    first: bool,
425    finish: Option<Finish>,
426) {
427    use std::arch::aarch64::*;
428    // SAFETY: the caller vouches for every address read and written.
429    unsafe {
430        let mut acc = [[vdupq_n_f32(0.0); NR / 4]; R];
431        for p in 0..kc {
432            let columns: [float32x4_t; NR / 4] =
433                std::array::from_fn(|q| vld1q_f32(panel.add(p * NR + 4 * q)));
434            for (r, row) in acc.iter_mut().enumerate() {
435                let value = *a.add(r * lda + p);
436                for (sum, &column) in row.iter_mut().zip(&columns) {
437                    *sum = vfmaq_n_f32(*sum, column, value);
438                }
439            }
440        }
441        for (r, row) in acc.iter().enumerate() {
442            for (q, &sum) in row.iter().enumerate() {
443                let at = c.add(r * ldc + 4 * q);
444                let mut value = if first {
445                    sum
446                } else {
447                    vaddq_f32(vld1q_f32(at), sum)
448                };
449                if let Some(finish) = finish {
450                    value = vaddq_f32(value, vld1q_f32(finish.bias.add(4 * q)));
451                    if finish.gelu {
452                        value = math::neon::gelu_unbounded(value);
453                    }
454                    if !finish.residual.is_null() {
455                        let residual = finish.residual.add(r * finish.stride + 4 * q);
456                        value = vaddq_f32(value, vld1q_f32(residual));
457                    }
458                }
459                vst1q_f32(at, value);
460            }
461        }
462    }
463}
464
465/// # Safety
466/// As for [`Kernel::tile`].
467#[inline]
468#[allow(clippy::too_many_arguments)]
469unsafe fn tile_rows_portable<const R: usize>(
470    kc: usize,
471    a: *const f32,
472    lda: usize,
473    panel: *const f32,
474    c: *mut f32,
475    ldc: usize,
476    first: bool,
477    finish: Option<Finish>,
478) {
479    let mut acc = [[0.0f32; NR]; R];
480    for p in 0..kc {
481        // SAFETY: the caller vouches for every address read.
482        let b = unsafe { std::slice::from_raw_parts(panel.add(p * NR), NR) };
483        for (r, row) in acc.iter_mut().enumerate() {
484            // SAFETY: as above.
485            let a = unsafe { *a.add(r * lda + p) };
486            for (sum, &value) in row.iter_mut().zip(b) {
487                *sum += a * value;
488            }
489        }
490    }
491    for (r, row) in acc.iter().enumerate() {
492        for (j, &sum) in row.iter().enumerate() {
493            // SAFETY: the caller vouches for the tile at c and for finish.
494            unsafe {
495                let at = c.add(r * ldc + j);
496                let mut value = if first { sum } else { *at + sum };
497                if let Some(finish) = finish {
498                    value += *finish.bias.add(j);
499                    if finish.gelu {
500                        value = math::gelu_unbounded(value);
501                    }
502                    if !finish.residual.is_null() {
503                        value += *finish.residual.add(r * finish.stride + j);
504                    }
505                }
506                *at = value;
507            }
508        }
509    }
510}
511
512/// Rows of A by a run of panels: one task's share of a GEMM.
513struct Band<'a> {
514    kernel: Kernel,
515    a: &'a [f32],
516    lda: usize,
517    rows: usize,
518    panels: Panels<'a>,
519    ldc: usize,
520    epilogue: Option<Placed<'a>>,
521}
522
523#[derive(Clone, Copy)]
524struct Placed<'a> {
525    epilogue: Epilogue<'a>,
526    row0: usize,
527    stride: usize,
528}
529
530#[derive(Clone, Copy)]
531struct Tile {
532    row: usize,
533    rows: usize,
534    col: usize,
535    cols: usize,
536}
537
538#[derive(Clone, Copy)]
539struct Finish {
540    bias: *const f32,
541    gelu: bool,
542    /// Null without a residual.
543    residual: *const f32,
544    stride: usize,
545}
546
547impl Band<'_> {
548    /// # Safety
549    /// `c` covers `rows` rows of `panels.n` values `ldc` apart that no other thread touches.
550    unsafe fn run(&self, c: *mut f32) {
551        let k = self.panels.k;
552        assert!(
553            self.a.len() >= (self.rows - 1) * self.lda + k,
554            "a holds the band's rows"
555        );
556        // Rows reread by many panels come from one contiguous copy in L1, not scattered rows.
557        let gather = self.rows <= GATHER_ROWS && self.panels.n >= GATHER_PANELS * NR;
558        let mut gathered = Vec::with_capacity(if gather { self.rows * KC } else { 0 });
559        for k0 in (0..k).step_by(KC) {
560            let kc = KC.min(k - k0);
561            let (a, lda) = if gather {
562                gathered.clear();
563                for r in 0..self.rows {
564                    gathered.extend_from_slice(&self.a[r * self.lda + k0..][..kc]);
565                }
566                (gathered.as_ptr(), kc)
567            } else {
568                (self.a[k0..].as_ptr(), self.lda)
569            };
570            // SAFETY: the caller vouches for c, and a holds the band's K block, rows lda apart.
571            unsafe { self.block(k0, kc, a, lda, c) };
572        }
573    }
574
575    /// One K block: whole panels' strips and row tails straight into C, a partial panel padded.
576    ///
577    /// # Safety
578    /// As for [`Band::run`], with `a` at this K block's first depth, rows `lda` apart.
579    unsafe fn block(&self, k0: usize, kc: usize, a: *const f32, lda: usize, c: *mut f32) {
580        let (n, k, ldc) = (self.panels.n, self.panels.k, self.ldc);
581        let (full, rest, whole) = (self.rows / MR, self.rows % MR, n / NR);
582        let (first, epilogue) = (k0 == 0, if k0 + kc == k { self.epilogue } else { None });
583        for (p, width) in panel_groups(n.div_ceil(NR), whole, self.kernel.span()) {
584            let slices = self.panels.slices(p, width, k0, kc);
585            if p == whole {
586                for row in (0..self.rows).step_by(MR) {
587                    let (rows, col) = (MR.min(self.rows - row), p * NR);
588                    let tile = Tile {
589                        row,
590                        rows,
591                        col,
592                        cols: n - col,
593                    };
594                    // SAFETY: the caller vouches for c and a.
595                    unsafe { self.edge(kc, a, lda, slices.values, c, tile, first, epilogue) };
596                }
597                continue;
598            }
599            if full > 0 {
600                let finish = self.finish(epilogue, 0, full * MR, p * NR, width * NR);
601                // SAFETY: as above.
602                unsafe {
603                    let c = c.add(p * NR);
604                    self.kernel
605                        .run(kc, a, lda, full, slices, c, ldc, first, finish);
606                }
607            }
608            if rest > 0 {
609                for q in 0..width {
610                    let (row, col) = (full * MR, (p + q) * NR);
611                    let finish = self.finish(epilogue, row, rest, col, NR);
612                    let panel = slices.values[q * slices.next..].as_ptr();
613                    // SAFETY: as above.
614                    unsafe {
615                        let (a, c) = (a.add(row * lda), c.add(row * ldc + col));
616                        self.kernel
617                            .tile(rest, kc, a, lda, panel, c, ldc, first, finish);
618                    }
619                }
620            }
621        }
622    }
623
624    fn finish(
625        &self,
626        epilogue: Option<Placed>,
627        row: usize,
628        rows: usize,
629        col: usize,
630        cols: usize,
631    ) -> Option<Finish> {
632        epilogue.map(
633            |Placed {
634                 epilogue,
635                 row0,
636                 stride,
637             }| Finish {
638                bias: epilogue.bias()[col..col + cols].as_ptr(),
639                gelu: matches!(epilogue, Epilogue::BiasGelu(_)),
640                residual: match epilogue {
641                    Epilogue::BiasResidual(_, residual) => {
642                        let at = (row0 + row) * stride + col;
643                        residual[at..at + (rows - 1) * stride + cols].as_ptr()
644                    }
645                    _ => std::ptr::null(),
646                },
647                stride,
648            },
649        )
650    }
651
652    /// Padded storage, same reduction order: edge tiles match full ones.
653    ///
654    /// # Safety
655    /// As for [`Band::block`].
656    #[allow(clippy::too_many_arguments)]
657    unsafe fn edge(
658        &self,
659        kc: usize,
660        a: *const f32,
661        lda: usize,
662        panel: &[f32],
663        c: *mut f32,
664        tile: Tile,
665        first: bool,
666        epilogue: Option<Placed>,
667    ) {
668        let ldc = self.ldc;
669        let mut buffer = [0.0f32; MR * NR];
670        let mut bias = [0.0f32; NR];
671        let mut residual = [0.0f32; MR * NR];
672        for r in 0..tile.rows {
673            let at = (tile.row + r) * ldc + tile.col;
674            // SAFETY: the caller vouches for the tile's cells at c.
675            let row = unsafe { std::slice::from_raw_parts(c.add(at), tile.cols) };
676            buffer[r * NR..r * NR + tile.cols].copy_from_slice(row);
677        }
678        let finish = epilogue.map(
679            |Placed {
680                 epilogue,
681                 row0,
682                 stride,
683             }| {
684                bias[..tile.cols].copy_from_slice(&epilogue.bias()[tile.col..tile.col + tile.cols]);
685                let with_residual = if let Epilogue::BiasResidual(_, source) = epilogue {
686                    for r in 0..tile.rows {
687                        let at = (row0 + tile.row + r) * stride + tile.col;
688                        residual[r * NR..r * NR + tile.cols]
689                            .copy_from_slice(&source[at..at + tile.cols]);
690                    }
691                    true
692                } else {
693                    false
694                };
695                Finish {
696                    bias: bias.as_ptr(),
697                    gelu: matches!(epilogue, Epilogue::BiasGelu(_)),
698                    residual: if with_residual {
699                        residual.as_ptr()
700                    } else {
701                        std::ptr::null()
702                    },
703                    stride: NR,
704                }
705            },
706        );
707        // SAFETY: the buffers hold a tile, and the caller vouches for a.
708        unsafe {
709            let (a, panel, out) = (a.add(tile.row * lda), panel.as_ptr(), buffer.as_mut_ptr());
710            self.kernel
711                .tile(tile.rows, kc, a, lda, panel, out, NR, first, finish);
712        }
713        for r in 0..tile.rows {
714            let at = (tile.row + r) * ldc + tile.col;
715            // SAFETY: as above, and no other thread touches these cells.
716            let row = unsafe { std::slice::from_raw_parts_mut(c.add(at), tile.cols) };
717            row.copy_from_slice(&buffer[r * NR..r * NR + tile.cols]);
718        }
719    }
720}
721
722impl Finish {
723    /// # Safety
724    /// A residual must extend that far.
725    unsafe fn down(self, rows: usize) -> Self {
726        Self {
727            residual: if self.residual.is_null() {
728                self.residual
729            } else {
730                // SAFETY: the caller vouches for the residual's extent.
731                unsafe { self.residual.add(rows * self.stride) }
732            },
733            ..self
734        }
735    }
736}
737
738impl Kernel {
739    /// Whole panels one [`Kernel::run`] call covers: AVX2 pairs them for its 3 x 32 tiles.
740    fn span(self) -> usize {
741        match self {
742            #[cfg(target_arch = "x86_64")]
743            Self::Avx2 => 2,
744            #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
745            Self::Neon => 1,
746            Self::Portable => 1,
747        }
748    }
749
750    /// # Safety
751    /// `a` holds `count` * MR rows of `kc` values `lda` apart, and `c` and `finish` those rows of
752    /// `slices.width` * NR values.
753    #[allow(clippy::too_many_arguments)]
754    unsafe fn run(
755        self,
756        kc: usize,
757        a: *const f32,
758        lda: usize,
759        count: usize,
760        slices: Slices,
761        c: *mut f32,
762        ldc: usize,
763        first: bool,
764        finish: Option<Finish>,
765    ) {
766        assert!(
767            (1..=self.span()).contains(&slices.width)
768                && slices.values.len() >= (slices.width - 1) * slices.next + kc * NR
769        );
770        #[cfg(target_arch = "x86_64")]
771        if self == Self::Avx2 && slices.width == 2 {
772            // SAFETY: Avx2 implies AVX2 and FMA; the caller vouches for every address.
773            unsafe { pairs_avx2(kc, count, a, lda, slices, c, ldc, first, finish) };
774            return;
775        }
776        for s in 0..count {
777            // SAFETY: the caller vouches for every strip's rows at a, c and in finish.
778            unsafe {
779                let (a, c) = (a.add(s * MR * lda), c.add(s * MR * ldc));
780                let finish = finish.map(|finish| finish.down(s * MR));
781                self.tile(
782                    MR,
783                    kc,
784                    a,
785                    lda,
786                    slices.values.as_ptr(),
787                    c,
788                    ldc,
789                    first,
790                    finish,
791                );
792            }
793        }
794    }
795
796    /// # Safety
797    /// `a` holds `rows` (1 to MR) rows of `kc` values `lda` apart, `panel` kc * NR values, and `c`
798    /// and `finish` those rows of NR values.
799    #[allow(clippy::too_many_arguments)]
800    unsafe fn tile(
801        self,
802        rows: usize,
803        kc: usize,
804        a: *const f32,
805        lda: usize,
806        panel: *const f32,
807        c: *mut f32,
808        ldc: usize,
809        first: bool,
810        finish: Option<Finish>,
811    ) {
812        // Specializing row tails avoids padding work without changing reduction order.
813        macro_rules! tile {
814            ($kernel:ident) => {
815                match rows {
816                    1 => $kernel::<1>(kc, a, lda, panel, c, ldc, first, finish),
817                    2 => $kernel::<2>(kc, a, lda, panel, c, ldc, first, finish),
818                    3 => $kernel::<3>(kc, a, lda, panel, c, ldc, first, finish),
819                    4 => $kernel::<4>(kc, a, lda, panel, c, ldc, first, finish),
820                    5 => $kernel::<5>(kc, a, lda, panel, c, ldc, first, finish),
821                    _ => $kernel::<MR>(kc, a, lda, panel, c, ldc, first, finish),
822                }
823            };
824        }
825        // SAFETY: the caller vouches for every address; the entry points check the features.
826        unsafe {
827            match self {
828                #[cfg(target_arch = "x86_64")]
829                Self::Avx2 => tile!(tile_rows_avx2),
830                #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
831                Self::Neon => tile!(tile_rows_neon),
832                Self::Portable => tile!(tile_rows_portable),
833            }
834        }
835    }
836}
837
838/// Strips by a panel pair as 3 x 32 tiles: half 6 x 16's broadcasts, each an extra uop on E-cores.
839///
840/// # Safety
841/// AVX2 and FMA; `a` holds `count` * MR rows of `kc` values `lda` apart, `slices` two panels, and
842/// `c` and `finish` those rows of 2NR values.
843#[cfg(target_arch = "x86_64")]
844#[target_feature(enable = "avx2,fma")]
845#[allow(clippy::too_many_arguments)]
846unsafe fn pairs_avx2(
847    kc: usize,
848    count: usize,
849    a: *const f32,
850    lda: usize,
851    slices: Slices,
852    c: *mut f32,
853    ldc: usize,
854    first: bool,
855    finish: Option<Finish>,
856) {
857    use std::arch::x86_64::*;
858    use std::mem::MaybeUninit;
859    let (b, next) = (slices.values.as_ptr(), slices.next);
860    let zero: Triple = [[_mm256_setzero_ps(); 4]; 3];
861    for chunk in (0..count).step_by(CHUNK) {
862        let strips = CHUNK.min(count - chunk);
863        let mut carried: [[Carry; 2]; CHUNK] = [[[MaybeUninit::uninit(); 12]; 2]; CHUNK];
864        for start in (0..kc).step_by(DEPTH) {
865            let depths = start..kc.min(start + DEPTH);
866            for (s, carries) in carried[..strips].iter_mut().enumerate() {
867                for (t, carry) in carries.iter_mut().enumerate() {
868                    // SAFETY: the caller vouches for the rows and panel slices read, and a carry
869                    // is read only after the previous depth block wrote it.
870                    let sums = unsafe {
871                        let a = a.add(((chunk + s) * MR + 3 * t) * lda);
872                        let from = if start == 0 {
873                            zero
874                        } else {
875                            std::array::from_fn(|r| {
876                                std::array::from_fn(|h| carry[4 * r + h].assume_init())
877                            })
878                        };
879                        triple_avx2(a, lda, b, next, depths.clone(), from)
880                    };
881                    for (slot, &sum) in carry.iter_mut().zip(sums.as_flattened()) {
882                        slot.write(sum);
883                    }
884                    if depths.end == kc {
885                        let row = (chunk + s) * MR + 3 * t;
886                        // SAFETY: the caller vouches for these rows at c and in finish, and every
887                        // slot was just written.
888                        unsafe { finish_triple_avx2(carry, c, ldc, row, first, finish) };
889                    }
890                }
891            }
892        }
893    }
894}
895
896/// Stores a 3 x 32 tile's sums at row `row`: out of line, so the pair loop keeps its registers.
897///
898/// # Safety
899/// AVX2 and FMA; every slot written, and rows `row..row + 3` of 2NR values at `c` and in `finish`.
900#[cfg(target_arch = "x86_64")]
901#[target_feature(enable = "avx2,fma")]
902#[inline(never)]
903unsafe fn finish_triple_avx2(
904    sums: &Carry,
905    c: *mut f32,
906    ldc: usize,
907    row: usize,
908    first: bool,
909    finish: Option<Finish>,
910) {
911    // SAFETY: the caller vouches for every slot and address.
912    unsafe {
913        let (c, finish) = (c.add(row * ldc), finish.map(|finish| finish.down(row)));
914        for (r, slots) in sums.as_chunks::<4>().0.iter().enumerate() {
915            let values = slots.map(|slot| slot.assume_init());
916            store_avx2(values, c, ldc, r, first, finish);
917        }
918    }
919}
920
921#[cfg(target_arch = "x86_64")]
922type Triple = [[std::arch::x86_64::__m256; 4]; 3];
923
924/// A 3 x 32 tile's sums between depth blocks, a slot per vector: a whole-Triple copy is a memmove.
925#[cfg(target_arch = "x86_64")]
926type Carry = [std::mem::MaybeUninit<std::arch::x86_64::__m256>; 12];
927
928/// Three rows by two panels over `depths`, from `acc`: 12 sums, 3 held A values, 1 B vector.
929///
930/// # Safety
931/// As for [`pairs_avx2`], for these three rows and depths.
932#[cfg(target_arch = "x86_64")]
933#[target_feature(enable = "avx2,fma")]
934#[inline]
935unsafe fn triple_avx2(
936    a: *const f32,
937    lda: usize,
938    b: *const f32,
939    next: usize,
940    depths: std::ops::Range<usize>,
941    mut acc: Triple,
942) -> Triple {
943    use std::arch::x86_64::*;
944    steps(depths, |p| {
945        // SAFETY: the caller vouches for every address read; a prefetch never faults.
946        unsafe {
947            _mm_prefetch::<_MM_HINT_T0>(b.wrapping_add((p + AHEAD) * NR).cast());
948            _mm_prefetch::<_MM_HINT_T0>(b.wrapping_add(next + (p + AHEAD) * NR).cast());
949            let values: [__m256; 3] =
950                std::array::from_fn(|r| _mm256_broadcast_ss(&*a.add(r * lda + p)));
951            for j in 0..4 {
952                let column = _mm256_loadu_ps(b.add(j / 2 * next + p * NR + j % 2 * 8));
953                for (row, &value) in acc.iter_mut().zip(&values) {
954                    row[j] = _mm256_fmadd_ps(value, column, row[j]);
955                }
956            }
957        }
958    });
959    acc
960}
961
962/// `step(p)` for every depth in `depths`, STEPS an iteration.
963#[cfg(target_arch = "x86_64")]
964#[inline(always)]
965fn steps(depths: std::ops::Range<usize>, mut step: impl FnMut(usize)) {
966    let (mut p, end) = (depths.start, depths.end);
967    while p + STEPS <= end {
968        for u in 0..STEPS {
969            step(p + u);
970        }
971        p += STEPS;
972    }
973    for p in p..end {
974        step(p);
975    }
976}
977
978/// A row's vectors take GELU together, so their dependent chains overlap.
979///
980/// # Safety
981/// AVX2 and FMA; row `r`'s N vectors at `c` and in `finish`.
982#[cfg(target_arch = "x86_64")]
983#[target_feature(enable = "avx2,fma")]
984#[inline]
985unsafe fn store_avx2<const N: usize>(
986    sums: [std::arch::x86_64::__m256; N],
987    c: *mut f32,
988    ldc: usize,
989    r: usize,
990    first: bool,
991    finish: Option<Finish>,
992) {
993    use std::arch::x86_64::*;
994    // SAFETY: the caller vouches for every address.
995    unsafe {
996        let at = c.add(r * ldc);
997        let mut values = sums;
998        if !first {
999            for (i, value) in values.iter_mut().enumerate() {
1000                *value = _mm256_add_ps(_mm256_loadu_ps(at.add(8 * i)), *value);
1001            }
1002        }
1003        if let Some(finish) = finish {
1004            for (i, value) in values.iter_mut().enumerate() {
1005                *value = _mm256_add_ps(*value, _mm256_loadu_ps(finish.bias.add(8 * i)));
1006            }
1007            if finish.gelu {
1008                values = math::avx2::gelu_unbounded_n(values);
1009            }
1010            if !finish.residual.is_null() {
1011                let residual = finish.residual.add(r * finish.stride);
1012                for (i, value) in values.iter_mut().enumerate() {
1013                    *value = _mm256_add_ps(*value, _mm256_loadu_ps(residual.add(8 * i)));
1014                }
1015            }
1016        }
1017        for (i, value) in values.into_iter().enumerate() {
1018            _mm256_storeu_ps(at.add(8 * i), value);
1019        }
1020    }
1021}
1022
1023#[cfg(test)]
1024mod tests {
1025    use super::*;
1026
1027    #[test]
1028    fn kernels_display_their_instruction_sets() {
1029        assert_eq!(Kernel::Portable.to_string(), "portable");
1030        #[cfg(target_arch = "x86_64")]
1031        assert_eq!(Kernel::Avx2.to_string(), "AVX2");
1032        #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
1033        assert_eq!(Kernel::Neon.to_string(), "NEON");
1034    }
1035
1036    #[test]
1037    fn short_inputs_match_batch_rows_in_every_pool() {
1038        // A short last panel and K block, so the edge tiles run.
1039        let (n, k) = (7 * NR + 5, 3 * KC + 11);
1040        let w: Vec<f32> = (0..n * k)
1041            .map(|at| ((at * 37 % 101) as f32 - 50.0) / 64.0)
1042            .collect();
1043        let weight = PackedWeight::new(&w, n, k);
1044        let bias: Vec<f32> = (0..n).map(|j| (j % 7) as f32 / 8.0 - 0.4).collect();
1045        let batch = SHORT_ROWS + 2 * MC;
1046        let a: Vec<f32> = (0..batch * k)
1047            .map(|at| ((at * 23 % 97) as f32 - 48.0) / 50.0)
1048            .collect();
1049        let residual: Vec<f32> = (0..batch * n)
1050            .map(|at| ((at % 13) as f32 - 6.0) / 8.0)
1051            .collect();
1052        let kernel = Kernel::detect();
1053        for epilogue in [
1054            Epilogue::Bias(&bias),
1055            Epilogue::BiasGelu(&bias),
1056            Epilogue::BiasResidual(&bias, &residual),
1057        ] {
1058            let mut all = vec![0.0; batch * n];
1059            crate::worker_pool("gemm-test-batch", 1)
1060                .unwrap()
1061                .install(|| gemm_current_pool(kernel, &a, batch, &weight, epilogue, &mut all));
1062            for threads in [2, 3, 8] {
1063                let pool = crate::worker_pool("gemm-test-short", threads).unwrap();
1064                for (start, rows) in [(0, 1), (5, 13), (40, SHORT_ROWS)] {
1065                    let part = match epilogue {
1066                        Epilogue::BiasResidual(bias, residual) => {
1067                            Epilogue::BiasResidual(bias, &residual[start * n..])
1068                        }
1069                        other => other,
1070                    };
1071                    let mut c = vec![f32::NAN; rows * n];
1072                    pool.install(|| {
1073                        let a = &a[start * k..(start + rows) * k];
1074                        gemm_current_pool(kernel, a, rows, &weight, part, &mut c)
1075                    });
1076                    assert!(
1077                        c.iter()
1078                            .zip(&all[start * n..(start + rows) * n])
1079                            .all(|(x, y)| x.to_bits() == y.to_bits()),
1080                        "{threads} threads: rows {start}..{} differ",
1081                        start + rows
1082                    );
1083                }
1084            }
1085        }
1086    }
1087
1088    /// One output by a kernel's recipe: per K block a chain from zero, added to earlier blocks.
1089    fn recipe_total(kernel: Kernel, a: &[f32], w: &[f32]) -> f32 {
1090        let mut total = 0.0;
1091        for k0 in (0..a.len()).step_by(KC) {
1092            let terms = a[k0..].iter().zip(&w[k0..]).take(KC);
1093            let sum = if kernel == Kernel::Portable {
1094                terms.fold(0.0_f32, |sum, (&x, &y)| sum + x * y)
1095            } else {
1096                terms.fold(0.0_f32, |sum, (&x, &y)| x.mul_add(y, sum))
1097            };
1098            total = if k0 == 0 { sum } else { total + sum };
1099        }
1100        total
1101    }
1102
1103    fn recipe(kernel: Kernel, a: &[f32], w: &[f32], m: usize, epilogue: Epilogue) -> Vec<f32> {
1104        let k = a.len() / m;
1105        let n = w.len() / k;
1106        let mut c = vec![0.0; m * n];
1107        for (i, row) in c.chunks_exact_mut(n).enumerate() {
1108            for (j, out) in row.iter_mut().enumerate() {
1109                let total = recipe_total(kernel, &a[i * k..][..k], &w[j * k..][..k]);
1110                let mut value = total + epilogue.bias()[j];
1111                if let Epilogue::BiasGelu(_) = epilogue {
1112                    value = math::gelu_unbounded(value);
1113                }
1114                if let Epilogue::BiasResidual(_, residual) = epilogue {
1115                    value += residual[i * n + j];
1116                }
1117                *out = value;
1118            }
1119        }
1120        c
1121    }
1122
1123    /// Kernels on different processors that repeat one recipe give the same bits.
1124    #[test]
1125    fn simd_kernels_match_the_fused_recipe_bit_for_bit() {
1126        let kernel = Kernel::detect();
1127        if kernel == Kernel::Portable {
1128            return;
1129        }
1130        // Panel pairs, a lone whole panel, a partial one, and K blocks of two depths.
1131        let (n, k) = ((GATHER_PANELS + 1) * NR + 5, 2 * KC + 37);
1132        let w: Vec<f32> = (0..n * k)
1133            .map(|at| ((at * 37 % 101) as f32 - 50.0) / 64.0)
1134            .collect();
1135        let weight = PackedWeight::new(&w, n, k);
1136        let bias: Vec<f32> = (0..n).map(|j| (j % 7) as f32 / 8.0 - 0.4).collect();
1137        // One worker's run feeds every panel, so short bands gather their rows; two read in place.
1138        let pools = [1, 2].map(|threads| crate::worker_pool("gemm-test-recipe", threads).unwrap());
1139        for m in [1, 13, SHORT_ROWS + MR + 1] {
1140            let a: Vec<f32> = (0..m * k)
1141                .map(|at| ((at * 23 % 97) as f32 - 48.0) / 50.0)
1142                .collect();
1143            let residual: Vec<f32> = (0..m * n)
1144                .map(|at| ((at % 13) as f32 - 6.0) / 8.0)
1145                .collect();
1146            for epilogue in [
1147                Epilogue::Bias(&bias),
1148                Epilogue::BiasGelu(&bias),
1149                Epilogue::BiasResidual(&bias, &residual),
1150            ] {
1151                let want = recipe(kernel, &a, &w, m, epilogue);
1152                for pool in &pools {
1153                    let mut c = vec![f32::NAN; m * n];
1154                    pool.install(|| gemm_current_pool(kernel, &a, m, &weight, epilogue, &mut c));
1155                    let threads = pool.current_num_threads();
1156                    for (at, (x, y)) in c.iter().zip(&want).enumerate() {
1157                        assert_eq!(
1158                            x.to_bits(),
1159                            y.to_bits(),
1160                            "{kernel:?}, {threads} threads: {m} rows, at {at}: {x} vs {y}"
1161                        );
1162                    }
1163                }
1164            }
1165        }
1166    }
1167
1168    /// Products of strided rows keep their kernel's recipe for every row tail and a partial panel.
1169    #[test]
1170    fn products_match_their_kernels_recipe_bit_for_bit() {
1171        // Panel pairs, a lone whole panel and a partial one, two K blocks, wide strides; rows read
1172        // in place, then gathered for enough panels.
1173        let (k, lda) = (KC + 37, KC + 41);
1174        let a: Vec<f32> = (0..13 * lda)
1175            .map(|at| ((at * 17 % 83) as f32 - 41.0) / 40.0)
1176            .collect();
1177        for n in [3 * NR + 5, (GATHER_PANELS + 1) * NR + 5] {
1178            let ldc = n + 3;
1179            let w: Vec<f32> = (0..n * k)
1180                .map(|at| ((at * 29 % 89) as f32 - 44.0) / 32.0)
1181                .collect();
1182            let weight = PackedWeight::new(&w, n, k);
1183            let panels = weight.columns(0, n.div_ceil(NR));
1184            for kernel in [Kernel::detect(), Kernel::Portable] {
1185                for rows in 1..=13 {
1186                    let mut c = vec![f32::NAN; rows * ldc];
1187                    product(kernel, &a, lda, rows, panels, &mut c, ldc);
1188                    for i in 0..rows {
1189                        for j in 0..n {
1190                            let want = recipe_total(kernel, &a[i * lda..][..k], &w[j * k..][..k]);
1191                            let got = c[i * ldc + j];
1192                            assert_eq!(
1193                                got.to_bits(),
1194                                want.to_bits(),
1195                                "{kernel:?}, {n} columns: {rows} rows, at ({i}, {j})"
1196                            );
1197                        }
1198                    }
1199                }
1200            }
1201        }
1202    }
1203}