Skip to main content

tract_linalg/frame/mmm/
mod.rs

1#[macro_use]
2mod macros;
3
4pub mod cost_model;
5#[macro_use]
6pub(crate) mod fuse;
7pub(crate) mod input_store;
8pub(crate) mod kernel;
9#[macro_use]
10pub(crate) mod panel_extract;
11mod scratch;
12mod select;
13mod storage;
14
15#[cfg(test)]
16#[macro_use]
17pub mod tests;
18
19use crate::multithread::Executor;
20use std::borrow::Cow;
21use std::fmt::Debug;
22use std::ops::Range;
23use tract_data::internal::*;
24
25pub use cost_model::*;
26pub use fuse::*;
27pub use input_store::*;
28pub use kernel::*;
29pub use panel_extract::*;
30pub use scratch::*;
31pub use select::*;
32pub use storage::*;
33
34pub fn no_prefetch(_ptr: *const u8, _len: usize) {}
35
36pub trait MatMatMul: Debug + dyn_clone::DynClone + Send + Sync + std::any::Any {
37    fn name(&self) -> &str;
38    fn mr(&self) -> usize;
39    fn nr(&self) -> usize;
40
41    /// Architecture this kernel is written for, `None` for the generic Rust every target
42    /// builds. What [`retain_best`] compares before anything else: a kernel written for the
43    /// machine at hand supersedes a portable one whatever their instruction sets.
44    fn arch(&self) -> Option<crate::isa::Arch>;
45
46    /// Whether the kernel computes its accumulator type by converting every operation to
47    /// another type, for a machine whose hardware has none. Orders of magnitude off a real
48    /// kernel, and always the only thing on offer where it is declared, so selection ignores
49    /// it and benches skip it.
50    fn emulated(&self) -> bool;
51
52    /// The preference this kernel's author spelled out, before the instruction-set default.
53    fn boost(&self) -> isize;
54
55    /// Where this kernel sits against the siblings of its own kind, which [`retain_best`]
56    /// weighs once [`Self::arch`] has not separated them: the level of the instruction set it
57    /// is written for, plus whatever a measurement said that level gets wrong. A kernel
58    /// written for a more capable set outranks one written for a less capable one by default;
59    /// a declared boost is how an exception is spelled, and must be big enough to cross the
60    /// levels it disagrees with. Never encode a preference in [`Self::runnable`] — that
61    /// silently skips the kernel's tests as well.
62    fn preference(&self) -> isize;
63
64    /// Whether a machine with this instruction set could execute the kernel: the architecture is
65    /// the one it is written for, and the set offers every feature it declares. Takes the machine
66    /// rather than reading the host, so the same question serves dispatch and an audit of what
67    /// another architecture would run.
68    ///
69    /// It says nothing about whether this build assembled the body — see [`Self::built`]. A
70    /// kernel can be runnable on a machine and still be a stub here.
71    fn runnable_on(&self, isa: &crate::isa::IsaSet) -> bool;
72
73    /// Whether this kernel can be executed here at all: this build compiled it
74    /// ([`Self::built`]) and the running CPU has the instruction set it declares
75    /// ([`Self::runnable_on`] against the probed set).
76    ///
77    /// Runnability only, never preference: this answers "would executing the kernel fault",
78    /// and the mmm test bodies gate on it, so a kernel that lies here has no test coverage at
79    /// all on the hosts it lies on. Say a kernel is worse than its sibling with
80    /// [`Self::preference`] instead.
81    fn runnable(&self) -> bool;
82
83    /// Whether this build compiled the kernel's body at all. False for a foreign arch's
84    /// kernel, which is metadata around a stub that bails when called.
85    fn built(&self) -> bool;
86
87    /// What the instruction set must offer for this kernel to run here.
88    fn isa(&self) -> crate::isa::IsaReq;
89
90    #[allow(clippy::type_complexity)]
91    fn packings(&self) -> &[(Box<dyn MMMInputFormat>, Box<dyn MMMInputFormat>)];
92
93    fn internal_type(&self) -> DatumType;
94
95    unsafe fn c_view(&self, m_axis: Option<usize>, n_axis: Option<usize>) -> OutputStoreSpec;
96    unsafe fn c_from_data_and_strides(
97        &self,
98        item_size: usize,
99        row_stride: isize,
100        col_stride: isize,
101    ) -> OutputStoreSpec;
102
103    fn can_fuse(&self, spec: &FusedSpec) -> bool;
104
105    fn stores(&self) -> Cow<'_, [DatumType]>;
106
107    unsafe fn run(&self, m: usize, n: usize, non_linear: &[FusedSpec]) -> TractResult<()> {
108        unsafe {
109            let mut scratch = self.allocate_scratch_space();
110            self.run_with_scratch_space(m, n, &mut *scratch, non_linear)
111        }
112    }
113
114    unsafe fn allocate_scratch_space(&self) -> Box<dyn ScratchSpace>;
115    unsafe fn can_use_scratch_space(&self, scratch: &dyn ScratchSpace) -> bool;
116    unsafe fn run_with_scratch_space(
117        &self,
118        m: usize,
119        n: usize,
120        scratch: &mut dyn ScratchSpace,
121        non_linear: &[FusedSpec],
122    ) -> TractResult<()>;
123}
124
125dyn_clone::clone_trait_object!(MatMatMul);
126
127impl PartialEq for Box<dyn MatMatMul> {
128    fn eq(&self, other: &Box<dyn MatMatMul>) -> bool {
129        self.name() == other.name()
130    }
131}
132impl Eq for Box<dyn MatMatMul> {}
133
134impl std::hash::Hash for Box<dyn MatMatMul> {
135    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
136        self.name().hash(state)
137    }
138}
139
140impl<K: MatMatMulKer> MatMatMul for K {
141    fn name(&self) -> &str {
142        self.name()
143    }
144    fn mr(&self) -> usize {
145        self.mr()
146    }
147    fn nr(&self) -> usize {
148        self.nr()
149    }
150
151    fn arch(&self) -> Option<crate::isa::Arch> {
152        MatMatMulKer::arch(self)
153    }
154
155    fn emulated(&self) -> bool {
156        MatMatMulKer::emulated(self)
157    }
158
159    fn boost(&self) -> isize {
160        MatMatMulKer::boost(self)
161    }
162
163    fn preference(&self) -> isize {
164        MatMatMulKer::preference(self)
165    }
166
167    fn runnable_on(&self, isa: &crate::isa::IsaSet) -> bool {
168        MatMatMulKer::runnable_on(self, isa)
169    }
170
171    fn runnable(&self) -> bool {
172        MatMatMulKer::runnable(self)
173    }
174
175    fn built(&self) -> bool {
176        MatMatMulKer::built(self)
177    }
178
179    fn isa(&self) -> crate::isa::IsaReq {
180        MatMatMulKer::isa(self)
181    }
182
183    fn packings(&self) -> &[(Box<dyn MMMInputFormat>, Box<dyn MMMInputFormat>)] {
184        self.packings()
185    }
186
187    fn internal_type(&self) -> DatumType {
188        K::Acc::datum_type()
189    }
190
191    fn can_fuse(&self, spec: &FusedSpec) -> bool {
192        self.can_fuse(spec)
193    }
194
195    unsafe fn c_view(&self, m_axis: Option<usize>, n_axis: Option<usize>) -> OutputStoreSpec {
196        OutputStoreSpec::View { m_axis, n_axis, mr: self.mr(), nr: self.nr() }
197    }
198
199    unsafe fn c_from_data_and_strides(
200        &self,
201        item_size: usize,
202        row_stride: isize,
203        col_stride: isize,
204    ) -> OutputStoreSpec {
205        OutputStoreSpec::Strides {
206            row_byte_stride: row_stride * item_size as isize,
207            col_byte_stride: col_stride * item_size as isize,
208            mr: self.mr(),
209            nr: self.nr(),
210        }
211    }
212
213    fn stores(&self) -> Cow<'_, [DatumType]> {
214        self.stores()
215    }
216
217    unsafe fn allocate_scratch_space(&self) -> Box<dyn ScratchSpace> {
218        Box::<ScratchSpaceImpl<K::Acc>>::default()
219    }
220
221    unsafe fn can_use_scratch_space(&self, scratch: &dyn ScratchSpace) -> bool {
222        scratch.downcast_ref::<ScratchSpaceImpl<K::Acc>>().is_some()
223    }
224
225    unsafe fn run_with_scratch_space(
226        &self,
227        m: usize,
228        n: usize,
229        scratch: &mut dyn ScratchSpace,
230        non_linear: &[FusedSpec],
231    ) -> TractResult<()> {
232        // Every AddMatMul must pass panels packed the way the named packing index
233        // expects; a mismatch reads the panels at the wrong stride and runs off the
234        // buffer. Guard it here so any caller — not just OptMatMul — is caught.
235        #[cfg(debug_assertions)]
236        {
237            use crate::pack::PackedFormat;
238            // Only raw PackedFormat panels can be read at the wrong stride; exotic
239            // inputs (lazy im2col, block-quant) materialise panels in the kernel's
240            // format via panel_bytes, so a differing wrapper type is fine. When both
241            // sides are PackedFormat, require same element type and row count
242            // (tolerating alignment/padding, but not an f16-vs-f32 element-size swap).
243            fn compatible(expected: &dyn MMMInputFormat, got: &dyn MMMInputFormat) -> bool {
244                if expected.dyn_eq(got) {
245                    return true;
246                }
247                match (expected.downcast_ref::<PackedFormat>(), got.downcast_ref::<PackedFormat>())
248                {
249                    (Some(e), Some(g)) => e.dt == g.dt && e.r == g.r,
250                    _ => true,
251                }
252            }
253            for spec in non_linear {
254                if let FusedSpec::AddMatMul { a, b, packing } = spec {
255                    let (pa, pb) = &self.packings()[*packing];
256                    debug_assert!(
257                        compatible(&**pa, a.format()),
258                        "A packed as {:?} but {} packing {packing} expects {pa:?}",
259                        a.format(),
260                        self.name(),
261                    );
262                    debug_assert!(
263                        compatible(&**pb, b.format()),
264                        "B packed as {:?} but {} packing {packing} expects {pb:?}",
265                        b.format(),
266                        self.name(),
267                    );
268                }
269            }
270        }
271        unsafe {
272            let scratch = scratch
273                .downcast_mut::<ScratchSpaceImpl<K::Acc>>()
274                .context("Wrong scratch space type")?;
275            scratch.prepare(self, m, n, non_linear)?;
276            if n == 1 && self.nr() == 1 {
277                run_with_scratch_space_vec(self, m, scratch, non_linear)
278            } else {
279                let (mut prefer_col, mut prefer_row) = (0, 0);
280                for uop in non_linear.iter() {
281                    if let Some(col) = uop.prefer_col_outer() {
282                        prefer_col = col as usize;
283                        prefer_row = (!col) as usize;
284                    }
285                }
286                // k drives the cache-block size; read it from the first
287                // AddMatMul's packed input (0 if none → max block).
288                let k = non_linear
289                    .iter()
290                    .find_map(|f| match f {
291                        FusedSpec::AddMatMul { a, .. } => Some(a.k()),
292                        _ => None,
293                    })
294                    .unwrap_or(0);
295                run_with_scratch_space_2d(
296                    self,
297                    m,
298                    n,
299                    k,
300                    prefer_col > prefer_row,
301                    scratch,
302                    non_linear,
303                )
304            }
305        }
306    }
307}
308
309unsafe fn run_with_scratch_space_vec<K: MatMatMulKer>(
310    ker: &K,
311    m: usize,
312    scratch: &mut ScratchSpaceImpl<K::Acc>,
313    non_linear: &[FusedSpec],
314) -> TractResult<()> {
315    unsafe {
316        match crate::multithread::current_tract_executor() {
317            Executor::SingleThread => scratch.run_in_tls_scope(|scratch, tls| {
318                for ia in 0..m.divceil(ker.mr()) {
319                    scratch.run_one_tile(ker, non_linear, tls, ia, 0)?;
320                }
321                TractResult::Ok(())
322            }),
323            #[cfg(feature = "multithread-mm")]
324            Executor::MultiThread(pool) => chunked_dispatch_rayon(
325                Some(&pool),
326                m.divceil(ker.mr()),
327                1,
328                ker.mr(),
329                ker.nr(),
330                |ia_start, ia_end, _, _, _| {
331                    scratch.run_in_tls_scope(|scratch, tls| {
332                        for ia in ia_start..ia_end {
333                            scratch.run_one_tile(ker, non_linear, tls, ia, 0)?;
334                        }
335                        TractResult::Ok(())
336                    })
337                },
338            ),
339            #[cfg(feature = "multithread-mm")]
340            Executor::RayonGlobal => chunked_dispatch_rayon(
341                None,
342                m.divceil(ker.mr()),
343                1,
344                ker.mr(),
345                ker.nr(),
346                |ia_start, ia_end, _, _, _| {
347                    scratch.run_in_tls_scope(|scratch, tls| {
348                        for ia in ia_start..ia_end {
349                            scratch.run_one_tile(ker, non_linear, tls, ia, 0)?;
350                        }
351                        TractResult::Ok(())
352                    })
353                },
354            ),
355        }
356    }
357}
358
359/// Upper bound on the inner (L2-resident) panel-block edge.
360const BLK_MAX: usize = 16;
361
362/// Upper bound on the outer (L3-resident) super-block edge. 4× the inner cap so
363/// an L3 several times larger than L2 can hold a meaningfully bigger super-block.
364const BLK_L3_MAX: usize = 64;
365
366/// Panel-block working-set budget (bytes) from a detected cache size: a fraction
367/// `num/den` of the cache (leaving room for the C accumulator tile + packing
368/// metadata), clamped to a sane range. `0` (cache unknown) ⇒ `fallback`, which
369/// is kept small so the block ≈ the naive loop and can never over-block a cache
370/// it can't see. Sizes come from the shared [`crate::cache`] probe.
371fn tier_budget_bytes(cache_bytes: usize, num: usize, den: usize, fallback: usize) -> usize {
372    if cache_bytes == 0 {
373        fallback
374    } else {
375        (cache_bytes * num / den).clamp(64 * 1024, 64 * 1024 * 1024)
376    }
377}
378
379/// Inner tier: ~a third of L2 (private per perf-core), 256 KiB fallback.
380fn l2_block_budget_bytes() -> usize {
381    tier_budget_bytes(crate::cache::cache_info().l2, 1, 3, 256 * 1024)
382}
383
384/// Outer tier: `(llc_bytes, budget_bytes)` — the raw last-level-cache size and the
385/// fraction of it the outer super-block may budget — but only when an L3/LLC larger
386/// than L2 is detected (otherwise an outer tier just duplicates the inner one).
387/// `None` ⇒ no outer tier; the walk stays single-level. The raw size is returned
388/// alongside the budget so the caller can check whether the working set even
389/// spills the cache before blocking. Both numbers are for the *whole* cache;
390/// concurrent walkers each get a share (see [`outer_block_edge`]).
391fn l3_block_budget_bytes() -> Option<(usize, usize)> {
392    use crate::cache::LlcKind;
393    let (bytes, kind) = crate::cache::last_level_cache()?;
394    // Dedicated cluster L3: ~half. A shared System-Level Cache is contended by the
395    // GPU/NPU/display, so we can't assume residency of lines they keep evicting —
396    // budget it to ~a quarter.
397    let (num, den) = match kind {
398        LlcKind::Dedicated => (1, 2),
399        LlcKind::SystemLevel => (1, 4),
400    };
401    Some((bytes, tier_budget_bytes(bytes, num, den, 0)))
402}
403
404/// Cache-adaptive panel-block edge for a given byte budget: large enough to
405/// amortise streaming, small enough that the block's A+B sub-panels
406/// (`~blk·(mr+nr)·k·elem_bytes`) stay cache-resident at the given `k`. Capped at
407/// `cap`; the floor of 1 degrades exactly to the naive loop, so an unknown/small
408/// cache can never over-block (regression-safe).
409#[inline]
410fn block_edge_for(
411    budget: usize,
412    mr: usize,
413    nr: usize,
414    k: usize,
415    elem_bytes: usize,
416    cap: usize,
417) -> usize {
418    if k == 0 {
419        return cap;
420    }
421    let per_blk = ((mr + nr) * k * elem_bytes.max(1)).max(1);
422    (budget / per_blk).clamp(1, cap)
423}
424
425/// Whether inner (L2) blocking captures reuse the naive stream cannot, given the
426/// operand the walk re-streams — A (the m side, `panels·r = m_panels·mr`) for a
427/// column-outer order, B (the n side) for a row-outer one. If that streamed
428/// operand already fits L2 it is re-read from cache, not DRAM, so reordering
429/// tiles buys no reuse and only disturbs the prefetchers; only when it spills L2
430/// does the block save re-fetches. Mirrors [`outer_tier_pays`] for the inner
431/// tier, keyed on the streamed operand rather than the whole working set.
432fn inner_tier_pays(panels: usize, r: usize, k: usize, elem_bytes: usize, l2_bytes: usize) -> bool {
433    let streamed = panels.saturating_mul(r).saturating_mul(k).saturating_mul(elem_bytes);
434    l2_bytes > 0 && streamed > l2_bytes
435}
436
437/// Inner (L2) panel-block edge, or `usize::MAX` (single block, i.e. the naive
438/// stream) when the streamed operand already fits L2 (see [`inner_tier_pays`]).
439/// The budget is **cache-size derived** (not a hard-coded constant), so it is
440/// correct across hardware.
441///
442/// `l2_share` is how many rectangles concurrently share this L2, so each walker
443/// may only assume its slice of it — like [`outer_block_edge`]'s `llc_share`, but
444/// bounded by the L2's physical sharing degree rather than the thread count. On a
445/// core-private L2 (`l2_share == 1`) this is the whole cache, unchanged; on a
446/// cluster-shared L2 (Cortex-A9/A53) it prevents sibling rectangles from evicting
447/// one another's blocks.
448#[inline]
449#[allow(clippy::too_many_arguments)]
450fn inner_block_edge(
451    mr: usize,
452    nr: usize,
453    k: usize,
454    elem_bytes: usize,
455    m_panels: usize,
456    n_panels: usize,
457    col_outer: bool,
458    l2_share: usize,
459) -> usize {
460    let (panels, r) = if col_outer { (m_panels, mr) } else { (n_panels, nr) };
461    let share = l2_share.max(1);
462    if !inner_tier_pays(panels, r, k, elem_bytes, crate::cache::cache_info().l2 / share) {
463        return usize::MAX;
464    }
465    block_edge_for(l2_block_budget_bytes() / share, mr, nr, k, elem_bytes, BLK_MAX)
466}
467
468/// Whether an L3 outer super-block can capture reuse the inner (L2) tier cannot.
469/// It only can when the packed working set (`A + B ≈ (m·mr + n·nr)·k·elem`)
470/// actually spills the last-level cache: if both operands already fit, they stay
471/// resident across the sweep regardless of traversal order, so the reorder buys
472/// no reuse and only disturbs the hardware prefetchers — a measured net loss on
473/// small models that never leave L3 (voicecom_float on jetson-orin-nx, +15.6%).
474/// This is exactly the precondition the outer tier was introduced for ("a grid
475/// that exceeds L2 still re-fetches A/B from DRAM"); without the check the tier
476/// also engages on grids that never leave the LLC.
477fn outer_tier_pays(
478    m_panels: usize,
479    n_panels: usize,
480    mr: usize,
481    nr: usize,
482    k: usize,
483    elem_bytes: usize,
484    llc_bytes: usize,
485) -> bool {
486    let working_set = m_panels
487        .saturating_mul(mr)
488        .saturating_add(n_panels.saturating_mul(nr))
489        .saturating_mul(k)
490        .saturating_mul(elem_bytes);
491    llc_bytes > 0 && working_set > llc_bytes
492}
493
494/// Outer (L3) super-block edge, or `usize::MAX` (one block over the whole
495/// rectangle, i.e. no outer tier) when no usable L3 is detected or the working set
496/// already fits it (see [`outer_tier_pays`]). Never smaller than the inner edge
497/// `inner`.
498///
499/// `llc_share` is how many rectangles are walked concurrently: the LLC is shared,
500/// so each walker may only assume its slice of it. Sizing every chunk of a
501/// multi-threaded dispatch against the whole LLC would have them evict each
502/// other's super-blocks.
503#[inline]
504#[allow(clippy::too_many_arguments)]
505fn outer_block_edge(
506    mr: usize,
507    nr: usize,
508    k: usize,
509    elem_bytes: usize,
510    inner: usize,
511    m_panels: usize,
512    n_panels: usize,
513    llc_share: usize,
514) -> usize {
515    let Some((llc, budget)) = l3_block_budget_bytes() else { return usize::MAX };
516    let share = llc_share.max(1);
517    if !outer_tier_pays(m_panels, n_panels, mr, nr, k, elem_bytes, llc / share) {
518        return usize::MAX;
519    }
520    block_edge_for(budget / share, mr, nr, k, elem_bytes, BLK_L3_MAX).max(inner)
521}
522
523/// Visit every `(ia, ib)` tile of the `m × n` panel rectangle exactly once,
524/// blocked two levels deep: an outer `blk_outer` super-block (L3-resident) holds
525/// inner `blk` blocks (L2-resident). `col_outer` selects the within-block inner
526/// order (B-reuse vs A-reuse). When `blk_outer` spans the whole rectangle the
527/// outer loop runs once and this is exactly the single-level inner walk. Pure
528/// tile reordering ⇒ no result changes; extracted so the nesting can be
529/// unit-tested independently of the kernel.
530#[inline]
531fn for_each_blocked_tile(
532    m: Range<usize>,
533    n: Range<usize>,
534    blk: usize,
535    blk_outer: usize,
536    col_outer: bool,
537    mut f: impl FnMut(usize, usize) -> TractResult<()>,
538) -> TractResult<()> {
539    let blk = blk.max(1);
540    let blk_outer = blk_outer.max(blk);
541    let mut jb3 = n.start;
542    while jb3 < n.end {
543        let jb3_end = jb3.saturating_add(blk_outer).min(n.end);
544        let mut ja3 = m.start;
545        while ja3 < m.end {
546            let ja3_end = ja3.saturating_add(blk_outer).min(m.end);
547            let mut jb = jb3;
548            while jb < jb3_end {
549                let jb_end = jb.saturating_add(blk).min(jb3_end);
550                let mut ja = ja3;
551                while ja < ja3_end {
552                    let ja_end = ja.saturating_add(blk).min(ja3_end);
553                    if col_outer {
554                        for ib in jb..jb_end {
555                            for ia in ja..ja_end {
556                                f(ia, ib)?;
557                            }
558                        }
559                    } else {
560                        for ia in ja..ja_end {
561                            for ib in jb..jb_end {
562                                f(ia, ib)?;
563                            }
564                        }
565                    }
566                    ja = ja_end;
567                }
568                jb = jb_end;
569            }
570            ja3 = ja3_end;
571        }
572        jb3 = jb3_end;
573    }
574    Ok(())
575}
576
577/// Tile walk over one panel rectangle — the whole grid on the single-thread
578/// path, one dispatch chunk on the rayon path — blocked into cache-sized panel
579/// blocks for locality (the naive nested loop re-streams the whole inner operand
580/// per outer panel at large k). Two tiers: an inner L2-resident block and, where
581/// an L3 is detected, an outer L3-resident super-block sized for one of
582/// `llc_share` concurrent walkers. Both tiers are gated on the rectangle's own
583/// extents, so a rectangle whose streamed operand already fits cache walks
584/// exactly the naive order. Reordering independent tiles changes no result —
585/// bit-exact with the naive loop at any chunking.
586#[inline]
587#[allow(clippy::too_many_arguments)]
588unsafe fn run_blocked<K: MatMatMulKer>(
589    ker: &K,
590    m: Range<usize>,
591    n: Range<usize>,
592    k: usize,
593    col_outer: bool,
594    llc_share: usize,
595    scratch: &ScratchSpaceImpl<K::Acc>,
596    non_linear: &[FusedSpec],
597) -> TractResult<()> {
598    unsafe {
599        let elem = K::Acc::datum_type().size_of();
600        let (mr, nr) = (ker.mr(), ker.nr());
601        let (m_panels, n_panels) = (m.len(), n.len());
602        let l2_share = llc_share.min(crate::cache::cache_info().l2_sharers_or_one());
603        let blk = inner_block_edge(mr, nr, k, elem, m_panels, n_panels, col_outer, l2_share);
604        let blk_outer = outer_block_edge(mr, nr, k, elem, blk, m_panels, n_panels, llc_share);
605        scratch.run_in_tls_scope(|scratch, tls| {
606            for_each_blocked_tile(m, n, blk, blk_outer, col_outer, |ia, ib| {
607                scratch.run_one_tile(ker, non_linear, tls, ia, ib)
608            })
609        })
610    }
611}
612
613/// Run the whole `m × n` output over the executor currently installed: as one
614/// rectangle when single-threaded, else split into the chunk grid
615/// [`chunk_grid`] picks. `col_outer` selects the tile order inside a rectangle
616/// (B-reuse vs A-reuse), from the fused ops' preference. `k` is only used to size
617/// the cache blocking.
618unsafe fn run_with_scratch_space_2d<K: MatMatMulKer>(
619    ker: &K,
620    m: usize,
621    n: usize,
622    k: usize,
623    col_outer: bool,
624    scratch: &ScratchSpaceImpl<K::Acc>,
625    non_linear: &[FusedSpec],
626) -> TractResult<()> {
627    unsafe {
628        let (m_panels, n_panels) = (m.divceil(ker.mr()), n.divceil(ker.nr()));
629        #[cfg(feature = "multithread-mm")]
630        let chunk = |ia_start, ia_end, ib_start, ib_end, concurrency| {
631            run_blocked(
632                ker,
633                ia_start..ia_end,
634                ib_start..ib_end,
635                k,
636                col_outer,
637                concurrency,
638                scratch,
639                non_linear,
640            )
641        };
642        match crate::multithread::current_tract_executor() {
643            Executor::SingleThread => {
644                run_blocked(ker, 0..m_panels, 0..n_panels, k, col_outer, 1, scratch, non_linear)
645            }
646            #[cfg(feature = "multithread-mm")]
647            Executor::MultiThread(pool) => {
648                chunked_dispatch_rayon(Some(&pool), m_panels, n_panels, ker.mr(), ker.nr(), chunk)
649            }
650            #[cfg(feature = "multithread-mm")]
651            Executor::RayonGlobal => {
652                chunked_dispatch_rayon(None, m_panels, n_panels, ker.mr(), ker.nr(), chunk)
653            }
654        }
655    }
656}
657
658/// Chunks per thread the 2D dispatch aims for. Above one, rayon can steal work
659/// when threads progress unevenly — a contended core, an E-core on a big.LITTLE
660/// part, a chunk carrying more border tiles — so a straggler costs at most its
661/// share rather than the whole grid's tail. Each extra chunk also re-reads a band
662/// of the packed operands, and that cost grows as `sqrt(chunks)` against a linear
663/// gain in slack, which is what keeps this small.
664#[cfg(feature = "multithread-mm")]
665const CHUNKS_PER_THREAD: usize = 4;
666
667/// Chunk grid for the 2D dispatch: `(nchunks_m, nchunks_n, dr_m, dr_n)`.
668///
669/// Aims for [`CHUNKS_PER_THREAD`]`· nth` chunks and shapes them to minimise how
670/// often the packed operands are re-read: a chunk covering `dr_m × dr_n` panels
671/// reads `dr_m·mr·k` of A and `dr_n·nr·k` of B, so over the whole grid A is read
672/// `nchunks_n` times and B `nchunks_m` times. Minimising
673/// `nchunks_n·m + nchunks_m·n` at a fixed chunk count puts
674/// `nchunks_m = sqrt(chunks · m / n)` — chunks as square as the operands'
675/// extents, rather than a band across one axis.
676///
677/// Cache locality *inside* a chunk is [`run_blocked`]'s job, not this function's;
678/// chunk count therefore tracks the thread count and not a cache size.
679///
680/// Both panel counts must be non-zero; the dispatcher returns early on an empty
681/// grid.
682#[cfg(feature = "multithread-mm")]
683fn chunk_grid(
684    n_panels_m: usize,
685    n_panels_n: usize,
686    mr: usize,
687    nr: usize,
688    nth: usize,
689) -> (usize, usize, usize, usize) {
690    let chunks = (CHUNKS_PER_THREAD * nth).max(1);
691    let (m, n) = (n_panels_m * mr, (n_panels_n * nr).max(1));
692    let nchunks_m = (chunks.saturating_mul(m) / n).isqrt().clamp(1, n_panels_m);
693    let nchunks_n = (chunks / nchunks_m).clamp(1, n_panels_n);
694    let nchunks_m = (chunks / nchunks_n).clamp(1, n_panels_m);
695    let dr_m = n_panels_m.div_ceil(nchunks_m);
696    let dr_n = n_panels_n.div_ceil(nchunks_n);
697    // Recount from the edges: `div_ceil` can make the last chunk of an axis land
698    // entirely outside the grid, and an empty work item is a wasted dispatch.
699    (n_panels_m.div_ceil(dr_m), n_panels_n.div_ceil(dr_n), dr_m, dr_n)
700}
701
702/// Dispatch the `m_panels × n_panels` panel grid across the rayon path, split into
703/// the 2D chunk grid [`chunk_grid`] picks. Grids below
704/// [`crate::multithread::current_threading_panel_threshold`] run whole on the
705/// calling thread instead.
706///
707/// The closure receives **chunk bounds** (`ia_start, ia_end, ib_start, ib_end`)
708/// plus the number of chunks running concurrently, not per-tile indices. Chunk
709/// bounds let it amortise per-worker setup (e.g.
710/// `ScratchSpaceImpl::run_in_tls_scope`) over all the tiles in the chunk; the
711/// concurrency lets it size shared-cache blocking against the share it actually
712/// gets. The closure is invoked exactly once per rayon work item, and once in
713/// total with a concurrency of 1 on the below-threshold path.
714///
715/// `pool`:
716///   * `Some(p)` with `p.current_num_threads() > 1` → scoped via `p.install`
717///     (native, custom pool path).
718///   * `Some(p)` with single-thread pool, or `None` → dispatched via
719///     `into_par_iter` directly, which uses rayon's GLOBAL pool. This is
720///     the only working path on `wasm32-unknown-unknown` via
721///     `wasm_bindgen_rayon::init_thread_pool`.
722#[cfg(feature = "multithread-mm")]
723unsafe fn chunked_dispatch_rayon<F>(
724    pool: Option<&rayon::ThreadPool>,
725    n_panels_m: usize,
726    n_panels_n: usize,
727    mr: usize,
728    nr: usize,
729    run_chunk: F,
730) -> TractResult<()>
731where
732    F: Fn(usize, usize, usize, usize, usize) -> TractResult<()> + Sync,
733{
734    use rayon::prelude::*;
735    if n_panels_m == 0 || n_panels_n == 0 {
736        return Ok(());
737    }
738    if n_panels_m * n_panels_n < crate::multithread::current_threading_panel_threshold() {
739        // Below the threading threshold: run the whole grid as a single chunk
740        // on the calling thread. Closure handles its own TLS scope.
741        return run_chunk(0, n_panels_m, 0, n_panels_n, 1);
742    }
743    let use_global = pool.is_none_or(|p| p.current_num_threads() <= 1);
744    let body = || {
745        let nth = rayon::current_num_threads();
746        let (nchunks_m, nchunks_n, dr_m, dr_n) = chunk_grid(n_panels_m, n_panels_n, mr, nr, nth);
747        let total = nchunks_m * nchunks_n;
748        let concurrency = nth.min(total);
749        (0..total).into_par_iter().try_for_each(|idx| {
750            let im = idx % nchunks_m;
751            let in_ = idx / nchunks_m;
752            let ia_start = im * dr_m;
753            let ia_end = (ia_start + dr_m).min(n_panels_m);
754            let ib_start = in_ * dr_n;
755            let ib_end = (ib_start + dr_n).min(n_panels_n);
756            run_chunk(ia_start, ia_end, ib_start, ib_end, concurrency)
757        })
758    };
759    if use_global { body() } else { pool.unwrap().install(body) }
760}
761
762#[cfg(test)]
763mod blocked_walk_tests {
764    use super::*;
765    use std::collections::HashSet;
766
767    fn collect(
768        m: Range<usize>,
769        n: Range<usize>,
770        blk: usize,
771        blk_outer: usize,
772        col_outer: bool,
773    ) -> Vec<(usize, usize)> {
774        let mut v = Vec::new();
775        for_each_blocked_tile(m, n, blk, blk_outer, col_outer, |ia, ib| {
776            v.push((ia, ib));
777            Ok(())
778        })
779        .unwrap();
780        v
781    }
782
783    /// Every tile of the rectangle is visited exactly once, for both inner orders
784    /// and a range of (blk, blk_outer) — single-tier (outer = MAX), two-tier, and
785    /// degenerate edges. Coverage being a permutation is what makes the walk
786    /// bit-exact with the naive loop. Offset rectangles are the dispatch chunks.
787    #[test]
788    fn covers_every_tile_once() {
789        for &(m, n) in &[(1, 1), (3, 5), (16, 16), (40, 7), (7, 40), (80, 80)] {
790            for &(m0, n0) in &[(0, 0), (3, 11)] {
791                // usize::MAX is how both tiers say "do not block"; on an offset
792                // rectangle the edge arithmetic must not overflow past the end.
793                for &blk in &[1, 3, 16, usize::MAX] {
794                    for &blk_outer in &[blk, blk.saturating_add(1), 64, usize::MAX] {
795                        for &col_outer in &[false, true] {
796                            let tiles = collect(m0..m0 + m, n0..n0 + n, blk, blk_outer, col_outer);
797                            assert_eq!(
798                                tiles.len(),
799                                m * n,
800                                "m={m} n={n} blk={blk} outer={blk_outer}"
801                            );
802                            let set: HashSet<_> = tiles.iter().copied().collect();
803                            assert_eq!(
804                                set.len(),
805                                m * n,
806                                "duplicate tiles m={m} n={n} blk={blk} outer={blk_outer}"
807                            );
808                            for ia in m0..m0 + m {
809                                for ib in n0..n0 + n {
810                                    assert!(set.contains(&(ia, ib)), "missing ({ia},{ib})");
811                                }
812                            }
813                        }
814                    }
815                }
816            }
817        }
818    }
819
820    /// With no outer tier (blk_outer = MAX) the two-tier walk must emit the exact
821    /// same order as the original single-level blocked loop — guarantees the L3
822    /// path is a pure no-op on hardware without a detectable L3.
823    #[test]
824    fn outer_max_matches_single_level() {
825        for &(m, n) in &[(40, 7), (80, 80), (13, 29)] {
826            for &blk in &[1, 4, 16] {
827                for &col_outer in &[false, true] {
828                    let two_tier = collect(0..m, 0..n, blk, usize::MAX, col_outer);
829                    let mut single = Vec::new();
830                    let mut jb = 0;
831                    while jb < n {
832                        let jb_end = (jb + blk).min(n);
833                        let mut ja = 0;
834                        while ja < m {
835                            let ja_end = (ja + blk).min(m);
836                            if col_outer {
837                                for ib in jb..jb_end {
838                                    for ia in ja..ja_end {
839                                        single.push((ia, ib));
840                                    }
841                                }
842                            } else {
843                                for ia in ja..ja_end {
844                                    for ib in jb..jb_end {
845                                        single.push((ia, ib));
846                                    }
847                                }
848                            }
849                            ja = ja_end;
850                        }
851                        jb = jb_end;
852                    }
853                    assert_eq!(two_tier, single, "m={m} n={n} blk={blk} col_outer={col_outer}");
854                }
855            }
856        }
857    }
858
859    /// The outer tier engages only when the packed working set spills the LLC.
860    /// A grid that already fits stays single-level (the reorder buys no reuse and
861    /// only hurts prefetch — the voicecom_float/Orin regression).
862    #[test]
863    fn outer_tier_gated_on_working_set_spilling_llc() {
864        let llc = 2 * 1024 * 1024; // 2 MiB, f32 (elem = 4)
865        // Small grid: (64·8 + 8·8)·64·4 ≈ 144 KiB ⇒ fits ⇒ no outer tier.
866        assert!(!outer_tier_pays(64, 8, 8, 8, 64, 4, llc));
867        // Large grid: (256·8 + 256·8)·256·4 ≈ 4 MiB ⇒ spills ⇒ engage.
868        assert!(outer_tier_pays(256, 256, 8, 8, 256, 4, llc));
869        // A boundary working set equal to the LLC does not spill it.
870        assert!(!outer_tier_pays(1, 0, llc, 0, 1, 1, llc));
871        // Unknown LLC (0) never engages, whatever the grid.
872        assert!(!outer_tier_pays(4096, 4096, 8, 8, 4096, 4, 0));
873        // k = 0 (empty reduction) has no working set ⇒ never engages.
874        assert!(!outer_tier_pays(4096, 4096, 8, 8, 0, 4, llc));
875    }
876
877    /// Inner blocking engages only when the operand the walk re-streams — A for a
878    /// column-outer order, B for a row-outer one — spills L2. A streamed operand
879    /// that fits is re-read from cache, so blocking only hurts prefetch.
880    #[test]
881    fn inner_tier_gated_on_streamed_operand_spilling_l2() {
882        let l2 = 1024 * 1024; // 1 MiB, f32 (elem = 4)
883        // inception Conv2d_4a_3x3 grid (16×12 kernel), k=720.
884        // col_outer streams A (m side, panels=12 r=16): 12·16·720·4 ≈ 540 KiB ⇒ fits.
885        assert!(!inner_tier_pays(12, 16, 720, 4, l2));
886        // row_outer streams B (n side, panels=421 r=12): 421·12·720·4 ≈ 14.5 MiB ⇒ spills.
887        assert!(inner_tier_pays(421, 12, 720, 4, l2));
888        // A large square (m side, panels=256 r=16, k=512): 256·16·512·4 ≈ 8 MiB ⇒ spills.
889        assert!(inner_tier_pays(256, 16, 512, 4, l2));
890        // Undetectable L2 (0) never engages — degrades to the naive loop.
891        assert!(!inner_tier_pays(4096, 16, 4096, 4, 0));
892        // k = 0 (empty reduction) has no working set.
893        assert!(!inner_tier_pays(4096, 16, 0, 4, l2));
894    }
895
896    /// Grids, kernel aspect ratios and thread counts worth checking the chunk
897    /// grid against: skewed both ways, square, prime-ish, and the degenerate
898    /// single-panel cases.
899    #[cfg(feature = "multithread-mm")]
900    const GRIDS: &[(usize, usize)] = &[
901        (1, 1),
902        (1, 5),
903        (5, 1),
904        (2, 3),
905        (3, 3),
906        (16, 96),
907        (96, 16),
908        (17, 17),
909        (64, 64),
910        (32, 384),
911        (128, 128),
912        (1, 4096),
913        (4096, 1),
914        (9, 1000),
915    ];
916
917    #[cfg(feature = "multithread-mm")]
918    const RATIOS: &[(usize, usize)] = &[(8, 8), (16, 4), (32, 32), (64, 1)];
919
920    /// The four numbers `chunk_grid` returns must tile the panel grid exactly:
921    /// `chunked_dispatch_rayon` turns them into work items, so an empty chunk is
922    /// a wasted dispatch, an overlap would double-compute a tile, and a gap would
923    /// leave part of C uninitialised.
924    #[cfg(feature = "multithread-mm")]
925    #[test]
926    fn chunk_grid_tiles_the_panel_grid() {
927        for &(m, n) in GRIDS {
928            for &(mr, nr) in RATIOS {
929                for nth in [1usize, 2, 3, 4, 6, 8, 16, 64] {
930                    let (cm, cn, dr_m, dr_n) = chunk_grid(m, n, mr, nr, nth);
931                    let ctx = format!("{m}x{n} panels, {mr}x{nr} kernel, {nth} threads");
932                    let mut seen = vec![false; m * n];
933                    for idx in 0..cm * cn {
934                        let (im, in_) = (idx % cm, idx / cm);
935                        let (a0, a1) = (im * dr_m, (im * dr_m + dr_m).min(m));
936                        let (b0, b1) = (in_ * dr_n, (in_ * dr_n + dr_n).min(n));
937                        assert!(a0 < a1 && b0 < b1, "empty chunk {idx} in {ctx}");
938                        for ia in a0..a1 {
939                            for ib in b0..b1 {
940                                assert!(!seen[ia * n + ib], "tile ({ia},{ib}) twice in {ctx}");
941                                seen[ia * n + ib] = true;
942                            }
943                        }
944                    }
945                    assert!(seen.iter().all(|s| *s), "tile left out in {ctx}");
946                }
947            }
948        }
949    }
950
951    /// Enough chunks to keep every thread fed, whenever the grid has that many
952    /// panels to go round. Recounting the chunks from the edges is what makes this
953    /// hold: naming more chunks than the edges cover would idle the difference.
954    #[cfg(feature = "multithread-mm")]
955    #[test]
956    fn chunk_grid_feeds_every_thread() {
957        for &(m, n) in GRIDS {
958            for &(mr, nr) in RATIOS {
959                for nth in [1usize, 2, 3, 4, 6, 8, 16, 64] {
960                    let (cm, cn, ..) = chunk_grid(m, n, mr, nr, nth);
961                    assert!(
962                        cm * cn >= nth.min(m * n),
963                        "{cm}x{cn} chunks for {nth} threads on {m}x{n} panels"
964                    );
965                }
966            }
967        }
968    }
969
970    /// The grid is shaped to minimise packed-operand re-reads: A is read once per
971    /// column of chunks and B once per row, so `nchunks_n·m + nchunks_m·n` is what
972    /// the shape trades off. It must never cost more than a band across either
973    /// axis at the same chunk count, which on a square grid costs 1.5x.
974    #[cfg(feature = "multithread-mm")]
975    #[test]
976    fn chunk_grid_shape_beats_a_band_on_operand_traffic() {
977        let traffic = |cm: usize, cn: usize, m: usize, n: usize| cn * m + cm * n;
978        for &(m, n) in GRIDS {
979            for &(mr, nr) in RATIOS {
980                for nth in [2usize, 4, 8, 16] {
981                    let (cm, cn, ..) = chunk_grid(m, n, mr, nr, nth);
982                    let chunks = cm * cn;
983                    // Only a band that fits along the axis is a real alternative:
984                    // one clamped shorter would be a different chunk count, and a
985                    // smaller chunk count trivially re-reads less.
986                    if chunks > m || chunks > n {
987                        continue;
988                    }
989                    let (m_ext, n_ext) = (m * mr, n * nr);
990                    let ours = traffic(cm, cn, m_ext, n_ext);
991                    let band_m = traffic(chunks, 1, m_ext, n_ext);
992                    let band_n = traffic(1, chunks, m_ext, n_ext);
993                    assert!(
994                        ours <= band_m.min(band_n),
995                        "{cm}x{cn} costs {ours}, bands cost {band_m}/{band_n} \
996                         on {m}x{n} panels, {mr}x{nr} kernel, {nth} threads"
997                    );
998                }
999            }
1000        }
1001    }
1002}